forked from google/perfetto
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathselection_manager.ts
More file actions
545 lines (495 loc) · 16.7 KB
/
selection_manager.ts
File metadata and controls
545 lines (495 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// Copyright (C) 2024 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {assertExists, assertTrue, assertUnreachable} from '../base/logging';
import {
Selection,
Area,
SelectionOpts,
SelectionManager,
TrackEventSelection,
AreaSelectionTab,
} from '../public/selection';
import {Time, TimeSpan} from '../base/time';
import {raf} from './raf_scheduler';
import {exists, getOrCreate} from '../base/utils';
import {TrackManagerImpl} from './track_manager';
import {Engine} from '../trace_processor/engine';
import {ScrollHelper} from './scroll_helper';
import {NoteManagerImpl} from './note_manager';
import {SearchResult} from '../public/search';
import {AsyncLimiter} from '../base/async_limiter';
import m from 'mithril';
import {SerializedSelection} from './state_serialization_schema';
import {showModal} from '../widgets/modal';
import {NUM, SqlValue, UNKNOWN} from '../trace_processor/query_result';
import {SourceDataset, UnionDataset} from '../trace_processor/dataset';
import {Trace} from '../public/trace';
import {Track} from '../public/track';
import {TimelineImpl} from './timeline';
import {HighPrecisionTime} from '../base/high_precision_time';
interface SelectionDetailsPanel {
isLoading: boolean;
render(): m.Children;
serializatonState(): unknown;
}
// There are two selection-related states in this class.
// 1. _selection: This is the "input" / locator of the selection, what other
// parts of the codebase specify (e.g., a tuple of trackUri + eventId) to say
// "please select this object if it exists".
// 2. _selected{Slice,ThreadState}: This is the resolved selection, that is, the
// rich details about the object that has been selected. If the input
// `_selection` is valid, this is filled in the near future. Doing so
// requires querying the SQL engine, which is an async operation.
export class SelectionManagerImpl implements SelectionManager {
private readonly detailsPanelLimiter = new AsyncLimiter();
private _selection: Selection = {kind: 'empty'};
private readonly detailsPanels = new WeakMap<
Selection,
SelectionDetailsPanel
>();
private _trace?: Trace;
public readonly areaSelectionTabs: AreaSelectionTab[] = [];
constructor(
private readonly engine: Engine,
private timeline: TimelineImpl,
private trackManager: TrackManagerImpl,
private noteManager: NoteManagerImpl,
private scrollHelper: ScrollHelper,
private onSelectionChange: (s: Selection, opts: SelectionOpts) => void,
) {}
get trace(): Trace {
return assertExists(this._trace);
}
setTrace(trace: Trace): void {
assertTrue(this._trace === undefined);
this._trace = trace;
}
clearSelection(): void {
this.setSelection({kind: 'empty'});
}
async selectTrackEvent(
trackUri: string,
eventId: number,
opts?: SelectionOpts,
) {
this.selectTrackEventInternal(trackUri, eventId, opts);
}
selectTrack(uri: string, opts?: SelectionOpts) {
this.setSelection({kind: 'track', trackUri: uri}, opts);
}
selectNote(args: {id: string}, opts?: SelectionOpts) {
this.setSelection(
{
kind: 'note',
id: args.id,
},
opts,
);
}
selectArea(area: Area, opts?: SelectionOpts): void {
const {start, end} = area;
assertTrue(start <= end);
// In the case of area selection, the caller provides a list of trackUris.
// However, all the consumers want to access the resolved Tracks. Rather
// than delegating this to the various consumers, we resolve them now once
// and for all and place them in the selection object.
const tracks = [];
for (const uri of area.trackUris) {
const trackDescr = this.trackManager.getTrack(uri);
if (trackDescr === undefined) continue;
tracks.push(trackDescr);
}
this.setSelection(
{
...area,
kind: 'area',
tracks,
},
opts,
);
}
deserialize(serialized: SerializedSelection | undefined) {
if (serialized === undefined) {
return;
}
this.deserializeInternal(serialized);
}
private async deserializeInternal(serialized: SerializedSelection) {
try {
switch (serialized.kind) {
case 'TRACK_EVENT':
await this.selectTrackEventInternal(
serialized.trackKey,
parseInt(serialized.eventId),
undefined,
serialized.detailsPanel,
);
break;
case 'AREA':
this.selectArea({
start: serialized.start,
end: serialized.end,
trackUris: serialized.trackUris,
});
}
} catch (ex) {
showModal({
owner: this.trace,
title: 'Failed to restore the selected event',
content: m(
'div',
m(
'p',
`Due to a version skew between the version of the UI the trace was
shared with and the version of the UI you are using, we were
unable to restore the selected event.`,
),
m(
'p',
`These backwards incompatible changes are very rare but is in some
cases unavoidable. We apologise for the inconvenience.`,
),
),
buttons: [
{
text: 'Continue',
primary: true,
},
],
});
}
}
toggleTrackAreaSelection(trackUri: string) {
const curSelection = this._selection;
if (curSelection.kind !== 'area') return;
let trackUris = curSelection.trackUris.slice();
if (!trackUris.includes(trackUri)) {
trackUris.push(trackUri);
} else {
trackUris = trackUris.filter((t) => t !== trackUri);
}
this.selectArea({
...curSelection,
trackUris,
});
}
toggleGroupAreaSelection(trackUris: string[]) {
const curSelection = this._selection;
if (curSelection.kind !== 'area') return;
const allTracksSelected = trackUris.every((t) =>
curSelection.trackUris.includes(t),
);
let newTrackUris: string[];
if (allTracksSelected) {
// Deselect all tracks in the list
newTrackUris = curSelection.trackUris.filter(
(t) => !trackUris.includes(t),
);
} else {
newTrackUris = curSelection.trackUris.slice();
trackUris.forEach((t) => {
if (!newTrackUris.includes(t)) {
newTrackUris.push(t);
}
});
}
this.selectArea({
...curSelection,
trackUris: newTrackUris,
});
}
get selection(): Selection {
return this._selection;
}
getDetailsPanelForSelection(): SelectionDetailsPanel | undefined {
return this.detailsPanels.get(this._selection);
}
async resolveSqlEvent(
sqlTableName: string,
id: number,
): Promise<{eventId: number; trackUri: string} | undefined> {
// This function:
// 1. Find the list of tracks whose rootTableName is the same as the one we
// are looking for
// 2. Groups them by their filter column - i.e. utid, cpu, or track_id.
// 3. Builds a map of which of these column values match which track.
// 4. Run one query per group, reading out the filter column value, and
// looking up the originating track in the map.
// One flaw of this approach is that.
const groups = new Map<string, [SourceDataset, Track][]>();
const tracksWithNoFilter: [SourceDataset, Track][] = [];
this.trackManager
.getAllTracks()
.filter((track) => track.renderer.rootTableName === sqlTableName)
.map((track) => {
const dataset = track.renderer.getDataset?.();
if (!dataset) return undefined;
return [dataset, track] as const;
})
.filter(exists)
.filter(([dataset]) => dataset.implements({id: NUM}))
.forEach(([dataset, track]) => {
const col = dataset.filter?.col;
if (col) {
const existingGroup = getOrCreate(groups, col, () => []);
existingGroup.push([dataset, track]);
} else {
tracksWithNoFilter.push([dataset, track]);
}
});
// Run one query per no-filter track. This is the only way we can reliably
// keep track of which track the event belonged to.
for (const [dataset, track] of tracksWithNoFilter) {
const query = `select id from (${dataset.query()}) where id = ${id}`;
const result = await this.engine.query(query);
if (result.numRows() > 0) {
return {eventId: id, trackUri: track.uri};
}
}
for (const [colName, values] of groups) {
// Build a map of the values -> track uri
const map = new Map<SqlValue, string>();
values.forEach(([dataset, track]) => {
const filter = dataset.filter;
if (filter) {
if ('eq' in filter) map.set(filter.eq, track.uri);
if ('in' in filter) filter.in.forEach((v) => map.set(v, track.uri));
}
});
const datasets = values.map(([dataset]) => dataset);
const union = new UnionDataset(datasets).optimize();
// Make sure to include the filter value in the schema.
const schema = {...union.schema, [colName]: UNKNOWN};
const query = `select * from (${union.query(schema)}) where id = ${id}`;
const result = await this.engine.query(query);
const row = result.iter(schema);
const value = row.get(colName);
let trackUri = map.get(value);
// If that didn't work, try converting the value to a number if it's a
// bigint. Unless specified as a NUM type, any integers on the wire will
// be parsed as a bigint to avoid losing precision.
if (trackUri === undefined && typeof value === 'bigint') {
trackUri = map.get(Number(value));
}
if (trackUri) {
return {eventId: id, trackUri};
}
}
return undefined;
}
selectSqlEvent(sqlTableName: string, id: number, opts?: SelectionOpts): void {
this.resolveSqlEvent(sqlTableName, id).then((selection) => {
selection &&
this.selectTrackEvent(selection.trackUri, selection.eventId, opts);
});
}
private setSelection(selection: Selection, opts?: SelectionOpts) {
this._selection = selection;
this.onSelectionChange(selection, opts ?? {});
if (opts?.scrollToSelection) {
this.scrollToSelection();
}
}
selectSearchResult(searchResult: SearchResult) {
const {source, eventId, trackUri} = searchResult;
if (eventId === undefined) {
return;
}
switch (source) {
case 'track':
this.selectTrack(trackUri, {
clearSearch: false,
scrollToSelection: true,
});
break;
case 'cpu':
this.selectSqlEvent('sched_slice', eventId, {
clearSearch: false,
scrollToSelection: true,
switchToCurrentSelectionTab: true,
});
break;
case 'log':
this.selectSqlEvent('android_logs', eventId, {
clearSearch: false,
scrollToSelection: true,
switchToCurrentSelectionTab: true,
});
break;
case 'slice':
// Search results only include slices from the slice table for now.
// When we include annotations we need to pass the correct table.
this.selectSqlEvent('slice', eventId, {
clearSearch: false,
scrollToSelection: true,
switchToCurrentSelectionTab: true,
});
break;
case 'event':
this.selectTrackEvent(trackUri, eventId, {
clearSearch: false,
scrollToSelection: true,
switchToCurrentSelectionTab: true,
});
break;
default:
assertUnreachable(source);
}
}
scrollToSelection() {
const uri = (() => {
switch (this.selection.kind) {
case 'track_event':
case 'track':
return this.selection.trackUri;
// TODO(stevegolton): Handle scrolling to area and note selections.
default:
return undefined;
}
})();
const range = this.getTimeSpanOfSelection();
this.scrollHelper.scrollTo({
time: range ? {...range} : undefined,
track: uri ? {uri, expandGroup: true} : undefined,
});
}
zoomOnSelection() {
const uri = (() => {
switch (this.selection.kind) {
case 'track_event':
case 'track':
return this.selection.trackUri;
// TODO(stevegolton): Handle scrolling to area and note selections.
default:
return undefined;
}
})();
const range = this.getTimeSpanOfSelection();
if (!range) {
// If there is no range, we cannot zoom to selection.
// This can happen if the selection is empty or if it is a note without
// a time span.
return;
}
const newDuration = this.timeline.visibleWindow.duration / 100;
const halfDuration = newDuration / 2;
const midEvent = Time.fromRaw(range.start + range.duration / 2n);
const newStart = new HighPrecisionTime(midEvent).subNumber(halfDuration);
this.scrollHelper.scrollTo({
time: {
start: newStart.toTime(),
end: newStart.addNumber(newDuration).toTime(),
},
track: uri ? {uri, expandGroup: true} : undefined,
});
}
private async selectTrackEventInternal(
trackUri: string,
eventId: number,
opts?: SelectionOpts,
serializedDetailsPanel?: unknown,
) {
const track = this.trackManager.getTrack(trackUri);
if (!track) {
throw new Error(
`Unable to resolve selection details: Track ${trackUri} not found`,
);
}
const trackRenderer = track.renderer;
if (!trackRenderer.getSelectionDetails) {
throw new Error(
`Unable to resolve selection details: Track ${trackUri} does not support selection details`,
);
}
const details = await trackRenderer.getSelectionDetails(eventId);
if (!exists(details)) {
throw new Error(
`Unable to resolve selection details: Track ${trackUri} returned no details for event ${eventId}`,
);
}
const selection: TrackEventSelection = {
...details,
kind: 'track_event',
trackUri,
eventId,
};
this.createTrackEventDetailsPanel(selection, serializedDetailsPanel);
this.setSelection(selection, opts);
}
private createTrackEventDetailsPanel(
selection: TrackEventSelection,
serializedState: unknown,
) {
const td = this.trackManager.getTrack(selection.trackUri);
if (!td) {
return;
}
const panel = td.renderer.detailsPanel?.(selection);
if (!panel) {
return;
}
if (panel.serialization && serializedState !== undefined) {
const res = panel.serialization.schema.safeParse(serializedState);
if (res.success) {
panel.serialization.state = res.data;
}
}
const detailsPanel: SelectionDetailsPanel = {
render: () => panel.render(),
serializatonState: () => panel.serialization?.state,
isLoading: true,
};
// Associate this details panel with this selection object
this.detailsPanels.set(selection, detailsPanel);
this.detailsPanelLimiter.schedule(async () => {
await panel?.load?.(selection);
detailsPanel.isLoading = false;
raf.scheduleFullRedraw();
});
}
getTimeSpanOfSelection(): TimeSpan | undefined {
const sel = this.selection;
if (sel.kind === 'area') {
return new TimeSpan(sel.start, sel.end);
} else if (sel.kind === 'note') {
const selectedNote = this.noteManager.getNote(sel.id);
if (selectedNote !== undefined) {
const kind = selectedNote.noteType;
switch (kind) {
case 'SPAN':
return new TimeSpan(selectedNote.start, selectedNote.end);
case 'DEFAULT':
// A TimeSpan where start === end is treated as an instant event.
return new TimeSpan(selectedNote.timestamp, selectedNote.timestamp);
default:
assertUnreachable(kind);
}
}
} else if (sel.kind === 'track_event') {
switch (sel.dur) {
case undefined:
case -1n:
// Events without a duration or with duration -1 (DNF) slices are just
// treated as if they were instant events.
return TimeSpan.fromTimeAndDuration(sel.ts, 0n);
default:
return TimeSpan.fromTimeAndDuration(sel.ts, sel.dur);
}
}
return undefined;
}
registerAreaSelectionTab(tab: AreaSelectionTab): void {
this.areaSelectionTabs.push(tab);
}
}