Sync with upstream
[llpp.git] / link.c
blob5856f61a71b8d713b94008e228726472454c76c9
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 #endif
13 extern char **environ;
15 #include <errno.h>
16 #include <stdio.h>
17 #include <ctype.h>
18 #include <string.h>
19 #include <stdlib.h>
20 #include <signal.h>
22 #include <math.h>
23 #include <wchar.h>
24 #include <locale.h>
25 #include <langinfo.h>
27 #include <unistd.h>
28 #include <pthread.h>
29 #include <sys/uio.h>
30 #include <sys/time.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/utsname.h>
37 #include <spawn.h>
39 #include <regex.h>
40 #include <stdarg.h>
41 #include <limits.h>
42 #include <inttypes.h>
44 #ifdef CIDER
45 #include <OpenGL/gl.h>
46 #else
47 #include <GL/gl.h>
48 #endif
50 #pragma GCC diagnostic push
51 #ifdef __clang__
52 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
53 #endif
54 #pragma GCC diagnostic ignored "-Wpedantic"
55 #define CAML_NAME_SPACE
56 #include <caml/fail.h>
57 #include <caml/alloc.h>
58 #include <caml/memory.h>
59 #include <caml/unixsupport.h>
61 #pragma GCC diagnostic push
62 #pragma GCC diagnostic ignored "-Wfloat-equal"
63 #include <mupdf/fitz.h>
64 #include <mupdf/pdf.h>
65 #pragma GCC diagnostic pop
67 #include <ft2build.h>
68 #include FT_FREETYPE_H
69 #pragma GCC diagnostic pop
71 #include "cutils.h"
73 #ifdef USE_NPOT
74 #define TEXT_TYPE GL_TEXTURE_2D
75 #else
76 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
77 #endif
79 #if 0
80 #define lprintf printf
81 #else
82 #define lprintf(...)
83 #endif
85 #define ARSERT(cond) for (;;) { \
86 if (!(cond)) { \
87 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
88 } \
89 break; \
90 } (void) 0
92 struct slice {
93 int h;
94 int texindex;
97 struct tile {
98 int w, h;
99 int slicecount;
100 int sliceheight;
101 struct bo *pbo;
102 fz_pixmap *pixmap;
103 struct slice slices[1];
106 struct pagedim {
107 int pageno;
108 int rotate;
109 int left;
110 int tctmready;
111 fz_irect bounds;
112 fz_rect pagebox;
113 fz_rect mediabox;
114 fz_matrix ctm, zoomctm, tctm;
117 struct slink {
118 enum { SLINK, SANNOT } tag;
119 fz_irect bbox;
120 union {
121 fz_link *link;
122 pdf_annot *annot;
123 } u;
126 struct annot {
127 fz_irect bbox;
128 pdf_annot *annot;
131 struct page {
132 int tgen;
133 int sgen;
134 int agen;
135 int pageno;
136 int pdimno;
137 fz_stext_page *text;
138 fz_page *fzpage;
139 fz_display_list *dlist;
140 fz_link *links;
141 int slinkcount;
142 struct slink *slinks;
143 int annotcount;
144 struct annot *annots;
145 fz_stext_char *fmark, *lmark;
148 enum { FitWidth, FitProportional, FitPage };
150 static struct {
151 int sliceheight;
152 struct pagedim *pagedims;
153 int pagecount;
154 int pagedimcount;
155 fz_document *doc;
156 fz_context *ctx;
157 int w, h;
159 int texindex;
160 int texcount;
161 GLuint *texids;
163 GLenum texiform;
164 GLenum texform;
165 GLenum texty;
167 fz_colorspace *colorspace;
168 float papercolor[4];
170 struct {
171 int w, h;
172 struct slice *slice;
173 } *texowners;
175 int rotate;
176 int fitmodel;
177 int trimmargins;
178 int needoutline;
179 int gen;
180 int aalevel;
182 int trimanew;
183 fz_irect trimfuzz;
184 fz_pixmap *pig;
186 pthread_t thread;
187 int csock;
188 FT_Face face;
190 char *trimcachepath;
191 int dirty;
193 GLuint stid;
195 int bo_usable;
196 GLuint boid;
198 void (*glBindBufferARB) (GLenum, GLuint);
199 GLboolean (*glUnmapBufferARB) (GLenum);
200 void *(*glMapBufferARB) (GLenum, GLenum);
201 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
202 void (*glGenBuffersARB) (GLsizei, GLuint *);
203 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
205 GLfloat texcoords[8];
206 GLfloat vertices[16];
208 int utf8cs;
209 } state;
211 struct bo {
212 GLuint id;
213 void *ptr;
214 size_t size;
217 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
219 static void lock (const char *cap)
221 int ret = pthread_mutex_lock (&mutex);
222 if (ret) {
223 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
227 static void unlock (const char *cap)
229 int ret = pthread_mutex_unlock (&mutex);
230 if (ret) {
231 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
235 static int trylock (const char *cap)
237 int ret = pthread_mutex_trylock (&mutex);
238 if (ret && ret != EBUSY) {
239 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
241 return ret == EBUSY;
244 static int hasdata (void)
246 int ret, avail;
247 ret = ioctl (state.csock, FIONREAD, &avail);
248 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
249 return avail > 0;
252 value ml_hasdata (value fd_v);
253 value ml_hasdata (value fd_v)
255 CAMLparam1 (fd_v);
256 int ret, avail;
258 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
259 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
260 CAMLreturn (Val_bool (avail > 0));
263 static void readdata (int fd, void *p, int size)
265 ssize_t n;
267 again:
268 n = read (fd, p, size);
269 if (n - size) {
270 if (n < 0 && errno == EINTR) goto again;
271 if (!n) errx (1, "EOF while reading");
272 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
276 static void writedata (int fd, char *p, int size)
278 ssize_t n;
279 uint32_t size4 = size;
280 struct iovec iov[2] = {
281 { .iov_base = &size4, .iov_len = 4 },
282 { .iov_base = p, .iov_len = size }
285 again:
286 n = writev (fd, iov, 2);
287 if (n < 0 && errno == EINTR) goto again;
288 if (n - size - 4) {
289 if (!n) errx (1, "EOF while writing data");
290 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
294 static int readlen (int fd)
296 uint32_t u;
297 readdata (fd, &u, 4);
298 return u;
301 void ml_wcmd (value fd_v, value bytes_v, value len_v);
302 void ml_wcmd (value fd_v, value bytes_v, value len_v)
304 CAMLparam3 (fd_v, bytes_v, len_v);
305 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
306 CAMLreturn0;
309 value ml_rcmd (value fd_v);
310 value ml_rcmd (value fd_v)
312 CAMLparam1 (fd_v);
313 CAMLlocal1 (strdata_v);
314 int fd = Int_val (fd_v);
315 int len = readlen (fd);
316 strdata_v = caml_alloc_string (len);
317 readdata (fd, String_val (strdata_v), len);
318 CAMLreturn (strdata_v);
321 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
323 char fbuf[64];
324 int size = sizeof (fbuf), len;
325 va_list ap;
326 char *buf = fbuf;
328 for (;;) {
329 va_start (ap, fmt);
330 len = vsnprintf (buf, size, fmt, ap);
331 va_end (ap);
333 if (len > -1) {
334 if (len < size - 4) {
335 writedata (state.csock, buf, len);
336 break;
338 else size = len + 5;
340 else {
341 err (1, "vsnprintf for `%s' failed", fmt);
343 buf = realloc (buf == fbuf ? NULL : buf, size);
344 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
346 if (buf != fbuf) free (buf);
349 static void closedoc (void)
351 if (state.doc) {
352 fz_drop_document (state.ctx, state.doc);
353 state.doc = NULL;
357 static int openxref (char *filename, char *password, int layouth)
359 for (int i = 0; i < state.texcount; ++i) {
360 state.texowners[i].w = -1;
361 state.texowners[i].slice = NULL;
364 closedoc ();
366 state.dirty = 0;
367 if (state.pagedims) {
368 free (state.pagedims);
369 state.pagedims = NULL;
371 state.pagedimcount = 0;
373 fz_set_aa_level (state.ctx, state.aalevel);
374 state.doc = fz_open_document (state.ctx, filename);
375 if (fz_needs_password (state.ctx, state.doc)) {
376 if (password && !*password) {
377 printd ("pass");
378 return 0;
380 else {
381 int ok = fz_authenticate_password (state.ctx, state.doc, password);
382 if (!ok) {
383 printd ("pass fail");
384 return 0;
388 if (layouth >= 0)
389 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
390 state.pagecount = fz_count_pages (state.ctx, state.doc);
391 return 1;
394 static void docinfo (void)
396 struct { char *tag; char *name; } metatbl[] = {
397 { FZ_META_INFO_TITLE, "Title" },
398 { FZ_META_INFO_AUTHOR, "Author" },
399 { FZ_META_FORMAT, "Format" },
400 { FZ_META_ENCRYPTION, "Encryption" },
401 { "info:Creator", "Creator" },
402 { "info:Producer", "Producer" },
403 { "info:CreationDate", "Creation date" },
405 int len = 0;
406 char *buf = NULL;
408 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
409 int need;
410 again:
411 need = fz_lookup_metadata (state.ctx, state.doc,
412 metatbl[i].tag, buf, len);
413 if (need > 0) {
414 if (need <= len) {
415 printd ("info %s\t%s", metatbl[i].name, buf);
417 else {
418 buf = realloc (buf, need + 1);
419 if (!buf) err (1, "docinfo realloc %d", need + 1);
420 len = need + 1;
421 goto again;
425 free (buf);
427 printd ("infoend");
430 static void unlinktile (struct tile *tile)
432 for (int i = 0; i < tile->slicecount; ++i) {
433 struct slice *s = &tile->slices[i];
435 if (s->texindex != -1) {
436 if (state.texowners[s->texindex].slice == s) {
437 state.texowners[s->texindex].slice = NULL;
443 static void freepage (struct page *page)
445 if (!page) return;
446 if (page->text) {
447 fz_drop_stext_page (state.ctx, page->text);
449 if (page->slinks) {
450 free (page->slinks);
452 fz_drop_display_list (state.ctx, page->dlist);
453 fz_drop_page (state.ctx, page->fzpage);
454 free (page);
457 static void freetile (struct tile *tile)
459 unlinktile (tile);
460 if (!tile->pbo) {
461 #if 0
462 fz_drop_pixmap (state.ctx, tile->pixmap);
463 #else /* piggyback */
464 if (state.pig) {
465 fz_drop_pixmap (state.ctx, state.pig);
467 state.pig = tile->pixmap;
468 #endif
470 else {
471 free (tile->pbo);
472 fz_drop_pixmap (state.ctx, tile->pixmap);
474 free (tile);
477 static void trimctm (pdf_page *page, int pindex)
479 struct pagedim *pdim = &state.pagedims[pindex];
481 if (!page) return;
482 if (!pdim->tctmready) {
483 fz_rect realbox, mediabox;
484 fz_matrix page_ctm, ctm;
486 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
487 realbox = fz_transform_rect (pdim->mediabox, ctm);
488 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
489 pdim->tctm = fz_concat (
490 fz_invert_matrix (page_ctm),
491 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
492 pdim->tctmready = 1;
496 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
498 fz_matrix ctm;
499 ptrdiff_t pdimno = pdim - state.pagedims;
501 ARSERT (pdim - state.pagedims < INT_MAX);
502 if (pdf_specifics (state.ctx, state.doc)) {
503 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
504 ctm = fz_concat (pdim->tctm, pdim->ctm);
506 else {
507 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
508 pdim->ctm);
510 return ctm;
513 static fz_matrix pagectm (struct page *page)
515 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
518 static void *loadpage (int pageno, int pindex)
520 fz_device *dev;
521 struct page *page;
523 page = calloc (sizeof (struct page), 1);
524 if (!page) {
525 err (1, "calloc page %d", pageno);
528 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
529 dev = fz_new_list_device (state.ctx, page->dlist);
530 fz_try (state.ctx) {
531 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
532 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
534 fz_catch (state.ctx) {
535 page->fzpage = NULL;
537 fz_close_device (state.ctx, dev);
538 fz_drop_device (state.ctx, dev);
540 page->pdimno = pindex;
541 page->pageno = pageno;
542 page->sgen = state.gen;
543 page->agen = state.gen;
544 page->tgen = state.gen;
545 return page;
548 static struct tile *alloctile (int h)
550 int slicecount;
551 size_t tilesize;
552 struct tile *tile;
554 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
555 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
556 tile = calloc (tilesize, 1);
557 if (!tile) {
558 err (1, "cannot allocate tile (%zu bytes)", tilesize);
560 for (int i = 0; i < slicecount; ++i) {
561 int sh = fz_mini (h, state.sliceheight);
562 tile->slices[i].h = sh;
563 tile->slices[i].texindex = -1;
564 h -= sh;
566 tile->slicecount = slicecount;
567 tile->sliceheight = state.sliceheight;
568 return tile;
571 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
572 struct bo *pbo)
574 fz_irect bbox;
575 fz_matrix ctm;
576 fz_device *dev;
577 struct tile *tile;
578 struct pagedim *pdim;
580 tile = alloctile (h);
581 pdim = &state.pagedims[page->pdimno];
583 bbox = pdim->bounds;
584 bbox.x0 += x;
585 bbox.y0 += y;
586 bbox.x1 = bbox.x0 + w;
587 bbox.y1 = bbox.y0 + h;
589 if (state.pig) {
590 if (state.pig->w == w
591 && state.pig->h == h
592 && state.pig->colorspace == state.colorspace) {
593 tile->pixmap = state.pig;
594 tile->pixmap->x = bbox.x0;
595 tile->pixmap->y = bbox.y0;
597 else {
598 fz_drop_pixmap (state.ctx, state.pig);
600 state.pig = NULL;
602 if (!tile->pixmap) {
603 if (pbo) {
604 tile->pixmap =
605 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
606 bbox, NULL, 1, pbo->ptr);
607 tile->pbo = pbo;
609 else {
610 tile->pixmap =
611 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
612 NULL, 1);
616 tile->w = w;
617 tile->h = h;
618 fz_fill_pixmap_with_color (state.ctx, tile->pixmap,
619 fz_device_rgb (state.ctx),
620 state.papercolor,
621 fz_default_color_params);
623 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
624 ctm = pagectm (page);
625 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
626 fz_rect_from_irect (bbox), NULL);
627 fz_close_device (state.ctx, dev);
628 fz_drop_device (state.ctx, dev);
630 return tile;
633 static void initpdims (void)
635 FILE *trimf = NULL;
636 fz_rect rootmediabox = fz_empty_rect;
637 int pageno, trim, show;
638 int trimw = 0, cxcount;
639 fz_context *ctx = state.ctx;
640 pdf_document *pdf = pdf_specifics (ctx, state.doc);
642 fz_var (trimw);
643 fz_var (trimf);
644 fz_var (cxcount);
646 if (state.trimmargins && state.trimcachepath) {
647 trimf = fopen (state.trimcachepath, "rb");
648 if (!trimf) {
649 trimf = fopen (state.trimcachepath, "wb");
650 trimw = 1;
654 cxcount = state.pagecount;
655 if (pdf) {
656 pdf_obj *obj;
657 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
658 "Root/Pages/MediaBox");
659 rootmediabox = pdf_to_rect (ctx, obj);
660 pdf_load_page_tree (ctx, pdf);
663 for (pageno = 0; pageno < cxcount; ++pageno) {
664 int rotate = 0;
665 struct pagedim *p;
666 fz_rect mediabox = fz_empty_rect;
668 fz_var (rotate);
669 if (pdf) {
670 pdf_obj *pageobj = NULL;
672 fz_var (pageobj);
673 if (pdf->rev_page_map) {
674 for (int i = 0; i < pdf->rev_page_count; ++i) {
675 if (pdf->rev_page_map[i].page == pageno) {
676 pageobj = pdf_get_xref_entry (
677 ctx, pdf, pdf->rev_page_map[i].object
678 )->obj;
679 break;
683 if (!pageobj) {
684 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
687 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
689 if (state.trimmargins) {
690 pdf_obj *obj;
691 pdf_page *page;
693 fz_try (ctx) {
694 page = pdf_load_page (ctx, pdf, pageno);
695 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
696 trim = state.trimanew || !obj;
697 if (trim) {
698 fz_rect rect;
699 fz_device *dev;
700 fz_matrix ctm, page_ctm;
702 dev = fz_new_bbox_device (ctx, &rect);
703 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
704 ctm = fz_invert_matrix (page_ctm);
705 pdf_run_page (ctx, page, dev, fz_identity, NULL);
706 fz_close_device (ctx, dev);
707 fz_drop_device (ctx, dev);
709 rect.x0 += state.trimfuzz.x0;
710 rect.x1 += state.trimfuzz.x1;
711 rect.y0 += state.trimfuzz.y0;
712 rect.y1 += state.trimfuzz.y1;
713 rect = fz_transform_rect (rect, ctm);
714 rect = fz_intersect_rect (rect, mediabox);
716 if (!fz_is_empty_rect (rect)) {
717 mediabox = rect;
720 obj = pdf_new_array (ctx, pdf, 4);
721 pdf_array_push (ctx, obj,
722 pdf_new_real (ctx, mediabox.x0));
723 pdf_array_push (ctx, obj,
724 pdf_new_real (ctx, mediabox.y0));
725 pdf_array_push (ctx, obj,
726 pdf_new_real (ctx, mediabox.x1));
727 pdf_array_push (ctx, obj,
728 pdf_new_real (ctx, mediabox.y1));
729 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
731 else {
732 mediabox.x0 = pdf_to_real (ctx,
733 pdf_array_get (ctx, obj, 0));
734 mediabox.y0 = pdf_to_real (ctx,
735 pdf_array_get (ctx, obj, 1));
736 mediabox.x1 = pdf_to_real (ctx,
737 pdf_array_get (ctx, obj, 2));
738 mediabox.y1 = pdf_to_real (ctx,
739 pdf_array_get (ctx, obj, 3));
742 fz_drop_page (ctx, &page->super);
743 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
744 if (show) {
745 printd ("progress %f Trimming %d",
746 (double) (pageno + 1) / state.pagecount,
747 pageno + 1);
750 fz_catch (ctx) {
751 printd ("emsg failed to load page %d", pageno);
754 else {
755 int empty = 0;
756 fz_rect cropbox;
758 mediabox =
759 pdf_to_rect (ctx, pdf_dict_get_inheritable (
760 ctx,
761 pageobj,
762 PDF_NAME (MediaBox)
765 if (fz_is_empty_rect (mediabox)) {
766 mediabox.x0 = 0;
767 mediabox.y0 = 0;
768 mediabox.x1 = 612;
769 mediabox.y1 = 792;
770 empty = 1;
773 cropbox =
774 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
775 if (!fz_is_empty_rect (cropbox)) {
776 if (empty) {
777 mediabox = cropbox;
779 else {
780 mediabox = fz_intersect_rect (mediabox, cropbox);
783 else {
784 if (empty) {
785 if (fz_is_empty_rect (rootmediabox)) {
786 printd ("emsg cannot find page size for page %d",
787 pageno);
789 else {
790 mediabox = rootmediabox;
796 else {
797 if (state.trimmargins && trimw) {
798 fz_page *page;
800 fz_try (ctx) {
801 page = fz_load_page (ctx, state.doc, pageno);
802 mediabox = fz_bound_page (ctx, page);
803 if (state.trimmargins) {
804 fz_rect rect;
805 fz_device *dev;
807 dev = fz_new_bbox_device (ctx, &rect);
808 fz_run_page (ctx, page, dev, fz_identity, NULL);
809 fz_close_device (ctx, dev);
810 fz_drop_device (ctx, dev);
812 rect.x0 += state.trimfuzz.x0;
813 rect.x1 += state.trimfuzz.x1;
814 rect.y0 += state.trimfuzz.y0;
815 rect.y1 += state.trimfuzz.y1;
816 rect = fz_intersect_rect (rect, mediabox);
818 if (!fz_is_empty_rect (rect)) {
819 mediabox = rect;
822 fz_drop_page (ctx, page);
824 fz_catch (ctx) {
826 if (trimf) {
827 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
828 if (n - 1) {
829 err (1, "fwrite trim mediabox");
833 else {
834 if (trimf) {
835 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
836 if (n - 1) {
837 err (1, "fread trim mediabox %d", pageno);
840 else {
841 fz_page *page;
842 fz_try (ctx) {
843 page = fz_load_page (ctx, state.doc, pageno);
844 mediabox = fz_bound_page (ctx, page);
845 fz_drop_page (ctx, page);
847 show = !state.trimmargins && pageno % 20 == 0;
848 if (show) {
849 printd ("progress %f Gathering dimensions %d",
850 (double) (pageno) / state.pagecount,
851 pageno);
854 fz_catch (ctx) {
855 printd ("emsg failed to load page %d", pageno);
861 if (state.pagedimcount == 0
862 || ((void) (p = &state.pagedims[state.pagedimcount-1])
863 , p->rotate != rotate)
864 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
865 size_t size;
867 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
868 state.pagedims = realloc (state.pagedims, size);
869 if (!state.pagedims) {
870 err (1, "realloc pagedims to %zu (%d elems)",
871 size, state.pagedimcount + 1);
874 p = &state.pagedims[state.pagedimcount++];
875 p->rotate = rotate;
876 p->mediabox = mediabox;
877 p->pageno = pageno;
880 state.trimanew = 0;
881 if (trimf) {
882 if (fclose (trimf)) {
883 err (1, "fclose");
888 static void layout (void)
890 int pindex;
891 fz_rect box;
892 fz_matrix ctm;
893 struct pagedim *p = NULL;
894 float zw, w, maxw = 0.0, zoom = 1.0;
896 if (state.pagedimcount == 0) return;
898 switch (state.fitmodel) {
899 case FitProportional:
900 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
901 float x0, x1;
903 p = &state.pagedims[pindex];
904 box = fz_transform_rect (p->mediabox,
905 fz_rotate (p->rotate + state.rotate));
907 x0 = fz_min (box.x0, box.x1);
908 x1 = fz_max (box.x0, box.x1);
910 w = x1 - x0;
911 maxw = fz_max (w, maxw);
912 zoom = state.w / maxw;
914 break;
916 case FitPage:
917 maxw = state.w;
918 break;
920 case FitWidth:
921 break;
923 default:
924 ARSERT (0 && state.fitmodel);
927 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
928 p = &state.pagedims[pindex];
929 ctm = fz_rotate (state.rotate);
930 box = fz_transform_rect (p->mediabox,
931 fz_rotate (p->rotate + state.rotate));
932 w = box.x1 - box.x0;
933 switch (state.fitmodel) {
934 case FitProportional:
935 p->left = (int) (((maxw - w) * zoom) / 2.f);
936 break;
937 case FitPage:
939 float zh, h;
940 zw = maxw / w;
941 h = box.y1 - box.y0;
942 zh = state.h / h;
943 zoom = fz_min (zw, zh);
944 p->left = (int) ((maxw - (w * zoom)) / 2.f);
946 break;
947 case FitWidth:
948 p->left = 0;
949 zoom = state.w / w;
950 break;
953 p->zoomctm = fz_scale (zoom, zoom);
954 ctm = fz_concat (p->zoomctm, ctm);
956 p->pagebox = p->mediabox;
957 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
958 p->pagebox.x1 -= p->pagebox.x0;
959 p->pagebox.y1 -= p->pagebox.y0;
960 p->pagebox.x0 = 0;
961 p->pagebox.y0 = 0;
962 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
963 p->ctm = ctm;
965 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
966 fz_scale (zoom, -zoom));
967 p->tctmready = 0;
970 do {
971 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
972 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
973 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
974 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
975 int boundw = x1 - x0;
976 int boundh = y1 - y0;
978 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
979 } while (p-- != state.pagedims);
982 static struct pagedim *pdimofpageno (int pageno)
984 struct pagedim *pdim = state.pagedims;
986 for (int i = 0; i < state.pagedimcount; ++i) {
987 if (state.pagedims[i].pageno > pageno)
988 break;
989 pdim = &state.pagedims[i];
991 return pdim;
994 static void recurse_outline (fz_outline *outline, int level)
996 while (outline) {
997 if (outline->page >= 0) {
998 fz_point p = {.x = outline->x, .y = outline->y};
999 struct pagedim *pdim = pdimofpageno (outline->page);
1000 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1001 p = fz_transform_point (p, pdim->ctm);
1002 printd ("o %d %d %d %d %s",
1003 level, outline->page, (int) p.y, h, outline->title);
1005 else {
1006 printd ("on %d %s", level, outline->title);
1008 if (outline->down) {
1009 recurse_outline (outline->down, level + 1);
1011 outline = outline->next;
1015 static void process_outline (void)
1017 fz_outline *outline;
1019 if (!state.needoutline || !state.pagedimcount) return;
1021 state.needoutline = 0;
1022 outline = fz_load_outline (state.ctx, state.doc);
1023 if (outline) {
1024 recurse_outline (outline, 0);
1025 fz_drop_outline (state.ctx, outline);
1029 static char *strofline (fz_stext_line *line)
1031 char *p;
1032 char utf8[10];
1033 fz_stext_char *ch;
1034 size_t size = 0, cap = 80;
1036 p = malloc (cap + 1);
1037 if (!p) return NULL;
1039 for (ch = line->first_char; ch; ch = ch->next) {
1040 int n = fz_runetochar (utf8, ch->c);
1041 if (size + n > cap) {
1042 cap *= 2;
1043 p = realloc (p, cap + 1);
1044 if (!p) return NULL;
1047 memcpy (p + size, utf8, n);
1048 size += n;
1050 p[size] = 0;
1051 return p;
1054 static int matchline (regex_t *re, fz_stext_line *line,
1055 int stop, int pageno, double start)
1057 int ret;
1058 char *p;
1059 regmatch_t rm;
1061 p = strofline (line);
1062 if (!p) return -1;
1064 ret = regexec (re, p, 1, &rm, 0);
1065 if (ret) {
1066 free (p);
1067 if (ret != REG_NOMATCH) {
1068 size_t size;
1069 char errbuf[80];
1070 size = regerror (ret, re, errbuf, sizeof (errbuf));
1071 printd ("msg regexec error `%.*s'",
1072 (int) size, errbuf);
1073 return -1;
1075 return 0;
1077 else {
1078 fz_quad s, e;
1079 fz_stext_char *ch;
1080 int o = 0;
1082 for (ch = line->first_char; ch; ch = ch->next) {
1083 o += fz_runelen (ch->c);
1084 if (o > rm.rm_so) {
1085 s = ch->quad;
1086 break;
1089 for (;ch; ch = ch->next) {
1090 o += fz_runelen (ch->c);
1091 if (o > rm.rm_eo) break;
1093 e = ch->quad;
1095 if (!stop) {
1096 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1097 pageno, 1,
1098 s.ul.x, s.ul.y,
1099 e.ur.x, s.ul.y,
1100 e.lr.x, e.lr.y,
1101 s.ul.x, e.lr.y);
1103 printd ("progress 1 found at %d `%.*s' in %f sec",
1104 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1105 now () - start);
1107 else {
1108 printd ("match %d %d %f %f %f %f %f %f %f %f",
1109 pageno, 2,
1110 s.ul.x, s.ul.y,
1111 e.ur.x, s.ul.y,
1112 e.lr.x, e.lr.y,
1113 s.ul.x, e.lr.y);
1115 free (p);
1116 return 1;
1120 /* wishful thinking function */
1121 static void search (regex_t *re, int pageno, int y, int forward)
1123 fz_device *tdev;
1124 fz_stext_page *text;
1125 struct pagedim *pdim;
1126 int stop = 0, niters = 0;
1127 double start, end;
1128 fz_page *page;
1129 fz_stext_block *block;
1131 start = now ();
1132 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1133 if (niters++ == 5) {
1134 niters = 0;
1135 if (hasdata ()) {
1136 printd ("progress 1 attention requested aborting search at %d",
1137 pageno);
1138 stop = 1;
1140 else {
1141 printd ("progress %f searching in page %d",
1142 (double) (pageno + 1) / state.pagecount,
1143 pageno);
1146 pdim = pdimofpageno (pageno);
1147 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1148 tdev = fz_new_stext_device (state.ctx, text, 0);
1150 page = fz_load_page (state.ctx, state.doc, pageno);
1151 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1153 fz_close_device (state.ctx, tdev);
1154 fz_drop_device (state.ctx, tdev);
1156 if (forward) {
1157 for (block = text->first_block; block; block = block->next) {
1158 fz_stext_line *line;
1160 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1161 for (line = block->u.t.first_line; line; line = line->next) {
1162 if (line->bbox.y0 < y + 1) continue;
1164 switch (matchline (re, line, stop, pageno, start)) {
1165 case 0: break;
1166 case 1: stop = 1; break;
1167 case -1: stop = 1; goto endloop;
1172 else {
1173 for (block = text->last_block; block; block = block->prev) {
1174 fz_stext_line *line;
1176 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1177 for (line = block->u.t.last_line; line; line = line->prev) {
1178 if (line->bbox.y0 < y + 1) continue;
1180 switch (matchline (re, line, stop, pageno, start)) {
1181 case 0: break;
1182 case 1: stop = 1; break;
1183 case -1: stop = 1; goto endloop;
1189 if (forward) {
1190 pageno += 1;
1191 y = 0;
1193 else {
1194 pageno -= 1;
1195 y = INT_MAX;
1197 endloop:
1198 fz_drop_stext_page (state.ctx, text);
1199 fz_drop_page (state.ctx, page);
1201 end = now ();
1202 if (!stop) {
1203 printd ("progress 1 no matches %f sec", end - start);
1205 printd ("clearrects");
1208 static void set_tex_params (int colorspace)
1210 switch (colorspace) {
1211 case 0:
1212 state.texiform = GL_RGBA8;
1213 state.texform = GL_RGBA;
1214 state.texty = GL_UNSIGNED_BYTE;
1215 state.colorspace = fz_device_rgb (state.ctx);
1216 break;
1217 case 1:
1218 state.texiform = GL_LUMINANCE_ALPHA;
1219 state.texform = GL_LUMINANCE_ALPHA;
1220 state.texty = GL_UNSIGNED_BYTE;
1221 state.colorspace = fz_device_gray (state.ctx);
1222 break;
1223 default:
1224 errx (1, "invalid colorspce %d", colorspace);
1228 static void realloctexts (int texcount)
1230 size_t size;
1232 if (texcount == state.texcount) return;
1234 if (texcount < state.texcount) {
1235 glDeleteTextures (state.texcount - texcount,
1236 state.texids + texcount);
1239 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1240 state.texids = realloc (state.texids, size);
1241 if (!state.texids) {
1242 err (1, "realloc texs %zu", size);
1245 state.texowners = (void *) (state.texids + texcount);
1246 if (texcount > state.texcount) {
1247 glGenTextures (texcount - state.texcount,
1248 state.texids + state.texcount);
1249 for (int i = state.texcount; i < texcount; ++i) {
1250 state.texowners[i].w = -1;
1251 state.texowners[i].slice = NULL;
1254 state.texcount = texcount;
1255 state.texindex = 0;
1258 static char *mbtoutf8 (char *s)
1260 char *p, *r;
1261 wchar_t *tmp;
1262 size_t i, ret, len;
1264 if (state.utf8cs) {
1265 return s;
1268 len = mbstowcs (NULL, s, strlen (s));
1269 if (len == 0 || len == (size_t) -1) {
1270 if (len)
1271 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1272 return s;
1275 tmp = calloc (len, sizeof (wchar_t));
1276 if (!tmp) {
1277 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1278 len, sizeof (wchar_t), errno, strerror (errno));
1279 return s;
1282 ret = mbstowcs (tmp, s, len);
1283 if (ret == (size_t) -1) {
1284 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1285 len, errno, strerror (errno));
1286 free (tmp);
1287 return s;
1290 len = 0;
1291 for (i = 0; i < ret; ++i) {
1292 len += fz_runelen (tmp[i]);
1295 p = r = malloc (len + 1);
1296 if (!r) {
1297 printd ("emsg mbtoutf8: malloc(%zu)", len);
1298 free (tmp);
1299 return s;
1302 for (i = 0; i < ret; ++i) {
1303 p += fz_runetochar (p, tmp[i]);
1305 *p = 0;
1306 free (tmp);
1307 return r;
1310 value ml_mbtoutf8 (value s_v);
1311 value ml_mbtoutf8 (value s_v)
1313 CAMLparam1 (s_v);
1314 CAMLlocal1 (ret_v);
1315 char *s, *r;
1317 s = String_val (s_v);
1318 r = mbtoutf8 (s);
1319 if (r == s) {
1320 ret_v = s_v;
1322 else {
1323 ret_v = caml_copy_string (r);
1324 free (r);
1326 CAMLreturn (ret_v);
1329 static void * mainloop (void UNUSED_ATTR *unused)
1331 char *p = NULL;
1332 int len, ret, oldlen = 0;
1334 fz_var (p);
1335 fz_var (oldlen);
1336 for (;;) {
1337 len = readlen (state.csock);
1338 if (len == 0) {
1339 errx (1, "readlen returned 0");
1342 if (oldlen < len + 1) {
1343 p = realloc (p, len + 1);
1344 if (!p) {
1345 err (1, "realloc %d failed", len + 1);
1347 oldlen = len + 1;
1349 readdata (state.csock, p, len);
1350 p[len] = 0;
1352 if (!strncmp ("open", p, 4)) {
1353 int off, usedoccss, ok = 0, layouth;
1354 char *password;
1355 char *filename;
1356 char *utf8filename;
1357 size_t filenamelen;
1359 fz_var (ok);
1360 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1361 if (ret != 2) {
1362 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1365 filename = p + 5 + off;
1366 filenamelen = strlen (filename);
1367 password = filename + filenamelen + 1;
1369 if (password[strlen (password) + 1]) {
1370 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1373 lock ("open");
1374 fz_set_use_document_css (state.ctx, usedoccss);
1375 fz_try (state.ctx) {
1376 ok = openxref (filename, password, layouth);
1378 fz_catch (state.ctx) {
1379 utf8filename = mbtoutf8 (filename);
1380 printd ("emsg Error loading %s: %s",
1381 utf8filename, fz_caught_message (state.ctx));
1382 if (utf8filename != filename) {
1383 free (utf8filename);
1386 if (ok) {
1387 docinfo ();
1388 initpdims ();
1390 unlock ("open");
1391 state.needoutline = ok;
1393 else if (!strncmp ("cs", p, 2)) {
1394 int i, colorspace;
1396 ret = sscanf (p + 2, " %d", &colorspace);
1397 if (ret != 1) {
1398 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1400 lock ("cs");
1401 set_tex_params (colorspace);
1402 for (i = 0; i < state.texcount; ++i) {
1403 state.texowners[i].w = -1;
1404 state.texowners[i].slice = NULL;
1406 unlock ("cs");
1408 else if (!strncmp ("freepage", p, 8)) {
1409 void *ptr;
1411 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1412 if (ret != 1) {
1413 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1415 lock ("freepage");
1416 freepage (ptr);
1417 unlock ("freepage");
1419 else if (!strncmp ("freetile", p, 8)) {
1420 void *ptr;
1422 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1423 if (ret != 1) {
1424 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1426 lock ("freetile");
1427 freetile (ptr);
1428 unlock ("freetile");
1430 else if (!strncmp ("search", p, 6)) {
1431 int icase, pageno, y, len2, forward;
1432 char *pattern;
1433 regex_t re;
1435 ret = sscanf (p + 6, " %d %d %d %d,%n",
1436 &icase, &pageno, &y, &forward, &len2);
1437 if (ret != 4) {
1438 errx (1, "malformed search `%s' ret=%d", p, ret);
1441 pattern = p + 6 + len2;
1442 ret = regcomp (&re, pattern,
1443 REG_EXTENDED | (icase ? REG_ICASE : 0));
1444 if (ret) {
1445 char errbuf[80];
1446 size_t size;
1448 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1449 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1451 else {
1452 lock ("search");
1453 search (&re, pageno, y, forward);
1454 unlock ("search");
1455 regfree (&re);
1458 else if (!strncmp ("geometry", p, 8)) {
1459 int w, h, fitmodel;
1461 printd ("clear");
1462 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1463 if (ret != 3) {
1464 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1467 lock ("geometry");
1468 state.h = h;
1469 if (w != state.w) {
1470 state.w = w;
1471 for (int i = 0; i < state.texcount; ++i) {
1472 state.texowners[i].slice = NULL;
1475 state.fitmodel = fitmodel;
1476 layout ();
1477 process_outline ();
1479 state.gen++;
1480 unlock ("geometry");
1481 printd ("continue %d", state.pagecount);
1483 else if (!strncmp ("reqlayout", p, 9)) {
1484 char *nameddest;
1485 int rotate, off, h;
1486 int fitmodel;
1487 pdf_document *pdf;
1489 printd ("clear");
1490 ret = sscanf (p + 9, " %d %d %d %n",
1491 &rotate, &fitmodel, &h, &off);
1492 if (ret != 3) {
1493 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1495 lock ("reqlayout");
1496 pdf = pdf_specifics (state.ctx, state.doc);
1497 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1498 state.gen += 1;
1500 state.rotate = rotate;
1501 state.fitmodel = fitmodel;
1502 state.h = h;
1503 layout ();
1504 process_outline ();
1506 nameddest = p + 9 + off;
1507 if (pdf && nameddest && *nameddest) {
1508 fz_point xy;
1509 struct pagedim *pdim;
1510 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1511 &xy.x, &xy.y);
1512 pdim = pdimofpageno (pageno);
1513 xy = fz_transform_point (xy, pdim->ctm);
1514 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1517 state.gen++;
1518 unlock ("reqlayout");
1519 printd ("continue %d", state.pagecount);
1521 else if (!strncmp ("page", p, 4)) {
1522 double a, b;
1523 struct page *page;
1524 int pageno, pindex;
1526 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1527 if (ret != 2) {
1528 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1531 lock ("page");
1532 a = now ();
1533 page = loadpage (pageno, pindex);
1534 b = now ();
1535 unlock ("page");
1537 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1539 else if (!strncmp ("tile", p, 4)) {
1540 int x, y, w, h;
1541 struct page *page;
1542 struct tile *tile;
1543 double a, b;
1544 void *data;
1546 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1547 (uintptr_t *) &page, &x, &y, &w, &h,
1548 (uintptr_t *) &data);
1549 if (ret != 6) {
1550 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1553 lock ("tile");
1554 a = now ();
1555 tile = rendertile (page, x, y, w, h, data);
1556 b = now ();
1557 unlock ("tile");
1559 printd ("tile %d %d %" PRIxPTR " %u %f",
1560 x, y, (uintptr_t) (tile),
1561 tile->w * tile->h * tile->pixmap->n,
1562 b - a);
1564 else if (!strncmp ("trimset", p, 7)) {
1565 fz_irect fuzz;
1566 int trimmargins;
1568 ret = sscanf (p + 7, " %d %d %d %d %d",
1569 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1570 if (ret != 5) {
1571 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1573 lock ("trimset");
1574 state.trimmargins = trimmargins;
1575 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1576 state.trimanew = 1;
1577 state.trimfuzz = fuzz;
1579 unlock ("trimset");
1581 else if (!strncmp ("settrim", p, 7)) {
1582 fz_irect fuzz;
1583 int trimmargins;
1585 ret = sscanf (p + 7, " %d %d %d %d %d",
1586 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1587 if (ret != 5) {
1588 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1590 printd ("clear");
1591 lock ("settrim");
1592 state.trimmargins = trimmargins;
1593 state.needoutline = 1;
1594 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1595 state.trimanew = 1;
1596 state.trimfuzz = fuzz;
1598 state.pagedimcount = 0;
1599 free (state.pagedims);
1600 state.pagedims = NULL;
1601 initpdims ();
1602 layout ();
1603 process_outline ();
1604 unlock ("settrim");
1605 printd ("continue %d", state.pagecount);
1607 else if (!strncmp ("sliceh", p, 6)) {
1608 int h;
1610 ret = sscanf (p + 6, " %d", &h);
1611 if (ret != 1) {
1612 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1614 if (h != state.sliceheight) {
1615 state.sliceheight = h;
1616 for (int i = 0; i < state.texcount; ++i) {
1617 state.texowners[i].w = -1;
1618 state.texowners[i].h = -1;
1619 state.texowners[i].slice = NULL;
1623 else if (!strncmp ("interrupt", p, 9)) {
1624 printd ("vmsg interrupted");
1626 else {
1627 errx (1, "unknown command %.*s", len, p);
1630 return 0;
1633 value ml_isexternallink (value uri_v);
1634 value ml_isexternallink (value uri_v)
1636 CAMLparam1 (uri_v);
1637 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1638 CAMLreturn (Val_bool (ext));
1641 value ml_uritolocation (value uri_v);
1642 value ml_uritolocation (value uri_v)
1644 CAMLparam1 (uri_v);
1645 CAMLlocal1 (ret_v);
1646 int pageno;
1647 fz_point xy;
1648 struct pagedim *pdim;
1650 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1651 &xy.x, &xy.y).page;
1652 pdim = pdimofpageno (pageno);
1653 xy = fz_transform_point (xy, pdim->ctm);
1654 ret_v = caml_alloc_tuple (3);
1655 Field (ret_v, 0) = Val_int (pageno);
1656 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1657 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1658 CAMLreturn (ret_v);
1661 value ml_realloctexts (value texcount_v);
1662 value ml_realloctexts (value texcount_v)
1664 CAMLparam1 (texcount_v);
1665 int ok;
1667 if (trylock (__func__)) {
1668 ok = 0;
1669 goto done;
1671 realloctexts (Int_val (texcount_v));
1672 ok = 1;
1673 unlock (__func__);
1675 done:
1676 CAMLreturn (Val_bool (ok));
1679 static void recti (int x0, int y0, int x1, int y1)
1681 GLfloat *v = state.vertices;
1683 glVertexPointer (2, GL_FLOAT, 0, v);
1684 v[0] = x0; v[1] = y0;
1685 v[2] = x1; v[3] = y0;
1686 v[4] = x0; v[5] = y1;
1687 v[6] = x1; v[7] = y1;
1688 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1691 static void showsel (struct page *page, int ox, int oy)
1693 fz_irect bbox;
1694 fz_rect rect;
1695 fz_stext_block *block;
1696 int seen = 0;
1697 unsigned char selcolor[] = {15,15,15,140};
1699 if (!page->fmark || !page->lmark) return;
1701 glEnable (GL_BLEND);
1702 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1703 glColor4ubv (selcolor);
1705 ox += state.pagedims[page->pdimno].bounds.x0;
1706 oy += state.pagedims[page->pdimno].bounds.y0;
1708 for (block = page->text->first_block; block; block = block->next) {
1709 fz_stext_line *line;
1711 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1712 for (line = block->u.t.first_line; line; line = line->next) {
1713 fz_stext_char *ch;
1715 rect = fz_empty_rect;
1716 for (ch = line->first_char; ch; ch = ch->next) {
1717 fz_rect r;
1718 if (ch == page->fmark) seen = 1;
1719 r = fz_rect_from_quad (ch->quad);
1720 if (seen) rect = fz_union_rect (rect, r);
1721 if (ch == page->lmark) {
1722 bbox = fz_round_rect (rect);
1723 recti (bbox.x0 + ox, bbox.y0 + oy,
1724 bbox.x1 + ox, bbox.y1 + oy);
1725 goto done;
1728 bbox = fz_round_rect (rect);
1729 recti (bbox.x0 + ox, bbox.y0 + oy,
1730 bbox.x1 + ox, bbox.y1 + oy);
1733 done:
1734 glDisable (GL_BLEND);
1737 #pragma GCC diagnostic push
1738 #pragma GCC diagnostic ignored "-Wconversion"
1739 #include "glfont.c"
1740 #pragma GCC diagnostic pop
1742 static void stipplerect (fz_matrix m,
1743 fz_point p1,
1744 fz_point p2,
1745 fz_point p3,
1746 fz_point p4,
1747 GLfloat *texcoords,
1748 GLfloat *vertices)
1750 p1 = fz_transform_point (p1, m);
1751 p2 = fz_transform_point (p2, m);
1752 p3 = fz_transform_point (p3, m);
1753 p4 = fz_transform_point (p4, m);
1755 float w, h, s, t;
1757 w = p2.x - p1.x;
1758 h = p2.y - p1.y;
1759 t = hypotf (w, h) * .25f;
1761 w = p3.x - p2.x;
1762 h = p3.y - p2.y;
1763 s = hypotf (w, h) * .25f;
1765 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1766 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1768 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1769 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1771 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1772 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1774 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1775 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1777 glDrawArrays (GL_LINES, 0, 8);
1780 static void solidrect (fz_matrix m,
1781 fz_point p1,
1782 fz_point p2,
1783 fz_point p3,
1784 fz_point p4,
1785 GLfloat *vertices)
1787 p1 = fz_transform_point (p1, m);
1788 p2 = fz_transform_point (p2, m);
1789 p3 = fz_transform_point (p3, m);
1790 p4 = fz_transform_point (p4, m);
1791 vertices[0] = p1.x; vertices[1] = p1.y;
1792 vertices[2] = p2.x; vertices[3] = p2.y;
1794 vertices[4] = p3.x; vertices[5] = p3.y;
1795 vertices[6] = p4.x; vertices[7] = p4.y;
1796 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1799 static void ensurelinks (struct page *page)
1801 if (!page->links)
1802 page->links = fz_load_links (state.ctx, page->fzpage);
1805 static void highlightlinks (struct page *page, int xoff, int yoff)
1807 fz_matrix ctm;
1808 fz_link *link;
1809 GLfloat *texcoords = state.texcoords;
1810 GLfloat *vertices = state.vertices;
1812 ensurelinks (page);
1814 glEnable (GL_TEXTURE_1D);
1815 glEnable (GL_BLEND);
1816 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1817 glBindTexture (GL_TEXTURE_1D, state.stid);
1819 xoff -= state.pagedims[page->pdimno].bounds.x0;
1820 yoff -= state.pagedims[page->pdimno].bounds.y0;
1821 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1823 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1824 glVertexPointer (2, GL_FLOAT, 0, vertices);
1826 for (link = page->links; link; link = link->next) {
1827 fz_point p1, p2, p3, p4;
1829 p1.x = link->rect.x0;
1830 p1.y = link->rect.y0;
1832 p2.x = link->rect.x1;
1833 p2.y = link->rect.y0;
1835 p3.x = link->rect.x1;
1836 p3.y = link->rect.y1;
1838 p4.x = link->rect.x0;
1839 p4.y = link->rect.y1;
1841 /* TODO: different colours for different schemes */
1842 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1843 else glColor3ub (255, 0, 0);
1845 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1848 for (int i = 0; i < page->annotcount; ++i) {
1849 fz_point p1, p2, p3, p4;
1850 struct annot *annot = &page->annots[i];
1852 p1.x = annot->bbox.x0;
1853 p1.y = annot->bbox.y0;
1855 p2.x = annot->bbox.x1;
1856 p2.y = annot->bbox.y0;
1858 p3.x = annot->bbox.x1;
1859 p3.y = annot->bbox.y1;
1861 p4.x = annot->bbox.x0;
1862 p4.y = annot->bbox.y1;
1864 glColor3ub (0, 0, 128);
1865 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1868 glDisable (GL_BLEND);
1869 glDisable (GL_TEXTURE_1D);
1872 static int compareslinks (const void *l, const void *r)
1874 struct slink const *ls = l;
1875 struct slink const *rs = r;
1876 if (ls->bbox.y0 == rs->bbox.y0) {
1877 return rs->bbox.x0 - rs->bbox.x0;
1879 return ls->bbox.y0 - rs->bbox.y0;
1882 static void droptext (struct page *page)
1884 if (page->text) {
1885 fz_drop_stext_page (state.ctx, page->text);
1886 page->fmark = NULL;
1887 page->lmark = NULL;
1888 page->text = NULL;
1892 static void dropannots (struct page *page)
1894 if (page->annots) {
1895 free (page->annots);
1896 page->annots = NULL;
1897 page->annotcount = 0;
1901 static void ensureannots (struct page *page)
1903 int i, count = 0;
1904 size_t annotsize = sizeof (*page->annots);
1905 pdf_annot *annot;
1906 pdf_document *pdf;
1907 pdf_page *pdfpage;
1909 pdf = pdf_specifics (state.ctx, state.doc);
1910 if (!pdf) return;
1912 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1913 if (state.gen != page->agen) {
1914 dropannots (page);
1915 page->agen = state.gen;
1917 if (page->annots) return;
1919 for (annot = pdf_first_annot (state.ctx, pdfpage);
1920 annot;
1921 annot = pdf_next_annot (state.ctx, annot)) {
1922 count++;
1925 if (count > 0) {
1926 page->annotcount = count;
1927 page->annots = calloc (count, annotsize);
1928 if (!page->annots) {
1929 err (1, "calloc annots %d", count);
1932 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1933 annot;
1934 annot = pdf_next_annot (state.ctx, annot), i++) {
1935 fz_rect rect;
1937 rect = pdf_bound_annot (state.ctx, annot);
1938 page->annots[i].annot = annot;
1939 page->annots[i].bbox = fz_round_rect (rect);
1944 static void dropslinks (struct page *page)
1946 if (page->slinks) {
1947 free (page->slinks);
1948 page->slinks = NULL;
1949 page->slinkcount = 0;
1951 if (page->links) {
1952 fz_drop_link (state.ctx, page->links);
1953 page->links = NULL;
1957 static void ensureslinks (struct page *page)
1959 fz_matrix ctm;
1960 int i, count;
1961 size_t slinksize = sizeof (*page->slinks);
1962 fz_link *link;
1964 ensureannots (page);
1965 if (state.gen != page->sgen) {
1966 dropslinks (page);
1967 page->sgen = state.gen;
1969 if (page->slinks) return;
1971 ensurelinks (page);
1972 ctm = pagectm (page);
1974 count = page->annotcount;
1975 for (link = page->links; link; link = link->next) {
1976 count++;
1978 if (count > 0) {
1979 int j;
1981 page->slinkcount = count;
1982 page->slinks = calloc (count, slinksize);
1983 if (!page->slinks) {
1984 err (1, "calloc slinks %d", count);
1987 for (i = 0, link = page->links; link; ++i, link = link->next) {
1988 fz_rect rect;
1990 rect = link->rect;
1991 rect = fz_transform_rect (rect, ctm);
1992 page->slinks[i].tag = SLINK;
1993 page->slinks[i].u.link = link;
1994 page->slinks[i].bbox = fz_round_rect (rect);
1996 for (j = 0; j < page->annotcount; ++j, ++i) {
1997 fz_rect rect;
1998 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1999 rect = fz_transform_rect (rect, ctm);
2000 page->slinks[i].bbox = fz_round_rect (rect);
2002 page->slinks[i].tag = SANNOT;
2003 page->slinks[i].u.annot = page->annots[j].annot;
2005 qsort (page->slinks, count, slinksize, compareslinks);
2009 static void highlightslinks (struct page *page, int xoff, int yoff,
2010 int noff, char *targ, mlsize_t tlen, int hfsize)
2012 char buf[40];
2013 struct slink *slink;
2014 float x0, y0, x1, y1, w;
2016 ensureslinks (page);
2017 glColor3ub (0xc3, 0xb0, 0x91);
2018 for (int i = 0; i < page->slinkcount; ++i) {
2019 fmt_linkn (buf, i + noff);
2020 if (!tlen || !strncmp (targ, buf, tlen)) {
2021 slink = &page->slinks[i];
2023 x0 = slink->bbox.x0 + xoff - 5;
2024 y1 = slink->bbox.y0 + yoff - 5;
2025 y0 = y1 + 10 + hfsize;
2026 w = measure_string (state.face, hfsize, buf);
2027 x1 = x0 + w + 10;
2028 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2032 glEnable (GL_BLEND);
2033 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2034 glEnable (GL_TEXTURE_2D);
2035 glColor3ub (0, 0, 0);
2036 for (int i = 0; i < page->slinkcount; ++i) {
2037 fmt_linkn (buf, i + noff);
2038 if (!tlen || !strncmp (targ, buf, tlen)) {
2039 slink = &page->slinks[i];
2041 x0 = slink->bbox.x0 + xoff;
2042 y0 = slink->bbox.y0 + yoff + hfsize;
2043 draw_string (state.face, hfsize, x0, y0, buf);
2046 glDisable (GL_TEXTURE_2D);
2047 glDisable (GL_BLEND);
2050 static void uploadslice (struct tile *tile, struct slice *slice)
2052 int offset;
2053 struct slice *slice1;
2054 unsigned char *texdata;
2056 offset = 0;
2057 for (slice1 = tile->slices; slice != slice1; slice1++) {
2058 offset += slice1->h * tile->w * tile->pixmap->n;
2060 if (slice->texindex != -1 && slice->texindex < state.texcount
2061 && state.texowners[slice->texindex].slice == slice) {
2062 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2064 else {
2065 int subimage = 0;
2066 int texindex = state.texindex++ % state.texcount;
2068 if (state.texowners[texindex].w == tile->w) {
2069 if (state.texowners[texindex].h >= slice->h) {
2070 subimage = 1;
2072 else {
2073 state.texowners[texindex].h = slice->h;
2076 else {
2077 state.texowners[texindex].h = slice->h;
2080 state.texowners[texindex].w = tile->w;
2081 state.texowners[texindex].slice = slice;
2082 slice->texindex = texindex;
2084 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2085 #if TEXT_TYPE == GL_TEXTURE_2D
2086 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2087 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2088 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2089 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2090 #endif
2091 if (tile->pbo) {
2092 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2093 texdata = 0;
2095 else {
2096 texdata = tile->pixmap->samples;
2098 if (subimage) {
2099 glTexSubImage2D (TEXT_TYPE,
2103 tile->w,
2104 slice->h,
2105 state.texform,
2106 state.texty,
2107 texdata+offset
2110 else {
2111 glTexImage2D (TEXT_TYPE,
2113 state.texiform,
2114 tile->w,
2115 slice->h,
2117 state.texform,
2118 state.texty,
2119 texdata+offset
2122 if (tile->pbo) {
2123 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2128 void ml_begintiles (void);
2129 void ml_begintiles (void)
2131 glEnable (TEXT_TYPE);
2132 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2133 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2136 void ml_endtiles (void);
2137 void ml_endtiles (void)
2139 glDisable (TEXT_TYPE);
2142 void ml_drawtile (value args_v, value ptr_v);
2143 void ml_drawtile (value args_v, value ptr_v)
2145 CAMLparam2 (args_v, ptr_v);
2146 int dispx = Int_val (Field (args_v, 0));
2147 int dispy = Int_val (Field (args_v, 1));
2148 int dispw = Int_val (Field (args_v, 2));
2149 int disph = Int_val (Field (args_v, 3));
2150 int tilex = Int_val (Field (args_v, 4));
2151 int tiley = Int_val (Field (args_v, 5));
2152 char *s = String_val (ptr_v);
2153 struct tile *tile = parse_pointer (__func__, s);
2154 int slicey, firstslice;
2155 struct slice *slice;
2156 GLfloat *texcoords = state.texcoords;
2157 GLfloat *vertices = state.vertices;
2159 firstslice = tiley / tile->sliceheight;
2160 slice = &tile->slices[firstslice];
2161 slicey = tiley % tile->sliceheight;
2163 while (disph > 0) {
2164 int dh;
2166 dh = slice->h - slicey;
2167 dh = fz_mini (disph, dh);
2168 uploadslice (tile, slice);
2170 texcoords[0] = tilex; texcoords[1] = slicey;
2171 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2172 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2173 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2175 vertices[0] = dispx; vertices[1] = dispy;
2176 vertices[2] = dispx+dispw; vertices[3] = dispy;
2177 vertices[4] = dispx; vertices[5] = dispy+dh;
2178 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2180 #if TEXT_TYPE == GL_TEXTURE_2D
2181 for (int i = 0; i < 8; ++i) {
2182 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2184 #endif
2186 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2187 dispy += dh;
2188 disph -= dh;
2189 slice++;
2190 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2191 slicey = 0;
2193 CAMLreturn0;
2196 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2198 fz_matrix ctm;
2199 fz_point p1, p2, p3, p4;
2200 GLfloat *vertices = state.vertices;
2202 xoff -= state.pagedims[page->pdimno].bounds.x0;
2203 yoff -= state.pagedims[page->pdimno].bounds.y0;
2204 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2206 glEnable (GL_BLEND);
2207 glVertexPointer (2, GL_FLOAT, 0, vertices);
2209 glColor4d (
2210 Double_array_field (rects_v, 0),
2211 Double_array_field (rects_v, 1),
2212 Double_array_field (rects_v, 2),
2213 Double_array_field (rects_v, 3)
2215 p1.x = (float) Double_array_field (rects_v, 4);
2216 p1.y = (float) Double_array_field (rects_v, 5);
2218 p2.x = (float) Double_array_field (rects_v, 6);
2219 p2.y = p1.y;
2221 p3.x = p2.x;
2222 p3.y = (float) Double_array_field (rects_v, 7);
2224 p4.x = p1.x;
2225 p4.y = p3.y;
2226 solidrect (ctm, p1, p2, p3, p4, vertices);
2227 glDisable (GL_BLEND);
2230 value ml_postprocess (value ptr_v, value hlinks_v,
2231 value xoff_v, value yoff_v,
2232 value li_v);
2233 value ml_postprocess (value ptr_v, value hlinks_v,
2234 value xoff_v, value yoff_v,
2235 value li_v)
2237 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2238 int xoff = Int_val (xoff_v);
2239 int yoff = Int_val (yoff_v);
2240 int noff = Int_val (Field (li_v, 0));
2241 char *targ = String_val (Field (li_v, 1));
2242 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2243 int hfsize = Int_val (Field (li_v, 2));
2244 char *s = String_val (ptr_v);
2245 int hlmask = Int_val (hlinks_v);
2246 struct page *page = parse_pointer (__func__, s);
2248 if (!page->fzpage) {
2249 /* deal with loadpage failed pages */
2250 goto done;
2253 if (trylock (__func__)) {
2254 noff = -1;
2255 goto done;
2258 ensureannots (page);
2259 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2260 if (hlmask & 2) {
2261 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2262 noff = page->slinkcount;
2264 if (page->tgen == state.gen) {
2265 showsel (page, xoff, yoff);
2267 unlock (__func__);
2269 done:
2270 CAMLreturn (Val_int (noff));
2273 void ml_drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v);
2274 void ml_drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v)
2276 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2277 int xoff = Int_val (xoff_v);
2278 int yoff = Int_val (yoff_v);
2279 char *s = String_val (ptr_v);
2280 struct page *page = parse_pointer (__func__, s);
2282 drawprect (page, xoff, yoff, rects_v);
2283 CAMLreturn0;
2286 static struct annot *getannot (struct page *page, int x, int y)
2288 fz_point p;
2289 fz_matrix ctm;
2290 const fz_matrix *tctm;
2291 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2293 if (!page->annots) return NULL;
2295 if (pdf) {
2296 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2297 tctm = &state.pagedims[page->pdimno].tctm;
2299 else {
2300 tctm = &fz_identity;
2303 p.x = x;
2304 p.y = y;
2306 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2307 ctm = fz_invert_matrix (ctm);
2308 p = fz_transform_point (p, ctm);
2310 if (pdf) {
2311 for (int i = 0; i < page->annotcount; ++i) {
2312 struct annot *a = &page->annots[i];
2313 fz_rect rect;
2315 rect = pdf_bound_annot (state.ctx, a->annot);
2316 if (p.x >= rect.x0 && p.x <= rect.x1) {
2317 if (p.y >= rect.y0 && p.y <= rect.y1)
2318 return a;
2322 return NULL;
2325 static fz_link *getlink (struct page *page, int x, int y)
2327 fz_point p;
2328 fz_link *link;
2330 ensureslinks (page);
2332 p.x = x;
2333 p.y = y;
2335 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2337 for (link = page->links; link; link = link->next) {
2338 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2339 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2340 return link;
2344 return NULL;
2347 static void ensuretext (struct page *page)
2349 if (state.gen != page->tgen) {
2350 droptext (page);
2351 page->tgen = state.gen;
2353 if (!page->text) {
2354 fz_device *tdev;
2356 page->text = fz_new_stext_page (state.ctx,
2357 state.pagedims[page->pdimno].mediabox);
2358 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2359 fz_run_display_list (state.ctx, page->dlist,
2360 tdev, pagectm (page), fz_infinite_rect, NULL);
2361 fz_close_device (state.ctx, tdev);
2362 fz_drop_device (state.ctx, tdev);
2366 value ml_find_page_with_links (value start_page_v, value dir_v);
2367 value ml_find_page_with_links (value start_page_v, value dir_v)
2369 CAMLparam2 (start_page_v, dir_v);
2370 CAMLlocal1 (ret_v);
2371 int i, dir = Int_val (dir_v);
2372 int start_page = Int_val (start_page_v);
2373 int end_page = dir > 0 ? state.pagecount : -1;
2374 pdf_document *pdf;
2376 fz_var (end_page);
2377 ret_v = Val_int (0);
2378 lock (__func__);
2379 pdf = pdf_specifics (state.ctx, state.doc);
2380 for (i = start_page + dir; i != end_page; i += dir) {
2381 int found;
2383 fz_var (found);
2384 if (pdf) {
2385 pdf_page *page = NULL;
2387 fz_var (page);
2388 fz_try (state.ctx) {
2389 page = pdf_load_page (state.ctx, pdf, i);
2390 found = !!page->links || !!page->annots;
2392 fz_catch (state.ctx) {
2393 found = 0;
2395 if (page) {
2396 fz_drop_page (state.ctx, &page->super);
2399 else {
2400 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2401 fz_link *link = fz_load_links (state.ctx, page);
2402 found = !!link;
2403 fz_drop_link (state.ctx, link);
2404 fz_drop_page (state.ctx, page);
2407 if (found) {
2408 ret_v = caml_alloc_small (1, 1);
2409 Field (ret_v, 0) = Val_int (i);
2410 goto unlock;
2413 unlock:
2414 unlock (__func__);
2415 CAMLreturn (ret_v);
2418 enum { dir_first, dir_last };
2419 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2421 value ml_findlink (value ptr_v, value dir_v);
2422 value ml_findlink (value ptr_v, value dir_v)
2424 CAMLparam2 (ptr_v, dir_v);
2425 CAMLlocal2 (ret_v, pos_v);
2426 struct page *page;
2427 int dirtag, i, slinkindex;
2428 struct slink *found = NULL ,*slink;
2429 char *s = String_val (ptr_v);
2431 page = parse_pointer (__func__, s);
2432 ret_v = Val_int (0);
2433 lock (__func__);
2434 ensureslinks (page);
2436 if (Is_block (dir_v)) {
2437 dirtag = Tag_val (dir_v);
2438 switch (dirtag) {
2439 case dir_first_visible:
2441 int x0, y0, dir, first_index, last_index;
2443 pos_v = Field (dir_v, 0);
2444 x0 = Int_val (Field (pos_v, 0));
2445 y0 = Int_val (Field (pos_v, 1));
2446 dir = Int_val (Field (pos_v, 2));
2448 if (dir >= 0) {
2449 dir = 1;
2450 first_index = 0;
2451 last_index = page->slinkcount;
2453 else {
2454 first_index = page->slinkcount - 1;
2455 last_index = -1;
2458 for (i = first_index; i != last_index; i += dir) {
2459 slink = &page->slinks[i];
2460 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2461 found = slink;
2462 break;
2466 break;
2468 case dir_left:
2469 slinkindex = Int_val (Field (dir_v, 0));
2470 found = &page->slinks[slinkindex];
2471 for (i = slinkindex - 1; i >= 0; --i) {
2472 slink = &page->slinks[i];
2473 if (slink->bbox.x0 < found->bbox.x0) {
2474 found = slink;
2475 break;
2478 break;
2480 case dir_right:
2481 slinkindex = Int_val (Field (dir_v, 0));
2482 found = &page->slinks[slinkindex];
2483 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2484 slink = &page->slinks[i];
2485 if (slink->bbox.x0 > found->bbox.x0) {
2486 found = slink;
2487 break;
2490 break;
2492 case dir_down:
2493 slinkindex = Int_val (Field (dir_v, 0));
2494 found = &page->slinks[slinkindex];
2495 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2496 slink = &page->slinks[i];
2497 if (slink->bbox.y0 >= found->bbox.y0) {
2498 found = slink;
2499 break;
2502 break;
2504 case dir_up:
2505 slinkindex = Int_val (Field (dir_v, 0));
2506 found = &page->slinks[slinkindex];
2507 for (i = slinkindex - 1; i >= 0; --i) {
2508 slink = &page->slinks[i];
2509 if (slink->bbox.y0 <= found->bbox.y0) {
2510 found = slink;
2511 break;
2514 break;
2517 else {
2518 dirtag = Int_val (dir_v);
2519 switch (dirtag) {
2520 case dir_first:
2521 found = page->slinks;
2522 break;
2524 case dir_last:
2525 if (page->slinks) {
2526 found = page->slinks + (page->slinkcount - 1);
2528 break;
2531 if (found) {
2532 ret_v = caml_alloc_small (2, 1);
2533 Field (ret_v, 0) = Val_int (found - page->slinks);
2536 unlock (__func__);
2537 CAMLreturn (ret_v);
2540 enum { uuri, utext, uannot };
2542 value ml_getlink (value ptr_v, value n_v);
2543 value ml_getlink (value ptr_v, value n_v)
2545 CAMLparam2 (ptr_v, n_v);
2546 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2547 fz_link *link;
2548 struct page *page;
2549 char *s = String_val (ptr_v);
2550 struct slink *slink;
2552 ret_v = Val_int (0);
2553 page = parse_pointer (__func__, s);
2555 lock (__func__);
2556 ensureslinks (page);
2557 slink = &page->slinks[Int_val (n_v)];
2558 if (slink->tag == SLINK) {
2559 link = slink->u.link;
2560 str_v = caml_copy_string (link->uri);
2561 ret_v = caml_alloc_small (1, uuri);
2562 Field (ret_v, 0) = str_v;
2564 else {
2565 ret_v = caml_alloc_small (1, uannot);
2566 tup_v = caml_alloc_tuple (2);
2567 Field (ret_v, 0) = tup_v;
2568 Field (tup_v, 0) = ptr_v;
2569 Field (tup_v, 1) = n_v;
2571 unlock (__func__);
2573 CAMLreturn (ret_v);
2576 value ml_getannotcontents (value ptr_v, value n_v);
2577 value ml_getannotcontents (value ptr_v, value n_v)
2579 CAMLparam2 (ptr_v, n_v);
2580 CAMLlocal1 (ret_v);
2581 pdf_document *pdf;
2582 const char *contents = "";
2584 lock (__func__);
2585 pdf = pdf_specifics (state.ctx, state.doc);
2586 if (pdf) {
2587 char *s = String_val (ptr_v);
2588 struct page *page;
2589 struct slink *slink;
2591 page = parse_pointer (__func__, s);
2592 slink = &page->slinks[Int_val (n_v)];
2593 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2595 unlock (__func__);
2596 ret_v = caml_copy_string (contents);
2597 CAMLreturn (ret_v);
2600 value ml_getlinkcount (value ptr_v);
2601 value ml_getlinkcount (value ptr_v)
2603 CAMLparam1 (ptr_v);
2604 struct page *page;
2605 char *s = String_val (ptr_v);
2607 page = parse_pointer (__func__, s);
2608 CAMLreturn (Val_int (page->slinkcount));
2611 value ml_getlinkrect (value ptr_v, value n_v);
2612 value ml_getlinkrect (value ptr_v, value n_v)
2614 CAMLparam2 (ptr_v, n_v);
2615 CAMLlocal1 (ret_v);
2616 struct page *page;
2617 struct slink *slink;
2618 char *s = String_val (ptr_v);
2620 page = parse_pointer (__func__, s);
2621 ret_v = caml_alloc_tuple (4);
2622 lock (__func__);
2623 ensureslinks (page);
2625 slink = &page->slinks[Int_val (n_v)];
2626 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2627 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2628 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2629 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2630 unlock (__func__);
2631 CAMLreturn (ret_v);
2634 value ml_whatsunder (value ptr_v, value x_v, value y_v);
2635 value ml_whatsunder (value ptr_v, value x_v, value y_v)
2637 CAMLparam3 (ptr_v, x_v, y_v);
2638 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2639 fz_link *link;
2640 struct annot *annot;
2641 struct page *page;
2642 char *ptr = String_val (ptr_v);
2643 int x = Int_val (x_v), y = Int_val (y_v);
2644 struct pagedim *pdim;
2646 ret_v = Val_int (0);
2647 if (trylock (__func__)) {
2648 goto done;
2651 page = parse_pointer (__func__, ptr);
2652 pdim = &state.pagedims[page->pdimno];
2653 x += pdim->bounds.x0;
2654 y += pdim->bounds.y0;
2657 annot = getannot (page, x, y);
2658 if (annot) {
2659 int i, n = -1;
2661 ensureslinks (page);
2662 for (i = 0; i < page->slinkcount; ++i) {
2663 if (page->slinks[i].tag == SANNOT
2664 && page->slinks[i].u.annot == annot->annot) {
2665 n = i;
2666 break;
2669 ret_v = caml_alloc_small (1, uannot);
2670 tup_v = caml_alloc_tuple (2);
2671 Field (ret_v, 0) = tup_v;
2672 Field (tup_v, 0) = ptr_v;
2673 Field (tup_v, 1) = Val_int (n);
2674 goto unlock;
2678 link = getlink (page, x, y);
2679 if (link) {
2680 str_v = caml_copy_string (link->uri);
2681 ret_v = caml_alloc_small (1, uuri);
2682 Field (ret_v, 0) = str_v;
2684 else {
2685 fz_rect *b;
2686 fz_stext_block *block;
2688 ensuretext (page);
2690 for (block = page->text->first_block; block; block = block->next) {
2691 fz_stext_line *line;
2693 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2694 b = &block->bbox;
2695 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2696 continue;
2698 for (line = block->u.t.first_line; line; line = line->next) {
2699 fz_stext_char *ch;
2701 b = &line->bbox;
2702 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2703 continue;
2705 for (ch = line->first_char; ch; ch = ch->next) {
2706 fz_quad *q = &ch->quad;
2708 if (x >= q->ul.x && x <= q->ur.x
2709 && y >= q->ul.y && y <= q->ll.y) {
2710 const char *n2 = fz_font_name (state.ctx, ch->font);
2711 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2712 ch->font);
2714 if (!n2) n2 = "<unknown font>";
2716 if (face && face->family_name) {
2717 char *s;
2718 char *n1 = face->family_name;
2719 size_t l1 = strlen (n1);
2720 size_t l2 = strlen (n2);
2722 if (l1 != l2 || memcmp (n1, n2, l1)) {
2723 s = malloc (l1 + l2 + 2);
2724 if (s) {
2725 memcpy (s, n2, l2);
2726 s[l2] = '=';
2727 memcpy (s + l2 + 1, n1, l1 + 1);
2728 str_v = caml_copy_string (s);
2729 free (s);
2733 if (str_v == Val_unit) {
2734 str_v = caml_copy_string (n2);
2736 ret_v = caml_alloc_small (1, utext);
2737 Field (ret_v, 0) = str_v;
2738 goto unlock;
2744 unlock:
2745 unlock (__func__);
2747 done:
2748 CAMLreturn (ret_v);
2751 enum { mark_page, mark_block, mark_line, mark_word };
2753 void ml_clearmark (value ptr_v);
2754 void ml_clearmark (value ptr_v)
2756 CAMLparam1 (ptr_v);
2757 char *s = String_val (ptr_v);
2758 struct page *page;
2760 if (trylock (__func__)) {
2761 goto done;
2764 page = parse_pointer (__func__, s);
2765 page->fmark = NULL;
2766 page->lmark = NULL;
2768 unlock (__func__);
2769 done:
2770 CAMLreturn0;
2773 static int uninteresting (int c)
2775 return isspace (c) || ispunct (c);
2778 value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v);
2779 value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2781 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2782 CAMLlocal1 (ret_v);
2783 fz_rect *b;
2784 struct page *page;
2785 fz_stext_line *line;
2786 fz_stext_block *block;
2787 struct pagedim *pdim;
2788 int mark = Int_val (mark_v);
2789 char *s = String_val (ptr_v);
2790 int x = Int_val (x_v), y = Int_val (y_v);
2792 ret_v = Val_bool (0);
2793 if (trylock (__func__)) {
2794 goto done;
2797 page = parse_pointer (__func__, s);
2798 pdim = &state.pagedims[page->pdimno];
2800 ensuretext (page);
2802 if (mark == mark_page) {
2803 page->fmark = page->text->first_block->u.t.first_line->first_char;
2804 page->lmark = page->text->last_block->u.t.last_line->last_char;
2805 ret_v = Val_bool (1);
2806 goto unlock;
2809 x += pdim->bounds.x0;
2810 y += pdim->bounds.y0;
2812 for (block = page->text->first_block; block; block = block->next) {
2813 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2814 b = &block->bbox;
2815 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2816 continue;
2818 if (mark == mark_block) {
2819 page->fmark = block->u.t.first_line->first_char;
2820 page->lmark = block->u.t.last_line->last_char;
2821 ret_v = Val_bool (1);
2822 goto unlock;
2825 for (line = block->u.t.first_line; line; line = line->next) {
2826 fz_stext_char *ch;
2828 b = &line->bbox;
2829 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2830 continue;
2832 if (mark == mark_line) {
2833 page->fmark = line->first_char;
2834 page->lmark = line->last_char;
2835 ret_v = Val_bool (1);
2836 goto unlock;
2839 for (ch = line->first_char; ch; ch = ch->next) {
2840 fz_stext_char *ch2, *first = NULL, *last = NULL;
2841 fz_quad *q = &ch->quad;
2842 if (x >= q->ul.x && x <= q->ur.x
2843 && y >= q->ul.y && y <= q->ll.y) {
2844 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2845 if (uninteresting (ch2->c)) first = NULL;
2846 else if (!first) first = ch2;
2848 for (ch2 = ch; ch2; ch2 = ch2->next) {
2849 if (uninteresting (ch2->c)) break;
2850 last = ch2;
2853 page->fmark = first;
2854 page->lmark = last;
2855 ret_v = Val_bool (1);
2856 goto unlock;
2861 unlock:
2862 if (!Bool_val (ret_v)) {
2863 page->fmark = NULL;
2864 page->lmark = NULL;
2866 unlock (__func__);
2868 done:
2869 CAMLreturn (ret_v);
2872 value ml_rectofblock (value ptr_v, value x_v, value y_v);
2873 value ml_rectofblock (value ptr_v, value x_v, value y_v)
2875 CAMLparam3 (ptr_v, x_v, y_v);
2876 CAMLlocal2 (ret_v, res_v);
2877 fz_rect *b = NULL;
2878 struct page *page;
2879 struct pagedim *pdim;
2880 fz_stext_block *block;
2881 char *s = String_val (ptr_v);
2882 int x = Int_val (x_v), y = Int_val (y_v);
2884 ret_v = Val_int (0);
2885 if (trylock (__func__)) {
2886 goto done;
2889 page = parse_pointer (__func__, s);
2890 pdim = &state.pagedims[page->pdimno];
2891 x += pdim->bounds.x0;
2892 y += pdim->bounds.y0;
2894 ensuretext (page);
2896 for (block = page->text->first_block; block; block = block->next) {
2897 switch (block->type) {
2898 case FZ_STEXT_BLOCK_TEXT:
2899 b = &block->bbox;
2900 break;
2902 case FZ_STEXT_BLOCK_IMAGE:
2903 b = &block->bbox;
2904 break;
2906 default:
2907 continue;
2910 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2911 break;
2912 b = NULL;
2914 if (b) {
2915 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2916 ret_v = caml_alloc_small (1, 1);
2917 Store_double_field (res_v, 0, (double) b->x0);
2918 Store_double_field (res_v, 1, (double) b->x1);
2919 Store_double_field (res_v, 2, (double) b->y0);
2920 Store_double_field (res_v, 3, (double) b->y1);
2921 Field (ret_v, 0) = res_v;
2923 unlock (__func__);
2925 done:
2926 CAMLreturn (ret_v);
2929 void ml_seltext (value ptr_v, value rect_v);
2930 void ml_seltext (value ptr_v, value rect_v)
2932 CAMLparam2 (ptr_v, rect_v);
2933 struct page *page;
2934 struct pagedim *pdim;
2935 char *s = String_val (ptr_v);
2936 int x0, x1, y0, y1;
2937 fz_stext_char *ch;
2938 fz_stext_line *line;
2939 fz_stext_block *block;
2940 fz_stext_char *fc, *lc;
2942 if (trylock (__func__)) {
2943 goto done;
2946 page = parse_pointer (__func__, s);
2947 ensuretext (page);
2949 pdim = &state.pagedims[page->pdimno];
2950 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2951 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2952 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2953 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2955 if (y0 > y1) {
2956 int t = y0;
2957 y0 = y1;
2958 y1 = t;
2959 x0 = x1;
2960 x1 = t;
2963 fc = page->fmark;
2964 lc = page->lmark;
2966 for (block = page->text->first_block; block; block = block->next) {
2967 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2968 for (line = block->u.t.first_line; line; line = line->next) {
2969 for (ch = line->first_char; ch; ch = ch->next) {
2970 fz_quad q = ch->quad;
2971 if (x0 >= q.ul.x && x0 <= q.ur.x
2972 && y0 >= q.ul.y && y0 <= q.ll.y) {
2973 fc = ch;
2975 if (x1 >= q.ul.x && x1 <= q.ur.x
2976 && y1 >= q.ul.y && y1 <= q.ll.y) {
2977 lc = ch;
2982 if (x1 < x0 && fc == lc) {
2983 fz_stext_char *t;
2985 t = fc;
2986 fc = lc;
2987 lc = t;
2990 page->fmark = fc;
2991 page->lmark = lc;
2993 unlock (__func__);
2995 done:
2996 CAMLreturn0;
2999 static int pipechar (FILE *f, fz_stext_char *ch)
3001 char buf[4];
3002 int len;
3003 size_t ret;
3005 len = fz_runetochar (buf, ch->c);
3006 ret = fwrite (buf, len, 1, f);
3007 if (ret != 1) {
3008 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3009 len, ret, errno, strerror (errno));
3010 return -1;
3012 return 0;
3015 value ml_spawn (value command_v, value fds_v);
3016 value ml_spawn (value command_v, value fds_v)
3018 CAMLparam2 (command_v, fds_v);
3019 CAMLlocal2 (l_v, tup_v);
3020 int ret, ret1;
3021 pid_t pid = (pid_t) -1;
3022 char *msg = NULL;
3023 value earg_v = Nothing;
3024 posix_spawnattr_t attr;
3025 posix_spawn_file_actions_t fa;
3026 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3028 argv[2] = String_val (command_v);
3030 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3031 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3034 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3035 msg = "posix_spawnattr_init";
3036 goto fail1;
3039 #ifdef POSIX_SPAWN_USEVFORK
3040 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3041 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3042 goto fail;
3044 #endif
3046 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3047 int fd1, fd2;
3049 tup_v = Field (l_v, 0);
3050 fd1 = Int_val (Field (tup_v, 0));
3051 fd2 = Int_val (Field (tup_v, 1));
3052 if (fd2 < 0) {
3053 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3054 msg = "posix_spawn_file_actions_addclose";
3055 earg_v = tup_v;
3056 goto fail;
3059 else {
3060 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3061 msg = "posix_spawn_file_actions_adddup2";
3062 earg_v = tup_v;
3063 goto fail;
3068 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3069 msg = "posix_spawn";
3070 goto fail;
3073 fail:
3074 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3075 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3078 fail1:
3079 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3080 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3081 ret1, strerror (ret1));
3084 if (msg)
3085 unix_error (ret, msg, earg_v);
3087 CAMLreturn (Val_int (pid));
3090 value ml_hassel (value ptr_v);
3091 value ml_hassel (value ptr_v)
3093 CAMLparam1 (ptr_v);
3094 CAMLlocal1 (ret_v);
3095 struct page *page;
3096 char *s = String_val (ptr_v);
3098 ret_v = Val_bool (0);
3099 if (trylock (__func__)) {
3100 goto done;
3103 page = parse_pointer (__func__, s);
3104 ret_v = Val_bool (page->fmark && page->lmark);
3105 unlock (__func__);
3106 done:
3107 CAMLreturn (ret_v);
3110 void ml_copysel (value fd_v, value ptr_v);
3111 void ml_copysel (value fd_v, value ptr_v)
3113 CAMLparam2 (fd_v, ptr_v);
3114 FILE *f;
3115 int seen = 0;
3116 struct page *page;
3117 fz_stext_line *line;
3118 fz_stext_block *block;
3119 int fd = Int_val (fd_v);
3120 char *s = String_val (ptr_v);
3122 if (trylock (__func__)) {
3123 goto done;
3126 page = parse_pointer (__func__, s);
3128 if (!page->fmark || !page->lmark) {
3129 printd ("emsg nothing to copy on page %d", page->pageno);
3130 goto unlock;
3133 f = fdopen (fd, "w");
3134 if (!f) {
3135 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3136 fd, errno, strerror (errno));
3137 f = stdout;
3140 for (block = page->text->first_block; block; block = block->next) {
3141 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3142 for (line = block->u.t.first_line; line; line = line->next) {
3143 fz_stext_char *ch;
3144 for (ch = line->first_char; ch; ch = ch->next) {
3145 if (seen || ch == page->fmark) {
3146 do {
3147 pipechar (f, ch);
3148 if (ch == page->lmark) goto close;
3149 } while ((ch = ch->next));
3150 seen = 1;
3151 break;
3154 if (seen) fputc ('\n', f);
3157 close:
3158 if (f != stdout) {
3159 int ret = fclose (f);
3160 fd = -1;
3161 if (ret == -1) {
3162 if (errno != ECHILD) {
3163 printd ("emsg failed to close sel pipe: %d:%s",
3164 errno, strerror (errno));
3168 unlock:
3169 unlock (__func__);
3171 done:
3172 if (fd >= 0) {
3173 if (close (fd)) {
3174 printd ("emsg failed to close sel pipe: %d:%s",
3175 errno, strerror (errno));
3178 CAMLreturn0;
3181 value ml_getpdimrect (value pagedimno_v);
3182 value ml_getpdimrect (value pagedimno_v)
3184 CAMLparam1 (pagedimno_v);
3185 CAMLlocal1 (ret_v);
3186 int pagedimno = Int_val (pagedimno_v);
3187 fz_rect box;
3189 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3190 if (trylock (__func__)) {
3191 box = fz_empty_rect;
3193 else {
3194 box = state.pagedims[pagedimno].mediabox;
3195 unlock (__func__);
3198 Store_double_field (ret_v, 0, (double) box.x0);
3199 Store_double_field (ret_v, 1, (double) box.x1);
3200 Store_double_field (ret_v, 2, (double) box.y0);
3201 Store_double_field (ret_v, 3, (double) box.y1);
3203 CAMLreturn (ret_v);
3206 value ml_zoom_for_height (value winw_v, value winh_v,
3207 value dw_v, value cols_v);
3208 value ml_zoom_for_height (value winw_v, value winh_v,
3209 value dw_v, value cols_v)
3211 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3212 CAMLlocal1 (ret_v);
3213 int i;
3214 float zoom = -1.;
3215 float maxh = 0.0;
3216 struct pagedim *p;
3217 float winw = Int_val (winw_v);
3218 float winh = Int_val (winh_v);
3219 float dw = Int_val (dw_v);
3220 float cols = Int_val (cols_v);
3221 float pw = 1.0, ph = 1.0;
3223 if (trylock (__func__)) {
3224 goto done;
3227 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3228 float w = p->pagebox.x1 / cols;
3229 float h = p->pagebox.y1;
3230 if (h > maxh) {
3231 maxh = h;
3232 ph = h;
3233 if (state.fitmodel != FitProportional) pw = w;
3235 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3238 zoom = (((winh / ph) * pw) + dw) / winw;
3239 unlock (__func__);
3240 done:
3241 ret_v = caml_copy_double ((double) zoom);
3242 CAMLreturn (ret_v);
3245 value ml_getmaxw (value unit_v);
3246 value ml_getmaxw (value unit_v)
3248 CAMLparam1 (unit_v);
3249 CAMLlocal1 (ret_v);
3250 int i;
3251 float maxw = -1.;
3252 struct pagedim *p;
3254 if (trylock (__func__)) {
3255 goto done;
3258 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3259 float w = p->pagebox.x1;
3260 maxw = fz_max (maxw, w);
3263 unlock (__func__);
3264 done:
3265 ret_v = caml_copy_double ((double) maxw);
3266 CAMLreturn (ret_v);
3269 value ml_draw_string (value pt_v, value x_v,
3270 value y_v, value string_v);
3271 value ml_draw_string (value pt_v, value x_v,
3272 value y_v, value string_v)
3274 CAMLparam4 (pt_v, x_v, y_v, string_v);
3275 CAMLlocal1 (ret_v);
3276 int pt = Int_val(pt_v);
3277 int x = Int_val (x_v);
3278 int y = Int_val (y_v);
3279 float w;
3281 w = draw_string (state.face, pt, x, y, String_val (string_v));
3282 ret_v = caml_copy_double (w);
3283 CAMLreturn (ret_v);
3286 value ml_measure_string (value pt_v, value string_v);
3287 value ml_measure_string (value pt_v, value string_v)
3289 CAMLparam2 (pt_v, string_v);
3290 CAMLlocal1 (ret_v);
3291 int pt = Int_val (pt_v);
3292 double w;
3294 w = (double) measure_string (state.face, pt, String_val (string_v));
3295 ret_v = caml_copy_double (w);
3296 CAMLreturn (ret_v);
3299 value ml_getpagebox (value opaque_v);
3300 value ml_getpagebox (value opaque_v)
3302 CAMLparam1 (opaque_v);
3303 CAMLlocal1 (ret_v);
3304 fz_rect rect;
3305 fz_irect bbox;
3306 fz_device *dev;
3307 char *s = String_val (opaque_v);
3308 struct page *page = parse_pointer (__func__, s);
3310 ret_v = caml_alloc_tuple (4);
3311 dev = fz_new_bbox_device (state.ctx, &rect);
3313 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3315 fz_close_device (state.ctx, dev);
3316 fz_drop_device (state.ctx, dev);
3317 bbox = fz_round_rect (rect);
3318 Field (ret_v, 0) = Val_int (bbox.x0);
3319 Field (ret_v, 1) = Val_int (bbox.y0);
3320 Field (ret_v, 2) = Val_int (bbox.x1);
3321 Field (ret_v, 3) = Val_int (bbox.y1);
3323 CAMLreturn (ret_v);
3326 void ml_setaalevel (value level_v);
3327 void ml_setaalevel (value level_v)
3329 CAMLparam1 (level_v);
3331 state.aalevel = Int_val (level_v);
3332 CAMLreturn0;
3335 void ml_setpapercolor (value rgba_v);
3336 void ml_setpapercolor (value rgba_v)
3338 CAMLparam1 (rgba_v);
3340 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3341 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3342 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3343 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3344 CAMLreturn0;
3347 value ml_keysymtoutf8 (value keysym_v);
3348 #ifndef CIDER
3349 value ml_keysymtoutf8 (value keysym_v)
3351 CAMLparam1 (keysym_v);
3352 CAMLlocal1 (str_v);
3353 KeySym keysym = Int_val (keysym_v);
3354 Rune rune;
3355 extern long keysym2ucs (KeySym);
3356 int len;
3357 char buf[5];
3359 rune = (Rune) keysym2ucs (keysym);
3360 len = fz_runetochar (buf, rune);
3361 buf[len] = 0;
3362 str_v = caml_copy_string (buf);
3363 CAMLreturn (str_v);
3365 #else
3366 value ml_keysymtoutf8 (value keysym_v)
3368 CAMLparam1 (keysym_v);
3369 CAMLlocal1 (str_v);
3370 long ucs = Long_val (keysym_v);
3371 int len;
3372 char buf[5];
3374 len = fz_runetochar (buf, (int) ucs);
3375 buf[len] = 0;
3376 str_v = caml_copy_string (buf);
3377 CAMLreturn (str_v);
3379 #endif
3381 enum { piunknown, pilinux, pimacos, pibsd };
3383 value ml_platform (value unit_v);
3384 value ml_platform (value unit_v)
3386 CAMLparam1 (unit_v);
3387 CAMLlocal2 (tup_v, arr_v);
3388 int platid = piunknown;
3389 struct utsname buf;
3391 #if defined __linux__
3392 platid = pilinux;
3393 #elif defined __DragonFly__ || defined __FreeBSD__
3394 || defined __OpenBSD__ || defined __NetBSD__
3395 platid = pibsd;
3396 #elif defined __APPLE__
3397 platid = pimacos;
3398 #endif
3399 if (uname (&buf)) err (1, "uname");
3401 tup_v = caml_alloc_tuple (2);
3403 char const *sar[] = {
3404 buf.sysname,
3405 buf.release,
3406 buf.version,
3407 buf.machine,
3408 NULL
3410 arr_v = caml_copy_string_array (sar);
3412 Field (tup_v, 0) = Val_int (platid);
3413 Field (tup_v, 1) = arr_v;
3414 CAMLreturn (tup_v);
3417 void ml_cloexec (value fd_v);
3418 void ml_cloexec (value fd_v)
3420 CAMLparam1 (fd_v);
3421 int fd = Int_val (fd_v);
3423 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3424 uerror ("fcntl", Nothing);
3426 CAMLreturn0;
3429 value ml_getpbo (value w_v, value h_v, value cs_v);
3430 value ml_getpbo (value w_v, value h_v, value cs_v)
3432 CAMLparam2 (w_v, h_v);
3433 CAMLlocal1 (ret_v);
3434 struct bo *pbo;
3435 int w = Int_val (w_v);
3436 int h = Int_val (h_v);
3437 int cs = Int_val (cs_v);
3439 if (state.bo_usable) {
3440 pbo = calloc (sizeof (*pbo), 1);
3441 if (!pbo) {
3442 err (1, "calloc pbo");
3445 switch (cs) {
3446 case 0:
3447 case 1:
3448 pbo->size = w*h*4;
3449 break;
3450 case 2:
3451 pbo->size = w*h*2;
3452 break;
3453 default:
3454 errx (1, "%s: invalid colorspace %d", __func__, cs);
3457 state.glGenBuffersARB (1, &pbo->id);
3458 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3459 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3460 NULL, GL_STREAM_DRAW);
3461 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3462 GL_READ_WRITE);
3463 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3464 if (!pbo->ptr) {
3465 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3466 state.glDeleteBuffersARB (1, &pbo->id);
3467 free (pbo);
3468 ret_v = caml_copy_string ("0");
3470 else {
3471 int res;
3472 char *s;
3474 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3475 if (res < 0) {
3476 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3478 s = malloc (res+1);
3479 if (!s) {
3480 err (1, "malloc %d bytes failed", res+1);
3482 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3483 if (res < 0) {
3484 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3486 ret_v = caml_copy_string (s);
3487 free (s);
3490 else {
3491 ret_v = caml_copy_string ("0");
3493 CAMLreturn (ret_v);
3496 void ml_freepbo (value s_v);
3497 void ml_freepbo (value s_v)
3499 CAMLparam1 (s_v);
3500 char *s = String_val (s_v);
3501 struct tile *tile = parse_pointer (__func__, s);
3503 if (tile->pbo) {
3504 state.glDeleteBuffersARB (1, &tile->pbo->id);
3505 tile->pbo->id = -1;
3506 tile->pbo->ptr = NULL;
3507 tile->pbo->size = -1;
3509 CAMLreturn0;
3512 void ml_unmappbo (value s_v);
3513 void ml_unmappbo (value s_v)
3515 CAMLparam1 (s_v);
3516 char *s = String_val (s_v);
3517 struct tile *tile = parse_pointer (__func__, s);
3519 if (tile->pbo) {
3520 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3521 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3522 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3524 tile->pbo->ptr = NULL;
3525 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3527 CAMLreturn0;
3530 static void setuppbo (void)
3532 extern void (*wsigladdr (const char *name)) (void);
3533 #pragma GCC diagnostic push
3534 #ifdef __clang__
3535 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3536 #endif
3537 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3538 state.bo_usable = GPA (glBindBufferARB)
3539 && GPA (glUnmapBufferARB)
3540 && GPA (glMapBufferARB)
3541 && GPA (glBufferDataARB)
3542 && GPA (glGenBuffersARB)
3543 && GPA (glDeleteBuffersARB);
3544 #undef GPA
3545 #pragma GCC diagnostic pop
3548 value ml_bo_usable (void);
3549 value ml_bo_usable (void)
3551 return Val_bool (state.bo_usable);
3554 value ml_unproject (value ptr_v, value x_v, value y_v);
3555 value ml_unproject (value ptr_v, value x_v, value y_v)
3557 CAMLparam3 (ptr_v, x_v, y_v);
3558 CAMLlocal2 (ret_v, tup_v);
3559 struct page *page;
3560 char *s = String_val (ptr_v);
3561 int x = Int_val (x_v), y = Int_val (y_v);
3562 struct pagedim *pdim;
3563 fz_point p;
3565 page = parse_pointer (__func__, s);
3566 pdim = &state.pagedims[page->pdimno];
3568 ret_v = Val_int (0);
3569 if (trylock (__func__)) {
3570 goto done;
3573 p.x = x + pdim->bounds.x0;
3574 p.y = y + pdim->bounds.y0;
3576 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3577 pdim->ctm)));
3579 tup_v = caml_alloc_tuple (2);
3580 ret_v = caml_alloc_small (1, 1);
3581 Field (tup_v, 0) = Val_int (p.x);
3582 Field (tup_v, 1) = Val_int (p.y);
3583 Field (ret_v, 0) = tup_v;
3585 unlock (__func__);
3586 done:
3587 CAMLreturn (ret_v);
3590 value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3591 value x_v, value y_v);
3592 value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3593 value x_v, value y_v)
3595 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3596 CAMLlocal1 (ret_v);
3597 struct page *page;
3598 char *s = String_val (ptr_v);
3599 int pageno = Int_val (pageno_v);
3600 int pdimno = Int_val (pdimno_v);
3601 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3602 struct pagedim *pdim;
3603 fz_point p;
3604 fz_matrix ctm;
3606 ret_v = Val_int (0);
3607 lock (__func__);
3609 if (!*s) {
3610 page = loadpage (pageno, pdimno);
3612 else {
3613 page = parse_pointer (__func__, s);
3615 pdim = &state.pagedims[pdimno];
3617 if (pdf_specifics (state.ctx, state.doc)) {
3618 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3619 ctm = state.pagedims[page->pdimno].tctm;
3621 else {
3622 ctm = fz_identity;
3624 p.x = x + pdim->bounds.x0;
3625 p.y = y + pdim->bounds.y0;
3627 ctm = fz_concat (pdim->tctm, pdim->ctm);
3628 p = fz_transform_point (p, ctm);
3630 ret_v = caml_alloc_tuple (2);
3631 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3632 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3634 if (!*s) {
3635 freepage (page);
3637 unlock (__func__);
3638 CAMLreturn (ret_v);
3641 void ml_addannot (value ptr_v, value x_v, value y_v, value contents_v);
3642 void ml_addannot (value ptr_v, value x_v, value y_v, value contents_v)
3644 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3645 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3647 if (pdf) {
3648 pdf_annot *annot;
3649 struct page *page;
3650 fz_rect r;
3651 char *s = String_val (ptr_v);
3653 page = parse_pointer (__func__, s);
3654 annot = pdf_create_annot (state.ctx,
3655 pdf_page_from_fz_page (state.ctx,
3656 page->fzpage),
3657 PDF_ANNOT_TEXT);
3658 r.x0 = Int_val (x_v) - 10;
3659 r.y0 = Int_val (y_v) - 10;
3660 r.x1 = r.x0 + 20;
3661 r.y1 = r.y0 + 20;
3662 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3663 pdf_set_annot_rect (state.ctx, annot, r);
3665 state.dirty = 1;
3667 CAMLreturn0;
3670 void ml_delannot (value ptr_v, value n_v);
3671 void ml_delannot (value ptr_v, value n_v)
3673 CAMLparam2 (ptr_v, n_v);
3674 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3676 if (pdf) {
3677 struct page *page;
3678 char *s = String_val (ptr_v);
3679 struct slink *slink;
3681 page = parse_pointer (__func__, s);
3682 slink = &page->slinks[Int_val (n_v)];
3683 pdf_delete_annot (state.ctx,
3684 pdf_page_from_fz_page (state.ctx, page->fzpage),
3685 (pdf_annot *) slink->u.annot);
3686 state.dirty = 1;
3688 CAMLreturn0;
3691 void ml_modannot (value ptr_v, value n_v, value str_v);
3692 void ml_modannot (value ptr_v, value n_v, value str_v)
3694 CAMLparam3 (ptr_v, n_v, str_v);
3695 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3697 if (pdf) {
3698 struct page *page;
3699 char *s = String_val (ptr_v);
3700 struct slink *slink;
3702 page = parse_pointer (__func__, s);
3703 slink = &page->slinks[Int_val (n_v)];
3704 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3705 String_val (str_v));
3706 state.dirty = 1;
3708 CAMLreturn0;
3711 value ml_hasunsavedchanges (void);
3712 value ml_hasunsavedchanges (void)
3714 return Val_bool (state.dirty);
3717 void ml_savedoc (value path_v);
3718 void ml_savedoc (value path_v)
3720 CAMLparam1 (path_v);
3721 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3723 if (pdf) {
3724 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3726 CAMLreturn0;
3729 static void makestippletex (void)
3731 const char pixels[] = "\xff\xff\0\0";
3732 glGenTextures (1, &state.stid);
3733 glBindTexture (GL_TEXTURE_1D, state.stid);
3734 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3735 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3736 glTexImage1D (
3737 GL_TEXTURE_1D,
3739 GL_ALPHA,
3742 GL_ALPHA,
3743 GL_UNSIGNED_BYTE,
3744 pixels
3748 value ml_fz_version (void);
3749 value ml_fz_version (void)
3751 return caml_copy_string (FZ_VERSION);
3754 value ml_llpp_version (void);
3755 value ml_llpp_version (void)
3757 extern char llpp_version[];
3758 return caml_copy_string (llpp_version);
3761 static void diag_callback (void *user, const char *message)
3763 printd ("emsg %s %s", (char *) user, message);
3766 void ml_init (value csock_v, value params_v);
3767 void ml_init (value csock_v, value params_v)
3769 CAMLparam2 (csock_v, params_v);
3770 CAMLlocal2 (trim_v, fuzz_v);
3771 int ret;
3772 int texcount;
3773 char *fontpath;
3774 int colorspace;
3775 int mustoresize;
3777 state.csock = Int_val (csock_v);
3778 state.rotate = Int_val (Field (params_v, 0));
3779 state.fitmodel = Int_val (Field (params_v, 1));
3780 trim_v = Field (params_v, 2);
3781 texcount = Int_val (Field (params_v, 3));
3782 state.sliceheight = Int_val (Field (params_v, 4));
3783 mustoresize = Int_val (Field (params_v, 5));
3784 colorspace = Int_val (Field (params_v, 6));
3785 fontpath = String_val (Field (params_v, 7));
3787 #ifdef CIDER
3788 state.utf8cs = 1;
3789 #else
3790 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3791 if (setlocale (LC_CTYPE, "")) {
3792 const char *cset = nl_langinfo (CODESET);
3793 state.utf8cs = !strcmp (cset, "UTF-8");
3795 else {
3796 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3798 #endif
3800 if (caml_string_length (Field (params_v, 8)) > 0) {
3801 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3803 if (!state.trimcachepath) {
3804 printd ("emsg failed to strdup trimcachepath: %d:%s",
3805 errno, strerror (errno));
3809 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3810 fz_register_document_handlers (state.ctx);
3811 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3812 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3814 state.trimmargins = Bool_val (Field (trim_v, 0));
3815 fuzz_v = Field (trim_v, 1);
3816 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3817 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3818 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3819 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3821 set_tex_params (colorspace);
3823 if (*fontpath) {
3824 state.face = load_font (fontpath);
3826 else {
3827 int len;
3828 const unsigned char *data;
3830 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3831 state.face = load_builtin_font (data, len);
3833 if (!state.face) _exit (1);
3835 realloctexts (texcount);
3836 setuppbo ();
3837 makestippletex ();
3839 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3840 if (ret) {
3841 errx (1, "pthread_create: %s", strerror (ret));
3844 CAMLreturn0;
3847 #if FIXME || !FIXME
3848 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3849 #endif