-
Notifications
You must be signed in to change notification settings - Fork 491
Expand file tree
/
Copy pathCanvas.tsx
More file actions
520 lines (457 loc) · 17 KB
/
Copy pathCanvas.tsx
File metadata and controls
520 lines (457 loc) · 17 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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import * as React from 'react';
import memoize from 'memoize-immutable';
import { withChartViewport, type Viewport } from '../shared/chart/Viewport';
import { ChartCanvas } from '../shared/chart/Canvas';
import { FastFillStyle } from '../../utils';
import TextMeasurement from '../../utils/text-measurement';
import {
mapCategoryColorNameToStackChartStyles,
getForegroundColor,
getBackgroundColor,
} from '../../utils/colors';
import {
formatCallNodeNumberWithUnit,
formatPercent,
} from 'firefox-profiler/utils/format-numbers';
import { TooltipCallNode } from 'firefox-profiler/components/tooltip/CallNode';
import { getTimingsForCallNodeIndex } from 'firefox-profiler/profile-logic/profile-data';
import MixedTupleMap from 'mixedtuplemap';
import type {
Thread,
CategoryList,
CssPixels,
DevicePixels,
Milliseconds,
IndexIntoCallNodeTable,
CallTreeSummaryStrategy,
WeightType,
SamplesLikeTable,
InnerWindowID,
Page,
SampleCategoriesAndSubcategories,
} from 'firefox-profiler/types';
import type {
FlameGraphTiming,
FlameGraphDepth,
IndexIntoFlameGraphTiming,
} from 'firefox-profiler/profile-logic/flame-graph';
import type { CallNodeInfo } from 'firefox-profiler/profile-logic/call-node-info';
import type {
ChartCanvasScale,
ChartCanvasHoverInfo,
} from '../shared/chart/Canvas';
import type {
CallTree,
CallTreeTimingsNonInverted,
} from 'firefox-profiler/profile-logic/call-tree';
export type OwnProps = {
readonly thread: Thread;
readonly weightType: WeightType;
readonly innerWindowIDToPageMap: Map<InnerWindowID, Page> | null;
readonly maxStackDepthPlusOne: number;
readonly flameGraphTiming: FlameGraphTiming;
readonly callNodeInfo: CallNodeInfo;
readonly callTree: CallTree;
readonly stackFrameHeight: CssPixels;
readonly selectedCallNodeIndex: IndexIntoCallNodeTable | null;
readonly rightClickedCallNodeIndex: IndexIntoCallNodeTable | null;
readonly onSelectionChange: (param: IndexIntoCallNodeTable | null) => void;
readonly onRightClick: (param: IndexIntoCallNodeTable | null) => void;
readonly onDoubleClick: (param: IndexIntoCallNodeTable | null) => void;
readonly shouldDisplayTooltips: () => boolean;
readonly scrollToSelectionGeneration: number;
readonly categories: CategoryList;
readonly interval: Milliseconds;
readonly isInverted: boolean;
readonly callTreeSummaryStrategy: CallTreeSummaryStrategy;
readonly ctssSamples: SamplesLikeTable;
readonly ctssSampleCategoriesAndSubcategories: SampleCategoriesAndSubcategories;
readonly tracedTiming: CallTreeTimingsNonInverted | null;
readonly displayStackType: boolean;
};
type Props = OwnProps & {
// Bring in the viewport props from the higher order Viewport component.
readonly viewport: Viewport;
};
type HoveredStackTiming = {
readonly depth: FlameGraphDepth;
readonly flameGraphTimingIndex: IndexIntoFlameGraphTiming;
};
import './Canvas.css';
const ROW_HEIGHT = 16;
const TEXT_OFFSET_START = 3;
const TEXT_OFFSET_TOP = 11;
const FONT_SIZE = 10;
/**
* Round the given value to integers, consistently rounding x.5 towards positive infinity.
* This is different from Math.round: Math.round rounds 0.5 to the right (to 1), and -0.5
* to the left (to -1).
* snap should be preferred over Math.round for rounding coordinates which might
* be negative, so that there is no discontinuity when a box moves past zero.
*/
function snap(floatDeviceValue: DevicePixels): DevicePixels {
return Math.floor(floatDeviceValue + 0.5);
}
/**
* Round the given value to a multiple of `integerFactor`.
*/
function snapValueToMultipleOf(
floatDeviceValue: DevicePixels,
integerFactor: number
): DevicePixels {
return snap(floatDeviceValue / integerFactor) * integerFactor;
}
class FlameGraphCanvasImpl extends React.PureComponent<Props> {
_textMeasurement: TextMeasurement | null = null;
_textMeasurementCssToDeviceScale: number = 1;
override componentDidUpdate(prevProps: Props) {
// If the stack depth changes (say, when changing the time range
// selection or applying a transform), move the viewport
// vertically so that its offset from the base of the flame graph
// is maintained.
if (prevProps.maxStackDepthPlusOne !== this.props.maxStackDepthPlusOne) {
this.props.viewport.moveViewport(
0,
(prevProps.maxStackDepthPlusOne - this.props.maxStackDepthPlusOne) *
ROW_HEIGHT
);
}
// We want to scroll the selection into view when this component
// is mounted, but using componentDidMount won't work here as the
// viewport will not have completed setting its size by
// then. Instead, look for when the viewport's isSizeSet prop
// changes to true.
const viewportDidMount =
!prevProps.viewport.isSizeSet && this.props.viewport.isSizeSet;
if (
viewportDidMount ||
this.props.scrollToSelectionGeneration >
prevProps.scrollToSelectionGeneration
) {
this._scrollSelectionIntoView();
}
}
_scrollSelectionIntoView = () => {
const { selectedCallNodeIndex, maxStackDepthPlusOne, callNodeInfo } =
this.props;
if (selectedCallNodeIndex === null) {
return;
}
const callNodeTable = callNodeInfo.getCallNodeTable();
const depth = callNodeTable.depth[selectedCallNodeIndex];
const y = (maxStackDepthPlusOne - depth - 1) * ROW_HEIGHT;
if (y < this.props.viewport.viewportTop) {
this.props.viewport.moveViewport(0, this.props.viewport.viewportTop - y);
} else if (y + ROW_HEIGHT > this.props.viewport.viewportBottom) {
this.props.viewport.moveViewport(
0,
this.props.viewport.viewportBottom - (y + ROW_HEIGHT)
);
}
};
_drawCanvas = (
ctx: CanvasRenderingContext2D,
scale: ChartCanvasScale,
hoverInfo: ChartCanvasHoverInfo<HoveredStackTiming>
) => {
const {
thread,
flameGraphTiming,
callNodeInfo,
stackFrameHeight,
maxStackDepthPlusOne,
rightClickedCallNodeIndex,
selectedCallNodeIndex,
categories,
viewport: {
containerWidth,
containerHeight,
viewportTop,
viewportBottom,
},
} = this.props;
const { hoveredItem } = hoverInfo;
const { cssToDeviceScale, cssToUserScale } = scale;
if (cssToDeviceScale !== cssToUserScale) {
throw new Error(
'FlameGraphCanvasImpl sets scaleCtxToCssPixels={false}, so canvas user space units should be equal to device pixels.'
);
}
const deviceContainerWidth = containerWidth * cssToDeviceScale;
const deviceContainerHeight = containerHeight * cssToDeviceScale;
// Set the font before creating the text renderer. The font property resets
// automatically whenever the canvas size is changed, so we set it on every
// call.
ctx.font = `${FONT_SIZE * cssToDeviceScale}px sans-serif`;
// Ensure the text measurement tool is created, since this is the first time
// this class has access to a ctx. We also need to recreate it when the scale
// changes because we are working with device coordinates.
if (
!this._textMeasurement ||
this._textMeasurementCssToDeviceScale !== cssToDeviceScale
) {
this._textMeasurement = new TextMeasurement(ctx);
this._textMeasurementCssToDeviceScale = cssToDeviceScale;
}
const textMeasurement = this._textMeasurement;
const fastFillStyle = new FastFillStyle(ctx);
const deviceHorizontalPadding: DevicePixels = Math.round(
TEXT_OFFSET_START * cssToDeviceScale
);
fastFillStyle.set(getBackgroundColor());
ctx.fillRect(0, 0, deviceContainerWidth, deviceContainerHeight);
const callNodeTable = callNodeInfo.getCallNodeTable();
const startDepth = Math.floor(
maxStackDepthPlusOne - viewportBottom / stackFrameHeight
);
const endDepth = Math.ceil(
maxStackDepthPlusOne - viewportTop / stackFrameHeight
);
// Only draw the stack frames that are vertically within view.
// The graph is drawn from bottom to top, in order of increasing depth.
for (let depth = startDepth; depth < endDepth; depth++) {
// Get the timing information for a row of stack frames.
const stackTiming = flameGraphTiming[depth];
if (!stackTiming) {
continue;
}
const cssRowTop: CssPixels =
(maxStackDepthPlusOne - depth - 1) * ROW_HEIGHT - viewportTop;
const cssRowBottom: CssPixels =
(maxStackDepthPlusOne - depth) * ROW_HEIGHT - viewportTop;
const deviceRowTop: DevicePixels = snap(cssRowTop * cssToDeviceScale);
const deviceRowBottom: DevicePixels =
snap(cssRowBottom * cssToDeviceScale) - 1;
const deviceRowHeight: DevicePixels = deviceRowBottom - deviceRowTop;
const deviceTextTop =
deviceRowTop + snap(TEXT_OFFSET_TOP * cssToDeviceScale);
for (let i = 0; i < stackTiming.length; i++) {
// For each box, snap the left and right edges to the nearest multiple
// of two device pixels. If both edges snap to the same value, the box
// becomes empty and is not drawn.
//
// Boxes which remain are at least two device pixels wide. We create a
// translucent gap the end of each box by shifting the right edge to the
// left by 0.8 device pixels, so that this gap pixel column is filled to
// 20%.
const boxLeftFraction = stackTiming.start[i];
const boxRightFraction = stackTiming.end[i];
const deviceBoxLeftUnsnapped = boxLeftFraction * deviceContainerWidth;
const deviceBoxRightUnsnapped = boxRightFraction * deviceContainerWidth;
const deviceBoxLeft: DevicePixels = snapValueToMultipleOf(
deviceBoxLeftUnsnapped,
2
);
const deviceBoxRight: DevicePixels =
snapValueToMultipleOf(deviceBoxRightUnsnapped, 2) - 0.8;
const deviceBoxWidth: DevicePixels = deviceBoxRight - deviceBoxLeft;
if (deviceBoxWidth <= 0) {
// Skip drawing boxes which snapped away to nothing.
continue;
}
const callNodeIndex = stackTiming.callNode[i];
const isSelected = selectedCallNodeIndex === callNodeIndex;
const isRightClicked = rightClickedCallNodeIndex === callNodeIndex;
const isHovered =
hoveredItem &&
depth === hoveredItem.depth &&
i === hoveredItem.flameGraphTimingIndex;
const isHighlighted = isSelected || isRightClicked || isHovered;
const categoryIndex = callNodeTable.category[callNodeIndex];
const category = categories[categoryIndex];
const colorStyles = mapCategoryColorNameToStackChartStyles(
category.color
);
const background = isHighlighted
? colorStyles.getSelectedFillStyle()
: colorStyles.getUnselectedFillStyle();
fastFillStyle.set(background);
ctx.fillRect(
deviceBoxLeft,
deviceRowTop,
deviceBoxWidth,
deviceRowHeight
);
const deviceTextLeft: DevicePixels =
deviceBoxLeft + deviceHorizontalPadding;
const deviceTextWidth: DevicePixels = deviceBoxRight - deviceTextLeft;
if (deviceTextWidth > textMeasurement.minWidth) {
const funcIndex = callNodeTable.func[callNodeIndex];
const funcName = thread.stringTable.getString(
thread.funcTable.name[funcIndex]
);
const fittedText = textMeasurement.getFittedText(
funcName,
deviceTextWidth
);
if (fittedText) {
const foreground = isHighlighted
? colorStyles.getSelectedTextColor()
: getForegroundColor();
fastFillStyle.set(foreground);
// TODO - L10N RTL.
ctx.fillText(fittedText, deviceTextLeft, deviceTextTop);
}
}
}
}
};
// Properly memoize this derived information for the Tooltip component.
_getTimingsForCallNodeIndex = memoize(getTimingsForCallNodeIndex, {
cache: new MixedTupleMap(),
});
_getHoveredStackInfo = ({
depth,
flameGraphTimingIndex,
}: HoveredStackTiming): React.ReactNode => {
const {
thread,
flameGraphTiming,
callTree,
callNodeInfo,
shouldDisplayTooltips,
categories,
interval,
callTreeSummaryStrategy,
innerWindowIDToPageMap,
weightType,
ctssSamples,
ctssSampleCategoriesAndSubcategories,
tracedTiming,
displayStackType,
} = this.props;
if (!shouldDisplayTooltips()) {
return null;
}
const stackTiming = flameGraphTiming[depth];
if (!stackTiming) {
return null;
}
const callNodeIndex = stackTiming.callNode[flameGraphTimingIndex];
if (callNodeIndex === undefined) {
return null;
}
const ratio =
stackTiming.end[flameGraphTimingIndex] -
stackTiming.start[flameGraphTimingIndex];
let percentage = formatPercent(ratio);
if (tracedTiming) {
const time = formatCallNodeNumberWithUnit(
'tracing-ms',
false,
tracedTiming.total[callNodeIndex]
);
percentage = `${time} (${percentage})`;
}
const shouldComputeTimings =
// This is currently too slow for JS Tracer threads.
!thread.isJsTracer &&
// Only calculate this if our summary strategy is actually timing related.
// This function could be made more generic to handle other summary
// strategies, but it may not be worth implementing it.
callTreeSummaryStrategy === 'timing';
return (
// Important! Only pass in props that have been properly memoized so this component
// doesn't over-render.
<TooltipCallNode
thread={thread}
weightType={weightType}
innerWindowIDToPageMap={innerWindowIDToPageMap}
interval={interval}
callNodeIndex={callNodeIndex}
callNodeInfo={callNodeInfo}
categories={categories}
durationText={percentage}
displayData={callTree.getDisplayData(callNodeIndex)}
callTreeSummaryStrategy={callTreeSummaryStrategy}
timings={
shouldComputeTimings
? this._getTimingsForCallNodeIndex(
callNodeIndex,
callNodeInfo,
categories,
ctssSamples,
ctssSampleCategoriesAndSubcategories
)
: undefined
}
displayStackType={displayStackType}
/>
);
};
_getCallNodeIndexFromHoveredItem(
hoveredItem: HoveredStackTiming | null
): IndexIntoCallNodeTable | null {
if (hoveredItem === null) {
return null;
}
const { depth, flameGraphTimingIndex } = hoveredItem;
const { flameGraphTiming } = this.props;
const stackTiming = flameGraphTiming[depth];
const callNodeIndex = stackTiming.callNode[flameGraphTimingIndex];
return callNodeIndex;
}
_onSelectItem = (hoveredItem: HoveredStackTiming | null) => {
// Change our selection to the hovered item, or deselect (with
// null) if there's nothing hovered.
const callNodeIndex = this._getCallNodeIndexFromHoveredItem(hoveredItem);
this.props.onSelectionChange(callNodeIndex);
};
_onRightClick = (hoveredItem: HoveredStackTiming | null) => {
// Change our selection to the hovered item, or deselect (with
// null) if there's nothing hovered.
const callNodeIndex = this._getCallNodeIndexFromHoveredItem(hoveredItem);
this.props.onRightClick(callNodeIndex);
};
_onDoubleClick = (hoveredItem: HoveredStackTiming | null) => {
const callNodeIndex = this._getCallNodeIndexFromHoveredItem(hoveredItem);
this.props.onDoubleClick(callNodeIndex);
};
_hitTest = (x: CssPixels, y: CssPixels): HoveredStackTiming | null => {
const {
flameGraphTiming,
maxStackDepthPlusOne,
viewport: { viewportTop, containerWidth },
} = this.props;
const pos = x / containerWidth;
const depth = Math.floor(
maxStackDepthPlusOne - (y + viewportTop) / ROW_HEIGHT
);
const stackTiming = flameGraphTiming[depth];
if (!stackTiming) {
return null;
}
for (let i = 0; i < stackTiming.length; i++) {
const start = stackTiming.start[i];
const end = stackTiming.end[i];
if (start < pos && end > pos) {
return { depth, flameGraphTimingIndex: i };
}
}
return null;
};
override render() {
const { containerWidth, containerHeight, isDragging } = this.props.viewport;
return (
<ChartCanvas
className="flameGraphCanvas"
containerWidth={containerWidth}
containerHeight={containerHeight}
isDragging={isDragging}
scaleCtxToCssPixels={false}
onDoubleClickItem={this._onDoubleClick}
getHoveredItemInfo={this._getHoveredStackInfo}
drawCanvas={this._drawCanvas}
hitTest={this._hitTest}
onSelectItem={this._onSelectItem}
onRightClick={this._onRightClick}
drawCanvasAfterRaf={false}
/>
);
}
}
export const FlameGraphCanvas =
withChartViewport<OwnProps>(FlameGraphCanvasImpl);