Krolyxon
Commit 50f7b76

Branches

Refs →

nsxivmain.c

941 lines · 21.1 KB · C

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