diff --git a/.claude/skills/feature-review/SKILL.md b/.claude/skills/feature-review/SKILL.md index 5f67157b3b..42395206e2 100644 --- a/.claude/skills/feature-review/SKILL.md +++ b/.claude/skills/feature-review/SKILL.md @@ -104,6 +104,12 @@ Go through these areas. Skip an area if it doesn't apply, but say so in one line than the same kind of file in the comparison features (`wc -l`), a file that grew a lot (`git log --stat`), the same lines found twice with `git grep`, a helper from the "Shared helpers" list in [references/conventions.md](references/conventions.md) re-implemented in the feature. +10. **Tests** — which logic of the feature has no unit tests in `Source/NETworkManager.Tests`: parsing, mapping and + conversion (e.g. frequency → channel), decisions (e.g. which dialog / mode, what counts as a change), comparisons, + validation, export field lists. Logic hidden in a view model or a private method that could be a small public + static method in `NETworkManager.Models` (no `InternalsVisibleTo` in the solution, reference: + `IPScannerNeighborCheck`, `IPScannerScanComparer`). A bug that a test would have caught is a strong hint + (report it as `T1`, ... with the bugs it would have caught). #### Refactoring: only if the code gets simpler @@ -184,6 +190,9 @@ Compared with: ### Other (security, localization, docs) | # | Finding | Proposed fix | +### Tests +| # | Untested logic (`path:line`) | Bugs it would have caught | Proposal (move to `NETworkManager.Models` if needed + test cases) | + ### Refactoring / simplification | # | Where | Problem (duplication / complexity) | Proposal | Gain | Must stay identical / test | @@ -220,6 +229,12 @@ When fixing: already exists in two or more places. Keep the code simple: no new abstraction for a single use. - One commit per finding, with its ID in the subject (e.g. `Fix: Port Scanner: ... (B3)`); a refactoring gets its own commit without behaviour changes. +- Write unit tests with every fix and feature where possible, in the same commit (xUnit, + `Source/NETworkManager.Tests//Tests.cs`), so the coverage of the tool grows with each change: a bug fix + gets a test that fails without the fix, new logic gets tests for its cases and edge cases. Move testable logic + (parsing, mapping, decisions, comparisons) out of the view model / private methods into a small public static + method or class in `NETworkManager.Models` first. What can't be tested (UI, WinRT / system APIs, network) goes into + the manual Windows tests of the handover file. - Add strings to `Strings.resx` and, in alphabetical order, to `Strings.Designer.cs`. - Update the feature documentation and add a changelog entry in `Website/docs/changelog/next-release.md`. - Never modify `Source/3rdparty/`. diff --git a/.claude/skills/feature-review/references/conventions.md b/.claude/skills/feature-review/references/conventions.md index c8090b97f1..fef65d97ea 100644 --- a/.claude/skills/feature-review/references/conventions.md +++ b/.claude/skills/feature-review/references/conventions.md @@ -134,6 +134,8 @@ Reference: `HostsFileEditorView.xaml`, `FirewallView.xaml`. - Child windows: set `ConfigurationManager.Current.IsChildWindowOpen` before showing and reset it in both OK and Cancel handlers; dialog view models get OK/Cancel actions. +- Commands that open a dialog or run behind one (scan, refresh, auto refresh, modify) check + `!DialogHelper.IsAnyDialogOpen()` in their `CanExecute` (main window, MahApps dialog, child window), no own copy. - Add/edit/copy dialogs share one view model with `EditMode` (`Add`, `Edit`, `Copy`; profiles use `ProfileEditMode`). Copy appends `" - " + Strings.CopyNoun` to a name where names identify items. - Deletes are confirmed with `DialogHelper.ShowConfirmationMessageAsync(..., ChildWindowIcon.Info, Strings.Delete)`. diff --git a/Source/NETworkManager.Converters/WiFiChannelBandwidthToStringConverter.cs b/Source/NETworkManager.Converters/WiFiChannelBandwidthToStringConverter.cs index eed8d891e1..c438c615ac 100644 --- a/Source/NETworkManager.Converters/WiFiChannelBandwidthToStringConverter.cs +++ b/Source/NETworkManager.Converters/WiFiChannelBandwidthToStringConverter.cs @@ -1,14 +1,27 @@ using System; using System.Globalization; using System.Windows.Data; +using NETworkManager.Models.Network; namespace NETworkManager.Converters; +/// +/// Channel width of a WiFi network () as text, e.g. "80 MHz", or "~80 MHz" if it was +/// estimated (see ). +/// public sealed class WiFiChannelBandwidthToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - return value is not int bandwidth ? "-/-" : $"{bandwidth} MHz"; + return value is not WiFiNetworkInfo info ? "-/-" : Format(info); + } + + /// + /// Gets the channel width of a network as text (e.g. "80 MHz", "~80 MHz" if estimated). + /// + public static string Format(WiFiNetworkInfo info) + { + return $"{(info.IsChannelBandwidthEstimated ? "~" : string.Empty)}{info.ChannelBandwidth} MHz"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) diff --git a/Source/NETworkManager.Converters/WiFiNetworkChangeToStringConverter.cs b/Source/NETworkManager.Converters/WiFiNetworkChangeToStringConverter.cs new file mode 100644 index 0000000000..68fb88c09f --- /dev/null +++ b/Source/NETworkManager.Converters/WiFiNetworkChangeToStringConverter.cs @@ -0,0 +1,60 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using NETworkManager.Localization.Resources; +using NETworkManager.Models.Network; + +namespace NETworkManager.Converters; + +/// +/// Convert the of a network (since the previous scan) to a translated +/// (e.g. "New"), or a to the tooltip of a changed network. +/// +public sealed class WiFiNetworkChangeToStringConverter : IValueConverter +{ + /// + /// Convert the change of a network to a translated . + /// + /// + /// Change of the network as , or the network as with + /// the parameter "ToolTip". + /// + /// + /// "ToolTip" for the values of the previous scan of a changed network. + /// + /// Translated change (empty if there is none), or the tooltip (null without previous values). + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (parameter is "ToolTip") + return value is WiFiNetworkInfo { Previous: { } previous } + ? string.Format(Strings.PreviouslyX, + $"{Strings.Channel} {previous.Channel} · {WiFiChannelBandwidthToStringConverter.Format(previous)} · {previous.NetworkAuthenticationType}") + : null; + + return value is WiFiNetworkChange change ? ToLocalizedString(change) : string.Empty; + } + + /// + /// Gets the translated change of a network. + /// + /// Change of the network. + /// Translated change, empty for . + public static string ToLocalizedString(WiFiNetworkChange change) + { + return change switch + { + WiFiNetworkChange.New => Strings.HostChange_New, + WiFiNetworkChange.Gone => Strings.HostChange_Gone, + WiFiNetworkChange.Changed => Strings.WiFiNetworkChange_Changed, + _ => string.Empty + }; + } + + /// + /// !!! Method not implemented !!! + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } +} diff --git a/Source/NETworkManager.Converters/WiFiNetworkToSsidStringConverter.cs b/Source/NETworkManager.Converters/WiFiNetworkToSsidStringConverter.cs new file mode 100644 index 0000000000..05ebb67284 --- /dev/null +++ b/Source/NETworkManager.Converters/WiFiNetworkToSsidStringConverter.cs @@ -0,0 +1,45 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using NETworkManager.Localization.Resources; +using NETworkManager.Models.Network; + +namespace NETworkManager.Converters; + +/// +/// Convert a to the SSID as it is shown ("Hidden Network" for a hidden network). +/// +public sealed class WiFiNetworkToSsidStringConverter : IValueConverter +{ + /// + /// Convert a network to its shown SSID. + /// + /// Network as . + /// + /// + /// + /// Shown SSID, empty without a network. + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return value is WiFiNetworkInfo network ? GetSsid(network) : string.Empty; + } + + /// + /// Gets the SSID of a network as it is shown in the grid, the charts and the messages ("Hidden Network" for a + /// hidden network). + /// + /// Network. + /// Shown SSID. + public static string GetSsid(WiFiNetworkInfo network) + { + return network.IsHidden ? Strings.HiddenNetwork : network.AvailableNetwork.Ssid; + } + + /// + /// !!! Method not implemented !!! + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } +} diff --git a/Source/NETworkManager.Documentation/DocumentationManager.cs b/Source/NETworkManager.Documentation/DocumentationManager.cs index 4a436cf7dc..5cf844de12 100644 --- a/Source/NETworkManager.Documentation/DocumentationManager.cs +++ b/Source/NETworkManager.Documentation/DocumentationManager.cs @@ -260,6 +260,7 @@ public static DocumentationIdentifier GetIdentifierBySettingsName(SettingsName n SettingsName.Settings => DocumentationIdentifier.SettingsSettings, SettingsName.Dashboard => GetIdentifierByApplicationName(ApplicationName.Dashboard), SettingsName.NetworkInterface => GetIdentifierByApplicationName(ApplicationName.NetworkInterface), + SettingsName.WiFi => GetIdentifierByApplicationName(ApplicationName.WiFi), SettingsName.IPScanner => GetIdentifierByApplicationName(ApplicationName.IPScanner), SettingsName.PortScanner => GetIdentifierByApplicationName(ApplicationName.PortScanner), SettingsName.PingMonitor => GetIdentifierByApplicationName(ApplicationName.PingMonitor), diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index b9b02ec7bc..59d4543c33 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -1855,6 +1855,15 @@ public static string ChannelWidth { } } + /// + /// Looks up a localized string similar to Estimated from the band and the WiFi standard: the channel width could not be read from the beacon of the access point.. + /// + public static string ChannelWidthEstimatedToolTip { + get { + return ResourceManager.GetString("ChannelWidthEstimatedToolTip", resourceCulture); + } + } + /// /// Looks up a localized string similar to Chart time (seconds). /// @@ -2606,6 +2615,15 @@ public static string CouldNotDetectSubnetmask { } } + /// + /// Looks up a localized string similar to Could not disconnect from {0} ({1})!. + /// + public static string CouldNotDisconnectFromXXXReasonXXX { + get { + return ResourceManager.GetString("CouldNotDisconnectFromXXXReasonXXX", resourceCulture); + } + } + /// /// Looks up a localized string similar to Could not find the application "{0}". Maybe the application was hidden in the settings?. /// @@ -6320,6 +6338,15 @@ public static string HelpMessage_UseCustomThemes { } } + /// + /// Looks up a localized string similar to Only when the networks are scanned automatically ("Automatically update every") and WiFi is shown: one notification per scan with the changes since the previous scan of the adapter.. + /// + public static string HelpMessage_WiFiChangesNotification { + get { + return ResourceManager.GetString("HelpMessage_WiFiChangesNotification", resourceCulture); + } + } + /// /// Looks up a localized string similar to Windows credentials for the Windows host information of this tab (also for repeated scans and Rescan), replacing the ones of the profile / group. They are not saved and are discarded when the tab is closed. Without credentials, the user running NETworkManager is used.. /// @@ -9805,6 +9832,15 @@ public static string Preview { } } + /// + /// Looks up a localized string similar to Previously: {0}. + /// + public static string PreviouslyX { + get { + return ResourceManager.GetString("PreviouslyX", resourceCulture); + } + } + /// /// Looks up a localized string similar to Previous MAC address: {0}. /// @@ -15496,6 +15532,15 @@ public static string WiFiConnectionStatus_UnsupportedAuthenticationProtocol { } } + /// + /// Looks up a localized string similar to Changed. + /// + public static string WiFiNetworkChange_Changed { + get { + return ResourceManager.GetString("WiFiNetworkChange_Changed", resourceCulture); + } + } + /// /// Looks up a localized string similar to Window. /// @@ -15640,6 +15685,15 @@ public static string XADNSRecordsResolvedForXXXMessage { } } + /// + /// Looks up a localized string similar to {0} Changed. + /// + public static string XChanged { + get { + return ResourceManager.GetString("XChanged", resourceCulture); + } + } + /// /// Looks up a localized string similar to {0} Closed. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index 7debb8294a..98dc2d0292 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5450,4 +5450,22 @@ Do you want to start the scan? Beta: this feature is tested publicly and may change. Please report problems on GitHub. + + Could not disconnect from {0} ({1})! + + + Estimated from the band and the WiFi standard: the channel width could not be read from the beacon of the access point. + + + Changed + + + {0} Changed + + + Previously: {0} + + + Only when the networks are scanned automatically ("Automatically update every") and WiFi is shown: one notification per scan with the changes since the previous scan of the adapter. + \ No newline at end of file diff --git a/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs index 78e866df04..d33a86bf35 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs @@ -6,12 +6,59 @@ using System.Text; using System.Xml.Linq; using NETworkManager.Models.Network; +using NETworkManager.Utilities; using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { + /// + /// Exported column (CSV) / element (XML, JSON key) of a WiFi network, see . + /// + /// Name of the column / element. + /// Gets the value of a network (e.g. a string, a number, an enum or a time span). + /// The value is quoted in the CSV file (text that may contain a comma, e.g. the SSID). + private sealed record WiFiNetworkExportField( + string Name, + Func GetValue, + bool IsQuoted = false); + + /// + /// Exported values of a WiFi network - one list for CSV, XML and JSON. The released columns come first, new ones + /// are appended at the end, so the position of a column never changes. + /// + private static readonly WiFiNetworkExportField[] WiFiNetworkExportFields = + [ + new(nameof(WiFiNetworkInfo.Bssid), x => x.Bssid), + new(nameof(WiFiNetworkInfo.AvailableNetwork.Ssid), x => x.AvailableNetwork.Ssid, true), + new(nameof(WiFiNetworkInfo.AvailableNetwork.ChannelCenterFrequencyInKilohertz), + x => x.AvailableNetwork.ChannelCenterFrequencyInKilohertz), + new(nameof(WiFiNetworkInfo.AvailableNetwork.SignalBars), x => x.AvailableNetwork.SignalBars), + new(nameof(WiFiNetworkInfo.AvailableNetwork.IsWiFiDirect), x => x.AvailableNetwork.IsWiFiDirect), + new(nameof(WiFiNetworkInfo.AvailableNetwork.NetworkRssiInDecibelMilliwatts), + x => x.AvailableNetwork.NetworkRssiInDecibelMilliwatts), + new(nameof(WiFiNetworkInfo.AvailableNetwork.PhyKind), x => x.AvailableNetwork.PhyKind), + new(nameof(WiFiNetworkInfo.AvailableNetwork.NetworkKind), x => x.AvailableNetwork.NetworkKind), + new(nameof(WiFiNetworkInfo.AvailableNetwork.SecuritySettings.NetworkAuthenticationType), + x => x.AvailableNetwork.SecuritySettings.NetworkAuthenticationType), + new(nameof(WiFiNetworkInfo.AvailableNetwork.SecuritySettings.NetworkEncryptionType), + x => x.AvailableNetwork.SecuritySettings.NetworkEncryptionType), + new(nameof(WiFiNetworkInfo.AvailableNetwork.BeaconInterval), x => x.AvailableNetwork.BeaconInterval), + new(nameof(WiFiNetworkInfo.AvailableNetwork.Uptime), x => x.AvailableNetwork.Uptime), + // Values shown in the grid + new(nameof(WiFiNetworkInfo.IsConnected), x => x.IsConnected), + // Human-readable authentication type (e.g. "WPA2 Personal (PSK)") + new("Security", x => x.NetworkAuthenticationType, true), + new(nameof(WiFiNetworkInfo.Channel), x => x.Channel), + // MHz, estimated if the width could not be read from the beacon + new("ChannelWidth", x => x.ChannelBandwidth), + new("ChannelWidthEstimated", x => x.IsChannelBandwidthEstimated), + new(nameof(WiFiNetworkInfo.Vendor), x => x.Vendor, true), + // Change since the previous scan of the same adapter (empty without a previous scan / change) + new(nameof(WiFiNetworkInfo.Change), x => x.Change == WiFiNetworkChange.None ? null : x.Change.ToString()) + ]; + /// /// Method to export objects from type to a file. /// @@ -46,12 +93,15 @@ private static void CreateCsv(IEnumerable collection, string fi { var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine( - $"{nameof(WiFiNetworkInfo.AvailableNetwork.Bssid)},{nameof(WiFiNetworkInfo.AvailableNetwork.Ssid)},{nameof(WiFiNetworkInfo.AvailableNetwork.ChannelCenterFrequencyInKilohertz)},{nameof(WiFiNetworkInfo.AvailableNetwork.SignalBars)},{nameof(WiFiNetworkInfo.AvailableNetwork.IsWiFiDirect)},{nameof(WiFiNetworkInfo.AvailableNetwork.NetworkRssiInDecibelMilliwatts)},{nameof(WiFiNetworkInfo.AvailableNetwork.PhyKind)},{nameof(WiFiNetworkInfo.AvailableNetwork.NetworkKind)},{nameof(WiFiNetworkInfo.AvailableNetwork.SecuritySettings.NetworkAuthenticationType)},{nameof(WiFiNetworkInfo.AvailableNetwork.SecuritySettings.NetworkEncryptionType)},{nameof(WiFiNetworkInfo.AvailableNetwork.BeaconInterval)},{nameof(WiFiNetworkInfo.AvailableNetwork.Uptime)}"); + stringBuilder.AppendLine(string.Join(",", WiFiNetworkExportFields.Select(field => field.Name))); foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.AvailableNetwork.Bssid},{info.AvailableNetwork.Ssid},{info.AvailableNetwork.ChannelCenterFrequencyInKilohertz},{info.AvailableNetwork.SignalBars},{info.AvailableNetwork.IsWiFiDirect},{info.AvailableNetwork.NetworkRssiInDecibelMilliwatts},{info.AvailableNetwork.PhyKind},{info.AvailableNetwork.NetworkKind},{info.AvailableNetwork.SecuritySettings.NetworkAuthenticationType},{info.AvailableNetwork.SecuritySettings.NetworkEncryptionType},{info.AvailableNetwork.BeaconInterval},{info.AvailableNetwork.Uptime}"); + stringBuilder.AppendLine(string.Join(",", WiFiNetworkExportFields.Select(field => + { + var value = Convert.ToString(field.GetValue(info), CultureInfo.CurrentCulture); + + return field.IsQuoted ? CsvHelper.QuoteString(value) : value; + }))); File.WriteAllText(filePath, stringBuilder.ToString()); } @@ -67,32 +117,9 @@ private static void CreateXml(IEnumerable collection, string fi new XElement(ApplicationName.WiFi.ToString(), new XElement(nameof(WiFiNetworkInfo) + "s", from info in collection - select - new XElement(nameof(WiFiNetworkInfo), - new XElement(nameof(WiFiNetworkInfo.AvailableNetwork.Bssid), info.AvailableNetwork.Bssid), - new XElement(nameof(WiFiNetworkInfo.AvailableNetwork.Ssid), info.AvailableNetwork.Ssid), - new XElement(nameof(WiFiNetworkInfo.AvailableNetwork.ChannelCenterFrequencyInKilohertz), - info.AvailableNetwork.ChannelCenterFrequencyInKilohertz), - new XElement(nameof(WiFiNetworkInfo.AvailableNetwork.SignalBars), - info.AvailableNetwork.SignalBars), - new XElement(nameof(WiFiNetworkInfo.AvailableNetwork.IsWiFiDirect), - info.AvailableNetwork.IsWiFiDirect), - new XElement(nameof(WiFiNetworkInfo.AvailableNetwork.NetworkRssiInDecibelMilliwatts), - info.AvailableNetwork.NetworkRssiInDecibelMilliwatts), - new XElement(nameof(WiFiNetworkInfo.AvailableNetwork.PhyKind), - info.AvailableNetwork.PhyKind), - new XElement(nameof(WiFiNetworkInfo.AvailableNetwork.NetworkKind), - info.AvailableNetwork.NetworkKind), - new XElement( - nameof(WiFiNetworkInfo.AvailableNetwork.SecuritySettings.NetworkAuthenticationType), - info.AvailableNetwork.SecuritySettings.NetworkAuthenticationType), - new XElement( - nameof(WiFiNetworkInfo.AvailableNetwork.SecuritySettings.NetworkEncryptionType), - info.AvailableNetwork.SecuritySettings.NetworkEncryptionType), - new XElement(nameof(WiFiNetworkInfo.AvailableNetwork.BeaconInterval), - info.AvailableNetwork.BeaconInterval), - new XElement(nameof(WiFiNetworkInfo.AvailableNetwork.Uptime), - info.AvailableNetwork.Uptime))))); + select new XElement(nameof(WiFiNetworkInfo), + from field in WiFiNetworkExportFields + select new XElement(field.Name, field.GetValue(info)))))); document.Save(filePath); } @@ -104,28 +131,17 @@ from info in collection /// Path to the export file. private static void CreateJson(IReadOnlyList collection, string filePath) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new + var jsonData = collection + .Select(info => WiFiNetworkExportFields.ToDictionary(field => field.Name, field => { - collection[i].AvailableNetwork.Bssid, - collection[i].AvailableNetwork.Ssid, - collection[i].AvailableNetwork.ChannelCenterFrequencyInKilohertz, - SignalBars = collection[i].AvailableNetwork.SignalBars.ToString(), - IsWiFiDirect = collection[i].AvailableNetwork.IsWiFiDirect.ToString(), - NetworkRssiInDecibelMilliwatts = collection[i].AvailableNetwork.NetworkRssiInDecibelMilliwatts - .ToString(CultureInfo.CurrentCulture), - PhyKind = collection[i].AvailableNetwork.PhyKind.ToString(), - NetworkKind = collection[i].AvailableNetwork.NetworkKind.ToString(), - NetworkAuthenticationType = - collection[i].AvailableNetwork.SecuritySettings.NetworkAuthenticationType.ToString(), - NetworkEncryptionType = - collection[i].AvailableNetwork.SecuritySettings.NetworkEncryptionType.ToString(), - BeaconInterval = collection[i].AvailableNetwork.BeaconInterval.ToString(), - Uptime = collection[i].AvailableNetwork.Uptime.ToString() - }; + var value = field.GetValue(info); + + // Numbers (frequency), text and empty values as they are, other values (enums, time spans, signal bars, + // RSSI) as text like in the CSV file + return value is null or int or string ? value : Convert.ToString(value, CultureInfo.CurrentCulture); + })) + .ToArray(); File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Network/WiFi.cs b/Source/NETworkManager.Models/Network/WiFi.cs index d9475faca6..ca7ab25944 100644 --- a/Source/NETworkManager.Models/Network/WiFi.cs +++ b/Source/NETworkManager.Models/Network/WiFi.cs @@ -7,6 +7,7 @@ using Windows.Networking.Connectivity; using Windows.Security.Credentials; using NETworkManager.Models.Lookup; +using NETworkManager.Utilities; namespace NETworkManager.Models.Network; @@ -46,7 +47,8 @@ public static async Task> GetAdapterAsync() wifiAdapterInfos.Add(new WiFiAdapterInfo { NetworkInterfaceInfo = networkInterface, - WiFiAdapter = wiFiAdapter + WiFiAdapter = wiFiAdapter, + IsOperational = networkInterface.IsOperational }); else Log.Warn($"Could not find network interface for WiFi adapter with id: {wiFiAdapterId}"); @@ -55,6 +57,34 @@ public static async Task> GetAdapterAsync() return wifiAdapterInfos; } + /// + /// Updates of the adapters (e.g. after connecting or + /// disconnecting). Reads only the operational status of the network interfaces (fast), not all + /// their information like . + /// + /// Wi-Fi adapters to update. + public static void UpdateAdapterStates(IEnumerable adapters) + { + // Optional (only the icon of the adapter selection): an error keeps the previous states instead of failing the + // scan it is called after + try + { + var states = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var networkInterface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) + states.TryAdd(networkInterface.Id, + networkInterface.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up); + + foreach (var adapter in adapters) + if (states.TryGetValue(adapter.NetworkInterfaceInfo.Id, out var isOperational)) + adapter.IsOperational = isOperational; + } + catch (Exception ex) + { + Log.Error("Error while reading the state of the WiFi adapters.", ex); + } + } + /// /// Get all available Wi-Fi networks for an adapter with additional information's. /// @@ -65,32 +95,52 @@ public static async Task GetNetworksAsync(WiFiAdapter adapt // Scan network adapter async await adapter.ScanAsync(); - // Try to get the current connected Wi-Fi network of this network adapter - var (_, bssid) = TryGetConnectedNetworkFromWiFiAdapter(adapter.NetworkAdapter.NetworkAdapterId.ToString()); + // The rest (native calls, vendor lookups) runs in the background - the caller continues on the UI thread + // after ScanAsync + return await Task.Run(() => CreateScanInfo(adapter)); + } + + /// + /// Creates the result of a scan from the network report of the adapter. + /// + /// WiFi adapter as after the scan. + /// A report as including a list of . + private static WiFiNetworkScanInfo CreateScanInfo(WiFiAdapter adapter) + { + var adapterId = adapter.NetworkAdapter.NetworkAdapterId; + + // Read once: every access returns the current report, the networks and the time must be of the same one + var report = adapter.NetworkReport; - // The WinRT API does not expose the channel bandwidth, so it is read from the native - // BSS list (wlanapi.dll) and matched by BSSID below. Failures yield an empty map and we - // fall back to a heuristic per network. - var channelWidths = WlanApi.GetBssChannelWidths(adapter.NetworkAdapter.NetworkAdapterId); + // BSSID of the network this adapter is connected to (null if not connected or not read). The WinRT API does + // not expose the channel bandwidth (and its center), so it is read from the native BSS list (wlanapi.dll) + // and matched by BSSID below. Failures yield an empty map and we fall back to a heuristic per network. + var (bssid, channels) = WlanApi.GetBssInfo(adapterId); var wifiNetworkInfos = new List(); - foreach (var availableNetwork in adapter.NetworkReport.AvailableNetworks) + foreach (var availableNetwork in report.AvailableNetworks) { var channelFrequencyInGigahertz = ConvertChannelFrequencyToGigahertz(availableNetwork.ChannelCenterFrequencyInKilohertz); var radio = GetWiFiRadioFromChannelFrequency(channelFrequencyInGigahertz); + var (channelBandwidth, channelBandwidthCenterFrequencyInGigahertz, isChannelBandwidthEstimated) = + GetChannelBandwidth(channels, availableNetwork.Bssid, radio, availableNetwork.PhyKind, + channelFrequencyInGigahertz); var wifiNetworkInfo = new WiFiNetworkInfo { AvailableNetwork = availableNetwork, + Bssid = MACAddressHelper.GetDefaultFormat(availableNetwork.Bssid), Radio = radio, ChannelCenterFrequencyInGigahertz = channelFrequencyInGigahertz, Channel = GetChannelFromChannelFrequency(channelFrequencyInGigahertz), - ChannelBandwidth = GetChannelBandwidth(channelWidths, availableNetwork.Bssid, radio, availableNetwork.PhyKind), + ChannelBandwidth = channelBandwidth, + ChannelBandwidthCenterFrequencyInGigahertz = channelBandwidthCenterFrequencyInGigahertz, + IsChannelBandwidthEstimated = isChannelBandwidthEstimated, IsHidden = string.IsNullOrEmpty(availableNetwork.Ssid), IsConnected = availableNetwork.Bssid.Equals(bssid, StringComparison.OrdinalIgnoreCase), NetworkAuthenticationType = GetHumanReadableNetworkAuthenticationType(availableNetwork.SecuritySettings.NetworkAuthenticationType), - Vendor = (await OUILookup.LookupByMacAddressAsync(availableNetwork.Bssid)).FirstOrDefault()?.Vendor ?? "-/-", + Vendor = OUILookup.LookupByMacAddress(availableNetwork.Bssid).FirstOrDefault()?.Vendor ?? "-/-", PhyKind = GetHumanReadablePhyKind(availableNetwork.PhyKind) }; @@ -99,77 +149,11 @@ public static async Task GetNetworksAsync(WiFiAdapter adapt return new WiFiNetworkScanInfo { - NetworkAdapterId = adapter.NetworkAdapter.NetworkAdapterId, WiFiNetworkInfos = wifiNetworkInfos, - Timestamp = adapter.NetworkReport.Timestamp.LocalDateTime + Timestamp = report.Timestamp.LocalDateTime }; } - /// - /// Try to get the current connected Wi-Fi network (SSID and BSSID) of a network adapter from - /// netsh.exe. - /// Calling netsh.exe and parsing the output feels so dirty, but Microsoft's API returns only - /// the WLAN profile and the SSID of the connected network. The BSSID is needed to find a - /// specific access point among several. - /// - /// GUID of the Wi-Fi network adapter. - /// SSID and BSSID of the connected Wi-Fi network. Values are null if not detected. - // ReSharper disable once UnusedTupleComponentInReturnValue - private static (string SSID, string BSSID) TryGetConnectedNetworkFromWiFiAdapter(string adapterId) - { - string ssid = null; - string bssid = null; - - using (var powerShell = System.Management.Automation.PowerShell.Create()) - { - powerShell.AddScript("netsh wlan show interfaces"); - - var psOutputs = powerShell.Invoke(); - - /* - if (powerShell.Streams.Error.Count > 0) { // Handle error? } - if (powerShell.Streams.Warning.Count > 0) { // Handle warning? } - */ - - /* Each object looks like this: - * - * Name : Wireless - * Description : Intel ... - * GUID : 90d8... - * SSID : Devices - * BSSID : 6a:d7:... - */ - - var foundAdapter = false; - - foreach (var outputItem in psOutputs) - { - // Find line with the network adapter id... - if (outputItem.ToString().Contains(adapterId, StringComparison.OrdinalIgnoreCase)) - foundAdapter = true; - - // ...and skip all lines until we found it. - if (!foundAdapter) - continue; - - // Extract SSID from the line - if (outputItem.ToString().Contains(" SSID ", StringComparison.OrdinalIgnoreCase)) - ssid = outputItem.ToString().Split(':')[1].Trim(); - - // Extract BSSID from the line - if (outputItem.ToString().Contains(" BSSID ", StringComparison.OrdinalIgnoreCase)) - bssid = outputItem.ToString().Split(':', 2)[1].Trim(); - - // Break if we got the values, otherwise we might overwrite them - // with values from another adapter. - if (!string.IsNullOrEmpty(ssid) && !string.IsNullOrEmpty(bssid)) - break; - } - } - - return (ssid, bssid); - } - /// /// Connect to a Wi-Fi network with Pre-shared key, EAP or no security. /// @@ -189,12 +173,7 @@ public static async Task ConnectAsync(WiFiAdapter adapter, else connectionResult = await adapter.ConnectAsync(network, reconnectionKind, credential, ssid); - // Wrong password may cause connection to timeout. - // Disconnect any network from the adapter to return it to a non-busy state. - if (connectionResult.ConnectionStatus == WiFiConnectionStatus.Timeout) - Disconnect(adapter); - - return connectionResult.ConnectionStatus; + return GetConnectionStatus(adapter, connectionResult); } /// @@ -210,6 +189,17 @@ public static async Task ConnectWpsAsync(WiFiAdapter adapt var connectionResult = await adapter.ConnectAsync(network, reconnectionKind, null, string.Empty, WiFiConnectionMethod.WpsPushButton); + return GetConnectionStatus(adapter, connectionResult); + } + + /// + /// Gets the status of a connection attempt. After a timeout the adapter is disconnected. + /// + /// Wi-Fi adapter which was used for the connection. + /// Result of the connection attempt. + /// Status of the connection. + private static WiFiConnectionStatus GetConnectionStatus(WiFiAdapter adapter, WiFiConnectionResult connectionResult) + { // Wrong password may cause connection to timeout. // Disconnect any network from the adapter to return it to a non-busy state. if (connectionResult.ConnectionStatus == WiFiConnectionStatus.Timeout) @@ -235,16 +225,30 @@ public static void Disconnect(WiFiAdapter adapter) /// Connect mode as . public static WiFiConnectMode GetConnectMode(WiFiAvailableNetwork network) { - // Enterprise - if (network.SecuritySettings.NetworkAuthenticationType is NetworkAuthenticationType.Rsna or NetworkAuthenticationType.Wpa) + return GetConnectMode(network.SecuritySettings.NetworkAuthenticationType, + network.SecuritySettings.NetworkEncryptionType); + } + + /// + /// Get the connect mode from the authentication and encryption type of a Wi-Fi network. + /// + /// Authentication type of the network. + /// Encryption type of the network. + /// Connect mode as . + public static WiFiConnectMode GetConnectMode(NetworkAuthenticationType authenticationType, + NetworkEncryptionType encryptionType) + { + // Enterprise (WPA, WPA2, WPA3) + if (authenticationType is NetworkAuthenticationType.Rsna or NetworkAuthenticationType.Wpa + or NetworkAuthenticationType.Wpa3Enterprise or NetworkAuthenticationType.Wpa3Enterprise192Bits) return WiFiConnectMode.Eap; - // Open - if (network.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 || - network.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None) + // Open (no encryption), also OWE (Enhanced Open: encrypted, but without a password). Not Open80211 with WEP: + // the authentication is open, but the WEP key is needed (Pre-Shared-Key) + if (authenticationType == NetworkAuthenticationType.Owe || encryptionType == NetworkEncryptionType.None) return WiFiConnectMode.Open; - // Pre-Shared-Key + // Pre-Shared-Key (WEP, WPA, WPA2, WPA3 SAE) return WiFiConnectMode.Psk; } @@ -265,8 +269,8 @@ public static async Task IsWpsAvailable(WiFiAdapter adapter, WiFiAvailable /// Get the Wi-Fi channel from channel frequency. /// /// Input like 2.422 or 5.240. - /// Wi-Fi channel like 3 or 48. - private static int GetChannelFromChannelFrequency(double gigahertz) + /// Wi-Fi channel like 3 or 48, -1 if the frequency is not a channel. + public static int GetChannelFromChannelFrequency(double gigahertz) { // Convert to integer MHz to avoid floating-point precision issues from the // kilohertz / 1_000_000.0 conversion in ConvertChannelFrequencyToGigahertz. @@ -278,17 +282,39 @@ private static int GetChannelFromChannelFrequency(double gigahertz) if (mhz == 2484) return 14; - // 5 GHz: channels follow f = 5000 + ch×5 MHz - if (mhz is >= 5180 and <= 5825) + // 5 GHz: channels 32-177 follow f = 5000 + ch×5 MHz (169-177 = UNII-4) + if (mhz is >= 5160 and <= 5885) return (mhz - 5000) / 5; - // 6 GHz: channels 1-233 follow f = 5950 + ch×5 MHz + // 6 GHz: channel 2 is at 5935 MHz, channels 1-233 follow f = 5950 + ch×5 MHz + if (mhz == 5935) + return 2; + if (mhz is >= 5955 and <= 7115) return (mhz - 5950) / 5; return -1; } + /// + /// Get the frequency of a Wi-Fi channel (the inverse of ). + /// + /// Channel like 3 or 48. + /// Band of the channel (the channel numbers of the bands overlap). + /// Frequency in MHz like 2422 or 5240. + public static int GetFrequencyFromChannel(int channel, WiFiRadio radio) + { + return radio switch + { + // Channel 14 is at 2484 MHz and does not follow the ch×5 + 2407 spacing + WiFiRadio.GHz2dot4 => channel == 14 ? 2484 : 2407 + channel * 5, + WiFiRadio.GHz5 => 5000 + channel * 5, + // Channel 2 is at 5935 MHz, below channel 1 (5955 MHz) + WiFiRadio.GHz6 => channel == 2 ? 5935 : 5950 + channel * 5, + _ => 0 + }; + } + /// /// Convert the channel frequency to gigahertz. /// @@ -304,40 +330,43 @@ private static double ConvertChannelFrequencyToGigahertz(int kilohertz) /// /// Frequency in gigahertz like 2.412 or 5.180. /// Radio like 2.4 GHz, 5 GHz, etc. as . - private static WiFiRadio GetWiFiRadioFromChannelFrequency(double gigahertz) + public static WiFiRadio GetWiFiRadioFromChannelFrequency(double gigahertz) { return gigahertz switch { >= 2.412 and <= 2.484 => WiFiRadio.GHz2dot4, - >= 5.180 and <= 5.825 => WiFiRadio.GHz5, + >= 5.160 and <= 5.885 => WiFiRadio.GHz5, >= 5.925 and <= 7.125 => WiFiRadio.GHz6, _ => WiFiRadio.Unknown }; } /// - /// Determines the channel bandwidth (MHz) for a network. Prefers the value parsed from the - /// native BSS list (); if unavailable, falls back to a heuristic based - /// on the radio band and PHY kind, and finally to 20 MHz. + /// Determines the channel bandwidth (MHz) and its center frequency (GHz) for a network. Prefers + /// the values parsed from the native BSS list (); if unavailable, falls back + /// to a heuristic based on the radio band and PHY kind (centered on the primary channel, marked as estimated). /// - private static int GetChannelBandwidth(IReadOnlyDictionary channelWidths, string networkBssid, - WiFiRadio radio, WiFiPhyKind phyKind) + private static (int Bandwidth, double CenterFrequencyInGigahertz, bool IsEstimated) GetChannelBandwidth( + IReadOnlyDictionary channels, string networkBssid, WiFiRadio radio, + WiFiPhyKind phyKind, double primaryFrequencyInGigahertz) { - if (!string.IsNullOrEmpty(networkBssid) && channelWidths.TryGetValue(networkBssid, out var width) && width > 0) - return width; - - return GetHeuristicChannelBandwidth(radio, phyKind); + if (!string.IsNullOrEmpty(networkBssid) && channels.TryGetValue(networkBssid, out var channel) && + channel.BandwidthMHz > 0 && channel.CenterFrequencyMHz > 0) + return (channel.BandwidthMHz, channel.CenterFrequencyMHz / 1000.0, false); + + return (GetHeuristicChannelBandwidth(radio, phyKind), primaryFrequencyInGigahertz, true); } /// /// Estimates the channel bandwidth (MHz) from the radio band and PHY kind when the exact - /// value could not be read from the BSS list. + /// value could not be read from the BSS list. 2.4 GHz is always 20 MHz: 40 MHz is supported since + /// 802.11n, but rarely used (only 3 channels without overlap). /// private static int GetHeuristicChannelBandwidth(WiFiRadio radio, WiFiPhyKind phyKind) { return radio switch { - WiFiRadio.GHz2dot4 => phyKind == WiFiPhyKind.HT ? 40 : 20, + WiFiRadio.GHz2dot4 => 20, WiFiRadio.GHz5 => phyKind switch { WiFiPhyKind.Vht or WiFiPhyKind.HE or WiFiPhyKind.Eht => 80, @@ -358,8 +387,8 @@ public static string GetHumanReadableNetworkAuthenticationType(NetworkAuthentica { return networkAuthenticationType switch { - NetworkAuthenticationType.None => "-/-", - NetworkAuthenticationType.Unknown => "Unknown", + // No value like an unknown vendor ("Unknown" is not translated in the model) + NetworkAuthenticationType.None or NetworkAuthenticationType.Unknown => "-/-", NetworkAuthenticationType.Open80211 => "Open", NetworkAuthenticationType.SharedKey80211 => "WEP", NetworkAuthenticationType.Wpa => "WPA Enterprise", @@ -385,7 +414,7 @@ public static string GetHumanReadablePhyKind(WiFiPhyKind phyKind) { return phyKind switch { - WiFiPhyKind.Unknown => "Unknown", + WiFiPhyKind.Unknown => "-/-", WiFiPhyKind.Dsss or WiFiPhyKind.Fhss => "802.11", WiFiPhyKind.Ofdm => "802.11a", WiFiPhyKind.Hrdsss => "802.11b", diff --git a/Source/NETworkManager.Models/Network/WiFiAdapterInfo.cs b/Source/NETworkManager.Models/Network/WiFiAdapterInfo.cs index 46dfdd190d..134db6716e 100644 --- a/Source/NETworkManager.Models/Network/WiFiAdapterInfo.cs +++ b/Source/NETworkManager.Models/Network/WiFiAdapterInfo.cs @@ -1,9 +1,28 @@ -using Windows.Devices.WiFi; +using NETworkManager.Utilities; +using Windows.Devices.WiFi; namespace NETworkManager.Models.Network; -public class WiFiAdapterInfo +public class WiFiAdapterInfo : PropertyChangedBase { public NetworkInterfaceInfo NetworkInterfaceInfo { get; set; } public WiFiAdapter WiFiAdapter { get; set; } + + /// + /// Indicates if the adapter is up (connected to a network). Updated after each scan (see + /// ), is the state when the adapters + /// were loaded. + /// + public bool IsOperational + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/WiFiChannelAxis.cs b/Source/NETworkManager.Models/Network/WiFiChannelAxis.cs new file mode 100644 index 0000000000..c62344bba4 --- /dev/null +++ b/Source/NETworkManager.Models/Network/WiFiChannelAxis.cs @@ -0,0 +1,90 @@ +using System; + +namespace NETworkManager.Models.Network; + +/// +/// Position of a WiFi channel on the X axis of a channel chart. The axis is in channel-number space (5 MHz per +/// unit, linear with the frequency). In the 5 GHz chart the unused range between channel 64 (UNII-2) and channel +/// 100 (UNII-2 Extended) is compressed; the 6 GHz band is split into a lower (1 - 125) and an upper (129 - 233) +/// chart. +/// +public static class WiFiChannelAxis +{ + /// + /// Channel that splits the 6 GHz band into the lower (1 - 125) and the upper (129 - 233) chart. It sits between + /// the operating channels 125 and 129. + /// + public const int SixGHzSplitChannel = 127; + + // The 5 GHz range 64 - 100 is shown with 16 units instead of 36: channels above 64 are shifted left, leaving a + // small gap that still has room for the channel-width trapezoids. + private const int FiveGHzGapStartChannel = 64; + private const int FiveGHzGapEndChannel = 100; + private const int FiveGHzGapDisplayUnits = 16; + private const int FiveGHzGapShift = FiveGHzGapEndChannel - FiveGHzGapStartChannel - FiveGHzGapDisplayUnits; + + /// + /// Converts a frequency (e.g. the center of a channel) to channel-number space (5 MHz per unit). + /// + /// Frequency in MHz like 2422 or 5210. + /// Band of the frequency. + /// Channel number, fractional between two channels (e.g. 3 for 2422 MHz, 42 for 5210 MHz). + public static double FrequencyToChannel(double frequencyMHz, WiFiRadio radio) + { + return radio switch + { + // Channel 14 is at 2484 MHz and does not follow the standard ch×5 + 2407 spacing. + WiFiRadio.GHz2dot4 => (int)Math.Round(frequencyMHz) == 2484 ? 14.0 : (frequencyMHz - 2407) / 5.0, + WiFiRadio.GHz5 => (frequencyMHz - 5000) / 5.0, + // Channel 2 is at 5935 MHz, below channel 1 (5955 MHz) - drawn at its real position (-3) + WiFiRadio.GHz6 => (frequencyMHz - 5950) / 5.0, + _ => 0 + }; + } + + /// + /// Maps a channel number to its position on the X axis (the 5 GHz gap is compressed). + /// + /// Channel number (see ). + /// Band of the channel. + /// Position on the X axis. + public static double ChannelToPosition(double channel, WiFiRadio radio) + { + if (radio == WiFiRadio.GHz5 && channel > FiveGHzGapStartChannel) + return channel - FiveGHzGapShift; + + return channel; + } + + /// + /// Maps a position on the X axis back to the channel number (the inverse of ), + /// for the labels of the axis. + /// + /// Position on the X axis (rounded to a whole channel). + /// Band of the chart. + /// Channel number at the position. + public static int PositionToChannel(int position, WiFiRadio radio) + { + if (radio == WiFiRadio.GHz5 && position > FiveGHzGapStartChannel) + return position + FiveGHzGapShift; + + return position; + } + + /// + /// Gets the 6 GHz charts a channel is drawn in: the lower (1 - 125), the upper (129 - 233) or both, if the + /// channel crosses the split (e.g. 320 MHz around channel 127 covers 95 - 159). + /// + /// Center frequency of the whole channel in MHz. + /// Channel width in MHz (20, 40, 80, 160, 320). + /// Whether the channel is drawn in the lower and / or the upper chart. + public static (bool Lower, bool Upper) GetSixGHzCharts(double centerFrequencyMHz, int bandwidthMHz) + { + var center = FrequencyToChannel(centerFrequencyMHz, WiFiRadio.GHz6); + + // Channel-number space uses 5 MHz per unit: half of the width is bandwidth / 10 units + var halfWidth = bandwidthMHz / 10.0; + + return (center - halfWidth < SixGHzSplitChannel, center + halfWidth > SixGHzSplitChannel); + } +} diff --git a/Source/NETworkManager.Models/Network/WiFiNetworkChange.cs b/Source/NETworkManager.Models/Network/WiFiNetworkChange.cs new file mode 100644 index 0000000000..f14561f3c4 --- /dev/null +++ b/Source/NETworkManager.Models/Network/WiFiNetworkChange.cs @@ -0,0 +1,28 @@ +namespace NETworkManager.Models.Network; + +/// +/// Change of a WiFi network (BSSID) since the previous scan of the same adapter (see ). +/// +public enum WiFiNetworkChange +{ + /// + /// No change, or there is no previous scan to compare with. + /// + None, + + /// + /// The network is visible now, it was not visible in the previous scan. + /// + New, + + /// + /// The network was visible in the previous scan, it is not visible now. + /// + Gone, + + /// + /// The channel, the channel width or the security of the network changed (e.g. the access point switched the + /// channel because of interference or radar). + /// + Changed +} diff --git a/Source/NETworkManager.Models/Network/WiFiNetworkInfo.cs b/Source/NETworkManager.Models/Network/WiFiNetworkInfo.cs index 025c839c50..0e8b398eef 100644 --- a/Source/NETworkManager.Models/Network/WiFiNetworkInfo.cs +++ b/Source/NETworkManager.Models/Network/WiFiNetworkInfo.cs @@ -7,14 +7,6 @@ namespace NETworkManager.Models.Network; /// public class WiFiNetworkInfo { - /// - /// /// Create an instance of . - /// - public WiFiNetworkInfo() - { - - } - #region Variables /// @@ -22,13 +14,20 @@ public WiFiNetworkInfo() /// public WiFiAvailableNetwork AvailableNetwork { get; init; } + /// + /// BSSID (MAC address of the access point) in the default format of the application (e.g. + /// AA:BB:CC:DD:EE:FF), like the MAC addresses of the other tools. + /// + public string Bssid { get; init; } + /// /// Radio that is used like 2.4 GHz, 5 GHz, etc. /// public WiFiRadio Radio { get; init; } /// - /// The channel center frequency in Gigahertz like 2.4 GHz, 5 GHz, etc. + /// The channel center frequency in Gigahertz like 2.4 GHz, 5 GHz, etc. of the primary 20 MHz channel (where the + /// beacons are sent). /// public double ChannelCenterFrequencyInGigahertz { get; set; } @@ -43,6 +42,18 @@ public WiFiNetworkInfo() /// public int ChannelBandwidth { get; set; } + /// + /// The center frequency in Gigahertz of the whole channel (), e.g. 5.21 for + /// 80 MHz on the channels 36 - 48. The frequency of the primary channel if the bandwidth is estimated. + /// + public double ChannelBandwidthCenterFrequencyInGigahertz { get; set; } + + /// + /// Indicates if the is estimated from the radio band and the PHY kind, because it + /// could not be read from the beacon of the access point. + /// + public bool IsChannelBandwidthEstimated { get; set; } + /// /// Indicates if the Wi-Fi network Ssid is hidden. /// @@ -67,5 +78,17 @@ public WiFiNetworkInfo() /// Human-readable phy kind. /// public string PhyKind { get; set; } + + /// + /// Change since the previous scan of the same adapter (set by the view model after the scan, see + /// ). + /// + public WiFiNetworkChange Change { get; set; } + + /// + /// The network of the previous scan if it (channel, channel width or + /// security), otherwise null. + /// + public WiFiNetworkInfo Previous { get; set; } #endregion } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/WiFiNetworkScannfo.cs b/Source/NETworkManager.Models/Network/WiFiNetworkScanInfo.cs similarity index 65% rename from Source/NETworkManager.Models/Network/WiFiNetworkScannfo.cs rename to Source/NETworkManager.Models/Network/WiFiNetworkScanInfo.cs index d5f2c389b2..231bbfa459 100644 --- a/Source/NETworkManager.Models/Network/WiFiNetworkScannfo.cs +++ b/Source/NETworkManager.Models/Network/WiFiNetworkScanInfo.cs @@ -8,20 +8,8 @@ namespace NETworkManager.Models.Network; /// public class WiFiNetworkScanInfo { - /// - /// Create an instance of . - /// - public WiFiNetworkScanInfo() - { - } - #region Variables - /// - /// If of the network adapter who performed the scan. - /// - public Guid NetworkAdapterId { get; set; } - /// /// List of available WiFi networks on the network adapter. /// diff --git a/Source/NETworkManager.Models/Network/WiFiScanComparer.cs b/Source/NETworkManager.Models/Network/WiFiScanComparer.cs new file mode 100644 index 0000000000..234ed9ec2f --- /dev/null +++ b/Source/NETworkManager.Models/Network/WiFiScanComparer.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; + +namespace NETworkManager.Models.Network; + +/// +/// Result of . +/// +/// +/// Networks of the current scan with a change ( or +/// ) and the network of the previous scan (null if new). +/// +/// Networks of the previous scan that are not visible now (in the order of the previous scan). +public sealed record WiFiScanComparison( + IReadOnlyList<(WiFiNetworkInfo Network, WiFiNetworkChange Change, WiFiNetworkInfo Previous)> Changes, + IReadOnlyList Gone); + +/// +/// Compares a scan of the WiFi networks with the previous scan of the same adapter, by BSSID: which networks are +/// new, gone or changed their channel, channel width or security. The signal strength is not a change (it varies +/// with every scan). +/// +public static class WiFiScanComparer +{ + /// + /// Compares the current scan with the previous one. + /// + /// Networks of the previous scan. + /// Networks of the current scan. + /// Changes of the current networks and the gone networks. + public static WiFiScanComparison Compare(IReadOnlyList previous, + IReadOnlyList current) + { + var previousByBssid = ByBssid(previous); + var currentByBssid = ByBssid(current); + + var changes = new List<(WiFiNetworkInfo, WiFiNetworkChange, WiFiNetworkInfo)>(); + var gone = new List(); + + foreach (var network in currentByBssid.Values) + { + if (!previousByBssid.TryGetValue(network.Bssid, out var previousNetwork)) + changes.Add((network, WiFiNetworkChange.New, null)); + else if (IsChanged(previousNetwork, network)) + changes.Add((network, WiFiNetworkChange.Changed, previousNetwork)); + } + + foreach (var network in previousByBssid.Values) + { + if (!currentByBssid.ContainsKey(network.Bssid)) + gone.Add(network); + } + + return new WiFiScanComparison(changes, gone); + } + + /// + /// The channel, the channel width or the security changed. A width that was estimated in one of the scans is not + /// compared (it differs if the beacon could be read in one scan only). + /// + private static bool IsChanged(WiFiNetworkInfo previous, WiFiNetworkInfo current) + { + return previous.Channel != current.Channel || + (!previous.IsChannelBandwidthEstimated && !current.IsChannelBandwidthEstimated && + previous.ChannelBandwidth != current.ChannelBandwidth) || + !string.Equals(previous.NetworkAuthenticationType, current.NetworkAuthenticationType, + StringComparison.Ordinal); + } + + /// + /// Networks by BSSID, in their order (the first one if a BSSID is reported twice). + /// + private static Dictionary ByBssid(IEnumerable networks) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var network in networks) + if (!string.IsNullOrEmpty(network.Bssid)) + result.TryAdd(network.Bssid, network); + + return result; + } +} diff --git a/Source/NETworkManager.Models/Network/WlanApi.cs b/Source/NETworkManager.Models/Network/WlanApi.cs index 8ac684c0e9..b9e8d242ff 100644 --- a/Source/NETworkManager.Models/Network/WlanApi.cs +++ b/Source/NETworkManager.Models/Network/WlanApi.cs @@ -7,13 +7,14 @@ namespace NETworkManager.Models.Network; /// /// Native Wi-Fi (wlanapi.dll) interop used to determine the channel bandwidth -/// (20 / 40 / 80 / 160 MHz) of nearby access points. +/// (20 / 40 / 80 / 160 / 320 MHz) and its center frequency of nearby access points. /// /// The Windows Runtime Wi-Fi API () does -/// not expose the channel width. The native BSS list (WlanGetNetworkBssList) however -/// returns the raw 802.11 information elements (IEs) of each beacon / probe response. The width -/// is parsed from the HT-Operation (802.11n), VHT-Operation (802.11ac) and HE-Operation -/// (802.11ax / 6 GHz) elements. +/// not expose the channel width, its frequency is the one of the primary 20 MHz channel (where +/// the beacons are sent). The native BSS list (WlanGetNetworkBssList) however returns the +/// raw 802.11 information elements (IEs) of each beacon / probe response. The width and the +/// center of the whole channel are parsed from the HT-Operation (802.11n), VHT-Operation +/// (802.11ac), HE-Operation (802.11ax / 6 GHz) and EHT-Operation (802.11be) elements. /// /// All calls are wrapped in try/catch; on any failure an empty result is returned so the caller /// can fall back to a heuristic (see ). @@ -25,11 +26,28 @@ public static class WlanApi private const uint WlanApiVersion2 = 0x00000002; private const uint ErrorSuccess = 0; + // WLAN_INTF_OPCODE wlan_intf_opcode_current_connection: WLAN_CONNECTION_ATTRIBUTES of the interface. + private const uint WlanIntfOpcodeCurrentConnection = 7; + + // Offset of WLAN_ASSOCIATION_ATTRIBUTES.dot11Bssid in WLAN_CONNECTION_ATTRIBUTES: isState (4), wlanConnectionMode + // (4), strProfileName (WCHAR[256] = 512), dot11Ssid (4 + 32), dot11BssType (4). + private const int ConnectionAttributesBssidOffset = 4 + 4 + 512 + 36 + 4; + // 802.11 information element identifiers. private const byte EidHtOperation = 61; private const byte EidVhtOperation = 192; private const byte EidExtension = 255; private const byte ExtEidHeOperation = 36; + private const byte ExtEidEhtOperation = 106; + + /// + /// Channel of an access point parsed from its information elements. + /// + /// Channel width in MHz (20, 40, 80, 160, 320), 0 if unknown. + /// + /// Center frequency of the whole channel in MHz (e.g. 5210 for 80 MHz on the channels 36 - 48), 0 if unknown. + /// + public readonly record struct WlanBssChannel(int BandwidthMHz, int CenterFrequencyMHz); private enum DOT11_BSS_TYPE { @@ -55,6 +73,10 @@ private static extern uint WlanGetNetworkBssList(IntPtr hClientHandle, ref Guid IntPtr pDot11Ssid, DOT11_BSS_TYPE dot11BssType, [MarshalAs(UnmanagedType.Bool)] bool bSecurityEnabled, IntPtr pReserved, out IntPtr ppWlanBssList); + [DllImport("wlanapi.dll")] + private static extern uint WlanQueryInterface(IntPtr hClientHandle, ref Guid pInterfaceGuid, uint opCode, + IntPtr pReserved, out uint pdwDataSize, out IntPtr ppData, IntPtr pWlanOpcodeValueType); + [DllImport("wlanapi.dll")] private static extern uint WlanEnumInterfaces(IntPtr hClientHandle, IntPtr pReserved, out IntPtr ppInterfaceList); @@ -123,15 +145,19 @@ private struct WLAN_BSS_ENTRY } /// - /// Returns a map of BSSID (lowercase, colon-separated, e.g. aa:bb:cc:dd:ee:ff) to the - /// channel bandwidth in MHz for all access points visible to the given Wi-Fi interface. - /// BSSIDs whose width could not be parsed are omitted from the result. + /// Reads the BSSID of the connected access point and the channels (width and center) of all access points + /// visible to the given Wi-Fi interface, with one client handle. /// /// GUID of the Wi-Fi interface (NetworkAdapter.NetworkAdapterId). - /// A (possibly empty) map of BSSID to channel bandwidth in MHz. - public static Dictionary GetBssChannelWidths(Guid interfaceGuid) + /// + /// The BSSID of the connected access point (lowercase, colon-separated, e.g. aa:bb:cc:dd:ee:ff; null if + /// not connected or not read) and a (possibly empty) map of BSSID to its channel. BSSIDs whose width could not + /// be parsed are omitted. + /// + public static (string ConnectedBssid, Dictionary Channels) GetBssInfo(Guid interfaceGuid) { - var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + var channels = new Dictionary(StringComparer.OrdinalIgnoreCase); + string connectedBssid = null; var clientHandle = IntPtr.Zero; @@ -142,15 +168,17 @@ public static Dictionary GetBssChannelWidths(Guid interfaceGuid) if (ret != ErrorSuccess) { Log.Warn($"WlanOpenHandle failed with error code {ret}."); - return result; + return (null, channels); } + connectedBssid = GetConnectedBssid(clientHandle, interfaceGuid); + // The WinRT NetworkAdapterId normally matches the native WLAN interface GUID. If it does // not (driver/OS specifics), fall back to enumerating all WLAN interfaces and merging // their BSS lists (matching is done by BSSID, so mixing interfaces is harmless). - if (!TryQueryBssList(clientHandle, interfaceGuid, result)) + if (!TryQueryBssList(clientHandle, interfaceGuid, channels)) foreach (var guid in EnumerateInterfaces(clientHandle)) - TryQueryBssList(clientHandle, guid, result); + TryQueryBssList(clientHandle, guid, channels); } catch (Exception ex) { @@ -162,14 +190,55 @@ public static Dictionary GetBssChannelWidths(Guid interfaceGuid) WlanCloseHandle(clientHandle, IntPtr.Zero); } - return result; + return (connectedBssid, channels); } /// - /// Queries the BSS list for a single WLAN interface and adds the parsed channel widths to + /// Returns the BSSID of the access point the given Wi-Fi interface is connected to. + /// + /// Open client handle. + /// GUID of the Wi-Fi interface. + /// The BSSID, or null if the interface is not connected or it could not be read. + private static string GetConnectedBssid(IntPtr clientHandle, Guid interfaceGuid) + { + var dataPtr = IntPtr.Zero; + + try + { + var guid = interfaceGuid; + + // Fails with ERROR_INVALID_STATE (5023) if the interface is not connected + var ret = WlanQueryInterface(clientHandle, ref guid, WlanIntfOpcodeCurrentConnection, IntPtr.Zero, + out var dataSize, out dataPtr, IntPtr.Zero); + + if (ret != ErrorSuccess || dataPtr == IntPtr.Zero || dataSize < ConnectionAttributesBssidOffset + 6) + return null; + + var bssid = new byte[6]; + Marshal.Copy(IntPtr.Add(dataPtr, ConnectionAttributesBssidOffset), bssid, 0, 6); + + return FormatBssid(bssid); + } + catch (Exception ex) + { + // Optional (marks the connected network): the BSS list is still read + Log.Error("Error while reading the connected Wi-Fi network via wlanapi.dll.", ex); + + return null; + } + finally + { + if (dataPtr != IntPtr.Zero) + WlanFreeMemory(dataPtr); + } + } + + /// + /// Queries the BSS list for a single WLAN interface and adds the parsed channels to /// . Returns if the query succeeded. /// - private static bool TryQueryBssList(IntPtr clientHandle, Guid interfaceGuid, Dictionary result) + private static bool TryQueryBssList(IntPtr clientHandle, Guid interfaceGuid, + Dictionary result) { var bssListPtr = IntPtr.Zero; @@ -213,10 +282,11 @@ private static bool TryQueryBssList(IntPtr clientHandle, Guid interfaceGuid, Dic var ie = new byte[ieSize]; Marshal.Copy(IntPtr.Add(bssListPtr, (int)ieStart), ie, 0, ieSize); - var width = GetBandwidthFromInformationElements(ie); + // Frequency of the primary channel (kHz) + var channel = GetChannelFromInformationElements(ie, (int)(entry.ulChCenterFrequency / 1000)); - if (width > 0) - result[FormatBssid(entry.dot11Bssid)] = width; + if (channel.BandwidthMHz > 0) + result[FormatBssid(entry.dot11Bssid)] = channel; } return true; @@ -267,13 +337,18 @@ private static List EnumerateInterfaces(IntPtr clientHandle) } /// - /// Walks the TLV-encoded 802.11 information elements and returns the widest channel - /// bandwidth (MHz) advertised by the HT-, VHT- or HE-Operation element. Returns 0 if none - /// of these elements are present. + /// Walks the TLV-encoded 802.11 information elements and returns the widest channel advertised + /// by the HT-, VHT-, HE- or EHT-Operation element, with the center frequency of the whole channel. + /// Returns default (width 0) if none of these elements are present. /// - private static int GetBandwidthFromInformationElements(byte[] ie) + /// Information elements of a beacon / probe response. + /// Frequency of the primary 20 MHz channel in MHz (e.g. 5180). + public static WlanBssChannel GetChannelFromInformationElements(byte[] ie, int primaryFrequencyMHz) { - int htWidth = 0, vhtWidth = 0, heWidth = 0; + WlanBssChannel ht = default; + byte[] vhtOperation = null; + int heOffset = -1, heLength = 0; + int ehtOffset = -1, ehtLength = 0; var pos = 0; @@ -289,50 +364,94 @@ private static int GetBandwidthFromInformationElements(byte[] ie) switch (id) { case EidHtOperation when len >= 2: - { - // HT Operation Information byte 0: bits 0-1 secondary channel offset, - // bit 2 STA channel width (0 = 20 MHz, 1 = any/40 MHz). - var info = ie[data + 1]; - var secondaryChannelOffset = info & 0x03; - var staChannelWidth = (info >> 2) & 0x01; - htWidth = staChannelWidth == 1 && secondaryChannelOffset != 0 ? 40 : 20; + ht = ParseHtChannel(ie[data + 1], primaryFrequencyMHz); break; - } case EidVhtOperation when len >= 3: - vhtWidth = ParseVhtWidth(ie[data], ie[data + 1], ie[data + 2], htWidth); + vhtOperation = [ie[data], ie[data + 1], ie[data + 2]]; break; case EidExtension when len >= 1 && ie[data] == ExtEidHeOperation: - heWidth = ParseHeWidth(ie, data + 1, len - 1, htWidth); + heOffset = data + 1; + heLength = len - 1; + break; + case EidExtension when len >= 1 && ie[data] == ExtEidEhtOperation: + ehtOffset = data + 1; + ehtLength = len - 1; break; } pos = data + len; } - return Math.Max(htWidth, Math.Max(vhtWidth, heWidth)); + // VHT and HE defer to HT for 20 / 40 MHz, so they are parsed after the loop (independent of the order) + var vht = vhtOperation == null + ? default + : ParseVhtChannel(vhtOperation[0], vhtOperation[1], vhtOperation[2], ht, primaryFrequencyMHz); + + var he = heOffset < 0 ? default : ParseHeChannel(ie, heOffset, heLength, ht, primaryFrequencyMHz); + + var eht = ehtOffset < 0 ? default : ParseEhtChannel(ie, ehtOffset, ehtLength, primaryFrequencyMHz); + + // The widest channel; on a tie the newer element (its center is the more precise one) + return Widest(Widest(Widest(ht, vht), he), eht); } /// - /// Resolves the channel width from a VHT-Operation channel-width field plus its two center - /// frequency segments. Falls back to when the VHT field signals - /// "20/40 MHz". + /// Returns if it is at least as wide as . /// - private static int ParseVhtWidth(int channelWidth, int segment0, int segment1, int htWidth) + private static WlanBssChannel Widest(WlanBssChannel current, WlanBssChannel candidate) + { + return candidate.BandwidthMHz > 0 && candidate.BandwidthMHz >= current.BandwidthMHz ? candidate : current; + } + + /// + /// Parses the HT Operation Information byte 0: bits 0-1 secondary channel offset (1 = above, + /// 3 = below), bit 2 STA channel width (0 = 20 MHz, 1 = any / 40 MHz). + /// + private static WlanBssChannel ParseHtChannel(byte info, int primaryFrequencyMHz) + { + var secondaryChannelOffset = info & 0x03; + var staChannelWidth = (info >> 2) & 0x01; + + if (staChannelWidth == 1 && secondaryChannelOffset == 1) + return new WlanBssChannel(40, primaryFrequencyMHz + 10); + + if (staChannelWidth == 1 && secondaryChannelOffset == 3) + return new WlanBssChannel(40, primaryFrequencyMHz - 10); + + return new WlanBssChannel(20, primaryFrequencyMHz); + } + + /// + /// Resolves the channel from a VHT-Operation channel-width field plus its two channel center + /// frequency segments (CCFS, channel numbers). Falls back to when the + /// VHT field signals "20/40 MHz". + /// + private static WlanBssChannel ParseVhtChannel(int channelWidth, int segment0, int segment1, WlanBssChannel ht, + int primaryFrequencyMHz) { switch (channelWidth) { case 0: // 20/40 MHz -> defer to HT - return htWidth > 0 ? htWidth : 20; + return ht.BandwidthMHz > 0 ? ht : new WlanBssChannel(20, primaryFrequencyMHz); case 1: // 80 MHz, unless the segments indicate 160 / 80+80 MHz if (segment1 == 0) - return 80; + return new WlanBssChannel(80, ChannelToFrequency(segment0, primaryFrequencyMHz)); + var diff = Math.Abs(segment0 - segment1); - return diff is 8 or > 16 ? 160 : 80; - case 2: // 160 MHz (deprecated encoding) + + // 160 MHz: segment 1 is the center of the 160 MHz channel + if (diff == 8) + return new WlanBssChannel(160, ChannelToFrequency(segment1, primaryFrequencyMHz)); + + // 80+80 MHz (two separate 80 MHz segments) is shown as 160 MHz around the primary segment + return diff > 16 + ? new WlanBssChannel(160, ChannelToFrequency(segment0, primaryFrequencyMHz)) + : new WlanBssChannel(80, ChannelToFrequency(segment0, primaryFrequencyMHz)); + case 2: // 160 MHz (deprecated encoding): segment 0 is the center of the 160 MHz channel case 3: // 80+80 MHz (deprecated encoding) - treated as 160 MHz for display - return 160; + return new WlanBssChannel(160, ChannelToFrequency(segment0, primaryFrequencyMHz)); default: - return 80; + return new WlanBssChannel(80, ChannelToFrequency(segment0, primaryFrequencyMHz)); } } @@ -340,18 +459,20 @@ private static int ParseVhtWidth(int channelWidth, int segment0, int segment1, i /// Parses the HE-Operation element (802.11ax). Optional sub-fields (VHT Operation /// Information, 6 GHz Operation Information) are only present when the corresponding bit in /// the HE Operation Parameters is set; their offsets therefore depend on the preceding - /// fields. This is a best-effort parse: on any ambiguity 0 is returned so the caller can - /// fall back to a heuristic. + /// fields. This is a best-effort parse: on any ambiguity default (width 0) is returned so + /// the caller can fall back to a heuristic. /// /// The full information element buffer. /// Offset of the HE Operation Parameters (after the extension id byte). /// Remaining length of the HE-Operation element after the extension id. - /// Width parsed from the HT-Operation element (used as VHT fallback). - private static int ParseHeWidth(byte[] ie, int offset, int length, int htWidth) + /// Channel parsed from the HT-Operation element (used as VHT fallback). + /// Frequency of the primary 20 MHz channel in MHz. + private static WlanBssChannel ParseHeChannel(byte[] ie, int offset, int length, WlanBssChannel ht, + int primaryFrequencyMHz) { // HE Operation Parameters (3) + BSS Color (1) + Basic HE-MCS And NSS Set (2) = 6 bytes minimum. if (length < 6) - return 0; + return default; var end = offset + length; @@ -363,12 +484,12 @@ private static int ParseHeWidth(byte[] ie, int offset, int length, int htWidth) var sixGhzOperationInformationPresent = ((heOperationParameters >> 17) & 1) == 1; var cursor = offset + 3 + 1 + 2; // skip parameters, BSS color, basic HE-MCS - var width = 0; + WlanBssChannel channel = default; if (vhtOperationInformationPresent) { if (cursor + 3 <= end) - width = Math.Max(width, ParseVhtWidth(ie[cursor], ie[cursor + 1], ie[cursor + 2], htWidth)); + channel = ParseVhtChannel(ie[cursor], ie[cursor + 1], ie[cursor + 2], ht, primaryFrequencyMHz); cursor += 3; } @@ -378,21 +499,84 @@ private static int ParseHeWidth(byte[] ie, int offset, int length, int htWidth) if (sixGhzOperationInformationPresent && cursor + 2 <= end) { - // 6 GHz Operation Information: Primary Channel (1), Control (1), ... + // 6 GHz Operation Information: Primary Channel (1), Control (1), CCFS0 (1), CCFS1 (1), ... // Control byte bits 0-1 = channel width (0 = 20, 1 = 40, 2 = 80, 3 = 160/80+80 MHz). - var channelWidth = ie[cursor + 1] & 0x03; - var sixGhzWidth = channelWidth switch + var sixGhzWidth = (ie[cursor + 1] & 0x03) switch { 0 => 20, 1 => 40, 2 => 80, - 3 => 160, - _ => 0 + _ => 160 }; - width = Math.Max(width, sixGhzWidth); + + // CCFS0 is the center of the channel (of the primary 80 MHz channel for 160 MHz), CCFS1 the center of + // the 160 MHz channel (0 for narrower channels). For 80+80 MHz (segments more than 8 channels apart), + // CCFS1 is the center of the second segment: shown as 160 MHz around the primary segment, like VHT. + var segment0 = cursor + 3 <= end ? ie[cursor + 2] : 0; + var segment1 = cursor + 4 <= end ? ie[cursor + 3] : 0; + var centerChannel = sixGhzWidth == 160 && segment1 != 0 && Math.Abs(segment1 - segment0) == 8 + ? segment1 + : segment0; + + channel = Widest(channel, + new WlanBssChannel(sixGhzWidth, ChannelToFrequency(centerChannel, primaryFrequencyMHz))); } - return width; + return channel; + } + + /// + /// Parses the EHT-Operation element (802.11be): EHT Operation Parameters (1, bit 0 = EHT + /// Operation Information present) and Basic EHT-MCS And NSS Set (4), followed by the EHT + /// Operation Information: Control (1, bits 0-2 = 20 / 40 / 80 / 160 / 320 MHz), CCFS0 (1), + /// CCFS1 (1). Only present if the channel differs from the HT / VHT / HE elements (e.g. 320 MHz). + /// + /// The full information element buffer. + /// Offset of the EHT Operation Parameters (after the extension id byte). + /// Remaining length of the EHT-Operation element after the extension id. + /// Frequency of the primary 20 MHz channel in MHz. + private static WlanBssChannel ParseEhtChannel(byte[] ie, int offset, int length, int primaryFrequencyMHz) + { + if (length < 8 || (ie[offset] & 0x01) == 0) + return default; + + var cursor = offset + 1 + 4; // skip parameters, basic EHT-MCS + + var width = (ie[cursor] & 0x07) switch + { + 0 => 20, + 1 => 40, + 2 => 80, + 3 => 160, + 4 => 320, + _ => 0 + }; + + if (width == 0) + return default; + + // CCFS0 is the center of the channel (of the primary 80 / 160 MHz channel for 160 / 320 MHz), CCFS1 the + // center of the 160 / 320 MHz channel + var segment0 = ie[cursor + 1]; + var segment1 = ie[cursor + 2]; + var centerChannel = width >= 160 && segment1 != 0 ? segment1 : segment0; + + return new WlanBssChannel(width, ChannelToFrequency(centerChannel, primaryFrequencyMHz)); + } + + /// + /// Converts a channel number of the band of the primary channel to its frequency in MHz. + /// + /// Channel number (e.g. 42), 0 if not set. + /// Frequency of the primary channel, used for the band and as fallback. + private static int ChannelToFrequency(int channel, int primaryFrequencyMHz) + { + if (channel == 0) + return primaryFrequencyMHz; + + var radio = WiFi.GetWiFiRadioFromChannelFrequency(primaryFrequencyMHz / 1000.0); + + return radio == WiFiRadio.Unknown ? primaryFrequencyMHz : WiFi.GetFrequencyFromChannel(channel, radio); } /// diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs index 9510cc5c14..164f09a5b1 100644 --- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs +++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs @@ -144,6 +144,10 @@ public static class GlobalStaticConfiguration public static AutoRefreshTimeInfo WiFi_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); + public static bool WiFi_ShowNotificationPopup => true; + public static bool WiFi_NotificationSound => false; + public static int WiFi_NotificationCloseTime => 10; + public static ExportFileType WiFi_ExportFileType => ExportFileType.Csv; // Application: IP Scanner diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs index fb066d7d30..15dd18dcc3 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -1151,6 +1151,54 @@ public AutoRefreshTimeInfo WiFi_AutoRefreshTime } } = GlobalStaticConfiguration.WiFi_AutoRefreshTime; + /// + /// Show a notification when an automatic refresh found changes. + /// + public bool WiFi_ShowNotificationPopup + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.WiFi_ShowNotificationPopup; + + /// + /// Play a sound when an automatic refresh found changes. + /// + public bool WiFi_NotificationSound + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.WiFi_NotificationSound; + + /// + /// Seconds until the notification of an automatic refresh is closed. + /// + public int WiFi_NotificationCloseTime + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.WiFi_NotificationCloseTime; + public string WiFi_ExportFilePath { get; diff --git a/Source/NETworkManager.Settings/SettingsName.cs b/Source/NETworkManager.Settings/SettingsName.cs index fe1bd17791..75fb9a3afd 100644 --- a/Source/NETworkManager.Settings/SettingsName.cs +++ b/Source/NETworkManager.Settings/SettingsName.cs @@ -15,6 +15,7 @@ public enum SettingsName Settings, Dashboard, NetworkInterface, + WiFi, IPScanner, PortScanner, PingMonitor, diff --git a/Source/NETworkManager.Settings/SettingsViewManager.cs b/Source/NETworkManager.Settings/SettingsViewManager.cs index d5d13ddd1a..b19c8e7eb7 100644 --- a/Source/NETworkManager.Settings/SettingsViewManager.cs +++ b/Source/NETworkManager.Settings/SettingsViewManager.cs @@ -50,6 +50,8 @@ public static class SettingsViewManager SettingsGroup.Application), new(SettingsName.NetworkInterface, ApplicationManager.GetIcon(ApplicationName.NetworkInterface), SettingsGroup.Application), + new(SettingsName.WiFi, ApplicationManager.GetIcon(ApplicationName.WiFi), + SettingsGroup.Application), new(SettingsName.IPScanner, ApplicationManager.GetIcon(ApplicationName.IPScanner), SettingsGroup.Application), new(SettingsName.PortScanner, ApplicationManager.GetIcon(ApplicationName.PortScanner), diff --git a/Source/NETworkManager.Tests/Network/WiFiChannelAxisTests.cs b/Source/NETworkManager.Tests/Network/WiFiChannelAxisTests.cs new file mode 100644 index 0000000000..ed9ef1c7d6 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/WiFiChannelAxisTests.cs @@ -0,0 +1,77 @@ +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class WiFiChannelAxisTests +{ + [Theory] + [InlineData(2412, WiFiRadio.GHz2dot4, 1)] + [InlineData(2484, WiFiRadio.GHz2dot4, 14)] + // 40 MHz on the channels 1 + 5: center at channel 3 + [InlineData(2422, WiFiRadio.GHz2dot4, 3)] + // 80 MHz on the channels 36 - 48: center at channel 42 (B19) + [InlineData(5210, WiFiRadio.GHz5, 42)] + [InlineData(5180, WiFiRadio.GHz5, 36)] + [InlineData(5955, WiFiRadio.GHz6, 1)] + // 6 GHz channel 2 is below channel 1 + [InlineData(5935, WiFiRadio.GHz6, -3)] + public void FrequencyToChannel_ReturnsTheChannelNumber(double frequencyMHz, WiFiRadio radio, double expected) + { + Assert.Equal(expected, WiFiChannelAxis.FrequencyToChannel(frequencyMHz, radio), 6); + } + + [Theory] + [InlineData(36, 36)] + [InlineData(64, 64)] + // The range 64 - 100 is compressed to 16 units + [InlineData(100, 80)] + [InlineData(149, 129)] + [InlineData(177, 157)] + public void ChannelToPosition_CompressesTheFiveGHzGap(double channel, double expected) + { + Assert.Equal(expected, WiFiChannelAxis.ChannelToPosition(channel, WiFiRadio.GHz5)); + } + + [Theory] + [InlineData(WiFiRadio.GHz2dot4, 13)] + [InlineData(WiFiRadio.GHz6, 129)] + public void ChannelToPosition_KeepsTheChannelOutsideOfFiveGHz(WiFiRadio radio, double channel) + { + Assert.Equal(channel, WiFiChannelAxis.ChannelToPosition(channel, radio)); + } + + [Theory] + [InlineData(36)] + [InlineData(64)] + [InlineData(100)] + [InlineData(144)] + // Labels above 144 (B9) + [InlineData(149)] + [InlineData(165)] + [InlineData(177)] + public void PositionToChannel_IsTheInverseOfChannelToPosition(int channel) + { + var position = (int)WiFiChannelAxis.ChannelToPosition(channel, WiFiRadio.GHz5); + + Assert.Equal(channel, WiFiChannelAxis.PositionToChannel(position, WiFiRadio.GHz5)); + } + + [Theory] + // 20 MHz on channel 1 / 233 + [InlineData(5955, 20, true, false)] + [InlineData(7115, 20, false, true)] + // 160 MHz on the channels 97 - 125 (center 111) / 129 - 157 (center 143) + [InlineData(6505, 160, true, false)] + [InlineData(6665, 160, false, true)] + // 320 MHz around channel 127 covers 95 - 159: both charts (B32) + [InlineData(6585, 320, true, true)] + // Channel 2 (5935 MHz) + [InlineData(5935, 20, true, false)] + public void GetSixGHzCharts_ReturnsTheChartsOfTheChannel(double centerFrequencyMHz, int bandwidthMHz, + bool expectedLower, bool expectedUpper) + { + Assert.Equal((expectedLower, expectedUpper), + WiFiChannelAxis.GetSixGHzCharts(centerFrequencyMHz, bandwidthMHz)); + } +} diff --git a/Source/NETworkManager.Tests/Network/WiFiChannelTests.cs b/Source/NETworkManager.Tests/Network/WiFiChannelTests.cs new file mode 100644 index 0000000000..222774de2c --- /dev/null +++ b/Source/NETworkManager.Tests/Network/WiFiChannelTests.cs @@ -0,0 +1,58 @@ +using System.Linq; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class WiFiChannelTests +{ + [Theory] + [InlineData(2.412, 1)] + [InlineData(2.472, 13)] + [InlineData(2.484, 14)] + [InlineData(5.160, 32)] + [InlineData(5.180, 36)] + [InlineData(5.825, 165)] + [InlineData(5.885, 177)] + [InlineData(5.935, 2)] + [InlineData(5.955, 1)] + [InlineData(7.115, 233)] + [InlineData(5.000, -1)] + public void GetChannelFromChannelFrequency_ReturnsTheChannel(double gigahertz, int expected) + { + Assert.Equal(expected, WiFi.GetChannelFromChannelFrequency(gigahertz)); + } + + [Theory] + [InlineData(WiFiRadio.GHz2dot4, 1, 14)] + [InlineData(WiFiRadio.GHz5, 32, 177)] + [InlineData(WiFiRadio.GHz6, 1, 233)] + public void GetFrequencyFromChannel_IsTheInverseOfGetChannelFromChannelFrequency(WiFiRadio radio, int first, + int last) + { + // Every channel of the band (also 2.4 GHz channel 14 and 6 GHz channel 2) back and forth, in the same band + int[] channels = radio == WiFiRadio.GHz6 ? [2, .. Enumerable.Range(first, last - first + 1)] + : [.. Enumerable.Range(first, last - first + 1)]; + + foreach (var channel in channels) + { + var gigahertz = WiFi.GetFrequencyFromChannel(channel, radio) / 1000.0; + + Assert.Equal(channel, WiFi.GetChannelFromChannelFrequency(gigahertz)); + Assert.Equal(radio, WiFi.GetWiFiRadioFromChannelFrequency(gigahertz)); + } + } + + [Theory] + [InlineData(2.412, WiFiRadio.GHz2dot4)] + [InlineData(2.484, WiFiRadio.GHz2dot4)] + [InlineData(5.180, WiFiRadio.GHz5)] + [InlineData(5.885, WiFiRadio.GHz5)] + [InlineData(5.935, WiFiRadio.GHz6)] + [InlineData(7.115, WiFiRadio.GHz6)] + [InlineData(3.000, WiFiRadio.Unknown)] + public void GetWiFiRadioFromChannelFrequency_ReturnsTheBand(double gigahertz, WiFiRadio expected) + { + Assert.Equal(expected, WiFi.GetWiFiRadioFromChannelFrequency(gigahertz)); + } +} diff --git a/Source/NETworkManager.Tests/Network/WiFiConnectModeTests.cs b/Source/NETworkManager.Tests/Network/WiFiConnectModeTests.cs new file mode 100644 index 0000000000..4dfc9fe78f --- /dev/null +++ b/Source/NETworkManager.Tests/Network/WiFiConnectModeTests.cs @@ -0,0 +1,28 @@ +using NETworkManager.Models.Network; +using Windows.Networking.Connectivity; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class WiFiConnectModeTests +{ + [Theory] + [InlineData(NetworkAuthenticationType.Open80211, NetworkEncryptionType.None, WiFiConnectMode.Open)] + [InlineData(NetworkAuthenticationType.Owe, NetworkEncryptionType.Ccmp, WiFiConnectMode.Open)] + [InlineData(NetworkAuthenticationType.RsnaPsk, NetworkEncryptionType.None, WiFiConnectMode.Open)] + [InlineData(NetworkAuthenticationType.SharedKey80211, NetworkEncryptionType.Wep, WiFiConnectMode.Psk)] + [InlineData(NetworkAuthenticationType.Open80211, NetworkEncryptionType.Wep, WiFiConnectMode.Psk)] + [InlineData(NetworkAuthenticationType.Open80211, NetworkEncryptionType.Wep40, WiFiConnectMode.Psk)] + [InlineData(NetworkAuthenticationType.WpaPsk, NetworkEncryptionType.Tkip, WiFiConnectMode.Psk)] + [InlineData(NetworkAuthenticationType.RsnaPsk, NetworkEncryptionType.Ccmp, WiFiConnectMode.Psk)] + [InlineData(NetworkAuthenticationType.Wpa3Sae, NetworkEncryptionType.Ccmp, WiFiConnectMode.Psk)] + [InlineData(NetworkAuthenticationType.Wpa, NetworkEncryptionType.Tkip, WiFiConnectMode.Eap)] + [InlineData(NetworkAuthenticationType.Rsna, NetworkEncryptionType.Ccmp, WiFiConnectMode.Eap)] + [InlineData(NetworkAuthenticationType.Wpa3Enterprise, NetworkEncryptionType.Ccmp, WiFiConnectMode.Eap)] + [InlineData(NetworkAuthenticationType.Wpa3Enterprise192Bits, NetworkEncryptionType.Ccmp, WiFiConnectMode.Eap)] + public void GetConnectMode_ReturnsTheDialogMode(NetworkAuthenticationType authenticationType, + NetworkEncryptionType encryptionType, WiFiConnectMode expected) + { + Assert.Equal(expected, WiFi.GetConnectMode(authenticationType, encryptionType)); + } +} diff --git a/Source/NETworkManager.Tests/Network/WiFiScanComparerTests.cs b/Source/NETworkManager.Tests/Network/WiFiScanComparerTests.cs new file mode 100644 index 0000000000..84a5228c7a --- /dev/null +++ b/Source/NETworkManager.Tests/Network/WiFiScanComparerTests.cs @@ -0,0 +1,112 @@ +using System.Linq; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class WiFiScanComparerTests +{ + private static WiFiNetworkInfo Network(string bssid, int channel = 36, int width = 80, + string security = "WPA2 Personal (PSK)", bool isEstimated = false) + { + return new WiFiNetworkInfo + { + Bssid = bssid, + Channel = channel, + ChannelBandwidth = width, + IsChannelBandwidthEstimated = isEstimated, + NetworkAuthenticationType = security + }; + } + + [Fact] + public void SameNetworks_HaveNoChange() + { + var result = WiFiScanComparer.Compare([Network("AA"), Network("BB")], [Network("BB"), Network("AA")]); + + Assert.Empty(result.Changes); + Assert.Empty(result.Gone); + } + + [Fact] + public void SignalStrength_IsNoChange() + { + // Only the BSSID, channel, width and security are compared - another object with the same values + var result = WiFiScanComparer.Compare([Network("AA")], [Network("AA")]); + + Assert.Empty(result.Changes); + } + + [Fact] + public void NetworkVisibleNow_IsNew() + { + var current = Network("BB"); + + var result = WiFiScanComparer.Compare([Network("AA")], [Network("AA"), current]); + + var change = Assert.Single(result.Changes); + Assert.Same(current, change.Network); + Assert.Equal(WiFiNetworkChange.New, change.Change); + Assert.Null(change.Previous); + } + + [Fact] + public void NetworkNotVisibleNow_IsGone() + { + var previous = Network("BB"); + + var result = WiFiScanComparer.Compare([Network("AA"), previous], [Network("AA")]); + + Assert.Same(previous, Assert.Single(result.Gone)); + Assert.Empty(result.Changes); + } + + [Theory] + [InlineData(40, 80, "WPA2 Personal (PSK)")] // Channel + [InlineData(36, 160, "WPA2 Personal (PSK)")] // Channel width + [InlineData(36, 80, "WPA3 Personal (SAE)")] // Security + public void ChannelWidthOrSecurity_IsChanged(int channel, int width, string security) + { + var previous = Network("AA"); + + var result = WiFiScanComparer.Compare([previous], [Network("AA", channel, width, security)]); + + var change = Assert.Single(result.Changes); + Assert.Equal(WiFiNetworkChange.Changed, change.Change); + Assert.Same(previous, change.Previous); + } + + [Fact] + public void EstimatedWidth_IsNotCompared() + { + var result = WiFiScanComparer.Compare([Network("AA", width: 80)], + [Network("AA", width: 20, isEstimated: true)]); + + Assert.Empty(result.Changes); + } + + [Fact] + public void Bssid_IsComparedCaseInsensitive() + { + var result = WiFiScanComparer.Compare([Network("aa:bb")], [Network("AA:BB")]); + + Assert.Empty(result.Changes); + Assert.Empty(result.Gone); + } + + [Fact] + public void DuplicateBssid_UsesTheFirst() + { + var result = WiFiScanComparer.Compare([Network("AA"), Network("AA", 40)], [Network("AA")]); + + Assert.Empty(result.Changes); + } + + [Fact] + public void Gone_KeepsTheOrderOfThePreviousScan() + { + var result = WiFiScanComparer.Compare([Network("CC"), Network("AA"), Network("BB")], []); + + Assert.Equal(["CC", "AA", "BB"], result.Gone.Select(x => x.Bssid)); + } +} diff --git a/Source/NETworkManager.Tests/Network/WlanApiTests.cs b/Source/NETworkManager.Tests/Network/WlanApiTests.cs new file mode 100644 index 0000000000..a394a27b17 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/WlanApiTests.cs @@ -0,0 +1,153 @@ +using System.Linq; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class WlanApiTests +{ + // HT Operation (61): primary channel, info byte (bits 0-1 secondary channel offset, bit 2 STA channel width), + // 20 more bytes + private static byte[] HtOperation(byte info) + { + return [61, 22, 0, info, .. new byte[20]]; + } + + // VHT Operation (192): channel width, CCFS0, CCFS1, basic VHT-MCS and NSS set (2) + private static byte[] VhtOperation(byte channelWidth, byte segment0, byte segment1) + { + return [192, 5, channelWidth, segment0, segment1, 0, 0]; + } + + // HE Operation (255 / 36) with the 6 GHz Operation Information: primary channel, control (bits 0-1 channel + // width), CCFS0, CCFS1, minimum rate + private static byte[] HeOperation6GHz(byte control, byte segment0, byte segment1) + { + // Parameters (3, B17 = 6 GHz Operation Information present), BSS color (1), basic HE-MCS and NSS set (2) + byte[] body = [36, 0x00, 0x00, 0x02, 0, 0, 0, 1, control, segment0, segment1, 0]; + return [255, (byte)body.Length, .. body]; + } + + // EHT Operation (255 / 106): parameters (bit 0 = EHT Operation Information present), basic EHT-MCS and NSS set (4), + // control (bits 0-2 channel width), CCFS0, CCFS1 + private static byte[] EhtOperation(byte control, byte segment0, byte segment1) + { + byte[] body = [106, 0x01, 0, 0, 0, 0, control, segment0, segment1]; + return [255, (byte)body.Length, .. body]; + } + + private static WlanApi.WlanBssChannel Parse(int primaryFrequencyMHz, params byte[][] elements) + { + return WlanApi.GetChannelFromInformationElements(elements.SelectMany(x => x).ToArray(), primaryFrequencyMHz); + } + + [Fact] + public void NoOperationElement_IsUnknown() + { + // SSID element only + Assert.Equal(default, Parse(5180, [0, 4, 0x54, 0x65, 0x73, 0x74])); + } + + [Fact] + public void Ht20_IsCenteredOnThePrimaryChannel() + { + Assert.Equal(new WlanApi.WlanBssChannel(20, 2437), Parse(2437, HtOperation(0x00))); + } + + [Theory] + [InlineData(0x05, 2422)] // Secondary channel above: channels 1 + 5, center channel 3 + [InlineData(0x07, 2442)] // Secondary channel below: channels 9 + 5, center channel 7 (primary channel 9 = 2452) + public void Ht40_IsCenteredBetweenPrimaryAndSecondaryChannel(byte info, int expectedCenter) + { + var primary = info == 0x05 ? 2412 : 2452; + + Assert.Equal(new WlanApi.WlanBssChannel(40, expectedCenter), Parse(primary, HtOperation(info))); + } + + [Fact] + public void Ht40WithoutSecondaryChannel_Is20() + { + Assert.Equal(new WlanApi.WlanBssChannel(20, 2412), Parse(2412, HtOperation(0x04))); + } + + [Fact] + public void Vht80_IsCenteredOnSegment0() + { + // Primary channel 36, 80 MHz on the channels 36 - 48 (center channel 42) + Assert.Equal(new WlanApi.WlanBssChannel(80, 5210), Parse(5180, HtOperation(0x05), VhtOperation(1, 42, 0))); + } + + [Fact] + public void Vht160_IsCenteredOnSegment1() + { + // Primary channel 36, 160 MHz on the channels 36 - 64 (center channel 50, segment 0 = primary 80 MHz) + Assert.Equal(new WlanApi.WlanBssChannel(160, 5250), Parse(5180, HtOperation(0x05), VhtOperation(1, 42, 50))); + } + + [Fact] + public void Vht160DeprecatedEncoding_IsCenteredOnSegment0() + { + Assert.Equal(new WlanApi.WlanBssChannel(160, 5250), Parse(5180, HtOperation(0x05), VhtOperation(2, 50, 0))); + } + + [Fact] + public void Vht20Or40_DefersToHt() + { + Assert.Equal(new WlanApi.WlanBssChannel(40, 5190), Parse(5180, HtOperation(0x05), VhtOperation(0, 0, 0))); + } + + [Fact] + public void VhtBeforeHt_IsParsedTheSame() + { + Assert.Equal(new WlanApi.WlanBssChannel(40, 5190), Parse(5180, VhtOperation(0, 0, 0), HtOperation(0x05))); + } + + [Theory] + [InlineData(0, 1, 0, 20, 5955)] // Channel 1 + [InlineData(1, 3, 0, 40, 5965)] // Channels 1 - 5, center channel 3 + [InlineData(2, 7, 0, 80, 5985)] // Channels 1 - 13, center channel 7 + [InlineData(3, 7, 15, 160, 6025)] // Channels 1 - 29, center channel 15 (segment 0 = primary 80 MHz) + [InlineData(3, 15, 0, 160, 6025)] // Old encoding: segment 0 is the center + public void He6GHz_IsCenteredOnTheChannelCenter(byte control, byte segment0, byte segment1, int expectedWidth, + int expectedCenter) + { + Assert.Equal(new WlanApi.WlanBssChannel(expectedWidth, expectedCenter), + Parse(5955, HeOperation6GHz(control, segment0, segment1))); + } + + [Fact] + public void He6GHz80Plus80_IsCenteredOnThePrimarySegment() + { + // Segments around the channels 7 and 71: 160 MHz around the primary segment (channel 7), like VHT + Assert.Equal(new WlanApi.WlanBssChannel(160, 5985), Parse(5955, HeOperation6GHz(3, 7, 71))); + } + + [Fact] + public void He6GHzChannel2_IsAt5935() + { + Assert.Equal(new WlanApi.WlanBssChannel(20, 5935), Parse(5935, HeOperation6GHz(0, 2, 0))); + } + + [Fact] + public void Eht320_IsCenteredOnSegment1() + { + // Primary channel 1, 320 MHz on the channels 1 - 61 (center channel 31, segment 0 = primary 160 MHz) + Assert.Equal(new WlanApi.WlanBssChannel(320, 6105), + Parse(5955, HeOperation6GHz(3, 7, 15), EhtOperation(4, 15, 31))); + } + + [Fact] + public void EhtWithoutOperationInformation_KeepsHe() + { + byte[] eht = [255, 6, 106, 0x00, 0, 0, 0, 0]; + + Assert.Equal(new WlanApi.WlanBssChannel(160, 6025), Parse(5955, HeOperation6GHz(3, 7, 15), eht)); + } + + [Fact] + public void TruncatedElement_IsIgnored() + { + // Length 22, but only 3 bytes follow + Assert.Equal(default, Parse(5180, [61, 22, 0, 0x05, 0])); + } +} diff --git a/Source/NETworkManager/Controls/LiveChartsWiFiChannelTooltip.xaml.cs b/Source/NETworkManager/Controls/LiveChartsWiFiChannelTooltip.xaml.cs index c19f58d2a2..6c1bb02846 100644 --- a/Source/NETworkManager/Controls/LiveChartsWiFiChannelTooltip.xaml.cs +++ b/Source/NETworkManager/Controls/LiveChartsWiFiChannelTooltip.xaml.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows; @@ -9,6 +9,7 @@ using LiveChartsCore.Kernel.Sketches; using LiveChartsCore.SkiaSharpView; using LiveChartsCore.SkiaSharpView.Painting; +using NETworkManager.Converters; using NETworkManager.Localization.Resources; using NETworkManager.Models.Network; using SkiaSharp; @@ -55,10 +56,10 @@ public void Show(IEnumerable tooltipPoints, Chart chart) if (!seenNetworks.Add(network)) continue; - var ssid = network.IsHidden ? Strings.HiddenNetwork : network.AvailableNetwork.Ssid; - var bssid = network.AvailableNetwork.Bssid; + var ssid = WiFiNetworkToSsidStringConverter.GetSsid(network); + var bssid = network.Bssid; var dbm = $"{network.AvailableNetwork.NetworkRssiInDecibelMilliwatts} dBm"; - var widthText = $"{network.ChannelBandwidth} MHz"; + var widthText = WiFiChannelBandwidthToStringConverter.Format(network); var channelDetail = $"{Strings.Channel} {network.Channel} · {widthText}"; TooltipEntries.Add(new TooltipEntry(SkColorToBrush(GetSeriesColor(point)), ssid, bssid, dbm, channelDetail)); diff --git a/Source/NETworkManager/Controls/WiFiChannelChart.cs b/Source/NETworkManager/Controls/WiFiChannelChart.cs new file mode 100644 index 0000000000..a83b2cf7fb --- /dev/null +++ b/Source/NETworkManager/Controls/WiFiChannelChart.cs @@ -0,0 +1,76 @@ +using System.Collections.Generic; +using LiveChartsCore; +using LiveChartsCore.SkiaSharpView; +using System.Windows.Media; +using NETworkManager.Utilities; + +namespace NETworkManager.Controls; + +/// +/// One channel chart of the WiFi tool (2.4 GHz, 5 GHz, 6 GHz lower / upper): the axes and signal-quality sections +/// (fixed) and the series and legend of the networks (replaced on every scan). +/// +/// X axis (channels of the band). +/// Y axis (signal strength). +/// Signal-quality bands in the background. +public class WiFiChannelChart(Axis[] xAxes, Axis[] yAxes, RectangularSection[] sections) : PropertyChangedBase +{ + public Axis[] XAxes { get; } = xAxes; + + public Axis[] YAxes { get; } = yAxes; + + public RectangularSection[] Sections { get; } = sections; + + /// + /// Gets one series per network (a trapezoid over its channel width). + /// + public ISeries[] Series + { + get; + private set + { + field = value; + OnPropertyChanged(); + } + } = []; + + /// + /// Gets the legend below the chart (color, SSID and BSSID of each network). + /// + public WiFiChannelLegendEntry[] Legend + { + get; + private set + { + field = value; + OnPropertyChanged(); + } + } = []; + + /// + /// Shows the networks of a scan. + /// + /// One series per network. + /// Legend entry of each series (same order). + public void Update(IEnumerable series, IEnumerable legend) + { + Series = [.. series]; + Legend = [.. legend]; + } + + /// + /// Removes the networks. + /// + public void Clear() + { + Update([], []); + } +} + +/// +/// Legend entry of a network below a channel chart. +/// +/// Color of the series of the network. +/// Shown SSID ("Hidden Network" for a hidden network). +/// BSSID of the network. +public record WiFiChannelLegendEntry(SolidColorBrush Color, string Ssid, string Bssid); diff --git a/Source/NETworkManager/DialogHelper.cs b/Source/NETworkManager/DialogHelper.cs index 59d40aa040..6da99c2531 100644 --- a/Source/NETworkManager/DialogHelper.cs +++ b/Source/NETworkManager/DialogHelper.cs @@ -1,4 +1,5 @@ -using MahApps.Metro.SimpleChildWindow; +using MahApps.Metro.Controls; +using MahApps.Metro.SimpleChildWindow; using NETworkManager.Localization.Resources; using NETworkManager.Settings; using NETworkManager.Utilities; @@ -108,6 +109,18 @@ public static async Task ShowConfirmationMessageAsync(Window parentWindow, return result; } + /// + /// Gets whether a dialog (MahApps dialog or child window) is open in the main window, or the main window doesn't + /// exist yet - commands that would open another dialog, or run (e.g. refresh) behind it, can't be executed. + /// + /// True if a dialog is open or there is no main window. + public static bool IsAnyDialogOpen() + { + return Application.Current.MainWindow is not MetroWindow mainWindow || + mainWindow.IsAnyDialogOpen || + ConfigurationManager.Current.IsChildWindowOpen; + } + /// /// Formats the given items as a bulleted list (one item per line, prefixed with "- ") to show them /// in a dialog message, e.g. the entries that will be deleted. Only the first diff --git a/Source/NETworkManager/ViewModels/BitCalculatorViewModel.cs b/Source/NETworkManager/ViewModels/BitCalculatorViewModel.cs index 9d9141aa88..8bd4da2372 100644 --- a/Source/NETworkManager/ViewModels/BitCalculatorViewModel.cs +++ b/Source/NETworkManager/ViewModels/BitCalculatorViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Localization.Resources; using NETworkManager.Models.Export; @@ -181,9 +180,7 @@ private void LoadSettings() /// true if the command can be executed; otherwise, false. private bool Calculate_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } /// diff --git a/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs b/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs index 555ed6decd..9b3b191627 100644 --- a/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs +++ b/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Localization; using NETworkManager.Localization.Resources; @@ -281,9 +280,7 @@ private set /// true if the command can be executed; otherwise, false. private bool Refresh_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen && + return !DialogHelper.IsAnyDialogOpen() && !IsRefreshing && !AutoRefreshEnabled; } diff --git a/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs b/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs index 1fe380227e..4edb355348 100644 --- a/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs @@ -1,6 +1,5 @@ using DnsClient; using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Controls; using NETworkManager.Localization.Resources; @@ -342,9 +341,7 @@ private void LoadTypes() /// true if the command can be executed; otherwise, false. private bool Query_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } /// diff --git a/Source/NETworkManager/ViewModels/FirewallViewModel.cs b/Source/NETworkManager/ViewModels/FirewallViewModel.cs index 2df7ca0155..dd96babc4f 100644 --- a/Source/NETworkManager/ViewModels/FirewallViewModel.cs +++ b/Source/NETworkManager/ViewModels/FirewallViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Controls; using NETworkManager.Converters; @@ -554,9 +553,7 @@ private async Task DeleteRules() private bool ModifyRule_CanExecute() { return ConfigurationManager.Current.IsAdmin && - Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen && + !DialogHelper.IsAnyDialogOpen() && !IsRefreshing && !IsModifying; } diff --git a/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs b/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs index 0a95474a86..d61ed5d59c 100644 --- a/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs +++ b/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Localization.Resources; using NETworkManager.Models; @@ -270,9 +269,7 @@ private void LoadSettings() /// true if the command can be executed; otherwise, false. private bool Refresh_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen && + return !DialogHelper.IsAnyDialogOpen() && !IsRefreshing && !IsModifying; } @@ -635,9 +632,7 @@ private async Task DeleteEntryAction() private bool ModifyEntry_CanExecute(object obj) { return ConfigurationManager.Current.IsAdmin && - Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen && + !DialogHelper.IsAnyDialogOpen() && !IsRefreshing && !IsModifying; } diff --git a/Source/NETworkManager/ViewModels/IPGeolocationViewModel.cs b/Source/NETworkManager/ViewModels/IPGeolocationViewModel.cs index 8f24b9eabd..5b8821c809 100644 --- a/Source/NETworkManager/ViewModels/IPGeolocationViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPGeolocationViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Controls; using NETworkManager.Localization.Resources; @@ -194,9 +193,7 @@ private void LoadSettings() /// true if the command can be executed; otherwise, false. private bool Query_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } /// diff --git a/Source/NETworkManager/ViewModels/IPScannerViewModel.cs b/Source/NETworkManager/ViewModels/IPScannerViewModel.cs index 0374f001ac..8d43f81cf2 100644 --- a/Source/NETworkManager/ViewModels/IPScannerViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPScannerViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Controls; using NETworkManager.Converters; @@ -733,9 +732,7 @@ public void OnLoaded() private bool Scan_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void ScanAction() diff --git a/Source/NETworkManager/ViewModels/ListenersViewModel.cs b/Source/NETworkManager/ViewModels/ListenersViewModel.cs index 33814dfbe0..0b4ae001ae 100644 --- a/Source/NETworkManager/ViewModels/ListenersViewModel.cs +++ b/Source/NETworkManager/ViewModels/ListenersViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Localization.Resources; using NETworkManager.Models.Export; @@ -272,9 +271,7 @@ private set /// true if the command can be executed; otherwise, false. private bool Refresh_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen && + return !DialogHelper.IsAnyDialogOpen() && !IsRefreshing && !AutoRefreshEnabled; } diff --git a/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs b/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs index 0a3ca4a7ff..35b0ea1b5e 100644 --- a/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Localization.Resources; using NETworkManager.Models.Export; @@ -188,9 +187,7 @@ public bool NothingFound /// true if the command can be executed; otherwise, false. private bool OUILookup_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen && + return !DialogHelper.IsAnyDialogOpen() && !HasError; } diff --git a/Source/NETworkManager/ViewModels/LookupPortViewModel.cs b/Source/NETworkManager/ViewModels/LookupPortViewModel.cs index 7a5cda2a85..9dfa14b708 100644 --- a/Source/NETworkManager/ViewModels/LookupPortViewModel.cs +++ b/Source/NETworkManager/ViewModels/LookupPortViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Localization.Resources; using NETworkManager.Models.Export; @@ -186,9 +185,7 @@ public bool NothingFound /// true if the command can be executed; otherwise, false. private bool PortLookup_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen && !HasError; + return !DialogHelper.IsAnyDialogOpen() && !HasError; } /// diff --git a/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs b/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs index 6613a2c2bb..d6b3b2fc3d 100644 --- a/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs +++ b/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Localization.Resources; using NETworkManager.Models.Export; @@ -284,9 +283,7 @@ private set private bool Refresh_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen && + return !DialogHelper.IsAnyDialogOpen() && !IsRefreshing && !IsModifying && !AutoRefreshEnabled; @@ -401,9 +398,7 @@ private async Task AddEntryAction() private bool ModifyEntry_CanExecute(object parameter) { return ConfigurationManager.Current.IsAdmin && - Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen && + !DialogHelper.IsAnyDialogOpen() && !IsRefreshing && !IsModifying; } diff --git a/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs b/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs index 70f1e90188..9a77766a01 100644 --- a/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs +++ b/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs @@ -5,7 +5,6 @@ using LiveChartsCore.SkiaSharpView.Painting; using LiveChartsCore.SkiaSharpView.Painting.Effects; using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Localization.Resources; using NETworkManager.Models; @@ -748,9 +747,7 @@ private async Task LoadNetworkInterfaces() private bool ReloadNetworkInterfaces_CanExecute(object obj) { return !IsNetworkInterfaceLoading && - Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + !DialogHelper.IsAnyDialogOpen(); } /// @@ -841,15 +838,11 @@ private void ApplyProfileAction() private bool AdditionalCommands_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private bool ConfigureCommands_CanExecute(object parameter) => HasPermissionToConfigure && - Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + !DialogHelper.IsAnyDialogOpen(); /// /// Gets the command to restart the application with administrator privileges. diff --git a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs index 3ea8185627..625abfbdb3 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs @@ -1,4 +1,3 @@ -using MahApps.Metro.Controls; using NETworkManager.Converters; using NETworkManager.Localization.Resources; using NETworkManager.Models; @@ -196,9 +195,7 @@ public PingMonitorHostViewModel() private bool Ping_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void PingAction() diff --git a/Source/NETworkManager/ViewModels/PortScannerViewModel.cs b/Source/NETworkManager/ViewModels/PortScannerViewModel.cs index aa2c83892a..567f8ffba7 100644 --- a/Source/NETworkManager/ViewModels/PortScannerViewModel.cs +++ b/Source/NETworkManager/ViewModels/PortScannerViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Controls; using NETworkManager.Converters; @@ -693,9 +692,7 @@ public void OnClose() private bool Scan_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void ScanAction() diff --git a/Source/NETworkManager/ViewModels/RDAPViewModel.cs b/Source/NETworkManager/ViewModels/RDAPViewModel.cs index 487560ab72..ce5e91f3d6 100644 --- a/Source/NETworkManager/ViewModels/RDAPViewModel.cs +++ b/Source/NETworkManager/ViewModels/RDAPViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Controls; using NETworkManager.Localization.Resources; @@ -247,9 +246,7 @@ private void LoadSettings() private bool Query_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void QueryAction() diff --git a/Source/NETworkManager/ViewModels/SNMPViewModel.cs b/Source/NETworkManager/ViewModels/SNMPViewModel.cs index ac69b07627..8ffdcf8914 100644 --- a/Source/NETworkManager/ViewModels/SNMPViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNMPViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Controls; using NETworkManager.Localization; @@ -438,9 +437,7 @@ private set private bool Work_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void WorkAction() diff --git a/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs b/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs index ce64260c65..65bfee71ed 100644 --- a/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs @@ -169,9 +169,7 @@ private void LoadSettings() private bool Query_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void QueryAction() diff --git a/Source/NETworkManager/ViewModels/SettingsViewModel.cs b/Source/NETworkManager/ViewModels/SettingsViewModel.cs index 900f4db799..ef7bf08b10 100644 --- a/Source/NETworkManager/ViewModels/SettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsViewModel.cs @@ -121,6 +121,7 @@ public SettingsViewInfo SelectedSettingsView private SettingsProfilesView _settingsProfilesView; private DashboardSettingsView _dashboardSettingsView; private NetworkInterfaceSettingsView _networkInterfaceSettingsView; + private WiFiSettingsView _wiFiSettingsView; private IPScannerSettingsView _ipScannerSettingsView; private PortScannerSettingsView _portScannerSettingsView; private PingMonitorSettingsView _pingMonitorSettingsView; @@ -273,6 +274,11 @@ private void ChangeSettingsContent(SettingsViewInfo settingsViewInfo) SettingsContent = _networkInterfaceSettingsView; break; + case SettingsName.WiFi: + _wiFiSettingsView ??= new WiFiSettingsView(); + + SettingsContent = _wiFiSettingsView; + break; case SettingsName.IPScanner: _ipScannerSettingsView ??= new IPScannerSettingsView(); diff --git a/Source/NETworkManager/ViewModels/SubnetCalculatorCalculatorViewModel.cs b/Source/NETworkManager/ViewModels/SubnetCalculatorCalculatorViewModel.cs index 6c62b44e98..359b370bf9 100644 --- a/Source/NETworkManager/ViewModels/SubnetCalculatorCalculatorViewModel.cs +++ b/Source/NETworkManager/ViewModels/SubnetCalculatorCalculatorViewModel.cs @@ -4,7 +4,6 @@ using System.Windows; using System.Windows.Data; using System.Windows.Input; -using MahApps.Metro.Controls; using NETworkManager.Models.Network; using NETworkManager.Settings; using NETworkManager.Utilities; @@ -88,9 +87,7 @@ private set private bool Calculate_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void CalculateAction() diff --git a/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs b/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs index 904b9162e4..8847bdacd7 100644 --- a/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs +++ b/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Localization.Resources; using NETworkManager.Models.Export; @@ -150,9 +149,7 @@ public IList SelectedResults private bool Calculate_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void CalculateAction() diff --git a/Source/NETworkManager/ViewModels/SubnetCalculatorWideSubnetViewModel.cs b/Source/NETworkManager/ViewModels/SubnetCalculatorWideSubnetViewModel.cs index 4410227493..7d5e6d6cc8 100644 --- a/Source/NETworkManager/ViewModels/SubnetCalculatorWideSubnetViewModel.cs +++ b/Source/NETworkManager/ViewModels/SubnetCalculatorWideSubnetViewModel.cs @@ -4,7 +4,6 @@ using System.Windows; using System.Windows.Data; using System.Windows.Input; -using MahApps.Metro.Controls; using NETworkManager.Models.Network; using NETworkManager.Settings; using NETworkManager.Utilities; @@ -106,9 +105,7 @@ private set private bool Calculate_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void CalculateAction() diff --git a/Source/NETworkManager/ViewModels/TracerouteViewModel.cs b/Source/NETworkManager/ViewModels/TracerouteViewModel.cs index d125f1caba..d7ec5ec390 100644 --- a/Source/NETworkManager/ViewModels/TracerouteViewModel.cs +++ b/Source/NETworkManager/ViewModels/TracerouteViewModel.cs @@ -283,9 +283,7 @@ private void LoadSettings() private bool Trace_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow)!.IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void TraceAction() diff --git a/Source/NETworkManager/ViewModels/WakeOnLANViewModel.cs b/Source/NETworkManager/ViewModels/WakeOnLANViewModel.cs index f34adb2788..c686513669 100644 --- a/Source/NETworkManager/ViewModels/WakeOnLANViewModel.cs +++ b/Source/NETworkManager/ViewModels/WakeOnLANViewModel.cs @@ -1,4 +1,3 @@ -using MahApps.Metro.Controls; using NETworkManager.Localization.Resources; using NETworkManager.Models; using NETworkManager.Models.Network; @@ -169,9 +168,7 @@ public WakeOnLANViewModel() private bool WakeUpAction_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void WakeUpAction() diff --git a/Source/NETworkManager/ViewModels/WhoisViewModel.cs b/Source/NETworkManager/ViewModels/WhoisViewModel.cs index 03f0c4d8d5..fc55bf03ab 100644 --- a/Source/NETworkManager/ViewModels/WhoisViewModel.cs +++ b/Source/NETworkManager/ViewModels/WhoisViewModel.cs @@ -1,5 +1,4 @@ using log4net; -using MahApps.Metro.Controls; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Controls; using NETworkManager.Localization.Resources; @@ -149,9 +148,7 @@ private void LoadSettings() private bool Query_CanExecute(object parameter) { - return Application.Current.MainWindow != null && - !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && - !ConfigurationManager.Current.IsChildWindowOpen; + return !DialogHelper.IsAnyDialogOpen(); } private void QueryAction() diff --git a/Source/NETworkManager/ViewModels/WiFiConnectViewModel.cs b/Source/NETworkManager/ViewModels/WiFiConnectViewModel.cs index 7c706f9ca7..2b459473b3 100644 --- a/Source/NETworkManager/ViewModels/WiFiConnectViewModel.cs +++ b/Source/NETworkManager/ViewModels/WiFiConnectViewModel.cs @@ -1,3 +1,4 @@ +using log4net; using NETworkManager.Models.Network; using NETworkManager.Utilities; using NETworkManager.Settings; @@ -10,6 +11,8 @@ namespace NETworkManager.ViewModels; public class WiFiConnectViewModel : ViewModelBase { + private static readonly ILog Log = LogManager.GetLogger(typeof(WiFiConnectViewModel)); + /// /// Current WiFi adapter info and network info. /// @@ -273,6 +276,10 @@ public bool IsWpsAvailable } } + /// + /// Checks if WPS (push button) is available for the network (shows the WPS button). Called when the dialog is + /// loaded. + /// public async Task CheckWpsAsync() { // Only check if WPS is available for networks secured by Pre-shared key who are not hidden @@ -280,15 +287,25 @@ public async Task CheckWpsAsync() return; IsWpsChecking = true; - // Make the user happy, let him see a reload animation (and he cannot spam the reload command) - await Task.Delay(GlobalStaticConfiguration.ApplicationUIRefreshInterval / 2); - IsWpsAvailable = - await WiFi.IsWpsAvailable(Options.AdapterInfo.WiFiAdapter, Options.NetworkInfo.AvailableNetwork); + try + { + // Takes at least the refresh interval, so the animation is visible - the check runs at the same time + IsWpsAvailable = await TaskHelper.WithMinimumDurationAsync( + () => WiFi.IsWpsAvailable(Options.AdapterInfo.WiFiAdapter, Options.NetworkInfo.AvailableNetwork), + GlobalStaticConfiguration.ApplicationUIRefreshInterval); + } + catch (Exception ex) + { + // Optional: the network can still be connected with the pre-shared key + Log.Error("Error while checking if WPS is available.", ex); - // Make the user happy, let him see a reload animation (and he cannot spam the reload command) - await Task.Delay(GlobalStaticConfiguration.ApplicationUIRefreshInterval / 2); - IsWpsChecking = false; + IsWpsAvailable = false; + } + finally + { + IsWpsChecking = false; + } } /// diff --git a/Source/NETworkManager/ViewModels/WiFiSettingsViewModel.cs b/Source/NETworkManager/ViewModels/WiFiSettingsViewModel.cs new file mode 100644 index 0000000000..3753e3e2b4 --- /dev/null +++ b/Source/NETworkManager/ViewModels/WiFiSettingsViewModel.cs @@ -0,0 +1,98 @@ +using NETworkManager.Settings; + +namespace NETworkManager.ViewModels; + +/// +/// ViewModel for the WiFi settings. +/// +public class WiFiSettingsViewModel : ViewModelBase +{ + #region Variables + + private readonly bool _isLoading; + + /// + /// Gets or sets a value indicating whether a notification is shown when an automatic refresh found changes. + /// + public bool ShowNotificationPopup + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.WiFi_ShowNotificationPopup = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets a value indicating whether a sound is played when an automatic refresh found changes. + /// + public bool NotificationSound + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.WiFi_NotificationSound = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the seconds until the notification is closed. + /// + public int NotificationCloseTime + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.WiFi_NotificationCloseTime = value; + + field = value; + OnPropertyChanged(); + } + } + + #endregion + + #region Constructor, load settings + + /// + /// Initializes a new instance of the class. + /// + public WiFiSettingsViewModel() + { + _isLoading = true; + + LoadSettings(); + + _isLoading = false; + } + + /// + /// Loads the settings into the ViewModel. + /// + private void LoadSettings() + { + ShowNotificationPopup = SettingsManager.Current.WiFi_ShowNotificationPopup; + NotificationSound = SettingsManager.Current.WiFi_NotificationSound; + NotificationCloseTime = SettingsManager.Current.WiFi_NotificationCloseTime; + } + + #endregion +} diff --git a/Source/NETworkManager/ViewModels/WiFiViewModel.cs b/Source/NETworkManager/ViewModels/WiFiViewModel.cs index fd90245358..283a4da165 100644 --- a/Source/NETworkManager/ViewModels/WiFiViewModel.cs +++ b/Source/NETworkManager/ViewModels/WiFiViewModel.cs @@ -7,8 +7,10 @@ using log4net; using MahApps.Metro.SimpleChildWindow; using NETworkManager.Controls; +using NETworkManager.Converters; using NETworkManager.Localization; using NETworkManager.Localization.Resources; +using NETworkManager.Models; using NETworkManager.Models.Export; using NETworkManager.Models.Network; using NETworkManager.Settings; @@ -41,6 +43,11 @@ public class WiFiViewModel : ViewModelBase private static readonly ILog Log = LogManager.GetLogger(typeof(WiFiViewModel)); private readonly bool _isLoading; + + /// + /// The access to the WiFi adapter is being checked again (see ). + /// + private bool _isCheckingAccess; /// /// Refreshes the view automatically (see ). /// @@ -83,6 +90,7 @@ public bool IsAdaptersLoading field = value; OnPropertyChanged(); + OnPropertyChanged(nameof(CanChangeAdapter)); } } @@ -112,7 +120,13 @@ public WiFiAdapterInfo SelectedAdapter if (!_isLoading) SettingsManager.Current.WiFi_InterfaceId = value.NetworkInterfaceInfo.Id; - _ = ScanAsync(value); + // The same adapter after the adapters were reloaded: refresh in the background (the networks stay + // visible), another adapter: show the loading indicator instead of the networks of the previous one. + // Compared with the adapter of the shown networks, not the previous selection: replacing the adapters + // clears the selection of the combo box (null) before the reloaded adapter is selected. + var isSameAdapter = value.NetworkInterfaceInfo.Id == _previousScanAdapterId; + + _ = ScanAsync(value, isSameAdapter); } field = value; @@ -120,6 +134,14 @@ public WiFiAdapterInfo SelectedAdapter } } + /// + /// Gets whether another adapter can be selected: not while the adapters are reloaded (the reloaded adapter is + /// selected afterwards), the networks are scanned (the result of the previous adapter could arrive after the one + /// of the new adapter) or a connection is made. + /// + public bool CanChangeAdapter => !IsAdaptersLoading && !IsNetworksLoading && !IsBackgroundSearchRunning && + !IsConnecting; + public bool IsNetworksLoading { get; @@ -130,6 +152,7 @@ public bool IsNetworksLoading field = value; OnPropertyChanged(); + OnPropertyChanged(nameof(CanChangeAdapter)); } } @@ -276,25 +299,21 @@ public bool Show6GHzNetworks } } - public ObservableCollection Networks - { - get; - init - { - if (value != null && value == field) - return; - - field = value; - OnPropertyChanged(); - } - } = new(); + /// + /// Networks of the last successful scan and the id of its adapter: the next scan of the same adapter is compared + /// with it (see ). Only in memory. + /// + private IReadOnlyList _previousScan; - public ICollectionView NetworksView { get; } + private string _previousScanAdapterId; - public WiFiNetworkInfo SelectedNetwork + /// + /// Gets whether the shown networks are compared with a previous scan (shows the column and the counters). + /// + public bool HasComparison { get; - set + private set { if (value == field) return; @@ -304,115 +323,101 @@ public WiFiNetworkInfo SelectedNetwork } } - public IList SelectedNetworks + /// + /// Gets the number of networks that are visible now and were not in the previous scan. + /// + public int NetworksNew { get; - set + private set { - if (Equals(value, field)) + if (value == field) return; field = value; OnPropertyChanged(); } - } = new ArrayList(); + } - public ISeries[] Radio2Dot4GHzSeries + /// + /// Gets the number of networks that were visible in the previous scan and are not now. + /// + public int NetworksGone { get; private set { - field = value; - OnPropertyChanged(); - } - } = []; + if (value == field) + return; - public ISeries[] Radio5GHzSeries - { - get; - private set - { field = value; OnPropertyChanged(); } - } = []; + } - // 6 GHz spans a very wide range (channels 1-233). It is split into a lower (1-125) and an upper - // (129-233) chart for readability, similar to the UniFi channel view. - public ISeries[] Radio6GHzLowerSeries + /// + /// Gets the number of networks whose channel, channel width or security changed since the previous scan. + /// + public int NetworksChanged { get; private set { + if (value == field) + return; + field = value; OnPropertyChanged(); } - } = []; + } - public ISeries[] Radio6GHzUpperSeries + public ObservableRangeCollection Networks { get; - private set + init { + if (value != null && value == field) + return; + field = value; OnPropertyChanged(); } - } = []; - - public Axis[] Radio2Dot4GHzXAxes { get; private set; } - public Axis[] Radio5GHzXAxes { get; private set; } - public Axis[] Radio6GHzLowerXAxes { get; private set; } - public Axis[] Radio6GHzUpperXAxes { get; private set; } - - public Axis[] Radio2Dot4GHzYAxes { get; private set; } - public Axis[] Radio5GHzYAxes { get; private set; } - public Axis[] Radio6GHzLowerYAxes { get; private set; } - public Axis[] Radio6GHzUpperYAxes { get; private set; } + } = new(); - public RectangularSection[] Radio2Dot4GHzSections { get; private set; } - public RectangularSection[] Radio5GHzSections { get; private set; } - public RectangularSection[] Radio6GHzLowerSections { get; private set; } - public RectangularSection[] Radio6GHzUpperSections { get; private set; } + public ICollectionView NetworksView { get; } - public WiFiChannelLegendEntry[] Radio2Dot4GHzLegend + public WiFiNetworkInfo SelectedNetwork { get; - private set + set { - field = value; - OnPropertyChanged(); - } - } = []; + if (value == field) + return; - public WiFiChannelLegendEntry[] Radio5GHzLegend - { - get; - private set - { field = value; OnPropertyChanged(); } - } = []; + } - public WiFiChannelLegendEntry[] Radio6GHzLowerLegend + public IList SelectedNetworks { get; - private set + set { - field = value; - OnPropertyChanged(); - } - } = []; + if (Equals(value, field)) + return; - public WiFiChannelLegendEntry[] Radio6GHzUpperLegend - { - get; - private set - { field = value; OnPropertyChanged(); } - } = []; + } = new ArrayList(); + + // 6 GHz spans a very wide range (channels 1-233). It is split into a lower (1-125) and an upper + // (129-233) chart for readability, similar to the UniFi channel view. + public WiFiChannelChart Chart2Dot4GHz { get; private set; } + public WiFiChannelChart Chart5GHz { get; private set; } + public WiFiChannelChart Chart6GHzLower { get; private set; } + public WiFiChannelChart Chart6GHzUpper { get; private set; } public bool IsStatusMessageDisplayed { @@ -437,6 +442,7 @@ public bool IsBackgroundSearchRunning field = value; OnPropertyChanged(); + OnPropertyChanged(nameof(CanChangeAdapter)); } } @@ -463,6 +469,7 @@ public bool IsConnecting field = value; OnPropertyChanged(); + OnPropertyChanged(nameof(CanChangeAdapter)); } } @@ -502,30 +509,10 @@ public WiFiViewModel() _isLoading = true; - // Set up the channel charts (axes, sections, paints) unconditionally so the chart bindings - // are never null, even on the code paths that return early below. + // Set up the channel charts (axes, sections, paints), the list and the timers unconditionally, so the + // bindings are never null - also if the WiFi API is not available or the access is denied (yet) InitializeCharts(); - // Check if Microsoft.Windows.SDK.Contracts is available - SdkContractAvailable = ApiInformation.IsTypePresent("Windows.Devices.WiFi.WiFiAdapter"); - - if (!SdkContractAvailable) - { - _isLoading = false; - - return; - } - - // Check if the access is denied and show a message - WiFiAdapterAccessEnabled = RequestAccess(); - - if (!WiFiAdapterAccessEnabled) - { - _isLoading = false; - - return; - } - // Result view + search NetworksView = CollectionViewSource.GetDefaultView(Networks); NetworksView.SortDescriptions.Add(new SortDescription( @@ -548,29 +535,31 @@ public WiFiViewModel() if (string.IsNullOrEmpty(Search)) return true; - // Search by SSID, authentication type, channel frequency, channel, BSSID, vendor and PHY kind - return info.AvailableNetwork.Ssid.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || + // Search by SSID ("Hidden Network" as shown), authentication type, channel frequency, channel, BSSID, + // vendor and PHY kind + return WiFiNetworkToSsidStringConverter.GetSsid(info).IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.NetworkAuthenticationType.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || $"{info.ChannelCenterFrequencyInGigahertz}".IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || $"{info.Channel}".IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || - info.AvailableNetwork.Bssid.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || + info.Bssid.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.Vendor.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || - info.PhyKind.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1; + info.PhyKind.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || + (HasComparison && WiFiNetworkChangeToStringConverter.ToLocalizedString(info.Change) + .IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1); }; - // Load network adapters - _ = LoadAdaptersAsync(SettingsManager.Current.WiFi_InterfaceId); - - // Auto refresh - // Not while networks are loading or a connection is made (tried again after the interval) - _autoRefreshTimer = new AutoRefreshTimer(() => ScanAsync(SelectedAdapter, true), - () => !IsNetworksLoading && !IsBackgroundSearchRunning && !IsConnecting); + // Auto refresh (enabled when the access is allowed, see Start) + // Not without an adapter, while a dialog is open (e.g. connect), or while the adapters are reloaded (they select + // the adapter again, which scans it), networks are loading or a connection is made (tried again after the + // interval) + _autoRefreshTimer = new AutoRefreshTimer(() => ScanAsync(SelectedAdapter, true, isAutoRefresh: true), + () => SelectedAdapter != null && !DialogHelper.IsAnyDialogOpen() && !IsAdaptersLoading && !IsNetworksLoading && + !IsBackgroundSearchRunning && !IsConnecting); AutoRefreshTimes = CollectionViewSource.GetDefaultView(AutoRefreshTime.GetDefaults); SelectedAutoRefreshTime = AutoRefreshTimes.Cast().FirstOrDefault(x => x.Value == SettingsManager.Current.WiFi_AutoRefreshTime.Value && x.TimeUnit == SettingsManager.Current.WiFi_AutoRefreshTime.TimeUnit); - AutoRefreshEnabled = SettingsManager.Current.WiFi_AutoRefreshEnabled; // Hide ConnectionStatusMessage automatically _hideConnectionStatusMessageTimer.Interval = new TimeSpan(0, 0, 15); @@ -579,9 +568,57 @@ public WiFiViewModel() // Load settings LoadSettings(); + // Check if Microsoft.Windows.SDK.Contracts is available + SdkContractAvailable = ApiInformation.IsTypePresent("Windows.Devices.WiFi.WiFiAdapter"); + + if (SdkContractAvailable) + { + // Check if the access is denied and show a message (checked again, see CheckAccessAsync) + WiFiAdapterAccessEnabled = RequestAccess(); + + if (WiFiAdapterAccessEnabled) + Start(); + } + _isLoading = false; } + /// + /// Loads the adapters (scans the networks of the selected one) and enables the auto refresh. Called once the + /// access to the WiFi adapter is allowed. + /// + private void Start() + { + _ = LoadAdaptersAsync(SettingsManager.Current.WiFi_InterfaceId); + + AutoRefreshEnabled = SettingsManager.Current.WiFi_AutoRefreshEnabled; + } + + /// + /// Checks the access to the WiFi adapter again while it is denied (e.g. it was allowed in the Windows settings + /// after the message was shown), and starts if it is allowed now - without a restart of the application. + /// + private async Task CheckAccessAsync() + { + if (!SdkContractAvailable || WiFiAdapterAccessEnabled || _isCheckingAccess) + return; + + _isCheckingAccess = true; + + try + { + // Not on the UI thread (called on every switch to WiFi while the access is denied) + WiFiAdapterAccessEnabled = await RequestAccessAsync(); + } + finally + { + _isCheckingAccess = false; + } + + if (WiFiAdapterAccessEnabled) + Start(); + } + private void LoadSettings() { Show2Dot4GHzNetworks = SettingsManager.Current.WiFi_Show2dot4GHzNetworks; @@ -597,7 +634,9 @@ private void LoadSettings() private bool ReloadAdapter_CanExecute(object obj) { - return !IsAdaptersLoading && !IsNetworksLoading && !IsBackgroundSearchRunning && !AutoRefreshEnabled && !IsConnecting; + // Not blocked by the auto refresh (it only scans the networks): without an adapter its toggle is hidden + return !DialogHelper.IsAnyDialogOpen() && !IsAdaptersLoading && !IsNetworksLoading && !IsBackgroundSearchRunning && + !IsConnecting; } private void ReloadAdapterAction() @@ -610,7 +649,8 @@ private void ReloadAdapterAction() private bool ScanNetworks_CanExecute(object obj) { - return !IsAdaptersLoading && !IsNetworksLoading && !IsBackgroundSearchRunning && !AutoRefreshEnabled && !IsConnecting; + return SelectedAdapter != null && !DialogHelper.IsAnyDialogOpen() && !IsAdaptersLoading && !IsNetworksLoading && + !IsBackgroundSearchRunning && !AutoRefreshEnabled && !IsConnecting; } private async Task ScanNetworksAction() @@ -618,18 +658,52 @@ private async Task ScanNetworksAction() await ScanAsync(SelectedAdapter, true); } - public ICommand ConnectCommand => new RelayCommand(_ => ConnectAction()); + public ICommand ConnectCommand => new RelayCommand(_ => ConnectAction(), ConnectDisconnect_CanExecute); + + /// + /// A network is selected that is still visible (not gone since the last scan), no connection is made, no scan is + /// running and the adapters are not reloaded at the moment (connecting and disconnecting scan the networks again + /// afterwards, the reload scans the reloaded adapter). + /// + private bool ConnectDisconnect_CanExecute(object obj) + { + return SelectedNetwork is { Change: not WiFiNetworkChange.Gone } && !IsConnecting && !IsAdaptersLoading && + !IsNetworksLoading && !IsBackgroundSearchRunning; + } private void ConnectAction() { Connect(); } - public ICommand DisconnectCommand => new RelayCommand(_ => DisconnectAction()); + public ICommand DisconnectCommand => new RelayCommand(_ => DisconnectAction(), ConnectDisconnect_CanExecute); private void DisconnectAction() { - Disconnect(); + _ = DisconnectAsync(); + } + + /// + /// Gets the command to copy a value of all selected networks (one per line, in the order shown in the grid, + /// without duplicates). Parameter: SSID or BSSID. + /// + public ICommand CopySelectedNetworksCommand => new RelayCommand(CopySelectedNetworksAction); + + private void CopySelectedNetworksAction(object parameter) + { + Func selector = parameter switch + { + // Hidden networks have no SSID + "SSID" => x => x.AvailableNetwork.Ssid, + "BSSID" => x => x.Bssid, + _ => null + }; + + if (selector == null) + return; + + ClipboardHelper.SetClipboard(string.Join(Environment.NewLine, + GetSelectedNetworksInGridOrder().Select(selector).Where(x => !string.IsNullOrEmpty(x)).Distinct())); } public ICommand ExportCommand => new RelayCommand(_ => ExportAction()); @@ -639,6 +713,8 @@ private void ExportAction() _ = Export(); } + public ICommand CheckAccessCommand => new RelayCommand(_ => { _ = CheckAccessAsync(); }); + public ICommand OpenSettingsCommand => new RelayCommand(_ => OpenSettingsAction()); private static void OpenSettingsAction() @@ -655,10 +731,20 @@ private static void OpenSettingsAction() /// /// Fails if the access is denied. private static bool RequestAccess() + { + // Safe to block: the continuation of RequestAccessAsync doesn't need the UI thread (ConfigureAwait(false)) + return RequestAccessAsync().GetAwaiter().GetResult(); + } + + /// + /// Request access to the Wi-Fi adapter without blocking the calling thread. + /// + /// Fails if the access is denied. + private static async Task RequestAccessAsync() { try { - var accessStatus = WiFiAdapter.RequestAccessAsync().GetAwaiter().GetResult(); + var accessStatus = await WiFiAdapter.RequestAccessAsync().AsTask().ConfigureAwait(false); return accessStatus == WiFiAccessStatus.Allowed; } @@ -692,7 +778,8 @@ private async Task LoadAdaptersAsync(string adapterId = null) { Log.Error("Error trying to get WiFi adapters.", ex); - Adapters.Clear(); + // A new list (Clear() on the list doesn't update the view, it would keep showing the previous adapters) + Adapters = []; } // Check if we found any adapters @@ -721,6 +808,9 @@ private async Task LoadAdaptersAsync(string adapterId = null) else { Log.Debug("LoadAdaptersAsync - No WiFi adapters found."); + + // E.g. the USB adapter was unplugged: no auto refresh of the removed adapter (its toggle is hidden now) + SelectedAdapter = null; } IsAdaptersLoading = false; @@ -728,7 +818,17 @@ private async Task LoadAdaptersAsync(string adapterId = null) Log.Debug("LoadAdaptersAsync - Done."); } - private async Task ScanAsync(WiFiAdapterInfo adapterInfo, bool refreshing = false, int delayInMs = 0) + /// + /// Scans the networks of an adapter and shows them (with the changes since the previous scan). + /// + /// Adapter to scan. + /// + /// A refresh of the shown networks (in the background, they stay visible), not the first scan of the adapter. + /// + /// Delay before the scan (e.g. after connecting). + /// The scan is an automatic refresh: changes are notified (see settings). + private async Task ScanAsync(WiFiAdapterInfo adapterInfo, bool refreshing = false, int delayInMs = 0, + bool isAutoRefresh = false) { Log.Debug($"ScanAsync - Scanning WiFi adapter \"{adapterInfo.NetworkInterfaceInfo.Name}\" with delay of {delayInMs} ms..."); @@ -751,73 +851,85 @@ private async Task ScanAsync(WiFiAdapterInfo adapterInfo, bool refreshing = fals Log.Debug("ScanAsync - Scan completed. Found " + wiFiNetworkScanInfo.WiFiNetworkInfos.Count + " networks."); - // Clear the values after the scan to make the UI smoother - Log.Debug("ScanAsync - Clearing old values..."); - Networks.Clear(); + // Remember the selected network, because replacing the networks clears the selection + var selectedBssid = SelectedNetwork?.Bssid; - Log.Debug("ScanAsync - Adding new values..."); - List series2Dot4GHz = []; - List series5GHz = []; - List series6GHzLower = []; - List series6GHzUpper = []; - List legend2Dot4GHz = []; - List legend5GHz = []; - List legend6GHzLower = []; - List legend6GHzUpper = []; + // Replace all networks with a single notification, so the view is filtered / sorted only once. With the + // networks that are gone since the previous scan of this adapter. + Networks.ReplaceAll(CompareWithPreviousScan(adapterInfo, wiFiNetworkScanInfo.WiFiNetworkInfos)); - foreach (var network in wiFiNetworkScanInfo.WiFiNetworkInfos) + if (isAutoRefresh && HasComparison) + NotifyChanges(adapterInfo); + + // Select the network again (e.g. after an auto refresh), so the selection and the scroll position are kept. + // If several networks were selected, only this one is selected again. Not if it is hidden by the filter. + if (selectedBssid != null) + { + var network = Networks.FirstOrDefault(x => x.Bssid == selectedBssid); + + if (network != null && NetworksView.Contains(network)) + SelectedNetwork = network; + } + + // Series and legend of each chart. The color of a network depends on its position in its chart; the two 6 GHz + // charts count together, so a network that is drawn in both has the same color in both. + var charts = new Dictionary Series, List Legend)> { - Log.Debug("ScanAsync - Add network: " + network.AvailableNetwork.Ssid + " with channel frequency: " + - network.AvailableNetwork.ChannelCenterFrequencyInKilohertz); + [Chart2Dot4GHz] = ([], []), + [Chart5GHz] = ([], []), + [Chart6GHzLower] = ([], []), + [Chart6GHzUpper] = ([], []) + }; - Networks.Add(network); + var sixGHzColorIndex = 0; + void AddToChart(WiFiChannelChart chart, WiFiNetworkInfo network, int? colorIndex = null) + { + var (series, legend) = charts[chart]; + var (networkSeries, networkLegend) = BuildNetworkSeries(network, colorIndex ?? series.Count); + + series.Add(networkSeries); + legend.Add(networkLegend); + } + + foreach (var network in wiFiNetworkScanInfo.WiFiNetworkInfos) + { switch (network.Radio) { case WiFiRadio.GHz2dot4: - var (s24, l24) = BuildNetworkSeries(network, series2Dot4GHz.Count); - series2Dot4GHz.Add(s24); - legend2Dot4GHz.Add(l24); + AddToChart(Chart2Dot4GHz, network); break; case WiFiRadio.GHz5: - var (s5, l5) = BuildNetworkSeries(network, series5GHz.Count); - series5GHz.Add(s5); - legend5GHz.Add(l5); + AddToChart(Chart5GHz, network); break; case WiFiRadio.GHz6: - // Split by channel center into the lower (1-125) and upper (129-233) chart. - var centerChannel = FrequencyToChannelAxis( - network.ChannelCenterFrequencyInGigahertz * 1000, WiFiRadio.GHz6); - - if (centerChannel < SixGHzSplitChannel) - { - var (s6L, l6L) = BuildNetworkSeries(network, series6GHzLower.Count); - series6GHzLower.Add(s6L); - legend6GHzLower.Add(l6L); - } - else - { - var (s6U, l6U) = BuildNetworkSeries(network, series6GHzUpper.Count); - series6GHzUpper.Add(s6U); - legend6GHzUpper.Add(l6U); - } + // Split into the lower (1-125) and upper (129-233) chart by the channels the network covers + // (channel-number space, 5 MHz per unit). A network that crosses the split (e.g. 320 MHz + // around channel 127 covers 95 - 159) is drawn in both charts. + var (lower, upper) = WiFiChannelAxis.GetSixGHzCharts( + network.ChannelBandwidthCenterFrequencyInGigahertz * 1000, network.ChannelBandwidth); + + if (lower) + AddToChart(Chart6GHzLower, network, sixGHzColorIndex); + + if (upper) + AddToChart(Chart6GHzUpper, network, sixGHzColorIndex); + + sixGHzColorIndex++; break; } } - Radio2Dot4GHzSeries = [.. series2Dot4GHz]; - Radio5GHzSeries = [.. series5GHz]; - Radio6GHzLowerSeries = [.. series6GHzLower]; - Radio6GHzUpperSeries = [.. series6GHzUpper]; - Radio2Dot4GHzLegend = [.. legend2Dot4GHz]; - Radio5GHzLegend = [.. legend5GHz]; - Radio6GHzLowerLegend = [.. legend6GHzLower]; - Radio6GHzUpperLegend = [.. legend6GHzUpper]; + foreach (var (chart, (series, legend)) in charts) + chart.Update(series, legend); LastRefreshTime = wiFiNetworkScanInfo.Timestamp; + + // Connected / disconnected (also outside of NETworkManager) - the icon of the adapter selection + WiFi.UpdateAdapterStates(Adapters); } catch (Exception ex) { @@ -826,16 +938,27 @@ private async Task ScanAsync(WiFiAdapterInfo adapterInfo, bool refreshing = fals statusMessage = string.Format(Strings.ErrorWhileScanningWiFiAdapterXXXWithErrorXXX, adapterInfo.NetworkInterfaceInfo.Name, ex.Message); - // Clear the existing old values if an error occurs - Networks.Clear(); - Radio2Dot4GHzSeries = []; - Radio5GHzSeries = []; - Radio6GHzLowerSeries = []; - Radio6GHzUpperSeries = []; - Radio2Dot4GHzLegend = []; - Radio5GHzLegend = []; - Radio6GHzLowerLegend = []; - Radio6GHzUpperLegend = []; + // A refresh (manual, automatic, after connecting) keeps the networks of the last scan (e.g. the adapter is + // busy shortly after connecting); the header still shows the time of the last scan. The networks of + // another adapter (first scan) are cleared. + if (!refreshing) + { + // No time of the last scan and no changes of the previous adapter in the header, nothing to compare + // the next scan with (the networks are cleared) + LastRefreshTime = null; + _previousScan = null; + _previousScanAdapterId = null; + HasComparison = false; + NetworksNew = 0; + NetworksGone = 0; + NetworksChanged = 0; + + Networks.Clear(); + Chart2Dot4GHz.Clear(); + Chart5GHz.Clear(); + Chart6GHzLower.Clear(); + Chart6GHzUpper.Clear(); + } } finally { @@ -870,29 +993,19 @@ private async Task ScanAsync(WiFiAdapterInfo adapterInfo, bool refreshing = fals // 2.4 GHz operating channels are 1, 2, 3, ... 14 (every channel number), labeled with the channel private static readonly HashSet ValidChannels2Dot4GHz = BuildChannelSet(1, 14, 1); - // 5 GHz operating channels are 36, 40, 44, ... 165 (every 4 in channel-number space), labeled with + // 5 GHz operating channels are 36 - 64 and 100 - 144 (every 4 in channel-number space) and 149 - 177 (UNII-3 / -4, + // odd channel numbers), labeled with the channel private static readonly HashSet ValidChannels5GHz = [ .. BuildChannelSet(36, 64, 4), - .. BuildChannelSet(100, 165, 4) + .. BuildChannelSet(100, 144, 4), + .. BuildChannelSet(149, 177, 4) ]; - // 6 GHz operating channels are 1, 5, 9, ... 233 (every 4 in channel-number space), labeled with the + // 6 GHz operating channels are 1, 5, 9, ... 233 (every 4 in channel-number space), labeled with the channel. + // Channel 2 (5935 MHz) is below channel 1, at -3 on the axis - not labeled (the tooltip shows it). private static readonly HashSet ValidChannels6GHz = BuildChannelSet(1, 233, 4); - // Channel that splits the 6 GHz band into the lower (1-125) and upper (129-233) chart. 127 sits - // cleanly between the operating channels 125 and 129. - private const int SixGHzSplitChannel = 127; - - // The 5 GHz band has a large unused range between channel 64 (UNII-2) and channel 100 - // (UNII-2 Extended). On a frequency-linear axis this would render as dead space, so it is - // compressed: channels above 64 are shifted left, leaving only a small visual gap that still - // provides room for the channel-width trapezoids. - private const int FiveGHzGapStartChannel = 64; - private const int FiveGHzGapEndChannel = 100; - private const int FiveGHzGapDisplayUnits = 16; - private const int FiveGHzGapShift = FiveGHzGapEndChannel - FiveGHzGapStartChannel - FiveGHzGapDisplayUnits; - private static HashSet BuildChannelSet(int first, int last, int step) { var set = new HashSet(); @@ -920,29 +1033,22 @@ private void InitializeCharts() // (min, max) in display space. The lower bound is extended below the first channel so the // left flank of its trapezoid reaches the baseline instead of being clipped. The 5 GHz // upper bound is reduced because the 64..100 dead zone is compressed. - Radio2Dot4GHzXAxes = BuildXAxes(-2, 16, ValidChannels2Dot4GHz, false, labelColor); - Radio5GHzXAxes = BuildXAxes(30, 152, ValidChannels5GHz, true, labelColor); - Radio6GHzLowerXAxes = BuildXAxes(-2, 128, ValidChannels6GHz, false, labelColor); - Radio6GHzUpperXAxes = BuildXAxes(126, 236, ValidChannels6GHz, false, labelColor); - - Radio2Dot4GHzYAxes = BuildYAxes(labelColor, separatorColor); - Radio5GHzYAxes = BuildYAxes(labelColor, separatorColor); - Radio6GHzLowerYAxes = BuildYAxes(labelColor, separatorColor); - Radio6GHzUpperYAxes = BuildYAxes(labelColor, separatorColor); - - Radio2Dot4GHzSections = BuildSections(); - Radio5GHzSections = BuildSections(); - Radio6GHzLowerSections = BuildSections(); - Radio6GHzUpperSections = BuildSections(); + Chart2Dot4GHz = new WiFiChannelChart(BuildXAxes(-2, 16, ValidChannels2Dot4GHz, WiFiRadio.GHz2dot4, labelColor), + BuildYAxes(labelColor, separatorColor), BuildSections()); + Chart5GHz = new WiFiChannelChart(BuildXAxes(30, 160, ValidChannels5GHz, WiFiRadio.GHz5, labelColor), + BuildYAxes(labelColor, separatorColor), BuildSections()); + Chart6GHzLower = new WiFiChannelChart(BuildXAxes(-6, 128, ValidChannels6GHz, WiFiRadio.GHz6, labelColor), + BuildYAxes(labelColor, separatorColor), BuildSections()); + Chart6GHzUpper = new WiFiChannelChart(BuildXAxes(126, 236, ValidChannels6GHz, WiFiRadio.GHz6, labelColor), + BuildYAxes(labelColor, separatorColor), BuildSections()); } /// /// Builds an X-axis in channel-number space (which is linear with the channel frequency). /// Only channels contained in are labeled; all other tick - /// positions stay blank. When is set, the 5 GHz gap shift - /// is reversed before the label lookup. + /// positions stay blank (see ). /// - private static Axis[] BuildXAxes(double min, double max, HashSet validChannels, bool applyFiveGHzGap, + private static Axis[] BuildXAxes(double min, double max, HashSet validChannels, WiFiRadio radio, SKColor labelColor) { return @@ -958,10 +1064,7 @@ private static Axis[] BuildXAxes(double min, double max, HashSet validChann ForceStepToMin = true, Labeler = value => { - var channel = (int)Math.Round(value); - - if (applyFiveGHzGap && channel > FiveGHzGapStartChannel) - channel += FiveGHzGapShift; + var channel = WiFiChannelAxis.PositionToChannel((int)Math.Round(value), radio); return validChannels.Contains(channel) ? channel.ToString() : string.Empty; }, @@ -1033,15 +1136,16 @@ private static RectangularSection NewSection(double yi, double yj, string color) /// /// Builds a line series and a matching legend entry for a single network, rendered as a - /// trapezoid centered on its channel center frequency. + /// trapezoid centered on the center frequency of the whole channel (not of the primary channel). /// private static (LineSeries Series, WiFiChannelLegendEntry Legend) BuildNetworkSeries(WiFiNetworkInfo network, int colorIndex) { var color = ChartPalette[colorIndex % ChartPalette.Length]; double dbm = network.AvailableNetwork.NetworkRssiInDecibelMilliwatts; - var center = ChannelNumberToDisplay( - FrequencyToChannelAxis(network.ChannelCenterFrequencyInGigahertz * 1000, network.Radio), network.Radio); + var center = WiFiChannelAxis.ChannelToPosition( + WiFiChannelAxis.FrequencyToChannel(network.ChannelBandwidthCenterFrequencyInGigahertz * 1000, + network.Radio), network.Radio); // Channel-number space uses 5 MHz per unit, so a bandwidth in MHz spans bandwidth/5 units. var bandwidth = network.ChannelBandwidth; @@ -1074,13 +1178,11 @@ private static (LineSeries Series, WiFiChannelLegendEntry Lege var points = pointList.ToArray(); - var name = network.IsHidden - ? $"{Strings.HiddenNetwork} ({network.AvailableNetwork.Bssid})" - : $"{network.AvailableNetwork.Ssid} ({network.AvailableNetwork.Bssid})"; + var ssid = WiFiNetworkToSsidStringConverter.GetSsid(network); var series = new LineSeries { - Name = name, + Name = $"{ssid} ({network.Bssid})", Values = points, // Plot in 0..100 space (dBm + 100) so the area fill drops to the bottom baseline. Mapping = (point, _) => new Coordinate(point.ChannelAxis, point.Dbm + SignalOffset), @@ -1091,38 +1193,122 @@ private static (LineSeries Series, WiFiChannelLegendEntry Lege }; var wpfColor = Color.FromArgb(color.Alpha, color.Red, color.Green, color.Blue); - var legendSsid = network.IsHidden ? Strings.HiddenNetwork : network.AvailableNetwork.Ssid; - var legend = new WiFiChannelLegendEntry(new SolidColorBrush(wpfColor), legendSsid, network.AvailableNetwork.Bssid); + var legend = new WiFiChannelLegendEntry(new SolidColorBrush(wpfColor), ssid, network.Bssid); return (series, legend); } /// - /// Converts a channel center frequency (MHz) to channel-number space for the chart X axis. - /// This mapping is linear with frequency (5 MHz per unit). + /// Compares the networks of a scan with the previous scan of the same adapter: marks new and changed networks, + /// adds the networks that are gone (shown until the next scan). The scan becomes the one the next scan is + /// compared with. Another adapter (or the first scan) starts without a comparison. /// - private static double FrequencyToChannelAxis(double frequencyMHz, WiFiRadio radio) + /// Adapter of the scan. + /// Networks of the scan. + /// The networks to show (the scanned ones and the gone ones). + private List CompareWithPreviousScan(WiFiAdapterInfo adapterInfo, + IReadOnlyList networks) { - return radio switch + var rows = new List(networks); + var adapterId = adapterInfo.NetworkInterfaceInfo.Id; + + if (_previousScan != null && _previousScanAdapterId == adapterId) { - // Channel 14 is at 2484 MHz and does not follow the standard ch×5 + 2407 spacing. - WiFiRadio.GHz2dot4 => (int)Math.Round(frequencyMHz) == 2484 ? 14.0 : (frequencyMHz - 2407) / 5.0, - WiFiRadio.GHz5 => (frequencyMHz - 5000) / 5.0, - WiFiRadio.GHz6 => (frequencyMHz - 5950) / 5.0, - _ => 0 - }; + // The networks of the previous scan are not shown anymore (except the gone ones): no chain of previous + // networks over the scans + foreach (var network in _previousScan) + network.Previous = null; + + var comparison = WiFiScanComparer.Compare(_previousScan, networks); + + foreach (var (network, change, previous) in comparison.Changes) + { + network.Change = change; + network.Previous = previous; + } + + // Shown as they were in the previous scan (not connected, not drawn in the charts) + foreach (var network in comparison.Gone) + { + network.Change = WiFiNetworkChange.Gone; + network.IsConnected = false; + + rows.Add(network); + } + + NetworksNew = comparison.Changes.Count(x => x.Change == WiFiNetworkChange.New); + NetworksGone = comparison.Gone.Count; + NetworksChanged = comparison.Changes.Count(x => x.Change == WiFiNetworkChange.Changed); + HasComparison = true; + } + else + { + NetworksNew = 0; + NetworksGone = 0; + NetworksChanged = 0; + HasComparison = false; + } + + _previousScan = networks; + _previousScanAdapterId = adapterId; + + return rows; } /// - /// Maps a channel number to its display position on the X axis. For 5 GHz the unused - /// 64..100 range is compressed so it does not render as dead space. + /// Shows a notification with the changes since the previous scan (popup and / or sound, see settings), if there + /// are any. Like the IP Scanner, only for an automatic refresh. A click on it shows WiFi. /// - private static double ChannelNumberToDisplay(double channelNumber, WiFiRadio radio) + /// Adapter of the scan (title of the notification). + private void NotifyChanges(WiFiAdapterInfo adapterInfo) { - if (radio == WiFiRadio.GHz5 && channelNumber > FiveGHzGapStartChannel) - return channelNumber - FiveGHzGapShift; + var showPopup = SettingsManager.Current.WiFi_ShowNotificationPopup; + var playSound = SettingsManager.Current.WiFi_NotificationSound; + + if (!showPopup && !playSound) + return; + + var changes = Networks.Where(x => x.Change != WiFiNetworkChange.None) + .OrderBy(WiFiNetworkToSsidStringConverter.GetSsid, StringComparer.CurrentCultureIgnoreCase) + .ThenBy(x => x.Bssid, StringComparer.OrdinalIgnoreCase) + .ToList(); + + if (changes.Count == 0) + return; + + // "MyNetwork (AA:BB:CC:DD:EE:FF) · New" - new = up, gone = down, changed = changed + var lines = changes.Select(x => new NotificationLine($"{WiFiNetworkToSsidStringConverter.GetSsid(x)} ({x.Bssid})", + WiFiNetworkChangeToStringConverter.ToLocalizedString(x.Change), GetNotificationStatus(x.Change))).ToList(); + + var summary = new[] + { + (Count: NetworksNew, Format: Strings.XNew, Status: NotificationStatus.Up), + (Count: NetworksGone, Format: Strings.XGone, Status: NotificationStatus.Down), + (Count: NetworksChanged, Format: Strings.XChanged, Status: NotificationStatus.Changed) + } + .Where(x => x.Count > 0) + .Select(x => new NotificationLine(null, string.Format(x.Format, x.Count), x.Status)).ToList(); + + // New = up, gone = down, both = up and down, only changed = changed + var status = NotificationStatusHelper.FromChanges(NetworksNew, NetworksGone, NetworksChanged); - return channelNumber; + NotificationManager.Show(new NotificationInfo(ApplicationName.WiFi, status, + adapterInfo.NetworkInterfaceInfo.Name, NotificationManager.FormatChanges(lines, summary), + SettingsManager.Current.WiFi_NotificationCloseTime), + showPopup, playSound); + } + + /// + /// Gets the status (icon / color) of a change in the notification. + /// + private static NotificationStatus GetNotificationStatus(WiFiNetworkChange change) + { + return change switch + { + WiFiNetworkChange.New => NotificationStatus.Up, + WiFiNetworkChange.Gone => NotificationStatus.Down, + _ => NotificationStatus.Changed + }; } private void Connect() @@ -1142,59 +1328,32 @@ private void Connect() var ssid = selectedNetwork.IsHidden ? instance.Ssid : selectedNetwork.AvailableNetwork.Ssid; - // Show status message (not hidden by the timer of a previous message) - _hideConnectionStatusMessageTimer.Stop(); - IsConnecting = true; - ConnectionStatusMessage = string.Format(Strings.ConnectingToXXX, ssid); - IsConnectionStatusMessageDisplayed = true; - - // Connect to the network - var reconnectionKind = instance.ConnectAutomatically - ? WiFiReconnectionKind.Automatic - : WiFiReconnectionKind.Manual; - - PasswordCredential credential = new(); - - switch (instance.ConnectMode) + await ConnectAsync(ssid, () => { - case WiFiConnectMode.Psk: - credential.Password = SecureStringHelper.ConvertToString(instance.PreSharedKey); - break; - case WiFiConnectMode.Eap: - credential.UserName = instance.Username; - - if (!string.IsNullOrEmpty(instance.Domain)) - credential.Resource = instance.Domain; - - credential.Password = SecureStringHelper.ConvertToString(instance.Password); - break; - } - - WiFiConnectionStatus connectionResult; - - if (selectedNetwork.IsHidden) - connectionResult = await WiFi.ConnectAsync(instance.Options.AdapterInfo.WiFiAdapter, - instance.Options.NetworkInfo.AvailableNetwork, reconnectionKind, credential, instance.Ssid); - else - connectionResult = await WiFi.ConnectAsync(instance.Options.AdapterInfo.WiFiAdapter, - instance.Options.NetworkInfo.AvailableNetwork, reconnectionKind, credential); + PasswordCredential credential = new(); - // Done connecting - IsConnecting = false; + switch (instance.ConnectMode) + { + case WiFiConnectMode.Psk: + credential.Password = SecureStringHelper.ConvertToString(instance.PreSharedKey); + break; + // Without credentials, Windows uses the logged-on user or a certificate (like an open network, + // an empty credential is passed) + case WiFiConnectMode.Eap when instance.UseCredentials: + credential.UserName = instance.Username; - // Get result - ConnectionStatusMessage = connectionResult == WiFiConnectionStatus.Success - ? string.Format(Strings.SuccessfullyConnectedToXXX, ssid) - : string.Format(Strings.CouldNotConnectToXXXReasonXXX, ssid, - ResourceTranslator.Translate(ResourceIdentifier.WiFiConnectionStatus, connectionResult)); + if (!string.IsNullOrEmpty(instance.Domain)) + credential.Resource = instance.Domain; - // Hide message automatically - _hideConnectionStatusMessageTimer.Stop(); - _hideConnectionStatusMessageTimer.Start(); + credential.Password = SecureStringHelper.ConvertToString(instance.Password); + break; + } - // Update the Wi-Fi networks. - // Wait because an error may occur if a refresh is done directly after connecting. - await ScanAsync(SelectedAdapter, true, 5000); + // The SSID only for a hidden network + return WiFi.ConnectAsync(instance.Options.AdapterInfo.WiFiAdapter, + instance.Options.NetworkInfo.AvailableNetwork, GetReconnectionKind(instance), credential, + selectedNetwork.IsHidden ? instance.Ssid : null); + }); }, async instance => { // Connect WPS @@ -1203,37 +1362,8 @@ private void Connect() var ssid = selectedNetwork.IsHidden ? instance.Ssid : selectedNetwork.AvailableNetwork.Ssid; - // Show status message (not hidden by the timer of a previous message) - _hideConnectionStatusMessageTimer.Stop(); - IsConnecting = true; - ConnectionStatusMessage = string.Format(Strings.ConnectingToXXX, ssid); - IsConnectionStatusMessageDisplayed = true; - - // Connect to the network - var reconnectionKind = instance.ConnectAutomatically - ? WiFiReconnectionKind.Automatic - : WiFiReconnectionKind.Manual; - - var connectionResult = await WiFi.ConnectWpsAsync( - instance.Options.AdapterInfo.WiFiAdapter, instance.Options.NetworkInfo.AvailableNetwork, - reconnectionKind); - - // Done connecting - IsConnecting = false; - - // Get result - ConnectionStatusMessage = connectionResult == WiFiConnectionStatus.Success - ? string.Format(Strings.SuccessfullyConnectedToXXX, ssid) - : string.Format(Strings.CouldNotConnectToXXXReasonXXX, ssid, - ResourceTranslator.Translate(ResourceIdentifier.WiFiConnectionStatus, connectionResult)); - - // Hide message automatically - _hideConnectionStatusMessageTimer.Stop(); - _hideConnectionStatusMessageTimer.Start(); - - // Update the Wi-Fi networks. - // Wait because an error may occur if a refresh is done directly after connecting. - await ScanAsync(SelectedAdapter, true, 5000); + await ConnectAsync(ssid, () => WiFi.ConnectWpsAsync(instance.Options.AdapterInfo.WiFiAdapter, + instance.Options.NetworkInfo.AvailableNetwork, GetReconnectionKind(instance))); }, _ => { @@ -1254,27 +1384,103 @@ private void Connect() _ = Application.Current.MainWindow.ShowChildWindowAsync(childWindow); } - private async void Disconnect() + /// + /// Gets the reconnection kind of the connect dialog ("Connect automatically"). + /// + private static WiFiReconnectionKind GetReconnectionKind(WiFiConnectViewModel instance) { - var connectedNetwork = Networks.FirstOrDefault(x => x.IsConnected); + return instance.ConnectAutomatically ? WiFiReconnectionKind.Automatic : WiFiReconnectionKind.Manual; + } - WiFi.Disconnect(SelectedAdapter.WiFiAdapter); + /// + /// Connects to a network and shows the status (connecting, result) below the networks. The networks are + /// scanned again afterwards. + /// + /// SSID of the network, shown in the status message. + /// Connects to the network (Open / PSK / EAP or WPS) and returns the result. + private async Task ConnectAsync(string ssid, Func> connect) + { + // Show status message (not hidden by the timer of a previous message) + _hideConnectionStatusMessageTimer.Stop(); + IsConnecting = true; + ConnectionStatusMessage = string.Format(Strings.ConnectingToXXX, ssid); + IsConnectionStatusMessageDisplayed = true; - if (connectedNetwork != null) + try { - ConnectionStatusMessage = string.Format(Strings.XXXDisconnected, - connectedNetwork.AvailableNetwork.Ssid); - IsConnectionStatusMessageDisplayed = true; + // Connect to the network + var connectionResult = await connect(); - // Hide message automatically - _hideConnectionStatusMessageTimer.Stop(); - _hideConnectionStatusMessageTimer.Start(); + // Get result + ConnectionStatusMessage = connectionResult == WiFiConnectionStatus.Success + ? string.Format(Strings.SuccessfullyConnectedToXXX, ssid) + : string.Format(Strings.CouldNotConnectToXXXReasonXXX, ssid, + ResourceTranslator.Translate(ResourceIdentifier.WiFiConnectionStatus, connectionResult)); + } + catch (Exception ex) + { + // E.g. the adapter was disabled while connecting + Log.Error($"Error while connecting to the WiFi network \"{ssid}\".", ex); + + ConnectionStatusMessage = string.Format(Strings.CouldNotConnectToXXXReasonXXX, ssid, ex.Message); + } + finally + { + // Done connecting + IsConnecting = false; } + // Hide message automatically + _hideConnectionStatusMessageTimer.Stop(); + _hideConnectionStatusMessageTimer.Start(); + + // Update the Wi-Fi networks. + // Wait because an error may occur if a refresh is done directly after connecting. + await ScanAsync(SelectedAdapter, true, 5000); + } + + private async Task DisconnectAsync() + { + // The menu item is only shown for the connected network (the selected one if no network is marked anymore) + var connectedNetwork = Networks.FirstOrDefault(x => x.IsConnected) ?? SelectedNetwork; + + try + { + WiFi.Disconnect(SelectedAdapter.WiFiAdapter); + + if (connectedNetwork != null) + { + ConnectionStatusMessage = string.Format(Strings.XXXDisconnected, WiFiNetworkToSsidStringConverter.GetSsid(connectedNetwork)); + IsConnectionStatusMessageDisplayed = true; + } + } + catch (Exception ex) + { + Log.Error("Error while disconnecting the WiFi adapter.", ex); + + ConnectionStatusMessage = string.Format(Strings.CouldNotDisconnectFromXXXReasonXXX, + WiFiNetworkToSsidStringConverter.GetSsid(connectedNetwork), ex.Message); + IsConnectionStatusMessageDisplayed = true; + } + + // Hide message automatically + _hideConnectionStatusMessageTimer.Stop(); + _hideConnectionStatusMessageTimer.Start(); + // Refresh await ScanAsync(SelectedAdapter, true, GlobalStaticConfiguration.ApplicationUIRefreshInterval); } + /// + /// Gets the selected networks in the order they are shown in the grid (not in the order they were selected). + /// + private List GetSelectedNetworksInGridOrder() + { + var selectedNetworks = new HashSet(SelectedNetworks.Cast()); + + return NetworksView.Cast().Where(selectedNetworks.Contains).ToList(); + } + private Task Export() { var childWindow = new ExportChildWindow(); @@ -1286,11 +1492,13 @@ private Task Export() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Networks - : new ObservableCollection(SelectedNetworks.Cast() - .ToArray())); + // The networks shown in the grid (band filter, search) in their order. Copied on the UI thread, exported + // in the background + var networks = instance.ExportAll + ? NetworksView.Cast().ToList() + : GetSelectedNetworksInGridOrder(); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, networks)); } catch (Exception ex) { @@ -1323,6 +1531,9 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Erro public void OnViewVisible() { + // The access may have been allowed in the Windows settings in the meantime + _ = CheckAccessAsync(); + _autoRefreshTimer.Resume(); } @@ -1356,6 +1567,4 @@ private void ApplySearch() } #endregion -} - -public record WiFiChannelLegendEntry(SolidColorBrush Color, string Ssid, string Bssid); \ No newline at end of file +} \ No newline at end of file diff --git a/Source/NETworkManager/Views/WiFiConnectChildWindow.xaml.cs b/Source/NETworkManager/Views/WiFiConnectChildWindow.xaml.cs index b8dda18fb2..05b318e71a 100644 --- a/Source/NETworkManager/Views/WiFiConnectChildWindow.xaml.cs +++ b/Source/NETworkManager/Views/WiFiConnectChildWindow.xaml.cs @@ -1,6 +1,8 @@ using System; using System.Windows; using System.Windows.Threading; +using NETworkManager.Models.Network; +using NETworkManager.ViewModels; namespace NETworkManager.Views; @@ -13,12 +15,21 @@ public WiFiConnectChildWindow() private void ChildWindow_OnLoaded(object sender, RoutedEventArgs e) { + if (DataContext is not WiFiConnectViewModel viewModel) + return; + + // Focus the first input: SSID of a hidden network, otherwise the pre-shared key or the username (EAP) Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(delegate { - if (PasswordBoxPreSharedKey.Visibility == Visibility.Visible) - PasswordBoxPreSharedKey.Focus(); - else + if (viewModel.IsSsidRequired) + TextBoxSsid.Focus(); + else if (viewModel.ConnectMode == WiFiConnectMode.Psk) PasswordBoxPreSharedKey.Focus(); + else if (viewModel.ConnectMode == WiFiConnectMode.Eap) + TextBoxUsername.Focus(); })); + + // Shows the WPS button if WPS is available for the network + _ = viewModel.CheckWpsAsync(); } } \ No newline at end of file diff --git a/Source/NETworkManager/Views/WiFiSettingsView.xaml b/Source/NETworkManager/Views/WiFiSettingsView.xaml new file mode 100644 index 0000000000..a8650e1246 --- /dev/null +++ b/Source/NETworkManager/Views/WiFiSettingsView.xaml @@ -0,0 +1,31 @@ + + + + + + + + + + @@ -76,7 +114,8 @@ + SelectedItem="{Binding Path=SelectedAdapter}" + IsEnabled="{Binding Path=CanChangeAdapter}"> @@ -95,7 +134,7 @@ Value="{DynamicResource ResourceKey=MahApps.Brushes.Gray3}" /> @@ -213,6 +252,43 @@ Text="{x:Static Member=localization:Strings.Networks}" Style="{StaticResource ResourceKey=HeaderTextBlock}" Margin="0,0,0,0" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -418,6 +506,12 @@ + + + + @@ -428,7 +522,7 @@ - + + Binding="{Binding Path=(network:WiFiNetworkInfo.AvailableNetwork).SecuritySettings.NetworkEncryptionType}" + Value="None" /> + Binding="{Binding Path=(network:WiFiNetworkInfo.AvailableNetwork).SecuritySettings.NetworkEncryptionType}" + Value="None" /> + Binding="{Binding Path=(network:WiFiNetworkInfo.AvailableNetwork).SecuritySettings.NetworkEncryptionType}" + Value="None" /> + Binding="{Binding Path=(network:WiFiNetworkInfo.AvailableNetwork).SecuritySettings.NetworkEncryptionType}" + Value="None" /> + Binding="{Binding Path=(network:WiFiNetworkInfo.AvailableNetwork).SecuritySettings.NetworkEncryptionType}" + Value="None" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -610,9 +770,23 @@ MinWidth="80" /> + MinWidth="120"> + + + + + Style="{StaticResource ResourceKey=WiFiChannelChart}" + Series="{Binding Path=Chart2Dot4GHz.Series}" + XAxes="{Binding Path=Chart2Dot4GHz.XAxes}" + YAxes="{Binding Path=Chart2Dot4GHz.YAxes}" + Sections="{Binding Path=Chart2Dot4GHz.Sections}"> @@ -731,44 +900,17 @@ HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled" Margin="0,4,0,0"> - - - - - - - - - - - - - - - - - - + + Style="{StaticResource ResourceKey=WiFiChannelChart}" + Series="{Binding Path=Chart5GHz.Series}" + XAxes="{Binding Path=Chart5GHz.XAxes}" + YAxes="{Binding Path=Chart5GHz.YAxes}" + Sections="{Binding Path=Chart5GHz.Sections}"> @@ -777,30 +919,8 @@ HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled" Margin="0,4,0,0"> - - - - - - - - - - - - - - - - - - + @@ -818,16 +938,11 @@ + Style="{StaticResource ResourceKey=WiFiChannelChart}" + Series="{Binding Path=Chart6GHzLower.Series}" + XAxes="{Binding Path=Chart6GHzLower.XAxes}" + YAxes="{Binding Path=Chart6GHzLower.YAxes}" + Sections="{Binding Path=Chart6GHzLower.Sections}"> @@ -836,44 +951,17 @@ HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled" Margin="0,4,0,0"> - - - - - - - - - - - - - - - - - - + + Style="{StaticResource ResourceKey=WiFiChannelChart}" + Series="{Binding Path=Chart6GHzUpper.Series}" + XAxes="{Binding Path=Chart6GHzUpper.XAxes}" + YAxes="{Binding Path=Chart6GHzUpper.YAxes}" + Sections="{Binding Path=Chart6GHzUpper.Sections}"> @@ -882,30 +970,8 @@ HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled" Margin="0,4,0,0"> - - - - - - - - - - - - - - - - - - + @@ -1013,24 +1079,46 @@ - + + + + + \ No newline at end of file diff --git a/Source/NETworkManager/Views/WiFiView.xaml.cs b/Source/NETworkManager/Views/WiFiView.xaml.cs index 942768fd1d..82015a5dc4 100644 --- a/Source/NETworkManager/Views/WiFiView.xaml.cs +++ b/Source/NETworkManager/Views/WiFiView.xaml.cs @@ -1,5 +1,8 @@ -using System.Windows; +using System; +using System.Collections.Specialized; +using System.Windows; using System.Windows.Controls; +using System.Windows.Threading; using NETworkManager.ViewModels; namespace NETworkManager.Views; @@ -17,6 +20,29 @@ public WiFiView() InitializeComponent(); DataContext = _viewModel; + + _viewModel.Networks.CollectionChanged += Networks_CollectionChanged; + } + + /// + /// Scrolls the selected network into view after the networks were replaced by a scan (it is selected again, + /// see ). Not when the user changes the selection (e.g. Ctrl+click), + /// the grid would jump. + /// + private void Networks_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + { + if (e.Action != NotifyCollectionChangedAction.Reset) + return; + + // Wait until the network is selected again and the DataGrid has processed the new items and the selection + Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => + { + var network = _viewModel.SelectedNetwork; + + // The network may be hidden by the filter / search + if (network != null && DataGridNetworks.Items.Contains(network)) + DataGridNetworks.ScrollIntoView(network); + })); } public void OnViewHide() diff --git a/Website/docs/application/wifi.md b/Website/docs/application/wifi.md index f43bee8866..8b3d0e9c12 100644 --- a/Website/docs/application/wifi.md +++ b/Website/docs/application/wifi.md @@ -14,64 +14,151 @@ keywords: ] --- -# WiFi -The **WiFi** tool shows available wireless networks, including channel, signal strength, and encryption details. +# WiFi -Hidden wireless networks are shown as `Hidden Network`. +The **WiFi** tool shows the wireless networks (access points) in range of a WiFi adapter, with channel, channel width, signal strength and security, shows them on the channels of the 2.4, 5 and 6 GHz bands and connects to them. :::info -Wi-Fi is a wireless networking technology based on IEEE 802.11 standards. Access points periodically advertise network information (such as SSID and security capabilities), which clients can scan and display. +Wi-Fi is a wireless networking technology based on IEEE 802.11 standards. Access points periodically advertise network information (such as SSID and security capabilities) in beacons, which clients can scan and display. + +::: + +:::note + +Starting with Windows 11 24H2, you must allow access to the Wi-Fi adapter: open `Windows Settings > Privacy & security > Location` and enable access for Desktop Apps / NETworkManager. **Open settings** below the message opens these settings; after allowing the access, **Refresh** below the message (or switching back to **WiFi**) loads the adapters, a restart is not needed. ::: ## WiFi -On the **WiFi** tab, you can select which wireless adapter is used for scanning. Results can be filtered by the 2.4 GHz, 5 GHz, and 6 GHz bands. +![WiFi](../img/wifi.png) -In the search field, you can filter wireless networks by `SSID`, `Security`, `Frequency`, `Channel`, `BSSID (MAC Address)`, `Vendor`, and `PHY kind`. Search is case-insensitive. +### Toolbar + +| Element | Description | +| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Interface** | WiFi adapter that is scanned (the icon shows if it is connected). The selected adapter is saved. The button next to it reloads the adapters (e.g. after an adapter was plugged in). The adapter can't be changed while scanning or connecting. | +| **Last scan at** | Time of the last scan (the tooltip shows the date), with **Automatically update every** a countdown to the next scan (`Next refresh in 00:12`). | +| **Automatically update every** | Scans the networks again after the selected interval (`5 s` to `5 min`, default `30 s`, the pause after a scan). It pauses while another tool or a dialog is shown. The interval and the checkbox are saved. | +| **Refresh** | Scans the networks again (`F5`). Not available while **Automatically update every** is enabled. | +| **2.4 GHz** / **5 GHz** / **6 GHz** | Show or hide the networks of a band (saved). | +| Search | Filters the networks by SSID (`Hidden Network` for hidden networks), security, frequency, channel, BSSID (MAC address), vendor, PHY kind and the change since the last scan. Case-insensitive, after a short delay while typing (`Enter` filters right away). | + +A refresh (manual, automatic or after connecting) keeps the networks and the selected network visible while scanning (the refresh icon spins). If a refresh fails, the networks of the last scan stay and the error is shown below them. + +### Columns + +| Column | Description | +| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Icon | Signal bars, with a lock if the network is secured (sorts by the signal bars) | +| **Since last scan** | Change since the previous scan, see [Changes since the last scan](#changes-since-the-last-scan) (only if the networks are compared with one) | +| **SSID** | Name of the network, `Hidden Network` for a hidden network | +| **Connected** | The selected adapter is connected to this access point | +| **Security** | Authentication, e.g. `WPA2 Personal (PSK)`, `WPA3 Personal (SAE)`, `WPA2 Enterprise`, `OWE`, `Open` | +| **Frequency** | Frequency of the primary channel (e.g. `5.18 GHz`) | +| **Channel** | Primary channel (where the access point sends its beacons, e.g. `36`) | +| **Channel width** | Channel width (`20`, `40`, `80`, `160` or `320 MHz`), read from the beacon of the access point. If it can't be read, it is estimated from the band and the WiFi standard and shown as `~80 MHz` (the tooltip explains it) | +| **Signal strength** | Received signal strength (RSSI) in dBm | +| **Authentication** | Authentication type as reported by Windows (e.g. `RsnaPsk`) | +| **Encryption** | Encryption type as reported by Windows (e.g. `Ccmp`) | +| **BSSID** | MAC address of the access point (e.g. `AA:BB:CC:DD:EE:FF`) | +| **Vendor** | Vendor of the BSSID (OUI) | +| **PHY kind** | WiFi standard, e.g. `802.11ax` | +| **Network kind** | `Infrastructure` (access point) or `Adhoc` | +| **Beacon interval** | Interval of the beacons in milliseconds | +| **Uptime** | Time since the access point was started | + +### Changes since the last scan + +Each scan is compared with the previous scan of the same adapter (by BSSID): + +- **New**: the network is visible now, it was not visible in the last scan. +- **Gone**: the network was visible in the last scan, it is not visible now. The row is shown faded (as it was in the last scan) until the next scan; it can't be connected. +- **Changed**: the channel, the channel width or the security of the network changed (e.g. the access point switched the channel because of interference or radar). The tooltip shows the previous values. A change of the signal strength is not shown (it varies with every scan), and an estimated channel width is not compared. + +The **Since last scan** column and the counters right of the **Networks** header (e.g. `2 New · 1 Gone`) are only shown if the networks are compared with a previous scan. The counters count all networks, also the ones hidden by the band filter or the search. Changing the adapter starts over. The last scan is only kept in memory. The change is also in the search and the export (`Change`). Together with **Automatically update every**, this shows new access points or channel changes in the area; the changes of an automatic refresh can be shown as a notification, see [Show notification popup on changes](#show-notification-popup-on-changes). -:::note +### Context menu -Starting with Windows 11 24H2, you must allow access to the Wi-Fi adapter. +| Action | Description | +| -------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| **Connect...** | Opens a dialog to connect to the selected network, see [Connect](#connect) (only if not connected) | +| **Disconnect** | Disconnects the adapter from the selected network (only if connected) | +| **Copy...** | Copies a value of the selected network to the clipboard | +| **Export...** | Opens a dialog to export the selected or all networks to a file, see [Export](#export) | -Open `Windows Settings > Privacy & security > Location`, enable access for Desktop Apps / NETworkManager, then restart the application. +If multiple networks are selected, **Copy...** > **SSID** / **BSSID** (one value per line, in the order shown, without duplicates) and **Export...** are available. -::: +### Connect -![WiFi](../img/wifi.png) +**Connect...** opens a dialog with the fields required by the security of the network: -### Context menu +| Field | Description | +| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| **SSID** | Name of the network (only for a hidden network) | +| **Connect automatically** | Windows connects to the network automatically in the future | +| **Pre-shared key** | Password of a WPA / WPA2 / WPA3 Personal (or WEP) network | +| **Use credentials** | WPA / WPA2 / WPA3 Enterprise (EAP) network: connect with **Username**, **Domain** (optional) and **Password**. If disabled, Windows uses the logged-on user or a certificate | + +Open and OWE (Enhanced Open) networks need no password. If the network supports WPS (push button), **WPS** connects by pressing the WPS button of the access point (checked when the dialog is opened, `Checking WPS...`). + +The status of the connection (`Connecting to ...`, the result or the error) is shown below the networks for 15 seconds, and the networks are scanned again a few seconds later. -| Action | Description | -| -------------- | ---------------------------------------------------------------------------------- | -| **Connect...** | Opens a dialog to connect to the selected wireless network (only if not connected) | -| **Disconnect** | Disconnects from the selected wireless network (only if connected) | -| **Export...** | Opens a dialog to export the selected or all wireless networks to a file | -| **Copy** | Copies the selected information to the clipboard | +### Export + +**Export...** exports the networks as CSV, XML or JSON: **all** exports the networks shown (filtered by band and search) in the order shown, **selected** the selected networks in the order shown. Columns / elements: `Bssid`, `Ssid`, `ChannelCenterFrequencyInKilohertz`, `SignalBars`, `IsWiFiDirect`, `NetworkRssiInDecibelMilliwatts`, `PhyKind`, `NetworkKind`, `NetworkAuthenticationType`, `NetworkEncryptionType`, `BeaconInterval`, `Uptime`, `IsConnected`, `Security`, `Channel`, `ChannelWidth` (MHz), `ChannelWidthEstimated`, `Vendor` and `Change`. ### Keyboard shortcuts -| Key | Action | -| ---- | ----------------- | -| `F5` | Scan for networks | +| Key | Action | +| ---- | ----------------------------------------------------------------- | +| `F5` | Scan the networks (not while **Automatically update every** is enabled) | ## Channels -On the **Channels** tab, all wireless networks of the selected wireless adapter are displayed in a graphical view with channel, channel width, and signal strength. This helps identify overlapping wireless networks that do not originate from the same access point. +On the **Channels** tab, the networks of the selected adapter are drawn on the channels of their band, with their channel width and signal strength. This helps to find overlapping networks and a free channel. The tab is split into two sub-tabs: -- **2.4 & 5 GHz** — shows networks on the 2.4 GHz and 5 GHz bands in a single chart each. -- **6 GHz** — shows 6 GHz networks in two separate charts: lower channels (1–125) and upper channels (129–233). +- **2.4 & 5 GHz**: one chart for the 2.4 GHz and one for the 5 GHz band. The unused range between the channels 64 and 100 of the 5 GHz band is compressed. +- **6 GHz**: the lower (channels 1 - 125) and the upper channels (129 - 233) in two charts. A network whose channel crosses the split (e.g. 320 MHz around channel 127) is shown in both. + +Each network is drawn as a band over its whole channel width (20, 40, 80, 160 or 320 MHz), centered on the center of the channel (e.g. 80 MHz with the primary channel 36 covers the channels 36 - 48), so overlapping networks can be identified. If the channel width is estimated, the network is drawn around its primary channel. The legend below each chart lists the networks with their color (SSID and BSSID). The background shows the signal quality: excellent (-30 dBm and better), good (-67 to -30 dBm), reliable (-70 to -67 dBm), weak (-80 to -70 dBm) and poor (below -80 dBm). -Each network is drawn as a proportional band reflecting its channel width (20, 40, 80, or 160 MHz), so overlapping networks can be identified more accurately. +The charts show all networks of the last scan: the band filter, the search and the gone networks don't apply. ![WiFi - Channel](../img/wifi--channel.png) :::note -Move the mouse over a network band to display details such as SSID, channel, channel width, and signal strength in a tooltip. +Move the mouse over a network to display details such as SSID, BSSID, channel, channel width and signal strength in a tooltip. ::: + +## Settings + +### Show notification popup on changes + +Show a notification popup in the bottom-right corner of the primary screen when an automatic refresh (**Automatically update every**) found changes since the previous scan (see [Changes since the last scan](#changes-since-the-last-scan)). One notification per scan: up to three changes, one per line with the SSID and BSSID and the change in its color (e.g. `MyNetwork (AA:BB:CC:DD:EE:FF) · New`, green for new, red for gone, orange for changed), otherwise one line per counter (e.g. `5 New`, `2 Gone`). Not for a scan that was started manually, and only while **WiFi** is shown (the automatic refresh pauses while another tool is shown). The header shows the tool, the title the adapter; the status icon is green for only new networks, red for only gone networks, half green / half red for both, orange for only changed networks. A click opens **WiFi**. + +**Type:** `Boolean` + +**Default:** `Enabled` + +### Play sound on changes + +Play a system sound when an automatic refresh found changes. Independent of the [popup](#show-notification-popup-on-changes). + +**Type:** `Boolean` + +**Default:** `Disabled` + +### Display duration (seconds) + +Time in seconds the notification popup is shown before it closes automatically. + +**Type:** `Integer` [Min `3`, Max `60`] + +**Default:** `10` diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 51b3142570..55d37ec050 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -34,18 +34,23 @@ Release date: **xx.xx.2026** - Run command: the **Port Scanner** needs ports, which can also be names of port profiles, also several and together with ports (e.g. `portscan 10.0.0.1 webserver` or `portscan 10.0.0.1 "DNS (via TCP)";webserver;22`, suggested after the host and after a `;`). Own history size for the run command (default 20, [Settings > General](../settings/general.md#number-of-stored-entries-run-command)). `Tab` also completes profiles and port profiles, `PageUp`/`PageDown` move the selection by 5 suggestions. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) - Run command dialog redesigned: the icon of the recognized feature, the syntax with the part being typed highlighted, the values as they were understood (e.g. `Hosts: borntoberoot.net`, `Type: AAAA`), validation while typing, grouped suggestions with the typed text highlighted, examples and key hints (can be hidden in the settings). The dialog uses more space in a large window. The title bar shows a **Run command...** box in the center (like the command center of VS Code) instead of the icon. Type only a target (e.g. `10.0.0.1`, `server-01`, `00:11:22:33:44:55`, `10.0.0.0/24`) to get the commands that accept it, recent commands are also suggested while typing (e.g. a host); optionally, a target in the clipboard is suggested ([Settings > General](../settings/general.md#suggest-the-clipboard-content-as-target)). `Ctrl+Enter` runs and keeps the dialog open, `Shift+Enter` fills in the input without starting, `Shift+Del` or the remove button removes a recent command. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -**RDAP** +**Settings** -- New [**RDAP**](../application/rdap.md) tool to look up registration data via the Registration Data Access Protocol, the standardized, JSON-based successor of Whois. Supports domains, nameservers, top-level domains, IP addresses/CIDR prefixes, AS numbers and entity handles; the type is detected automatically or can be selected. The RDAP server is determined automatically using the IANA bootstrap files, which are cached locally and can be updated in the new **Settings > RDAP** page. Results are shown in a structured view (details, status, events, nameservers, DNSSEC, networks and AS numbers of an organization, contacts, notices) or as raw JSON, and can be exported as JSON or text. For domains (e.g. `.com`/`.net`), the referral to the registrar's RDAP server is followed as well (can be disabled in **Settings > RDAP**). Includes profile support. If no RDAP server is known for a domain, it can be opened in **Whois** with a single click. IP addresses and hostnames can be queried from the context menu of **IP Scanner** and **Traceroute**, AS numbers from **Traceroute**; for a hostname (e.g. `www.borntoberoot.net`), the registered domain is queried (determined with the included [Public Suffix List](https://publicsuffix.org/)). [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) [#3642](https://github.com/BornToBeRoot/NETworkManager/pull/3642) +- New global **DNS suffix** options in [Settings > Network](../settings/network.md): **Add DNS suffix (primary) to hostname** appends the Windows primary (or, if none is set, the active network adapter's connection-specific) DNS suffix to a bare hostname before resolving it, and **Use custom DNS suffix** lets you override it with a suffix of your own. Previously only available in DNS Lookup, this now also applies to every other tool that resolves hostnames through NETworkManager's shared DNS resolver (e.g. Ping, Traceroute, Port Scanner, IP Scanner, SNTP Lookup) — DNS Lookup stays independent. [#3591](https://github.com/BornToBeRoot/NETworkManager/pull/3591) +- **DNS server(s)** in [Settings > Network](../settings/network.md) is now a list of servers (IP address + port), configured via an **Edit DNS server** dialog, replacing the previous single semicolon-separated, port-53-only text field. [#3591](https://github.com/BornToBeRoot/NETworkManager/pull/3591) + +**WiFi** + +- Changes since the last scan: each scan is compared with the previous scan of the same adapter (by BSSID). The new column **Since last scan** shows networks that are **New**, **Gone** (shown faded until the next scan) or **Changed** (channel, channel width or security, the tooltip shows the previous values), the header shows the counters (e.g. `2 New · 1 Gone`). Also in the search and the export (`Change`). Useful with **Automatically update every** to see new access points or channel changes. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Notification for changes: when **Automatically update every** finds new, gone or changed networks, a notification popup (and optionally a sound) shows them, like the **IP Scanner**. Configurable in the new [WiFi settings](../application/wifi.md#settings) (**Show notification popup on changes**, **Play sound on changes**, **Display duration**). [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) **Traceroute** - New **Map** view below the hop list, visualizing each resolved hop's geolocation on an offline world map. Consecutive hops are connected with curved, directional arrows; hovering a marker shows its location, ISP/ASN, hostname, IP address and average round-trip time, while hovering an arrow shows the source and destination location of that segment. The map supports mouse-wheel zoom and drag-to-pan, and can be collapsed via a toggle button on the map itself, similar to the Profiles panel. The map is only shown if **Check IP geolocation** and the new **Show map** setting are both enabled, since hops need a resolved geolocation to be plotted. [#3520](https://github.com/BornToBeRoot/NETworkManager/pull/3520) -**Settings** +**RDAP** -- New global **DNS suffix** options in [Settings > Network](../settings/network.md): **Add DNS suffix (primary) to hostname** appends the Windows primary (or, if none is set, the active network adapter's connection-specific) DNS suffix to a bare hostname before resolving it, and **Use custom DNS suffix** lets you override it with a suffix of your own. Previously only available in DNS Lookup, this now also applies to every other tool that resolves hostnames through NETworkManager's shared DNS resolver (e.g. Ping, Traceroute, Port Scanner, IP Scanner, SNTP Lookup) — DNS Lookup stays independent. [#3591](https://github.com/BornToBeRoot/NETworkManager/pull/3591) -- **DNS server(s)** in [Settings > Network](../settings/network.md) is now a list of servers (IP address + port), configured via an **Edit DNS server** dialog, replacing the previous single semicolon-separated, port-53-only text field. [#3591](https://github.com/BornToBeRoot/NETworkManager/pull/3591) +- New [**RDAP**](../application/rdap.md) tool to look up registration data via the Registration Data Access Protocol, the standardized, JSON-based successor of Whois. Supports domains, nameservers, top-level domains, IP addresses/CIDR prefixes, AS numbers and entity handles; the type is detected automatically or can be selected. The RDAP server is determined automatically using the IANA bootstrap files, which are cached locally and can be updated in the new **Settings > RDAP** page. Results are shown in a structured view (details, status, events, nameservers, DNSSEC, networks and AS numbers of an organization, contacts, notices) or as raw JSON, and can be exported as JSON or text. For domains (e.g. `.com`/`.net`), the referral to the registrar's RDAP server is followed as well (can be disabled in **Settings > RDAP**). Includes profile support. If no RDAP server is known for a domain, it can be opened in **Whois** with a single click. IP addresses and hostnames can be queried from the context menu of **IP Scanner** and **Traceroute**, AS numbers from **Traceroute**; for a hostname (e.g. `www.borntoberoot.net`), the registered domain is queried (determined with the included [Public Suffix List](https://publicsuffix.org/)). [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) [#3642](https://github.com/BornToBeRoot/NETworkManager/pull/3642) ## Improvements @@ -54,13 +59,32 @@ Release date: **xx.xx.2026** - The collapsed/expanded state of profile groups (e.g. **linux-server**) is now remembered per profile file and shared across all tools, instead of resetting every time you switch tools or restart the application. [#3539](https://github.com/BornToBeRoot/NETworkManager/pull/3539) - The **Experimental features** setting in **Settings > Update** is removed: features in testing are marked with a **Beta** label at their own setting instead (e.g. **Read Windows host information** of the **IP Scanner**). [#3691](https://github.com/BornToBeRoot/NETworkManager/pull/3691) +**Profiles** + +- **Settings > Profiles**: `Enter` in the search box filters the profiles right away instead of after the delay while typing. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) + +**Dashboard** + +- Checking the **IP geolocation** and the **DNS resolver** is faster (the minimum of 2.5 seconds runs during the request, not before); the refresh icons spin until the check is finished. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) + **Network Interface** - Members of the **Network Configuration Operators** group can now change the network configuration (IP address, DNS servers, release/renew) without being an administrator. NETworkManager has to run elevated (**Restart as Administrator**, confirm with your own credentials). The hint is now also shown as tooltip on **Apply** in the profile context menu. [#3606](https://github.com/BornToBeRoot/NETworkManager/issues/3606) -**Whois** +**WiFi** -- Added an **Export...** button below the result, like in the other tools. [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) +- The search filters after a short delay while typing instead of on every key press, `Enter` filters right away. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) +- The time of the last scan of the networks (`Last scan at 14:32`, the date in the tooltip) is shown in their header, with **Automatically update every** a countdown to the next scan; the line below only shows errors and the connection status. Reloading the network adapters is faster (the minimum of 2.5 seconds runs while loading) and the reload icon spins until it is finished. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- A channel width that could not be read from the beacon of the access point and is estimated is shown as `~80 MHz` (grid, copy and the tooltip of the **Channels** tab), the tooltip of the cell explains it. Estimated widths on 2.4 GHz are 20 MHz (40 MHz is rarely used there). [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- After allowing the access to the WiFi adapter in the Windows settings (location), **Refresh** below the message (or switching back to WiFi) loads the adapters. A restart of the application is no longer needed. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- The BSSID is shown, copied and exported in the same format as the MAC addresses of the other tools (`AA:BB:CC:DD:EE:FF` instead of `aa:bb:cc:dd:ee:ff`). [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Reloading the adapters keeps the networks visible while they are scanned again (the refresh icon spins), instead of replacing them by the loading indicator. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- An unknown security or PHY kind is shown as `-/-` (like an unknown vendor) instead of the untranslated text `Unknown`. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- The export contains the values shown in the grid that were missing: `IsConnected`, `Security`, `Channel`, `ChannelWidth` (MHz), `ChannelWidthEstimated` and `Vendor` (appended as the last columns / elements). [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- **Export...** > all exports the networks shown in the grid (filtered by band and search) in the order shown, the selected networks are exported in the order shown too. The file is written in the background. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Scanning the networks (also **Automatically update every**) no longer freezes the window briefly: the connected network is read from the WiFi API instead of `netsh` via PowerShell, and the vendor lookups run in the background. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- The selected network stays selected (and in view) when the networks are scanned again, e.g. with **Automatically update every**. The list is replaced at once instead of network by network. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- If several networks are selected, **Copy...** > **SSID** / **BSSID** copies the values of all selected networks (one per line, in the order shown, without duplicates). [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) **IP Scanner** @@ -190,9 +214,9 @@ Release date: **xx.xx.2026** - `Enter` in the search box filters the rules right away instead of after the delay while typing. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - The time of the last refresh (`Reloaded at 14:32`, the date in the tooltip) is shown in the header instead of a status line below the list; the line below the list only shows errors (e.g. rules loaded with errors, a failed action). A manual refresh is faster (the minimum of 2.5 seconds runs while loading, not before) and the refresh icon spins until the rules are loaded (also with **Show all rules**). [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) -**Profiles** +**Whois** -- **Settings > Profiles**: `Enter` in the search box filters the profiles right away instead of after the delay while typing. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) +- Added an **Export...** button below the result, like in the other tools. [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) **Connections** @@ -209,15 +233,6 @@ Release date: **xx.xx.2026** - The search filters after a short delay while typing instead of on every key press (smoother with many entries), `Enter` filters right away. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - The time of the last refresh (`Reloaded at 14:32`, the date in the tooltip) is shown in the header instead of a status line below the list; with **Automatically update every**, a countdown to the next refresh (`Next refresh in 00:04`). The line below the list only shows errors. A manual refresh is faster (the minimum of 2.5 seconds runs while loading, not before) and the refresh icon spins until it is finished. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) -**WiFi** - -- The search filters after a short delay while typing instead of on every key press, `Enter` filters right away. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -- The time of the last scan of the networks (`Last scan at 14:32`, the date in the tooltip) is shown in their header, with **Automatically update every** a countdown to the next scan; the line below only shows errors and the connection status. Reloading the network adapters is faster (the minimum of 2.5 seconds runs while loading) and the reload icon spins until it is finished. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) - -**Dashboard** - -- Checking the **IP geolocation** and the **DNS resolver** is faster (the minimum of 2.5 seconds runs during the request, not before); the refresh icons spin until the check is finished. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) - ## Bug Fixes - Fixed changes to lists in the settings (e.g. query histories, port profiles, custom commands) not being saved if no other setting was changed in the same session. This happened since the settings are stored as JSON. [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) @@ -227,57 +242,39 @@ Release date: **xx.xx.2026** - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in **About** and the DNS server profiles in **Settings > Network**. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) - Fixed the screenshot that is shown in place of embedded windows (**Remote Desktop**, **PowerShell**, **PuTTY**, **TigerVNC**, **Web Console**) while a dialog is open being cropped / stretched with a display scaling above 100% or on a monitor with a different scaling, and being stretched / scaled if the window is resized while the dialog is open (it keeps its size now). The `AirspacePanel` of [AirspaceFixer](https://github.com/chris84948/AirspaceFixer) is now part of NETworkManager, based on the fork [AirspaceFixerDotNet](https://github.com/ellipticbit/AirspaceFixerDotNet) with per monitor DPI support, which also fixes a GDI handle leak. [#3681](https://github.com/BornToBeRoot/NETworkManager/pull/3681) -**Firewall** - -- Fixed the name of the feature not being translatable in the list of features, the settings and the run command (missing translation key). [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) -- Fixed `F5` not refreshing the rule list, although it is documented as shortcut. [#3637](https://github.com/BornToBeRoot/NETworkManager/pull/3637) -- Fixed an empty rule list with "Reloaded at ..." being shown if the rules could not be loaded (e.g. the Windows Firewall service is not running). An error is shown now, and a message if the rules could only be loaded partially. [#3637](https://github.com/BornToBeRoot/NETworkManager/pull/3637) -- Fixed the Firewall not working until the application was restarted if loading the PowerShell module `NetSecurity` failed once. [#3637](https://github.com/BornToBeRoot/NETworkManager/pull/3637) -- Fixed keywords like `LocalSubnet` or `DNS` being accepted for **Local addresses** in the add / edit / copy rule dialog, although Windows only accepts `Any` there (saving the rule failed). The same applies to `Any4` / `Any6` for local and remote addresses. [#3637](https://github.com/BornToBeRoot/NETworkManager/pull/3637) -- Fixed a horizontal scrollbar appearing in the add / edit / copy rule dialog when the name or description is very long. [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) -- Fixed port keywords (e.g. `RPC`) and combinations of interface types being shown as **Any**. Editing a rule that was changed outside of NETworkManager to use such values no longer silently removes them (the rule can't be edited in this case). [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) -- Fixed the program of a rule not being shown in the row details and the edit dialog. Saving the edit dialog then removed the program from the rule, so the rule applied to all programs. [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) -- Fixed editing a rule deleting and re-creating it, which removed properties that are not supported by NETworkManager (e.g. ICMP types or a service set in the Windows Firewall management console). Only the changed properties are updated now (ICMP types are reset if the protocol is changed). [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) -- Fixed program paths with environment variables (e.g. `%SystemRoot%\System32\svchost.exe`) being rejected as non-existent in the add / edit / copy rule dialog. [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) -- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) - -**Ping Monitor** - -- Fixed long error messages (e.g. from a failed host resolution) in the tooltip of the error icon not being wrapped. [#3626](https://github.com/BornToBeRoot/NETworkManager/pull/3626) -- Fixed the ping not working when the ICMP **Buffer** was set to more than `65500` bytes (Windows limit). The maximum is now `65500`, higher values are lowered to `65500`. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) -- Fixed hosts being added twice if the inputs overlap (e.g. `10.0.0.1; 10.0.0.0/24`). If an IP address is also entered as hostname, the hostname is kept; different hostnames of the same IP address (e.g. two names of one server) are all kept. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) -- Fixed **Copy** > **Hostname** copying a hostname resolved via DNS (`PTR`) with a trailing dot (e.g. `server.example.com.`). [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - -**Traceroute** +**History** -- Fixed the trace not working when the ICMP **Buffer** was set to more than `65500` bytes (Windows limit). The maximum is now `65500`, higher values are lowered to `65500`. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) -- Fixed hostnames of the hops resolved via DNS (`PTR`) being shown with a trailing dot (e.g. `server.example.com.`), also in the export and when opened in another feature (e.g. **RDAP**). A single-label name (e.g. `gateway.`) keeps the dot, so the DNS suffix isn't appended, except for **Remote Desktop**, **PuTTY**, **TigerVNC** and **PowerShell**, which resolve it via Windows. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper), e.g. to read a long hostname. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +- Fixed adding an entry to the history of an input (e.g. hosts, ports, domains) failing when the number of stored entries is set to `0` in [Settings > General](../settings/general.md#number-of-stored-entries). With `0`, no entries are stored. Removing an entry from the history (also the oldest one, shared by several tabs) no longer clears the input that shows it. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -**Network Interface** +**Input validation** -- Fixed errors when changing the network configuration (e.g. missing permissions) not being shown — the change was reported as successful although it failed. The error message of Windows is now shown. [#3606](https://github.com/BornToBeRoot/NETworkManager/issues/3606) +- Fixed host names being accepted with a hyphen at the start or end of a label other than the first (e.g. `server.-bad-.com`) and with only digits (e.g. `10.0.0.` or `192.168.1`, which are an incomplete IPv4 address). The same applies to the domain in **Whois**. IPv4 addresses are still accepted in all host fields, now checked explicitly in the **Remote Desktop** host field. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) +- Fixed MAC addresses and their first 3 bytes (**Wake on LAN**, **Lookup** > **OUI**, profiles) being accepted with any character instead of a dot in the format `0000.0000.0000` (e.g. `0011 2233 4455`). [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) +- Fixed IPv6 subnets in the **Subnet Calculator** being accepted with a leading `s` (e.g. `sss2001:db8::/32`) and rejected with an embedded IPv4 address (e.g. `::ffff:192.168.0.1/96`). [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) +- Fixed the port of the **Remote Desktop** host field (`host:port`) being accepted empty or as `0`. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) +- Fixed the application freezing when validating an invalid domain with many labels in **Whois** (exponential backtracking of the regular expression). [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) +- Fixed IPv6 subnets with whitespace or a zone index (e.g. `fe80::1%eth0/64`) being accepted in the **Subnet Calculator**, which can't calculate them. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) +- Fixed an empty entry in **Lookup** > **OUI** / **Port** (e.g. `22;;80`) finding every vendor or service. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) +- Fixed **Lookup** > **Port** searching for a port with an upper-case protocol (e.g. `22/TCP`) as a service instead of the port and protocol. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -**Connections** +**Profiles** -- Fixed the auto refresh continuing in the background after switching to another tool, or after it was disabled, if this happened while a refresh was running. [#3639](https://github.com/BornToBeRoot/NETworkManager/pull/3639) -- Fixed **Automatically update every** `1` / `5` minutes refreshing only every hour / every 5 hours. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) -- Fixed the hostname of the remote address (DNS `PTR`) being shown with a trailing dot (e.g. `server.example.com.`), also in the export. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +- Fixed `Enter` in the search box of the import result importing the profiles (default button). It filters the found profiles right away now, instead of after the delay while typing. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) +- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the groups (Settings > Profiles) and the import result. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +- Fixed the names of the features in the group dialog shown without spaces (e.g. `RemoteDesktop` instead of **Remote Desktop**). [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) +- Fixed the profiles of a group renamed only by case (e.g. `servers` → `Servers`) keeping the old group name. Opening them in a feature with group settings (e.g. **Remote Desktop**, **PuTTY**) failed, and editing one could create a second group with the old name. Profile files with such profiles are repaired when they are loaded. [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) -**Listeners** +**Dashboard** -- Fixed the auto refresh continuing in the background after switching to another tool, or after it was disabled, if this happened while a refresh was running. [#3639](https://github.com/BornToBeRoot/NETworkManager/pull/3639) -- Fixed **Automatically update every** `1` / `5` minutes refreshing only every hour / every 5 hours. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) -- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +- Fixed the **Network Connection** widget running a full connection check on every application startup, even if the Status Window or Dashboard was never opened. It now only checks when actually shown - via the tray icon, on a network change, or when the Dashboard tab is opened. [#3553](https://github.com/BornToBeRoot/NETworkManager/pull/3553) +- Fixed the DNS status (Computer/Router/Internet) in the **Network Connection** widget showing as an error when no PTR record exists for the address, which is common and expected for private IP ranges. This is now shown as informational instead of critical. [#3553](https://github.com/BornToBeRoot/NETworkManager/pull/3553) +- Fixed a race condition in the **Network Connection** widget where results from a superseded check could overwrite the results of a newer, still-running check after quickly reopening the widget. [#3553](https://github.com/BornToBeRoot/NETworkManager/pull/3553) +- Fixed the Status Window closing by itself after being opened from the tray icon (or with the hotkey), if it was opened automatically on a network change shortly before. [#3639](https://github.com/BornToBeRoot/NETworkManager/pull/3639) +- Fixed the DNS hostname (`PTR`) in the **Network Connection** widget being shown with a trailing dot (e.g. `router.example.com.`). [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -**Neighbor Table** +**Network Interface** -- Fixed the **State** of the entries being shifted by one (e.g. `Reachable` entries were shown as `Stale`, `Permanent` entries as `Reachable`, `Unreachable` entries as `0`) since the table is read with the Windows API (2026.7.7). [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) -- Fixed adding and deleting entries not working until the application was restarted if loading the PowerShell module `NetTCPIP` failed once. [cc05937](https://github.com/BornToBeRoot/NETworkManager/commit/cc05937a7de2bf1247621845f47077f3796b9bb2) -- Fixed the auto refresh continuing in the background after switching to another tool, or after it was disabled, if this happened while a refresh was running. [#3639](https://github.com/BornToBeRoot/NETworkManager/pull/3639) -- Fixed **Automatically update every** `1` / `5` minutes refreshing only every hour / every 5 hours. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) -- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +- Fixed errors when changing the network configuration (e.g. missing permissions) not being shown — the change was reported as successful although it failed. The error message of Windows is now shown. [#3606](https://github.com/BornToBeRoot/NETworkManager/issues/3606) **WiFi** @@ -285,22 +282,30 @@ Release date: **xx.xx.2026** - Fixed **Automatically update every** `1` / `5` minutes refreshing only every hour / every 5 hours. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) - Fixed the auto refresh not being resumed after switching back from another tool. [#3639](https://github.com/BornToBeRoot/NETworkManager/pull/3639) - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) - -**Dashboard** - -- Fixed the **Network Connection** widget running a full connection check on every application startup, even if the Status Window or Dashboard was never opened. It now only checks when actually shown - via the tray icon, on a network change, or when the Dashboard tab is opened. [#3553](https://github.com/BornToBeRoot/NETworkManager/pull/3553) -- Fixed the DNS status (Computer/Router/Internet) in the **Network Connection** widget showing as an error when no PTR record exists for the address, which is common and expected for private IP ranges. This is now shown as informational instead of critical. [#3553](https://github.com/BornToBeRoot/NETworkManager/pull/3553) -- Fixed a race condition in the **Network Connection** widget where results from a superseded check could overwrite the results of a newer, still-running check after quickly reopening the widget. [#3553](https://github.com/BornToBeRoot/NETworkManager/pull/3553) -- Fixed the Status Window closing by itself after being opened from the tray icon (or with the hotkey), if it was opened automatically on a network change shortly before. [#3639](https://github.com/BornToBeRoot/NETworkManager/pull/3639) -- Fixed the DNS hostname (`PTR`) in the **Network Connection** widget being shown with a trailing dot (e.g. `router.example.com.`). [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - -**DNS Lookup** - -- Fixed **Inherit host from general** of a profile being saved with the value of the **Traceroute**, so the host of the DNS lookup could be replaced with the host of the profile. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -- Fixed a DNS server opened with the run command in another case than configured (e.g. `cloudflare` for `Cloudflare`) being looked up as hostname instead of using the configured DNS server. Names of DNS servers are case-insensitive now. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -- Fixed **Add DNS suffix (primary) to hostname** silently appending no suffix at all on machines without a Windows primary DNS suffix configured (e.g. not domain-joined), even though a usable suffix was available via the active network adapter's connection-specific DNS suffix (shown under **DNS Suffix Search List** in `ipconfig /all`). It now falls back to that adapter's suffix in this case. [#3591](https://github.com/BornToBeRoot/NETworkManager/pull/3591) -- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the DNS server profiles in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) -- Fixed a technical error (*An invalid IP address was specified*) being shown for a hostname looked up with `PTR`. A message is shown and the hostname is skipped, the other hosts are looked up. [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) +- Fixed the application crashing when **Automatically update every** was enabled and no WiFi adapter was found (e.g. disabled or unplugged). `F5` no longer tries to scan without an adapter. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the **Refresh** button below "No WiFi adapters found" being disabled while **Automatically update every** was enabled. The adapters could only be loaded again after a restart. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the application crashing if connecting to or disconnecting from a network failed with an error (e.g. the adapter was disabled meanwhile). The error is shown in the status below the networks, and scanning is no longer blocked afterwards. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed **Connect...** and **Disconnect** being available while a connection is made, and **Connect...** failing if the networks were scanned again while the context menu was open. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed **Use credentials** being ignored when connecting to a WPA / WPA2 / WPA3 Enterprise network (EAP). If it is disabled, no username and password are sent and Windows uses the logged-on user or a certificate. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the **WPS** button of the connect dialog never being shown. Whether a network supports WPS (push button) is checked again when the dialog is opened. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the connect dialog not focusing the first input: the SSID of a hidden network or the username (EAP) was not focused. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the connect dialog asking for a pre-shared key for WPA3 Enterprise networks (instead of username and password) and for OWE (Enhanced Open) networks, which need no password. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed networks with a channel width of 40, 80 or 160 MHz being drawn at the wrong position on the **Channels** tab: they were centered on their primary channel (e.g. 80 MHz on channel 36 over the channels 28 - 44 instead of 36 - 48), so overlapping networks were shown wrong. The center of the whole channel is read from the beacon now. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed WiFi 7 (802.11be) networks with a channel width of 320 MHz being shown with 160 MHz. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the 5 GHz chart of the **Channels** tab labeling the channels above 144 as 148, 152 ... 164 instead of 149, 153 ... 165. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed networks on the 5 GHz channels 169 - 177 (UNII-4) and 32 being shown with channel `-1`, without band (always shown, not affected by the band filter) and missing on the **Channels** tab. 6 GHz channel 2 (5935 MHz) is shown as channel `2` instead of `-1`. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed sorting by the signal icon (first column) and by **Encryption** not changing the order of the networks. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the networks of the previously selected adapter possibly being shown after selecting another adapter while a scan was running. The adapter can't be changed while scanning or connecting. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed all networks and charts being removed if a refresh (manual, **Automatically update every** or after connecting) failed. The networks of the last scan stay, the error is shown below them. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the message after disconnecting from a hidden network missing the name (" disconnected!"), and the search not finding hidden networks by the shown text `Hidden Network`. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the icon of the adapter selection (connected / disconnected) keeping the state of when the adapters were loaded. It is updated after each scan, e.g. after connecting or disconnecting. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed `F5` scanning and **Automatically update every** refreshing the networks behind an open dialog (e.g. **Connect...** or **Export...**). The auto refresh waits until the dialog is closed. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the CSV export breaking the row of a network whose SSID contains a comma or a quote. SSID, security and vendor are quoted. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed a network being marked as **Connected** that the selected adapter isn't connected to, if the computer has several WiFi adapters and the selected one was disconnected. An error while reading the connected network no longer ends the scan. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the connection status message (e.g. "Connecting to ...") being hidden too early, while still connecting, if a previous message (e.g. after connecting or disconnecting) was shown shortly before. Each message is now shown for 15 seconds. [#3638](https://github.com/BornToBeRoot/NETworkManager/pull/3638) +- Fixed the adapter list and the auto refresh keeping a removed adapter (e.g. an unplugged USB adapter) after **Refresh** found no adapter or failed: "No WiFi adapters found" is shown now. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed WEP networks with open authentication being treated as unsecured: the connect dialog asked for no key (the connection failed) and the signal icon showed no lock. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed **Disconnect** (and **Connect...**) while the networks were scanned or the adapters were reloaded starting a second scan at the same time (the scan could fail with "busy"). Both wait until the scan / reload is finished. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) **IP Scanner** @@ -358,40 +363,30 @@ Release date: **xx.xx.2026** - Fixed the ports of different hosts with the same hostname (DNS `PTR`, e.g. a generic name of a provider or a server with two IP addresses) being shown in one group. The results are grouped per IP address, the group header shows the hostname and the IP address. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - Fixed **Edit** (`F2`, double-click) and **Delete** (`Del`) of a port profile in the settings being available without a selected profile (edit created a new profile). The delete confirmation shows the name of the profile. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -**IP Geolocation** - -- Fixed the query history of **IP Geolocation** being written to the history of **Whois** instead of its own. [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) - -**WiFi** - -- Fixed the connection status message (e.g. "Connecting to ...") being hidden too early, while still connecting, if a previous message (e.g. after connecting or disconnecting) was shown shortly before. Each message is now shown for 15 seconds. [#3638](https://github.com/BornToBeRoot/NETworkManager/pull/3638) - -**History** +**Ping Monitor** -- Fixed adding an entry to the history of an input (e.g. hosts, ports, domains) failing when the number of stored entries is set to `0` in [Settings > General](../settings/general.md#number-of-stored-entries). With `0`, no entries are stored. Removing an entry from the history (also the oldest one, shared by several tabs) no longer clears the input that shows it. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) +- Fixed long error messages (e.g. from a failed host resolution) in the tooltip of the error icon not being wrapped. [#3626](https://github.com/BornToBeRoot/NETworkManager/pull/3626) +- Fixed the ping not working when the ICMP **Buffer** was set to more than `65500` bytes (Windows limit). The maximum is now `65500`, higher values are lowered to `65500`. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) +- Fixed hosts being added twice if the inputs overlap (e.g. `10.0.0.1; 10.0.0.0/24`). If an IP address is also entered as hostname, the hostname is kept; different hostnames of the same IP address (e.g. two names of one server) are all kept. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) +- Fixed **Copy** > **Hostname** copying a hostname resolved via DNS (`PTR`) with a trailing dot (e.g. `server.example.com.`). [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -**Input validation** +**Traceroute** -- Fixed host names being accepted with a hyphen at the start or end of a label other than the first (e.g. `server.-bad-.com`) and with only digits (e.g. `10.0.0.` or `192.168.1`, which are an incomplete IPv4 address). The same applies to the domain in **Whois**. IPv4 addresses are still accepted in all host fields, now checked explicitly in the **Remote Desktop** host field. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -- Fixed MAC addresses and their first 3 bytes (**Wake on LAN**, **Lookup** > **OUI**, profiles) being accepted with any character instead of a dot in the format `0000.0000.0000` (e.g. `0011 2233 4455`). [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -- Fixed IPv6 subnets in the **Subnet Calculator** being accepted with a leading `s` (e.g. `sss2001:db8::/32`) and rejected with an embedded IPv4 address (e.g. `::ffff:192.168.0.1/96`). [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -- Fixed the port of the **Remote Desktop** host field (`host:port`) being accepted empty or as `0`. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -- Fixed the application freezing when validating an invalid domain with many labels in **Whois** (exponential backtracking of the regular expression). [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -- Fixed IPv6 subnets with whitespace or a zone index (e.g. `fe80::1%eth0/64`) being accepted in the **Subnet Calculator**, which can't calculate them. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -- Fixed an empty entry in **Lookup** > **OUI** / **Port** (e.g. `22;;80`) finding every vendor or service. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -- Fixed **Lookup** > **Port** searching for a port with an upper-case protocol (e.g. `22/TCP`) as a service instead of the port and protocol. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) +- Fixed the trace not working when the ICMP **Buffer** was set to more than `65500` bytes (Windows limit). The maximum is now `65500`, higher values are lowered to `65500`. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) +- Fixed hostnames of the hops resolved via DNS (`PTR`) being shown with a trailing dot (e.g. `server.example.com.`), also in the export and when opened in another feature (e.g. **RDAP**). A single-label name (e.g. `gateway.`) keeps the dot, so the DNS suffix isn't appended, except for **Remote Desktop**, **PuTTY**, **TigerVNC** and **PowerShell**, which resolve it via Windows. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) +- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper), e.g. to read a long hostname. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) -**Subnet Calculator** +**DNS Lookup** -- Fixed **Subnetting** getting stuck when the new subnet mask is smaller than the subnet mask of the subnet (e.g. `10.0.0.0/24` with `/16`) or too large for the address family (e.g. `/40` for IPv4). An error is shown instead. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) -- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the subnetting result. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +- Fixed **Inherit host from general** of a profile being saved with the value of the **Traceroute**, so the host of the DNS lookup could be replaced with the host of the profile. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) +- Fixed a DNS server opened with the run command in another case than configured (e.g. `cloudflare` for `Cloudflare`) being looked up as hostname instead of using the configured DNS server. Names of DNS servers are case-insensitive now. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) +- Fixed **Add DNS suffix (primary) to hostname** silently appending no suffix at all on machines without a Windows primary DNS suffix configured (e.g. not domain-joined), even though a usable suffix was available via the active network adapter's connection-specific DNS suffix (shown under **DNS Suffix Search List** in `ipconfig /all`). It now falls back to that adapter's suffix in this case. [#3591](https://github.com/BornToBeRoot/NETworkManager/pull/3591) +- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the DNS server profiles in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +- Fixed a technical error (*An invalid IP address was specified*) being shown for a hostname looked up with `PTR`. A message is shown and the hostname is skipped, the other hosts are looked up. [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) -**Profiles** +**Web Console** -- Fixed `Enter` in the search box of the import result importing the profiles (default button). It filters the found profiles right away now, instead of after the delay while typing. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the groups (Settings > Profiles) and the import result. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) -- Fixed the names of the features in the group dialog shown without spaces (e.g. `RemoteDesktop` instead of **Remote Desktop**). [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) -- Fixed the profiles of a group renamed only by case (e.g. `servers` → `Servers`) keeping the old group name. Opening them in a feature with group settings (e.g. **Remote Desktop**, **PuTTY**) failed, and editing one could create a second group with the old name. Profile files with such profiles are repaired when they are loaded. [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) +- Fixed no message being shown after **Delete browsing data** in the settings (whether the browsing data was deleted or an error occurred), and an error (e.g. the WebView2 runtime is not installed) not being handled. **SNMP** @@ -402,21 +397,61 @@ Release date: **xx.xx.2026** - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the SNTP server profiles in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +**Hosts File Editor** + +- Fixed the retry of a locked hosts file waiting 5 seconds between the attempts (the message said 2) and once more after the last attempt. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) + +**Firewall** + +- Fixed the name of the feature not being translatable in the list of features, the settings and the run command (missing translation key). [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) +- Fixed `F5` not refreshing the rule list, although it is documented as shortcut. [#3637](https://github.com/BornToBeRoot/NETworkManager/pull/3637) +- Fixed an empty rule list with "Reloaded at ..." being shown if the rules could not be loaded (e.g. the Windows Firewall service is not running). An error is shown now, and a message if the rules could only be loaded partially. [#3637](https://github.com/BornToBeRoot/NETworkManager/pull/3637) +- Fixed the Firewall not working until the application was restarted if loading the PowerShell module `NetSecurity` failed once. [#3637](https://github.com/BornToBeRoot/NETworkManager/pull/3637) +- Fixed keywords like `LocalSubnet` or `DNS` being accepted for **Local addresses** in the add / edit / copy rule dialog, although Windows only accepts `Any` there (saving the rule failed). The same applies to `Any4` / `Any6` for local and remote addresses. [#3637](https://github.com/BornToBeRoot/NETworkManager/pull/3637) +- Fixed a horizontal scrollbar appearing in the add / edit / copy rule dialog when the name or description is very long. [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) +- Fixed port keywords (e.g. `RPC`) and combinations of interface types being shown as **Any**. Editing a rule that was changed outside of NETworkManager to use such values no longer silently removes them (the rule can't be edited in this case). [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) +- Fixed the program of a rule not being shown in the row details and the edit dialog. Saving the edit dialog then removed the program from the rule, so the rule applied to all programs. [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) +- Fixed editing a rule deleting and re-creating it, which removed properties that are not supported by NETworkManager (e.g. ICMP types or a service set in the Windows Firewall management console). Only the changed properties are updated now (ICMP types are reset if the protocol is changed). [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) +- Fixed program paths with environment variables (e.g. `%SystemRoot%\System32\svchost.exe`) being rejected as non-existent in the add / edit / copy rule dialog. [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) +- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) + **RDAP** - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the bootstrap files in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +**IP Geolocation** + +- Fixed the query history of **IP Geolocation** being written to the history of **Whois** instead of its own. [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) + +**Subnet Calculator** + +- Fixed **Subnetting** getting stuck when the new subnet mask is smaller than the subnet mask of the subnet (e.g. `10.0.0.0/24` with `/16`) or too large for the address family (e.g. `/40` for IPv4). An error is shown instead. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) +- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the subnetting result. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) + **Lookup** - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the OUI and port lookup. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) -**Web Console** +**Connections** -- Fixed no message being shown after **Delete browsing data** in the settings (whether the browsing data was deleted or an error occurred), and an error (e.g. the WebView2 runtime is not installed) not being handled. +- Fixed the auto refresh continuing in the background after switching to another tool, or after it was disabled, if this happened while a refresh was running. [#3639](https://github.com/BornToBeRoot/NETworkManager/pull/3639) +- Fixed **Automatically update every** `1` / `5` minutes refreshing only every hour / every 5 hours. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- Fixed the hostname of the remote address (DNS `PTR`) being shown with a trailing dot (e.g. `server.example.com.`), also in the export. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) +- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) -**Hosts File Editor** +**Listeners** -- Fixed the retry of a locked hosts file waiting 5 seconds between the attempts (the message said 2) and once more after the last attempt. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- Fixed the auto refresh continuing in the background after switching to another tool, or after it was disabled, if this happened while a refresh was running. [#3639](https://github.com/BornToBeRoot/NETworkManager/pull/3639) +- Fixed **Automatically update every** `1` / `5` minutes refreshing only every hour / every 5 hours. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) + +**Neighbor Table** + +- Fixed the **State** of the entries being shifted by one (e.g. `Reachable` entries were shown as `Stale`, `Permanent` entries as `Reachable`, `Unreachable` entries as `0`) since the table is read with the Windows API (2026.7.7). [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- Fixed adding and deleting entries not working until the application was restarted if loading the PowerShell module `NetTCPIP` failed once. [cc05937](https://github.com/BornToBeRoot/NETworkManager/commit/cc05937a7de2bf1247621845f47077f3796b9bb2) +- Fixed the auto refresh continuing in the background after switching to another tool, or after it was disabled, if this happened while a refresh was running. [#3639](https://github.com/BornToBeRoot/NETworkManager/pull/3639) +- Fixed **Automatically update every** `1` / `5` minutes refreshing only every hour / every 5 hours. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) ## Dependencies, Refactoring & Documentation