Krolyxon
Commit 1263f23

Branches

Refs →

nsxivmain.c

954 lines · 21.5 KB · C

1/* Copyright 2011-2020 Bert Muennich
2 * Copyright 2021-2022 nsxiv contributors
3 *
4 * This file is a part of nsxiv.
5 *
6 * nsxiv is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published
8 * by the Free Software Foundation; either version 2 of the License,
9 * or (at your option) any later version.
10 *
11 * nsxiv is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with nsxiv. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include "nsxiv.h"
21#define INCLUDE_MAPPINGS_CONFIG
22#include "commands.h"
23#include "config.h"
24
25#include <errno.h>
26#include <fcntl.h>
27#include <locale.h>
28#include <poll.h>
29#include <signal.h>
30#include <stdarg.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <sys/wait.h>
37#include <time.h>
38#include <unistd.h>
39
40#include <X11/XF86keysym.h>
41#include <X11/keysym.h>
42
43#define MODMASK(mask) ((mask) & USED_MODMASK)
44#define BAR_SEP " "
45
46#define TV_DIFF(t1,t2) (((t1)->tv_sec - (t2)->tv_sec ) * 1000 + \
47 ((t1)->tv_usec - (t2)->tv_usec) / 1000)
48#define TV_ADD_MSEC(tv,t) { \
49 (tv)->tv_sec += (t) / 1000; \
50 (tv)->tv_usec += (t) % 1000 * 1000; \
51}
52
53typedef struct {
54 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 < (int)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, ((int)win.w + 1) / 2);
438
439 if (x < nw)
440 return 0;
441 else if (x < (int)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 open_info();
725 redraw();
726 }
727 } else if (init_thumb) {
728 set_timeout(redraw, TO_REDRAW_THUMBS, false);
729 if (!tns_load(&tns, tns.initnext, false, true))
730 remove_file(tns.initnext, false);
731 } else {
732 pfd[FD_X].fd = ConnectionNumber(win.env.dpy);
733 pfd[FD_INFO].fd = info.fd;
734 pfd[FD_ARL].fd = arl.fd;
735 pfd[FD_X].events = pfd[FD_INFO].events = pfd[FD_ARL].events = POLLIN;
736
737 if (poll(pfd, ARRLEN(pfd), to_set ? timeout : -1) < 0)
738 continue;
739 if (pfd[FD_INFO].revents & POLLIN)
740 read_info();
741 if (pfd[FD_ARL].revents & POLLIN) {
742 if (arl_handle(&arl)) {
743 /* when too fast, imlib2 can't load the image */
744 nanosleep(&ten_ms, NULL);
745 img_close(&img, true);
746 load_image(fileidx);
747 redraw();
748 }
749 }
750 }
751 continue;
752 }
753
754 do {
755 XNextEvent(win.env.dpy, &ev);
756 discard = false;
757 if (XEventsQueued(win.env.dpy, QueuedAlready) > 0) {
758 XPeekEvent(win.env.dpy, &nextev);
759 switch (ev.type) {
760 case ConfigureNotify:
761 case MotionNotify:
762 discard = ev.type == nextev.type;
763 break;
764 case KeyPress:
765 discard = (nextev.type == KeyPress || nextev.type == KeyRelease)
766 && ev.xkey.keycode == nextev.xkey.keycode;
767 break;
768 }
769 }
770 } while (discard);
771
772 switch (ev.type) {
773 /* handle events */
774 case ButtonPress:
775 on_buttonpress(&ev.xbutton);
776 break;
777 case ClientMessage:
778 if ((Atom) ev.xclient.data.l[0] == atoms[ATOM_WM_DELETE_WINDOW])
779 cg_quit(EXIT_SUCCESS);
780 break;
781 case DestroyNotify:
782 cg_quit(EXIT_FAILURE);
783 break;
784 case ConfigureNotify:
785 if (win_configure(&win, &ev.xconfigure)) {
786 if (mode == MODE_IMAGE) {
787 img.dirty = true;
788 img.checkpan = true;
789 } else {
790 tns.dirty = true;
791 }
792 if (!resized) {
793 redraw();
794 set_timeout(clear_resize, TO_REDRAW_RESIZE, false);
795 resized = true;
796 } else {
797 set_timeout(redraw, TO_REDRAW_RESIZE, false);
798 }
799 }
800 break;
801 case KeyPress:
802 on_keypress(&ev.xkey);
803 break;
804 case MotionNotify:
805 if (mode == MODE_IMAGE) {
806 set_timeout(reset_cursor, TO_CURSOR_HIDE, true);
807 reset_cursor();
808 }
809 break;
810 }
811 }
812}
813
814static int fncmp(const void *a, const void *b)
815{
816 return strcoll(((fileinfo_t*) a)->name, ((fileinfo_t*) b)->name);
817}
818
819static void sigchld(int sig)
820{
821 while (waitpid(-1, NULL, WNOHANG) > 0);
822}
823
824static void setup_signal(int sig, void (*handler)(int sig))
825{
826 struct sigaction sa;
827
828 sa.sa_handler = handler;
829 sigemptyset(&sa.sa_mask);
830 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
831 if (sigaction(sig, &sa, 0) == -1)
832 error(EXIT_FAILURE, errno, "signal %d", sig);
833}
834
835int main(int argc, char *argv[])
836{
837 int i, start;
838 size_t n;
839 char *filename;
840 const char *homedir, *dsuffix = "";
841 struct stat fstats;
842 r_dir_t dir;
843
844 setup_signal(SIGCHLD, sigchld);
845 setup_signal(SIGPIPE, SIG_IGN);
846
847 setlocale(LC_COLLATE, "");
848
849 parse_options(argc, argv);
850
851 if (options->clean_cache) {
852 tns_init(&tns, NULL, NULL, NULL, NULL);
853 tns_clean_cache();
854 exit(EXIT_SUCCESS);
855 }
856
857 if (options->filecnt == 0 && !options->from_stdin) {
858 print_usage();
859 exit(EXIT_FAILURE);
860 }
861
862 if (options->recursive || options->from_stdin)
863 filecnt = 1024;
864 else
865 filecnt = options->filecnt;
866
867 files = ecalloc(filecnt, sizeof(*files));
868 fileidx = 0;
869
870 if (options->from_stdin) {
871 n = 0;
872 filename = NULL;
873 while (xgetline(&filename, &n))
874 check_add_file(filename, true);
875 free(filename);
876 }
877
878 for (i = 0; i < options->filecnt; i++) {
879 filename = options->filenames[i];
880
881 if (stat(filename, &fstats) < 0) {
882 error(0, errno, "%s", filename);
883 continue;
884 }
885 if (!S_ISDIR(fstats.st_mode)) {
886 check_add_file(filename, true);
887 } else {
888 if (r_opendir(&dir, filename, options->recursive) < 0) {
889 error(0, errno, "%s", filename);
890 continue;
891 }
892 start = fileidx;
893 while ((filename = r_readdir(&dir, true)) != NULL) {
894 check_add_file(filename, false);
895 free((void*) filename);
896 }
897 r_closedir(&dir);
898 if (fileidx - start > 1)
899 qsort(files + start, fileidx - start, sizeof(fileinfo_t), fncmp);
900 }
901 }
902
903 if (fileidx == 0)
904 error(EXIT_FAILURE, 0, "No valid image file given, aborting");
905
906 filecnt = fileidx;
907 fileidx = options->startnum < filecnt ? options->startnum : 0;
908
909 win_init(&win);
910 img_init(&img, &win);
911 arl_init(&arl);
912
913 if ((homedir = getenv("XDG_CONFIG_HOME")) == NULL || homedir[0] == '\0') {
914 homedir = getenv("HOME");
915 dsuffix = "/.config";
916 }
917 if (homedir != NULL) {
918 extcmd_t *cmd[] = { &info.f, &info.ft, &keyhandler.f, &wintitle.f };
919 const char *name[] = { "image-info", "thumb-info", "key-handler", "win-title" };
920 const char *s = "/nsxiv/exec/";
921
922 for (i = 0; i < (int)ARRLEN(cmd); i++) {
923 n = strlen(homedir) + strlen(dsuffix) + strlen(s) + strlen(name[i]) + 1;
924 cmd[i]->cmd = emalloc(n);
925 snprintf(cmd[i]->cmd, n, "%s%s%s%s", homedir, dsuffix, s, name[i]);
926 if (access(cmd[i]->cmd, X_OK) != 0)
927 cmd[i]->err = errno;
928 }
929 } else {
930 error(0, 0, "Exec directory not found");
931 }
932 info.fd = -1;
933
934 if (options->thumb_mode) {
935 mode = MODE_THUMB;
936 tns_init(&tns, files, &filecnt, &fileidx, &win);
937 while (!tns_load(&tns, fileidx, false, false))
938 remove_file(fileidx, false);
939 } else {
940 mode = MODE_IMAGE;
941 tns.thumbs = NULL;
942 load_image(fileidx);
943 }
944 win_open(&win);
945 win_set_cursor(&win, CURSOR_WATCH);
946
947 atexit(cleanup);
948
949 set_timeout(redraw, 25, false);
950
951 run();
952
953 return 0;
954}