Krolyxon
Commit 1ef0c1f

Branches

Refs →

nsxivmain.c

956 lines · 21.2 KB · C

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