Krolyxon
Commit 34d4295

Branches

Refs →

nsxivmain.c

956 lines · 21.5 KB · C

1/* Copyright 2011-2020 Bert Muennich
2 * Copyright 2021-2022 nsxiv contributors
3 *
4 * This file is a part of nsxiv.
5 *
6 * nsxiv is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published
8 * by the Free Software Foundation; either version 2 of the License,
9 * or (at your option) any later version.
10 *
11 * nsxiv is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with nsxiv. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include "nsxiv.h"
21#define INCLUDE_MAPPINGS_CONFIG
22#include "commands.h"
23#include "config.h"
24
25#include <errno.h>
26#include <fcntl.h>
27#include <locale.h>
28#include <poll.h>
29#include <signal.h>
30#include <stdarg.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <sys/wait.h>
37#include <time.h>
38#include <unistd.h>
39
40#include <X11/XF86keysym.h>
41#include <X11/keysym.h>
42
43#define MODMASK(mask) ((mask) & USED_MODMASK)
44#define BAR_SEP " "
45
46#define TV_DIFF(t1,t2) (((t1)->tv_sec - (t2)->tv_sec ) * 1000 + \
47 ((t1)->tv_usec - (t2)->tv_usec) / 1000)
48#define TV_ADD_MSEC(tv,t) { \
49 (tv)->tv_sec += (t) / 1000; \
50 (tv)->tv_usec += (t) % 1000 * 1000; \
51}
52
53typedef struct {
54 int err;
55 char *cmd;
56} extcmd_t;
57
58/* these are not declared in nsxiv.h, as it causes too many -Wshadow warnings */
59arl_t arl;
60img_t img;
61tns_t tns;
62win_t win;
63
64appmode_t mode;
65fileinfo_t *files;
66int filecnt, fileidx;
67int alternate;
68int markcnt;
69int markidx;
70int prefix;
71bool title_dirty;
72const XButtonEvent *xbutton_ev;
73
74static bool extprefix;
75static bool resized = false;
76
77static struct {
78 extcmd_t f, ft;
79 int fd;
80 pid_t pid;
81} info, wintitle;
82
83static struct {
84 extcmd_t f;
85 bool warned;
86} keyhandler;
87
88static struct {
89 timeout_f handler;
90 struct timeval when;
91 bool active;
92} timeouts[] = {
93 { redraw },
94 { reset_cursor },
95 { slideshow },
96 { animate },
97 { clear_resize },
98};
99
100/*
101 * function implementations
102 */
103
104static void cleanup(void)
105{
106 img_close(&img, false);
107 arl_cleanup(&arl);
108 tns_free(&tns);
109 win_close(&win);
110}
111
112static bool xgetline(char **lineptr, size_t *n)
113{
114 ssize_t len = getdelim(lineptr, n, options->using_null ? '\0' : '\n', stdin);
115 if (!options->using_null && len > 0 && (*lineptr)[len-1] == '\n')
116 (*lineptr)[len-1] = '\0';
117 return len > 0;
118}
119
120static int fncmp(const void *a, const void *b)
121{
122 return strcoll(((fileinfo_t *)a)->name, ((fileinfo_t *)b)->name);
123}
124
125static void check_add_file(const char *filename, bool given)
126{
127 char *path;
128
129 if (*filename == '\0')
130 return;
131
132 if (access(filename, R_OK) < 0 ||
133 (path = realpath(filename, NULL)) == NULL)
134 {
135 if (given)
136 error(0, errno, "%s", filename);
137 return;
138 }
139
140 if (fileidx == filecnt) {
141 filecnt *= 2;
142 files = erealloc(files, filecnt * sizeof(*files));
143 memset(&files[filecnt/2], 0, filecnt/2 * sizeof(*files));
144 }
145
146 files[fileidx].name = estrdup(filename);
147 files[fileidx].path = path;
148 if (given)
149 files[fileidx].flags |= FF_WARN;
150 fileidx++;
151}
152
153static void add_entry(const char *entry_name)
154{
155 int start;
156 char *filename;
157 struct stat fstats;
158 r_dir_t dir;
159
160 if (stat(entry_name, &fstats) < 0) {
161 error(0, errno, "%s", entry_name);
162 return;
163 }
164 if (!S_ISDIR(fstats.st_mode)) {
165 check_add_file(entry_name, true);
166 } else {
167 if (r_opendir(&dir, entry_name, options->recursive) < 0) {
168 error(0, errno, "%s", entry_name);
169 return;
170 }
171 start = fileidx;
172 while ((filename = r_readdir(&dir, true)) != NULL) {
173 check_add_file(filename, false);
174 free(filename);
175 }
176 r_closedir(&dir);
177 if (fileidx - start > 1)
178 qsort(files + start, fileidx - start, sizeof(*files), fncmp);
179 }
180}
181
182void remove_file(int n, bool manual)
183{
184 if (n < 0 || n >= filecnt)
185 return;
186
187 if (filecnt == 1) {
188 if (!manual)
189 fprintf(stderr, "%s: no more files to display, aborting\n", progname);
190 exit(manual ? EXIT_SUCCESS : EXIT_FAILURE);
191 }
192 if (files[n].flags & FF_MARK)
193 markcnt--;
194
195 if (files[n].path != files[n].name)
196 free((void*) files[n].path);
197 free((void*) files[n].name);
198
199 if (n + 1 < filecnt) {
200 if (tns.thumbs != NULL) {
201 if (tns.thumbs[n].im != NULL) {
202 imlib_context_set_image(tns.thumbs[n].im);
203 imlib_free_image_and_decache();
204 }
205 memmove(tns.thumbs + n, tns.thumbs + n + 1, (filecnt - n - 1) *
206 sizeof(*tns.thumbs));
207 memset(tns.thumbs + filecnt - 1, 0, sizeof(*tns.thumbs));
208 }
209 memmove(files + n, files + n + 1, (filecnt - n - 1) * sizeof(*files));
210 }
211 filecnt--;
212 if (fileidx > n || fileidx == filecnt)
213 fileidx--;
214 if (alternate > n || alternate == filecnt)
215 alternate--;
216 if (markidx > n || markidx == filecnt)
217 markidx--;
218}
219
220void set_timeout(timeout_f handler, int time, bool overwrite)
221{
222 unsigned int i;
223
224 for (i = 0; i < ARRLEN(timeouts); i++) {
225 if (timeouts[i].handler == handler) {
226 if (!timeouts[i].active || overwrite) {
227 gettimeofday(&timeouts[i].when, 0);
228 TV_ADD_MSEC(&timeouts[i].when, time);
229 timeouts[i].active = true;
230 }
231 return;
232 }
233 }
234}
235
236void reset_timeout(timeout_f handler)
237{
238 unsigned int i;
239
240 for (i = 0; i < ARRLEN(timeouts); i++) {
241 if (timeouts[i].handler == handler) {
242 timeouts[i].active = false;
243 return;
244 }
245 }
246}
247
248static bool check_timeouts(int *t)
249{
250 int i = 0, tdiff, tmin = -1;
251 struct timeval now;
252
253 while (i < (int)ARRLEN(timeouts)) {
254 if (timeouts[i].active) {
255 gettimeofday(&now, 0);
256 tdiff = TV_DIFF(&timeouts[i].when, &now);
257 if (tdiff <= 0) {
258 timeouts[i].active = false;
259 if (timeouts[i].handler != NULL)
260 timeouts[i].handler();
261 i = tmin = -1;
262 } else if (tmin < 0 || tdiff < tmin) {
263 tmin = tdiff;
264 }
265 }
266 i++;
267 }
268 if (tmin > 0 && t != NULL)
269 *t = tmin;
270 return tmin > 0;
271}
272
273static void kill_close(pid_t pid, int *fd)
274{
275 if (fd != NULL && *fd != -1) {
276 kill(pid, SIGTERM);
277 close(*fd);
278 *fd = -1;
279 }
280}
281
282static void close_title(void)
283{
284 kill_close(wintitle.pid, &wintitle.fd);
285}
286
287static void read_title(void)
288{
289 ssize_t n;
290 char buf[512];
291
292 if ((n = read(wintitle.fd, buf, sizeof(buf)-1)) > 0) {
293 buf[n] = '\0';
294 win_set_title(&win, buf, n);
295 }
296 close_title();
297}
298
299static void open_title(void)
300{
301 char *argv[8];
302 char w[12] = "", h[12] = "", z[12] = "", fidx[12], fcnt[12];
303
304 if (wintitle.f.err || !title_dirty)
305 return;
306
307 close_title();
308 if (mode == MODE_IMAGE) {
309 snprintf(w, ARRLEN(w), "%d", img.w);
310 snprintf(h, ARRLEN(h), "%d", img.h);
311 snprintf(z, ARRLEN(z), "%d", (int)(img.zoom * 100));
312 }
313 snprintf(fidx, ARRLEN(fidx), "%d", fileidx+1);
314 snprintf(fcnt, ARRLEN(fcnt), "%d", filecnt);
315 construct_argv(argv, ARRLEN(argv), wintitle.f.cmd, files[fileidx].path,
316 fidx, fcnt, w, h, z, NULL);
317 if ((wintitle.pid = spawn(&wintitle.fd, NULL, argv)) > 0)
318 fcntl(wintitle.fd, F_SETFL, O_NONBLOCK);
319 title_dirty = false;
320}
321
322void close_info(void)
323{
324 kill_close(info.pid, &info.fd);
325}
326
327void open_info(void)
328{
329 char *argv[6], w[12] = "", h[12] = "";
330 char *cmd = mode == MODE_IMAGE ? info.f.cmd : info.ft.cmd;
331 bool ferr = mode == MODE_IMAGE ? info.f.err : info.ft.err;
332
333 if (ferr || info.fd >= 0 || win.bar.h == 0)
334 return;
335 win.bar.l.buf[0] = '\0';
336 if (mode == MODE_IMAGE) {
337 snprintf(w, sizeof(w), "%d", img.w);
338 snprintf(h, sizeof(h), "%d", img.h);
339 }
340 construct_argv(argv, ARRLEN(argv), cmd, files[fileidx].name, w, h,
341 files[fileidx].path, NULL);
342 if ((info.pid = spawn(&info.fd, NULL, argv)) > 0)
343 fcntl(info.fd, F_SETFL, O_NONBLOCK);
344}
345
346static void read_info(void)
347{
348 ssize_t i, n;
349
350 if ((n = read(info.fd, win.bar.l.buf, win.bar.l.size - 1)) > 0) {
351 win.bar.l.buf[n] = '\0';
352 for (i = 0; i < n; ++i) {
353 if (win.bar.l.buf[i] == '\n')
354 win.bar.l.buf[i] = ' ';
355 }
356 win_draw(&win);
357 }
358 close_info();
359}
360
361void load_image(int new)
362{
363 bool prev = new < fileidx;
364 static int current;
365
366 if (new < 0 || new >= filecnt)
367 return;
368
369 if (win.xwin != None)
370 win_set_cursor(&win, CURSOR_WATCH);
371 reset_timeout(slideshow);
372
373 if (new != current)
374 alternate = current;
375
376 img_close(&img, false);
377 while (!img_load(&img, &files[new])) {
378 remove_file(new, false);
379 if (new >= filecnt)
380 new = filecnt - 1;
381 else if (new > 0 && prev)
382 new--;
383 }
384 files[new].flags &= ~FF_WARN;
385 fileidx = current = new;
386
387 close_info();
388 open_info();
389 arl_add(&arl, files[fileidx].path);
390 title_dirty = true;
391
392 if (img.multi.cnt > 0 && img.multi.animate)
393 set_timeout(animate, img.multi.frames[img.multi.sel].delay, true);
394 else
395 reset_timeout(animate);
396}
397
398bool mark_image(int n, bool on)
399{
400 markidx = n;
401 if (!!(files[n].flags & FF_MARK) != on) {
402 files[n].flags ^= FF_MARK;
403 markcnt += on ? 1 : -1;
404 if (mode == MODE_THUMB)
405 tns_mark(&tns, n, on);
406 return true;
407 }
408 return false;
409}
410
411static void bar_put(win_bar_t *bar, const char *fmt, ...)
412{
413 size_t len = bar->size - (bar->p - bar->buf), n;
414 va_list ap;
415
416 va_start(ap, fmt);
417 n = vsnprintf(bar->p, len, fmt, ap);
418 bar->p += MIN(len, n);
419 va_end(ap);
420}
421
422static void update_info(void)
423{
424 unsigned int i, fn, fw;
425 const char *mark;
426 win_bar_t *l = &win.bar.l, *r = &win.bar.r;
427
428 /* update bar contents */
429 if (win.bar.h == 0 || extprefix)
430 return;
431 for (fw = 0, i = filecnt; i > 0; fw++, i /= 10);
432 mark = files[fileidx].flags & FF_MARK ? "* " : "";
433 l->p = l->buf;
434 r->p = r->buf;
435 if (mode == MODE_THUMB) {
436 if (tns.loadnext < tns.end)
437 bar_put(l, "Loading... %0*d", fw, tns.loadnext + 1);
438 else if (tns.initnext < filecnt)
439 bar_put(l, "Caching... %0*d", fw, tns.initnext + 1);
440 else if (info.ft.err)
441 strncpy(l->buf, files[fileidx].name, l->size);
442 bar_put(r, "%s%0*d/%d", mark, fw, fileidx + 1, filecnt);
443 } else {
444 bar_put(r, "%s", mark);
445 if (img.ss.on) {
446 if (img.ss.delay % 10 != 0)
447 bar_put(r, "%2.1fs" BAR_SEP, (float)img.ss.delay / 10);
448 else
449 bar_put(r, "%ds" BAR_SEP, img.ss.delay / 10);
450 }
451 if (img.gamma)
452 bar_put(r, "G%+d" BAR_SEP, img.gamma);
453 if (img.brightness)
454 bar_put(r, "B%+d" BAR_SEP, img.brightness);
455 if (img.contrast)
456 bar_put(r, "C%+d" BAR_SEP, img.contrast);
457 bar_put(r, "%3d%%" BAR_SEP, (int) (img.zoom * 100.0));
458 if (img.multi.cnt > 0) {
459 for (fn = 0, i = img.multi.cnt; i > 0; fn++, i /= 10);
460 bar_put(r, "%0*d/%d" BAR_SEP, fn, img.multi.sel + 1, img.multi.cnt);
461 }
462 bar_put(r, "%0*d/%d", fw, fileidx + 1, filecnt);
463 if (info.f.err)
464 strncpy(l->buf, files[fileidx].name, l->size);
465 }
466}
467
468int nav_button(void)
469{
470 int x, y, nw;
471
472 if (NAV_WIDTH == 0)
473 return 1;
474
475 win_cursor_pos(&win, &x, &y);
476 nw = NAV_IS_REL ? win.w * NAV_WIDTH / 100 : NAV_WIDTH;
477 nw = MIN(nw, ((int)win.w + 1) / 2);
478
479 if (x < nw)
480 return 0;
481 else if (x < (int)win.w - nw)
482 return 1;
483 else
484 return 2;
485}
486
487void redraw(void)
488{
489 int t;
490
491 if (mode == MODE_IMAGE) {
492 img_render(&img);
493 if (img.ss.on) {
494 t = img.ss.delay * 100;
495 if (img.multi.cnt > 0 && img.multi.animate)
496 t = MAX(t, img.multi.length);
497 set_timeout(slideshow, t, false);
498 }
499 } else {
500 tns_render(&tns);
501 }
502 update_info();
503 open_title();
504 win_draw(&win);
505 reset_timeout(redraw);
506 reset_cursor();
507}
508
509void reset_cursor(void)
510{
511 int c;
512 unsigned int i;
513 cursor_t cursor = CURSOR_NONE;
514
515 if (mode == MODE_IMAGE) {
516 for (i = 0; i < ARRLEN(timeouts); i++) {
517 if (timeouts[i].handler == reset_cursor) {
518 if (timeouts[i].active) {
519 c = nav_button();
520 c = MAX(fileidx > 0 ? 0 : 1, c);
521 c = MIN(fileidx + 1 < filecnt ? 2 : 1, c);
522 cursor = imgcursor[c];
523 }
524 break;
525 }
526 }
527 } else {
528 if (tns.loadnext < tns.end || tns.initnext < filecnt)
529 cursor = CURSOR_WATCH;
530 else
531 cursor = CURSOR_ARROW;
532 }
533 win_set_cursor(&win, cursor);
534}
535
536void animate(void)
537{
538 if (img_frame_animate(&img)) {
539 set_timeout(animate, img.multi.frames[img.multi.sel].delay, true);
540 redraw();
541 }
542}
543
544void slideshow(void)
545{
546 load_image(fileidx + 1 < filecnt ? fileidx + 1 : 0);
547 redraw();
548}
549
550void clear_resize(void)
551{
552 resized = false;
553}
554
555static Bool is_input_ev(Display *dpy, XEvent *ev, XPointer arg)
556{
557 return ev->type == ButtonPress || ev->type == KeyPress;
558}
559
560void handle_key_handler(bool init)
561{
562 extprefix = init;
563 if (win.bar.h == 0)
564 return;
565 if (init) {
566 close_info();
567 snprintf(win.bar.l.buf, win.bar.l.size, "Getting key handler input "
568 "(%s to abort)...", XKeysymToString(KEYHANDLER_ABORT));
569 } else { /* abort */
570 open_info();
571 update_info();
572 }
573 win_draw(&win);
574}
575
576static bool run_key_handler(const char *key, unsigned int mask)
577{
578 FILE *pfs;
579 bool marked = mode == MODE_THUMB && markcnt > 0;
580 bool changed = false;
581 pid_t pid;
582 int writefd, f, i;
583 int fcnt = marked ? markcnt : 1;
584 char kstr[32];
585 struct stat *oldst, st;
586 XEvent dump;
587 char *argv[3];
588
589 if (keyhandler.f.err) {
590 if (!keyhandler.warned) {
591 error(0, keyhandler.f.err, "%s", keyhandler.f.cmd);
592 keyhandler.warned = true;
593 }
594 return false;
595 }
596 if (key == NULL)
597 return false;
598
599 close_info();
600 strncpy(win.bar.l.buf, "Running key handler...", win.bar.l.size);
601 win_draw(&win);
602 win_set_cursor(&win, CURSOR_WATCH);
603 setenv("NSXIV_USING_NULL", options->using_null ? "1" : "0", 1);
604
605 snprintf(kstr, sizeof(kstr), "%s%s%s%s",
606 mask & ControlMask ? "C-" : "",
607 mask & Mod1Mask ? "M-" : "",
608 mask & ShiftMask ? "S-" : "", key);
609 construct_argv(argv, ARRLEN(argv), keyhandler.f.cmd, kstr, NULL);
610 if ((pid = spawn(NULL, &writefd, argv)) < 0)
611 return false;
612 if ((pfs = fdopen(writefd, "w")) == NULL) {
613 error(0, errno, "open pipe");
614 close(writefd);
615 return false;
616 }
617
618 oldst = emalloc(fcnt * sizeof(*oldst));
619 for (f = i = 0; f < fcnt; i++) {
620 if ((marked && (files[i].flags & FF_MARK)) || (!marked && i == fileidx)) {
621 stat(files[i].path, &oldst[f]);
622 fprintf(pfs, "%s%c", files[i].name, options->using_null ? '\0' : '\n');
623 f++;
624 }
625 }
626 fclose(pfs);
627 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR);
628
629 for (f = i = 0; f < fcnt; i++) {
630 if ((marked && (files[i].flags & FF_MARK)) || (!marked && i == fileidx)) {
631 if (stat(files[i].path, &st) != 0 ||
632 memcmp(&oldst[f].st_mtime, &st.st_mtime, sizeof(st.st_mtime)) != 0)
633 {
634 if (tns.thumbs != NULL) {
635 tns_unload(&tns, i);
636 tns.loadnext = MIN(tns.loadnext, i);
637 }
638 changed = true;
639 }
640 f++;
641 }
642 }
643 /* drop user input events that occurred while running the key handler */
644 while (XCheckIfEvent(win.env.dpy, &dump, is_input_ev, NULL));
645
646 if (mode == MODE_IMAGE && changed) {
647 img_close(&img, true);
648 load_image(fileidx);
649 } else {
650 open_info();
651 }
652 free(oldst);
653 reset_cursor();
654 return true;
655}
656
657static bool process_bindings(const keymap_t *bindings, unsigned int len, KeySym ksym_or_button,
658 unsigned int state, unsigned int implicit_mod)
659{
660 unsigned int i;
661 bool dirty = false;
662
663 for (i = 0; i < len; i++) {
664 if (bindings[i].ksym_or_button == ksym_or_button &&
665 MODMASK(bindings[i].mask | implicit_mod) == MODMASK(state) &&
666 bindings[i].cmd.func != NULL &&
667 (bindings[i].cmd.mode == MODE_ALL || bindings[i].cmd.mode == mode))
668 {
669 if (bindings[i].cmd.func(bindings[i].arg))
670 dirty = true;
671 }
672 }
673 return dirty;
674}
675
676static void on_keypress(XKeyEvent *kev)
677{
678 unsigned int sh = 0;
679 KeySym ksym, shksym;
680 char dummy, key;
681 bool dirty = false;
682
683 XLookupString(kev, &key, 1, &ksym, NULL);
684
685 if (kev->state & ShiftMask) {
686 kev->state &= ~ShiftMask;
687 XLookupString(kev, &dummy, 1, &shksym, NULL);
688 kev->state |= ShiftMask;
689 if (ksym != shksym)
690 sh = ShiftMask;
691 }
692 if (IsModifierKey(ksym))
693 return;
694 if (extprefix && ksym == KEYHANDLER_ABORT && MODMASK(kev->state) == 0) {
695 handle_key_handler(false);
696 } else if (extprefix) {
697 if ((dirty = run_key_handler(XKeysymToString(ksym), kev->state & ~sh)))
698 extprefix = false;
699 else
700 handle_key_handler(false);
701 } else if (key >= '0' && key <= '9') {
702 /* number prefix for commands */
703 prefix = prefix * 10 + (int) (key - '0');
704 return;
705 } else {
706 dirty = process_bindings(keys, ARRLEN(keys), ksym, kev->state, sh);
707 }
708 if (dirty)
709 redraw();
710 prefix = 0;
711}
712
713static void on_buttonpress(const XButtonEvent *bev)
714{
715 bool dirty = false;
716
717 if (mode == MODE_IMAGE) {
718 set_timeout(reset_cursor, TO_CURSOR_HIDE, true);
719 reset_cursor();
720 dirty = process_bindings(buttons_img, ARRLEN(buttons_img), bev->button, bev->state, 0);
721 } else { /* thumbnail mode */
722 dirty = process_bindings(buttons_tns, ARRLEN(buttons_tns), bev->button, bev->state, 0);
723 }
724 if (dirty)
725 redraw();
726 prefix = 0;
727}
728
729static void run(void)
730{
731 enum { FD_X, FD_INFO, FD_TITLE, FD_ARL, FD_CNT };
732 struct pollfd pfd[FD_CNT];
733 int timeout = 0;
734 const struct timespec ten_ms = {0, 10000000};
735 bool discard, init_thumb, load_thumb, to_set;
736 XEvent ev, nextev;
737
738 xbutton_ev = &ev.xbutton;
739 while (true) {
740 to_set = check_timeouts(&timeout);
741 init_thumb = mode == MODE_THUMB && tns.initnext < filecnt;
742 load_thumb = mode == MODE_THUMB && tns.loadnext < tns.end;
743
744 if ((init_thumb || load_thumb || to_set || info.fd != -1 ||
745 arl.fd != -1) && XPending(win.env.dpy) == 0)
746 {
747 if (load_thumb) {
748 set_timeout(redraw, TO_REDRAW_THUMBS, false);
749 if (!tns_load(&tns, tns.loadnext, false, false)) {
750 remove_file(tns.loadnext, false);
751 tns.dirty = true;
752 }
753 if (tns.loadnext >= tns.end) {
754 open_info();
755 redraw();
756 }
757 } else if (init_thumb) {
758 set_timeout(redraw, TO_REDRAW_THUMBS, false);
759 if (!tns_load(&tns, tns.initnext, false, true))
760 remove_file(tns.initnext, false);
761 } else {
762 pfd[FD_X].fd = ConnectionNumber(win.env.dpy);
763 pfd[FD_INFO].fd = info.fd;
764 pfd[FD_TITLE].fd = wintitle.fd;
765 pfd[FD_ARL].fd = arl.fd;
766 pfd[FD_X].events = pfd[FD_INFO].events = pfd[FD_TITLE].events = pfd[FD_ARL].events = POLLIN;
767
768 if (poll(pfd, ARRLEN(pfd), to_set ? timeout : -1) < 0)
769 continue;
770 if (pfd[FD_INFO].revents & POLLIN)
771 read_info();
772 if (pfd[FD_TITLE].revents & POLLIN)
773 read_title();
774 if (pfd[FD_ARL].revents & POLLIN) {
775 if (arl_handle(&arl)) {
776 /* when too fast, imlib2 can't load the image */
777 nanosleep(&ten_ms, NULL);
778 img_close(&img, true);
779 load_image(fileidx);
780 redraw();
781 }
782 }
783 }
784 continue;
785 }
786
787 do {
788 XNextEvent(win.env.dpy, &ev);
789 discard = false;
790 if (XEventsQueued(win.env.dpy, QueuedAlready) > 0) {
791 XPeekEvent(win.env.dpy, &nextev);
792 switch (ev.type) {
793 case ConfigureNotify:
794 case MotionNotify:
795 discard = ev.type == nextev.type;
796 break;
797 case KeyPress:
798 discard = (nextev.type == KeyPress || nextev.type == KeyRelease)
799 && ev.xkey.keycode == nextev.xkey.keycode;
800 break;
801 }
802 }
803 } while (discard);
804
805 switch (ev.type) { /* handle events */
806 case ButtonPress:
807 on_buttonpress(&ev.xbutton);
808 break;
809 case ClientMessage:
810 if ((Atom) ev.xclient.data.l[0] == atoms[ATOM_WM_DELETE_WINDOW])
811 cg_quit(EXIT_SUCCESS);
812 break;
813 case DestroyNotify:
814 cg_quit(EXIT_FAILURE);
815 break;
816 case ConfigureNotify:
817 if (win_configure(&win, &ev.xconfigure)) {
818 if (mode == MODE_IMAGE) {
819 img.dirty = true;
820 img.checkpan = true;
821 } else {
822 tns.dirty = true;
823 }
824 if (!resized) {
825 redraw();
826 set_timeout(clear_resize, TO_REDRAW_RESIZE, false);
827 resized = true;
828 } else {
829 set_timeout(redraw, TO_REDRAW_RESIZE, false);
830 }
831 }
832 break;
833 case KeyPress:
834 on_keypress(&ev.xkey);
835 break;
836 case MotionNotify:
837 if (mode == MODE_IMAGE) {
838 set_timeout(reset_cursor, TO_CURSOR_HIDE, true);
839 reset_cursor();
840 }
841 break;
842 }
843 }
844}
845
846static void sigchld(int sig)
847{
848 while (waitpid(-1, NULL, WNOHANG) > 0);
849}
850
851static void setup_signal(int sig, void (*handler)(int sig))
852{
853 struct sigaction sa;
854
855 sa.sa_handler = handler;
856 sigemptyset(&sa.sa_mask);
857 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
858 if (sigaction(sig, &sa, 0) == -1)
859 error(EXIT_FAILURE, errno, "signal %d", sig);
860}
861
862int main(int argc, char *argv[])
863{
864 int i;
865 size_t n;
866 const char *homedir, *dsuffix = "";
867
868 setup_signal(SIGCHLD, sigchld);
869 setup_signal(SIGPIPE, SIG_IGN);
870
871 setlocale(LC_COLLATE, "");
872
873 parse_options(argc, argv);
874
875 if (options->clean_cache) {
876 tns_init(&tns, NULL, NULL, NULL, NULL);
877 tns_clean_cache();
878 exit(EXIT_SUCCESS);
879 }
880
881 if (options->filecnt == 0 && !options->from_stdin) {
882 print_usage();
883 exit(EXIT_FAILURE);
884 }
885
886 if (options->recursive || options->from_stdin)
887 filecnt = 1024;
888 else
889 filecnt = options->filecnt;
890
891 files = ecalloc(filecnt, sizeof(*files));
892 fileidx = 0;
893
894 if (options->from_stdin) {
895 char *filename = NULL;
896 n = 0;
897 while (xgetline(&filename, &n))
898 add_entry(filename);
899 free(filename);
900 }
901
902 for (i = 0; i < options->filecnt; i++)
903 add_entry(options->filenames[i]);
904
905 if (fileidx == 0)
906 error(EXIT_FAILURE, 0, "No valid image file given, aborting");
907
908 filecnt = fileidx;
909 fileidx = options->startnum < filecnt ? options->startnum : 0;
910
911 win_init(&win);
912 img_init(&img, &win);
913 arl_init(&arl);
914
915 if ((homedir = getenv("XDG_CONFIG_HOME")) == NULL || homedir[0] == '\0') {
916 homedir = getenv("HOME");
917 dsuffix = "/.config";
918 }
919 if (homedir != NULL) {
920 extcmd_t *cmd[] = { &info.f, &info.ft, &keyhandler.f, &wintitle.f };
921 const char *name[] = { "image-info", "thumb-info", "key-handler", "win-title" };
922 const char *s = "/nsxiv/exec/";
923
924 for (i = 0; i < (int)ARRLEN(cmd); i++) {
925 n = strlen(homedir) + strlen(dsuffix) + strlen(s) + strlen(name[i]) + 1;
926 cmd[i]->cmd = emalloc(n);
927 snprintf(cmd[i]->cmd, n, "%s%s%s%s", homedir, dsuffix, s, name[i]);
928 if (access(cmd[i]->cmd, X_OK) != 0)
929 cmd[i]->err = errno;
930 }
931 } else {
932 error(0, 0, "Exec directory not found");
933 }
934 wintitle.fd = info.fd = -1;
935
936 if (options->thumb_mode) {
937 mode = MODE_THUMB;
938 tns_init(&tns, files, &filecnt, &fileidx, &win);
939 while (!tns_load(&tns, fileidx, false, false))
940 remove_file(fileidx, false);
941 } else {
942 mode = MODE_IMAGE;
943 tns.thumbs = NULL;
944 load_image(fileidx);
945 }
946 win_open(&win);
947 win_set_cursor(&win, CURSOR_WATCH);
948
949 atexit(cleanup);
950
951 set_timeout(redraw, 25, false);
952
953 run();
954
955 return 0;
956}