1 /* 2 * Copyright (c) 2025 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 #ifndef CALLBACK_CODE_NAPI_H 17 #define CALLBACK_CODE_NAPI_H 18 19 #include <napi/native_api.h> 20 #include <napi/native_node_api.h> 21 #include "frontend_api_defines.h" 22 #include "api_caller_client.h" 23 24 namespace OHOS::perftest { 25 // Define a lock structure to synchronously wait for the callback function to complete execution 26 class ThreadLock { 27 public: 28 ThreadLock() = default; 29 ~ThreadLock() = default; 30 void LockRelease(string errorMessage); 31 public: 32 mutex mutex; 33 condition_variable condition; 34 bool ready = false; 35 bool res = false; 36 string errMsg; 37 }; 38 39 struct CodeCallbackContext { 40 napi_env env; 41 string callbackId; 42 napi_ref callbackRef; 43 uint32_t timeout; 44 napi_callback cb; 45 }; 46 47 class CallbackCodeNapi { 48 public: 49 void PreprocessCallback(napi_env env, ApiCallInfo &call, napi_value jsThis, 50 napi_value jsParam, ApiCallErr &err); 51 void InitCallbackContext(napi_env env, const ApiCallInfo &in, ApiReplyInfo &out, 52 shared_ptr<CodeCallbackContext> ctx); 53 void BindPromiseCallbacks(napi_env env, napi_value promise, ThreadLock* threadLock); 54 void WaitforCallbackFinish(napi_env env, shared_ptr<CodeCallbackContext> context, 55 ThreadLock* threadLock, ApiReplyInfo &out); 56 void ExecuteCallback(napi_env env, const ApiCallInfo &in, ApiReplyInfo &out); 57 void DestroyCallbacks(napi_env env, const ApiCallInfo &in, ApiReplyInfo &out); 58 void HandleCallbackEvent(napi_env env, const ApiCallInfo &in, ApiReplyInfo &out); 59 static CallbackCodeNapi &Get(); 60 61 private: 62 CallbackCodeNapi() = default; 63 const string ACTION_CODE_FUNC_NAME = "actionCode"; 64 const string RESET_CODE_FUNC_NAME = "resetCode"; 65 }; 66 } // namespace OHOS::perftest 67 68 #endif