Krolyxon
Commit 810a965

Branches

Refs →

nsxivmain.c

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