Move swaybar's event loop to common directory and refactor

* The loop functions are now prefixed with `loop_`.
* It is now easy to add timers to the loop.
* Timers are implemented using pollfd and timerfd, rather than manually
checking them when any other event happens to arrive.
This commit is contained in:
Ryan Dwyer 2018-10-13 16:04:37 +10:00
parent 7f2e6d812a
commit 4056c09e13
10 changed files with 172 additions and 192 deletions

47
include/loop.h Normal file
View file

@ -0,0 +1,47 @@
#ifndef _SWAY_LOOP_H
#define _SWAY_LOOP_H
#include <stdbool.h>
/**
* This is an event loop system designed for sway clients, not sway itself.
*
* It uses pollfds to block on multiple file descriptors at once, and provides
* an easy way to set timers. Typically the Wayland display's fd will be one of
* the fds in the loop.
*/
struct loop;
/**
* Create an event loop.
*/
struct loop *loop_create(void);
/**
* Destroy the event loop (eg. on program termination).
*/
void loop_destroy(struct loop *loop);
/**
* Poll the event loop. This will block until one of the fds has data.
*/
void loop_poll(struct loop *loop);
/**
* Add an fd to the loop.
*/
struct loop_event *loop_add_fd(struct loop *loop, int fd, short mask,
void (*func)(int fd, short mask, void *data), void *data);
/**
* Add a timer to the loop.
*/
struct loop_event *loop_add_timer(struct loop *loop, int ms,
void (*callback)(int fd, short mask, void *data), void *data);
/**
* Remove an event from the loop.
*/
bool loop_remove_event(struct loop *loop, struct loop_event *event);
#endif

View file

@ -8,6 +8,8 @@
struct swaybar_config;
struct swaybar_output;
struct swaybar_workspace;
struct loop;
struct loop_event;
struct swaybar_pointer {
struct wl_pointer *pointer;
@ -66,6 +68,9 @@ struct swaybar {
struct swaybar_pointer pointer;
struct status_line *status;
struct loop *eventloop;
struct loop_event *status_event;
int ipc_event_socketfd;
int ipc_socketfd;

View file

@ -1,26 +0,0 @@
#ifndef _SWAYBAR_EVENT_LOOP_H
#define _SWAYBAR_EVENT_LOOP_H
#include <stdbool.h>
#include <time.h>
void add_event(int fd, short mask,
void(*cb)(int fd, short mask, void *data),
void *data);
// Not guaranteed to notify cb immediately
void add_timer(timer_t timer,
void(*cb)(timer_t timer, void *data),
void *data);
// Returns false if nothing exists, true otherwise
bool remove_event(int fd);
// Returns false if nothing exists, true otherwise
bool remove_timer(timer_t timer);
// Blocks and returns after sending callbacks
void event_loop_poll(void);
void init_event_loop(void);
#endif

View file

@ -14,6 +14,8 @@ enum status_protocol {
};
struct status_line {
struct swaybar *bar;
pid_t pid;
int read_fd, write_fd;
FILE *read, *write;