1 /*
2  * Copyright (c) 2021 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 
16 #include "bridge/declarative_frontend/interfaces/profiler/js_profiler.h"
17 
18 #include <memory>
19 
20 #include "bridge/declarative_frontend/engine/bindings.h"
21 #include "bridge/declarative_frontend/engine/functions/js_function.h"
22 #include "bridge/declarative_frontend/engine/js_ref_ptr.h"
23 #include "bridge/declarative_frontend/engine/js_types.h"
24 #include "core/common/container.h"
25 
26 namespace OHOS::Ace::Framework {
27 
JSBind(BindingTarget globalObj)28 void JSProfiler::JSBind(BindingTarget globalObj)
29 {
30     JSClass<JSProfiler>::Declare("Profiler");
31     JSClass<JSProfiler>::StaticMethod("registerVsyncCallback", &JSProfiler::JsRegisterVsyncCallback);
32     JSClass<JSProfiler>::StaticMethod("unregisterVsyncCallback", &JSProfiler::JsUnregisterVsyncCallback);
33     JSClass<JSProfiler>::Bind<>(globalObj);
34 }
35 
JsRegisterVsyncCallback(const JSCallbackInfo & args)36 void JSProfiler::JsRegisterVsyncCallback(const JSCallbackInfo& args)
37 {
38     if (!args[0]->IsFunction()) {
39         LOGE("fail to register callback due to args is not function");
40         return;
41     }
42     auto container = Container::Current();
43     auto pipelineContext = container ? container->GetPipelineContext() : nullptr;
44     if (!pipelineContext) {
45         LOGE("fail to register callback due to pipeline is null");
46         return;
47     }
48     auto onVsyncJsFunc = AceType::MakeRefPtr<JsFunction>(JSRef<JSFunc>::Cast(args[0]));
49     auto onVsyncFunc = [execCtx = args.GetExecutionContext(), func = std::move(onVsyncJsFunc)](
50                            const std::string& value) {
51         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
52         JSRef<JSVal> params[1];
53         params[0] = JSRef<JSVal>::Make(ToJSValue(value));
54         func->ExecuteJS(1, params);
55     };
56     pipelineContext->SetOnVsyncProfiler(onVsyncFunc);
57 }
58 
JsUnregisterVsyncCallback()59 void JSProfiler::JsUnregisterVsyncCallback()
60 {
61     auto container = Container::Current();
62     auto pipelineContext = container ? container->GetPipelineContext() : nullptr;
63     if (!pipelineContext) {
64         LOGE("fail to unregister callback due to pipeline is null");
65         return;
66     }
67     pipelineContext->ResetOnVsyncProfiler();
68 }
69 
70 } // namespace OHOS::Ace::Framework
71