summaryrefslogtreecommitdiffstats
path: root/devtools/client/performance/performance-view.js
blob: f490dda5fcea089255ab9e62e70d41ca68909c49 (plain)
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
/* 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-globals-from performance-controller.js */
/* globals OverviewView, window */
"use strict";
/**
 * Master view handler for the performance tool.
 */
var PerformanceView = {

  _state: null,

  // Set to true if the front emits a "buffer-status" event, indicating
  // that the server has support for determining buffer status.
  _bufferStatusSupported: false,

  // Mapping of state to selectors for different properties and their values,
  // from the main profiler view. Used in `PerformanceView.setState()`
  states: {
    "unavailable": [
      {
        sel: "#performance-view",
        opt: "selectedPanel",
        val: () => $("#unavailable-notice")
      },
      {
        sel: "#performance-view-content",
        opt: "hidden",
        val: () => true
      },
    ],
    "empty": [
      {
        sel: "#performance-view",
        opt: "selectedPanel",
        val: () => $("#empty-notice")
      },
      {
        sel: "#performance-view-content",
        opt: "hidden",
        val: () => true
      },
    ],
    "recording": [
      {
        sel: "#performance-view",
        opt: "selectedPanel",
        val: () => $("#performance-view-content")
      },
      {
        sel: "#performance-view-content",
        opt: "hidden",
        val: () => false
      },
      {
        sel: "#details-pane-container",
        opt: "selectedPanel",
        val: () => $("#recording-notice")
      },
    ],
    "console-recording": [
      {
        sel: "#performance-view",
        opt: "selectedPanel",
        val: () => $("#performance-view-content")
      },
      {
        sel: "#performance-view-content",
        opt: "hidden",
        val: () => false
      },
      {
        sel: "#details-pane-container",
        opt: "selectedPanel",
        val: () => $("#console-recording-notice")
      },
    ],
    "recorded": [
      {
        sel: "#performance-view",
        opt: "selectedPanel",
        val: () => $("#performance-view-content")
      },
      {
        sel: "#performance-view-content",
        opt: "hidden",
        val: () => false
      },
      {
        sel: "#details-pane-container",
        opt: "selectedPanel",
        val: () => $("#details-pane")
      },
    ],
    "loading": [
      {
        sel: "#performance-view",
        opt: "selectedPanel",
        val: () => $("#performance-view-content")
      },
      {
        sel: "#performance-view-content",
        opt: "hidden",
        val: () => false
      },
      {
        sel: "#details-pane-container",
        opt: "selectedPanel",
        val: () => $("#loading-notice")
      },
    ]
  },

  /**
   * Sets up the view with event binding and main subviews.
   */
  initialize: Task.async(function* () {
    this._onRecordButtonClick = this._onRecordButtonClick.bind(this);
    this._onImportButtonClick = this._onImportButtonClick.bind(this);
    this._onClearButtonClick = this._onClearButtonClick.bind(this);
    this._onRecordingSelected = this._onRecordingSelected.bind(this);
    this._onProfilerStatusUpdated = this._onProfilerStatusUpdated.bind(this);
    this._onRecordingStateChange = this._onRecordingStateChange.bind(this);
    this._onNewRecordingFailed = this._onNewRecordingFailed.bind(this);

    // Bind to controller events to unlock the record button
    PerformanceController.on(EVENTS.RECORDING_SELECTED, this._onRecordingSelected);
    PerformanceController.on(EVENTS.RECORDING_PROFILER_STATUS_UPDATE,
                             this._onProfilerStatusUpdated);
    PerformanceController.on(EVENTS.RECORDING_STATE_CHANGE, this._onRecordingStateChange);
    PerformanceController.on(EVENTS.RECORDING_ADDED, this._onRecordingStateChange);
    PerformanceController.on(EVENTS.BACKEND_FAILED_AFTER_RECORDING_START,
                             this._onNewRecordingFailed);

    if (yield PerformanceController.canCurrentlyRecord()) {
      this.setState("empty");
    } else {
      this.setState("unavailable");
    }

    // Initialize the ToolbarView first, because other views may need access
    // to the OptionsView via the controller, to read prefs.
    yield ToolbarView.initialize();
    yield RecordingsView.initialize();
    yield OverviewView.initialize();
    yield DetailsView.initialize();

    // DE-XUL: Begin migrating the toolbar to React. Temporarily hold state here.
    this._recordingControlsState = {
      onRecordButtonClick: this._onRecordButtonClick,
      onImportButtonClick: this._onImportButtonClick,
      onClearButtonClick: this._onClearButtonClick,
      isRecording: false,
      isDisabled: false
    };
    // Mount to an HTML element.
    const {createHtmlMount} = PerformanceUtils;
    this._recordingControlsMount = createHtmlMount($("#recording-controls-mount"));
    this._recordingButtonsMounts = Array.from($$(".recording-button-mount"))
                                        .map(createHtmlMount);

    this._renderRecordingControls();
  }),

  /**
   * DE-XUL: Render the recording controls and buttons using React.
   */
  _renderRecordingControls: function () {
    ReactDOM.render(RecordingControls(this._recordingControlsState),
                    this._recordingControlsMount);
    for (let button of this._recordingButtonsMounts) {
      ReactDOM.render(RecordingButton(this._recordingControlsState), button);
    }
  },

  /**
   * Unbinds events and destroys subviews.
   */
  destroy: Task.async(function* () {
    PerformanceController.off(EVENTS.RECORDING_SELECTED, this._onRecordingSelected);
    PerformanceController.off(EVENTS.RECORDING_PROFILER_STATUS_UPDATE,
                              this._onProfilerStatusUpdated);
    PerformanceController.off(EVENTS.RECORDING_STATE_CHANGE,
                              this._onRecordingStateChange);
    PerformanceController.off(EVENTS.RECORDING_ADDED, this._onRecordingStateChange);
    PerformanceController.off(EVENTS.BACKEND_FAILED_AFTER_RECORDING_START,
                              this._onNewRecordingFailed);

    yield ToolbarView.destroy();
    yield RecordingsView.destroy();
    yield OverviewView.destroy();
    yield DetailsView.destroy();
  }),

  /**
   * Sets the state of the profiler view. Possible options are "unavailable",
   * "empty", "recording", "console-recording", "recorded".
   */
  setState: function (state) {
    // Make sure that the focus isn't captured on a hidden iframe. This fixes a
    // XUL bug where shortcuts stop working.
    const iframes = window.document.querySelectorAll("iframe");
    for (let iframe of iframes) {
      iframe.blur();
    }
    window.focus();

    let viewConfig = this.states[state];
    if (!viewConfig) {
      throw new Error(`Invalid state for PerformanceView: ${state}`);
    }
    for (let { sel, opt, val } of viewConfig) {
      for (let el of $$(sel)) {
        el[opt] = val();
      }
    }

    this._state = state;

    if (state === "console-recording") {
      let recording = PerformanceController.getCurrentRecording();
      let label = recording.getLabel() || "";

      // Wrap the label in quotes if it exists for the commands.
      label = label ? `"${label}"` : "";

      let startCommand = $(".console-profile-recording-notice .console-profile-command");
      let stopCommand = $(".console-profile-stop-notice .console-profile-command");

      startCommand.value = `console.profile(${label})`;
      stopCommand.value = `console.profileEnd(${label})`;
    }

    this.updateBufferStatus();
    this.emit(EVENTS.UI_STATE_CHANGED, state);
  },

  /**
   * Returns the state of the PerformanceView.
   */
  getState: function () {
    return this._state;
  },

  /**
   * Updates the displayed buffer status.
   */
  updateBufferStatus: function () {
    // If we've never seen a "buffer-status" event from the front, ignore
    // and keep the buffer elements hidden.
    if (!this._bufferStatusSupported) {
      return;
    }

    let recording = PerformanceController.getCurrentRecording();
    if (!recording || !recording.isRecording()) {
      return;
    }

    let bufferUsage = PerformanceController.getBufferUsageForRecording(recording) || 0;

    // Normalize to a percentage value
    let percent = Math.floor(bufferUsage * 100);

    let $container = $("#details-pane-container");
    let $bufferLabel = $(".buffer-status-message", $container.selectedPanel);

    // Be a little flexible on the buffer status, although not sure how
    // this could happen, as RecordingModel clamps.
    if (percent >= 99) {
      $container.setAttribute("buffer-status", "full");
    } else {
      $container.setAttribute("buffer-status", "in-progress");
    }

    $bufferLabel.value = L10N.getFormatStr("profiler.bufferFull", percent);
    this.emit(EVENTS.UI_RECORDING_PROFILER_STATUS_RENDERED, percent);
  },

  /**
   * Toggles the `locked` attribute on the record buttons based
   * on `lock`.
   *
   * @param {boolean} lock
   */
  _lockRecordButtons: function (lock) {
    this._recordingControlsState.isLocked = lock;
    this._renderRecordingControls();
  },

  /*
   * Toggles the `checked` attribute on the record buttons based
   * on `activate`.
   *
   * @param {boolean} activate
   */
  _toggleRecordButtons: function (activate) {
    this._recordingControlsState.isRecording = !!activate;
    this._renderRecordingControls();
  },

  /**
   * When a recording has started.
   */
  _onRecordingStateChange: function () {
    let currentRecording = PerformanceController.getCurrentRecording();
    let recordings = PerformanceController.getRecordings();

    this._toggleRecordButtons(recordings.find(r => !r.isConsole() && r.isRecording()));
    this._lockRecordButtons(recordings.find(r => !r.isConsole() && r.isFinalizing()));

    if (currentRecording && currentRecording.isFinalizing()) {
      this.setState("loading");
    }
    if (currentRecording && currentRecording.isCompleted()) {
      this.setState("recorded");
    }
    if (currentRecording && currentRecording.isRecording()) {
      this.updateBufferStatus();
    }
  },

  /**
   * When starting a recording has failed.
   */
  _onNewRecordingFailed: function (e) {
    this._lockRecordButtons(false);
    this._toggleRecordButtons(false);
  },

  /**
   * Handler for clicking the clear button.
   */
  _onClearButtonClick: function (e) {
    this.emit(EVENTS.UI_CLEAR_RECORDINGS);
  },

  /**
   * Handler for clicking the record button.
   */
  _onRecordButtonClick: function (e) {
    if (this._recordingControlsState.isRecording) {
      this.emit(EVENTS.UI_STOP_RECORDING);
    } else {
      this._lockRecordButtons(true);
      this._toggleRecordButtons(true);
      this.emit(EVENTS.UI_START_RECORDING);
    }
  },

  /**
   * Handler for clicking the import button.
   */
  _onImportButtonClick: function (e) {
    let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
    fp.init(window, L10N.getStr("recordingsList.importDialogTitle"),
            Ci.nsIFilePicker.modeOpen);
    fp.appendFilter(L10N.getStr("recordingsList.saveDialogJSONFilter"), "*.json");
    fp.appendFilter(L10N.getStr("recordingsList.saveDialogAllFilter"), "*.*");

    if (fp.show() == Ci.nsIFilePicker.returnOK) {
      this.emit(EVENTS.UI_IMPORT_RECORDING, fp.file);
    }
  },

  /**
   * Fired when a recording is selected. Used to toggle the profiler view state.
   */
  _onRecordingSelected: function (_, recording) {
    if (!recording) {
      this.setState("empty");
    } else if (recording.isRecording() && recording.isConsole()) {
      this.setState("console-recording");
    } else if (recording.isRecording()) {
      this.setState("recording");
    } else {
      this.setState("recorded");
    }
  },

  /**
   * Fired when the controller has updated information on the buffer's status.
   * Update the buffer status display if shown.
   */
  _onProfilerStatusUpdated: function (_, profilerStatus) {
    // We only care about buffer status here, so check to see
    // if it has position.
    if (!profilerStatus || profilerStatus.position === void 0) {
      return;
    }
    // If this is our first buffer event, set the status and add a class
    if (!this._bufferStatusSupported) {
      this._bufferStatusSupported = true;
      $("#details-pane-container").setAttribute("buffer-status", "in-progress");
    }

    if (!this.getState("recording") && !this.getState("console-recording")) {
      return;
    }

    this.updateBufferStatus();
  },

  toString: () => "[object PerformanceView]"
};

/**
 * Convenient way of emitting events from the view.
 */
EventEmitter.decorate(PerformanceView);