Debian Codegraph @

sent.c

raw symbols SCIP
1 /* See LICENSE file for copyright and license details. */
2 #include <sys/types.h>
3 #include <arpa/inet.h>
4
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <math.h>
8 #include <regex.h>
9 #include <stdarg.h>
10 #include <stdio.h>
11 #include <stdint.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <X11/keysym.h>
16 #include <X11/XKBlib.h>
17 #include <X11/Xatom.h>
18 #include <X11/Xlib.h>
19 #include <X11/Xutil.h>
20 #include <X11/Xft/Xft.h>
21
22 #include "arg.h"
23 #include "util.h"
24 #include "drw.h"
25
26 char *argv0;
27
28 /* macros */
29 #define LEN(a) (sizeof(a) / sizeof(a)[0])
30 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
31 #define MAXFONTSTRLEN 128
32
33 typedef enum {
34 NONE = 0,
35 SCALED = 1,
36 } imgstate;
37
38 typedef struct {
39 unsigned char *buf;
40 unsigned int bufwidth, bufheight;
41 imgstate state;
42 XImage *ximg;
43 int numpasses;
44 } Image;
45
46 typedef struct {
47 char *regex;
48 char *bin;
49 } Filter;
50
51 typedef struct {
52 unsigned int linecount;
53 char **lines;
54 Image *img;
55 char *embed;
56 } Slide;
57
58 /* Purely graphic info */
59 typedef struct {
60 Display *dpy;
61 Window win;
62 Atom wmdeletewin, netwmname;
63 Visual *vis;
64 XSetWindowAttributes attrs;
65 int scr;
66 int w, h;
67 int uw, uh; /* usable dimensions for drawing text and images */
68 } XWindow;
69
70 typedef union {
71 int i;
72 unsigned int ui;
73 float f;
74 const void *v;
75 } Arg;
76
77 typedef struct {
78 unsigned int b;
79 void (*func)(const Arg *);
80 const Arg arg;
81 } Mousekey;
82
83 typedef struct {
84 KeySym keysym;
85 void (*func)(const Arg *);
86 const Arg arg;
87 } Shortcut;
88
89 static void fffree(Image *img);
90 static void ffload(Slide *s);
91 static void ffprepare(Image *img);
92 static void ffscale(Image *img);
93 static void ffdraw(Image *img);
94
95 static void getfontsize(Slide *s, unsigned int *width, unsigned int *height);
96 static void cleanup(int slidesonly);
97 static void reload(const Arg *arg);
98 static void load(FILE *fp);
99 static void advance(const Arg *arg);
100 static void quit(const Arg *arg);
101 static void resize(int width, int height);
102 static void run();
103 static void usage();
104 static void xdraw();
105 static void xhints();
106 static void xinit();
107 static void xloadfonts();
108
109 static void bpress(XEvent *);
110 static void cmessage(XEvent *);
111 static void expose(XEvent *);
112 static void kpress(XEvent *);
113 static void configure(XEvent *);
114
115 /* config.h for applying patches and the configuration. */
116 #include "config.h"
117
118 /* Globals */
119 static const char *fname = NULL;
120 static Slide *slides = NULL;
121 static int idx = 0;
122 static int slidecount = 0;
123 static XWindow xw;
124 static Drw *d = NULL;
125 static Clr *sc;
126 static Fnt *fonts[NUMFONTSCALES];
127 static int running = 1;
128
129 static void (*handler[LASTEvent])(XEvent *) = {
130 [ButtonPress] = bpress,
131 [ClientMessage] = cmessage,
132 [ConfigureNotify] = configure,
133 [Expose] = expose,
134 [KeyPress] = kpress,
135 };
136
137 int
138 filter(int fd, const char *cmd)
139 {
140 int fds[2];
141
142 if (pipe(fds) < 0)
143 die("sent: Unable to create pipe:");
144
145 switch (fork()) {
146 case -1:
147 die("sent: Unable to fork:");
148 case 0:
149 dup2(fd, 0);
150 dup2(fds[1], 1);
151 close(fds[0]);
152 close(fds[1]);
153 execlp("sh", "sh", "-c", cmd, (char *)0);
154 fprintf(stderr, "sent: execlp sh -c '%s': %s\n", cmd, strerror(errno));
155 _exit(1);
156 }
157 close(fds[1]);
158 return fds[0];
159 }
160
161 void
162 fffree(Image *img)
163 {
164 free(img->buf);
165 if (img->ximg)
166 XDestroyImage(img->ximg);
167 free(img);
168 }
169
170 void
171 ffload(Slide *s)
172 {
173 uint32_t y, x;
174 uint16_t *row;
175 uint8_t opac, fg_r, fg_g, fg_b, bg_r, bg_g, bg_b;
176 size_t rowlen, off, nbytes, i;
177 ssize_t count;
178 unsigned char hdr[16];
179 char *bin = NULL;
180 char *filename;
181 regex_t regex;
182 int fdin, fdout;
183
184 if (s->img || !(filename = s->embed) || !s->embed[0])
185 return; /* already done */
186
187 for (i = 0; i < LEN(filters); i++) {
188 if (regcomp(&regex, filters[i].regex,
189 REG_NOSUB | REG_EXTENDED | REG_ICASE)) {
190 fprintf(stderr, "sent: Invalid regex '%s'\n", filters[i].regex);
191 continue;
192 }
193 if (!regexec(&regex, filename, 0, NULL, 0)) {
194 bin = filters[i].bin;
195 regfree(&regex);
196 break;
197 }
198 regfree(&regex);
199 }
200 if (!bin)
201 die("sent: Unable to find matching filter for '%s'", filename);
202
203 if ((fdin = open(filename, O_RDONLY)) < 0)
204 die("sent: Unable to open '%s':", filename);
205
206 if ((fdout = filter(fdin, bin)) < 0)
207 die("sent: Unable to filter '%s':", filename);
208 close(fdin);
209
210 if (read(fdout, hdr, 16) != 16)
211 die("sent: Unable to read filtered file '%s':", filename);
212 if (memcmp("farbfeld", hdr, 8))
213 die("sent: Filtered file '%s' has no valid farbfeld header", filename);
214
215 s->img = ecalloc(1, sizeof(Image));
216 s->img->bufwidth = ntohl(*(uint32_t *)&hdr[8]);
217 s->img->bufheight = ntohl(*(uint32_t *)&hdr[12]);
218
219 if (s->img->buf)
220 free(s->img->buf);
221 /* internally the image is stored in 888 format */
222 s->img->buf = ecalloc(s->img->bufwidth * s->img->bufheight, strlen("888"));
223
224 /* scratch buffer to read row by row */
225 rowlen = s->img->bufwidth * 2 * strlen("RGBA");
226 row = ecalloc(1, rowlen);
227
228 /* extract window background color channels for transparency */
229 bg_r = (sc[ColBg].pixel >> 16) % 256;
230 bg_g = (sc[ColBg].pixel >> 8) % 256;
231 bg_b = (sc[ColBg].pixel >> 0) % 256;
232
233 for (off = 0, y = 0; y < s->img->bufheight; y++) {
234 nbytes = 0;
235 while (nbytes < rowlen) {
236 count = read(fdout, (char *)row + nbytes, rowlen - nbytes);
237 if (count < 0)
238 die("sent: Unable to read from pipe:");
239 nbytes += count;
240 }
241 for (x = 0; x < rowlen / 2; x += 4) {
242 fg_r = ntohs(row[x + 0]) / 257;
243 fg_g = ntohs(row[x + 1]) / 257;
244 fg_b = ntohs(row[x + 2]) / 257;
245 opac = ntohs(row[x + 3]) / 257;
246 /* blend opaque part of image data with window background color to
247 * emulate transparency */
248 s->img->buf[off++] = (fg_r * opac + bg_r * (255 - opac)) / 255;
249 s->img->buf[off++] = (fg_g * opac + bg_g * (255 - opac)) / 255;
250 s->img->buf[off++] = (fg_b * opac + bg_b * (255 - opac)) / 255;
251 }
252 }
253
254 free(row);
255 close(fdout);
256 }
257
258 void
259 ffprepare(Image *img)
260 {
261 int depth = DefaultDepth(xw.dpy, xw.scr);
262 int width = xw.uw;
263 int height = xw.uh;
264
265 if (xw.uw * img->bufheight > xw.uh * img->bufwidth)
266 width = img->bufwidth * xw.uh / img->bufheight;
267 else
268 height = img->bufheight * xw.uw / img->bufwidth;
269
270 if (depth < 24)
271 die("sent: Display color depths < 24 not supported");
272
273 if (!(img->ximg = XCreateImage(xw.dpy, CopyFromParent, depth, ZPixmap, 0,
274 NULL, width, height, 32, 0)))
275 die("sent: Unable to create XImage");
276
277 img->ximg->data = ecalloc(height, img->ximg->bytes_per_line);
278 if (!XInitImage(img->ximg))
279 die("sent: Unable to initiate XImage");
280
281 ffscale(img);
282 img->state |= SCALED;
283 }
284
285 void
286 ffscale(Image *img)
287 {
288 unsigned int x, y;
289 unsigned int width = img->ximg->width;
290 unsigned int height = img->ximg->height;
291 char* newBuf = img->ximg->data;
292 unsigned char* ibuf;
293 unsigned int jdy = img->ximg->bytes_per_line / 4 - width;
294 unsigned int dx = (img->bufwidth << 10) / width;
295
296 for (y = 0; y < height; y++) {
297 unsigned int bufx = img->bufwidth / width;
298 ibuf = &img->buf[y * img->bufheight / height * img->bufwidth * 3];
299
300 for (x = 0; x < width; x++) {
301 *newBuf++ = (ibuf[(bufx >> 10)*3+2]);
302 *newBuf++ = (ibuf[(bufx >> 10)*3+1]);
303 *newBuf++ = (ibuf[(bufx >> 10)*3+0]);
304 newBuf++;
305 bufx += dx;
306 }
307 newBuf += jdy;
308 }
309 }
310
311 void
312 ffdraw(Image *img)
313 {
314 int xoffset = (xw.w - img->ximg->width) / 2;
315 int yoffset = (xw.h - img->ximg->height) / 2;
316 XPutImage(xw.dpy, xw.win, d->gc, img->ximg, 0, 0,
317 xoffset, yoffset, img->ximg->width, img->ximg->height);
318 XFlush(xw.dpy);
319 }
320
321 void
322 getfontsize(Slide *s, unsigned int *width, unsigned int *height)
323 {
324 int i, j;
325 unsigned int curw, newmax;
326 float lfac = linespacing * (s->linecount - 1) + 1;
327
328 /* fit height */
329 for (j = NUMFONTSCALES - 1; j >= 0; j--)
330 if (fonts[j]->h * lfac <= xw.uh)
331 break;
332 LIMIT(j, 0, NUMFONTSCALES - 1);
333 drw_setfontset(d, fonts[j]);
334
335 /* fit width */
336 *width = 0;
337 for (i = 0; i < s->linecount; i++) {
338 curw = drw_fontset_getwidth(d, s->lines[i]);
339 newmax = (curw >= *width);
340 while (j > 0 && curw > xw.uw) {
341 drw_setfontset(d, fonts[--j]);
342 curw = drw_fontset_getwidth(d, s->lines[i]);
343 }
344 if (newmax)
345 *width = curw;
346 }
347 *height = fonts[j]->h * lfac;
348 }
349
350 void
351 cleanup(int slidesonly)
352 {
353 unsigned int i, j;
354
355 if (!slidesonly) {
356 for (i = 0; i < NUMFONTSCALES; i++)
357 drw_fontset_free(fonts[i]);
358 free(sc);
359 drw_free(d);
360
361 XDestroyWindow(xw.dpy, xw.win);
362 XSync(xw.dpy, False);
363 XCloseDisplay(xw.dpy);
364 }
365
366 if (slides) {
367 for (i = 0; i < slidecount; i++) {
368 for (j = 0; j < slides[i].linecount; j++)
369 free(slides[i].lines[j]);
370 free(slides[i].lines);
371 if (slides[i].img)
372 fffree(slides[i].img);
373 }
374 if (!slidesonly) {
375 free(slides);
376 slides = NULL;
377 }
378 }
379 }
380
381 void
382 reload(const Arg *arg)
383 {
384 FILE *fp = NULL;
385 unsigned int i;
386
387 if (!fname) {
388 fprintf(stderr, "sent: Cannot reload from stdin. Use a file!\n");
389 return;
390 }
391
392 cleanup(1);
393 slidecount = 0;
394
395 if (!(fp = fopen(fname, "r")))
396 die("sent: Unable to open '%s' for reading:", fname);
397 load(fp);
398 fclose(fp);
399
400 LIMIT(idx, 0, slidecount-1);
401 for (i = 0; i < slidecount; i++)
402 ffload(&slides[i]);
403 xdraw();
404 }
405
406 void
407 load(FILE *fp)
408 {
409 static size_t size = 0;
410 size_t blen, maxlines;
411 char buf[BUFSIZ], *p;
412 Slide *s;
413
414 /* read each line from fp and add it to the item list */
415 while (1) {
416 /* eat consecutive empty lines */
417 while ((p = fgets(buf, sizeof(buf), fp)))
418 if (strcmp(buf, "\n") != 0 && buf[0] != '#')
419 break;
420 if (!p)
421 break;
422
423 if ((slidecount+1) * sizeof(*slides) >= size)
424 if (!(slides = realloc(slides, (size += BUFSIZ))))
425 die("sent: Unable to reallocate %u bytes:", size);
426
427 /* read one slide */
428 maxlines = 0;
429 memset((s = &slides[slidecount]), 0, sizeof(Slide));
430 do {
431 if (buf[0] == '#')
432 continue;
433
434 /* grow lines array */
435 if (s->linecount >= maxlines) {
436 maxlines = 2 * s->linecount + 1;
437 if (!(s->lines = realloc(s->lines, maxlines * sizeof(s->lines[0]))))
438 die("sent: Unable to reallocate %u bytes:", maxlines * sizeof(s->lines[0]));
439 }
440
441 blen = strlen(buf);
442 if (!(s->lines[s->linecount] = strdup(buf)))
443 die("sent: Unable to strdup:");
444 if (s->lines[s->linecount][blen-1] == '\n')
445 s->lines[s->linecount][blen-1] = '\0';
446
447 /* mark as image slide if first line of a slide starts with @ */
448 if (s->linecount == 0 && s->lines[0][0] == '@')
449 s->embed = &s->lines[0][1];
450
451 if (s->lines[s->linecount][0] == '\\')
452 memmove(s->lines[s->linecount], &s->lines[s->linecount][1], blen);
453 s->linecount++;
454 } while ((p = fgets(buf, sizeof(buf), fp)) && strcmp(buf, "\n") != 0);
455
456 slidecount++;
457 if (!p)
458 break;
459 }
460 }
461
462 void
463 advance(const Arg *arg)
464 {
465 int new_idx = idx + arg->i;
466 LIMIT(new_idx, 0, slidecount-1);
467 if (new_idx != idx) {
468 if (slides[idx].img)
469 slides[idx].img->state &= ~SCALED;
470 idx = new_idx;
471 xdraw();
472 }
473 }
474
475 void
476 quit(const Arg *arg)
477 {
478 running = 0;
479 }
480
481 void
482 resize(int width, int height)
483 {
484 xw.w = width;
485 xw.h = height;
486 xw.uw = usablewidth * width;
487 xw.uh = usableheight * height;
488 drw_resize(d, width, height);
489 }
490
491 void
492 run()
493 {
494 XEvent ev;
495
496 /* Waiting for window mapping */
497 while (1) {
498 XNextEvent(xw.dpy, &ev);
499 if (ev.type == ConfigureNotify) {
500 resize(ev.xconfigure.width, ev.xconfigure.height);
501 } else if (ev.type == MapNotify) {
502 break;
503 }
504 }
505
506 while (running) {
507 XNextEvent(xw.dpy, &ev);
508 if (handler[ev.type])
509 (handler[ev.type])(&ev);
510 }
511 }
512
513 void
514 xdraw()
515 {
516 unsigned int height, width, i;
517 Image *im = slides[idx].img;
518
519 getfontsize(&slides[idx], &width, &height);
520 XClearWindow(xw.dpy, xw.win);
521
522 if (!im) {
523 drw_rect(d, 0, 0, xw.w, xw.h, 1, 1);
524 for (i = 0; i < slides[idx].linecount; i++)
525 drw_text(d,
526 (xw.w - width) / 2,
527 (xw.h - height) / 2 + i * linespacing * d->fonts->h,
528 width,
529 d->fonts->h,
530 0,
531 slides[idx].lines[i],
532 0);
533 drw_map(d, xw.win, 0, 0, xw.w, xw.h);
534 } else {
535 if (!(im->state & SCALED))
536 ffprepare(im);
537 ffdraw(im);
538 }
539 }
540
541 void
542 xhints()
543 {
544 XClassHint class = {.res_name = "sent", .res_class = "presenter"};
545 XWMHints wm = {.flags = InputHint, .input = True};
546 XSizeHints *sizeh = NULL;
547
548 if (!(sizeh = XAllocSizeHints()))
549 die("sent: Unable to allocate size hints");
550
551 sizeh->flags = PSize;
552 sizeh->height = xw.h;
553 sizeh->width = xw.w;
554
555 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
556 XFree(sizeh);
557 }
558
559 void
560 xinit()
561 {
562 XTextProperty prop;
563 unsigned int i;
564
565 if (!(xw.dpy = XOpenDisplay(NULL)))
566 die("sent: Unable to open display");
567 xw.scr = XDefaultScreen(xw.dpy);
568 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
569 resize(DisplayWidth(xw.dpy, xw.scr), DisplayHeight(xw.dpy, xw.scr));
570
571 xw.attrs.bit_gravity = CenterGravity;
572 xw.attrs.event_mask = KeyPressMask | ExposureMask | StructureNotifyMask |
573 ButtonMotionMask | ButtonPressMask;
574
575 xw.win = XCreateWindow(xw.dpy, XRootWindow(xw.dpy, xw.scr), 0, 0,
576 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr),
577 InputOutput, xw.vis, CWBitGravity | CWEventMask,
578 &xw.attrs);
579
580 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
581 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
582 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
583
584 if (!(d = drw_create(xw.dpy, xw.scr, xw.win, xw.w, xw.h)))
585 die("sent: Unable to create drawing context");
586 sc = drw_scm_create(d, colors, 2);
587 drw_setscheme(d, sc);
588 XSetWindowBackground(xw.dpy, xw.win, sc[ColBg].pixel);
589
590 xloadfonts();
591 for (i = 0; i < slidecount; i++)
592 ffload(&slides[i]);
593
594 XStringListToTextProperty(&argv0, 1, &prop);
595 XSetWMName(xw.dpy, xw.win, &prop);
596 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
597 XFree(prop.value);
598 XMapWindow(xw.dpy, xw.win);
599 xhints();
600 XSync(xw.dpy, False);
601 }
602
603 void
604 xloadfonts()
605 {
606 int i, j;
607 char *fstrs[LEN(fontfallbacks)];
608
609 for (j = 0; j < LEN(fontfallbacks); j++) {
610 fstrs[j] = ecalloc(1, MAXFONTSTRLEN);
611 }
612
613 for (i = 0; i < NUMFONTSCALES; i++) {
614 for (j = 0; j < LEN(fontfallbacks); j++) {
615 if (MAXFONTSTRLEN < snprintf(fstrs[j], MAXFONTSTRLEN, "%s:size=%d", fontfallbacks[j], FONTSZ(i)))
616 die("sent: Font string too long");
617 }
618 if (!(fonts[i] = drw_fontset_create(d, (const char**)fstrs, LEN(fstrs))))
619 die("sent: Unable to load any font for size %d", FONTSZ(i));
620 }
621
622 for (j = 0; j < LEN(fontfallbacks); j++)
623 if (fstrs[j])
624 free(fstrs[j]);
625 }
626
627 void
628 bpress(XEvent *e)
629 {
630 unsigned int i;
631
632 for (i = 0; i < LEN(mshortcuts); i++)
633 if (e->xbutton.button == mshortcuts[i].b && mshortcuts[i].func)
634 mshortcuts[i].func(&(mshortcuts[i].arg));
635 }
636
637 void
638 cmessage(XEvent *e)
639 {
640 if (e->xclient.data.l[0] == xw.wmdeletewin)
641 running = 0;
642 }
643
644 void
645 expose(XEvent *e)
646 {
647 if (0 == e->xexpose.count)
648 xdraw();
649 }
650
651 void
652 kpress(XEvent *e)
653 {
654 unsigned int i;
655 KeySym sym;
656
657 sym = XkbKeycodeToKeysym(xw.dpy, (KeyCode)e->xkey.keycode, 0, 0);
658 for (i = 0; i < LEN(shortcuts); i++)
659 if (sym == shortcuts[i].keysym && shortcuts[i].func)
660 shortcuts[i].func(&(shortcuts[i].arg));
661 }
662
663 void
664 configure(XEvent *e)
665 {
666 resize(e->xconfigure.width, e->xconfigure.height);
667 if (slides[idx].img)
668 slides[idx].img->state &= ~SCALED;
669 xdraw();
670 }
671
672 void
673 usage()
674 {
675 die("usage: %s [file]", argv0);
676 }
677
678 int
679 main(int argc, char *argv[])
680 {
681 FILE *fp = NULL;
682
683 ARGBEGIN {
684 case 'v':
685 fprintf(stderr, "sent-"VERSION"\n");
686 return 0;
687 default:
688 usage();
689 } ARGEND
690
691 if (!argv[0] || !strcmp(argv[0], "-"))
692 fp = stdin;
693 else if (!(fp = fopen(fname = argv[0], "r")))
694 die("sent: Unable to open '%s' for reading:", fname);
695 load(fp);
696 fclose(fp);
697
698 if (!slidecount)
699 usage();
700
701 xinit();
702 run();
703
704 cleanup(0);
705 return 0;
706 }