Save the bandwidth
[llpp.git] / link.c
blob26ab1d1a22df3d48e3a77c302eee54ad4621555b
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;
163 int texindex;
164 int texcount;
165 GLuint *texids;
167 GLenum texiform;
168 GLenum texform;
169 GLenum texty;
171 fz_colorspace *colorspace;
172 float papercolor[4];
174 struct {
175 int w, h;
176 struct slice *slice;
177 } *texowners;
179 int rotate;
180 int fitmodel;
181 int trimmargins;
182 int needoutline;
183 int gen;
184 int aalevel;
186 int trimanew;
187 fz_irect trimfuzz;
188 fz_pixmap *pig;
190 pthread_t thread;
191 int csock;
192 FT_Face face;
194 char *trimcachepath;
195 int dirty;
197 GLuint stid;
199 int bo_usable;
200 GLuint boid;
202 void (*glBindBufferARB) (GLenum, GLuint);
203 GLboolean (*glUnmapBufferARB) (GLenum);
204 void *(*glMapBufferARB) (GLenum, GLenum);
205 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
206 void (*glGenBuffersARB) (GLsizei, GLuint *);
207 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
209 GLfloat texcoords[8];
210 GLfloat vertices[16];
212 int utf8cs;
213 } state;
215 struct bo {
216 GLuint id;
217 void *ptr;
218 size_t size;
221 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
223 static void lock (const char *cap)
225 int ret = pthread_mutex_lock (&mutex);
226 if (ret) {
227 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
231 static void unlock (const char *cap)
233 int ret = pthread_mutex_unlock (&mutex);
234 if (ret) {
235 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
239 static int trylock (const char *cap)
241 int ret = pthread_mutex_trylock (&mutex);
242 if (ret && ret != EBUSY) {
243 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
245 return ret == EBUSY;
248 static int hasdata (void)
250 int ret, avail;
251 ret = ioctl (state.csock, FIONREAD, &avail);
252 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
253 return avail > 0;
256 ML (hasdata (value fd_v))
258 CAMLparam1 (fd_v);
259 int ret, avail;
261 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
262 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
263 CAMLreturn (Val_bool (avail > 0));
266 static void readdata (int fd, void *p, int size)
268 ssize_t n;
270 again:
271 n = read (fd, p, size);
272 if (n - size) {
273 if (n < 0 && errno == EINTR) goto again;
274 if (!n) errx (1, "EOF while reading");
275 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
279 static void writedata (int fd, char *p, int size)
281 ssize_t n;
282 uint32_t size4 = size;
283 struct iovec iov[2] = {
284 { .iov_base = &size4, .iov_len = 4 },
285 { .iov_base = p, .iov_len = size }
288 again:
289 n = writev (fd, iov, 2);
290 if (n < 0 && errno == EINTR) goto again;
291 if (n - size - 4) {
292 if (!n) errx (1, "EOF while writing data");
293 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
297 static int readlen (int fd)
299 uint32_t u;
300 readdata (fd, &u, 4);
301 return u;
304 ML0 (wcmd (value fd_v, value bytes_v, value len_v))
306 CAMLparam3 (fd_v, bytes_v, len_v);
307 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
308 CAMLreturn0;
311 ML (rcmd (value fd_v))
313 CAMLparam1 (fd_v);
314 CAMLlocal1 (strdata_v);
315 int fd = Int_val (fd_v);
316 int len = readlen (fd);
317 strdata_v = caml_alloc_string (len);
318 readdata (fd, Bytes_val (strdata_v), len);
319 CAMLreturn (strdata_v);
322 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
324 char fbuf[64];
325 int size = sizeof (fbuf), len;
326 va_list ap;
327 char *buf = fbuf;
329 for (;;) {
330 va_start (ap, fmt);
331 len = vsnprintf (buf, size, fmt, ap);
332 va_end (ap);
334 if (len > -1) {
335 if (len < size - 4) {
336 writedata (state.csock, buf, len);
337 break;
339 else size = len + 5;
341 else {
342 err (1, "vsnprintf for `%s' failed", fmt);
344 buf = realloc (buf == fbuf ? NULL : buf, size);
345 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
347 if (buf != fbuf) free (buf);
350 static void closedoc (void)
352 if (state.doc) {
353 fz_drop_document (state.ctx, state.doc);
354 state.doc = NULL;
358 static int openxref (char *filename, char *password, int layouth)
360 for (int i = 0; i < state.texcount; ++i) {
361 state.texowners[i].w = -1;
362 state.texowners[i].slice = NULL;
365 closedoc ();
367 state.dirty = 0;
368 if (state.pagedims) {
369 free (state.pagedims);
370 state.pagedims = NULL;
372 state.pagedimcount = 0;
374 fz_set_aa_level (state.ctx, state.aalevel);
375 state.doc = fz_open_document (state.ctx, filename);
376 if (fz_needs_password (state.ctx, state.doc)) {
377 if (password && !*password) {
378 printd ("pass");
379 return 0;
381 else {
382 int ok = fz_authenticate_password (state.ctx, state.doc, password);
383 if (!ok) {
384 printd ("pass fail");
385 return 0;
389 if (layouth >= 0)
390 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; } metatbl[] = {
398 { FZ_META_INFO_TITLE, "Title" },
399 { FZ_META_INFO_AUTHOR, "Author" },
400 { FZ_META_FORMAT, "Format" },
401 { FZ_META_ENCRYPTION, "Encryption" },
402 { "info:Creator", "Creator" },
403 { "info:Producer", "Producer" },
404 { "info:CreationDate", "Creation date" },
406 int len = 0;
407 char *buf = NULL;
409 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
410 int need;
411 again:
412 need = fz_lookup_metadata (state.ctx, state.doc,
413 metatbl[i].tag, buf, len);
414 if (need > 0) {
415 if (need <= len) {
416 printd ("info %s\t%s", metatbl[i].name, buf);
418 else {
419 buf = realloc (buf, need + 1);
420 if (!buf) err (1, "docinfo realloc %d", need + 1);
421 len = need + 1;
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.texowners[s->texindex].slice == s) {
438 state.texowners[s->texindex].slice = NULL;
444 static void freepage (struct page *page)
446 if (!page) return;
447 if (page->text) {
448 fz_drop_stext_page (state.ctx, page->text);
450 if (page->slinks) {
451 free (page->slinks);
453 fz_drop_display_list (state.ctx, page->dlist);
454 fz_drop_page (state.ctx, page->fzpage);
455 free (page);
458 static void freetile (struct tile *tile)
460 unlinktile (tile);
461 if (!tile->pbo) {
462 #if 0
463 fz_drop_pixmap (state.ctx, tile->pixmap);
464 #else /* piggyback */
465 if (state.pig) {
466 fz_drop_pixmap (state.ctx, state.pig);
468 state.pig = tile->pixmap;
469 #endif
471 else {
472 free (tile->pbo);
473 fz_drop_pixmap (state.ctx, tile->pixmap);
475 free (tile);
478 static void trimctm (pdf_page *page, int pindex)
480 struct pagedim *pdim = &state.pagedims[pindex];
482 if (!page) return;
483 if (!pdim->tctmready) {
484 fz_rect realbox, mediabox;
485 fz_matrix page_ctm, ctm;
487 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
488 realbox = fz_transform_rect (pdim->mediabox, ctm);
489 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
490 pdim->tctm = fz_concat (
491 fz_invert_matrix (page_ctm),
492 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
493 pdim->tctmready = 1;
497 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
499 fz_matrix ctm;
500 ptrdiff_t pdimno = pdim - state.pagedims;
502 ARSERT (pdim - state.pagedims < INT_MAX);
503 if (pdf_specifics (state.ctx, state.doc)) {
504 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
505 ctm = fz_concat (pdim->tctm, pdim->ctm);
507 else {
508 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
509 pdim->ctm);
511 return ctm;
514 static fz_matrix pagectm (struct page *page)
516 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
519 static void *loadpage (int pageno, int pindex)
521 fz_device *dev;
522 struct page *page;
524 page = calloc (sizeof (struct page), 1);
525 if (!page) {
526 err (1, "calloc page %d", pageno);
529 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
530 dev = fz_new_list_device (state.ctx, page->dlist);
531 fz_try (state.ctx) {
532 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
533 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
535 fz_catch (state.ctx) {
536 page->fzpage = NULL;
538 fz_close_device (state.ctx, dev);
539 fz_drop_device (state.ctx, dev);
541 page->pdimno = pindex;
542 page->pageno = pageno;
543 page->sgen = state.gen;
544 page->agen = state.gen;
545 page->tgen = state.gen;
546 return page;
549 static struct tile *alloctile (int h)
551 int slicecount;
552 size_t tilesize;
553 struct tile *tile;
555 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
556 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
557 tile = calloc (tilesize, 1);
558 if (!tile) {
559 err (1, "cannot allocate tile (%zu bytes)", tilesize);
561 for (int i = 0; i < slicecount; ++i) {
562 int sh = fz_mini (h, state.sliceheight);
563 tile->slices[i].h = sh;
564 tile->slices[i].texindex = -1;
565 h -= sh;
567 tile->slicecount = slicecount;
568 tile->sliceheight = state.sliceheight;
569 return tile;
572 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
573 struct bo *pbo)
575 fz_irect bbox;
576 fz_matrix ctm;
577 fz_device *dev;
578 struct tile *tile;
579 struct pagedim *pdim;
581 tile = alloctile (h);
582 pdim = &state.pagedims[page->pdimno];
584 bbox = pdim->bounds;
585 bbox.x0 += x;
586 bbox.y0 += y;
587 bbox.x1 = bbox.x0 + w;
588 bbox.y1 = bbox.y0 + h;
590 if (state.pig) {
591 if (state.pig->w == w
592 && state.pig->h == h
593 && state.pig->colorspace == state.colorspace) {
594 tile->pixmap = state.pig;
595 tile->pixmap->x = bbox.x0;
596 tile->pixmap->y = bbox.y0;
598 else {
599 fz_drop_pixmap (state.ctx, state.pig);
601 state.pig = NULL;
603 if (!tile->pixmap) {
604 if (pbo) {
605 tile->pixmap =
606 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
607 bbox, NULL, 1, pbo->ptr);
608 tile->pbo = pbo;
610 else {
611 tile->pixmap =
612 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
613 NULL, 1);
617 tile->w = w;
618 tile->h = h;
619 fz_fill_pixmap_with_color (state.ctx, tile->pixmap,
620 fz_device_rgb (state.ctx),
621 state.papercolor,
622 fz_default_color_params);
624 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
625 ctm = pagectm (page);
626 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
627 fz_rect_from_irect (bbox), NULL);
628 fz_close_device (state.ctx, dev);
629 fz_drop_device (state.ctx, dev);
631 return tile;
634 static void initpdims (void)
636 FILE *trimf = NULL;
637 int pageno, trim, show;
638 int trimw = 0, cxcount;
639 struct pagedim *p = NULL;
640 fz_context *ctx = state.ctx;
641 fz_rect rootmediabox = fz_empty_rect;
642 pdf_document *pdf = pdf_specifics (ctx, state.doc);
644 fz_var (p);
645 fz_var (trimw);
646 fz_var (trimf);
647 fz_var (cxcount);
649 if (state.trimmargins && state.trimcachepath) {
650 trimf = fopen (state.trimcachepath, "rb");
651 if (!trimf) {
652 trimf = fopen (state.trimcachepath, "wb");
653 trimw = 1;
657 cxcount = state.pagecount;
658 if (pdf) {
659 pdf_obj *obj;
660 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
661 "Root/Pages/MediaBox");
662 rootmediabox = pdf_to_rect (ctx, obj);
663 pdf_load_page_tree (ctx, pdf);
666 for (pageno = 0; pageno < cxcount; ++pageno) {
667 int rotate = 0;
668 fz_rect mediabox = fz_empty_rect;
670 fz_var (rotate);
671 if (pdf) {
672 pdf_obj *pageobj = NULL;
674 fz_var (pageobj);
675 if (pdf->rev_page_map) {
676 for (int i = 0; i < pdf->rev_page_count; ++i) {
677 if (pdf->rev_page_map[i].page == pageno) {
678 pageobj = pdf_get_xref_entry (
679 ctx, pdf, pdf->rev_page_map[i].object
680 )->obj;
681 break;
685 if (!pageobj) {
686 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
689 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
691 if (state.trimmargins) {
692 pdf_obj *obj;
693 pdf_page *page;
695 fz_try (ctx) {
696 page = pdf_load_page (ctx, pdf, pageno);
697 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
698 trim = state.trimanew || !obj;
699 if (trim) {
700 fz_rect rect;
701 fz_device *dev;
702 fz_matrix ctm, page_ctm;
704 dev = fz_new_bbox_device (ctx, &rect);
705 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
706 ctm = fz_invert_matrix (page_ctm);
707 pdf_run_page (ctx, page, dev, fz_identity, NULL);
708 fz_close_device (ctx, dev);
709 fz_drop_device (ctx, dev);
711 rect.x0 += state.trimfuzz.x0;
712 rect.x1 += state.trimfuzz.x1;
713 rect.y0 += state.trimfuzz.y0;
714 rect.y1 += state.trimfuzz.y1;
715 rect = fz_transform_rect (rect, ctm);
716 rect = fz_intersect_rect (rect, mediabox);
718 if (!fz_is_empty_rect (rect)) {
719 mediabox = rect;
722 obj = pdf_new_array (ctx, pdf, 4);
723 pdf_array_push_real (ctx, obj, mediabox.x0);
724 pdf_array_push_real (ctx, obj, mediabox.y0);
725 pdf_array_push_real (ctx, obj, mediabox.x1);
726 pdf_array_push_real (ctx, obj, mediabox.y1);
727 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
729 else {
730 mediabox.x0 = pdf_array_get_real (ctx, obj, 0);
731 mediabox.y0 = pdf_array_get_real (ctx, obj, 1);
732 mediabox.x1 = pdf_array_get_real (ctx, obj, 2);
733 mediabox.y1 = pdf_array_get_real (ctx, obj, 3);
736 fz_drop_page (ctx, &page->super);
737 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
738 if (show) {
739 printd ("progress %f Trimming %d",
740 (double) (pageno + 1) / state.pagecount,
741 pageno + 1);
744 fz_catch (ctx) {
745 printd ("emsg failed to load page %d", pageno);
748 else {
749 int empty = 0;
750 fz_rect cropbox;
752 mediabox =
753 pdf_to_rect (ctx, pdf_dict_get_inheritable (
754 ctx,
755 pageobj,
756 PDF_NAME (MediaBox)
759 if (fz_is_empty_rect (mediabox)) {
760 mediabox.x0 = 0;
761 mediabox.y0 = 0;
762 mediabox.x1 = 612;
763 mediabox.y1 = 792;
764 empty = 1;
767 cropbox =
768 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
769 if (!fz_is_empty_rect (cropbox)) {
770 if (empty) {
771 mediabox = cropbox;
773 else {
774 mediabox = fz_intersect_rect (mediabox, cropbox);
777 else {
778 if (empty) {
779 if (fz_is_empty_rect (rootmediabox)) {
780 printd ("emsg cannot find page size for page %d",
781 pageno);
783 else {
784 mediabox = rootmediabox;
790 else {
791 if (state.trimmargins && trimw) {
792 fz_page *page;
794 fz_try (ctx) {
795 page = fz_load_page (ctx, state.doc, pageno);
796 mediabox = fz_bound_page (ctx, page);
797 if (state.trimmargins) {
798 fz_rect rect;
799 fz_device *dev;
801 dev = fz_new_bbox_device (ctx, &rect);
802 fz_run_page (ctx, page, dev, fz_identity, NULL);
803 fz_close_device (ctx, dev);
804 fz_drop_device (ctx, dev);
806 rect.x0 += state.trimfuzz.x0;
807 rect.x1 += state.trimfuzz.x1;
808 rect.y0 += state.trimfuzz.y0;
809 rect.y1 += state.trimfuzz.y1;
810 rect = fz_intersect_rect (rect, mediabox);
812 if (!fz_is_empty_rect (rect)) {
813 mediabox = rect;
816 fz_drop_page (ctx, page);
818 fz_catch (ctx) {
820 if (trimf) {
821 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
822 if (n - 1) {
823 err (1, "fwrite trim mediabox");
827 else {
828 if (trimf) {
829 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
830 if (n - 1) {
831 err (1, "fread trim mediabox %d", pageno);
834 else {
835 fz_page *page;
836 fz_try (ctx) {
837 page = fz_load_page (ctx, state.doc, pageno);
838 mediabox = fz_bound_page (ctx, page);
839 fz_drop_page (ctx, page);
841 show = !state.trimmargins && pageno % 20 == 0;
842 if (show) {
843 printd ("progress %f Gathering dimensions %d",
844 (double) (pageno) / state.pagecount,
845 pageno);
848 fz_catch (ctx) {
849 printd ("emsg failed to load page %d", pageno);
855 if (!p || p->rotate != rotate
856 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
857 size_t size;
859 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
860 state.pagedims = realloc (state.pagedims, size);
861 if (!state.pagedims) {
862 err (1, "realloc pagedims to %zu (%d elems)",
863 size, state.pagedimcount + 1);
866 p = &state.pagedims[state.pagedimcount++];
867 p->rotate = rotate;
868 p->mediabox = mediabox;
869 p->pageno = pageno;
872 state.trimanew = 0;
873 if (trimf) {
874 if (fclose (trimf)) {
875 err (1, "fclose");
880 static void layout (void)
882 int pindex;
883 fz_rect box;
884 fz_matrix ctm;
885 struct pagedim *p = NULL;
886 float zw, w, maxw = 0.0, zoom = 1.0;
888 if (state.pagedimcount == 0) return;
890 switch (state.fitmodel) {
891 case FitProportional:
892 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
893 float x0, x1;
895 p = &state.pagedims[pindex];
896 box = fz_transform_rect (p->mediabox,
897 fz_rotate (p->rotate + state.rotate));
899 x0 = fz_min (box.x0, box.x1);
900 x1 = fz_max (box.x0, box.x1);
902 w = x1 - x0;
903 maxw = fz_max (w, maxw);
904 zoom = state.w / maxw;
906 break;
908 case FitPage:
909 maxw = state.w;
910 break;
912 case FitWidth:
913 break;
915 default:
916 ARSERT (0 && state.fitmodel);
919 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
920 p = &state.pagedims[pindex];
921 ctm = fz_rotate (state.rotate);
922 box = fz_transform_rect (p->mediabox,
923 fz_rotate (p->rotate + state.rotate));
924 w = box.x1 - box.x0;
925 switch (state.fitmodel) {
926 case FitProportional:
927 p->left = (int) (((maxw - w) * zoom) / 2.f);
928 break;
929 case FitPage:
931 float zh, h;
932 zw = maxw / w;
933 h = box.y1 - box.y0;
934 zh = state.h / h;
935 zoom = fz_min (zw, zh);
936 p->left = (int) ((maxw - (w * zoom)) / 2.f);
938 break;
939 case FitWidth:
940 p->left = 0;
941 zoom = state.w / w;
942 break;
945 p->zoomctm = fz_scale (zoom, zoom);
946 ctm = fz_concat (p->zoomctm, ctm);
948 p->pagebox = p->mediabox;
949 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
950 p->pagebox.x1 -= p->pagebox.x0;
951 p->pagebox.y1 -= p->pagebox.y0;
952 p->pagebox.x0 = 0;
953 p->pagebox.y0 = 0;
954 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
955 p->ctm = ctm;
957 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
958 fz_scale (zoom, -zoom));
959 p->tctmready = 0;
962 do {
963 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
964 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
965 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
966 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
967 int boundw = x1 - x0;
968 int boundh = y1 - y0;
970 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
971 } while (p-- != state.pagedims);
974 static struct pagedim *pdimofpageno (int pageno)
976 struct pagedim *pdim = state.pagedims;
978 for (int i = 0; i < state.pagedimcount; ++i) {
979 if (state.pagedims[i].pageno > pageno)
980 break;
981 pdim = &state.pagedims[i];
983 return pdim;
986 static void recurse_outline (fz_outline *outline, int level)
988 while (outline) {
989 if (outline->page >= 0) {
990 fz_point p = {.x = outline->x, .y = outline->y};
991 struct pagedim *pdim = pdimofpageno (outline->page);
992 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
993 p = fz_transform_point (p, pdim->ctm);
994 printd ("o %d %d %d %d %s",
995 level, outline->page, (int) p.y, h, outline->title);
997 else {
998 printd ("on %d %s", level, outline->title);
1000 if (outline->down) {
1001 recurse_outline (outline->down, level + 1);
1003 outline = outline->next;
1007 static void process_outline (void)
1009 fz_outline *outline;
1011 if (!state.needoutline || !state.pagedimcount) return;
1013 state.needoutline = 0;
1014 outline = fz_load_outline (state.ctx, state.doc);
1015 if (outline) {
1016 recurse_outline (outline, 0);
1017 fz_drop_outline (state.ctx, outline);
1021 static char *strofline (fz_stext_line *line)
1023 char *p;
1024 char utf8[10];
1025 fz_stext_char *ch;
1026 size_t size = 0, cap = 80;
1028 p = malloc (cap + 1);
1029 if (!p) return NULL;
1031 for (ch = line->first_char; ch; ch = ch->next) {
1032 int n = fz_runetochar (utf8, ch->c);
1033 if (size + n > cap) {
1034 cap *= 2;
1035 p = realloc (p, cap + 1);
1036 if (!p) return NULL;
1039 memcpy (p + size, utf8, n);
1040 size += n;
1042 p[size] = 0;
1043 return p;
1046 static int matchline (regex_t *re, fz_stext_line *line,
1047 int stop, int pageno, double start)
1049 int ret;
1050 char *p;
1051 regmatch_t rm;
1053 p = strofline (line);
1054 if (!p) return -1;
1056 ret = regexec (re, p, 1, &rm, 0);
1057 if (ret) {
1058 free (p);
1059 if (ret != REG_NOMATCH) {
1060 size_t size;
1061 char errbuf[80];
1062 size = regerror (ret, re, errbuf, sizeof (errbuf));
1063 printd ("msg regexec error `%.*s'",
1064 (int) size, errbuf);
1065 return -1;
1067 return 0;
1069 else {
1070 fz_quad s, e;
1071 fz_stext_char *ch;
1072 int o = 0;
1074 for (ch = line->first_char; ch; ch = ch->next) {
1075 o += fz_runelen (ch->c);
1076 if (o > rm.rm_so) {
1077 s = ch->quad;
1078 break;
1081 for (;ch; ch = ch->next) {
1082 o += fz_runelen (ch->c);
1083 if (o > rm.rm_eo) break;
1085 e = ch->quad;
1087 if (!stop) {
1088 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1089 pageno, 1,
1090 s.ul.x, s.ul.y,
1091 e.ur.x, s.ul.y,
1092 e.lr.x, e.lr.y,
1093 s.ul.x, e.lr.y);
1095 printd ("progress 1 found at %d `%.*s' in %f sec",
1096 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1097 now () - start);
1099 else {
1100 printd ("match %d %d %f %f %f %f %f %f %f %f",
1101 pageno, 2,
1102 s.ul.x, s.ul.y,
1103 e.ur.x, s.ul.y,
1104 e.lr.x, e.lr.y,
1105 s.ul.x, e.lr.y);
1107 free (p);
1108 return 1;
1112 /* wishful thinking function */
1113 static void search (regex_t *re, int pageno, int y, int forward)
1115 fz_device *tdev;
1116 fz_stext_page *text;
1117 struct pagedim *pdim;
1118 int stop = 0, niters = 0;
1119 double start, end;
1120 fz_page *page;
1121 fz_stext_block *block;
1123 start = now ();
1124 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1125 if (niters++ == 5) {
1126 niters = 0;
1127 if (hasdata ()) {
1128 printd ("progress 1 attention requested aborting search at %d",
1129 pageno);
1130 stop = 1;
1132 else {
1133 printd ("progress %f searching in page %d",
1134 (double) (pageno + 1) / state.pagecount,
1135 pageno);
1138 pdim = pdimofpageno (pageno);
1139 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1140 tdev = fz_new_stext_device (state.ctx, text, 0);
1142 page = fz_load_page (state.ctx, state.doc, pageno);
1143 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1145 fz_close_device (state.ctx, tdev);
1146 fz_drop_device (state.ctx, tdev);
1148 if (forward) {
1149 for (block = text->first_block; block; block = block->next) {
1150 fz_stext_line *line;
1152 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1153 for (line = block->u.t.first_line; line; line = line->next) {
1154 if (line->bbox.y0 < y + 1) continue;
1156 switch (matchline (re, line, stop, pageno, start)) {
1157 case 0: break;
1158 case 1: stop = 1; break;
1159 case -1: stop = 1; goto endloop;
1164 else {
1165 for (block = text->last_block; block; block = block->prev) {
1166 fz_stext_line *line;
1168 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1169 for (line = block->u.t.last_line; line; line = line->prev) {
1170 if (line->bbox.y0 < y + 1) continue;
1172 switch (matchline (re, line, stop, pageno, start)) {
1173 case 0: break;
1174 case 1: stop = 1; break;
1175 case -1: stop = 1; goto endloop;
1181 if (forward) {
1182 pageno += 1;
1183 y = 0;
1185 else {
1186 pageno -= 1;
1187 y = INT_MAX;
1189 endloop:
1190 fz_drop_stext_page (state.ctx, text);
1191 fz_drop_page (state.ctx, page);
1193 end = now ();
1194 if (!stop) {
1195 printd ("progress 1 no matches %f sec", end - start);
1197 printd ("clearrects");
1200 static void set_tex_params (int colorspace)
1202 switch (colorspace) {
1203 case 0:
1204 state.texiform = GL_RGBA8;
1205 state.texform = GL_RGBA;
1206 state.texty = GL_UNSIGNED_BYTE;
1207 state.colorspace = fz_device_rgb (state.ctx);
1208 break;
1209 case 1:
1210 state.texiform = GL_LUMINANCE_ALPHA;
1211 state.texform = GL_LUMINANCE_ALPHA;
1212 state.texty = GL_UNSIGNED_BYTE;
1213 state.colorspace = fz_device_gray (state.ctx);
1214 break;
1215 default:
1216 errx (1, "invalid colorspce %d", colorspace);
1220 static void realloctexts (int texcount)
1222 size_t size;
1224 if (texcount == state.texcount) return;
1226 if (texcount < state.texcount) {
1227 glDeleteTextures (state.texcount - texcount,
1228 state.texids + texcount);
1231 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1232 state.texids = realloc (state.texids, size);
1233 if (!state.texids) {
1234 err (1, "realloc texs %zu", size);
1237 state.texowners = (void *) (state.texids + texcount);
1238 if (texcount > state.texcount) {
1239 glGenTextures (texcount - state.texcount,
1240 state.texids + state.texcount);
1241 for (int i = state.texcount; i < texcount; ++i) {
1242 state.texowners[i].w = -1;
1243 state.texowners[i].slice = NULL;
1246 state.texcount = texcount;
1247 state.texindex = 0;
1250 static char *mbtoutf8 (char *s)
1252 char *p, *r;
1253 wchar_t *tmp;
1254 size_t i, ret, len;
1256 if (state.utf8cs) {
1257 return s;
1260 len = mbstowcs (NULL, s, strlen (s));
1261 if (len == 0 || len == (size_t) -1) {
1262 if (len)
1263 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1264 return s;
1267 tmp = calloc (len, sizeof (wchar_t));
1268 if (!tmp) {
1269 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1270 len, sizeof (wchar_t), errno, strerror (errno));
1271 return s;
1274 ret = mbstowcs (tmp, s, len);
1275 if (ret == (size_t) -1) {
1276 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1277 len, errno, strerror (errno));
1278 free (tmp);
1279 return s;
1282 len = 0;
1283 for (i = 0; i < ret; ++i) {
1284 len += fz_runelen (tmp[i]);
1287 p = r = malloc (len + 1);
1288 if (!r) {
1289 printd ("emsg mbtoutf8: malloc(%zu)", len);
1290 free (tmp);
1291 return s;
1294 for (i = 0; i < ret; ++i) {
1295 p += fz_runetochar (p, tmp[i]);
1297 *p = 0;
1298 free (tmp);
1299 return r;
1302 ML (mbtoutf8 (value s_v))
1304 CAMLparam1 (s_v);
1305 CAMLlocal1 (ret_v);
1306 char *s, *r;
1308 s = &Byte (s_v, 0);
1309 r = mbtoutf8 (s);
1310 if (r == s) {
1311 ret_v = s_v;
1313 else {
1314 ret_v = caml_copy_string (r);
1315 free (r);
1317 CAMLreturn (ret_v);
1320 static void * mainloop (void UNUSED_ATTR *unused)
1322 char *p = NULL;
1323 int len, ret, oldlen = 0;
1325 fz_var (p);
1326 fz_var (oldlen);
1327 for (;;) {
1328 len = readlen (state.csock);
1329 if (len == 0) {
1330 errx (1, "readlen returned 0");
1333 if (oldlen < len + 1) {
1334 p = realloc (p, len + 1);
1335 if (!p) {
1336 err (1, "realloc %d failed", len + 1);
1338 oldlen = len + 1;
1340 readdata (state.csock, p, len);
1341 p[len] = 0;
1343 if (!strncmp ("open", p, 4)) {
1344 int off, usedoccss, ok = 0, layouth;
1345 char *password;
1346 char *filename;
1347 char *utf8filename;
1348 size_t filenamelen;
1350 fz_var (ok);
1351 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1352 if (ret != 2) {
1353 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1356 filename = p + 5 + off;
1357 filenamelen = strlen (filename);
1358 password = filename + filenamelen + 1;
1360 if (password[strlen (password) + 1]) {
1361 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1364 lock ("open");
1365 fz_set_use_document_css (state.ctx, usedoccss);
1366 fz_try (state.ctx) {
1367 ok = openxref (filename, password, layouth);
1369 fz_catch (state.ctx) {
1370 utf8filename = mbtoutf8 (filename);
1371 printd ("emsg Error loading %s: %s",
1372 utf8filename, fz_caught_message (state.ctx));
1373 if (utf8filename != filename) {
1374 free (utf8filename);
1377 if (ok) {
1378 docinfo ();
1379 initpdims ();
1381 unlock ("open");
1382 state.needoutline = ok;
1384 else if (!strncmp ("cs", p, 2)) {
1385 int i, colorspace;
1387 ret = sscanf (p + 2, " %d", &colorspace);
1388 if (ret != 1) {
1389 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1391 lock ("cs");
1392 set_tex_params (colorspace);
1393 for (i = 0; i < state.texcount; ++i) {
1394 state.texowners[i].w = -1;
1395 state.texowners[i].slice = NULL;
1397 unlock ("cs");
1399 else if (!strncmp ("freepage", p, 8)) {
1400 void *ptr;
1402 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1403 if (ret != 1) {
1404 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1406 lock ("freepage");
1407 freepage (ptr);
1408 unlock ("freepage");
1410 else if (!strncmp ("freetile", p, 8)) {
1411 void *ptr;
1413 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1414 if (ret != 1) {
1415 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1417 lock ("freetile");
1418 freetile (ptr);
1419 unlock ("freetile");
1421 else if (!strncmp ("search", p, 6)) {
1422 int icase, pageno, y, len2, forward;
1423 char *pattern;
1424 regex_t re;
1426 ret = sscanf (p + 6, " %d %d %d %d,%n",
1427 &icase, &pageno, &y, &forward, &len2);
1428 if (ret != 4) {
1429 errx (1, "malformed search `%s' ret=%d", p, ret);
1432 pattern = p + 6 + len2;
1433 ret = regcomp (&re, pattern,
1434 REG_EXTENDED | (icase ? REG_ICASE : 0));
1435 if (ret) {
1436 char errbuf[80];
1437 size_t size;
1439 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1440 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1442 else {
1443 lock ("search");
1444 search (&re, pageno, y, forward);
1445 unlock ("search");
1446 regfree (&re);
1449 else if (!strncmp ("geometry", p, 8)) {
1450 int w, h, fitmodel;
1452 printd ("clear");
1453 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1454 if (ret != 3) {
1455 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1458 lock ("geometry");
1459 state.h = h;
1460 if (w != state.w) {
1461 state.w = w;
1462 for (int i = 0; i < state.texcount; ++i) {
1463 state.texowners[i].slice = NULL;
1466 state.fitmodel = fitmodel;
1467 layout ();
1468 process_outline ();
1470 state.gen++;
1471 unlock ("geometry");
1472 printd ("continue %d", state.pagecount);
1474 else if (!strncmp ("reqlayout", p, 9)) {
1475 char *nameddest;
1476 int rotate, off, h;
1477 int fitmodel;
1478 pdf_document *pdf;
1480 printd ("clear");
1481 ret = sscanf (p + 9, " %d %d %d %n",
1482 &rotate, &fitmodel, &h, &off);
1483 if (ret != 3) {
1484 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1486 lock ("reqlayout");
1487 pdf = pdf_specifics (state.ctx, state.doc);
1488 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1489 state.gen += 1;
1491 state.rotate = rotate;
1492 state.fitmodel = fitmodel;
1493 state.h = h;
1494 layout ();
1495 process_outline ();
1497 nameddest = p + 9 + off;
1498 if (pdf && nameddest && *nameddest) {
1499 fz_point xy;
1500 struct pagedim *pdim;
1501 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1502 &xy.x, &xy.y);
1503 pdim = pdimofpageno (pageno);
1504 xy = fz_transform_point (xy, pdim->ctm);
1505 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1508 state.gen++;
1509 unlock ("reqlayout");
1510 printd ("continue %d", state.pagecount);
1512 else if (!strncmp ("page", p, 4)) {
1513 double a, b;
1514 struct page *page;
1515 int pageno, pindex;
1517 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1518 if (ret != 2) {
1519 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1522 lock ("page");
1523 a = now ();
1524 page = loadpage (pageno, pindex);
1525 b = now ();
1526 unlock ("page");
1528 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1530 else if (!strncmp ("tile", p, 4)) {
1531 int x, y, w, h;
1532 struct page *page;
1533 struct tile *tile;
1534 double a, b;
1535 void *data;
1537 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1538 (uintptr_t *) &page, &x, &y, &w, &h,
1539 (uintptr_t *) &data);
1540 if (ret != 6) {
1541 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1544 lock ("tile");
1545 a = now ();
1546 tile = rendertile (page, x, y, w, h, data);
1547 b = now ();
1548 unlock ("tile");
1550 printd ("tile %d %d %" PRIxPTR " %u %f",
1551 x, y, (uintptr_t) (tile),
1552 tile->w * tile->h * tile->pixmap->n,
1553 b - a);
1555 else if (!strncmp ("trimset", p, 7)) {
1556 fz_irect fuzz;
1557 int trimmargins;
1559 ret = sscanf (p + 7, " %d %d %d %d %d",
1560 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1561 if (ret != 5) {
1562 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1564 lock ("trimset");
1565 state.trimmargins = trimmargins;
1566 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1567 state.trimanew = 1;
1568 state.trimfuzz = fuzz;
1570 unlock ("trimset");
1572 else if (!strncmp ("settrim", p, 7)) {
1573 fz_irect fuzz;
1574 int trimmargins;
1576 ret = sscanf (p + 7, " %d %d %d %d %d",
1577 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1578 if (ret != 5) {
1579 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1581 printd ("clear");
1582 lock ("settrim");
1583 state.trimmargins = trimmargins;
1584 state.needoutline = 1;
1585 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1586 state.trimanew = 1;
1587 state.trimfuzz = fuzz;
1589 state.pagedimcount = 0;
1590 free (state.pagedims);
1591 state.pagedims = NULL;
1592 initpdims ();
1593 layout ();
1594 process_outline ();
1595 unlock ("settrim");
1596 printd ("continue %d", state.pagecount);
1598 else if (!strncmp ("sliceh", p, 6)) {
1599 int h;
1601 ret = sscanf (p + 6, " %d", &h);
1602 if (ret != 1) {
1603 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1605 if (h != state.sliceheight) {
1606 state.sliceheight = h;
1607 for (int i = 0; i < state.texcount; ++i) {
1608 state.texowners[i].w = -1;
1609 state.texowners[i].h = -1;
1610 state.texowners[i].slice = NULL;
1614 else if (!strncmp ("interrupt", p, 9)) {
1615 printd ("vmsg interrupted");
1617 else {
1618 errx (1, "unknown command %.*s", len, p);
1621 return 0;
1624 ML (isexternallink (value uri_v))
1626 CAMLparam1 (uri_v);
1627 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1628 CAMLreturn (Val_bool (ext));
1631 ML (uritolocation (value uri_v))
1633 CAMLparam1 (uri_v);
1634 CAMLlocal1 (ret_v);
1635 int pageno;
1636 fz_point xy;
1637 struct pagedim *pdim;
1639 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1640 &xy.x, &xy.y).page;
1641 pdim = pdimofpageno (pageno);
1642 xy = fz_transform_point (xy, pdim->ctm);
1643 ret_v = caml_alloc_tuple (3);
1644 Field (ret_v, 0) = Val_int (pageno);
1645 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1646 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1647 CAMLreturn (ret_v);
1650 ML (realloctexts (value texcount_v))
1652 CAMLparam1 (texcount_v);
1653 int ok;
1655 if (trylock (__func__)) {
1656 ok = 0;
1657 goto done;
1659 realloctexts (Int_val (texcount_v));
1660 ok = 1;
1661 unlock (__func__);
1663 done:
1664 CAMLreturn (Val_bool (ok));
1667 static void recti (int x0, int y0, int x1, int y1)
1669 GLfloat *v = state.vertices;
1671 glVertexPointer (2, GL_FLOAT, 0, v);
1672 v[0] = x0; v[1] = y0;
1673 v[2] = x1; v[3] = y0;
1674 v[4] = x0; v[5] = y1;
1675 v[6] = x1; v[7] = y1;
1676 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1679 static void showsel (struct page *page, int ox, int oy)
1681 fz_irect bbox;
1682 fz_rect rect;
1683 fz_stext_block *block;
1684 int seen = 0;
1685 unsigned char selcolor[] = {15,15,15,140};
1687 if (!page->fmark || !page->lmark) return;
1689 glEnable (GL_BLEND);
1690 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1691 glColor4ubv (selcolor);
1693 ox += state.pagedims[page->pdimno].bounds.x0;
1694 oy += state.pagedims[page->pdimno].bounds.y0;
1696 for (block = page->text->first_block; block; block = block->next) {
1697 fz_stext_line *line;
1699 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1700 for (line = block->u.t.first_line; line; line = line->next) {
1701 fz_stext_char *ch;
1703 rect = fz_empty_rect;
1704 for (ch = line->first_char; ch; ch = ch->next) {
1705 fz_rect r;
1706 if (ch == page->fmark) seen = 1;
1707 r = fz_rect_from_quad (ch->quad);
1708 if (seen) rect = fz_union_rect (rect, r);
1709 if (ch == page->lmark) {
1710 bbox = fz_round_rect (rect);
1711 recti (bbox.x0 + ox, bbox.y0 + oy,
1712 bbox.x1 + ox, bbox.y1 + oy);
1713 goto done;
1716 bbox = fz_round_rect (rect);
1717 recti (bbox.x0 + ox, bbox.y0 + oy,
1718 bbox.x1 + ox, bbox.y1 + oy);
1721 done:
1722 glDisable (GL_BLEND);
1725 #pragma GCC diagnostic push
1726 #pragma GCC diagnostic ignored "-Wconversion"
1727 #include "glfont.c"
1728 #pragma GCC diagnostic pop
1730 static void stipplerect (fz_matrix m,
1731 fz_point p1,
1732 fz_point p2,
1733 fz_point p3,
1734 fz_point p4,
1735 GLfloat *texcoords,
1736 GLfloat *vertices)
1738 p1 = fz_transform_point (p1, m);
1739 p2 = fz_transform_point (p2, m);
1740 p3 = fz_transform_point (p3, m);
1741 p4 = fz_transform_point (p4, m);
1743 float w, h, s, t;
1745 w = p2.x - p1.x;
1746 h = p2.y - p1.y;
1747 t = hypotf (w, h) * .25f;
1749 w = p3.x - p2.x;
1750 h = p3.y - p2.y;
1751 s = hypotf (w, h) * .25f;
1753 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1754 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1756 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1757 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1759 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1760 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1762 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1763 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1765 glDrawArrays (GL_LINES, 0, 8);
1768 static void solidrect (fz_matrix m,
1769 fz_point p1,
1770 fz_point p2,
1771 fz_point p3,
1772 fz_point p4,
1773 GLfloat *vertices)
1775 p1 = fz_transform_point (p1, m);
1776 p2 = fz_transform_point (p2, m);
1777 p3 = fz_transform_point (p3, m);
1778 p4 = fz_transform_point (p4, m);
1779 vertices[0] = p1.x; vertices[1] = p1.y;
1780 vertices[2] = p2.x; vertices[3] = p2.y;
1782 vertices[4] = p3.x; vertices[5] = p3.y;
1783 vertices[6] = p4.x; vertices[7] = p4.y;
1784 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1787 static void ensurelinks (struct page *page)
1789 if (!page->links)
1790 page->links = fz_load_links (state.ctx, page->fzpage);
1793 static void highlightlinks (struct page *page, int xoff, int yoff)
1795 fz_matrix ctm;
1796 fz_link *link;
1797 GLfloat *texcoords = state.texcoords;
1798 GLfloat *vertices = state.vertices;
1800 ensurelinks (page);
1802 glEnable (GL_TEXTURE_1D);
1803 glEnable (GL_BLEND);
1804 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1805 glBindTexture (GL_TEXTURE_1D, state.stid);
1807 xoff -= state.pagedims[page->pdimno].bounds.x0;
1808 yoff -= state.pagedims[page->pdimno].bounds.y0;
1809 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1811 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1812 glVertexPointer (2, GL_FLOAT, 0, vertices);
1814 for (link = page->links; link; link = link->next) {
1815 fz_point p1, p2, p3, p4;
1817 p1.x = link->rect.x0;
1818 p1.y = link->rect.y0;
1820 p2.x = link->rect.x1;
1821 p2.y = link->rect.y0;
1823 p3.x = link->rect.x1;
1824 p3.y = link->rect.y1;
1826 p4.x = link->rect.x0;
1827 p4.y = link->rect.y1;
1829 /* TODO: different colours for different schemes */
1830 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1831 else glColor3ub (255, 0, 0);
1833 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1836 for (int i = 0; i < page->annotcount; ++i) {
1837 fz_point p1, p2, p3, p4;
1838 struct annot *annot = &page->annots[i];
1840 p1.x = annot->bbox.x0;
1841 p1.y = annot->bbox.y0;
1843 p2.x = annot->bbox.x1;
1844 p2.y = annot->bbox.y0;
1846 p3.x = annot->bbox.x1;
1847 p3.y = annot->bbox.y1;
1849 p4.x = annot->bbox.x0;
1850 p4.y = annot->bbox.y1;
1852 glColor3ub (0, 0, 128);
1853 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1856 glDisable (GL_BLEND);
1857 glDisable (GL_TEXTURE_1D);
1860 static int compareslinks (const void *l, const void *r)
1862 struct slink const *ls = l;
1863 struct slink const *rs = r;
1864 if (ls->bbox.y0 == rs->bbox.y0) {
1865 return ls->bbox.x0 - rs->bbox.x0;
1867 return ls->bbox.y0 - rs->bbox.y0;
1870 static void droptext (struct page *page)
1872 if (page->text) {
1873 fz_drop_stext_page (state.ctx, page->text);
1874 page->fmark = NULL;
1875 page->lmark = NULL;
1876 page->text = NULL;
1880 static void dropannots (struct page *page)
1882 if (page->annots) {
1883 free (page->annots);
1884 page->annots = NULL;
1885 page->annotcount = 0;
1889 static void ensureannots (struct page *page)
1891 int i, count = 0;
1892 size_t annotsize = sizeof (*page->annots);
1893 pdf_annot *annot;
1894 pdf_document *pdf;
1895 pdf_page *pdfpage;
1897 pdf = pdf_specifics (state.ctx, state.doc);
1898 if (!pdf) return;
1900 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1901 if (state.gen != page->agen) {
1902 dropannots (page);
1903 page->agen = state.gen;
1905 if (page->annots) return;
1907 for (annot = pdf_first_annot (state.ctx, pdfpage);
1908 annot;
1909 annot = pdf_next_annot (state.ctx, annot)) {
1910 count++;
1913 if (count > 0) {
1914 page->annotcount = count;
1915 page->annots = calloc (count, annotsize);
1916 if (!page->annots) {
1917 err (1, "calloc annots %d", count);
1920 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1921 annot;
1922 annot = pdf_next_annot (state.ctx, annot), i++) {
1923 fz_rect rect;
1925 rect = pdf_bound_annot (state.ctx, annot);
1926 page->annots[i].annot = annot;
1927 page->annots[i].bbox = fz_round_rect (rect);
1932 static void dropslinks (struct page *page)
1934 if (page->slinks) {
1935 free (page->slinks);
1936 page->slinks = NULL;
1937 page->slinkcount = 0;
1939 if (page->links) {
1940 fz_drop_link (state.ctx, page->links);
1941 page->links = NULL;
1945 static void ensureslinks (struct page *page)
1947 fz_matrix ctm;
1948 int i, count;
1949 size_t slinksize = sizeof (*page->slinks);
1950 fz_link *link;
1952 ensureannots (page);
1953 if (state.gen != page->sgen) {
1954 dropslinks (page);
1955 page->sgen = state.gen;
1957 if (page->slinks) return;
1959 ensurelinks (page);
1960 ctm = pagectm (page);
1962 count = page->annotcount;
1963 for (link = page->links; link; link = link->next) {
1964 count++;
1966 if (count > 0) {
1967 int j;
1969 page->slinkcount = count;
1970 page->slinks = calloc (count, slinksize);
1971 if (!page->slinks) {
1972 err (1, "calloc slinks %d", count);
1975 for (i = 0, link = page->links; link; ++i, link = link->next) {
1976 fz_rect rect;
1978 rect = link->rect;
1979 rect = fz_transform_rect (rect, ctm);
1980 page->slinks[i].tag = SLINK;
1981 page->slinks[i].u.link = link;
1982 page->slinks[i].bbox = fz_round_rect (rect);
1984 for (j = 0; j < page->annotcount; ++j, ++i) {
1985 fz_rect rect;
1986 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1987 rect = fz_transform_rect (rect, ctm);
1988 page->slinks[i].bbox = fz_round_rect (rect);
1990 page->slinks[i].tag = SANNOT;
1991 page->slinks[i].u.annot = page->annots[j].annot;
1993 qsort (page->slinks, count, slinksize, compareslinks);
1997 static void highlightslinks (struct page *page, int xoff, int yoff,
1998 int noff, const char *targ,
1999 mlsize_t tlen, int hfsize)
2001 char buf[40];
2002 struct slink *slink;
2003 float x0, y0, x1, y1, w;
2005 ensureslinks (page);
2006 glColor3ub (0xc3, 0xb0, 0x91);
2007 for (int i = 0; i < page->slinkcount; ++i) {
2008 fmt_linkn (buf, i + noff);
2009 if (!tlen || !strncmp (targ, buf, tlen)) {
2010 slink = &page->slinks[i];
2012 x0 = slink->bbox.x0 + xoff - 5;
2013 y1 = slink->bbox.y0 + yoff - 5;
2014 y0 = y1 + 10 + hfsize;
2015 w = measure_string (state.face, hfsize, buf);
2016 x1 = x0 + w + 10;
2017 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2021 glEnable (GL_BLEND);
2022 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2023 glEnable (GL_TEXTURE_2D);
2024 glColor3ub (0, 0, 0);
2025 for (int i = 0; i < page->slinkcount; ++i) {
2026 fmt_linkn (buf, i + noff);
2027 if (!tlen || !strncmp (targ, buf, tlen)) {
2028 slink = &page->slinks[i];
2030 x0 = slink->bbox.x0 + xoff;
2031 y0 = slink->bbox.y0 + yoff + hfsize;
2032 draw_string (state.face, hfsize, x0, y0, buf);
2035 glDisable (GL_TEXTURE_2D);
2036 glDisable (GL_BLEND);
2039 static void uploadslice (struct tile *tile, struct slice *slice)
2041 int offset;
2042 struct slice *slice1;
2043 unsigned char *texdata;
2045 offset = 0;
2046 for (slice1 = tile->slices; slice != slice1; slice1++) {
2047 offset += slice1->h * tile->w * tile->pixmap->n;
2049 if (slice->texindex != -1 && slice->texindex < state.texcount
2050 && state.texowners[slice->texindex].slice == slice) {
2051 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2053 else {
2054 int subimage = 0;
2055 int texindex = state.texindex++ % state.texcount;
2057 if (state.texowners[texindex].w == tile->w) {
2058 if (state.texowners[texindex].h >= slice->h) {
2059 subimage = 1;
2061 else {
2062 state.texowners[texindex].h = slice->h;
2065 else {
2066 state.texowners[texindex].h = slice->h;
2069 state.texowners[texindex].w = tile->w;
2070 state.texowners[texindex].slice = slice;
2071 slice->texindex = texindex;
2073 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2074 #if TEXT_TYPE == GL_TEXTURE_2D
2075 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2076 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2077 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2078 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2079 #endif
2080 if (tile->pbo) {
2081 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2082 texdata = 0;
2084 else {
2085 texdata = tile->pixmap->samples;
2087 if (subimage) {
2088 glTexSubImage2D (TEXT_TYPE,
2092 tile->w,
2093 slice->h,
2094 state.texform,
2095 state.texty,
2096 texdata+offset
2099 else {
2100 glTexImage2D (TEXT_TYPE,
2102 state.texiform,
2103 tile->w,
2104 slice->h,
2106 state.texform,
2107 state.texty,
2108 texdata+offset
2111 if (tile->pbo) {
2112 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2117 ML0 (begintiles (void))
2119 glEnable (TEXT_TYPE);
2120 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2121 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2124 ML0 (endtiles (void))
2126 glDisable (TEXT_TYPE);
2129 ML0 (drawtile (value args_v, value ptr_v))
2131 CAMLparam2 (args_v, ptr_v);
2132 int dispx = Int_val (Field (args_v, 0));
2133 int dispy = Int_val (Field (args_v, 1));
2134 int dispw = Int_val (Field (args_v, 2));
2135 int disph = Int_val (Field (args_v, 3));
2136 int tilex = Int_val (Field (args_v, 4));
2137 int tiley = Int_val (Field (args_v, 5));
2138 const char *s = String_val (ptr_v);
2139 struct tile *tile = parse_pointer (__func__, s);
2140 int slicey, firstslice;
2141 struct slice *slice;
2142 GLfloat *texcoords = state.texcoords;
2143 GLfloat *vertices = state.vertices;
2145 firstslice = tiley / tile->sliceheight;
2146 slice = &tile->slices[firstslice];
2147 slicey = tiley % tile->sliceheight;
2149 while (disph > 0) {
2150 int dh;
2152 dh = slice->h - slicey;
2153 dh = fz_mini (disph, dh);
2154 uploadslice (tile, slice);
2156 texcoords[0] = tilex; texcoords[1] = slicey;
2157 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2158 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2159 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2161 vertices[0] = dispx; vertices[1] = dispy;
2162 vertices[2] = dispx+dispw; vertices[3] = dispy;
2163 vertices[4] = dispx; vertices[5] = dispy+dh;
2164 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2166 #if TEXT_TYPE == GL_TEXTURE_2D
2167 for (int i = 0; i < 8; ++i) {
2168 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2170 #endif
2172 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2173 dispy += dh;
2174 disph -= dh;
2175 slice++;
2176 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2177 slicey = 0;
2179 CAMLreturn0;
2182 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2184 fz_matrix ctm;
2185 fz_point p1, p2, p3, p4;
2186 GLfloat *vertices = state.vertices;
2188 xoff -= state.pagedims[page->pdimno].bounds.x0;
2189 yoff -= state.pagedims[page->pdimno].bounds.y0;
2190 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2192 glEnable (GL_BLEND);
2193 glVertexPointer (2, GL_FLOAT, 0, vertices);
2195 glColor4d (
2196 Double_array_field (rects_v, 0),
2197 Double_array_field (rects_v, 1),
2198 Double_array_field (rects_v, 2),
2199 Double_array_field (rects_v, 3)
2201 p1.x = (float) Double_array_field (rects_v, 4);
2202 p1.y = (float) Double_array_field (rects_v, 5);
2204 p2.x = (float) Double_array_field (rects_v, 6);
2205 p2.y = p1.y;
2207 p3.x = p2.x;
2208 p3.y = (float) Double_array_field (rects_v, 7);
2210 p4.x = p1.x;
2211 p4.y = p3.y;
2212 solidrect (ctm, p1, p2, p3, p4, vertices);
2213 glDisable (GL_BLEND);
2216 ML (postprocess (value ptr_v, value hlinks_v,
2217 value xoff_v, value yoff_v,
2218 value li_v))
2220 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2221 int xoff = Int_val (xoff_v);
2222 int yoff = Int_val (yoff_v);
2223 int noff = Int_val (Field (li_v, 0));
2224 const char *targ = String_val (Field (li_v, 1));
2225 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2226 int hfsize = Int_val (Field (li_v, 2));
2227 const char *s = String_val (ptr_v);
2228 int hlmask = Int_val (hlinks_v);
2229 struct page *page = parse_pointer (__func__, s);
2231 if (!page->fzpage) {
2232 /* deal with loadpage failed pages */
2233 goto done;
2236 if (trylock (__func__)) {
2237 noff = -1;
2238 goto done;
2241 ensureannots (page);
2242 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2243 if (hlmask & 2) {
2244 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2245 noff = page->slinkcount;
2247 if (page->tgen == state.gen) {
2248 showsel (page, xoff, yoff);
2250 unlock (__func__);
2252 done:
2253 CAMLreturn (Val_int (noff));
2256 ML0 (drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v))
2258 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2259 int xoff = Int_val (xoff_v);
2260 int yoff = Int_val (yoff_v);
2261 const char *s = String_val (ptr_v);
2262 struct page *page = parse_pointer (__func__, s);
2264 drawprect (page, xoff, yoff, rects_v);
2265 CAMLreturn0;
2268 static struct annot *getannot (struct page *page, int x, int y)
2270 fz_point p;
2271 fz_matrix ctm;
2272 const fz_matrix *tctm;
2273 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2275 if (!page->annots) return NULL;
2277 if (pdf) {
2278 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2279 tctm = &state.pagedims[page->pdimno].tctm;
2281 else {
2282 tctm = &fz_identity;
2285 p.x = x;
2286 p.y = y;
2288 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2289 ctm = fz_invert_matrix (ctm);
2290 p = fz_transform_point (p, ctm);
2292 if (pdf) {
2293 for (int i = 0; i < page->annotcount; ++i) {
2294 struct annot *a = &page->annots[i];
2295 fz_rect rect;
2297 rect = pdf_bound_annot (state.ctx, a->annot);
2298 if (p.x >= rect.x0 && p.x <= rect.x1) {
2299 if (p.y >= rect.y0 && p.y <= rect.y1)
2300 return a;
2304 return NULL;
2307 static fz_link *getlink (struct page *page, int x, int y)
2309 fz_point p;
2310 fz_link *link;
2312 ensureslinks (page);
2314 p.x = x;
2315 p.y = y;
2317 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2319 for (link = page->links; link; link = link->next) {
2320 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2321 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2322 return link;
2326 return NULL;
2329 static void ensuretext (struct page *page)
2331 if (state.gen != page->tgen) {
2332 droptext (page);
2333 page->tgen = state.gen;
2335 if (!page->text) {
2336 fz_device *tdev;
2338 page->text = fz_new_stext_page (state.ctx,
2339 state.pagedims[page->pdimno].mediabox);
2340 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2341 fz_run_display_list (state.ctx, page->dlist,
2342 tdev, pagectm (page), fz_infinite_rect, NULL);
2343 fz_close_device (state.ctx, tdev);
2344 fz_drop_device (state.ctx, tdev);
2348 ML (find_page_with_links (value start_page_v, value dir_v))
2350 CAMLparam2 (start_page_v, dir_v);
2351 CAMLlocal1 (ret_v);
2352 int i, dir = Int_val (dir_v);
2353 int start_page = Int_val (start_page_v);
2354 int end_page = dir > 0 ? state.pagecount : -1;
2355 pdf_document *pdf;
2357 fz_var (end_page);
2358 ret_v = Val_int (0);
2359 lock (__func__);
2360 pdf = pdf_specifics (state.ctx, state.doc);
2361 for (i = start_page + dir; i != end_page; i += dir) {
2362 int found;
2364 fz_var (found);
2365 if (pdf) {
2366 pdf_page *page = NULL;
2368 fz_var (page);
2369 fz_try (state.ctx) {
2370 page = pdf_load_page (state.ctx, pdf, i);
2371 found = !!page->links || !!page->annots;
2373 fz_catch (state.ctx) {
2374 found = 0;
2376 if (page) {
2377 fz_drop_page (state.ctx, &page->super);
2380 else {
2381 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2382 fz_link *link = fz_load_links (state.ctx, page);
2383 found = !!link;
2384 fz_drop_link (state.ctx, link);
2385 fz_drop_page (state.ctx, page);
2388 if (found) {
2389 ret_v = caml_alloc_small (1, 1);
2390 Field (ret_v, 0) = Val_int (i);
2391 goto unlock;
2394 unlock:
2395 unlock (__func__);
2396 CAMLreturn (ret_v);
2399 enum { dir_first, dir_last };
2400 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2402 ML (findlink (value ptr_v, value dir_v))
2404 CAMLparam2 (ptr_v, dir_v);
2405 CAMLlocal2 (ret_v, pos_v);
2406 struct page *page;
2407 int dirtag, i, slinkindex;
2408 struct slink *found = NULL ,*slink;
2409 const char *s = String_val (ptr_v);
2411 page = parse_pointer (__func__, s);
2412 ret_v = Val_int (0);
2413 lock (__func__);
2414 ensureslinks (page);
2416 if (Is_block (dir_v)) {
2417 dirtag = Tag_val (dir_v);
2418 switch (dirtag) {
2419 case dir_first_visible:
2421 int x0, y0, dir, first_index, last_index;
2423 pos_v = Field (dir_v, 0);
2424 x0 = Int_val (Field (pos_v, 0));
2425 y0 = Int_val (Field (pos_v, 1));
2426 dir = Int_val (Field (pos_v, 2));
2428 if (dir >= 0) {
2429 dir = 1;
2430 first_index = 0;
2431 last_index = page->slinkcount;
2433 else {
2434 first_index = page->slinkcount - 1;
2435 last_index = -1;
2438 for (i = first_index; i != last_index; i += dir) {
2439 slink = &page->slinks[i];
2440 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2441 found = slink;
2442 break;
2446 break;
2448 case dir_left:
2449 slinkindex = Int_val (Field (dir_v, 0));
2450 found = &page->slinks[slinkindex];
2451 for (i = slinkindex - 1; i >= 0; --i) {
2452 slink = &page->slinks[i];
2453 if (slink->bbox.x0 < found->bbox.x0) {
2454 found = slink;
2455 break;
2458 break;
2460 case dir_right:
2461 slinkindex = Int_val (Field (dir_v, 0));
2462 found = &page->slinks[slinkindex];
2463 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2464 slink = &page->slinks[i];
2465 if (slink->bbox.x0 > found->bbox.x0) {
2466 found = slink;
2467 break;
2470 break;
2472 case dir_down:
2473 slinkindex = Int_val (Field (dir_v, 0));
2474 found = &page->slinks[slinkindex];
2475 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2476 slink = &page->slinks[i];
2477 if (slink->bbox.y0 >= found->bbox.y0) {
2478 found = slink;
2479 break;
2482 break;
2484 case dir_up:
2485 slinkindex = Int_val (Field (dir_v, 0));
2486 found = &page->slinks[slinkindex];
2487 for (i = slinkindex - 1; i >= 0; --i) {
2488 slink = &page->slinks[i];
2489 if (slink->bbox.y0 <= found->bbox.y0) {
2490 found = slink;
2491 break;
2494 break;
2497 else {
2498 dirtag = Int_val (dir_v);
2499 switch (dirtag) {
2500 case dir_first:
2501 found = page->slinks;
2502 break;
2504 case dir_last:
2505 if (page->slinks) {
2506 found = page->slinks + (page->slinkcount - 1);
2508 break;
2511 if (found) {
2512 ret_v = caml_alloc_small (2, 1);
2513 Field (ret_v, 0) = Val_int (found - page->slinks);
2516 unlock (__func__);
2517 CAMLreturn (ret_v);
2520 enum { uuri, utext, uannot };
2522 ML (getlink (value ptr_v, value n_v))
2524 CAMLparam2 (ptr_v, n_v);
2525 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2526 fz_link *link;
2527 struct page *page;
2528 const char *s = String_val (ptr_v);
2529 struct slink *slink;
2531 ret_v = Val_int (0);
2532 page = parse_pointer (__func__, s);
2534 lock (__func__);
2535 ensureslinks (page);
2536 slink = &page->slinks[Int_val (n_v)];
2537 if (slink->tag == SLINK) {
2538 link = slink->u.link;
2539 str_v = caml_copy_string (link->uri);
2540 ret_v = caml_alloc_small (1, uuri);
2541 Field (ret_v, 0) = str_v;
2543 else {
2544 ret_v = caml_alloc_small (1, uannot);
2545 tup_v = caml_alloc_tuple (2);
2546 Field (ret_v, 0) = tup_v;
2547 Field (tup_v, 0) = ptr_v;
2548 Field (tup_v, 1) = n_v;
2550 unlock (__func__);
2552 CAMLreturn (ret_v);
2555 ML (getannotcontents (value ptr_v, value n_v))
2557 CAMLparam2 (ptr_v, n_v);
2558 CAMLlocal1 (ret_v);
2559 pdf_document *pdf;
2560 const char *contents = "";
2562 lock (__func__);
2563 pdf = pdf_specifics (state.ctx, state.doc);
2564 if (pdf) {
2565 const char *s = String_val (ptr_v);
2566 struct page *page;
2567 struct slink *slink;
2569 page = parse_pointer (__func__, s);
2570 slink = &page->slinks[Int_val (n_v)];
2571 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2573 unlock (__func__);
2574 ret_v = caml_copy_string (contents);
2575 CAMLreturn (ret_v);
2578 ML (getlinkcount (value ptr_v))
2580 CAMLparam1 (ptr_v);
2581 struct page *page;
2582 const char *s = String_val (ptr_v);
2584 page = parse_pointer (__func__, s);
2585 CAMLreturn (Val_int (page->slinkcount));
2588 ML (getlinkrect (value ptr_v, value n_v))
2590 CAMLparam2 (ptr_v, n_v);
2591 CAMLlocal1 (ret_v);
2592 struct page *page;
2593 struct slink *slink;
2594 const char *s = String_val (ptr_v);
2596 page = parse_pointer (__func__, s);
2597 ret_v = caml_alloc_tuple (4);
2598 lock (__func__);
2599 ensureslinks (page);
2601 slink = &page->slinks[Int_val (n_v)];
2602 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2603 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2604 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2605 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2606 unlock (__func__);
2607 CAMLreturn (ret_v);
2610 ML (whatsunder (value ptr_v, value x_v, value y_v))
2612 CAMLparam3 (ptr_v, x_v, y_v);
2613 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2614 fz_link *link;
2615 struct annot *annot;
2616 struct page *page;
2617 const char *ptr = String_val (ptr_v);
2618 int x = Int_val (x_v), y = Int_val (y_v);
2619 struct pagedim *pdim;
2621 ret_v = Val_int (0);
2622 if (trylock (__func__)) {
2623 goto done;
2626 page = parse_pointer (__func__, ptr);
2627 pdim = &state.pagedims[page->pdimno];
2628 x += pdim->bounds.x0;
2629 y += pdim->bounds.y0;
2632 annot = getannot (page, x, y);
2633 if (annot) {
2634 int i, n = -1;
2636 ensureslinks (page);
2637 for (i = 0; i < page->slinkcount; ++i) {
2638 if (page->slinks[i].tag == SANNOT
2639 && page->slinks[i].u.annot == annot->annot) {
2640 n = i;
2641 break;
2644 ret_v = caml_alloc_small (1, uannot);
2645 tup_v = caml_alloc_tuple (2);
2646 Field (ret_v, 0) = tup_v;
2647 Field (tup_v, 0) = ptr_v;
2648 Field (tup_v, 1) = Val_int (n);
2649 goto unlock;
2653 link = getlink (page, x, y);
2654 if (link) {
2655 str_v = caml_copy_string (link->uri);
2656 ret_v = caml_alloc_small (1, uuri);
2657 Field (ret_v, 0) = str_v;
2659 else {
2660 fz_rect *b;
2661 fz_stext_block *block;
2663 ensuretext (page);
2665 for (block = page->text->first_block; block; block = block->next) {
2666 fz_stext_line *line;
2668 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2669 b = &block->bbox;
2670 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2671 continue;
2673 for (line = block->u.t.first_line; line; line = line->next) {
2674 fz_stext_char *ch;
2676 b = &line->bbox;
2677 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2678 continue;
2680 for (ch = line->first_char; ch; ch = ch->next) {
2681 fz_quad *q = &ch->quad;
2683 if (x >= q->ul.x && x <= q->ur.x
2684 && y >= q->ul.y && y <= q->ll.y) {
2685 const char *n2 = fz_font_name (state.ctx, ch->font);
2686 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2687 ch->font);
2689 if (!n2) n2 = "<unknown font>";
2691 if (face && face->family_name) {
2692 char *s;
2693 char *n1 = face->family_name;
2694 size_t l1 = strlen (n1);
2695 size_t l2 = strlen (n2);
2697 if (l1 != l2 || memcmp (n1, n2, l1)) {
2698 s = malloc (l1 + l2 + 2);
2699 if (s) {
2700 memcpy (s, n2, l2);
2701 s[l2] = '=';
2702 memcpy (s + l2 + 1, n1, l1 + 1);
2703 str_v = caml_copy_string (s);
2704 free (s);
2708 if (str_v == Val_unit) {
2709 str_v = caml_copy_string (n2);
2711 ret_v = caml_alloc_small (1, utext);
2712 Field (ret_v, 0) = str_v;
2713 goto unlock;
2719 unlock:
2720 unlock (__func__);
2722 done:
2723 CAMLreturn (ret_v);
2726 enum { mark_page, mark_block, mark_line, mark_word };
2728 ML0 (clearmark (value ptr_v))
2730 CAMLparam1 (ptr_v);
2731 const char *s = String_val (ptr_v);
2732 struct page *page;
2734 if (trylock (__func__)) {
2735 goto done;
2738 page = parse_pointer (__func__, s);
2739 page->fmark = NULL;
2740 page->lmark = NULL;
2742 unlock (__func__);
2743 done:
2744 CAMLreturn0;
2747 static int uninteresting (int c)
2749 return isspace (c) || ispunct (c);
2752 ML (markunder (value ptr_v, value x_v, value y_v, value mark_v))
2754 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2755 CAMLlocal1 (ret_v);
2756 fz_rect *b;
2757 struct page *page;
2758 fz_stext_line *line;
2759 fz_stext_block *block;
2760 struct pagedim *pdim;
2761 int mark = Int_val (mark_v);
2762 const char *s = String_val (ptr_v);
2763 int x = Int_val (x_v), y = Int_val (y_v);
2765 ret_v = Val_bool (0);
2766 if (trylock (__func__)) {
2767 goto done;
2770 page = parse_pointer (__func__, s);
2771 pdim = &state.pagedims[page->pdimno];
2773 ensuretext (page);
2775 if (mark == mark_page) {
2776 page->fmark = page->text->first_block->u.t.first_line->first_char;
2777 page->lmark = page->text->last_block->u.t.last_line->last_char;
2778 ret_v = Val_bool (1);
2779 goto unlock;
2782 x += pdim->bounds.x0;
2783 y += pdim->bounds.y0;
2785 for (block = page->text->first_block; block; block = block->next) {
2786 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2787 b = &block->bbox;
2788 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2789 continue;
2791 if (mark == mark_block) {
2792 page->fmark = block->u.t.first_line->first_char;
2793 page->lmark = block->u.t.last_line->last_char;
2794 ret_v = Val_bool (1);
2795 goto unlock;
2798 for (line = block->u.t.first_line; line; line = line->next) {
2799 fz_stext_char *ch;
2801 b = &line->bbox;
2802 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2803 continue;
2805 if (mark == mark_line) {
2806 page->fmark = line->first_char;
2807 page->lmark = line->last_char;
2808 ret_v = Val_bool (1);
2809 goto unlock;
2812 for (ch = line->first_char; ch; ch = ch->next) {
2813 fz_stext_char *ch2, *first = NULL, *last = NULL;
2814 fz_quad *q = &ch->quad;
2815 if (x >= q->ul.x && x <= q->ur.x
2816 && y >= q->ul.y && y <= q->ll.y) {
2817 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2818 if (uninteresting (ch2->c)) first = NULL;
2819 else if (!first) first = ch2;
2821 for (ch2 = ch; ch2; ch2 = ch2->next) {
2822 if (uninteresting (ch2->c)) break;
2823 last = ch2;
2826 page->fmark = first;
2827 page->lmark = last;
2828 ret_v = Val_bool (1);
2829 goto unlock;
2834 unlock:
2835 if (!Bool_val (ret_v)) {
2836 page->fmark = NULL;
2837 page->lmark = NULL;
2839 unlock (__func__);
2841 done:
2842 CAMLreturn (ret_v);
2845 ML (rectofblock (value ptr_v, value x_v, value y_v))
2847 CAMLparam3 (ptr_v, x_v, y_v);
2848 CAMLlocal2 (ret_v, res_v);
2849 fz_rect *b = NULL;
2850 struct page *page;
2851 struct pagedim *pdim;
2852 fz_stext_block *block;
2853 const char *s = String_val (ptr_v);
2854 int x = Int_val (x_v), y = Int_val (y_v);
2856 ret_v = Val_int (0);
2857 if (trylock (__func__)) {
2858 goto done;
2861 page = parse_pointer (__func__, s);
2862 pdim = &state.pagedims[page->pdimno];
2863 x += pdim->bounds.x0;
2864 y += pdim->bounds.y0;
2866 ensuretext (page);
2868 for (block = page->text->first_block; block; block = block->next) {
2869 switch (block->type) {
2870 case FZ_STEXT_BLOCK_TEXT:
2871 b = &block->bbox;
2872 break;
2874 case FZ_STEXT_BLOCK_IMAGE:
2875 b = &block->bbox;
2876 break;
2878 default:
2879 continue;
2882 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2883 break;
2884 b = NULL;
2886 if (b) {
2887 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2888 ret_v = caml_alloc_small (1, 1);
2889 Store_double_field (res_v, 0, (double) b->x0);
2890 Store_double_field (res_v, 1, (double) b->x1);
2891 Store_double_field (res_v, 2, (double) b->y0);
2892 Store_double_field (res_v, 3, (double) b->y1);
2893 Field (ret_v, 0) = res_v;
2895 unlock (__func__);
2897 done:
2898 CAMLreturn (ret_v);
2901 ML0 (seltext (value ptr_v, value rect_v))
2903 CAMLparam2 (ptr_v, rect_v);
2904 struct page *page;
2905 struct pagedim *pdim;
2906 const char *s = String_val (ptr_v);
2907 int x0, x1, y0, y1;
2908 fz_stext_char *ch;
2909 fz_stext_line *line;
2910 fz_stext_block *block;
2911 fz_stext_char *fc, *lc;
2913 if (trylock (__func__)) {
2914 goto done;
2917 page = parse_pointer (__func__, s);
2918 ensuretext (page);
2920 pdim = &state.pagedims[page->pdimno];
2921 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2922 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2923 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2924 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2926 if (y0 > y1) {
2927 int t = y0;
2928 y0 = y1;
2929 y1 = t;
2930 x0 = x1;
2931 x1 = t;
2934 fc = page->fmark;
2935 lc = page->lmark;
2937 for (block = page->text->first_block; block; block = block->next) {
2938 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2939 for (line = block->u.t.first_line; line; line = line->next) {
2940 for (ch = line->first_char; ch; ch = ch->next) {
2941 fz_quad q = ch->quad;
2942 if (x0 >= q.ul.x && x0 <= q.ur.x
2943 && y0 >= q.ul.y && y0 <= q.ll.y) {
2944 fc = ch;
2946 if (x1 >= q.ul.x && x1 <= q.ur.x
2947 && y1 >= q.ul.y && y1 <= q.ll.y) {
2948 lc = ch;
2953 if (x1 < x0 && fc == lc) {
2954 fz_stext_char *t;
2956 t = fc;
2957 fc = lc;
2958 lc = t;
2961 page->fmark = fc;
2962 page->lmark = lc;
2964 unlock (__func__);
2966 done:
2967 CAMLreturn0;
2970 static int pipechar (FILE *f, fz_stext_char *ch)
2972 char buf[4];
2973 int len;
2974 size_t ret;
2976 len = fz_runetochar (buf, ch->c);
2977 ret = fwrite (buf, len, 1, f);
2978 if (ret != 1) {
2979 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
2980 len, ret, errno, strerror (errno));
2981 return -1;
2983 return 0;
2986 ML (spawn (value command_v, value fds_v))
2988 CAMLparam2 (command_v, fds_v);
2989 CAMLlocal2 (l_v, tup_v);
2990 int ret, ret1;
2991 pid_t pid = (pid_t) -1;
2992 char *msg = NULL;
2993 value earg_v = Nothing;
2994 posix_spawnattr_t attr;
2995 posix_spawn_file_actions_t fa;
2996 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
2998 argv[2] = &Byte (command_v, 0);
2999 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3000 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3003 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3004 msg = "posix_spawnattr_init";
3005 goto fail1;
3008 #ifdef POSIX_SPAWN_USEVFORK
3009 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3010 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3011 goto fail;
3013 #endif
3015 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3016 int fd1, fd2;
3018 tup_v = Field (l_v, 0);
3019 fd1 = Int_val (Field (tup_v, 0));
3020 fd2 = Int_val (Field (tup_v, 1));
3021 if (fd2 < 0) {
3022 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3023 msg = "posix_spawn_file_actions_addclose";
3024 earg_v = tup_v;
3025 goto fail;
3028 else {
3029 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3030 msg = "posix_spawn_file_actions_adddup2";
3031 earg_v = tup_v;
3032 goto fail;
3037 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3038 msg = "posix_spawn";
3039 goto fail;
3042 fail:
3043 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3044 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3047 fail1:
3048 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3049 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3050 ret1, strerror (ret1));
3053 if (msg)
3054 unix_error (ret, msg, earg_v);
3056 CAMLreturn (Val_int (pid));
3059 ML (hassel (value ptr_v))
3061 CAMLparam1 (ptr_v);
3062 CAMLlocal1 (ret_v);
3063 struct page *page;
3064 const char *s = String_val (ptr_v);
3066 ret_v = Val_bool (0);
3067 if (trylock (__func__)) {
3068 goto done;
3071 page = parse_pointer (__func__, s);
3072 ret_v = Val_bool (page->fmark && page->lmark);
3073 unlock (__func__);
3074 done:
3075 CAMLreturn (ret_v);
3078 ML0 (copysel (value fd_v, value ptr_v))
3080 CAMLparam2 (fd_v, ptr_v);
3081 FILE *f;
3082 int seen = 0;
3083 struct page *page;
3084 fz_stext_line *line;
3085 fz_stext_block *block;
3086 int fd = Int_val (fd_v);
3087 const char *s = String_val (ptr_v);
3089 if (trylock (__func__)) {
3090 goto done;
3093 page = parse_pointer (__func__, s);
3095 if (!page->fmark || !page->lmark) {
3096 printd ("emsg nothing to copy on page %d", page->pageno);
3097 goto unlock;
3100 f = fdopen (fd, "w");
3101 if (!f) {
3102 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3103 fd, errno, strerror (errno));
3104 f = stdout;
3107 for (block = page->text->first_block; block; block = block->next) {
3108 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3109 for (line = block->u.t.first_line; line; line = line->next) {
3110 fz_stext_char *ch;
3111 for (ch = line->first_char; ch; ch = ch->next) {
3112 if (seen || ch == page->fmark) {
3113 do {
3114 pipechar (f, ch);
3115 if (ch == page->lmark) goto close;
3116 } while ((ch = ch->next));
3117 seen = 1;
3118 break;
3121 if (seen) fputc ('\n', f);
3124 close:
3125 if (f != stdout) {
3126 int ret = fclose (f);
3127 fd = -1;
3128 if (ret == -1) {
3129 if (errno != ECHILD) {
3130 printd ("emsg failed to close sel pipe: %d:%s",
3131 errno, strerror (errno));
3135 unlock:
3136 unlock (__func__);
3138 done:
3139 if (fd >= 0) {
3140 if (close (fd)) {
3141 printd ("emsg failed to close sel pipe: %d:%s",
3142 errno, strerror (errno));
3145 CAMLreturn0;
3148 ML (getpdimrect (value pagedimno_v))
3150 CAMLparam1 (pagedimno_v);
3151 CAMLlocal1 (ret_v);
3152 int pagedimno = Int_val (pagedimno_v);
3153 fz_rect box;
3155 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3156 if (trylock (__func__)) {
3157 box = fz_empty_rect;
3159 else {
3160 box = state.pagedims[pagedimno].mediabox;
3161 unlock (__func__);
3164 Store_double_field (ret_v, 0, (double) box.x0);
3165 Store_double_field (ret_v, 1, (double) box.x1);
3166 Store_double_field (ret_v, 2, (double) box.y0);
3167 Store_double_field (ret_v, 3, (double) box.y1);
3169 CAMLreturn (ret_v);
3172 ML (zoom_for_height (value winw_v, value winh_v, value dw_v, value cols_v))
3174 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3175 CAMLlocal1 (ret_v);
3176 int i;
3177 float zoom = -1.;
3178 float maxh = 0.0;
3179 struct pagedim *p;
3180 float winw = Int_val (winw_v);
3181 float winh = Int_val (winh_v);
3182 float dw = Int_val (dw_v);
3183 float cols = Int_val (cols_v);
3184 float pw = 1.0, ph = 1.0;
3186 if (trylock (__func__)) {
3187 goto done;
3190 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3191 float w = p->pagebox.x1 / cols;
3192 float h = p->pagebox.y1;
3193 if (h > maxh) {
3194 maxh = h;
3195 ph = h;
3196 if (state.fitmodel != FitProportional) pw = w;
3198 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3201 zoom = (((winh / ph) * pw) + dw) / winw;
3202 unlock (__func__);
3203 done:
3204 ret_v = caml_copy_double ((double) zoom);
3205 CAMLreturn (ret_v);
3208 ML (getmaxw (value unit_v))
3210 CAMLparam1 (unit_v);
3211 CAMLlocal1 (ret_v);
3212 int i;
3213 float maxw = -1.;
3214 struct pagedim *p;
3216 if (trylock (__func__)) {
3217 goto done;
3220 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3221 float w = p->pagebox.x1;
3222 maxw = fz_max (maxw, w);
3225 unlock (__func__);
3226 done:
3227 ret_v = caml_copy_double ((double) maxw);
3228 CAMLreturn (ret_v);
3231 ML (draw_string (value pt_v, value x_v, value y_v, value string_v))
3233 CAMLparam4 (pt_v, x_v, y_v, string_v);
3234 CAMLlocal1 (ret_v);
3235 int pt = Int_val(pt_v);
3236 int x = Int_val (x_v);
3237 int y = Int_val (y_v);
3238 float w;
3240 w = draw_string (state.face, pt, x, y, String_val (string_v));
3241 ret_v = caml_copy_double (w);
3242 CAMLreturn (ret_v);
3245 ML (measure_string (value pt_v, value string_v))
3247 CAMLparam2 (pt_v, string_v);
3248 CAMLlocal1 (ret_v);
3249 int pt = Int_val (pt_v);
3250 double w;
3252 w = (double) measure_string (state.face, pt, String_val (string_v));
3253 ret_v = caml_copy_double (w);
3254 CAMLreturn (ret_v);
3257 ML (getpagebox (value opaque_v))
3259 CAMLparam1 (opaque_v);
3260 CAMLlocal1 (ret_v);
3261 fz_rect rect;
3262 fz_irect bbox;
3263 fz_device *dev;
3264 const char *s = String_val (opaque_v);
3265 struct page *page = parse_pointer (__func__, s);
3267 ret_v = caml_alloc_tuple (4);
3268 dev = fz_new_bbox_device (state.ctx, &rect);
3270 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3272 fz_close_device (state.ctx, dev);
3273 fz_drop_device (state.ctx, dev);
3274 bbox = fz_round_rect (rect);
3275 Field (ret_v, 0) = Val_int (bbox.x0);
3276 Field (ret_v, 1) = Val_int (bbox.y0);
3277 Field (ret_v, 2) = Val_int (bbox.x1);
3278 Field (ret_v, 3) = Val_int (bbox.y1);
3280 CAMLreturn (ret_v);
3283 ML0 (setaalevel (value level_v))
3285 CAMLparam1 (level_v);
3287 state.aalevel = Int_val (level_v);
3288 CAMLreturn0;
3291 ML0 (setpapercolor (value rgba_v))
3293 CAMLparam1 (rgba_v);
3295 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3296 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3297 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3298 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3299 CAMLreturn0;
3302 value ml_keysymtoutf8 (value keysym_v);
3303 #ifndef CIDER
3304 value ml_keysymtoutf8 (value keysym_v)
3306 CAMLparam1 (keysym_v);
3307 CAMLlocal1 (str_v);
3308 unsigned short keysym = (unsigned short) Int_val (keysym_v);
3309 Rune rune;
3310 extern long keysym2ucs (unsigned short);
3311 int len;
3312 char buf[5];
3314 rune = (Rune) keysym2ucs (keysym);
3315 len = fz_runetochar (buf, rune);
3316 buf[len] = 0;
3317 str_v = caml_copy_string (buf);
3318 CAMLreturn (str_v);
3320 #else
3321 value ml_keysymtoutf8 (value keysym_v)
3323 CAMLparam1 (keysym_v);
3324 CAMLlocal1 (str_v);
3325 long ucs = Long_val (keysym_v);
3326 int len;
3327 char buf[5];
3329 len = fz_runetochar (buf, (int) ucs);
3330 buf[len] = 0;
3331 str_v = caml_copy_string (buf);
3332 CAMLreturn (str_v);
3334 #endif
3336 enum { piunknown, pilinux, pimacos, pibsd };
3338 ML (platform (value unit_v))
3340 CAMLparam1 (unit_v);
3341 CAMLlocal2 (tup_v, arr_v);
3342 int platid = piunknown;
3343 struct utsname buf;
3345 #if defined __linux__
3346 platid = pilinux;
3347 #elif defined __DragonFly__ || defined __FreeBSD__
3348 || defined __OpenBSD__ || defined __NetBSD__
3349 platid = pibsd;
3350 #elif defined __APPLE__
3351 platid = pimacos;
3352 #endif
3353 if (uname (&buf)) err (1, "uname");
3355 tup_v = caml_alloc_tuple (2);
3357 char const *sar[] = {
3358 buf.sysname,
3359 buf.release,
3360 buf.version,
3361 buf.machine,
3362 NULL
3364 arr_v = caml_copy_string_array (sar);
3366 Field (tup_v, 0) = Val_int (platid);
3367 Field (tup_v, 1) = arr_v;
3368 CAMLreturn (tup_v);
3371 ML0 (cloexec (value fd_v))
3373 CAMLparam1 (fd_v);
3374 int fd = Int_val (fd_v);
3376 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3377 uerror ("fcntl", Nothing);
3379 CAMLreturn0;
3382 ML (getpbo (value w_v, value h_v, value cs_v))
3384 CAMLparam2 (w_v, h_v);
3385 CAMLlocal1 (ret_v);
3386 struct bo *pbo;
3387 int w = Int_val (w_v);
3388 int h = Int_val (h_v);
3389 int cs = Int_val (cs_v);
3391 if (state.bo_usable) {
3392 pbo = calloc (sizeof (*pbo), 1);
3393 if (!pbo) {
3394 err (1, "calloc pbo");
3397 switch (cs) {
3398 case 0:
3399 case 1:
3400 pbo->size = w*h*4;
3401 break;
3402 case 2:
3403 pbo->size = w*h*2;
3404 break;
3405 default:
3406 errx (1, "%s: invalid colorspace %d", __func__, cs);
3409 state.glGenBuffersARB (1, &pbo->id);
3410 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3411 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3412 NULL, GL_STREAM_DRAW);
3413 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3414 GL_READ_WRITE);
3415 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3416 if (!pbo->ptr) {
3417 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3418 state.glDeleteBuffersARB (1, &pbo->id);
3419 free (pbo);
3420 ret_v = caml_copy_string ("0");
3422 else {
3423 int res;
3424 char *s;
3426 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3427 if (res < 0) {
3428 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3430 s = malloc (res+1);
3431 if (!s) {
3432 err (1, "malloc %d bytes failed", res+1);
3434 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3435 if (res < 0) {
3436 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3438 ret_v = caml_copy_string (s);
3439 free (s);
3442 else {
3443 ret_v = caml_copy_string ("0");
3445 CAMLreturn (ret_v);
3448 ML0 (freepbo (value s_v))
3450 CAMLparam1 (s_v);
3451 const char *s = String_val (s_v);
3452 struct tile *tile = parse_pointer (__func__, s);
3454 if (tile->pbo) {
3455 state.glDeleteBuffersARB (1, &tile->pbo->id);
3456 tile->pbo->id = -1;
3457 tile->pbo->ptr = NULL;
3458 tile->pbo->size = -1;
3460 CAMLreturn0;
3463 ML0 (unmappbo (value s_v))
3465 CAMLparam1 (s_v);
3466 const char *s = String_val (s_v);
3467 struct tile *tile = parse_pointer (__func__, s);
3469 if (tile->pbo) {
3470 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3471 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3472 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3474 tile->pbo->ptr = NULL;
3475 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3477 CAMLreturn0;
3480 static void setuppbo (void)
3482 extern void (*wsigladdr (const char *name)) (void);
3483 #pragma GCC diagnostic push
3484 #ifdef __clang__
3485 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3486 #endif
3487 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3488 state.bo_usable = GPA (glBindBufferARB)
3489 && GPA (glUnmapBufferARB)
3490 && GPA (glMapBufferARB)
3491 && GPA (glBufferDataARB)
3492 && GPA (glGenBuffersARB)
3493 && GPA (glDeleteBuffersARB);
3494 #undef GPA
3495 #pragma GCC diagnostic pop
3498 ML (bo_usable (void))
3500 return Val_bool (state.bo_usable);
3503 ML (unproject (value ptr_v, value x_v, value y_v))
3505 CAMLparam3 (ptr_v, x_v, y_v);
3506 CAMLlocal2 (ret_v, tup_v);
3507 struct page *page;
3508 const char *s = String_val (ptr_v);
3509 int x = Int_val (x_v), y = Int_val (y_v);
3510 struct pagedim *pdim;
3511 fz_point p;
3513 page = parse_pointer (__func__, s);
3514 pdim = &state.pagedims[page->pdimno];
3516 ret_v = Val_int (0);
3517 if (trylock (__func__)) {
3518 goto done;
3521 p.x = x + pdim->bounds.x0;
3522 p.y = y + pdim->bounds.y0;
3524 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3525 pdim->ctm)));
3527 tup_v = caml_alloc_tuple (2);
3528 ret_v = caml_alloc_small (1, 1);
3529 Field (tup_v, 0) = Val_int (p.x);
3530 Field (tup_v, 1) = Val_int (p.y);
3531 Field (ret_v, 0) = tup_v;
3533 unlock (__func__);
3534 done:
3535 CAMLreturn (ret_v);
3538 ML (project (value ptr_v, value pageno_v, value pdimno_v, value x_v, value y_v))
3540 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3541 CAMLlocal1 (ret_v);
3542 struct page *page;
3543 const char *s = String_val (ptr_v);
3544 int pageno = Int_val (pageno_v);
3545 int pdimno = Int_val (pdimno_v);
3546 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3547 struct pagedim *pdim;
3548 fz_point p;
3549 fz_matrix ctm;
3551 ret_v = Val_int (0);
3552 lock (__func__);
3554 if (!*s) {
3555 page = loadpage (pageno, pdimno);
3557 else {
3558 page = parse_pointer (__func__, s);
3560 pdim = &state.pagedims[pdimno];
3562 if (pdf_specifics (state.ctx, state.doc)) {
3563 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3564 ctm = state.pagedims[page->pdimno].tctm;
3566 else {
3567 ctm = fz_identity;
3569 p.x = x + pdim->bounds.x0;
3570 p.y = y + pdim->bounds.y0;
3572 ctm = fz_concat (pdim->tctm, pdim->ctm);
3573 p = fz_transform_point (p, ctm);
3575 ret_v = caml_alloc_tuple (2);
3576 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3577 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3579 if (!*s) {
3580 freepage (page);
3582 unlock (__func__);
3583 CAMLreturn (ret_v);
3586 ML0 (addannot (value ptr_v, value x_v, value y_v, value contents_v))
3588 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3589 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3591 if (pdf) {
3592 pdf_annot *annot;
3593 struct page *page;
3594 fz_rect r;
3595 const char *s = String_val (ptr_v);
3597 page = parse_pointer (__func__, s);
3598 annot = pdf_create_annot (state.ctx,
3599 pdf_page_from_fz_page (state.ctx,
3600 page->fzpage),
3601 PDF_ANNOT_TEXT);
3602 r.x0 = Int_val (x_v) - 10;
3603 r.y0 = Int_val (y_v) - 10;
3604 r.x1 = r.x0 + 20;
3605 r.y1 = r.y0 + 20;
3606 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3607 pdf_set_annot_rect (state.ctx, annot, r);
3609 state.dirty = 1;
3611 CAMLreturn0;
3614 ML0 (delannot (value ptr_v, value n_v))
3616 CAMLparam2 (ptr_v, n_v);
3617 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3619 if (pdf) {
3620 struct page *page;
3621 const char *s = String_val (ptr_v);
3622 struct slink *slink;
3624 page = parse_pointer (__func__, s);
3625 slink = &page->slinks[Int_val (n_v)];
3626 pdf_delete_annot (state.ctx,
3627 pdf_page_from_fz_page (state.ctx, page->fzpage),
3628 (pdf_annot *) slink->u.annot);
3629 state.dirty = 1;
3631 CAMLreturn0;
3634 ML0 (modannot (value ptr_v, value n_v, value str_v))
3636 CAMLparam3 (ptr_v, n_v, str_v);
3637 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3639 if (pdf) {
3640 struct page *page;
3641 const char *s = String_val (ptr_v);
3642 struct slink *slink;
3644 page = parse_pointer (__func__, s);
3645 slink = &page->slinks[Int_val (n_v)];
3646 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3647 String_val (str_v));
3648 state.dirty = 1;
3650 CAMLreturn0;
3653 ML (hasunsavedchanges (void))
3655 return Val_bool (state.dirty);
3658 ML0 (savedoc (value path_v))
3660 CAMLparam1 (path_v);
3661 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3663 if (pdf) {
3664 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3666 CAMLreturn0;
3669 static void makestippletex (void)
3671 const char pixels[] = "\xff\xff\0\0";
3672 glGenTextures (1, &state.stid);
3673 glBindTexture (GL_TEXTURE_1D, state.stid);
3674 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3675 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3676 glTexImage1D (
3677 GL_TEXTURE_1D,
3679 GL_ALPHA,
3682 GL_ALPHA,
3683 GL_UNSIGNED_BYTE,
3684 pixels
3688 ML (fz_version (void))
3690 return caml_copy_string (FZ_VERSION);
3693 ML (llpp_version (void))
3695 extern char llpp_version[];
3696 return caml_copy_string (llpp_version);
3699 static void diag_callback (void *user, const char *message)
3701 printd ("emsg %s %s", (char *) user, message);
3704 ML0 (init (value csock_v, value params_v))
3706 CAMLparam2 (csock_v, params_v);
3707 CAMLlocal2 (trim_v, fuzz_v);
3708 int ret;
3709 int texcount;
3710 const char *fontpath;
3711 int colorspace;
3712 int mustoresize;
3714 state.csock = Int_val (csock_v);
3715 state.rotate = Int_val (Field (params_v, 0));
3716 state.fitmodel = Int_val (Field (params_v, 1));
3717 trim_v = Field (params_v, 2);
3718 texcount = Int_val (Field (params_v, 3));
3719 state.sliceheight = Int_val (Field (params_v, 4));
3720 mustoresize = Int_val (Field (params_v, 5));
3721 colorspace = Int_val (Field (params_v, 6));
3722 fontpath = String_val (Field (params_v, 7));
3724 #ifdef CIDER
3725 state.utf8cs = 1;
3726 #else
3727 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3728 if (setlocale (LC_CTYPE, "")) {
3729 const char *cset = nl_langinfo (CODESET);
3730 state.utf8cs = !strcmp (cset, "UTF-8");
3732 else {
3733 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3735 #endif
3737 if (caml_string_length (Field (params_v, 8)) > 0) {
3738 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3740 if (!state.trimcachepath) {
3741 printd ("emsg failed to strdup trimcachepath: %d:%s",
3742 errno, strerror (errno));
3746 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3747 fz_register_document_handlers (state.ctx);
3748 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3749 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3751 state.trimmargins = Bool_val (Field (trim_v, 0));
3752 fuzz_v = Field (trim_v, 1);
3753 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3754 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3755 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3756 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3758 set_tex_params (colorspace);
3760 if (*fontpath) {
3761 state.face = load_font (fontpath);
3763 else {
3764 int len;
3765 const unsigned char *data;
3767 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3768 state.face = load_builtin_font (data, len);
3770 if (!state.face) _exit (1);
3772 realloctexts (texcount);
3773 setuppbo ();
3774 makestippletex ();
3776 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3777 if (ret) {
3778 errx (1, "pthread_create: %s", strerror (ret));
3781 CAMLreturn0;
3784 #if FIXME || !FIXME
3785 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3786 #endif