Cosmetics
[llpp.git] / link.c
blob960771cb9ee1f2fbe1dffa28ace0022d3b4e5ddf
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 { FZ_META_INFO_CREATOR, "Creator" },
403 { FZ_META_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;
644 fz_var (p);
645 fz_var (pdf);
646 fz_var (trimw);
647 fz_var (trimf);
648 fz_var (cxcount);
650 cxcount = state.pagecount;
651 if (state.trimmargins && state.trimcachepath) {
652 trimf = fopen (state.trimcachepath, "rb");
653 if (!trimf) {
654 trimf = fopen (state.trimcachepath, "wb");
655 trimw = 1;
657 pdf = NULL;
659 else {
660 pdf = pdf_specifics (ctx, state.doc);
661 pdf_obj *obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
662 "Root/Pages/MediaBox");
663 rootmediabox = pdf_to_rect (ctx, obj);
664 pdf_load_page_tree (ctx, pdf);
667 for (pageno = 0; pageno < cxcount; ++pageno) {
668 int rotate = 0;
669 fz_rect mediabox = fz_empty_rect;
671 fz_var (rotate);
672 if (pdf) {
673 pdf_obj *pageobj = NULL;
675 fz_var (pageobj);
676 if (pdf->rev_page_map) {
677 for (int i = 0; i < pdf->rev_page_count; ++i) {
678 if (pdf->rev_page_map[i].page == pageno) {
679 pageobj = pdf_get_xref_entry (
680 ctx, pdf, pdf->rev_page_map[i].object
681 )->obj;
682 break;
686 if (!pageobj) {
687 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
690 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
692 if (state.trimmargins) {
693 pdf_obj *obj;
694 pdf_page *page;
696 fz_try (ctx) {
697 page = pdf_load_page (ctx, pdf, pageno);
698 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
699 trim = state.trimanew || !obj;
700 if (trim) {
701 fz_rect rect;
702 fz_device *dev;
703 fz_matrix ctm, page_ctm;
705 dev = fz_new_bbox_device (ctx, &rect);
706 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
707 ctm = fz_invert_matrix (page_ctm);
708 pdf_run_page (ctx, page, dev, fz_identity, NULL);
709 fz_close_device (ctx, dev);
710 fz_drop_device (ctx, dev);
712 rect.x0 += state.trimfuzz.x0;
713 rect.x1 += state.trimfuzz.x1;
714 rect.y0 += state.trimfuzz.y0;
715 rect.y1 += state.trimfuzz.y1;
716 rect = fz_transform_rect (rect, ctm);
717 rect = fz_intersect_rect (rect, mediabox);
719 if (!fz_is_empty_rect (rect)) {
720 mediabox = rect;
723 obj = pdf_new_array (ctx, pdf, 4);
724 pdf_array_push_real (ctx, obj, mediabox.x0);
725 pdf_array_push_real (ctx, obj, mediabox.y0);
726 pdf_array_push_real (ctx, obj, mediabox.x1);
727 pdf_array_push_real (ctx, obj, mediabox.y1);
728 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
730 else {
731 mediabox.x0 = pdf_array_get_real (ctx, obj, 0);
732 mediabox.y0 = pdf_array_get_real (ctx, obj, 1);
733 mediabox.x1 = pdf_array_get_real (ctx, obj, 2);
734 mediabox.y1 = pdf_array_get_real (ctx, obj, 3);
737 fz_drop_page (ctx, &page->super);
738 show = (pageno + 1 == state.pagecount)
739 || (trim ? pageno % 5 == 0 : pageno % 20 == 0);
740 if (show) {
741 printd ("progress %f Trimming %d",
742 (double) (pageno + 1) / state.pagecount,
743 pageno + 1);
746 fz_catch (ctx) {
747 printd ("emsg failed to load page %d", pageno);
750 else {
751 int empty = 0;
752 fz_rect cropbox;
754 mediabox =
755 pdf_to_rect (ctx, pdf_dict_get_inheritable (
756 ctx,
757 pageobj,
758 PDF_NAME (MediaBox)
761 if (fz_is_empty_rect (mediabox)) {
762 mediabox.x0 = 0;
763 mediabox.y0 = 0;
764 mediabox.x1 = 612;
765 mediabox.y1 = 792;
766 empty = 1;
769 cropbox =
770 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
771 if (!fz_is_empty_rect (cropbox)) {
772 if (empty) {
773 mediabox = cropbox;
775 else {
776 mediabox = fz_intersect_rect (mediabox, cropbox);
779 else {
780 if (empty) {
781 if (fz_is_empty_rect (rootmediabox)) {
782 printd ("emsg cannot find page size for page %d",
783 pageno);
785 else {
786 mediabox = rootmediabox;
792 else {
793 if (state.trimmargins && trimw) {
794 fz_page *page;
796 fz_try (ctx) {
797 page = fz_load_page (ctx, state.doc, pageno);
798 mediabox = fz_bound_page (ctx, page);
799 if (state.trimmargins) {
800 fz_rect rect;
801 fz_device *dev;
803 dev = fz_new_bbox_device (ctx, &rect);
804 fz_run_page (ctx, page, dev, fz_identity, NULL);
805 fz_close_device (ctx, dev);
806 fz_drop_device (ctx, dev);
808 rect.x0 += state.trimfuzz.x0;
809 rect.x1 += state.trimfuzz.x1;
810 rect.y0 += state.trimfuzz.y0;
811 rect.y1 += state.trimfuzz.y1;
812 rect = fz_intersect_rect (rect, mediabox);
814 if (!fz_is_empty_rect (rect)) {
815 mediabox = rect;
818 fz_drop_page (ctx, page);
820 fz_catch (ctx) {
822 if (trimf) {
823 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
824 if (n - 1) {
825 err (1, "fwrite trim mediabox");
829 else {
830 if (trimf) {
831 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
832 if (n - 1) {
833 err (1, "fread trim mediabox %d", pageno);
836 else {
837 fz_page *page;
838 fz_try (ctx) {
839 page = fz_load_page (ctx, state.doc, pageno);
840 mediabox = fz_bound_page (ctx, page);
841 fz_drop_page (ctx, page);
843 show = !state.trimmargins && pageno % 20 == 0;
844 if (show) {
845 printd ("progress %f Gathering dimensions %d",
846 (double) (pageno) / state.pagecount,
847 pageno);
850 fz_catch (ctx) {
851 printd ("emsg failed to load page %d", pageno);
857 if (!p || p->rotate != rotate
858 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
859 size_t size;
861 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
862 state.pagedims = realloc (state.pagedims, size);
863 if (!state.pagedims) {
864 err (1, "realloc pagedims to %zu (%d elems)",
865 size, state.pagedimcount + 1);
868 p = &state.pagedims[state.pagedimcount++];
869 p->rotate = rotate;
870 p->mediabox = mediabox;
871 p->pageno = pageno;
874 state.trimanew = 0;
875 if (trimf) {
876 if (fclose (trimf)) {
877 err (1, "fclose");
882 static void layout (void)
884 int pindex;
885 fz_rect box;
886 fz_matrix ctm;
887 struct pagedim *p = NULL;
888 float zw, w, maxw = 0.0, zoom = 1.0;
890 if (state.pagedimcount == 0) return;
892 switch (state.fitmodel) {
893 case FitProportional:
894 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
895 float x0, x1;
897 p = &state.pagedims[pindex];
898 box = fz_transform_rect (p->mediabox,
899 fz_rotate (p->rotate + state.rotate));
901 x0 = fz_min (box.x0, box.x1);
902 x1 = fz_max (box.x0, box.x1);
904 w = x1 - x0;
905 maxw = fz_max (w, maxw);
906 zoom = state.w / maxw;
908 break;
910 case FitPage:
911 maxw = state.w;
912 break;
914 case FitWidth:
915 break;
917 default:
918 ARSERT (0 && state.fitmodel);
921 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
922 p = &state.pagedims[pindex];
923 ctm = fz_rotate (state.rotate);
924 box = fz_transform_rect (p->mediabox,
925 fz_rotate (p->rotate + state.rotate));
926 w = box.x1 - box.x0;
927 switch (state.fitmodel) {
928 case FitProportional:
929 p->left = (int) (((maxw - w) * zoom) / 2.f);
930 break;
931 case FitPage:
933 float zh, h;
934 zw = maxw / w;
935 h = box.y1 - box.y0;
936 zh = state.h / h;
937 zoom = fz_min (zw, zh);
938 p->left = (int) ((maxw - (w * zoom)) / 2.f);
940 break;
941 case FitWidth:
942 p->left = 0;
943 zoom = state.w / w;
944 break;
947 p->zoomctm = fz_scale (zoom, zoom);
948 ctm = fz_concat (p->zoomctm, ctm);
950 p->pagebox = p->mediabox;
951 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
952 p->pagebox.x1 -= p->pagebox.x0;
953 p->pagebox.y1 -= p->pagebox.y0;
954 p->pagebox.x0 = 0;
955 p->pagebox.y0 = 0;
956 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
957 p->ctm = ctm;
959 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
960 fz_scale (zoom, -zoom));
961 p->tctmready = 0;
964 do {
965 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
966 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
967 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
968 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
969 int boundw = x1 - x0;
970 int boundh = y1 - y0;
972 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
973 } while (p-- != state.pagedims);
976 static struct pagedim *pdimofpageno (int pageno)
978 struct pagedim *pdim = state.pagedims;
980 for (int i = 0; i < state.pagedimcount; ++i) {
981 if (state.pagedims[i].pageno > pageno)
982 break;
983 pdim = &state.pagedims[i];
985 return pdim;
988 static void recurse_outline (fz_outline *outline, int level)
990 while (outline) {
991 if (outline->page >= 0) {
992 fz_point p = {.x = outline->x, .y = outline->y};
993 struct pagedim *pdim = pdimofpageno (outline->page);
994 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
995 p = fz_transform_point (p, pdim->ctm);
996 printd ("o %d %d %d %d %s",
997 level, outline->page, (int) p.y, h, outline->title);
999 else {
1000 printd ("on %d %s", level, outline->title);
1002 if (outline->down) {
1003 recurse_outline (outline->down, level + 1);
1005 outline = outline->next;
1009 static void process_outline (void)
1011 fz_outline *outline;
1013 if (!state.needoutline || !state.pagedimcount) return;
1015 state.needoutline = 0;
1016 outline = fz_load_outline (state.ctx, state.doc);
1017 if (outline) {
1018 recurse_outline (outline, 0);
1019 fz_drop_outline (state.ctx, outline);
1023 static char *strofline (fz_stext_line *line)
1025 char *p;
1026 char utf8[10];
1027 fz_stext_char *ch;
1028 size_t size = 0, cap = 80;
1030 p = malloc (cap + 1);
1031 if (!p) return NULL;
1033 for (ch = line->first_char; ch; ch = ch->next) {
1034 int n = fz_runetochar (utf8, ch->c);
1035 if (size + n > cap) {
1036 cap *= 2;
1037 p = realloc (p, cap + 1);
1038 if (!p) return NULL;
1041 memcpy (p + size, utf8, n);
1042 size += n;
1044 p[size] = 0;
1045 return p;
1048 static int matchline (regex_t *re, fz_stext_line *line,
1049 int stop, int pageno, double start)
1051 int ret;
1052 char *p;
1053 regmatch_t rm;
1055 p = strofline (line);
1056 if (!p) return -1;
1058 ret = regexec (re, p, 1, &rm, 0);
1059 if (ret) {
1060 free (p);
1061 if (ret != REG_NOMATCH) {
1062 size_t size;
1063 char errbuf[80];
1064 size = regerror (ret, re, errbuf, sizeof (errbuf));
1065 printd ("msg regexec error `%.*s'",
1066 (int) size, errbuf);
1067 return -1;
1069 return 0;
1071 else {
1072 fz_quad s, e;
1073 fz_stext_char *ch;
1074 int o = 0;
1076 for (ch = line->first_char; ch; ch = ch->next) {
1077 o += fz_runelen (ch->c);
1078 if (o > rm.rm_so) {
1079 s = ch->quad;
1080 break;
1083 for (;ch; ch = ch->next) {
1084 o += fz_runelen (ch->c);
1085 if (o > rm.rm_eo) break;
1087 e = ch->quad;
1089 if (!stop) {
1090 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1091 pageno, 1,
1092 s.ul.x, s.ul.y,
1093 e.ur.x, s.ul.y,
1094 e.lr.x, e.lr.y,
1095 s.ul.x, e.lr.y);
1097 printd ("progress 1 found at %d `%.*s' in %f sec",
1098 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1099 now () - start);
1101 else {
1102 printd ("match %d %d %f %f %f %f %f %f %f %f",
1103 pageno, 2,
1104 s.ul.x, s.ul.y,
1105 e.ur.x, s.ul.y,
1106 e.lr.x, e.lr.y,
1107 s.ul.x, e.lr.y);
1109 free (p);
1110 return 1;
1114 /* wishful thinking function */
1115 static void search (regex_t *re, int pageno, int y, int forward)
1117 fz_device *tdev;
1118 fz_stext_page *text;
1119 struct pagedim *pdim;
1120 int stop = 0, niters = 0;
1121 double start, end;
1122 fz_page *page;
1123 fz_stext_block *block;
1125 start = now ();
1126 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1127 if (niters++ == 5) {
1128 niters = 0;
1129 if (hasdata ()) {
1130 printd ("progress 1 attention requested aborting search at %d",
1131 pageno);
1132 stop = 1;
1134 else {
1135 printd ("progress %f searching in page %d",
1136 (double) (pageno + 1) / state.pagecount,
1137 pageno);
1140 pdim = pdimofpageno (pageno);
1141 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1142 tdev = fz_new_stext_device (state.ctx, text, 0);
1144 page = fz_load_page (state.ctx, state.doc, pageno);
1145 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1147 fz_close_device (state.ctx, tdev);
1148 fz_drop_device (state.ctx, tdev);
1150 if (forward) {
1151 for (block = text->first_block; block; block = block->next) {
1152 fz_stext_line *line;
1154 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1155 for (line = block->u.t.first_line; line; line = line->next) {
1156 if (line->bbox.y0 < y + 1) continue;
1158 switch (matchline (re, line, stop, pageno, start)) {
1159 case 0: break;
1160 case 1: stop = 1; break;
1161 case -1: stop = 1; goto endloop;
1166 else {
1167 for (block = text->last_block; block; block = block->prev) {
1168 fz_stext_line *line;
1170 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1171 for (line = block->u.t.last_line; line; line = line->prev) {
1172 if (line->bbox.y0 < y + 1) continue;
1174 switch (matchline (re, line, stop, pageno, start)) {
1175 case 0: break;
1176 case 1: stop = 1; break;
1177 case -1: stop = 1; goto endloop;
1183 if (forward) {
1184 pageno += 1;
1185 y = 0;
1187 else {
1188 pageno -= 1;
1189 y = INT_MAX;
1191 endloop:
1192 fz_drop_stext_page (state.ctx, text);
1193 fz_drop_page (state.ctx, page);
1195 end = now ();
1196 if (!stop) {
1197 printd ("progress 1 no matches %f sec", end - start);
1199 printd ("clearrects");
1202 static void set_tex_params (int colorspace)
1204 switch (colorspace) {
1205 case 0:
1206 state.texiform = GL_RGBA8;
1207 state.texform = GL_RGBA;
1208 state.texty = GL_UNSIGNED_BYTE;
1209 state.colorspace = fz_device_rgb (state.ctx);
1210 break;
1211 case 1:
1212 state.texiform = GL_LUMINANCE_ALPHA;
1213 state.texform = GL_LUMINANCE_ALPHA;
1214 state.texty = GL_UNSIGNED_BYTE;
1215 state.colorspace = fz_device_gray (state.ctx);
1216 break;
1217 default:
1218 errx (1, "invalid colorspce %d", colorspace);
1222 static void realloctexts (int texcount)
1224 size_t size;
1226 if (texcount == state.texcount) return;
1228 if (texcount < state.texcount) {
1229 glDeleteTextures (state.texcount - texcount,
1230 state.texids + texcount);
1233 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1234 state.texids = realloc (state.texids, size);
1235 if (!state.texids) {
1236 err (1, "realloc texs %zu", size);
1239 state.texowners = (void *) (state.texids + texcount);
1240 if (texcount > state.texcount) {
1241 glGenTextures (texcount - state.texcount,
1242 state.texids + state.texcount);
1243 for (int i = state.texcount; i < texcount; ++i) {
1244 state.texowners[i].w = -1;
1245 state.texowners[i].slice = NULL;
1248 state.texcount = texcount;
1249 state.texindex = 0;
1252 static char *mbtoutf8 (char *s)
1254 char *p, *r;
1255 wchar_t *tmp;
1256 size_t i, ret, len;
1258 if (state.utf8cs) {
1259 return s;
1262 len = mbstowcs (NULL, s, strlen (s));
1263 if (len == 0 || len == (size_t) -1) {
1264 if (len)
1265 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1266 return s;
1269 tmp = calloc (len, sizeof (wchar_t));
1270 if (!tmp) {
1271 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1272 len, sizeof (wchar_t), errno, strerror (errno));
1273 return s;
1276 ret = mbstowcs (tmp, s, len);
1277 if (ret == (size_t) -1) {
1278 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1279 len, errno, strerror (errno));
1280 free (tmp);
1281 return s;
1284 len = 0;
1285 for (i = 0; i < ret; ++i) {
1286 len += fz_runelen (tmp[i]);
1289 p = r = malloc (len + 1);
1290 if (!r) {
1291 printd ("emsg mbtoutf8: malloc(%zu)", len);
1292 free (tmp);
1293 return s;
1296 for (i = 0; i < ret; ++i) {
1297 p += fz_runetochar (p, tmp[i]);
1299 *p = 0;
1300 free (tmp);
1301 return r;
1304 ML (mbtoutf8 (value s_v))
1306 CAMLparam1 (s_v);
1307 CAMLlocal1 (ret_v);
1308 char *s, *r;
1310 s = &Byte (s_v, 0);
1311 r = mbtoutf8 (s);
1312 if (r == s) {
1313 ret_v = s_v;
1315 else {
1316 ret_v = caml_copy_string (r);
1317 free (r);
1319 CAMLreturn (ret_v);
1322 static void * mainloop (void UNUSED_ATTR *unused)
1324 char *p = NULL;
1325 int len, ret, oldlen = 0;
1327 fz_var (p);
1328 fz_var (oldlen);
1329 for (;;) {
1330 len = readlen (state.csock);
1331 if (len == 0) {
1332 errx (1, "readlen returned 0");
1335 if (oldlen < len + 1) {
1336 p = realloc (p, len + 1);
1337 if (!p) {
1338 err (1, "realloc %d failed", len + 1);
1340 oldlen = len + 1;
1342 readdata (state.csock, p, len);
1343 p[len] = 0;
1345 if (!strncmp ("open", p, 4)) {
1346 int off, usedoccss, ok = 0, layouth;
1347 char *password;
1348 char *filename;
1349 char *utf8filename;
1350 size_t filenamelen;
1352 fz_var (ok);
1353 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1354 if (ret != 2) {
1355 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1358 filename = p + 5 + off;
1359 filenamelen = strlen (filename);
1360 password = filename + filenamelen + 1;
1362 if (password[strlen (password) + 1]) {
1363 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1366 lock ("open");
1367 fz_set_use_document_css (state.ctx, usedoccss);
1368 fz_try (state.ctx) {
1369 ok = openxref (filename, password, layouth);
1371 fz_catch (state.ctx) {
1372 utf8filename = mbtoutf8 (filename);
1373 printd ("emsg Error loading %s: %s",
1374 utf8filename, fz_caught_message (state.ctx));
1375 if (utf8filename != filename) {
1376 free (utf8filename);
1379 if (ok) {
1380 docinfo ();
1381 initpdims ();
1383 unlock ("open");
1384 state.needoutline = ok;
1386 else if (!strncmp ("cs", p, 2)) {
1387 int i, colorspace;
1389 ret = sscanf (p + 2, " %d", &colorspace);
1390 if (ret != 1) {
1391 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1393 lock ("cs");
1394 set_tex_params (colorspace);
1395 for (i = 0; i < state.texcount; ++i) {
1396 state.texowners[i].w = -1;
1397 state.texowners[i].slice = NULL;
1399 unlock ("cs");
1401 else if (!strncmp ("freepage", p, 8)) {
1402 void *ptr;
1404 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1405 if (ret != 1) {
1406 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1408 lock ("freepage");
1409 freepage (ptr);
1410 unlock ("freepage");
1412 else if (!strncmp ("freetile", p, 8)) {
1413 void *ptr;
1415 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1416 if (ret != 1) {
1417 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1419 lock ("freetile");
1420 freetile (ptr);
1421 unlock ("freetile");
1423 else if (!strncmp ("search", p, 6)) {
1424 int icase, pageno, y, len2, forward;
1425 char *pattern;
1426 regex_t re;
1428 ret = sscanf (p + 6, " %d %d %d %d,%n",
1429 &icase, &pageno, &y, &forward, &len2);
1430 if (ret != 4) {
1431 errx (1, "malformed search `%s' ret=%d", p, ret);
1434 pattern = p + 6 + len2;
1435 ret = regcomp (&re, pattern,
1436 REG_EXTENDED | (icase ? REG_ICASE : 0));
1437 if (ret) {
1438 char errbuf[80];
1439 size_t size;
1441 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1442 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1444 else {
1445 lock ("search");
1446 search (&re, pageno, y, forward);
1447 unlock ("search");
1448 regfree (&re);
1451 else if (!strncmp ("geometry", p, 8)) {
1452 int w, h, fitmodel;
1454 printd ("clear");
1455 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1456 if (ret != 3) {
1457 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1460 lock ("geometry");
1461 state.h = h;
1462 if (w != state.w) {
1463 state.w = w;
1464 for (int i = 0; i < state.texcount; ++i) {
1465 state.texowners[i].slice = NULL;
1468 state.fitmodel = fitmodel;
1469 layout ();
1470 process_outline ();
1472 state.gen++;
1473 unlock ("geometry");
1474 printd ("continue %d", state.pagecount);
1476 else if (!strncmp ("reqlayout", p, 9)) {
1477 char *nameddest;
1478 int rotate, off, h;
1479 int fitmodel;
1480 pdf_document *pdf;
1482 printd ("clear");
1483 ret = sscanf (p + 9, " %d %d %d %n",
1484 &rotate, &fitmodel, &h, &off);
1485 if (ret != 3) {
1486 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1488 lock ("reqlayout");
1489 pdf = pdf_specifics (state.ctx, state.doc);
1490 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1491 state.gen += 1;
1493 state.rotate = rotate;
1494 state.fitmodel = fitmodel;
1495 state.h = h;
1496 layout ();
1497 process_outline ();
1499 nameddest = p + 9 + off;
1500 if (pdf && nameddest && *nameddest) {
1501 fz_point xy;
1502 struct pagedim *pdim;
1503 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1504 &xy.x, &xy.y);
1505 pdim = pdimofpageno (pageno);
1506 xy = fz_transform_point (xy, pdim->ctm);
1507 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1510 state.gen++;
1511 unlock ("reqlayout");
1512 printd ("continue %d", state.pagecount);
1514 else if (!strncmp ("page", p, 4)) {
1515 double a, b;
1516 struct page *page;
1517 int pageno, pindex;
1519 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1520 if (ret != 2) {
1521 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1524 lock ("page");
1525 a = now ();
1526 page = loadpage (pageno, pindex);
1527 b = now ();
1528 unlock ("page");
1530 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1532 else if (!strncmp ("tile", p, 4)) {
1533 int x, y, w, h;
1534 struct page *page;
1535 struct tile *tile;
1536 double a, b;
1537 void *data;
1539 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1540 (uintptr_t *) &page, &x, &y, &w, &h,
1541 (uintptr_t *) &data);
1542 if (ret != 6) {
1543 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1546 lock ("tile");
1547 a = now ();
1548 tile = rendertile (page, x, y, w, h, data);
1549 b = now ();
1550 unlock ("tile");
1552 printd ("tile %d %d %" PRIxPTR " %u %f",
1553 x, y, (uintptr_t) (tile),
1554 tile->w * tile->h * tile->pixmap->n,
1555 b - a);
1557 else if (!strncmp ("trimset", p, 7)) {
1558 fz_irect fuzz;
1559 int trimmargins;
1561 ret = sscanf (p + 7, " %d %d %d %d %d",
1562 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1563 if (ret != 5) {
1564 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1566 lock ("trimset");
1567 state.trimmargins = trimmargins;
1568 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1569 state.trimanew = 1;
1570 state.trimfuzz = fuzz;
1572 unlock ("trimset");
1574 else if (!strncmp ("settrim", p, 7)) {
1575 fz_irect fuzz;
1576 int trimmargins;
1578 ret = sscanf (p + 7, " %d %d %d %d %d",
1579 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1580 if (ret != 5) {
1581 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1583 printd ("clear");
1584 lock ("settrim");
1585 state.trimmargins = trimmargins;
1586 state.needoutline = 1;
1587 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1588 state.trimanew = 1;
1589 state.trimfuzz = fuzz;
1591 state.pagedimcount = 0;
1592 free (state.pagedims);
1593 state.pagedims = NULL;
1594 initpdims ();
1595 layout ();
1596 process_outline ();
1597 unlock ("settrim");
1598 printd ("continue %d", state.pagecount);
1600 else if (!strncmp ("sliceh", p, 6)) {
1601 int h;
1603 ret = sscanf (p + 6, " %d", &h);
1604 if (ret != 1) {
1605 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1607 if (h != state.sliceheight) {
1608 state.sliceheight = h;
1609 for (int i = 0; i < state.texcount; ++i) {
1610 state.texowners[i].w = -1;
1611 state.texowners[i].h = -1;
1612 state.texowners[i].slice = NULL;
1616 else if (!strncmp ("interrupt", p, 9)) {
1617 printd ("vmsg interrupted");
1619 else {
1620 errx (1, "unknown command %.*s", len, p);
1623 return 0;
1626 ML (isexternallink (value uri_v))
1628 CAMLparam1 (uri_v);
1629 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1630 CAMLreturn (Val_bool (ext));
1633 ML (uritolocation (value uri_v))
1635 CAMLparam1 (uri_v);
1636 CAMLlocal1 (ret_v);
1637 int pageno;
1638 fz_point xy;
1639 struct pagedim *pdim;
1641 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1642 &xy.x, &xy.y).page;
1643 pdim = pdimofpageno (pageno);
1644 xy = fz_transform_point (xy, pdim->ctm);
1645 ret_v = caml_alloc_tuple (3);
1646 Field (ret_v, 0) = Val_int (pageno);
1647 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1648 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1649 CAMLreturn (ret_v);
1652 ML (realloctexts (value texcount_v))
1654 CAMLparam1 (texcount_v);
1655 int ok;
1657 if (trylock (__func__)) {
1658 ok = 0;
1659 goto done;
1661 realloctexts (Int_val (texcount_v));
1662 ok = 1;
1663 unlock (__func__);
1665 done:
1666 CAMLreturn (Val_bool (ok));
1669 static void recti (int x0, int y0, int x1, int y1)
1671 GLfloat *v = state.vertices;
1673 glVertexPointer (2, GL_FLOAT, 0, v);
1674 v[0] = x0; v[1] = y0;
1675 v[2] = x1; v[3] = y0;
1676 v[4] = x0; v[5] = y1;
1677 v[6] = x1; v[7] = y1;
1678 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1681 static void showsel (struct page *page, int ox, int oy)
1683 fz_irect bbox;
1684 fz_rect rect;
1685 fz_stext_block *block;
1686 int seen = 0;
1687 unsigned char selcolor[] = {15,15,15,140};
1689 if (!page->fmark || !page->lmark) return;
1691 glEnable (GL_BLEND);
1692 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1693 glColor4ubv (selcolor);
1695 ox += state.pagedims[page->pdimno].bounds.x0;
1696 oy += state.pagedims[page->pdimno].bounds.y0;
1698 for (block = page->text->first_block; block; block = block->next) {
1699 fz_stext_line *line;
1701 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1702 for (line = block->u.t.first_line; line; line = line->next) {
1703 fz_stext_char *ch;
1705 rect = fz_empty_rect;
1706 for (ch = line->first_char; ch; ch = ch->next) {
1707 fz_rect r;
1708 if (ch == page->fmark) seen = 1;
1709 r = fz_rect_from_quad (ch->quad);
1710 if (seen) rect = fz_union_rect (rect, r);
1711 if (ch == page->lmark) {
1712 bbox = fz_round_rect (rect);
1713 recti (bbox.x0 + ox, bbox.y0 + oy,
1714 bbox.x1 + ox, bbox.y1 + oy);
1715 goto done;
1718 bbox = fz_round_rect (rect);
1719 recti (bbox.x0 + ox, bbox.y0 + oy,
1720 bbox.x1 + ox, bbox.y1 + oy);
1723 done:
1724 glDisable (GL_BLEND);
1727 #pragma GCC diagnostic push
1728 #pragma GCC diagnostic ignored "-Wconversion"
1729 #include "glfont.c"
1730 #pragma GCC diagnostic pop
1732 static void stipplerect (fz_matrix m,
1733 fz_point p1,
1734 fz_point p2,
1735 fz_point p3,
1736 fz_point p4,
1737 GLfloat *texcoords,
1738 GLfloat *vertices)
1740 p1 = fz_transform_point (p1, m);
1741 p2 = fz_transform_point (p2, m);
1742 p3 = fz_transform_point (p3, m);
1743 p4 = fz_transform_point (p4, m);
1745 float w, h, s, t;
1747 w = p2.x - p1.x;
1748 h = p2.y - p1.y;
1749 t = hypotf (w, h) * .25f;
1751 w = p3.x - p2.x;
1752 h = p3.y - p2.y;
1753 s = hypotf (w, h) * .25f;
1755 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1756 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1758 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1759 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1761 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1762 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1764 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1765 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1767 glDrawArrays (GL_LINES, 0, 8);
1770 static void solidrect (fz_matrix m,
1771 fz_point p1,
1772 fz_point p2,
1773 fz_point p3,
1774 fz_point p4,
1775 GLfloat *vertices)
1777 p1 = fz_transform_point (p1, m);
1778 p2 = fz_transform_point (p2, m);
1779 p3 = fz_transform_point (p3, m);
1780 p4 = fz_transform_point (p4, m);
1781 vertices[0] = p1.x; vertices[1] = p1.y;
1782 vertices[2] = p2.x; vertices[3] = p2.y;
1784 vertices[4] = p3.x; vertices[5] = p3.y;
1785 vertices[6] = p4.x; vertices[7] = p4.y;
1786 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1789 static void ensurelinks (struct page *page)
1791 if (!page->links)
1792 page->links = fz_load_links (state.ctx, page->fzpage);
1795 static void highlightlinks (struct page *page, int xoff, int yoff)
1797 fz_matrix ctm;
1798 fz_link *link;
1799 GLfloat *texcoords = state.texcoords;
1800 GLfloat *vertices = state.vertices;
1802 ensurelinks (page);
1804 glEnable (GL_TEXTURE_1D);
1805 glEnable (GL_BLEND);
1806 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1807 glBindTexture (GL_TEXTURE_1D, state.stid);
1809 xoff -= state.pagedims[page->pdimno].bounds.x0;
1810 yoff -= state.pagedims[page->pdimno].bounds.y0;
1811 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1813 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1814 glVertexPointer (2, GL_FLOAT, 0, vertices);
1816 for (link = page->links; link; link = link->next) {
1817 fz_point p1, p2, p3, p4;
1819 p1.x = link->rect.x0;
1820 p1.y = link->rect.y0;
1822 p2.x = link->rect.x1;
1823 p2.y = link->rect.y0;
1825 p3.x = link->rect.x1;
1826 p3.y = link->rect.y1;
1828 p4.x = link->rect.x0;
1829 p4.y = link->rect.y1;
1831 /* TODO: different colours for different schemes */
1832 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1833 else glColor3ub (255, 0, 0);
1835 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1838 for (int i = 0; i < page->annotcount; ++i) {
1839 fz_point p1, p2, p3, p4;
1840 struct annot *annot = &page->annots[i];
1842 p1.x = annot->bbox.x0;
1843 p1.y = annot->bbox.y0;
1845 p2.x = annot->bbox.x1;
1846 p2.y = annot->bbox.y0;
1848 p3.x = annot->bbox.x1;
1849 p3.y = annot->bbox.y1;
1851 p4.x = annot->bbox.x0;
1852 p4.y = annot->bbox.y1;
1854 glColor3ub (0, 0, 128);
1855 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1858 glDisable (GL_BLEND);
1859 glDisable (GL_TEXTURE_1D);
1862 static int compareslinks (const void *l, const void *r)
1864 struct slink const *ls = l;
1865 struct slink const *rs = r;
1866 if (ls->bbox.y0 == rs->bbox.y0) {
1867 return ls->bbox.x0 - rs->bbox.x0;
1869 return ls->bbox.y0 - rs->bbox.y0;
1872 static void droptext (struct page *page)
1874 if (page->text) {
1875 fz_drop_stext_page (state.ctx, page->text);
1876 page->fmark = NULL;
1877 page->lmark = NULL;
1878 page->text = NULL;
1882 static void dropannots (struct page *page)
1884 if (page->annots) {
1885 free (page->annots);
1886 page->annots = NULL;
1887 page->annotcount = 0;
1891 static void ensureannots (struct page *page)
1893 int i, count = 0;
1894 size_t annotsize = sizeof (*page->annots);
1895 pdf_annot *annot;
1896 pdf_document *pdf;
1897 pdf_page *pdfpage;
1899 pdf = pdf_specifics (state.ctx, state.doc);
1900 if (!pdf) return;
1902 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1903 if (state.gen != page->agen) {
1904 dropannots (page);
1905 page->agen = state.gen;
1907 if (page->annots) return;
1909 for (annot = pdf_first_annot (state.ctx, pdfpage);
1910 annot;
1911 annot = pdf_next_annot (state.ctx, annot)) {
1912 count++;
1915 if (count > 0) {
1916 page->annotcount = count;
1917 page->annots = calloc (count, annotsize);
1918 if (!page->annots) {
1919 err (1, "calloc annots %d", count);
1922 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1923 annot;
1924 annot = pdf_next_annot (state.ctx, annot), i++) {
1925 fz_rect rect;
1927 rect = pdf_bound_annot (state.ctx, annot);
1928 page->annots[i].annot = annot;
1929 page->annots[i].bbox = fz_round_rect (rect);
1934 static void dropslinks (struct page *page)
1936 if (page->slinks) {
1937 free (page->slinks);
1938 page->slinks = NULL;
1939 page->slinkcount = 0;
1941 if (page->links) {
1942 fz_drop_link (state.ctx, page->links);
1943 page->links = NULL;
1947 static void ensureslinks (struct page *page)
1949 fz_matrix ctm;
1950 int i, count;
1951 size_t slinksize = sizeof (*page->slinks);
1952 fz_link *link;
1954 ensureannots (page);
1955 if (state.gen != page->sgen) {
1956 dropslinks (page);
1957 page->sgen = state.gen;
1959 if (page->slinks) return;
1961 ensurelinks (page);
1962 ctm = pagectm (page);
1964 count = page->annotcount;
1965 for (link = page->links; link; link = link->next) {
1966 count++;
1968 if (count > 0) {
1969 int j;
1971 page->slinkcount = count;
1972 page->slinks = calloc (count, slinksize);
1973 if (!page->slinks) {
1974 err (1, "calloc slinks %d", count);
1977 for (i = 0, link = page->links; link; ++i, link = link->next) {
1978 fz_rect rect;
1980 rect = link->rect;
1981 rect = fz_transform_rect (rect, ctm);
1982 page->slinks[i].tag = SLINK;
1983 page->slinks[i].u.link = link;
1984 page->slinks[i].bbox = fz_round_rect (rect);
1986 for (j = 0; j < page->annotcount; ++j, ++i) {
1987 fz_rect rect;
1988 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1989 rect = fz_transform_rect (rect, ctm);
1990 page->slinks[i].bbox = fz_round_rect (rect);
1992 page->slinks[i].tag = SANNOT;
1993 page->slinks[i].u.annot = page->annots[j].annot;
1995 qsort (page->slinks, count, slinksize, compareslinks);
1999 static void highlightslinks (struct page *page, int xoff, int yoff,
2000 int noff, const char *targ,
2001 mlsize_t tlen, int hfsize)
2003 char buf[40];
2004 struct slink *slink;
2005 float x0, y0, x1, y1, w;
2007 ensureslinks (page);
2008 glColor3ub (0xc3, 0xb0, 0x91);
2009 for (int i = 0; i < page->slinkcount; ++i) {
2010 fmt_linkn (buf, i + noff);
2011 if (!tlen || !strncmp (targ, buf, tlen)) {
2012 slink = &page->slinks[i];
2014 x0 = slink->bbox.x0 + xoff - 5;
2015 y1 = slink->bbox.y0 + yoff - 5;
2016 y0 = y1 + 10 + hfsize;
2017 w = measure_string (state.face, hfsize, buf);
2018 x1 = x0 + w + 10;
2019 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2023 glEnable (GL_BLEND);
2024 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2025 glEnable (GL_TEXTURE_2D);
2026 glColor3ub (0, 0, 0);
2027 for (int i = 0; i < page->slinkcount; ++i) {
2028 fmt_linkn (buf, i + noff);
2029 if (!tlen || !strncmp (targ, buf, tlen)) {
2030 slink = &page->slinks[i];
2032 x0 = slink->bbox.x0 + xoff;
2033 y0 = slink->bbox.y0 + yoff + hfsize;
2034 draw_string (state.face, hfsize, x0, y0, buf);
2037 glDisable (GL_TEXTURE_2D);
2038 glDisable (GL_BLEND);
2041 static void uploadslice (struct tile *tile, struct slice *slice)
2043 int offset;
2044 struct slice *slice1;
2045 unsigned char *texdata;
2047 offset = 0;
2048 for (slice1 = tile->slices; slice != slice1; slice1++) {
2049 offset += slice1->h * tile->w * tile->pixmap->n;
2051 if (slice->texindex != -1 && slice->texindex < state.texcount
2052 && state.texowners[slice->texindex].slice == slice) {
2053 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2055 else {
2056 int subimage = 0;
2057 int texindex = state.texindex++ % state.texcount;
2059 if (state.texowners[texindex].w == tile->w) {
2060 if (state.texowners[texindex].h >= slice->h) {
2061 subimage = 1;
2063 else {
2064 state.texowners[texindex].h = slice->h;
2067 else {
2068 state.texowners[texindex].h = slice->h;
2071 state.texowners[texindex].w = tile->w;
2072 state.texowners[texindex].slice = slice;
2073 slice->texindex = texindex;
2075 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2076 #if TEXT_TYPE == GL_TEXTURE_2D
2077 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2078 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2079 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2080 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2081 #endif
2082 if (tile->pbo) {
2083 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2084 texdata = 0;
2086 else {
2087 texdata = tile->pixmap->samples;
2089 if (subimage) {
2090 glTexSubImage2D (TEXT_TYPE,
2094 tile->w,
2095 slice->h,
2096 state.texform,
2097 state.texty,
2098 texdata+offset
2101 else {
2102 glTexImage2D (TEXT_TYPE,
2104 state.texiform,
2105 tile->w,
2106 slice->h,
2108 state.texform,
2109 state.texty,
2110 texdata+offset
2113 if (tile->pbo) {
2114 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2119 ML0 (begintiles (void))
2121 glEnable (TEXT_TYPE);
2122 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2123 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2126 ML0 (endtiles (void))
2128 glDisable (TEXT_TYPE);
2131 ML0 (drawtile (value args_v, value ptr_v))
2133 CAMLparam2 (args_v, ptr_v);
2134 int dispx = Int_val (Field (args_v, 0));
2135 int dispy = Int_val (Field (args_v, 1));
2136 int dispw = Int_val (Field (args_v, 2));
2137 int disph = Int_val (Field (args_v, 3));
2138 int tilex = Int_val (Field (args_v, 4));
2139 int tiley = Int_val (Field (args_v, 5));
2140 const char *s = String_val (ptr_v);
2141 struct tile *tile = parse_pointer (__func__, s);
2142 int slicey, firstslice;
2143 struct slice *slice;
2144 GLfloat *texcoords = state.texcoords;
2145 GLfloat *vertices = state.vertices;
2147 firstslice = tiley / tile->sliceheight;
2148 slice = &tile->slices[firstslice];
2149 slicey = tiley % tile->sliceheight;
2151 while (disph > 0) {
2152 int dh;
2154 dh = slice->h - slicey;
2155 dh = fz_mini (disph, dh);
2156 uploadslice (tile, slice);
2158 texcoords[0] = tilex; texcoords[1] = slicey;
2159 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2160 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2161 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2163 vertices[0] = dispx; vertices[1] = dispy;
2164 vertices[2] = dispx+dispw; vertices[3] = dispy;
2165 vertices[4] = dispx; vertices[5] = dispy+dh;
2166 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2168 #if TEXT_TYPE == GL_TEXTURE_2D
2169 for (int i = 0; i < 8; ++i) {
2170 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2172 #endif
2174 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2175 dispy += dh;
2176 disph -= dh;
2177 slice++;
2178 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2179 slicey = 0;
2181 CAMLreturn0;
2184 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2186 fz_matrix ctm;
2187 fz_point p1, p2, p3, p4;
2188 GLfloat *vertices = state.vertices;
2190 xoff -= state.pagedims[page->pdimno].bounds.x0;
2191 yoff -= state.pagedims[page->pdimno].bounds.y0;
2192 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2194 glEnable (GL_BLEND);
2195 glVertexPointer (2, GL_FLOAT, 0, vertices);
2197 glColor4d (
2198 Double_array_field (rects_v, 0),
2199 Double_array_field (rects_v, 1),
2200 Double_array_field (rects_v, 2),
2201 Double_array_field (rects_v, 3)
2203 p1.x = (float) Double_array_field (rects_v, 4);
2204 p1.y = (float) Double_array_field (rects_v, 5);
2206 p2.x = (float) Double_array_field (rects_v, 6);
2207 p2.y = p1.y;
2209 p3.x = p2.x;
2210 p3.y = (float) Double_array_field (rects_v, 7);
2212 p4.x = p1.x;
2213 p4.y = p3.y;
2214 solidrect (ctm, p1, p2, p3, p4, vertices);
2215 glDisable (GL_BLEND);
2218 ML (postprocess (value ptr_v, value hlinks_v,
2219 value xoff_v, value yoff_v,
2220 value li_v))
2222 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2223 int xoff = Int_val (xoff_v);
2224 int yoff = Int_val (yoff_v);
2225 int noff = Int_val (Field (li_v, 0));
2226 const char *targ = String_val (Field (li_v, 1));
2227 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2228 int hfsize = Int_val (Field (li_v, 2));
2229 const char *s = String_val (ptr_v);
2230 int hlmask = Int_val (hlinks_v);
2231 struct page *page = parse_pointer (__func__, s);
2233 if (!page->fzpage) {
2234 /* deal with loadpage failed pages */
2235 goto done;
2238 if (trylock (__func__)) {
2239 noff = -1;
2240 goto done;
2243 ensureannots (page);
2244 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2245 if (hlmask & 2) {
2246 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2247 noff = page->slinkcount;
2249 if (page->tgen == state.gen) {
2250 showsel (page, xoff, yoff);
2252 unlock (__func__);
2254 done:
2255 CAMLreturn (Val_int (noff));
2258 ML0 (drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v))
2260 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2261 int xoff = Int_val (xoff_v);
2262 int yoff = Int_val (yoff_v);
2263 const char *s = String_val (ptr_v);
2264 struct page *page = parse_pointer (__func__, s);
2266 drawprect (page, xoff, yoff, rects_v);
2267 CAMLreturn0;
2270 static struct annot *getannot (struct page *page, int x, int y)
2272 fz_point p;
2273 fz_matrix ctm;
2274 const fz_matrix *tctm;
2275 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2277 if (!page->annots) return NULL;
2279 if (pdf) {
2280 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2281 tctm = &state.pagedims[page->pdimno].tctm;
2283 else {
2284 tctm = &fz_identity;
2287 p.x = x;
2288 p.y = y;
2290 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2291 ctm = fz_invert_matrix (ctm);
2292 p = fz_transform_point (p, ctm);
2294 if (pdf) {
2295 for (int i = 0; i < page->annotcount; ++i) {
2296 struct annot *a = &page->annots[i];
2297 fz_rect rect;
2299 rect = pdf_bound_annot (state.ctx, a->annot);
2300 if (p.x >= rect.x0 && p.x <= rect.x1) {
2301 if (p.y >= rect.y0 && p.y <= rect.y1)
2302 return a;
2306 return NULL;
2309 static fz_link *getlink (struct page *page, int x, int y)
2311 fz_point p;
2312 fz_link *link;
2314 ensureslinks (page);
2316 p.x = x;
2317 p.y = y;
2319 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2321 for (link = page->links; link; link = link->next) {
2322 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2323 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2324 return link;
2328 return NULL;
2331 static void ensuretext (struct page *page)
2333 if (state.gen != page->tgen) {
2334 droptext (page);
2335 page->tgen = state.gen;
2337 if (!page->text) {
2338 fz_device *tdev;
2340 page->text = fz_new_stext_page (state.ctx,
2341 state.pagedims[page->pdimno].mediabox);
2342 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2343 fz_run_display_list (state.ctx, page->dlist,
2344 tdev, pagectm (page), fz_infinite_rect, NULL);
2345 fz_close_device (state.ctx, tdev);
2346 fz_drop_device (state.ctx, tdev);
2350 ML (find_page_with_links (value start_page_v, value dir_v))
2352 CAMLparam2 (start_page_v, dir_v);
2353 CAMLlocal1 (ret_v);
2354 int i, dir = Int_val (dir_v);
2355 int start_page = Int_val (start_page_v);
2356 int end_page = dir > 0 ? state.pagecount : -1;
2357 pdf_document *pdf;
2359 fz_var (end_page);
2360 ret_v = Val_int (0);
2361 lock (__func__);
2362 pdf = pdf_specifics (state.ctx, state.doc);
2363 for (i = start_page + dir; i != end_page; i += dir) {
2364 int found;
2366 fz_var (found);
2367 if (pdf) {
2368 pdf_page *page = NULL;
2370 fz_var (page);
2371 fz_try (state.ctx) {
2372 page = pdf_load_page (state.ctx, pdf, i);
2373 found = !!page->links || !!page->annots;
2375 fz_catch (state.ctx) {
2376 found = 0;
2378 if (page) {
2379 fz_drop_page (state.ctx, &page->super);
2382 else {
2383 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2384 fz_link *link = fz_load_links (state.ctx, page);
2385 found = !!link;
2386 fz_drop_link (state.ctx, link);
2387 fz_drop_page (state.ctx, page);
2390 if (found) {
2391 ret_v = caml_alloc_small (1, 1);
2392 Field (ret_v, 0) = Val_int (i);
2393 goto unlock;
2396 unlock:
2397 unlock (__func__);
2398 CAMLreturn (ret_v);
2401 enum { dir_first, dir_last };
2402 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2404 ML (findlink (value ptr_v, value dir_v))
2406 CAMLparam2 (ptr_v, dir_v);
2407 CAMLlocal2 (ret_v, pos_v);
2408 struct page *page;
2409 int dirtag, i, slinkindex;
2410 struct slink *found = NULL ,*slink;
2411 const char *s = String_val (ptr_v);
2413 page = parse_pointer (__func__, s);
2414 ret_v = Val_int (0);
2415 lock (__func__);
2416 ensureslinks (page);
2418 if (Is_block (dir_v)) {
2419 dirtag = Tag_val (dir_v);
2420 switch (dirtag) {
2421 case dir_first_visible:
2423 int x0, y0, dir, first_index, last_index;
2425 pos_v = Field (dir_v, 0);
2426 x0 = Int_val (Field (pos_v, 0));
2427 y0 = Int_val (Field (pos_v, 1));
2428 dir = Int_val (Field (pos_v, 2));
2430 if (dir >= 0) {
2431 dir = 1;
2432 first_index = 0;
2433 last_index = page->slinkcount;
2435 else {
2436 first_index = page->slinkcount - 1;
2437 last_index = -1;
2440 for (i = first_index; i != last_index; i += dir) {
2441 slink = &page->slinks[i];
2442 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2443 found = slink;
2444 break;
2448 break;
2450 case dir_left:
2451 slinkindex = Int_val (Field (dir_v, 0));
2452 found = &page->slinks[slinkindex];
2453 for (i = slinkindex - 1; i >= 0; --i) {
2454 slink = &page->slinks[i];
2455 if (slink->bbox.x0 < found->bbox.x0) {
2456 found = slink;
2457 break;
2460 break;
2462 case dir_right:
2463 slinkindex = Int_val (Field (dir_v, 0));
2464 found = &page->slinks[slinkindex];
2465 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2466 slink = &page->slinks[i];
2467 if (slink->bbox.x0 > found->bbox.x0) {
2468 found = slink;
2469 break;
2472 break;
2474 case dir_down:
2475 slinkindex = Int_val (Field (dir_v, 0));
2476 found = &page->slinks[slinkindex];
2477 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2478 slink = &page->slinks[i];
2479 if (slink->bbox.y0 >= found->bbox.y0) {
2480 found = slink;
2481 break;
2484 break;
2486 case dir_up:
2487 slinkindex = Int_val (Field (dir_v, 0));
2488 found = &page->slinks[slinkindex];
2489 for (i = slinkindex - 1; i >= 0; --i) {
2490 slink = &page->slinks[i];
2491 if (slink->bbox.y0 <= found->bbox.y0) {
2492 found = slink;
2493 break;
2496 break;
2499 else {
2500 dirtag = Int_val (dir_v);
2501 switch (dirtag) {
2502 case dir_first:
2503 found = page->slinks;
2504 break;
2506 case dir_last:
2507 if (page->slinks) {
2508 found = page->slinks + (page->slinkcount - 1);
2510 break;
2513 if (found) {
2514 ret_v = caml_alloc_small (2, 1);
2515 Field (ret_v, 0) = Val_int (found - page->slinks);
2518 unlock (__func__);
2519 CAMLreturn (ret_v);
2522 enum { uuri, utext, uannot };
2524 ML (getlink (value ptr_v, value n_v))
2526 CAMLparam2 (ptr_v, n_v);
2527 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2528 fz_link *link;
2529 struct page *page;
2530 const char *s = String_val (ptr_v);
2531 struct slink *slink;
2533 ret_v = Val_int (0);
2534 page = parse_pointer (__func__, s);
2536 lock (__func__);
2537 ensureslinks (page);
2538 slink = &page->slinks[Int_val (n_v)];
2539 if (slink->tag == SLINK) {
2540 link = slink->u.link;
2541 str_v = caml_copy_string (link->uri);
2542 ret_v = caml_alloc_small (1, uuri);
2543 Field (ret_v, 0) = str_v;
2545 else {
2546 ret_v = caml_alloc_small (1, uannot);
2547 tup_v = caml_alloc_tuple (2);
2548 Field (ret_v, 0) = tup_v;
2549 Field (tup_v, 0) = ptr_v;
2550 Field (tup_v, 1) = n_v;
2552 unlock (__func__);
2554 CAMLreturn (ret_v);
2557 ML (getannotcontents (value ptr_v, value n_v))
2559 CAMLparam2 (ptr_v, n_v);
2560 CAMLlocal1 (ret_v);
2561 pdf_document *pdf;
2562 const char *contents = "";
2564 lock (__func__);
2565 pdf = pdf_specifics (state.ctx, state.doc);
2566 if (pdf) {
2567 const char *s = String_val (ptr_v);
2568 struct page *page;
2569 struct slink *slink;
2571 page = parse_pointer (__func__, s);
2572 slink = &page->slinks[Int_val (n_v)];
2573 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2575 unlock (__func__);
2576 ret_v = caml_copy_string (contents);
2577 CAMLreturn (ret_v);
2580 ML (getlinkcount (value ptr_v))
2582 CAMLparam1 (ptr_v);
2583 struct page *page;
2584 const char *s = String_val (ptr_v);
2586 page = parse_pointer (__func__, s);
2587 CAMLreturn (Val_int (page->slinkcount));
2590 ML (getlinkrect (value ptr_v, value n_v))
2592 CAMLparam2 (ptr_v, n_v);
2593 CAMLlocal1 (ret_v);
2594 struct page *page;
2595 struct slink *slink;
2596 const char *s = String_val (ptr_v);
2598 page = parse_pointer (__func__, s);
2599 ret_v = caml_alloc_tuple (4);
2600 lock (__func__);
2601 ensureslinks (page);
2603 slink = &page->slinks[Int_val (n_v)];
2604 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2605 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2606 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2607 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2608 unlock (__func__);
2609 CAMLreturn (ret_v);
2612 ML (whatsunder (value ptr_v, value x_v, value y_v))
2614 CAMLparam3 (ptr_v, x_v, y_v);
2615 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2616 fz_link *link;
2617 struct annot *annot;
2618 struct page *page;
2619 const char *ptr = String_val (ptr_v);
2620 int x = Int_val (x_v), y = Int_val (y_v);
2621 struct pagedim *pdim;
2623 ret_v = Val_int (0);
2624 if (trylock (__func__)) {
2625 goto done;
2628 page = parse_pointer (__func__, ptr);
2629 pdim = &state.pagedims[page->pdimno];
2630 x += pdim->bounds.x0;
2631 y += pdim->bounds.y0;
2634 annot = getannot (page, x, y);
2635 if (annot) {
2636 int i, n = -1;
2638 ensureslinks (page);
2639 for (i = 0; i < page->slinkcount; ++i) {
2640 if (page->slinks[i].tag == SANNOT
2641 && page->slinks[i].u.annot == annot->annot) {
2642 n = i;
2643 break;
2646 ret_v = caml_alloc_small (1, uannot);
2647 tup_v = caml_alloc_tuple (2);
2648 Field (ret_v, 0) = tup_v;
2649 Field (tup_v, 0) = ptr_v;
2650 Field (tup_v, 1) = Val_int (n);
2651 goto unlock;
2655 link = getlink (page, x, y);
2656 if (link) {
2657 str_v = caml_copy_string (link->uri);
2658 ret_v = caml_alloc_small (1, uuri);
2659 Field (ret_v, 0) = str_v;
2661 else {
2662 fz_rect *b;
2663 fz_stext_block *block;
2665 ensuretext (page);
2667 for (block = page->text->first_block; block; block = block->next) {
2668 fz_stext_line *line;
2670 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2671 b = &block->bbox;
2672 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2673 continue;
2675 for (line = block->u.t.first_line; line; line = line->next) {
2676 fz_stext_char *ch;
2678 b = &line->bbox;
2679 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2680 continue;
2682 for (ch = line->first_char; ch; ch = ch->next) {
2683 fz_quad *q = &ch->quad;
2685 if (x >= q->ul.x && x <= q->ur.x
2686 && y >= q->ul.y && y <= q->ll.y) {
2687 const char *n2 = fz_font_name (state.ctx, ch->font);
2688 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2689 ch->font);
2691 if (!n2) n2 = "<unknown font>";
2693 if (face && face->family_name) {
2694 char *s;
2695 char *n1 = face->family_name;
2696 size_t l1 = strlen (n1);
2697 size_t l2 = strlen (n2);
2699 if (l1 != l2 || memcmp (n1, n2, l1)) {
2700 s = malloc (l1 + l2 + 2);
2701 if (s) {
2702 memcpy (s, n2, l2);
2703 s[l2] = '=';
2704 memcpy (s + l2 + 1, n1, l1 + 1);
2705 str_v = caml_copy_string (s);
2706 free (s);
2710 if (str_v == Val_unit) {
2711 str_v = caml_copy_string (n2);
2713 ret_v = caml_alloc_small (1, utext);
2714 Field (ret_v, 0) = str_v;
2715 goto unlock;
2721 unlock:
2722 unlock (__func__);
2724 done:
2725 CAMLreturn (ret_v);
2728 enum { mark_page, mark_block, mark_line, mark_word };
2730 ML0 (clearmark (value ptr_v))
2732 CAMLparam1 (ptr_v);
2733 const char *s = String_val (ptr_v);
2734 struct page *page;
2736 if (trylock (__func__)) {
2737 goto done;
2740 page = parse_pointer (__func__, s);
2741 page->fmark = NULL;
2742 page->lmark = NULL;
2744 unlock (__func__);
2745 done:
2746 CAMLreturn0;
2749 static int uninteresting (int c)
2751 return isspace (c) || ispunct (c);
2754 ML (markunder (value ptr_v, value x_v, value y_v, value mark_v))
2756 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2757 CAMLlocal1 (ret_v);
2758 fz_rect *b;
2759 struct page *page;
2760 fz_stext_line *line;
2761 fz_stext_block *block;
2762 struct pagedim *pdim;
2763 int mark = Int_val (mark_v);
2764 const char *s = String_val (ptr_v);
2765 int x = Int_val (x_v), y = Int_val (y_v);
2767 ret_v = Val_bool (0);
2768 if (trylock (__func__)) {
2769 goto done;
2772 page = parse_pointer (__func__, s);
2773 pdim = &state.pagedims[page->pdimno];
2775 ensuretext (page);
2777 if (mark == mark_page) {
2778 page->fmark = page->text->first_block->u.t.first_line->first_char;
2779 page->lmark = page->text->last_block->u.t.last_line->last_char;
2780 ret_v = Val_bool (1);
2781 goto unlock;
2784 x += pdim->bounds.x0;
2785 y += pdim->bounds.y0;
2787 for (block = page->text->first_block; block; block = block->next) {
2788 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2789 b = &block->bbox;
2790 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2791 continue;
2793 if (mark == mark_block) {
2794 page->fmark = block->u.t.first_line->first_char;
2795 page->lmark = block->u.t.last_line->last_char;
2796 ret_v = Val_bool (1);
2797 goto unlock;
2800 for (line = block->u.t.first_line; line; line = line->next) {
2801 fz_stext_char *ch;
2803 b = &line->bbox;
2804 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2805 continue;
2807 if (mark == mark_line) {
2808 page->fmark = line->first_char;
2809 page->lmark = line->last_char;
2810 ret_v = Val_bool (1);
2811 goto unlock;
2814 for (ch = line->first_char; ch; ch = ch->next) {
2815 fz_stext_char *ch2, *first = NULL, *last = NULL;
2816 fz_quad *q = &ch->quad;
2817 if (x >= q->ul.x && x <= q->ur.x
2818 && y >= q->ul.y && y <= q->ll.y) {
2819 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2820 if (uninteresting (ch2->c)) first = NULL;
2821 else if (!first) first = ch2;
2823 for (ch2 = ch; ch2; ch2 = ch2->next) {
2824 if (uninteresting (ch2->c)) break;
2825 last = ch2;
2828 page->fmark = first;
2829 page->lmark = last;
2830 ret_v = Val_bool (1);
2831 goto unlock;
2836 unlock:
2837 if (!Bool_val (ret_v)) {
2838 page->fmark = NULL;
2839 page->lmark = NULL;
2841 unlock (__func__);
2843 done:
2844 CAMLreturn (ret_v);
2847 ML (rectofblock (value ptr_v, value x_v, value y_v))
2849 CAMLparam3 (ptr_v, x_v, y_v);
2850 CAMLlocal2 (ret_v, res_v);
2851 fz_rect *b = NULL;
2852 struct page *page;
2853 struct pagedim *pdim;
2854 fz_stext_block *block;
2855 const char *s = String_val (ptr_v);
2856 int x = Int_val (x_v), y = Int_val (y_v);
2858 ret_v = Val_int (0);
2859 if (trylock (__func__)) {
2860 goto done;
2863 page = parse_pointer (__func__, s);
2864 pdim = &state.pagedims[page->pdimno];
2865 x += pdim->bounds.x0;
2866 y += pdim->bounds.y0;
2868 ensuretext (page);
2870 for (block = page->text->first_block; block; block = block->next) {
2871 switch (block->type) {
2872 case FZ_STEXT_BLOCK_TEXT:
2873 b = &block->bbox;
2874 break;
2876 case FZ_STEXT_BLOCK_IMAGE:
2877 b = &block->bbox;
2878 break;
2880 default:
2881 continue;
2884 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2885 break;
2886 b = NULL;
2888 if (b) {
2889 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2890 ret_v = caml_alloc_small (1, 1);
2891 Store_double_field (res_v, 0, (double) b->x0);
2892 Store_double_field (res_v, 1, (double) b->x1);
2893 Store_double_field (res_v, 2, (double) b->y0);
2894 Store_double_field (res_v, 3, (double) b->y1);
2895 Field (ret_v, 0) = res_v;
2897 unlock (__func__);
2899 done:
2900 CAMLreturn (ret_v);
2903 ML0 (seltext (value ptr_v, value rect_v))
2905 CAMLparam2 (ptr_v, rect_v);
2906 struct page *page;
2907 struct pagedim *pdim;
2908 const char *s = String_val (ptr_v);
2909 int x0, x1, y0, y1;
2910 fz_stext_char *ch;
2911 fz_stext_line *line;
2912 fz_stext_block *block;
2913 fz_stext_char *fc, *lc;
2915 if (trylock (__func__)) {
2916 goto done;
2919 page = parse_pointer (__func__, s);
2920 ensuretext (page);
2922 pdim = &state.pagedims[page->pdimno];
2923 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2924 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2925 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2926 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2928 if (y0 > y1) {
2929 int t = y0;
2930 y0 = y1;
2931 y1 = t;
2932 x0 = x1;
2933 x1 = t;
2936 fc = page->fmark;
2937 lc = page->lmark;
2939 for (block = page->text->first_block; block; block = block->next) {
2940 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2941 for (line = block->u.t.first_line; line; line = line->next) {
2942 for (ch = line->first_char; ch; ch = ch->next) {
2943 fz_quad q = ch->quad;
2944 if (x0 >= q.ul.x && x0 <= q.ur.x
2945 && y0 >= q.ul.y && y0 <= q.ll.y) {
2946 fc = ch;
2948 if (x1 >= q.ul.x && x1 <= q.ur.x
2949 && y1 >= q.ul.y && y1 <= q.ll.y) {
2950 lc = ch;
2955 if (x1 < x0 && fc == lc) {
2956 fz_stext_char *t;
2958 t = fc;
2959 fc = lc;
2960 lc = t;
2963 page->fmark = fc;
2964 page->lmark = lc;
2966 unlock (__func__);
2968 done:
2969 CAMLreturn0;
2972 static int pipechar (FILE *f, fz_stext_char *ch)
2974 char buf[4];
2975 int len;
2976 size_t ret;
2978 len = fz_runetochar (buf, ch->c);
2979 ret = fwrite (buf, len, 1, f);
2980 if (ret != 1) {
2981 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
2982 len, ret, errno, strerror (errno));
2983 return -1;
2985 return 0;
2988 ML (spawn (value command_v, value fds_v))
2990 CAMLparam2 (command_v, fds_v);
2991 CAMLlocal2 (l_v, tup_v);
2992 int ret, ret1;
2993 pid_t pid = (pid_t) -1;
2994 char *msg = NULL;
2995 value earg_v = Nothing;
2996 posix_spawnattr_t attr;
2997 posix_spawn_file_actions_t fa;
2998 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3000 argv[2] = &Byte (command_v, 0);
3001 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3002 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3005 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3006 msg = "posix_spawnattr_init";
3007 goto fail1;
3010 #ifdef POSIX_SPAWN_USEVFORK
3011 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3012 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3013 goto fail;
3015 #endif
3017 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3018 int fd1, fd2;
3020 tup_v = Field (l_v, 0);
3021 fd1 = Int_val (Field (tup_v, 0));
3022 fd2 = Int_val (Field (tup_v, 1));
3023 if (fd2 < 0) {
3024 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3025 msg = "posix_spawn_file_actions_addclose";
3026 earg_v = tup_v;
3027 goto fail;
3030 else {
3031 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3032 msg = "posix_spawn_file_actions_adddup2";
3033 earg_v = tup_v;
3034 goto fail;
3039 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3040 msg = "posix_spawn";
3041 goto fail;
3044 fail:
3045 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3046 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3049 fail1:
3050 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3051 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3052 ret1, strerror (ret1));
3055 if (msg)
3056 unix_error (ret, msg, earg_v);
3058 CAMLreturn (Val_int (pid));
3061 ML (hassel (value ptr_v))
3063 CAMLparam1 (ptr_v);
3064 CAMLlocal1 (ret_v);
3065 struct page *page;
3066 const char *s = String_val (ptr_v);
3068 ret_v = Val_bool (0);
3069 if (trylock (__func__)) {
3070 goto done;
3073 page = parse_pointer (__func__, s);
3074 ret_v = Val_bool (page->fmark && page->lmark);
3075 unlock (__func__);
3076 done:
3077 CAMLreturn (ret_v);
3080 ML0 (copysel (value fd_v, value ptr_v))
3082 CAMLparam2 (fd_v, ptr_v);
3083 FILE *f;
3084 int seen = 0;
3085 struct page *page;
3086 fz_stext_line *line;
3087 fz_stext_block *block;
3088 int fd = Int_val (fd_v);
3089 const char *s = String_val (ptr_v);
3091 if (trylock (__func__)) {
3092 goto done;
3095 page = parse_pointer (__func__, s);
3097 if (!page->fmark || !page->lmark) {
3098 printd ("emsg nothing to copy on page %d", page->pageno);
3099 goto unlock;
3102 f = fdopen (fd, "w");
3103 if (!f) {
3104 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3105 fd, errno, strerror (errno));
3106 f = stdout;
3109 for (block = page->text->first_block; block; block = block->next) {
3110 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3111 for (line = block->u.t.first_line; line; line = line->next) {
3112 fz_stext_char *ch;
3113 for (ch = line->first_char; ch; ch = ch->next) {
3114 if (seen || ch == page->fmark) {
3115 do {
3116 pipechar (f, ch);
3117 if (ch == page->lmark) goto close;
3118 } while ((ch = ch->next));
3119 seen = 1;
3120 break;
3123 if (seen) fputc ('\n', f);
3126 close:
3127 if (f != stdout) {
3128 int ret = fclose (f);
3129 fd = -1;
3130 if (ret == -1) {
3131 if (errno != ECHILD) {
3132 printd ("emsg failed to close sel pipe: %d:%s",
3133 errno, strerror (errno));
3137 unlock:
3138 unlock (__func__);
3140 done:
3141 if (fd >= 0) {
3142 if (close (fd)) {
3143 printd ("emsg failed to close sel pipe: %d:%s",
3144 errno, strerror (errno));
3147 CAMLreturn0;
3150 ML (getpdimrect (value pagedimno_v))
3152 CAMLparam1 (pagedimno_v);
3153 CAMLlocal1 (ret_v);
3154 int pagedimno = Int_val (pagedimno_v);
3155 fz_rect box;
3157 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3158 if (trylock (__func__)) {
3159 box = fz_empty_rect;
3161 else {
3162 box = state.pagedims[pagedimno].mediabox;
3163 unlock (__func__);
3166 Store_double_field (ret_v, 0, (double) box.x0);
3167 Store_double_field (ret_v, 1, (double) box.x1);
3168 Store_double_field (ret_v, 2, (double) box.y0);
3169 Store_double_field (ret_v, 3, (double) box.y1);
3171 CAMLreturn (ret_v);
3174 ML (zoom_for_height (value winw_v, value winh_v, value dw_v, value cols_v))
3176 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3177 CAMLlocal1 (ret_v);
3178 int i;
3179 float zoom = -1.;
3180 float maxh = 0.0;
3181 struct pagedim *p;
3182 float winw = Int_val (winw_v);
3183 float winh = Int_val (winh_v);
3184 float dw = Int_val (dw_v);
3185 float cols = Int_val (cols_v);
3186 float pw = 1.0, ph = 1.0;
3188 if (trylock (__func__)) {
3189 goto done;
3192 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3193 float w = p->pagebox.x1 / cols;
3194 float h = p->pagebox.y1;
3195 if (h > maxh) {
3196 maxh = h;
3197 ph = h;
3198 if (state.fitmodel != FitProportional) pw = w;
3200 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3203 zoom = (((winh / ph) * pw) + dw) / winw;
3204 unlock (__func__);
3205 done:
3206 ret_v = caml_copy_double ((double) zoom);
3207 CAMLreturn (ret_v);
3210 ML (getmaxw (value unit_v))
3212 CAMLparam1 (unit_v);
3213 CAMLlocal1 (ret_v);
3214 int i;
3215 float maxw = -1.;
3216 struct pagedim *p;
3218 if (trylock (__func__)) {
3219 goto done;
3222 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3223 float w = p->pagebox.x1;
3224 maxw = fz_max (maxw, w);
3227 unlock (__func__);
3228 done:
3229 ret_v = caml_copy_double ((double) maxw);
3230 CAMLreturn (ret_v);
3233 ML (draw_string (value pt_v, value x_v, value y_v, value string_v))
3235 CAMLparam4 (pt_v, x_v, y_v, string_v);
3236 CAMLlocal1 (ret_v);
3237 int pt = Int_val(pt_v);
3238 int x = Int_val (x_v);
3239 int y = Int_val (y_v);
3240 float w;
3242 w = draw_string (state.face, pt, x, y, String_val (string_v));
3243 ret_v = caml_copy_double (w);
3244 CAMLreturn (ret_v);
3247 ML (measure_string (value pt_v, value string_v))
3249 CAMLparam2 (pt_v, string_v);
3250 CAMLlocal1 (ret_v);
3251 int pt = Int_val (pt_v);
3252 double w;
3254 w = (double) measure_string (state.face, pt, String_val (string_v));
3255 ret_v = caml_copy_double (w);
3256 CAMLreturn (ret_v);
3259 ML (getpagebox (value opaque_v))
3261 CAMLparam1 (opaque_v);
3262 CAMLlocal1 (ret_v);
3263 fz_rect rect;
3264 fz_irect bbox;
3265 fz_device *dev;
3266 const char *s = String_val (opaque_v);
3267 struct page *page = parse_pointer (__func__, s);
3269 ret_v = caml_alloc_tuple (4);
3270 dev = fz_new_bbox_device (state.ctx, &rect);
3272 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3274 fz_close_device (state.ctx, dev);
3275 fz_drop_device (state.ctx, dev);
3276 bbox = fz_round_rect (rect);
3277 Field (ret_v, 0) = Val_int (bbox.x0);
3278 Field (ret_v, 1) = Val_int (bbox.y0);
3279 Field (ret_v, 2) = Val_int (bbox.x1);
3280 Field (ret_v, 3) = Val_int (bbox.y1);
3282 CAMLreturn (ret_v);
3285 ML0 (setaalevel (value level_v))
3287 CAMLparam1 (level_v);
3289 state.aalevel = Int_val (level_v);
3290 CAMLreturn0;
3293 ML0 (setpapercolor (value rgba_v))
3295 CAMLparam1 (rgba_v);
3297 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3298 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3299 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3300 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3301 CAMLreturn0;
3304 value ml_keysymtoutf8 (value keysym_v);
3305 #ifndef CIDER
3306 value ml_keysymtoutf8 (value keysym_v)
3308 CAMLparam1 (keysym_v);
3309 CAMLlocal1 (str_v);
3310 unsigned short keysym = (unsigned short) Int_val (keysym_v);
3311 Rune rune;
3312 extern long keysym2ucs (unsigned short);
3313 int len;
3314 char buf[5];
3316 rune = (Rune) keysym2ucs (keysym);
3317 len = fz_runetochar (buf, rune);
3318 buf[len] = 0;
3319 str_v = caml_copy_string (buf);
3320 CAMLreturn (str_v);
3322 #else
3323 value ml_keysymtoutf8 (value keysym_v)
3325 CAMLparam1 (keysym_v);
3326 CAMLlocal1 (str_v);
3327 long ucs = Long_val (keysym_v);
3328 int len;
3329 char buf[5];
3331 len = fz_runetochar (buf, (int) ucs);
3332 buf[len] = 0;
3333 str_v = caml_copy_string (buf);
3334 CAMLreturn (str_v);
3336 #endif
3338 enum { piunknown, pilinux, pimacos, pibsd };
3340 ML (platform (value unit_v))
3342 CAMLparam1 (unit_v);
3343 CAMLlocal2 (tup_v, arr_v);
3344 int platid = piunknown;
3345 struct utsname buf;
3347 #if defined __linux__
3348 platid = pilinux;
3349 #elif defined __DragonFly__ || defined __FreeBSD__
3350 || defined __OpenBSD__ || defined __NetBSD__
3351 platid = pibsd;
3352 #elif defined __APPLE__
3353 platid = pimacos;
3354 #endif
3355 if (uname (&buf)) err (1, "uname");
3357 tup_v = caml_alloc_tuple (2);
3359 char const *sar[] = {
3360 buf.sysname,
3361 buf.release,
3362 buf.version,
3363 buf.machine,
3364 NULL
3366 arr_v = caml_copy_string_array (sar);
3368 Field (tup_v, 0) = Val_int (platid);
3369 Field (tup_v, 1) = arr_v;
3370 CAMLreturn (tup_v);
3373 ML0 (cloexec (value fd_v))
3375 CAMLparam1 (fd_v);
3376 int fd = Int_val (fd_v);
3378 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3379 uerror ("fcntl", Nothing);
3381 CAMLreturn0;
3384 ML (getpbo (value w_v, value h_v, value cs_v))
3386 CAMLparam2 (w_v, h_v);
3387 CAMLlocal1 (ret_v);
3388 struct bo *pbo;
3389 int w = Int_val (w_v);
3390 int h = Int_val (h_v);
3391 int cs = Int_val (cs_v);
3393 if (state.bo_usable) {
3394 pbo = calloc (sizeof (*pbo), 1);
3395 if (!pbo) {
3396 err (1, "calloc pbo");
3399 switch (cs) {
3400 case 0:
3401 case 1:
3402 pbo->size = w*h*4;
3403 break;
3404 case 2:
3405 pbo->size = w*h*2;
3406 break;
3407 default:
3408 errx (1, "%s: invalid colorspace %d", __func__, cs);
3411 state.glGenBuffersARB (1, &pbo->id);
3412 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3413 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3414 NULL, GL_STREAM_DRAW);
3415 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3416 GL_READ_WRITE);
3417 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3418 if (!pbo->ptr) {
3419 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3420 state.glDeleteBuffersARB (1, &pbo->id);
3421 free (pbo);
3422 ret_v = caml_copy_string ("0");
3424 else {
3425 int res;
3426 char *s;
3428 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3429 if (res < 0) {
3430 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3432 s = malloc (res+1);
3433 if (!s) {
3434 err (1, "malloc %d bytes failed", res+1);
3436 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3437 if (res < 0) {
3438 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3440 ret_v = caml_copy_string (s);
3441 free (s);
3444 else {
3445 ret_v = caml_copy_string ("0");
3447 CAMLreturn (ret_v);
3450 ML0 (freepbo (value s_v))
3452 CAMLparam1 (s_v);
3453 const char *s = String_val (s_v);
3454 struct tile *tile = parse_pointer (__func__, s);
3456 if (tile->pbo) {
3457 state.glDeleteBuffersARB (1, &tile->pbo->id);
3458 tile->pbo->id = -1;
3459 tile->pbo->ptr = NULL;
3460 tile->pbo->size = -1;
3462 CAMLreturn0;
3465 ML0 (unmappbo (value s_v))
3467 CAMLparam1 (s_v);
3468 const char *s = String_val (s_v);
3469 struct tile *tile = parse_pointer (__func__, s);
3471 if (tile->pbo) {
3472 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3473 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3474 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3476 tile->pbo->ptr = NULL;
3477 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3479 CAMLreturn0;
3482 static void setuppbo (void)
3484 extern void (*wsigladdr (const char *name)) (void);
3485 #pragma GCC diagnostic push
3486 #ifdef __clang__
3487 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3488 #endif
3489 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3490 state.bo_usable = GPA (glBindBufferARB)
3491 && GPA (glUnmapBufferARB)
3492 && GPA (glMapBufferARB)
3493 && GPA (glBufferDataARB)
3494 && GPA (glGenBuffersARB)
3495 && GPA (glDeleteBuffersARB);
3496 #undef GPA
3497 #pragma GCC diagnostic pop
3500 ML (bo_usable (void))
3502 return Val_bool (state.bo_usable);
3505 ML (unproject (value ptr_v, value x_v, value y_v))
3507 CAMLparam3 (ptr_v, x_v, y_v);
3508 CAMLlocal2 (ret_v, tup_v);
3509 struct page *page;
3510 const char *s = String_val (ptr_v);
3511 int x = Int_val (x_v), y = Int_val (y_v);
3512 struct pagedim *pdim;
3513 fz_point p;
3515 page = parse_pointer (__func__, s);
3516 pdim = &state.pagedims[page->pdimno];
3518 ret_v = Val_int (0);
3519 if (trylock (__func__)) {
3520 goto done;
3523 p.x = x + pdim->bounds.x0;
3524 p.y = y + pdim->bounds.y0;
3526 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3527 pdim->ctm)));
3529 tup_v = caml_alloc_tuple (2);
3530 ret_v = caml_alloc_small (1, 1);
3531 Field (tup_v, 0) = Val_int (p.x);
3532 Field (tup_v, 1) = Val_int (p.y);
3533 Field (ret_v, 0) = tup_v;
3535 unlock (__func__);
3536 done:
3537 CAMLreturn (ret_v);
3540 ML (project (value ptr_v, value pageno_v, value pdimno_v, value x_v, value y_v))
3542 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3543 CAMLlocal1 (ret_v);
3544 struct page *page;
3545 const char *s = String_val (ptr_v);
3546 int pageno = Int_val (pageno_v);
3547 int pdimno = Int_val (pdimno_v);
3548 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3549 struct pagedim *pdim;
3550 fz_point p;
3551 fz_matrix ctm;
3553 ret_v = Val_int (0);
3554 lock (__func__);
3556 if (!*s) {
3557 page = loadpage (pageno, pdimno);
3559 else {
3560 page = parse_pointer (__func__, s);
3562 pdim = &state.pagedims[pdimno];
3564 if (pdf_specifics (state.ctx, state.doc)) {
3565 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3566 ctm = state.pagedims[page->pdimno].tctm;
3568 else {
3569 ctm = fz_identity;
3571 p.x = x + pdim->bounds.x0;
3572 p.y = y + pdim->bounds.y0;
3574 ctm = fz_concat (pdim->tctm, pdim->ctm);
3575 p = fz_transform_point (p, ctm);
3577 ret_v = caml_alloc_tuple (2);
3578 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3579 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3581 if (!*s) {
3582 freepage (page);
3584 unlock (__func__);
3585 CAMLreturn (ret_v);
3588 ML0 (addannot (value ptr_v, value x_v, value y_v, value contents_v))
3590 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3591 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3593 if (pdf) {
3594 pdf_annot *annot;
3595 struct page *page;
3596 fz_rect r;
3597 const char *s = String_val (ptr_v);
3599 page = parse_pointer (__func__, s);
3600 annot = pdf_create_annot (state.ctx,
3601 pdf_page_from_fz_page (state.ctx,
3602 page->fzpage),
3603 PDF_ANNOT_TEXT);
3604 r.x0 = Int_val (x_v) - 10;
3605 r.y0 = Int_val (y_v) - 10;
3606 r.x1 = r.x0 + 20;
3607 r.y1 = r.y0 + 20;
3608 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3609 pdf_set_annot_rect (state.ctx, annot, r);
3611 state.dirty = 1;
3613 CAMLreturn0;
3616 ML0 (delannot (value ptr_v, value n_v))
3618 CAMLparam2 (ptr_v, n_v);
3619 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3621 if (pdf) {
3622 struct page *page;
3623 const char *s = String_val (ptr_v);
3624 struct slink *slink;
3626 page = parse_pointer (__func__, s);
3627 slink = &page->slinks[Int_val (n_v)];
3628 pdf_delete_annot (state.ctx,
3629 pdf_page_from_fz_page (state.ctx, page->fzpage),
3630 (pdf_annot *) slink->u.annot);
3631 state.dirty = 1;
3633 CAMLreturn0;
3636 ML0 (modannot (value ptr_v, value n_v, value str_v))
3638 CAMLparam3 (ptr_v, n_v, str_v);
3639 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3641 if (pdf) {
3642 struct page *page;
3643 const char *s = String_val (ptr_v);
3644 struct slink *slink;
3646 page = parse_pointer (__func__, s);
3647 slink = &page->slinks[Int_val (n_v)];
3648 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3649 String_val (str_v));
3650 state.dirty = 1;
3652 CAMLreturn0;
3655 ML (hasunsavedchanges (void))
3657 return Val_bool (state.dirty);
3660 ML0 (savedoc (value path_v))
3662 CAMLparam1 (path_v);
3663 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3665 if (pdf) {
3666 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3668 CAMLreturn0;
3671 static void makestippletex (void)
3673 const char pixels[] = "\xff\xff\0\0";
3674 glGenTextures (1, &state.stid);
3675 glBindTexture (GL_TEXTURE_1D, state.stid);
3676 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3677 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3678 glTexImage1D (
3679 GL_TEXTURE_1D,
3681 GL_ALPHA,
3684 GL_ALPHA,
3685 GL_UNSIGNED_BYTE,
3686 pixels
3690 ML (fz_version (void))
3692 return caml_copy_string (FZ_VERSION);
3695 ML (llpp_version (void))
3697 extern char llpp_version[];
3698 return caml_copy_string (llpp_version);
3701 static void diag_callback (void *user, const char *message)
3703 printd ("emsg %s %s", (char *) user, message);
3706 static fz_font *lsff (fz_context *ctx,int UNUSED_ATTR script,
3707 int UNUSED_ATTR language, int UNUSED_ATTR serif,
3708 int UNUSED_ATTR bold, int UNUSED_ATTR italic)
3710 static fz_font *font;
3711 static int done;
3713 if (!done) {
3714 char *path = getenv ("LLPP_FALLBACK_FONT");
3715 if (path) font = fz_new_font_from_file (ctx, NULL, path, 0, 1);
3716 done = 1;
3718 return font;
3721 ML0 (settrimcachepath (value path_v))
3723 CAMLparam1 (path_v);
3724 const char *path = String_val (path_v);
3726 if (!path || !strlen (path)) {
3727 free (state.trimcachepath);
3728 state.trimcachepath = NULL;
3730 else {
3731 free (state.trimcachepath);
3732 state.trimcachepath = ystrdup (path);
3734 if (!state.trimcachepath) {
3735 printd ("emsg failed to strdup trimcachepath: %d:%s",
3736 errno, strerror (errno));
3739 CAMLreturn0;
3742 ML0 (init (value csock_v, value params_v))
3744 CAMLparam2 (csock_v, params_v);
3745 CAMLlocal2 (trim_v, fuzz_v);
3746 int ret;
3747 int texcount;
3748 const char *fontpath;
3749 int colorspace;
3750 int mustoresize;
3752 state.csock = Int_val (csock_v);
3753 state.rotate = Int_val (Field (params_v, 0));
3754 state.fitmodel = Int_val (Field (params_v, 1));
3755 trim_v = Field (params_v, 2);
3756 texcount = Int_val (Field (params_v, 3));
3757 state.sliceheight = Int_val (Field (params_v, 4));
3758 mustoresize = Int_val (Field (params_v, 5));
3759 colorspace = Int_val (Field (params_v, 6));
3760 fontpath = String_val (Field (params_v, 7));
3762 #ifdef CIDER
3763 state.utf8cs = 1;
3764 #else
3765 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3766 if (setlocale (LC_CTYPE, "")) {
3767 const char *cset = nl_langinfo (CODESET);
3768 state.utf8cs = !strcmp (cset, "UTF-8");
3770 else {
3771 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3773 #endif
3775 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3776 fz_register_document_handlers (state.ctx);
3777 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3778 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3779 fz_install_load_system_font_funcs (state.ctx, NULL, NULL, lsff);
3781 state.trimmargins = Bool_val (Field (trim_v, 0));
3782 fuzz_v = Field (trim_v, 1);
3783 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3784 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3785 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3786 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3788 set_tex_params (colorspace);
3790 if (*fontpath) {
3791 state.face = load_font (fontpath);
3793 else {
3794 int len;
3795 const unsigned char *data;
3797 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3798 state.face = load_builtin_font (data, len);
3800 if (!state.face) _exit (1);
3802 realloctexts (texcount);
3803 setuppbo ();
3804 makestippletex ();
3806 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3807 if (ret) {
3808 errx (1, "pthread_create: %s", strerror (ret));
3811 CAMLreturn0;
3814 #if FIXME || !FIXME
3815 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3816 #endif