1 /* 2 * Copyright (c) 2024 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 OHOS_DISTRIBUTED_DATA_PASTEBOARD_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_CENTER_H 17 #define OHOS_DISTRIBUTED_DATA_PASTEBOARD_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_CENTER_H 18 #include <list> 19 #include <queue> 20 #include <memory> 21 #include "common/concurrent_map.h" 22 #include "eventcenter/event.h" 23 #include "api/visibility.h" 24 namespace OHOS::MiscServices { 25 class EventCenter { 26 public: 27 enum : int32_t { 28 CODE_SYNC = 1, 29 CODE_ASYNC, 30 CODE_INVALID_ARGS, 31 }; 32 33 class Defer final { 34 public: 35 API_EXPORT Defer(std::function<void(const Event &)> handler = nullptr, int32_t evtId = Event::EVT_INVALID); 36 API_EXPORT ~Defer(); 37 void *operator new (size_t size) = delete; 38 void *operator new[] (size_t size) = delete; 39 void operator delete (void *) = delete; 40 void operator delete[] (void *) = delete; 41 }; 42 API_EXPORT static EventCenter &GetInstance(); 43 API_EXPORT bool Subscribe(int32_t evtId, const std::function<void(const Event &)> &observer); 44 API_EXPORT bool Unsubscribe(int32_t evtId); 45 API_EXPORT int32_t PostEvent(std::unique_ptr<Event> evt) const; 46 private: 47 void Dispatch(const Event &evt) const; 48 class AsyncQueue final { 49 public: 50 static constexpr int32_t MAX_CAPABILITY = 100; 51 AsyncQueue &operator++(); 52 AsyncQueue &operator--(); 53 bool operator<=(int32_t depth) const; 54 void Post(std::unique_ptr<Event> event); 55 void AddHandler(int32_t evtId, std::function<void(const Event &)> handler); 56 private: 57 std::map<int32_t, std::function<void(const Event &)>> handlers_; 58 std::deque<std::unique_ptr<Event>> events_; 59 int32_t depth_ = 0; 60 }; 61 ConcurrentMap<int32_t, std::list<std::function<void(const Event &)>>> observers_; 62 static thread_local AsyncQueue *asyncQueue_; 63 }; 64 } // namespace OHOS::MiscServices 65 #endif // OHOS_DISTRIBUTED_DATA_PASTEBOARD_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_CENTER_H 66