Krolyxon
Commit 2434e83

Branches

Refs →

nsxivmain.c

950 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) (USED_MODMASK & (mask))
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) do { \
49 (tv)->tv_sec += (t) / 1000; \
50 (tv)->tv_usec += (t) % 1000 * 1000; \
51} while (0)
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,
204 (filecnt - n - 1) * 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 -= 1;
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,
566 "Getting key handler input (%s to abort)...",
567 XKeysymToString(KEYHANDLER_ABORT));
568 } else { /* abort */
569 open_info();
570 update_info();
571 }
572 win_draw(&win);
573}
574
575static bool run_key_handler(const char *key, unsigned int mask)
576{
577 FILE *pfs;
578 bool marked = mode == MODE_THUMB && markcnt > 0;
579 bool changed = false;
580 pid_t pid;
581 int writefd, f, i;
582 int fcnt = marked ? markcnt : 1;
583 char kstr[32];
584 struct stat *oldst, st;
585 XEvent dump;
586 char *argv[3];
587
588 if (keyhandler.f.err) {
589 if (!keyhandler.warned) {
590 error(0, keyhandler.f.err, "%s", keyhandler.f.cmd);
591 keyhandler.warned = true;
592 }
593 return false;
594 }
595 if (key == NULL)
596 return false;
597
598 close_info();
599 strncpy(win.bar.l.buf, "Running key handler...", win.bar.l.size);
600 win_draw(&win);
601 win_set_cursor(&win, CURSOR_WATCH);
602 setenv("NSXIV_USING_NULL", options->using_null ? "1" : "0", 1);
603
604 snprintf(kstr, sizeof(kstr), "%s%s%s%s",
605 mask & ControlMask ? "C-" : "",
606 mask & Mod1Mask ? "M-" : "",
607 mask & ShiftMask ? "S-" : "", key);
608 construct_argv(argv, ARRLEN(argv), keyhandler.f.cmd, kstr, NULL);
609 if ((pid = spawn(NULL, &writefd, argv)) < 0)
610 return false;
611 if ((pfs = fdopen(writefd, "w")) == NULL) {
612 error(0, errno, "open pipe");
613 close(writefd);
614 return false;
615 }
616
617 oldst = emalloc(fcnt * sizeof(*oldst));
618 for (f = i = 0; f < fcnt; i++) {
619 if ((marked && (files[i].flags & FF_MARK)) || (!marked && i == fileidx)) {
620 stat(files[i].path, &oldst[f]);
621 fprintf(pfs, "%s%c", files[i].name, options->using_null ? '\0' : '\n');
622 f++;
623 }
624 }
625 fclose(pfs);
626 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR);
627
628 for (f = i = 0; f < fcnt; i++) {
629 if ((marked && (files[i].flags & FF_MARK)) || (!marked && i == fileidx)) {
630 if (stat(files[i].path, &st) != 0 ||
631 memcmp(&oldst[f].st_mtime, &st.st_mtime, sizeof(st.st_mtime)) != 0)
632 {
633 if (tns.thumbs != NULL) {
634 tns_unload(&tns, i);
635 tns.loadnext = MIN(tns.loadnext, i);
636 }
637 changed = true;
638 }
639 f++;
640 }
641 }
642 /* drop user input events that occurred while running the key handler */
643 while (XCheckIfEvent(win.env.dpy, &dump, is_input_ev, NULL));
644
645 if (mode == MODE_IMAGE && changed) {
646 img_close(&img, true);
647 load_image(fileidx);
648 } else {
649 open_info();
650 }
651 free(oldst);
652 reset_cursor();
653 return true;
654}
655
656static bool process_bindings(const keymap_t *bindings, unsigned int len, KeySym ksym_or_button,
657 unsigned int state, unsigned int implicit_mod)
658{
659 unsigned int i;
660 bool dirty = false;
661
662 for (i = 0; i < len; i++) {
663 if (bindings[i].ksym_or_button == ksym_or_button &&
664 MODMASK(bindings[i].mask | implicit_mod) == MODMASK(state) &&
665 bindings[i].cmd.func != NULL &&
666 (bindings[i].cmd.mode == MODE_ALL || bindings[i].cmd.mode == mode))
667 {
668 if (bindings[i].cmd.func(bindings[i].arg))
669 dirty = true;
670 }
671 }
672 return dirty;
673}
674
675static void on_keypress(XKeyEvent *kev)
676{
677 unsigned int sh = 0;
678 KeySym ksym, shksym;
679 char dummy, key;
680 bool dirty = false;
681
682 XLookupString(kev, &key, 1, &ksym, NULL);
683
684 if (kev->state & ShiftMask) {
685 kev->state &= ~ShiftMask;
686 XLookupString(kev, &dummy, 1, &shksym, NULL);
687 kev->state |= ShiftMask;
688 if (ksym != shksym)
689 sh = ShiftMask;
690 }
691 if (IsModifierKey(ksym))
692 return;
693 if (extprefix && ksym == KEYHANDLER_ABORT && MODMASK(kev->state) == 0) {
694 handle_key_handler(false);
695 } else if (extprefix) {
696 if ((dirty = run_key_handler(XKeysymToString(ksym), kev->state & ~sh)))
697 extprefix = false;
698 else
699 handle_key_handler(false);
700 } else if (key >= '0' && key <= '9') {
701 /* number prefix for commands */
702 prefix = prefix * 10 + (int) (key - '0');
703 return;
704 } else {
705 dirty = process_bindings(keys, ARRLEN(keys), ksym, kev->state, sh);
706 }
707 if (dirty)
708 redraw();
709 prefix = 0;
710}
711
712static void on_buttonpress(const XButtonEvent *bev)
713{
714 bool dirty = false;
715
716 if (mode == MODE_IMAGE) {
717 set_timeout(reset_cursor, TO_CURSOR_HIDE, true);
718 reset_cursor();
719 dirty = process_bindings(buttons_img, ARRLEN(buttons_img), bev->button, bev->state, 0);
720 } else { /* thumbnail mode */
721 dirty = process_bindings(buttons_tns, ARRLEN(buttons_tns), bev->button, bev->state, 0);
722 }
723 if (dirty)
724 redraw();
725 prefix = 0;
726}
727
728static void run(void)
729{
730 enum { FD_X, FD_INFO, FD_TITLE, FD_ARL, FD_CNT };
731 struct pollfd pfd[FD_CNT];
732 int timeout = 0;
733 const struct timespec ten_ms = {0, 10000000};
734 bool discard, init_thumb, load_thumb, to_set;
735 XEvent ev, nextev;
736
737 xbutton_ev = &ev.xbutton;
738 while (true) {
739 to_set = check_timeouts(&timeout);
740 init_thumb = mode == MODE_THUMB && tns.initnext < filecnt;
741 load_thumb = mode == MODE_THUMB && tns.loadnext < tns.end;
742
743 if ((init_thumb || load_thumb || to_set || info.fd != -1 || arl.fd != -1) &&
744 XPending(win.env.dpy) == 0)
745 {
746 if (load_thumb) {
747 set_timeout(redraw, TO_REDRAW_THUMBS, false);
748 if (!tns_load(&tns, tns.loadnext, false, false)) {
749 remove_file(tns.loadnext, false);
750 tns.dirty = true;
751 }
752 if (tns.loadnext >= tns.end) {
753 open_info();
754 redraw();
755 }
756 } else if (init_thumb) {
757 set_timeout(redraw, TO_REDRAW_THUMBS, false);
758 if (!tns_load(&tns, tns.initnext, false, true))
759 remove_file(tns.initnext, false);
760 } else {
761 pfd[FD_X].fd = ConnectionNumber(win.env.dpy);
762 pfd[FD_INFO].fd = info.fd;
763 pfd[FD_TITLE].fd = wintitle.fd;
764 pfd[FD_ARL].fd = arl.fd;
765 pfd[FD_X].events = pfd[FD_INFO].events = pfd[FD_TITLE].events = pfd[FD_ARL].events = POLLIN;
766
767 if (poll(pfd, ARRLEN(pfd), to_set ? timeout : -1) < 0)
768 continue;
769 if (pfd[FD_INFO].revents & POLLIN)
770 read_info();
771 if (pfd[FD_TITLE].revents & POLLIN)
772 read_title();
773 if (pfd[FD_ARL].revents & POLLIN) {
774 if (arl_handle(&arl)) {
775 /* when too fast, imlib2 can't load the image */
776 nanosleep(&ten_ms, NULL);
777 img_close(&img, true);
778 load_image(fileidx);
779 redraw();
780 }
781 }
782 }
783 continue;
784 }
785
786 do {
787 XNextEvent(win.env.dpy, &ev);
788 discard = false;
789 if (XEventsQueued(win.env.dpy, QueuedAlready) > 0) {
790 XPeekEvent(win.env.dpy, &nextev);
791 switch (ev.type) {
792 case ConfigureNotify:
793 case MotionNotify:
794 discard = ev.type == nextev.type;
795 break;
796 case KeyPress:
797 discard = (nextev.type == KeyPress || nextev.type == KeyRelease) &&
798 ev.xkey.keycode == nextev.xkey.keycode;
799 break;
800 }
801 }
802 } while (discard);
803
804 switch (ev.type) { /* handle events */
805 case ButtonPress:
806 on_buttonpress(&ev.xbutton);
807 break;
808 case ClientMessage:
809 if ((Atom) ev.xclient.data.l[0] == atoms[ATOM_WM_DELETE_WINDOW])
810 cg_quit(EXIT_SUCCESS);
811 break;
812 case DestroyNotify:
813 cg_quit(EXIT_FAILURE);
814 break;
815 case ConfigureNotify:
816 if (win_configure(&win, &ev.xconfigure)) {
817 if (mode == MODE_IMAGE) {
818 img.dirty = true;
819 img.checkpan = true;
820 } else {
821 tns.dirty = true;
822 }
823 if (!resized) {
824 redraw();
825 set_timeout(clear_resize, TO_REDRAW_RESIZE, false);
826 resized = true;
827 } else {
828 set_timeout(redraw, TO_REDRAW_RESIZE, false);
829 }
830 }
831 break;
832 case KeyPress:
833 on_keypress(&ev.xkey);
834 break;
835 case MotionNotify:
836 if (mode == MODE_IMAGE) {
837 set_timeout(reset_cursor, TO_CURSOR_HIDE, true);
838 reset_cursor();
839 }
840 break;
841 }
842 }
843}
844
845static void setup_signal(int sig, void (*handler)(int sig), int flags)
846{
847 struct sigaction sa;
848
849 sa.sa_handler = handler;
850 sigemptyset(&sa.sa_mask);
851 sa.sa_flags = flags;
852 if (sigaction(sig, &sa, NULL) < 0)
853 error(EXIT_FAILURE, errno, "signal %d", sig);
854}
855
856int main(int argc, char *argv[])
857{
858 int i;
859 size_t n;
860 const char *homedir, *dsuffix = "";
861
862 setup_signal(SIGCHLD, SIG_DFL, SA_RESTART|SA_NOCLDSTOP|SA_NOCLDWAIT);
863 setup_signal(SIGPIPE, SIG_IGN, 0);
864
865 setlocale(LC_COLLATE, "");
866
867 parse_options(argc, argv);
868
869 if (options->clean_cache) {
870 tns_init(&tns, NULL, NULL, NULL, NULL);
871 tns_clean_cache();
872 exit(EXIT_SUCCESS);
873 }
874
875 if (options->filecnt == 0 && !options->from_stdin) {
876 print_usage();
877 exit(EXIT_FAILURE);
878 }
879
880 if (options->recursive || options->from_stdin)
881 filecnt = 1024;
882 else
883 filecnt = options->filecnt;
884
885 files = ecalloc(filecnt, sizeof(*files));
886 fileidx = 0;
887
888 if (options->from_stdin) {
889 char *filename = NULL;
890 n = 0;
891 while (xgetline(&filename, &n))
892 add_entry(filename);
893 free(filename);
894 }
895
896 for (i = 0; i < options->filecnt; i++)
897 add_entry(options->filenames[i]);
898
899 if (fileidx == 0)
900 error(EXIT_FAILURE, 0, "No valid image file given, aborting");
901
902 filecnt = fileidx;
903 fileidx = options->startnum < filecnt ? options->startnum : 0;
904
905 win_init(&win);
906 img_init(&img, &win);
907 arl_init(&arl);
908
909 if ((homedir = getenv("XDG_CONFIG_HOME")) == NULL || homedir[0] == '\0') {
910 homedir = getenv("HOME");
911 dsuffix = "/.config";
912 }
913 if (homedir != NULL) {
914 extcmd_t *cmd[] = { &info.f, &info.ft, &keyhandler.f, &wintitle.f };
915 const char *name[] = { "image-info", "thumb-info", "key-handler", "win-title" };
916 const char *s = "/nsxiv/exec/";
917
918 for (i = 0; i < (int)ARRLEN(cmd); i++) {
919 n = strlen(homedir) + strlen(dsuffix) + strlen(s) + strlen(name[i]) + 1;
920 cmd[i]->cmd = emalloc(n);
921 snprintf(cmd[i]->cmd, n, "%s%s%s%s", homedir, dsuffix, s, name[i]);
922 if (access(cmd[i]->cmd, X_OK) != 0)
923 cmd[i]->err = errno;
924 }
925 } else {
926 error(0, 0, "Exec directory not found");
927 }
928 wintitle.fd = info.fd = -1;
929
930 if (options->thumb_mode) {
931 mode = MODE_THUMB;
932 tns_init(&tns, files, &filecnt, &fileidx, &win);
933 while (!tns_load(&tns, fileidx, false, false))
934 remove_file(fileidx, false);
935 } else {
936 mode = MODE_IMAGE;
937 tns.thumbs = NULL;
938 load_image(fileidx);
939 }
940 win_open(&win);
941 win_set_cursor(&win, CURSOR_WATCH);
942
943 atexit(cleanup);
944
945 set_timeout(redraw, 25, false);
946
947 run();
948
949 return 0;
950}