Krolyxon
Commit a1165df

Branches

Refs →

nsxivmain.c

938 lines · 20.3 KB · C

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