Krolyxon
Commit e438009

Branches

Refs →

nsxivmain.c

949 lines · 21.4 KB · C

1/* Copyright 2011-2020 Bert Muennich
2 * Copyright 2021-2023 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 if (tns.thumbs != NULL)
199 tns_unload(&tns, n);
200
201 if (n + 1 < filecnt) {
202 if (tns.thumbs != NULL) {
203 memmove(tns.thumbs + n, tns.thumbs + n + 1, (filecnt - n - 1) *
204 sizeof(*tns.thumbs));
205 memset(tns.thumbs + filecnt - 1, 0, sizeof(*tns.thumbs));
206 }
207 memmove(files + n, files + n + 1, (filecnt - n - 1) * sizeof(*files));
208 }
209 filecnt--;
210 if (fileidx > n || fileidx == filecnt)
211 fileidx--;
212 if (alternate > n || alternate == filecnt)
213 alternate--;
214 if (markidx > n || markidx == filecnt)
215 markidx--;
216}
217
218void set_timeout(timeout_f handler, int time, bool overwrite)
219{
220 unsigned int i;
221
222 for (i = 0; i < ARRLEN(timeouts); i++) {
223 if (timeouts[i].handler == handler) {
224 if (!timeouts[i].active || overwrite) {
225 gettimeofday(&timeouts[i].when, 0);
226 TV_ADD_MSEC(&timeouts[i].when, time);
227 timeouts[i].active = true;
228 }
229 return;
230 }
231 }
232}
233
234void reset_timeout(timeout_f handler)
235{
236 unsigned int i;
237
238 for (i = 0; i < ARRLEN(timeouts); i++) {
239 if (timeouts[i].handler == handler) {
240 timeouts[i].active = false;
241 return;
242 }
243 }
244}
245
246static bool check_timeouts(int *t)
247{
248 int i = 0, tdiff, tmin = -1;
249 struct timeval now;
250
251 while (i < (int)ARRLEN(timeouts)) {
252 if (timeouts[i].active) {
253 gettimeofday(&now, 0);
254 tdiff = TV_DIFF(&timeouts[i].when, &now);
255 if (tdiff <= 0) {
256 timeouts[i].active = false;
257 if (timeouts[i].handler != NULL)
258 timeouts[i].handler();
259 i = tmin = -1;
260 } else if (tmin < 0 || tdiff < tmin) {
261 tmin = tdiff;
262 }
263 }
264 i++;
265 }
266 if (tmin > 0 && t != NULL)
267 *t = tmin;
268 return tmin > 0;
269}
270
271static void kill_close(pid_t pid, int *fd)
272{
273 if (fd != NULL && *fd != -1) {
274 kill(pid, SIGTERM);
275 close(*fd);
276 *fd = -1;
277 }
278}
279
280static void close_title(void)
281{
282 kill_close(wintitle.pid, &wintitle.fd);
283}
284
285static void read_title(void)
286{
287 ssize_t n;
288 char buf[512];
289
290 if ((n = read(wintitle.fd, buf, sizeof(buf)-1)) > 0) {
291 buf[n] = '\0';
292 win_set_title(&win, buf, n);
293 }
294 close_title();
295}
296
297static void open_title(void)
298{
299 char *argv[8];
300 char w[12] = "", h[12] = "", z[12] = "", fidx[12], fcnt[12];
301
302 if (wintitle.f.err || !title_dirty)
303 return;
304
305 close_title();
306 if (mode == MODE_IMAGE) {
307 snprintf(w, ARRLEN(w), "%d", img.w);
308 snprintf(h, ARRLEN(h), "%d", img.h);
309 snprintf(z, ARRLEN(z), "%d", (int)(img.zoom * 100));
310 }
311 snprintf(fidx, ARRLEN(fidx), "%d", fileidx+1);
312 snprintf(fcnt, ARRLEN(fcnt), "%d", filecnt);
313 construct_argv(argv, ARRLEN(argv), wintitle.f.cmd, files[fileidx].path,
314 fidx, fcnt, w, h, z, NULL);
315 if ((wintitle.pid = spawn(&wintitle.fd, NULL, argv)) > 0)
316 fcntl(wintitle.fd, F_SETFL, O_NONBLOCK);
317 title_dirty = false;
318}
319
320void close_info(void)
321{
322 kill_close(info.pid, &info.fd);
323}
324
325void open_info(void)
326{
327 char *argv[6], w[12] = "", h[12] = "";
328 char *cmd = mode == MODE_IMAGE ? info.f.cmd : info.ft.cmd;
329 bool ferr = mode == MODE_IMAGE ? info.f.err : info.ft.err;
330
331 if (ferr || info.fd >= 0 || win.bar.h == 0)
332 return;
333 win.bar.l.buf[0] = '\0';
334 if (mode == MODE_IMAGE) {
335 snprintf(w, sizeof(w), "%d", img.w);
336 snprintf(h, sizeof(h), "%d", img.h);
337 }
338 construct_argv(argv, ARRLEN(argv), cmd, files[fileidx].name, w, h,
339 files[fileidx].path, NULL);
340 if ((info.pid = spawn(&info.fd, NULL, argv)) > 0)
341 fcntl(info.fd, F_SETFL, O_NONBLOCK);
342}
343
344static void read_info(void)
345{
346 ssize_t i, n;
347
348 if ((n = read(info.fd, win.bar.l.buf, win.bar.l.size - 1)) > 0) {
349 win.bar.l.buf[n] = '\0';
350 for (i = 0; i < n; ++i) {
351 if (win.bar.l.buf[i] == '\n')
352 win.bar.l.buf[i] = ' ';
353 }
354 win_draw(&win);
355 }
356 close_info();
357}
358
359void load_image(int new)
360{
361 bool prev = new < fileidx;
362 static int current;
363
364 if (new < 0 || new >= filecnt)
365 return;
366
367 if (win.xwin != None)
368 win_set_cursor(&win, CURSOR_WATCH);
369 reset_timeout(slideshow);
370
371 if (new != current)
372 alternate = current;
373
374 img_close(&img, false);
375 while (!img_load(&img, &files[new])) {
376 remove_file(new, false);
377 if (new >= filecnt)
378 new = filecnt - 1;
379 else if (new > 0 && prev)
380 new--;
381 }
382 files[new].flags &= ~FF_WARN;
383 fileidx = current = new;
384
385 close_info();
386 open_info();
387 arl_add(&arl, files[fileidx].path);
388 title_dirty = true;
389
390 if (img.multi.cnt > 0 && img.multi.animate)
391 set_timeout(animate, img.multi.frames[img.multi.sel].delay, true);
392 else
393 reset_timeout(animate);
394}
395
396bool mark_image(int n, bool on)
397{
398 markidx = n;
399 if (!!(files[n].flags & FF_MARK) != on) {
400 files[n].flags ^= FF_MARK;
401 markcnt += on ? 1 : -1;
402 if (mode == MODE_THUMB)
403 tns_mark(&tns, n, on);
404 return true;
405 }
406 return false;
407}
408
409static void bar_put(win_bar_t *bar, const char *fmt, ...)
410{
411 size_t len = bar->size - (bar->p - bar->buf), n;
412 va_list ap;
413
414 va_start(ap, fmt);
415 n = vsnprintf(bar->p, len, fmt, ap);
416 bar->p += MIN(len, n);
417 va_end(ap);
418}
419
420static void update_info(void)
421{
422 unsigned int i, fn, fw;
423 const char *mark;
424 win_bar_t *l = &win.bar.l, *r = &win.bar.r;
425
426 /* update bar contents */
427 if (win.bar.h == 0 || extprefix)
428 return;
429 for (fw = 0, i = filecnt; i > 0; fw++, i /= 10);
430 mark = files[fileidx].flags & FF_MARK ? "* " : "";
431 l->p = l->buf;
432 r->p = r->buf;
433 if (mode == MODE_THUMB) {
434 if (tns.loadnext < tns.end)
435 bar_put(l, "Loading... %0*d", fw, tns.loadnext + 1);
436 else if (tns.initnext < filecnt)
437 bar_put(l, "Caching... %0*d", fw, tns.initnext + 1);
438 else if (info.ft.err)
439 strncpy(l->buf, files[fileidx].name, l->size);
440 bar_put(r, "%s%0*d/%d", mark, fw, fileidx + 1, filecnt);
441 } else {
442 bar_put(r, "%s", mark);
443 if (img.ss.on) {
444 if (img.ss.delay % 10 != 0)
445 bar_put(r, "%2.1fs" BAR_SEP, (float)img.ss.delay / 10);
446 else
447 bar_put(r, "%ds" BAR_SEP, img.ss.delay / 10);
448 }
449 if (img.gamma)
450 bar_put(r, "G%+d" BAR_SEP, img.gamma);
451 if (img.brightness)
452 bar_put(r, "B%+d" BAR_SEP, img.brightness);
453 if (img.contrast)
454 bar_put(r, "C%+d" BAR_SEP, img.contrast);
455 bar_put(r, "%3d%%" BAR_SEP, (int) (img.zoom * 100.0));
456 if (img.multi.cnt > 0) {
457 for (fn = 0, i = img.multi.cnt; i > 0; fn++, i /= 10);
458 bar_put(r, "%0*d/%d" BAR_SEP, fn, img.multi.sel + 1, img.multi.cnt);
459 }
460 bar_put(r, "%0*d/%d", fw, fileidx + 1, filecnt);
461 if (info.f.err)
462 strncpy(l->buf, files[fileidx].name, l->size);
463 }
464}
465
466int nav_button(void)
467{
468 int x, y, nw;
469
470 if (NAV_WIDTH == 0)
471 return 1;
472
473 win_cursor_pos(&win, &x, &y);
474 nw = NAV_IS_REL ? win.w * NAV_WIDTH / 100 : NAV_WIDTH;
475 nw = MIN(nw, ((int)win.w + 1) / 2);
476
477 if (x < nw)
478 return 0;
479 else if (x < (int)win.w - nw)
480 return 1;
481 else
482 return 2;
483}
484
485void redraw(void)
486{
487 int t;
488
489 if (mode == MODE_IMAGE) {
490 img_render(&img);
491 if (img.ss.on) {
492 t = img.ss.delay * 100;
493 if (img.multi.cnt > 0 && img.multi.animate)
494 t = MAX(t, img.multi.length);
495 set_timeout(slideshow, t, false);
496 }
497 } else {
498 tns_render(&tns);
499 }
500 update_info();
501 open_title();
502 win_draw(&win);
503 reset_timeout(redraw);
504 reset_cursor();
505}
506
507void reset_cursor(void)
508{
509 int c;
510 unsigned int i;
511 cursor_t cursor = CURSOR_NONE;
512
513 if (mode == MODE_IMAGE) {
514 for (i = 0; i < ARRLEN(timeouts); i++) {
515 if (timeouts[i].handler == reset_cursor) {
516 if (timeouts[i].active) {
517 c = nav_button();
518 c = MAX(fileidx > 0 ? 0 : 1, c);
519 c = MIN(fileidx + 1 < filecnt ? 2 : 1, c);
520 cursor = imgcursor[c];
521 }
522 break;
523 }
524 }
525 } else {
526 if (tns.loadnext < tns.end || tns.initnext < filecnt)
527 cursor = CURSOR_WATCH;
528 else
529 cursor = CURSOR_ARROW;
530 }
531 win_set_cursor(&win, cursor);
532}
533
534void animate(void)
535{
536 if (img_frame_animate(&img)) {
537 set_timeout(animate, img.multi.frames[img.multi.sel].delay, true);
538 redraw();
539 }
540}
541
542void slideshow(void)
543{
544 load_image(fileidx + 1 < filecnt ? fileidx + 1 : 0);
545 redraw();
546}
547
548void clear_resize(void)
549{
550 resized = false;
551}
552
553static Bool is_input_ev(Display *dpy, XEvent *ev, XPointer arg)
554{
555 return ev->type == ButtonPress || ev->type == KeyPress;
556}
557
558void handle_key_handler(bool init)
559{
560 extprefix = init;
561 if (win.bar.h == 0)
562 return;
563 if (init) {
564 close_info();
565 snprintf(win.bar.l.buf, win.bar.l.size, "Getting key handler input "
566 "(%s to abort)...", XKeysymToString(KEYHANDLER_ABORT));
567 } else { /* abort */
568 open_info();
569 update_info();
570 }
571 win_draw(&win);
572}
573
574static bool run_key_handler(const char *key, unsigned int mask)
575{
576 FILE *pfs;
577 bool marked = mode == MODE_THUMB && markcnt > 0;
578 bool changed = false;
579 pid_t pid;
580 int writefd, f, i;
581 int fcnt = marked ? markcnt : 1;
582 char kstr[32];
583 struct stat *oldst, st;
584 XEvent dump;
585 char *argv[3];
586
587 if (keyhandler.f.err) {
588 if (!keyhandler.warned) {
589 error(0, keyhandler.f.err, "%s", keyhandler.f.cmd);
590 keyhandler.warned = true;
591 }
592 return false;
593 }
594 if (key == NULL)
595 return false;
596
597 close_info();
598 strncpy(win.bar.l.buf, "Running key handler...", win.bar.l.size);
599 win_draw(&win);
600 win_set_cursor(&win, CURSOR_WATCH);
601 setenv("NSXIV_USING_NULL", options->using_null ? "1" : "0", 1);
602
603 snprintf(kstr, sizeof(kstr), "%s%s%s%s",
604 mask & ControlMask ? "C-" : "",
605 mask & Mod1Mask ? "M-" : "",
606 mask & ShiftMask ? "S-" : "", key);
607 construct_argv(argv, ARRLEN(argv), keyhandler.f.cmd, kstr, NULL);
608 if ((pid = spawn(NULL, &writefd, argv)) < 0)
609 return false;
610 if ((pfs = fdopen(writefd, "w")) == NULL) {
611 error(0, errno, "open pipe");
612 close(writefd);
613 return false;
614 }
615
616 oldst = emalloc(fcnt * sizeof(*oldst));
617 for (f = i = 0; f < fcnt; i++) {
618 if ((marked && (files[i].flags & FF_MARK)) || (!marked && i == fileidx)) {
619 stat(files[i].path, &oldst[f]);
620 fprintf(pfs, "%s%c", files[i].name, options->using_null ? '\0' : '\n');
621 f++;
622 }
623 }
624 fclose(pfs);
625 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR);
626
627 for (f = i = 0; f < fcnt; i++) {
628 if ((marked && (files[i].flags & FF_MARK)) || (!marked && i == fileidx)) {
629 if (stat(files[i].path, &st) != 0 ||
630 memcmp(&oldst[f].st_mtime, &st.st_mtime, sizeof(st.st_mtime)) != 0)
631 {
632 if (tns.thumbs != NULL) {
633 tns_unload(&tns, i);
634 tns.loadnext = MIN(tns.loadnext, i);
635 }
636 changed = true;
637 }
638 f++;
639 }
640 }
641 /* drop user input events that occurred while running the key handler */
642 while (XCheckIfEvent(win.env.dpy, &dump, is_input_ev, NULL));
643
644 if (mode == MODE_IMAGE && changed) {
645 img_close(&img, true);
646 load_image(fileidx);
647 } else {
648 open_info();
649 }
650 free(oldst);
651 reset_cursor();
652 return true;
653}
654
655static bool process_bindings(const keymap_t *bindings, unsigned int len, KeySym ksym_or_button,
656 unsigned int state, unsigned int implicit_mod)
657{
658 unsigned int i;
659 bool dirty = false;
660
661 for (i = 0; i < len; i++) {
662 if (bindings[i].ksym_or_button == ksym_or_button &&
663 MODMASK(bindings[i].mask | implicit_mod) == MODMASK(state) &&
664 bindings[i].cmd.func != NULL &&
665 (bindings[i].cmd.mode == MODE_ALL || bindings[i].cmd.mode == mode))
666 {
667 if (bindings[i].cmd.func(bindings[i].arg))
668 dirty = true;
669 }
670 }
671 return dirty;
672}
673
674static void on_keypress(XKeyEvent *kev)
675{
676 unsigned int sh = 0;
677 KeySym ksym, shksym;
678 char dummy, key;
679 bool dirty = false;
680
681 XLookupString(kev, &key, 1, &ksym, NULL);
682
683 if (kev->state & ShiftMask) {
684 kev->state &= ~ShiftMask;
685 XLookupString(kev, &dummy, 1, &shksym, NULL);
686 kev->state |= ShiftMask;
687 if (ksym != shksym)
688 sh = ShiftMask;
689 }
690 if (IsModifierKey(ksym))
691 return;
692 if (extprefix && ksym == KEYHANDLER_ABORT && MODMASK(kev->state) == 0) {
693 handle_key_handler(false);
694 } else if (extprefix) {
695 if ((dirty = run_key_handler(XKeysymToString(ksym), kev->state & ~sh)))
696 extprefix = false;
697 else
698 handle_key_handler(false);
699 } else if (key >= '0' && key <= '9') {
700 /* number prefix for commands */
701 prefix = prefix * 10 + (int) (key - '0');
702 return;
703 } else {
704 dirty = process_bindings(keys, ARRLEN(keys), ksym, kev->state, sh);
705 }
706 if (dirty)
707 redraw();
708 prefix = 0;
709}
710
711static void on_buttonpress(const XButtonEvent *bev)
712{
713 bool dirty = false;
714
715 if (mode == MODE_IMAGE) {
716 set_timeout(reset_cursor, TO_CURSOR_HIDE, true);
717 reset_cursor();
718 dirty = process_bindings(buttons_img, ARRLEN(buttons_img), bev->button, bev->state, 0);
719 } else { /* thumbnail mode */
720 dirty = process_bindings(buttons_tns, ARRLEN(buttons_tns), bev->button, bev->state, 0);
721 }
722 if (dirty)
723 redraw();
724 prefix = 0;
725}
726
727static void run(void)
728{
729 enum { FD_X, FD_INFO, FD_TITLE, FD_ARL, FD_CNT };
730 struct pollfd pfd[FD_CNT];
731 int timeout = 0;
732 const struct timespec ten_ms = {0, 10000000};
733 bool discard, init_thumb, load_thumb, to_set;
734 XEvent ev, nextev;
735
736 xbutton_ev = &ev.xbutton;
737 while (true) {
738 to_set = check_timeouts(&timeout);
739 init_thumb = mode == MODE_THUMB && tns.initnext < filecnt;
740 load_thumb = mode == MODE_THUMB && tns.loadnext < tns.end;
741
742 if ((init_thumb || load_thumb || to_set || info.fd != -1 ||
743 arl.fd != -1) && XPending(win.env.dpy) == 0)
744 {
745 if (load_thumb) {
746 set_timeout(redraw, TO_REDRAW_THUMBS, false);
747 if (!tns_load(&tns, tns.loadnext, false, false)) {
748 remove_file(tns.loadnext, false);
749 tns.dirty = true;
750 }
751 if (tns.loadnext >= tns.end) {
752 open_info();
753 redraw();
754 }
755 } else if (init_thumb) {
756 set_timeout(redraw, TO_REDRAW_THUMBS, false);
757 if (!tns_load(&tns, tns.initnext, false, true))
758 remove_file(tns.initnext, false);
759 } else {
760 pfd[FD_X].fd = ConnectionNumber(win.env.dpy);
761 pfd[FD_INFO].fd = info.fd;
762 pfd[FD_TITLE].fd = wintitle.fd;
763 pfd[FD_ARL].fd = arl.fd;
764 pfd[FD_X].events = pfd[FD_INFO].events = pfd[FD_TITLE].events = pfd[FD_ARL].events = POLLIN;
765
766 if (poll(pfd, ARRLEN(pfd), to_set ? timeout : -1) < 0)
767 continue;
768 if (pfd[FD_INFO].revents & POLLIN)
769 read_info();
770 if (pfd[FD_TITLE].revents & POLLIN)
771 read_title();
772 if (pfd[FD_ARL].revents & POLLIN) {
773 if (arl_handle(&arl)) {
774 /* when too fast, imlib2 can't load the image */
775 nanosleep(&ten_ms, NULL);
776 img_close(&img, true);
777 load_image(fileidx);
778 redraw();
779 }
780 }
781 }
782 continue;
783 }
784
785 do {
786 XNextEvent(win.env.dpy, &ev);
787 discard = false;
788 if (XEventsQueued(win.env.dpy, QueuedAlready) > 0) {
789 XPeekEvent(win.env.dpy, &nextev);
790 switch (ev.type) {
791 case ConfigureNotify:
792 case MotionNotify:
793 discard = ev.type == nextev.type;
794 break;
795 case KeyPress:
796 discard = (nextev.type == KeyPress || nextev.type == KeyRelease)
797 && ev.xkey.keycode == nextev.xkey.keycode;
798 break;
799 }
800 }
801 } while (discard);
802
803 switch (ev.type) { /* handle events */
804 case ButtonPress:
805 on_buttonpress(&ev.xbutton);
806 break;
807 case ClientMessage:
808 if ((Atom) ev.xclient.data.l[0] == atoms[ATOM_WM_DELETE_WINDOW])
809 cg_quit(EXIT_SUCCESS);
810 break;
811 case DestroyNotify:
812 cg_quit(EXIT_FAILURE);
813 break;
814 case ConfigureNotify:
815 if (win_configure(&win, &ev.xconfigure)) {
816 if (mode == MODE_IMAGE) {
817 img.dirty = true;
818 img.checkpan = true;
819 } else {
820 tns.dirty = true;
821 }
822 if (!resized) {
823 redraw();
824 set_timeout(clear_resize, TO_REDRAW_RESIZE, false);
825 resized = true;
826 } else {
827 set_timeout(redraw, TO_REDRAW_RESIZE, false);
828 }
829 }
830 break;
831 case KeyPress:
832 on_keypress(&ev.xkey);
833 break;
834 case MotionNotify:
835 if (mode == MODE_IMAGE) {
836 set_timeout(reset_cursor, TO_CURSOR_HIDE, true);
837 reset_cursor();
838 }
839 break;
840 }
841 }
842}
843
844static void setup_signal(int sig, void (*handler)(int sig), int flags)
845{
846 struct sigaction sa;
847
848 sa.sa_handler = handler;
849 sigemptyset(&sa.sa_mask);
850 sa.sa_flags = flags;
851 if (sigaction(sig, &sa, NULL) < 0)
852 error(EXIT_FAILURE, errno, "signal %d", sig);
853}
854
855int main(int argc, char *argv[])
856{
857 int i;
858 size_t n;
859 const char *homedir, *dsuffix = "";
860
861 setup_signal(SIGCHLD, SIG_DFL, SA_RESTART|SA_NOCLDSTOP|SA_NOCLDWAIT);
862 setup_signal(SIGPIPE, SIG_IGN, 0);
863
864 setlocale(LC_COLLATE, "");
865
866 parse_options(argc, argv);
867
868 if (options->clean_cache) {
869 tns_init(&tns, NULL, NULL, NULL, NULL);
870 tns_clean_cache();
871 exit(EXIT_SUCCESS);
872 }
873
874 if (options->filecnt == 0 && !options->from_stdin) {
875 print_usage();
876 exit(EXIT_FAILURE);
877 }
878
879 if (options->recursive || options->from_stdin)
880 filecnt = 1024;
881 else
882 filecnt = options->filecnt;
883
884 files = ecalloc(filecnt, sizeof(*files));
885 fileidx = 0;
886
887 if (options->from_stdin) {
888 char *filename = NULL;
889 n = 0;
890 while (xgetline(&filename, &n))
891 add_entry(filename);
892 free(filename);
893 }
894
895 for (i = 0; i < options->filecnt; i++)
896 add_entry(options->filenames[i]);
897
898 if (fileidx == 0)
899 error(EXIT_FAILURE, 0, "No valid image file given, aborting");
900
901 filecnt = fileidx;
902 fileidx = options->startnum < filecnt ? options->startnum : 0;
903
904 win_init(&win);
905 img_init(&img, &win);
906 arl_init(&arl);
907
908 if ((homedir = getenv("XDG_CONFIG_HOME")) == NULL || homedir[0] == '\0') {
909 homedir = getenv("HOME");
910 dsuffix = "/.config";
911 }
912 if (homedir != NULL) {
913 extcmd_t *cmd[] = { &info.f, &info.ft, &keyhandler.f, &wintitle.f };
914 const char *name[] = { "image-info", "thumb-info", "key-handler", "win-title" };
915 const char *s = "/nsxiv/exec/";
916
917 for (i = 0; i < (int)ARRLEN(cmd); i++) {
918 n = strlen(homedir) + strlen(dsuffix) + strlen(s) + strlen(name[i]) + 1;
919 cmd[i]->cmd = emalloc(n);
920 snprintf(cmd[i]->cmd, n, "%s%s%s%s", homedir, dsuffix, s, name[i]);
921 if (access(cmd[i]->cmd, X_OK) != 0)
922 cmd[i]->err = errno;
923 }
924 } else {
925 error(0, 0, "Exec directory not found");
926 }
927 wintitle.fd = info.fd = -1;
928
929 if (options->thumb_mode) {
930 mode = MODE_THUMB;
931 tns_init(&tns, files, &filecnt, &fileidx, &win);
932 while (!tns_load(&tns, fileidx, false, false))
933 remove_file(fileidx, false);
934 } else {
935 mode = MODE_IMAGE;
936 tns.thumbs = NULL;
937 load_image(fileidx);
938 }
939 win_open(&win);
940 win_set_cursor(&win, CURSOR_WATCH);
941
942 atexit(cleanup);
943
944 set_timeout(redraw, 25, false);
945
946 run();
947
948 return 0;
949}