summaryrefslogtreecommitdiff
path: root/chromium/third_party/catapult/tracing/tracing/ui/base/draw_helpers.html
blob: 89b9d5dab967e28acf939f55b954d53a4b931123 (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
<!DOCTYPE html>
<!--
Copyright (c) 2013 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.
-->

<link rel="import" href="/tracing/base/sorted_array_utils.html">
<link rel="import" href="/tracing/ui/base/elided_cache.html">
<link rel="import" href="/tracing/ui/base/event_presenter.html">

<script>
'use strict';

/**
 * @fileoverview Provides various helper methods for drawing to a provided
 * canvas.
 */
tr.exportTo('tr.ui.b', function() {
  var elidedTitleCache = new tr.ui.b.ElidedTitleCache();
  var ColorScheme = tr.b.ColorScheme;
  var colorsAsStrings = ColorScheme.colorsAsStrings;

  var EventPresenter = tr.ui.b.EventPresenter;
  var blackColorId = ColorScheme.getColorIdForReservedName('black');

  /**
   * This value is used to allow for consistent style UI elements.
   * Thread time visualisation uses a smaller rectangle that has this height.
   * @const
   */
  var THIN_SLICE_HEIGHT = 4;

  /**
   * This value is used to for performance considerations when drawing large
   * zoomed out traces that feature cpu time in the slices. If the waiting
   * width is less than the threshold, we only draw the rectangle as a solid.
   * @const
   */
  var SLICE_WAITING_WIDTH_DRAW_THRESHOLD = 3;

  /**
   * If the slice has mostly been waiting to be scheduled on the cpu, the
   * wall clock will be far greater than the cpu clock. Draw the slice
   * only as an idle slice, if the active width is not thicker than the
   * threshold.
   * @const
   */
  var SLICE_ACTIVE_WIDTH_DRAW_THRESHOLD = 1;

  /**
   * Should we elide text on trace labels?
   * Without eliding, text that is too wide isn't drawn at all.
   * Disable if you feel this causes a performance problem.
   * This is a default value that can be overridden in tracks for testing.
   * @const
   */
  var SHOULD_ELIDE_TEXT = true;

  /**
   * Draw the define line into |ctx|.
   *
   * @param {Context} ctx The context to draw into.
   * @param {float} x1 The start x position of the line.
   * @param {float} y1 The start y position of the line.
   * @param {float} x2 The end x position of the line.
   * @param {float} y2 The end y position of the line.
   */
  function drawLine(ctx, x1, y1, x2, y2) {
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
  }

  /**
   * Draw the defined triangle into |ctx|.
   *
   * @param {Context} ctx The context to draw into.
   * @param {float} x1 The first corner x.
   * @param {float} y1 The first corner y.
   * @param {float} x2 The second corner x.
   * @param {float} y2 The second corner y.
   * @param {float} x3 The third corner x.
   * @param {float} y3 The third corner y.
   */
  function drawTriangle(ctx, x1, y1, x2, y2, x3, y3) {
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.lineTo(x3, y3);
    ctx.closePath();
  }

  /**
   * Draw an arrow into |ctx|.
   *
   * @param {Context} ctx The context to draw into.
   * @param {float} x1 The shaft x.
   * @param {float} y1 The shaft y.
   * @param {float} x2 The head x.
   * @param {float} y2 The head y.
   * @param {float} arrowLength The length of the head.
   * @param {float} arrowWidth The width of the head.
   */
  function drawArrow(ctx, x1, y1, x2, y2, arrowLength, arrowWidth) {
    var dx = x2 - x1;
    var dy = y2 - y1;
    var len = Math.sqrt(dx * dx + dy * dy);
    var perc = (len - arrowLength) / len;
    var bx = x1 + perc * dx;
    var by = y1 + perc * dy;
    var ux = dx / len;
    var uy = dy / len;
    var ax = uy * arrowWidth;
    var ay = -ux * arrowWidth;

    ctx.beginPath();
    drawLine(ctx, x1, y1, x2, y2);
    ctx.stroke();

    drawTriangle(ctx,
        bx + ax, by + ay,
        x2, y2,
        bx - ax, by - ay);
    ctx.fill();
  }

  /**
   * Draw the provided slices to the screen.
   *
   * Each of the elements in |slices| must provide the follow methods:
   *   * start
   *   * duration
   *   * colorId
   *   * selected
   *
   * @param {Context} ctx The canvas context.
   * @param {TimelineDrawTransform} dt The draw transform.
   * @param {float} viewLWorld The left most point of the world viewport.
   * @param {float} viewRWorld The right most point of the world viewport.
   * @param {float} viewHeight The height of the viewport.
   * @param {Array} slices The slices to draw.
   * @param {bool} async Whether the slices are drawn with async style.
   */
  function drawSlices(ctx, dt, viewLWorld, viewRWorld, viewHeight, slices,
                      async) {
    var pixelRatio = window.devicePixelRatio || 1;
    var pixWidth = dt.xViewVectorToWorld(1);
    var height = viewHeight * pixelRatio;

    var darkRectHeight = THIN_SLICE_HEIGHT * pixelRatio;

    // Not enough space for both colors, use light color only.
    if (height < darkRectHeight)
      darkRectHeight = 0;

    var lightRectHeight = height - darkRectHeight;

    // Begin rendering in world space.
    ctx.save();
    dt.applyTransformToCanvas(ctx);

    var rect = new tr.ui.b.FastRectRenderer(
        ctx, 2 * pixWidth, 2 * pixWidth, colorsAsStrings);
    rect.setYandH(0, height);

    var lowSlice = tr.b.findLowIndexInSortedArray(
        slices,
        function(slice) { return slice.start + slice.duration; },
        viewLWorld);

    var hadTopLevel = false;

    for (var i = lowSlice; i < slices.length; ++i) {
      var slice = slices[i];
      var x = slice.start;
      if (x > viewRWorld)
        break;

      var w = pixWidth;
      if (slice.duration > 0) {
        w = Math.max(slice.duration, 0.000001);
        if (w < pixWidth)
          w = pixWidth;
      }

      var colorId = EventPresenter.getSliceColorId(slice);
      var alpha = EventPresenter.getSliceAlpha(slice, async);
      var lightAlpha = alpha * 0.70;

      if (async && slice.isTopLevel) {
        rect.setYandH(3, height - 3);
        hadTopLevel = true;
      } else {
        rect.setYandH(0, height);
      }

      // If cpuDuration is available, draw rectangles proportional to the
      // amount of cpu time taken.
      if (!slice.cpuDuration) {
        // No cpuDuration available, draw using only one alpha.
        rect.fillRect(x, w, colorId, alpha);
        continue;
      }

      var activeWidth = w * (slice.cpuDuration / slice.duration);
      var waitingWidth = w - activeWidth;

      // Check if we have enough screen space to draw the whole slice, with
      // both color tones.
      //
      // Truncate the activeWidth to 0 if it is less than 'threshold' pixels.
      if (activeWidth < SLICE_ACTIVE_WIDTH_DRAW_THRESHOLD * pixWidth) {
        activeWidth = 0;
        waitingWidth = w;
      }

      // Truncate the waitingWidth to 0 if it is less than 'threshold' pixels.
      if (waitingWidth < SLICE_WAITING_WIDTH_DRAW_THRESHOLD * pixWidth) {
        activeWidth = w;
        waitingWidth = 0;
      }

      // We now draw the two rectangles making up the event slice.
      // NOTE: The if statements are necessary for performance considerations.
      // We do not want to force draws, if the width of the rectangle is 0.
      //
      // First draw the solid color, representing the 'active' part.
      if (activeWidth > 0) {
        rect.fillRect(x, activeWidth, colorId, alpha);
      }

      // Next draw the two toned 'idle' part.
      // NOTE: Substracting pixWidth and drawing one extra pixel is done to
      // prevent drawing artifacts. Without it, the two parts of the slice,
      // ('active' and 'idle') may appear split apart.
      if (waitingWidth > 0) {
        // First draw the light toned top part.
        rect.setYandH(0, lightRectHeight);
        rect.fillRect(x + activeWidth - pixWidth,
            waitingWidth + pixWidth, colorId, lightAlpha);
        // Then the solid bottom half.
        rect.setYandH(lightRectHeight, darkRectHeight);
        rect.fillRect(x + activeWidth - pixWidth,
            waitingWidth + pixWidth, colorId, alpha);
        // Reset for the next slice.
        rect.setYandH(0, height);
      }
    }
    rect.flush();

    if (async && hadTopLevel) {
      // Draw a top border over async slices in order to visually separate
      // them from events above it.
      // See https://github.com/google/trace-viewer/issues/725.
      rect.setYandH(2, 1);
      for (var i = lowSlice; i < slices.length; ++i) {
        var slice = slices[i];
        var x = slice.start;
        if (x > viewRWorld)
          break;

        if (!slice.isTopLevel)
          continue;

        var w = pixWidth;
        if (slice.duration > 0) {
          w = Math.max(slice.duration, 0.000001);
          if (w < pixWidth)
            w = pixWidth;
        }

        rect.fillRect(x, w, blackColorId, 0.7);
      }
      rect.flush();
    }

    ctx.restore();
  }

  /**
   * Draw the provided instant slices as lines to the screen.
   *
   * Each of the elements in |slices| must provide the follow methods:
   *   * start
   *   * duration with value of 0.
   *   * colorId
   *   * selected
   *
   * @param {Context} ctx The canvas context.
   * @param {TimelineDrawTransform} dt The draw transform.
   * @param {float} viewLWorld The left most point of the world viewport.
   * @param {float} viewRWorld The right most point of the world viewport.
   * @param {float} viewHeight The height of the viewport.
   * @param {Array} slices The slices to draw.
   * @param {Numer} lineWidthInPixels The width of the lines.
   */
  function drawInstantSlicesAsLines(
      ctx, dt, viewLWorld, viewRWorld, viewHeight, slices, lineWidthInPixels) {
    var pixelRatio = window.devicePixelRatio || 1;
    var height = viewHeight * pixelRatio;

    var pixWidth = dt.xViewVectorToWorld(1);

    // Begin rendering in world space.
    ctx.save();
    ctx.lineWidth = pixWidth * lineWidthInPixels * pixelRatio;
    dt.applyTransformToCanvas(ctx);
    ctx.beginPath();

    var lowSlice = tr.b.findLowIndexInSortedArray(
        slices,
        function(slice) { return slice.start; },
        viewLWorld);

    for (var i = lowSlice; i < slices.length; ++i) {
      var slice = slices[i];
      var x = slice.start;
      if (x > viewRWorld)
        break;

      ctx.strokeStyle = EventPresenter.getInstantSliceColor(slice);

      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, height);
      ctx.stroke();
    }
    ctx.restore();
  }

  /**
   * Draws the labels for the given slices.
   *
   * The |slices| array must contain objects with the following API:
   *   * start
   *   * duration
   *   * title
   *   * didNotFinish (optional)
   *
   * @param {Context} ctx The graphics context.
   * @param {TimelineDrawTransform} dt The draw transform.
   * @param {float} viewLWorld The left most point of the world viewport.
   * @param {float} viewRWorld The right most point of the world viewport.
   * @param {Array} slices The slices to label.
   * @param {bool} async Whether the slice labels are drawn with async style.
   * @param {float} fontSize The font size.
   * @param {float} yOffset The font offset.
   */
  function drawLabels(ctx, dt, viewLWorld, viewRWorld, slices, async,
                      fontSize, yOffset) {
    var pixelRatio = window.devicePixelRatio || 1;
    var pixWidth = dt.xViewVectorToWorld(1);

    ctx.save();

    ctx.textAlign = 'center';
    ctx.textBaseline = 'top';
    ctx.font = (fontSize * pixelRatio) + 'px sans-serif';

    if (async)
      ctx.font = 'italic ' + ctx.font;

    var cY = yOffset * pixelRatio;

    var lowSlice = tr.b.findLowIndexInSortedArray(
        slices,
        function(slice) { return slice.start + slice.duration; },
        viewLWorld);

    // Don't render text until until it is 20px wide
    var quickDiscardThresshold = pixWidth * 20;
    for (var i = lowSlice; i < slices.length; ++i) {
      var slice = slices[i];
      if (slice.start > viewRWorld)
        break;

      if (slice.duration <= quickDiscardThresshold)
        continue;

      var title = slice.title +
          (slice.didNotFinish ? ' (Did Not Finish)' : '');

      var drawnTitle = title;
      var drawnWidth = elidedTitleCache.labelWidth(ctx, drawnTitle);
      var fullLabelWidth = elidedTitleCache.labelWidthWorld(
          ctx, drawnTitle, pixWidth);
      if (SHOULD_ELIDE_TEXT && fullLabelWidth > slice.duration) {
        var elidedValues = elidedTitleCache.get(
            ctx, pixWidth,
            drawnTitle, drawnWidth,
            slice.duration);
        drawnTitle = elidedValues.string;
        drawnWidth = elidedValues.width;
      }

      if (drawnWidth * pixWidth < slice.duration) {
        ctx.fillStyle = EventPresenter.getTextColor(slice);
        var cX = dt.xWorldToView(slice.start + 0.5 * slice.duration);
        ctx.fillText(drawnTitle, cX, cY, drawnWidth);
      }
    }
    ctx.restore();
  }

  return {
    drawSlices: drawSlices,
    drawInstantSlicesAsLines: drawInstantSlicesAsLines,
    drawLabels: drawLabels,

    drawLine: drawLine,
    drawTriangle: drawTriangle,
    drawArrow: drawArrow,

    elidedTitleCache_: elidedTitleCache,

    THIN_SLICE_HEIGHT: THIN_SLICE_HEIGHT
  };
});
</script>