1 /* 2 * Copyright (c) 2023 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 #ifndef OHOS_INPUT_CALLBACK_HANDLER_H 16 #define OHOS_INPUT_CALLBACK_HANDLER_H 17 18 #include <functional> 19 #include "inputmethod_trace.h" 20 #include "js_callback_object.h" 21 #include "js_util.h" 22 #include "napi/native_api.h" 23 #include "napi/native_node_api.h" 24 25 namespace OHOS { 26 namespace MiscServices { 27 class JsCallbackHandler { 28 public: 29 using ArgvProvider = std::function<bool(napi_env, napi_value *, size_t)>; 30 struct ArgContainer { 31 size_t argc{ 0 }; 32 ArgvProvider argvProvider{ nullptr }; 33 }; 34 // 0 means the callback has no param. 35 static void Traverse(const std::vector<std::shared_ptr<JSCallbackObject>> &objects, 36 const ArgContainer &argContainer = { 0, nullptr }) 37 { 38 InputMethodSyncTrace tracer("Traverse callback"); 39 for (const auto &object : objects) { 40 if (object == nullptr) { 41 continue; 42 } 43 JsUtil::ScopeGuard scopeGuard(object->env_); 44 napi_value jsOutput = nullptr; 45 Execute(object, argContainer, jsOutput); 46 } 47 } 48 template<typename T> Traverse(const std::vector<std::shared_ptr<JSCallbackObject>> & objects,const ArgContainer & argContainer,T & output)49 static void Traverse(const std::vector<std::shared_ptr<JSCallbackObject>> &objects, 50 const ArgContainer &argContainer, T &output) 51 { 52 InputMethodSyncTrace tracer("Traverse callback with output"); 53 for (const auto &object : objects) { 54 if (object == nullptr) { 55 continue; 56 } 57 JsUtil::ScopeGuard scopeGuard(object->env_); 58 napi_value jsOutput = nullptr; 59 Execute(object, argContainer, jsOutput); 60 if (jsOutput != nullptr && JsUtil::GetValue(object->env_, jsOutput, output)) { 61 break; 62 } 63 } 64 } 65 66 private: 67 static void Execute(const std::shared_ptr<JSCallbackObject> &object, const ArgContainer &argContainer, 68 napi_value &output); 69 }; 70 } // namespace MiscServices 71 } // namespace OHOS 72 #endif // OHOS_INPUT_CALLBACK_HANDLER_H 73