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