summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/gpu_internals/timeline.js
blob: 6a08cd53f7750e4739940e770b345d69c36658ff (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
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
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.


/**
 * @fileoverview Interactive visualizaiton of TimelineModel objects
 * based loosely on gantt charts. Each thread in the TimelineModel is given a
 * set of TimelineTracks, one per subrow in the thread. The Timeline class
 * acts as a controller, creating the individual tracks, while TimelineTracks
 * do actual drawing.
 *
 * Visually, the Timeline produces (prettier) visualizations like the following:
 *    Thread1:  AAAAAAAAAA         AAAAA
 *                  BBBB              BB
 *    Thread2:     CCCCCC                 CCCCC
 *
 */
cr.define('gpu', function() {

  /**
   * The TimelineViewport manages the transform used for navigating
   * within the timeline. It is a simple transform:
   *   x' = (x+pan) * scale
   *
   * The timeline code tries to avoid directly accessing this transform,
   * instead using this class to do conversion between world and view space,
   * as well as the math for centering the viewport in various interesting
   * ways.
   *
   * @constructor
   * @extends {cr.EventTarget}
   */
  function TimelineViewport() {
    this.scaleX_ = 1;
    this.panX_ = 0;
    this.gridTimebase_ = 0;
    this.gridStep_ = 1000 / 60;
    this.gridEnabled_ = false;
  }

  TimelineViewport.prototype = {
    __proto__: cr.EventTarget.prototype,

    get scaleX() {
      return this.scaleX_;
    },
    set scaleX(s) {
      var changed = this.scaleX_ != s;
      if (changed) {
        this.scaleX_ = s;
        cr.dispatchSimpleEvent(this, 'change');
      }
    },

    get panX() {
      return this.panX_;
    },
    set panX(p) {
      var changed = this.panX_ != p;
      if (changed) {
        this.panX_ = p;
        cr.dispatchSimpleEvent(this, 'change');
      }
    },

    setPanAndScale: function(p, s) {
      var changed = this.scaleX_ != s || this.panX_ != p;
      if (changed) {
        this.scaleX_ = s;
        this.panX_ = p;
        cr.dispatchSimpleEvent(this, 'change');
      }
    },

    xWorldToView: function(x) {
      return (x + this.panX_) * this.scaleX_;
    },

    xWorldVectorToView: function(x) {
      return x * this.scaleX_;
    },

    xViewToWorld: function(x) {
      return (x / this.scaleX_) - this.panX_;
    },

    xViewVectorToWorld: function(x) {
      return x / this.scaleX_;
    },

    xPanWorldPosToViewPos: function(worldX, viewX, viewWidth) {
      if (typeof viewX == 'string') {
        if (viewX == 'left') {
          viewX = 0;
        } else if (viewX == 'center') {
          viewX = viewWidth / 2;
        } else if (viewX == 'right') {
          viewX = viewWidth - 1;
        } else {
          throw Error('unrecognized string for viewPos. left|center|right');
        }
      }
      this.panX = (viewX / this.scaleX_) - worldX;
    },

    get gridEnabled() {
      return this.gridEnabled_;
    },

    set gridEnabled(enabled) {
      if (this.gridEnabled_ == enabled)
        return;
      this.gridEnabled_ = enabled && true;
      cr.dispatchSimpleEvent(this, 'change');
    },

    get gridTimebase() {
      return this.gridTimebase_;
    },

    set gridTimebase(timebase) {
      if (this.gridTimebase_ == timebase)
        return;
      this.gridTimebase_ = timebase;
      cr.dispatchSimpleEvent(this, 'change');
    },

    get gridStep() {
      return this.gridStep_;
    },

    applyTransformToCanavs: function(ctx) {
      ctx.transform(this.scaleX_, 0, 0, 1, this.panX_ * this.scaleX_, 0);
    }
  };

  /**
   * Renders a TimelineModel into a div element, making one
   * TimelineTrack for each subrow in each thread of the model, managing
   * overall track layout, and handling user interaction with the
   * viewport.
   *
   * @constructor
   * @extends {HTMLDivElement}
   */
  Timeline = cr.ui.define('div');

  Timeline.prototype = {
    __proto__: HTMLDivElement.prototype,

    model_: null,

    decorate: function() {
      this.classList.add('timeline');
      this.needsViewportReset_ = false;

      this.viewport_ = new TimelineViewport();
      this.viewport_.addEventListener('change',
                                      this.viewportChange_.bind(this));

      this.invalidatePending_ = false;

      this.tracks_ = this.ownerDocument.createElement('div');
      this.tracks_.invalidate = this.invalidate.bind(this);
      this.appendChild(this.tracks_);

      this.dragBox_ = this.ownerDocument.createElement('div');
      this.dragBox_.className = 'timeline-drag-box';
      this.appendChild(this.dragBox_);

      // The following code uses a setInterval to monitor the timeline control
      // for size changes. This is so that we can keep the canvas' bitmap size
      // correctly synchronized with its presentation size.
      // TODO(nduca): detect this in a more efficient way, e.g. iframe hack.
      this.lastSize_ = this.clientWidth + 'x' + this.clientHeight;
      this.ownerDocument.defaultView.setInterval(function() {
        var curSize = this.clientWidth + 'x' + this.clientHeight;
        if (this.clientWidth && curSize != this.lastSize_) {
          this.lastSize_ = curSize;
          this.onResize();
        }
      }.bind(this), 250);

      document.addEventListener('keypress', this.onKeypress_.bind(this));
      document.addEventListener('mousedown', this.onMouseDown_.bind(this));
      document.addEventListener('mousemove', this.onMouseMove_.bind(this));
      document.addEventListener('mouseup', this.onMouseUp_.bind(this));

      this.lastMouseViewPos_ = {x: 0, y: 0};

      this.selection_ = [];
    },

    get model() {
      return this.model_;
    },

    set model(model) {
      if (!model)
        throw Error('Model cannot be null');
      if (this.model) {
        throw Error('Cannot set model twice.');
      }
      this.model_ = model;

      // Create tracks.
      this.tracks_.textContent = '';
      var threads = model.getAllThreads();
      for (var tI = 0; tI < threads.length; tI++) {
        var thread = threads[tI];
        var track = new TimelineThreadTrack();
        track.thread = thread;
        track.viewport = this.viewport_;
        this.tracks_.appendChild(track);

      }

      this.needsViewportReset_ = true;
    },

    viewportChange_: function() {
      this.invalidate();
    },

    invalidate: function() {
      if (this.invalidatePending_)
        return;
      this.invalidatePending_ = true;
      window.setTimeout(function() {
        this.invalidatePending_ = false;
        this.redrawAllTracks_();
      }.bind(this), 0);
    },

    onResize: function() {
      for (var i = 0; i < this.tracks_.children.length; ++i) {
        var track = this.tracks_.children[i];
        track.onResize();
      }
    },

    redrawAllTracks_: function() {
      if (this.needsViewportReset_ && this.clientWidth != 0) {
        this.needsViewportReset_ = false;
        /* update viewport */
        var rangeTimestamp = this.model_.maxTimestamp -
            this.model_.minTimestamp;
        var w = this.firstCanvas.width;
        console.log('viewport was reset with w=', w);
        var scaleX = w / rangeTimestamp;
        var panX = -this.model_.minTimestamp;
        this.viewport_.setPanAndScale(panX, scaleX);
      }
      for (var i = 0; i < this.tracks_.children.length; ++i) {
        this.tracks_.children[i].redraw();
      }
    },

    updateChildViewports_: function() {
      for (var cI = 0; cI < this.tracks_.children.length; ++cI) {
        var child = this.tracks_.children[cI];
        child.setViewport(this.panX, this.scaleX);
      }
    },

    onKeypress_: function(e) {
      var vp = this.viewport_;
      if (this.firstCanvas) {
        var viewWidth = this.firstCanvas.clientWidth;
        var curMouseV, curCenterW;
        switch (event.keyCode) {
          case 101: // e
            var vX = this.lastMouseViewPos_.x;
            var wX = vp.xViewToWorld(this.lastMouseViewPos_.x);
            var distFromCenter = vX - (viewWidth / 2);
            var percFromCenter = distFromCenter / viewWidth;
            var percFromCenterSq = percFromCenter * percFromCenter;
            vp.xPanWorldPosToViewPos(wX, 'center', viewWidth);
            break;
          case 119:  // w
            curMouseV = this.lastMouseViewPos_.x;
            curCenterW = vp.xViewToWorld(curMouseV);
            vp.scaleX = vp.scaleX * 1.5;
            vp.xPanWorldPosToViewPos(curCenterW, curMouseV, viewWidth);
            break;
          case 115:  // s
            curMouseV = this.lastMouseViewPos_.x;
            curCenterW = vp.xViewToWorld(curMouseV);
            vp.scaleX = vp.scaleX / 1.5;
            vp.xPanWorldPosToViewPos(curCenterW, curMouseV, viewWidth);
            break;
          case 103:  // g
            this.onGridToggle_(true);
            break;
          case 71:  // G
            this.onGridToggle_(false);
            break;
          case 87:  // W
            curMouseV = this.lastMouseViewPos_.x;
            curCenterW = vp.xViewToWorld(curMouseV);
            vp.scaleX = vp.scaleX * 10;
            vp.xPanWorldPosToViewPos(curCenterW, curMouseV, viewWidth);
            break;
          case 83:  // S
            curMouseV = this.lastMouseViewPos_.x;
            curCenterW = vp.xViewToWorld(curMouseV);
            vp.scaleX = vp.scaleX / 10;
            vp.xPanWorldPosToViewPos(curCenterW, curMouseV, viewWidth);
            break;
          case 97:  // a
            vp.panX += vp.xViewVectorToWorld(viewWidth * 0.1);
            break;
          case 100:  // d
            vp.panX -= vp.xViewVectorToWorld(viewWidth * 0.1);
            break;
          case 65:  // A
            vp.panX += vp.xViewVectorToWorld(viewWidth * 0.5);
            break;
          case 68:  // D
            vp.panX -= vp.xViewVectorToWorld(viewWidth * 0.5);
            break;
        }
      }
    },

    get keyHelp() {
      return 'Keyboard shortcuts:\n' +
          ' w/s   : Zoom in/out\n' +
          ' a/d   : Pan left/right\n' +
          ' e     : Center on mouse' +
          ' g/G   : Shows grid at the start/end of the selected task';
    },

    get selection() {
      return this.selection_;
    },

    get firstCanvas() {
      return this.tracks_.firstChild ?
          this.tracks_.firstChild.firstCanvas : undefined;
    },

    showDragBox_: function() {
    },

    hideDragBox_: function() {
      this.dragBox_.style.left = '-1000px';
      this.dragBox_.style.top = '-1000px';
      this.dragBox_.style.width = 0;
      this.dragBox_.style.height = 0;
    },

    setDragBoxPosition_: function(eDown, eCur) {
      var loX = Math.min(eDown.clientX, eCur.clientX);
      var hiX = Math.max(eDown.clientX, eCur.clientX);
      var loY = Math.min(eDown.clientY, eCur.clientY);
      var hiY = Math.max(eDown.clientY, eCur.clientY);

      this.dragBox_.style.left = loX + 'px';
      this.dragBox_.style.top = loY + 'px';
      this.dragBox_.style.width = hiX - loX + 'px';
      this.dragBox_.style.height = hiY - loY + 'px';

      var canv = this.firstCanvas;
      var loWX = this.viewport_.xViewToWorld(loX - canv.offsetLeft);
      var hiWX = this.viewport_.xViewToWorld(hiX - canv.offsetLeft);

      var roundedDuration = Math.round((hiWX - loWX) * 100) / 100;
      this.dragBox_.textContent = roundedDuration + 'ms';

      var e = new cr.Event('selectionChanging');
      e.loWX = loWX;
      e.hiWX = hiWX;
      this.dispatchEvent(e);
    },

    onGridToggle_: function(left) {
      var tb;
      if (left)
        tb = Math.min.apply(Math, this.selection_.map(
            function(x) { return x.slice.start; }));
      else
        tb = Math.max.apply(Math, this.selection_.map(
            function(x) { return x.slice.end; }));

      // Shift the timebase left until its just left of minTimestamp.
      var numInterfvalsSinceStart = Math.ceil((tb - this.model_.minTimestamp) /
          this.viewport_.gridStep_);
      this.viewport_.gridTimebase = tb -
          (numInterfvalsSinceStart + 1) * this.viewport_.gridStep_;
      this.viewport_.gridEnabled = true;
    },

    onMouseDown_: function(e) {
      if (e.clientX < this.offsetLeft ||
          e.clientX >= this.offsetLeft + this.offsetWidth ||
          e.clientY < this.offsetTop ||
          e.clientY >= this.offsetTop + this.offsetHeight)
        return;

      var canv = this.firstCanvas;
      var pos = {
        x: e.clientX - canv.offsetLeft,
        y: e.clientY - canv.offsetTop
      };

      var wX = this.viewport_.xViewToWorld(pos.x);

      // Update the drag box position
      this.showDragBox_();
      this.setDragBoxPosition_(e, e);
      this.dragBeginEvent_ = e;
      e.preventDefault();
    },

    onMouseMove_: function(e) {
      if (!this.firstCanvas)
        return;
      var canv = this.firstCanvas;
      var pos = {
        x: e.clientX - canv.offsetLeft,
        y: e.clientY - canv.offsetTop
      };

      // Remember position. Used during keyboard zooming.
      this.lastMouseViewPos_ = pos;

      // Update the drag box
      if (this.dragBeginEvent_) {
        this.setDragBoxPosition_(this.dragBeginEvent_, e);
      }
    },

    onMouseUp_: function(e) {
      var i;
      if (this.dragBeginEvent_) {
        // Stop the dragging.
        this.hideDragBox_();
        var eDown = this.dragBeginEvent_;
        this.dragBeginEvent_ = null;

        // Figure out extents of the drag.
        var loX = Math.min(eDown.clientX, e.clientX);
        var hiX = Math.max(eDown.clientX, e.clientX);
        var loY = Math.min(eDown.clientY, e.clientY);
        var hiY = Math.max(eDown.clientY, e.clientY);

        // Convert to worldspace.
        var canv = this.firstCanvas;
        var loWX = this.viewport_.xViewToWorld(loX - canv.offsetLeft);
        var hiWX = this.viewport_.xViewToWorld(hiX - canv.offsetLeft);

        // Clear old selection.
        for (i = 0; i < this.selection_.length; ++i) {
          this.selection_[i].slice.selected = false;
        }

        // Figure out what has been hit.
        var selection = [];
        function addHit(type, track, slice) {
          selection.push({track: track, slice: slice});
        }
        for (i = 0; i < this.tracks_.children.length; ++i) {
          var track = this.tracks_.children[i];

          // Only check tracks that insersect the rect.
          var trackClientRect = track.getBoundingClientRect();
          var a = Math.max(loY, trackClientRect.top);
          var b = Math.min(hiY, trackClientRect.bottom);
          if (a <= b) {
            track.pickRange(loWX, hiWX, loY, hiY, addHit);
          }
        }
        // Activate the new selection.
        this.selection_ = selection;
        cr.dispatchSimpleEvent(this, 'selectionChange');
        for (i = 0; i < this.selection_.length; ++i) {
          this.selection_[i].slice.selected = true;
        }
        this.invalidate();  // Cause tracks to redraw.
      }
    }
  };

  /**
   * The TimelineModel being viewed by the timeline
   * @type {TimelineModel}
   */
  cr.defineProperty(Timeline, 'model', cr.PropertyKind.JS);

  return {
    Timeline: Timeline
  };
});