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 #include <functional> 24 #include "napi/native_api.h" 25 #include "print_job.h" 26 27 namespace OHOS { 28 namespace AbilityRuntime { 29 class JsRuntime; 30 struct WorkParam { 31 napi_env env; 32 std::string funcName; 33 std::string printerId; 34 Print::PrintJob job; WorkParamWorkParam35 WorkParam(napi_env env, std::string funcName) : env(env), funcName(funcName) {} 36 }; 37 class JsPrintCallback : public std::enable_shared_from_this<JsPrintCallback> { 38 public: 39 explicit JsPrintCallback(JsRuntime &jsRutime); 40 ~JsPrintCallback() = default; 41 static bool Call(napi_env env, WorkParam *param, std::function<void(WorkParam*)> workCb); 42 napi_value Exec(napi_value jsObj, const std::string &name, napi_value const *argv = nullptr, size_t argc = 0, 43 bool isSync = true); 44 45 private: 46 uv_loop_s *GetJsLoop(JsRuntime &jsRuntime); 47 uv_work_t* BuildJsWorker(napi_value jsObj, const std::string &name, 48 napi_value const *argv, size_t argc, bool isSync); 49 int UvQueueWork(uv_loop_s* loop, uv_work_t* worker); 50 51 private: 52 struct JsWorkParam { 53 std::shared_ptr<JsPrintCallback> self; 54 napi_env nativeEngine; 55 napi_value jsObj; 56 napi_value jsMethod; 57 napi_value const *argv; 58 size_t argc; 59 napi_value jsResult; 60 bool isSync; 61 bool isCompleted; JsWorkParamJsWorkParam62 JsWorkParam() 63 { 64 self = nullptr; 65 nativeEngine = nullptr; 66 jsObj = nullptr; 67 jsMethod = nullptr; 68 argv = nullptr; 69 argc = 0; 70 jsResult = nullptr; 71 isSync = false; 72 isCompleted = false; 73 } 74 }; 75 76 JsRuntime &jsRuntime_; 77 78 JsPrintCallback::JsWorkParam jsParam_; 79 80 std::mutex conditionMutex_; 81 std::condition_variable syncCon_; 82 static constexpr int SYNC_TIME_OUT = 1000; 83 }; 84 } // namespace AbilityRuntime 85 } // namespace OHOS 86 #endif // JS_PRINT_CALLBACK_H 87