Krolyxon
Commit ad571e7

Branches

Refs →

nsxivautoreload_inotify.c

111 lines · 2.7 KB · C

1/* Copyright 2017 Max Voit, Bert Muennich
2 *
3 * This file is a part of nsxiv.
4 *
5 * nsxiv is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published
7 * by the Free Software Foundation; either version 2 of the License,
8 * or (at your option) any later version.
9 *
10 * nsxiv is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with nsxiv. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19#include "nsxiv.h"
20
21#include <errno.h>
22#include <stdlib.h>
23#include <string.h>
24#include <unistd.h>
25#include <sys/inotify.h>
26
27static union {
28 char d[4096]; /* aligned buffer */
29 struct inotify_event e;
30} buf;
31
32void arl_init(arl_t *arl)
33{
34 arl->fd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
35 arl->wd_dir = arl->wd_file = -1;
36 if (arl->fd == -1)
37 error(0, 0, "Could not initialize inotify, no automatic image reloading");
38}
39
40CLEANUP void arl_cleanup(arl_t *arl)
41{
42 if (arl->fd != -1)
43 close(arl->fd);
44 free(arl->filename);
45}
46
47static void rm_watch(int fd, int *wd)
48{
49 if (*wd != -1) {
50 inotify_rm_watch(fd, *wd);
51 *wd = -1;
52 }
53}
54
55static void add_watch(int fd, int *wd, const char *path, uint32_t mask)
56{
57 *wd = inotify_add_watch(fd, path, mask);
58 if (*wd == -1)
59 error(0, errno, "inotify: %s", path);
60}
61
62void arl_setup(arl_t *arl, const char *filepath)
63{
64 char *base = strrchr(filepath, '/');
65
66 if (arl->fd == -1)
67 return;
68
69 rm_watch(arl->fd, &arl->wd_dir);
70 rm_watch(arl->fd, &arl->wd_file);
71
72 add_watch(arl->fd, &arl->wd_file, filepath, IN_CLOSE_WRITE | IN_DELETE_SELF);
73
74 free(arl->filename);
75 arl->filename = estrdup(filepath);
76
77 if (base != NULL) {
78 arl->filename[++base - filepath] = '\0';
79 add_watch(arl->fd, &arl->wd_dir, arl->filename, IN_CREATE | IN_MOVED_TO);
80 strcpy(arl->filename, base);
81 }
82}
83
84bool arl_handle(arl_t *arl)
85{
86 bool reload = false;
87 char *ptr;
88 const struct inotify_event *e;
89
90 while (true) {
91 ssize_t len = read(arl->fd, buf.d, sizeof(buf.d));
92
93 if (len == -1) {
94 if (errno == EINTR)
95 continue;
96 break;
97 }
98 for (ptr = buf.d; ptr < buf.d + len; ptr += sizeof(*e) + e->len) {
99 e = (const struct inotify_event*) ptr;
100 if (e->wd == arl->wd_file && (e->mask & IN_CLOSE_WRITE)) {
101 reload = true;
102 } else if (e->wd == arl->wd_file && (e->mask & IN_DELETE_SELF)) {
103 rm_watch(arl->fd, &arl->wd_file);
104 } else if (e->wd == arl->wd_dir && (e->mask & (IN_CREATE | IN_MOVED_TO))) {
105 if (STREQ(e->name, arl->filename))
106 reload = true;
107 }
108 }
109 }
110 return reload;
111}