Fixed data structure corruption in the navigation history.
[llpp.git] / link.c
blob04cabd5d3ee00c818d5fd2c99656b661ffe430ea
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 = NULL;
644 fz_var (p);
645 fz_var (trimw);
646 fz_var (trimf);
647 fz_var (cxcount);
649 if (state.trimmargins && state.trimcachepath) {
650 trimf = fopen (state.trimcachepath, "rb");
651 if (!trimf) {
652 trimf = fopen (state.trimcachepath, "wb");
653 trimw = 1;
656 else {
657 pdf = pdf_specifics (ctx, state.doc);
660 cxcount = state.pagecount;
661 if (pdf) {
662 pdf_obj *obj;
663 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
664 "Root/Pages/MediaBox");
665 rootmediabox = pdf_to_rect (ctx, obj);
666 pdf_load_page_tree (ctx, pdf);
669 for (pageno = 0; pageno < cxcount; ++pageno) {
670 int rotate = 0;
671 fz_rect mediabox = fz_empty_rect;
673 fz_var (rotate);
674 if (pdf) {
675 pdf_obj *pageobj = NULL;
677 fz_var (pageobj);
678 if (pdf->rev_page_map) {
679 for (int i = 0; i < pdf->rev_page_count; ++i) {
680 if (pdf->rev_page_map[i].page == pageno) {
681 pageobj = pdf_get_xref_entry (
682 ctx, pdf, pdf->rev_page_map[i].object
683 )->obj;
684 break;
688 if (!pageobj) {
689 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
692 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
694 if (state.trimmargins) {
695 pdf_obj *obj;
696 pdf_page *page;
698 fz_try (ctx) {
699 page = pdf_load_page (ctx, pdf, pageno);
700 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
701 trim = state.trimanew || !obj;
702 if (trim) {
703 fz_rect rect;
704 fz_device *dev;
705 fz_matrix ctm, page_ctm;
707 dev = fz_new_bbox_device (ctx, &rect);
708 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
709 ctm = fz_invert_matrix (page_ctm);
710 pdf_run_page (ctx, page, dev, fz_identity, NULL);
711 fz_close_device (ctx, dev);
712 fz_drop_device (ctx, dev);
714 rect.x0 += state.trimfuzz.x0;
715 rect.x1 += state.trimfuzz.x1;
716 rect.y0 += state.trimfuzz.y0;
717 rect.y1 += state.trimfuzz.y1;
718 rect = fz_transform_rect (rect, ctm);
719 rect = fz_intersect_rect (rect, mediabox);
721 if (!fz_is_empty_rect (rect)) {
722 mediabox = rect;
725 obj = pdf_new_array (ctx, pdf, 4);
726 pdf_array_push_real (ctx, obj, mediabox.x0);
727 pdf_array_push_real (ctx, obj, mediabox.y0);
728 pdf_array_push_real (ctx, obj, mediabox.x1);
729 pdf_array_push_real (ctx, obj, mediabox.y1);
730 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
732 else {
733 mediabox.x0 = pdf_array_get_real (ctx, obj, 0);
734 mediabox.y0 = pdf_array_get_real (ctx, obj, 1);
735 mediabox.x1 = pdf_array_get_real (ctx, obj, 2);
736 mediabox.y1 = pdf_array_get_real (ctx, obj, 3);
739 fz_drop_page (ctx, &page->super);
740 show = (pageno + 1 == state.pagecount)
741 || (trim ? pageno % 5 == 0 : pageno % 20 == 0);
742 if (show) {
743 printd ("progress %f Trimming %d",
744 (double) (pageno + 1) / state.pagecount,
745 pageno + 1);
748 fz_catch (ctx) {
749 printd ("emsg failed to load page %d", pageno);
752 else {
753 int empty = 0;
754 fz_rect cropbox;
756 mediabox =
757 pdf_to_rect (ctx, pdf_dict_get_inheritable (
758 ctx,
759 pageobj,
760 PDF_NAME (MediaBox)
763 if (fz_is_empty_rect (mediabox)) {
764 mediabox.x0 = 0;
765 mediabox.y0 = 0;
766 mediabox.x1 = 612;
767 mediabox.y1 = 792;
768 empty = 1;
771 cropbox =
772 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
773 if (!fz_is_empty_rect (cropbox)) {
774 if (empty) {
775 mediabox = cropbox;
777 else {
778 mediabox = fz_intersect_rect (mediabox, cropbox);
781 else {
782 if (empty) {
783 if (fz_is_empty_rect (rootmediabox)) {
784 printd ("emsg cannot find page size for page %d",
785 pageno);
787 else {
788 mediabox = rootmediabox;
794 else {
795 if (state.trimmargins && trimw) {
796 fz_page *page;
798 fz_try (ctx) {
799 page = fz_load_page (ctx, state.doc, pageno);
800 mediabox = fz_bound_page (ctx, page);
801 if (state.trimmargins) {
802 fz_rect rect;
803 fz_device *dev;
805 dev = fz_new_bbox_device (ctx, &rect);
806 fz_run_page (ctx, page, dev, fz_identity, NULL);
807 fz_close_device (ctx, dev);
808 fz_drop_device (ctx, dev);
810 rect.x0 += state.trimfuzz.x0;
811 rect.x1 += state.trimfuzz.x1;
812 rect.y0 += state.trimfuzz.y0;
813 rect.y1 += state.trimfuzz.y1;
814 rect = fz_intersect_rect (rect, mediabox);
816 if (!fz_is_empty_rect (rect)) {
817 mediabox = rect;
820 fz_drop_page (ctx, page);
822 fz_catch (ctx) {
824 if (trimf) {
825 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
826 if (n - 1) {
827 err (1, "fwrite trim mediabox");
831 else {
832 if (trimf) {
833 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
834 if (n - 1) {
835 err (1, "fread trim mediabox %d", pageno);
838 else {
839 fz_page *page;
840 fz_try (ctx) {
841 page = fz_load_page (ctx, state.doc, pageno);
842 mediabox = fz_bound_page (ctx, page);
843 fz_drop_page (ctx, page);
845 show = !state.trimmargins && pageno % 20 == 0;
846 if (show) {
847 printd ("progress %f Gathering dimensions %d",
848 (double) (pageno) / state.pagecount,
849 pageno);
852 fz_catch (ctx) {
853 printd ("emsg failed to load page %d", pageno);
859 if (!p || p->rotate != rotate
860 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
861 size_t size;
863 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
864 state.pagedims = realloc (state.pagedims, size);
865 if (!state.pagedims) {
866 err (1, "realloc pagedims to %zu (%d elems)",
867 size, state.pagedimcount + 1);
870 p = &state.pagedims[state.pagedimcount++];
871 p->rotate = rotate;
872 p->mediabox = mediabox;
873 p->pageno = pageno;
876 state.trimanew = 0;
877 if (trimf) {
878 if (fclose (trimf)) {
879 err (1, "fclose");
884 static void layout (void)
886 int pindex;
887 fz_rect box;
888 fz_matrix ctm;
889 struct pagedim *p = NULL;
890 float zw, w, maxw = 0.0, zoom = 1.0;
892 if (state.pagedimcount == 0) return;
894 switch (state.fitmodel) {
895 case FitProportional:
896 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
897 float x0, x1;
899 p = &state.pagedims[pindex];
900 box = fz_transform_rect (p->mediabox,
901 fz_rotate (p->rotate + state.rotate));
903 x0 = fz_min (box.x0, box.x1);
904 x1 = fz_max (box.x0, box.x1);
906 w = x1 - x0;
907 maxw = fz_max (w, maxw);
908 zoom = state.w / maxw;
910 break;
912 case FitPage:
913 maxw = state.w;
914 break;
916 case FitWidth:
917 break;
919 default:
920 ARSERT (0 && state.fitmodel);
923 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
924 p = &state.pagedims[pindex];
925 ctm = fz_rotate (state.rotate);
926 box = fz_transform_rect (p->mediabox,
927 fz_rotate (p->rotate + state.rotate));
928 w = box.x1 - box.x0;
929 switch (state.fitmodel) {
930 case FitProportional:
931 p->left = (int) (((maxw - w) * zoom) / 2.f);
932 break;
933 case FitPage:
935 float zh, h;
936 zw = maxw / w;
937 h = box.y1 - box.y0;
938 zh = state.h / h;
939 zoom = fz_min (zw, zh);
940 p->left = (int) ((maxw - (w * zoom)) / 2.f);
942 break;
943 case FitWidth:
944 p->left = 0;
945 zoom = state.w / w;
946 break;
949 p->zoomctm = fz_scale (zoom, zoom);
950 ctm = fz_concat (p->zoomctm, ctm);
952 p->pagebox = p->mediabox;
953 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
954 p->pagebox.x1 -= p->pagebox.x0;
955 p->pagebox.y1 -= p->pagebox.y0;
956 p->pagebox.x0 = 0;
957 p->pagebox.y0 = 0;
958 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
959 p->ctm = ctm;
961 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
962 fz_scale (zoom, -zoom));
963 p->tctmready = 0;
966 do {
967 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
968 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
969 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
970 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
971 int boundw = x1 - x0;
972 int boundh = y1 - y0;
974 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
975 } while (p-- != state.pagedims);
978 static struct pagedim *pdimofpageno (int pageno)
980 struct pagedim *pdim = state.pagedims;
982 for (int i = 0; i < state.pagedimcount; ++i) {
983 if (state.pagedims[i].pageno > pageno)
984 break;
985 pdim = &state.pagedims[i];
987 return pdim;
990 static void recurse_outline (fz_outline *outline, int level)
992 while (outline) {
993 if (outline->page >= 0) {
994 fz_point p = {.x = outline->x, .y = outline->y};
995 struct pagedim *pdim = pdimofpageno (outline->page);
996 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
997 p = fz_transform_point (p, pdim->ctm);
998 printd ("o %d %d %d %d %s",
999 level, outline->page, (int) p.y, h, outline->title);
1001 else {
1002 printd ("on %d %s", level, outline->title);
1004 if (outline->down) {
1005 recurse_outline (outline->down, level + 1);
1007 outline = outline->next;
1011 static void process_outline (void)
1013 fz_outline *outline;
1015 if (!state.needoutline || !state.pagedimcount) return;
1017 state.needoutline = 0;
1018 outline = fz_load_outline (state.ctx, state.doc);
1019 if (outline) {
1020 recurse_outline (outline, 0);
1021 fz_drop_outline (state.ctx, outline);
1025 static char *strofline (fz_stext_line *line)
1027 char *p;
1028 char utf8[10];
1029 fz_stext_char *ch;
1030 size_t size = 0, cap = 80;
1032 p = malloc (cap + 1);
1033 if (!p) return NULL;
1035 for (ch = line->first_char; ch; ch = ch->next) {
1036 int n = fz_runetochar (utf8, ch->c);
1037 if (size + n > cap) {
1038 cap *= 2;
1039 p = realloc (p, cap + 1);
1040 if (!p) return NULL;
1043 memcpy (p + size, utf8, n);
1044 size += n;
1046 p[size] = 0;
1047 return p;
1050 static int matchline (regex_t *re, fz_stext_line *line,
1051 int stop, int pageno, double start)
1053 int ret;
1054 char *p;
1055 regmatch_t rm;
1057 p = strofline (line);
1058 if (!p) return -1;
1060 ret = regexec (re, p, 1, &rm, 0);
1061 if (ret) {
1062 free (p);
1063 if (ret != REG_NOMATCH) {
1064 size_t size;
1065 char errbuf[80];
1066 size = regerror (ret, re, errbuf, sizeof (errbuf));
1067 printd ("msg regexec error `%.*s'",
1068 (int) size, errbuf);
1069 return -1;
1071 return 0;
1073 else {
1074 fz_quad s, e;
1075 fz_stext_char *ch;
1076 int o = 0;
1078 for (ch = line->first_char; ch; ch = ch->next) {
1079 o += fz_runelen (ch->c);
1080 if (o > rm.rm_so) {
1081 s = ch->quad;
1082 break;
1085 for (;ch; ch = ch->next) {
1086 o += fz_runelen (ch->c);
1087 if (o > rm.rm_eo) break;
1089 e = ch->quad;
1091 if (!stop) {
1092 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1093 pageno, 1,
1094 s.ul.x, s.ul.y,
1095 e.ur.x, s.ul.y,
1096 e.lr.x, e.lr.y,
1097 s.ul.x, e.lr.y);
1099 printd ("progress 1 found at %d `%.*s' in %f sec",
1100 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1101 now () - start);
1103 else {
1104 printd ("match %d %d %f %f %f %f %f %f %f %f",
1105 pageno, 2,
1106 s.ul.x, s.ul.y,
1107 e.ur.x, s.ul.y,
1108 e.lr.x, e.lr.y,
1109 s.ul.x, e.lr.y);
1111 free (p);
1112 return 1;
1116 /* wishful thinking function */
1117 static void search (regex_t *re, int pageno, int y, int forward)
1119 fz_device *tdev;
1120 fz_stext_page *text;
1121 struct pagedim *pdim;
1122 int stop = 0, niters = 0;
1123 double start, end;
1124 fz_page *page;
1125 fz_stext_block *block;
1127 start = now ();
1128 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1129 if (niters++ == 5) {
1130 niters = 0;
1131 if (hasdata ()) {
1132 printd ("progress 1 attention requested aborting search at %d",
1133 pageno);
1134 stop = 1;
1136 else {
1137 printd ("progress %f searching in page %d",
1138 (double) (pageno + 1) / state.pagecount,
1139 pageno);
1142 pdim = pdimofpageno (pageno);
1143 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1144 tdev = fz_new_stext_device (state.ctx, text, 0);
1146 page = fz_load_page (state.ctx, state.doc, pageno);
1147 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1149 fz_close_device (state.ctx, tdev);
1150 fz_drop_device (state.ctx, tdev);
1152 if (forward) {
1153 for (block = text->first_block; block; block = block->next) {
1154 fz_stext_line *line;
1156 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1157 for (line = block->u.t.first_line; line; line = line->next) {
1158 if (line->bbox.y0 < y + 1) continue;
1160 switch (matchline (re, line, stop, pageno, start)) {
1161 case 0: break;
1162 case 1: stop = 1; break;
1163 case -1: stop = 1; goto endloop;
1168 else {
1169 for (block = text->last_block; block; block = block->prev) {
1170 fz_stext_line *line;
1172 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1173 for (line = block->u.t.last_line; line; line = line->prev) {
1174 if (line->bbox.y0 < y + 1) continue;
1176 switch (matchline (re, line, stop, pageno, start)) {
1177 case 0: break;
1178 case 1: stop = 1; break;
1179 case -1: stop = 1; goto endloop;
1185 if (forward) {
1186 pageno += 1;
1187 y = 0;
1189 else {
1190 pageno -= 1;
1191 y = INT_MAX;
1193 endloop:
1194 fz_drop_stext_page (state.ctx, text);
1195 fz_drop_page (state.ctx, page);
1197 end = now ();
1198 if (!stop) {
1199 printd ("progress 1 no matches %f sec", end - start);
1201 printd ("clearrects");
1204 static void set_tex_params (int colorspace)
1206 switch (colorspace) {
1207 case 0:
1208 state.texiform = GL_RGBA8;
1209 state.texform = GL_RGBA;
1210 state.texty = GL_UNSIGNED_BYTE;
1211 state.colorspace = fz_device_rgb (state.ctx);
1212 break;
1213 case 1:
1214 state.texiform = GL_LUMINANCE_ALPHA;
1215 state.texform = GL_LUMINANCE_ALPHA;
1216 state.texty = GL_UNSIGNED_BYTE;
1217 state.colorspace = fz_device_gray (state.ctx);
1218 break;
1219 default:
1220 errx (1, "invalid colorspce %d", colorspace);
1224 static void realloctexts (int texcount)
1226 size_t size;
1228 if (texcount == state.texcount) return;
1230 if (texcount < state.texcount) {
1231 glDeleteTextures (state.texcount - texcount,
1232 state.texids + texcount);
1235 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1236 state.texids = realloc (state.texids, size);
1237 if (!state.texids) {
1238 err (1, "realloc texs %zu", size);
1241 state.texowners = (void *) (state.texids + texcount);
1242 if (texcount > state.texcount) {
1243 glGenTextures (texcount - state.texcount,
1244 state.texids + state.texcount);
1245 for (int i = state.texcount; i < texcount; ++i) {
1246 state.texowners[i].w = -1;
1247 state.texowners[i].slice = NULL;
1250 state.texcount = texcount;
1251 state.texindex = 0;
1254 static char *mbtoutf8 (char *s)
1256 char *p, *r;
1257 wchar_t *tmp;
1258 size_t i, ret, len;
1260 if (state.utf8cs) {
1261 return s;
1264 len = mbstowcs (NULL, s, strlen (s));
1265 if (len == 0 || len == (size_t) -1) {
1266 if (len)
1267 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1268 return s;
1271 tmp = calloc (len, sizeof (wchar_t));
1272 if (!tmp) {
1273 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1274 len, sizeof (wchar_t), errno, strerror (errno));
1275 return s;
1278 ret = mbstowcs (tmp, s, len);
1279 if (ret == (size_t) -1) {
1280 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1281 len, errno, strerror (errno));
1282 free (tmp);
1283 return s;
1286 len = 0;
1287 for (i = 0; i < ret; ++i) {
1288 len += fz_runelen (tmp[i]);
1291 p = r = malloc (len + 1);
1292 if (!r) {
1293 printd ("emsg mbtoutf8: malloc(%zu)", len);
1294 free (tmp);
1295 return s;
1298 for (i = 0; i < ret; ++i) {
1299 p += fz_runetochar (p, tmp[i]);
1301 *p = 0;
1302 free (tmp);
1303 return r;
1306 ML (mbtoutf8 (value s_v))
1308 CAMLparam1 (s_v);
1309 CAMLlocal1 (ret_v);
1310 char *s, *r;
1312 s = &Byte (s_v, 0);
1313 r = mbtoutf8 (s);
1314 if (r == s) {
1315 ret_v = s_v;
1317 else {
1318 ret_v = caml_copy_string (r);
1319 free (r);
1321 CAMLreturn (ret_v);
1324 static void * mainloop (void UNUSED_ATTR *unused)
1326 char *p = NULL;
1327 int len, ret, oldlen = 0;
1329 fz_var (p);
1330 fz_var (oldlen);
1331 for (;;) {
1332 len = readlen (state.csock);
1333 if (len == 0) {
1334 errx (1, "readlen returned 0");
1337 if (oldlen < len + 1) {
1338 p = realloc (p, len + 1);
1339 if (!p) {
1340 err (1, "realloc %d failed", len + 1);
1342 oldlen = len + 1;
1344 readdata (state.csock, p, len);
1345 p[len] = 0;
1347 if (!strncmp ("open", p, 4)) {
1348 int off, usedoccss, ok = 0, layouth;
1349 char *password;
1350 char *filename;
1351 char *utf8filename;
1352 size_t filenamelen;
1354 fz_var (ok);
1355 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1356 if (ret != 2) {
1357 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1360 filename = p + 5 + off;
1361 filenamelen = strlen (filename);
1362 password = filename + filenamelen + 1;
1364 if (password[strlen (password) + 1]) {
1365 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1368 lock ("open");
1369 fz_set_use_document_css (state.ctx, usedoccss);
1370 fz_try (state.ctx) {
1371 ok = openxref (filename, password, layouth);
1373 fz_catch (state.ctx) {
1374 utf8filename = mbtoutf8 (filename);
1375 printd ("emsg Error loading %s: %s",
1376 utf8filename, fz_caught_message (state.ctx));
1377 if (utf8filename != filename) {
1378 free (utf8filename);
1381 if (ok) {
1382 docinfo ();
1383 initpdims ();
1385 unlock ("open");
1386 state.needoutline = ok;
1388 else if (!strncmp ("cs", p, 2)) {
1389 int i, colorspace;
1391 ret = sscanf (p + 2, " %d", &colorspace);
1392 if (ret != 1) {
1393 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1395 lock ("cs");
1396 set_tex_params (colorspace);
1397 for (i = 0; i < state.texcount; ++i) {
1398 state.texowners[i].w = -1;
1399 state.texowners[i].slice = NULL;
1401 unlock ("cs");
1403 else if (!strncmp ("freepage", p, 8)) {
1404 void *ptr;
1406 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1407 if (ret != 1) {
1408 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1410 lock ("freepage");
1411 freepage (ptr);
1412 unlock ("freepage");
1414 else if (!strncmp ("freetile", p, 8)) {
1415 void *ptr;
1417 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1418 if (ret != 1) {
1419 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1421 lock ("freetile");
1422 freetile (ptr);
1423 unlock ("freetile");
1425 else if (!strncmp ("search", p, 6)) {
1426 int icase, pageno, y, len2, forward;
1427 char *pattern;
1428 regex_t re;
1430 ret = sscanf (p + 6, " %d %d %d %d,%n",
1431 &icase, &pageno, &y, &forward, &len2);
1432 if (ret != 4) {
1433 errx (1, "malformed search `%s' ret=%d", p, ret);
1436 pattern = p + 6 + len2;
1437 ret = regcomp (&re, pattern,
1438 REG_EXTENDED | (icase ? REG_ICASE : 0));
1439 if (ret) {
1440 char errbuf[80];
1441 size_t size;
1443 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1444 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1446 else {
1447 lock ("search");
1448 search (&re, pageno, y, forward);
1449 unlock ("search");
1450 regfree (&re);
1453 else if (!strncmp ("geometry", p, 8)) {
1454 int w, h, fitmodel;
1456 printd ("clear");
1457 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1458 if (ret != 3) {
1459 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1462 lock ("geometry");
1463 state.h = h;
1464 if (w != state.w) {
1465 state.w = w;
1466 for (int i = 0; i < state.texcount; ++i) {
1467 state.texowners[i].slice = NULL;
1470 state.fitmodel = fitmodel;
1471 layout ();
1472 process_outline ();
1474 state.gen++;
1475 unlock ("geometry");
1476 printd ("continue %d", state.pagecount);
1478 else if (!strncmp ("reqlayout", p, 9)) {
1479 char *nameddest;
1480 int rotate, off, h;
1481 int fitmodel;
1482 pdf_document *pdf;
1484 printd ("clear");
1485 ret = sscanf (p + 9, " %d %d %d %n",
1486 &rotate, &fitmodel, &h, &off);
1487 if (ret != 3) {
1488 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1490 lock ("reqlayout");
1491 pdf = pdf_specifics (state.ctx, state.doc);
1492 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1493 state.gen += 1;
1495 state.rotate = rotate;
1496 state.fitmodel = fitmodel;
1497 state.h = h;
1498 layout ();
1499 process_outline ();
1501 nameddest = p + 9 + off;
1502 if (pdf && nameddest && *nameddest) {
1503 fz_point xy;
1504 struct pagedim *pdim;
1505 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1506 &xy.x, &xy.y);
1507 pdim = pdimofpageno (pageno);
1508 xy = fz_transform_point (xy, pdim->ctm);
1509 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1512 state.gen++;
1513 unlock ("reqlayout");
1514 printd ("continue %d", state.pagecount);
1516 else if (!strncmp ("page", p, 4)) {
1517 double a, b;
1518 struct page *page;
1519 int pageno, pindex;
1521 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1522 if (ret != 2) {
1523 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1526 lock ("page");
1527 a = now ();
1528 page = loadpage (pageno, pindex);
1529 b = now ();
1530 unlock ("page");
1532 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1534 else if (!strncmp ("tile", p, 4)) {
1535 int x, y, w, h;
1536 struct page *page;
1537 struct tile *tile;
1538 double a, b;
1539 void *data;
1541 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1542 (uintptr_t *) &page, &x, &y, &w, &h,
1543 (uintptr_t *) &data);
1544 if (ret != 6) {
1545 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1548 lock ("tile");
1549 a = now ();
1550 tile = rendertile (page, x, y, w, h, data);
1551 b = now ();
1552 unlock ("tile");
1554 printd ("tile %d %d %" PRIxPTR " %u %f",
1555 x, y, (uintptr_t) (tile),
1556 tile->w * tile->h * tile->pixmap->n,
1557 b - a);
1559 else if (!strncmp ("trimset", p, 7)) {
1560 fz_irect fuzz;
1561 int trimmargins;
1563 ret = sscanf (p + 7, " %d %d %d %d %d",
1564 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1565 if (ret != 5) {
1566 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1568 lock ("trimset");
1569 state.trimmargins = trimmargins;
1570 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1571 state.trimanew = 1;
1572 state.trimfuzz = fuzz;
1574 unlock ("trimset");
1576 else if (!strncmp ("settrim", p, 7)) {
1577 fz_irect fuzz;
1578 int trimmargins;
1580 ret = sscanf (p + 7, " %d %d %d %d %d",
1581 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1582 if (ret != 5) {
1583 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1585 printd ("clear");
1586 lock ("settrim");
1587 state.trimmargins = trimmargins;
1588 state.needoutline = 1;
1589 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1590 state.trimanew = 1;
1591 state.trimfuzz = fuzz;
1593 state.pagedimcount = 0;
1594 free (state.pagedims);
1595 state.pagedims = NULL;
1596 initpdims ();
1597 layout ();
1598 process_outline ();
1599 unlock ("settrim");
1600 printd ("continue %d", state.pagecount);
1602 else if (!strncmp ("sliceh", p, 6)) {
1603 int h;
1605 ret = sscanf (p + 6, " %d", &h);
1606 if (ret != 1) {
1607 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1609 if (h != state.sliceheight) {
1610 state.sliceheight = h;
1611 for (int i = 0; i < state.texcount; ++i) {
1612 state.texowners[i].w = -1;
1613 state.texowners[i].h = -1;
1614 state.texowners[i].slice = NULL;
1618 else if (!strncmp ("interrupt", p, 9)) {
1619 printd ("vmsg interrupted");
1621 else {
1622 errx (1, "unknown command %.*s", len, p);
1625 return 0;
1628 ML (isexternallink (value uri_v))
1630 CAMLparam1 (uri_v);
1631 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1632 CAMLreturn (Val_bool (ext));
1635 ML (uritolocation (value uri_v))
1637 CAMLparam1 (uri_v);
1638 CAMLlocal1 (ret_v);
1639 int pageno;
1640 fz_point xy;
1641 struct pagedim *pdim;
1643 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1644 &xy.x, &xy.y).page;
1645 pdim = pdimofpageno (pageno);
1646 xy = fz_transform_point (xy, pdim->ctm);
1647 ret_v = caml_alloc_tuple (3);
1648 Field (ret_v, 0) = Val_int (pageno);
1649 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1650 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1651 CAMLreturn (ret_v);
1654 ML (realloctexts (value texcount_v))
1656 CAMLparam1 (texcount_v);
1657 int ok;
1659 if (trylock (__func__)) {
1660 ok = 0;
1661 goto done;
1663 realloctexts (Int_val (texcount_v));
1664 ok = 1;
1665 unlock (__func__);
1667 done:
1668 CAMLreturn (Val_bool (ok));
1671 static void recti (int x0, int y0, int x1, int y1)
1673 GLfloat *v = state.vertices;
1675 glVertexPointer (2, GL_FLOAT, 0, v);
1676 v[0] = x0; v[1] = y0;
1677 v[2] = x1; v[3] = y0;
1678 v[4] = x0; v[5] = y1;
1679 v[6] = x1; v[7] = y1;
1680 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1683 static void showsel (struct page *page, int ox, int oy)
1685 fz_irect bbox;
1686 fz_rect rect;
1687 fz_stext_block *block;
1688 int seen = 0;
1689 unsigned char selcolor[] = {15,15,15,140};
1691 if (!page->fmark || !page->lmark) return;
1693 glEnable (GL_BLEND);
1694 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1695 glColor4ubv (selcolor);
1697 ox += state.pagedims[page->pdimno].bounds.x0;
1698 oy += state.pagedims[page->pdimno].bounds.y0;
1700 for (block = page->text->first_block; block; block = block->next) {
1701 fz_stext_line *line;
1703 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1704 for (line = block->u.t.first_line; line; line = line->next) {
1705 fz_stext_char *ch;
1707 rect = fz_empty_rect;
1708 for (ch = line->first_char; ch; ch = ch->next) {
1709 fz_rect r;
1710 if (ch == page->fmark) seen = 1;
1711 r = fz_rect_from_quad (ch->quad);
1712 if (seen) rect = fz_union_rect (rect, r);
1713 if (ch == page->lmark) {
1714 bbox = fz_round_rect (rect);
1715 recti (bbox.x0 + ox, bbox.y0 + oy,
1716 bbox.x1 + ox, bbox.y1 + oy);
1717 goto done;
1720 bbox = fz_round_rect (rect);
1721 recti (bbox.x0 + ox, bbox.y0 + oy,
1722 bbox.x1 + ox, bbox.y1 + oy);
1725 done:
1726 glDisable (GL_BLEND);
1729 #pragma GCC diagnostic push
1730 #pragma GCC diagnostic ignored "-Wconversion"
1731 #include "glfont.c"
1732 #pragma GCC diagnostic pop
1734 static void stipplerect (fz_matrix m,
1735 fz_point p1,
1736 fz_point p2,
1737 fz_point p3,
1738 fz_point p4,
1739 GLfloat *texcoords,
1740 GLfloat *vertices)
1742 p1 = fz_transform_point (p1, m);
1743 p2 = fz_transform_point (p2, m);
1744 p3 = fz_transform_point (p3, m);
1745 p4 = fz_transform_point (p4, m);
1747 float w, h, s, t;
1749 w = p2.x - p1.x;
1750 h = p2.y - p1.y;
1751 t = hypotf (w, h) * .25f;
1753 w = p3.x - p2.x;
1754 h = p3.y - p2.y;
1755 s = hypotf (w, h) * .25f;
1757 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1758 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1760 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1761 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1763 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1764 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1766 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1767 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1769 glDrawArrays (GL_LINES, 0, 8);
1772 static void solidrect (fz_matrix m,
1773 fz_point p1,
1774 fz_point p2,
1775 fz_point p3,
1776 fz_point p4,
1777 GLfloat *vertices)
1779 p1 = fz_transform_point (p1, m);
1780 p2 = fz_transform_point (p2, m);
1781 p3 = fz_transform_point (p3, m);
1782 p4 = fz_transform_point (p4, m);
1783 vertices[0] = p1.x; vertices[1] = p1.y;
1784 vertices[2] = p2.x; vertices[3] = p2.y;
1786 vertices[4] = p3.x; vertices[5] = p3.y;
1787 vertices[6] = p4.x; vertices[7] = p4.y;
1788 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1791 static void ensurelinks (struct page *page)
1793 if (!page->links)
1794 page->links = fz_load_links (state.ctx, page->fzpage);
1797 static void highlightlinks (struct page *page, int xoff, int yoff)
1799 fz_matrix ctm;
1800 fz_link *link;
1801 GLfloat *texcoords = state.texcoords;
1802 GLfloat *vertices = state.vertices;
1804 ensurelinks (page);
1806 glEnable (GL_TEXTURE_1D);
1807 glEnable (GL_BLEND);
1808 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1809 glBindTexture (GL_TEXTURE_1D, state.stid);
1811 xoff -= state.pagedims[page->pdimno].bounds.x0;
1812 yoff -= state.pagedims[page->pdimno].bounds.y0;
1813 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1815 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1816 glVertexPointer (2, GL_FLOAT, 0, vertices);
1818 for (link = page->links; link; link = link->next) {
1819 fz_point p1, p2, p3, p4;
1821 p1.x = link->rect.x0;
1822 p1.y = link->rect.y0;
1824 p2.x = link->rect.x1;
1825 p2.y = link->rect.y0;
1827 p3.x = link->rect.x1;
1828 p3.y = link->rect.y1;
1830 p4.x = link->rect.x0;
1831 p4.y = link->rect.y1;
1833 /* TODO: different colours for different schemes */
1834 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1835 else glColor3ub (255, 0, 0);
1837 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1840 for (int i = 0; i < page->annotcount; ++i) {
1841 fz_point p1, p2, p3, p4;
1842 struct annot *annot = &page->annots[i];
1844 p1.x = annot->bbox.x0;
1845 p1.y = annot->bbox.y0;
1847 p2.x = annot->bbox.x1;
1848 p2.y = annot->bbox.y0;
1850 p3.x = annot->bbox.x1;
1851 p3.y = annot->bbox.y1;
1853 p4.x = annot->bbox.x0;
1854 p4.y = annot->bbox.y1;
1856 glColor3ub (0, 0, 128);
1857 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1860 glDisable (GL_BLEND);
1861 glDisable (GL_TEXTURE_1D);
1864 static int compareslinks (const void *l, const void *r)
1866 struct slink const *ls = l;
1867 struct slink const *rs = r;
1868 if (ls->bbox.y0 == rs->bbox.y0) {
1869 return ls->bbox.x0 - rs->bbox.x0;
1871 return ls->bbox.y0 - rs->bbox.y0;
1874 static void droptext (struct page *page)
1876 if (page->text) {
1877 fz_drop_stext_page (state.ctx, page->text);
1878 page->fmark = NULL;
1879 page->lmark = NULL;
1880 page->text = NULL;
1884 static void dropannots (struct page *page)
1886 if (page->annots) {
1887 free (page->annots);
1888 page->annots = NULL;
1889 page->annotcount = 0;
1893 static void ensureannots (struct page *page)
1895 int i, count = 0;
1896 size_t annotsize = sizeof (*page->annots);
1897 pdf_annot *annot;
1898 pdf_document *pdf;
1899 pdf_page *pdfpage;
1901 pdf = pdf_specifics (state.ctx, state.doc);
1902 if (!pdf) return;
1904 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1905 if (state.gen != page->agen) {
1906 dropannots (page);
1907 page->agen = state.gen;
1909 if (page->annots) return;
1911 for (annot = pdf_first_annot (state.ctx, pdfpage);
1912 annot;
1913 annot = pdf_next_annot (state.ctx, annot)) {
1914 count++;
1917 if (count > 0) {
1918 page->annotcount = count;
1919 page->annots = calloc (count, annotsize);
1920 if (!page->annots) {
1921 err (1, "calloc annots %d", count);
1924 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1925 annot;
1926 annot = pdf_next_annot (state.ctx, annot), i++) {
1927 fz_rect rect;
1929 rect = pdf_bound_annot (state.ctx, annot);
1930 page->annots[i].annot = annot;
1931 page->annots[i].bbox = fz_round_rect (rect);
1936 static void dropslinks (struct page *page)
1938 if (page->slinks) {
1939 free (page->slinks);
1940 page->slinks = NULL;
1941 page->slinkcount = 0;
1943 if (page->links) {
1944 fz_drop_link (state.ctx, page->links);
1945 page->links = NULL;
1949 static void ensureslinks (struct page *page)
1951 fz_matrix ctm;
1952 int i, count;
1953 size_t slinksize = sizeof (*page->slinks);
1954 fz_link *link;
1956 ensureannots (page);
1957 if (state.gen != page->sgen) {
1958 dropslinks (page);
1959 page->sgen = state.gen;
1961 if (page->slinks) return;
1963 ensurelinks (page);
1964 ctm = pagectm (page);
1966 count = page->annotcount;
1967 for (link = page->links; link; link = link->next) {
1968 count++;
1970 if (count > 0) {
1971 int j;
1973 page->slinkcount = count;
1974 page->slinks = calloc (count, slinksize);
1975 if (!page->slinks) {
1976 err (1, "calloc slinks %d", count);
1979 for (i = 0, link = page->links; link; ++i, link = link->next) {
1980 fz_rect rect;
1982 rect = link->rect;
1983 rect = fz_transform_rect (rect, ctm);
1984 page->slinks[i].tag = SLINK;
1985 page->slinks[i].u.link = link;
1986 page->slinks[i].bbox = fz_round_rect (rect);
1988 for (j = 0; j < page->annotcount; ++j, ++i) {
1989 fz_rect rect;
1990 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1991 rect = fz_transform_rect (rect, ctm);
1992 page->slinks[i].bbox = fz_round_rect (rect);
1994 page->slinks[i].tag = SANNOT;
1995 page->slinks[i].u.annot = page->annots[j].annot;
1997 qsort (page->slinks, count, slinksize, compareslinks);
2001 static void highlightslinks (struct page *page, int xoff, int yoff,
2002 int noff, const char *targ,
2003 mlsize_t tlen, int hfsize)
2005 char buf[40];
2006 struct slink *slink;
2007 float x0, y0, x1, y1, w;
2009 ensureslinks (page);
2010 glColor3ub (0xc3, 0xb0, 0x91);
2011 for (int i = 0; i < page->slinkcount; ++i) {
2012 fmt_linkn (buf, i + noff);
2013 if (!tlen || !strncmp (targ, buf, tlen)) {
2014 slink = &page->slinks[i];
2016 x0 = slink->bbox.x0 + xoff - 5;
2017 y1 = slink->bbox.y0 + yoff - 5;
2018 y0 = y1 + 10 + hfsize;
2019 w = measure_string (state.face, hfsize, buf);
2020 x1 = x0 + w + 10;
2021 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2025 glEnable (GL_BLEND);
2026 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2027 glEnable (GL_TEXTURE_2D);
2028 glColor3ub (0, 0, 0);
2029 for (int i = 0; i < page->slinkcount; ++i) {
2030 fmt_linkn (buf, i + noff);
2031 if (!tlen || !strncmp (targ, buf, tlen)) {
2032 slink = &page->slinks[i];
2034 x0 = slink->bbox.x0 + xoff;
2035 y0 = slink->bbox.y0 + yoff + hfsize;
2036 draw_string (state.face, hfsize, x0, y0, buf);
2039 glDisable (GL_TEXTURE_2D);
2040 glDisable (GL_BLEND);
2043 static void uploadslice (struct tile *tile, struct slice *slice)
2045 int offset;
2046 struct slice *slice1;
2047 unsigned char *texdata;
2049 offset = 0;
2050 for (slice1 = tile->slices; slice != slice1; slice1++) {
2051 offset += slice1->h * tile->w * tile->pixmap->n;
2053 if (slice->texindex != -1 && slice->texindex < state.texcount
2054 && state.texowners[slice->texindex].slice == slice) {
2055 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2057 else {
2058 int subimage = 0;
2059 int texindex = state.texindex++ % state.texcount;
2061 if (state.texowners[texindex].w == tile->w) {
2062 if (state.texowners[texindex].h >= slice->h) {
2063 subimage = 1;
2065 else {
2066 state.texowners[texindex].h = slice->h;
2069 else {
2070 state.texowners[texindex].h = slice->h;
2073 state.texowners[texindex].w = tile->w;
2074 state.texowners[texindex].slice = slice;
2075 slice->texindex = texindex;
2077 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2078 #if TEXT_TYPE == GL_TEXTURE_2D
2079 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2080 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2081 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2082 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2083 #endif
2084 if (tile->pbo) {
2085 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2086 texdata = 0;
2088 else {
2089 texdata = tile->pixmap->samples;
2091 if (subimage) {
2092 glTexSubImage2D (TEXT_TYPE,
2096 tile->w,
2097 slice->h,
2098 state.texform,
2099 state.texty,
2100 texdata+offset
2103 else {
2104 glTexImage2D (TEXT_TYPE,
2106 state.texiform,
2107 tile->w,
2108 slice->h,
2110 state.texform,
2111 state.texty,
2112 texdata+offset
2115 if (tile->pbo) {
2116 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2121 ML0 (begintiles (void))
2123 glEnable (TEXT_TYPE);
2124 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2125 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2128 ML0 (endtiles (void))
2130 glDisable (TEXT_TYPE);
2133 ML0 (drawtile (value args_v, value ptr_v))
2135 CAMLparam2 (args_v, ptr_v);
2136 int dispx = Int_val (Field (args_v, 0));
2137 int dispy = Int_val (Field (args_v, 1));
2138 int dispw = Int_val (Field (args_v, 2));
2139 int disph = Int_val (Field (args_v, 3));
2140 int tilex = Int_val (Field (args_v, 4));
2141 int tiley = Int_val (Field (args_v, 5));
2142 const char *s = String_val (ptr_v);
2143 struct tile *tile = parse_pointer (__func__, s);
2144 int slicey, firstslice;
2145 struct slice *slice;
2146 GLfloat *texcoords = state.texcoords;
2147 GLfloat *vertices = state.vertices;
2149 firstslice = tiley / tile->sliceheight;
2150 slice = &tile->slices[firstslice];
2151 slicey = tiley % tile->sliceheight;
2153 while (disph > 0) {
2154 int dh;
2156 dh = slice->h - slicey;
2157 dh = fz_mini (disph, dh);
2158 uploadslice (tile, slice);
2160 texcoords[0] = tilex; texcoords[1] = slicey;
2161 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2162 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2163 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2165 vertices[0] = dispx; vertices[1] = dispy;
2166 vertices[2] = dispx+dispw; vertices[3] = dispy;
2167 vertices[4] = dispx; vertices[5] = dispy+dh;
2168 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2170 #if TEXT_TYPE == GL_TEXTURE_2D
2171 for (int i = 0; i < 8; ++i) {
2172 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2174 #endif
2176 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2177 dispy += dh;
2178 disph -= dh;
2179 slice++;
2180 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2181 slicey = 0;
2183 CAMLreturn0;
2186 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2188 fz_matrix ctm;
2189 fz_point p1, p2, p3, p4;
2190 GLfloat *vertices = state.vertices;
2192 xoff -= state.pagedims[page->pdimno].bounds.x0;
2193 yoff -= state.pagedims[page->pdimno].bounds.y0;
2194 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2196 glEnable (GL_BLEND);
2197 glVertexPointer (2, GL_FLOAT, 0, vertices);
2199 glColor4d (
2200 Double_array_field (rects_v, 0),
2201 Double_array_field (rects_v, 1),
2202 Double_array_field (rects_v, 2),
2203 Double_array_field (rects_v, 3)
2205 p1.x = (float) Double_array_field (rects_v, 4);
2206 p1.y = (float) Double_array_field (rects_v, 5);
2208 p2.x = (float) Double_array_field (rects_v, 6);
2209 p2.y = p1.y;
2211 p3.x = p2.x;
2212 p3.y = (float) Double_array_field (rects_v, 7);
2214 p4.x = p1.x;
2215 p4.y = p3.y;
2216 solidrect (ctm, p1, p2, p3, p4, vertices);
2217 glDisable (GL_BLEND);
2220 ML (postprocess (value ptr_v, value hlinks_v,
2221 value xoff_v, value yoff_v,
2222 value li_v))
2224 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2225 int xoff = Int_val (xoff_v);
2226 int yoff = Int_val (yoff_v);
2227 int noff = Int_val (Field (li_v, 0));
2228 const char *targ = String_val (Field (li_v, 1));
2229 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2230 int hfsize = Int_val (Field (li_v, 2));
2231 const char *s = String_val (ptr_v);
2232 int hlmask = Int_val (hlinks_v);
2233 struct page *page = parse_pointer (__func__, s);
2235 if (!page->fzpage) {
2236 /* deal with loadpage failed pages */
2237 goto done;
2240 if (trylock (__func__)) {
2241 noff = -1;
2242 goto done;
2245 ensureannots (page);
2246 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2247 if (hlmask & 2) {
2248 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2249 noff = page->slinkcount;
2251 if (page->tgen == state.gen) {
2252 showsel (page, xoff, yoff);
2254 unlock (__func__);
2256 done:
2257 CAMLreturn (Val_int (noff));
2260 ML0 (drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v))
2262 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2263 int xoff = Int_val (xoff_v);
2264 int yoff = Int_val (yoff_v);
2265 const char *s = String_val (ptr_v);
2266 struct page *page = parse_pointer (__func__, s);
2268 drawprect (page, xoff, yoff, rects_v);
2269 CAMLreturn0;
2272 static struct annot *getannot (struct page *page, int x, int y)
2274 fz_point p;
2275 fz_matrix ctm;
2276 const fz_matrix *tctm;
2277 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2279 if (!page->annots) return NULL;
2281 if (pdf) {
2282 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2283 tctm = &state.pagedims[page->pdimno].tctm;
2285 else {
2286 tctm = &fz_identity;
2289 p.x = x;
2290 p.y = y;
2292 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2293 ctm = fz_invert_matrix (ctm);
2294 p = fz_transform_point (p, ctm);
2296 if (pdf) {
2297 for (int i = 0; i < page->annotcount; ++i) {
2298 struct annot *a = &page->annots[i];
2299 fz_rect rect;
2301 rect = pdf_bound_annot (state.ctx, a->annot);
2302 if (p.x >= rect.x0 && p.x <= rect.x1) {
2303 if (p.y >= rect.y0 && p.y <= rect.y1)
2304 return a;
2308 return NULL;
2311 static fz_link *getlink (struct page *page, int x, int y)
2313 fz_point p;
2314 fz_link *link;
2316 ensureslinks (page);
2318 p.x = x;
2319 p.y = y;
2321 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2323 for (link = page->links; link; link = link->next) {
2324 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2325 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2326 return link;
2330 return NULL;
2333 static void ensuretext (struct page *page)
2335 if (state.gen != page->tgen) {
2336 droptext (page);
2337 page->tgen = state.gen;
2339 if (!page->text) {
2340 fz_device *tdev;
2342 page->text = fz_new_stext_page (state.ctx,
2343 state.pagedims[page->pdimno].mediabox);
2344 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2345 fz_run_display_list (state.ctx, page->dlist,
2346 tdev, pagectm (page), fz_infinite_rect, NULL);
2347 fz_close_device (state.ctx, tdev);
2348 fz_drop_device (state.ctx, tdev);
2352 ML (find_page_with_links (value start_page_v, value dir_v))
2354 CAMLparam2 (start_page_v, dir_v);
2355 CAMLlocal1 (ret_v);
2356 int i, dir = Int_val (dir_v);
2357 int start_page = Int_val (start_page_v);
2358 int end_page = dir > 0 ? state.pagecount : -1;
2359 pdf_document *pdf;
2361 fz_var (end_page);
2362 ret_v = Val_int (0);
2363 lock (__func__);
2364 pdf = pdf_specifics (state.ctx, state.doc);
2365 for (i = start_page + dir; i != end_page; i += dir) {
2366 int found;
2368 fz_var (found);
2369 if (pdf) {
2370 pdf_page *page = NULL;
2372 fz_var (page);
2373 fz_try (state.ctx) {
2374 page = pdf_load_page (state.ctx, pdf, i);
2375 found = !!page->links || !!page->annots;
2377 fz_catch (state.ctx) {
2378 found = 0;
2380 if (page) {
2381 fz_drop_page (state.ctx, &page->super);
2384 else {
2385 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2386 fz_link *link = fz_load_links (state.ctx, page);
2387 found = !!link;
2388 fz_drop_link (state.ctx, link);
2389 fz_drop_page (state.ctx, page);
2392 if (found) {
2393 ret_v = caml_alloc_small (1, 1);
2394 Field (ret_v, 0) = Val_int (i);
2395 goto unlock;
2398 unlock:
2399 unlock (__func__);
2400 CAMLreturn (ret_v);
2403 enum { dir_first, dir_last };
2404 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2406 ML (findlink (value ptr_v, value dir_v))
2408 CAMLparam2 (ptr_v, dir_v);
2409 CAMLlocal2 (ret_v, pos_v);
2410 struct page *page;
2411 int dirtag, i, slinkindex;
2412 struct slink *found = NULL ,*slink;
2413 const char *s = String_val (ptr_v);
2415 page = parse_pointer (__func__, s);
2416 ret_v = Val_int (0);
2417 lock (__func__);
2418 ensureslinks (page);
2420 if (Is_block (dir_v)) {
2421 dirtag = Tag_val (dir_v);
2422 switch (dirtag) {
2423 case dir_first_visible:
2425 int x0, y0, dir, first_index, last_index;
2427 pos_v = Field (dir_v, 0);
2428 x0 = Int_val (Field (pos_v, 0));
2429 y0 = Int_val (Field (pos_v, 1));
2430 dir = Int_val (Field (pos_v, 2));
2432 if (dir >= 0) {
2433 dir = 1;
2434 first_index = 0;
2435 last_index = page->slinkcount;
2437 else {
2438 first_index = page->slinkcount - 1;
2439 last_index = -1;
2442 for (i = first_index; i != last_index; i += dir) {
2443 slink = &page->slinks[i];
2444 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2445 found = slink;
2446 break;
2450 break;
2452 case dir_left:
2453 slinkindex = Int_val (Field (dir_v, 0));
2454 found = &page->slinks[slinkindex];
2455 for (i = slinkindex - 1; i >= 0; --i) {
2456 slink = &page->slinks[i];
2457 if (slink->bbox.x0 < found->bbox.x0) {
2458 found = slink;
2459 break;
2462 break;
2464 case dir_right:
2465 slinkindex = Int_val (Field (dir_v, 0));
2466 found = &page->slinks[slinkindex];
2467 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2468 slink = &page->slinks[i];
2469 if (slink->bbox.x0 > found->bbox.x0) {
2470 found = slink;
2471 break;
2474 break;
2476 case dir_down:
2477 slinkindex = Int_val (Field (dir_v, 0));
2478 found = &page->slinks[slinkindex];
2479 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2480 slink = &page->slinks[i];
2481 if (slink->bbox.y0 >= found->bbox.y0) {
2482 found = slink;
2483 break;
2486 break;
2488 case dir_up:
2489 slinkindex = Int_val (Field (dir_v, 0));
2490 found = &page->slinks[slinkindex];
2491 for (i = slinkindex - 1; i >= 0; --i) {
2492 slink = &page->slinks[i];
2493 if (slink->bbox.y0 <= found->bbox.y0) {
2494 found = slink;
2495 break;
2498 break;
2501 else {
2502 dirtag = Int_val (dir_v);
2503 switch (dirtag) {
2504 case dir_first:
2505 found = page->slinks;
2506 break;
2508 case dir_last:
2509 if (page->slinks) {
2510 found = page->slinks + (page->slinkcount - 1);
2512 break;
2515 if (found) {
2516 ret_v = caml_alloc_small (2, 1);
2517 Field (ret_v, 0) = Val_int (found - page->slinks);
2520 unlock (__func__);
2521 CAMLreturn (ret_v);
2524 enum { uuri, utext, uannot };
2526 ML (getlink (value ptr_v, value n_v))
2528 CAMLparam2 (ptr_v, n_v);
2529 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2530 fz_link *link;
2531 struct page *page;
2532 const char *s = String_val (ptr_v);
2533 struct slink *slink;
2535 ret_v = Val_int (0);
2536 page = parse_pointer (__func__, s);
2538 lock (__func__);
2539 ensureslinks (page);
2540 slink = &page->slinks[Int_val (n_v)];
2541 if (slink->tag == SLINK) {
2542 link = slink->u.link;
2543 str_v = caml_copy_string (link->uri);
2544 ret_v = caml_alloc_small (1, uuri);
2545 Field (ret_v, 0) = str_v;
2547 else {
2548 ret_v = caml_alloc_small (1, uannot);
2549 tup_v = caml_alloc_tuple (2);
2550 Field (ret_v, 0) = tup_v;
2551 Field (tup_v, 0) = ptr_v;
2552 Field (tup_v, 1) = n_v;
2554 unlock (__func__);
2556 CAMLreturn (ret_v);
2559 ML (getannotcontents (value ptr_v, value n_v))
2561 CAMLparam2 (ptr_v, n_v);
2562 CAMLlocal1 (ret_v);
2563 pdf_document *pdf;
2564 const char *contents = "";
2566 lock (__func__);
2567 pdf = pdf_specifics (state.ctx, state.doc);
2568 if (pdf) {
2569 const char *s = String_val (ptr_v);
2570 struct page *page;
2571 struct slink *slink;
2573 page = parse_pointer (__func__, s);
2574 slink = &page->slinks[Int_val (n_v)];
2575 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2577 unlock (__func__);
2578 ret_v = caml_copy_string (contents);
2579 CAMLreturn (ret_v);
2582 ML (getlinkcount (value ptr_v))
2584 CAMLparam1 (ptr_v);
2585 struct page *page;
2586 const char *s = String_val (ptr_v);
2588 page = parse_pointer (__func__, s);
2589 CAMLreturn (Val_int (page->slinkcount));
2592 ML (getlinkrect (value ptr_v, value n_v))
2594 CAMLparam2 (ptr_v, n_v);
2595 CAMLlocal1 (ret_v);
2596 struct page *page;
2597 struct slink *slink;
2598 const char *s = String_val (ptr_v);
2600 page = parse_pointer (__func__, s);
2601 ret_v = caml_alloc_tuple (4);
2602 lock (__func__);
2603 ensureslinks (page);
2605 slink = &page->slinks[Int_val (n_v)];
2606 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2607 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2608 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2609 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2610 unlock (__func__);
2611 CAMLreturn (ret_v);
2614 ML (whatsunder (value ptr_v, value x_v, value y_v))
2616 CAMLparam3 (ptr_v, x_v, y_v);
2617 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2618 fz_link *link;
2619 struct annot *annot;
2620 struct page *page;
2621 const char *ptr = String_val (ptr_v);
2622 int x = Int_val (x_v), y = Int_val (y_v);
2623 struct pagedim *pdim;
2625 ret_v = Val_int (0);
2626 if (trylock (__func__)) {
2627 goto done;
2630 page = parse_pointer (__func__, ptr);
2631 pdim = &state.pagedims[page->pdimno];
2632 x += pdim->bounds.x0;
2633 y += pdim->bounds.y0;
2636 annot = getannot (page, x, y);
2637 if (annot) {
2638 int i, n = -1;
2640 ensureslinks (page);
2641 for (i = 0; i < page->slinkcount; ++i) {
2642 if (page->slinks[i].tag == SANNOT
2643 && page->slinks[i].u.annot == annot->annot) {
2644 n = i;
2645 break;
2648 ret_v = caml_alloc_small (1, uannot);
2649 tup_v = caml_alloc_tuple (2);
2650 Field (ret_v, 0) = tup_v;
2651 Field (tup_v, 0) = ptr_v;
2652 Field (tup_v, 1) = Val_int (n);
2653 goto unlock;
2657 link = getlink (page, x, y);
2658 if (link) {
2659 str_v = caml_copy_string (link->uri);
2660 ret_v = caml_alloc_small (1, uuri);
2661 Field (ret_v, 0) = str_v;
2663 else {
2664 fz_rect *b;
2665 fz_stext_block *block;
2667 ensuretext (page);
2669 for (block = page->text->first_block; block; block = block->next) {
2670 fz_stext_line *line;
2672 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2673 b = &block->bbox;
2674 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2675 continue;
2677 for (line = block->u.t.first_line; line; line = line->next) {
2678 fz_stext_char *ch;
2680 b = &line->bbox;
2681 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2682 continue;
2684 for (ch = line->first_char; ch; ch = ch->next) {
2685 fz_quad *q = &ch->quad;
2687 if (x >= q->ul.x && x <= q->ur.x
2688 && y >= q->ul.y && y <= q->ll.y) {
2689 const char *n2 = fz_font_name (state.ctx, ch->font);
2690 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2691 ch->font);
2693 if (!n2) n2 = "<unknown font>";
2695 if (face && face->family_name) {
2696 char *s;
2697 char *n1 = face->family_name;
2698 size_t l1 = strlen (n1);
2699 size_t l2 = strlen (n2);
2701 if (l1 != l2 || memcmp (n1, n2, l1)) {
2702 s = malloc (l1 + l2 + 2);
2703 if (s) {
2704 memcpy (s, n2, l2);
2705 s[l2] = '=';
2706 memcpy (s + l2 + 1, n1, l1 + 1);
2707 str_v = caml_copy_string (s);
2708 free (s);
2712 if (str_v == Val_unit) {
2713 str_v = caml_copy_string (n2);
2715 ret_v = caml_alloc_small (1, utext);
2716 Field (ret_v, 0) = str_v;
2717 goto unlock;
2723 unlock:
2724 unlock (__func__);
2726 done:
2727 CAMLreturn (ret_v);
2730 enum { mark_page, mark_block, mark_line, mark_word };
2732 ML0 (clearmark (value ptr_v))
2734 CAMLparam1 (ptr_v);
2735 const char *s = String_val (ptr_v);
2736 struct page *page;
2738 if (trylock (__func__)) {
2739 goto done;
2742 page = parse_pointer (__func__, s);
2743 page->fmark = NULL;
2744 page->lmark = NULL;
2746 unlock (__func__);
2747 done:
2748 CAMLreturn0;
2751 static int uninteresting (int c)
2753 return isspace (c) || ispunct (c);
2756 ML (markunder (value ptr_v, value x_v, value y_v, value mark_v))
2758 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2759 CAMLlocal1 (ret_v);
2760 fz_rect *b;
2761 struct page *page;
2762 fz_stext_line *line;
2763 fz_stext_block *block;
2764 struct pagedim *pdim;
2765 int mark = Int_val (mark_v);
2766 const char *s = String_val (ptr_v);
2767 int x = Int_val (x_v), y = Int_val (y_v);
2769 ret_v = Val_bool (0);
2770 if (trylock (__func__)) {
2771 goto done;
2774 page = parse_pointer (__func__, s);
2775 pdim = &state.pagedims[page->pdimno];
2777 ensuretext (page);
2779 if (mark == mark_page) {
2780 page->fmark = page->text->first_block->u.t.first_line->first_char;
2781 page->lmark = page->text->last_block->u.t.last_line->last_char;
2782 ret_v = Val_bool (1);
2783 goto unlock;
2786 x += pdim->bounds.x0;
2787 y += pdim->bounds.y0;
2789 for (block = page->text->first_block; block; block = block->next) {
2790 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2791 b = &block->bbox;
2792 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2793 continue;
2795 if (mark == mark_block) {
2796 page->fmark = block->u.t.first_line->first_char;
2797 page->lmark = block->u.t.last_line->last_char;
2798 ret_v = Val_bool (1);
2799 goto unlock;
2802 for (line = block->u.t.first_line; line; line = line->next) {
2803 fz_stext_char *ch;
2805 b = &line->bbox;
2806 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2807 continue;
2809 if (mark == mark_line) {
2810 page->fmark = line->first_char;
2811 page->lmark = line->last_char;
2812 ret_v = Val_bool (1);
2813 goto unlock;
2816 for (ch = line->first_char; ch; ch = ch->next) {
2817 fz_stext_char *ch2, *first = NULL, *last = NULL;
2818 fz_quad *q = &ch->quad;
2819 if (x >= q->ul.x && x <= q->ur.x
2820 && y >= q->ul.y && y <= q->ll.y) {
2821 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2822 if (uninteresting (ch2->c)) first = NULL;
2823 else if (!first) first = ch2;
2825 for (ch2 = ch; ch2; ch2 = ch2->next) {
2826 if (uninteresting (ch2->c)) break;
2827 last = ch2;
2830 page->fmark = first;
2831 page->lmark = last;
2832 ret_v = Val_bool (1);
2833 goto unlock;
2838 unlock:
2839 if (!Bool_val (ret_v)) {
2840 page->fmark = NULL;
2841 page->lmark = NULL;
2843 unlock (__func__);
2845 done:
2846 CAMLreturn (ret_v);
2849 ML (rectofblock (value ptr_v, value x_v, value y_v))
2851 CAMLparam3 (ptr_v, x_v, y_v);
2852 CAMLlocal2 (ret_v, res_v);
2853 fz_rect *b = NULL;
2854 struct page *page;
2855 struct pagedim *pdim;
2856 fz_stext_block *block;
2857 const char *s = String_val (ptr_v);
2858 int x = Int_val (x_v), y = Int_val (y_v);
2860 ret_v = Val_int (0);
2861 if (trylock (__func__)) {
2862 goto done;
2865 page = parse_pointer (__func__, s);
2866 pdim = &state.pagedims[page->pdimno];
2867 x += pdim->bounds.x0;
2868 y += pdim->bounds.y0;
2870 ensuretext (page);
2872 for (block = page->text->first_block; block; block = block->next) {
2873 switch (block->type) {
2874 case FZ_STEXT_BLOCK_TEXT:
2875 b = &block->bbox;
2876 break;
2878 case FZ_STEXT_BLOCK_IMAGE:
2879 b = &block->bbox;
2880 break;
2882 default:
2883 continue;
2886 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2887 break;
2888 b = NULL;
2890 if (b) {
2891 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2892 ret_v = caml_alloc_small (1, 1);
2893 Store_double_field (res_v, 0, (double) b->x0);
2894 Store_double_field (res_v, 1, (double) b->x1);
2895 Store_double_field (res_v, 2, (double) b->y0);
2896 Store_double_field (res_v, 3, (double) b->y1);
2897 Field (ret_v, 0) = res_v;
2899 unlock (__func__);
2901 done:
2902 CAMLreturn (ret_v);
2905 ML0 (seltext (value ptr_v, value rect_v))
2907 CAMLparam2 (ptr_v, rect_v);
2908 struct page *page;
2909 struct pagedim *pdim;
2910 const char *s = String_val (ptr_v);
2911 int x0, x1, y0, y1;
2912 fz_stext_char *ch;
2913 fz_stext_line *line;
2914 fz_stext_block *block;
2915 fz_stext_char *fc, *lc;
2917 if (trylock (__func__)) {
2918 goto done;
2921 page = parse_pointer (__func__, s);
2922 ensuretext (page);
2924 pdim = &state.pagedims[page->pdimno];
2925 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2926 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2927 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2928 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2930 if (y0 > y1) {
2931 int t = y0;
2932 y0 = y1;
2933 y1 = t;
2934 x0 = x1;
2935 x1 = t;
2938 fc = page->fmark;
2939 lc = page->lmark;
2941 for (block = page->text->first_block; block; block = block->next) {
2942 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2943 for (line = block->u.t.first_line; line; line = line->next) {
2944 for (ch = line->first_char; ch; ch = ch->next) {
2945 fz_quad q = ch->quad;
2946 if (x0 >= q.ul.x && x0 <= q.ur.x
2947 && y0 >= q.ul.y && y0 <= q.ll.y) {
2948 fc = ch;
2950 if (x1 >= q.ul.x && x1 <= q.ur.x
2951 && y1 >= q.ul.y && y1 <= q.ll.y) {
2952 lc = ch;
2957 if (x1 < x0 && fc == lc) {
2958 fz_stext_char *t;
2960 t = fc;
2961 fc = lc;
2962 lc = t;
2965 page->fmark = fc;
2966 page->lmark = lc;
2968 unlock (__func__);
2970 done:
2971 CAMLreturn0;
2974 static int pipechar (FILE *f, fz_stext_char *ch)
2976 char buf[4];
2977 int len;
2978 size_t ret;
2980 len = fz_runetochar (buf, ch->c);
2981 ret = fwrite (buf, len, 1, f);
2982 if (ret != 1) {
2983 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
2984 len, ret, errno, strerror (errno));
2985 return -1;
2987 return 0;
2990 ML (spawn (value command_v, value fds_v))
2992 CAMLparam2 (command_v, fds_v);
2993 CAMLlocal2 (l_v, tup_v);
2994 int ret, ret1;
2995 pid_t pid = (pid_t) -1;
2996 char *msg = NULL;
2997 value earg_v = Nothing;
2998 posix_spawnattr_t attr;
2999 posix_spawn_file_actions_t fa;
3000 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3002 argv[2] = &Byte (command_v, 0);
3003 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3004 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3007 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3008 msg = "posix_spawnattr_init";
3009 goto fail1;
3012 #ifdef POSIX_SPAWN_USEVFORK
3013 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3014 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3015 goto fail;
3017 #endif
3019 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3020 int fd1, fd2;
3022 tup_v = Field (l_v, 0);
3023 fd1 = Int_val (Field (tup_v, 0));
3024 fd2 = Int_val (Field (tup_v, 1));
3025 if (fd2 < 0) {
3026 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3027 msg = "posix_spawn_file_actions_addclose";
3028 earg_v = tup_v;
3029 goto fail;
3032 else {
3033 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3034 msg = "posix_spawn_file_actions_adddup2";
3035 earg_v = tup_v;
3036 goto fail;
3041 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3042 msg = "posix_spawn";
3043 goto fail;
3046 fail:
3047 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3048 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3051 fail1:
3052 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3053 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3054 ret1, strerror (ret1));
3057 if (msg)
3058 unix_error (ret, msg, earg_v);
3060 CAMLreturn (Val_int (pid));
3063 ML (hassel (value ptr_v))
3065 CAMLparam1 (ptr_v);
3066 CAMLlocal1 (ret_v);
3067 struct page *page;
3068 const char *s = String_val (ptr_v);
3070 ret_v = Val_bool (0);
3071 if (trylock (__func__)) {
3072 goto done;
3075 page = parse_pointer (__func__, s);
3076 ret_v = Val_bool (page->fmark && page->lmark);
3077 unlock (__func__);
3078 done:
3079 CAMLreturn (ret_v);
3082 ML0 (copysel (value fd_v, value ptr_v))
3084 CAMLparam2 (fd_v, ptr_v);
3085 FILE *f;
3086 int seen = 0;
3087 struct page *page;
3088 fz_stext_line *line;
3089 fz_stext_block *block;
3090 int fd = Int_val (fd_v);
3091 const char *s = String_val (ptr_v);
3093 if (trylock (__func__)) {
3094 goto done;
3097 page = parse_pointer (__func__, s);
3099 if (!page->fmark || !page->lmark) {
3100 printd ("emsg nothing to copy on page %d", page->pageno);
3101 goto unlock;
3104 f = fdopen (fd, "w");
3105 if (!f) {
3106 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3107 fd, errno, strerror (errno));
3108 f = stdout;
3111 for (block = page->text->first_block; block; block = block->next) {
3112 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3113 for (line = block->u.t.first_line; line; line = line->next) {
3114 fz_stext_char *ch;
3115 for (ch = line->first_char; ch; ch = ch->next) {
3116 if (seen || ch == page->fmark) {
3117 do {
3118 pipechar (f, ch);
3119 if (ch == page->lmark) goto close;
3120 } while ((ch = ch->next));
3121 seen = 1;
3122 break;
3125 if (seen) fputc ('\n', f);
3128 close:
3129 if (f != stdout) {
3130 int ret = fclose (f);
3131 fd = -1;
3132 if (ret == -1) {
3133 if (errno != ECHILD) {
3134 printd ("emsg failed to close sel pipe: %d:%s",
3135 errno, strerror (errno));
3139 unlock:
3140 unlock (__func__);
3142 done:
3143 if (fd >= 0) {
3144 if (close (fd)) {
3145 printd ("emsg failed to close sel pipe: %d:%s",
3146 errno, strerror (errno));
3149 CAMLreturn0;
3152 ML (getpdimrect (value pagedimno_v))
3154 CAMLparam1 (pagedimno_v);
3155 CAMLlocal1 (ret_v);
3156 int pagedimno = Int_val (pagedimno_v);
3157 fz_rect box;
3159 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3160 if (trylock (__func__)) {
3161 box = fz_empty_rect;
3163 else {
3164 box = state.pagedims[pagedimno].mediabox;
3165 unlock (__func__);
3168 Store_double_field (ret_v, 0, (double) box.x0);
3169 Store_double_field (ret_v, 1, (double) box.x1);
3170 Store_double_field (ret_v, 2, (double) box.y0);
3171 Store_double_field (ret_v, 3, (double) box.y1);
3173 CAMLreturn (ret_v);
3176 ML (zoom_for_height (value winw_v, value winh_v, value dw_v, value cols_v))
3178 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3179 CAMLlocal1 (ret_v);
3180 int i;
3181 float zoom = -1.;
3182 float maxh = 0.0;
3183 struct pagedim *p;
3184 float winw = Int_val (winw_v);
3185 float winh = Int_val (winh_v);
3186 float dw = Int_val (dw_v);
3187 float cols = Int_val (cols_v);
3188 float pw = 1.0, ph = 1.0;
3190 if (trylock (__func__)) {
3191 goto done;
3194 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3195 float w = p->pagebox.x1 / cols;
3196 float h = p->pagebox.y1;
3197 if (h > maxh) {
3198 maxh = h;
3199 ph = h;
3200 if (state.fitmodel != FitProportional) pw = w;
3202 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3205 zoom = (((winh / ph) * pw) + dw) / winw;
3206 unlock (__func__);
3207 done:
3208 ret_v = caml_copy_double ((double) zoom);
3209 CAMLreturn (ret_v);
3212 ML (getmaxw (value unit_v))
3214 CAMLparam1 (unit_v);
3215 CAMLlocal1 (ret_v);
3216 int i;
3217 float maxw = -1.;
3218 struct pagedim *p;
3220 if (trylock (__func__)) {
3221 goto done;
3224 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3225 float w = p->pagebox.x1;
3226 maxw = fz_max (maxw, w);
3229 unlock (__func__);
3230 done:
3231 ret_v = caml_copy_double ((double) maxw);
3232 CAMLreturn (ret_v);
3235 ML (draw_string (value pt_v, value x_v, value y_v, value string_v))
3237 CAMLparam4 (pt_v, x_v, y_v, string_v);
3238 CAMLlocal1 (ret_v);
3239 int pt = Int_val(pt_v);
3240 int x = Int_val (x_v);
3241 int y = Int_val (y_v);
3242 float w;
3244 w = draw_string (state.face, pt, x, y, String_val (string_v));
3245 ret_v = caml_copy_double (w);
3246 CAMLreturn (ret_v);
3249 ML (measure_string (value pt_v, value string_v))
3251 CAMLparam2 (pt_v, string_v);
3252 CAMLlocal1 (ret_v);
3253 int pt = Int_val (pt_v);
3254 double w;
3256 w = (double) measure_string (state.face, pt, String_val (string_v));
3257 ret_v = caml_copy_double (w);
3258 CAMLreturn (ret_v);
3261 ML (getpagebox (value opaque_v))
3263 CAMLparam1 (opaque_v);
3264 CAMLlocal1 (ret_v);
3265 fz_rect rect;
3266 fz_irect bbox;
3267 fz_device *dev;
3268 const char *s = String_val (opaque_v);
3269 struct page *page = parse_pointer (__func__, s);
3271 ret_v = caml_alloc_tuple (4);
3272 dev = fz_new_bbox_device (state.ctx, &rect);
3274 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3276 fz_close_device (state.ctx, dev);
3277 fz_drop_device (state.ctx, dev);
3278 bbox = fz_round_rect (rect);
3279 Field (ret_v, 0) = Val_int (bbox.x0);
3280 Field (ret_v, 1) = Val_int (bbox.y0);
3281 Field (ret_v, 2) = Val_int (bbox.x1);
3282 Field (ret_v, 3) = Val_int (bbox.y1);
3284 CAMLreturn (ret_v);
3287 ML0 (setaalevel (value level_v))
3289 CAMLparam1 (level_v);
3291 state.aalevel = Int_val (level_v);
3292 CAMLreturn0;
3295 ML0 (setpapercolor (value rgba_v))
3297 CAMLparam1 (rgba_v);
3299 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3300 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3301 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3302 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3303 CAMLreturn0;
3306 value ml_keysymtoutf8 (value keysym_v);
3307 #ifndef CIDER
3308 value ml_keysymtoutf8 (value keysym_v)
3310 CAMLparam1 (keysym_v);
3311 CAMLlocal1 (str_v);
3312 unsigned short keysym = (unsigned short) Int_val (keysym_v);
3313 Rune rune;
3314 extern long keysym2ucs (unsigned short);
3315 int len;
3316 char buf[5];
3318 rune = (Rune) keysym2ucs (keysym);
3319 len = fz_runetochar (buf, rune);
3320 buf[len] = 0;
3321 str_v = caml_copy_string (buf);
3322 CAMLreturn (str_v);
3324 #else
3325 value ml_keysymtoutf8 (value keysym_v)
3327 CAMLparam1 (keysym_v);
3328 CAMLlocal1 (str_v);
3329 long ucs = Long_val (keysym_v);
3330 int len;
3331 char buf[5];
3333 len = fz_runetochar (buf, (int) ucs);
3334 buf[len] = 0;
3335 str_v = caml_copy_string (buf);
3336 CAMLreturn (str_v);
3338 #endif
3340 enum { piunknown, pilinux, pimacos, pibsd };
3342 ML (platform (value unit_v))
3344 CAMLparam1 (unit_v);
3345 CAMLlocal2 (tup_v, arr_v);
3346 int platid = piunknown;
3347 struct utsname buf;
3349 #if defined __linux__
3350 platid = pilinux;
3351 #elif defined __DragonFly__ || defined __FreeBSD__
3352 || defined __OpenBSD__ || defined __NetBSD__
3353 platid = pibsd;
3354 #elif defined __APPLE__
3355 platid = pimacos;
3356 #endif
3357 if (uname (&buf)) err (1, "uname");
3359 tup_v = caml_alloc_tuple (2);
3361 char const *sar[] = {
3362 buf.sysname,
3363 buf.release,
3364 buf.version,
3365 buf.machine,
3366 NULL
3368 arr_v = caml_copy_string_array (sar);
3370 Field (tup_v, 0) = Val_int (platid);
3371 Field (tup_v, 1) = arr_v;
3372 CAMLreturn (tup_v);
3375 ML0 (cloexec (value fd_v))
3377 CAMLparam1 (fd_v);
3378 int fd = Int_val (fd_v);
3380 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3381 uerror ("fcntl", Nothing);
3383 CAMLreturn0;
3386 ML (getpbo (value w_v, value h_v, value cs_v))
3388 CAMLparam2 (w_v, h_v);
3389 CAMLlocal1 (ret_v);
3390 struct bo *pbo;
3391 int w = Int_val (w_v);
3392 int h = Int_val (h_v);
3393 int cs = Int_val (cs_v);
3395 if (state.bo_usable) {
3396 pbo = calloc (sizeof (*pbo), 1);
3397 if (!pbo) {
3398 err (1, "calloc pbo");
3401 switch (cs) {
3402 case 0:
3403 case 1:
3404 pbo->size = w*h*4;
3405 break;
3406 case 2:
3407 pbo->size = w*h*2;
3408 break;
3409 default:
3410 errx (1, "%s: invalid colorspace %d", __func__, cs);
3413 state.glGenBuffersARB (1, &pbo->id);
3414 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3415 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3416 NULL, GL_STREAM_DRAW);
3417 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3418 GL_READ_WRITE);
3419 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3420 if (!pbo->ptr) {
3421 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3422 state.glDeleteBuffersARB (1, &pbo->id);
3423 free (pbo);
3424 ret_v = caml_copy_string ("0");
3426 else {
3427 int res;
3428 char *s;
3430 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3431 if (res < 0) {
3432 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3434 s = malloc (res+1);
3435 if (!s) {
3436 err (1, "malloc %d bytes failed", res+1);
3438 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3439 if (res < 0) {
3440 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3442 ret_v = caml_copy_string (s);
3443 free (s);
3446 else {
3447 ret_v = caml_copy_string ("0");
3449 CAMLreturn (ret_v);
3452 ML0 (freepbo (value s_v))
3454 CAMLparam1 (s_v);
3455 const char *s = String_val (s_v);
3456 struct tile *tile = parse_pointer (__func__, s);
3458 if (tile->pbo) {
3459 state.glDeleteBuffersARB (1, &tile->pbo->id);
3460 tile->pbo->id = -1;
3461 tile->pbo->ptr = NULL;
3462 tile->pbo->size = -1;
3464 CAMLreturn0;
3467 ML0 (unmappbo (value s_v))
3469 CAMLparam1 (s_v);
3470 const char *s = String_val (s_v);
3471 struct tile *tile = parse_pointer (__func__, s);
3473 if (tile->pbo) {
3474 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3475 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3476 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3478 tile->pbo->ptr = NULL;
3479 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3481 CAMLreturn0;
3484 static void setuppbo (void)
3486 extern void (*wsigladdr (const char *name)) (void);
3487 #pragma GCC diagnostic push
3488 #ifdef __clang__
3489 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3490 #endif
3491 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3492 state.bo_usable = GPA (glBindBufferARB)
3493 && GPA (glUnmapBufferARB)
3494 && GPA (glMapBufferARB)
3495 && GPA (glBufferDataARB)
3496 && GPA (glGenBuffersARB)
3497 && GPA (glDeleteBuffersARB);
3498 #undef GPA
3499 #pragma GCC diagnostic pop
3502 ML (bo_usable (void))
3504 return Val_bool (state.bo_usable);
3507 ML (unproject (value ptr_v, value x_v, value y_v))
3509 CAMLparam3 (ptr_v, x_v, y_v);
3510 CAMLlocal2 (ret_v, tup_v);
3511 struct page *page;
3512 const char *s = String_val (ptr_v);
3513 int x = Int_val (x_v), y = Int_val (y_v);
3514 struct pagedim *pdim;
3515 fz_point p;
3517 page = parse_pointer (__func__, s);
3518 pdim = &state.pagedims[page->pdimno];
3520 ret_v = Val_int (0);
3521 if (trylock (__func__)) {
3522 goto done;
3525 p.x = x + pdim->bounds.x0;
3526 p.y = y + pdim->bounds.y0;
3528 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3529 pdim->ctm)));
3531 tup_v = caml_alloc_tuple (2);
3532 ret_v = caml_alloc_small (1, 1);
3533 Field (tup_v, 0) = Val_int (p.x);
3534 Field (tup_v, 1) = Val_int (p.y);
3535 Field (ret_v, 0) = tup_v;
3537 unlock (__func__);
3538 done:
3539 CAMLreturn (ret_v);
3542 ML (project (value ptr_v, value pageno_v, value pdimno_v, value x_v, value y_v))
3544 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3545 CAMLlocal1 (ret_v);
3546 struct page *page;
3547 const char *s = String_val (ptr_v);
3548 int pageno = Int_val (pageno_v);
3549 int pdimno = Int_val (pdimno_v);
3550 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3551 struct pagedim *pdim;
3552 fz_point p;
3553 fz_matrix ctm;
3555 ret_v = Val_int (0);
3556 lock (__func__);
3558 if (!*s) {
3559 page = loadpage (pageno, pdimno);
3561 else {
3562 page = parse_pointer (__func__, s);
3564 pdim = &state.pagedims[pdimno];
3566 if (pdf_specifics (state.ctx, state.doc)) {
3567 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3568 ctm = state.pagedims[page->pdimno].tctm;
3570 else {
3571 ctm = fz_identity;
3573 p.x = x + pdim->bounds.x0;
3574 p.y = y + pdim->bounds.y0;
3576 ctm = fz_concat (pdim->tctm, pdim->ctm);
3577 p = fz_transform_point (p, ctm);
3579 ret_v = caml_alloc_tuple (2);
3580 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3581 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3583 if (!*s) {
3584 freepage (page);
3586 unlock (__func__);
3587 CAMLreturn (ret_v);
3590 ML0 (addannot (value ptr_v, value x_v, value y_v, value contents_v))
3592 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3593 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3595 if (pdf) {
3596 pdf_annot *annot;
3597 struct page *page;
3598 fz_rect r;
3599 const char *s = String_val (ptr_v);
3601 page = parse_pointer (__func__, s);
3602 annot = pdf_create_annot (state.ctx,
3603 pdf_page_from_fz_page (state.ctx,
3604 page->fzpage),
3605 PDF_ANNOT_TEXT);
3606 r.x0 = Int_val (x_v) - 10;
3607 r.y0 = Int_val (y_v) - 10;
3608 r.x1 = r.x0 + 20;
3609 r.y1 = r.y0 + 20;
3610 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3611 pdf_set_annot_rect (state.ctx, annot, r);
3613 state.dirty = 1;
3615 CAMLreturn0;
3618 ML0 (delannot (value ptr_v, value n_v))
3620 CAMLparam2 (ptr_v, n_v);
3621 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3623 if (pdf) {
3624 struct page *page;
3625 const char *s = String_val (ptr_v);
3626 struct slink *slink;
3628 page = parse_pointer (__func__, s);
3629 slink = &page->slinks[Int_val (n_v)];
3630 pdf_delete_annot (state.ctx,
3631 pdf_page_from_fz_page (state.ctx, page->fzpage),
3632 (pdf_annot *) slink->u.annot);
3633 state.dirty = 1;
3635 CAMLreturn0;
3638 ML0 (modannot (value ptr_v, value n_v, value str_v))
3640 CAMLparam3 (ptr_v, n_v, str_v);
3641 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3643 if (pdf) {
3644 struct page *page;
3645 const char *s = String_val (ptr_v);
3646 struct slink *slink;
3648 page = parse_pointer (__func__, s);
3649 slink = &page->slinks[Int_val (n_v)];
3650 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3651 String_val (str_v));
3652 state.dirty = 1;
3654 CAMLreturn0;
3657 ML (hasunsavedchanges (void))
3659 return Val_bool (state.dirty);
3662 ML0 (savedoc (value path_v))
3664 CAMLparam1 (path_v);
3665 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3667 if (pdf) {
3668 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3670 CAMLreturn0;
3673 static void makestippletex (void)
3675 const char pixels[] = "\xff\xff\0\0";
3676 glGenTextures (1, &state.stid);
3677 glBindTexture (GL_TEXTURE_1D, state.stid);
3678 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3679 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3680 glTexImage1D (
3681 GL_TEXTURE_1D,
3683 GL_ALPHA,
3686 GL_ALPHA,
3687 GL_UNSIGNED_BYTE,
3688 pixels
3692 ML (fz_version (void))
3694 return caml_copy_string (FZ_VERSION);
3697 ML (llpp_version (void))
3699 extern char llpp_version[];
3700 return caml_copy_string (llpp_version);
3703 static void diag_callback (void *user, const char *message)
3705 printd ("emsg %s %s", (char *) user, message);
3708 static fz_font *lsff (fz_context *ctx,int UNUSED_ATTR script,
3709 int UNUSED_ATTR language, int UNUSED_ATTR serif,
3710 int UNUSED_ATTR bold, int UNUSED_ATTR italic)
3712 static fz_font *font;
3713 static int done;
3715 if (!done) {
3716 char *path = getenv ("LLPP_FALLBACK_FONT");
3717 if (path) font = fz_new_font_from_file (ctx, NULL, path, 0, 1);
3718 done = 1;
3720 return font;
3723 ML0 (settrimcachepath (value path_v))
3725 CAMLparam1 (path_v);
3726 const char *path = String_val (path_v);
3728 if (!path || !strlen (path)) {
3729 free (state.trimcachepath);
3730 state.trimcachepath = NULL;
3732 else {
3733 free (state.trimcachepath);
3734 state.trimcachepath = ystrdup (path);
3736 if (!state.trimcachepath) {
3737 printd ("emsg failed to strdup trimcachepath: %d:%s",
3738 errno, strerror (errno));
3741 CAMLreturn0;
3744 ML0 (init (value csock_v, value params_v))
3746 CAMLparam2 (csock_v, params_v);
3747 CAMLlocal2 (trim_v, fuzz_v);
3748 int ret;
3749 int texcount;
3750 const char *fontpath;
3751 int colorspace;
3752 int mustoresize;
3754 state.csock = Int_val (csock_v);
3755 state.rotate = Int_val (Field (params_v, 0));
3756 state.fitmodel = Int_val (Field (params_v, 1));
3757 trim_v = Field (params_v, 2);
3758 texcount = Int_val (Field (params_v, 3));
3759 state.sliceheight = Int_val (Field (params_v, 4));
3760 mustoresize = Int_val (Field (params_v, 5));
3761 colorspace = Int_val (Field (params_v, 6));
3762 fontpath = String_val (Field (params_v, 7));
3764 #ifdef CIDER
3765 state.utf8cs = 1;
3766 #else
3767 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3768 if (setlocale (LC_CTYPE, "")) {
3769 const char *cset = nl_langinfo (CODESET);
3770 state.utf8cs = !strcmp (cset, "UTF-8");
3772 else {
3773 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3775 #endif
3777 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3778 fz_register_document_handlers (state.ctx);
3779 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3780 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3781 fz_install_load_system_font_funcs (state.ctx, NULL, NULL, lsff);
3783 state.trimmargins = Bool_val (Field (trim_v, 0));
3784 fuzz_v = Field (trim_v, 1);
3785 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3786 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3787 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3788 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3790 set_tex_params (colorspace);
3792 if (*fontpath) {
3793 state.face = load_font (fontpath);
3795 else {
3796 int len;
3797 const unsigned char *data;
3799 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3800 state.face = load_builtin_font (data, len);
3802 if (!state.face) _exit (1);
3804 realloctexts (texcount);
3805 setuppbo ();
3806 makestippletex ();
3808 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3809 if (ret) {
3810 errx (1, "pthread_create: %s", strerror (ret));
3813 CAMLreturn0;
3816 #if FIXME || !FIXME
3817 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3818 #endif