1 /* 2 * Copyright (C) 2023-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 * Description: supply napi callback for interfaces. 15 * Author: zhangjingnan 16 * Create: 2023-4-11 17 */ 18 19 #ifndef NAPI_CALLBACK_H 20 #define NAPI_CALLBACK_H 21 22 #include <functional> 23 #include <list> 24 #include "napi/native_api.h" 25 #include "napi/native_common.h" 26 #include "napi/native_node_api.h" 27 #include "uv.h" 28 29 namespace OHOS { 30 namespace CastEngine { 31 namespace CastEngineClient { 32 class NapiCallback final : public std::enable_shared_from_this<NapiCallback> { 33 public: 34 using NapiArgsGetter = std::function<void(napi_env env, int &argc, napi_value *argv)>; 35 36 explicit NapiCallback(napi_env env); 37 ~NapiCallback(); 38 39 napi_env GetEnv() const; 40 41 void HandleEvent(int32_t event, NapiArgsGetter &getter); 42 napi_status AddCallback(napi_env env, int32_t event, napi_value callback); 43 napi_status RemoveCallback(napi_env env, int32_t event, napi_value callback); 44 bool IsCallbackListEmpty(); 45 46 private: 47 struct DataContext { 48 napi_env env; 49 napi_ref method; 50 NapiArgsGetter getter; 51 std::shared_ptr<NapiCallback> callback; 52 int32_t event; 53 }; 54 void Call(napi_ref method, NapiArgsGetter &getter, int32_t event); 55 void AfterWorkCallback(std::shared_ptr<DataContext> context); 56 bool IsCallbackValid(napi_env env, napi_ref ref, int32_t event); 57 napi_status ReleaseRef(napi_env env, napi_ref ref); 58 59 static constexpr int EVENT_TYPE_MAX = 30; 60 static constexpr size_t ARGC_MAX = 6; 61 62 napi_env env_ = nullptr; 63 uv_loop_s *loop_ = nullptr; 64 std::mutex lock_; 65 std::list<napi_ref> callbacks_[EVENT_TYPE_MAX] {}; 66 }; 67 } // namespace CastEngineClient 68 } // namespace CastEngine 69 } // namespace OHOS 70 #endif