xref: /aosp_15_r20/external/perfetto/ui/src/components/time_utils.ts (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1// Copyright (C) 2024 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import m from 'mithril';
16import {Duration, duration, time, Time} from '../base/time';
17import {Trace} from '../public/trace';
18import {DurationPrecision, TimestampFormat} from '../public/timeline';
19
20export function renderTimecode(time: time) {
21  const {dhhmmss, millis, micros, nanos} = Time.toTimecode(time);
22  return m(
23    'span.pf-timecode',
24    m('span.pf-timecode-hms', dhhmmss),
25    '.',
26    m('span.pf-timecode-millis', millis),
27    m('span.pf-timecode-micros', micros),
28    m('span.pf-timecode-nanos', nanos),
29  );
30}
31
32export function formatDuration(trace: Trace, dur: duration): string {
33  const fmt = trace.timeline.timestampFormat;
34  switch (fmt) {
35    case TimestampFormat.UTC:
36    case TimestampFormat.TraceTz:
37    case TimestampFormat.Timecode:
38      return renderFormattedDuration(trace, dur);
39    case TimestampFormat.TraceNs:
40      return dur.toString();
41    case TimestampFormat.TraceNsLocale:
42      return dur.toLocaleString();
43    case TimestampFormat.Seconds:
44      return Duration.formatSeconds(dur);
45    case TimestampFormat.Milliseconds:
46      return Duration.formatMilliseconds(dur);
47    case TimestampFormat.Microseconds:
48      return Duration.formatMicroseconds(dur);
49    default:
50      const x: never = fmt;
51      throw new Error(`Invalid format ${x}`);
52  }
53}
54
55function renderFormattedDuration(trace: Trace, dur: duration): string {
56  const fmt = trace.timeline.durationPrecision;
57  switch (fmt) {
58    case DurationPrecision.HumanReadable:
59      return Duration.humanise(dur);
60    case DurationPrecision.Full:
61      return Duration.format(dur);
62    default:
63      const x: never = fmt;
64      throw new Error(`Invalid format ${x}`);
65  }
66}
67