summaryrefslogtreecommitdiff
path: root/chromium/third_party/catapult/tracing/tracing/base/unit.html
blob: c260f55fe26a4a0082d5569f852e6deb383eef88 (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
<!DOCTYPE html>
<!--
Copyright 2015 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/event.html">
<link rel="import" href="/tracing/base/event_target.html">
<link rel="import" href="/tracing/base/iteration_helpers.html">
<link rel="import" href="/tracing/base/time_display_modes.html">
<link rel="import" href="/tracing/base/unit_scale.html">

<script>
'use strict';

tr.exportTo('tr.b', function() {
  var TimeDisplayModes = tr.b.TimeDisplayModes;

  var PLUS_MINUS_SIGN = String.fromCharCode(177);

  function max(a, b) {
    if (a === undefined)
      return b;
    if (b === undefined)
      return a;
    return a.scale > b.scale ? a : b;
  }

  /** @enum */
  var ImprovementDirection = {
    DONT_CARE: 0,
    BIGGER_IS_BETTER: 1,
    SMALLER_IS_BETTER: 2
  };

  /** @constructor */
  function Unit(unitName, jsonName, basePrefix, isDelta, improvementDirection,
      formatSpec) {
    this.unitName = unitName;
    this.jsonName = jsonName;
    this.basePrefix = basePrefix;
    this.isDelta = isDelta;
    this.improvementDirection = improvementDirection;
    this.formatSpec_ = formatSpec;

    // Example: powerInWattsDelta_biggerIsBetter -> powerInWatts.
    this.baseUnit = undefined;

    // Example: energyInJoules_smallerIsBetter ->
    // energyInJoulesDelta_smallerIsBetter.
    this.correspondingDeltaUnit = undefined;
  }

  Unit.prototype = {
    asJSON: function() {
      return this.jsonName;
    },

    get unitString() {
      // TODO(benjhayden): Refactor with format() and test.
      var formatSpec = this.formatSpec_;
      if (typeof formatSpec === 'function')
        formatSpec = formatSpec();
      if (!formatSpec.unit) {
        return '';
      }

      var unitString = '';
      var unitPrefix = formatSpec.unitPrefix;
      if (unitPrefix !== undefined) {
        var selectedPrefix;
        if (unitPrefix instanceof Array) {
          selectedPrefix = unitPrefix[0];
        } else {
          selectedPrefix = unitPrefix;
        }
        unitString += selectedPrefix.symbol || '';
      }
      unitString += formatSpec.unit;

      return unitString;
    },

    format: function(value, opt_context) {
      var context = opt_context || {};
      var formatSpec = this.formatSpec_;
      if (typeof formatSpec === 'function')
        formatSpec = formatSpec();

      function resolveProperty(propertyName) {
        if (propertyName in context)
          return context[propertyName];
        else if (propertyName in formatSpec)
          return formatSpec[propertyName];
        else
          return undefined;
      }

      var signString = '';
      if (value < 0) {
        signString = '-';
        value = -value;  // Treat positive and negative values symmetrically.
      } else if (this.isDelta) {
        signString = value === 0 ? PLUS_MINUS_SIGN : '+';
      }

      var unitString = '';
      if (formatSpec.unit) {
        if (formatSpec.unitHasPrecedingSpace !== false)
          unitString += ' ';
        var unitPrefix = resolveProperty('unitPrefix');
        if (unitPrefix !== undefined) {
          var selectedPrefix;
          if (unitPrefix instanceof Array) {
            var i = 0;
            while (i < unitPrefix.length - 1 &&
                   value / unitPrefix[i + 1].value >= 1) {
              i++;
            }
            selectedPrefix = unitPrefix[i];
          } else {
            selectedPrefix = unitPrefix;
          }
          unitString += selectedPrefix.symbol || '';
          value = tr.b.convertUnit(value, this.basePrefix, selectedPrefix);
        } else {
          value = tr.b.convertUnit(value, this.basePrefix,
              tr.b.UnitScale.Metric.NONE);
        }
        unitString += formatSpec.unit;
      }

      var minimumFractionDigits = resolveProperty('minimumFractionDigits');
      var maximumFractionDigits = resolveProperty('maximumFractionDigits');

      // If the context overrides only one of the two |*FractionDigits|
      // properties and the other one is provided by the unit, we might need to
      // shift the other property so that
      // |minimumFractionDigits| <= |maximumFractionDigits|.
      if (minimumFractionDigits > maximumFractionDigits) {
        if ('minimumFractionDigits' in context &&
            !('maximumFractionDigits' in context)) {
          // Only minimumFractionDigits was overriden by context.
          maximumFractionDigits = minimumFractionDigits;
        } else if ('maximumFractionDigits' in context &&
            !('minimumFractionDigits' in context)) {
          // Only maximumFractionDigits was overriden by context.
          minimumFractionDigits = maximumFractionDigits;
        }
      }

      var numberString = value.toLocaleString(undefined, {
        minimumFractionDigits: minimumFractionDigits,
        maximumFractionDigits: maximumFractionDigits
      });

      return signString + numberString + unitString;
    }
  };

  Unit.reset = function() {
    Unit.currentTimeDisplayMode = TimeDisplayModes.ms;
  };

  Unit.timestampFromUs = function(us) {
    return tr.b.convertUnit(us, tr.b.UnitScale.Metric.MICRO,
        tr.b.UnitScale.Metric.MILLI);
  };

  Object.defineProperty(Unit, 'currentTimeDisplayMode', {
    get: function() {
      return Unit.currentTimeDisplayMode_;
    },
    // Use tr-v-ui-preferred-display-unit element instead of directly setting.
    set: function(value) {
      if (Unit.currentTimeDisplayMode_ === value)
        return;

      Unit.currentTimeDisplayMode_ = value;
      Unit.dispatchEvent(new tr.b.Event('display-mode-changed'));
    }
  });

  Unit.didPreferredTimeDisplayUnitChange = function() {
    var largest = undefined;
    var els = tr.b.findDeepElementsMatching(document.body,
        'tr-v-ui-preferred-display-unit');
    els.forEach(function(el) {
      largest = max(largest, el.preferredTimeDisplayMode);
    });

    Unit.currentDisplayUnit = largest === undefined ?
        TimeDisplayModes.ms : largest;
  };

  Unit.byName = {};
  Unit.byJSONName = {};

  Unit.fromJSON = function(object) {
    var u = Unit.byJSONName[object];
    if (u) {
      return u;
    }
    throw new Error('Unrecognized unit');
  };

  /**
   * Define all combinations of a unit with isDelta and improvementDirection
   * flags. For example, the following code:
   *
   *   Unit.define({
   *     baseUnitName: 'powerInWatts'
   *     baseJsonName: 'W'
   *     formatSpec: {
   *       // Specification of how the unit should be formatted (unit symbol,
   *       // unit prefix, fraction digits, etc), or a function returning such
   *       // a specification.
   *     }
   *   });
   *
   * generates the following six units (JSON names shown in parentheses):
   *
   *   Unit.byName.powerInWatts (W)
   *   Unit.byName.powerInWatts_smallerIsBetter (W_smallerIsBetter)
   *   Unit.byName.powerInWatts_biggerIsBetter (W_biggerIsBetter)
   *   Unit.byName.powerInWattsDelta (WDelta)
   *   Unit.byName.powerInWattsDelta_smallerIsBetter (WDelta_smallerIsBetter)
   *   Unit.byName.powerInWattsDelta_biggerIsBetter (WDelta_biggerIsBetter)
   *
   * with the appropriate flags and formatting code (including +/- prefixes
   * for deltas).
   */
  Unit.define = function(params) {
    var definedUnits = [];

    tr.b.iterItems(ImprovementDirection, function(_, improvementDirection) {
      var regularUnit =
          Unit.defineUnitVariant_(params, false, improvementDirection);
      var deltaUnit =
          Unit.defineUnitVariant_(params, true, improvementDirection);

      regularUnit.correspondingDeltaUnit = deltaUnit;
      deltaUnit.correspondingDeltaUnit = deltaUnit;
      definedUnits.push(regularUnit, deltaUnit);
    });

    var baseUnit = Unit.byName[params.baseUnitName];
    definedUnits.forEach(u => u.baseUnit = baseUnit);
  };

  Unit.nameSuffixForImprovementDirection = function(improvementDirection) {
    switch (improvementDirection) {
      case ImprovementDirection.DONT_CARE:
        return '';
      case ImprovementDirection.BIGGER_IS_BETTER:
        return '_biggerIsBetter';
      case ImprovementDirection.SMALLER_IS_BETTER:
        return '_smallerIsBetter';
      default:
        throw new Error(
            'Unknown improvement direction: ' + improvementDirection);
    }
  };

  Unit.defineUnitVariant_ = function(params, isDelta, improvementDirection) {
    var nameSuffix = isDelta ? 'Delta' : '';
    nameSuffix += Unit.nameSuffixForImprovementDirection(improvementDirection);

    var unitName = params.baseUnitName + nameSuffix;
    var jsonName = params.baseJsonName + nameSuffix;
    if (Unit.byName[unitName] !== undefined)
      throw new Error('Unit \'' + unitName + '\' already exists');
    if (Unit.byJSONName[jsonName] !== undefined)
      throw new Error('JSON unit \'' + jsonName + '\' alread exists');

    var basePrefix = params.basePrefix ?
        params.basePrefix : tr.b.UnitScale.Metric.NONE;
    var unit = new Unit(unitName, jsonName, basePrefix,
        isDelta, improvementDirection, params.formatSpec);
    Unit.byName[unitName] = unit;
    Unit.byJSONName[jsonName] = unit;

    return unit;
  };

  tr.b.EventTarget.decorate(Unit);
  Unit.reset();

  // Known display units follow.
  //////////////////////////////////////////////////////////////////////////////

  Unit.define({
    baseUnitName: 'timeDurationInMs',
    baseJsonName: 'ms',
    basePrefix: tr.b.UnitScale.Metric.MILLI,
    formatSpec: function() {
      return Unit.currentTimeDisplayMode_.formatSpec;
    }
  });

  Unit.define({
    baseUnitName: 'timeStampInMs',
    baseJsonName: 'tsMs',
    basePrefix: tr.b.UnitScale.Metric.MILLI,
    formatSpec: function() {
      return Unit.currentTimeDisplayMode_.formatSpec;
    }
  });

  Unit.define({
    baseUnitName: 'normalizedPercentage',
    baseJsonName: 'n%',
    formatSpec: {
      unit: '%',
      unitPrefix: { value: 0.01 },
      unitHasPrecedingSpace: false,
      minimumFractionDigits: 3,
      maximumFractionDigits: 3
    }
  });

  Unit.define({
    baseUnitName: 'sizeInBytes',
    baseJsonName: 'sizeInBytes',
    formatSpec: {
      unit: 'B',
      unitPrefix: tr.b.UnitScale.Binary.AUTO,
      minimumFractionDigits: 1,
      maximumFractionDigits: 1
    }
  });

  Unit.define({
    baseUnitName: 'energyInJoules',
    baseJsonName: 'J',
    formatSpec: {
      unit: 'J',
      minimumFractionDigits: 3
    }
  });

  Unit.define({
    baseUnitName: 'powerInWatts',
    baseJsonName: 'W',
    formatSpec: {
      unit: 'W',
      minimumFractionDigits: 3
    }
  });

  Unit.define({
    baseUnitName: 'unitlessNumber',
    baseJsonName: 'unitless',
    formatSpec: {
      minimumFractionDigits: 3,
      maximumFractionDigits: 3
    }
  });

  Unit.define({
    baseUnitName: 'count',
    baseJsonName: 'count',
    formatSpec: {
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }
  });

  Unit.define({
    baseUnitName: 'sigma',
    baseJsonName: 'sigma',
    formatSpec: {
      unit: String.fromCharCode(963),
      minimumFractionDigits: 1,
      maximumFractionDigits: 1
    }
  });

  return {
    ImprovementDirection: ImprovementDirection,
    Unit: Unit
  };
});
</script>