-
Notifications
You must be signed in to change notification settings - Fork 469
Expand file tree
/
Copy pathActivityGraphCanvas.tsx
More file actions
305 lines (275 loc) · 9.64 KB
/
ActivityGraphCanvas.tsx
File metadata and controls
305 lines (275 loc) · 9.64 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
/* 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 { InView } from 'react-intersection-observer';
import memoizeOne from 'memoize-one';
import type {
ActivityFillGraphQuerier,
CategoryDrawStyles,
} from './ActivityGraphFills';
import {
computeActivityGraphFills,
precomputePositions,
} from './ActivityGraphFills';
import { timeCode } from 'firefox-profiler/utils/time-code';
import { mapCategoryColorNameToStyles } from 'firefox-profiler/utils/colors';
import type {
Thread,
Milliseconds,
IndexIntoSamplesTable,
CategoryList,
} from 'firefox-profiler/types';
import type { SizeProps } from 'firefox-profiler/components/shared/WithSize';
type CanvasProps = {
readonly className: string;
readonly trackName: string;
readonly fullThread: Thread;
readonly rangeFilteredThread: Thread;
readonly interval: Milliseconds;
readonly rangeStart: Milliseconds;
readonly rangeEnd: Milliseconds;
readonly sampleIndexOffset: number;
readonly sampleSelectedStates: Uint8Array;
readonly treeOrderSampleComparator: (
a: IndexIntoSamplesTable,
b: IndexIntoSamplesTable
) => number;
readonly categories: CategoryList;
readonly passFillsQuerier: (param: ActivityFillGraphQuerier) => void;
readonly onClick: (param: React.MouseEvent<HTMLCanvasElement>) => void;
} & SizeProps;
export class ActivityGraphCanvas extends React.PureComponent<CanvasProps> {
_canvas: { current: null | HTMLCanvasElement } = React.createRef();
_categoryDrawStyles: null | CategoryDrawStyles = null;
_canvasState: { renderScheduled: boolean; inView: boolean } = {
renderScheduled: false,
inView: false,
};
_memoizedPrecomputePositions = memoizeOne(precomputePositions);
_renderCanvas() {
if (!this._canvasState.inView) {
// Canvas is not in the view. Schedule the render for a later intersection
// observer callback.
this._canvasState.renderScheduled = true;
return;
}
// Canvas is in the view. Render the canvas and reset the schedule state.
this._canvasState.renderScheduled = false;
const canvas = this._canvas.current;
if (canvas !== null) {
timeCode('ThreadActivityGraph render', () => {
this.drawCanvas(canvas);
});
}
}
/**
* Get or lazily create the category info. It requires the 2d ctx to exist in order
* to create the fill patterns.
*/
_getCategoryDrawStyles(ctx: CanvasRenderingContext2D): CategoryDrawStyles {
if (this._categoryDrawStyles === null) {
// Lazily initialize this list.
this._categoryDrawStyles = this.props.categories.map(
({ color: colorName }, categoryIndex) => {
const styles = mapCategoryColorNameToStyles(colorName);
return {
...styles,
category: categoryIndex,
filteredOutByTransformFillStyle: _createDiagonalStripePattern(
ctx,
styles.getUnselectedFillStyle()
),
};
}
);
}
return this._categoryDrawStyles;
}
_observerCallback = (inView: boolean, _entry: IntersectionObserverEntry) => {
this._canvasState.inView = inView;
if (!this._canvasState.renderScheduled) {
// Skip if render is not scheduled.
return;
}
this._renderCanvas();
};
override componentDidMount() {
this._renderCanvas();
window.addEventListener('profiler-theme-change', this._onThemeChange);
}
override componentWillUnmount() {
window.removeEventListener('profiler-theme-change', this._onThemeChange);
}
_onThemeChange = () => {
// Invalidate the cached category draw styles,
// so they are recreated with the new theme colors.
this._categoryDrawStyles = null;
this._renderCanvas();
};
override componentDidUpdate() {
this._renderCanvas();
}
drawCanvas(canvas: HTMLCanvasElement) {
const {
fullThread,
rangeFilteredThread,
interval,
rangeStart,
rangeEnd,
sampleIndexOffset,
sampleSelectedStates,
treeOrderSampleComparator,
width,
height,
} = this.props;
const ctx = canvas.getContext('2d')!;
const canvasPixelWidth = Math.round(width * window.devicePixelRatio);
const canvasPixelHeight = Math.round(height * window.devicePixelRatio);
canvas.width = canvasPixelWidth;
canvas.height = canvasPixelHeight;
const xPixelsPerMs = canvasPixelWidth / (rangeEnd - rangeStart);
const precomputedPositions = this._memoizedPrecomputePositions(
fullThread.samples.time,
sampleIndexOffset,
rangeFilteredThread.samples.length,
rangeStart,
xPixelsPerMs,
interval,
canvasPixelWidth
);
const { fills, fillsQuerier } = computeActivityGraphFills({
canvasPixelWidth,
canvasPixelHeight,
fullThread,
rangeFilteredThread,
interval,
rangeStart,
rangeEnd,
sampleIndexOffset,
sampleSelectedStates,
xPixelsPerMs: canvasPixelWidth / (rangeEnd - rangeStart),
treeOrderSampleComparator,
categoryDrawStyles: this._getCategoryDrawStyles(ctx!),
precomputedPositions,
});
// The value in fillsQuerier is needed in ActivityGraph but is computed in this method
// The value had to be passed through the passFillsQuerier custom prop and received in ActivityGraph by a setter function
this.props.passFillsQuerier(fillsQuerier);
// Draw adjacent filled paths using Operator ADD and disjoint paths.
// This avoids any bleeding and seams.
// lighter === OP_ADD
ctx.globalCompositeOperation = 'lighter';
// The previousUpperEdge keeps track of where the "mountain ridge" is after the
// previous fill.
let previousUpperEdge = new Float32Array(canvasPixelWidth);
for (const { fillStyle, accumulatedUpperEdge } of fills) {
if (fillStyle === 'transparent') {
// Skip any drawing work for the Idle category.
previousUpperEdge = accumulatedUpperEdge;
continue;
}
ctx.fillStyle = fillStyle;
// Some fills might not span the full width of the graph - they have parts where
// their contribution stays zero for some time. So instead of having one fill call
// with a path that is mostly empty, we split the shape of the fill so that we have
// potentially multiple fill calls, one fill call for each range during which the
// fill has an uninterrupted sequence of non-zero-contribution pixels.
let lastNonZeroRangeEnd = 0;
while (lastNonZeroRangeEnd < canvasPixelWidth) {
const currentNonZeroRangeStart = _findNextDifferentIndex(
accumulatedUpperEdge,
previousUpperEdge,
lastNonZeroRangeEnd
);
if (currentNonZeroRangeStart >= canvasPixelWidth) {
break;
}
let currentNonZeroRangeEnd = canvasPixelWidth;
ctx.beginPath();
ctx.moveTo(
currentNonZeroRangeStart,
(1 - previousUpperEdge[currentNonZeroRangeStart]) * canvasPixelHeight
);
for (let i = currentNonZeroRangeStart + 1; i < canvasPixelWidth; i++) {
const lastVal = previousUpperEdge[i];
const thisVal = accumulatedUpperEdge[i];
ctx.lineTo(i, (1 - lastVal) * canvasPixelHeight);
if (lastVal === thisVal) {
currentNonZeroRangeEnd = i;
break;
}
}
for (
let i = currentNonZeroRangeEnd - 1;
i >= currentNonZeroRangeStart;
i--
) {
ctx.lineTo(i, (1 - accumulatedUpperEdge[i]) * canvasPixelHeight);
}
ctx.closePath();
ctx.fill();
lastNonZeroRangeEnd = currentNonZeroRangeEnd;
}
previousUpperEdge = accumulatedUpperEdge;
}
}
override render() {
const { className, trackName, onClick } = this.props;
return (
<InView onChange={this._observerCallback}>
<canvas className={className} ref={this._canvas} onClick={onClick}>
<h2>Activity Graph for {trackName}</h2>
<p>This graph shows a visual chart of thread activity.</p>
</canvas>
</InView>
);
}
}
/**
* Filtered out samples use a diagonal stripe pattern, create that here.
*/
function _createDiagonalStripePattern(
chartCtx: CanvasRenderingContext2D,
color: string
): CanvasPattern | string {
if (color === 'transparent') {
return 'transparent';
}
// Create a second canvas, draw to it in order to create a pattern. This canvas
// and context will be discarded after the pattern is created.
const patternCanvas = document.createElement('canvas');
const dpr = Math.round(window.devicePixelRatio);
patternCanvas.width = 4 * dpr;
patternCanvas.height = 4 * dpr;
const patternContext = patternCanvas.getContext('2d')!;
patternContext.scale(dpr, dpr);
const linear = patternContext.createLinearGradient(0, 0, 4, 4);
linear.addColorStop(0, color);
linear.addColorStop(0.25, color);
linear.addColorStop(0.25, 'transparent');
linear.addColorStop(0.5, 'transparent');
linear.addColorStop(0.5, color);
linear.addColorStop(0.75, color);
linear.addColorStop(0.75, 'transparent');
linear.addColorStop(1, 'transparent');
patternContext.fillStyle = linear;
patternContext.fillRect(0, 0, 4, 4);
return chartCtx.createPattern(patternCanvas, 'repeat')!;
}
/**
* Search an array from a starting index to find where two arrays diverge.
*/
function _findNextDifferentIndex(
arr1: Float32Array,
arr2: Float32Array,
startIndex: number
): number {
for (let i = startIndex; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return i;
}
}
return arr1.length;
}