c528d42ab5375e7779e5a908615f89fd46b02d1b
[staging/windowmanager.git] / src / util.hpp
1 #ifndef WM_UTIL_HPP
2 #define WM_UTIL_HPP
3
4 #include <functional>
5 #include <sys/poll.h>
6
7 #include <vector>
8
9 extern "C" {
10 #include <afb/afb-binding.h>
11 };
12
13 #ifdef __GNUC__
14 #define ATTR_FORMAT(stringindex, firsttocheck) \
15    __attribute__((format(printf, stringindex, firsttocheck)))
16 #define ATTR_NORETURN __attribute__((noreturn))
17 #else
18 #define ATTR_FORMAT(stringindex, firsttocheck)
19 #define ATTR_NORETURN
20 #endif
21
22 #define lognotice(...) AFB_NOTICE(__VA_ARGS__)
23 #define logerror(...) AFB_ERROR(__VA_ARGS__)
24 #define fatal(...)            \
25    do {                       \
26       AFB_ERROR(__VA_ARGS__); \
27       abort();                \
28    } while (0)
29
30 #ifdef DEBUG_OUTPUT
31 #define logdebug(...) AFB_DEBUG(__VA_ARGS__)
32 #else
33 #define logdebug(...)
34 #endif
35
36 #ifndef NDEBUG
37 #define DB(expr)                                                           \
38    do {                                                                    \
39       std::ostringstream o;                                                \
40       o << __FILE__ << ":" << __LINE__ << ":" << __func__ << ": " << expr; \
41       logdebug("%s", o.str().c_str());                                     \
42    } while (0)
43 #else
44 #define DB(expr)
45 #endif
46
47 //      _                   _                 _                       __     _
48 //  ___| |_ _ __ _   _  ___| |_   _   _ _ __ (_) __ _ _   _  ___     / _| __| |
49 // / __| __| '__| | | |/ __| __| | | | | '_ \| |/ _` | | | |/ _ \   | |_ / _` |
50 // \__ \ |_| |  | |_| | (__| |_  | |_| | | | | | (_| | |_| |  __/   |  _| (_| |
51 // |___/\__|_|   \__,_|\___|\__|  \__,_|_| |_|_|\__, |\__,_|\___|___|_|  \__,_|
52 //                                                 |_|         |_____|
53 struct unique_fd {
54    int fd{-1};
55    unique_fd() = default;
56    explicit unique_fd(int f) : fd{f} {}
57    operator int() const { return fd; }
58    ~unique_fd();
59    unique_fd(unique_fd const &) = delete;
60    unique_fd &operator=(unique_fd const &) = delete;
61    unique_fd(unique_fd &&o) : fd(o.fd) { o.fd = -1; }
62    unique_fd &operator=(unique_fd &&o) {
63       std::swap(this->fd, o.fd);
64       return *this;
65    }
66 };
67
68 //      _                   _     ____       _ _
69 //  ___| |_ _ __ _   _  ___| |_  |  _ \ ___ | | | ___ _ __
70 // / __| __| '__| | | |/ __| __| | |_) / _ \| | |/ _ \ '__|
71 // \__ \ |_| |  | |_| | (__| |_  |  __/ (_) | | |  __/ |
72 // |___/\__|_|   \__,_|\___|\__| |_|   \___/|_|_|\___|_|
73 //
74 struct Poller {
75    std::vector<std::function<int(int)>> handlers;
76    std::vector<struct pollfd> pfds;
77
78    Poller() = default;
79    void add_fd(int fd, std::function<int(int)> handler);
80    int check_events();
81 };
82
83 #endif  // !WM_UTIL_HPP