Krolyxon
Commit 0e81802

Branches

Refs →

nsxivmain.c

802 lines · 16.9 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#define _POSIX_C_SOURCE 200112L
20#define _MAPPINGS_CONFIG
21
22#include <stdlib.h>
23#include <stdio.h>
24#include <string.h>
25#include <fcntl.h>
26#include <unistd.h>
27#include <errno.h>
28#include <signal.h>
29#include <sys/select.h>
30#include <sys/stat.h>
31#include <sys/time.h>
32#include <sys/wait.h>
33#include <X11/keysym.h>
34
35#include "types.h"
36#include "commands.h"
37#include "image.h"
38#include "options.h"
39#include "thumbs.h"
40#include "util.h"
41#include "window.h"
42#include "config.h"
43
44enum {
45 FILENAME_CNT = 1024,
46 TITLE_LEN = 256
47};
48
49#define EXEC_REL_DIR ".sxiv/exec"
50
51enum {
52 EXEC_INFO,
53 EXEC_KEY
54};
55
56typedef struct {
57 const char *name;
58 char *cmd;
59} exec_t;
60
61typedef struct {
62 struct timeval when;
63 bool active;
64 timeout_f handler;
65} timeout_t;
66
67/* timeout handler functions: */
68void redraw(void);
69void reset_cursor(void);
70void animate(void);
71void clear_resize(void);
72
73appmode_t mode;
74img_t img;
75tns_t tns;
76win_t win;
77
78fileinfo_t *files;
79int filecnt, fileidx;
80int alternate;
81
82int prefix;
83
84bool resized = false;
85
86exec_t exec[] = {
87 { "image-info", NULL },
88 { "key-handler", NULL }
89};
90
91struct {
92 char *cmd;
93 int fd;
94 unsigned int i, lastsep;
95 bool open;
96} info;
97
98timeout_t timeouts[] = {
99 { { 0, 0 }, false, redraw },
100 { { 0, 0 }, false, reset_cursor },
101 { { 0, 0 }, false, animate },
102 { { 0, 0 }, false, clear_resize },
103};
104
105void cleanup(void)
106{
107 static bool in = false;
108
109 if (!in) {
110 in = true;
111 img_close(&img, false);
112 tns_free(&tns);
113 win_close(&win);
114 }
115}
116
117void check_add_file(char *filename)
118{
119 const char *bn;
120
121 if (filename == NULL || *filename == '\0')
122 return;
123
124 if (access(filename, R_OK) < 0) {
125 warn("could not open file: %s", filename);
126 return;
127 }
128
129 if (fileidx == filecnt) {
130 filecnt *= 2;
131 files = (fileinfo_t*) s_realloc(files, filecnt * sizeof(fileinfo_t));
132 }
133 if (*filename != '/') {
134 files[fileidx].path = absolute_path(filename);
135 if (files[fileidx].path == NULL) {
136 warn("could not get absolute path of file: %s\n", filename);
137 return;
138 }
139 }
140 files[fileidx].loaded = false;
141 files[fileidx].name = s_strdup(filename);
142 if (*filename == '/')
143 files[fileidx].path = files[fileidx].name;
144 if ((bn = strrchr(files[fileidx].name , '/')) != NULL && bn[1] != '\0')
145 files[fileidx].base = ++bn;
146 else
147 files[fileidx].base = files[fileidx].name;
148 fileidx++;
149}
150
151void remove_file(int n, bool manual)
152{
153 if (n < 0 || n >= filecnt)
154 return;
155
156 if (filecnt == 1) {
157 if (!manual)
158 fprintf(stderr, "sxiv: no more files to display, aborting\n");
159 cleanup();
160 exit(manual ? EXIT_SUCCESS : EXIT_FAILURE);
161 }
162
163 if (files[n].path != files[n].name)
164 free((void*) files[n].path);
165 free((void*) files[n].name);
166
167 if (n + 1 < filecnt)
168 memmove(files + n, files + n + 1, (filecnt - n - 1) * sizeof(fileinfo_t));
169 if (n + 1 < tns.cnt) {
170 memmove(tns.thumbs + n, tns.thumbs + n + 1, (tns.cnt - n - 1) *
171 sizeof(thumb_t));
172 memset(tns.thumbs + tns.cnt - 1, 0, sizeof(thumb_t));
173 }
174
175 filecnt--;
176 if (n < tns.cnt)
177 tns.cnt--;
178 if (n < alternate)
179 alternate--;
180}
181
182void set_timeout(timeout_f handler, int time, bool overwrite)
183{
184 int i;
185
186 for (i = 0; i < ARRLEN(timeouts); i++) {
187 if (timeouts[i].handler == handler) {
188 if (!timeouts[i].active || overwrite) {
189 gettimeofday(&timeouts[i].when, 0);
190 TV_ADD_MSEC(&timeouts[i].when, time);
191 timeouts[i].active = true;
192 }
193 return;
194 }
195 }
196}
197
198void reset_timeout(timeout_f handler)
199{
200 int i;
201
202 for (i = 0; i < ARRLEN(timeouts); i++) {
203 if (timeouts[i].handler == handler) {
204 timeouts[i].active = false;
205 return;
206 }
207 }
208}
209
210bool check_timeouts(struct timeval *t)
211{
212 int i = 0, tdiff, tmin = -1;
213 struct timeval now;
214
215 while (i < ARRLEN(timeouts)) {
216 if (timeouts[i].active) {
217 gettimeofday(&now, 0);
218 tdiff = TV_DIFF(&timeouts[i].when, &now);
219 if (tdiff <= 0) {
220 timeouts[i].active = false;
221 if (timeouts[i].handler != NULL)
222 timeouts[i].handler();
223 i = tmin = -1;
224 } else if (tmin < 0 || tdiff < tmin) {
225 tmin = tdiff;
226 }
227 }
228 i++;
229 }
230 if (tmin > 0 && t != NULL)
231 TV_SET_MSEC(t, tmin);
232 return tmin > 0;
233}
234
235void open_info(void)
236{
237 static pid_t pid;
238 int pfd[2];
239
240 if (info.cmd == NULL || info.open || win.bar.h == 0)
241 return;
242 if (info.fd != -1) {
243 close(info.fd);
244 kill(pid, SIGTERM);
245 info.fd = -1;
246 }
247 win.bar.l[0] = '\0';
248
249 if (pipe(pfd) < 0)
250 return;
251 pid = fork();
252 if (pid > 0) {
253 close(pfd[1]);
254 fcntl(pfd[0], F_SETFL, O_NONBLOCK);
255 info.fd = pfd[0];
256 info.i = info.lastsep = 0;
257 info.open = true;
258 } else if (pid == 0) {
259 close(pfd[0]);
260 dup2(pfd[1], 1);
261 execl(info.cmd, info.cmd, files[fileidx].name, NULL);
262 warn("could not exec: %s", info.cmd);
263 exit(EXIT_FAILURE);
264 }
265}
266
267void read_info(void)
268{
269 ssize_t i, n;
270 char buf[BAR_L_LEN];
271
272 while (true) {
273 n = read(info.fd, buf, sizeof(buf));
274 if (n < 0 && errno == EAGAIN)
275 return;
276 else if (n == 0)
277 goto end;
278 for (i = 0; i < n; i++) {
279 if (buf[i] == '\n') {
280 if (info.lastsep == 0) {
281 win.bar.l[info.i++] = ' ';
282 info.lastsep = 1;
283 }
284 } else {
285 win.bar.l[info.i++] = buf[i];
286 info.lastsep = 0;
287 }
288 if (info.i + 1 == sizeof(win.bar.l))
289 goto end;
290 }
291 }
292end:
293 info.i -= info.lastsep;
294 win.bar.l[info.i] = '\0';
295 win_update_bar(&win);
296 close(info.fd);
297 info.fd = -1;
298 while (waitpid(-1, NULL, WNOHANG) > 0);
299}
300
301void load_image(int new)
302{
303 if (new < 0 || new >= filecnt)
304 return;
305
306 win_set_cursor(&win, CURSOR_WATCH);
307
308 if (new != fileidx)
309 alternate = fileidx;
310
311 img_close(&img, false);
312 while (!img_load(&img, &files[new])) {
313 remove_file(new, false);
314 if (new >= filecnt)
315 new = filecnt - 1;
316 else if (new > 0 && new < fileidx)
317 new--;
318 }
319 files[new].loaded = true;
320 fileidx = new;
321
322 info.open = false;
323 open_info();
324
325 if (img.multi.cnt > 0 && img.multi.animate)
326 set_timeout(animate, img.multi.frames[img.multi.sel].delay, true);
327 else
328 reset_timeout(animate);
329}
330
331void update_info(void)
332{
333 int sel;
334 unsigned int i, fn, fw, n;
335 unsigned int llen = sizeof(win.bar.l), rlen = sizeof(win.bar.r);
336 char *lt = win.bar.l, *rt = win.bar.r, title[TITLE_LEN];
337 const char * mark;
338 bool ow_info;
339
340 for (fw = 0, i = filecnt; i > 0; fw++, i /= 10);
341 sel = mode == MODE_IMAGE ? fileidx : tns.sel;
342
343 /* update window title */
344 if (mode == MODE_THUMB) {
345 win_set_title(&win, "sxiv");
346 } else {
347 snprintf(title, sizeof(title), "sxiv - %s", files[sel].name);
348 win_set_title(&win, title);
349 }
350
351 /* update bar contents */
352 if (win.bar.h == 0)
353 return;
354 mark = files[sel].marked ? "* " : "";
355 if (mode == MODE_THUMB) {
356 if (tns.cnt == filecnt) {
357 n = snprintf(rt, rlen, "%s%0*d/%d", mark, fw, sel + 1, filecnt);
358 ow_info = true;
359 } else {
360 snprintf(lt, llen, "Loading... %0*d/%d", fw, tns.cnt, filecnt);
361 rt[0] = '\0';
362 ow_info = false;
363 }
364 } else {
365 n = snprintf(rt, rlen, "%s", mark);
366 if (img.gamma != 0)
367 n += snprintf(rt + n, rlen - n, "G%+d | ", img.gamma);
368 n += snprintf(rt + n, rlen - n, "%3d%% | ", (int) (img.zoom * 100.0));
369 if (img.multi.cnt > 0) {
370 for (fn = 0, i = img.multi.cnt; i > 0; fn++, i /= 10);
371 n += snprintf(rt + n, rlen - n, "%0*d/%d | ",
372 fn, img.multi.sel + 1, img.multi.cnt);
373 }
374 n += snprintf(rt + n, rlen - n, "%0*d/%d", fw, sel + 1, filecnt);
375 ow_info = info.cmd == NULL;
376 }
377 if (ow_info) {
378 fn = strlen(files[sel].name);
379 if (fn < llen &&
380 win_textwidth(files[sel].name, fn, true) +
381 win_textwidth(rt, n, true) < win.w)
382 {
383 strncpy(lt, files[sel].name, llen);
384 } else {
385 strncpy(lt, files[sel].base, llen);
386 }
387 }
388}
389
390void redraw(void)
391{
392 if (mode == MODE_IMAGE)
393 img_render(&img);
394 else
395 tns_render(&tns);
396 update_info();
397 win_draw(&win);
398 reset_timeout(redraw);
399 reset_cursor();
400}
401
402void reset_cursor(void)
403{
404 int i;
405 cursor_t cursor = CURSOR_NONE;
406
407 if (mode == MODE_IMAGE) {
408 for (i = 0; i < ARRLEN(timeouts); i++) {
409 if (timeouts[i].handler == reset_cursor) {
410 if (timeouts[i].active)
411 cursor = CURSOR_ARROW;
412 break;
413 }
414 }
415 } else {
416 if (tns.cnt != filecnt)
417 cursor = CURSOR_WATCH;
418 else
419 cursor = CURSOR_ARROW;
420 }
421 win_set_cursor(&win, cursor);
422}
423
424void animate(void)
425{
426 if (img_frame_animate(&img, false)) {
427 redraw();
428 set_timeout(animate, img.multi.frames[img.multi.sel].delay, true);
429 }
430}
431
432void clear_resize(void)
433{
434 resized = false;
435}
436
437void key_handler(const char *key, unsigned int mask)
438{
439 pid_t pid;
440 int retval, status, n = mode == MODE_IMAGE ? fileidx : tns.sel;
441 char *cmd = exec[EXEC_KEY].cmd, kstr[32];
442
443 if (cmd == NULL || key == NULL)
444 return;
445
446 snprintf(kstr, sizeof(kstr), "%s%s%s%s",
447 mask & ControlMask ? "C-" : "",
448 mask & Mod1Mask ? "M-" : "",
449 mask & ShiftMask ? "S-" : "", key);
450
451 if ((pid = fork()) == 0) {
452 execl(cmd, cmd, kstr, files[n].path, NULL);
453 warn("could not exec key handler");
454 exit(EXIT_FAILURE);
455 } else if (pid < 0) {
456 warn("could not fork key handler");
457 return;
458 }
459 win_set_cursor(&win, CURSOR_WATCH);
460
461 waitpid(pid, &status, 0);
462 retval = WEXITSTATUS(status);
463 if (WIFEXITED(status) == 0 || retval != 0)
464 warn("key handler exited with non-zero return value: %d", retval);
465 if (mode == MODE_IMAGE) {
466 img_close(&img, true);
467 load_image(fileidx);
468 }
469 if (!tns_load(&tns, n, &files[n], true, mode == MODE_IMAGE) &&
470 mode == MODE_THUMB)
471 {
472 remove_file(tns.sel, false);
473 tns.dirty = true;
474 if (tns.sel >= tns.cnt)
475 tns.sel = tns.cnt - 1;
476 }
477 redraw();
478}
479
480#define MODMASK(mask) ((mask) & (ShiftMask|ControlMask|Mod1Mask))
481
482void on_keypress(XKeyEvent *kev)
483{
484 int i;
485 unsigned int sh;
486 KeySym ksym, shksym;
487 char key;
488
489 if (kev == NULL)
490 return;
491
492 if (kev->state & ShiftMask) {
493 kev->state &= ~ShiftMask;
494 XLookupString(kev, &key, 1, &shksym, NULL);
495 kev->state |= ShiftMask;
496 }
497 XLookupString(kev, &key, 1, &ksym, NULL);
498 sh = (kev->state & ShiftMask) && ksym != shksym ? ShiftMask : 0;
499
500 if (IsModifierKey(ksym))
501 return;
502
503 if ((ksym == XK_Escape && MODMASK(kev->state) == 0) ||
504 (key >= '0' && key <= '9'))
505 {
506 /* number prefix for commands */
507 prefix = ksym == XK_Escape ? 0 : prefix * 10 + (int) (key - '0');
508 return;
509 }
510
511 for (i = 0; i < ARRLEN(keys); i++) {
512 if (keys[i].ksym == ksym &&
513 MODMASK(keys[i].mask | sh) == MODMASK(kev->state))
514 {
515 if (keys[i].cmd != NULL && keys[i].cmd(keys[i].arg))
516 redraw();
517 prefix = 0;
518 return;
519 }
520 }
521 key_handler(XKeysymToString(ksym), kev->state & ~sh);
522}
523
524void on_buttonpress(XButtonEvent *bev)
525{
526 int i, sel;
527
528 if (bev == NULL)
529 return;
530
531 if (mode == MODE_IMAGE) {
532 win_set_cursor(&win, CURSOR_ARROW);
533 set_timeout(reset_cursor, TO_CURSOR_HIDE, true);
534
535 for (i = 0; i < ARRLEN(buttons); i++) {
536 if (buttons[i].button == bev->button &&
537 MODMASK(buttons[i].mask) == MODMASK(bev->state))
538 {
539 if (buttons[i].cmd != NULL && buttons[i].cmd(buttons[i].arg))
540 redraw();
541 return;
542 }
543 }
544 } else {
545 /* thumbnail mode (hard-coded) */
546 switch (bev->button) {
547 case Button1:
548 if ((sel = tns_translate(&tns, bev->x, bev->y)) >= 0) {
549 if (sel == tns.sel) {
550 mode = MODE_IMAGE;
551 set_timeout(reset_cursor, TO_CURSOR_HIDE, true);
552 load_image(tns.sel);
553 } else {
554 tns_highlight(&tns, tns.sel, false);
555 tns_highlight(&tns, sel, true);
556 tns.sel = sel;
557 }
558 redraw();
559 break;
560 }
561 break;
562 case Button3:
563 if ((sel = tns_translate(&tns, bev->x, bev->y)) >= 0) {
564 files[sel].marked = !files[sel].marked;
565 tns_mark(&tns, sel, files[sel].marked);
566 redraw();
567 }
568 break;
569 case Button4:
570 case Button5:
571 if (tns_scroll(&tns, bev->button == Button4 ? DIR_UP : DIR_DOWN,
572 (bev->state & ControlMask) != 0))
573 redraw();
574 break;
575 }
576 }
577}
578
579void run(void)
580{
581 int xfd;
582 fd_set fds;
583 struct timeval timeout;
584 bool discard, to_set;
585 XEvent ev, nextev;
586
587 redraw();
588
589 while (true) {
590 while (mode == MODE_THUMB && tns.cnt < filecnt &&
591 XPending(win.env.dpy) == 0)
592 {
593 /* load thumbnails */
594 set_timeout(redraw, TO_REDRAW_THUMBS, false);
595 if (tns_load(&tns, tns.cnt, &files[tns.cnt], false, false)) {
596 tns.cnt++;
597 } else {
598 remove_file(tns.cnt, false);
599 if (tns.sel > 0 && tns.sel >= tns.cnt)
600 tns.sel--;
601 }
602 if (tns.cnt == filecnt)
603 redraw();
604 else
605 check_timeouts(NULL);
606 }
607
608 while (XPending(win.env.dpy) == 0
609 && ((to_set = check_timeouts(&timeout)) || info.fd != -1))
610 {
611 /* check for timeouts & input */
612 xfd = ConnectionNumber(win.env.dpy);
613 FD_ZERO(&fds);
614 FD_SET(xfd, &fds);
615 if (info.fd != -1) {
616 FD_SET(info.fd, &fds);
617 xfd = MAX(xfd, info.fd);
618 }
619 select(xfd + 1, &fds, 0, 0, to_set ? &timeout : NULL);
620 if (info.fd != -1 && FD_ISSET(info.fd, &fds))
621 read_info();
622 }
623
624 do {
625 XNextEvent(win.env.dpy, &ev);
626 discard = false;
627 if (XEventsQueued(win.env.dpy, QueuedAlready) > 0) {
628 XPeekEvent(win.env.dpy, &nextev);
629 switch (ev.type) {
630 case ConfigureNotify:
631 discard = ev.type == nextev.type;
632 break;
633 case KeyPress:
634 discard = (nextev.type == KeyPress || nextev.type == KeyRelease)
635 && ev.xkey.keycode == nextev.xkey.keycode;
636 break;
637 }
638 }
639 } while (discard);
640
641 switch (ev.type) {
642 /* handle events */
643 case ButtonPress:
644 on_buttonpress(&ev.xbutton);
645 break;
646 case ClientMessage:
647 if ((Atom) ev.xclient.data.l[0] == wm_delete_win)
648 return;
649 break;
650 case ConfigureNotify:
651 if (win_configure(&win, &ev.xconfigure)) {
652 if (mode == MODE_IMAGE) {
653 img.dirty = true;
654 img.checkpan = true;
655 } else {
656 tns.dirty = true;
657 }
658 if (!resized || win.fullscreen) {
659 redraw();
660 set_timeout(clear_resize, TO_REDRAW_RESIZE, false);
661 resized = true;
662 } else {
663 set_timeout(redraw, TO_REDRAW_RESIZE, false);
664 }
665 }
666 break;
667 case Expose:
668 win_expose(&win, &ev.xexpose);
669 break;
670 case KeyPress:
671 on_keypress(&ev.xkey);
672 break;
673 case MotionNotify:
674 if (mode == MODE_IMAGE) {
675 win_set_cursor(&win, CURSOR_ARROW);
676 set_timeout(reset_cursor, TO_CURSOR_HIDE, true);
677 }
678 break;
679 }
680 }
681}
682
683int fncmp(const void *a, const void *b)
684{
685 return strcoll(((fileinfo_t*) a)->name, ((fileinfo_t*) b)->name);
686}
687
688int main(int argc, char **argv)
689{
690 int i, start;
691 size_t n;
692 ssize_t len;
693 char *filename;
694 const char *homedir;
695 struct stat fstats;
696 r_dir_t dir;
697
698 parse_options(argc, argv);
699
700 if (options->clean_cache) {
701 tns_init(&tns, 0, NULL);
702 tns_clean_cache(&tns);
703 exit(EXIT_SUCCESS);
704 }
705
706 if (options->filecnt == 0 && !options->from_stdin) {
707 print_usage();
708 exit(EXIT_FAILURE);
709 }
710
711 if (options->recursive || options->from_stdin)
712 filecnt = FILENAME_CNT;
713 else
714 filecnt = options->filecnt;
715
716 files = (fileinfo_t*) s_malloc(filecnt * sizeof(fileinfo_t));
717 fileidx = 0;
718
719 if (options->from_stdin) {
720 filename = NULL;
721 while ((len = get_line(&filename, &n, stdin)) > 0) {
722 if (filename[len-1] == '\n')
723 filename[len-1] = '\0';
724 check_add_file(filename);
725 }
726 if (filename != NULL)
727 free(filename);
728 }
729
730 for (i = 0; i < options->filecnt; i++) {
731 filename = options->filenames[i];
732
733 if (stat(filename, &fstats) < 0) {
734 warn("could not stat file: %s", filename);
735 continue;
736 }
737 if (!S_ISDIR(fstats.st_mode)) {
738 check_add_file(filename);
739 } else {
740 if (!options->recursive) {
741 warn("ignoring directory: %s", filename);
742 continue;
743 }
744 if (r_opendir(&dir, filename) < 0) {
745 warn("could not open directory: %s", filename);
746 continue;
747 }
748 start = fileidx;
749 while ((filename = r_readdir(&dir)) != NULL) {
750 check_add_file(filename);
751 free((void*) filename);
752 }
753 r_closedir(&dir);
754 if (fileidx - start > 1)
755 qsort(files + start, fileidx - start, sizeof(fileinfo_t), fncmp);
756 }
757 }
758
759 if (fileidx == 0) {
760 fprintf(stderr, "sxiv: no valid image file given, aborting\n");
761 exit(EXIT_FAILURE);
762 }
763
764 filecnt = fileidx;
765 fileidx = options->startnum < filecnt ? options->startnum : 0;
766
767 win_init(&win);
768 img_init(&img, &win);
769
770 if ((homedir = getenv("HOME")) == NULL) {
771 warn("could not locate home directory");
772 } else for (i = 0; i < ARRLEN(exec); i++) {
773 len = strlen(homedir) + strlen(EXEC_REL_DIR) + strlen(exec[i].name) + 3;
774 exec[i].cmd = (char*) s_malloc(len);
775 snprintf(exec[i].cmd, len, "%s/%s/%s", homedir, EXEC_REL_DIR, exec[i].name);
776 if (access(exec[i].cmd, X_OK) != 0) {
777 free(exec[i].cmd);
778 exec[i].cmd = NULL;
779 }
780 }
781 info.fd = -1;
782 info.cmd = exec[EXEC_INFO].cmd;
783
784 if (options->thumb_mode) {
785 mode = MODE_THUMB;
786 tns_init(&tns, filecnt, &win);
787 while (!tns_load(&tns, 0, &files[0], false, false))
788 remove_file(0, false);
789 tns.cnt = 1;
790 } else {
791 mode = MODE_IMAGE;
792 tns.thumbs = NULL;
793 load_image(fileidx);
794 }
795
796 win_open(&win);
797
798 run();
799 cleanup();
800
801 return 0;
802}