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

122 lines
6.6 KiB
C#
Raw Normal View History

using System.Drawing.Drawing2D;
namespace UCVL.VPNPlus;
// Reads only existing proxy-outbound counters; never the physical adapter.
internal sealed class TrafficChart : Control
{
private readonly Queue<(DateTimeOffset Time, double Up, double Down)> _points = new();
private TimeSpan _period = TimeSpan.FromMinutes(5);
internal int PeriodMinutes => (int)_period.TotalMinutes;
internal int PointCount => _points.Count;
internal int VisiblePointCount => VisiblePoints().Length;
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 (DateTimeOffset Time, double Up, double Down)[] VisiblePoints()
{
var end = _points.Count == 0 ? DateTimeOffset.Now : _points.Last().Time;
return _points.Where(point => end - point.Time <= _period).ToArray();
}
internal TrafficChart()
{
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)
{
var at = time ?? DateTimeOffset.Now;
double Clean(double n) => double.IsFinite(n) ? Math.Max(0, n) : 0;
_points.Enqueue((at, Clean(up), Clean(down)));
// Bounded current-session samples only: never turn daily accounting
// totals into a fictitious speed curve. Changing range preserves samples.
while (_points.Count > 3600 || (_points.Count > 0 && at - _points.Peek().Time > TimeSpan.FromMinutes(60))) _points.Dequeue();
Invalidate();
}
internal void Reset() { _points.Clear(); Invalidate(); }
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
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 = points.Length == 0 ? DateTimeOffset.Now : points[^1].Time;
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, "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted,
ChartAxis.PaintFlags | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
return;
}
PointF[] Line(bool up) => points.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: points.Length == 1);
ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: points.Length == 1);
}
}
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);
}
}