forked from flutter/devtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtreemap.dart
More file actions
905 lines (805 loc) · 27 KB
/
treemap.dart
File metadata and controls
905 lines (805 loc) · 27 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
// Copyright 2020 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 'package:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import '../primitives/byte_utils.dart';
import '../primitives/trees.dart';
import '../ui/colors.dart';
import '../ui/common_widgets.dart';
enum PivotType { pivotByMiddle, pivotBySize }
final _log = Logger('charts/treemap');
class Treemap extends StatefulWidget {
// TODO(peterdjlee): Consider auto-expanding rootNode named 'src'.
const Treemap.fromRoot({
super.key,
required this.rootNode,
this.nodes,
required this.levelsVisible,
this.isOutermostLevel = false,
required this.width,
required this.height,
required this.onRootChangedCallback,
}) : assert((rootNode == null) != (nodes == null));
const Treemap.fromNodes({
super.key,
this.rootNode,
required this.nodes,
required this.levelsVisible,
this.isOutermostLevel = false,
required this.width,
required this.height,
required this.onRootChangedCallback,
}) : assert((rootNode == null) != (nodes == null));
final TreemapNode? rootNode;
final List<TreemapNode>? nodes;
/// The depth of children visible from this Treemap widget.
///
/// A decremented level should be passed in when constructing [Treemap.fromRoot],
/// but not when constructing [Treemap.fromNodes]. This is because
/// when constructing from a root, [Treemap] either builds a nested [Treemap] to
/// show its node's children, or it shows its node. When constructing from a list
/// of nodes, however, [Treemap] is built to become part of a bigger treemap,
/// which means the level should not change.
///
/// For example, levelsVisible = 2:
/// ```none
/// _______________
/// | Root |
/// ---------------
/// | 1 |
/// | --------- |
/// | | 2 | |
/// | | | |
/// | | | |
/// | --------- |
/// ---------------
/// ```
final int levelsVisible;
/// Whether current levelsVisible matches the outermost level.
final bool isOutermostLevel;
final double width;
final double height;
final void Function(TreemapNode? node) onRootChangedCallback;
static const pivotType = PivotType.pivotByMiddle;
static const treeMapHeaderHeight = 20.0;
static const minHeightToDisplayTitleText = 100.0;
static const minWidthToDisplayCellText = 40.0;
static const minHeightToDisplayCellText = 50.0;
@override
State<Treemap> createState() => _TreemapState();
}
class _TreemapState extends State<Treemap> {
TreemapNode? hoveredNode;
/// Computes the total size of a given list of treemap nodes.
/// [endIndex] defaults to nodes.length - 1.
int computeByteSizeForNodes({
required List<TreemapNode> nodes,
int startIndex = 0,
int? endIndex,
}) {
endIndex ??= nodes.length - 1;
int sum = 0;
for (int i = startIndex; i <= endIndex; i++) {
sum += nodes[i].unsignedByteSize;
}
return sum;
}
int computePivot(List<TreemapNode> children) {
switch (Treemap.pivotType) {
case PivotType.pivotByMiddle:
return (children.length / 2).floor();
case PivotType.pivotBySize:
int pivotIndex = -1;
double maxSize = double.negativeInfinity;
for (int i = 0; i < children.length; i++) {
if (children[i].unsignedByteSize > maxSize) {
maxSize = children[i].unsignedByteSize.toDouble();
pivotIndex = i;
}
}
return pivotIndex;
}
}
/// Implements the ordered treemap algorithm studied in [this research paper](https://www.cs.umd.edu/~ben/papers/Shneiderman2001Ordered.pdf).
///
/// **Algorithm**
///
/// Divides a given list of treemap nodes into four parts:
/// L1, P, L2, L3.
///
/// P (pivot) is the treemap node chosen to be the pivot based on the pivot type.
/// L1 includes all treemap nodes before the pivot treemap node.
/// L2 and L3 combined include all treemap nodes after the pivot treemap node.
/// A combination of elements are put into L2 and L3 so that
/// the aspect ratio of the pivot cell (P) is as close to 1 as it can be.
///
/// **Layout**
/// ```none
/// ----------------------
/// | | P | |
/// | | | |
/// | L1 |------| L3 |
/// | | L2 | |
/// | | | |
/// ----------------------
/// ```
List<PositionedCell> buildTreemaps({
required List<TreemapNode> children,
required double x,
required double y,
required double width,
required double height,
}) {
final isHorizontalRectangle = width > height;
final totalByteSize = computeByteSizeForNodes(nodes: children);
// If there's no children or the children have a size of zero, there's
// nothing to display.
if (children.isEmpty || totalByteSize == 0) {
return [];
}
// Sort the list of treemap nodes, descending in size.
children.sort((a, b) => b.unsignedByteSize.compareTo(a.unsignedByteSize));
if (children.length <= 2) {
final positionedChildren = <PositionedCell>[];
double offset = 0;
for (final child in children) {
final ratio = child.unsignedByteSize / totalByteSize;
final newWidth = isHorizontalRectangle ? ratio * width : width;
final newHeight = isHorizontalRectangle ? height : ratio * height;
positionedChildren.add(
PositionedCell(
rect: Rect.fromLTWH(
isHorizontalRectangle ? x + offset : x,
isHorizontalRectangle ? y : y + offset,
newWidth,
newHeight,
),
node: child,
child: Treemap.fromRoot(
rootNode: child,
levelsVisible: widget.levelsVisible - 1,
onRootChangedCallback: widget.onRootChangedCallback,
width: newWidth,
height: newHeight,
),
),
);
offset += isHorizontalRectangle ? ratio * width : ratio * height;
}
return positionedChildren;
}
final pivotIndex = computePivot(children);
final pivotNode = children[pivotIndex];
final pivotByteSize = pivotNode.unsignedByteSize;
final list1 = children.sublist(0, pivotIndex);
final list1ByteSize = computeByteSizeForNodes(nodes: list1);
var list2 = <TreemapNode>[];
int list2ByteSize = 0;
var list3 = <TreemapNode>[];
int list3ByteSize = 0;
// The maximum amount of data we can put in [list3].
final l3MaxLength = children.length - pivotIndex - 1;
int bestIndex = 0;
double pivotBestWidth = 0;
double pivotBestHeight = 0;
// We need to be able to put at least 3 elements in [list3] for this algorithm.
if (l3MaxLength >= 3) {
double pivotBestAspectRatio = double.infinity;
// Iterate through different combinations of [list2] and [list3] to find
// the combination where the aspect ratio of pivot is the lowest.
for (int i = pivotIndex + 1; i < children.length; i++) {
final list2Size = computeByteSizeForNodes(
nodes: children,
startIndex: pivotIndex + 1,
endIndex: i,
);
// Calculate the aspect ratio for the pivot treemap node.
final pivotAndList2Ratio = (pivotByteSize + list2Size) / totalByteSize;
final pivotRatio = pivotByteSize / (pivotByteSize + list2Size);
final pivotWidth =
isHorizontalRectangle
? pivotAndList2Ratio * width
: pivotRatio * width;
final pivotHeight =
isHorizontalRectangle
? pivotRatio * height
: pivotAndList2Ratio * height;
final pivotAspectRatio = pivotWidth / pivotHeight;
// Best aspect ratio that is the closest to 1.
if ((1 - pivotAspectRatio).abs() < (1 - pivotBestAspectRatio).abs()) {
pivotBestAspectRatio = pivotAspectRatio;
bestIndex = i;
// Kept track of width and height to construct the pivot cell.
pivotBestWidth = pivotWidth;
pivotBestHeight = pivotHeight;
}
}
// Split the rest of the data into [list2] and [list3].
list2 = children.sublist(pivotIndex + 1, bestIndex + 1);
list2ByteSize = computeByteSizeForNodes(nodes: list2);
list3 = children.sublist(bestIndex + 1);
list3ByteSize = computeByteSizeForNodes(nodes: list3);
} else {
// Put all data in [list2] and none in [list3].
list2 = children.sublist(pivotIndex + 1);
list2ByteSize = computeByteSizeForNodes(nodes: list2);
final pivotAndList2Ratio =
(pivotByteSize + list2ByteSize) / totalByteSize;
final pivotRatio = pivotByteSize / (pivotByteSize + list2ByteSize);
pivotBestWidth =
isHorizontalRectangle
? pivotAndList2Ratio * width
: pivotRatio * width;
pivotBestHeight =
isHorizontalRectangle
? pivotRatio * height
: pivotAndList2Ratio * height;
}
final positionedTreemaps = <PositionedCell>[];
// Construct list 1 sub-treemap.
final list1SizeRatio = list1ByteSize / totalByteSize;
final list1Width = isHorizontalRectangle ? width * list1SizeRatio : width;
final list1Height =
isHorizontalRectangle ? height : height * list1SizeRatio;
if (list1.isNotEmpty) {
positionedTreemaps.addAll(
buildTreemaps(
children: list1,
x: x,
y: y,
width: list1Width,
height: list1Height,
),
);
}
// Construct list 2 sub-treemap.
final list2Width =
isHorizontalRectangle ? pivotBestWidth : width - pivotBestWidth;
final list2Height =
isHorizontalRectangle ? height - pivotBestHeight : pivotBestHeight;
final list2XCoord = isHorizontalRectangle ? list1Width : 0.0;
final list2YCoord = isHorizontalRectangle ? pivotBestHeight : list1Height;
if (list2.isNotEmpty) {
positionedTreemaps.addAll(
buildTreemaps(
children: list2,
x: x + list2XCoord,
y: y + list2YCoord,
width: list2Width,
height: list2Height,
),
);
}
// Construct pivot cell.
final pivotXCoord = isHorizontalRectangle ? list1Width : list2Width;
final pivotYCoord = isHorizontalRectangle ? 0.0 : list1Height;
positionedTreemaps.add(
PositionedCell(
rect: Rect.fromLTWH(
x + pivotXCoord,
y + pivotYCoord,
pivotBestWidth,
pivotBestHeight,
),
node: pivotNode,
child: Treemap.fromRoot(
rootNode: pivotNode,
levelsVisible: widget.levelsVisible - 1,
onRootChangedCallback: widget.onRootChangedCallback,
width: width,
height: height,
),
),
);
// Construct list 3 sub-treemap.
final list3Ratio = list3ByteSize / totalByteSize;
final list3Width = isHorizontalRectangle ? list3Ratio * width : width;
final list3Height = isHorizontalRectangle ? height : list3Ratio * height;
final list3XCoord =
isHorizontalRectangle ? list1Width + pivotBestWidth : 0.0;
final list3YCoord =
isHorizontalRectangle ? 0.0 : list1Height + pivotBestHeight;
if (list3.isNotEmpty) {
positionedTreemaps.addAll(
buildTreemaps(
children: list3,
x: x + list3XCoord,
y: y + list3YCoord,
width: list3Width,
height: list3Height,
),
);
}
return positionedTreemaps;
}
@override
Widget build(BuildContext context) {
if (widget.rootNode == null && widget.nodes!.isNotEmpty) {
// If constructed with Treemap.fromNodes
return buildSubTreemaps();
} else {
// If constructed with Treemap.fromRoot
return buildTreemap();
}
}
Widget buildSubTreemaps() {
assert(widget.nodes != null && widget.nodes!.isNotEmpty);
return LayoutBuilder(
builder: (context, constraints) {
final defaultTextStyle = Theme.of(context).regularTextStyle;
// TODO(peterdjlee): Investigate why exception is thrown without this check
// and if there are any other cases.
if (constraints.maxHeight == 0 || constraints.maxWidth == 0) {
return const SizedBox();
}
final positionedChildren = buildTreemaps(
children: widget.nodes!,
x: 0,
y: 0,
width: constraints.maxWidth,
height: constraints.maxHeight,
);
if (widget.levelsVisible == 1) {
// If this is the second to the last level, paint all cells in the last level
// instead of creating widgets to improve performance.
return DevToolsTooltip(
// A key is required to force a rebuild of the tooltips for each cell.
// Use tooltipMessage as the key to prevent rebuilds within a cell.
key: Key(hoveredNode?.displayText() ?? ''),
richMessage:
hoveredNode?.displayTextSpan(
defaultTextStyle: defaultTextStyle,
) ??
const TextSpan(text: ''),
waitDuration: tooltipWaitLong,
child: MouseRegion(
onHover: (event) => _onHover(event, positionedChildren),
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTapDown: (details) {
widget.onRootChangedCallback(hoveredNode);
},
child: CustomPaint(
painter: MultiCellPainter(
nodes: positionedChildren,
defaultTextStyle: defaultTextStyle,
),
size: Size(constraints.maxWidth, constraints.maxHeight),
),
),
),
);
} else {
// Else all widgets should still be positioned Treemap widgets.
return Stack(children: positionedChildren);
}
},
);
}
/// **Treemap widget layout**
/// ```none
/// ----------------------------
/// | Title Text |
/// |--------------------------|
/// | |
/// | Cell |
/// | |
/// | |
/// ----------------------------
/// ```
Widget buildTreemap() {
assert(widget.rootNode != null);
if (widget.rootNode!.children.isNotEmpty) {
return Padding(
padding: const EdgeInsets.all(1.0),
child: buildTreemapFromNodes(),
);
} else {
// If given a root node but its children are empty, draw itself.
return buildTreemapFromRoot();
}
}
Widget buildTreemapFromNodes() {
return Column(
children: [
if (widget.height > Treemap.minHeightToDisplayTitleText)
_TitleBar(
rootNode: widget.rootNode!,
isOutermostLevel: widget.isOutermostLevel,
onRootChangedCallback: widget.onRootChangedCallback,
),
Expanded(
child: Treemap.fromNodes(
nodes: widget.rootNode!.children,
levelsVisible: widget.levelsVisible,
onRootChangedCallback: widget.onRootChangedCallback,
width: widget.width,
height: widget.height,
),
),
],
);
}
Column buildTreemapFromRoot() {
final rootNode = widget.rootNode!;
final child = _TreeMapCell(treeMapHeight: widget.height, node: rootNode);
return Column(
children: [
if (widget.isOutermostLevel)
_TitleBar(
rootNode: widget.rootNode!,
isOutermostLevel: widget.isOutermostLevel,
onRootChangedCallback: widget.onRootChangedCallback,
),
Expanded(
child:
widget.isOutermostLevel
? child
: _SelectableTreemapNode(
node: rootNode,
onRootChangedCallback: widget.onRootChangedCallback,
child: child,
),
),
],
);
}
/// Checks if the touch point of the given [event] is overlapping with a cell
/// in [positionedCells].
///
/// If so, saves the matching hoveredNode.
void _onHover(PointerHoverEvent event, List<PositionedCell> positionedCells) {
final x = event.localPosition.dx;
final y = event.localPosition.dy;
final touchPoint = Offset(x, y);
// TODO(peterdjlee): Optimize with more efficient algorithm to find the overlapping cell.
// Currently O(positionedCells.length) but an optimized algorithm with
// O(log(positionedCells.length)) is possible.
for (final cell in positionedCells) {
if (cell.rect.contains(touchPoint)) {
setState(() {
hoveredNode = cell.node;
});
}
}
}
}
class _TreeMapCell extends StatelessWidget {
const _TreeMapCell({required this.treeMapHeight, required this.node});
final double treeMapHeight;
final TreemapNode node;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: node.displayColor,
border: Border.all(color: Colors.black87),
),
child: Center(
child:
treeMapHeight > Treemap.minHeightToDisplayCellText
? _NameAndSizeText(
node: node,
color: node.showDiff ? Colors.white : Colors.black,
singleLine: false,
)
: const SizedBox(),
),
);
}
}
class _TitleBar extends StatelessWidget {
const _TitleBar({
required this.rootNode,
required this.onRootChangedCallback,
required this.isOutermostLevel,
});
final TreemapNode rootNode;
final void Function(TreemapNode? node) onRootChangedCallback;
final bool isOutermostLevel;
@override
Widget build(BuildContext context) {
if (isOutermostLevel) {
return _BreadcrumbNavigator(
pathFromRoot: rootNode.pathFromRoot(),
onRootChangedCallback: onRootChangedCallback,
);
} else {
return _SelectableTreemapNode(
node: rootNode,
onRootChangedCallback: onRootChangedCallback,
child: Container(
height: Treemap.treeMapHeaderHeight,
width: double.infinity,
decoration: BoxDecoration(border: Border.all(color: Colors.black87)),
child: _NameAndSizeText(
node: rootNode,
color: Theme.of(context).colorScheme.onSurface,
singleLine: true,
),
),
);
}
}
}
class _NameAndSizeText extends StatelessWidget {
const _NameAndSizeText({
required this.node,
required this.color,
required this.singleLine,
});
final TreemapNode node;
final Color color;
final bool singleLine;
@override
Widget build(BuildContext context) {
return RichText(
text: node.displayTextSpan(
singleLine: singleLine,
color: color,
defaultTextStyle: Theme.of(context).regularTextStyle,
),
selectionColor: color,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
);
}
}
class _BreadcrumbNavigator extends StatelessWidget {
const _BreadcrumbNavigator({
required this.pathFromRoot,
required this.onRootChangedCallback,
});
final List<TreemapNode> pathFromRoot;
final void Function(TreemapNode? node) onRootChangedCallback;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: denseRowSpacing),
child: BreadcrumbNavigator.builder(
itemCount: pathFromRoot.length,
builder: (context, index) {
final node = pathFromRoot[index];
return Breadcrumb(
text:
index < pathFromRoot.length - 1
? node.name
: node.displayText(),
isRoot: index == 0,
onPressed: () => onRootChangedCallback(node),
);
},
),
);
}
}
/// A selectable container with [child] as its child.
///
/// Selecting this widget will trigger a re-root of the tree
/// to [node].
class _SelectableTreemapNode extends StatelessWidget {
const _SelectableTreemapNode({
required this.node,
required this.onRootChangedCallback,
required this.child,
});
final TreemapNode node;
final void Function(TreemapNode? node) onRootChangedCallback;
final Widget child;
@override
Widget build(BuildContext context) {
return DevToolsTooltip(
message: node.displayText(),
waitDuration: tooltipWaitLong,
child: InkWell(
onTap: () {
onRootChangedCallback(node);
},
child: child,
),
);
}
}
class TreemapNode extends TreeNode<TreemapNode> {
TreemapNode({
required this.name,
this.byteSize = 0,
this.childrenMap = const <String, TreemapNode>{},
this.showDiff = false,
this.backgroundColor,
this.caption,
});
final String name;
final Map<String, TreemapNode> childrenMap;
int byteSize;
final bool showDiff;
final Color? backgroundColor;
final String? caption;
int get unsignedByteSize => byteSize.abs();
Color get displayColor {
if (!showDiff) {
return backgroundColor ?? mainUiColor;
}
return byteSize < 0 ? treemapDecreaseColor : treemapIncreaseColor;
}
String displayText({bool singleLine = true, bool includeCaption = true}) {
var displayName = name;
// Trim beginning of the name of [this] if it starts with its parent's name.
// If the parent node and the child node's name are exactly the same,
// do not trim in order to avoid empty names.
final parent = this.parent;
if (parent != null) {
final parentName = parent.name;
if (displayName.startsWith(parentName) && displayName != parentName) {
displayName = displayName.replaceFirst(parentName, '');
if (displayName.startsWith('/')) {
displayName = displayName.replaceFirst('/', '');
}
}
}
final separator = singleLine ? ' ' : '\n';
displayName = '$displayName$separator[${prettyByteSize()}]';
if (includeCaption && caption != null) {
displayName = '$displayName$separator$caption';
}
return displayName;
}
TextSpan displayTextSpan({
required TextStyle defaultTextStyle,
Color? color,
bool singleLine = true,
}) {
final textColor = color ?? (showDiff ? Colors.white : Colors.black);
final separator = singleLine ? ' ' : '\n';
return TextSpan(
text: displayText(includeCaption: false, singleLine: singleLine),
style: defaultTextStyle.copyWith(color: textColor),
children: [
if (caption != null)
TextSpan(
text: '$separator$caption',
style: defaultTextStyle.copyWith(
fontStyle: FontStyle.italic,
color: textColor,
),
),
],
);
}
String prettyByteSize() {
// Negative sign isn't explicitly added since a regular print of a negative number includes it.
final plusSign = showDiff && byteSize > 0 ? '+' : '';
return '$plusSign${prettyPrintBytes(byteSize, includeUnit: true)}';
}
/// Returns a list of [TreemapNode] in the path from root node to `this`.
List<TreemapNode> pathFromRoot() {
TreemapNode? node = this;
final path = <TreemapNode>[];
while (node != null) {
path.add(node);
node = node.parent;
}
return path.reversed.toList();
}
/// Returns the package path for this node.
///
/// Includes only package nodes (nodes that start with 'package:').
List<String> packagePath() {
final reversedPath = <String>[];
TreemapNode? current = this;
while (current != null) {
if (current.name.contains('(Dart AOT)')) {
// This as far up the tree as we want to go, since this is the root of
// the Dart AOT snapshot.
return reversedPath.reversed.toList();
}
// Prevent duplicated package names from being added to the path.
// Sometimes the hierarchy can look like this:
// package:a
// package: a
// <Type>
// <OneByteString>
if ((current.name.startsWith('package:') ||
current.name.startsWith('dart:')) &&
(reversedPath.isEmpty || reversedPath.last != current.name)) {
reversedPath.add(current.name);
}
current = current.parent;
}
return [];
}
void printTree() {
printTreeHelper(this, '');
}
void printTreeHelper(TreemapNode root, String tabs) {
_log.info('$tabs$root');
for (final child in root.children) {
printTreeHelper(child, '$tabs\t');
}
}
@override
String toString() {
return '{name: $name, size: $byteSize}';
}
@override
TreemapNode shallowCopy() {
throw UnimplementedError(
'This method is not implemented. Implement if you '
'need to call `shallowCopy` on an instance of this class.',
);
}
}
class PositionedCell extends Positioned {
PositionedCell({
super.key,
required this.rect,
required this.node,
required super.child,
}) : super(
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
);
final Rect rect;
final TreemapNode node;
}
class MultiCellPainter extends CustomPainter {
const MultiCellPainter({required this.nodes, required this.defaultTextStyle});
final List<PositionedCell> nodes;
final TextStyle defaultTextStyle;
@override
void paint(Canvas canvas, Size size) {
for (final positionedCell in nodes) {
paintCell(
canvas,
Size(positionedCell.width!, positionedCell.height!),
positionedCell,
);
}
}
void paintCell(Canvas canvas, Size size, PositionedCell positionedCell) {
final node = positionedCell.node;
final bounds = Rect.fromLTWH(
positionedCell.left!,
positionedCell.top!,
size.width,
size.height,
);
final rectPaint = Paint();
rectPaint.color = node.displayColor;
canvas.drawRect(bounds, rectPaint);
final borderPaint =
Paint()
..color = Colors.black45
..style = PaintingStyle.stroke;
canvas.drawRect(bounds, borderPaint);
if (positionedCell.width! > Treemap.minWidthToDisplayCellText &&
positionedCell.height! > Treemap.minHeightToDisplayCellText) {
final textPainter = TextPainter(
text: node.displayTextSpan(
defaultTextStyle: defaultTextStyle,
singleLine: false,
),
textDirection: TextDirection.ltr,
textAlign: TextAlign.center,
ellipsis: '...',
)..layout(maxWidth: size.width);
final centerX =
positionedCell.left! + bounds.width / 2 - textPainter.width / 2;
final centerY =
positionedCell.top! + bounds.height / 2 - textPainter.height / 2;
textPainter
..paint(canvas, Offset(centerX, centerY))
..dispose();
}
}
@override
bool shouldRepaint(MultiCellPainter oldDelegate) {
return false;
}
}