Files
ucvl-zonghengjia-open-source/windows/TrafficChart.cs

421 lines
21 KiB
C#

using System.Drawing.Drawing2D;
namespace UCVL.VPNPlus;
internal enum TrafficChartSeries { Both, Upload, Download }
// Reads only existing proxy-outbound counters; never the physical adapter.
internal sealed class TrafficChart : Control
{
private const TextFormatFlags LabelFlags = ChartAxis.PaintFlags | TextFormatFlags.NoPadding |
TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter;
internal static readonly Color DownloadColor = Color.FromArgb(0, 106, 129);
private static readonly Color AxisText = Color.FromArgb(36, 65, 107);
private static readonly Color GridColor = Color.FromArgb(108, 130, 171, 209);
private static readonly Color AxisStroke = Color.FromArgb(136, 111, 159, 205);
private readonly TrafficChartTimeline _timeline;
private TimeSpan _period = TimeSpan.FromMinutes(5);
private TrafficChartSeries _displayedSeries;
internal TrafficChartSeries DisplayedSeries
{
get => _displayedSeries;
set
{
if (_displayedSeries == value) return;
_displayedSeries = value;
Invalidate();
}
}
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<DateTimeOffset>? clock = null)
{
_timeline = new TrafficChartTimeline(clock);
DoubleBuffered = true;
ResizeRedraw = true;
SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.Opaque, false);
BackColor = Color.Transparent;
Font = Brand.Font(7.3f);
AccessibleName = "本机代理流量趋势";
}
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 axis = ChartAxisY.Create(peak, speed: true);
var g = e.Graphics;
var scale = DeviceDpi / 96f;
g.SmoothingMode = SmoothingMode.AntiAlias;
var end = _timeline.End;
var plot = DrawAxes(g, ClientRectangle, axis, end, scale);
if (plot.IsEmpty) return;
if (points.Length == 0)
{
DrawEmptyState(g, plot, scale);
return;
}
var clip = g.Save();
g.SetClip(RectangleF.Inflate(plot, scale, scale), CombineMode.Intersect);
foreach (var segment in points.GroupBy(point => point.Segment))
{
var samples = segment.ToArray();
PointF[] Line(bool up) => samples.Select(p => new PointF(
plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / _period.TotalSeconds, 0, 1) * plot.Width,
plot.Bottom - (float)((up ? p.Up : p.Down) / axis.MaximumBytes) * plot.Height)).ToArray();
if (DisplayedSeries != TrafficChartSeries.Download)
ChartAxis.Curve(g, Line(true), Brand.RoyalBlue, DeviceDpi, dots: samples.Length == 1);
if (DisplayedSeries != TrafficChartSeries.Upload)
ChartAxis.Curve(g, Line(false), DownloadColor, DeviceDpi, dots: samples.Length == 1);
}
g.Restore(clip);
if (!HasFreshSample)
{
var inset = Math.Max(2, (int)Math.Round(5 * scale));
var height = Measure(g, "采样暂不可用").Height;
var badge = Rectangle.FromLTRB((int)plot.Left + inset, (int)plot.Top + inset, (int)plot.Right - inset,
(int)plot.Top + inset + height);
if (badge.Width > 0 && badge.Bottom <= plot.Bottom)
TextRenderer.DrawText(g, "采样暂不可用", Font, badge, AxisText, LabelFlags | TextFormatFlags.Right);
}
}
private Size Measure(Graphics g, string text)
{
var size = TextRenderer.MeasureText(g, text, Font, Size.Empty, LabelFlags);
return new Size(size.Width, Math.Max(size.Height, (int)Math.Ceiling(Font.GetHeight(DeviceDpi))));
}
private RectangleF DrawAxes(Graphics g, Rectangle bounds, ChartAxisY axis, DateTimeOffset end, float scale)
{
if (bounds.Width < 12 || bounds.Height < 10) return RectangleF.Empty;
var padding = Math.Max(2, (int)Math.Round(7 * scale));
var labelHeight = Measure(g, axis.UnitText).Height;
var timeGap = labelHeight / 2 + Math.Max(2, padding / 3);
var fullYAxis = bounds.Height >= labelHeight * 4 + padding * 3;
var showTime = bounds.Height >= labelHeight * 3 + padding;
var showCompactLimit = !fullYAxis && bounds.Height >= labelHeight * 2 + padding;
var firstY = bounds.Top + (fullYAxis ? labelHeight + labelHeight / 2 + padding : padding / 2);
var lastY = bounds.Bottom - (showTime ? labelHeight + timeGap + padding / 2 : padding / 2);
var axisWidth = Math.Max(Measure(g, axis.UnitText).Width, Measure(g, axis.Tick(axis.MaximumUnits)).Width);
if (showCompactLimit) axisWidth = Math.Max(axisWidth, Measure(g, axis.UpperLimitLabel).Width);
var left = bounds.Left + axisWidth + 2 * padding;
var plot = RectangleF.FromLTRB(left, firstY, bounds.Right - padding, lastY);
if (plot.Width <= 3 || plot.Height <= 3) return RectangleF.Empty;
using var plotFill = new LinearGradientBrush(plot, Color.FromArgb(172, 248, 253, 255),
Color.FromArgb(143, 233, 246, 255), 90f);
using var grid = new Pen(GridColor, Math.Max(.75f, .65f * scale)) { DashStyle = DashStyle.Dot };
using var outline = new Pen(AxisStroke, Math.Max(1f, .65f * scale));
g.FillRectangle(plotFill, plot);
g.DrawRectangle(outline, plot.X, plot.Y, plot.Width, plot.Height);
var unitTop = bounds.Top + Math.Max(1, padding / 3);
var labelLeft = bounds.Left + padding;
var labelWidth = left - labelLeft - Math.Max(2, padding / 2);
TextRenderer.DrawText(g, axis.UnitText, Font, new Rectangle(labelLeft, unitTop, labelWidth, labelHeight),
AxisText, LabelFlags);
if (fullYAxis)
{
var quarterTenths = axis.MaximumUnits * 2.5;
var regularDivisions = Math.Abs(quarterTenths - Math.Round(quarterTenths)) < .0001 ? 4 : 5;
var divisions = plot.Height >= labelHeight * (regularDivisions + 1) ? regularDivisions
: plot.Height >= labelHeight * 3 ? 2 : 1;
for (var i = 0; i <= divisions; i++)
{
var y = plot.Bottom - plot.Height * i / divisions;
if (i > 0 && i < divisions) g.DrawLine(grid, plot.Left, y, plot.Right, y);
var yTop = (int)Math.Round(y) - labelHeight / 2;
TextRenderer.DrawText(g, axis.Tick(axis.MaximumUnits * i / divisions), Font,
new Rectangle(labelLeft, yTop, labelWidth, labelHeight), AxisText, LabelFlags | TextFormatFlags.Right);
}
}
else if (showCompactLimit && unitTop + 2 * labelHeight <= (showTime ? plot.Bottom + timeGap : bounds.Bottom))
{
TextRenderer.DrawText(g, axis.UpperLimitLabel, Font,
new Rectangle(labelLeft, unitTop + labelHeight, labelWidth, labelHeight), AxisText, LabelFlags);
}
if (showTime) DrawTimes(g, bounds, plot, end, labelHeight, padding, timeGap, grid);
return plot;
}
private void DrawTimes(Graphics g, Rectangle bounds, RectangleF plot, DateTimeOffset end,
int labelHeight, int padding, int timeGap, Pen grid)
{
var format = PeriodMinutes == 1 ? "HH:mm:ss" : "HH:mm";
var labelWidth = Measure(g, end.ToString(format)).Width;
var capacity = Math.Max(1, (int)(plot.Width / (labelWidth + padding)) + 1);
var nominalStep = PeriodMinutes switch { 1 => 10, 5 => 60, 15 => 180, _ => 600 };
var nominalSlots = _period.TotalSeconds / nominalStep;
var labelTop = (int)Math.Round(plot.Bottom) + timeGap;
void DrawLabel(DateTimeOffset time, float x)
{
var text = time.ToString(format);
var width = Measure(g, text).Width;
var right = Math.Max(bounds.Left + 2, bounds.Right - width - 2);
var left = Math.Clamp((int)Math.Round(x - width / 2f), bounds.Left + 2, right);
TextRenderer.DrawText(g, text, Font, new Rectangle(left, labelTop, width, labelHeight),
AxisText, LabelFlags);
}
if (capacity == 1)
{
DrawLabel(end, plot.Right - labelWidth / 2f);
return;
}
var step = TimeSpan.FromSeconds(nominalStep * Math.Ceiling(nominalSlots / (capacity - 1)));
var start = end.Subtract(_period);
var initialTick = (step.Ticks - start.Ticks % step.Ticks) % step.Ticks;
for (var tick = initialTick; tick <= _period.Ticks; tick += step.Ticks)
{
var x = plot.Left + (float)(tick / (double)_period.Ticks) * plot.Width;
if (tick > 0 && tick < _period.Ticks) g.DrawLine(grid, x, plot.Top, x, plot.Bottom);
DrawLabel(start.AddTicks(tick), x);
}
}
private void DrawEmptyState(Graphics g, RectangleF plot, float scale)
{
var message = LastSampleAt.HasValue ? "采样暂不可用" : "等待代理流量采样 …";
var text = Measure(g, message);
var centerX = plot.Left + plot.Width / 2;
var centerY = plot.Top + plot.Height / 2;
var iconSize = 35 * scale;
var gap = 6 * scale;
if (plot.Height >= iconSize + gap + text.Height + 8 * scale && plot.Width >= iconSize)
{
var top = centerY - (iconSize + gap + text.Height) / 2;
DrawSignal(g, new RectangleF(centerX - iconSize / 2, top, iconSize, iconSize));
centerY = top + iconSize + gap + text.Height / 2f;
}
var label = Rectangle.FromLTRB((int)plot.Left + 2, (int)(centerY - text.Height / 2f),
(int)plot.Right - 2, (int)Math.Ceiling(centerY + text.Height / 2f));
if (label.Width > 0)
{
var maskWidth = Math.Min(label.Width, text.Width + (int)Math.Ceiling(10 * scale));
var maskBounds = new Rectangle(label.Left + (label.Width - maskWidth) / 2, label.Top, maskWidth, label.Height);
if (maskBounds.Width > 2 && maskBounds.Height > 2)
{
using var mask = UiGeometry.RoundedRectangle(maskBounds, Math.Min(maskBounds.Width, maskBounds.Height) / 2);
using var tint = new SolidBrush(Color.FromArgb(224, 240, 249, 255));
g.FillPath(tint, mask);
}
TextRenderer.DrawText(g, message, Font, label, AxisText,
LabelFlags | TextFormatFlags.HorizontalCenter | TextFormatFlags.EndEllipsis);
}
}
private static void DrawSignal(Graphics g, RectangleF bounds)
{
var state = g.Save();
g.TranslateTransform(bounds.X, bounds.Y);
g.ScaleTransform(bounds.Width / 40, bounds.Height / 40);
using var outer = new Pen(Color.FromArgb(180, 97, 162, 224), 1.7f)
{ StartCap = LineCap.Round, EndCap = LineCap.Round };
using var inner = new Pen(Color.FromArgb(202, 54, 114, 182), 1.85f)
{ StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round };
using var center = new SolidBrush(Color.FromArgb(60, 126, 194));
g.DrawArc(outer, 2, 3, 36, 27, 135, 90);
g.DrawArc(outer, 2, 3, 36, 27, 315, 90);
g.DrawArc(inner, 8, 8, 24, 17, 135, 90);
g.DrawArc(inner, 8, 8, 24, 17, 315, 90);
g.FillEllipse(center, 17, 13.5f, 6, 6);
g.DrawLines(inner, [new PointF(11, 35), new(20, 22), new(29, 35)]);
g.DrawLine(inner, 14, 31, 26, 31);
g.Restore(state);
}
}
// 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<Sample> _points = new();
private readonly Func<DateTimeOffset> _clock;
private DateTimeOffset? _end, _lastSampleAt;
private bool _gapPending, _unavailable = true;
private long _segment;
internal TrafficChartTimeline(Func<DateTimeOffset>? 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;
}
}
// Pure axis description keeps the labels and plotted byte scale consistent.
internal readonly record struct ChartAxisY(double UnitBytes, string UnitText, double MaximumUnits, bool Speed)
{
internal double MaximumBytes => MaximumUnits * UnitBytes;
internal string Tick(double value) => Speed ? SpeedDisplay.Number(value) : value.ToString("0.#");
internal string UpperLimitLabel => "上限 " + Tick(MaximumUnits);
internal static ChartAxisY Create(double peak, bool speed)
{
if (!double.IsFinite(peak) || peak < 0) peak = 0;
double unit;
string unitName;
if (speed) (unit, unitName) = SpeedDisplay.UnitFor(peak);
else
{
unit = peak >= 1024d * 1024 * 1024 ? 1024d * 1024 * 1024 : peak >= 1024d * 1024 ? 1024d * 1024 : peak >= 1024 ? 1024d : 1d;
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;
return new(unit, unitName, maximum, speed);
}
}
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 axis = ChartAxisY.Create(peak, speed);
var maximum = axis.MaximumUnits;
var fontHeight = TextRenderer.MeasureText(g, "0", font).Height;
// In the compact dashboard the heading and range occupy their own
// left rail. Keep the vertical budget for the curve; units and the
// explicitly captioned upper limit stay inside the axis gutter rather
// than costing a top row. A bare maximum below the top gridline looks
// like a tick at the wrong height, so label this as scale metadata.
var denseSpeed = speed && bounds.Height < 82 * scale;
var left = Math.Max(31 * scale, TextRenderer.MeasureText(g,
denseSpeed ? axis.UpperLimitLabel : axis.Tick(maximum), font).Width + 5 * scale);
var plot = denseSpeed
? new RectangleF(left, 2 * scale, Math.Max(1, bounds.Width - left - 9 * scale), Math.Max(1, bounds.Height - fontHeight - 5 * scale))
: 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;
var compactAxis = plot.Height < fontHeight * 3;
TextRenderer.DrawText(g, axis.UnitText + (compactAxis && !denseSpeed ? " · " + axis.Tick(maximum) : ""), font,
new Rectangle(0, 0, denseSpeed ? (int)left : bounds.Width, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding);
if(denseSpeed) TextRenderer.DrawText(g, axis.UpperLimitLabel, font, new Rectangle(0, fontHeight, (int)left-4, fontHeight),
Brand.Muted, PaintFlags | TextFormatFlags.Right | 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);
// A fitted chart can be only a few text lines tall. Keep its
// explicit upper-limit metadata legible instead of drawing a
// redundant zero label across that second line in the gutter.
var drawTick = denseSpeed ? i == 0 && y - fontHeight / 2 >= fontHeight * 2 + 2 * scale : !compactAxis || i == 0;
if (drawTick) TextRenderer.DrawText(g, axis.Tick(maximum * i / 2), 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, axis.MaximumBytes);
}
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);
}
}