Integrate internal fixes
[platform/core/system/sensord.git] / src / shared / event_loop.h
1 /*
2  * sensord
3  *
4  * Copyright (c) 2017 Samsung Electronics Co., Ltd.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19
20 #ifndef __EVENT_LOOP_H__
21 #define __EVENT_LOOP_H__
22
23 #include <stdint.h>
24 #include <glib.h>
25 #include <atomic>
26 #include <map>
27
28 #include "event_handler.h"
29
30 namespace ipc {
31
32 enum event_condition_e {
33         EVENT_IN =  G_IO_IN,
34         EVENT_OUT = G_IO_OUT,
35         EVENT_HUP = G_IO_HUP,
36         EVENT_NVAL = G_IO_NVAL,
37 };
38
39 /* move it to file */
40 class idle_handler {
41         virtual ~idle_handler();
42         bool handle(int fd);
43 };
44
45 class event_loop;
46
47 class handler_info {
48 public:
49         handler_info(uint64_t _id, int _fd, GIOChannel *_ch, GSource *_src, event_handler *_handler, event_loop *_loop)
50         : id(_id)
51         , fd(_fd)
52         , g_ch(_ch)
53         , g_src(_src)
54         , handler(_handler)
55         , loop(_loop)
56         {}
57
58         uint64_t id;
59         int fd;
60         GIOChannel *g_ch;
61         GSource *g_src;
62         event_handler *handler;
63         event_loop *loop;
64 };
65
66 class event_loop {
67 public:
68         typedef unsigned int event_condition;
69         typedef bool (*idle_cb)(void *);
70
71         event_loop();
72         event_loop(GMainLoop *mainloop);
73         ~event_loop();
74
75         void set_mainloop(GMainLoop *mainloop);
76
77         uint64_t add_event(const int fd, const event_condition cond, event_handler *handler);
78         uint64_t add_idle_event(unsigned int priority, idle_handler *handler);
79
80         bool remove_event(uint64_t id, bool close_channel = false);
81         void remove_all_events(void);
82
83         void release_info(handler_info *info);
84
85         bool run(int timeout = 0);
86         void stop(void);
87         void terminate(void);
88
89         bool is_running(void);
90         bool is_terminator(int fd);
91
92 private:
93         GMainLoop *m_mainloop;
94         std::atomic<bool> m_running;
95         std::atomic<bool> m_terminating;
96         std::atomic<uint64_t> m_sequence;
97         std::map<uint64_t, handler_info *> m_handlers;
98
99         int m_term_fd;
100 };
101
102 }
103
104 #endif /* __EVENT_LOOP_H__ */