using System.Drawing.Drawing2D; namespace UCVL.VPNPlus; // Reads only existing proxy-outbound counters; never the physical adapter. internal sealed class TrafficChart : Control { private readonly TrafficChartTimeline _timeline; private TimeSpan _period = TimeSpan.FromMinutes(5); internal int PeriodMinutes => (int)_period.TotalMinutes; internal int PointCount => _timeline.PointCount; internal int VisiblePointCount => VisiblePoints().Length; internal bool HasFreshSample => _timeline.HasFreshSample; internal DateTimeOffset? LastSampleAt => _timeline.LastSampleAt; internal DateTimeOffset TimelineEnd => _timeline.End; internal void SetPeriodMinutes(int minutes) { if (minutes is not (1 or 5 or 15 or 60)) throw new ArgumentOutOfRangeException(nameof(minutes)); _period = TimeSpan.FromMinutes(minutes); Invalidate(); } private TrafficChartTimeline.Sample[] VisiblePoints() => _timeline.Visible(_period); internal TrafficChart(Func? clock = null) { _timeline = new TrafficChartTimeline(clock); DoubleBuffered = true; SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.Opaque, false); BackColor = Color.Transparent; Font = Brand.Font(7.3f); } internal void Add(double up, double down, DateTimeOffset? time = null) { _timeline.Add(up, down, time); Invalidate(); } // Called by the existing sampling timer even when the reader is busy or // returns no counters. Neither method invents a zero-speed sample or bytes. internal void AdvanceClock(DateTimeOffset? now = null) { _timeline.AdvanceClock(now); Invalidate(); } internal void MarkUnavailable(DateTimeOffset? now = null) { _timeline.MarkUnavailable(now); Invalidate(); } internal void Reset() { _timeline.Reset(); Invalidate(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); _timeline.AdvanceClock(); var points = VisiblePoints(); var peak = points.Length == 0 ? 1024 : Math.Max(1024, points.Max(p => Math.Max(p.Up, p.Down))); var chart = ChartAxis.Draw(e.Graphics, ClientRectangle, Font, DeviceDpi, peak, speed: true); if (chart.Plot.Width < 1 || chart.Plot.Height < 1) return; var end = _timeline.End; ChartAxis.TimeLabels(e.Graphics, chart.Plot, Font, [end.Subtract(_period).ToString("HH:mm"), end.Subtract(_period / 2).ToString("HH:mm"), end.ToString("HH:mm")]); if (points.Length == 0) { TextRenderer.DrawText(e.Graphics, LastSampleAt.HasValue ? "采样暂不可用" : "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted, ChartAxis.PaintFlags | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); return; } foreach (var segment in points.GroupBy(point => point.Segment)) { var samples = segment.ToArray(); PointF[] Line(bool up) => samples.Select(p => new PointF( chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / _period.TotalSeconds, 0, 1) * chart.Plot.Width, chart.Plot.Bottom - (float)((up ? p.Up : p.Down) / chart.Maximum) * chart.Plot.Height)).ToArray(); ChartAxis.Curve(e.Graphics, Line(true), Brand.RoyalBlue, DeviceDpi, dots: samples.Length == 1); ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: samples.Length == 1); } if (!HasFreshSample) TextRenderer.DrawText(e.Graphics, "采样暂不可用", Font, Rectangle.Round(chart.Plot), Brand.Muted, ChartAxis.PaintFlags | TextFormatFlags.Right | TextFormatFlags.Top | TextFormatFlags.SingleLine); } } // Pure presentation history: no proxy/adapter reads, cumulative byte totals or // timers. An injected clock makes missing-sample behavior deterministic in tests. internal sealed class TrafficChartTimeline { internal readonly record struct Sample(DateTimeOffset Time, double Up, double Down, long Segment); internal static readonly TimeSpan MaximumSampleAge = TimeSpan.FromSeconds(15); private static readonly TimeSpan Retention = TimeSpan.FromMinutes(60); private readonly Queue _points = new(); private readonly Func _clock; private DateTimeOffset? _end, _lastSampleAt; private bool _gapPending, _unavailable = true; private long _segment; internal TrafficChartTimeline(Func? clock = null) => _clock = clock ?? (() => DateTimeOffset.Now); internal int PointCount => _points.Count; internal DateTimeOffset End => _end ?? _clock(); internal DateTimeOffset? LastSampleAt => _lastSampleAt; internal bool HasFreshSample => !_unavailable && _lastSampleAt is { } last && End - last <= MaximumSampleAge; private void MoveEnd(DateTimeOffset at) { if (!_end.HasValue || at > _end.Value) _end = at; while (_points.Count > 3600 || (_points.Count > 0 && End - _points.Peek().Time > Retention)) _points.Dequeue(); } internal void AdvanceClock(DateTimeOffset? now = null) { MoveEnd(now ?? _clock()); if (_lastSampleAt is { } last && End - last > MaximumSampleAge) _gapPending = _unavailable = true; } internal void MarkUnavailable(DateTimeOffset? now = null) { AdvanceClock(now); _gapPending = _unavailable = true; } internal bool Add(double up, double down, DateTimeOffset? time = null) { var at = time ?? _clock(); if (!double.IsFinite(up) || !double.IsFinite(down) || up < 0 || down < 0) { MarkUnavailable(at); return false; } // Late/duplicate callbacks must not move the axis backwards, inject a // second point or turn a newer good sample into an unavailable one. if (_lastSampleAt is { } previous && at <= previous) return false; if (_lastSampleAt is { } last && (_gapPending || at - last > MaximumSampleAge)) _segment++; _points.Enqueue(new Sample(at, up, down, _segment)); _lastSampleAt = at; _gapPending = _unavailable = false; MoveEnd(at); return true; } internal Sample[] Visible(TimeSpan period) => _points.Where(point => End - point.Time <= period).ToArray(); internal void Reset() { _points.Clear(); _end = _lastSampleAt = null; _gapPending = false; _unavailable = true; _segment = 0; } } internal static class ChartAxis { internal const TextFormatFlags PaintFlags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping; internal static (RectangleF Plot, double Maximum) Draw(Graphics g, Rectangle bounds, Font font, int dpi, double peak, bool speed) { var scale = dpi / 96f; var unit = peak >= 1024d * 1024 * 1024 ? 1024d * 1024 * 1024 : peak >= 1024d * 1024 ? 1024d * 1024 : peak >= 1024 ? 1024d : 1d; var unitName = unit >= 1024d * 1024 * 1024 ? "GB" : unit >= 1024d * 1024 ? "MB" : unit >= 1024 ? "KB" : "B"; var raw = Math.Max(1, peak / unit) * 1.15; var power = Math.Pow(10, Math.Floor(Math.Log10(raw))); var normal = raw / power; var maximum = (normal <= 1 ? 1 : normal <= 2 ? 2 : normal <= 2.5 ? 2.5 : normal <= 5 ? 5 : 10) * power; var fontHeight = TextRenderer.MeasureText(g, "0", font).Height; var left = Math.Max(31 * scale, TextRenderer.MeasureText(g, maximum.ToString("0.#"), font).Width + 5 * scale); var plot = new RectangleF(left, fontHeight + 1, Math.Max(1, bounds.Width - left - 9 * scale), Math.Max(1, bounds.Height - fontHeight * 2 - 7 * scale)); g.SmoothingMode = SmoothingMode.AntiAlias; TextRenderer.DrawText(g, unitName + (speed ? "/s" : ""), font, new Rectangle(0, 0, bounds.Width, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding); using var grid = new Pen(Color.FromArgb(218, 230, 245), Math.Max(1, scale * .6f)) { DashStyle = DashStyle.Dash }; for (var i = 0; i <= 2; i++) { var y = plot.Bottom - plot.Height * i / 2; g.DrawLine(grid, plot.Left, y, plot.Right, y); TextRenderer.DrawText(g, (maximum * i / 2).ToString("0.#"), font, new Rectangle(0, (int)y - fontHeight / 2, (int)left - 4, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.Right | TextFormatFlags.NoPadding); } for (var i = 0; i <= 6; i++) { var x = plot.Left + plot.Width * i / 6; g.DrawLine(grid, x, plot.Top, x, plot.Bottom); } return (plot, maximum * unit); } internal static void TimeLabels(Graphics g, RectangleF plot, Font font, string[] labels) { for (var i = 0; i < labels.Length; i++) { var width = TextRenderer.MeasureText(g, labels[i], font).Width; var x = plot.Left + i * plot.Width / Math.Max(1, labels.Length - 1); // Align edge labels inside the chart rather than cutting their final digits. var left = i == 0 ? x : i == labels.Length - 1 ? x - width : x - width / 2; TextRenderer.DrawText(g, labels[i], font, new Point((int)left, (int)plot.Bottom + 3), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding); } } internal static void Curve(Graphics g, PointF[] points, Color color, int dpi, bool dots) { if (points.Length == 0) return; var scale = dpi / 96f; using var pen = new Pen(color, 1.8f * scale) { LineJoin = LineJoin.Round }; if (points.Length > 1) g.DrawLines(pen, points); if (!dots) return; using var brush = new SolidBrush(color); var radius = 2.5f * scale; foreach (var p in points) g.FillEllipse(brush, p.X - radius, p.Y - radius, radius * 2, radius * 2); } }