forked from react/react-native-devtools-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimelineFlameChartDataProvider.ts
More file actions
1364 lines (1212 loc) · 53.6 KB
/
Copy pathTimelineFlameChartDataProvider.ts
File metadata and controls
1364 lines (1212 loc) · 53.6 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 (C) 2014 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Root from '../../core/root/root.js';
import * as Bindings from '../../models/bindings/bindings.js';
import * as Trace from '../../models/trace/trace.js';
import * as PerfUI from '../../ui/legacy/components/perf_ui/perf_ui.js';
import * as UI from '../../ui/legacy/legacy.js';
import * as ThemeSupport from '../../ui/legacy/theme_support/theme_support.js';
import {CompatibilityTracksAppender, type DrawOverride, type TrackAppenderName} from './CompatibilityTracksAppender.js';
import {initiatorsDataToDraw} from './Initiators.js';
import {ModificationsManager} from './ModificationsManager.js';
import {ThreadAppender} from './ThreadAppender.js';
import timelineFlamechartPopoverStyles from './timelineFlamechartPopover.css.js';
import {FlameChartStyle, Selection} from './TimelineFlameChartView.js';
import {
selectionFromEvent,
selectionIsRange,
selectionsEqual,
type TimelineSelection,
} from './TimelineSelection.js';
import * as Utils from './utils/utils.js';
const UIStrings = {
/**
*@description Text for rendering frames
*/
frames: 'Frames',
/**
*@description Text in Timeline Flame Chart Data Provider of the Performance panel
*/
idleFrame: 'Idle frame',
/**
*@description Text in Timeline Frame Chart Data Provider of the Performance panel
*/
droppedFrame: 'Dropped frame',
/**
*@description Text in Timeline Frame Chart Data Provider of the Performance panel
*/
partiallyPresentedFrame: 'Partially-presented frame',
/**
*@description Text for a rendering frame
*/
frame: 'Frame',
/**
*@description Text for Hiding a function from the Flame Chart
*/
hideFunction: 'Hide function',
/**
*@description Text for Hiding all children of a function from the Flame Chart
*/
hideChildren: 'Hide children',
/**
*@description Text for Hiding all child entries that are identical to the selected entry from the Flame Chart
*/
hideRepeatingChildren: 'Hide repeating children',
/**
*@description Text for remove script from ignore list from the Flame Chart
*/
removeScriptFromIgnoreList: 'Remove script from ignore list',
/**
*@description Text for add script to ignore list from the Flame Chart
*/
addScriptToIgnoreList: 'Add script to ignore list',
/**
*@description Text for an action that shows all of the hidden children of an entry
*/
resetChildren: 'Reset children',
/**
*@description Text for an action that shows all of the hidden entries of the Flame Chart
*/
resetTrace: 'Reset trace',
} as const;
const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineFlameChartDataProvider.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
export class TimelineFlameChartDataProvider extends Common.ObjectWrapper.ObjectWrapper<EventTypes> implements
PerfUI.FlameChart.FlameChartDataProvider {
private isReactNative = false;
private droppedFramePatternCanvas: HTMLCanvasElement;
private partialFramePatternCanvas: HTMLCanvasElement;
private timelineDataInternal: PerfUI.FlameChart.FlameChartTimelineData|null = null;
private currentLevel = 0;
private compatibilityTracksAppender: CompatibilityTracksAppender|null = null;
private parsedTrace: Trace.Handlers.Types.ParsedTrace|null = null;
#minimumBoundary = 0;
private timeSpan = 0;
private readonly framesGroupStyle: PerfUI.FlameChart.GroupStyle;
private readonly screenshotsGroupStyle: PerfUI.FlameChart.GroupStyle;
// Contains all the entries that are DRAWN onto the track. Entries that have
// been hidden - either by a user action, or because they aren't visible at
// all - will not appear in this array and it will change per-render. For
// example, if a user collapses an icicle in the flamechart, those entries
// that are now hidden will no longer be in this array.
// This also includes entrys that used to be special cased (e.g.
// TimelineFrames) that are now of type Types.Events.Event and so the old
// `TimelineFlameChartEntry` type has been removed in faovur of using
// Trace.Types.Events.Event directly. See crrev.com/c/5973695 for details.
private entryData: Trace.Types.Events.Event[] = [];
private entryTypeByLevel: EntryType[] = [];
private entryIndexToTitle: string[] = [];
private lastInitiatorEntry = -1;
private lastInitiatorsData: PerfUI.FlameChart.FlameChartInitiatorData[] = [];
private lastSelection: Selection|null = null;
readonly #font = `${PerfUI.Font.DEFAULT_FONT_SIZE} ${PerfUI.Font.getFontFamilyForCanvas()}`;
#eventIndexByEvent = new WeakMap<Trace.Types.Events.Event, number|null>();
#entityMapper: Utils.EntityMapper.EntityMapper|null = null;
constructor() {
super();
// [RN] Used to scope down available features for React Native targets
this.isReactNative = Root.Runtime.experiments.isEnabled(
Root.Runtime.ExperimentName.REACT_NATIVE_SPECIFIC_UI,
);
this.reset();
this.droppedFramePatternCanvas = document.createElement('canvas');
this.partialFramePatternCanvas = document.createElement('canvas');
this.preparePatternCanvas();
this.framesGroupStyle = this.buildGroupStyle({useFirstLineForOverview: true});
this.screenshotsGroupStyle =
this.buildGroupStyle({useFirstLineForOverview: true, nestingLevel: 1, collapsible: false, itemsHeight: 150});
ThemeSupport.ThemeSupport.instance().addEventListener(ThemeSupport.ThemeChangeEvent.eventName, () => {
const headers = [
this.framesGroupStyle,
this.screenshotsGroupStyle,
];
for (const header of headers) {
header.color = ThemeSupport.ThemeSupport.instance().getComputedValue('--sys-color-on-surface');
header.backgroundColor =
ThemeSupport.ThemeSupport.instance().getComputedValue('--sys-color-cdt-base-container');
}
});
Utils.ImageCache.emitter.addEventListener(
'screenshot-loaded', () => this.dispatchEventToListeners(Events.DATA_CHANGED));
Common.Settings.Settings.instance()
.moduleSetting('skip-stack-frames-pattern')
.addChangeListener(this.#onIgnoreListChanged.bind(this));
Common.Settings.Settings.instance()
.moduleSetting('skip-content-scripts')
.addChangeListener(this.#onIgnoreListChanged.bind(this));
Common.Settings.Settings.instance()
.moduleSetting('automatically-ignore-list-known-third-party-scripts')
.addChangeListener(this.#onIgnoreListChanged.bind(this));
Common.Settings.Settings.instance()
.moduleSetting('enable-ignore-listing')
.addChangeListener(this.#onIgnoreListChanged.bind(this));
Common.Settings.Settings.instance()
.moduleSetting('skip-anonymous-scripts')
.addChangeListener(this.#onIgnoreListChanged.bind(this));
}
hasTrackConfigurationMode(): boolean {
return true;
}
getPossibleActions(entryIndex: number, groupIndex: number): PerfUI.FlameChart.PossibleFilterActions|void {
const data = this.timelineData();
if (!data) {
return;
}
const group = data.groups.at(groupIndex);
// Early exit here if there is no group or:
// 1. The group is not expanded: it needs to be expanded to allow the
// context menu actions to occur.
// 2. The group does not have the showStackContextMenu flag which indicates
// that it does not show entries that support the stack actions.
if (!group || !group.expanded || !group.showStackContextMenu) {
return;
}
// Check which actions are possible on an entry.
// If an action would not change the entries (for example it has no children to collapse), we do not need to show it.
return this.findPossibleContextMenuActions(entryIndex);
}
customizedContextMenu(mouseEvent: MouseEvent, entryIndex: number, groupIndex: number): UI.ContextMenu.ContextMenu
|undefined {
const entry = this.eventByIndex(entryIndex);
if (!entry) {
return;
}
const possibleActions = this.getPossibleActions(entryIndex, groupIndex);
// This action and its 'execute' is defined in `freestyler-meta`
const PERF_AI_ACTION_ID = 'drjones.performance-panel-context';
const perfAIEntryPointEnabled =
Boolean(entry && this.parsedTrace && UI.ActionRegistry.ActionRegistry.instance().hasAction(PERF_AI_ACTION_ID));
if (!possibleActions && !perfAIEntryPointEnabled) {
// Early exit: no possible actions (e.g. collapsing children) and no AI
// entrypoint, so we don't need to do anything.
return;
}
const contextMenu = new UI.ContextMenu.ContextMenu(mouseEvent);
if (perfAIEntryPointEnabled && this.parsedTrace) {
const aiCallTree = Utils.AICallTree.AICallTree.fromEvent(entry, this.parsedTrace);
if (aiCallTree) {
const action = UI.ActionRegistry.ActionRegistry.instance().getAction(PERF_AI_ACTION_ID);
contextMenu.footerSection().appendItem(action.title(), () => {
const event = this.eventByIndex(entryIndex);
if (!event || !this.parsedTrace) {
return;
}
// The other side of setFlavor is handleTraceEntryNodeFlavorChange() in FreestylerPanel
UI.Context.Context.instance().setFlavor(Utils.AICallTree.AICallTree, aiCallTree);
return action.execute();
}, {jslogContext: PERF_AI_ACTION_ID});
}
}
if (!possibleActions) {
// All the code below here adds possible actions to the context menu,
// some of which may be marked as disabled. If we didn't get any possible
// actions, rather than add them all and mark all of them as disabled, we
// early exit + don't add any of them.
return contextMenu;
}
const hideEntryOption = contextMenu.defaultSection().appendItem(i18nString(UIStrings.hideFunction), () => {
this.modifyTree(PerfUI.FlameChart.FilterAction.MERGE_FUNCTION, entryIndex);
}, {
disabled: !possibleActions?.[PerfUI.FlameChart.FilterAction.MERGE_FUNCTION],
jslogContext: 'hide-function',
});
hideEntryOption.setAccelerator(UI.KeyboardShortcut.Keys.H, [UI.KeyboardShortcut.Modifiers.None]);
hideEntryOption.setIsDevToolsPerformanceMenuItem(true);
const hideChildrenOption = contextMenu.defaultSection().appendItem(i18nString(UIStrings.hideChildren), () => {
this.modifyTree(PerfUI.FlameChart.FilterAction.COLLAPSE_FUNCTION, entryIndex);
}, {
disabled: !possibleActions?.[PerfUI.FlameChart.FilterAction.COLLAPSE_FUNCTION],
jslogContext: 'hide-children',
});
hideChildrenOption.setAccelerator(UI.KeyboardShortcut.Keys.C, [UI.KeyboardShortcut.Modifiers.None]);
hideChildrenOption.setIsDevToolsPerformanceMenuItem(true);
const hideRepeatingChildrenOption =
contextMenu.defaultSection().appendItem(i18nString(UIStrings.hideRepeatingChildren), () => {
this.modifyTree(PerfUI.FlameChart.FilterAction.COLLAPSE_REPEATING_DESCENDANTS, entryIndex);
}, {
disabled: !possibleActions?.[PerfUI.FlameChart.FilterAction.COLLAPSE_REPEATING_DESCENDANTS],
jslogContext: 'hide-repeating-children',
});
hideRepeatingChildrenOption.setAccelerator(UI.KeyboardShortcut.Keys.R, [UI.KeyboardShortcut.Modifiers.None]);
hideRepeatingChildrenOption.setIsDevToolsPerformanceMenuItem(true);
const resetChildrenOption = contextMenu.defaultSection().appendItem(i18nString(UIStrings.resetChildren), () => {
this.modifyTree(PerfUI.FlameChart.FilterAction.RESET_CHILDREN, entryIndex);
}, {
disabled: !possibleActions?.[PerfUI.FlameChart.FilterAction.RESET_CHILDREN],
jslogContext: 'reset-children',
});
resetChildrenOption.setAccelerator(UI.KeyboardShortcut.Keys.U, [UI.KeyboardShortcut.Modifiers.None]);
resetChildrenOption.setIsDevToolsPerformanceMenuItem(true);
contextMenu.defaultSection().appendItem(i18nString(UIStrings.resetTrace), () => {
this.modifyTree(PerfUI.FlameChart.FilterAction.UNDO_ALL_ACTIONS, entryIndex);
}, {
disabled: !possibleActions?.[PerfUI.FlameChart.FilterAction.UNDO_ALL_ACTIONS],
jslogContext: 'reset-trace',
});
if (!this.parsedTrace || Trace.Types.Events.isLegacyTimelineFrame(entry)) {
return contextMenu;
}
const url = Utils.SourceMapsResolver.SourceMapsResolver.resolvedURLForEntry(this.parsedTrace, entry);
if (!url) {
return contextMenu;
}
if (Utils.IgnoreList.isIgnoreListedEntry(entry)) {
contextMenu.defaultSection().appendItem(i18nString(UIStrings.removeScriptFromIgnoreList), () => {
Bindings.IgnoreListManager.IgnoreListManager.instance().unIgnoreListURL(url);
this.#onIgnoreListChanged();
}, {
jslogContext: 'remove-from-ignore-list',
});
} else {
contextMenu.defaultSection().appendItem(i18nString(UIStrings.addScriptToIgnoreList), () => {
Bindings.IgnoreListManager.IgnoreListManager.instance().ignoreListURL(url);
this.#onIgnoreListChanged();
}, {
jslogContext: 'add-to-ignore-list',
});
}
return contextMenu;
}
#onIgnoreListChanged(): void {
this.timelineData(/* rebuild= */ true);
this.dispatchEventToListeners(Events.DATA_CHANGED);
}
entryHasAnnotations(entryIndex: number): boolean {
const event = this.eventByIndex(entryIndex);
if (!event) {
return false;
}
const annotations = ModificationsManager.activeManager()?.annotationsForEntry(event);
return annotations ? annotations.length > 0 : false;
}
deleteAnnotationsForEntry(entryIndex: number): void {
const event = this.eventByIndex(entryIndex);
if (!event) {
return;
}
ModificationsManager.activeManager()?.deleteEntryAnnotations(event);
}
modifyTree(action: PerfUI.FlameChart.FilterAction, entryIndex: number): void {
const entry = this.entryData[entryIndex];
ModificationsManager.activeManager()?.getEntriesFilter().applyFilterAction({type: action, entry});
this.timelineData(true);
this.buildFlowForInitiator(entryIndex);
this.dispatchEventToListeners(Events.DATA_CHANGED);
}
findPossibleContextMenuActions(entryIndex: number): PerfUI.FlameChart.PossibleFilterActions|void {
const entry = this.entryData[entryIndex];
return ModificationsManager.activeManager()?.getEntriesFilter().findPossibleActions(entry);
}
handleFlameChartTransformKeyboardEvent(event: KeyboardEvent, entryIndex: number, groupIndex: number): void {
const possibleActions = this.getPossibleActions(entryIndex, groupIndex);
if (!possibleActions) {
return;
}
let handled = false;
if (event.code === 'KeyH' && possibleActions[PerfUI.FlameChart.FilterAction.MERGE_FUNCTION]) {
this.modifyTree(PerfUI.FlameChart.FilterAction.MERGE_FUNCTION, entryIndex);
handled = true;
} else if (event.code === 'KeyC' && possibleActions[PerfUI.FlameChart.FilterAction.COLLAPSE_FUNCTION]) {
this.modifyTree(PerfUI.FlameChart.FilterAction.COLLAPSE_FUNCTION, entryIndex);
handled = true;
} else if (
event.code === 'KeyR' && possibleActions[PerfUI.FlameChart.FilterAction.COLLAPSE_REPEATING_DESCENDANTS]) {
this.modifyTree(PerfUI.FlameChart.FilterAction.COLLAPSE_REPEATING_DESCENDANTS, entryIndex);
handled = true;
} else if (event.code === 'KeyU') {
this.modifyTree(PerfUI.FlameChart.FilterAction.RESET_CHILDREN, entryIndex);
handled = true;
}
if (handled) {
event.consume(true);
}
}
private buildGroupStyle(extra: Object): PerfUI.FlameChart.GroupStyle {
const defaultGroupStyle = {
padding: 4,
height: 17,
collapsible: true,
color: ThemeSupport.ThemeSupport.instance().getComputedValue('--sys-color-on-surface'),
backgroundColor: ThemeSupport.ThemeSupport.instance().getComputedValue('--sys-color-cdt-base-container'),
nestingLevel: 0,
shareHeaderLine: true,
};
return Object.assign(defaultGroupStyle, extra);
}
setModel(parsedTrace: Trace.Handlers.Types.ParsedTrace, entityMapper: Utils.EntityMapper.EntityMapper): void {
this.reset();
this.parsedTrace = parsedTrace;
const {traceBounds} = parsedTrace.Meta;
const minTime = Trace.Helpers.Timing.microToMilli(traceBounds.min);
const maxTime = Trace.Helpers.Timing.microToMilli(traceBounds.max);
this.#minimumBoundary = minTime;
this.timeSpan = minTime === maxTime ? 1000 : maxTime - this.#minimumBoundary;
this.#entityMapper = entityMapper;
}
/**
* Instances and caches a CompatibilityTracksAppender using the
* internal flame chart data and the trace parsed data coming from the
* trace engine.
* The model data must have been set to the data provider instance before
* attempting to instance the CompatibilityTracksAppender.
*/
compatibilityTracksAppenderInstance(forceNew = false): CompatibilityTracksAppender {
if (!this.compatibilityTracksAppender || forceNew) {
if (!this.parsedTrace) {
throw new Error(
'Attempted to instantiate a CompatibilityTracksAppender without having set the trace parse data first.');
}
this.timelineDataInternal = this.#instantiateTimelineData();
this.compatibilityTracksAppender = new CompatibilityTracksAppender(
this.timelineDataInternal, this.parsedTrace, this.entryData, this.entryTypeByLevel, this.#entityMapper);
}
return this.compatibilityTracksAppender;
}
/**
* Returns the instance of the timeline flame chart data, without
* adding data to it. In case the timeline data hasn't been instanced
* creates a new instance and returns it.
*/
#instantiateTimelineData(): PerfUI.FlameChart.FlameChartTimelineData {
if (!this.timelineDataInternal) {
this.timelineDataInternal = PerfUI.FlameChart.FlameChartTimelineData.createEmpty();
}
return this.timelineDataInternal;
}
/**
* Builds the flame chart data using the track appenders
*/
buildFromTrackAppendersForTest(options?: {filterThreadsByName?: string, expandedTracks?: Set<TrackAppenderName>}):
void {
if (!this.compatibilityTracksAppender) {
return;
}
const appenders = this.compatibilityTracksAppender.allVisibleTrackAppenders();
for (const appender of appenders) {
const skipThreadAppenderByName =
appender instanceof ThreadAppender && !appender.trackName().includes(options?.filterThreadsByName || '');
if (skipThreadAppenderByName) {
continue;
}
const expanded = Boolean(options?.expandedTracks?.has(appender.appenderName));
this.currentLevel = appender.appendTrackAtLevel(this.currentLevel, expanded);
}
}
groupTreeEvents(group: PerfUI.FlameChart.Group): Trace.Types.Events.Event[]|null {
return this.compatibilityTracksAppender?.groupEventsForTreeView(group) ?? null;
}
mainFrameNavigationStartEvents(): readonly Trace.Types.Events.NavigationStart[] {
if (!this.parsedTrace) {
return [];
}
return this.parsedTrace.Meta.mainFrameNavigations;
}
entryTitle(entryIndex: number): string|null {
const entryType = this.#entryTypeForIndex(entryIndex);
if (entryType === EntryType.SCREENSHOT) {
return '';
}
if (entryType === EntryType.TRACK_APPENDER) {
const timelineData = (this.timelineDataInternal as PerfUI.FlameChart.FlameChartTimelineData);
const eventLevel = timelineData.entryLevels[entryIndex];
const event = (this.entryData[entryIndex]);
return this.compatibilityTracksAppender?.titleForEvent(event, eventLevel) || null;
}
let title: Common.UIString.LocalizedString|string = this.entryIndexToTitle[entryIndex];
if (!title) {
title = `Unexpected entryIndex ${entryIndex}`;
console.error(title);
}
return title;
}
textColor(index: number): string {
const event = this.entryData[index];
return Utils.IgnoreList.isIgnoreListedEntry(event) ? '#888' : FlameChartStyle.textColor;
}
entryFont(_index: number): string|null {
return this.#font;
}
/**
* Clear the cache and rebuild the timeline data This should be called
* when the trace file is the same but we want to rebuild the timeline
* data. Some possible example: when we hide/unhide an event, or the
* ignore list is changed etc.
*/
rebuildTimelineData(): void {
this.currentLevel = 0;
this.entryData = [];
this.entryTypeByLevel = [];
this.entryIndexToTitle = [];
this.#eventIndexByEvent = new Map();
if (this.timelineDataInternal) {
this.compatibilityTracksAppender?.setFlameChartDataAndEntryData(
this.timelineDataInternal, this.entryData, this.entryTypeByLevel);
this.compatibilityTracksAppender?.threadAppenders().forEach(
threadAppender => threadAppender.setHeaderAppended(false));
}
}
/**
* Reset all data other than the UI elements.
* This should be called when
* - initialized the data provider
* - a new trace file is coming (when `setModel()` is called)
* etc.
*/
reset(): void {
this.currentLevel = 0;
this.entryData = [];
this.entryTypeByLevel = [];
this.entryIndexToTitle = [];
this.#eventIndexByEvent = new Map();
this.#minimumBoundary = 0;
this.timeSpan = 0;
this.compatibilityTracksAppender?.reset();
this.compatibilityTracksAppender = null;
this.timelineDataInternal = null;
this.parsedTrace = null;
this.#entityMapper = null;
}
maxStackDepth(): number {
return this.currentLevel;
}
/**
* Builds the flame chart data using the tracks appender (which use
* the new trace engine). The result built data is cached and returned.
*/
timelineData(rebuild = false): PerfUI.FlameChart.FlameChartTimelineData {
if (!rebuild && this.timelineDataInternal && this.timelineDataInternal.entryLevels.length !== 0) {
// If the flame chart data is built already and we don't want to rebuild, we can return the cached data.
// |entryLevels.length| is used to check if the cached data is not empty (correctly built),
return this.timelineDataInternal;
}
this.timelineDataInternal = PerfUI.FlameChart.FlameChartTimelineData.createEmpty();
if (rebuild) {
// This function will interact with the |compatibilityTracksAppender|, which needs the reference of
// |timelineDataInternal|, so make sure this is called after the correct |timelineDataInternal|.
this.rebuildTimelineData();
}
this.currentLevel = 0;
if (this.parsedTrace) {
this.compatibilityTracksAppender = this.compatibilityTracksAppenderInstance();
if (this.parsedTrace.Meta.traceIsGeneric) {
this.#processGenericTrace();
} else {
this.#processInspectorTrace();
}
}
return this.timelineDataInternal;
}
/**
* Register the groups (aka tracks) with the VisualElements framework so
* later on we can log when an entry inside this group is selected.
*/
#processGenericTrace(): void {
if (!this.compatibilityTracksAppender) {
return;
}
const appendersByProcess = this.compatibilityTracksAppender.allThreadAppendersByProcess();
for (const [pid, threadAppenders] of appendersByProcess) {
const processGroupStyle = this.buildGroupStyle({shareHeaderLine: false});
const processName = this.parsedTrace?.Meta.processNames.get(pid)?.args.name || 'Process';
this.appendHeader(`${processName} (${pid})`, processGroupStyle, true, false);
for (const appender of threadAppenders) {
appender.setHeaderNestingLevel(1);
this.currentLevel = appender.appendTrackAtLevel(this.currentLevel);
}
}
}
#processInspectorTrace(): void {
// In CPU Profiles the trace data will not have frames nor
// screenshots, so we can keep this call as it will be a no-op in
// these cases.
this.#appendFramesAndScreenshotsTrack();
const weight = (track: {type?: string, forMainFrame?: boolean, appenderName?: TrackAppenderName}): number => {
switch (track.appenderName) {
case 'Animations':
return 0;
case 'Timings':
return 1;
case 'Interactions':
return 2;
case 'LayoutShifts':
return 3;
case 'Extension':
return 4;
case 'Thread':
return 5;
case 'ServerTimings':
return 6;
case 'GPU':
return 7;
case 'Thread_AuctionWorklet':
return 8;
default:
return 9;
}
};
const allTrackAppenders =
this.compatibilityTracksAppender ? this.compatibilityTracksAppender.allVisibleTrackAppenders() : [];
allTrackAppenders.sort((a, b) => weight(a) - weight(b));
for (const appender of allTrackAppenders) {
if (!this.parsedTrace) {
continue;
}
this.currentLevel = appender.appendTrackAtLevel(this.currentLevel);
// If there is not a selected group, we want to default to selecting the
// main thread track. Therefore in this check we look to see if the
// current appender is a ThreadAppender and represnets the Main Thread.
// If it is, we mark the group as selected.
if (this.timelineDataInternal && !this.timelineDataInternal.selectedGroup) {
if (appender instanceof ThreadAppender &&
(appender.threadType === Trace.Handlers.Threads.ThreadType.MAIN_THREAD ||
appender.threadType === Trace.Handlers.Threads.ThreadType.CPU_PROFILE)) {
const group = this.compatibilityTracksAppender?.groupForAppender(appender);
if (group) {
this.timelineDataInternal.selectedGroup = group;
}
}
}
}
if (this.timelineDataInternal?.selectedGroup) {
this.timelineDataInternal.selectedGroup.expanded = true;
}
}
minimumBoundary(): number {
return this.#minimumBoundary;
}
totalTime(): number {
return this.timeSpan;
}
search(visibleWindow: Trace.Types.Timing.TraceWindowMicro, filter?: Trace.Extras.TraceFilter.TraceFilter):
PerfUI.FlameChart.DataProviderSearchResult[] {
const results: PerfUI.FlameChart.DataProviderSearchResult[] = [];
this.timelineData();
for (let i = 0; i < this.entryData.length; ++i) {
const entry = this.entryData[i];
if (!entry) {
continue;
}
if (Trace.Types.Events.isLegacyTimelineFrame(entry)) {
continue;
}
if (Trace.Types.Events.isLegacyScreenshot(entry)) {
// Screenshots are represented as trace events, but you can't search for them, so skip.
continue;
}
if (!Trace.Helpers.Timing.eventIsInBounds(entry, visibleWindow)) {
continue;
}
if (!filter || filter.accept(entry, this.parsedTrace || undefined)) {
const startTimeMilli = Trace.Helpers.Timing.microToMilli(entry.ts);
results.push({index: i, startTimeMilli, provider: 'main'});
}
}
return results;
}
getEntryTypeForLevel(level: number): EntryType {
return this.entryTypeByLevel[level];
}
/**
* The frames and screenshots track is special cased because it is rendered
* differently to the rest of the tracks and not as a series of events. This
* is why it is not done via the appender system; we track frames &
* screenshots as a different EntryType to the TrackAppender entries,
* because then when it comes to drawing we can decorate them differently.
**/
#appendFramesAndScreenshotsTrack(): void {
if (!this.parsedTrace) {
return;
}
const filmStrip = Trace.Extras.FilmStrip.fromParsedTrace(this.parsedTrace);
const hasScreenshots = filmStrip.frames.length > 0;
const hasFrames = this.parsedTrace.Frames.frames.length > 0;
if (!hasFrames && !hasScreenshots) {
return;
}
this.framesGroupStyle.collapsible = hasScreenshots;
const expanded = Root.Runtime.Runtime.queryParam('flamechart-force-expand') === 'frames';
this.appendHeader(i18nString(UIStrings.frames), this.framesGroupStyle, false /* selectable */, expanded);
this.entryTypeByLevel[this.currentLevel] = EntryType.FRAME;
for (const frame of this.parsedTrace.Frames.frames) {
this.#appendFrame(frame);
}
++this.currentLevel;
if (!hasScreenshots) {
return;
}
this.#appendScreenshots(filmStrip);
}
#appendScreenshots(filmStrip: Trace.Extras.FilmStrip.Data): void {
if (!this.timelineDataInternal || !this.parsedTrace) {
return;
}
this.appendHeader('', this.screenshotsGroupStyle, false /* selectable */);
this.entryTypeByLevel[this.currentLevel] = EntryType.SCREENSHOT;
let prevTimestamp: Trace.Types.Timing.Milli|undefined = undefined;
for (const filmStripFrame of filmStrip.frames) {
const screenshotTimeInMilliSeconds = Trace.Helpers.Timing.microToMilli(filmStripFrame.screenshotEvent.ts);
this.entryData.push(filmStripFrame.screenshotEvent);
(this.timelineDataInternal.entryLevels as number[]).push(this.currentLevel);
(this.timelineDataInternal.entryStartTimes as number[]).push(screenshotTimeInMilliSeconds);
if (prevTimestamp) {
(this.timelineDataInternal.entryTotalTimes as number[]).push(screenshotTimeInMilliSeconds - prevTimestamp);
}
prevTimestamp = screenshotTimeInMilliSeconds;
}
if (filmStrip.frames.length && prevTimestamp !== undefined) {
const maxRecordTimeMillis = Trace.Helpers.Timing.traceWindowMilliSeconds(this.parsedTrace.Meta.traceBounds).max;
// Set the total time of the final screenshot so it takes up the remainder of the trace.
(this.timelineDataInternal.entryTotalTimes as number[]).push(maxRecordTimeMillis - prevTimestamp);
}
++this.currentLevel;
}
#entryTypeForIndex(entryIndex: number): EntryType {
const level = this.timelineData().entryLevels[entryIndex];
return this.entryTypeByLevel[level];
}
preparePopoverElement(entryIndex: number): Element|null {
let time = '';
let title;
let warningElements: Element[] = [];
let timeElementClassName = 'popoverinfo-time';
const additionalContent: HTMLElement[] = [];
const entryType = this.#entryTypeForIndex(entryIndex);
if (entryType === EntryType.TRACK_APPENDER) {
if (!this.compatibilityTracksAppender) {
return null;
}
const event = (this.entryData[entryIndex]);
const timelineData = (this.timelineDataInternal as PerfUI.FlameChart.FlameChartTimelineData);
const eventLevel = timelineData.entryLevels[entryIndex];
const popoverInfo = this.compatibilityTracksAppender.popoverInfo(event, eventLevel);
title = popoverInfo.title;
time = popoverInfo.formattedTime;
warningElements = popoverInfo.warningElements || warningElements;
if (popoverInfo.additionalElements?.length) {
additionalContent.push(...popoverInfo.additionalElements);
}
this.dispatchEventToListeners(Events.FLAME_CHART_ITEM_HOVERED, event);
} else if (entryType === EntryType.FRAME) {
const frame = (this.entryData[entryIndex] as Trace.Types.Events.LegacyTimelineFrame);
time = i18n.TimeUtilities.preciseMillisToString(Trace.Helpers.Timing.microToMilli(frame.duration), 1);
if (frame.idle) {
title = i18nString(UIStrings.idleFrame);
} else if (frame.dropped) {
title = frame.isPartial ? i18nString(UIStrings.partiallyPresentedFrame) : i18nString(UIStrings.droppedFrame);
timeElementClassName = 'popoverinfo-warning';
} else {
title = i18nString(UIStrings.frame);
}
} else {
this.dispatchEventToListeners(Events.FLAME_CHART_ITEM_HOVERED, null);
return null;
}
const popoverElement = document.createElement('div');
const root = UI.UIUtils.createShadowRootWithCoreStyles(popoverElement, {cssFile: timelineFlamechartPopoverStyles});
const popoverContents = root.createChild('div', 'timeline-flamechart-popover');
popoverContents.createChild('span', timeElementClassName).textContent = time;
popoverContents.createChild('span', 'popoverinfo-title').textContent = title;
for (const warningElement of warningElements) {
warningElement.classList.add('popoverinfo-warning');
popoverContents.appendChild(warningElement);
}
for (const elem of additionalContent) {
popoverContents.appendChild(elem);
}
return popoverElement;
}
preparePopoverForCollapsedArrow(entryIndex: number): Element|null {
const element = document.createElement('div');
const root = UI.UIUtils.createShadowRootWithCoreStyles(element, {cssFile: timelineFlamechartPopoverStyles});
const entry = this.entryData[entryIndex];
const hiddenEntriesAmount =
ModificationsManager.activeManager()?.getEntriesFilter().findHiddenDescendantsAmount(entry);
if (!hiddenEntriesAmount) {
return null;
}
const contents = root.createChild('div', 'timeline-flamechart-popover');
contents.createChild('span', 'popoverinfo-title').textContent = hiddenEntriesAmount + ' hidden';
return element;
}
getDrawOverride(entryIndex: number): DrawOverride|undefined {
const entryType = this.#entryTypeForIndex(entryIndex);
if (entryType !== EntryType.TRACK_APPENDER) {
return;
}
const timelineData = (this.timelineDataInternal as PerfUI.FlameChart.FlameChartTimelineData);
const eventLevel = timelineData.entryLevels[entryIndex];
const event = (this.entryData[entryIndex]);
return this.compatibilityTracksAppender?.getDrawOverride(event, eventLevel);
}
#entryColorForFrame(entryIndex: number): string {
const frame = (this.entryData[entryIndex] as Trace.Types.Events.LegacyTimelineFrame);
if (frame.idle) {
return 'white';
}
if (frame.dropped) {
if (frame.isPartial) {
// For partially presented frame boxes, paint a yellow background with
// a sparse white dashed-line pattern overlay.
return '#f0e442';
}
// For dropped frame boxes, paint a red background with a dense white
// solid-line pattern overlay.
return '#f08080';
}
return '#d7f0d1';
}
entryColor(entryIndex: number): string {
const entryType = this.#entryTypeForIndex(entryIndex);
if (entryType === EntryType.FRAME) {
return this.#entryColorForFrame(entryIndex);
}
if (entryType === EntryType.TRACK_APPENDER) {
const timelineData = (this.timelineDataInternal as PerfUI.FlameChart.FlameChartTimelineData);
const eventLevel = timelineData.entryLevels[entryIndex];
const event = (this.entryData[entryIndex]);
return this.compatibilityTracksAppender?.colorForEvent(event, eventLevel) || '';
}
return '';
}
private preparePatternCanvas(): void {
// Set the candy stripe pattern to 17px so it repeats well.
const size = 17;
this.droppedFramePatternCanvas.width = size;
this.droppedFramePatternCanvas.height = size;
this.partialFramePatternCanvas.width = size;
this.partialFramePatternCanvas.height = size;
const ctx = this.droppedFramePatternCanvas.getContext('2d');
if (ctx) {
// Make a dense solid-line pattern.
ctx.translate(size * 0.5, size * 0.5);
ctx.rotate(Math.PI * 0.25);
ctx.translate(-size * 0.5, -size * 0.5);
ctx.fillStyle = 'rgb(255, 255, 255)';
for (let x = -size; x < size * 2; x += 3) {
ctx.fillRect(x, -size, 1, size * 3);
}
}
const ctx2 = this.partialFramePatternCanvas.getContext('2d');
if (ctx2) {
// Make a sparse dashed-line pattern.
ctx2.strokeStyle = 'rgb(255, 255, 255)';
ctx2.lineWidth = 2;
ctx2.beginPath();
ctx2.moveTo(17, 0);
ctx2.lineTo(10, 7);
ctx2.moveTo(8, 9);
ctx2.lineTo(2, 15);
ctx2.stroke();
}
}
private drawFrame(
entryIndex: number, context: CanvasRenderingContext2D, barX: number, barY: number, barWidth: number,
barHeight: number, transformColor: (color: string) => string): void {
const hPadding = 1;
const frame = this.entryData[entryIndex] as Trace.Types.Events.LegacyTimelineFrame;
barX += hPadding;
barWidth -= 2 * hPadding;
context.fillStyle = transformColor(this.entryColor(entryIndex));
if (frame.dropped) {
if (frame.isPartial) {
// For partially presented frame boxes, paint a yellow background with
// a sparse white dashed-line pattern overlay.
context.fillRect(barX, barY, barWidth, barHeight);
const overlay = context.createPattern(this.partialFramePatternCanvas, 'repeat');
context.fillStyle = overlay || context.fillStyle;
} else {
// For dropped frame boxes, paint a red background with a dense white
// solid-line pattern overlay.
context.fillRect(barX, barY, barWidth, barHeight);
const overlay = context.createPattern(this.droppedFramePatternCanvas, 'repeat');
context.fillStyle = overlay || context.fillStyle;
}
}
context.fillRect(barX, barY, barWidth, barHeight);
const frameDurationText =
i18n.TimeUtilities.preciseMillisToString(Trace.Helpers.Timing.microToMilli(frame.duration), 1);
const textWidth = context.measureText(frameDurationText).width;
if (textWidth <= barWidth) {
context.fillStyle = this.textColor(entryIndex);
context.fillText(frameDurationText, barX + (barWidth - textWidth) / 2, barY + barHeight - 4);
}
}
private async drawScreenshot(
entryIndex: number, context: CanvasRenderingContext2D, barX: number, barY: number, barWidth: number,
barHeight: number): Promise<void> {
const screenshot = (this.entryData[entryIndex] as Trace.Types.Events.LegacySyntheticScreenshot);
const image = Utils.ImageCache.getOrQueue(screenshot);
if (!image) {
return;
}
const imageX = barX + 1;
const imageY = barY + 1;
const imageHeight = barHeight - 2;
const scale = imageHeight / image.naturalHeight;
const imageWidth = Math.floor(image.naturalWidth * scale);
context.save();
context.beginPath();
context.rect(barX, barY, barWidth, barHeight);
context.clip();
context.drawImage(image, imageX, imageY, imageWidth, imageHeight);
context.strokeStyle = '#ccc';
context.strokeRect(imageX - 0.5, imageY - 0.5, Math.min(barWidth - 1, imageWidth + 1), imageHeight);
context.restore();
}
decorateEntry(
entryIndex: number, context: CanvasRenderingContext2D, text: string|null, barX: number, barY: number,