catpoint

simple slides viewer
git clone git://git.2f30.org/catpoint.git
Log | Files | Refs | README | LICENSE

catpoint.c (1675B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <sys/types.h>
      3 #include <sys/stat.h>
      4 #include <sys/mman.h>
      5 
      6 #include <err.h>
      7 #include <curses.h>
      8 #include <fcntl.h>
      9 #include <locale.h>
     10 #include <stdio.h>
     11 #include <stdlib.h>
     12 #include <unistd.h>
     13 
     14 struct slide {
     15 	char *buf;
     16 	size_t siz;
     17 };
     18 
     19 static void
     20 printslide(struct slide *s)
     21 {
     22 	printw("%.*s", (int)s->siz, s->buf);
     23 }
     24 
     25 int
     26 main(int argc, char *argv[])
     27 {
     28 	int c, i, fd;
     29 	struct slide *s;
     30 	struct stat sb;
     31 
     32 	if (argc == 1)
     33 		errx(1, "usage: %s file ...", argv[0]);
     34 	argv++;
     35 	argc--;
     36 
     37 	setlocale(LC_ALL, "");
     38 
     39 	s = malloc(argc * sizeof(struct slide));
     40 	if (s == NULL)
     41 		err(1, "malloc");
     42 
     43 	/* map files to mem */
     44 	for (i = 0; argv[i] != NULL; i++) {
     45 		fd = open(argv[i], O_RDONLY);
     46 		if (fd == -1)
     47 			err(1, "open: %s", argv[i]);
     48 		fstat(fd, &sb);
     49 		s[i].buf = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
     50 		if (s[i].buf == MAP_FAILED)
     51 			err(1, "mmap");
     52 		s[i].siz = sb.st_size;
     53 		close(fd);
     54 	}
     55 
     56 	/* init curses */
     57 	initscr();
     58 	cbreak();
     59 	noecho();
     60 	nonl();
     61 	intrflush(stdscr, FALSE);
     62 	keypad(stdscr, TRUE);
     63 	curs_set(FALSE); /* hide cursor */
     64 
     65 	/* start */
     66 	i = 0;
     67 show:
     68 	/* display slide */
     69 	clear();
     70 	printslide(&s[i]);
     71 again:
     72 	c = getch();
     73 	switch (c) {
     74 	case 'q':
     75 		break;
     76 	/* next */
     77 	case 'l':
     78 	case 'j':
     79 	case KEY_RIGHT:
     80 	case KEY_DOWN:
     81 		if (i < argc - 1) {
     82 			i++;
     83 			goto show;
     84 		}
     85 		goto again;
     86 	/* prev */
     87 	case 'h':
     88 	case 'k':
     89 	case KEY_LEFT:
     90 	case KEY_UP:
     91 		if (i > 0) {
     92 			i--;
     93 			goto show;
     94 		}
     95 		goto again;
     96 	default:
     97 		goto again;
     98 	}
     99 
    100 	/* unmap mem */
    101 	for (i = 0; argv[i] != NULL; i++)
    102 		munmap(s[i].buf, s[i].siz);
    103 	free(s);
    104 
    105 	endwin(); /* restore terminal */
    106 
    107 	return (0);
    108 }