1 /*
2 * Copyright (c) 2024 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 #include "core/common/recorder/inspector_tree_collector.h"
16
17 #include <memory>
18 #include <string>
19
20 namespace OHOS::Ace::Recorder {
InspectorTreeCollector(OnInspectorTreeResult && callback,bool isBackground)21 InspectorTreeCollector::InspectorTreeCollector(OnInspectorTreeResult&& callback, bool isBackground)
22 : onResultFunc_(std::move(callback)), isBackground_(isBackground)
23 {
24 root_ = JsonUtil::Create(true);
25 }
26
IncreaseTaskNum()27 void InspectorTreeCollector::IncreaseTaskNum()
28 {
29 if (isBackground_) {
30 std::unique_lock<std::mutex> lock(mutex_);
31 UpdateTaskNum(1);
32 } else {
33 UpdateTaskNum(1);
34 }
35 }
36
DecreaseTaskNum()37 void InspectorTreeCollector::DecreaseTaskNum()
38 {
39 if (isBackground_) {
40 std::unique_lock<std::mutex> lock(mutex_);
41 UpdateTaskNum(-1);
42 } else {
43 UpdateTaskNum(-1);
44 }
45 }
46
UpdateTaskNum(int32_t num)47 void InspectorTreeCollector::UpdateTaskNum(int32_t num)
48 {
49 taskNum_ += num;
50 if (taskNum_ == 0) {
51 if (!root_) {
52 return;
53 }
54 if (!onResultFunc_) {
55 root_ = JsonUtil::Create(true);
56 return;
57 }
58 onResultFunc_(std::make_shared<std::string>(root_->ToString()));
59 root_ = JsonUtil::Create(true);
60 if (taskExecutor_ && isBackground_) {
61 taskExecutor_->PostTask(
62 [collector = shared_from_this()]() {
63 collector->cacheNodes_.clear();
64 },
65 TaskExecutor::TaskType::UI, "InspectorTreeCollector");
66 }
67 }
68 }
69
CreateJson()70 void InspectorTreeCollector::CreateJson()
71 {
72 root_ = JsonUtil::Create(true);
73 }
74
GetJson()75 std::unique_ptr<JsonValue>& InspectorTreeCollector::GetJson()
76 {
77 return root_;
78 }
79
RetainNode(const RefPtr<NG::UINode> & node)80 void InspectorTreeCollector::RetainNode(const RefPtr<NG::UINode>& node)
81 {
82 cacheNodes_.emplace_back(node);
83 }
84
SetTaskExecutor(const RefPtr<TaskExecutor> & taskExecutor)85 void InspectorTreeCollector::SetTaskExecutor(const RefPtr<TaskExecutor>& taskExecutor)
86 {
87 taskExecutor_ = taskExecutor;
88 }
89 } // namespace OHOS::Ace::Recorder
90