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 InputMethodSyncTrace tracer("Traverse callback"); 38 for (const auto &object : objects) { 39 JsUtil::ScopeGuard scopeGuard(object->env_); 40 napi_value jsOutput = nullptr; 41 Execute(object, argContainer, jsOutput); 42 } 43 } 44 template<typename T> Traverse(const std::vector<std::shared_ptr<JSCallbackObject>> & objects,const ArgContainer & argContainer,T & output)45 static void Traverse( 46 const std::vector<std::shared_ptr<JSCallbackObject>> &objects, const ArgContainer &argContainer, T &output) 47 { 48 InputMethodSyncTrace tracer("Traverse callback with output"); 49 for (const auto &object : objects) { 50 JsUtil::ScopeGuard scopeGuard(object->env_); 51 napi_value jsOutput = nullptr; 52 Execute(object, argContainer, jsOutput); 53 if (jsOutput != nullptr && JsUtil::GetValue(object->env_, jsOutput, output)) { 54 break; 55 } 56 } 57 } 58 59 private: 60 static void Execute( 61 const std::shared_ptr<JSCallbackObject> &object, const ArgContainer &argContainer, napi_value &output); 62 }; 63 } // namespace MiscServices 64 } // namespace OHOS 65 #endif // OHOS_INPUT_CALLBACK_HANDLER_H 66