Bo more resilient in presence of cache absence
[llpp.git] / link.c
blobdf7f9b76bd6a36e60f30cc0d8f9b002d4c7f11f3
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 extern char **environ;
16 #include <errno.h>
17 #include <stdio.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <signal.h>
23 #include <math.h>
24 #include <wchar.h>
25 #include <locale.h>
26 #include <langinfo.h>
28 #include <unistd.h>
29 #include <pthread.h>
30 #include <sys/uio.h>
31 #include <sys/time.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/utsname.h>
38 #include <spawn.h>
40 #include <regex.h>
41 #include <stdarg.h>
42 #include <limits.h>
43 #include <inttypes.h>
45 #ifdef CIDER
46 #include <OpenGL/gl.h>
47 #else
48 #include <GL/gl.h>
49 #endif
51 #pragma GCC diagnostic push
52 #ifdef __clang__
53 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
54 #endif
55 #pragma GCC diagnostic ignored "-Wpedantic"
56 #define CAML_NAME_SPACE
57 #include <caml/fail.h>
58 #include <caml/alloc.h>
59 #include <caml/memory.h>
60 #include <caml/unixsupport.h>
62 #pragma GCC diagnostic push
63 #pragma GCC diagnostic ignored "-Wfloat-equal"
64 #include <mupdf/fitz.h>
65 #include <mupdf/pdf.h>
66 #pragma GCC diagnostic pop
68 #include <ft2build.h>
69 #include FT_FREETYPE_H
70 #pragma GCC diagnostic pop
72 #include "cutils.h"
74 #ifdef USE_NPOT
75 #define TEXT_TYPE GL_TEXTURE_2D
76 #else
77 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
78 #endif
80 #if 0
81 #define lprintf printf
82 #else
83 #define lprintf(...)
84 #endif
86 #define ARSERT(cond) for (;;) { \
87 if (!(cond)) { \
88 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
89 } \
90 break; \
91 } (void) 0
93 #define ML(d) extern value ml_##d; value ml_##d
94 #define ML0(d) extern void ml_##d; void ml_##d
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;
164 struct {
165 int index, count;
166 GLuint *ids;
167 GLenum iform, form, ty;
168 struct {
169 int w, h;
170 struct slice *slice;
171 } *owners;
172 } tex;
174 fz_colorspace *colorspace;
175 float papercolor[4];
177 FT_Face face;
178 fz_pixmap *pig;
179 pthread_t thread;
180 fz_irect trimfuzz;
181 GLuint stid, boid;
182 int trimmargins, needoutline, gen, rotate, aalevel,
183 fitmodel, trimanew, csock, dirty, bo_usable, utf8cs;
185 void (*glBindBufferARB) (GLenum, GLuint);
186 GLboolean (*glUnmapBufferARB) (GLenum);
187 void *(*glMapBufferARB) (GLenum, GLenum);
188 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
189 void (*glGenBuffersARB) (GLsizei, GLuint *);
190 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
192 GLfloat texcoords[8], vertices[16];
193 } state;
195 struct bo {
196 GLuint id;
197 void *ptr;
198 size_t size;
201 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
203 static void lock (const char *cap)
205 int ret = pthread_mutex_lock (&mutex);
206 if (ret) {
207 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
211 static void unlock (const char *cap)
213 int ret = pthread_mutex_unlock (&mutex);
214 if (ret) {
215 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
219 static int trylock (const char *cap)
221 int ret = pthread_mutex_trylock (&mutex);
222 if (ret && ret != EBUSY) {
223 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
225 return ret == EBUSY;
228 static int hasdata (void)
230 int ret, avail;
231 ret = ioctl (state.csock, FIONREAD, &avail);
232 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
233 return avail > 0;
236 ML (hasdata (value fd_v))
238 CAMLparam1 (fd_v);
239 int ret, avail;
241 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
242 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
243 CAMLreturn (Val_bool (avail > 0));
246 static void readdata (int fd, void *p, int size)
248 ssize_t n;
250 again:
251 n = read (fd, p, size);
252 if (n - size) {
253 if (n < 0 && errno == EINTR) goto again;
254 if (!n) errx (1, "EOF while reading");
255 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
259 static void writedata (int fd, char *p, int size)
261 ssize_t n;
262 uint32_t size4 = size;
263 struct iovec iov[2] = {
264 { .iov_base = &size4, .iov_len = 4 },
265 { .iov_base = p, .iov_len = size }
268 again:
269 n = writev (fd, iov, 2);
270 if (n < 0 && errno == EINTR) goto again;
271 if (n - size - 4) {
272 if (!n) errx (1, "EOF while writing data");
273 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
277 static int readlen (int fd)
279 uint32_t u;
280 readdata (fd, &u, 4);
281 return u;
284 ML0 (wcmd (value fd_v, value bytes_v, value len_v))
286 CAMLparam3 (fd_v, bytes_v, len_v);
287 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
288 CAMLreturn0;
291 ML (rcmd (value fd_v))
293 CAMLparam1 (fd_v);
294 CAMLlocal1 (strdata_v);
295 int fd = Int_val (fd_v);
296 int len = readlen (fd);
297 strdata_v = caml_alloc_string (len);
298 readdata (fd, Bytes_val (strdata_v), len);
299 CAMLreturn (strdata_v);
302 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
304 char fbuf[64];
305 int size = sizeof (fbuf), len;
306 va_list ap;
307 char *buf = fbuf;
309 for (;;) {
310 va_start (ap, fmt);
311 len = vsnprintf (buf, size, fmt, ap);
312 va_end (ap);
314 if (len > -1) {
315 if (len < size - 4) {
316 writedata (state.csock, buf, len);
317 break;
319 else size = len + 5;
321 else {
322 err (1, "vsnprintf for `%s' failed", fmt);
324 buf = realloc (buf == fbuf ? NULL : buf, size);
325 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
327 if (buf != fbuf) free (buf);
330 static void closedoc (void)
332 if (state.doc) {
333 fz_drop_document (state.ctx, state.doc);
334 state.doc = NULL;
338 static int openxref (char *filename, char *password, int layouth)
340 for (int i = 0; i < state.tex.count; ++i) {
341 state.tex.owners[i].w = -1;
342 state.tex.owners[i].slice = NULL;
345 closedoc ();
347 state.dirty = 0;
348 if (state.pagedims) {
349 free (state.pagedims);
350 state.pagedims = NULL;
352 state.pagedimcount = 0;
354 fz_set_aa_level (state.ctx, state.aalevel);
355 state.doc = fz_open_document (state.ctx, filename);
356 if (fz_needs_password (state.ctx, state.doc)) {
357 if (password && !*password) {
358 printd ("pass");
359 return 0;
361 else {
362 int ok = fz_authenticate_password (state.ctx, state.doc, password);
363 if (!ok) {
364 printd ("pass fail");
365 return 0;
369 if (layouth >= 0)
370 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
371 state.pagecount = fz_count_pages (state.ctx, state.doc);
372 return 1;
375 static void docinfo (void)
377 struct { char *tag; char *name; } metatbl[] = {
378 { FZ_META_INFO_TITLE, "Title" },
379 { FZ_META_INFO_AUTHOR, "Author" },
380 { FZ_META_FORMAT, "Format" },
381 { FZ_META_ENCRYPTION, "Encryption" },
382 { FZ_META_INFO_CREATOR, "Creator" },
383 { FZ_META_INFO_PRODUCER, "Producer" },
384 { "info:CreationDate", "Creation date" },
386 int len = 0;
387 char *buf = NULL;
389 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
390 int need;
391 again:
392 need = fz_lookup_metadata (state.ctx, state.doc,
393 metatbl[i].tag, buf, len);
394 if (need > 0) {
395 if (need <= len) {
396 printd ("info %s\t%s", metatbl[i].name, buf);
398 else {
399 buf = realloc (buf, need + 1);
400 if (!buf) err (1, "docinfo realloc %d", need + 1);
401 len = need + 1;
402 goto again;
406 free (buf);
408 printd ("infoend");
411 static void unlinktile (struct tile *tile)
413 for (int i = 0; i < tile->slicecount; ++i) {
414 struct slice *s = &tile->slices[i];
416 if (s->texindex != -1) {
417 if (state.tex.owners[s->texindex].slice == s) {
418 state.tex.owners[s->texindex].slice = NULL;
424 static void freepage (struct page *page)
426 if (!page) return;
427 if (page->text) {
428 fz_drop_stext_page (state.ctx, page->text);
430 if (page->slinks) {
431 free (page->slinks);
433 fz_drop_display_list (state.ctx, page->dlist);
434 fz_drop_page (state.ctx, page->fzpage);
435 free (page);
438 static void freetile (struct tile *tile)
440 unlinktile (tile);
441 if (!tile->pbo) {
442 #if 0
443 fz_drop_pixmap (state.ctx, tile->pixmap);
444 #else /* piggyback */
445 if (state.pig) {
446 fz_drop_pixmap (state.ctx, state.pig);
448 state.pig = tile->pixmap;
449 #endif
451 else {
452 free (tile->pbo);
453 fz_drop_pixmap (state.ctx, tile->pixmap);
455 free (tile);
458 static void trimctm (pdf_page *page, int pindex)
460 struct pagedim *pdim = &state.pagedims[pindex];
462 if (!page) return;
463 if (!pdim->tctmready) {
464 fz_rect realbox, mediabox;
465 fz_matrix page_ctm, ctm;
467 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
468 realbox = fz_transform_rect (pdim->mediabox, ctm);
469 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
470 pdim->tctm = fz_concat (
471 fz_invert_matrix (page_ctm),
472 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
473 pdim->tctmready = 1;
477 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
479 fz_matrix ctm;
480 ptrdiff_t pdimno = pdim - state.pagedims;
482 ARSERT (pdim - state.pagedims < INT_MAX);
483 if (pdf_specifics (state.ctx, state.doc)) {
484 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
485 ctm = fz_concat (pdim->tctm, pdim->ctm);
487 else {
488 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
489 pdim->ctm);
491 return ctm;
494 static fz_matrix pagectm (struct page *page)
496 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
499 static void *loadpage (int pageno, int pindex)
501 fz_device *dev;
502 struct page *page;
504 page = calloc (sizeof (struct page), 1);
505 if (!page) {
506 err (1, "calloc page %d", pageno);
509 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
510 dev = fz_new_list_device (state.ctx, page->dlist);
511 fz_try (state.ctx) {
512 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
513 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
515 fz_catch (state.ctx) {
516 page->fzpage = NULL;
518 fz_close_device (state.ctx, dev);
519 fz_drop_device (state.ctx, dev);
521 page->pdimno = pindex;
522 page->pageno = pageno;
523 page->sgen = state.gen;
524 page->agen = state.gen;
525 page->tgen = state.gen;
526 return page;
529 static struct tile *alloctile (int h)
531 int slicecount;
532 size_t tilesize;
533 struct tile *tile;
535 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
536 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
537 tile = calloc (tilesize, 1);
538 if (!tile) {
539 err (1, "cannot allocate tile (%zu bytes)", tilesize);
541 for (int i = 0; i < slicecount; ++i) {
542 int sh = fz_mini (h, state.sliceheight);
543 tile->slices[i].h = sh;
544 tile->slices[i].texindex = -1;
545 h -= sh;
547 tile->slicecount = slicecount;
548 tile->sliceheight = state.sliceheight;
549 return tile;
552 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
553 struct bo *pbo)
555 fz_irect bbox;
556 fz_matrix ctm;
557 fz_device *dev;
558 struct tile *tile;
559 struct pagedim *pdim;
561 tile = alloctile (h);
562 pdim = &state.pagedims[page->pdimno];
564 bbox = pdim->bounds;
565 bbox.x0 += x;
566 bbox.y0 += y;
567 bbox.x1 = bbox.x0 + w;
568 bbox.y1 = bbox.y0 + h;
570 if (state.pig) {
571 if (state.pig->w == w
572 && state.pig->h == h
573 && state.pig->colorspace == state.colorspace) {
574 tile->pixmap = state.pig;
575 tile->pixmap->x = bbox.x0;
576 tile->pixmap->y = bbox.y0;
578 else {
579 fz_drop_pixmap (state.ctx, state.pig);
581 state.pig = NULL;
583 if (!tile->pixmap) {
584 if (pbo) {
585 tile->pixmap =
586 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
587 bbox, NULL, 1, pbo->ptr);
588 tile->pbo = pbo;
590 else {
591 tile->pixmap =
592 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
593 NULL, 1);
597 tile->w = w;
598 tile->h = h;
599 fz_fill_pixmap_with_color (state.ctx, tile->pixmap,
600 fz_device_rgb (state.ctx),
601 state.papercolor,
602 fz_default_color_params);
604 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
605 ctm = pagectm (page);
606 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
607 fz_rect_from_irect (bbox), NULL);
608 fz_close_device (state.ctx, dev);
609 fz_drop_device (state.ctx, dev);
611 return tile;
614 static void initpdims1 (void)
616 struct pagedim *p;
617 pdf_document *pdf;
618 fz_context *ctx = state.ctx;
619 int pageno, trim, show, cxcount;
620 fz_rect rootmediabox = fz_empty_rect;
622 fz_var (p);
623 fz_var (pdf);
624 fz_var (cxcount);
626 cxcount = state.pagecount;
627 if ((pdf = pdf_specifics (ctx, state.doc))) {
628 pdf_obj *obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
629 "Root/Pages/MediaBox");
630 rootmediabox = pdf_to_rect (ctx, obj);
631 pdf_load_page_tree (ctx, pdf);
634 for (pageno = 0; pageno < cxcount; ++pageno) {
635 int rotate = 0;
636 fz_rect mediabox = fz_empty_rect;
638 fz_var (rotate);
639 if (pdf) {
640 pdf_obj *pageobj = NULL;
642 fz_var (pageobj);
643 if (pdf->rev_page_map) {
644 for (int i = 0; i < pdf->rev_page_count; ++i) {
645 if (pdf->rev_page_map[i].page == pageno) {
646 pageobj = pdf_get_xref_entry (
647 ctx, pdf, pdf->rev_page_map[i].object
648 )->obj;
649 break;
653 if (!pageobj) {
654 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
657 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
659 if (state.trimmargins) {
660 pdf_obj *obj;
661 pdf_page *page;
663 fz_try (ctx) {
664 page = pdf_load_page (ctx, pdf, pageno);
665 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
666 trim = state.trimanew || !obj;
667 if (trim) {
668 fz_rect rect;
669 fz_device *dev;
670 fz_matrix ctm, page_ctm;
672 dev = fz_new_bbox_device (ctx, &rect);
673 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
674 ctm = fz_invert_matrix (page_ctm);
675 pdf_run_page (ctx, page, dev, fz_identity, NULL);
676 fz_close_device (ctx, dev);
677 fz_drop_device (ctx, dev);
679 rect.x0 += state.trimfuzz.x0;
680 rect.x1 += state.trimfuzz.x1;
681 rect.y0 += state.trimfuzz.y0;
682 rect.y1 += state.trimfuzz.y1;
683 rect = fz_transform_rect (rect, ctm);
684 rect = fz_intersect_rect (rect, mediabox);
686 if (!fz_is_empty_rect (rect)) {
687 mediabox = rect;
690 obj = pdf_new_array (ctx, pdf, 4);
691 pdf_array_push_real (ctx, obj, mediabox.x0);
692 pdf_array_push_real (ctx, obj, mediabox.y0);
693 pdf_array_push_real (ctx, obj, mediabox.x1);
694 pdf_array_push_real (ctx, obj, mediabox.y1);
695 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
697 else {
698 mediabox.x0 = pdf_array_get_real (ctx, obj, 0);
699 mediabox.y0 = pdf_array_get_real (ctx, obj, 1);
700 mediabox.x1 = pdf_array_get_real (ctx, obj, 2);
701 mediabox.y1 = pdf_array_get_real (ctx, obj, 3);
704 fz_drop_page (ctx, &page->super);
705 show = (pageno + 1 == state.pagecount)
706 || (trim ? pageno % 5 == 0 : pageno % 20 == 0);
707 if (show) {
708 printd ("progress %f Trimming %d",
709 (double) (pageno + 1) / state.pagecount,
710 pageno + 1);
713 fz_catch (ctx) {
714 printd ("emsg failed to load page %d", pageno);
717 else {
718 int empty = 0;
719 fz_rect cropbox;
721 mediabox =
722 pdf_to_rect (ctx,
723 pdf_dict_get_inheritable (
724 ctx,
725 pageobj,
726 PDF_NAME (MediaBox)
729 if (fz_is_empty_rect (mediabox)) {
730 mediabox.x0 = 0;
731 mediabox.y0 = 0;
732 mediabox.x1 = 612;
733 mediabox.y1 = 792;
734 empty = 1;
737 cropbox =
738 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
739 if (!fz_is_empty_rect (cropbox)) {
740 if (empty) {
741 mediabox = cropbox;
743 else {
744 mediabox = fz_intersect_rect (mediabox, cropbox);
747 else {
748 if (empty) {
749 if (fz_is_empty_rect (rootmediabox)) {
750 printd ("emsg cannot find page size for page %d",
751 pageno);
753 else {
754 mediabox = rootmediabox;
760 else {
761 if (state.trimmargins) {
762 fz_page *page;
764 fz_try (ctx) {
765 page = fz_load_page (ctx, state.doc, pageno);
766 mediabox = fz_bound_page (ctx, page);
767 if (state.trimmargins) {
768 fz_rect rect;
769 fz_device *dev;
771 dev = fz_new_bbox_device (ctx, &rect);
772 fz_run_page (ctx, page, dev, fz_identity, NULL);
773 fz_close_device (ctx, dev);
774 fz_drop_device (ctx, dev);
776 rect.x0 += state.trimfuzz.x0;
777 rect.x1 += state.trimfuzz.x1;
778 rect.y0 += state.trimfuzz.y0;
779 rect.y1 += state.trimfuzz.y1;
780 rect = fz_intersect_rect (rect, mediabox);
782 if (!fz_is_empty_rect (rect)) {
783 mediabox = rect;
786 fz_drop_page (ctx, page);
788 fz_catch (ctx) {
791 else {
792 fz_page *page;
793 fz_try (ctx) {
794 page = fz_load_page (ctx, state.doc, pageno);
795 mediabox = fz_bound_page (ctx, page);
796 fz_drop_page (ctx, page);
798 show = !state.trimmargins && pageno % 20 == 0;
799 if (show) {
800 printd ("progress %f Gathering dimensions %d",
801 (double) (pageno) / state.pagecount,
802 pageno);
805 fz_catch (ctx) {
806 printd ("emsg failed to load page %d", pageno);
811 if (!p || p->rotate != rotate
812 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
813 size_t size;
815 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
816 state.pagedims = realloc (state.pagedims, size);
817 if (!state.pagedims) {
818 err (1, "realloc pagedims to %zu (%d elems)",
819 size, state.pagedimcount + 1);
822 p = &state.pagedims[state.pagedimcount++];
823 p->rotate = rotate;
824 p->mediabox = mediabox;
825 p->pageno = pageno;
828 state.trimanew = 0;
831 static void initpdims (void)
833 FILE *f = state.dcf ? fopen (state.dcf, "rb") : NULL;
834 if (f) {
835 size_t nread;
837 nread = fread (&state.pagedimcount, sizeof (state.pagedimcount),
838 1, f);
839 if (nread - 1) {
840 err (1, "fread pagedim %zu", sizeof (state.pagedimcount));
842 size_t size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
843 state.pagedims = realloc (state.pagedims, size);
844 if (!state.pagedims) {
845 err (1, "realloc pagedims to %zu (%d elems)",
846 size, state.pagedimcount + 1);
848 if (fread (state.pagedims,
849 sizeof (*state.pagedims),
850 state.pagedimcount+1,
851 f) - (state.pagedimcount+1)) {
852 err (1, "fread pagedim data %zu %d",
853 sizeof (*state.pagedims), state.pagedimcount+1);
855 fclose (f);
858 if (!state.pagedims) {
859 initpdims1 ();
860 if (state.dcf) {
861 f = fopen (state.dcf, "wb");
862 if (!f) {
863 err (1, "fopen %s for writing", state.dcf);
865 if (fwrite (&state.pagedimcount,
866 sizeof (state.pagedimcount), 1, f) - 1) {
867 err (1, "fwrite pagedimcunt %zu", sizeof (state.pagedimcount));
869 if (fwrite (state.pagedims, sizeof (*state.pagedims),
870 state.pagedimcount + 1, f)
871 - (state.pagedimcount + 1)) {
872 err (1, "fwrite pagedim data %zu %u",
873 sizeof (*state.pagedims), state.pagedimcount+1);
874 } fclose (f);
879 static void layout (void)
881 int pindex;
882 fz_rect box;
883 fz_matrix ctm;
884 struct pagedim *p = NULL;
885 float zw, w, maxw = 0.0, zoom = 1.0;
887 if (state.pagedimcount == 0) return;
889 switch (state.fitmodel) {
890 case FitProportional:
891 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
892 float x0, x1;
894 p = &state.pagedims[pindex];
895 box = fz_transform_rect (p->mediabox,
896 fz_rotate (p->rotate + state.rotate));
898 x0 = fz_min (box.x0, box.x1);
899 x1 = fz_max (box.x0, box.x1);
901 w = x1 - x0;
902 maxw = fz_max (w, maxw);
903 zoom = state.w / maxw;
905 break;
907 case FitPage:
908 maxw = state.w;
909 break;
911 case FitWidth:
912 break;
914 default:
915 ARSERT (0 && state.fitmodel);
918 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
919 p = &state.pagedims[pindex];
920 ctm = fz_rotate (state.rotate);
921 box = fz_transform_rect (p->mediabox,
922 fz_rotate (p->rotate + state.rotate));
923 w = box.x1 - box.x0;
924 switch (state.fitmodel) {
925 case FitProportional:
926 p->left = (int) (((maxw - w) * zoom) / 2.f);
927 break;
928 case FitPage:
930 float zh, h;
931 zw = maxw / w;
932 h = box.y1 - box.y0;
933 zh = state.h / h;
934 zoom = fz_min (zw, zh);
935 p->left = (int) ((maxw - (w * zoom)) / 2.f);
937 break;
938 case FitWidth:
939 p->left = 0;
940 zoom = state.w / w;
941 break;
944 p->zoomctm = fz_scale (zoom, zoom);
945 ctm = fz_concat (p->zoomctm, ctm);
947 p->pagebox = p->mediabox;
948 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
949 p->pagebox.x1 -= p->pagebox.x0;
950 p->pagebox.y1 -= p->pagebox.y0;
951 p->pagebox.x0 = 0;
952 p->pagebox.y0 = 0;
953 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
954 p->ctm = ctm;
956 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
957 fz_scale (zoom, -zoom));
958 p->tctmready = 0;
961 do {
962 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
963 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
964 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
965 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
966 int boundw = x1 - x0;
967 int boundh = y1 - y0;
969 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
970 } while (p-- != state.pagedims);
973 static struct pagedim *pdimofpageno (int pageno)
975 struct pagedim *pdim = state.pagedims;
977 for (int i = 0; i < state.pagedimcount; ++i) {
978 if (state.pagedims[i].pageno > pageno)
979 break;
980 pdim = &state.pagedims[i];
982 return pdim;
985 static void recurse_outline (fz_outline *outline, int level)
987 while (outline) {
988 if (outline->page >= 0) {
989 fz_point p = {.x = outline->x, .y = outline->y};
990 struct pagedim *pdim = pdimofpageno (outline->page);
991 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
992 p = fz_transform_point (p, pdim->ctm);
993 printd ("o %d %d %d %d %s",
994 level, outline->page, (int) p.y, h, outline->title);
996 else {
997 printd ("on %d %s", level, outline->title);
999 if (outline->down) {
1000 recurse_outline (outline->down, level + 1);
1002 outline = outline->next;
1006 static void process_outline (void)
1008 fz_outline *outline;
1010 if (!state.needoutline || !state.pagedimcount) return;
1012 state.needoutline = 0;
1013 outline = fz_load_outline (state.ctx, state.doc);
1014 if (outline) {
1015 recurse_outline (outline, 0);
1016 fz_drop_outline (state.ctx, outline);
1020 static char *strofline (fz_stext_line *line)
1022 char *p;
1023 char utf8[10];
1024 fz_stext_char *ch;
1025 size_t size = 0, cap = 80;
1027 p = malloc (cap + 1);
1028 if (!p) return NULL;
1030 for (ch = line->first_char; ch; ch = ch->next) {
1031 int n = fz_runetochar (utf8, ch->c);
1032 if (size + n > cap) {
1033 cap *= 2;
1034 p = realloc (p, cap + 1);
1035 if (!p) return NULL;
1038 memcpy (p + size, utf8, n);
1039 size += n;
1041 p[size] = 0;
1042 return p;
1045 static int matchline (regex_t *re, fz_stext_line *line,
1046 int stop, int pageno, double start)
1048 int ret;
1049 char *p;
1050 regmatch_t rm;
1052 p = strofline (line);
1053 if (!p) return -1;
1055 ret = regexec (re, p, 1, &rm, 0);
1056 if (ret) {
1057 free (p);
1058 if (ret != REG_NOMATCH) {
1059 size_t size;
1060 char errbuf[80];
1061 size = regerror (ret, re, errbuf, sizeof (errbuf));
1062 printd ("msg regexec error `%.*s'",
1063 (int) size, errbuf);
1064 return -1;
1066 return 0;
1068 else {
1069 fz_quad s, e;
1070 fz_stext_char *ch;
1071 int o = 0;
1073 for (ch = line->first_char; ch; ch = ch->next) {
1074 o += fz_runelen (ch->c);
1075 if (o > rm.rm_so) {
1076 s = ch->quad;
1077 break;
1080 for (;ch; ch = ch->next) {
1081 o += fz_runelen (ch->c);
1082 if (o > rm.rm_eo) break;
1084 e = ch->quad;
1086 if (!stop) {
1087 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1088 pageno, 1,
1089 s.ul.x, s.ul.y,
1090 e.ur.x, s.ul.y,
1091 e.lr.x, e.lr.y,
1092 s.ul.x, e.lr.y);
1094 printd ("progress 1 found at %d `%.*s' in %f sec",
1095 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1096 now () - start);
1098 else {
1099 printd ("match %d %d %f %f %f %f %f %f %f %f",
1100 pageno, 2,
1101 s.ul.x, s.ul.y,
1102 e.ur.x, s.ul.y,
1103 e.lr.x, e.lr.y,
1104 s.ul.x, e.lr.y);
1106 free (p);
1107 return 1;
1111 /* wishful thinking function */
1112 static void search (regex_t *re, int pageno, int y, int forward)
1114 fz_device *tdev;
1115 fz_stext_page *text;
1116 struct pagedim *pdim;
1117 int stop = 0, niters = 0;
1118 double start, end;
1119 fz_page *page;
1120 fz_stext_block *block;
1122 start = now ();
1123 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1124 if (niters++ == 5) {
1125 niters = 0;
1126 if (hasdata ()) {
1127 printd ("progress 1 attention requested aborting search at %d",
1128 pageno);
1129 stop = 1;
1131 else {
1132 printd ("progress %f searching in page %d",
1133 (double) (pageno + 1) / state.pagecount,
1134 pageno);
1137 pdim = pdimofpageno (pageno);
1138 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1139 tdev = fz_new_stext_device (state.ctx, text, 0);
1141 page = fz_load_page (state.ctx, state.doc, pageno);
1142 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1144 fz_close_device (state.ctx, tdev);
1145 fz_drop_device (state.ctx, tdev);
1147 if (forward) {
1148 for (block = text->first_block; block; block = block->next) {
1149 fz_stext_line *line;
1151 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1152 for (line = block->u.t.first_line; line; line = line->next) {
1153 if (line->bbox.y0 < y + 1) continue;
1155 switch (matchline (re, line, stop, pageno, start)) {
1156 case 0: break;
1157 case 1: stop = 1; break;
1158 case -1: stop = 1; goto endloop;
1163 else {
1164 for (block = text->last_block; block; block = block->prev) {
1165 fz_stext_line *line;
1167 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1168 for (line = block->u.t.last_line; line; line = line->prev) {
1169 if (line->bbox.y0 < y + 1) continue;
1171 switch (matchline (re, line, stop, pageno, start)) {
1172 case 0: break;
1173 case 1: stop = 1; break;
1174 case -1: stop = 1; goto endloop;
1180 if (forward) {
1181 pageno += 1;
1182 y = 0;
1184 else {
1185 pageno -= 1;
1186 y = INT_MAX;
1188 endloop:
1189 fz_drop_stext_page (state.ctx, text);
1190 fz_drop_page (state.ctx, page);
1192 end = now ();
1193 if (!stop) {
1194 printd ("progress 1 no matches %f sec", end - start);
1196 printd ("clearrects");
1199 static void set_tex_params (int colorspace)
1201 switch (colorspace) {
1202 case 0:
1203 state.tex.iform = GL_RGBA8;
1204 state.tex.form = GL_RGBA;
1205 state.tex.ty = GL_UNSIGNED_BYTE;
1206 state.colorspace = fz_device_rgb (state.ctx);
1207 break;
1208 case 1:
1209 state.tex.iform = GL_LUMINANCE_ALPHA;
1210 state.tex.form = GL_LUMINANCE_ALPHA;
1211 state.tex.ty = GL_UNSIGNED_BYTE;
1212 state.colorspace = fz_device_gray (state.ctx);
1213 break;
1214 default:
1215 errx (1, "invalid colorspce %d", colorspace);
1219 static void realloctexts (int texcount)
1221 size_t size;
1223 if (texcount == state.tex.count) return;
1225 if (texcount < state.tex.count) {
1226 glDeleteTextures (state.tex.count - texcount,
1227 state.tex.ids + texcount);
1230 size = texcount * (sizeof (*state.tex.ids) + sizeof (*state.tex.owners));
1231 state.tex.ids = realloc (state.tex.ids, size);
1232 if (!state.tex.ids) {
1233 err (1, "realloc texs %zu", size);
1236 state.tex.owners = (void *) (state.tex.ids + texcount);
1237 if (texcount > state.tex.count) {
1238 glGenTextures (texcount - state.tex.count,
1239 state.tex.ids + state.tex.count);
1240 for (int i = state.tex.count; i < texcount; ++i) {
1241 state.tex.owners[i].w = -1;
1242 state.tex.owners[i].slice = NULL;
1245 state.tex.count = texcount;
1246 state.tex.index = 0;
1249 static char *mbtoutf8 (char *s)
1251 char *p, *r;
1252 wchar_t *tmp;
1253 size_t i, ret, len;
1255 if (state.utf8cs) {
1256 return s;
1259 len = mbstowcs (NULL, s, strlen (s));
1260 if (len == 0 || len == (size_t) -1) {
1261 if (len)
1262 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1263 return s;
1266 tmp = calloc (len, sizeof (wchar_t));
1267 if (!tmp) {
1268 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1269 len, sizeof (wchar_t), errno, strerror (errno));
1270 return s;
1273 ret = mbstowcs (tmp, s, len);
1274 if (ret == (size_t) -1) {
1275 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1276 len, errno, strerror (errno));
1277 free (tmp);
1278 return s;
1281 len = 0;
1282 for (i = 0; i < ret; ++i) {
1283 len += fz_runelen (tmp[i]);
1286 p = r = malloc (len + 1);
1287 if (!r) {
1288 printd ("emsg mbtoutf8: malloc(%zu)", len);
1289 free (tmp);
1290 return s;
1293 for (i = 0; i < ret; ++i) {
1294 p += fz_runetochar (p, tmp[i]);
1296 *p = 0;
1297 free (tmp);
1298 return r;
1301 ML (mbtoutf8 (value s_v))
1303 CAMLparam1 (s_v);
1304 CAMLlocal1 (ret_v);
1305 char *s, *r;
1307 s = &Byte (s_v, 0);
1308 r = mbtoutf8 (s);
1309 if (r == s) {
1310 ret_v = s_v;
1312 else {
1313 ret_v = caml_copy_string (r);
1314 free (r);
1316 CAMLreturn (ret_v);
1319 static void * mainloop (void UNUSED_ATTR *unused)
1321 char *p = NULL;
1322 int len, ret, oldlen = 0;
1324 fz_var (p);
1325 fz_var (oldlen);
1326 for (;;) {
1327 len = readlen (state.csock);
1328 if (len == 0) {
1329 errx (1, "readlen returned 0");
1332 if (oldlen < len + 1) {
1333 p = realloc (p, len + 1);
1334 if (!p) {
1335 err (1, "realloc %d failed", len + 1);
1337 oldlen = len + 1;
1339 readdata (state.csock, p, len);
1340 p[len] = 0;
1342 if (!strncmp ("open", p, 4)) {
1343 int off, usedoccss, ok = 0, layouth;
1344 char *password;
1345 char *filename;
1346 char *utf8filename;
1347 size_t filenamelen;
1349 fz_var (ok);
1350 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1351 if (ret != 2) {
1352 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1355 filename = p + 5 + off;
1356 filenamelen = strlen (filename);
1357 password = filename + filenamelen + 1;
1359 if (password[strlen (password) + 1]) {
1360 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1363 lock ("open");
1364 fz_set_use_document_css (state.ctx, usedoccss);
1365 fz_try (state.ctx) {
1366 ok = openxref (filename, password, layouth);
1368 fz_catch (state.ctx) {
1369 utf8filename = mbtoutf8 (filename);
1370 printd ("emsg Error loading %s: %s",
1371 utf8filename, fz_caught_message (state.ctx));
1372 if (utf8filename != filename) {
1373 free (utf8filename);
1376 if (ok) {
1377 docinfo ();
1378 initpdims ();
1380 unlock ("open");
1381 state.needoutline = ok;
1383 else if (!strncmp ("cs", p, 2)) {
1384 int i, colorspace;
1386 ret = sscanf (p + 2, " %d", &colorspace);
1387 if (ret != 1) {
1388 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1390 lock ("cs");
1391 set_tex_params (colorspace);
1392 for (i = 0; i < state.tex.count; ++i) {
1393 state.tex.owners[i].w = -1;
1394 state.tex.owners[i].slice = NULL;
1396 unlock ("cs");
1398 else if (!strncmp ("freepage", p, 8)) {
1399 void *ptr;
1401 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1402 if (ret != 1) {
1403 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1405 lock ("freepage");
1406 freepage (ptr);
1407 unlock ("freepage");
1409 else if (!strncmp ("freetile", p, 8)) {
1410 void *ptr;
1412 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1413 if (ret != 1) {
1414 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1416 lock ("freetile");
1417 freetile (ptr);
1418 unlock ("freetile");
1420 else if (!strncmp ("search", p, 6)) {
1421 int icase, pageno, y, len2, forward;
1422 char *pattern;
1423 regex_t re;
1425 ret = sscanf (p + 6, " %d %d %d %d,%n",
1426 &icase, &pageno, &y, &forward, &len2);
1427 if (ret != 4) {
1428 errx (1, "malformed search `%s' ret=%d", p, ret);
1431 pattern = p + 6 + len2;
1432 ret = regcomp (&re, pattern,
1433 REG_EXTENDED | (icase ? REG_ICASE : 0));
1434 if (ret) {
1435 char errbuf[80];
1436 size_t size;
1438 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1439 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1441 else {
1442 lock ("search");
1443 search (&re, pageno, y, forward);
1444 unlock ("search");
1445 regfree (&re);
1448 else if (!strncmp ("geometry", p, 8)) {
1449 int w, h, fitmodel;
1451 printd ("clear");
1452 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1453 if (ret != 3) {
1454 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1457 lock ("geometry");
1458 state.h = h;
1459 if (w != state.w) {
1460 state.w = w;
1461 for (int i = 0; i < state.tex.count; ++i) {
1462 state.tex.owners[i].slice = NULL;
1465 state.fitmodel = fitmodel;
1466 layout ();
1467 process_outline ();
1469 state.gen++;
1470 unlock ("geometry");
1471 printd ("continue %d", state.pagecount);
1473 else if (!strncmp ("reqlayout", p, 9)) {
1474 char *nameddest;
1475 int rotate, off, h;
1476 int fitmodel;
1477 pdf_document *pdf;
1479 printd ("clear");
1480 ret = sscanf (p + 9, " %d %d %d %n",
1481 &rotate, &fitmodel, &h, &off);
1482 if (ret != 3) {
1483 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1485 lock ("reqlayout");
1486 pdf = pdf_specifics (state.ctx, state.doc);
1487 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1488 state.gen += 1;
1490 state.rotate = rotate;
1491 state.fitmodel = fitmodel;
1492 state.h = h;
1493 layout ();
1494 process_outline ();
1496 nameddest = p + 9 + off;
1497 if (pdf && nameddest && *nameddest) {
1498 fz_point xy;
1499 struct pagedim *pdim;
1500 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1501 &xy.x, &xy.y);
1502 pdim = pdimofpageno (pageno);
1503 xy = fz_transform_point (xy, pdim->ctm);
1504 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1507 state.gen++;
1508 unlock ("reqlayout");
1509 printd ("continue %d", state.pagecount);
1511 else if (!strncmp ("page", p, 4)) {
1512 double a, b;
1513 struct page *page;
1514 int pageno, pindex;
1516 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1517 if (ret != 2) {
1518 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1521 lock ("page");
1522 a = now ();
1523 page = loadpage (pageno, pindex);
1524 b = now ();
1525 unlock ("page");
1527 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1529 else if (!strncmp ("tile", p, 4)) {
1530 int x, y, w, h;
1531 struct page *page;
1532 struct tile *tile;
1533 double a, b;
1534 void *data;
1536 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1537 (uintptr_t *) &page, &x, &y, &w, &h,
1538 (uintptr_t *) &data);
1539 if (ret != 6) {
1540 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1543 lock ("tile");
1544 a = now ();
1545 tile = rendertile (page, x, y, w, h, data);
1546 b = now ();
1547 unlock ("tile");
1549 printd ("tile %d %d %" PRIxPTR " %u %f",
1550 x, y, (uintptr_t) (tile),
1551 tile->w * tile->h * tile->pixmap->n,
1552 b - a);
1554 else if (!strncmp ("trimset", p, 7)) {
1555 fz_irect fuzz;
1556 int trimmargins;
1558 ret = sscanf (p + 7, " %d %d %d %d %d",
1559 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1560 if (ret != 5) {
1561 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1563 lock ("trimset");
1564 state.trimmargins = trimmargins;
1565 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1566 state.trimanew = 1;
1567 state.trimfuzz = fuzz;
1569 unlock ("trimset");
1571 else if (!strncmp ("settrim", p, 7)) {
1572 fz_irect fuzz;
1573 int trimmargins;
1575 ret = sscanf (p + 7, " %d %d %d %d %d",
1576 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1577 if (ret != 5) {
1578 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1580 printd ("clear");
1581 lock ("settrim");
1582 state.trimmargins = trimmargins;
1583 state.needoutline = 1;
1584 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1585 state.trimanew = 1;
1586 state.trimfuzz = fuzz;
1588 state.pagedimcount = 0;
1589 free (state.pagedims);
1590 state.pagedims = NULL;
1591 initpdims ();
1592 layout ();
1593 process_outline ();
1594 unlock ("settrim");
1595 printd ("continue %d", state.pagecount);
1597 else if (!strncmp ("sliceh", p, 6)) {
1598 int h;
1600 ret = sscanf (p + 6, " %d", &h);
1601 if (ret != 1) {
1602 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1604 if (h != state.sliceheight) {
1605 state.sliceheight = h;
1606 for (int i = 0; i < state.tex.count; ++i) {
1607 state.tex.owners[i].w = -1;
1608 state.tex.owners[i].h = -1;
1609 state.tex.owners[i].slice = NULL;
1613 else if (!strncmp ("interrupt", p, 9)) {
1614 printd ("vmsg interrupted");
1616 else {
1617 errx (1, "unknown command %.*s", len, p);
1620 return 0;
1623 ML (isexternallink (value uri_v))
1625 CAMLparam1 (uri_v);
1626 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1627 CAMLreturn (Val_bool (ext));
1630 ML (uritolocation (value uri_v))
1632 CAMLparam1 (uri_v);
1633 CAMLlocal1 (ret_v);
1634 int pageno;
1635 fz_point xy;
1636 struct pagedim *pdim;
1638 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1639 &xy.x, &xy.y).page;
1640 pdim = pdimofpageno (pageno);
1641 xy = fz_transform_point (xy, pdim->ctm);
1642 ret_v = caml_alloc_tuple (3);
1643 Field (ret_v, 0) = Val_int (pageno);
1644 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1645 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1646 CAMLreturn (ret_v);
1649 ML (realloctexts (value texcount_v))
1651 CAMLparam1 (texcount_v);
1652 int ok;
1654 if (trylock (__func__)) {
1655 ok = 0;
1656 goto done;
1658 realloctexts (Int_val (texcount_v));
1659 ok = 1;
1660 unlock (__func__);
1662 done:
1663 CAMLreturn (Val_bool (ok));
1666 static void recti (int x0, int y0, int x1, int y1)
1668 GLfloat *v = state.vertices;
1670 glVertexPointer (2, GL_FLOAT, 0, v);
1671 v[0] = x0; v[1] = y0;
1672 v[2] = x1; v[3] = y0;
1673 v[4] = x0; v[5] = y1;
1674 v[6] = x1; v[7] = y1;
1675 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1678 static void showsel (struct page *page, int ox, int oy)
1680 fz_irect bbox;
1681 fz_rect rect;
1682 fz_stext_block *block;
1683 int seen = 0;
1684 unsigned char selcolor[] = {15,15,15,140};
1686 if (!page->fmark || !page->lmark) return;
1688 glEnable (GL_BLEND);
1689 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1690 glColor4ubv (selcolor);
1692 ox += state.pagedims[page->pdimno].bounds.x0;
1693 oy += state.pagedims[page->pdimno].bounds.y0;
1695 for (block = page->text->first_block; block; block = block->next) {
1696 fz_stext_line *line;
1698 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1699 for (line = block->u.t.first_line; line; line = line->next) {
1700 fz_stext_char *ch;
1702 rect = fz_empty_rect;
1703 for (ch = line->first_char; ch; ch = ch->next) {
1704 fz_rect r;
1705 if (ch == page->fmark) seen = 1;
1706 r = fz_rect_from_quad (ch->quad);
1707 if (seen) rect = fz_union_rect (rect, r);
1708 if (ch == page->lmark) {
1709 bbox = fz_round_rect (rect);
1710 recti (bbox.x0 + ox, bbox.y0 + oy,
1711 bbox.x1 + ox, bbox.y1 + oy);
1712 goto done;
1715 bbox = fz_round_rect (rect);
1716 recti (bbox.x0 + ox, bbox.y0 + oy,
1717 bbox.x1 + ox, bbox.y1 + oy);
1720 done:
1721 glDisable (GL_BLEND);
1724 #pragma GCC diagnostic push
1725 #pragma GCC diagnostic ignored "-Wconversion"
1726 #include "glfont.c"
1727 #pragma GCC diagnostic pop
1729 static void stipplerect (fz_matrix m,
1730 fz_point p1,
1731 fz_point p2,
1732 fz_point p3,
1733 fz_point p4,
1734 GLfloat *texcoords,
1735 GLfloat *vertices)
1737 p1 = fz_transform_point (p1, m);
1738 p2 = fz_transform_point (p2, m);
1739 p3 = fz_transform_point (p3, m);
1740 p4 = fz_transform_point (p4, m);
1742 float w, h, s, t;
1744 w = p2.x - p1.x;
1745 h = p2.y - p1.y;
1746 t = hypotf (w, h) * .25f;
1748 w = p3.x - p2.x;
1749 h = p3.y - p2.y;
1750 s = hypotf (w, h) * .25f;
1752 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1753 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1755 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1756 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1758 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1759 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1761 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1762 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1764 glDrawArrays (GL_LINES, 0, 8);
1767 static void solidrect (fz_matrix m,
1768 fz_point p1,
1769 fz_point p2,
1770 fz_point p3,
1771 fz_point p4,
1772 GLfloat *vertices)
1774 p1 = fz_transform_point (p1, m);
1775 p2 = fz_transform_point (p2, m);
1776 p3 = fz_transform_point (p3, m);
1777 p4 = fz_transform_point (p4, m);
1778 vertices[0] = p1.x; vertices[1] = p1.y;
1779 vertices[2] = p2.x; vertices[3] = p2.y;
1781 vertices[4] = p3.x; vertices[5] = p3.y;
1782 vertices[6] = p4.x; vertices[7] = p4.y;
1783 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1786 static void ensurelinks (struct page *page)
1788 if (!page->links)
1789 page->links = fz_load_links (state.ctx, page->fzpage);
1792 static void highlightlinks (struct page *page, int xoff, int yoff)
1794 fz_matrix ctm;
1795 fz_link *link;
1796 GLfloat *texcoords = state.texcoords;
1797 GLfloat *vertices = state.vertices;
1799 ensurelinks (page);
1801 glEnable (GL_TEXTURE_1D);
1802 glEnable (GL_BLEND);
1803 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1804 glBindTexture (GL_TEXTURE_1D, state.stid);
1806 xoff -= state.pagedims[page->pdimno].bounds.x0;
1807 yoff -= state.pagedims[page->pdimno].bounds.y0;
1808 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1810 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1811 glVertexPointer (2, GL_FLOAT, 0, vertices);
1813 for (link = page->links; link; link = link->next) {
1814 fz_point p1, p2, p3, p4;
1816 p1.x = link->rect.x0;
1817 p1.y = link->rect.y0;
1819 p2.x = link->rect.x1;
1820 p2.y = link->rect.y0;
1822 p3.x = link->rect.x1;
1823 p3.y = link->rect.y1;
1825 p4.x = link->rect.x0;
1826 p4.y = link->rect.y1;
1828 /* TODO: different colours for different schemes */
1829 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1830 else glColor3ub (255, 0, 0);
1832 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1835 for (int i = 0; i < page->annotcount; ++i) {
1836 fz_point p1, p2, p3, p4;
1837 struct annot *annot = &page->annots[i];
1839 p1.x = annot->bbox.x0;
1840 p1.y = annot->bbox.y0;
1842 p2.x = annot->bbox.x1;
1843 p2.y = annot->bbox.y0;
1845 p3.x = annot->bbox.x1;
1846 p3.y = annot->bbox.y1;
1848 p4.x = annot->bbox.x0;
1849 p4.y = annot->bbox.y1;
1851 glColor3ub (0, 0, 128);
1852 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1855 glDisable (GL_BLEND);
1856 glDisable (GL_TEXTURE_1D);
1859 static int compareslinks (const void *l, const void *r)
1861 struct slink const *ls = l;
1862 struct slink const *rs = r;
1863 if (ls->bbox.y0 == rs->bbox.y0) {
1864 return ls->bbox.x0 - rs->bbox.x0;
1866 return ls->bbox.y0 - rs->bbox.y0;
1869 static void droptext (struct page *page)
1871 if (page->text) {
1872 fz_drop_stext_page (state.ctx, page->text);
1873 page->fmark = NULL;
1874 page->lmark = NULL;
1875 page->text = NULL;
1879 static void dropannots (struct page *page)
1881 if (page->annots) {
1882 free (page->annots);
1883 page->annots = NULL;
1884 page->annotcount = 0;
1888 static void ensureannots (struct page *page)
1890 int i, count = 0;
1891 size_t annotsize = sizeof (*page->annots);
1892 pdf_annot *annot;
1893 pdf_document *pdf;
1894 pdf_page *pdfpage;
1896 pdf = pdf_specifics (state.ctx, state.doc);
1897 if (!pdf) return;
1899 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1900 if (state.gen != page->agen) {
1901 dropannots (page);
1902 page->agen = state.gen;
1904 if (page->annots) return;
1906 for (annot = pdf_first_annot (state.ctx, pdfpage);
1907 annot;
1908 annot = pdf_next_annot (state.ctx, annot)) {
1909 count++;
1912 if (count > 0) {
1913 page->annotcount = count;
1914 page->annots = calloc (count, annotsize);
1915 if (!page->annots) {
1916 err (1, "calloc annots %d", count);
1919 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1920 annot;
1921 annot = pdf_next_annot (state.ctx, annot), i++) {
1922 fz_rect rect;
1924 rect = pdf_bound_annot (state.ctx, annot);
1925 page->annots[i].annot = annot;
1926 page->annots[i].bbox = fz_round_rect (rect);
1931 static void dropslinks (struct page *page)
1933 if (page->slinks) {
1934 free (page->slinks);
1935 page->slinks = NULL;
1936 page->slinkcount = 0;
1938 if (page->links) {
1939 fz_drop_link (state.ctx, page->links);
1940 page->links = NULL;
1944 static void ensureslinks (struct page *page)
1946 fz_matrix ctm;
1947 int i, count;
1948 size_t slinksize = sizeof (*page->slinks);
1949 fz_link *link;
1951 ensureannots (page);
1952 if (state.gen != page->sgen) {
1953 dropslinks (page);
1954 page->sgen = state.gen;
1956 if (page->slinks) return;
1958 ensurelinks (page);
1959 ctm = pagectm (page);
1961 count = page->annotcount;
1962 for (link = page->links; link; link = link->next) {
1963 count++;
1965 if (count > 0) {
1966 int j;
1968 page->slinkcount = count;
1969 page->slinks = calloc (count, slinksize);
1970 if (!page->slinks) {
1971 err (1, "calloc slinks %d", count);
1974 for (i = 0, link = page->links; link; ++i, link = link->next) {
1975 fz_rect rect;
1977 rect = link->rect;
1978 rect = fz_transform_rect (rect, ctm);
1979 page->slinks[i].tag = SLINK;
1980 page->slinks[i].u.link = link;
1981 page->slinks[i].bbox = fz_round_rect (rect);
1983 for (j = 0; j < page->annotcount; ++j, ++i) {
1984 fz_rect rect;
1985 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1986 rect = fz_transform_rect (rect, ctm);
1987 page->slinks[i].bbox = fz_round_rect (rect);
1989 page->slinks[i].tag = SANNOT;
1990 page->slinks[i].u.annot = page->annots[j].annot;
1992 qsort (page->slinks, count, slinksize, compareslinks);
1996 static void highlightslinks (struct page *page, int xoff, int yoff,
1997 int noff, const char *targ,
1998 mlsize_t tlen, int hfsize)
2000 char buf[40];
2001 struct slink *slink;
2002 float x0, y0, x1, y1, w;
2004 ensureslinks (page);
2005 glColor3ub (0xc3, 0xb0, 0x91);
2006 for (int i = 0; i < page->slinkcount; ++i) {
2007 fmt_linkn (buf, i + noff);
2008 if (!tlen || !strncmp (targ, buf, tlen)) {
2009 slink = &page->slinks[i];
2011 x0 = slink->bbox.x0 + xoff - 5;
2012 y1 = slink->bbox.y0 + yoff - 5;
2013 y0 = y1 + 10 + hfsize;
2014 w = measure_string (state.face, hfsize, buf);
2015 x1 = x0 + w + 10;
2016 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2020 glEnable (GL_BLEND);
2021 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2022 glEnable (GL_TEXTURE_2D);
2023 glColor3ub (0, 0, 0);
2024 for (int i = 0; i < page->slinkcount; ++i) {
2025 fmt_linkn (buf, i + noff);
2026 if (!tlen || !strncmp (targ, buf, tlen)) {
2027 slink = &page->slinks[i];
2029 x0 = slink->bbox.x0 + xoff;
2030 y0 = slink->bbox.y0 + yoff + hfsize;
2031 draw_string (state.face, hfsize, x0, y0, buf);
2034 glDisable (GL_TEXTURE_2D);
2035 glDisable (GL_BLEND);
2038 static void uploadslice (struct tile *tile, struct slice *slice)
2040 int offset;
2041 struct slice *slice1;
2042 unsigned char *texdata;
2044 offset = 0;
2045 for (slice1 = tile->slices; slice != slice1; slice1++) {
2046 offset += slice1->h * tile->w * tile->pixmap->n;
2048 if (slice->texindex != -1 && slice->texindex < state.tex.count
2049 && state.tex.owners[slice->texindex].slice == slice) {
2050 glBindTexture (TEXT_TYPE, state.tex.ids[slice->texindex]);
2052 else {
2053 int subimage = 0;
2054 int texindex = state.tex.index++ % state.tex.count;
2056 if (state.tex.owners[texindex].w == tile->w) {
2057 if (state.tex.owners[texindex].h >= slice->h) {
2058 subimage = 1;
2060 else {
2061 state.tex.owners[texindex].h = slice->h;
2064 else {
2065 state.tex.owners[texindex].h = slice->h;
2068 state.tex.owners[texindex].w = tile->w;
2069 state.tex.owners[texindex].slice = slice;
2070 slice->texindex = texindex;
2072 glBindTexture (TEXT_TYPE, state.tex.ids[texindex]);
2073 #if TEXT_TYPE == GL_TEXTURE_2D
2074 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2075 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2076 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2077 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2078 #endif
2079 if (tile->pbo) {
2080 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2081 texdata = 0;
2083 else {
2084 texdata = tile->pixmap->samples;
2086 if (subimage) {
2087 glTexSubImage2D (TEXT_TYPE,
2091 tile->w,
2092 slice->h,
2093 state.tex.form,
2094 state.tex.ty,
2095 texdata+offset
2098 else {
2099 glTexImage2D (TEXT_TYPE,
2101 state.tex.iform,
2102 tile->w,
2103 slice->h,
2105 state.tex.form,
2106 state.tex.ty,
2107 texdata+offset
2110 if (tile->pbo) {
2111 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2116 ML0 (begintiles (void))
2118 glEnable (TEXT_TYPE);
2119 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2120 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2123 ML0 (endtiles (void))
2125 glDisable (TEXT_TYPE);
2128 ML0 (drawtile (value args_v, value ptr_v))
2130 CAMLparam2 (args_v, ptr_v);
2131 int dispx = Int_val (Field (args_v, 0));
2132 int dispy = Int_val (Field (args_v, 1));
2133 int dispw = Int_val (Field (args_v, 2));
2134 int disph = Int_val (Field (args_v, 3));
2135 int tilex = Int_val (Field (args_v, 4));
2136 int tiley = Int_val (Field (args_v, 5));
2137 const char *s = String_val (ptr_v);
2138 struct tile *tile = parse_pointer (__func__, s);
2139 int slicey, firstslice;
2140 struct slice *slice;
2141 GLfloat *texcoords = state.texcoords;
2142 GLfloat *vertices = state.vertices;
2144 firstslice = tiley / tile->sliceheight;
2145 slice = &tile->slices[firstslice];
2146 slicey = tiley % tile->sliceheight;
2148 while (disph > 0) {
2149 int dh;
2151 dh = slice->h - slicey;
2152 dh = fz_mini (disph, dh);
2153 uploadslice (tile, slice);
2155 texcoords[0] = tilex; texcoords[1] = slicey;
2156 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2157 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2158 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2160 vertices[0] = dispx; vertices[1] = dispy;
2161 vertices[2] = dispx+dispw; vertices[3] = dispy;
2162 vertices[4] = dispx; vertices[5] = dispy+dh;
2163 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2165 #if TEXT_TYPE == GL_TEXTURE_2D
2166 for (int i = 0; i < 8; ++i) {
2167 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2169 #endif
2171 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2172 dispy += dh;
2173 disph -= dh;
2174 slice++;
2175 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2176 slicey = 0;
2178 CAMLreturn0;
2181 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2183 fz_matrix ctm;
2184 fz_point p1, p2, p3, p4;
2185 GLfloat *vertices = state.vertices;
2187 xoff -= state.pagedims[page->pdimno].bounds.x0;
2188 yoff -= state.pagedims[page->pdimno].bounds.y0;
2189 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2191 glEnable (GL_BLEND);
2192 glVertexPointer (2, GL_FLOAT, 0, vertices);
2194 glColor4d (
2195 Double_array_field (rects_v, 0),
2196 Double_array_field (rects_v, 1),
2197 Double_array_field (rects_v, 2),
2198 Double_array_field (rects_v, 3)
2200 p1.x = (float) Double_array_field (rects_v, 4);
2201 p1.y = (float) Double_array_field (rects_v, 5);
2203 p2.x = (float) Double_array_field (rects_v, 6);
2204 p2.y = p1.y;
2206 p3.x = p2.x;
2207 p3.y = (float) Double_array_field (rects_v, 7);
2209 p4.x = p1.x;
2210 p4.y = p3.y;
2211 solidrect (ctm, p1, p2, p3, p4, vertices);
2212 glDisable (GL_BLEND);
2215 ML (postprocess (value ptr_v, value hlinks_v,
2216 value xoff_v, value yoff_v,
2217 value li_v))
2219 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2220 int xoff = Int_val (xoff_v);
2221 int yoff = Int_val (yoff_v);
2222 int noff = Int_val (Field (li_v, 0));
2223 const char *targ = String_val (Field (li_v, 1));
2224 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2225 int hfsize = Int_val (Field (li_v, 2));
2226 const char *s = String_val (ptr_v);
2227 int hlmask = Int_val (hlinks_v);
2228 struct page *page = parse_pointer (__func__, s);
2230 if (!page->fzpage) {
2231 /* deal with loadpage failed pages */
2232 goto done;
2235 if (trylock (__func__)) {
2236 noff = -1;
2237 goto done;
2240 ensureannots (page);
2241 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2242 if (hlmask & 2) {
2243 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2244 noff = page->slinkcount;
2246 if (page->tgen == state.gen) {
2247 showsel (page, xoff, yoff);
2249 unlock (__func__);
2251 done:
2252 CAMLreturn (Val_int (noff));
2255 ML0 (drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v))
2257 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2258 int xoff = Int_val (xoff_v);
2259 int yoff = Int_val (yoff_v);
2260 const char *s = String_val (ptr_v);
2261 struct page *page = parse_pointer (__func__, s);
2263 drawprect (page, xoff, yoff, rects_v);
2264 CAMLreturn0;
2267 static struct annot *getannot (struct page *page, int x, int y)
2269 fz_point p;
2270 fz_matrix ctm;
2271 const fz_matrix *tctm;
2272 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2274 if (!page->annots) return NULL;
2276 if (pdf) {
2277 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2278 tctm = &state.pagedims[page->pdimno].tctm;
2280 else {
2281 tctm = &fz_identity;
2284 p.x = x;
2285 p.y = y;
2287 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2288 ctm = fz_invert_matrix (ctm);
2289 p = fz_transform_point (p, ctm);
2291 if (pdf) {
2292 for (int i = 0; i < page->annotcount; ++i) {
2293 struct annot *a = &page->annots[i];
2294 fz_rect rect;
2296 rect = pdf_bound_annot (state.ctx, a->annot);
2297 if (p.x >= rect.x0 && p.x <= rect.x1) {
2298 if (p.y >= rect.y0 && p.y <= rect.y1)
2299 return a;
2303 return NULL;
2306 static fz_link *getlink (struct page *page, int x, int y)
2308 fz_point p;
2309 fz_link *link;
2311 ensureslinks (page);
2313 p.x = x;
2314 p.y = y;
2316 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2318 for (link = page->links; link; link = link->next) {
2319 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2320 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2321 return link;
2325 return NULL;
2328 static void ensuretext (struct page *page)
2330 if (state.gen != page->tgen) {
2331 droptext (page);
2332 page->tgen = state.gen;
2334 if (!page->text) {
2335 fz_device *tdev;
2337 page->text = fz_new_stext_page (state.ctx,
2338 state.pagedims[page->pdimno].mediabox);
2339 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2340 fz_run_display_list (state.ctx, page->dlist,
2341 tdev, pagectm (page), fz_infinite_rect, NULL);
2342 fz_close_device (state.ctx, tdev);
2343 fz_drop_device (state.ctx, tdev);
2347 ML (find_page_with_links (value start_page_v, value dir_v))
2349 CAMLparam2 (start_page_v, dir_v);
2350 CAMLlocal1 (ret_v);
2351 int i, dir = Int_val (dir_v);
2352 int start_page = Int_val (start_page_v);
2353 int end_page = dir > 0 ? state.pagecount : -1;
2354 pdf_document *pdf;
2356 fz_var (end_page);
2357 ret_v = Val_int (0);
2358 lock (__func__);
2359 pdf = pdf_specifics (state.ctx, state.doc);
2360 for (i = start_page + dir; i != end_page; i += dir) {
2361 int found;
2363 fz_var (found);
2364 if (pdf) {
2365 pdf_page *page = NULL;
2367 fz_var (page);
2368 fz_try (state.ctx) {
2369 page = pdf_load_page (state.ctx, pdf, i);
2370 found = !!page->links || !!page->annots;
2372 fz_catch (state.ctx) {
2373 found = 0;
2375 if (page) {
2376 fz_drop_page (state.ctx, &page->super);
2379 else {
2380 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2381 fz_link *link = fz_load_links (state.ctx, page);
2382 found = !!link;
2383 fz_drop_link (state.ctx, link);
2384 fz_drop_page (state.ctx, page);
2387 if (found) {
2388 ret_v = caml_alloc_small (1, 1);
2389 Field (ret_v, 0) = Val_int (i);
2390 goto unlock;
2393 unlock:
2394 unlock (__func__);
2395 CAMLreturn (ret_v);
2398 enum { dir_first, dir_last };
2399 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2401 ML (findlink (value ptr_v, value dir_v))
2403 CAMLparam2 (ptr_v, dir_v);
2404 CAMLlocal2 (ret_v, pos_v);
2405 struct page *page;
2406 int dirtag, i, slinkindex;
2407 struct slink *found = NULL ,*slink;
2408 const char *s = String_val (ptr_v);
2410 page = parse_pointer (__func__, s);
2411 ret_v = Val_int (0);
2412 lock (__func__);
2413 ensureslinks (page);
2415 if (Is_block (dir_v)) {
2416 dirtag = Tag_val (dir_v);
2417 switch (dirtag) {
2418 case dir_first_visible:
2420 int x0, y0, dir, first_index, last_index;
2422 pos_v = Field (dir_v, 0);
2423 x0 = Int_val (Field (pos_v, 0));
2424 y0 = Int_val (Field (pos_v, 1));
2425 dir = Int_val (Field (pos_v, 2));
2427 if (dir >= 0) {
2428 dir = 1;
2429 first_index = 0;
2430 last_index = page->slinkcount;
2432 else {
2433 first_index = page->slinkcount - 1;
2434 last_index = -1;
2437 for (i = first_index; i != last_index; i += dir) {
2438 slink = &page->slinks[i];
2439 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2440 found = slink;
2441 break;
2445 break;
2447 case dir_left:
2448 slinkindex = Int_val (Field (dir_v, 0));
2449 found = &page->slinks[slinkindex];
2450 for (i = slinkindex - 1; i >= 0; --i) {
2451 slink = &page->slinks[i];
2452 if (slink->bbox.x0 < found->bbox.x0) {
2453 found = slink;
2454 break;
2457 break;
2459 case dir_right:
2460 slinkindex = Int_val (Field (dir_v, 0));
2461 found = &page->slinks[slinkindex];
2462 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2463 slink = &page->slinks[i];
2464 if (slink->bbox.x0 > found->bbox.x0) {
2465 found = slink;
2466 break;
2469 break;
2471 case dir_down:
2472 slinkindex = Int_val (Field (dir_v, 0));
2473 found = &page->slinks[slinkindex];
2474 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2475 slink = &page->slinks[i];
2476 if (slink->bbox.y0 >= found->bbox.y0) {
2477 found = slink;
2478 break;
2481 break;
2483 case dir_up:
2484 slinkindex = Int_val (Field (dir_v, 0));
2485 found = &page->slinks[slinkindex];
2486 for (i = slinkindex - 1; i >= 0; --i) {
2487 slink = &page->slinks[i];
2488 if (slink->bbox.y0 <= found->bbox.y0) {
2489 found = slink;
2490 break;
2493 break;
2496 else {
2497 dirtag = Int_val (dir_v);
2498 switch (dirtag) {
2499 case dir_first:
2500 found = page->slinks;
2501 break;
2503 case dir_last:
2504 if (page->slinks) {
2505 found = page->slinks + (page->slinkcount - 1);
2507 break;
2510 if (found) {
2511 ret_v = caml_alloc_small (2, 1);
2512 Field (ret_v, 0) = Val_int (found - page->slinks);
2515 unlock (__func__);
2516 CAMLreturn (ret_v);
2519 enum { uuri, utext, uannot };
2521 ML (getlink (value ptr_v, value n_v))
2523 CAMLparam2 (ptr_v, n_v);
2524 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2525 fz_link *link;
2526 struct page *page;
2527 const char *s = String_val (ptr_v);
2528 struct slink *slink;
2530 ret_v = Val_int (0);
2531 page = parse_pointer (__func__, s);
2533 lock (__func__);
2534 ensureslinks (page);
2535 slink = &page->slinks[Int_val (n_v)];
2536 if (slink->tag == SLINK) {
2537 link = slink->u.link;
2538 str_v = caml_copy_string (link->uri);
2539 ret_v = caml_alloc_small (1, uuri);
2540 Field (ret_v, 0) = str_v;
2542 else {
2543 ret_v = caml_alloc_small (1, uannot);
2544 tup_v = caml_alloc_tuple (2);
2545 Field (ret_v, 0) = tup_v;
2546 Field (tup_v, 0) = ptr_v;
2547 Field (tup_v, 1) = n_v;
2549 unlock (__func__);
2551 CAMLreturn (ret_v);
2554 ML (getannotcontents (value ptr_v, value n_v))
2556 CAMLparam2 (ptr_v, n_v);
2557 CAMLlocal1 (ret_v);
2558 pdf_document *pdf;
2559 const char *contents = "";
2561 lock (__func__);
2562 pdf = pdf_specifics (state.ctx, state.doc);
2563 if (pdf) {
2564 const char *s = String_val (ptr_v);
2565 struct page *page;
2566 struct slink *slink;
2568 page = parse_pointer (__func__, s);
2569 slink = &page->slinks[Int_val (n_v)];
2570 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2572 unlock (__func__);
2573 ret_v = caml_copy_string (contents);
2574 CAMLreturn (ret_v);
2577 ML (getlinkcount (value ptr_v))
2579 CAMLparam1 (ptr_v);
2580 struct page *page;
2581 const char *s = String_val (ptr_v);
2583 page = parse_pointer (__func__, s);
2584 CAMLreturn (Val_int (page->slinkcount));
2587 ML (getlinkrect (value ptr_v, value n_v))
2589 CAMLparam2 (ptr_v, n_v);
2590 CAMLlocal1 (ret_v);
2591 struct page *page;
2592 struct slink *slink;
2593 const char *s = String_val (ptr_v);
2595 page = parse_pointer (__func__, s);
2596 ret_v = caml_alloc_tuple (4);
2597 lock (__func__);
2598 ensureslinks (page);
2600 slink = &page->slinks[Int_val (n_v)];
2601 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2602 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2603 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2604 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2605 unlock (__func__);
2606 CAMLreturn (ret_v);
2609 ML (whatsunder (value ptr_v, value x_v, value y_v))
2611 CAMLparam3 (ptr_v, x_v, y_v);
2612 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2613 fz_link *link;
2614 struct annot *annot;
2615 struct page *page;
2616 const char *ptr = String_val (ptr_v);
2617 int x = Int_val (x_v), y = Int_val (y_v);
2618 struct pagedim *pdim;
2620 ret_v = Val_int (0);
2621 if (trylock (__func__)) {
2622 goto done;
2625 page = parse_pointer (__func__, ptr);
2626 pdim = &state.pagedims[page->pdimno];
2627 x += pdim->bounds.x0;
2628 y += pdim->bounds.y0;
2631 annot = getannot (page, x, y);
2632 if (annot) {
2633 int i, n = -1;
2635 ensureslinks (page);
2636 for (i = 0; i < page->slinkcount; ++i) {
2637 if (page->slinks[i].tag == SANNOT
2638 && page->slinks[i].u.annot == annot->annot) {
2639 n = i;
2640 break;
2643 ret_v = caml_alloc_small (1, uannot);
2644 tup_v = caml_alloc_tuple (2);
2645 Field (ret_v, 0) = tup_v;
2646 Field (tup_v, 0) = ptr_v;
2647 Field (tup_v, 1) = Val_int (n);
2648 goto unlock;
2652 link = getlink (page, x, y);
2653 if (link) {
2654 str_v = caml_copy_string (link->uri);
2655 ret_v = caml_alloc_small (1, uuri);
2656 Field (ret_v, 0) = str_v;
2658 else {
2659 fz_rect *b;
2660 fz_stext_block *block;
2662 ensuretext (page);
2664 for (block = page->text->first_block; block; block = block->next) {
2665 fz_stext_line *line;
2667 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2668 b = &block->bbox;
2669 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2670 continue;
2672 for (line = block->u.t.first_line; line; line = line->next) {
2673 fz_stext_char *ch;
2675 b = &line->bbox;
2676 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2677 continue;
2679 for (ch = line->first_char; ch; ch = ch->next) {
2680 fz_quad *q = &ch->quad;
2682 if (x >= q->ul.x && x <= q->ur.x
2683 && y >= q->ul.y && y <= q->ll.y) {
2684 const char *n2 = fz_font_name (state.ctx, ch->font);
2685 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2686 ch->font);
2688 if (!n2) n2 = "<unknown font>";
2690 if (face && face->family_name) {
2691 char *s;
2692 char *n1 = face->family_name;
2693 size_t l1 = strlen (n1);
2694 size_t l2 = strlen (n2);
2696 if (l1 != l2 || memcmp (n1, n2, l1)) {
2697 s = malloc (l1 + l2 + 2);
2698 if (s) {
2699 memcpy (s, n2, l2);
2700 s[l2] = '=';
2701 memcpy (s + l2 + 1, n1, l1 + 1);
2702 str_v = caml_copy_string (s);
2703 free (s);
2707 if (str_v == Val_unit) {
2708 str_v = caml_copy_string (n2);
2710 ret_v = caml_alloc_small (1, utext);
2711 Field (ret_v, 0) = str_v;
2712 goto unlock;
2718 unlock:
2719 unlock (__func__);
2721 done:
2722 CAMLreturn (ret_v);
2725 enum { mark_page, mark_block, mark_line, mark_word };
2727 ML0 (clearmark (value ptr_v))
2729 CAMLparam1 (ptr_v);
2730 const char *s = String_val (ptr_v);
2731 struct page *page;
2733 if (trylock (__func__)) {
2734 goto done;
2737 page = parse_pointer (__func__, s);
2738 page->fmark = NULL;
2739 page->lmark = NULL;
2741 unlock (__func__);
2742 done:
2743 CAMLreturn0;
2746 static int uninteresting (int c)
2748 return isspace (c) || ispunct (c);
2751 ML (markunder (value ptr_v, value x_v, value y_v, value mark_v))
2753 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2754 CAMLlocal1 (ret_v);
2755 fz_rect *b;
2756 struct page *page;
2757 fz_stext_line *line;
2758 fz_stext_block *block;
2759 struct pagedim *pdim;
2760 int mark = Int_val (mark_v);
2761 const char *s = String_val (ptr_v);
2762 int x = Int_val (x_v), y = Int_val (y_v);
2764 ret_v = Val_bool (0);
2765 if (trylock (__func__)) {
2766 goto done;
2769 page = parse_pointer (__func__, s);
2770 pdim = &state.pagedims[page->pdimno];
2772 ensuretext (page);
2774 if (mark == mark_page) {
2775 page->fmark = page->text->first_block->u.t.first_line->first_char;
2776 page->lmark = page->text->last_block->u.t.last_line->last_char;
2777 ret_v = Val_bool (1);
2778 goto unlock;
2781 x += pdim->bounds.x0;
2782 y += pdim->bounds.y0;
2784 for (block = page->text->first_block; block; block = block->next) {
2785 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2786 b = &block->bbox;
2787 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2788 continue;
2790 if (mark == mark_block) {
2791 page->fmark = block->u.t.first_line->first_char;
2792 page->lmark = block->u.t.last_line->last_char;
2793 ret_v = Val_bool (1);
2794 goto unlock;
2797 for (line = block->u.t.first_line; line; line = line->next) {
2798 fz_stext_char *ch;
2800 b = &line->bbox;
2801 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2802 continue;
2804 if (mark == mark_line) {
2805 page->fmark = line->first_char;
2806 page->lmark = line->last_char;
2807 ret_v = Val_bool (1);
2808 goto unlock;
2811 for (ch = line->first_char; ch; ch = ch->next) {
2812 fz_stext_char *ch2, *first = NULL, *last = NULL;
2813 fz_quad *q = &ch->quad;
2814 if (x >= q->ul.x && x <= q->ur.x
2815 && y >= q->ul.y && y <= q->ll.y) {
2816 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2817 if (uninteresting (ch2->c)) first = NULL;
2818 else if (!first) first = ch2;
2820 for (ch2 = ch; ch2; ch2 = ch2->next) {
2821 if (uninteresting (ch2->c)) break;
2822 last = ch2;
2825 page->fmark = first;
2826 page->lmark = last;
2827 ret_v = Val_bool (1);
2828 goto unlock;
2833 unlock:
2834 if (!Bool_val (ret_v)) {
2835 page->fmark = NULL;
2836 page->lmark = NULL;
2838 unlock (__func__);
2840 done:
2841 CAMLreturn (ret_v);
2844 ML (rectofblock (value ptr_v, value x_v, value y_v))
2846 CAMLparam3 (ptr_v, x_v, y_v);
2847 CAMLlocal2 (ret_v, res_v);
2848 fz_rect *b = NULL;
2849 struct page *page;
2850 struct pagedim *pdim;
2851 fz_stext_block *block;
2852 const char *s = String_val (ptr_v);
2853 int x = Int_val (x_v), y = Int_val (y_v);
2855 ret_v = Val_int (0);
2856 if (trylock (__func__)) {
2857 goto done;
2860 page = parse_pointer (__func__, s);
2861 pdim = &state.pagedims[page->pdimno];
2862 x += pdim->bounds.x0;
2863 y += pdim->bounds.y0;
2865 ensuretext (page);
2867 for (block = page->text->first_block; block; block = block->next) {
2868 switch (block->type) {
2869 case FZ_STEXT_BLOCK_TEXT:
2870 b = &block->bbox;
2871 break;
2873 case FZ_STEXT_BLOCK_IMAGE:
2874 b = &block->bbox;
2875 break;
2877 default:
2878 continue;
2881 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2882 break;
2883 b = NULL;
2885 if (b) {
2886 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2887 ret_v = caml_alloc_small (1, 1);
2888 Store_double_field (res_v, 0, (double) b->x0);
2889 Store_double_field (res_v, 1, (double) b->x1);
2890 Store_double_field (res_v, 2, (double) b->y0);
2891 Store_double_field (res_v, 3, (double) b->y1);
2892 Field (ret_v, 0) = res_v;
2894 unlock (__func__);
2896 done:
2897 CAMLreturn (ret_v);
2900 ML0 (seltext (value ptr_v, value rect_v))
2902 CAMLparam2 (ptr_v, rect_v);
2903 struct page *page;
2904 struct pagedim *pdim;
2905 const char *s = String_val (ptr_v);
2906 int x0, x1, y0, y1;
2907 fz_stext_char *ch;
2908 fz_stext_line *line;
2909 fz_stext_block *block;
2910 fz_stext_char *fc, *lc;
2912 if (trylock (__func__)) {
2913 goto done;
2916 page = parse_pointer (__func__, s);
2917 ensuretext (page);
2919 pdim = &state.pagedims[page->pdimno];
2920 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2921 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2922 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2923 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2925 if (y0 > y1) {
2926 int t = y0;
2927 y0 = y1;
2928 y1 = t;
2929 x0 = x1;
2930 x1 = t;
2933 fc = page->fmark;
2934 lc = page->lmark;
2936 for (block = page->text->first_block; block; block = block->next) {
2937 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2938 for (line = block->u.t.first_line; line; line = line->next) {
2939 for (ch = line->first_char; ch; ch = ch->next) {
2940 fz_quad q = ch->quad;
2941 if (x0 >= q.ul.x && x0 <= q.ur.x
2942 && y0 >= q.ul.y && y0 <= q.ll.y) {
2943 fc = ch;
2945 if (x1 >= q.ul.x && x1 <= q.ur.x
2946 && y1 >= q.ul.y && y1 <= q.ll.y) {
2947 lc = ch;
2952 if (x1 < x0 && fc == lc) {
2953 fz_stext_char *t;
2955 t = fc;
2956 fc = lc;
2957 lc = t;
2960 page->fmark = fc;
2961 page->lmark = lc;
2963 unlock (__func__);
2965 done:
2966 CAMLreturn0;
2969 static int pipechar (FILE *f, fz_stext_char *ch)
2971 char buf[4];
2972 int len;
2973 size_t ret;
2975 len = fz_runetochar (buf, ch->c);
2976 ret = fwrite (buf, len, 1, f);
2977 if (ret != 1) {
2978 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
2979 len, ret, errno, strerror (errno));
2980 return -1;
2982 return 0;
2985 ML (spawn (value command_v, value fds_v))
2987 CAMLparam2 (command_v, fds_v);
2988 CAMLlocal2 (l_v, tup_v);
2989 int ret, ret1;
2990 pid_t pid = (pid_t) -1;
2991 char *msg = NULL;
2992 value earg_v = Nothing;
2993 posix_spawnattr_t attr;
2994 posix_spawn_file_actions_t fa;
2995 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
2997 argv[2] = &Byte (command_v, 0);
2998 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
2999 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3002 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3003 msg = "posix_spawnattr_init";
3004 goto fail1;
3007 #ifdef POSIX_SPAWN_USEVFORK
3008 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3009 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3010 goto fail;
3012 #endif
3014 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3015 int fd1, fd2;
3017 tup_v = Field (l_v, 0);
3018 fd1 = Int_val (Field (tup_v, 0));
3019 fd2 = Int_val (Field (tup_v, 1));
3020 if (fd2 < 0) {
3021 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3022 msg = "posix_spawn_file_actions_addclose";
3023 earg_v = tup_v;
3024 goto fail;
3027 else {
3028 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3029 msg = "posix_spawn_file_actions_adddup2";
3030 earg_v = tup_v;
3031 goto fail;
3036 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3037 msg = "posix_spawn";
3038 goto fail;
3041 fail:
3042 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3043 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3046 fail1:
3047 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3048 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3049 ret1, strerror (ret1));
3052 if (msg)
3053 unix_error (ret, msg, earg_v);
3055 CAMLreturn (Val_int (pid));
3058 ML (hassel (value ptr_v))
3060 CAMLparam1 (ptr_v);
3061 CAMLlocal1 (ret_v);
3062 struct page *page;
3063 const char *s = String_val (ptr_v);
3065 ret_v = Val_bool (0);
3066 if (trylock (__func__)) {
3067 goto done;
3070 page = parse_pointer (__func__, s);
3071 ret_v = Val_bool (page->fmark && page->lmark);
3072 unlock (__func__);
3073 done:
3074 CAMLreturn (ret_v);
3077 ML0 (copysel (value fd_v, value ptr_v))
3079 CAMLparam2 (fd_v, ptr_v);
3080 FILE *f;
3081 int seen = 0;
3082 struct page *page;
3083 fz_stext_line *line;
3084 fz_stext_block *block;
3085 int fd = Int_val (fd_v);
3086 const char *s = String_val (ptr_v);
3088 if (trylock (__func__)) {
3089 goto done;
3092 page = parse_pointer (__func__, s);
3094 if (!page->fmark || !page->lmark) {
3095 printd ("emsg nothing to copy on page %d", page->pageno);
3096 goto unlock;
3099 f = fdopen (fd, "w");
3100 if (!f) {
3101 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3102 fd, errno, strerror (errno));
3103 f = stdout;
3106 for (block = page->text->first_block; block; block = block->next) {
3107 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3108 for (line = block->u.t.first_line; line; line = line->next) {
3109 fz_stext_char *ch;
3110 for (ch = line->first_char; ch; ch = ch->next) {
3111 if (seen || ch == page->fmark) {
3112 do {
3113 pipechar (f, ch);
3114 if (ch == page->lmark) goto close;
3115 } while ((ch = ch->next));
3116 seen = 1;
3117 break;
3120 if (seen) fputc ('\n', f);
3123 close:
3124 if (f != stdout) {
3125 int ret = fclose (f);
3126 fd = -1;
3127 if (ret == -1) {
3128 if (errno != ECHILD) {
3129 printd ("emsg failed to close sel pipe: %d:%s",
3130 errno, strerror (errno));
3134 unlock:
3135 unlock (__func__);
3137 done:
3138 if (fd >= 0) {
3139 if (close (fd)) {
3140 printd ("emsg failed to close sel pipe: %d:%s",
3141 errno, strerror (errno));
3144 CAMLreturn0;
3147 ML (getpdimrect (value pagedimno_v))
3149 CAMLparam1 (pagedimno_v);
3150 CAMLlocal1 (ret_v);
3151 int pagedimno = Int_val (pagedimno_v);
3152 fz_rect box;
3154 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3155 if (trylock (__func__)) {
3156 box = fz_empty_rect;
3158 else {
3159 box = state.pagedims[pagedimno].mediabox;
3160 unlock (__func__);
3163 Store_double_field (ret_v, 0, (double) box.x0);
3164 Store_double_field (ret_v, 1, (double) box.x1);
3165 Store_double_field (ret_v, 2, (double) box.y0);
3166 Store_double_field (ret_v, 3, (double) box.y1);
3168 CAMLreturn (ret_v);
3171 ML (zoom_for_height (value winw_v, value winh_v, value dw_v, value cols_v))
3173 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3174 CAMLlocal1 (ret_v);
3175 int i;
3176 float zoom = -1.;
3177 float maxh = 0.0;
3178 struct pagedim *p;
3179 float winw = Int_val (winw_v);
3180 float winh = Int_val (winh_v);
3181 float dw = Int_val (dw_v);
3182 float cols = Int_val (cols_v);
3183 float pw = 1.0, ph = 1.0;
3185 if (trylock (__func__)) {
3186 goto done;
3189 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3190 float w = p->pagebox.x1 / cols;
3191 float h = p->pagebox.y1;
3192 if (h > maxh) {
3193 maxh = h;
3194 ph = h;
3195 if (state.fitmodel != FitProportional) pw = w;
3197 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3200 zoom = (((winh / ph) * pw) + dw) / winw;
3201 unlock (__func__);
3202 done:
3203 ret_v = caml_copy_double ((double) zoom);
3204 CAMLreturn (ret_v);
3207 ML (getmaxw (value unit_v))
3209 CAMLparam1 (unit_v);
3210 CAMLlocal1 (ret_v);
3211 int i;
3212 float maxw = -1.;
3213 struct pagedim *p;
3215 if (trylock (__func__)) {
3216 goto done;
3219 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3220 float w = p->pagebox.x1;
3221 maxw = fz_max (maxw, w);
3224 unlock (__func__);
3225 done:
3226 ret_v = caml_copy_double ((double) maxw);
3227 CAMLreturn (ret_v);
3230 ML (draw_string (value pt_v, value x_v, value y_v, value string_v))
3232 CAMLparam4 (pt_v, x_v, y_v, string_v);
3233 CAMLlocal1 (ret_v);
3234 int pt = Int_val(pt_v);
3235 int x = Int_val (x_v);
3236 int y = Int_val (y_v);
3237 float w;
3239 w = draw_string (state.face, pt, x, y, String_val (string_v));
3240 ret_v = caml_copy_double (w);
3241 CAMLreturn (ret_v);
3244 ML (measure_string (value pt_v, value string_v))
3246 CAMLparam2 (pt_v, string_v);
3247 CAMLlocal1 (ret_v);
3248 int pt = Int_val (pt_v);
3249 double w;
3251 w = (double) measure_string (state.face, pt, String_val (string_v));
3252 ret_v = caml_copy_double (w);
3253 CAMLreturn (ret_v);
3256 ML (getpagebox (value opaque_v))
3258 CAMLparam1 (opaque_v);
3259 CAMLlocal1 (ret_v);
3260 fz_rect rect;
3261 fz_irect bbox;
3262 fz_device *dev;
3263 const char *s = String_val (opaque_v);
3264 struct page *page = parse_pointer (__func__, s);
3266 ret_v = caml_alloc_tuple (4);
3267 dev = fz_new_bbox_device (state.ctx, &rect);
3269 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3271 fz_close_device (state.ctx, dev);
3272 fz_drop_device (state.ctx, dev);
3273 bbox = fz_round_rect (rect);
3274 Field (ret_v, 0) = Val_int (bbox.x0);
3275 Field (ret_v, 1) = Val_int (bbox.y0);
3276 Field (ret_v, 2) = Val_int (bbox.x1);
3277 Field (ret_v, 3) = Val_int (bbox.y1);
3279 CAMLreturn (ret_v);
3282 ML0 (setaalevel (value level_v))
3284 CAMLparam1 (level_v);
3286 state.aalevel = Int_val (level_v);
3287 CAMLreturn0;
3290 ML0 (setpapercolor (value rgba_v))
3292 CAMLparam1 (rgba_v);
3294 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3295 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3296 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3297 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3298 CAMLreturn0;
3301 value ml_keysymtoutf8 (value keysym_v);
3302 #ifndef CIDER
3303 value ml_keysymtoutf8 (value keysym_v)
3305 CAMLparam1 (keysym_v);
3306 CAMLlocal1 (str_v);
3307 unsigned short keysym = (unsigned short) Int_val (keysym_v);
3308 Rune rune;
3309 extern long keysym2ucs (unsigned short);
3310 int len;
3311 char buf[5];
3313 rune = (Rune) keysym2ucs (keysym);
3314 len = fz_runetochar (buf, rune);
3315 buf[len] = 0;
3316 str_v = caml_copy_string (buf);
3317 CAMLreturn (str_v);
3319 #else
3320 value ml_keysymtoutf8 (value keysym_v)
3322 CAMLparam1 (keysym_v);
3323 CAMLlocal1 (str_v);
3324 long ucs = Long_val (keysym_v);
3325 int len;
3326 char buf[5];
3328 len = fz_runetochar (buf, (int) ucs);
3329 buf[len] = 0;
3330 str_v = caml_copy_string (buf);
3331 CAMLreturn (str_v);
3333 #endif
3335 enum { piunknown, pilinux, pimacos, pibsd };
3337 ML (platform (value unit_v))
3339 CAMLparam1 (unit_v);
3340 CAMLlocal2 (tup_v, arr_v);
3341 int platid = piunknown;
3342 struct utsname buf;
3344 #if defined __linux__
3345 platid = pilinux;
3346 #elif defined __DragonFly__ || defined __FreeBSD__
3347 || defined __OpenBSD__ || defined __NetBSD__
3348 platid = pibsd;
3349 #elif defined __APPLE__
3350 platid = pimacos;
3351 #endif
3352 if (uname (&buf)) err (1, "uname");
3354 tup_v = caml_alloc_tuple (2);
3356 char const *sar[] = {
3357 buf.sysname,
3358 buf.release,
3359 buf.version,
3360 buf.machine,
3361 NULL
3363 arr_v = caml_copy_string_array (sar);
3365 Field (tup_v, 0) = Val_int (platid);
3366 Field (tup_v, 1) = arr_v;
3367 CAMLreturn (tup_v);
3370 ML0 (cloexec (value fd_v))
3372 CAMLparam1 (fd_v);
3373 int fd = Int_val (fd_v);
3375 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3376 uerror ("fcntl", Nothing);
3378 CAMLreturn0;
3381 ML (getpbo (value w_v, value h_v, value cs_v))
3383 CAMLparam2 (w_v, h_v);
3384 CAMLlocal1 (ret_v);
3385 struct bo *pbo;
3386 int w = Int_val (w_v);
3387 int h = Int_val (h_v);
3388 int cs = Int_val (cs_v);
3390 if (state.bo_usable) {
3391 pbo = calloc (sizeof (*pbo), 1);
3392 if (!pbo) {
3393 err (1, "calloc pbo");
3396 switch (cs) {
3397 case 0:
3398 case 1:
3399 pbo->size = w*h*4;
3400 break;
3401 case 2:
3402 pbo->size = w*h*2;
3403 break;
3404 default:
3405 errx (1, "%s: invalid colorspace %d", __func__, cs);
3408 state.glGenBuffersARB (1, &pbo->id);
3409 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3410 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3411 NULL, GL_STREAM_DRAW);
3412 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3413 GL_READ_WRITE);
3414 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3415 if (!pbo->ptr) {
3416 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3417 state.glDeleteBuffersARB (1, &pbo->id);
3418 free (pbo);
3419 ret_v = caml_copy_string ("0");
3421 else {
3422 int res;
3423 char *s;
3425 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3426 if (res < 0) {
3427 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3429 s = malloc (res+1);
3430 if (!s) {
3431 err (1, "malloc %d bytes failed", res+1);
3433 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3434 if (res < 0) {
3435 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3437 ret_v = caml_copy_string (s);
3438 free (s);
3441 else {
3442 ret_v = caml_copy_string ("0");
3444 CAMLreturn (ret_v);
3447 ML0 (freepbo (value s_v))
3449 CAMLparam1 (s_v);
3450 const char *s = String_val (s_v);
3451 struct tile *tile = parse_pointer (__func__, s);
3453 if (tile->pbo) {
3454 state.glDeleteBuffersARB (1, &tile->pbo->id);
3455 tile->pbo->id = -1;
3456 tile->pbo->ptr = NULL;
3457 tile->pbo->size = -1;
3459 CAMLreturn0;
3462 ML0 (unmappbo (value s_v))
3464 CAMLparam1 (s_v);
3465 const char *s = String_val (s_v);
3466 struct tile *tile = parse_pointer (__func__, s);
3468 if (tile->pbo) {
3469 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3470 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3471 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3473 tile->pbo->ptr = NULL;
3474 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3476 CAMLreturn0;
3479 static void setuppbo (void)
3481 extern void (*wsigladdr (const char *name)) (void);
3482 #pragma GCC diagnostic push
3483 #ifdef __clang__
3484 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3485 #endif
3486 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3487 state.bo_usable = GPA (glBindBufferARB)
3488 && GPA (glUnmapBufferARB)
3489 && GPA (glMapBufferARB)
3490 && GPA (glBufferDataARB)
3491 && GPA (glGenBuffersARB)
3492 && GPA (glDeleteBuffersARB);
3493 #undef GPA
3494 #pragma GCC diagnostic pop
3497 ML (bo_usable (void))
3499 return Val_bool (state.bo_usable);
3502 ML (unproject (value ptr_v, value x_v, value y_v))
3504 CAMLparam3 (ptr_v, x_v, y_v);
3505 CAMLlocal2 (ret_v, tup_v);
3506 struct page *page;
3507 const char *s = String_val (ptr_v);
3508 int x = Int_val (x_v), y = Int_val (y_v);
3509 struct pagedim *pdim;
3510 fz_point p;
3512 page = parse_pointer (__func__, s);
3513 pdim = &state.pagedims[page->pdimno];
3515 ret_v = Val_int (0);
3516 if (trylock (__func__)) {
3517 goto done;
3520 p.x = x + pdim->bounds.x0;
3521 p.y = y + pdim->bounds.y0;
3523 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3524 pdim->ctm)));
3526 tup_v = caml_alloc_tuple (2);
3527 ret_v = caml_alloc_small (1, 1);
3528 Field (tup_v, 0) = Val_int (p.x);
3529 Field (tup_v, 1) = Val_int (p.y);
3530 Field (ret_v, 0) = tup_v;
3532 unlock (__func__);
3533 done:
3534 CAMLreturn (ret_v);
3537 ML (project (value ptr_v, value pageno_v, value pdimno_v, value x_v, value y_v))
3539 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3540 CAMLlocal1 (ret_v);
3541 struct page *page;
3542 const char *s = String_val (ptr_v);
3543 int pageno = Int_val (pageno_v);
3544 int pdimno = Int_val (pdimno_v);
3545 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3546 struct pagedim *pdim;
3547 fz_point p;
3548 fz_matrix ctm;
3550 ret_v = Val_int (0);
3551 lock (__func__);
3553 if (!*s) {
3554 page = loadpage (pageno, pdimno);
3556 else {
3557 page = parse_pointer (__func__, s);
3559 pdim = &state.pagedims[pdimno];
3561 if (pdf_specifics (state.ctx, state.doc)) {
3562 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3563 ctm = state.pagedims[page->pdimno].tctm;
3565 else {
3566 ctm = fz_identity;
3568 p.x = x + pdim->bounds.x0;
3569 p.y = y + pdim->bounds.y0;
3571 ctm = fz_concat (pdim->tctm, pdim->ctm);
3572 p = fz_transform_point (p, ctm);
3574 ret_v = caml_alloc_tuple (2);
3575 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3576 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3578 if (!*s) {
3579 freepage (page);
3581 unlock (__func__);
3582 CAMLreturn (ret_v);
3585 ML0 (addannot (value ptr_v, value x_v, value y_v, value contents_v))
3587 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3588 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3590 if (pdf) {
3591 pdf_annot *annot;
3592 struct page *page;
3593 fz_rect r;
3594 const char *s = String_val (ptr_v);
3596 page = parse_pointer (__func__, s);
3597 annot = pdf_create_annot (state.ctx,
3598 pdf_page_from_fz_page (state.ctx,
3599 page->fzpage),
3600 PDF_ANNOT_TEXT);
3601 r.x0 = Int_val (x_v) - 10;
3602 r.y0 = Int_val (y_v) - 10;
3603 r.x1 = r.x0 + 20;
3604 r.y1 = r.y0 + 20;
3605 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3606 pdf_set_annot_rect (state.ctx, annot, r);
3608 state.dirty = 1;
3610 CAMLreturn0;
3613 ML0 (delannot (value ptr_v, value n_v))
3615 CAMLparam2 (ptr_v, n_v);
3616 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3618 if (pdf) {
3619 struct page *page;
3620 const char *s = String_val (ptr_v);
3621 struct slink *slink;
3623 page = parse_pointer (__func__, s);
3624 slink = &page->slinks[Int_val (n_v)];
3625 pdf_delete_annot (state.ctx,
3626 pdf_page_from_fz_page (state.ctx, page->fzpage),
3627 (pdf_annot *) slink->u.annot);
3628 state.dirty = 1;
3630 CAMLreturn0;
3633 ML0 (modannot (value ptr_v, value n_v, value str_v))
3635 CAMLparam3 (ptr_v, n_v, str_v);
3636 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3638 if (pdf) {
3639 struct page *page;
3640 const char *s = String_val (ptr_v);
3641 struct slink *slink;
3643 page = parse_pointer (__func__, s);
3644 slink = &page->slinks[Int_val (n_v)];
3645 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3646 String_val (str_v));
3647 state.dirty = 1;
3649 CAMLreturn0;
3652 ML (hasunsavedchanges (void))
3654 return Val_bool (state.dirty);
3657 ML0 (savedoc (value path_v))
3659 CAMLparam1 (path_v);
3660 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3662 if (pdf) {
3663 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3665 CAMLreturn0;
3668 static void makestippletex (void)
3670 const char pixels[] = "\xff\xff\0\0";
3671 glGenTextures (1, &state.stid);
3672 glBindTexture (GL_TEXTURE_1D, state.stid);
3673 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3674 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3675 glTexImage1D (
3676 GL_TEXTURE_1D,
3678 GL_ALPHA,
3681 GL_ALPHA,
3682 GL_UNSIGNED_BYTE,
3683 pixels
3687 ML (fz_version (void))
3689 return caml_copy_string (FZ_VERSION);
3692 ML (llpp_version (void))
3694 extern char llpp_version[];
3695 return caml_copy_string (llpp_version);
3698 static void diag_callback (void *user, const char *message)
3700 printd ("emsg %s %s", (char *) user, message);
3703 static fz_font *lsff (fz_context *ctx,int UNUSED_ATTR script,
3704 int UNUSED_ATTR language, int UNUSED_ATTR serif,
3705 int UNUSED_ATTR bold, int UNUSED_ATTR italic)
3707 static fz_font *font;
3708 static int done;
3710 if (!done) {
3711 char *path = getenv ("LLPP_FALLBACK_FONT");
3712 if (path) font = fz_new_font_from_file (ctx, NULL, path, 0, 1);
3713 done = 1;
3715 return font;
3718 ML0 (setdcf (value path_v))
3720 free (state.dcf);
3721 state.dcf = NULL;
3722 const char *p = String_val (path_v);
3723 size_t len = strlen (p);
3724 if (*p) {
3725 state.dcf = malloc (len + 1);
3726 if (!state.dcf) {
3727 err (1, "malloc dimpath %zu", len + 1);
3729 memcpy (state.dcf, p, len + 1);
3733 ML0 (init (value csock_v, value params_v))
3735 CAMLparam2 (csock_v, params_v);
3736 CAMLlocal2 (trim_v, fuzz_v);
3737 int ret;
3738 int texcount;
3739 const char *fontpath;
3740 int colorspace;
3741 int mustoresize;
3743 state.csock = Int_val (csock_v);
3744 state.rotate = Int_val (Field (params_v, 0));
3745 state.fitmodel = Int_val (Field (params_v, 1));
3746 trim_v = Field (params_v, 2);
3747 texcount = Int_val (Field (params_v, 3));
3748 state.sliceheight = Int_val (Field (params_v, 4));
3749 mustoresize = Int_val (Field (params_v, 5));
3750 colorspace = Int_val (Field (params_v, 6));
3751 fontpath = String_val (Field (params_v, 7));
3753 #ifdef CIDER
3754 state.utf8cs = 1;
3755 #else
3756 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3757 if (setlocale (LC_CTYPE, "")) {
3758 const char *cset = nl_langinfo (CODESET);
3759 state.utf8cs = !strcmp (cset, "UTF-8");
3761 else {
3762 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3764 #endif
3766 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3767 fz_register_document_handlers (state.ctx);
3768 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3769 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3770 fz_install_load_system_font_funcs (state.ctx, NULL, NULL, lsff);
3772 state.trimmargins = Bool_val (Field (trim_v, 0));
3773 fuzz_v = Field (trim_v, 1);
3774 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3775 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3776 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3777 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3779 set_tex_params (colorspace);
3781 if (*fontpath) {
3782 state.face = load_font (fontpath);
3784 else {
3785 int len;
3786 const unsigned char *data;
3788 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3789 state.face = load_builtin_font (data, len);
3791 if (!state.face) _exit (1);
3793 realloctexts (texcount);
3794 setuppbo ();
3795 makestippletex ();
3797 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3798 if (ret) {
3799 errx (1, "pthread_create: %s", strerror (ret));
3802 CAMLreturn0;
3805 #if FIXME || !FIXME
3806 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3807 #endif