Krolyxon
Commit 57ff8af

Branches

Refs →

nsxivmain.c

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