Make regexec failure case more robust
[llpp.git] / link.c
blobf9653ce3244b3e6d5dd4fbc22c8695800a17636c
1 /* lots of code c&p-ed directly from mupdf */
2 #define FIXME 0
4 #ifdef __clang__
5 #pragma GCC diagnostic error "-Weverything"
6 #pragma GCC diagnostic ignored "-Wpadded"
7 #pragma GCC diagnostic ignored "-Wsign-conversion"
8 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
9 #pragma GCC diagnostic ignored "-Wdocumentation"
10 #pragma GCC diagnostic ignored "-Wdouble-promotion"
11 #pragma GCC diagnostic ignored "-Wimplicit-int-float-conversion"
12 #endif
14 #include <errno.h>
15 #include <stdio.h>
16 #include <ctype.h>
17 #include <string.h>
18 #include <stdlib.h>
19 #include <signal.h>
21 #include <math.h>
22 #include <wchar.h>
23 #include <locale.h>
24 #include <langinfo.h>
26 #include <unistd.h>
27 #include <pthread.h>
28 #include <sys/uio.h>
29 #include <sys/time.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <sys/types.h>
33 #include <sys/ioctl.h>
34 #include <sys/utsname.h>
36 #include <spawn.h>
38 #include <regex.h>
39 #include <stdarg.h>
40 #include <limits.h>
41 #include <inttypes.h>
43 #ifdef CIDER
44 #include <OpenGL/gl.h>
45 #else
46 #include <GL/gl.h>
47 #endif
49 #pragma GCC diagnostic push
50 #ifdef __clang__
51 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
52 #endif
53 #pragma GCC diagnostic ignored "-Wpedantic"
54 #define CAML_NAME_SPACE
55 #include <caml/fail.h>
56 #include <caml/alloc.h>
57 #include <caml/memory.h>
58 #include <caml/unixsupport.h>
60 #pragma GCC diagnostic push
61 #pragma GCC diagnostic ignored "-Wfloat-equal"
62 #include <mupdf/fitz.h>
63 #include <mupdf/pdf.h>
64 #pragma GCC diagnostic pop
66 #include <ft2build.h>
67 #include FT_FREETYPE_H
68 #pragma GCC diagnostic pop
70 #include "cutils.h"
72 #ifdef USE_NPOT
73 #define TEXT_TYPE GL_TEXTURE_2D
74 #else
75 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
76 #endif
78 #if 0
79 #define lprintf printf
80 #else
81 #define lprintf(...)
82 #endif
84 #define ARSERT(cond) for (;;) { \
85 if (!(cond)) { \
86 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
87 } \
88 break; \
89 } (void) 0
91 #define ML(d) extern value ml_##d; value ml_##d
92 #define ML0(d) extern void ml_##d; void ml_##d
94 #define STTI(st) ((unsigned int) st)
96 struct slice {
97 int h;
98 int texindex;
101 struct tile {
102 int w, h;
103 int slicecount;
104 int sliceheight;
105 struct bo *pbo;
106 fz_pixmap *pixmap;
107 struct slice slices[1];
110 struct pagedim {
111 int pageno;
112 int rotate;
113 int left;
114 int tctmready;
115 fz_irect bounds;
116 fz_rect pagebox;
117 fz_rect mediabox;
118 fz_matrix ctm, zoomctm, tctm;
121 struct slink {
122 enum { SLINK, SANNOT } tag;
123 fz_irect bbox;
124 union {
125 fz_link *link;
126 pdf_annot *annot;
127 } u;
130 struct annot {
131 fz_irect bbox;
132 pdf_annot *annot;
135 struct page {
136 int tgen;
137 int sgen;
138 int agen;
139 int pageno;
140 int pdimno;
141 fz_stext_page *text;
142 fz_page *fzpage;
143 fz_display_list *dlist;
144 fz_link *links;
145 int slinkcount;
146 struct slink *slinks;
147 int annotcount;
148 struct annot *annots;
149 fz_stext_char *fmark, *lmark;
152 enum { FitWidth, FitProportional, FitPage };
154 static struct {
155 int sliceheight;
156 struct pagedim *pagedims;
157 int pagecount;
158 int pagedimcount;
159 fz_document *doc;
160 fz_context *ctx;
161 int w, h;
162 char *dcf;
163 int pfds[2];
165 struct {
166 int index, count;
167 GLuint *ids;
168 GLenum iform, form, ty;
169 struct {
170 int w, h;
171 struct slice *slice;
172 } *owners;
173 } tex;
175 fz_colorspace *colorspace;
176 float papercolor[4];
178 FT_Face face;
179 fz_pixmap *pig;
180 pthread_t thread;
181 fz_irect trimfuzz;
182 GLuint stid, boid;
183 int trimmargins, needoutline, gen, rotate, aalevel,
184 fitmodel, trimanew, csock, dirty, bo_usable, utf8cs;
186 void (*glBindBufferARB) (GLenum, GLuint);
187 GLboolean (*glUnmapBufferARB) (GLenum);
188 void *(*glMapBufferARB) (GLenum, GLenum);
189 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
190 void (*glGenBuffersARB) (GLsizei, GLuint *);
191 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
193 GLfloat texcoords[8], vertices[16];
194 } state;
196 struct bo {
197 GLuint id;
198 void *ptr;
199 size_t size;
202 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
204 static void lock (const char *cap)
206 int ret = pthread_mutex_lock (&mutex);
207 if (ret) {
208 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
212 static void unlock (const char *cap)
214 int ret = pthread_mutex_unlock (&mutex);
215 if (ret) {
216 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
220 static int trylock (const char *cap)
222 int ret = pthread_mutex_trylock (&mutex);
223 if (ret && ret != EBUSY) {
224 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
226 return ret == EBUSY;
229 static int hasdata (void)
231 int ret, avail;
232 ret = ioctl (state.csock, FIONREAD, &avail);
233 if (ret) {
234 err (1, "hasdata: FIONREAD error ret=%d", ret);
236 return avail > 0;
239 ML (hasdata (value fd_v))
241 CAMLparam1 (fd_v);
242 int ret, avail;
244 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
245 if (ret) {
246 uerror ("ioctl (FIONREAD)", Nothing);
248 CAMLreturn (Val_bool (avail > 0));
251 static void readdata (int fd, void *p, int size)
253 ssize_t n;
255 again:
256 n = read (fd, p, size);
257 if (n - size) {
258 if (n < 0 && errno == EINTR) {
259 goto again;
261 if (!n) {
262 errx (1, "EOF while reading");
264 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
268 static void writedata (int fd, char *p, int size)
270 ssize_t n;
271 uint32_t size4 = size;
272 struct iovec iov[2] = {
273 { .iov_base = &size4, .iov_len = 4 },
274 { .iov_base = p, .iov_len = size }
277 again:
278 n = writev (fd, iov, 2);
279 if (n < 0 && errno == EINTR) {
280 goto again;
282 if (n - size - 4) {
283 if (!n) {
284 errx (1, "EOF while writing data");
286 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
290 static int readlen (int fd)
292 uint32_t u;
293 readdata (fd, &u, 4);
294 return u;
297 ML0 (wcmd (value fd_v, value bytes_v, value len_v))
299 CAMLparam3 (fd_v, bytes_v, len_v);
300 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
301 CAMLreturn0;
304 ML (rcmd (value fd_v))
306 CAMLparam1 (fd_v);
307 CAMLlocal1 (strdata_v);
308 int fd = Int_val (fd_v);
309 int len = readlen (fd);
310 strdata_v = caml_alloc_string (len);
311 readdata (fd, Bytes_val (strdata_v), len);
312 CAMLreturn (strdata_v);
315 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
317 char fbuf[64];
318 int size = sizeof (fbuf), len;
319 va_list ap;
320 char *buf = fbuf;
322 for (;;) {
323 va_start (ap, fmt);
324 len = vsnprintf (buf, size, fmt, ap);
325 va_end (ap);
327 if (len > -1) {
328 if (len < size - 4) {
329 writedata (state.csock, buf, len);
330 break;
332 else {
333 size = len + 5;
336 else {
337 err (1, "vsnprintf for `%s' failed", fmt);
339 buf = realloc (buf == fbuf ? NULL : buf, size);
340 if (!buf) {
341 err (1, "realloc for temp buf (%d bytes) failed", size);
344 if (buf != fbuf) {
345 free (buf);
349 static void closedoc (void)
351 if (state.doc) {
352 fz_drop_document (state.ctx, state.doc);
353 state.doc = NULL;
357 static int openxref (char *filename, char *password, int layouth)
359 for (int i = 0; i < state.tex.count; ++i) {
360 state.tex.owners[i].w = -1;
361 state.tex.owners[i].slice = NULL;
364 closedoc ();
366 state.dirty = 0;
367 if (state.pagedims) {
368 free (state.pagedims);
369 state.pagedims = NULL;
371 state.pagedimcount = 0;
373 fz_set_aa_level (state.ctx, state.aalevel);
374 state.doc = fz_open_document (state.ctx, filename);
375 if (fz_needs_password (state.ctx, state.doc)) {
376 if (password && !*password) {
377 printd ("pass");
378 return 0;
380 else {
381 int ok = fz_authenticate_password (state.ctx, state.doc, password);
382 if (!ok) {
383 printd ("pass fail");
384 return 0;
388 if (layouth >= 0) {
389 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
391 state.pagecount = fz_count_pages (state.ctx, state.doc);
392 return 1;
395 static void docinfo (void)
397 struct { char *tag; char *name; } tab[] = {
398 { FZ_META_INFO_TITLE, "Title" },
399 { FZ_META_INFO_AUTHOR, "Author" },
400 { FZ_META_FORMAT, "Format" },
401 { FZ_META_ENCRYPTION, "Encryption" },
402 { FZ_META_INFO_CREATOR, "Creator" },
403 { FZ_META_INFO_PRODUCER, "Producer" },
404 { "info:CreationDate", "Creation date" },
406 int len = 0, need;
407 char *buf = NULL;
409 for (size_t i = 0; i < sizeof (tab) / sizeof (*tab); ++i) {
410 again:
411 need = fz_lookup_metadata (state.ctx, state.doc, tab[i].tag, buf, len);
412 if (need > 0) {
413 if (need <= len) {
414 printd ("info %s\t%s", tab[i].name, buf);
416 else {
417 buf = realloc (buf, need);
418 if (!buf){
419 err (1, "docinfo realloc %d", need);
421 len = need;
422 goto again;
426 free (buf);
428 printd ("infoend");
431 static void unlinktile (struct tile *tile)
433 for (int i = 0; i < tile->slicecount; ++i) {
434 struct slice *s = &tile->slices[i];
436 if (s->texindex != -1) {
437 if (state.tex.owners[s->texindex].slice == s) {
438 state.tex.owners[s->texindex].slice = NULL;
444 static void freepage (struct page *page)
446 if (!page) {
447 return;
449 if (page->text) {
450 fz_drop_stext_page (state.ctx, page->text);
452 if (page->slinks) {
453 free (page->slinks);
455 fz_drop_display_list (state.ctx, page->dlist);
456 fz_drop_page (state.ctx, page->fzpage);
457 free (page);
460 static void freetile (struct tile *tile)
462 unlinktile (tile);
463 if (!tile->pbo) {
464 #if 0
465 fz_drop_pixmap (state.ctx, tile->pixmap);
466 #else /* piggyback */
467 if (state.pig) {
468 fz_drop_pixmap (state.ctx, state.pig);
470 state.pig = tile->pixmap;
471 #endif
473 else {
474 free (tile->pbo);
475 fz_drop_pixmap (state.ctx, tile->pixmap);
477 free (tile);
480 static void trimctm (pdf_page *page, int pindex)
482 struct pagedim *pdim = &state.pagedims[pindex];
484 if (!page) {
485 return;
487 if (!pdim->tctmready) {
488 fz_rect realbox, mediabox;
489 fz_matrix page_ctm, ctm;
491 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
492 realbox = fz_transform_rect (pdim->mediabox, ctm);
493 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
494 pdim->tctm = fz_concat (
495 fz_invert_matrix (page_ctm),
496 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
497 pdim->tctmready = 1;
501 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
503 fz_matrix ctm;
504 ptrdiff_t pdimno = pdim - state.pagedims;
506 ARSERT (pdim - state.pagedims < INT_MAX);
507 if (pdf_specifics (state.ctx, state.doc)) {
508 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
509 ctm = fz_concat (pdim->tctm, pdim->ctm);
511 else {
512 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
513 pdim->ctm);
515 return ctm;
518 static fz_matrix pagectm (struct page *page)
520 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
523 static void *loadpage (int pageno, int pindex)
525 fz_device *dev;
526 struct page *page;
528 page = calloc (sizeof (struct page), 1);
529 if (!page) {
530 err (1, "calloc page %d", pageno);
533 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
534 dev = fz_new_list_device (state.ctx, page->dlist);
535 fz_try (state.ctx) {
536 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
537 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
539 fz_catch (state.ctx) {
540 page->fzpage = NULL;
542 fz_close_device (state.ctx, dev);
543 fz_drop_device (state.ctx, dev);
545 page->pdimno = pindex;
546 page->pageno = pageno;
547 page->sgen = state.gen;
548 page->agen = state.gen;
549 page->tgen = state.gen;
550 return page;
553 static struct tile *alloctile (int h)
555 int slicecount;
556 size_t tilesize;
557 struct tile *tile;
559 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
560 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
561 tile = calloc (tilesize, 1);
562 if (!tile) {
563 err (1, "cannot allocate tile (%zu bytes)", tilesize);
565 for (int i = 0; i < slicecount; ++i) {
566 int sh = fz_mini (h, state.sliceheight);
567 tile->slices[i].h = sh;
568 tile->slices[i].texindex = -1;
569 h -= sh;
571 tile->slicecount = slicecount;
572 tile->sliceheight = state.sliceheight;
573 return tile;
576 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
577 struct bo *pbo)
579 fz_irect bbox;
580 fz_matrix ctm;
581 fz_device *dev;
582 struct tile *tile;
583 struct pagedim *pdim;
585 tile = alloctile (h);
586 pdim = &state.pagedims[page->pdimno];
588 bbox = pdim->bounds;
589 bbox.x0 += x;
590 bbox.y0 += y;
591 bbox.x1 = bbox.x0 + w;
592 bbox.y1 = bbox.y0 + h;
594 if (state.pig) {
595 if (state.pig->w == w
596 && state.pig->h == h
597 && state.pig->colorspace == state.colorspace) {
598 tile->pixmap = state.pig;
599 tile->pixmap->x = bbox.x0;
600 tile->pixmap->y = bbox.y0;
602 else {
603 fz_drop_pixmap (state.ctx, state.pig);
605 state.pig = NULL;
607 if (!tile->pixmap) {
608 if (pbo) {
609 tile->pixmap =
610 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
611 bbox, NULL, 1, pbo->ptr);
612 tile->pbo = pbo;
614 else {
615 tile->pixmap = fz_new_pixmap_with_bbox (state.ctx,
616 state.colorspace,
617 bbox, NULL, 1);
621 tile->w = w;
622 tile->h = h;
623 fz_fill_pixmap_with_color (state.ctx, tile->pixmap,
624 fz_device_rgb (state.ctx),
625 state.papercolor,
626 fz_default_color_params);
628 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
629 ctm = pagectm (page);
630 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
631 fz_rect_from_irect (bbox), NULL);
632 fz_close_device (state.ctx, dev);
633 fz_drop_device (state.ctx, dev);
635 return tile;
638 static void initpdims1 (void)
640 struct pagedim *p;
641 pdf_document *pdf;
642 fz_context *ctx = state.ctx;
643 int pageno, trim, show, cxcount;
644 fz_rect rootmediabox = fz_empty_rect;
646 fz_var (p);
647 fz_var (pdf);
648 fz_var (cxcount);
650 cxcount = state.pagecount;
651 if ((pdf = pdf_specifics (ctx, state.doc))) {
652 pdf_obj *obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
653 "Root/Pages/MediaBox");
654 rootmediabox = pdf_to_rect (ctx, obj);
655 pdf_load_page_tree (ctx, pdf);
658 for (pageno = 0; pageno < cxcount; ++pageno) {
659 int rotate = 0;
660 fz_rect mediabox = fz_empty_rect;
662 fz_var (rotate);
663 if (pdf) {
664 pdf_obj *pageobj = NULL;
666 fz_var (pageobj);
667 if (pdf->rev_page_map) {
668 for (int i = 0; i < pdf->rev_page_count; ++i) {
669 if (pdf->rev_page_map[i].page == pageno) {
670 pageobj = pdf_get_xref_entry (
671 ctx, pdf, pdf->rev_page_map[i].object
672 )->obj;
673 break;
677 if (!pageobj) {
678 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
681 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
683 if (state.trimmargins) {
684 pdf_obj *obj;
685 pdf_page *page;
687 fz_try (ctx) {
688 page = pdf_load_page (ctx, pdf, pageno);
689 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
690 trim = state.trimanew || !obj;
691 if (trim) {
692 fz_rect rect;
693 fz_device *dev;
694 fz_matrix ctm, page_ctm;
696 dev = fz_new_bbox_device (ctx, &rect);
697 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
698 ctm = fz_invert_matrix (page_ctm);
699 pdf_run_page (ctx, page, dev, fz_identity, NULL);
700 fz_close_device (ctx, dev);
701 fz_drop_device (ctx, dev);
703 rect.x0 += state.trimfuzz.x0;
704 rect.x1 += state.trimfuzz.x1;
705 rect.y0 += state.trimfuzz.y0;
706 rect.y1 += state.trimfuzz.y1;
707 rect = fz_transform_rect (rect, ctm);
708 rect = fz_intersect_rect (rect, mediabox);
710 if (!fz_is_empty_rect (rect)) {
711 mediabox = rect;
714 obj = pdf_new_array (ctx, pdf, 4);
715 pdf_array_push_real (ctx, obj, mediabox.x0);
716 pdf_array_push_real (ctx, obj, mediabox.y0);
717 pdf_array_push_real (ctx, obj, mediabox.x1);
718 pdf_array_push_real (ctx, obj, mediabox.y1);
719 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
721 else {
722 mediabox.x0 = pdf_array_get_real (ctx, obj, 0);
723 mediabox.y0 = pdf_array_get_real (ctx, obj, 1);
724 mediabox.x1 = pdf_array_get_real (ctx, obj, 2);
725 mediabox.y1 = pdf_array_get_real (ctx, obj, 3);
728 fz_drop_page (ctx, &page->super);
729 show = (pageno + 1 == state.pagecount)
730 || (trim ? pageno % 5 == 0 : pageno % 20 == 0);
731 if (show) {
732 printd ("progress %f Trimming %d",
733 (double) (pageno + 1) / state.pagecount,
734 pageno + 1);
737 fz_catch (ctx) {
738 printd ("emsg failed to load page %d", pageno);
741 else {
742 int empty = 0;
743 fz_rect cropbox;
745 mediabox =
746 pdf_to_rect (ctx,
747 pdf_dict_get_inheritable (
748 ctx,
749 pageobj,
750 PDF_NAME (MediaBox)
753 if (fz_is_empty_rect (mediabox)) {
754 mediabox.x0 = 0;
755 mediabox.y0 = 0;
756 mediabox.x1 = 612;
757 mediabox.y1 = 792;
758 empty = 1;
761 cropbox =
762 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
763 if (!fz_is_empty_rect (cropbox)) {
764 if (empty) {
765 mediabox = cropbox;
767 else {
768 mediabox = fz_intersect_rect (mediabox, cropbox);
771 else {
772 if (empty) {
773 if (fz_is_empty_rect (rootmediabox)) {
774 printd ("emsg cannot find page %d size", pageno);
776 else {
777 mediabox = rootmediabox;
783 else {
784 if (state.trimmargins) {
785 fz_page *page;
787 fz_try (ctx) {
788 page = fz_load_page (ctx, state.doc, pageno);
789 mediabox = fz_bound_page (ctx, page);
790 if (state.trimmargins) {
791 fz_rect rect;
792 fz_device *dev;
794 dev = fz_new_bbox_device (ctx, &rect);
795 fz_run_page (ctx, page, dev, fz_identity, NULL);
796 fz_close_device (ctx, dev);
797 fz_drop_device (ctx, dev);
799 rect.x0 += state.trimfuzz.x0;
800 rect.x1 += state.trimfuzz.x1;
801 rect.y0 += state.trimfuzz.y0;
802 rect.y1 += state.trimfuzz.y1;
803 rect = fz_intersect_rect (rect, mediabox);
805 if (!fz_is_empty_rect (rect)) {
806 mediabox = rect;
809 fz_drop_page (ctx, page);
811 fz_catch (ctx) {
814 else {
815 fz_page *page;
816 fz_try (ctx) {
817 page = fz_load_page (ctx, state.doc, pageno);
818 mediabox = fz_bound_page (ctx, page);
819 fz_drop_page (ctx, page);
821 show = !state.trimmargins && pageno % 20 == 0;
822 if (show) {
823 printd ("progress %f Gathering dimensions %d",
824 (double) (pageno) / state.pagecount, pageno);
827 fz_catch (ctx) {
828 printd ("emsg failed to load page %d", pageno);
832 if (state.pagedimcount == 0
833 || ((void) (p = &state.pagedims[state.pagedimcount-1])
834 , p->rotate != rotate)
835 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
836 size_t size;
838 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
839 state.pagedims = realloc (state.pagedims, size);
840 if (!state.pagedims) {
841 err (1, "realloc pagedims to %zu (%d elems)",
842 size, state.pagedimcount + 1);
845 p = &state.pagedims[state.pagedimcount++];
846 p->rotate = rotate;
847 p->mediabox = mediabox;
848 p->pageno = pageno;
851 state.trimanew = 0;
854 static void initpdims (void)
856 FILE *f = state.dcf ? fopen (state.dcf, "rb") : NULL;
857 if (f) {
858 size_t nread;
860 nread = fread (&state.pagedimcount, sizeof (state.pagedimcount),
861 1, f);
862 if (nread - 1) {
863 err (1, "fread pagedim %zu", sizeof (state.pagedimcount));
865 size_t size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
866 state.pagedims = realloc (state.pagedims, size);
867 if (!state.pagedims) {
868 err (1, "realloc pagedims to %zu (%d elems)",
869 size, state.pagedimcount + 1);
871 if (fread (state.pagedims,
872 sizeof (*state.pagedims),
873 state.pagedimcount+1,
874 f) - (state.pagedimcount+1)) {
875 err (1, "fread pagedim data %zu %d",
876 sizeof (*state.pagedims), state.pagedimcount+1);
878 fclose (f);
881 if (!state.pagedims) {
882 initpdims1 ();
883 if (state.dcf) {
884 f = fopen (state.dcf, "wb");
885 if (!f) {
886 err (1, "fopen %s for writing", state.dcf);
888 if (fwrite (&state.pagedimcount,
889 sizeof (state.pagedimcount), 1, f) - 1) {
890 err (1, "fwrite pagedimcunt %zu", sizeof (state.pagedimcount));
892 if (fwrite (state.pagedims, sizeof (*state.pagedims),
893 state.pagedimcount + 1, f)
894 - (state.pagedimcount + 1)) {
895 err (1, "fwrite pagedim data %zu %u",
896 sizeof (*state.pagedims), state.pagedimcount+1);
898 fclose (f);
903 static void layout (void)
905 int pindex;
906 fz_rect box;
907 fz_matrix ctm;
908 struct pagedim *p = NULL;
909 float zw, w, maxw = 0.0, zoom = 1.0;
911 if (state.pagedimcount == 0) {
912 return;
915 switch (state.fitmodel) {
916 case FitProportional:
917 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
918 float x0, x1;
920 p = &state.pagedims[pindex];
921 box = fz_transform_rect (p->mediabox,
922 fz_rotate (p->rotate + state.rotate));
924 x0 = fz_min (box.x0, box.x1);
925 x1 = fz_max (box.x0, box.x1);
927 w = x1 - x0;
928 maxw = fz_max (w, maxw);
929 zoom = state.w / maxw;
931 break;
933 case FitPage:
934 maxw = state.w;
935 break;
937 case FitWidth:
938 break;
940 default:
941 ARSERT (0 && state.fitmodel);
944 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
945 p = &state.pagedims[pindex];
946 ctm = fz_rotate (state.rotate);
947 box = fz_transform_rect (p->mediabox,
948 fz_rotate (p->rotate + state.rotate));
949 w = box.x1 - box.x0;
950 switch (state.fitmodel) {
951 case FitProportional:
952 p->left = (int) (((maxw - w) * zoom) / 2.f);
953 break;
954 case FitPage:
956 float zh, h;
957 zw = maxw / w;
958 h = box.y1 - box.y0;
959 zh = state.h / h;
960 zoom = fz_min (zw, zh);
961 p->left = (int) ((maxw - (w * zoom)) / 2.f);
963 break;
964 case FitWidth:
965 p->left = 0;
966 zoom = state.w / w;
967 break;
970 p->zoomctm = fz_scale (zoom, zoom);
971 ctm = fz_concat (p->zoomctm, ctm);
973 p->pagebox = p->mediabox;
974 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
975 p->pagebox.x1 -= p->pagebox.x0;
976 p->pagebox.y1 -= p->pagebox.y0;
977 p->pagebox.x0 = 0;
978 p->pagebox.y0 = 0;
979 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
980 p->ctm = ctm;
982 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
983 fz_scale (zoom, -zoom));
984 p->tctmready = 0;
987 do {
988 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
989 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
990 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
991 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
992 int boundw = x1 - x0;
993 int boundh = y1 - y0;
995 printd ("pdim %u %d %d %d", p->pageno, boundw, boundh, p->left);
996 } while (p-- != state.pagedims);
999 static struct pagedim *pdimofpageno (int pageno)
1001 struct pagedim *pdim = state.pagedims;
1003 for (int i = 0; i < state.pagedimcount; ++i) {
1004 if (state.pagedims[i].pageno > pageno) {
1005 break;
1007 pdim = &state.pagedims[i];
1009 return pdim;
1012 static void recurse_outline (fz_outline *outline, int level)
1014 while (outline) {
1015 if (outline->page >= 0) {
1016 fz_point p = {.x = outline->x, .y = outline->y};
1017 struct pagedim *pdim = pdimofpageno (outline->page);
1018 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1019 p = fz_transform_point (p, pdim->ctm);
1020 printd ("o %d %d %d %d %s",
1021 level, outline->page, (int) p.y, h, outline->title);
1023 else {
1024 printd ("on %d %s", level, outline->title);
1026 if (outline->down) {
1027 recurse_outline (outline->down, level + 1);
1029 outline = outline->next;
1033 static void process_outline (void)
1035 fz_outline *outline;
1037 if (!state.needoutline || !state.pagedimcount) {
1038 return;
1041 state.needoutline = 0;
1042 outline = fz_load_outline (state.ctx, state.doc);
1043 if (outline) {
1044 recurse_outline (outline, 0);
1045 fz_drop_outline (state.ctx, outline);
1049 static char *strofline (fz_stext_line *line)
1051 char *p;
1052 char utf8[10];
1053 fz_stext_char *ch;
1054 size_t size = 0, cap = 80;
1056 p = malloc (cap + 1);
1057 if (!p) {
1058 return NULL;
1061 for (ch = line->first_char; ch; ch = ch->next) {
1062 int n = fz_runetochar (utf8, ch->c);
1063 if (size + n > cap) {
1064 cap *= 2;
1065 p = realloc (p, cap + 1);
1066 if (!p) {
1067 return NULL;
1071 memcpy (p + size, utf8, n);
1072 size += n;
1074 p[size] = 0;
1075 return p;
1078 static int matchline (regex_t *re, fz_stext_line *line,
1079 int stop, int pageno, double start)
1081 int ret;
1082 char *p;
1083 regmatch_t rm;
1085 p = strofline (line);
1086 if (!p) {
1087 return -1;
1090 ret = regexec (re, p, 1, &rm, 0);
1091 if (ret) {
1092 free (p);
1093 if (ret != REG_NOMATCH) {
1094 int isize;
1095 size_t size;
1096 char errbuf[80], *trail;
1098 size = regerror (ret, re, errbuf, sizeof (errbuf));
1099 if (size > 23) {
1100 isize = 23;
1101 trail = "...";
1103 else {
1104 isize = size;
1105 trail = "";
1107 printd ("msg regexec error '%*s%s'", isize, errbuf, trail);
1108 return -1;
1110 return 0;
1112 else {
1113 fz_quad s, e;
1114 fz_stext_char *ch;
1115 int o = 0;
1117 for (ch = line->first_char; ch; ch = ch->next) {
1118 o += fz_runelen (ch->c);
1119 if (o > rm.rm_so) {
1120 s = ch->quad;
1121 break;
1124 for (;ch; ch = ch->next) {
1125 o += fz_runelen (ch->c);
1126 if (o > rm.rm_eo) {
1127 break;
1130 e = ch->quad;
1132 if (!stop) {
1133 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1134 pageno, 1,
1135 s.ul.x, s.ul.y,
1136 e.ur.x, s.ul.y,
1137 e.lr.x, e.lr.y,
1138 s.ul.x, e.lr.y);
1140 printd ("progress 1 found at %d `%.*s' in %f sec",
1141 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1142 now () - start);
1144 else {
1145 printd ("match %d %d %f %f %f %f %f %f %f %f",
1146 pageno, 2,
1147 s.ul.x, s.ul.y,
1148 e.ur.x, s.ul.y,
1149 e.lr.x, e.lr.y,
1150 s.ul.x, e.lr.y);
1152 free (p);
1153 return 1;
1157 /* wishful thinking function */
1158 static void search (regex_t *re, int pageno, int y, int forward)
1160 fz_device *tdev;
1161 fz_stext_page *text;
1162 struct pagedim *pdim;
1163 int stop = 0, niters = 0;
1164 double start, end;
1165 fz_page *page;
1166 fz_stext_block *block;
1168 start = now ();
1169 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1170 if (niters++ == 5) {
1171 niters = 0;
1172 if (hasdata ()) {
1173 printd ("progress 1 attention requested aborting search at %d",
1174 pageno);
1175 stop = 1;
1177 else {
1178 printd ("progress %f searching in page %d",
1179 (double) (pageno + 1) / state.pagecount,
1180 pageno);
1183 pdim = pdimofpageno (pageno);
1184 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1185 tdev = fz_new_stext_device (state.ctx, text, 0);
1187 page = fz_load_page (state.ctx, state.doc, pageno);
1188 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1190 fz_close_device (state.ctx, tdev);
1191 fz_drop_device (state.ctx, tdev);
1193 if (forward) {
1194 for (block = text->first_block; block; block = block->next) {
1195 fz_stext_line *line;
1197 if (block->type != FZ_STEXT_BLOCK_TEXT) {
1198 continue;
1201 for (line = block->u.t.first_line; line; line = line->next) {
1202 if (line->bbox.y0 < y + 1) {
1203 continue;
1206 switch (matchline (re, line, stop, pageno, start)) {
1207 case 0: break;
1208 case 1: stop = 1; break;
1209 case -1: stop = 1; goto endloop;
1214 else {
1215 for (block = text->last_block; block; block = block->prev) {
1216 fz_stext_line *line;
1218 if (block->type != FZ_STEXT_BLOCK_TEXT) {
1219 continue;
1222 for (line = block->u.t.last_line; line; line = line->prev) {
1223 if (line->bbox.y0 < y + 1) {
1224 continue;
1227 switch (matchline (re, line, stop, pageno, start)) {
1228 case 0: break;
1229 case 1: stop = 1; break;
1230 case -1: stop = 1; goto endloop;
1236 if (forward) {
1237 pageno += 1;
1238 y = 0;
1240 else {
1241 pageno -= 1;
1242 y = INT_MAX;
1244 endloop:
1245 fz_drop_stext_page (state.ctx, text);
1246 fz_drop_page (state.ctx, page);
1248 end = now ();
1249 if (!stop) {
1250 printd ("progress 1 no matches %f sec", end - start);
1252 printd ("clearrects");
1255 static void set_tex_params (int colorspace)
1257 switch (colorspace) {
1258 case 0:
1259 state.tex.iform = GL_RGBA8;
1260 state.tex.form = GL_RGBA;
1261 state.tex.ty = GL_UNSIGNED_BYTE;
1262 state.colorspace = fz_device_rgb (state.ctx);
1263 break;
1264 case 1:
1265 state.tex.iform = GL_LUMINANCE_ALPHA;
1266 state.tex.form = GL_LUMINANCE_ALPHA;
1267 state.tex.ty = GL_UNSIGNED_BYTE;
1268 state.colorspace = fz_device_gray (state.ctx);
1269 break;
1270 default:
1271 errx (1, "invalid colorspce %d", colorspace);
1275 static void realloctexts (int texcount)
1277 size_t size;
1279 if (texcount == state.tex.count) {
1280 return;
1283 if (texcount < state.tex.count) {
1284 glDeleteTextures (state.tex.count - texcount,
1285 state.tex.ids + texcount);
1288 size = texcount * (sizeof (*state.tex.ids) + sizeof (*state.tex.owners));
1289 state.tex.ids = realloc (state.tex.ids, size);
1290 if (!state.tex.ids) {
1291 err (1, "realloc texs %zu", size);
1294 state.tex.owners = (void *) (state.tex.ids + texcount);
1295 if (texcount > state.tex.count) {
1296 glGenTextures (texcount - state.tex.count,
1297 state.tex.ids + state.tex.count);
1298 for (int i = state.tex.count; i < texcount; ++i) {
1299 state.tex.owners[i].w = -1;
1300 state.tex.owners[i].slice = NULL;
1303 state.tex.count = texcount;
1304 state.tex.index = 0;
1307 static char *mbtoutf8 (char *s)
1309 char *p, *r;
1310 wchar_t *tmp;
1311 size_t i, ret, len;
1313 if (state.utf8cs) {
1314 return s;
1317 len = mbstowcs (NULL, s, strlen (s));
1318 if (len == 0 || len == (size_t) -1) {
1319 if (len) {
1320 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1322 return s;
1325 tmp = calloc (len, sizeof (wchar_t));
1326 if (!tmp) {
1327 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1328 len, sizeof (wchar_t), errno, strerror (errno));
1329 return s;
1332 ret = mbstowcs (tmp, s, len);
1333 if (ret == (size_t) -1) {
1334 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1335 len, errno, strerror (errno));
1336 free (tmp);
1337 return s;
1340 len = 0;
1341 for (i = 0; i < ret; ++i) {
1342 len += fz_runelen (tmp[i]);
1345 p = r = malloc (len + 1);
1346 if (!r) {
1347 printd ("emsg mbtoutf8: malloc(%zu)", len);
1348 free (tmp);
1349 return s;
1352 for (i = 0; i < ret; ++i) {
1353 p += fz_runetochar (p, tmp[i]);
1355 *p = 0;
1356 free (tmp);
1357 return r;
1360 ML (mbtoutf8 (value s_v))
1362 CAMLparam1 (s_v);
1363 CAMLlocal1 (ret_v);
1364 char *s, *r;
1366 s = &Byte (s_v, 0);
1367 r = mbtoutf8 (s);
1368 if (r == s) {
1369 ret_v = s_v;
1371 else {
1372 ret_v = caml_copy_string (r);
1373 free (r);
1375 CAMLreturn (ret_v);
1378 enum {
1379 Copen=23, Ccs, Cfreepage, Cfreetile, Csearch, Cgeometry,
1380 Creqlayout, Cpage, Ctile, Ctrimset, Csettrim, Csliceh, Cinterrupt
1383 static void *mainloop (void UNUSED_ATTR *unused)
1385 char *p = NULL, c;
1386 int len, ret, oldlen = 0;
1388 fz_var (p);
1389 fz_var (oldlen);
1390 for (;;) {
1391 len = readlen (state.csock);
1392 if (len == 0) {
1393 errx (1, "readlen returned 0");
1396 if (oldlen < len) {
1397 p = realloc (p, len);
1398 if (!p) {
1399 err (1, "realloc %d failed", len);
1401 oldlen = len;
1403 readdata (state.csock, p, len);
1404 c = p[len-1];
1405 p[len-1] = 0;
1407 switch (c) {
1408 case Copen: {
1409 int off, usedoccss, ok = 0, layouth;
1410 char *password;
1411 char *filename;
1412 char *utf8filename;
1413 size_t filenamelen;
1415 fz_var (ok);
1416 ret = sscanf (p, "%d %d %n", &usedoccss, &layouth, &off);
1417 if (ret != 2) {
1418 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1421 filename = p + off;
1422 filenamelen = strlen (filename);
1423 password = filename + filenamelen + 1;
1425 if (password[strlen (password) + 1]) {
1426 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1429 lock ("open");
1430 fz_set_use_document_css (state.ctx, usedoccss);
1431 fz_try (state.ctx) {
1432 ok = openxref (filename, password, layouth);
1434 fz_catch (state.ctx) {
1435 utf8filename = mbtoutf8 (filename);
1436 printd ("emsg Error loading %s: %s",
1437 utf8filename, fz_caught_message (state.ctx));
1438 if (utf8filename != filename) {
1439 free (utf8filename);
1442 if (ok) {
1443 docinfo ();
1444 initpdims ();
1446 unlock ("open");
1447 state.needoutline = ok;
1448 break;
1450 case Ccs: {
1451 int i, colorspace;
1453 ret = sscanf (p, "%d", &colorspace);
1454 if (ret != 1) {
1455 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1457 lock ("cs");
1458 set_tex_params (colorspace);
1459 for (i = 0; i < state.tex.count; ++i) {
1460 state.tex.owners[i].w = -1;
1461 state.tex.owners[i].slice = NULL;
1463 unlock ("cs");
1464 break;
1466 case Cfreepage: {
1467 void *ptr;
1469 ret = sscanf (p, "%" SCNxPTR, (uintptr_t *) &ptr);
1470 if (ret != 1) {
1471 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1473 lock ("freepage");
1474 freepage (ptr);
1475 unlock ("freepage");
1476 break;
1478 case Cfreetile: {
1479 void *ptr;
1481 ret = sscanf (p, "%" SCNxPTR, (uintptr_t *) &ptr);
1482 if (ret != 1) {
1483 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1485 lock ("freetile");
1486 freetile (ptr);
1487 unlock ("freetile");
1488 break;
1490 case Csearch: {
1491 int icase, pageno, y, len2, forward;
1492 char *pattern;
1493 regex_t re;
1495 ret = sscanf (p, "%d %d %d %d,%n",
1496 &icase, &pageno, &y, &forward, &len2);
1497 if (ret != 4) {
1498 errx (1, "malformed search `%s' ret=%d", p, ret);
1501 pattern = p + len2;
1502 ret = regcomp (&re, pattern,
1503 REG_EXTENDED | (icase ? REG_ICASE : 0));
1504 if (ret) {
1505 char errbuf[80];
1506 size_t size;
1508 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1509 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1511 else {
1512 lock ("search");
1513 search (&re, pageno, y, forward);
1514 unlock ("search");
1515 regfree (&re);
1517 break;
1519 case Cgeometry: {
1520 int w, h, fitmodel;
1522 printd ("clear");
1523 ret = sscanf (p, "%d %d %d", &w, &h, &fitmodel);
1524 if (ret != 3) {
1525 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1528 lock ("geometry");
1529 state.h = h;
1530 if (w != state.w) {
1531 state.w = w;
1532 for (int i = 0; i < state.tex.count; ++i) {
1533 state.tex.owners[i].slice = NULL;
1536 state.fitmodel = fitmodel;
1537 layout ();
1538 process_outline ();
1540 state.gen++;
1541 unlock ("geometry");
1542 printd ("continue %d", state.pagecount);
1543 break;
1545 case Creqlayout: {
1546 char *nameddest;
1547 int rotate, off, h;
1548 int fitmodel;
1549 pdf_document *pdf;
1551 printd ("clear");
1552 ret = sscanf (p, "%d %d %d %n", &rotate, &fitmodel, &h, &off);
1553 if (ret != 3) {
1554 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1556 lock ("reqlayout");
1557 pdf = pdf_specifics (state.ctx, state.doc);
1558 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1559 state.gen += 1;
1561 state.rotate = rotate;
1562 state.fitmodel = fitmodel;
1563 state.h = h;
1564 layout ();
1565 process_outline ();
1567 nameddest = p + off;
1568 if (pdf && nameddest && *nameddest) {
1569 fz_point xy;
1570 struct pagedim *pdim;
1571 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1572 &xy.x, &xy.y);
1573 pdim = pdimofpageno (pageno);
1574 xy = fz_transform_point (xy, pdim->ctm);
1575 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1578 state.gen++;
1579 unlock ("reqlayout");
1580 printd ("continue %d", state.pagecount);
1581 break;
1583 case Cpage: {
1584 double a, b;
1585 struct page *page;
1586 int pageno, pindex;
1588 ret = sscanf (p, "%d %d", &pageno, &pindex);
1589 if (ret != 2) {
1590 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1593 lock ("page");
1594 a = now ();
1595 page = loadpage (pageno, pindex);
1596 b = now ();
1597 unlock ("page");
1599 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1600 break;
1602 case Ctile: {
1603 int x, y, w, h;
1604 struct page *page;
1605 struct tile *tile;
1606 double a, b;
1607 void *data;
1609 ret = sscanf (p, "%" SCNxPTR " %d %d %d %d %" SCNxPTR,
1610 (uintptr_t *) &page, &x, &y, &w, &h,
1611 (uintptr_t *) &data);
1612 if (ret != 6) {
1613 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1616 lock ("tile");
1617 a = now ();
1618 tile = rendertile (page, x, y, w, h, data);
1619 b = now ();
1620 unlock ("tile");
1622 printd ("tile %d %d %" PRIxPTR " %u %f",
1623 x, y, (uintptr_t) (tile),
1624 tile->w * tile->h * tile->pixmap->n,
1625 b - a);
1626 break;
1628 case Ctrimset: {
1629 fz_irect fuzz;
1630 int trimmargins;
1632 ret = sscanf (p, "%d %d %d %d %d",
1633 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1634 if (ret != 5) {
1635 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1638 lock ("trimset");
1639 state.trimmargins = trimmargins;
1640 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1641 state.trimanew = 1;
1642 state.trimfuzz = fuzz;
1644 unlock ("trimset");
1645 break;
1647 case Csettrim: {
1648 fz_irect fuzz;
1649 int trimmargins;
1651 ret = sscanf (p, "%d %d %d %d %d",
1652 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1653 if (ret != 5) {
1654 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1656 printd ("clear");
1657 lock ("settrim");
1658 state.trimmargins = trimmargins;
1659 state.needoutline = 1;
1660 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1661 state.trimanew = 1;
1662 state.trimfuzz = fuzz;
1664 state.pagedimcount = 0;
1665 free (state.pagedims);
1666 state.pagedims = NULL;
1667 initpdims ();
1668 layout ();
1669 process_outline ();
1670 unlock ("settrim");
1671 printd ("continue %d", state.pagecount);
1672 break;
1674 case Csliceh: {
1675 int h;
1677 ret = sscanf (p, "%d", &h);
1678 if (ret != 1) {
1679 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1681 if (h != state.sliceheight) {
1682 state.sliceheight = h;
1683 for (int i = 0; i < state.tex.count; ++i) {
1684 state.tex.owners[i].w = -1;
1685 state.tex.owners[i].h = -1;
1686 state.tex.owners[i].slice = NULL;
1689 break;
1691 case Cinterrupt:
1692 printd ("vmsg interrupted");
1693 break;
1694 default:
1695 errx (1, "unknown command - %d [%.*s]", c, len, p);
1698 return 0;
1701 ML (isexternallink (value uri_v))
1703 CAMLparam1 (uri_v);
1704 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1705 CAMLreturn (Val_bool (ext));
1708 ML (uritolocation (value uri_v))
1710 CAMLparam1 (uri_v);
1711 CAMLlocal1 (ret_v);
1712 int pageno;
1713 fz_point xy;
1714 struct pagedim *pdim;
1716 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1717 &xy.x, &xy.y).page;
1718 pdim = pdimofpageno (pageno);
1719 xy = fz_transform_point (xy, pdim->ctm);
1720 ret_v = caml_alloc_tuple (3);
1721 Field (ret_v, 0) = Val_int (pageno);
1722 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1723 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1724 CAMLreturn (ret_v);
1727 ML (realloctexts (value texcount_v))
1729 CAMLparam1 (texcount_v);
1730 int ok;
1732 if (trylock (__func__)) {
1733 ok = 0;
1734 goto done;
1736 realloctexts (Int_val (texcount_v));
1737 ok = 1;
1738 unlock (__func__);
1740 done:
1741 CAMLreturn (Val_bool (ok));
1744 static void recti (int x0, int y0, int x1, int y1)
1746 GLfloat *v = state.vertices;
1748 glVertexPointer (2, GL_FLOAT, 0, v);
1749 v[0] = x0; v[1] = y0;
1750 v[2] = x1; v[3] = y0;
1751 v[4] = x0; v[5] = y1;
1752 v[6] = x1; v[7] = y1;
1753 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1756 static void showsel (struct page *page, int ox, int oy)
1758 fz_irect bbox;
1759 fz_rect rect;
1760 fz_stext_block *block;
1761 int seen = 0;
1762 unsigned char selcolor[] = {15,15,15,140};
1764 if (!page->fmark || !page->lmark) {
1765 return;
1768 glEnable (GL_BLEND);
1769 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1770 glColor4ubv (selcolor);
1772 ox += state.pagedims[page->pdimno].bounds.x0;
1773 oy += state.pagedims[page->pdimno].bounds.y0;
1775 for (block = page->text->first_block; block; block = block->next) {
1776 fz_stext_line *line;
1778 if (block->type != FZ_STEXT_BLOCK_TEXT) {
1779 continue;
1781 for (line = block->u.t.first_line; line; line = line->next) {
1782 fz_stext_char *ch;
1784 rect = fz_empty_rect;
1785 for (ch = line->first_char; ch; ch = ch->next) {
1786 fz_rect r;
1787 if (ch == page->fmark) {
1788 seen = 1;
1790 r = fz_rect_from_quad (ch->quad);
1791 if (seen) {
1792 rect = fz_union_rect (rect, r);
1794 if (ch == page->lmark) {
1795 bbox = fz_round_rect (rect);
1796 recti (bbox.x0 + ox, bbox.y0 + oy,
1797 bbox.x1 + ox, bbox.y1 + oy);
1798 goto done;
1801 if (!fz_is_empty_rect (rect)) {
1802 bbox = fz_round_rect (rect);
1803 recti (bbox.x0 + ox, bbox.y0 + oy,
1804 bbox.x1 + ox, bbox.y1 + oy);
1808 done:
1809 glDisable (GL_BLEND);
1812 #pragma GCC diagnostic push
1813 #pragma GCC diagnostic ignored "-Wconversion"
1814 #include "glfont.c"
1815 #pragma GCC diagnostic pop
1817 static void stipplerect (fz_matrix m,
1818 fz_point p1,
1819 fz_point p2,
1820 fz_point p3,
1821 fz_point p4,
1822 GLfloat *texcoords,
1823 GLfloat *vertices)
1825 p1 = fz_transform_point (p1, m);
1826 p2 = fz_transform_point (p2, m);
1827 p3 = fz_transform_point (p3, m);
1828 p4 = fz_transform_point (p4, m);
1830 float w, h, s, t;
1832 w = p2.x - p1.x;
1833 h = p2.y - p1.y;
1834 t = hypotf (w, h) * .25f;
1836 w = p3.x - p2.x;
1837 h = p3.y - p2.y;
1838 s = hypotf (w, h) * .25f;
1840 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1841 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1843 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1844 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1846 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1847 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1849 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1850 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1852 glDrawArrays (GL_LINES, 0, 8);
1855 static void solidrect (fz_matrix m,
1856 fz_point p1,
1857 fz_point p2,
1858 fz_point p3,
1859 fz_point p4,
1860 GLfloat *vertices)
1862 p1 = fz_transform_point (p1, m);
1863 p2 = fz_transform_point (p2, m);
1864 p3 = fz_transform_point (p3, m);
1865 p4 = fz_transform_point (p4, m);
1866 vertices[0] = p1.x; vertices[1] = p1.y;
1867 vertices[2] = p2.x; vertices[3] = p2.y;
1869 vertices[4] = p3.x; vertices[5] = p3.y;
1870 vertices[6] = p4.x; vertices[7] = p4.y;
1871 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1874 static void ensurelinks (struct page *page)
1876 if (!page->links) {
1877 page->links = fz_load_links (state.ctx, page->fzpage);
1881 static void highlightlinks (struct page *page, int xoff, int yoff)
1883 fz_matrix ctm;
1884 fz_link *link;
1885 GLfloat *texcoords = state.texcoords;
1886 GLfloat *vertices = state.vertices;
1888 ensurelinks (page);
1890 glEnable (GL_TEXTURE_1D);
1891 glEnable (GL_BLEND);
1892 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1893 glBindTexture (GL_TEXTURE_1D, state.stid);
1895 xoff -= state.pagedims[page->pdimno].bounds.x0;
1896 yoff -= state.pagedims[page->pdimno].bounds.y0;
1897 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1899 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1900 glVertexPointer (2, GL_FLOAT, 0, vertices);
1902 for (link = page->links; link; link = link->next) {
1903 fz_point p1, p2, p3, p4;
1905 p1.x = link->rect.x0;
1906 p1.y = link->rect.y0;
1908 p2.x = link->rect.x1;
1909 p2.y = link->rect.y0;
1911 p3.x = link->rect.x1;
1912 p3.y = link->rect.y1;
1914 p4.x = link->rect.x0;
1915 p4.y = link->rect.y1;
1917 /* TODO: different colours for different schemes */
1918 if (fz_is_external_link (state.ctx, link->uri)) {
1919 glColor3ub (0, 0, 255);
1921 else {
1922 glColor3ub (255, 0, 0);
1925 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1928 for (int i = 0; i < page->annotcount; ++i) {
1929 fz_point p1, p2, p3, p4;
1930 struct annot *annot = &page->annots[i];
1932 p1.x = annot->bbox.x0;
1933 p1.y = annot->bbox.y0;
1935 p2.x = annot->bbox.x1;
1936 p2.y = annot->bbox.y0;
1938 p3.x = annot->bbox.x1;
1939 p3.y = annot->bbox.y1;
1941 p4.x = annot->bbox.x0;
1942 p4.y = annot->bbox.y1;
1944 glColor3ub (0, 0, 128);
1945 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1948 glDisable (GL_BLEND);
1949 glDisable (GL_TEXTURE_1D);
1952 static int compareslinks (const void *l, const void *r)
1954 struct slink const *ls = l;
1955 struct slink const *rs = r;
1956 if (ls->bbox.y0 == rs->bbox.y0) {
1957 return ls->bbox.x0 - rs->bbox.x0;
1959 return ls->bbox.y0 - rs->bbox.y0;
1962 static void droptext (struct page *page)
1964 if (page->text) {
1965 fz_drop_stext_page (state.ctx, page->text);
1966 page->fmark = NULL;
1967 page->lmark = NULL;
1968 page->text = NULL;
1972 static void dropannots (struct page *page)
1974 if (page->annots) {
1975 free (page->annots);
1976 page->annots = NULL;
1977 page->annotcount = 0;
1981 static void ensureannots (struct page *page)
1983 int i, count = 0;
1984 size_t annotsize = sizeof (*page->annots);
1985 pdf_annot *annot;
1986 pdf_document *pdf;
1987 pdf_page *pdfpage;
1989 pdf = pdf_specifics (state.ctx, state.doc);
1990 if (!pdf) {
1991 return;
1994 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1995 if (state.gen != page->agen) {
1996 dropannots (page);
1997 page->agen = state.gen;
1999 if (page->annots) {
2000 return;
2003 for (annot = pdf_first_annot (state.ctx, pdfpage);
2004 annot;
2005 annot = pdf_next_annot (state.ctx, annot)) {
2006 count++;
2009 if (count > 0) {
2010 page->annotcount = count;
2011 page->annots = calloc (count, annotsize);
2012 if (!page->annots) {
2013 err (1, "calloc annots %d", count);
2016 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
2017 annot;
2018 annot = pdf_next_annot (state.ctx, annot), i++) {
2019 fz_rect rect;
2021 rect = pdf_bound_annot (state.ctx, annot);
2022 page->annots[i].annot = annot;
2023 page->annots[i].bbox = fz_round_rect (rect);
2028 static void dropslinks (struct page *page)
2030 if (page->slinks) {
2031 free (page->slinks);
2032 page->slinks = NULL;
2033 page->slinkcount = 0;
2035 if (page->links) {
2036 fz_drop_link (state.ctx, page->links);
2037 page->links = NULL;
2041 static void ensureslinks (struct page *page)
2043 fz_matrix ctm;
2044 int i, count;
2045 size_t slinksize = sizeof (*page->slinks);
2046 fz_link *link;
2048 ensureannots (page);
2049 if (state.gen != page->sgen) {
2050 dropslinks (page);
2051 page->sgen = state.gen;
2053 if (page->slinks) {
2054 return;
2057 ensurelinks (page);
2058 ctm = pagectm (page);
2060 count = page->annotcount;
2061 for (link = page->links; link; link = link->next) {
2062 count++;
2064 if (count > 0) {
2065 int j;
2067 page->slinkcount = count;
2068 page->slinks = calloc (count, slinksize);
2069 if (!page->slinks) {
2070 err (1, "calloc slinks %d", count);
2073 for (i = 0, link = page->links; link; ++i, link = link->next) {
2074 fz_rect rect;
2076 rect = link->rect;
2077 rect = fz_transform_rect (rect, ctm);
2078 page->slinks[i].tag = SLINK;
2079 page->slinks[i].u.link = link;
2080 page->slinks[i].bbox = fz_round_rect (rect);
2082 for (j = 0; j < page->annotcount; ++j, ++i) {
2083 fz_rect rect;
2084 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
2085 rect = fz_transform_rect (rect, ctm);
2086 page->slinks[i].bbox = fz_round_rect (rect);
2088 page->slinks[i].tag = SANNOT;
2089 page->slinks[i].u.annot = page->annots[j].annot;
2091 qsort (page->slinks, count, slinksize, compareslinks);
2095 static void highlightslinks (struct page *page, int xoff, int yoff,
2096 int noff, const char *targ, unsigned int tlen,
2097 const char *chars, unsigned int clen, int hfsize)
2099 char buf[40];
2100 struct slink *slink;
2101 float x0, y0, x1, y1, w;
2103 ensureslinks (page);
2104 glColor3ub (0xc3, 0xb0, 0x91);
2105 for (int i = 0; i < page->slinkcount; ++i) {
2106 fmt_linkn (buf, chars, clen, i + noff);
2107 if (!tlen || !strncmp (targ, buf, tlen)) {
2108 slink = &page->slinks[i];
2110 x0 = slink->bbox.x0 + xoff - 5;
2111 y1 = slink->bbox.y0 + yoff - 5;
2112 y0 = y1 + 10 + hfsize;
2113 w = measure_string (state.face, hfsize, buf);
2114 x1 = x0 + w + 10;
2115 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2119 glEnable (GL_BLEND);
2120 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2121 glEnable (GL_TEXTURE_2D);
2122 glColor3ub (0, 0, 0);
2123 for (int i = 0; i < page->slinkcount; ++i) {
2124 fmt_linkn (buf, chars, clen, i + noff);
2125 if (!tlen || !strncmp (targ, buf, tlen)) {
2126 slink = &page->slinks[i];
2128 x0 = slink->bbox.x0 + xoff;
2129 y0 = slink->bbox.y0 + yoff + hfsize;
2130 draw_string (state.face, hfsize, x0, y0, buf);
2133 glDisable (GL_TEXTURE_2D);
2134 glDisable (GL_BLEND);
2137 static void uploadslice (struct tile *tile, struct slice *slice)
2139 int offset;
2140 struct slice *slice1;
2141 unsigned char *texdata;
2143 offset = 0;
2144 for (slice1 = tile->slices; slice != slice1; slice1++) {
2145 offset += slice1->h * tile->w * tile->pixmap->n;
2147 if (slice->texindex != -1 && slice->texindex < state.tex.count
2148 && state.tex.owners[slice->texindex].slice == slice) {
2149 glBindTexture (TEXT_TYPE, state.tex.ids[slice->texindex]);
2151 else {
2152 int subimage = 0;
2153 int texindex = state.tex.index++ % state.tex.count;
2155 if (state.tex.owners[texindex].w == tile->w) {
2156 if (state.tex.owners[texindex].h >= slice->h) {
2157 subimage = 1;
2159 else {
2160 state.tex.owners[texindex].h = slice->h;
2163 else {
2164 state.tex.owners[texindex].h = slice->h;
2167 state.tex.owners[texindex].w = tile->w;
2168 state.tex.owners[texindex].slice = slice;
2169 slice->texindex = texindex;
2171 glBindTexture (TEXT_TYPE, state.tex.ids[texindex]);
2172 #if TEXT_TYPE == GL_TEXTURE_2D
2173 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2174 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2175 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2176 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2177 #endif
2178 if (tile->pbo) {
2179 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2180 texdata = 0;
2182 else {
2183 texdata = tile->pixmap->samples;
2185 if (subimage) {
2186 glTexSubImage2D (TEXT_TYPE, 0, 0, 0, tile->w, slice->h,
2187 state.tex.form, state.tex.ty, texdata+offset );
2189 else {
2190 glTexImage2D (TEXT_TYPE, 0, state.tex.iform, tile->w, slice->h,
2191 0, state.tex.form, state.tex.ty, texdata+offset);
2194 if (tile->pbo) {
2195 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2200 ML0 (begintiles (void))
2202 glEnable (TEXT_TYPE);
2203 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2204 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2207 ML0 (endtiles (void))
2209 glDisable (TEXT_TYPE);
2212 ML0 (drawtile (value args_v, value ptr_v))
2214 CAMLparam2 (args_v, ptr_v);
2215 int dispx = Int_val (Field (args_v, 0));
2216 int dispy = Int_val (Field (args_v, 1));
2217 int dispw = Int_val (Field (args_v, 2));
2218 int disph = Int_val (Field (args_v, 3));
2219 int tilex = Int_val (Field (args_v, 4));
2220 int tiley = Int_val (Field (args_v, 5));
2221 struct tile *tile = parse_pointer (__func__, String_val (ptr_v));
2222 int slicey, firstslice;
2223 struct slice *slice;
2224 GLfloat *texcoords = state.texcoords;
2225 GLfloat *vertices = state.vertices;
2227 firstslice = tiley / tile->sliceheight;
2228 slice = &tile->slices[firstslice];
2229 slicey = tiley % tile->sliceheight;
2231 while (disph > 0) {
2232 int dh;
2234 dh = slice->h - slicey;
2235 dh = fz_mini (disph, dh);
2236 uploadslice (tile, slice);
2238 texcoords[0] = tilex; texcoords[1] = slicey;
2239 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2240 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2241 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2243 vertices[0] = dispx; vertices[1] = dispy;
2244 vertices[2] = dispx+dispw; vertices[3] = dispy;
2245 vertices[4] = dispx; vertices[5] = dispy+dh;
2246 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2248 #if TEXT_TYPE == GL_TEXTURE_2D
2249 for (int i = 0; i < 8; ++i) {
2250 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2252 #endif
2254 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2255 dispy += dh;
2256 disph -= dh;
2257 slice++;
2258 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2259 slicey = 0;
2261 CAMLreturn0;
2264 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2266 fz_matrix ctm;
2267 fz_point p1, p2, p3, p4;
2268 GLfloat *vertices = state.vertices;
2270 xoff -= state.pagedims[page->pdimno].bounds.x0;
2271 yoff -= state.pagedims[page->pdimno].bounds.y0;
2272 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2274 glEnable (GL_BLEND);
2275 glVertexPointer (2, GL_FLOAT, 0, vertices);
2277 glColor4d (
2278 Double_array_field (rects_v, 0),
2279 Double_array_field (rects_v, 1),
2280 Double_array_field (rects_v, 2),
2281 Double_array_field (rects_v, 3)
2283 p1.x = (float) Double_array_field (rects_v, 4);
2284 p1.y = (float) Double_array_field (rects_v, 5);
2286 p2.x = (float) Double_array_field (rects_v, 6);
2287 p2.y = p1.y;
2289 p3.x = p2.x;
2290 p3.y = (float) Double_array_field (rects_v, 7);
2292 p4.x = p1.x;
2293 p4.y = p3.y;
2294 solidrect (ctm, p1, p2, p3, p4, vertices);
2295 glDisable (GL_BLEND);
2298 ML (postprocess (value ptr_v, value hlinks_v,
2299 value xoff_v, value yoff_v,
2300 value li_v))
2302 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2303 int xoff = Int_val (xoff_v);
2304 int yoff = Int_val (yoff_v);
2305 int noff = Int_val (Field (li_v, 0));
2306 const char *targ = String_val (Field (li_v, 1));
2307 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2308 int hfsize = Int_val (Field (li_v, 2));
2309 const char *chars = String_val (Field (li_v, 3));
2310 mlsize_t clen = caml_string_length (Field (li_v, 3));
2311 int hlmask = Int_val (hlinks_v);
2312 struct page *page = parse_pointer (__func__, String_val (ptr_v));
2314 if (!page->fzpage) {
2315 /* deal with loadpage failed pages */
2316 goto done;
2319 if (trylock (__func__)) {
2320 noff = -1;
2321 goto done;
2324 ensureannots (page);
2325 if (hlmask & 1) {
2326 highlightlinks (page, xoff, yoff);
2328 if (hlmask & 2) {
2329 highlightslinks (page, xoff, yoff, noff, targ, STTI (tlen),
2330 chars, STTI (clen), hfsize);
2331 noff = page->slinkcount;
2333 if (page->tgen == state.gen) {
2334 showsel (page, xoff, yoff);
2336 unlock (__func__);
2338 done:
2339 CAMLreturn (Val_int (noff));
2342 ML0 (drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v))
2344 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2345 int xoff = Int_val (xoff_v);
2346 int yoff = Int_val (yoff_v);
2347 struct page *page = parse_pointer (__func__, String_val (ptr_v));
2349 drawprect (page, xoff, yoff, rects_v);
2350 CAMLreturn0;
2353 static struct annot *getannot (struct page *page, int x, int y)
2355 fz_point p;
2356 fz_matrix ctm;
2357 const fz_matrix *tctm;
2358 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2360 if (!page->annots) {
2361 return NULL;
2364 if (pdf) {
2365 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2366 tctm = &state.pagedims[page->pdimno].tctm;
2368 else {
2369 tctm = &fz_identity;
2372 p.x = x;
2373 p.y = y;
2375 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2376 ctm = fz_invert_matrix (ctm);
2377 p = fz_transform_point (p, ctm);
2379 if (pdf) {
2380 for (int i = 0; i < page->annotcount; ++i) {
2381 struct annot *a = &page->annots[i];
2382 if (fz_is_point_inside_rect (p, pdf_bound_annot (state.ctx,
2383 a->annot))) {
2384 return a;
2388 return NULL;
2391 static fz_link *getlink (struct page *page, int x, int y)
2393 fz_point p;
2394 fz_link *link;
2396 ensureslinks (page);
2398 p.x = x;
2399 p.y = y;
2401 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2403 for (link = page->links; link; link = link->next) {
2404 if (fz_is_point_inside_rect (p, link->rect)) {
2405 return link;
2408 return NULL;
2411 static void ensuretext (struct page *page)
2413 if (state.gen != page->tgen) {
2414 droptext (page);
2415 page->tgen = state.gen;
2417 if (!page->text) {
2418 fz_device *tdev;
2420 page->text = fz_new_stext_page (state.ctx,
2421 state.pagedims[page->pdimno].mediabox);
2422 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2423 fz_run_display_list (state.ctx, page->dlist,
2424 tdev, pagectm (page), fz_infinite_rect, NULL);
2425 fz_close_device (state.ctx, tdev);
2426 fz_drop_device (state.ctx, tdev);
2430 ML (find_page_with_links (value start_page_v, value dir_v))
2432 CAMLparam2 (start_page_v, dir_v);
2433 CAMLlocal1 (ret_v);
2434 int i, dir = Int_val (dir_v);
2435 int start_page = Int_val (start_page_v);
2436 int end_page = dir > 0 ? state.pagecount : -1;
2437 pdf_document *pdf;
2439 fz_var (end_page);
2440 ret_v = Val_int (0);
2441 lock (__func__);
2442 pdf = pdf_specifics (state.ctx, state.doc);
2443 for (i = start_page + dir; i != end_page; i += dir) {
2444 int found;
2446 fz_var (found);
2447 if (pdf) {
2448 pdf_page *page = NULL;
2450 fz_var (page);
2451 fz_try (state.ctx) {
2452 page = pdf_load_page (state.ctx, pdf, i);
2453 found = !!page->links || !!page->annots;
2455 fz_catch (state.ctx) {
2456 found = 0;
2458 if (page) {
2459 fz_drop_page (state.ctx, &page->super);
2462 else {
2463 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2464 fz_link *link = fz_load_links (state.ctx, page);
2465 found = !!link;
2466 fz_drop_link (state.ctx, link);
2467 fz_drop_page (state.ctx, page);
2470 if (found) {
2471 ret_v = caml_alloc_small (1, 1);
2472 Field (ret_v, 0) = Val_int (i);
2473 goto unlock;
2476 unlock:
2477 unlock (__func__);
2478 CAMLreturn (ret_v);
2481 enum { dir_first, dir_last };
2482 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2484 ML (findlink (value ptr_v, value dir_v))
2486 CAMLparam2 (ptr_v, dir_v);
2487 CAMLlocal2 (ret_v, pos_v);
2488 struct page *page;
2489 int dirtag, i, slinkindex;
2490 struct slink *found = NULL ,*slink;
2492 page = parse_pointer (__func__, String_val (ptr_v));
2493 ret_v = Val_int (0);
2494 lock (__func__);
2495 ensureslinks (page);
2497 if (Is_block (dir_v)) {
2498 dirtag = Tag_val (dir_v);
2499 switch (dirtag) {
2500 case dir_first_visible:
2502 int x0, y0, dir, first_index, last_index;
2504 pos_v = Field (dir_v, 0);
2505 x0 = Int_val (Field (pos_v, 0));
2506 y0 = Int_val (Field (pos_v, 1));
2507 dir = Int_val (Field (pos_v, 2));
2509 if (dir >= 0) {
2510 dir = 1;
2511 first_index = 0;
2512 last_index = page->slinkcount;
2514 else {
2515 first_index = page->slinkcount - 1;
2516 last_index = -1;
2519 for (i = first_index; i != last_index; i += dir) {
2520 slink = &page->slinks[i];
2521 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2522 found = slink;
2523 break;
2527 break;
2529 case dir_left:
2530 slinkindex = Int_val (Field (dir_v, 0));
2531 found = &page->slinks[slinkindex];
2532 for (i = slinkindex - 1; i >= 0; --i) {
2533 slink = &page->slinks[i];
2534 if (slink->bbox.x0 < found->bbox.x0) {
2535 found = slink;
2536 break;
2539 break;
2541 case dir_right:
2542 slinkindex = Int_val (Field (dir_v, 0));
2543 found = &page->slinks[slinkindex];
2544 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2545 slink = &page->slinks[i];
2546 if (slink->bbox.x0 > found->bbox.x0) {
2547 found = slink;
2548 break;
2551 break;
2553 case dir_down:
2554 slinkindex = Int_val (Field (dir_v, 0));
2555 found = &page->slinks[slinkindex];
2556 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2557 slink = &page->slinks[i];
2558 if (slink->bbox.y0 >= found->bbox.y0) {
2559 found = slink;
2560 break;
2563 break;
2565 case dir_up:
2566 slinkindex = Int_val (Field (dir_v, 0));
2567 found = &page->slinks[slinkindex];
2568 for (i = slinkindex - 1; i >= 0; --i) {
2569 slink = &page->slinks[i];
2570 if (slink->bbox.y0 <= found->bbox.y0) {
2571 found = slink;
2572 break;
2575 break;
2578 else {
2579 dirtag = Int_val (dir_v);
2580 switch (dirtag) {
2581 case dir_first:
2582 found = page->slinks;
2583 break;
2585 case dir_last:
2586 if (page->slinks) {
2587 found = page->slinks + (page->slinkcount - 1);
2589 break;
2592 if (found) {
2593 ret_v = caml_alloc_small (2, 1);
2594 Field (ret_v, 0) = Val_int (found - page->slinks);
2597 unlock (__func__);
2598 CAMLreturn (ret_v);
2601 enum { uuri, utext, uannot, unone };
2603 ML (getlink (value ptr_v, value n_v))
2605 CAMLparam2 (ptr_v, n_v);
2606 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2607 fz_link *link;
2608 struct page *page;
2609 struct slink *slink;
2611 ret_v = Val_int (0);
2612 page = parse_pointer (__func__, String_val (ptr_v));
2614 lock (__func__);
2615 ensureslinks (page);
2616 slink = &page->slinks[Int_val (n_v)];
2617 if (slink->tag == SLINK) {
2618 link = slink->u.link;
2619 str_v = caml_copy_string (link->uri);
2620 ret_v = caml_alloc_small (1, uuri);
2621 Field (ret_v, 0) = str_v;
2623 else {
2624 ret_v = caml_alloc_small (1, uannot);
2625 tup_v = caml_alloc_tuple (2);
2626 Field (ret_v, 0) = tup_v;
2627 Field (tup_v, 0) = ptr_v;
2628 Field (tup_v, 1) = n_v;
2630 unlock (__func__);
2632 CAMLreturn (ret_v);
2635 ML (getlinkn (value ptr_v, value c_v, value n_v, value noff_v))
2637 CAMLparam4 (ptr_v, c_v, n_v, noff_v);
2638 CAMLlocal1 (ret_v);
2639 char buf[40];
2640 struct page *page;
2641 const char *c = String_val (c_v);
2642 const char *n = String_val (n_v);
2643 mlsize_t clen = caml_string_length (c_v);
2644 page = parse_pointer (__func__, String_val (ptr_v));
2646 lock (__func__);
2647 ensureslinks (page);
2649 ret_v = Val_int (-page->slinkcount);
2650 for (int i = 0; i < page->slinkcount; ++i) {
2651 fmt_linkn (buf, c, STTI (clen), i - Int_val (noff_v));
2652 if (!strncmp (buf, n, clen)) {
2653 ret_v = Val_int (i);
2654 break;
2658 unlock (__func__);
2659 CAMLreturn (ret_v);
2662 ML (getannotcontents (value ptr_v, value n_v))
2664 CAMLparam2 (ptr_v, n_v);
2665 CAMLlocal1 (ret_v);
2666 pdf_document *pdf;
2667 const char *contents = "";
2669 lock (__func__);
2670 pdf = pdf_specifics (state.ctx, state.doc);
2671 if (pdf) {
2672 struct page *page;
2673 struct slink *slink;
2675 page = parse_pointer (__func__, String_val (ptr_v));
2676 slink = &page->slinks[Int_val (n_v)];
2677 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2679 unlock (__func__);
2680 ret_v = caml_copy_string (contents);
2681 CAMLreturn (ret_v);
2684 ML (getlinkrect (value ptr_v, value n_v))
2686 CAMLparam2 (ptr_v, n_v);
2687 CAMLlocal1 (ret_v);
2688 struct page *page;
2689 struct slink *slink;
2691 page = parse_pointer (__func__, String_val (ptr_v));
2692 ret_v = caml_alloc_tuple (4);
2693 lock (__func__);
2694 ensureslinks (page);
2696 slink = &page->slinks[Int_val (n_v)];
2697 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2698 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2699 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2700 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2701 unlock (__func__);
2702 CAMLreturn (ret_v);
2705 ML (whatsunder (value ptr_v, value x_v, value y_v))
2707 CAMLparam3 (ptr_v, x_v, y_v);
2708 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2709 fz_link *link;
2710 struct annot *annot;
2711 struct page *page;
2712 const char *ptr = String_val (ptr_v);
2713 int x = Int_val (x_v), y = Int_val (y_v);
2714 struct pagedim *pdim;
2716 ret_v = Val_int (0);
2717 if (trylock (__func__)) {
2718 goto done;
2721 page = parse_pointer (__func__, ptr);
2722 pdim = &state.pagedims[page->pdimno];
2723 x += pdim->bounds.x0;
2724 y += pdim->bounds.y0;
2727 annot = getannot (page, x, y);
2728 if (annot) {
2729 int i, n = -1;
2731 ensureslinks (page);
2732 for (i = 0; i < page->slinkcount; ++i) {
2733 if (page->slinks[i].tag == SANNOT
2734 && page->slinks[i].u.annot == annot->annot) {
2735 n = i;
2736 break;
2739 ret_v = caml_alloc_small (1, uannot);
2740 tup_v = caml_alloc_tuple (2);
2741 Field (ret_v, 0) = tup_v;
2742 Field (tup_v, 0) = ptr_v;
2743 Field (tup_v, 1) = Val_int (n);
2744 goto unlock;
2748 link = getlink (page, x, y);
2749 if (link) {
2750 str_v = caml_copy_string (link->uri);
2751 ret_v = caml_alloc_small (1, uuri);
2752 Field (ret_v, 0) = str_v;
2754 else {
2755 fz_point p = { .x = x, .y = y };
2756 fz_stext_block *block;
2758 ensuretext (page);
2760 for (block = page->text->first_block; block; block = block->next) {
2761 fz_stext_line *line;
2763 if (block->type != FZ_STEXT_BLOCK_TEXT) {
2764 continue;
2766 if (!fz_is_point_inside_rect (p, block->bbox)) {
2767 continue;
2770 for (line = block->u.t.first_line; line; line = line->next) {
2771 fz_stext_char *ch;
2773 if (!fz_is_point_inside_rect (p, line->bbox)) {
2774 continue;
2777 for (ch = line->first_char; ch; ch = ch->next) {
2778 if (!fz_is_point_inside_quad (p, ch->quad)) {
2779 const char *n2 = fz_font_name (state.ctx, ch->font);
2780 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2781 ch->font);
2783 if (!n2) {
2784 n2 = "<unknown font>";
2787 if (face && face->family_name) {
2788 char *s;
2789 char *n1 = face->family_name;
2790 size_t l1 = strlen (n1);
2791 size_t l2 = strlen (n2);
2793 if (l1 != l2 || memcmp (n1, n2, l1)) {
2794 s = malloc (l1 + l2 + 2);
2795 if (s) {
2796 memcpy (s, n2, l2);
2797 s[l2] = '=';
2798 memcpy (s + l2 + 1, n1, l1 + 1);
2799 str_v = caml_copy_string (s);
2800 free (s);
2804 if (str_v == Val_unit) {
2805 str_v = caml_copy_string (n2);
2807 ret_v = caml_alloc_small (1, utext);
2808 Field (ret_v, 0) = str_v;
2809 goto unlock;
2815 unlock:
2816 unlock (__func__);
2818 done:
2819 CAMLreturn (ret_v);
2822 enum { mark_page, mark_block, mark_line, mark_word };
2824 ML0 (clearmark (value ptr_v))
2826 CAMLparam1 (ptr_v);
2827 struct page *page;
2829 if (trylock (__func__)) {
2830 goto done;
2833 page = parse_pointer (__func__, String_val (ptr_v));
2834 page->fmark = NULL;
2835 page->lmark = NULL;
2837 unlock (__func__);
2838 done:
2839 CAMLreturn0;
2842 static int uninteresting (int c)
2844 return isspace (c) || ispunct (c);
2847 ML (markunder (value ptr_v, value x_v, value y_v, value mark_v))
2849 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2850 CAMLlocal1 (ret_v);
2851 struct page *page;
2852 fz_stext_line *line;
2853 fz_stext_block *block;
2854 struct pagedim *pdim;
2855 int mark = Int_val (mark_v);
2856 fz_point p = { .x = Int_val (x_v), .y = Int_val (y_v) };
2858 ret_v = Val_bool (0);
2859 if (trylock (__func__)) {
2860 goto done;
2863 page = parse_pointer (__func__, String_val (ptr_v));
2864 pdim = &state.pagedims[page->pdimno];
2866 ensuretext (page);
2868 if (mark == mark_page) {
2869 page->fmark = page->text->first_block->u.t.first_line->first_char;
2870 page->lmark = page->text->last_block->u.t.last_line->last_char;
2871 ret_v = Val_bool (1);
2872 goto unlock;
2875 p.x += pdim->bounds.x0;
2876 p.y += pdim->bounds.y0;
2878 for (block = page->text->first_block; block; block = block->next) {
2879 if (block->type != FZ_STEXT_BLOCK_TEXT) {
2880 continue;
2882 if (!fz_is_point_inside_rect (p, block->bbox)) {
2883 continue;
2886 if (mark == mark_block) {
2887 page->fmark = block->u.t.first_line->first_char;
2888 page->lmark = block->u.t.last_line->last_char;
2889 ret_v = Val_bool (1);
2890 goto unlock;
2893 for (line = block->u.t.first_line; line; line = line->next) {
2894 fz_stext_char *ch;
2896 if (!fz_is_point_inside_rect (p, line->bbox)) {
2897 continue;
2900 if (mark == mark_line) {
2901 page->fmark = line->first_char;
2902 page->lmark = line->last_char;
2903 ret_v = Val_bool (1);
2904 goto unlock;
2907 for (ch = line->first_char; ch; ch = ch->next) {
2908 fz_stext_char *ch2, *first = NULL, *last = NULL;
2910 if (fz_is_point_inside_quad (p, ch->quad)) {
2911 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2912 if (uninteresting (ch2->c)) {
2913 first = NULL;
2915 else {
2916 if (!first) {
2917 first = ch2;
2921 for (ch2 = ch; ch2; ch2 = ch2->next) {
2922 if (uninteresting (ch2->c)) {
2923 break;
2925 last = ch2;
2928 page->fmark = first;
2929 page->lmark = last;
2930 ret_v = Val_bool (1);
2931 goto unlock;
2936 unlock:
2937 if (!Bool_val (ret_v)) {
2938 page->fmark = NULL;
2939 page->lmark = NULL;
2941 unlock (__func__);
2943 done:
2944 CAMLreturn (ret_v);
2947 ML (rectofblock (value ptr_v, value x_v, value y_v))
2949 CAMLparam3 (ptr_v, x_v, y_v);
2950 CAMLlocal2 (ret_v, res_v);
2951 fz_rect *b = NULL;
2952 struct page *page;
2953 struct pagedim *pdim;
2954 fz_stext_block *block;
2955 fz_point p = { .x = Int_val (x_v), .y = Int_val (y_v) };
2957 ret_v = Val_int (0);
2958 if (trylock (__func__)) {
2959 goto done;
2962 page = parse_pointer (__func__, String_val (ptr_v));
2963 pdim = &state.pagedims[page->pdimno];
2964 p.x += pdim->bounds.x0;
2965 p.y += pdim->bounds.y0;
2967 ensuretext (page);
2969 for (block = page->text->first_block; block; block = block->next) {
2970 switch (block->type) {
2971 case FZ_STEXT_BLOCK_TEXT:
2972 b = &block->bbox;
2973 break;
2975 case FZ_STEXT_BLOCK_IMAGE:
2976 b = &block->bbox;
2977 break;
2979 default:
2980 continue;
2983 if (fz_is_point_inside_rect (p, *b)) {
2984 break;
2986 b = NULL;
2988 if (b) {
2989 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2990 ret_v = caml_alloc_small (1, 1);
2991 Store_double_field (res_v, 0, (double) b->x0);
2992 Store_double_field (res_v, 1, (double) b->x1);
2993 Store_double_field (res_v, 2, (double) b->y0);
2994 Store_double_field (res_v, 3, (double) b->y1);
2995 Field (ret_v, 0) = res_v;
2997 unlock (__func__);
2999 done:
3000 CAMLreturn (ret_v);
3003 ML0 (seltext (value ptr_v, value rect_v))
3005 CAMLparam2 (ptr_v, rect_v);
3006 struct page *page;
3007 struct pagedim *pdim;
3008 int x0, x1, y0, y1;
3009 fz_stext_char *ch;
3010 fz_stext_line *line;
3011 fz_stext_block *block;
3012 fz_stext_char *fc, *lc;
3014 if (trylock (__func__)) {
3015 goto done;
3018 page = parse_pointer (__func__, String_val (ptr_v));
3019 ensuretext (page);
3021 pdim = &state.pagedims[page->pdimno];
3022 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3023 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3024 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3025 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3027 if (y0 > y1) {
3028 int t = y0;
3029 y0 = y1;
3030 y1 = t;
3031 x0 = x1;
3032 x1 = t;
3035 fc = page->fmark;
3036 lc = page->lmark;
3038 for (block = page->text->first_block; block; block = block->next) {
3039 if (block->type != FZ_STEXT_BLOCK_TEXT) {
3040 continue;
3043 for (line = block->u.t.first_line; line; line = line->next) {
3044 for (ch = line->first_char; ch; ch = ch->next) {
3045 fz_point p0 = { .x = x0, .y = y0 }, p1 = { .x = x1, .y = y1 };
3046 if (fz_is_point_inside_quad (p0, ch->quad)) {
3047 fc = ch;
3049 if (fz_is_point_inside_quad (p1, ch->quad)) {
3050 lc = ch;
3055 if (x1 < x0 && fc == lc) {
3056 fz_stext_char *t;
3058 t = fc;
3059 fc = lc;
3060 lc = t;
3063 page->fmark = fc;
3064 page->lmark = lc;
3066 unlock (__func__);
3068 done:
3069 CAMLreturn0;
3072 static int pipechar (FILE *f, fz_stext_char *ch)
3074 char buf[4];
3075 int len;
3076 size_t ret;
3078 len = fz_runetochar (buf, ch->c);
3079 ret = fwrite (buf, len, 1, f);
3080 if (ret != 1) {
3081 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3082 len, ret, errno, strerror (errno));
3083 return -1;
3085 return 0;
3088 ML (spawn (value command_v, value fds_v))
3090 CAMLparam2 (command_v, fds_v);
3091 CAMLlocal2 (l_v, tup_v);
3092 int ret, ret1;
3093 pid_t pid = (pid_t) -1;
3094 char *msg = NULL;
3095 value earg_v = Nothing;
3096 posix_spawnattr_t attr;
3097 posix_spawn_file_actions_t fa;
3098 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3100 argv[2] = &Byte (command_v, 0);
3101 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3102 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3105 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3106 msg = "posix_spawnattr_init";
3107 goto fail1;
3110 #ifdef POSIX_SPAWN_USEVFORK
3111 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3112 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3113 goto fail;
3115 #endif
3117 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3118 int fd1, fd2;
3120 tup_v = Field (l_v, 0);
3121 fd1 = Int_val (Field (tup_v, 0));
3122 fd2 = Int_val (Field (tup_v, 1));
3123 if (fd2 < 0) {
3124 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3125 msg = "posix_spawn_file_actions_addclose";
3126 earg_v = tup_v;
3127 goto fail;
3130 else {
3131 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3132 msg = "posix_spawn_file_actions_adddup2";
3133 earg_v = tup_v;
3134 goto fail;
3139 extern char **environ;
3140 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3141 msg = "posix_spawn";
3142 goto fail;
3145 fail:
3146 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3147 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3150 fail1:
3151 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3152 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3153 ret1, strerror (ret1));
3156 if (msg) {
3157 unix_error (ret, msg, earg_v);
3160 CAMLreturn (Val_int (pid));
3163 ML (hassel (value ptr_v))
3165 CAMLparam1 (ptr_v);
3166 CAMLlocal1 (ret_v);
3167 struct page *page;
3169 ret_v = Val_bool (0);
3170 if (trylock (__func__)) {
3171 goto done;
3174 page = parse_pointer (__func__, String_val (ptr_v));
3175 ret_v = Val_bool (page->fmark && page->lmark);
3176 unlock (__func__);
3177 done:
3178 CAMLreturn (ret_v);
3181 ML0 (copysel (value fd_v, value ptr_v))
3183 CAMLparam2 (fd_v, ptr_v);
3184 FILE *f;
3185 int seen = 0;
3186 struct page *page;
3187 fz_stext_line *line;
3188 fz_stext_block *block;
3189 int fd = Int_val (fd_v);
3191 if (trylock (__func__)) {
3192 goto done;
3195 page = parse_pointer (__func__, String_val (ptr_v));
3197 if (!page->fmark || !page->lmark) {
3198 printd ("emsg nothing to copy on page %d", page->pageno);
3199 goto unlock;
3202 f = fdopen (fd, "w");
3203 if (!f) {
3204 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3205 fd, errno, strerror (errno));
3206 f = stdout;
3209 for (block = page->text->first_block; block; block = block->next) {
3210 if (block->type != FZ_STEXT_BLOCK_TEXT) {
3211 continue;
3214 for (line = block->u.t.first_line; line; line = line->next) {
3215 fz_stext_char *ch;
3216 for (ch = line->first_char; ch; ch = ch->next) {
3217 if (seen || ch == page->fmark) {
3218 do {
3219 pipechar (f, ch);
3220 if (ch == page->lmark) {
3221 goto close;
3223 } while ((ch = ch->next));
3224 seen = 1;
3225 break;
3228 if (seen) {
3229 fputc ('\n', f);
3233 close:
3234 if (f != stdout) {
3235 int ret = fclose (f);
3236 fd = -1;
3237 if (ret == -1) {
3238 if (errno != ECHILD) {
3239 printd ("emsg failed to close sel pipe: %d:%s",
3240 errno, strerror (errno));
3244 unlock:
3245 unlock (__func__);
3247 done:
3248 if (fd >= 0) {
3249 if (close (fd)) {
3250 printd ("emsg failed to close sel pipe: %d:%s",
3251 errno, strerror (errno));
3254 CAMLreturn0;
3257 ML (getpdimrect (value pagedimno_v))
3259 CAMLparam1 (pagedimno_v);
3260 CAMLlocal1 (ret_v);
3261 int pagedimno = Int_val (pagedimno_v);
3262 fz_rect box;
3264 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3265 if (trylock (__func__)) {
3266 box = fz_empty_rect;
3268 else {
3269 box = state.pagedims[pagedimno].mediabox;
3270 unlock (__func__);
3273 Store_double_field (ret_v, 0, (double) box.x0);
3274 Store_double_field (ret_v, 1, (double) box.x1);
3275 Store_double_field (ret_v, 2, (double) box.y0);
3276 Store_double_field (ret_v, 3, (double) box.y1);
3278 CAMLreturn (ret_v);
3281 ML (zoom_for_height (value winw_v, value winh_v, value dw_v, value cols_v))
3283 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3284 CAMLlocal1 (ret_v);
3285 int i;
3286 float zoom = -1.;
3287 float maxh = 0.0;
3288 struct pagedim *p;
3289 float winw = Int_val (winw_v);
3290 float winh = Int_val (winh_v);
3291 float dw = Int_val (dw_v);
3292 float cols = Int_val (cols_v);
3293 float pw = 1.0, ph = 1.0;
3295 if (trylock (__func__)) {
3296 goto done;
3299 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3300 float w = p->pagebox.x1 / cols;
3301 float h = p->pagebox.y1;
3302 if (h > maxh) {
3303 maxh = h;
3304 ph = h;
3305 if (state.fitmodel != FitProportional) {
3306 pw = w;
3309 if ((state.fitmodel == FitProportional) && w > pw) {
3310 pw = w;
3314 zoom = (((winh / ph) * pw) + dw) / winw;
3315 unlock (__func__);
3316 done:
3317 ret_v = caml_copy_double ((double) zoom);
3318 CAMLreturn (ret_v);
3321 ML (getmaxw (value unit_v))
3323 CAMLparam1 (unit_v);
3324 CAMLlocal1 (ret_v);
3325 int i;
3326 float maxw = -1.;
3327 struct pagedim *p;
3329 if (trylock (__func__)) {
3330 goto done;
3333 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3334 float w = p->pagebox.x1;
3335 maxw = fz_max (maxw, w);
3338 unlock (__func__);
3339 done:
3340 ret_v = caml_copy_double ((double) maxw);
3341 CAMLreturn (ret_v);
3344 ML (draw_string (value pt_v, value x_v, value y_v, value string_v))
3346 CAMLparam4 (pt_v, x_v, y_v, string_v);
3347 CAMLlocal1 (ret_v);
3348 int pt = Int_val(pt_v);
3349 int x = Int_val (x_v);
3350 int y = Int_val (y_v);
3351 float w;
3353 w = draw_string (state.face, pt, x, y, String_val (string_v));
3354 ret_v = caml_copy_double (w);
3355 CAMLreturn (ret_v);
3358 ML (measure_string (value pt_v, value string_v))
3360 CAMLparam2 (pt_v, string_v);
3361 CAMLlocal1 (ret_v);
3362 int pt = Int_val (pt_v);
3363 double w;
3365 w = (double) measure_string (state.face, pt, String_val (string_v));
3366 ret_v = caml_copy_double (w);
3367 CAMLreturn (ret_v);
3370 ML (getpagebox (value ptr_v))
3372 CAMLparam1 (ptr_v);
3373 CAMLlocal1 (ret_v);
3374 fz_rect rect;
3375 fz_irect bbox;
3376 fz_device *dev;
3377 struct page *page = parse_pointer (__func__, String_val (ptr_v));
3379 ret_v = caml_alloc_tuple (4);
3380 dev = fz_new_bbox_device (state.ctx, &rect);
3382 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3384 fz_close_device (state.ctx, dev);
3385 fz_drop_device (state.ctx, dev);
3386 bbox = fz_round_rect (rect);
3387 Field (ret_v, 0) = Val_int (bbox.x0);
3388 Field (ret_v, 1) = Val_int (bbox.y0);
3389 Field (ret_v, 2) = Val_int (bbox.x1);
3390 Field (ret_v, 3) = Val_int (bbox.y1);
3392 CAMLreturn (ret_v);
3395 ML0 (setaalevel (value level_v))
3397 CAMLparam1 (level_v);
3399 state.aalevel = Int_val (level_v);
3400 CAMLreturn0;
3403 ML0 (setpapercolor (value rgba_v))
3405 CAMLparam1 (rgba_v);
3407 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3408 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3409 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3410 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3411 CAMLreturn0;
3414 value ml_keysymtoutf8 (value keysym_v);
3415 #ifndef CIDER
3416 value ml_keysymtoutf8 (value keysym_v)
3418 CAMLparam1 (keysym_v);
3419 CAMLlocal1 (str_v);
3420 unsigned short keysym = (unsigned short) Int_val (keysym_v);
3421 Rune rune;
3422 extern long keysym2ucs (unsigned short);
3423 int len;
3424 char buf[5];
3426 rune = (Rune) keysym2ucs (keysym);
3427 len = fz_runetochar (buf, rune);
3428 buf[len] = 0;
3429 str_v = caml_copy_string (buf);
3430 CAMLreturn (str_v);
3432 #else
3433 value ml_keysymtoutf8 (value keysym_v)
3435 CAMLparam1 (keysym_v);
3436 CAMLlocal1 (str_v);
3437 long ucs = Long_val (keysym_v);
3438 int len;
3439 char buf[5];
3441 len = fz_runetochar (buf, (int) ucs);
3442 buf[len] = 0;
3443 str_v = caml_copy_string (buf);
3444 CAMLreturn (str_v);
3446 #endif
3448 enum { piunknown, pilinux, pimacos, pibsd };
3450 ML (platform (value unit_v))
3452 CAMLparam1 (unit_v);
3453 CAMLlocal2 (tup_v, arr_v);
3454 int platid = piunknown;
3455 struct utsname buf;
3457 #if defined __linux__
3458 platid = pilinux;
3459 #elif defined __DragonFly__ || defined __FreeBSD__
3460 || defined __OpenBSD__ || defined __NetBSD__
3461 platid = pibsd;
3462 #elif defined __APPLE__
3463 platid = pimacos;
3464 #endif
3465 if (uname (&buf)) {
3466 err (1, "uname");
3469 tup_v = caml_alloc_tuple (2);
3471 char const *sar[] = {
3472 buf.sysname,
3473 buf.release,
3474 buf.version,
3475 buf.machine,
3476 NULL
3478 arr_v = caml_copy_string_array (sar);
3480 Field (tup_v, 0) = Val_int (platid);
3481 Field (tup_v, 1) = arr_v;
3482 CAMLreturn (tup_v);
3485 ML0 (cloexec (value fd_v))
3487 CAMLparam1 (fd_v);
3488 int fd = Int_val (fd_v);
3490 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3491 uerror ("fcntl", Nothing);
3493 CAMLreturn0;
3496 ML (getpbo (value w_v, value h_v, value cs_v))
3498 CAMLparam2 (w_v, h_v);
3499 CAMLlocal1 (ret_v);
3500 struct bo *pbo;
3501 int w = Int_val (w_v);
3502 int h = Int_val (h_v);
3503 int cs = Int_val (cs_v);
3505 if (state.bo_usable) {
3506 pbo = calloc (sizeof (*pbo), 1);
3507 if (!pbo) {
3508 err (1, "calloc pbo");
3511 switch (cs) {
3512 case 0:
3513 case 1:
3514 pbo->size = w*h*4;
3515 break;
3516 case 2:
3517 pbo->size = w*h*2;
3518 break;
3519 default:
3520 errx (1, "%s: invalid colorspace %d", __func__, cs);
3523 state.glGenBuffersARB (1, &pbo->id);
3524 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3525 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3526 NULL, GL_STREAM_DRAW);
3527 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3528 GL_READ_WRITE);
3529 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3530 if (!pbo->ptr) {
3531 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3532 state.glDeleteBuffersARB (1, &pbo->id);
3533 free (pbo);
3534 ret_v = caml_copy_string ("0");
3536 else {
3537 int res;
3538 char *s;
3540 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3541 if (res < 0) {
3542 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3544 s = malloc (res+1);
3545 if (!s) {
3546 err (1, "malloc %d bytes failed", res+1);
3548 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3549 if (res < 0) {
3550 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3552 ret_v = caml_copy_string (s);
3553 free (s);
3556 else {
3557 ret_v = caml_copy_string ("0");
3559 CAMLreturn (ret_v);
3562 ML0 (freepbo (value ptr_v))
3564 CAMLparam1 (ptr_v);
3565 struct tile *tile = parse_pointer (__func__, String_val (ptr_v));
3567 if (tile->pbo) {
3568 state.glDeleteBuffersARB (1, &tile->pbo->id);
3569 tile->pbo->id = -1;
3570 tile->pbo->ptr = NULL;
3571 tile->pbo->size = -1;
3573 CAMLreturn0;
3576 ML0 (unmappbo (value ptr_v))
3578 CAMLparam1 (ptr_v);
3579 struct tile *tile = parse_pointer (__func__, String_val (ptr_v));
3581 if (tile->pbo) {
3582 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3583 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3584 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3586 tile->pbo->ptr = NULL;
3587 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3589 CAMLreturn0;
3592 static void setuppbo (void)
3594 extern void (*wsigladdr (const char *name)) (void);
3595 #pragma GCC diagnostic push
3596 #ifdef __clang__
3597 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3598 #endif
3599 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3600 state.bo_usable = GPA (glBindBufferARB)
3601 && GPA (glUnmapBufferARB)
3602 && GPA (glMapBufferARB)
3603 && GPA (glBufferDataARB)
3604 && GPA (glGenBuffersARB)
3605 && GPA (glDeleteBuffersARB);
3606 #undef GPA
3607 #pragma GCC diagnostic pop
3610 ML (bo_usable (void))
3612 return Val_bool (state.bo_usable);
3615 ML (unproject (value ptr_v, value x_v, value y_v))
3617 CAMLparam3 (ptr_v, x_v, y_v);
3618 CAMLlocal2 (ret_v, tup_v);
3619 struct page *page;
3620 int x = Int_val (x_v), y = Int_val (y_v);
3621 struct pagedim *pdim;
3622 fz_point p;
3624 page = parse_pointer (__func__, String_val (ptr_v));
3625 pdim = &state.pagedims[page->pdimno];
3627 ret_v = Val_int (0);
3628 if (trylock (__func__)) {
3629 goto done;
3632 p.x = x + pdim->bounds.x0;
3633 p.y = y + pdim->bounds.y0;
3635 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3636 pdim->ctm)));
3638 tup_v = caml_alloc_tuple (2);
3639 ret_v = caml_alloc_small (1, 1);
3640 Field (tup_v, 0) = Val_int (p.x);
3641 Field (tup_v, 1) = Val_int (p.y);
3642 Field (ret_v, 0) = tup_v;
3644 unlock (__func__);
3645 done:
3646 CAMLreturn (ret_v);
3649 ML (project (value ptr_v, value pageno_v, value pdimno_v, value x_v, value y_v))
3651 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3652 CAMLlocal1 (ret_v);
3653 struct page *page;
3654 const char *s = String_val (ptr_v);
3655 int pageno = Int_val (pageno_v);
3656 int pdimno = Int_val (pdimno_v);
3657 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3658 struct pagedim *pdim;
3659 fz_point p;
3660 fz_matrix ctm;
3662 ret_v = Val_int (0);
3663 lock (__func__);
3665 if (!*s) {
3666 page = loadpage (pageno, pdimno);
3668 else {
3669 page = parse_pointer (__func__, String_val (ptr_v));
3671 pdim = &state.pagedims[pdimno];
3673 if (pdf_specifics (state.ctx, state.doc)) {
3674 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3675 ctm = state.pagedims[page->pdimno].tctm;
3677 else {
3678 ctm = fz_identity;
3681 p.x = x + pdim->bounds.x0;
3682 p.y = y + pdim->bounds.y0;
3684 ctm = fz_concat (pdim->tctm, pdim->ctm);
3685 p = fz_transform_point (p, ctm);
3687 ret_v = caml_alloc_tuple (2);
3688 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3689 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3691 if (!*s) {
3692 freepage (page);
3694 unlock (__func__);
3695 CAMLreturn (ret_v);
3698 ML0 (addannot (value ptr_v, value x_v, value y_v, value contents_v))
3700 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3701 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3703 if (pdf) {
3704 pdf_annot *annot;
3705 struct page *page;
3706 fz_rect r;
3708 page = parse_pointer (__func__, String_val (ptr_v));
3709 annot = pdf_create_annot (state.ctx,
3710 pdf_page_from_fz_page (state.ctx,
3711 page->fzpage),
3712 PDF_ANNOT_TEXT);
3713 r.x0 = Int_val (x_v) - 10;
3714 r.y0 = Int_val (y_v) - 10;
3715 r.x1 = r.x0 + 20;
3716 r.y1 = r.y0 + 20;
3717 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3718 pdf_set_annot_rect (state.ctx, annot, r);
3720 state.dirty = 1;
3722 CAMLreturn0;
3725 ML0 (delannot (value ptr_v, value n_v))
3727 CAMLparam2 (ptr_v, n_v);
3728 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3730 if (pdf) {
3731 struct page *page;
3732 struct slink *slink;
3734 page = parse_pointer (__func__, String_val (ptr_v));
3735 slink = &page->slinks[Int_val (n_v)];
3736 pdf_delete_annot (state.ctx,
3737 pdf_page_from_fz_page (state.ctx, page->fzpage),
3738 (pdf_annot *) slink->u.annot);
3739 state.dirty = 1;
3741 CAMLreturn0;
3744 ML0 (modannot (value ptr_v, value n_v, value str_v))
3746 CAMLparam3 (ptr_v, n_v, str_v);
3747 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3749 if (pdf) {
3750 struct page *page;
3751 struct slink *slink;
3753 page = parse_pointer (__func__, String_val (ptr_v));
3754 slink = &page->slinks[Int_val (n_v)];
3755 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3756 String_val (str_v));
3757 state.dirty = 1;
3759 CAMLreturn0;
3762 ML (hasunsavedchanges (void))
3764 return Val_bool (state.dirty);
3767 ML0 (savedoc (value path_v))
3769 CAMLparam1 (path_v);
3770 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3772 if (pdf) {
3773 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3775 CAMLreturn0;
3778 static void makestippletex (void)
3780 const char pixels[] = "\xff\xff\0\0";
3781 glGenTextures (1, &state.stid);
3782 glBindTexture (GL_TEXTURE_1D, state.stid);
3783 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3784 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3785 glTexImage1D (
3786 GL_TEXTURE_1D,
3788 GL_ALPHA,
3791 GL_ALPHA,
3792 GL_UNSIGNED_BYTE,
3793 pixels
3797 ML (fz_version (void))
3799 return caml_copy_string (FZ_VERSION);
3802 ML (llpp_version (void))
3804 extern char llpp_version[];
3805 return caml_copy_string (llpp_version);
3808 static void diag_callback (void *user, const char *message)
3810 printd ("emsg %s %s", (char *) user, message);
3813 static fz_font *lsff (fz_context *ctx,int UNUSED_ATTR script,
3814 int UNUSED_ATTR language, int UNUSED_ATTR serif,
3815 int UNUSED_ATTR bold, int UNUSED_ATTR italic)
3817 static fz_font *font;
3818 static int done;
3820 if (!done) {
3821 char *path = getenv ("LLPP_FALLBACK_FONT");
3822 if (path) {
3823 font = fz_new_font_from_file (ctx, NULL, path, 0, 1);
3825 done = 1;
3827 return font;
3830 ML0 (setdcf (value path_v))
3832 free (state.dcf);
3833 state.dcf = NULL;
3834 const char *p = String_val (path_v);
3835 size_t len = caml_string_length (path_v);
3836 if (*p) {
3837 state.dcf = malloc (len + 1);
3838 if (!state.dcf) {
3839 err (1, "malloc dimpath %zu", len + 1);
3841 memcpy (state.dcf, p, len);
3842 state.dcf[len] = 0;
3846 ML (init (value csock_v, value params_v))
3848 CAMLparam2 (csock_v, params_v);
3849 CAMLlocal2 (trim_v, fuzz_v);
3850 int ret, texcount, colorspace, mustoresize;
3851 const char *fontpath;
3853 state.csock = Int_val (csock_v);
3854 state.rotate = Int_val (Field (params_v, 0));
3855 state.fitmodel = Int_val (Field (params_v, 1));
3856 trim_v = Field (params_v, 2);
3857 texcount = Int_val (Field (params_v, 3));
3858 state.sliceheight = Int_val (Field (params_v, 4));
3859 mustoresize = Int_val (Field (params_v, 5));
3860 colorspace = Int_val (Field (params_v, 6));
3861 fontpath = String_val (Field (params_v, 7));
3863 if (Int_val (Field (params_v, 8))) {
3864 if (pipe (state.pfds)) {
3865 err (1, "pipe");
3867 for (int ntries = 0; ntries < 1737; ++ntries) {
3868 if (-1 == dup2 (state.pfds[1], 2)) {
3869 if (EINTR == errno) {
3870 continue;
3872 err (1, "dup2");
3874 break;
3876 } else {
3877 state.pfds[0] = 0;
3878 state.pfds[1] = 0;
3881 #ifdef CIDER
3882 state.utf8cs = 1;
3883 #else
3884 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3885 if (setlocale (LC_CTYPE, "")) {
3886 const char *cset = nl_langinfo (CODESET);
3887 state.utf8cs = !strcmp (cset, "UTF-8");
3889 else {
3890 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3892 #endif
3894 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3895 fz_register_document_handlers (state.ctx);
3896 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3897 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3898 fz_install_load_system_font_funcs (state.ctx, NULL, NULL, lsff);
3900 state.trimmargins = Bool_val (Field (trim_v, 0));
3901 fuzz_v = Field (trim_v, 1);
3902 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3903 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3904 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3905 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3907 set_tex_params (colorspace);
3909 if (*fontpath) {
3910 state.face = load_font (fontpath);
3912 else {
3913 int len;
3914 const unsigned char *data;
3916 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3917 state.face = load_builtin_font (data, len);
3919 if (!state.face) {
3920 _exit (1);
3923 realloctexts (texcount);
3924 setuppbo ();
3925 makestippletex ();
3927 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3928 if (ret) {
3929 errx (1, "pthread_create: %s", strerror (ret));
3932 CAMLreturn (Val_int (state.pfds[0]));
3935 #if FIXME || !FIXME
3936 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3937 #endif