diff --git a/AGENTS.md b/AGENTS.md index 9defa01725..260bd7218f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -620,6 +620,64 @@ WebView2) can't be animated, clipped or put in transparent windows. suggestions); not for results that are appended while a scan runs (those are buffered and flushed by a timer, see `IPScannerViewModel`). +### Dashboard widgets + +The dashboard (`Views/DashboardView.xaml(.cs)`) hosts the widgets: network connection, latency, speed test, +IP geolocation, DNS resolver. Each widget is `WidgetView` + `WidgetViewModel` in a `CardBorder`. + +**Look**: header with a 32 px Lucide icon + title (`MessageTextBlock`) and icon buttons on the right (Copy all, Refresh +for widgets that check once); content margin 10; rows 26 high with a gap of 5 (label normal, value bold, technical +values in `Fonts.Family.Mono`, states with `StatusDot`); values open in other tools via a context menu +(`NavigationManager.Open`) + Copy. + +**Show / enable**: +- `Dashboard_ShowWidget` shows / hides a widget (default shown). The view is created when it is shown the + first time (`ShowWidget`); a hidden widget doesn't check or send anything. +- Privacy defaults: a single connectivity ping per check is on by default (network connection: `Dashboard_PingPublicIPAddress`, + can be disabled). Anything that sends the IP address to a web service (ipify, ip-api.com) or runs continuously + (latency pings) is opt-in: `Dashboard_Check` off by default; while it is off the widget shows what it would + do and an **Enable** button that sets the setting (the network connection shows the pinged address instead). + A changed default only applies to new installations (saved settings keep their value). +- Settings > Dashboard has one section per widget in the order of the dashboard; the check switch is disabled while + the widget is hidden (the value is kept). + +**When widgets check**: +- *One-shot widgets* (network connection, IP geolocation, DNS resolver) never check in their constructor. The + dashboard calls `Check()` (`CheckWidgets`): at the start, after a network change, when a setting in `CheckSettings` + changed (marked outdated, checked in `OnViewVisible`), and when the dashboard / window is shown again and the last + check is at least `Dashboard_RecheckInterval` (60 s) old. "Shown again" = another tool / the settings were shown, or + the window is restored from minimized / the tray - not maximize / restore down. A check requested while one runs + is queued (`_recheckPending`) and dropped if the widget was hidden meanwhile. +- *Live widgets* (latency) only run while the widget is shown and enabled, the dashboard is the selected view + and the main window is shown (`OnViewHide`, `OnMainWindowHidden` from `MainWindow` on minimize / tray). They keep + the values of their time window (60 s, `Dashboard_LatencyWindow`) across pauses (a gap in the chart, not + counted as lost) and start empty after a network change or when their check is disabled. +- The speed test only runs when started; hiding it cancels a running test. + +**Sizes / layout**: +- The widgets are rows of a `StackPanel` with a gap of 10 between the visible rows (not below the last one). A row + that can hold two widgets is a `Grid` with the columns `* 10 * 10 *` and two rows: `ArrangeRow(row, first, second, + sideBySide)` puts them side by side (first 2/3, second 1/3) or one below the other with the full width (gap 10); a + hidden widget leaves no space, the other one spans the row. +- Side by side only if both fit: `IsSideBySide` checks first ≥ 2/3 (`FirstWidgetMinWidth` 600: speed test, IP + geolocation) and second ≥ 1/3 (`SecondWidgetMinWidth` 280: latency, DNS resolver) of the row. Both rows use the + same widths and switch together (~905 px), so the speed test and the IP geolocation always have the same width. + These are not `MinWidth`s of the widgets: in their own row they get the window width. +- The layout is arranged again only when the rows change between side by side and stacked (`SizeChanged` of the + widgets panel compares `IsSideBySide`), and after setting changes (`ApplyWidgetSettings` in `OnViewVisible`). +- A widget whose content depends on its place is told by the dashboard (e.g. `LatencyWidgetView + .SetNextToOtherWidget`: targets one below the other next to the speed test), not only by its own width (1/3 of a + maximized window is wide); its own width only decides in its own row (`IsCompact` below 500 px). +- Position settings per widget (e.g. `Dashboard_LatencyPosition`: next to the speed test / own row) instead + of a free layout. Next to another widget = right (1/3), like the DNS resolver next to the IP geolocation. + +**New widget**: settings (`Show`, opt-in `Check` if it contacts a third party, defaults in +`GlobalStaticConfiguration`) → view model + view (look above, `ScreenshotData` sample values) → `DashboardView` (content +control in a row, `ShowWidget`, min width + `ArrangeRow` if it shares a row, check or start / stop like the existing +widgets) → settings section → `Website/docs/application/dashboard.md` (widget section + `### +{#settings-}` with explicit ids, the widget names repeat) → changelog → manual test. Plans for further widgets: +`.claude/plans/dashboard-more-widgets.md`. + ### Embedded Tools Integration - **Remote Desktop**: Native RDP using `AxMSTSCLib`, `AxMsRdpClient10NotSafeForScripting` and `WindowsFormsHost` diff --git a/Source/NETworkManager.Converters/LatencyPositionToStringConverter.cs b/Source/NETworkManager.Converters/LatencyPositionToStringConverter.cs new file mode 100644 index 0000000000..d12acd89d0 --- /dev/null +++ b/Source/NETworkManager.Converters/LatencyPositionToStringConverter.cs @@ -0,0 +1,36 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using NETworkManager.Localization; +using NETworkManager.Models.Network; + +namespace NETworkManager.Converters; + +/// +/// Convert to translated . +/// +public sealed class LatencyPositionToStringConverter : IValueConverter +{ + /// + /// Convert to translated . + /// + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return value is not LatencyPosition position + ? "-/-" + : ResourceTranslator.Translate(ResourceIdentifier.LatencyPosition, position); + } + + /// + /// !!! Method not implemented !!! + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } +} diff --git a/Source/NETworkManager.Converters/LatencyTimeToStringConverter.cs b/Source/NETworkManager.Converters/LatencyTimeToStringConverter.cs new file mode 100644 index 0000000000..8429a7b459 --- /dev/null +++ b/Source/NETworkManager.Converters/LatencyTimeToStringConverter.cs @@ -0,0 +1,40 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using NETworkManager.Models.Network; + +namespace NETworkManager.Converters; + +/// +/// Convert a round-trip time in milliseconds ( or , e.g. the statistics of +/// the latency widget) to a string: <1 ms if it rounds to 0, -/- without a value. See +/// . +/// +public sealed class LatencyTimeToStringConverter : IValueConverter +{ + /// + /// Convert a round-trip time to a string. + /// + /// Round-trip time in milliseconds ( or ) or null. + /// + /// + /// + /// Formatted time, e.g. <1 ms, 9 ms, -/-. + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return LatencyStatistics.FormatTime(value switch + { + long time => time, + double time => time, + _ => null + }); + } + + /// + /// !!! Method not implemented !!! + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } +} diff --git a/Source/NETworkManager.Localization/ResourceIdentifier.cs b/Source/NETworkManager.Localization/ResourceIdentifier.cs index c812c623c9..e0e0aa137e 100644 --- a/Source/NETworkManager.Localization/ResourceIdentifier.cs +++ b/Source/NETworkManager.Localization/ResourceIdentifier.cs @@ -8,6 +8,7 @@ public enum ResourceIdentifier ApplicationName, ConnectionCheckReason, LLDPCDPProtocol, + LatencyPosition, IPStatus, PortState, ProfileName, diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 60163118bd..46fb8bff72 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -897,6 +897,15 @@ public static string AddTag { } } + /// + /// Looks up a localized string similar to Add target. + /// + public static string AddTarget { + get { + return ResourceManager.GetString("AddTarget", resourceCulture); + } + } + /// /// Looks up a localized string similar to Adjust screen. /// @@ -2170,6 +2179,15 @@ public static string CheckIPGeolocation { } } + /// + /// Looks up a localized string similar to Check latency. + /// + public static string CheckLatency { + get { + return ResourceManager.GetString("CheckLatency", resourceCulture); + } + } + /// /// Looks up a localized string similar to Check your network adapter configuration (dns) and if your dns server is configured correctly.. /// @@ -2639,7 +2657,7 @@ public static string ConnectionCheckReason_GatewayNoReply { } /// - /// Looks up a localized string similar to No reply to the ping and no public IP address from the API, but Windows reports internet access. ICMP and the API may be blocked by a firewall or only reachable via a proxy.. + /// Looks up a localized string similar to The ping or the public IP address check failed, but Windows reports internet access. ICMP or the API may be blocked by a firewall or only reachable via a proxy.. /// public static string ConnectionCheckReason_InternetAccessReportedByWindows { get { @@ -2648,7 +2666,25 @@ public static string ConnectionCheckReason_InternetAccessReportedByWindows { } /// - /// Looks up a localized string similar to The internet is not reachable (no reply to the ping of the public IP address and no answer from the public IP address API).. + /// Looks up a localized string similar to Windows reports internet access. The ping and the public IP address check are disabled in the settings.. + /// + public static string ConnectionCheckReason_InternetAccessReportedByWindowsOnly { + get { + return ResourceManager.GetString("ConnectionCheckReason_InternetAccessReportedByWindowsOnly", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Not checked: the ping and the public IP address check are disabled in the settings.. + /// + public static string ConnectionCheckReason_InternetCheckDisabled { + get { + return ResourceManager.GetString("ConnectionCheckReason_InternetCheckDisabled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The internet is not reachable (no reply to the ping of the public IP address, no answer from the public IP address API if enabled).. /// public static string ConnectionCheckReason_InternetNotReachable { get { @@ -2692,6 +2728,15 @@ public static string ConnectionCheckReason_NoGateway { } } + /// + /// Looks up a localized string similar to Windows reports no internet access. The ping and the public IP address check are disabled in the settings.. + /// + public static string ConnectionCheckReason_NoInternetAccessReportedByWindows { + get { + return ResourceManager.GetString("ConnectionCheckReason_NoInternetAccessReportedByWindows", resourceCulture); + } + } + /// /// Looks up a localized string similar to No IP address to resolve.. /// @@ -3784,6 +3829,26 @@ public static string DeleteTable { } } + /// + /// Looks up a localized string similar to Delete target. + /// + public static string DeleteTarget { + get { + return ResourceManager.GetString("DeleteTarget", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The selected target is permanently deleted: + /// + ///{0}. + /// + public static string DeleteTargetMessage { + get { + return ResourceManager.GetString("DeleteTargetMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to Description. /// @@ -4479,6 +4544,15 @@ public static string EditSNTPServer { } } + /// + /// Looks up a localized string similar to Edit target. + /// + public static string EditTarget { + get { + return ResourceManager.GetString("EditTarget", resourceCulture); + } + } + /// /// Looks up a localized string similar to EDNS. /// @@ -6320,7 +6394,7 @@ public static string HelpMessage_BindToNetworkInterface { } /// - /// Looks up a localized string similar to The DNS resolver is determined via ip-api.com. + /// Looks up a localized string similar to Requests the DNS server that resolves your requests from edns.ip-api.com with every check. ip-api.com receives your IP address and the IP address of your DNS server. /// ///URL: https://edns.ip-api.com/. /// @@ -6342,7 +6416,7 @@ public static string HelpMessage_CheckForUpdatesAtStartup { } /// - /// Looks up a localized string similar to The IP geolocation is determined via ip-api.com. + /// Looks up a localized string similar to Requests the location and the internet provider of your public IP address from ip-api.com with every check. ip-api.com receives your IP address (http, not encrypted). /// ///URL: http://ip-api.com/. /// @@ -6353,11 +6427,20 @@ public static string HelpMessage_CheckIPGeolocation { } /// - /// Looks up a localized string similar to The public IP address is determined via ipify.org. + /// Looks up a localized string similar to Pings the default gateway and the targets every few seconds, only while the dashboard is shown (not in the background, not while the window is minimized or in the tray). The targets receive a ping (ICMP echo request).. + /// + public static string HelpMessage_CheckLatency { + get { + return ResourceManager.GetString("HelpMessage_CheckLatency", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Requests your public IP address with every check of the network connection (dashboard and status window) to show it and to see if the internet is reachable. The service receives your IP address. /// - ///URL: https://api.ipify.org and https://api6.ipify.org + ///Default: ipify.org (https://api.ipify.org and https://api6.ipify.org), can be changed in the settings. /// - ///If disabled, the internet connection is only checked with a ping of the public IP address and the internet connectivity reported by Windows.. + ///If the ping and the public IP address check are disabled, only the internet connectivity reported by Windows is used.. /// public static string HelpMessage_CheckPublicIPAddress { get { @@ -6446,6 +6529,44 @@ public static string HelpMessage_GuessTheOperatingSystemFromTheTTL { } } + /// + /// Looks up a localized string similar to Pings the default gateway (router) of the network adapter that is used for the internet, in the first line in front of the targets. If only the targets fail, the problem is the internet connection, not your network. It is detected again when the pings start, e.g. after a network change (VPN, another Wi-Fi).. + /// + public static string HelpMessage_LatencyGateway { + get { + return ResourceManager.GetString("HelpMessage_LatencyGateway", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Time between the reply (or timeout) of a ping and the next ping of the target.. + /// + public static string HelpMessage_LatencyInterval { + get { + return ResourceManager.GetString("HelpMessage_LatencyInterval", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Next to the speed test: on the right of the speed test (1/3 of the width), the targets one below the other. In a narrow window or without the speed test, the widget gets its own row below the speed test. + /// + ///Own row: below the network connection, the targets side by side.. + /// + public static string HelpMessage_LatencyPosition { + get { + return ResourceManager.GetString("HelpMessage_LatencyPosition", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Up to 5 targets: IP addresses or host names on the internet or in your network (e.g. a server). In an internal or air-gapped network, replace the default targets on the internet with your own hosts.. + /// + public static string HelpMessage_LatencyTargets { + get { + return ResourceManager.GetString("HelpMessage_LatencyTargets", resourceCulture); + } + } + /// /// Looks up a localized string similar to Number of backups that are retained before the oldest one is deleted.. /// @@ -6536,6 +6657,19 @@ public static string HelpMessage_PingHostsBeforeScan { } } + /// + /// Looks up a localized string similar to Pings a public IP address with every check of the network connection (dashboard and status window) to see if the internet is reachable. The target receives a ping (ICMP echo request). + /// + ///Default: Cloudflare (1.1.1.1 and 2606:4700:4700::1111), can be changed in the settings. + /// + ///If the ping and the public IP address check are disabled, only the internet connectivity reported by Windows is used.. + /// + public static string HelpMessage_PingPublicIPAddress { + get { + return ResourceManager.GetString("HelpMessage_PingPublicIPAddress", resourceCulture); + } + } + /// /// Looks up a localized string similar to Host threads × port threads can be at most 8,192 connections at the same time (every connection uses a local port, this is half of them). Many connections at the same time may be blocked by a firewall or overload small routers.. /// @@ -6555,7 +6689,7 @@ public static string HelpMessage_ProfileHostPlaceholder { } /// - /// Looks up a localized string similar to Public IPv4 address (not the one of your computer) that is pinged to check the internet connection. The route to it is used to detect the local IPv4 address (of the network adapter that is used for the internet).. + /// Looks up a localized string similar to Public IPv4 address (not the one of your computer) that is pinged to check the internet connection (if enabled). The route to it is used to detect the local IPv4 address (of the network adapter that is used for the internet), nothing is sent for this.. /// public static string HelpMessage_PublicIPv4Address { get { @@ -6564,7 +6698,7 @@ public static string HelpMessage_PublicIPv4Address { } /// - /// Looks up a localized string similar to Public IPv6 address (not the one of your computer) that is pinged to check the internet connection. The route to it is used to detect the local IPv6 address (of the network adapter that is used for the internet).. + /// Looks up a localized string similar to Public IPv6 address (not the one of your computer) that is pinged to check the internet connection (if enabled). The route to it is used to detect the local IPv6 address (of the network adapter that is used for the internet), nothing is sent for this.. /// public static string HelpMessage_PublicIPv6Address { get { @@ -6711,7 +6845,16 @@ public static string HelpMessage_ShowIPApiWidget { } /// - /// Looks up a localized string similar to Shows the widget on the dashboard. The status window always shows the network connection.. + /// Looks up a localized string similar to Shows the widget on the dashboard. It only pings the default gateway and the targets if the check is enabled (below, in the welcome dialog or with the "Enable" button of the widget), otherwise it shows what it would ping. A hidden widget sends nothing.. + /// + public static string HelpMessage_ShowLatencyWidget { + get { + return ResourceManager.GetString("HelpMessage_ShowLatencyWidget", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Shows the widget on the dashboard. A hidden widget doesn't check anything, but the status window still checks the network connection (e.g. on a network change, see Settings > Status).. /// public static string HelpMessage_ShowNetworkConnectionWidget { get { @@ -6746,6 +6889,28 @@ public static string HelpMessage_UseCustomThemes { } } + /// + /// Looks up a localized string similar to Requests the location and the internet provider of your public IP address (dashboard) and of the hops of a trace (traceroute) from ip-api.com. ip-api.com receives these IP addresses (http, not encrypted). + /// + ///URL: http://ip-api.com/. + /// + public static string HelpMessage_WelcomeCheckIPGeolocation { + get { + return ResourceManager.GetString("HelpMessage_WelcomeCheckIPGeolocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Pings the default gateway and the targets of the latency widget every few seconds while the dashboard is shown. The targets receive a ping (ICMP echo request). + /// + ///Default targets: Cloudflare (1.1.1.1), Google (8.8.8.8) and Quad9 (9.9.9.9), can be changed in the settings.. + /// + public static string HelpMessage_WelcomeCheckLatency { + get { + return ResourceManager.GetString("HelpMessage_WelcomeCheckLatency", resourceCulture); + } + } + /// /// 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.. /// @@ -7313,6 +7478,15 @@ public static string Internet { } } + /// + /// Looks up a localized string similar to Interval (seconds). + /// + public static string IntervalInSeconds { + get { + return ResourceManager.GetString("IntervalInSeconds", resourceCulture); + } + } + /// /// Looks up a localized string similar to IP address. /// @@ -7764,6 +7938,43 @@ public static string Latency { } } + /// + /// Looks up a localized string similar to Next to the speed test. + /// + public static string LatencyPosition_NextToSpeedTest { + get { + return ResourceManager.GetString("LatencyPosition_NextToSpeedTest", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Own row. + /// + public static string LatencyPosition_OwnRow { + get { + return ResourceManager.GetString("LatencyPosition_OwnRow", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The maximum of {0} targets is reached. Delete a target to add another one.. + /// + public static string LatencyTargetLimitReachedMessage { + get { + return ResourceManager.GetString("LatencyTargetLimitReachedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Show the latency to your router and to targets on the internet or in your network (e.g. Cloudflare, Google and Quad9), updated live while the dashboard is shown. + ///The targets receive a ping (ICMP echo request) every few seconds.. + /// + public static string LatencyWidgetDisabledMessage { + get { + return ResourceManager.GetString("LatencyWidgetDisabledMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to Latitude. /// @@ -9187,7 +9398,7 @@ public static string NetworkConnectionType { } /// - /// Looks up a localized string similar to The network connection widget and the status window use these settings to check the internet.. + /// Looks up a localized string similar to The network connection widget and the status window use these settings to check the internet, also while the widget is hidden.. /// public static string NetworkConnectionWidgetAndStatusWindowUseTheseSettingsMessage { get { @@ -9501,6 +9712,15 @@ public static string NoFirewallRulesFoundMessage { } } + /// + /// Looks up a localized string similar to No targets configured.. + /// + public static string NoLatencyTargetsConfiguredMessage { + get { + return ResourceManager.GetString("NoLatencyTargetsConfiguredMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to No LLDP or CDP packets received!. /// @@ -10321,6 +10541,15 @@ public static string Ping { } } + /// + /// Looks up a localized string similar to Ping default gateway. + /// + public static string PingDefaultGateway { + get { + return ResourceManager.GetString("PingDefaultGateway", resourceCulture); + } + } + /// /// Looks up a localized string similar to Ping details. /// @@ -10375,6 +10604,15 @@ public static string PingMonitorNotification { } } + /// + /// Looks up a localized string similar to Ping public IP address. + /// + public static string PingPublicIPAddress { + get { + return ResourceManager.GetString("PingPublicIPAddress", resourceCulture); + } + } + /// /// Looks up a localized string similar to Ping status. /// @@ -10582,6 +10820,15 @@ public static string PortStatus { } } + /// + /// Looks up a localized string similar to Position. + /// + public static string Position { + get { + return ResourceManager.GetString("Position", resourceCulture); + } + } + /// /// Looks up a localized string similar to PowerShell. /// @@ -14863,6 +15110,15 @@ public static string StatusWindow { } } + /// + /// Looks up a localized string similar to The status window checks the network connection with the settings of Dashboard > Network connection (ping and public IP address).. + /// + public static string StatusWindowUsesDashboardSettingsMessage { + get { + return ResourceManager.GetString("StatusWindowUsesDashboardSettingsMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to Steel. /// @@ -15007,6 +15263,15 @@ public static string Tags { } } + /// + /// Looks up a localized string similar to Targets. + /// + public static string Targets { + get { + return ResourceManager.GetString("Targets", resourceCulture); + } + } + /// /// Looks up a localized string similar to Task Manager (Ctrl+Shift+Esc). /// @@ -16281,7 +16546,7 @@ public static string WelcomeMessage { } /// - /// Looks up a localized string similar to To provide additional features, third party services are used that are not operated by me. You can deselect them below. No data is transferred to me at any time.. + /// Looks up a localized string similar to Some features use third-party services. You can turn them off below. NETworkManager doesn't collect any data, nothing is sent to the developers.. /// public static string WelcomePrivacyMessage { get { diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index 916fdb5aff..15220c3a77 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -2090,11 +2090,11 @@ If you enjoy it, please consider supporting its development — whether by leavi URL: https://api.github.com/ - The public IP address is determined via ipify.org. + Requests your public IP address with every check of the network connection (dashboard and status window) to show it and to see if the internet is reachable. The service receives your IP address. -URL: https://api.ipify.org and https://api6.ipify.org +Default: ipify.org (https://api.ipify.org and https://api6.ipify.org), can be changed in the settings. -If disabled, the internet connection is only checked with a ping of the public IP address and the internet connectivity reported by Windows. +If the ping and the public IP address check are disabled, only the internet connectivity reported by Windows is used. Privacy @@ -3090,10 +3090,10 @@ Enable profile file encryption in Settings>Profile to store credentials secur Enter a valid IPv6 address! - Public IPv4 address (not the one of your computer) that is pinged to check the internet connection. The route to it is used to detect the local IPv4 address (of the network adapter that is used for the internet). + Public IPv4 address (not the one of your computer) that is pinged to check the internet connection (if enabled). The route to it is used to detect the local IPv4 address (of the network adapter that is used for the internet), nothing is sent for this. - Public IPv6 address (not the one of your computer) that is pinged to check the internet connection. The route to it is used to detect the local IPv6 address (of the network adapter that is used for the internet). + Public IPv6 address (not the one of your computer) that is pinged to check the internet connection (if enabled). The route to it is used to detect the local IPv6 address (of the network adapter that is used for the internet), nothing is sent for this. Public IPv4 address @@ -3726,17 +3726,17 @@ If the option is disabled again, the values are no longer modified. However, the Show map - The DNS resolver is determined via ip-api.com. + Requests the DNS server that resolves your requests from edns.ip-api.com with every check. ip-api.com receives your IP address and the IP address of your DNS server. URL: https://edns.ip-api.com/ - The IP geolocation is determined via ip-api.com. + Requests the location and the internet provider of your public IP address from ip-api.com with every check. ip-api.com receives your IP address (http, not encrypted). URL: http://ip-api.com/ - To provide additional features, third party services are used that are not operated by me. You can deselect them below. No data is transferred to me at any time. + Some features use third-party services. You can turn them off below. NETworkManager doesn't collect any data, nothing is sent to the developers. Checking DNS resolver... @@ -5734,10 +5734,10 @@ Do you want to start the scan? Windows reports limited internet access (e.g. a hotspot / captive portal that requires a sign-in). - No reply to the ping and no public IP address from the API, but Windows reports internet access. ICMP and the API may be blocked by a firewall or only reachable via a proxy. + The ping or the public IP address check failed, but Windows reports internet access. ICMP or the API may be blocked by a firewall or only reachable via a proxy. - The internet is not reachable (no reply to the ping of the public IP address and no answer from the public IP address API). + The internet is not reachable (no reply to the ping of the public IP address, no answer from the public IP address API if enabled). The public IP address is not requested (disabled in the settings). @@ -5772,12 +5772,109 @@ ip-api.com receives your IP address and the IP address of your DNS server.Show widget - Shows the widget on the dashboard. The status window always shows the network connection. + Shows the widget on the dashboard. A hidden widget doesn't check anything, but the status window still checks the network connection (e.g. on a network change, see Settings > Status). Shows the widget on the dashboard. It only sends a request to ip-api.com if the check is enabled (below, in the welcome dialog or with the "Enable" button of the widget), otherwise it shows what it would request. A hidden widget sends no request. - The network connection widget and the status window use these settings to check the internet. + The network connection widget and the status window use these settings to check the internet, also while the widget is hidden. + + + Interval (seconds) + + + Position + + + Check latency + + + Pings the default gateway and the targets every few seconds, only while the dashboard is shown (not in the background, not while the window is minimized or in the tray). The targets receive a ping (ICMP echo request). + + + Shows the widget on the dashboard. It only pings the default gateway and the targets if the check is enabled (below, in the welcome dialog or with the "Enable" button of the widget), otherwise it shows what it would ping. A hidden widget sends nothing. + + + Show the latency to your router and to targets on the internet or in your network (e.g. Cloudflare, Google and Quad9), updated live while the dashboard is shown. +The targets receive a ping (ICMP echo request) every few seconds. + + + Time between the reply (or timeout) of a ping and the next ping of the target. + + + No targets configured. + + + Next to the speed test + + + Own row + + + Next to the speed test: on the right of the speed test (1/3 of the width), the targets one below the other. In a narrow window or without the speed test, the widget gets its own row below the speed test. + +Own row: below the network connection, the targets side by side. + + + Targets + + + Add target + + + Edit target + + + Delete target + + + The selected target is permanently deleted: + +{0} + + + Pings the default gateway and the targets of the latency widget every few seconds while the dashboard is shown. The targets receive a ping (ICMP echo request). + +Default targets: Cloudflare (1.1.1.1), Google (8.8.8.8) and Quad9 (9.9.9.9), can be changed in the settings. + + + The maximum of {0} targets is reached. Delete a target to add another one. + + + Ping default gateway + + + Pings the default gateway (router) of the network adapter that is used for the internet, in the first line in front of the targets. If only the targets fail, the problem is the internet connection, not your network. It is detected again when the pings start, e.g. after a network change (VPN, another Wi-Fi). + + + Up to 5 targets: IP addresses or host names on the internet or in your network (e.g. a server). In an internal or air-gapped network, replace the default targets on the internet with your own hosts. + + + Ping public IP address + + + Pings a public IP address with every check of the network connection (dashboard and status window) to see if the internet is reachable. The target receives a ping (ICMP echo request). + +Default: Cloudflare (1.1.1.1 and 2606:4700:4700::1111), can be changed in the settings. + +If the ping and the public IP address check are disabled, only the internet connectivity reported by Windows is used. + + + Windows reports internet access. The ping and the public IP address check are disabled in the settings. + + + Windows reports no internet access. The ping and the public IP address check are disabled in the settings. + + + Not checked: the ping and the public IP address check are disabled in the settings. + + + Requests the location and the internet provider of your public IP address (dashboard) and of the hops of a trace (traceroute) from ip-api.com. ip-api.com receives these IP addresses (http, not encrypted). + +URL: http://ip-api.com/ + + + The status window checks the network connection with the settings of Dashboard > Network connection (ping and public IP address). \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/ConnectionCheckReason.cs b/Source/NETworkManager.Models/Network/ConnectionCheckReason.cs index 9b34c2f460..2d7bd77a4b 100644 --- a/Source/NETworkManager.Models/Network/ConnectionCheckReason.cs +++ b/Source/NETworkManager.Models/Network/ConnectionCheckReason.cs @@ -78,16 +78,32 @@ public enum ConnectionCheckReason CaptivePortal, /// - /// The ping and the public IP address API failed, but Windows reports internet access (e.g. ICMP and the API are - /// blocked by a firewall or only reachable via a proxy). + /// The enabled checks (ping, public IP address API) failed, but Windows reports internet access (e.g. ICMP or the + /// API are blocked by a firewall or only reachable via a proxy). /// InternetAccessReportedByWindows, /// - /// The internet is not reachable (no reply to the ping, no answer from the API). + /// The internet is not reachable (no reply to the ping, no answer from the API if enabled). /// InternetNotReachable, + /// + /// The ping and the public IP address are disabled in the settings and Windows reports internet access. + /// + InternetAccessReportedByWindowsOnly, + + /// + /// The ping and the public IP address are disabled in the settings and Windows reports no internet access. + /// + NoInternetAccessReportedByWindows, + + /// + /// The internet connection is not checked: the ping and the public IP address are disabled in the settings (IPv6, + /// or Windows doesn't report the connectivity). + /// + InternetCheckDisabled, + /// /// The public IP address is not requested (disabled in the settings). /// diff --git a/Source/NETworkManager.Models/Network/LatencyPosition.cs b/Source/NETworkManager.Models/Network/LatencyPosition.cs new file mode 100644 index 0000000000..5e9537ef9d --- /dev/null +++ b/Source/NETworkManager.Models/Network/LatencyPosition.cs @@ -0,0 +1,18 @@ +namespace NETworkManager.Models.Network; + +/// +/// Position of the latency widget on the dashboard. +/// +public enum LatencyPosition +{ + /// + /// Right next to the speed test (1/3 of the width, the targets one below the other). In a narrow window (or + /// without the speed test) it gets its own row below the speed test. + /// + NextToSpeedTest, + + /// + /// Own row below the network connection (the targets side by side). + /// + OwnRow +} diff --git a/Source/NETworkManager.Models/Network/LatencyStatistics.cs b/Source/NETworkManager.Models/Network/LatencyStatistics.cs new file mode 100644 index 0000000000..14889fcfbc --- /dev/null +++ b/Source/NETworkManager.Models/Network/LatencyStatistics.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace NETworkManager.Models.Network; + +/// +/// Result of one ping of a latency target (latency widget of the dashboard). +/// +/// Time of the ping (UTC: a clock change doesn't move the time window). +/// The target replied. +/// Round-trip time in milliseconds (0 without a reply). +public readonly record struct LatencySample(DateTime Timestamp, bool IsSuccess, long Time); + +/// +/// State of a latency target, shown as the status dot of the widget. +/// +public enum LatencyState +{ + /// + /// Not pinged yet. + /// + None, + + /// + /// The last ping was answered and no ping was lost in the time window. + /// + Ok, + + /// + /// The last ping was answered, but a ping was lost in the time window. + /// + Lost, + + /// + /// The last ping was not answered (e.g. timeout, unreachable). + /// + Failed +} + +/// +/// Statistics of the pings of a latency target in the time window. +/// +/// Number of pings. +/// Pings without a reply. +/// Lowest round-trip time, null without a reply. +/// Average round-trip time of the replies, null without a reply. +/// Highest round-trip time, null without a reply. +public sealed record LatencyStatisticsInfo(int Count, int Lost, long? Minimum, double? Average, long? Maximum) +{ + /// + /// Pings without a reply in percent (0 without pings). + /// + public double PacketLoss => Count == 0 ? 0 : (double)Lost / Count * 100; +} + +/// +/// Statistics and state of the pings of a latency target. +/// +public static class LatencyStatistics +{ + /// + /// Calculates the statistics of the pings. + /// + /// Pings in the time window. + /// Statistics, all values null without a reply. + public static LatencyStatisticsInfo Calculate(IReadOnlyCollection samples) + { + var replies = samples.Where(x => x.IsSuccess).Select(x => x.Time).ToList(); + + return replies.Count == 0 + ? new LatencyStatisticsInfo(samples.Count, samples.Count, null, null, null) + : new LatencyStatisticsInfo(samples.Count, samples.Count - replies.Count, replies.Min(), replies.Average(), + replies.Max()); + } + + /// + /// State of the target: the last ping decides whether it is reachable, a lost ping in the time window is a + /// warning. + /// + /// Pings in the time window, the last one is the newest. + /// State of the target. + public static LatencyState GetState(IReadOnlyList samples) + { + if (samples.Count == 0) + return LatencyState.None; + + if (!samples[^1].IsSuccess) + return LatencyState.Failed; + + return samples.Any(x => !x.IsSuccess) ? LatencyState.Lost : LatencyState.Ok; + } + + /// + /// Delays until a failed name lookup (or gateway detection) of a target is tried again: 5, 15, 30 seconds, then + /// every 60 seconds - a broken DNS server doesn't get a query every few seconds. + /// + private static readonly TimeSpan[] RetryDelays = + [ + TimeSpan.FromSeconds(5), + TimeSpan.FromSeconds(15), + TimeSpan.FromSeconds(30), + TimeSpan.FromSeconds(60) + ]; + + /// + /// Delay until the next attempt after failed attempts in a row. + /// + /// Failed attempts in a row (1 after the first one). + /// Delay (5, 15, 30, then 60 seconds). + public static TimeSpan GetRetryDelay(int failedAttempts) + { + return RetryDelays[Math.Clamp(failedAttempts - 1, 0, RetryDelays.Length - 1)]; + } + + /// + /// Formats a round-trip time for the widget: rounded to whole milliseconds, <1 ms if it rounds to 0 + /// (e.g. the gateway, like ), -/- without a value. + /// + /// Round-trip time (or average) in milliseconds, null without a reply. + /// Formatted time, e.g. <1 ms, 9 ms. + public static string FormatTime(double? milliseconds) + { + if (!milliseconds.HasValue) + return "-/-"; + + // Halves are rounded up (e.g. an average of 8.5 ms is 9 ms; "F0" and Math.Round would round to the even number) + var rounded = Math.Round(milliseconds.Value, MidpointRounding.AwayFromZero); + + return rounded < 1 ? "<1 ms" : $"{rounded.ToString("F0", CultureInfo.CurrentCulture)} ms"; + } + + /// + /// Removes the pings older than the time window (the list is ordered by time). + /// + /// Pings, the oldest first. + /// Current time. + /// Time window, e.g. 60 seconds. + public static void RemoveOutdated(List samples, DateTime now, TimeSpan window) + { + var cutoff = now - window; + var count = 0; + + while (count < samples.Count && samples[count].Timestamp < cutoff) + count++; + + samples.RemoveRange(0, count); + } +} diff --git a/Source/NETworkManager.Models/Network/LatencyTargetInfo.cs b/Source/NETworkManager.Models/Network/LatencyTargetInfo.cs new file mode 100644 index 0000000000..873a1585d5 --- /dev/null +++ b/Source/NETworkManager.Models/Network/LatencyTargetInfo.cs @@ -0,0 +1,46 @@ +namespace NETworkManager.Models.Network; + +/// +/// Target of the latency widget of the dashboard (Settings > Dashboard > Latency). The default gateway is not a +/// target of the list, see the setting Dashboard_LatencyPingGateway. +/// +public class LatencyTargetInfo +{ + /// + /// Creates an empty target (JSON deserialization of the settings). + /// + public LatencyTargetInfo() + { + } + + /// + /// Creates a target. + /// + /// Name shown in the widget, empty to show the host. + /// IP address or host name. + public LatencyTargetInfo(string name, string host) + { + Name = name; + Host = host; + } + + /// + /// Name shown in the widget, empty to show the host. + /// + public string Name { get; set; } + + /// + /// IP address or host name of the target. + /// + public string Host { get; set; } + + /// + /// Same name and host (the widget keeps the pings of an unchanged target when the list changes). + /// + /// Other target. + /// true if all values are the same. + public bool IsSameTarget(LatencyTargetInfo other) + { + return other != null && Name == other.Name && Host == other.Host; + } +} diff --git a/Source/NETworkManager.Models/Network/NetworkConnectionCheck.cs b/Source/NETworkManager.Models/Network/NetworkConnectionCheck.cs index 3a0964e655..82a19a4f59 100644 --- a/Source/NETworkManager.Models/Network/NetworkConnectionCheck.cs +++ b/Source/NETworkManager.Models/Network/NetworkConnectionCheck.cs @@ -124,46 +124,64 @@ public static ConnectionCheckResult GetPublicIPAddressResult(PublicIPAddressChec /// /// State of the internet connection (IPv4 or IPv6) from three sources: the ping of the public IP address - /// (setting), the public IP address API (if enabled) and the connectivity reported by Windows. + /// (setting, if enabled), the public IP address API (if enabled) and the connectivity reported by Windows. /// /// /// A public IP address from the API is OK (the HTTPS request reached the internet), even if Windows reports a /// captive portal (e.g. a proxy or web filter intercepts the probe of Windows). Otherwise a captive portal - /// (Windows, only used for IPv4) is a warning, also if the ping works (a captive portal may let ICMP through); a reply to the ping is OK; a private IP address from the API is a warning, as is a - /// failed API when the ping works (e.g. the API is blocked). If both fail but Windows reports internet access (only used for IPv4, Windows doesn't report it per - /// address family), ICMP and the API may be blocked: warning. Otherwise critical. + /// (Windows, only used for IPv4) is a warning, also if the ping works (a captive portal may let ICMP through); a + /// reply to the ping is OK; a private IP address from the API is a warning, as is a failed API when the ping + /// works (e.g. the API is blocked). If the enabled checks fail but Windows reports internet access (only used for + /// IPv4, Windows doesn't report it per address family), ICMP or the API may be blocked: warning. Otherwise + /// critical. With the ping and the API disabled, only Windows decides (IPv4); IPv6 is not checked then (info). /// /// IPv4 or IPv6. - /// The public IP address (setting) replied to the ping. + /// The public IP address (setting) replied to the ping, or null if the ping is + /// disabled. /// Result of the API, or null if disabled. /// Internet connectivity reported by Windows. /// State and reason. - public static ConnectionCheckResult GetInternetResult(AddressFamily addressFamily, bool isPingSuccessful, + public static ConnectionCheckResult GetInternetResult(AddressFamily addressFamily, bool? isPingSuccessful, PublicIPAddressCheckResult publicIPAddress, InternetConnectivityLevel connectivityLevel) { if (publicIPAddress is { Status: PublicIPAddressCheckStatus.Success }) return new ConnectionCheckResult(ConnectionState.OK); // Windows doesn't report the connectivity per address family (a captive portal is IPv4 in practice) - if (addressFamily == AddressFamily.InterNetwork && - connectivityLevel == InternetConnectivityLevel.ConstrainedInternetAccess) + var isIPv4 = addressFamily == AddressFamily.InterNetwork; + + if (isIPv4 && connectivityLevel == InternetConnectivityLevel.ConstrainedInternetAccess) return new ConnectionCheckResult(ConnectionState.Warning, ConnectionCheckReason.CaptivePortal); if (publicIPAddress is { Status: PublicIPAddressCheckStatus.PrivateIPAddress }) return GetPublicIPAddressResult(publicIPAddress); - if (isPingSuccessful) + if (isPingSuccessful == true) return publicIPAddress == null ? new ConnectionCheckResult(ConnectionState.OK) : new ConnectionCheckResult(ConnectionState.Warning, GetPublicIPAddressResult(publicIPAddress).Reason); - if (addressFamily == AddressFamily.InterNetwork && - connectivityLevel == InternetConnectivityLevel.InternetAccess) + // Ping and API disabled: only the connectivity reported by Windows (IPv4) + if (isPingSuccessful == null && publicIPAddress == null) + return isIPv4 + ? connectivityLevel switch + { + InternetConnectivityLevel.InternetAccess => new ConnectionCheckResult(ConnectionState.OK, + ConnectionCheckReason.InternetAccessReportedByWindowsOnly), + InternetConnectivityLevel.None or InternetConnectivityLevel.LocalAccess => new ConnectionCheckResult( + ConnectionState.Critical, ConnectionCheckReason.NoInternetAccessReportedByWindows), + _ => new ConnectionCheckResult(ConnectionState.Info, ConnectionCheckReason.InternetCheckDisabled) + } + : new ConnectionCheckResult(ConnectionState.Info, ConnectionCheckReason.InternetCheckDisabled); + + if (isIPv4 && connectivityLevel == InternetConnectivityLevel.InternetAccess) return new ConnectionCheckResult(ConnectionState.Warning, ConnectionCheckReason.InternetAccessReportedByWindows); - return publicIPAddress is { Status: PublicIPAddressCheckStatus.NameResolutionFailed } - ? new ConnectionCheckResult(ConnectionState.Critical, ConnectionCheckReason.NameResolutionFailed) - : new ConnectionCheckResult(ConnectionState.Critical, ConnectionCheckReason.InternetNotReachable); + // Ping disabled: the reason of the failed API (e.g. name resolution failed, request failed) + if (isPingSuccessful == null || publicIPAddress is { Status: PublicIPAddressCheckStatus.NameResolutionFailed }) + return GetPublicIPAddressResult(publicIPAddress); + + return new ConnectionCheckResult(ConnectionState.Critical, ConnectionCheckReason.InternetNotReachable); } } diff --git a/Source/NETworkManager.Models/Network/NetworkInterface.cs b/Source/NETworkManager.Models/Network/NetworkInterface.cs index ed8c09d3b7..e2eca9dab8 100644 --- a/Source/NETworkManager.Models/Network/NetworkInterface.cs +++ b/Source/NETworkManager.Models/Network/NetworkInterface.cs @@ -330,6 +330,21 @@ public static Task DetectLocalIPAddressBasedOnRoutingAsync(IPAddress return Task.Run(() => DetectLocalIPAddressFromRouting(remoteIPAddress)); } + /// + /// Detects the default gateway of the network adapter that is used to reach the remote IP address (the route to + /// it, then the gateway of the local IP address, like the network connection check of the dashboard). + /// + /// Remote IP address, e.g. the public IPv4 address of the dashboard settings. + /// Default gateway, or null if there is no route or the adapter has no gateway (e.g. a VPN). + public static async Task DetectGatewayBasedOnRoutingAsync(IPAddress remoteIPAddress) + { + var localIPAddress = await DetectLocalIPAddressBasedOnRoutingAsync(remoteIPAddress).ConfigureAwait(false); + + return localIPAddress == null + ? null + : await DetectGatewayFromLocalIPAddressAsync(localIPAddress).ConfigureAwait(false); + } + /// /// Determines the local IP address that would be used to route traffic to the specified remote IP address. /// diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs index 814d213686..d834963f19 100644 --- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs +++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs @@ -1,6 +1,5 @@ using DnsClient; using Lextm.SharpSnmpLib.Messaging; -using NETworkManager.Models; using NETworkManager.Models.Appearance; using NETworkManager.Models.Export; using NETworkManager.Models.Network; @@ -10,6 +9,7 @@ using NETworkManager.Models.RemoteDesktop; using NETworkManager.Utilities; using System; +using System.Collections.Generic; using System.IO; using System.Linq; @@ -134,12 +134,26 @@ public static class GlobalStaticConfiguration // Application: Dashboard public static string Dashboard_PublicIPv4Address => "1.1.1.1"; public static string Dashboard_PublicIPv6Address => "2606:4700:4700::1111"; - public static bool Dashboard_CheckPublicIPAddress => true; + public static bool Dashboard_PingPublicIPAddress => true; + public static bool Dashboard_CheckPublicIPAddress => false; public static string Dashboard_PublicIPv4AddressAPI => "https://api.ipify.org"; public static string Dashboard_PublicIPv6AddressAPI => "https://api6.ipify.org"; public static bool Dashboard_CheckIPApiIPGeolocation => false; public static bool Dashboard_CheckIPApiDNSResolver => false; + public static bool Dashboard_CheckLatency => false; + public static LatencyPosition Dashboard_LatencyPosition => LatencyPosition.NextToSpeedTest; + public static int Dashboard_LatencyInterval => 2; + public static bool Dashboard_LatencyPingGateway => true; + public static List Dashboard_LatencyTargets => + [ + new("Cloudflare", "1.1.1.1"), + new("Google", "8.8.8.8"), + new("Quad9", "9.9.9.9") + ]; + public static int Dashboard_LatencyMaxTargets => 5; + public static bool Dashboard_ShowNetworkConnectionWidget => true; + public static bool Dashboard_ShowLatencyWidget => true; public static bool Dashboard_ShowSpeedTestWidget => true; public static bool Dashboard_ShowIPGeolocationWidget => true; public static bool Dashboard_ShowDNSResolverWidget => true; @@ -150,7 +164,12 @@ public static class GlobalStaticConfiguration /// public static TimeSpan Dashboard_RecheckInterval => TimeSpan.FromSeconds(60); - // Ping of the gateway and the public IP address + /// + /// Time window of the chart and the statistics of the latency widget. + /// + public static TimeSpan Dashboard_LatencyWindow => TimeSpan.FromSeconds(60); + + // Ping of the gateway and the public IP address (also the targets of the latency widget) public static int Dashboard_PingTimeout => 2000; public static int Dashboard_PingAttempts => 2; public static int Dashboard_PingBuffer => 32; diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs index db63590ddc..03344913a6 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -972,6 +972,19 @@ public string Dashboard_PublicIPv6Address } } = GlobalStaticConfiguration.Dashboard_PublicIPv6Address; + public bool Dashboard_PingPublicIPAddress + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_PingPublicIPAddress; + public bool Dashboard_CheckPublicIPAddress { get; @@ -1063,6 +1076,72 @@ public bool Dashboard_CheckIPApiDNSResolver } } = GlobalStaticConfiguration.Dashboard_CheckIPApiDNSResolver; + public bool Dashboard_CheckLatency + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_CheckLatency; + + public LatencyPosition Dashboard_LatencyPosition + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_LatencyPosition; + + public int Dashboard_LatencyInterval + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_LatencyInterval; + + public bool Dashboard_LatencyPingGateway + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_LatencyPingGateway; + + public ObservableCollection Dashboard_LatencyTargets + { + get; + set + { + if (value == field) + return; + + UpdateCollectionChanged(field, value); + field = value; + OnPropertyChanged(); + } + } = [.. GlobalStaticConfiguration.Dashboard_LatencyTargets]; + public bool Dashboard_ShowNetworkConnectionWidget { get; @@ -1076,6 +1155,19 @@ public bool Dashboard_ShowNetworkConnectionWidget } } = GlobalStaticConfiguration.Dashboard_ShowNetworkConnectionWidget; + public bool Dashboard_ShowLatencyWidget + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_ShowLatencyWidget; + public bool Dashboard_ShowSpeedTestWidget { get; @@ -4841,6 +4933,9 @@ public SettingsInfo() // General General_ApplicationList.CollectionChanged += CollectionChanged; + // Dashboard + Dashboard_LatencyTargets.CollectionChanged += CollectionChanged; + // Run command RunCommand_History.CollectionChanged += CollectionChanged; diff --git a/Source/NETworkManager.Tests/Network/LatencyStatisticsTests.cs b/Source/NETworkManager.Tests/Network/LatencyStatisticsTests.cs new file mode 100644 index 0000000000..bd554446c5 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/LatencyStatisticsTests.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class LatencyStatisticsTests +{ + private static readonly DateTime Start = new(2026, 11, 28, 12, 0, 0); + + private static LatencySample Reply(int second, long time) => new(Start.AddSeconds(second), true, time); + + private static LatencySample Lost(int second) => new(Start.AddSeconds(second), false, 0); + + [Fact] + public void StatisticsOfNoPingsAreEmpty() + { + var info = LatencyStatistics.Calculate([]); + + Assert.Equal(0, info.Count); + Assert.Null(info.Minimum); + Assert.Null(info.Average); + Assert.Null(info.Maximum); + Assert.Equal(0, info.PacketLoss); + } + + [Fact] + public void StatisticsUseOnlyTheReplies() + { + var info = LatencyStatistics.Calculate([Reply(0, 10), Lost(2), Reply(4, 20), Reply(6, 30)]); + + Assert.Equal(4, info.Count); + Assert.Equal(1, info.Lost); + Assert.Equal(10, info.Minimum); + Assert.Equal(20, info.Average); + Assert.Equal(30, info.Maximum); + Assert.Equal(25, info.PacketLoss); + } + + [Fact] + public void StatisticsWithoutAReplyAreAllLost() + { + var info = LatencyStatistics.Calculate([Lost(0), Lost(2)]); + + Assert.Equal(2, info.Lost); + Assert.Null(info.Average); + Assert.Equal(100, info.PacketLoss); + } + + [Fact] + public void StateWithoutPingsIsNone() + { + Assert.Equal(LatencyState.None, LatencyStatistics.GetState([])); + } + + [Fact] + public void StateWithOnlyRepliesIsOk() + { + Assert.Equal(LatencyState.Ok, LatencyStatistics.GetState([Reply(0, 9), Reply(2, 8)])); + } + + [Fact] + public void StateWithALostPingInTheWindowIsLost() + { + Assert.Equal(LatencyState.Lost, LatencyStatistics.GetState([Reply(0, 9), Lost(2), Reply(4, 8)])); + } + + [Fact] + public void StateDependsOnTheLastPing() + { + Assert.Equal(LatencyState.Failed, LatencyStatistics.GetState([Reply(0, 9), Reply(2, 8), Lost(4)])); + } + + [Theory] + [InlineData(0, 5)] + [InlineData(1, 5)] + [InlineData(2, 15)] + [InlineData(3, 30)] + [InlineData(4, 60)] + [InlineData(100, 60)] + public void RetryDelayBacksOffToOneMinute(int failedAttempts, int expectedSeconds) + { + Assert.Equal(TimeSpan.FromSeconds(expectedSeconds), LatencyStatistics.GetRetryDelay(failedAttempts)); + } + + [Fact] + public void RemoveOutdatedKeepsTheTimeWindow() + { + List samples = [Reply(0, 1), Reply(30, 2), Reply(59, 3), Reply(61, 4), Reply(90, 5)]; + + LatencyStatistics.RemoveOutdated(samples, Start.AddSeconds(120), TimeSpan.FromSeconds(60)); + + Assert.Equal([4L, 5L], samples.ConvertAll(x => x.Time)); + } + + [Fact] + public void RemoveOutdatedKeepsAllRecentPings() + { + List samples = [Reply(0, 1), Reply(2, 2)]; + + LatencyStatistics.RemoveOutdated(samples, Start.AddSeconds(10), TimeSpan.FromSeconds(60)); + + Assert.Equal(2, samples.Count); + } + + [Theory] + [InlineData(0d, "<1 ms")] + [InlineData(0.4d, "<1 ms")] + [InlineData(0.5d, "1 ms")] + [InlineData(9d, "9 ms")] + [InlineData(9.5d, "10 ms")] + [InlineData(8.5d, "9 ms")] + public void FormatTimeShowsLessThanOneMillisecond(double milliseconds, string expected) + { + Assert.Equal(expected, LatencyStatistics.FormatTime(milliseconds)); + } + + [Fact] + public void FormatTimeWithoutValue() + { + Assert.Equal("-/-", LatencyStatistics.FormatTime(null)); + } +} diff --git a/Source/NETworkManager.Tests/Network/LatencyTargetInfoTests.cs b/Source/NETworkManager.Tests/Network/LatencyTargetInfoTests.cs new file mode 100644 index 0000000000..28eadbc58e --- /dev/null +++ b/Source/NETworkManager.Tests/Network/LatencyTargetInfoTests.cs @@ -0,0 +1,29 @@ +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class LatencyTargetInfoTests +{ + [Fact] + public void SameNameAndHostIsTheSameTarget() + { + Assert.True(new LatencyTargetInfo("Cloudflare", "1.1.1.1") + .IsSameTarget(new LatencyTargetInfo("Cloudflare", "1.1.1.1"))); + } + + [Theory] + [InlineData("CF", "1.1.1.1")] + [InlineData("Cloudflare", "1.0.0.1")] + public void AnotherValueIsAnotherTarget(string name, string host) + { + Assert.False(new LatencyTargetInfo("Cloudflare", "1.1.1.1") + .IsSameTarget(new LatencyTargetInfo(name, host))); + } + + [Fact] + public void NoTargetIsNotTheSameTarget() + { + Assert.False(new LatencyTargetInfo("Cloudflare", "1.1.1.1").IsSameTarget(null)); + } +} diff --git a/Source/NETworkManager.Tests/Network/NetworkConnectionCheckTests.cs b/Source/NETworkManager.Tests/Network/NetworkConnectionCheckTests.cs index db6905a3eb..3df1abfc45 100644 --- a/Source/NETworkManager.Tests/Network/NetworkConnectionCheckTests.cs +++ b/Source/NETworkManager.Tests/Network/NetworkConnectionCheckTests.cs @@ -155,7 +155,18 @@ private static PublicIPAddressCheckResult Api(PublicIPAddressCheckStatus? status [InlineData(false, PublicIPAddressCheckStatus.RequestFailed, InternetConnectivityLevel.LocalAccess, ConnectionState.Critical, ConnectionCheckReason.InternetNotReachable)] [InlineData(false, PublicIPAddressCheckStatus.InvalidResponse, InternetConnectivityLevel.Unknown, ConnectionState.Critical, ConnectionCheckReason.InternetNotReachable)] [InlineData(false, PublicIPAddressCheckStatus.NameResolutionFailed, InternetConnectivityLevel.None, ConnectionState.Critical, ConnectionCheckReason.NameResolutionFailed)] - public void GetInternetResult_IPv4(bool isPingSuccessful, PublicIPAddressCheckStatus? apiStatus, + // Ping disabled: API and Windows decide + [InlineData(null, PublicIPAddressCheckStatus.Success, InternetConnectivityLevel.LocalAccess, ConnectionState.OK, ConnectionCheckReason.None)] + [InlineData(null, PublicIPAddressCheckStatus.RequestFailed, InternetConnectivityLevel.InternetAccess, ConnectionState.Warning, ConnectionCheckReason.InternetAccessReportedByWindows)] + [InlineData(null, PublicIPAddressCheckStatus.RequestFailed, InternetConnectivityLevel.LocalAccess, ConnectionState.Critical, ConnectionCheckReason.PublicIPAddressRequestFailed)] + [InlineData(null, PublicIPAddressCheckStatus.NameResolutionFailed, InternetConnectivityLevel.None, ConnectionState.Critical, ConnectionCheckReason.NameResolutionFailed)] + // Ping and API disabled: only Windows + [InlineData(null, null, InternetConnectivityLevel.InternetAccess, ConnectionState.OK, ConnectionCheckReason.InternetAccessReportedByWindowsOnly)] + [InlineData(null, null, InternetConnectivityLevel.ConstrainedInternetAccess, ConnectionState.Warning, ConnectionCheckReason.CaptivePortal)] + [InlineData(null, null, InternetConnectivityLevel.LocalAccess, ConnectionState.Critical, ConnectionCheckReason.NoInternetAccessReportedByWindows)] + [InlineData(null, null, InternetConnectivityLevel.None, ConnectionState.Critical, ConnectionCheckReason.NoInternetAccessReportedByWindows)] + [InlineData(null, null, InternetConnectivityLevel.Unknown, ConnectionState.Info, ConnectionCheckReason.InternetCheckDisabled)] + public void GetInternetResult_IPv4(bool? isPingSuccessful, PublicIPAddressCheckStatus? apiStatus, InternetConnectivityLevel level, ConnectionState state, ConnectionCheckReason reason) { Assert.Equal(new ConnectionCheckResult(state, reason), @@ -173,6 +184,15 @@ public void GetInternetResult_IPv6_CaptivePortalOfWindowsIsNotUsed(bool isPingSu InternetConnectivityLevel.ConstrainedInternetAccess)); } + [Fact] + public void GetInternetResult_IPv6_NotCheckedWithoutPingAndAPI() + { + // Windows doesn't report the connectivity per address family + Assert.Equal(new ConnectionCheckResult(ConnectionState.Info, ConnectionCheckReason.InternetCheckDisabled), + NetworkConnectionCheck.GetInternetResult(AddressFamily.InterNetworkV6, null, null, + InternetConnectivityLevel.InternetAccess)); + } + [Fact] public void GetInternetResult_IPv6_WindowsInternetAccessIsNotUsed() { diff --git a/Source/NETworkManager/MainWindow.xaml.cs b/Source/NETworkManager/MainWindow.xaml.cs index d3ea6275e2..8ef505c9e6 100644 --- a/Source/NETworkManager/MainWindow.xaml.cs +++ b/Source/NETworkManager/MainWindow.xaml.cs @@ -489,7 +489,7 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Sett // Show welcome dialog if (SettingsManager.Current.WelcomeDialog_Show) { - var childWindow = new WelcomeChildWindow(); + var childWindow = new WelcomeChildWindow(this); var viewModel = new WelcomeViewModel(instance => { @@ -499,7 +499,9 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Sett // Set settings based on user choice SettingsManager.Current.Update_CheckForUpdatesAtStartup = instance.CheckForUpdatesAtStartup; + SettingsManager.Current.Dashboard_PingPublicIPAddress = instance.PingPublicIPAddress; SettingsManager.Current.Dashboard_CheckPublicIPAddress = instance.CheckPublicIPAddress; + SettingsManager.Current.Dashboard_CheckLatency = instance.CheckLatency; SettingsManager.Current.Dashboard_CheckIPApiIPGeolocation = instance.CheckIPApiIPGeolocation; SettingsManager.Current.Dashboard_CheckIPApiDNSResolver = instance.CheckIPApiDNSResolver; @@ -531,7 +533,7 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Sett } else if (SettingsManager.Current.UpgradeDialog_Show) { - var childWindow = new UpgradeChildWindow(); + var childWindow = new UpgradeChildWindow(this); var viewModel = new UpgradeViewModel(instance => { @@ -1598,6 +1600,12 @@ private void NotifyIcon_Click(object sender, EventArgs e) OpenStatusWindowCommand.Execute(null); } + /// + /// Window state before the last change: only a restore from minimized shows the window again (not maximize / + /// restore down). The window never starts minimized (the saved position is normal or maximized). + /// + private WindowState _previousWindowState = WindowState.Normal; + private void MetroWindowMain_StateChanged(object sender, EventArgs e) { // Keep the fixed size in screenshot mode (e.g. double-click on the title bar) @@ -1607,13 +1615,22 @@ private void MetroWindowMain_StateChanged(object sender, EventArgs e) return; } + var wasMinimized = _previousWindowState == WindowState.Minimized; + _previousWindowState = WindowState; + if (WindowState != WindowState.Minimized) { - // Restored: the dashboard may be outdated (e.g. a network change while minimized) - _dashboardView?.OnMainWindowShown(); + // Restored from minimized: the dashboard may be outdated (e.g. a network change while minimized). Maximize / + // restore down: the window was shown all the time, the widgets are not checked again + if (wasMinimized) + _dashboardView?.OnMainWindowShown(); + return; } + // Minimized: no live values in the background (latency) + _dashboardView?.OnMainWindowHidden(); + if (SettingsManager.Current.Window_MinimizeToTrayInsteadOfTaskbar) HideWindowToTray(); } @@ -1805,6 +1822,9 @@ private void HideWindowToTray() _notifyIcon.Visible = true; Hide(); + + // No live values in the background (latency) + _dashboardView?.OnMainWindowHidden(); } private void ShowWindowFromTray() @@ -1813,8 +1833,10 @@ private void ShowWindowFromTray() Show(); - // The dashboard may be outdated (e.g. a network change while in the tray) - _dashboardView?.OnMainWindowShown(); + // The dashboard may be outdated (e.g. a network change while in the tray). Still minimized (minimized to the + // tray): checked when it is restored (StateChanged), not while it is minimized + if (WindowState != WindowState.Minimized) + _dashboardView?.OnMainWindowShown(); _notifyIcon.Visible = SettingsManager.Current.TrayIcon_AlwaysShowIcon; } diff --git a/Source/NETworkManager/ScreenshotData.cs b/Source/NETworkManager/ScreenshotData.cs index ec2440aeb6..a94c004c46 100644 --- a/Source/NETworkManager/ScreenshotData.cs +++ b/Source/NETworkManager/ScreenshotData.cs @@ -365,4 +365,31 @@ private static IEnumerable CreateSamples(int count, double max) } #endregion + + #region Latency + + /// + /// Creates the pings of the last minute of a latency target (like the default targets: the gateway, Cloudflare, + /// Google and Quad9): a reply every 2 seconds with a few milliseconds of variation, ending now. + /// + /// Index of the target in the list (without the gateway), each has its own latency. + /// The default gateway: mostly below 1 ms (shown as "<1 ms"), some 1 ms replies. + public static IEnumerable CreateLatencySamples(int index, bool isGateway) + { + long[] baseTimes = [9, 8, 10]; + var now = DateTime.UtcNow; // like the widget (time window in UTC) + + for (var i = 30; i >= 0; i--) + { + var time = isGateway + ? Math.Max(0, (long)Math.Round(0.6 * Math.Sin(i * 0.9) + 0.4 * Math.Cos(i * 2.3), + MidpointRounding.AwayFromZero)) + : Math.Max(1, baseTimes[index % baseTimes.Length] + + (long)Math.Round(1.5 * Math.Sin((i + index * 7) * 0.9) + Math.Cos((i + index) * 2.3))); + + yield return new LatencySample(now.AddSeconds(-i * 2), true, time); + } + } + + #endregion } diff --git a/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs b/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs index d34534ddfa..2621950cbf 100644 --- a/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs @@ -1,4 +1,16 @@ +using System; +using System.Collections.Generic; using System.ComponentModel; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Data; +using System.Windows.Input; +using MahApps.Metro.SimpleChildWindow; +using NETworkManager.Controls; +using NETworkManager.Localization.Resources; +using NETworkManager.Utilities; +using NETworkManager.Views; +using NETworkManager.Models.Network; using NETworkManager.Settings; namespace NETworkManager.ViewModels; @@ -53,6 +65,25 @@ public string PublicIPv6Address } } + /// + /// Gets or sets a value indicating whether the public IP address (setting) is pinged to check the internet. + /// + public bool PingPublicIPAddressEnabled + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_PingPublicIPAddress = value; + + field = value; + OnPropertyChanged(); + } + } + /// /// Gets or sets a value indicating whether checking public IP address is enabled. /// @@ -205,6 +236,151 @@ public bool ShowNetworkConnectionWidget } } + /// + /// Gets or sets a value indicating whether the latency widget is shown on the dashboard. + /// + public bool ShowLatencyWidget + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_ShowLatencyWidget = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the positions of the latency widget. + /// + public IEnumerable LatencyPositions => Enum.GetValues(); + + /// + /// Gets or sets the position of the latency widget (next to the speed test or own row). + /// + public LatencyPosition LatencyPosition + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_LatencyPosition = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets a value indicating whether the latency widget pings its targets. + /// + public bool CheckLatencyEnabled + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_CheckLatency = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the time in seconds between the reply of a ping and the next ping of a target. + /// + public int LatencyInterval + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_LatencyInterval = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets a value indicating whether the latency widget pings the default gateway (first line). + /// + public bool LatencyPingGateway + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_LatencyPingGateway = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the targets of the latency widget. + /// + public ICollectionView LatencyTargets { get; } = + CollectionViewSource.GetDefaultView(SettingsManager.Current.Dashboard_LatencyTargets); + + /// + /// Gets a value indicating whether the list holds the maximum number of targets (Add is disabled, its tooltip + /// says why). + /// + public bool IsLatencyTargetLimitReached + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the tooltip of the disabled Add button (maximum number of targets reached). + /// + public string LatencyTargetLimitReachedMessage { get; } = string.Format(Strings.LatencyTargetLimitReachedMessage, + GlobalStaticConfiguration.Dashboard_LatencyMaxTargets); + + /// + /// Gets or sets the selected target of the latency widget. + /// + public LatencyTargetInfo SelectedLatencyTarget + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + /// /// Gets or sets a value indicating whether the speed test widget is shown on the dashboard. /// @@ -264,6 +440,102 @@ public bool ShowDNSResolverWidget #endregion + #region ICommands & Actions + + /// + /// Gets the command to add a target of the latency widget (up to the maximum). + /// + public ICommand AddLatencyTargetCommand => new RelayCommand(_ => AddLatencyTargetAction().ConfigureAwait(false), + _ => !IsLatencyTargetLimitReached); + + /// + /// Gets the command to edit the selected target. + /// + public ICommand EditLatencyTargetCommand => new RelayCommand(_ => EditLatencyTargetAction().ConfigureAwait(false), + _ => SelectedLatencyTarget != null); + + /// + /// Gets the command to delete the selected target. + /// + public ICommand DeleteLatencyTargetCommand => new RelayCommand( + _ => DeleteLatencyTargetAction().ConfigureAwait(false), _ => SelectedLatencyTarget != null); + + private Task AddLatencyTargetAction() + { + return ShowLatencyTargetDialog(Strings.AddTarget, null, + target => SettingsManager.Current.Dashboard_LatencyTargets.Add(target)); + } + + private Task EditLatencyTargetAction() + { + var selected = SelectedLatencyTarget; + + // Replaced at the same position (the order of the widget stays) + return ShowLatencyTargetDialog(Strings.EditTarget, selected, target => + { + var targets = SettingsManager.Current.Dashboard_LatencyTargets; + var index = targets.IndexOf(selected); + + // Deleted meanwhile (e.g. the settings were replaced): not added again, the list may be full + if (index < 0) + return; + + targets[index] = target; + + SelectedLatencyTarget = target; + }); + } + + private async Task DeleteLatencyTargetAction() + { + var target = SelectedLatencyTarget; + + // Prefixed with "- " like the bulleted list of other deletes (see DialogHelper.FormatItemList) + var item = string.IsNullOrWhiteSpace(target.Name) ? target.Host : $"{target.Name} ({target.Host})"; + + var result = await DialogHelper.ShowConfirmationMessageAsync(Application.Current.MainWindow, + Strings.DeleteTarget, string.Format(Strings.DeleteTargetMessage, $"- {item}"), ChildWindowIcon.Info, + Strings.Delete); + + if (!result) + return; + + SettingsManager.Current.Dashboard_LatencyTargets.Remove(target); + } + + /// + /// Shows the dialog to add or edit a target. + /// + /// Title of the dialog. + /// Target to edit, null to add one. + /// Saves the target of the dialog. + private static async Task ShowLatencyTargetDialog(string title, LatencyTargetInfo target, + Action save) + { + var childWindow = new LatencyTargetChildWindow(); + + var childWindowViewModel = new LatencyTargetDialogViewModel(instance => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + + save(instance.ToTarget()); + }, _ => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + }, target); + + childWindow.Title = title; + childWindow.DataContext = childWindowViewModel; + + ConfigurationManager.Current.IsChildWindowOpen = true; + + await Application.Current.MainWindow.ShowChildWindowAsync(childWindow); + } + + #endregion + #region Contructor, load settings /// @@ -279,6 +551,15 @@ public DashboardSettingsViewModel() // The checks can also be enabled in the widgets (the settings view is created once) SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + + SettingsManager.Current.Dashboard_LatencyTargets.CollectionChanged += (_, _) => UpdateLatencyTargetLimit(); + UpdateLatencyTargetLimit(); + } + + private void UpdateLatencyTargetLimit() + { + IsLatencyTargetLimitReached = SettingsManager.Current.Dashboard_LatencyTargets.Count >= + GlobalStaticConfiguration.Dashboard_LatencyMaxTargets; } private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) @@ -291,6 +572,9 @@ private void SettingsManager_PropertyChanged(object sender, PropertyChangedEvent case nameof(SettingsInfo.Dashboard_CheckIPApiDNSResolver): CheckIPApiDNSResolverEnabled = SettingsManager.Current.Dashboard_CheckIPApiDNSResolver; break; + case nameof(SettingsInfo.Dashboard_CheckLatency): + CheckLatencyEnabled = SettingsManager.Current.Dashboard_CheckLatency; + break; } } @@ -301,6 +585,7 @@ private void LoadSettings() { PublicIPv4Address = SettingsManager.Current.Dashboard_PublicIPv4Address; PublicIPv6Address = SettingsManager.Current.Dashboard_PublicIPv6Address; + PingPublicIPAddressEnabled = SettingsManager.Current.Dashboard_PingPublicIPAddress; CheckPublicIPAddressEnabled = SettingsManager.Current.Dashboard_CheckPublicIPAddress; UsePublicIPv4AddressCustomAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv4AddressAPI; CustomPublicIPv4AddressAPI = SettingsManager.Current.Dashboard_CustomPublicIPv4AddressAPI; @@ -309,6 +594,11 @@ private void LoadSettings() CheckIPApiIPGeolocationEnabled = SettingsManager.Current.Dashboard_CheckIPApiIPGeolocation; CheckIPApiDNSResolverEnabled = SettingsManager.Current.Dashboard_CheckIPApiDNSResolver; ShowNetworkConnectionWidget = SettingsManager.Current.Dashboard_ShowNetworkConnectionWidget; + ShowLatencyWidget = SettingsManager.Current.Dashboard_ShowLatencyWidget; + CheckLatencyEnabled = SettingsManager.Current.Dashboard_CheckLatency; + LatencyPosition = SettingsManager.Current.Dashboard_LatencyPosition; + LatencyInterval = SettingsManager.Current.Dashboard_LatencyInterval; + LatencyPingGateway = SettingsManager.Current.Dashboard_LatencyPingGateway; ShowSpeedTestWidget = SettingsManager.Current.Dashboard_ShowSpeedTestWidget; ShowIPGeolocationWidget = SettingsManager.Current.Dashboard_ShowIPGeolocationWidget; ShowDNSResolverWidget = SettingsManager.Current.Dashboard_ShowDNSResolverWidget; diff --git a/Source/NETworkManager/ViewModels/LatencyTargetDialogViewModel.cs b/Source/NETworkManager/ViewModels/LatencyTargetDialogViewModel.cs new file mode 100644 index 0000000000..ebad1d3141 --- /dev/null +++ b/Source/NETworkManager/ViewModels/LatencyTargetDialogViewModel.cs @@ -0,0 +1,78 @@ +using System; +using System.Windows.Input; +using NETworkManager.Models.Network; +using NETworkManager.Utilities; + +namespace NETworkManager.ViewModels; + +/// +/// View model of the dialog to add or edit a target of the latency widget (Settings > Dashboard > Latency). +/// +public class LatencyTargetDialogViewModel : ViewModelBase +{ + /// + /// Initializes a new instance of the class. + /// + /// Saves the target. + /// Closes the dialog. + /// Target to edit, null to add one. + public LatencyTargetDialogViewModel(Action saveCommand, + Action cancelHandler, LatencyTargetInfo target = null) + { + SaveCommand = new RelayCommand(_ => saveCommand(this)); + CancelCommand = new RelayCommand(_ => cancelHandler(this)); + + Name = target?.Name; + Host = target?.Host; + } + + /// + /// Gets the command to save the target. + /// + public ICommand SaveCommand { get; } + + /// + /// Gets the command to close the dialog. + /// + public ICommand CancelCommand { get; } + + /// + /// Gets or sets the name shown in the widget (empty: the host). + /// + public string Name + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the IP address or host name. + /// + public string Host + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Target of the dialog. + /// + public LatencyTargetInfo ToTarget() + { + return new LatencyTargetInfo(Name?.Trim(), Host?.Trim()); + } +} diff --git a/Source/NETworkManager/ViewModels/LatencyTargetViewModel.cs b/Source/NETworkManager/ViewModels/LatencyTargetViewModel.cs new file mode 100644 index 0000000000..c0ffe8f28c --- /dev/null +++ b/Source/NETworkManager/ViewModels/LatencyTargetViewModel.cs @@ -0,0 +1,570 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Input; +using LiveChartsCore; +using LiveChartsCore.Defaults; +using LiveChartsCore.Drawing; +using LiveChartsCore.Kernel.Sketches; +using LiveChartsCore.SkiaSharpView; +using log4net; +using NETworkManager.Controls; +using NETworkManager.Localization; +using NETworkManager.Localization.Resources; +using NETworkManager.Models; +using NETworkManager.Models.Network; +using NETworkManager.Settings; +using NETworkManager.Utilities; + +namespace NETworkManager.ViewModels; + +/// +/// One target of the latency widget: resolves the host, pings it in a loop while the widget runs and keeps +/// the pings of the last minute for the value, the statistics and the chart. +/// +public class LatencyTargetViewModel : ViewModelBase +{ + #region Variables + + private static readonly ILog Log = LogManager.GetLogger(typeof(LatencyTargetViewModel)); + + + // Range of the interval in seconds (Settings > Dashboard > Latency) + public const int MinInterval = 1; + public const int MaxInterval = 10; + + // All times are UTC: a clock change (daylight saving time, NTP correction) doesn't move the time window + + /// + /// Pings in the time window (), the oldest + /// first. + /// + private readonly List _samples = []; + + /// + /// Values of the chart (round-trip time, null for a lost ping: a gap in the line). + /// + private readonly ObservableCollection _chartValues = []; + + /// + /// X axis of the chart, the time window up to now. + /// + private readonly DateTimeAxis _xAxis = new(TimeSpan.FromSeconds(1), _ => string.Empty) { IsVisible = false }; + + /// + /// Gets the name of the target (the host if no name is configured). + /// + public string Name { get; } + + /// + /// Gets the host name or IP address of the target ("Gateway" for the default gateway, see + /// ). + /// + public string Host { get; } + + /// + /// Gets the target of the settings (the widget keeps the target when the list changes and it is the same), + /// null for the default gateway. + /// + public LatencyTargetInfo Info { get; } + + /// + /// Gets a value indicating whether the default gateway is pinged (setting Dashboard_LatencyPingGateway, + /// detected when the pings start, see ). + /// + public bool IsGateway => Info == null; + + /// + /// Gets the pinged IP address (resolved from the host), null before it is resolved. + /// + public string ResolvedIPAddress + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the value shown in the widget: the round-trip time of the last ping, the status of a failed ping or + /// -/-. + /// + public string Value + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = "-/-"; + + /// + /// Gets the status of the target (dot in front of the name). + /// + public StatusLevel StatusLevel + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the error why the target is not pinged (the host name could not be resolved), null otherwise. + /// + public string ErrorMessage + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the statistics of the pings in the time window (tooltip). + /// + public LatencyStatisticsInfo Statistics + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = LatencyStatistics.Calculate([]); + + /// + /// Gets the series of the chart. + /// + public ISeries[] Series { get; } + + /// + /// Gets the X axis of the chart. + /// + public ICartesianAxis[] XAxes { get; } + + /// + /// Gets the Y axis of the chart (from 0 ms). + /// + public ICartesianAxis[] YAxes { get; } = [new Axis { IsVisible = false, MinLimit = 0 }]; + + #endregion + + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + /// Target of the settings, null for the default gateway. + public LatencyTargetViewModel(LatencyTargetInfo info) + { + Info = info; + Host = IsGateway ? Strings.Gateway : info.Host?.Trim(); + Name = IsGateway || string.IsNullOrWhiteSpace(info.Name) ? Host : info.Name.Trim(); + + XAxes = [_xAxis]; + + Series = + [ + new LineSeries + { + Name = Name, + Values = _chartValues, + GeometrySize = 0, + LineSmoothness = 0.3, + DataPadding = new LvcPoint(0, 0), + Stroke = ChartColors.LineStroke(ChartColors.Primary), + Fill = ChartColors.AreaFill(ChartColors.Primary) + } + ]; + + UpdateXAxis(DateTime.UtcNow); + } + + #endregion + + #region ICommands & Actions + + /// + /// Gets the command to open the host in another tool (context menu, parameter: ). + /// + public ICommand OpenCommand => new RelayCommand(parameter => + { + if (parameter is ApplicationName application && Target != null) + NavigationManager.Open(application, Target); + }, _ => Target != null); + + /// + /// Gets the command to copy the host. + /// + public ICommand CopyCommand => new RelayCommand(_ => ClipboardHelper.SetClipboard(Target), _ => Target != null); + + /// + /// Host that is opened / copied: the host, or the detected IP address of the gateway (null before it is + /// detected). + /// + private string Target => IsGateway ? ResolvedIPAddress : Host; + + #endregion + + #region Methods + + /// + /// Resolves the host and pings it until the token is canceled. + /// + /// Keep the pings of the last minute (resumed after a pause, e.g. another tool was + /// shown): the pause is a gap in the chart and doesn't count as lost pings. Otherwise they are removed (e.g. + /// after a network change the latencies of another route would be mixed). + /// Stops the pings (dashboard hidden, check disabled, network changed). + public async Task RunAsync(bool keepHistory, CancellationToken cancellationToken) + { + if (keepHistory) + ResumeHistory(); + else + ClearHistory(); + + try + { + var ipAddress = await ResolveAsync(cancellationToken); + + // Not resolved (e.g. the DNS server of a new network is not reachable yet right after a network change): + // try again until it works, 5, 15, 30 s, then every minute (the error is shown meanwhile) + for (var failedAttempts = 1; ipAddress == null; failedAttempts++) + { + await Task.Delay(LatencyStatistics.GetRetryDelay(failedAttempts), cancellationToken); + + ipAddress = await ResolveAsync(cancellationToken); + } + + var buffer = new byte[GlobalStaticConfiguration.Dashboard_PingBuffer]; + + while (!cancellationToken.IsCancellationRequested) + { + PingInfo pingInfo; + + try + { + // Continues on the UI thread (the values are bound) + pingInfo = await PingProbe.PingAsync(ipAddress, GlobalStaticConfiguration.Dashboard_PingTimeout, 1, + buffer, cancellationToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // An unexpected error is a failed ping: the loop goes on (the task is not awaited by anyone) + Log.Error($"Latency: ping of {ipAddress} failed.", ex); + pingInfo = new PingInfo(DateTime.UtcNow, ipAddress, System.Net.NetworkInformation.IPStatus.Unknown); + } + + if (cancellationToken.IsCancellationRequested) + return; + + AddSample(new LatencySample(DateTime.UtcNow, pingInfo.Status == System.Net.NetworkInformation.IPStatus.Success, + pingInfo.Time), pingInfo.Status); + + // Range of the settings (a value edited in the settings file: no tight loop, no invalid delay) + await Task.Delay(TimeSpan.FromSeconds(Math.Clamp(SettingsManager.Current.Dashboard_LatencyInterval, + MinInterval, MaxInterval)), cancellationToken); + } + } + catch (OperationCanceledException) + { + // Stopped + } + catch (Exception ex) + { + // Not expected (ping and lookup errors are handled above): the task is not awaited by anyone, so log it + // instead of losing it - this target stops until the pings start again (e.g. the dashboard is shown again) + Log.Error($"Latency: pinging {Host} stopped.", ex); + } + } + + /// + /// Resolves the host name with the DNS settings of the application (an IP address is used as it is). + /// + /// IP address, null if the host name could not be resolved (the error is shown). + private async Task ResolveAsync(CancellationToken cancellationToken) + { + if (IsGateway) + return await DetectGatewayAsync(cancellationToken); + + if (IPAddress.TryParse(Host, out var ipAddress)) + { + ResolvedIPAddress = ipAddress.ToString(); + return ipAddress; + } + + string error; + + try + { + var dnsResult = await DNSClientHelper.ResolveAorAaaaAsync(Host, + SettingsManager.Current.Network_ResolveHostnamePreferIPv4); + + cancellationToken.ThrowIfCancellationRequested(); + + if (!dnsResult.HasError) + { + ErrorMessage = null; + ResolvedIPAddress = dnsResult.Value.ToString(); + + // Status from the pings of the time window again (not red until the next ping) + UpdateStatistics(); + + return dnsResult.Value; + } + + error = DNSClientHelper.FormatDNSClientResultError(Host, dnsResult); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // E.g. the DNS client is not configured: an error like a failed lookup (the task is not awaited by anyone) + Log.Error($"Latency: resolving {Host} failed.", ex); + + error = string.Format(Strings.CouldNotResolveIPAddressFor, Host); + } + + // Stopped meanwhile (the lookup can't be canceled): a new run may already use this target, its values stay + cancellationToken.ThrowIfCancellationRequested(); + + // Resolved again later (see RunAsync); no IP address, value, statistics or chart of an earlier run next to the + // error (e.g. resumed after a pause while the DNS server doesn't work) + ClearHistory(); + + ErrorMessage = error; + StatusLevel = StatusLevel.Error; + + Log.Warn($"Latency: {ErrorMessage}"); + + return null; + } + + /// + /// Detects the default gateway of the network adapter that is used for the internet (route to the public IPv4 + /// address of the network connection settings), like the network connection check. + /// + /// Gateway, null if there is none (e.g. a VPN without a gateway; shown as information, detected + /// again later). + private async Task DetectGatewayAsync(CancellationToken cancellationToken) + { + IPAddress gateway = null; + + try + { + var remote = IPAddress.TryParse(SettingsManager.Current.Dashboard_PublicIPv4Address, out var address) + ? address + : IPAddress.Parse(GlobalStaticConfiguration.Dashboard_PublicIPv4Address); + + gateway = await NetworkInterface.DetectGatewayBasedOnRoutingAsync(remote); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Log.Error("Latency: detecting the default gateway failed.", ex); + } + + cancellationToken.ThrowIfCancellationRequested(); + + if (gateway != null) + { + ErrorMessage = null; + ResolvedIPAddress = gateway.ToString(); + UpdateStatistics(); + + return gateway; + } + + // Not an error of the target: gray, like the network connection without a gateway (no values of the gateway + // of an earlier network) + ClearHistory(); + + ErrorMessage = Strings.ConnectionCheckReason_NoGateway; + + return null; + } + + /// + /// Adds a ping: updates the value, the status, the statistics and the chart. + /// + /// Ping. + /// Status of the ping (shown if it failed). + private void AddSample(LatencySample sample, System.Net.NetworkInformation.IPStatus status) + { + _samples.Add(sample); + _chartValues.Add(new DateTimePoint(sample.Timestamp, sample.IsSuccess ? sample.Time : null)); + + TrimToWindow(sample.Timestamp); + UpdateXAxis(sample.Timestamp); + + Value = sample.IsSuccess + ? FormatTime(sample.Time) + : ResourceTranslator.Translate(ResourceIdentifier.IPStatus, status); + + UpdateStatistics(); + } + + /// + /// Continues after a pause: removes the pings older than the time window and ends the line of the chart at the + /// last ping (a gap until the next one). The last value stays until the next ping, unless it is outside the + /// window. + /// + private void ResumeHistory() + { + var now = DateTime.UtcNow; + + ErrorMessage = null; + + TrimToWindow(now); + + if (_chartValues.Count > 0 && _chartValues[^1].Value != null) + _chartValues.Add(new DateTimePoint(_chartValues[^1].DateTime.AddMilliseconds(1), null)); + + UpdateXAxis(now); + + if (_samples.Count == 0) + Value = "-/-"; + + UpdateStatistics(); + } + + /// + /// Removes the pings and chart points older than the time window. + /// + private void TrimToWindow(DateTime now) + { + var window = GlobalStaticConfiguration.Dashboard_LatencyWindow; + + LatencyStatistics.RemoveOutdated(_samples, now, window); + + // Keep one point before the window, so the line starts at the left edge + while (_chartValues.Count > 1 && _chartValues[1].DateTime < now - window) + _chartValues.RemoveAt(0); + } + + /// + /// Updates the status dot and the statistics from the pings in the time window. + /// + private void UpdateStatistics() + { + StatusLevel = LatencyStatistics.GetState(_samples) switch + { + LatencyState.Ok => StatusLevel.Success, + LatencyState.Lost => StatusLevel.Warning, + LatencyState.Failed => StatusLevel.Error, + _ => StatusLevel.None + }; + + Statistics = LatencyStatistics.Calculate(_samples); + } + + /// + /// Shows samples without pinging (screenshot mode). + /// + /// Pings, the oldest first. + public void SetSamples(IEnumerable samples) + { + ClearHistory(); + + // Host is "Gateway" for the gateway: a sample IP address to open / copy (context menu) + ResolvedIPAddress = IsGateway ? ScreenshotData.RouterIPv4 : Host; + + foreach (var sample in samples) + AddSample(sample, sample.IsSuccess + ? System.Net.NetworkInformation.IPStatus.Success + : System.Net.NetworkInformation.IPStatus.TimedOut); + } + + /// + /// Applies the chart colors of the current theme. + /// + public void ApplyChartColors() + { + if (Series[0] is not LineSeries series) + return; + + series.Stroke = ChartColors.LineStroke(ChartColors.Primary); + series.Fill = ChartColors.AreaFill(ChartColors.Primary); + } + + /// + /// Text of the copy all button: name, host, IP address, last value and statistics. The host and the IP address + /// are only added if they differ from the name (a target without a name, the gateway). + /// + public string ToCopyText() + { + var details = new List(); + + // The host of the gateway is its name, a target without a name is named after its host + if (!IsGateway && Host != Name) + details.Add(Host); + + if (ResolvedIPAddress != null && ResolvedIPAddress != Host) + details.Add(ResolvedIPAddress); + + var label = details.Count == 0 ? Name : $"{Name} ({string.Join(", ", details)})"; + var value = ErrorMessage ?? Value; + var stats = Statistics; + + return stats.Count == 0 + ? $"{label}: {value}" + : $"{label}: {value} - {Strings.Minimum} {FormatTime(stats.Minimum)}, " + + $"{Strings.AverageTime} {FormatTime(stats.Average)}, " + + $"{Strings.Maximum} {FormatTime(stats.Maximum)}, " + + $"{Strings.PacketLoss} {stats.PacketLoss.ToString("F0", CultureInfo.CurrentCulture)} %"; + } + + // Like the tooltip (LatencyTimeToStringConverter): "<1 ms" for the gateway + private static string FormatTime(double? milliseconds) => LatencyStatistics.FormatTime(milliseconds); + + /// + /// Moves the X axis to the time window up to . + /// + private void UpdateXAxis(DateTime now) + { + _xAxis.MinLimit = (now - GlobalStaticConfiguration.Dashboard_LatencyWindow).Ticks; + _xAxis.MaxLimit = now.Ticks; + } + + /// + /// Removes the pings, the value, the status and the error (e.g. the check was disabled). + /// + public void ClearHistory() + { + _samples.Clear(); + _chartValues.Clear(); + UpdateXAxis(DateTime.UtcNow); + + Value = "-/-"; + StatusLevel = StatusLevel.None; + ErrorMessage = null; + ResolvedIPAddress = null; + Statistics = LatencyStatistics.Calculate([]); + } + + #endregion +} diff --git a/Source/NETworkManager/ViewModels/LatencyWidgetViewModel.cs b/Source/NETworkManager/ViewModels/LatencyWidgetViewModel.cs new file mode 100644 index 0000000000..dd7e2f023f --- /dev/null +++ b/Source/NETworkManager/ViewModels/LatencyWidgetViewModel.cs @@ -0,0 +1,281 @@ +using System; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Linq; +using System.Threading; +using System.Windows.Input; +using NETworkManager.Models.Network; +using NETworkManager.Settings; +using NETworkManager.Utilities; + +namespace NETworkManager.ViewModels; + +/// +/// View model for the latency widget: pings its targets live while the dashboard is shown. The +/// dashboard starts and stops it (, ). +/// +public class LatencyWidgetViewModel : ViewModelBase +{ + #region Variables + + /// + /// Stops the pings of the targets, null while the widget doesn't run. + /// + private CancellationTokenSource _cancellationTokenSource; + + /// + /// The network changed while the widget didn't run: the next start removes the pings of the last minute. + /// + private bool _isHistoryOutdated; + + /// + /// Gets the configured targets (a target without a host is not shown). + /// + public ObservableCollection Targets { get; } = []; + + /// + /// Target list of the settings whose changes are followed, see . + /// + private ObservableCollection _subscribedTargets; + + /// + /// Gets the number of targets per line when they are side by side (own row): up to 3. + /// + public int WideColumns + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = 1; + + /// + /// Gets a value indicating whether a target is configured. + /// + public bool HasTargets + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets a value indicating whether the targets are pinged. + /// + public bool IsRunning => _cancellationTokenSource != null; + + #endregion + + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + public LatencyWidgetViewModel() + { + SubscribeTargets(); + LoadTargets(); + + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + AppearanceManager.ThemeResourcesChanged += (_, _) => + { + foreach (var target in Targets) + target.ApplyChartColors(); + }; + } + + #endregion + + #region ICommands & Actions + + /// + /// Gets the command to enable the check (setting Dashboard_CheckLatency, off by default). The + /// dashboard starts the widget when the setting changes. + /// + public ICommand EnableCheckCommand => + new RelayCommand(_ => SettingsManager.Current.Dashboard_CheckLatency = true); + + /// + /// Gets the command to open the settings of the dashboard (no targets configured). + /// + public ICommand ConfigureCommand => new RelayCommand(_ => NavigationManager.OpenSettings()); + + /// + /// Gets the command to copy the values and statistics of all targets as text. + /// + public ICommand CopyAllCommand => new RelayCommand(_ => + ClipboardHelper.SetClipboard(string.Join(System.Environment.NewLine, + Targets.Select(x => x.ToCopyText()))), + _ => HasTargets); + + #endregion + + #region Methods + + /// + /// Starts the pings of all targets (if the check is enabled). Called by the dashboard when it is shown. The pings + /// of the last minute are kept (the pause is a gap in the chart). + /// + public void Start() + { + Start(true); + } + + /// + /// Starts the pings of all targets (if the check is enabled). + /// + /// Keep the pings of the last minute, see + /// . + private void Start(bool keepHistory) + { + if (IsRunning || !SettingsManager.Current.Dashboard_CheckLatency) + return; + + // Sample values instead of real pings + if (ScreenshotData.IsEnabled) + { + // Index in the list (without the gateway): Cloudflare, Google and Quad9 keep their sample latencies + var index = 0; + + foreach (var target in Targets) + target.SetSamples(ScreenshotData.CreateLatencySamples(target.IsGateway ? 0 : index++, + target.IsGateway)); + + return; + } + + _cancellationTokenSource = new CancellationTokenSource(); + + keepHistory &= !_isHistoryOutdated; + _isHistoryOutdated = false; + + foreach (var target in Targets) + _ = target.RunAsync(keepHistory, _cancellationTokenSource.Token); + } + + /// + /// Stops the pings (dashboard hidden, window minimized, widget hidden or check disabled). + /// + public void Stop() + { + if (!IsRunning) + return; + + _cancellationTokenSource.Cancel(); + _cancellationTokenSource.Dispose(); + _cancellationTokenSource = null; + } + + /// + /// Starts again if it runs: the host names are resolved again and the pings of the last minute are removed (e.g. + /// after a network change, the targets may be reached via another route). If it doesn't run, the next start + /// removes them. + /// + public void Restart() + { + if (!IsRunning) + { + _isHistoryOutdated = true; + return; + } + + Stop(); + Start(false); + } + + /// + /// Creates the targets from the settings: the default gateway first (if enabled), then the targets of the list. + /// + private void LoadTargets() + { + var wasRunning = IsRunning; + + Stop(); + + // Unchanged targets keep their pings of the last minute (e.g. another target was added) + var previous = Targets.ToList(); + + Targets.Clear(); + + if (SettingsManager.Current.Dashboard_LatencyPingGateway) + { + var gateway = previous.FirstOrDefault(x => x.IsGateway); + + if (gateway != null) + previous.Remove(gateway); + + Targets.Add(gateway ?? new LatencyTargetViewModel(null)); + } + + foreach (var info in SettingsManager.Current.Dashboard_LatencyTargets + .Where(x => !string.IsNullOrWhiteSpace(x.Host)) + .Take(GlobalStaticConfiguration.Dashboard_LatencyMaxTargets)) + { + var target = previous.FirstOrDefault(x => !x.IsGateway && x.Info.IsSameTarget(info)); + + if (target != null) + previous.Remove(target); + + Targets.Add(target ?? new LatencyTargetViewModel(info)); + } + + HasTargets = Targets.Count > 0; + + // Side by side: up to 3 per line, more targets in a second line + WideColumns = Math.Clamp(Targets.Count, 1, 3); + + if (wasRunning) + Start(); + } + + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + switch (e.PropertyName) + { + // Check disabled: no old values when it is enabled again (the dashboard stops the pings) + case nameof(SettingsInfo.Dashboard_CheckLatency) when !SettingsManager.Current.Dashboard_CheckLatency: + foreach (var target in Targets) + target.ClearHistory(); + break; + // The list was replaced (e.g. settings imported or reset) + case nameof(SettingsInfo.Dashboard_LatencyTargets): + SubscribeTargets(); + LoadTargets(); + break; + case nameof(SettingsInfo.Dashboard_LatencyPingGateway): + LoadTargets(); + break; + } + } + + /// + /// Follows the changes of the target list (add, edit, delete in the settings). + /// + private void SubscribeTargets() + { + if (_subscribedTargets != null) + _subscribedTargets.CollectionChanged -= Targets_CollectionChanged; + + _subscribedTargets = SettingsManager.Current.Dashboard_LatencyTargets; + _subscribedTargets.CollectionChanged += Targets_CollectionChanged; + } + + private void Targets_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + { + LoadTargets(); + } + + #endregion +} diff --git a/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs b/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs index 3459ec39d4..a09a5769b2 100644 --- a/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs +++ b/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs @@ -542,7 +542,7 @@ private static async Task PingPublicIPAddressAsync(string ipAddress, A /// /// Checks the internet connection of an address family: ping of the public IP address (setting) and the public IP - /// address API (if enabled) at the same time, see . + /// address API (each if enabled) at the same time, see . /// /// Item of the internet check (IPv4 or IPv6). /// IPv4 or IPv6. @@ -552,9 +552,11 @@ private static async Task PingPublicIPAddressAsync(string ipAddress, A private static async Task CheckInternetAsync(ConnectionCheckItem item, AddressFamily addressFamily, Task connectivityLevelTask) { - var pingTask = PingPublicIPAddressAsync(addressFamily == AddressFamily.InterNetwork - ? SettingsManager.Current.Dashboard_PublicIPv4Address - : SettingsManager.Current.Dashboard_PublicIPv6Address, addressFamily); + var pingTask = SettingsManager.Current.Dashboard_PingPublicIPAddress + ? PingPublicIPAddressAsync(addressFamily == AddressFamily.InterNetwork + ? SettingsManager.Current.Dashboard_PublicIPv4Address + : SettingsManager.Current.Dashboard_PublicIPv6Address, addressFamily) + : Task.FromResult(null); var publicIPAddressTask = SettingsManager.Current.Dashboard_CheckPublicIPAddress ? RequestPublicIPAddressAsync(addressFamily) @@ -566,6 +568,9 @@ private static async Task CheckInternetAsync(ConnectionCheckItem item var publicIPAddress = publicIPAddressTask.Result; var isPingSuccessful = pingInfo is { Status: IPStatus.Success }; + // Not pinged (disabled): decided by the API and Windows. An invalid address in the settings counts as failed. + bool? pingResult = SettingsManager.Current.Dashboard_PingPublicIPAddress ? isPingSuccessful : null; + // Public IP address (API), otherwise the pinged address with the round-trip time var value = publicIPAddress?.IPAddress?.ToString() ?? (isPingSuccessful ? $"{pingInfo.IPAddress} ({pingInfo.Time} ms)" : "-/-"); @@ -574,7 +579,7 @@ private static async Task CheckInternetAsync(ConnectionCheckItem item // captive portal) and not the pinged address (e.g. 1.1.1.1, it is not the IP address of the user) var publicIP = publicIPAddress is { Status: PublicIPAddressCheckStatus.Success } ? publicIPAddress.IPAddress : null; - item.Complete(value, NetworkConnectionCheck.GetInternetResult(addressFamily, isPingSuccessful, + item.Complete(value, NetworkConnectionCheck.GetInternetResult(addressFamily, pingResult, publicIPAddress, connectivityLevelTask.Result), publicIP?.ToString() ?? string.Empty); return publicIP; diff --git a/Source/NETworkManager/ViewModels/WelcomeViewModel.cs b/Source/NETworkManager/ViewModels/WelcomeViewModel.cs index eb5d822bb6..2e4da2ffd6 100644 --- a/Source/NETworkManager/ViewModels/WelcomeViewModel.cs +++ b/Source/NETworkManager/ViewModels/WelcomeViewModel.cs @@ -34,6 +34,19 @@ public bool CheckForUpdatesAtStartup } } = GlobalStaticConfiguration.Update_CheckForUpdatesAtStartup; + public bool PingPublicIPAddress + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_PingPublicIPAddress; + public bool CheckPublicIPAddress { get; @@ -47,6 +60,19 @@ public bool CheckPublicIPAddress } } = GlobalStaticConfiguration.Dashboard_CheckPublicIPAddress; + public bool CheckLatency + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_CheckLatency; + public bool CheckIPApiIPGeolocation { get; diff --git a/Source/NETworkManager/Views/DashboardSettingsView.xaml b/Source/NETworkManager/Views/DashboardSettingsView.xaml index 6494d29bbe..a0ebfad850 100644 --- a/Source/NETworkManager/Views/DashboardSettingsView.xaml +++ b/Source/NETworkManager/Views/DashboardSettingsView.xaml @@ -7,7 +7,15 @@ xmlns:viewModels="clr-namespace:NETworkManager.ViewModels" xmlns:localization="clr-namespace:NETworkManager.Localization.Resources;assembly=NETworkManager.Localization" xmlns:validators="clr-namespace:NETworkManager.Validators;assembly=NETworkManager.Validators" + xmlns:converters="clr-namespace:NETworkManager.Converters;assembly=NETworkManager.Converters" + xmlns:wpfHelpers="clr-namespace:NETworkManager.Utilities.WPF;assembly=NETworkManager.Utilities.WPF" + xmlns:network="clr-namespace:NETworkManager.Models.Network;assembly=NETworkManager.Models" + xmlns:icons="clr-namespace:NETworkManager.Controls;assembly=NETworkManager.Controls" mc:Ignorable="d" d:DataContext="{d:DesignInstance viewModels:DashboardSettingsViewModel}"> + + + + @@ -33,6 +41,17 @@ Text="{x:Static localization:Strings.NetworkConnectionWidgetAndStatusWindowUseTheseSettingsMessage}" TextWrapping="Wrap" Style="{StaticResource InfoTextBlock}" /> + + + + + + + + private bool _isOutdated; + // Width the widgets of a row need to be shown side by side (2/3 + 1/3, see ArrangeRow). Otherwise the widgets of + // the row are shown one below the other with the full width. Both rows (speed test / latency, IP geolocation / DNS + // resolver) use the same width, so they switch together (from about 905 px) and the speed test and the IP + // geolocation always have the same width. Not a MinWidth of the widget: in its own row it gets the window width. + private const double FirstWidgetMinWidth = 600; // Speed test: three columns, IP geolocation: location and network + private const double SecondWidgetMinWidth = 280; // Latency: dot, name, value and a short chart per line + + /// + /// The rows are shown side by side at the current width: the layout is only arranged again when this changes, + /// not on every resize. + /// + private bool _isSideBySide; + /// /// Start of the last check, see . /// @@ -41,6 +56,14 @@ public DashboardView() // Show the widgets ApplyWidgetSettings(); + UpdateLatency(); + + // Side by side or one below the other: only when a row changes, not on every resize + StackPanelWidgets.SizeChanged += (_, e) => + { + if (e.WidthChanged && IsSideBySide(e.NewSize.Width) != _isSideBySide) + ApplyLayout(); + }; // The settings are changed while the dashboard is hidden (settings view) - check again when it is shown SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; @@ -58,6 +81,7 @@ public void OnViewVisible() // The widgets may have been shown or hidden in the settings ApplyWidgetSettings(); + UpdateLatency(); CheckWidgetsIfOutdated(); } @@ -67,8 +91,20 @@ public void OnViewVisible() /// public void OnMainWindowShown() { - if (_isViewVisible) - CheckWidgetsIfOutdated(); + if (!_isViewVisible) + return; + + CheckWidgetsIfOutdated(); + UpdateLatency(); + } + + /// + /// Called by the main window when it is minimized or hidden to the tray: the latency widget stops + /// pinging (no live values in the background). + /// + public void OnMainWindowHidden() + { + UpdateLatency(); } public void OnViewHide() @@ -76,6 +112,8 @@ public void OnViewHide() _isViewVisible = false; _viewModel.OnViewHide(); + + UpdateLatency(); } /// @@ -89,6 +127,10 @@ public void OnNetworkChanged(bool isMainWindowShown) CheckWidgets(); else _isOutdated = true; + + // Resolve the host names again and remove the history (another route, e.g. a VPN) - only while it runs, it + // starts fresh anyway when the dashboard is shown again + _latencyWidgetView?.Restart(); } /// @@ -134,6 +176,8 @@ private void ApplyWidgetSettings() _networkConnectionWidgetView = ShowWidget(ContentControlNetworkConnection, settings.Dashboard_ShowNetworkConnectionWidget, _networkConnectionWidgetView); + _latencyWidgetView = ShowWidget(ContentControlLatency, + settings.Dashboard_ShowLatencyWidget, _latencyWidgetView); _speedTestWidgetView = ShowWidget(ContentControlSpeedTest, settings.Dashboard_ShowSpeedTestWidget, _speedTestWidgetView); _ipApiIPGeolocationWidgetView = ShowWidget(ContentControlIPApiIPGeolocation, @@ -141,19 +185,37 @@ private void ApplyWidgetSettings() _ipApiDNSResolverWidgetView = ShowWidget(ContentControlIPApiDNSResolver, settings.Dashboard_ShowDNSResolverWidget, _ipApiDNSResolverWidgetView); - // IP geolocation (2/3) and DNS resolver (1/3) in one row, the remaining one spans the row - var showIPGeolocation = settings.Dashboard_ShowIPGeolocationWidget; - var showDNSResolver = settings.Dashboard_ShowDNSResolverWidget; + ApplyLayout(); + } + + /// + /// Arranges the visible widgets: side by side or one below the other (position setting, width of the dashboard) + /// and the gaps between them. + /// + private void ApplyLayout() + { + var settings = SettingsManager.Current; + + _isSideBySide = IsSideBySide(StackPanelWidgets.ActualWidth); - GridIPApi.Visibility = showIPGeolocation || showDNSResolver ? Visibility.Visible : Visibility.Collapsed; + // Next to the speed test (right, 1/3) if the dashboard is wide enough, otherwise its own row below the speed + // test. Own row: above the speed test (below the network connection). + var isNextToSpeedTest = settings.Dashboard_LatencyPosition == LatencyPosition.OwnRow + ? ArrangeRow(GridSpeedTestLatency, ContentControlLatency, ContentControlSpeedTest, false) + : ArrangeRow(GridSpeedTestLatency, ContentControlSpeedTest, ContentControlLatency, + _isSideBySide); - Grid.SetColumnSpan(ContentControlIPApiIPGeolocation, showDNSResolver ? 3 : 5); - Grid.SetColumn(ContentControlIPApiDNSResolver, showIPGeolocation ? 4 : 0); - Grid.SetColumnSpan(ContentControlIPApiDNSResolver, showIPGeolocation ? 1 : 5); + // Next to the speed test the targets are always one below the other (not decided by the width of the widget: + // 1/3 of a maximized window is wide enough for them side by side) + _latencyWidgetView?.SetNextToOtherWidget(isNextToSpeedTest); + + // IP geolocation (2/3) and DNS resolver (1/3) side by side if the dashboard is wide enough (the DNS resolver + // is too narrow otherwise), the remaining one spans the row + ArrangeRow(GridIPApi, ContentControlIPApiIPGeolocation, ContentControlIPApiDNSResolver, _isSideBySide); // Gap of 10 between the visible widgets (not below the last one, the scroll viewer has a margin of 10) var visibleWidgets = new FrameworkElement[] - { ContentControlNetworkConnection, ContentControlSpeedTest, GridIPApi } + { ContentControlNetworkConnection, GridSpeedTestLatency, GridIPApi } .Where(x => x.Visibility == Visibility.Visible) .ToList(); @@ -163,6 +225,77 @@ private void ApplyWidgetSettings() EmptyStateMessageNoWidgets.Visibility = visibleWidgets.Count == 0 ? Visibility.Visible : Visibility.Collapsed; } + /// + /// The widgets of a row fit side by side at the width of the dashboard: the first one in 2/3 and the second + /// one in 1/3 of the width (columns * 10 * 10 * of the row). + /// + /// Width of the dashboard (the widgets). + private static bool IsSideBySide(double width) + { + var column = (width - 20) / 3; + + return 2 * column + 10 >= FirstWidgetMinWidth && column >= SecondWidgetMinWidth; + } + + /// + /// Arranges two widgets of a row (grid with 5 columns: 2/3, gap, 1/3 and 2 rows): side by side if both are shown + /// and , otherwise one below the other with the full width (gap of 10). A hidden + /// widget leaves no space; the row is hidden if both are. + /// + /// Grid of the row. + /// Left (2/3) or upper widget. + /// Right (1/3) or lower widget. + /// Show the widgets side by side (if both are shown). + /// true if the widgets are shown side by side. + private static bool ArrangeRow(FrameworkElement row, FrameworkElement first, FrameworkElement second, + bool sideBySide) + { + var showFirst = first.Visibility == Visibility.Visible; + var showSecond = second.Visibility == Visibility.Visible; + + row.Visibility = showFirst || showSecond ? Visibility.Visible : Visibility.Collapsed; + + var isSideBySide = sideBySide && showFirst && showSecond; + + Grid.SetRow(first, 0); + Grid.SetColumn(first, 0); + Grid.SetColumnSpan(first, isSideBySide ? 3 : 5); + first.Margin = new Thickness(0); + + var isBelow = showFirst && !isSideBySide; + + Grid.SetRow(second, isBelow ? 1 : 0); + Grid.SetColumn(second, isSideBySide ? 4 : 0); + Grid.SetColumnSpan(second, isSideBySide ? 1 : 5); + second.Margin = new Thickness(0, isBelow ? 10 : 0, 0, 0); + + return isSideBySide; + } + + /// + /// Starts the pings of the latency widget while it is shown and enabled, the dashboard is the selected + /// application and the main window is shown (not minimized, not in the tray); stops them otherwise. + /// + private void UpdateLatency() + { + var settings = SettingsManager.Current; + + if (_isViewVisible && IsMainWindowShown() && settings.Dashboard_ShowLatencyWidget && + settings.Dashboard_CheckLatency) + _latencyWidgetView?.Start(); + else + _latencyWidgetView?.Stop(); + } + + /// + /// The main window is shown (not minimized, not hidden to the tray). + /// + private static bool IsMainWindowShown() + { + return Application.Current?.MainWindow is not { } window || + (window.IsVisible && window.WindowState != WindowState.Minimized); + } + /// /// Shows or hides a widget. The view of the widget is created when it is shown the first time. /// @@ -193,6 +326,7 @@ private void ApplyWidgetSettings() [ nameof(SettingsInfo.Dashboard_PublicIPv4Address), nameof(SettingsInfo.Dashboard_PublicIPv6Address), + nameof(SettingsInfo.Dashboard_PingPublicIPAddress), nameof(SettingsInfo.Dashboard_CheckPublicIPAddress), nameof(SettingsInfo.Dashboard_UseCustomPublicIPv4AddressAPI), nameof(SettingsInfo.Dashboard_CustomPublicIPv4AddressAPI), @@ -214,6 +348,11 @@ private void SettingsManager_PropertyChanged(object sender, PropertyChangedEvent if (e.PropertyName != null && CheckSettings.Contains(e.PropertyName) && !isEnabledInWidget) _isOutdated = true; + // Latency: start / stop right away (e.g. the "Enable" button of the widget, or hidden in the settings) + if (e.PropertyName is nameof(SettingsInfo.Dashboard_ShowLatencyWidget) + or nameof(SettingsInfo.Dashboard_CheckLatency)) + UpdateLatency(); + // A hidden speed test widget doesn't measure (no data is transferred in the background): cancel it right away, // the dashboard is hidden while the settings are open if (e.PropertyName == nameof(SettingsInfo.Dashboard_ShowSpeedTestWidget) && diff --git a/Source/NETworkManager/Views/LatencyTargetChildWindow.xaml b/Source/NETworkManager/Views/LatencyTargetChildWindow.xaml new file mode 100644 index 0000000000..d32a2cc362 --- /dev/null +++ b/Source/NETworkManager/Views/LatencyTargetChildWindow.xaml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +