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 16 #ifndef JS_PRINT_CALLBACK_H 17 #define JS_PRINT_CALLBACK_H 18 19 #include <memory> 20 #include <mutex> 21 #include <uv.h> 22 #include <vector> 23 24 #include "napi/native_api.h" 25 26 namespace OHOS { 27 namespace AbilityRuntime { 28 class JsRuntime; 29 class JsPrintCallback : public std::enable_shared_from_this<JsPrintCallback> { 30 public: 31 explicit JsPrintCallback(JsRuntime &jsRutime); 32 ~JsPrintCallback() = default; 33 static bool Call(napi_env env, void *data, uv_after_work_cb afterCallback); 34 napi_value Exec(napi_value jsObj, const std::string &name, napi_value const *argv = nullptr, size_t argc = 0, 35 bool isSync = true); 36 37 private: 38 uv_loop_s *GetJsLoop(JsRuntime &jsRuntime); 39 uv_work_t* BuildJsWorker(napi_value jsObj, const std::string &name, 40 napi_value const *argv, size_t argc, bool isSync); 41 int UvQueueWork(uv_loop_s* loop, uv_work_t* worker); 42 43 private: 44 struct JsWorkParam { 45 std::shared_ptr<JsPrintCallback> self; 46 napi_env nativeEngine; 47 napi_value jsObj; 48 napi_value jsMethod; 49 napi_value const *argv; 50 size_t argc; 51 napi_value jsResult; 52 bool isSync; 53 bool isCompleted; JsWorkParamJsWorkParam54 JsWorkParam() 55 { 56 self = nullptr; 57 nativeEngine = nullptr; 58 jsObj = nullptr; 59 jsMethod = nullptr; 60 argv = nullptr; 61 argc = 0; 62 jsResult = nullptr; 63 isSync = false; 64 isCompleted = false; 65 } 66 }; 67 68 JsRuntime &jsRuntime_; 69 70 JsPrintCallback::JsWorkParam jsParam_; 71 72 std::mutex conditionMutex_; 73 std::condition_variable syncCon_; 74 static constexpr int SYNC_TIME_OUT = 1000; 75 }; 76 } // namespace AbilityRuntime 77 } // namespace OHOS 78 #endif // JS_PRINT_CALLBACK_H 79