util: move DB() debug macro from app
[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 //                                                 |_|         |_____|
54 struct unique_fd {
55    int fd{-1};
56    unique_fd() = default;
57    explicit unique_fd(int f) : fd{f} {}
58    operator int() const { return fd; }
59    ~unique_fd();
60    unique_fd(unique_fd const &) = delete;
61    unique_fd &operator=(unique_fd const &) = delete;
62    unique_fd(unique_fd &&o) : fd(o.fd) { o.fd = -1; }
63    unique_fd &operator=(unique_fd &&o) {
64       std::swap(this->fd, o.fd);
65       return *this;
66    }
67 };
68
69 //      _                   _     ____       _ _
70 //  ___| |_ _ __ _   _  ___| |_  |  _ \ ___ | | | ___ _ __
71 // / __| __| '__| | | |/ __| __| | |_) / _ \| | |/ _ \ '__|
72 // \__ \ |_| |  | |_| | (__| |_  |  __/ (_) | | |  __/ |
73 // |___/\__|_|   \__,_|\___|\__| |_|   \___/|_|_|\___|_|
74 //
75 struct Poller {
76    std::vector<std::function<int(int)>> handlers;
77    std::vector<struct pollfd> pfds;
78
79    Poller() = default;
80    void add_fd(int fd, std::function<int(int)> handler);
81    int check_events();
82 };
83
84 #endif  // !WM_UTIL_HPP