Krolyxon
Commit 6d5a040

Branches

Refs →

nsxivmain.c

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