-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgauge_box.dart
669 lines (540 loc) · 20.2 KB
/
gauge_box.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
import 'dart:async';
import 'dart:math';
import 'package:boatinstrument/boatinstrument_controller.dart';
import 'package:flutter/material.dart';
import 'double_value_box.dart';
class GaugeRange {
final double min;
final double max;
final Color color;
const GaugeRange(this.min, this.max, this.color);
}
abstract class DoubleValueGaugeBox extends DoubleValueBox {
final double step;
final List<GaugeRange> ranges;
const DoubleValueGaugeBox(super.config, super.title, super.path,
{super.minValue = 0, required super.maxValue, super.angle, super.smoothing,
this.step = 1, this.ranges = const [],
super.key});
@override
DoubleValueGaugeBoxState createState() => DoubleValueGaugeBoxState();
}
const double _defaultMax = 100;
class DoubleValueGaugeBoxState<T extends DoubleValueGaugeBox> extends DoubleValueBoxState<T> {
int minDisplay = 0;
int maxDisplay = 0;
int _displayStep = 0;
final List<GaugeRange> _displayRanges = [];
@override
void initState() {
super.initState();
minDisplay = widget.convert(widget.minValue??0).ceil();
maxDisplay = widget.convert(widget.maxValue??_defaultMax).floor();
double steps = ((widget.maxValue??100) - (widget.minValue??0))/widget.step;
_displayStep = ((maxDisplay - minDisplay)/steps).round();
_displayStep = _displayStep < 1 ? 1 : _displayStep;
for(GaugeRange r in widget.ranges) {
_displayRanges.add(GaugeRange(widget.convert(r.min), widget.convert(r.max), r.color));
}
}
}
class _SemiGaugePainter extends CustomPainter {
final BuildContext _context;
final GaugeOrientation _orientation;
final bool _mirror;
final int _minValue;
final int _maxValue;
final int _step;
final List<GaugeRange> _ranges;
_SemiGaugePainter(this._context, this._orientation, this._mirror, this._minValue, this._maxValue, this._step, this._ranges);
@override
void paint(Canvas canvas, Size canvasSize) {
ThemeData theme = Theme.of(_context);
double w = canvasSize.width;
double h = canvasSize.height;
Paint paint = Paint()
..style = PaintingStyle.stroke
..color = theme.colorScheme.onSurface
..strokeWidth = 2.0;
double base = w;
if(_orientation == GaugeOrientation.left ||
_orientation == GaugeOrientation.right) {
base = h;
}
canvas.save();
canvas.translate(base*_orientation.xm, base*_orientation.ym);
canvas.translate(base/2, base/2);
canvas.rotate(_orientation.rotation);
canvas.translate(-base/2, -base/2);
canvas.drawArc(Rect.fromLTWH(0, 0, base, base), 0.0, pi, true, paint);
paint.strokeWidth = 5.0;
int range = _maxValue - _minValue;
for(GaugeRange r in _ranges) {
paint.color = r.color;
double start = pi*((r.min - _minValue)/range);
double end = (pi*((r.max - _minValue)/range)) - start;
canvas.drawArc(Rect.fromLTWH(0, 0, base, base), start, end, false, paint);
}
canvas.restore();
TextPainter tp = TextPainter(textDirection: TextDirection.ltr);
try {
canvas.translate((base / 2) + base*_orientation.xm, (base / 2) + base*_orientation.ym);
double steps = range / _step;
double angleStep = pi/steps;
for (int i = 0; i <= steps; ++i) {
String label = (_minValue + (_step*i)).toInt().toString();
tp.text = TextSpan(
text: label,
style: theme.textTheme.bodyMedium?.copyWith(backgroundColor: theme.colorScheme.surface));
tp.layout();
double angle = (_mirror ? pi - angleStep*i : angleStep*i) + _orientation.rotation;
double x = cos(angle) * (base / 2 - 20.0);
double y = sin(angle) * (base / 2 - 20.0);
tp.paint(
canvas, Offset(x - tp.size.width / 2, y - tp.size.height / 2));
}
} finally {
tp.dispose();
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
class _SemiGaugeNeedlePainter extends CustomPainter {
final GaugeOrientation _orientation;
final double _angle;
_SemiGaugeNeedlePainter(this._orientation, this._angle);
@override
void paint(Canvas canvas, Size canvasSize) {
double w = canvasSize.width;
double h = canvasSize.height;
Paint paint = Paint()
..style = PaintingStyle.fill
..color = Colors.blue;
double base = w;
if(_orientation == GaugeOrientation.left ||
_orientation == GaugeOrientation.right) {
base = h;
}
Path needle = Path()
..moveTo(-10.0, 0.0)
..lineTo(0.0, base/2)
..lineTo(10.0, 0.0)
..moveTo(0.0, 0.0)
..addArc(const Offset(-10, -10.0) & const Size(20.0, 20.0), 0.0, -pi)
..close();
canvas.translate(base*_orientation.xm, base*_orientation.ym);
canvas.translate(base/2, base/2);
canvas.rotate(_orientation.rotation);
canvas.rotate(_angle);
canvas.drawPath(needle, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
abstract class DoubleValueSemiGaugeBox extends DoubleValueGaugeBox {
final GaugeOrientation orientation;
final bool mirror;
const DoubleValueSemiGaugeBox(super.config, super.title, this.orientation, super.path,
{super.minValue = 0, required super.maxValue, super.step, super.angle, super.smoothing, super.ranges,
this.mirror = false, super.key});
@override
DoubleValueSemiGaugeBoxState createState() => DoubleValueSemiGaugeBoxState();
}
class DoubleValueSemiGaugeBoxState<T extends DoubleValueSemiGaugeBox> extends DoubleValueGaugeBoxState<T> {
@override
Widget build(BuildContext context) {
GaugeOrientation o = widget.orientation;
List<Widget> stack = [
Positioned(top: o.titleTop, bottom: o.titleBottom, left: o.titleLeft, right: o.titleRight, child: Text(widget.title)),
Positioned(top: o.unitsTop, bottom: o.unitsBottom, left: o.unitsLeft, right: o.unitsRight, child: Text(widget.units(displayValue??0.0))),
CustomPaint(
size: Size.infinite,
painter: _SemiGaugePainter(context, o, widget.mirror, minDisplay, maxDisplay, _displayStep, _displayRanges)
)
];
if(displayValue != null) {
double angle = ((pi/((widget.maxValue??_defaultMax) - (widget.minValue??0))) * (value! - (widget.minValue??0))) - pi/2;
if(widget.mirror) {
angle = (pi*2)-angle;
}
stack.add(CustomPaint(
size: Size.infinite,
painter: _SemiGaugeNeedlePainter(o, angle)
));
}
return Container(padding: const EdgeInsets.all(15.0), child: RepaintBoundary(child: Stack(children: stack)));
}
}
// This is the number of degrees that the circular gauge starts at from dead south.
final double circularGaugeOffset = deg2Rad(20);
class _CircularGaugePainter extends CustomPainter {
final BuildContext _context;
final double _minValue;
final int _minDisplay;
final int _maxDisplay;
final int _displayStep;
final List<GaugeRange> _ranges;
_CircularGaugePainter(this._context, this._minValue, this._minDisplay, this._maxDisplay, this._displayStep, this._ranges);
@override
void paint(Canvas canvas, Size canvasSize) {
double size = min(canvasSize.width, canvasSize.height);
Paint paint = Paint()
..style = PaintingStyle.stroke
..color = Theme.of(_context).colorScheme.onSurface
..strokeWidth = 2.0;
canvas.drawArc(Rect.fromLTWH(0, 0, size, size), pi/2+circularGaugeOffset, 2*pi-(circularGaugeOffset*2), false, paint);
paint.strokeWidth = 5.0;
int range = _maxDisplay - _minDisplay;
double displayRange = (pi-circularGaugeOffset)*2;
for(GaugeRange r in _ranges) {
paint.color = r.color;
double start = displayRange*((r.min - _minValue)/range);
double end = (displayRange*((r.max - _minValue)/range)) - start;
canvas.drawArc(Rect.fromLTWH(0, 0, size, size), start+pi/2+circularGaugeOffset, end, false, paint);
}
TextPainter tp = TextPainter(textDirection: TextDirection.ltr);
try {
paint.color = Theme.of(_context).colorScheme.onSurface;
paint.strokeWidth = 20.0;
const double width = 0.02;
double steps = (_maxDisplay - _minValue) / _displayStep;
double angleStep = (2*pi-(circularGaugeOffset*2))/steps;
double convertOffset = (_minDisplay - _minValue) * angleStep;
for (int i = 0; i <= steps; ++i) {
canvas.drawArc(
const Offset(10.0, 10.0) & Size(size - 20.0, size - 20.0),
(i*angleStep) + (pi / 2) + circularGaugeOffset + convertOffset - (width / 2), width, false, paint);
tp.text = TextSpan(
text: (i*_displayStep+_minDisplay).toString(),
style: Theme
.of(_context)
.textTheme
.bodyMedium);
tp.layout();
double x = cos((i*angleStep) + (pi / 2) + circularGaugeOffset + convertOffset) * (size / 2 - 40.0);
double y = sin((i*angleStep) + (pi / 2) + circularGaugeOffset + convertOffset) * (size / 2 - 40.0);
canvas.save();
canvas.translate(size / 2, size / 2);
tp.paint(
canvas, Offset(x - tp.size.width / 2, y - tp.size.height / 2));
canvas.restore();
}
} finally {
tp.dispose();
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
class _CircularGaugeNeedlePainter extends CustomPainter {
final double _angle;
_CircularGaugeNeedlePainter(this._angle);
@override
void paint(Canvas canvas, Size canvasSize) {
double size = min(canvasSize.width, canvasSize.height);
Paint paint = Paint()
..style = PaintingStyle.fill
..color = Colors.blue;
Path needle = Path()
..moveTo(-10.0, 0.0)
..lineTo(0.0, -size/2)
..lineTo(10.0, 0.0)
..moveTo(0.0, 0.0)
..addArc(const Offset(-10, -10.0) & const Size(20.0, 20.0), 0.0, pi)
..close();
canvas.translate(size/2, size/2);
canvas.rotate(pi+_angle+circularGaugeOffset);
canvas.drawPath(needle, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
abstract class DoubleValueCircularGaugeBox extends DoubleValueGaugeBox {
const DoubleValueCircularGaugeBox(super.config, super.title, super.path,
{super.minValue = 0, required super.maxValue, required super.step,
super.ranges, super.smoothing, super.key});
@override
DoubleValueCircularGaugeBoxState createState() => DoubleValueCircularGaugeBoxState();
}
class DoubleValueCircularGaugeBoxState<T extends DoubleValueCircularGaugeBox> extends DoubleValueGaugeBoxState<T> {
@override
Widget build(BuildContext context) {
List<Widget> stack = [
Positioned(top: 0, left: 0, child: Text(widget.title)),
Positioned(top: 0, right: 0, child: Text(widget.units(displayValue??0.0))),
CustomPaint(
size: Size.infinite,
painter: _CircularGaugePainter(context, widget.convert(widget.minValue??0), minDisplay, maxDisplay, _displayStep, _displayRanges)
)
];
if(displayValue != null) {
double steps = (widget.maxValue??_defaultMax) - (widget.minValue??0);
double angleStep = (2*pi-(circularGaugeOffset*2))/steps;
double angle = angleStep * (value! - (widget.minValue??0));
stack.add(CustomPaint(
size: Size.infinite,
painter: _CircularGaugeNeedlePainter(angle)
));
}
return Container(padding: const EdgeInsets.all(5.0), child: RepaintBoundary(child: Stack(children: stack)));
}
}
class _BarGaugePainter extends CustomPainter {
final BuildContext _context;
final int _minValue;
final int _maxValue;
final int _step;
final List<GaugeRange> _ranges;
final double? _value;
_BarGaugePainter(this._context, this._minValue, this._maxValue, this._step, this._ranges, this._value);
@override
void paint(Canvas canvas, Size canvasSize) {
ThemeData theme = Theme.of(_context);
double w = canvasSize.width;
double h = canvasSize.height;
Paint paint = Paint()
..style = PaintingStyle.fill;
double step = h/(_maxValue - _minValue);
for(GaugeRange r in _ranges) {
paint.color = r.color;
canvas.drawRect(Rect.fromLTRB(0, h-(step*(r.max-_minValue)), w, h-(step*(r.min - _minValue))), paint);
}
if(_value != null) {
paint.color = Colors.blue;
canvas.drawRect(Rect.fromLTRB(35, h-(step*(_value-_minValue)), w, h), paint);
}
paint.color = theme.colorScheme.onSurface;
TextPainter tp = TextPainter(textDirection: TextDirection.ltr);
try {
double steps = (_maxValue - _minValue) / _step;
double lineStep = h / steps;
for (int i = 0; i <= steps; ++i) {
canvas.drawRect(Rect.fromLTWH(0, h-(lineStep*i)-1, w, 2), paint);
tp.text = TextSpan(
text: (i*_step+_minValue).toInt().toString(),
style: theme.textTheme.bodyMedium?.copyWith(backgroundColor: theme.colorScheme.surface));
tp.layout();
tp.paint(canvas, Offset(5, h-(i*lineStep)-(tp.size.height/2)));
}
} finally {
tp.dispose();
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
abstract class DoubleValueBarGaugeBox extends DoubleValueGaugeBox {
const DoubleValueBarGaugeBox(super.config, super.title, super.path,
{super.minValue = 0, required super.maxValue, required super.step,
super.ranges, super.smoothing, super.key});
@override
DoubleValueBarGaugeBoxState createState() => DoubleValueBarGaugeBoxState();
}
class DoubleValueBarGaugeBoxState<T extends DoubleValueBarGaugeBox> extends DoubleValueGaugeBoxState<T> {
@override
Widget build(BuildContext context) {
const double pad = 5.0;
return Column(mainAxisAlignment: MainAxisAlignment.start, children: [
Row(children: [Padding(padding: const EdgeInsets.all(pad), child: Text(widget.title, style: Theme.of(context).textTheme.titleMedium))]),
Expanded(child: Padding(padding: const EdgeInsets.only(left: pad, right: pad),
child: RepaintBoundary(child: CustomPaint(
size: Size.infinite,
painter: _BarGaugePainter(context, minDisplay, maxDisplay, _displayStep, _displayRanges, displayValue)
)))),
Row(children: [Padding(padding: const EdgeInsets.all(pad), child: Text(widget.units(value??0), style: Theme.of(context).textTheme.titleMedium))]),
]);
}
}
class DataPoint {
final DateTime date;
final double value;
DataPoint(this.date, this.value);
}
class _GraphPainter extends CustomPainter {
final BuildContext _context;
final GraphBox _widget;
final List<DataPoint> _data;
final int _minutes;
final int _step;
final List<GaugeRange> _ranges;
_GraphPainter(this._context, this._widget, this._data, this._minutes, this._step, this._ranges);
@override
void paint(Canvas canvas, Size canvasSize) {
ThemeData theme = Theme.of(_context);
double w = canvasSize.width;
double h = canvasSize.height;
List<double?> values = List.filled(w.toInt(), null);
if(_data.isEmpty) {
return;
}
int duration = _minutes*60*1000;
DateTime now = DateTime.now();
int slice = (duration/w).round();
DateTime start = now.subtract(Duration(milliseconds: duration));
int dp=0;
for(; dp<_data.length; ++dp) {
if(_data[dp].date.isAfter(start)) {
break;
}
}
double minDisplay = 0;
double maxDisplay = 0;
for(int i=0; i<values.length; ++i) {
double total = 0;
int count = 0;
DateTime end = start.add(Duration(milliseconds: slice));
while(dp < _data.length && _data[dp].date.isBefore(end)) {
total += _widget.convert(_data[dp].value);
++count;
++dp;
}
start = end;
if(count > 0) {
double displayValue = total/count;
values[i] = displayValue;
if(displayValue < minDisplay) minDisplay = displayValue;
if(displayValue > maxDisplay) maxDisplay = displayValue;
}
}
// Scale display range to the step above and below.
maxDisplay += _step - (maxDisplay % _step);
minDisplay -= (minDisplay % _step);
Paint paint = Paint()
..strokeWidth = 0.0
..style = PaintingStyle.fill;
double step = h/(maxDisplay - minDisplay);//TOTO these variables need better names!
double steps = (maxDisplay - minDisplay) / _step;
double lineStep = h / steps;
paint..color = theme.colorScheme.onSurface
..strokeWidth = 0.0
..style = PaintingStyle.fill;
for (int i = 0; i <= steps; ++i) {
canvas.drawRect(Rect.fromLTWH(0, h-(lineStep*i)-1, w, 2), paint);
}
for(GaugeRange r in _ranges) {
paint.color = r.color;
canvas.drawRect(Rect.fromLTRB(0, h-(step*(r.max-minDisplay))-1, w, h-(step*(r.min-minDisplay))+1), paint);
}
TextPainter tp = TextPainter(textDirection: TextDirection.ltr);
try {
for (int i = 0; i <= steps; ++i) {
tp.text = TextSpan(
text: (i*_step+minDisplay).toInt().toString(),
style: theme.textTheme.bodyMedium?.copyWith(backgroundColor: theme.colorScheme.surface));
tp.layout();
tp.paint(canvas, Offset(5, h-(i*lineStep)-(tp.size.height/2)));
}
} finally {
tp.dispose();
}
paint
..strokeWidth = 2.0
..style = PaintingStyle.stroke
..color = Colors.blue;
bool first = true;
Path p = Path();
for(int i=0; i<values.length; ++i) {
if(values[i] != null) {
if(first) {
first = false;
p.moveTo(i.toDouble(), h-(step*(values[i]!-minDisplay)));
} else {
p.lineTo(i.toDouble(), h-(step*(values[i]!-minDisplay)));
}
}
}
canvas.drawPath(p, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
abstract class GraphBox extends BoxWidget {
final String title;
final int step;
final List<GaugeRange> ranges;
const GraphBox(super.config, this.title,
{required this.step, this.ranges = const [], super.key});
List<DataPoint> get data;
double convert(double value);
String units(double value);
@override
createState() => GraphBoxState();
}
class GraphBoxState extends State<GraphBox> {
final List<GaugeRange> _displayRanges = [];
int _minutes = 5;
@override
void initState() {
super.initState();
widget.config.controller.configure();
for(GaugeRange r in widget.ranges) {
_displayRanges.add(GaugeRange(widget.convert(r.min), widget.convert(r.max), r.color));
}
Timer(Duration(seconds: 1), _update);
}
_update() {
if(mounted) {
setState(() {});
}
Timer(Duration(seconds: 1), _update);
}
@override
Widget build(BuildContext context) {
const double pad = 5.0;
return Column(mainAxisAlignment: MainAxisAlignment.start, children: [
Padding(padding: const EdgeInsets.all(pad), child: Row(children: [
Text('${widget.title} ${widget.units(0)} $_minutes mins', style: Theme.of(context).textTheme.titleMedium),
IconButton(icon: Icon(Icons.add), onPressed: _increaseTime),
IconButton(icon: Icon(Icons.remove), onPressed: _decreaseTime),
])),
Expanded(child: Padding(padding: const EdgeInsets.only(left: pad, right: pad, bottom: pad*2),
child: RepaintBoundary(child: CustomPaint(
size: Size.infinite,
painter: _GraphPainter(context, widget, widget.data, _minutes, widget.step, _displayRanges)
)))),
]);
}
void _increaseTime() {
setState(() {
++_minutes;
});
}
void _decreaseTime() {
setState(() {
--_minutes;
});
}
}
abstract class GraphBackground {
BoatInstrumentController? controller;
double? minValue;
double? maxValue;
bool smoothing;
GraphBackground(String path, {this.controller, this.smoothing = true, this.minValue, this.maxValue}) {
controller?.configure(onUpdate: processUpdates, paths: { path }, isBox: false);
}
List<DataPoint> get data;
void addDataPoint(DataPoint dataPoint);
double get value;
set value(double value);
processUpdates(List<Update>? updates) {
if(updates != null) {
try {
double next =(updates[0].value as num).toDouble();
if ((minValue == null || next >= minValue!) &&
(maxValue == null || next <= maxValue!)) {
if(smoothing) {
value = averageDouble(value, next,
smooth: controller!.valueSmoothing);
} else {
value = next;
}
addDataPoint(DataPoint(DateTime.now(), value));
}
} catch (e) {
controller!.l.e("Error converting $updates", error: e);
}
}
}
}