1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 * @extends {WebInspector.TimelineModel}
8 * @implements {WebInspector.TargetManager.Observer}
10 WebInspector.TimelineModelImpl = function()
12 WebInspector.TimelineModel.call(this);
13 /** @type {?WebInspector.Target} */
14 this._currentTarget = null;
16 this._bindings = new WebInspector.TimelineModelImpl.InterRecordBindings();
20 WebInspector.targetManager.addModelListener(WebInspector.TimelineManager, WebInspector.TimelineManager.EventTypes.TimelineEventRecorded, this._onRecordAdded, this);
21 WebInspector.targetManager.addModelListener(WebInspector.TimelineManager, WebInspector.TimelineManager.EventTypes.TimelineStarted, this._onStarted, this);
22 WebInspector.targetManager.addModelListener(WebInspector.TimelineManager, WebInspector.TimelineManager.EventTypes.TimelineStopped, this._onStopped, this);
23 WebInspector.targetManager.addModelListener(WebInspector.TimelineManager, WebInspector.TimelineManager.EventTypes.TimelineProgress, this._onProgress, this);
24 WebInspector.targetManager.observeTargets(this);
27 WebInspector.TimelineModelImpl.TransferChunkLengthBytes = 5000000;
29 WebInspector.TimelineModelImpl.prototype = {
31 * @param {!WebInspector.Target} target
33 targetAdded: function(target) { },
36 * @param {!WebInspector.Target} target
38 targetRemoved: function(target)
40 if (this._currentTarget === target)
41 this._currentTarget = null;
45 * @param {boolean} captureCauses
46 * @param {boolean} captureMemory
47 * @param {boolean} capturePictures
49 startRecording: function(captureCauses, captureMemory, capturePictures)
51 console.assert(!capturePictures, "Legacy timeline does not support capturing pictures");
53 this._currentTarget = WebInspector.context.flavor(WebInspector.Target);
54 console.assert(this._currentTarget);
56 this._clientInitiatedRecording = true;
57 var maxStackFrames = captureCauses ? 30 : 0;
58 var includeGPUEvents = Runtime.experiments.isEnabled("gpuTimeline");
59 var liveEvents = [ WebInspector.TimelineModel.RecordType.BeginFrame,
60 WebInspector.TimelineModel.RecordType.DrawFrame,
61 WebInspector.TimelineModel.RecordType.RequestMainThreadFrame,
62 WebInspector.TimelineModel.RecordType.ActivateLayerTree ];
63 this._currentTarget.timelineManager.start(maxStackFrames, liveEvents.join(","), captureMemory, includeGPUEvents, this._fireRecordingStarted.bind(this));
66 stopRecording: function()
68 if (!this._currentTarget)
71 if (!this._clientInitiatedRecording) {
72 this._currentTarget.timelineManager.start(undefined, undefined, undefined, undefined, stopTimeline.bind(this));
77 * Console started this one and we are just sniffing it. Initiate recording so that we
79 * @this {WebInspector.TimelineModelImpl}
81 function stopTimeline()
83 this._currentTarget.timelineManager.stop(this._fireRecordingStopped.bind(this));
86 this._clientInitiatedRecording = false;
87 this._currentTarget.timelineManager.stop(this._fireRecordingStopped.bind(this));
91 * @return {!Array.<!WebInspector.TimelineModel.Record>}
99 * @param {!WebInspector.Event} event
101 _onRecordAdded: function(event)
103 var timelineManager = /** @type {!WebInspector.TimelineManager} */ (event.target);
104 if (this._collectionEnabled && timelineManager.target() === this._currentTarget)
105 this._addRecord(/** @type {!TimelineAgent.TimelineEvent} */(event.data));
109 * @param {!WebInspector.Event} event
111 _onStarted: function(event)
113 if (!event.data || this._collectionEnabled)
115 // Started from console.
116 var timelineManager = /** @type {!WebInspector.TimelineManager} */ (event.target);
117 if (this._currentTarget !== timelineManager.target()) {
119 this._currentTarget = timelineManager.target();
121 this._fireRecordingStarted();
125 * @param {!WebInspector.Event} event
127 _onStopped: function(event)
129 var timelineManager = /** @type {!WebInspector.TimelineManager} */ (event.target);
130 if (timelineManager.target() !== this._currentTarget)
132 // We were buffering events, discard those that got through, the real ones are coming!
134 this._currentTarget = timelineManager.target();
136 var events = /** @type {!Array.<!TimelineAgent.TimelineEvent>} */ (event.data.events);
137 for (var i = 0; i < events.length; ++i)
138 this._addRecord(events[i]);
140 if (event.data.consoleTimeline) {
141 // Stopped from console.
142 this._fireRecordingStopped(null);
145 this._collectionEnabled = false;
149 * @param {!WebInspector.Event} event
151 _onProgress: function(event)
153 var timelineManager = /** @type {!WebInspector.TimelineManager} */ (event.target);
154 if (timelineManager.target() === this._currentTarget)
155 this.dispatchEventToListeners(WebInspector.TimelineModel.Events.RecordingProgress, event.data);
158 _fireRecordingStarted: function()
160 this._collectionEnabled = true;
161 this.dispatchEventToListeners(WebInspector.TimelineModel.Events.RecordingStarted);
165 * @param {?Protocol.Error} error
167 _fireRecordingStopped: function(error)
169 this.dispatchEventToListeners(WebInspector.TimelineModel.Events.RecordingStopped);
173 * @param {!TimelineAgent.TimelineEvent} payload
175 _addRecord: function(payload)
177 this._internStrings(payload);
178 this._payloads.push(payload);
180 var record = this._innerAddRecord(payload, null);
181 this._updateBoundaries(record);
182 this._records.push(record);
183 if (record.type() === WebInspector.TimelineModel.RecordType.Program)
184 this._mainThreadTasks.push(record);
185 if (record.type() === WebInspector.TimelineModel.RecordType.GPUTask)
186 this._gpuThreadTasks.push(record);
188 this.dispatchEventToListeners(WebInspector.TimelineModel.Events.RecordAdded, record);
192 * @param {!TimelineAgent.TimelineEvent} payload
193 * @param {?WebInspector.TimelineModel.Record} parentRecord
194 * @return {!WebInspector.TimelineModel.Record}
196 _innerAddRecord: function(payload, parentRecord)
198 var record = new WebInspector.TimelineModel.RecordImpl(this, payload, parentRecord);
199 if (WebInspector.TimelineUIUtilsImpl.isEventDivider(record))
200 this._eventDividerRecords.push(record);
202 for (var i = 0; payload.children && i < payload.children.length; ++i)
203 this._innerAddRecord.call(this, payload.children[i], record);
206 parentRecord._selfTime -= record.endTime() - record.startTime();
211 * @param {!WebInspector.ChunkedFileReader} fileReader
212 * @param {!WebInspector.Progress} progress
213 * @return {!WebInspector.OutputStream}
215 createLoader: function(fileReader, progress)
217 return new WebInspector.TimelineModelLoader(this, fileReader, progress);
221 * @param {!WebInspector.OutputStream} stream
223 writeToStream: function(stream)
225 var saver = new WebInspector.TimelineSaver(stream);
226 saver.save(this._payloads, window.navigator.appVersion);
231 if (!this._collectionEnabled)
232 this._currentTarget = null;
234 this._stringPool = {};
235 this._bindings._reset();
236 this._minimumRecordTime = 0;
237 this._maximumRecordTime = 0;
238 WebInspector.TimelineModel.prototype.reset.call(this);
244 minimumRecordTime: function()
246 return this._minimumRecordTime;
252 maximumRecordTime: function()
254 return this._maximumRecordTime;
258 * @param {!WebInspector.TimelineModel.Record} record
260 _updateBoundaries: function(record)
262 var startTime = record.startTime();
263 var endTime = record.endTime();
265 if (!this._minimumRecordTime || startTime < this._minimumRecordTime)
266 this._minimumRecordTime = startTime;
267 if (endTime > this._maximumRecordTime)
268 this._maximumRecordTime = endTime;
272 * @param {!TimelineAgent.TimelineEvent} record
274 _internStrings: function(record)
276 for (var name in record) {
277 var value = record[name];
278 if (typeof value !== "string")
281 var interned = this._stringPool[value];
282 if (typeof interned === "string")
283 record[name] = interned;
285 this._stringPool[value] = value;
288 var children = record.children;
289 for (var i = 0; children && i < children.length; ++i)
290 this._internStrings(children[i]);
293 __proto__: WebInspector.TimelineModel.prototype
300 WebInspector.TimelineModelImpl.InterRecordBindings = function() {
304 WebInspector.TimelineModelImpl.InterRecordBindings.prototype = {
307 this._sendRequestRecords = {};
308 this._timerRecords = {};
309 this._requestAnimationFrameRecords = {};
310 this._layoutInvalidate = {};
311 this._lastScheduleStyleRecalculation = {};
312 this._webSocketCreateRecords = {};
318 * @implements {WebInspector.TimelineModel.Record}
319 * @param {!WebInspector.TimelineModel} model
320 * @param {!TimelineAgent.TimelineEvent} timelineEvent
321 * @param {?WebInspector.TimelineModel.Record} parentRecord
323 WebInspector.TimelineModel.RecordImpl = function(model, timelineEvent, parentRecord)
326 var bindings = this._model._bindings;
327 this._record = timelineEvent;
328 this._thread = this._record.thread || WebInspector.TimelineModel.MainThreadName;
331 this.parent = parentRecord;
332 parentRecord.children().push(this);
335 this._selfTime = this.endTime() - this.startTime();
337 var recordTypes = WebInspector.TimelineModel.RecordType;
338 switch (timelineEvent.type) {
339 case recordTypes.ResourceSendRequest:
340 // Make resource receive record last since request was sent; make finish record last since response received.
341 bindings._sendRequestRecords[timelineEvent.data["requestId"]] = this;
344 case recordTypes.ResourceReceiveResponse:
345 case recordTypes.ResourceReceivedData:
346 case recordTypes.ResourceFinish:
347 this._initiator = bindings._sendRequestRecords[timelineEvent.data["requestId"]];
350 case recordTypes.TimerInstall:
351 bindings._timerRecords[timelineEvent.data["timerId"]] = this;
354 case recordTypes.TimerFire:
355 this._initiator = bindings._timerRecords[timelineEvent.data["timerId"]];
358 case recordTypes.RequestAnimationFrame:
359 bindings._requestAnimationFrameRecords[timelineEvent.data["id"]] = this;
362 case recordTypes.FireAnimationFrame:
363 this._initiator = bindings._requestAnimationFrameRecords[timelineEvent.data["id"]];
366 case recordTypes.ScheduleStyleRecalculation:
367 bindings._lastScheduleStyleRecalculation[this.frameId()] = this;
370 case recordTypes.RecalculateStyles:
371 this._initiator = bindings._lastScheduleStyleRecalculation[this.frameId()];
374 case recordTypes.InvalidateLayout:
375 // Consider style recalculation as a reason for layout invalidation,
376 // but only if we had no earlier layout invalidation records.
377 var layoutInitator = this;
378 if (!bindings._layoutInvalidate[this.frameId()] && parentRecord.type() === recordTypes.RecalculateStyles)
379 layoutInitator = parentRecord._initiator;
380 bindings._layoutInvalidate[this.frameId()] = layoutInitator;
383 case recordTypes.Layout:
384 this._initiator = bindings._layoutInvalidate[this.frameId()];
385 bindings._layoutInvalidate[this.frameId()] = null;
386 if (this.stackTrace())
387 this.addWarning(WebInspector.UIString("Forced synchronous layout is a possible performance bottleneck."));
390 case recordTypes.WebSocketCreate:
391 bindings._webSocketCreateRecords[timelineEvent.data["identifier"]] = this;
394 case recordTypes.WebSocketSendHandshakeRequest:
395 case recordTypes.WebSocketReceiveHandshakeResponse:
396 case recordTypes.WebSocketDestroy:
397 this._initiator = bindings._webSocketCreateRecords[timelineEvent.data["identifier"]];
402 WebInspector.TimelineModel.RecordImpl.prototype = {
404 * @return {?Array.<!ConsoleAgent.CallFrame>}
406 callSiteStackTrace: function()
408 return this._initiator ? this._initiator.stackTrace() : null;
412 * @return {?WebInspector.TimelineModel.Record}
414 initiator: function()
416 return this._initiator;
420 * @return {?WebInspector.Target}
424 return this._model._currentTarget;
432 return this._selfTime;
436 * @return {!Array.<!WebInspector.TimelineModel.Record>}
440 return this._children;
446 startTime: function()
448 return this._record.startTime;
464 return this._endTime || this._record.endTime || this._record.startTime;
468 * @param {number} endTime
470 setEndTime: function(endTime)
472 this._endTime = endTime;
480 return this._record.data;
488 return this._record.type;
496 return this._record.frameId || "";
500 * @return {?Array.<!ConsoleAgent.CallFrame>}
502 stackTrace: function()
504 if (this._record.stackTrace && this._record.stackTrace.length)
505 return this._record.stackTrace;
510 * @param {string} key
513 getUserObject: function(key)
515 if (!this._userObjects)
517 return this._userObjects.get(key);
521 * @param {string} key
522 * @param {?Object|undefined} value
524 setUserObject: function(key, value)
526 if (!this._userObjects)
527 this._userObjects = new Map();
528 this._userObjects.set(key, value);
532 * @param {string} message
534 addWarning: function(message)
538 this._warnings.push(message);
542 * @return {?Array.<string>}
546 return this._warnings;
552 * @implements {WebInspector.OutputStream}
553 * @param {!WebInspector.TimelineModel} model
554 * @param {!{cancel: function()}} reader
555 * @param {!WebInspector.Progress} progress
557 WebInspector.TimelineModelLoader = function(model, reader, progress)
560 this._reader = reader;
561 this._progress = progress;
563 this._firstChunk = true;
566 WebInspector.TimelineModelLoader.prototype = {
568 * @param {string} chunk
570 write: function(chunk)
572 var data = this._buffer + chunk;
577 lastIndex = WebInspector.TextUtils.findBalancedCurlyBrackets(data, index);
578 } while (lastIndex !== -1)
580 var json = data.slice(0, index) + "]";
581 this._buffer = data.slice(index);
586 if (this._firstChunk) {
587 this._firstChunk = false;
590 // Prepending "0" to turn string into valid JSON.
596 items = /** @type {!Array.<!TimelineAgent.TimelineEvent>} */ (JSON.parse(json));
598 WebInspector.console.error("Malformed timeline data.");
600 this._reader.cancel();
601 this._progress.done();
605 // Skip 0-th element - it is either version or 0.
606 for (var i = 1, size = items.length; i < size; ++i)
607 this._model._addRecord(items[i]);
617 * @param {!WebInspector.OutputStream} stream
619 WebInspector.TimelineSaver = function(stream)
621 this._stream = stream;
624 WebInspector.TimelineSaver.prototype = {
626 * @param {!Array.<*>} payloads
627 * @param {string} version
629 save: function(payloads, version)
631 this._payloads = payloads;
632 this._recordIndex = 0;
633 this._prologue = "[" + JSON.stringify(version);
635 this._writeNextChunk(this._stream);
638 _writeNextChunk: function(stream)
640 const separator = ",\n";
644 if (this._prologue) {
645 data.push(this._prologue);
646 length += this._prologue.length;
647 delete this._prologue;
649 if (this._recordIndex === this._payloads.length) {
655 while (this._recordIndex < this._payloads.length) {
656 var item = JSON.stringify(this._payloads[this._recordIndex]);
657 var itemLength = item.length + separator.length;
658 if (length + itemLength > WebInspector.TimelineModelImpl.TransferChunkLengthBytes)
660 length += itemLength;
664 if (this._recordIndex === this._payloads.length)
665 data.push(data.pop() + "]");
666 stream.write(data.join(separator), this._writeNextChunk.bind(this));