forked from flutter/devtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflame_chart.dart
More file actions
1568 lines (1357 loc) · 47.7 KB
/
Copy pathflame_chart.dart
File metadata and controls
1568 lines (1357 loc) · 47.7 KB
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd.
import 'dart:async';
import 'dart:math' as math;
import 'package:collection/collection.dart';
import 'package:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../primitives/extent_delegate_list.dart';
import '../primitives/flutter_widgets/linked_scroll_controller.dart';
import '../primitives/trees.dart';
import '../primitives/utils.dart';
import '../ui/colors.dart';
import '../ui/common_widgets.dart';
import '../ui/search.dart';
import '../ui/utils.dart';
import '../utils/utils.dart';
const rowPadding = 2.0;
// Flame chart rows contain text so are not readable if they do not scale with
// the font factor.
const chartRowHeight = 22.0;
double get rowHeightWithPadding => chartRowHeight + rowPadding;
// This spacing needs to be scaled by the font factor otherwise section
// labels will not have enough room. Typically spacing values should not depend
// on the font size scale factor. TODO(jacobr): clean up the section spacing so
// it is not used in a case where it is not really spacing.
const sectionSpacing = 16.0;
const sideInset = 70.0;
const sideInsetSmall = 60.0;
const baseTimelineGridIntervalPx = 150.0;
// TODO(kenz): add some indication that we are scrolled out of the relevant area
// so that users don't get lost in the extra pixels at the end of the chart.
// TODO(kenz): consider cleaning up by changing to a flame chart code to use a
// composition pattern instead of a class extension pattern.
abstract class FlameChart<T, V> extends StatefulWidget {
const FlameChart(
this.data, {
super.key,
required this.time,
required this.containerWidth,
required this.containerHeight,
required this.selectionNotifier,
required this.onDataSelected,
this.searchMatchesNotifier,
this.activeSearchMatchNotifier,
this.startInset = sideInset,
this.endInset = sideInset,
});
static const minZoomLevel = 1.0;
static const zoomMultiplier = 0.01;
static const minScrollOffset = 0.0;
static const rowOffsetForBottomPadding = 1;
static const rowOffsetForSectionSpacer = 1;
/// Maximum scroll delta allowed for scroll wheel based zooming.
///
/// This isn't really needed but is a reasonable for safety in case we
/// aren't handling some mouse based scroll wheel behavior well, etc.
static const maxScrollWheelDelta = 20.0;
final T data;
final TimeRange time;
final double containerWidth;
final double containerHeight;
final double startInset;
final double endInset;
final ValueListenable<V?> selectionNotifier;
final ValueListenable<List<V>>? searchMatchesNotifier;
final ValueListenable<V?>? activeSearchMatchNotifier;
final void Function(V data) onDataSelected;
double get startingContentWidth => containerWidth - startInset - endInset;
}
// TODO(kenz): cap number of nodes we can show per row at once - need this for
// performance improvements. Optionally we could also do something clever with
// grouping nodes that are close together until they are zoomed in (quad tree
// like implementation).
abstract class FlameChartState<
T extends FlameChart,
V extends FlameChartDataMixin<V>
>
extends State<T>
with AutoDisposeMixin, FlameChartColorMixin, TickerProviderStateMixin {
int get rowOffsetForTopPadding => 2;
// The "top" positional value for each flame chart node will be 0.0 because
// each node is positioned inside its own list.
final flameChartNodeTop = 0.0;
final rows = <FlameChartRow<V>>[];
final sections = <FlameChartSection>[];
// ignore: dispose-fields, false positive. Disposed via autoDisposeFocusNode.
final focusNode = FocusNode(debugLabel: 'flame-chart');
double? mouseHoverX;
final _hoveredNodeNotifier = ValueNotifier<V?>(null);
late final FixedExtentDelegate verticalExtentDelegate;
late final LinkedScrollControllerGroup verticalControllerGroup;
late final LinkedScrollControllerGroup horizontalControllerGroup;
late final ScrollController _verticalFlameChartScrollController;
/// Animation controller for animating flame chart zoom changes.
@visibleForTesting
late final AnimationController zoomController;
double currentZoom = FlameChart.minZoomLevel;
double horizontalScrollOffset = FlameChart.minScrollOffset;
double verticalScrollOffset = FlameChart.minScrollOffset;
// Scrolling via WASD controls will pan the left/right 25% of the view.
double get keyboardScrollUnit => widget.containerWidth * 0.25;
// Zooming in via WASD controls will zoom the view in by 50% on each zoom. For
// example, if the zoom level is 2.0, zooming by one unit would increase the
// level to 3.0 (e.g. 2 + (2 * 0.5) = 3).
double get keyboardZoomInUnit => currentZoom * 0.5;
// Zooming out via WASD controls will zoom the view out to the previous zoom
// level. For example, if the zoom level is 3.0, zooming out by one unit would
// decrease the level to 2.0 (e.g. 3 - 3 * 1/3 = 2). See [wasdZoomInUnit]
// for an explanation of how we previously zoomed from level 2.0 to level 3.0.
double get keyboardZoomOutUnit => currentZoom * 1 / 3;
double get contentWidthWithZoom => widget.startingContentWidth * currentZoom;
double get widthWithZoom =>
contentWidthWithZoom + widget.startInset + widget.endInset;
TimeRange get visibleTimeRange {
final horizontalScrollOffset = horizontalControllerGroup.offset;
final startMicros = horizontalScrollOffset < widget.startInset
? startTimeOffset
: startTimeOffset +
(horizontalScrollOffset - widget.startInset) /
currentZoom /
startingPxPerMicro;
final endMicros =
startTimeOffset +
(horizontalScrollOffset - widget.startInset + widget.containerWidth) /
currentZoom /
startingPxPerMicro;
return TimeRange(start: startMicros.round(), end: endMicros.round());
}
/// Starting pixels per microsecond in order to fit all the data in view at
/// start.
double get startingPxPerMicro =>
widget.startingContentWidth / widget.time.duration.inMicroseconds;
int get startTimeOffset => widget.time.start;
double get maxZoomLevel {
// The max zoom level is hit when 1 microsecond is the width of each grid
// interval (this may bottom out at 2 micros per interval due to rounding).
return math.max(
FlameChart.minZoomLevel,
baseTimelineGridIntervalPx *
widget.time.duration.inMicroseconds /
widget.startingContentWidth,
);
}
/// Provides widgets to be layered on top of the flame chart, if overridden.
///
/// The widgets will be layered in a [Stack] in the order that they are
/// returned.
List<Widget> buildChartOverlays(
BoxConstraints constraints,
BuildContext buildContext,
) {
return const [];
}
@override
void initState() {
super.initState();
initFlameChartElements();
horizontalControllerGroup = LinkedScrollControllerGroup();
verticalControllerGroup = LinkedScrollControllerGroup();
addAutoDisposeListener(horizontalControllerGroup.offsetNotifier, () {
setState(() {
horizontalScrollOffset = horizontalControllerGroup.offset;
});
});
addAutoDisposeListener(verticalControllerGroup.offsetNotifier, () {
setState(() {
verticalScrollOffset = verticalControllerGroup.offset;
});
});
_verticalFlameChartScrollController = verticalControllerGroup.addAndGet();
zoomController = AnimationController(
value: FlameChart.minZoomLevel,
lowerBound: FlameChart.minZoomLevel,
upperBound: maxZoomLevel,
vsync: this,
)..addListener(_handleZoomControllerValueUpdate);
verticalExtentDelegate = FixedExtentDelegate(
computeExtent: (index) =>
rows[index].nodes.isEmpty ? sectionSpacing : rowHeightWithPadding,
computeLength: () => rows.length,
);
if (widget.activeSearchMatchNotifier != null) {
addAutoDisposeListener(widget.activeSearchMatchNotifier, () async {
final activeSearch = widget.activeSearchMatchNotifier!.value as V?;
if (activeSearch == null) return;
// Ensure the [activeSearch] is vertically in view.
if (!isDataVerticallyInView(activeSearch)) {
await scrollVerticallyToData(activeSearch);
}
// TODO(kenz): zoom if the event is less than some min width.
// Ensure the [activeSearch] is horizontally in view.
if (!isDataHorizontallyInView(activeSearch)) {
await scrollHorizontallyToData(activeSearch);
}
});
}
autoDisposeFocusNode(focusNode);
}
@override
void didUpdateWidget(T oldWidget) {
if (widget.data != oldWidget.data) {
initFlameChartElements();
horizontalControllerGroup.resetScroll();
verticalControllerGroup.resetScroll();
zoomController.reset();
verticalExtentDelegate.recompute();
} else if (widget.containerWidth != oldWidget.containerWidth ||
widget.containerHeight != oldWidget.containerHeight) {
initFlameChartElements();
verticalExtentDelegate.recompute();
}
FocusScope.of(context).requestFocus(focusNode);
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
zoomController.dispose();
_verticalFlameChartScrollController.dispose();
_hoveredNodeNotifier.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MouseRegion(
onHover: _handleMouseHover,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapUp: _handleTapUp,
child: Focus(
autofocus: true,
focusNode: focusNode,
onKeyEvent: (node, event) => _handleKeyEvent(event),
// Scrollbar needs to wrap [LayoutBuilder] so that the scroll bar is
// rendered on top of the custom painters defined in [buildCustomPaints]
child: Scrollbar(
controller: _verticalFlameChartScrollController,
thumbVisibility: true,
child: LayoutBuilder(
builder: (context, constraints) {
final chartOverlays = buildChartOverlays(constraints, context);
final flameChart = _buildFlameChart(constraints);
return chartOverlays.isNotEmpty
? Stack(children: [flameChart, ...chartOverlays])
: flameChart;
},
),
),
),
),
);
}
Widget _buildFlameChart(BoxConstraints constraints) {
return ExtentDelegateListView(
physics: const ClampingScrollPhysics(),
controller: _verticalFlameChartScrollController,
extentDelegate: verticalExtentDelegate,
childrenDelegate: SliverChildBuilderDelegate(
(context, index) {
final nodes = rows[index].nodes;
var rowBackgroundColor = Colors.transparent;
if (index >= rowOffsetForTopPadding && nodes.isEmpty) {
// If this is a spacer row, we should use the background color of
// the previous row with nodes.
for (int i = index; i >= rowOffsetForTopPadding; i--) {
// Look back until we find the first non-empty row.
if (rows[i].nodes.isNotEmpty) {
rowBackgroundColor = alternatingColorForIndex(
rows[i].nodes.first.sectionIndex,
Theme.of(context).colorScheme,
);
break;
}
}
} else if (nodes.isNotEmpty) {
rowBackgroundColor = alternatingColorForIndex(
nodes.first.sectionIndex,
Theme.of(context).colorScheme,
);
}
// TODO(polinach): figure out how to get rid of the type cast.
// See https://github.com/flutter/devtools/pull/3738#discussion_r817135162
return ScrollingFlameChartRow<V>(
linkedScrollControllerGroup: horizontalControllerGroup,
nodes: nodes,
width: math.max(constraints.maxWidth, widthWithZoom),
startInset: widget.startInset,
hoveredNotifier: _hoveredNodeNotifier,
selectionNotifier: widget.selectionNotifier as ValueListenable<V?>,
searchMatchesNotifier:
widget.searchMatchesNotifier as ValueListenable<List<V>>?,
activeSearchMatchNotifier:
widget.activeSearchMatchNotifier as ValueListenable<V?>?,
backgroundColor: rowBackgroundColor,
zoom: currentZoom,
);
},
childCount: rows.length,
addAutomaticKeepAlives: false,
),
);
}
// This method must be overridden by all subclasses.
@mustCallSuper
void initFlameChartElements() {
rows.clear();
sections.clear();
}
void expandRows(int newRowLength) {
final currentLength = rows.length;
for (int i = currentLength; i < newRowLength; i++) {
rows.add(FlameChartRow<V>(i));
}
}
void _handleMouseHover(PointerHoverEvent event) {
mouseHoverX = event.localPosition.dx;
final mouseHoverY = event.localPosition.dy;
final topPaddingHeight = rowOffsetForTopPadding * sectionSpacing;
if (mouseHoverY <= topPaddingHeight) {
_hoveredNodeNotifier.value = null;
return;
}
final nodes = _nodesForRowAtY(mouseHoverY);
if (nodes == null) {
_hoveredNodeNotifier.value = null;
return;
}
final hoverNodeData = _binarySearchForNode(
x: event.localPosition.dx + horizontalControllerGroup.offset,
nodesInRow: nodes,
)?.data;
_hoveredNodeNotifier.value = hoverNodeData;
}
/// Returns the nodes for the row at the given [dy] mouse position.
///
/// Returns null if there is not a row at the given position.
List<FlameChartNode<V>>? _nodesForRowAtY(double dy) {
final rowIndex = _rowIndexForY(dy);
if (rowIndex == -1) {
return null;
}
return rows[rowIndex].nodes;
}
/// Returns the flame chart row index for the given [dy] mouse position.
///
/// Returns -1 if the row index is out of range for [rows].
int _rowIndexForY(double dy) {
final topPaddingHeight = rowOffsetForTopPadding * sectionSpacing;
final adjustedDy = verticalControllerGroup.offset + dy;
final rowIndex =
((adjustedDy - topPaddingHeight) ~/ rowHeightWithPadding) +
rowOffsetForTopPadding;
if (rowIndex < 0 || rowIndex >= rows.length) {
return -1;
}
return rowIndex;
}
void _handleTapUp(TapUpDetails details) {
final referenceBox = context.findRenderObject() as RenderBox;
final tapPosition = referenceBox.globalToLocal(details.globalPosition);
final nodes = _nodesForRowAtY(tapPosition.dy);
if (nodes != null) {
final nodeToSelect = _binarySearchForNode(
x: tapPosition.dx + horizontalControllerGroup.offset,
nodesInRow: nodes,
);
nodeToSelect?.onSelected(nodeToSelect.data);
}
focusNode.requestFocus();
}
FlameChartNode<V>? _binarySearchForNode({
required double x,
required List<FlameChartNode<V>> nodesInRow,
}) {
return binarySearchForNodeHelper(
x: x,
nodesInRow: nodesInRow,
zoom: currentZoom,
startInset: widget.startInset,
);
}
KeyEventResult _handleKeyEvent(KeyEvent event) {
if (!event.isKeyDownOrRepeat) return KeyEventResult.ignored;
// Only handle down events so logic is not duplicated on key up.
// TODO(kenz): zoom in/out faster if key is held. It actually zooms slower
// if the key is held currently.
// Handle zooming / navigation from WASD keys. Use physical keys to match
// other keyboard mappings like Dvorak, for which these keys would
// translate to ,AOE keys. See
// https://api.flutter.dev/flutter/services/KeyEvent/physicalKey.html.
final eventKey = event.physicalKey;
if (eventKey == PhysicalKeyboardKey.keyW) {
unawaited(
zoomTo(math.min(maxZoomLevel, currentZoom + keyboardZoomInUnit)),
);
return KeyEventResult.handled;
} else if (eventKey == PhysicalKeyboardKey.keyS) {
unawaited(
zoomTo(
math.max(FlameChart.minZoomLevel, currentZoom - keyboardZoomOutUnit),
),
);
return KeyEventResult.handled;
} else if (eventKey == PhysicalKeyboardKey.keyA) {
// `unawaited` does not work for FutureOr
// ignore: discarded_futures
scrollToX(horizontalControllerGroup.offset - keyboardScrollUnit);
return KeyEventResult.handled;
} else if (eventKey == PhysicalKeyboardKey.keyD) {
// `unawaited` does not work for FutureOr
// ignore: discarded_futures
scrollToX(horizontalControllerGroup.offset + keyboardScrollUnit);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
void _handleZoomControllerValueUpdate() {
final previousZoom = currentZoom;
final newZoom = zoomController.value;
if (previousZoom == newZoom) return;
// Store current scroll values for re-calculating scroll location on zoom.
final lastScrollOffset = horizontalControllerGroup.offset;
final safeMouseHoverX = mouseHoverX ?? widget.containerWidth / 2;
// Position in the zoomable coordinate space that we want to keep fixed.
final fixedX = safeMouseHoverX + lastScrollOffset - widget.startInset;
// Calculate the new horizontal scroll position.
final newScrollOffset = fixedX >= 0
? fixedX * newZoom / previousZoom + widget.startInset - safeMouseHoverX
// We are in the fixed portion of the window - no need to transform.
: lastScrollOffset;
setState(() {
currentZoom = zoomController.value;
// TODO(kenz): consult with Flutter team to see if there is a better place
// to call this that guarantees the scroll controller offsets will be
// updated for the new zoom level and layout size
// https://github.com/flutter/devtools/issues/2012.
// `unawaited` does not work for FutureOr
// ignore: discarded_futures
scrollToX(newScrollOffset, jump: true);
});
}
Future<void> zoomTo(
double zoom, {
double? forceMouseX,
bool jump = false,
}) async {
if (forceMouseX != null) {
mouseHoverX = forceMouseX;
}
await zoomController.animateTo(
zoom.clamp(FlameChart.minZoomLevel, maxZoomLevel),
duration: jump ? Duration.zero : shortDuration,
);
}
/// Scroll the flame chart horizontally to [offset] scroll position.
///
/// If this is being called immediately after a zoom call, without a chance
/// for the UI to build between the zoom call and the call to
/// this method, the call to this method should be placed inside of a
/// postFrameCallback:
/// `WidgetsBinding.instance.addPostFrameCallback((_) { ... });`.
FutureOr<void> scrollToX(double offset, {bool jump = false}) async {
final target = offset.clamp(
FlameChart.minScrollOffset,
horizontalControllerGroup.position.maxScrollExtent,
);
if (jump) {
horizontalControllerGroup.jumpTo(target);
} else {
await horizontalControllerGroup.animateTo(
target,
curve: defaultCurve,
duration: shortDuration,
);
}
}
Future<void> scrollVerticallyToData(V data) async {
await verticalControllerGroup.animateTo(
// Subtract [2 * rowHeightWithPadding] to give the target scroll event top padding.
(topYForData(data) - 2 * rowHeightWithPadding).clamp(
FlameChart.minScrollOffset,
verticalControllerGroup.position.maxScrollExtent,
),
duration: shortDuration,
curve: defaultCurve,
);
}
/// Scroll the flame chart horizontally to put [data] in view.
///
/// If this is being called immediately after a zoom call, the call to
/// this method should be placed inside of a postFrameCallback:
/// `WidgetsBinding.instance.addPostFrameCallback((_) { ... });`.
Future<void> scrollHorizontallyToData(V data) async {
final offset =
startXForData(data) + widget.startInset - widget.containerWidth * 0.1;
await scrollToX(offset);
}
Future<void> zoomAndScrollToData({
required int startMicros,
required int durationMicros,
required V data,
bool scrollVertically = true,
bool jumpZoom = false,
}) async {
await zoomToTimeRange(
startMicros: startMicros,
durationMicros: durationMicros,
jump: jumpZoom,
);
// Call these in a post frame callback so that the scroll controllers have
// had time to update their scroll extents. Otherwise, we can hit a race
// where are trying to scroll to an offset that is beyond what the scroll
// controller thinks its max scroll extent is.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
unawaited(scrollHorizontallyToData(data));
if (scrollVertically) unawaited(scrollVerticallyToData(data));
}
});
}
Future<void> zoomToTimeRange({
required int startMicros,
required int durationMicros,
double? targetWidth,
bool jump = false,
}) async {
targetWidth ??= widget.containerWidth * 0.8;
final startingWidth = durationMicros * startingPxPerMicro;
final zoom = targetWidth / startingWidth;
final mouseXForZoom =
(startMicros - startTimeOffset + durationMicros / 2) *
startingPxPerMicro +
widget.startInset;
await zoomTo(zoom, forceMouseX: mouseXForZoom, jump: jump);
}
bool isDataVerticallyInView(V data);
bool isDataHorizontallyInView(V data);
double topYForData(V data);
double startXForData(V data);
}
class ScrollingFlameChartRow<V extends FlameChartDataMixin<V>>
extends StatefulWidget {
const ScrollingFlameChartRow({
super.key,
required this.linkedScrollControllerGroup,
required this.nodes,
required this.width,
required this.startInset,
required this.hoveredNotifier,
required this.selectionNotifier,
required this.searchMatchesNotifier,
required this.activeSearchMatchNotifier,
required this.backgroundColor,
required this.zoom,
});
final LinkedScrollControllerGroup linkedScrollControllerGroup;
final List<FlameChartNode<V>> nodes;
final double width;
final double startInset;
final ValueListenable<V?> hoveredNotifier;
final ValueListenable<V?> selectionNotifier;
final ValueListenable<List<V>>? searchMatchesNotifier;
final ValueListenable<V?>? activeSearchMatchNotifier;
final Color backgroundColor;
final double zoom;
@override
ScrollingFlameChartRowState<V> createState() =>
ScrollingFlameChartRowState<V>();
}
class ScrollingFlameChartRowState<V extends FlameChartDataMixin<V>>
extends State<ScrollingFlameChartRow<V>>
with AutoDisposeMixin {
late final ScrollController scrollController;
late final _ScrollingFlameChartRowExtentDelegate _extentDelegate;
/// Convenience getter for widget.nodes.
List<FlameChartNode<V>> get nodes => widget.nodes;
late List<V> _nodeData;
V? selected;
V? hovered;
@override
void initState() {
super.initState();
scrollController = widget.linkedScrollControllerGroup.addAndGet();
_extentDelegate = _ScrollingFlameChartRowExtentDelegate(
nodeIntervals: nodes.toPaddedZoomedIntervals(
zoom: widget.zoom,
chartStartInset: widget.startInset,
chartWidth: widget.width,
),
zoom: widget.zoom,
chartStartInset: widget.startInset,
chartWidth: widget.width,
);
_initNodeDataList();
selected = widget.selectionNotifier.value;
addAutoDisposeListener(widget.selectionNotifier, () {
final containsPreviousSelected =
selected != null && _nodeData.contains(selected);
selected = widget.selectionNotifier.value;
final containsNewSelected = _nodeData.contains(selected);
// We only want to rebuild the row if it contains the previous or new
// selected node.
if (containsPreviousSelected || containsNewSelected) {
setState(() {});
}
});
hovered = widget.hoveredNotifier.value;
addAutoDisposeListener(widget.hoveredNotifier, () {
setState(() {
hovered = widget.hoveredNotifier.value;
});
});
if (widget.searchMatchesNotifier != null) {
addAutoDisposeListener(widget.searchMatchesNotifier);
}
if (widget.activeSearchMatchNotifier != null) {
addAutoDisposeListener(widget.activeSearchMatchNotifier);
}
}
@override
void didUpdateWidget(ScrollingFlameChartRow<V> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.nodes != widget.nodes) {
_initNodeDataList();
}
if (oldWidget.nodes != widget.nodes ||
oldWidget.zoom != widget.zoom ||
oldWidget.width != widget.width ||
oldWidget.startInset != widget.startInset) {
_extentDelegate.recomputeWith(
nodeIntervals: nodes.toPaddedZoomedIntervals(
zoom: widget.zoom,
chartStartInset: widget.startInset,
chartWidth: widget.width,
),
zoom: widget.zoom,
chartStartInset: widget.startInset,
chartWidth: widget.width,
);
}
_resetHovered();
}
@override
void dispose() {
scrollController.dispose();
_resetHovered();
super.dispose();
}
void _initNodeDataList() {
_nodeData = nodes.map((node) => node.data).toList();
}
@override
Widget build(BuildContext context) {
if (nodes.isEmpty) {
return EmptyFlameChartRow(
height: sectionSpacing,
width: widget.width,
backgroundColor: widget.backgroundColor,
);
}
return Container(
height: rowHeightWithPadding,
width: widget.width,
color: widget.backgroundColor,
// TODO(kenz): investigate if `addAutomaticKeepAlives: false` and
// `addRepaintBoundaries: false` are needed here for perf improvement.
child: ExtentDelegateListView(
controller: scrollController,
scrollDirection: Axis.horizontal,
extentDelegate: _extentDelegate,
childrenDelegate: SliverChildBuilderDelegate(
(context, index) {
final node = nodes[index];
return FlameChartNodeWidget(
index: index,
nodes: nodes,
zoom: widget.zoom,
startInset: widget.startInset,
chartWidth: widget.width,
selected: node.data == selected,
hovered: node.data == hovered,
);
},
childCount: nodes.length,
addRepaintBoundaries: false,
addAutomaticKeepAlives: false,
),
),
);
}
void _resetHovered() {
hovered = null;
}
}
class FlameChartNodeWidget extends StatelessWidget {
const FlameChartNodeWidget({
super.key,
required this.index,
required this.nodes,
required this.zoom,
required this.startInset,
required this.chartWidth,
required this.selected,
required this.hovered,
});
final int index;
final List<FlameChartNode> nodes;
final double zoom;
final double startInset;
final double chartWidth;
final bool selected;
final bool hovered;
@override
Widget build(BuildContext context) {
final node = nodes[index];
return Padding(
padding: EdgeInsets.only(
left: FlameChartUtils.leftPaddingForNode(
index,
nodes,
chartZoom: zoom,
chartStartInset: startInset,
),
right: FlameChartUtils.rightPaddingForNode(
index,
nodes,
chartZoom: zoom,
chartStartInset: startInset,
chartWidth: chartWidth,
),
bottom: rowPadding,
),
child: node.buildWidget(
selected: selected,
hovered: hovered,
searchMatch: node.data.isSearchMatch,
activeSearchMatch: node.data.isActiveSearchMatch,
zoom: FlameChartUtils.zoomForNode(node, zoom),
theme: Theme.of(context),
),
);
}
}
extension NodeListExtension on List<FlameChartNode> {
List<Range> toPaddedZoomedIntervals({
required double zoom,
required double chartStartInset,
required double chartWidth,
}) {
return List<Range>.generate(
length,
(index) => FlameChartUtils.paddedZoomedInterval(
index,
this,
chartZoom: zoom,
chartStartInset: chartStartInset,
chartWidth: chartWidth,
),
);
}
}
/// A namespace for flame chart utilities.
extension FlameChartUtils on Never {
static double leftPaddingForNode(
int index,
List<FlameChartNode> nodes, {
required double chartZoom,
required double chartStartInset,
}) {
final node = nodes[index];
double padding;
if (index != 0) {
padding = 0.0;
} else if (!node.selectable) {
padding = node.rect.left;
} else {
padding =
(node.rect.left - chartStartInset) * zoomForNode(node, chartZoom) +
chartStartInset;
}
// Floating point rounding error can result in slightly negative padding.
return math.max(0.0, padding);
}
static double rightPaddingForNode(
int index,
List<FlameChartNode> nodes, {
required double chartZoom,
required double chartStartInset,
required double chartWidth,
}) {
// TODO(kenz): workaround for https://github.com/flutter/devtools/issues/2012.
// This is a ridiculous amount of padding but it ensures that we don't hit
// the issue described in the bug where the scroll extent is smaller than
// where we want to `jumpTo`. Smaller values were experimented with but the
// issue still persisted, so we are using a very large number.
if (index == nodes.length - 1) return 1000000000000.0;
final node = nodes[index];
final nextNode = index == nodes.length - 1 ? null : nodes[index + 1];
final nodeZoom = zoomForNode(node, chartZoom);
final nextNodeZoom = zoomForNode(nextNode, chartZoom);
// Node right with zoom and insets taken into consideration.
final nodeRight =
(node.rect.right - chartStartInset) * nodeZoom + chartStartInset;
final padding = nextNode == null
? chartWidth - nodeRight
: ((nextNode.rect.left - chartStartInset) * nextNodeZoom +
chartStartInset) -
nodeRight;
// Floating point rounding error can result in slightly negative padding.
return math.max(0.0, padding);
}
static double zoomForNode(FlameChartNode? node, double chartZoom) {
return node != null && node.selectable
? chartZoom
: FlameChart.minZoomLevel;
}
static Range paddedZoomedInterval(
int index,
List<FlameChartNode> nodes, {
required double chartZoom,
required double chartStartInset,
required double chartWidth,
}) {
final node = nodes[index];
final zoomedRect = node.zoomedRect(chartZoom, chartStartInset);
final leftPadding = leftPaddingForNode(
index,
nodes,
chartZoom: chartZoom,
chartStartInset: chartStartInset,
);
final rightPadding = rightPaddingForNode(
index,
nodes,
chartZoom: chartZoom,
chartStartInset: chartStartInset,
chartWidth: chartWidth,
);
final left = zoomedRect.left - leftPadding;
final width = leftPadding + zoomedRect.width + rightPadding;
return Range(left, left + width);
}
}
class FlameChartSection {
FlameChartSection(this.index, {required this.startRow, required this.endRow});
final int index;
/// Start row (inclusive) for this section.
final int startRow;
/// End row (exclusive) for this section.
final int endRow;
}
class FlameChartRow<T extends FlameChartDataMixin<T>> {
FlameChartRow(this.index);
final nodes = <FlameChartNode<T>>[];
final int index;