Krolyxon
Commit 5cab2fb

Branches

Refs →

nsxivmain.c

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