-
Notifications
You must be signed in to change notification settings - Fork 105
/
utils.dart
286 lines (257 loc) · 8.94 KB
/
utils.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
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
/// This defines a colored placeholder with padding, used to represent a
/// generic widget in diagrams.
class Hole extends StatelessWidget {
const Hole({
super.key,
this.color = const Color(0xFFFFFFFF),
});
final Color color;
@override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: 1.0,
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Placeholder(
color: color,
),
),
);
}
}
/// This is a struct to represent a text label in the [LabelPainterWidget].
class Label {
const Label(this.key, this.text, this.anchor);
final GlobalKey key;
final String text;
final FractionalOffset anchor;
}
/// The will take a list of locations that a label should point to, defined
/// by the [Label] structure.
class LabelPainterWidget extends StatelessWidget {
/// Creates a widget that paints labels in defined locations.
///
/// All parameters are required and must not be null.
LabelPainterWidget({
required GlobalKey key,
required List<Label> labels,
required GlobalKey heroKey,
}) : painter =
LabelPainter(labels: labels, heroKey: heroKey, canvasKey: key),
super(key: key);
final LabelPainter painter;
@override
Widget build(BuildContext context) => CustomPaint(painter: painter);
}
/// The custom painter that [LabelPainterWidget] uses to paint the list of
/// labels it is given.
class LabelPainter extends CustomPainter {
LabelPainter({
required this.labels,
required this.heroKey,
required this.canvasKey,
}) : _painters = <Label, TextPainter>{} {
for (final Label label in labels) {
final TextPainter painter = TextPainter(
textDirection: TextDirection.ltr,
text: TextSpan(text: label.text, style: _labelTextStyle),
);
painter.layout();
_painters[label] = painter;
}
}
final List<Label> labels;
final GlobalKey heroKey;
final GlobalKey canvasKey;
final Map<Label, TextPainter> _painters;
static const TextStyle _labelTextStyle = TextStyle(color: Color(0xFF000000));
static const double margin = 16.0;
@override
void paint(Canvas canvas, Size size) {
final RenderBox hero =
heroKey.currentContext!.findRenderObject()! as RenderBox;
final RenderBox diagram =
canvasKey.currentContext!.findRenderObject()! as RenderBox;
final Paint dotPaint = Paint();
final Paint linePaint = Paint()..strokeWidth = 2.0;
final Offset heroTopLeft =
diagram.globalToLocal(hero.localToGlobal(Offset.zero));
for (final Label label in labels) {
final RenderBox box =
label.key.currentContext!.findRenderObject()! as RenderBox;
final Offset anchor = diagram
.globalToLocal(box.localToGlobal(label.anchor.alongSize(box.size)));
final Offset anchorOnHero = anchor - heroTopLeft;
final FractionalOffset relativeAnchor =
FractionalOffset.fromOffsetAndSize(anchorOnHero, hero.size);
final double distanceToTop = anchorOnHero.dy;
final double distanceToBottom = hero.size.height - anchorOnHero.dy;
final double distanceToLeft = anchorOnHero.dx;
final double distanceToRight = hero.size.width - anchorOnHero.dx;
Offset labelPosition;
Offset textPosition = Offset.zero;
final TextPainter painter = _painters[label]!;
if (distanceToTop <= distanceToLeft &&
distanceToTop <= distanceToRight &&
distanceToTop <= distanceToBottom) {
labelPosition = Offset(anchor.dx + (relativeAnchor.dx - 0.5) * margin,
heroTopLeft.dy - margin);
textPosition = Offset(labelPosition.dx - painter.width / 2.0,
labelPosition.dy - painter.height);
} else if (distanceToBottom < distanceToLeft &&
distanceToBottom < distanceToRight &&
distanceToTop > distanceToBottom) {
labelPosition =
Offset(anchor.dx, heroTopLeft.dy + hero.size.height + margin);
textPosition =
Offset(labelPosition.dx - painter.width / 2.0, labelPosition.dy);
} else if (distanceToLeft < distanceToRight) {
labelPosition = Offset(heroTopLeft.dx - margin, anchor.dy);
textPosition = Offset(labelPosition.dx - painter.width - 2.0,
labelPosition.dy - painter.height / 2.0);
} else if (distanceToLeft > distanceToRight) {
labelPosition =
Offset(heroTopLeft.dx + hero.size.width + margin, anchor.dy);
textPosition =
Offset(labelPosition.dx, labelPosition.dy - painter.height / 2.0);
} else {
labelPosition = Offset(anchor.dx, heroTopLeft.dy - margin * 2.0);
textPosition = Offset(anchor.dx - painter.width / 2.0,
anchor.dy - margin - painter.height);
}
canvas.drawCircle(anchor, 4.0, dotPaint);
canvas.drawLine(anchor, labelPosition, linePaint);
painter.paint(canvas, textPosition);
}
}
@override
bool shouldRepaint(LabelPainter oldDelegate) {
return labels != oldDelegate.labels || canvasKey != oldDelegate.canvasKey;
}
@override
bool hitTest(Offset position) => false;
}
/// Resolves [provider] and returns an [ui.Image] that can be used in a
/// [CustomPainter].
Future<ui.Image> getImage(ImageProvider provider) {
final Completer<ui.Image> completer = Completer<ui.Image>();
final ImageStream stream = provider.resolve(ImageConfiguration.empty);
late final ImageStreamListener listener;
listener = ImageStreamListener(
(ImageInfo image, bool sync) {
completer.complete(image.image);
stream.removeListener(listener);
},
onError: (Object error, StackTrace? stack) {
print(error);
throw error; // ignore: only_throw_errors
},
);
stream.addListener(listener);
return completer.future;
}
/// Paints [span] to [canvas] with a given offset and alignment.
void paintSpan(
Canvas canvas,
TextSpan span, {
required Offset offset,
Alignment alignment = Alignment.center,
EdgeInsets padding = EdgeInsets.zero,
TextAlign textAlign = TextAlign.center,
}) {
final TextPainter result = TextPainter(
textDirection: TextDirection.ltr,
text: span,
textAlign: textAlign,
);
result.layout();
final double width = result.width + padding.horizontal;
final double height = result.height + padding.vertical;
result.paint(
canvas,
Offset(
padding.left + offset.dx + (width / -2) + (alignment.x * width / 2),
padding.top + offset.dy + (height / -2) + (alignment.y * height / 2),
),
);
}
/// Similar to [paintSpan] but provides a default text style.
void paintLabel(
Canvas canvas,
String label, {
required Offset offset,
Alignment alignment = Alignment.center,
EdgeInsets padding = EdgeInsets.zero,
TextAlign textAlign = TextAlign.center,
TextStyle? style,
}) {
paintSpan(
canvas,
TextSpan(
text: label,
style: const TextStyle(
color: Colors.black,
fontSize: 14.0,
).merge(style ?? const TextStyle()),
),
offset: offset,
alignment: alignment,
padding: padding,
textAlign: textAlign,
);
}
/// Mixin on diagram states which provides concise callbacks for [Ticker]s.
///
/// This is useful to keep actions like gestures in sync with animations since
/// tickers in the diagram generator don't follow real-world time that [Timer]
/// and [Future.delayed] use in a live environment.
@optionalTypeArgs
mixin LockstepStateMixin<T extends StatefulWidget> on State<T>
implements TickerProvider {
late final Ticker _ticker;
final Map<Duration, Completer<void>> _completers =
<Duration, Completer<void>>{};
Duration elapsed = Duration.zero;
/// Waits for the total elapsed duration to reach [duration].
Future<void> waitLockstepElapsed(Duration duration) {
if (duration <= elapsed) {
return Future<void>.value();
}
final Completer<void> completer =
_completers.putIfAbsent(duration, () => Completer<void>());
return completer.future;
}
/// Waits for the ticker to elapse [duration].
Future<void> waitLockstep(Duration duration) {
return waitLockstepElapsed(elapsed + duration);
}
@override
void initState() {
super.initState();
_ticker = createTicker((Duration elapsed) {
this.elapsed = elapsed;
// Avoid concurrent modification of _completers by getting the durations
// all at once before removing them.
final List<Duration> ready = _completers.keys
.where((Duration duration) => elapsed >= duration)
.toList();
for (final Duration duration in ready) {
_completers[duration]!.complete();
_completers.remove(duration);
}
});
_ticker.start();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
}