Krolyxon
Commit ad95012

Branches

Refs →

nsxivmain.c

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