1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
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 */
15
16import byTrace from '@ohos.bytrace';
17import Log from './Log';
18
19/**
20 * Add method trace. Modify RECORD_TRACE before using.
21 */
22export default class Trace {
23  static readonly CORE_METHOD_START_DROPDOWNPANEL = 'startDropdownPanel';
24  static readonly CORE_METHOD_START_TOUCHEVENT = 'startTouchEvent';
25  static readonly CORE_METHOD_CLICK_CAPSULE = 'clickCapsuleEvent';
26  static readonly CORE_METHOD_CLICK_NOTIFICATION = 'clickNotificationEvent';
27  static readonly CORE_METHOD_START_VOLUMEPANEL = 'startVolumePanel';
28
29  private static readonly TRACE_TAG = 'Systemui:Trace';
30  private static readonly RECORD_TRACE = true;
31  private static readonly TRACE_LIMIT = 2000;
32
33  private static readonly TRACE_BASE_INDEX = 10000;
34
35  /**
36    * start trace method
37    *
38    * @param {string} methodName - methodName for tracing
39    */
40  static start(methodName: string) {
41    if (!Trace.RECORD_TRACE) return;
42    if (typeof globalThis.taskIdMap === 'undefined' || typeof globalThis.traceIndex === 'undefined') {
43      Trace.init();
44    }
45    let taskId = globalThis.taskIdMap.get(methodName);
46    if (taskId == undefined) {
47      taskId = globalThis.traceIndex;
48      globalThis.traceIndex++;
49      globalThis.taskIdMap.set(methodName, taskId);
50    }
51    Log.showInfo(this.TRACE_TAG, `start trace ${taskId}`);
52    byTrace.startTrace(this.TRACE_TAG + methodName, taskId, Trace.TRACE_LIMIT);
53  }
54
55  private static init() {
56    Log.showInfo(this.TRACE_TAG, 'init trace parameters');
57    globalThis.taskIdMap = new Map<string, number>();
58    globalThis.traceIndex = Trace.TRACE_BASE_INDEX;
59  }
60
61  /**
62    * stop trace method
63    *
64    * @param {string} methodName - methodName for tracing
65    */
66  static end(methodName: string) {
67    if (!Trace.RECORD_TRACE) return;
68    if (typeof globalThis.taskIdMap === 'undefined') {
69      return;
70    }
71    const taskId = globalThis.taskIdMap.get(methodName);
72    if (taskId == undefined) {
73      Log.showError(this.TRACE_TAG, `fail to end trace name ${methodName}`);
74      return;
75    }
76    Log.showInfo(this.TRACE_TAG, `end trace ${taskId}`);
77    byTrace.finishTrace(this.TRACE_TAG + methodName, taskId);
78  }
79}