Krolyxon
Commit ad571e7

Branches

Refs →

nsxivmain.c

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