From fc6f161d5a4ab53673a8aa2d9b341ad26d96164c Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:39:09 +0100 Subject: [PATCH 01/55] Feature: Dashboard: Latency statistics for the internet latency widget (L1) Samples of a ping target with the state (ok, lost ping in the time window, failed), min / avg / max / packet loss and the removal of samples older than the time window. Unit tests. Co-Authored-By: Claude Opus 5.5 --- .../Network/LatencyStatistics.cs | 110 ++++++++++++++++++ .../Network/LatencyStatisticsTests.cs | 94 +++++++++++++++ 2 files changed, 204 insertions(+) create mode 100644 Source/NETworkManager.Models/Network/LatencyStatistics.cs create mode 100644 Source/NETworkManager.Tests/Network/LatencyStatisticsTests.cs diff --git a/Source/NETworkManager.Models/Network/LatencyStatistics.cs b/Source/NETworkManager.Models/Network/LatencyStatistics.cs new file mode 100644 index 0000000000..65da406d70 --- /dev/null +++ b/Source/NETworkManager.Models/Network/LatencyStatistics.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace NETworkManager.Models.Network; + +/// +/// Result of one ping of a latency target (internet latency widget of the dashboard). +/// +/// Time of the ping. +/// 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; + } + + /// + /// 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.Tests/Network/LatencyStatisticsTests.cs b/Source/NETworkManager.Tests/Network/LatencyStatisticsTests.cs new file mode 100644 index 0000000000..b2434773f7 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/LatencyStatisticsTests.cs @@ -0,0 +1,94 @@ +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)])); + } + + [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); + } +} From bfb82c37c500cda352f4b2cef1fa15df96370f85 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:39:52 +0100 Subject: [PATCH 02/55] Feature: Dashboard: Settings and strings of the internet latency widget (L2) Dashboard_ShowInternetLatencyWidget (shown), Dashboard_CheckInternetLatency (off, opt-in), Dashboard_InternetLatencyInterval (2 s) and three targets (name + host): Cloudflare 1.1.1.1, Google 8.8.8.8, Quad9 9.9.9.9. Time window of the chart / statistics 60 s. Co-Authored-By: Claude Opus 5.5 --- .../Resources/Strings.Designer.cs | 82 ++++++++++++ .../Resources/Strings.resx | 28 +++++ .../GlobalStaticConfiguration.cs | 16 ++- .../NETworkManager.Settings/SettingsInfo.cs | 117 ++++++++++++++++++ 4 files changed, 242 insertions(+), 1 deletion(-) diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 60163118bd..4f19bcaf0e 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -2161,6 +2161,15 @@ public static string CheckingWPSDots { } } + /// + /// Looks up a localized string similar to Check internet latency. + /// + public static string CheckInternetLatency { + get { + return ResourceManager.GetString("CheckInternetLatency", resourceCulture); + } + } + /// /// Looks up a localized string similar to Check IP geolocation. /// @@ -6341,6 +6350,15 @@ public static string HelpMessage_CheckForUpdatesAtStartup { } } + /// + /// Looks up a localized string similar to Pings the targets only while the dashboard is shown (not in the background, not while the window is minimized or in the tray).. + /// + public static string HelpMessage_CheckInternetLatency { + get { + return ResourceManager.GetString("HelpMessage_CheckInternetLatency", resourceCulture); + } + } + /// /// Looks up a localized string similar to The IP geolocation is determined via ip-api.com. /// @@ -6446,6 +6464,15 @@ public static string HelpMessage_GuessTheOperatingSystemFromTheTTL { } } + /// + /// 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_InternetLatencyInterval { + get { + return ResourceManager.GetString("HelpMessage_InternetLatencyInterval", resourceCulture); + } + } + /// /// Looks up a localized string similar to Number of backups that are retained before the oldest one is deleted.. /// @@ -6701,6 +6728,15 @@ public static string HelpMessage_ScanForNetBIOS { } } + /// + /// Looks up a localized string similar to Shows the widget on the dashboard. It only pings the targets if the check is enabled (below or with the "Enable" button of the widget). A hidden widget sends nothing.. + /// + public static string HelpMessage_ShowInternetLatencyWidget { + get { + return ResourceManager.GetString("HelpMessage_ShowInternetLatencyWidget", resourceCulture); + } + } + /// /// Looks up a localized string similar to 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.. /// @@ -7313,6 +7349,34 @@ public static string Internet { } } + /// + /// Looks up a localized string similar to Internet latency. + /// + public static string InternetLatency { + get { + return ResourceManager.GetString("InternetLatency", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Show the latency to targets on the internet (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 InternetLatencyWidgetDisabledMessage { + get { + return ResourceManager.GetString("InternetLatencyWidgetDisabledMessage", resourceCulture); + } + } + + /// + /// 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. /// @@ -9501,6 +9565,15 @@ public static string NoFirewallRulesFoundMessage { } } + /// + /// Looks up a localized string similar to No targets configured. Add them in the settings of the dashboard.. + /// + public static string NoInternetLatencyTargetsConfiguredMessage { + get { + return ResourceManager.GetString("NoInternetLatencyTargetsConfiguredMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to No LLDP or CDP packets received!. /// @@ -15007,6 +15080,15 @@ public static string Tags { } } + /// + /// Looks up a localized string similar to Target. + /// + public static string Target { + get { + return ResourceManager.GetString("Target", resourceCulture); + } + } + /// /// Looks up a localized string similar to Task Manager (Ctrl+Shift+Esc). /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index 916fdb5aff..e9293e7b9a 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5780,4 +5780,32 @@ ip-api.com receives your IP address and the IP address of your DNS server. The network connection widget and the status window use these settings to check the internet. + + Internet latency + + + Check internet latency + + + Pings the targets only while the dashboard is shown (not in the background, not while the window is minimized or in the tray). + + + Shows the widget on the dashboard. It only pings the targets if the check is enabled (below or with the "Enable" button of the widget). A hidden widget sends nothing. + + + Show the latency to targets on the internet (e.g. Cloudflare, Google and Quad9), updated live while the dashboard is shown. +The targets receive a ping (ICMP echo request) every few seconds. + + + Interval (seconds) + + + Time between the reply (or timeout) of a ping and the next ping of the target. + + + Target + + + No targets configured. Add them in the settings of the dashboard. + \ No newline at end of file diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs index 814d213686..35f66b4016 100644 --- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs +++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs @@ -139,7 +139,16 @@ public static class GlobalStaticConfiguration 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_CheckInternetLatency => false; + public static int Dashboard_InternetLatencyInterval => 2; + public static string Dashboard_InternetLatencyTarget1Name => "Cloudflare"; + public static string Dashboard_InternetLatencyTarget1Host => "1.1.1.1"; + public static string Dashboard_InternetLatencyTarget2Name => "Google"; + public static string Dashboard_InternetLatencyTarget2Host => "8.8.8.8"; + public static string Dashboard_InternetLatencyTarget3Name => "Quad9"; + public static string Dashboard_InternetLatencyTarget3Host => "9.9.9.9"; public static bool Dashboard_ShowNetworkConnectionWidget => true; + public static bool Dashboard_ShowInternetLatencyWidget => true; public static bool Dashboard_ShowSpeedTestWidget => true; public static bool Dashboard_ShowIPGeolocationWidget => true; public static bool Dashboard_ShowDNSResolverWidget => true; @@ -150,7 +159,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 internet latency widget. + /// + public static TimeSpan Dashboard_InternetLatencyWindow => TimeSpan.FromSeconds(60); + + // Ping of the gateway and the public IP address (also the targets of the internet 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..5c2c5dee7b 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -1063,6 +1063,110 @@ public bool Dashboard_CheckIPApiDNSResolver } } = GlobalStaticConfiguration.Dashboard_CheckIPApiDNSResolver; + public bool Dashboard_CheckInternetLatency + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_CheckInternetLatency; + + public int Dashboard_InternetLatencyInterval + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_InternetLatencyInterval; + + public string Dashboard_InternetLatencyTarget1Name + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_InternetLatencyTarget1Name; + + public string Dashboard_InternetLatencyTarget1Host + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_InternetLatencyTarget1Host; + + public string Dashboard_InternetLatencyTarget2Name + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_InternetLatencyTarget2Name; + + public string Dashboard_InternetLatencyTarget2Host + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_InternetLatencyTarget2Host; + + public string Dashboard_InternetLatencyTarget3Name + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_InternetLatencyTarget3Name; + + public string Dashboard_InternetLatencyTarget3Host + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_InternetLatencyTarget3Host; + public bool Dashboard_ShowNetworkConnectionWidget { get; @@ -1076,6 +1180,19 @@ public bool Dashboard_ShowNetworkConnectionWidget } } = GlobalStaticConfiguration.Dashboard_ShowNetworkConnectionWidget; + public bool Dashboard_ShowInternetLatencyWidget + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_ShowInternetLatencyWidget; + public bool Dashboard_ShowSpeedTestWidget { get; From bc2a9371c0ac993fabae905fdbd316a520ff3eae Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:43:13 +0100 Subject: [PATCH 03/55] Feature: Dashboard: Internet latency widget (L3) Up to three targets side by side: status dot, name, round-trip time of the last ping and a chart of the last 60 seconds (gaps for lost pings). Each target is resolved once (DNS settings of the application) and pinged in its own loop (timeout 2 s, then the interval). Tooltip with host, IP address, min / avg / max and packet loss of the last minute; context menu opens the host in the Ping Monitor, Traceroute or DNS Lookup. Disabled check: text + Enable button; no targets: empty state. Sample values in the screenshot mode. Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager/ScreenshotData.cs | 23 + .../InternetLatencyTargetViewModel.cs | 394 ++++++++++++++++++ .../InternetLatencyWidgetViewModel.cs | 180 ++++++++ .../Views/InternetLatencyWidgetView.xaml | 229 ++++++++++ .../Views/InternetLatencyWidgetView.xaml.cs | 38 ++ 5 files changed, 864 insertions(+) create mode 100644 Source/NETworkManager/ViewModels/InternetLatencyTargetViewModel.cs create mode 100644 Source/NETworkManager/ViewModels/InternetLatencyWidgetViewModel.cs create mode 100644 Source/NETworkManager/Views/InternetLatencyWidgetView.xaml create mode 100644 Source/NETworkManager/Views/InternetLatencyWidgetView.xaml.cs diff --git a/Source/NETworkManager/ScreenshotData.cs b/Source/NETworkManager/ScreenshotData.cs index ec2440aeb6..f2e3b76cc9 100644 --- a/Source/NETworkManager/ScreenshotData.cs +++ b/Source/NETworkManager/ScreenshotData.cs @@ -365,4 +365,27 @@ private static IEnumerable CreateSamples(int count, double max) } #endregion + + #region Internet latency + + /// + /// Creates the pings of the last minute of an internet latency target (like the default targets Cloudflare, + /// Google and Quad9): a reply every 2 seconds with a few milliseconds of variation, ending now. + /// + /// Index of the target (0-2), each has its own latency. + public static IEnumerable CreateInternetLatencySamples(int index) + { + long[] baseTimes = [9, 8, 10]; + var baseTime = baseTimes[index % baseTimes.Length]; + var now = DateTime.Now; + + for (var i = 30; i >= 0; i--) + { + var variation = 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, Math.Max(1, baseTime + (long)variation)); + } + } + + #endregion } diff --git a/Source/NETworkManager/ViewModels/InternetLatencyTargetViewModel.cs b/Source/NETworkManager/ViewModels/InternetLatencyTargetViewModel.cs new file mode 100644 index 0000000000..c54822352d --- /dev/null +++ b/Source/NETworkManager/ViewModels/InternetLatencyTargetViewModel.cs @@ -0,0 +1,394 @@ +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 internet 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 InternetLatencyTargetViewModel : ViewModelBase +{ + #region Variables + + private static readonly ILog Log = LogManager.GetLogger(typeof(InternetLatencyTargetViewModel)); + + /// + /// 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. + /// + public string Host { get; } + + /// + /// 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. + /// + /// Name of the target, empty to show the host. + /// Host name or IP address of the target. + public InternetLatencyTargetViewModel(string name, string host) + { + Host = host; + Name = string.IsNullOrWhiteSpace(name) ? host : 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.Now); + } + + #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) + NavigationManager.Open(application, Host); + }); + + /// + /// Gets the command to copy the host. + /// + public ICommand CopyCommand => new RelayCommand(_ => ClipboardHelper.SetClipboard(Host)); + + #endregion + + #region Methods + + /// + /// Resolves the host and pings it until the token is canceled. The pings of an earlier run are removed (no + /// history while the widget doesn't run). + /// + /// Stops the pings (dashboard hidden, check disabled, network changed). + public async Task RunAsync(CancellationToken cancellationToken) + { + Clear(); + + try + { + var ipAddress = await ResolveAsync(cancellationToken); + + if (ipAddress == null) + return; + + var buffer = new byte[GlobalStaticConfiguration.Dashboard_PingBuffer]; + + while (!cancellationToken.IsCancellationRequested) + { + // Continues on the UI thread (the values are bound) + var pingInfo = await PingProbe.PingAsync(ipAddress, GlobalStaticConfiguration.Dashboard_PingTimeout, 1, + buffer, cancellationToken); + + if (cancellationToken.IsCancellationRequested) + return; + + AddSample(new LatencySample(DateTime.Now, pingInfo.Status == System.Net.NetworkInformation.IPStatus.Success, + pingInfo.Time), pingInfo.Status); + + await Task.Delay(TimeSpan.FromSeconds(SettingsManager.Current.Dashboard_InternetLatencyInterval), + cancellationToken); + } + } + catch (OperationCanceledException) + { + // Stopped + } + } + + /// + /// 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 (IPAddress.TryParse(Host, out var ipAddress)) + { + ResolvedIPAddress = ipAddress.ToString(); + return ipAddress; + } + + var dnsResult = await DNSClientHelper.ResolveAorAaaaAsync(Host, + SettingsManager.Current.Network_ResolveHostnamePreferIPv4); + + cancellationToken.ThrowIfCancellationRequested(); + + if (dnsResult.HasError) + { + // Checked again with the next start (e.g. a network change or when the dashboard is shown again) + ErrorMessage = DNSClientHelper.FormatDNSClientResultError(Host, dnsResult); + StatusLevel = StatusLevel.Error; + + Log.Warn($"Internet latency: {ErrorMessage}"); + + return null; + } + + ResolvedIPAddress = dnsResult.Value.ToString(); + + return dnsResult.Value; + } + + /// + /// 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) + { + var window = GlobalStaticConfiguration.Dashboard_InternetLatencyWindow; + + _samples.Add(sample); + LatencyStatistics.RemoveOutdated(_samples, sample.Timestamp, window); + + _chartValues.Add(new DateTimePoint(sample.Timestamp, sample.IsSuccess ? sample.Time : null)); + + // Keep one point before the window, so the line starts at the left edge + while (_chartValues.Count > 1 && _chartValues[1].DateTime < sample.Timestamp - window) + _chartValues.RemoveAt(0); + + UpdateXAxis(sample.Timestamp); + + Value = sample.IsSuccess + ? FormatTime(sample.Time) + : ResourceTranslator.Translate(ResourceIdentifier.IPStatus, status); + + 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) + { + Clear(); + + ResolvedIPAddress = 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. + /// + public string ToCopyText() + { + var host = ResolvedIPAddress == null || ResolvedIPAddress == Host ? Host : $"{Host}, {ResolvedIPAddress}"; + var value = ErrorMessage ?? Value; + var stats = Statistics; + + return stats.Count == 0 + ? $"{Name} ({host}): {value}" + : $"{Name} ({host}): {value} - {Strings.Minimum} {FormatTime(stats.Minimum)}, " + + $"{Strings.AverageTime} {FormatTime(stats.Average)}, " + + $"{Strings.Maximum} {FormatTime(stats.Maximum)}, " + + $"{Strings.PacketLoss} {stats.PacketLoss.ToString("F0", CultureInfo.CurrentCulture)} %"; + } + + private static string FormatTime(double? milliseconds) => + milliseconds.HasValue ? $"{Math.Round(milliseconds.Value).ToString(CultureInfo.CurrentCulture)} ms" : "-/-"; + + /// + /// Moves the X axis to the time window up to . + /// + private void UpdateXAxis(DateTime now) + { + _xAxis.MinLimit = (now - GlobalStaticConfiguration.Dashboard_InternetLatencyWindow).Ticks; + _xAxis.MaxLimit = now.Ticks; + } + + /// + /// Removes the pings, the value, the status and the error. + /// + private void Clear() + { + _samples.Clear(); + _chartValues.Clear(); + UpdateXAxis(DateTime.Now); + + Value = "-/-"; + StatusLevel = StatusLevel.None; + ErrorMessage = null; + Statistics = LatencyStatistics.Calculate([]); + } + + #endregion +} diff --git a/Source/NETworkManager/ViewModels/InternetLatencyWidgetViewModel.cs b/Source/NETworkManager/ViewModels/InternetLatencyWidgetViewModel.cs new file mode 100644 index 0000000000..f36f940b30 --- /dev/null +++ b/Source/NETworkManager/ViewModels/InternetLatencyWidgetViewModel.cs @@ -0,0 +1,180 @@ +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Threading; +using System.Windows.Input; +using NETworkManager.Settings; +using NETworkManager.Utilities; + +namespace NETworkManager.ViewModels; + +/// +/// View model for the internet latency widget: pings up to three targets live while the dashboard is shown. The +/// dashboard starts and stops it (, ). +/// +public class InternetLatencyWidgetViewModel : ViewModelBase +{ + #region Variables + + /// + /// Stops the pings of the targets, null while the widget doesn't run. + /// + private CancellationTokenSource _cancellationTokenSource; + + /// + /// Gets the configured targets (a target without a host is not shown). + /// + public ObservableCollection Targets { get; } = []; + + /// + /// 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 InternetLatencyWidgetViewModel() + { + 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_CheckInternetLatency, off by default). The + /// dashboard starts the widget when the setting changes. + /// + public ICommand EnableCheckCommand => + new RelayCommand(_ => SettingsManager.Current.Dashboard_CheckInternetLatency = true); + + /// + /// 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. + /// + public void Start() + { + if (IsRunning || !SettingsManager.Current.Dashboard_CheckInternetLatency) + return; + + // Sample values instead of real pings + if (ScreenshotData.IsEnabled) + { + foreach (var (target, index) in Targets.Select((x, i) => (x, i))) + target.SetSamples(ScreenshotData.CreateInternetLatencySamples(index)); + + return; + } + + _cancellationTokenSource = new CancellationTokenSource(); + + foreach (var target in Targets) + _ = target.RunAsync(_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 history is removed (e.g. after a network + /// change, the targets may be reached via another route). + /// + public void Restart() + { + if (!IsRunning) + return; + + Stop(); + Start(); + } + + /// + /// Creates the targets from the settings. + /// + private void LoadTargets() + { + var settings = SettingsManager.Current; + + Targets.Clear(); + + foreach (var (name, host) in new[] + { + (settings.Dashboard_InternetLatencyTarget1Name, settings.Dashboard_InternetLatencyTarget1Host), + (settings.Dashboard_InternetLatencyTarget2Name, settings.Dashboard_InternetLatencyTarget2Host), + (settings.Dashboard_InternetLatencyTarget3Name, settings.Dashboard_InternetLatencyTarget3Host) + }) + { + if (!string.IsNullOrWhiteSpace(host)) + Targets.Add(new InternetLatencyTargetViewModel(name, host.Trim())); + } + + HasTargets = Targets.Count > 0; + } + + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + // A changed target: create the targets again, a running widget pings the new ones right away + if (e.PropertyName == null || !e.PropertyName.StartsWith("Dashboard_InternetLatencyTarget")) + return; + + var wasRunning = IsRunning; + + Stop(); + LoadTargets(); + + if (wasRunning) + Start(); + } + + #endregion +} diff --git a/Source/NETworkManager/Views/InternetLatencyWidgetView.xaml b/Source/NETworkManager/Views/InternetLatencyWidgetView.xaml new file mode 100644 index 0000000000..b7bce0a24a --- /dev/null +++ b/Source/NETworkManager/Views/InternetLatencyWidgetView.xaml @@ -0,0 +1,229 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/NETworkManager/Views/DashboardSettingsView.xaml.cs b/Source/NETworkManager/Views/DashboardSettingsView.xaml.cs index 7db025366d..636a7377f4 100644 --- a/Source/NETworkManager/Views/DashboardSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/DashboardSettingsView.xaml.cs @@ -1,4 +1,5 @@ -using NETworkManager.ViewModels; +using System.Windows.Input; +using NETworkManager.ViewModels; namespace NETworkManager.Views; @@ -11,4 +12,10 @@ public DashboardSettingsView() InitializeComponent(); DataContext = _viewModel; } + + private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + if (_viewModel.EditLatencyTargetCommand.CanExecute(null)) + _viewModel.EditLatencyTargetCommand.Execute(null); + } } \ No newline at end of file diff --git a/Source/NETworkManager/Views/LatencyTargetChildWindow.xaml b/Source/NETworkManager/Views/LatencyTargetChildWindow.xaml new file mode 100644 index 0000000000..ae99eefb68 --- /dev/null +++ b/Source/NETworkManager/Views/LatencyTargetChildWindow.xaml @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + +