Krolyxon
Commit 48343e9

Branches

Refs →

nsxivmain.c

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