Make sure that progress always hits 100%
[llpp.git] / link.c
blob72568f147692208487aa53183c51c544938620e8
1 /* lots of code c&p-ed directly from mupdf */
2 #define FIXME 0
4 #ifdef __clang__
5 #pragma GCC diagnostic error "-Weverything"
6 #pragma GCC diagnostic ignored "-Wpadded"
7 #pragma GCC diagnostic ignored "-Wsign-conversion"
8 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
9 #pragma GCC diagnostic ignored "-Wdocumentation"
10 #pragma GCC diagnostic ignored "-Wdouble-promotion"
11 #pragma GCC diagnostic ignored "-Wimplicit-int-float-conversion"
12 #endif
14 extern char **environ;
16 #include <errno.h>
17 #include <stdio.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <signal.h>
23 #include <math.h>
24 #include <wchar.h>
25 #include <locale.h>
26 #include <langinfo.h>
28 #include <unistd.h>
29 #include <pthread.h>
30 #include <sys/uio.h>
31 #include <sys/time.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/utsname.h>
38 #include <spawn.h>
40 #include <regex.h>
41 #include <stdarg.h>
42 #include <limits.h>
43 #include <inttypes.h>
45 #ifdef CIDER
46 #include <OpenGL/gl.h>
47 #else
48 #include <GL/gl.h>
49 #endif
51 #pragma GCC diagnostic push
52 #ifdef __clang__
53 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
54 #endif
55 #pragma GCC diagnostic ignored "-Wpedantic"
56 #define CAML_NAME_SPACE
57 #include <caml/fail.h>
58 #include <caml/alloc.h>
59 #include <caml/memory.h>
60 #include <caml/unixsupport.h>
62 #pragma GCC diagnostic push
63 #pragma GCC diagnostic ignored "-Wfloat-equal"
64 #include <mupdf/fitz.h>
65 #include <mupdf/pdf.h>
66 #pragma GCC diagnostic pop
68 #include <ft2build.h>
69 #include FT_FREETYPE_H
70 #pragma GCC diagnostic pop
72 #include "cutils.h"
74 #ifdef USE_NPOT
75 #define TEXT_TYPE GL_TEXTURE_2D
76 #else
77 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
78 #endif
80 #if 0
81 #define lprintf printf
82 #else
83 #define lprintf(...)
84 #endif
86 #define ARSERT(cond) for (;;) { \
87 if (!(cond)) { \
88 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
89 } \
90 break; \
91 } (void) 0
93 #define ML(d) extern value ml_##d; value ml_##d
94 #define ML0(d) extern void ml_##d; void ml_##d
96 struct slice {
97 int h;
98 int texindex;
101 struct tile {
102 int w, h;
103 int slicecount;
104 int sliceheight;
105 struct bo *pbo;
106 fz_pixmap *pixmap;
107 struct slice slices[1];
110 struct pagedim {
111 int pageno;
112 int rotate;
113 int left;
114 int tctmready;
115 fz_irect bounds;
116 fz_rect pagebox;
117 fz_rect mediabox;
118 fz_matrix ctm, zoomctm, tctm;
121 struct slink {
122 enum { SLINK, SANNOT } tag;
123 fz_irect bbox;
124 union {
125 fz_link *link;
126 pdf_annot *annot;
127 } u;
130 struct annot {
131 fz_irect bbox;
132 pdf_annot *annot;
135 struct page {
136 int tgen;
137 int sgen;
138 int agen;
139 int pageno;
140 int pdimno;
141 fz_stext_page *text;
142 fz_page *fzpage;
143 fz_display_list *dlist;
144 fz_link *links;
145 int slinkcount;
146 struct slink *slinks;
147 int annotcount;
148 struct annot *annots;
149 fz_stext_char *fmark, *lmark;
152 enum { FitWidth, FitProportional, FitPage };
154 static struct {
155 int sliceheight;
156 struct pagedim *pagedims;
157 int pagecount;
158 int pagedimcount;
159 fz_document *doc;
160 fz_context *ctx;
161 int w, h;
163 int texindex;
164 int texcount;
165 GLuint *texids;
167 GLenum texiform;
168 GLenum texform;
169 GLenum texty;
171 fz_colorspace *colorspace;
172 float papercolor[4];
174 struct {
175 int w, h;
176 struct slice *slice;
177 } *texowners;
179 int rotate;
180 int fitmodel;
181 int trimmargins;
182 int needoutline;
183 int gen;
184 int aalevel;
186 int trimanew;
187 fz_irect trimfuzz;
188 fz_pixmap *pig;
190 pthread_t thread;
191 int csock;
192 FT_Face face;
194 char *trimcachepath;
195 int dirty;
197 GLuint stid;
199 int bo_usable;
200 GLuint boid;
202 void (*glBindBufferARB) (GLenum, GLuint);
203 GLboolean (*glUnmapBufferARB) (GLenum);
204 void *(*glMapBufferARB) (GLenum, GLenum);
205 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
206 void (*glGenBuffersARB) (GLsizei, GLuint *);
207 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
209 GLfloat texcoords[8];
210 GLfloat vertices[16];
212 int utf8cs;
213 } state;
215 struct bo {
216 GLuint id;
217 void *ptr;
218 size_t size;
221 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
223 static void lock (const char *cap)
225 int ret = pthread_mutex_lock (&mutex);
226 if (ret) {
227 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
231 static void unlock (const char *cap)
233 int ret = pthread_mutex_unlock (&mutex);
234 if (ret) {
235 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
239 static int trylock (const char *cap)
241 int ret = pthread_mutex_trylock (&mutex);
242 if (ret && ret != EBUSY) {
243 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
245 return ret == EBUSY;
248 static int hasdata (void)
250 int ret, avail;
251 ret = ioctl (state.csock, FIONREAD, &avail);
252 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
253 return avail > 0;
256 ML (hasdata (value fd_v))
258 CAMLparam1 (fd_v);
259 int ret, avail;
261 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
262 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
263 CAMLreturn (Val_bool (avail > 0));
266 static void readdata (int fd, void *p, int size)
268 ssize_t n;
270 again:
271 n = read (fd, p, size);
272 if (n - size) {
273 if (n < 0 && errno == EINTR) goto again;
274 if (!n) errx (1, "EOF while reading");
275 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
279 static void writedata (int fd, char *p, int size)
281 ssize_t n;
282 uint32_t size4 = size;
283 struct iovec iov[2] = {
284 { .iov_base = &size4, .iov_len = 4 },
285 { .iov_base = p, .iov_len = size }
288 again:
289 n = writev (fd, iov, 2);
290 if (n < 0 && errno == EINTR) goto again;
291 if (n - size - 4) {
292 if (!n) errx (1, "EOF while writing data");
293 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
297 static int readlen (int fd)
299 uint32_t u;
300 readdata (fd, &u, 4);
301 return u;
304 ML0 (wcmd (value fd_v, value bytes_v, value len_v))
306 CAMLparam3 (fd_v, bytes_v, len_v);
307 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
308 CAMLreturn0;
311 ML (rcmd (value fd_v))
313 CAMLparam1 (fd_v);
314 CAMLlocal1 (strdata_v);
315 int fd = Int_val (fd_v);
316 int len = readlen (fd);
317 strdata_v = caml_alloc_string (len);
318 readdata (fd, Bytes_val (strdata_v), len);
319 CAMLreturn (strdata_v);
322 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
324 char fbuf[64];
325 int size = sizeof (fbuf), len;
326 va_list ap;
327 char *buf = fbuf;
329 for (;;) {
330 va_start (ap, fmt);
331 len = vsnprintf (buf, size, fmt, ap);
332 va_end (ap);
334 if (len > -1) {
335 if (len < size - 4) {
336 writedata (state.csock, buf, len);
337 break;
339 else size = len + 5;
341 else {
342 err (1, "vsnprintf for `%s' failed", fmt);
344 buf = realloc (buf == fbuf ? NULL : buf, size);
345 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
347 if (buf != fbuf) free (buf);
350 static void closedoc (void)
352 if (state.doc) {
353 fz_drop_document (state.ctx, state.doc);
354 state.doc = NULL;
358 static int openxref (char *filename, char *password, int layouth)
360 for (int i = 0; i < state.texcount; ++i) {
361 state.texowners[i].w = -1;
362 state.texowners[i].slice = NULL;
365 closedoc ();
367 state.dirty = 0;
368 if (state.pagedims) {
369 free (state.pagedims);
370 state.pagedims = NULL;
372 state.pagedimcount = 0;
374 fz_set_aa_level (state.ctx, state.aalevel);
375 state.doc = fz_open_document (state.ctx, filename);
376 if (fz_needs_password (state.ctx, state.doc)) {
377 if (password && !*password) {
378 printd ("pass");
379 return 0;
381 else {
382 int ok = fz_authenticate_password (state.ctx, state.doc, password);
383 if (!ok) {
384 printd ("pass fail");
385 return 0;
389 if (layouth >= 0)
390 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
391 state.pagecount = fz_count_pages (state.ctx, state.doc);
392 return 1;
395 static void docinfo (void)
397 struct { char *tag; char *name; } metatbl[] = {
398 { FZ_META_INFO_TITLE, "Title" },
399 { FZ_META_INFO_AUTHOR, "Author" },
400 { FZ_META_FORMAT, "Format" },
401 { FZ_META_ENCRYPTION, "Encryption" },
402 { "info:Creator", "Creator" },
403 { "info:Producer", "Producer" },
404 { "info:CreationDate", "Creation date" },
406 int len = 0;
407 char *buf = NULL;
409 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
410 int need;
411 again:
412 need = fz_lookup_metadata (state.ctx, state.doc,
413 metatbl[i].tag, buf, len);
414 if (need > 0) {
415 if (need <= len) {
416 printd ("info %s\t%s", metatbl[i].name, buf);
418 else {
419 buf = realloc (buf, need + 1);
420 if (!buf) err (1, "docinfo realloc %d", need + 1);
421 len = need + 1;
422 goto again;
426 free (buf);
428 printd ("infoend");
431 static void unlinktile (struct tile *tile)
433 for (int i = 0; i < tile->slicecount; ++i) {
434 struct slice *s = &tile->slices[i];
436 if (s->texindex != -1) {
437 if (state.texowners[s->texindex].slice == s) {
438 state.texowners[s->texindex].slice = NULL;
444 static void freepage (struct page *page)
446 if (!page) return;
447 if (page->text) {
448 fz_drop_stext_page (state.ctx, page->text);
450 if (page->slinks) {
451 free (page->slinks);
453 fz_drop_display_list (state.ctx, page->dlist);
454 fz_drop_page (state.ctx, page->fzpage);
455 free (page);
458 static void freetile (struct tile *tile)
460 unlinktile (tile);
461 if (!tile->pbo) {
462 #if 0
463 fz_drop_pixmap (state.ctx, tile->pixmap);
464 #else /* piggyback */
465 if (state.pig) {
466 fz_drop_pixmap (state.ctx, state.pig);
468 state.pig = tile->pixmap;
469 #endif
471 else {
472 free (tile->pbo);
473 fz_drop_pixmap (state.ctx, tile->pixmap);
475 free (tile);
478 static void trimctm (pdf_page *page, int pindex)
480 struct pagedim *pdim = &state.pagedims[pindex];
482 if (!page) return;
483 if (!pdim->tctmready) {
484 fz_rect realbox, mediabox;
485 fz_matrix page_ctm, ctm;
487 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
488 realbox = fz_transform_rect (pdim->mediabox, ctm);
489 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
490 pdim->tctm = fz_concat (
491 fz_invert_matrix (page_ctm),
492 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
493 pdim->tctmready = 1;
497 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
499 fz_matrix ctm;
500 ptrdiff_t pdimno = pdim - state.pagedims;
502 ARSERT (pdim - state.pagedims < INT_MAX);
503 if (pdf_specifics (state.ctx, state.doc)) {
504 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
505 ctm = fz_concat (pdim->tctm, pdim->ctm);
507 else {
508 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
509 pdim->ctm);
511 return ctm;
514 static fz_matrix pagectm (struct page *page)
516 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
519 static void *loadpage (int pageno, int pindex)
521 fz_device *dev;
522 struct page *page;
524 page = calloc (sizeof (struct page), 1);
525 if (!page) {
526 err (1, "calloc page %d", pageno);
529 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
530 dev = fz_new_list_device (state.ctx, page->dlist);
531 fz_try (state.ctx) {
532 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
533 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
535 fz_catch (state.ctx) {
536 page->fzpage = NULL;
538 fz_close_device (state.ctx, dev);
539 fz_drop_device (state.ctx, dev);
541 page->pdimno = pindex;
542 page->pageno = pageno;
543 page->sgen = state.gen;
544 page->agen = state.gen;
545 page->tgen = state.gen;
546 return page;
549 static struct tile *alloctile (int h)
551 int slicecount;
552 size_t tilesize;
553 struct tile *tile;
555 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
556 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
557 tile = calloc (tilesize, 1);
558 if (!tile) {
559 err (1, "cannot allocate tile (%zu bytes)", tilesize);
561 for (int i = 0; i < slicecount; ++i) {
562 int sh = fz_mini (h, state.sliceheight);
563 tile->slices[i].h = sh;
564 tile->slices[i].texindex = -1;
565 h -= sh;
567 tile->slicecount = slicecount;
568 tile->sliceheight = state.sliceheight;
569 return tile;
572 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
573 struct bo *pbo)
575 fz_irect bbox;
576 fz_matrix ctm;
577 fz_device *dev;
578 struct tile *tile;
579 struct pagedim *pdim;
581 tile = alloctile (h);
582 pdim = &state.pagedims[page->pdimno];
584 bbox = pdim->bounds;
585 bbox.x0 += x;
586 bbox.y0 += y;
587 bbox.x1 = bbox.x0 + w;
588 bbox.y1 = bbox.y0 + h;
590 if (state.pig) {
591 if (state.pig->w == w
592 && state.pig->h == h
593 && state.pig->colorspace == state.colorspace) {
594 tile->pixmap = state.pig;
595 tile->pixmap->x = bbox.x0;
596 tile->pixmap->y = bbox.y0;
598 else {
599 fz_drop_pixmap (state.ctx, state.pig);
601 state.pig = NULL;
603 if (!tile->pixmap) {
604 if (pbo) {
605 tile->pixmap =
606 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
607 bbox, NULL, 1, pbo->ptr);
608 tile->pbo = pbo;
610 else {
611 tile->pixmap =
612 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
613 NULL, 1);
617 tile->w = w;
618 tile->h = h;
619 fz_fill_pixmap_with_color (state.ctx, tile->pixmap,
620 fz_device_rgb (state.ctx),
621 state.papercolor,
622 fz_default_color_params);
624 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
625 ctm = pagectm (page);
626 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
627 fz_rect_from_irect (bbox), NULL);
628 fz_close_device (state.ctx, dev);
629 fz_drop_device (state.ctx, dev);
631 return tile;
634 static void initpdims (void)
636 FILE *trimf = NULL;
637 int pageno, trim, show;
638 int trimw = 0, cxcount;
639 struct pagedim *p = NULL;
640 fz_context *ctx = state.ctx;
641 fz_rect rootmediabox = fz_empty_rect;
642 pdf_document *pdf = pdf_specifics (ctx, state.doc);
644 fz_var (p);
645 fz_var (trimw);
646 fz_var (trimf);
647 fz_var (cxcount);
649 if (state.trimmargins && state.trimcachepath) {
650 trimf = fopen (state.trimcachepath, "rb");
651 if (!trimf) {
652 trimf = fopen (state.trimcachepath, "wb");
653 trimw = 1;
657 cxcount = state.pagecount;
658 if (pdf) {
659 pdf_obj *obj;
660 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
661 "Root/Pages/MediaBox");
662 rootmediabox = pdf_to_rect (ctx, obj);
663 pdf_load_page_tree (ctx, pdf);
666 for (pageno = 0; pageno < cxcount; ++pageno) {
667 int rotate = 0;
668 fz_rect mediabox = fz_empty_rect;
670 fz_var (rotate);
671 if (pdf) {
672 pdf_obj *pageobj = NULL;
674 fz_var (pageobj);
675 if (pdf->rev_page_map) {
676 for (int i = 0; i < pdf->rev_page_count; ++i) {
677 if (pdf->rev_page_map[i].page == pageno) {
678 pageobj = pdf_get_xref_entry (
679 ctx, pdf, pdf->rev_page_map[i].object
680 )->obj;
681 break;
685 if (!pageobj) {
686 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
689 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
691 if (state.trimmargins) {
692 pdf_obj *obj;
693 pdf_page *page;
695 fz_try (ctx) {
696 page = pdf_load_page (ctx, pdf, pageno);
697 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
698 trim = state.trimanew || !obj;
699 if (trim) {
700 fz_rect rect;
701 fz_device *dev;
702 fz_matrix ctm, page_ctm;
704 dev = fz_new_bbox_device (ctx, &rect);
705 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
706 ctm = fz_invert_matrix (page_ctm);
707 pdf_run_page (ctx, page, dev, fz_identity, NULL);
708 fz_close_device (ctx, dev);
709 fz_drop_device (ctx, dev);
711 rect.x0 += state.trimfuzz.x0;
712 rect.x1 += state.trimfuzz.x1;
713 rect.y0 += state.trimfuzz.y0;
714 rect.y1 += state.trimfuzz.y1;
715 rect = fz_transform_rect (rect, ctm);
716 rect = fz_intersect_rect (rect, mediabox);
718 if (!fz_is_empty_rect (rect)) {
719 mediabox = rect;
722 obj = pdf_new_array (ctx, pdf, 4);
723 pdf_array_push_real (ctx, obj, mediabox.x0);
724 pdf_array_push_real (ctx, obj, mediabox.y0);
725 pdf_array_push_real (ctx, obj, mediabox.x1);
726 pdf_array_push_real (ctx, obj, mediabox.y1);
727 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
729 else {
730 mediabox.x0 = pdf_array_get_real (ctx, obj, 0);
731 mediabox.y0 = pdf_array_get_real (ctx, obj, 1);
732 mediabox.x1 = pdf_array_get_real (ctx, obj, 2);
733 mediabox.y1 = pdf_array_get_real (ctx, obj, 3);
736 fz_drop_page (ctx, &page->super);
737 show = (pageno + 1 == state.pagecount)
738 || (trim ? pageno % 5 == 0 : pageno % 20 == 0);
739 if (show) {
740 printd ("progress %f Trimming %d",
741 (double) (pageno + 1) / state.pagecount,
742 pageno + 1);
745 fz_catch (ctx) {
746 printd ("emsg failed to load page %d", pageno);
749 else {
750 int empty = 0;
751 fz_rect cropbox;
753 mediabox =
754 pdf_to_rect (ctx, pdf_dict_get_inheritable (
755 ctx,
756 pageobj,
757 PDF_NAME (MediaBox)
760 if (fz_is_empty_rect (mediabox)) {
761 mediabox.x0 = 0;
762 mediabox.y0 = 0;
763 mediabox.x1 = 612;
764 mediabox.y1 = 792;
765 empty = 1;
768 cropbox =
769 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
770 if (!fz_is_empty_rect (cropbox)) {
771 if (empty) {
772 mediabox = cropbox;
774 else {
775 mediabox = fz_intersect_rect (mediabox, cropbox);
778 else {
779 if (empty) {
780 if (fz_is_empty_rect (rootmediabox)) {
781 printd ("emsg cannot find page size for page %d",
782 pageno);
784 else {
785 mediabox = rootmediabox;
791 else {
792 if (state.trimmargins && trimw) {
793 fz_page *page;
795 fz_try (ctx) {
796 page = fz_load_page (ctx, state.doc, pageno);
797 mediabox = fz_bound_page (ctx, page);
798 if (state.trimmargins) {
799 fz_rect rect;
800 fz_device *dev;
802 dev = fz_new_bbox_device (ctx, &rect);
803 fz_run_page (ctx, page, dev, fz_identity, NULL);
804 fz_close_device (ctx, dev);
805 fz_drop_device (ctx, dev);
807 rect.x0 += state.trimfuzz.x0;
808 rect.x1 += state.trimfuzz.x1;
809 rect.y0 += state.trimfuzz.y0;
810 rect.y1 += state.trimfuzz.y1;
811 rect = fz_intersect_rect (rect, mediabox);
813 if (!fz_is_empty_rect (rect)) {
814 mediabox = rect;
817 fz_drop_page (ctx, page);
819 fz_catch (ctx) {
821 if (trimf) {
822 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
823 if (n - 1) {
824 err (1, "fwrite trim mediabox");
828 else {
829 if (trimf) {
830 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
831 if (n - 1) {
832 err (1, "fread trim mediabox %d", pageno);
835 else {
836 fz_page *page;
837 fz_try (ctx) {
838 page = fz_load_page (ctx, state.doc, pageno);
839 mediabox = fz_bound_page (ctx, page);
840 fz_drop_page (ctx, page);
842 show = !state.trimmargins && pageno % 20 == 0;
843 if (show) {
844 printd ("progress %f Gathering dimensions %d",
845 (double) (pageno) / state.pagecount,
846 pageno);
849 fz_catch (ctx) {
850 printd ("emsg failed to load page %d", pageno);
856 if (!p || p->rotate != rotate
857 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
858 size_t size;
860 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
861 state.pagedims = realloc (state.pagedims, size);
862 if (!state.pagedims) {
863 err (1, "realloc pagedims to %zu (%d elems)",
864 size, state.pagedimcount + 1);
867 p = &state.pagedims[state.pagedimcount++];
868 p->rotate = rotate;
869 p->mediabox = mediabox;
870 p->pageno = pageno;
873 state.trimanew = 0;
874 if (trimf) {
875 if (fclose (trimf)) {
876 err (1, "fclose");
881 static void layout (void)
883 int pindex;
884 fz_rect box;
885 fz_matrix ctm;
886 struct pagedim *p = NULL;
887 float zw, w, maxw = 0.0, zoom = 1.0;
889 if (state.pagedimcount == 0) return;
891 switch (state.fitmodel) {
892 case FitProportional:
893 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
894 float x0, x1;
896 p = &state.pagedims[pindex];
897 box = fz_transform_rect (p->mediabox,
898 fz_rotate (p->rotate + state.rotate));
900 x0 = fz_min (box.x0, box.x1);
901 x1 = fz_max (box.x0, box.x1);
903 w = x1 - x0;
904 maxw = fz_max (w, maxw);
905 zoom = state.w / maxw;
907 break;
909 case FitPage:
910 maxw = state.w;
911 break;
913 case FitWidth:
914 break;
916 default:
917 ARSERT (0 && state.fitmodel);
920 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
921 p = &state.pagedims[pindex];
922 ctm = fz_rotate (state.rotate);
923 box = fz_transform_rect (p->mediabox,
924 fz_rotate (p->rotate + state.rotate));
925 w = box.x1 - box.x0;
926 switch (state.fitmodel) {
927 case FitProportional:
928 p->left = (int) (((maxw - w) * zoom) / 2.f);
929 break;
930 case FitPage:
932 float zh, h;
933 zw = maxw / w;
934 h = box.y1 - box.y0;
935 zh = state.h / h;
936 zoom = fz_min (zw, zh);
937 p->left = (int) ((maxw - (w * zoom)) / 2.f);
939 break;
940 case FitWidth:
941 p->left = 0;
942 zoom = state.w / w;
943 break;
946 p->zoomctm = fz_scale (zoom, zoom);
947 ctm = fz_concat (p->zoomctm, ctm);
949 p->pagebox = p->mediabox;
950 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
951 p->pagebox.x1 -= p->pagebox.x0;
952 p->pagebox.y1 -= p->pagebox.y0;
953 p->pagebox.x0 = 0;
954 p->pagebox.y0 = 0;
955 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
956 p->ctm = ctm;
958 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
959 fz_scale (zoom, -zoom));
960 p->tctmready = 0;
963 do {
964 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
965 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
966 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
967 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
968 int boundw = x1 - x0;
969 int boundh = y1 - y0;
971 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
972 } while (p-- != state.pagedims);
975 static struct pagedim *pdimofpageno (int pageno)
977 struct pagedim *pdim = state.pagedims;
979 for (int i = 0; i < state.pagedimcount; ++i) {
980 if (state.pagedims[i].pageno > pageno)
981 break;
982 pdim = &state.pagedims[i];
984 return pdim;
987 static void recurse_outline (fz_outline *outline, int level)
989 while (outline) {
990 if (outline->page >= 0) {
991 fz_point p = {.x = outline->x, .y = outline->y};
992 struct pagedim *pdim = pdimofpageno (outline->page);
993 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
994 p = fz_transform_point (p, pdim->ctm);
995 printd ("o %d %d %d %d %s",
996 level, outline->page, (int) p.y, h, outline->title);
998 else {
999 printd ("on %d %s", level, outline->title);
1001 if (outline->down) {
1002 recurse_outline (outline->down, level + 1);
1004 outline = outline->next;
1008 static void process_outline (void)
1010 fz_outline *outline;
1012 if (!state.needoutline || !state.pagedimcount) return;
1014 state.needoutline = 0;
1015 outline = fz_load_outline (state.ctx, state.doc);
1016 if (outline) {
1017 recurse_outline (outline, 0);
1018 fz_drop_outline (state.ctx, outline);
1022 static char *strofline (fz_stext_line *line)
1024 char *p;
1025 char utf8[10];
1026 fz_stext_char *ch;
1027 size_t size = 0, cap = 80;
1029 p = malloc (cap + 1);
1030 if (!p) return NULL;
1032 for (ch = line->first_char; ch; ch = ch->next) {
1033 int n = fz_runetochar (utf8, ch->c);
1034 if (size + n > cap) {
1035 cap *= 2;
1036 p = realloc (p, cap + 1);
1037 if (!p) return NULL;
1040 memcpy (p + size, utf8, n);
1041 size += n;
1043 p[size] = 0;
1044 return p;
1047 static int matchline (regex_t *re, fz_stext_line *line,
1048 int stop, int pageno, double start)
1050 int ret;
1051 char *p;
1052 regmatch_t rm;
1054 p = strofline (line);
1055 if (!p) return -1;
1057 ret = regexec (re, p, 1, &rm, 0);
1058 if (ret) {
1059 free (p);
1060 if (ret != REG_NOMATCH) {
1061 size_t size;
1062 char errbuf[80];
1063 size = regerror (ret, re, errbuf, sizeof (errbuf));
1064 printd ("msg regexec error `%.*s'",
1065 (int) size, errbuf);
1066 return -1;
1068 return 0;
1070 else {
1071 fz_quad s, e;
1072 fz_stext_char *ch;
1073 int o = 0;
1075 for (ch = line->first_char; ch; ch = ch->next) {
1076 o += fz_runelen (ch->c);
1077 if (o > rm.rm_so) {
1078 s = ch->quad;
1079 break;
1082 for (;ch; ch = ch->next) {
1083 o += fz_runelen (ch->c);
1084 if (o > rm.rm_eo) break;
1086 e = ch->quad;
1088 if (!stop) {
1089 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1090 pageno, 1,
1091 s.ul.x, s.ul.y,
1092 e.ur.x, s.ul.y,
1093 e.lr.x, e.lr.y,
1094 s.ul.x, e.lr.y);
1096 printd ("progress 1 found at %d `%.*s' in %f sec",
1097 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1098 now () - start);
1100 else {
1101 printd ("match %d %d %f %f %f %f %f %f %f %f",
1102 pageno, 2,
1103 s.ul.x, s.ul.y,
1104 e.ur.x, s.ul.y,
1105 e.lr.x, e.lr.y,
1106 s.ul.x, e.lr.y);
1108 free (p);
1109 return 1;
1113 /* wishful thinking function */
1114 static void search (regex_t *re, int pageno, int y, int forward)
1116 fz_device *tdev;
1117 fz_stext_page *text;
1118 struct pagedim *pdim;
1119 int stop = 0, niters = 0;
1120 double start, end;
1121 fz_page *page;
1122 fz_stext_block *block;
1124 start = now ();
1125 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1126 if (niters++ == 5) {
1127 niters = 0;
1128 if (hasdata ()) {
1129 printd ("progress 1 attention requested aborting search at %d",
1130 pageno);
1131 stop = 1;
1133 else {
1134 printd ("progress %f searching in page %d",
1135 (double) (pageno + 1) / state.pagecount,
1136 pageno);
1139 pdim = pdimofpageno (pageno);
1140 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1141 tdev = fz_new_stext_device (state.ctx, text, 0);
1143 page = fz_load_page (state.ctx, state.doc, pageno);
1144 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1146 fz_close_device (state.ctx, tdev);
1147 fz_drop_device (state.ctx, tdev);
1149 if (forward) {
1150 for (block = text->first_block; block; block = block->next) {
1151 fz_stext_line *line;
1153 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1154 for (line = block->u.t.first_line; line; line = line->next) {
1155 if (line->bbox.y0 < y + 1) continue;
1157 switch (matchline (re, line, stop, pageno, start)) {
1158 case 0: break;
1159 case 1: stop = 1; break;
1160 case -1: stop = 1; goto endloop;
1165 else {
1166 for (block = text->last_block; block; block = block->prev) {
1167 fz_stext_line *line;
1169 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1170 for (line = block->u.t.last_line; line; line = line->prev) {
1171 if (line->bbox.y0 < y + 1) continue;
1173 switch (matchline (re, line, stop, pageno, start)) {
1174 case 0: break;
1175 case 1: stop = 1; break;
1176 case -1: stop = 1; goto endloop;
1182 if (forward) {
1183 pageno += 1;
1184 y = 0;
1186 else {
1187 pageno -= 1;
1188 y = INT_MAX;
1190 endloop:
1191 fz_drop_stext_page (state.ctx, text);
1192 fz_drop_page (state.ctx, page);
1194 end = now ();
1195 if (!stop) {
1196 printd ("progress 1 no matches %f sec", end - start);
1198 printd ("clearrects");
1201 static void set_tex_params (int colorspace)
1203 switch (colorspace) {
1204 case 0:
1205 state.texiform = GL_RGBA8;
1206 state.texform = GL_RGBA;
1207 state.texty = GL_UNSIGNED_BYTE;
1208 state.colorspace = fz_device_rgb (state.ctx);
1209 break;
1210 case 1:
1211 state.texiform = GL_LUMINANCE_ALPHA;
1212 state.texform = GL_LUMINANCE_ALPHA;
1213 state.texty = GL_UNSIGNED_BYTE;
1214 state.colorspace = fz_device_gray (state.ctx);
1215 break;
1216 default:
1217 errx (1, "invalid colorspce %d", colorspace);
1221 static void realloctexts (int texcount)
1223 size_t size;
1225 if (texcount == state.texcount) return;
1227 if (texcount < state.texcount) {
1228 glDeleteTextures (state.texcount - texcount,
1229 state.texids + texcount);
1232 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1233 state.texids = realloc (state.texids, size);
1234 if (!state.texids) {
1235 err (1, "realloc texs %zu", size);
1238 state.texowners = (void *) (state.texids + texcount);
1239 if (texcount > state.texcount) {
1240 glGenTextures (texcount - state.texcount,
1241 state.texids + state.texcount);
1242 for (int i = state.texcount; i < texcount; ++i) {
1243 state.texowners[i].w = -1;
1244 state.texowners[i].slice = NULL;
1247 state.texcount = texcount;
1248 state.texindex = 0;
1251 static char *mbtoutf8 (char *s)
1253 char *p, *r;
1254 wchar_t *tmp;
1255 size_t i, ret, len;
1257 if (state.utf8cs) {
1258 return s;
1261 len = mbstowcs (NULL, s, strlen (s));
1262 if (len == 0 || len == (size_t) -1) {
1263 if (len)
1264 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1265 return s;
1268 tmp = calloc (len, sizeof (wchar_t));
1269 if (!tmp) {
1270 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1271 len, sizeof (wchar_t), errno, strerror (errno));
1272 return s;
1275 ret = mbstowcs (tmp, s, len);
1276 if (ret == (size_t) -1) {
1277 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1278 len, errno, strerror (errno));
1279 free (tmp);
1280 return s;
1283 len = 0;
1284 for (i = 0; i < ret; ++i) {
1285 len += fz_runelen (tmp[i]);
1288 p = r = malloc (len + 1);
1289 if (!r) {
1290 printd ("emsg mbtoutf8: malloc(%zu)", len);
1291 free (tmp);
1292 return s;
1295 for (i = 0; i < ret; ++i) {
1296 p += fz_runetochar (p, tmp[i]);
1298 *p = 0;
1299 free (tmp);
1300 return r;
1303 ML (mbtoutf8 (value s_v))
1305 CAMLparam1 (s_v);
1306 CAMLlocal1 (ret_v);
1307 char *s, *r;
1309 s = &Byte (s_v, 0);
1310 r = mbtoutf8 (s);
1311 if (r == s) {
1312 ret_v = s_v;
1314 else {
1315 ret_v = caml_copy_string (r);
1316 free (r);
1318 CAMLreturn (ret_v);
1321 static void * mainloop (void UNUSED_ATTR *unused)
1323 char *p = NULL;
1324 int len, ret, oldlen = 0;
1326 fz_var (p);
1327 fz_var (oldlen);
1328 for (;;) {
1329 len = readlen (state.csock);
1330 if (len == 0) {
1331 errx (1, "readlen returned 0");
1334 if (oldlen < len + 1) {
1335 p = realloc (p, len + 1);
1336 if (!p) {
1337 err (1, "realloc %d failed", len + 1);
1339 oldlen = len + 1;
1341 readdata (state.csock, p, len);
1342 p[len] = 0;
1344 if (!strncmp ("open", p, 4)) {
1345 int off, usedoccss, ok = 0, layouth;
1346 char *password;
1347 char *filename;
1348 char *utf8filename;
1349 size_t filenamelen;
1351 fz_var (ok);
1352 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1353 if (ret != 2) {
1354 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1357 filename = p + 5 + off;
1358 filenamelen = strlen (filename);
1359 password = filename + filenamelen + 1;
1361 if (password[strlen (password) + 1]) {
1362 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1365 lock ("open");
1366 fz_set_use_document_css (state.ctx, usedoccss);
1367 fz_try (state.ctx) {
1368 ok = openxref (filename, password, layouth);
1370 fz_catch (state.ctx) {
1371 utf8filename = mbtoutf8 (filename);
1372 printd ("emsg Error loading %s: %s",
1373 utf8filename, fz_caught_message (state.ctx));
1374 if (utf8filename != filename) {
1375 free (utf8filename);
1378 if (ok) {
1379 docinfo ();
1380 initpdims ();
1382 unlock ("open");
1383 state.needoutline = ok;
1385 else if (!strncmp ("cs", p, 2)) {
1386 int i, colorspace;
1388 ret = sscanf (p + 2, " %d", &colorspace);
1389 if (ret != 1) {
1390 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1392 lock ("cs");
1393 set_tex_params (colorspace);
1394 for (i = 0; i < state.texcount; ++i) {
1395 state.texowners[i].w = -1;
1396 state.texowners[i].slice = NULL;
1398 unlock ("cs");
1400 else if (!strncmp ("freepage", p, 8)) {
1401 void *ptr;
1403 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1404 if (ret != 1) {
1405 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1407 lock ("freepage");
1408 freepage (ptr);
1409 unlock ("freepage");
1411 else if (!strncmp ("freetile", p, 8)) {
1412 void *ptr;
1414 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1415 if (ret != 1) {
1416 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1418 lock ("freetile");
1419 freetile (ptr);
1420 unlock ("freetile");
1422 else if (!strncmp ("search", p, 6)) {
1423 int icase, pageno, y, len2, forward;
1424 char *pattern;
1425 regex_t re;
1427 ret = sscanf (p + 6, " %d %d %d %d,%n",
1428 &icase, &pageno, &y, &forward, &len2);
1429 if (ret != 4) {
1430 errx (1, "malformed search `%s' ret=%d", p, ret);
1433 pattern = p + 6 + len2;
1434 ret = regcomp (&re, pattern,
1435 REG_EXTENDED | (icase ? REG_ICASE : 0));
1436 if (ret) {
1437 char errbuf[80];
1438 size_t size;
1440 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1441 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1443 else {
1444 lock ("search");
1445 search (&re, pageno, y, forward);
1446 unlock ("search");
1447 regfree (&re);
1450 else if (!strncmp ("geometry", p, 8)) {
1451 int w, h, fitmodel;
1453 printd ("clear");
1454 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1455 if (ret != 3) {
1456 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1459 lock ("geometry");
1460 state.h = h;
1461 if (w != state.w) {
1462 state.w = w;
1463 for (int i = 0; i < state.texcount; ++i) {
1464 state.texowners[i].slice = NULL;
1467 state.fitmodel = fitmodel;
1468 layout ();
1469 process_outline ();
1471 state.gen++;
1472 unlock ("geometry");
1473 printd ("continue %d", state.pagecount);
1475 else if (!strncmp ("reqlayout", p, 9)) {
1476 char *nameddest;
1477 int rotate, off, h;
1478 int fitmodel;
1479 pdf_document *pdf;
1481 printd ("clear");
1482 ret = sscanf (p + 9, " %d %d %d %n",
1483 &rotate, &fitmodel, &h, &off);
1484 if (ret != 3) {
1485 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1487 lock ("reqlayout");
1488 pdf = pdf_specifics (state.ctx, state.doc);
1489 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1490 state.gen += 1;
1492 state.rotate = rotate;
1493 state.fitmodel = fitmodel;
1494 state.h = h;
1495 layout ();
1496 process_outline ();
1498 nameddest = p + 9 + off;
1499 if (pdf && nameddest && *nameddest) {
1500 fz_point xy;
1501 struct pagedim *pdim;
1502 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1503 &xy.x, &xy.y);
1504 pdim = pdimofpageno (pageno);
1505 xy = fz_transform_point (xy, pdim->ctm);
1506 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1509 state.gen++;
1510 unlock ("reqlayout");
1511 printd ("continue %d", state.pagecount);
1513 else if (!strncmp ("page", p, 4)) {
1514 double a, b;
1515 struct page *page;
1516 int pageno, pindex;
1518 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1519 if (ret != 2) {
1520 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1523 lock ("page");
1524 a = now ();
1525 page = loadpage (pageno, pindex);
1526 b = now ();
1527 unlock ("page");
1529 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1531 else if (!strncmp ("tile", p, 4)) {
1532 int x, y, w, h;
1533 struct page *page;
1534 struct tile *tile;
1535 double a, b;
1536 void *data;
1538 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1539 (uintptr_t *) &page, &x, &y, &w, &h,
1540 (uintptr_t *) &data);
1541 if (ret != 6) {
1542 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1545 lock ("tile");
1546 a = now ();
1547 tile = rendertile (page, x, y, w, h, data);
1548 b = now ();
1549 unlock ("tile");
1551 printd ("tile %d %d %" PRIxPTR " %u %f",
1552 x, y, (uintptr_t) (tile),
1553 tile->w * tile->h * tile->pixmap->n,
1554 b - a);
1556 else if (!strncmp ("trimset", p, 7)) {
1557 fz_irect fuzz;
1558 int trimmargins;
1560 ret = sscanf (p + 7, " %d %d %d %d %d",
1561 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1562 if (ret != 5) {
1563 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1565 lock ("trimset");
1566 state.trimmargins = trimmargins;
1567 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1568 state.trimanew = 1;
1569 state.trimfuzz = fuzz;
1571 unlock ("trimset");
1573 else if (!strncmp ("settrim", p, 7)) {
1574 fz_irect fuzz;
1575 int trimmargins;
1577 ret = sscanf (p + 7, " %d %d %d %d %d",
1578 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1579 if (ret != 5) {
1580 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1582 printd ("clear");
1583 lock ("settrim");
1584 state.trimmargins = trimmargins;
1585 state.needoutline = 1;
1586 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1587 state.trimanew = 1;
1588 state.trimfuzz = fuzz;
1590 state.pagedimcount = 0;
1591 free (state.pagedims);
1592 state.pagedims = NULL;
1593 initpdims ();
1594 layout ();
1595 process_outline ();
1596 unlock ("settrim");
1597 printd ("continue %d", state.pagecount);
1599 else if (!strncmp ("sliceh", p, 6)) {
1600 int h;
1602 ret = sscanf (p + 6, " %d", &h);
1603 if (ret != 1) {
1604 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1606 if (h != state.sliceheight) {
1607 state.sliceheight = h;
1608 for (int i = 0; i < state.texcount; ++i) {
1609 state.texowners[i].w = -1;
1610 state.texowners[i].h = -1;
1611 state.texowners[i].slice = NULL;
1615 else if (!strncmp ("interrupt", p, 9)) {
1616 printd ("vmsg interrupted");
1618 else {
1619 errx (1, "unknown command %.*s", len, p);
1622 return 0;
1625 ML (isexternallink (value uri_v))
1627 CAMLparam1 (uri_v);
1628 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1629 CAMLreturn (Val_bool (ext));
1632 ML (uritolocation (value uri_v))
1634 CAMLparam1 (uri_v);
1635 CAMLlocal1 (ret_v);
1636 int pageno;
1637 fz_point xy;
1638 struct pagedim *pdim;
1640 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1641 &xy.x, &xy.y).page;
1642 pdim = pdimofpageno (pageno);
1643 xy = fz_transform_point (xy, pdim->ctm);
1644 ret_v = caml_alloc_tuple (3);
1645 Field (ret_v, 0) = Val_int (pageno);
1646 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1647 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1648 CAMLreturn (ret_v);
1651 ML (realloctexts (value texcount_v))
1653 CAMLparam1 (texcount_v);
1654 int ok;
1656 if (trylock (__func__)) {
1657 ok = 0;
1658 goto done;
1660 realloctexts (Int_val (texcount_v));
1661 ok = 1;
1662 unlock (__func__);
1664 done:
1665 CAMLreturn (Val_bool (ok));
1668 static void recti (int x0, int y0, int x1, int y1)
1670 GLfloat *v = state.vertices;
1672 glVertexPointer (2, GL_FLOAT, 0, v);
1673 v[0] = x0; v[1] = y0;
1674 v[2] = x1; v[3] = y0;
1675 v[4] = x0; v[5] = y1;
1676 v[6] = x1; v[7] = y1;
1677 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1680 static void showsel (struct page *page, int ox, int oy)
1682 fz_irect bbox;
1683 fz_rect rect;
1684 fz_stext_block *block;
1685 int seen = 0;
1686 unsigned char selcolor[] = {15,15,15,140};
1688 if (!page->fmark || !page->lmark) return;
1690 glEnable (GL_BLEND);
1691 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1692 glColor4ubv (selcolor);
1694 ox += state.pagedims[page->pdimno].bounds.x0;
1695 oy += state.pagedims[page->pdimno].bounds.y0;
1697 for (block = page->text->first_block; block; block = block->next) {
1698 fz_stext_line *line;
1700 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1701 for (line = block->u.t.first_line; line; line = line->next) {
1702 fz_stext_char *ch;
1704 rect = fz_empty_rect;
1705 for (ch = line->first_char; ch; ch = ch->next) {
1706 fz_rect r;
1707 if (ch == page->fmark) seen = 1;
1708 r = fz_rect_from_quad (ch->quad);
1709 if (seen) rect = fz_union_rect (rect, r);
1710 if (ch == page->lmark) {
1711 bbox = fz_round_rect (rect);
1712 recti (bbox.x0 + ox, bbox.y0 + oy,
1713 bbox.x1 + ox, bbox.y1 + oy);
1714 goto done;
1717 bbox = fz_round_rect (rect);
1718 recti (bbox.x0 + ox, bbox.y0 + oy,
1719 bbox.x1 + ox, bbox.y1 + oy);
1722 done:
1723 glDisable (GL_BLEND);
1726 #pragma GCC diagnostic push
1727 #pragma GCC diagnostic ignored "-Wconversion"
1728 #include "glfont.c"
1729 #pragma GCC diagnostic pop
1731 static void stipplerect (fz_matrix m,
1732 fz_point p1,
1733 fz_point p2,
1734 fz_point p3,
1735 fz_point p4,
1736 GLfloat *texcoords,
1737 GLfloat *vertices)
1739 p1 = fz_transform_point (p1, m);
1740 p2 = fz_transform_point (p2, m);
1741 p3 = fz_transform_point (p3, m);
1742 p4 = fz_transform_point (p4, m);
1744 float w, h, s, t;
1746 w = p2.x - p1.x;
1747 h = p2.y - p1.y;
1748 t = hypotf (w, h) * .25f;
1750 w = p3.x - p2.x;
1751 h = p3.y - p2.y;
1752 s = hypotf (w, h) * .25f;
1754 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1755 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1757 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1758 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1760 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1761 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1763 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1764 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1766 glDrawArrays (GL_LINES, 0, 8);
1769 static void solidrect (fz_matrix m,
1770 fz_point p1,
1771 fz_point p2,
1772 fz_point p3,
1773 fz_point p4,
1774 GLfloat *vertices)
1776 p1 = fz_transform_point (p1, m);
1777 p2 = fz_transform_point (p2, m);
1778 p3 = fz_transform_point (p3, m);
1779 p4 = fz_transform_point (p4, m);
1780 vertices[0] = p1.x; vertices[1] = p1.y;
1781 vertices[2] = p2.x; vertices[3] = p2.y;
1783 vertices[4] = p3.x; vertices[5] = p3.y;
1784 vertices[6] = p4.x; vertices[7] = p4.y;
1785 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1788 static void ensurelinks (struct page *page)
1790 if (!page->links)
1791 page->links = fz_load_links (state.ctx, page->fzpage);
1794 static void highlightlinks (struct page *page, int xoff, int yoff)
1796 fz_matrix ctm;
1797 fz_link *link;
1798 GLfloat *texcoords = state.texcoords;
1799 GLfloat *vertices = state.vertices;
1801 ensurelinks (page);
1803 glEnable (GL_TEXTURE_1D);
1804 glEnable (GL_BLEND);
1805 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1806 glBindTexture (GL_TEXTURE_1D, state.stid);
1808 xoff -= state.pagedims[page->pdimno].bounds.x0;
1809 yoff -= state.pagedims[page->pdimno].bounds.y0;
1810 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1812 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1813 glVertexPointer (2, GL_FLOAT, 0, vertices);
1815 for (link = page->links; link; link = link->next) {
1816 fz_point p1, p2, p3, p4;
1818 p1.x = link->rect.x0;
1819 p1.y = link->rect.y0;
1821 p2.x = link->rect.x1;
1822 p2.y = link->rect.y0;
1824 p3.x = link->rect.x1;
1825 p3.y = link->rect.y1;
1827 p4.x = link->rect.x0;
1828 p4.y = link->rect.y1;
1830 /* TODO: different colours for different schemes */
1831 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1832 else glColor3ub (255, 0, 0);
1834 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1837 for (int i = 0; i < page->annotcount; ++i) {
1838 fz_point p1, p2, p3, p4;
1839 struct annot *annot = &page->annots[i];
1841 p1.x = annot->bbox.x0;
1842 p1.y = annot->bbox.y0;
1844 p2.x = annot->bbox.x1;
1845 p2.y = annot->bbox.y0;
1847 p3.x = annot->bbox.x1;
1848 p3.y = annot->bbox.y1;
1850 p4.x = annot->bbox.x0;
1851 p4.y = annot->bbox.y1;
1853 glColor3ub (0, 0, 128);
1854 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1857 glDisable (GL_BLEND);
1858 glDisable (GL_TEXTURE_1D);
1861 static int compareslinks (const void *l, const void *r)
1863 struct slink const *ls = l;
1864 struct slink const *rs = r;
1865 if (ls->bbox.y0 == rs->bbox.y0) {
1866 return ls->bbox.x0 - rs->bbox.x0;
1868 return ls->bbox.y0 - rs->bbox.y0;
1871 static void droptext (struct page *page)
1873 if (page->text) {
1874 fz_drop_stext_page (state.ctx, page->text);
1875 page->fmark = NULL;
1876 page->lmark = NULL;
1877 page->text = NULL;
1881 static void dropannots (struct page *page)
1883 if (page->annots) {
1884 free (page->annots);
1885 page->annots = NULL;
1886 page->annotcount = 0;
1890 static void ensureannots (struct page *page)
1892 int i, count = 0;
1893 size_t annotsize = sizeof (*page->annots);
1894 pdf_annot *annot;
1895 pdf_document *pdf;
1896 pdf_page *pdfpage;
1898 pdf = pdf_specifics (state.ctx, state.doc);
1899 if (!pdf) return;
1901 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1902 if (state.gen != page->agen) {
1903 dropannots (page);
1904 page->agen = state.gen;
1906 if (page->annots) return;
1908 for (annot = pdf_first_annot (state.ctx, pdfpage);
1909 annot;
1910 annot = pdf_next_annot (state.ctx, annot)) {
1911 count++;
1914 if (count > 0) {
1915 page->annotcount = count;
1916 page->annots = calloc (count, annotsize);
1917 if (!page->annots) {
1918 err (1, "calloc annots %d", count);
1921 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1922 annot;
1923 annot = pdf_next_annot (state.ctx, annot), i++) {
1924 fz_rect rect;
1926 rect = pdf_bound_annot (state.ctx, annot);
1927 page->annots[i].annot = annot;
1928 page->annots[i].bbox = fz_round_rect (rect);
1933 static void dropslinks (struct page *page)
1935 if (page->slinks) {
1936 free (page->slinks);
1937 page->slinks = NULL;
1938 page->slinkcount = 0;
1940 if (page->links) {
1941 fz_drop_link (state.ctx, page->links);
1942 page->links = NULL;
1946 static void ensureslinks (struct page *page)
1948 fz_matrix ctm;
1949 int i, count;
1950 size_t slinksize = sizeof (*page->slinks);
1951 fz_link *link;
1953 ensureannots (page);
1954 if (state.gen != page->sgen) {
1955 dropslinks (page);
1956 page->sgen = state.gen;
1958 if (page->slinks) return;
1960 ensurelinks (page);
1961 ctm = pagectm (page);
1963 count = page->annotcount;
1964 for (link = page->links; link; link = link->next) {
1965 count++;
1967 if (count > 0) {
1968 int j;
1970 page->slinkcount = count;
1971 page->slinks = calloc (count, slinksize);
1972 if (!page->slinks) {
1973 err (1, "calloc slinks %d", count);
1976 for (i = 0, link = page->links; link; ++i, link = link->next) {
1977 fz_rect rect;
1979 rect = link->rect;
1980 rect = fz_transform_rect (rect, ctm);
1981 page->slinks[i].tag = SLINK;
1982 page->slinks[i].u.link = link;
1983 page->slinks[i].bbox = fz_round_rect (rect);
1985 for (j = 0; j < page->annotcount; ++j, ++i) {
1986 fz_rect rect;
1987 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1988 rect = fz_transform_rect (rect, ctm);
1989 page->slinks[i].bbox = fz_round_rect (rect);
1991 page->slinks[i].tag = SANNOT;
1992 page->slinks[i].u.annot = page->annots[j].annot;
1994 qsort (page->slinks, count, slinksize, compareslinks);
1998 static void highlightslinks (struct page *page, int xoff, int yoff,
1999 int noff, const char *targ,
2000 mlsize_t tlen, int hfsize)
2002 char buf[40];
2003 struct slink *slink;
2004 float x0, y0, x1, y1, w;
2006 ensureslinks (page);
2007 glColor3ub (0xc3, 0xb0, 0x91);
2008 for (int i = 0; i < page->slinkcount; ++i) {
2009 fmt_linkn (buf, i + noff);
2010 if (!tlen || !strncmp (targ, buf, tlen)) {
2011 slink = &page->slinks[i];
2013 x0 = slink->bbox.x0 + xoff - 5;
2014 y1 = slink->bbox.y0 + yoff - 5;
2015 y0 = y1 + 10 + hfsize;
2016 w = measure_string (state.face, hfsize, buf);
2017 x1 = x0 + w + 10;
2018 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2022 glEnable (GL_BLEND);
2023 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2024 glEnable (GL_TEXTURE_2D);
2025 glColor3ub (0, 0, 0);
2026 for (int i = 0; i < page->slinkcount; ++i) {
2027 fmt_linkn (buf, i + noff);
2028 if (!tlen || !strncmp (targ, buf, tlen)) {
2029 slink = &page->slinks[i];
2031 x0 = slink->bbox.x0 + xoff;
2032 y0 = slink->bbox.y0 + yoff + hfsize;
2033 draw_string (state.face, hfsize, x0, y0, buf);
2036 glDisable (GL_TEXTURE_2D);
2037 glDisable (GL_BLEND);
2040 static void uploadslice (struct tile *tile, struct slice *slice)
2042 int offset;
2043 struct slice *slice1;
2044 unsigned char *texdata;
2046 offset = 0;
2047 for (slice1 = tile->slices; slice != slice1; slice1++) {
2048 offset += slice1->h * tile->w * tile->pixmap->n;
2050 if (slice->texindex != -1 && slice->texindex < state.texcount
2051 && state.texowners[slice->texindex].slice == slice) {
2052 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2054 else {
2055 int subimage = 0;
2056 int texindex = state.texindex++ % state.texcount;
2058 if (state.texowners[texindex].w == tile->w) {
2059 if (state.texowners[texindex].h >= slice->h) {
2060 subimage = 1;
2062 else {
2063 state.texowners[texindex].h = slice->h;
2066 else {
2067 state.texowners[texindex].h = slice->h;
2070 state.texowners[texindex].w = tile->w;
2071 state.texowners[texindex].slice = slice;
2072 slice->texindex = texindex;
2074 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2075 #if TEXT_TYPE == GL_TEXTURE_2D
2076 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2077 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2078 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2079 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2080 #endif
2081 if (tile->pbo) {
2082 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2083 texdata = 0;
2085 else {
2086 texdata = tile->pixmap->samples;
2088 if (subimage) {
2089 glTexSubImage2D (TEXT_TYPE,
2093 tile->w,
2094 slice->h,
2095 state.texform,
2096 state.texty,
2097 texdata+offset
2100 else {
2101 glTexImage2D (TEXT_TYPE,
2103 state.texiform,
2104 tile->w,
2105 slice->h,
2107 state.texform,
2108 state.texty,
2109 texdata+offset
2112 if (tile->pbo) {
2113 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2118 ML0 (begintiles (void))
2120 glEnable (TEXT_TYPE);
2121 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2122 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2125 ML0 (endtiles (void))
2127 glDisable (TEXT_TYPE);
2130 ML0 (drawtile (value args_v, value ptr_v))
2132 CAMLparam2 (args_v, ptr_v);
2133 int dispx = Int_val (Field (args_v, 0));
2134 int dispy = Int_val (Field (args_v, 1));
2135 int dispw = Int_val (Field (args_v, 2));
2136 int disph = Int_val (Field (args_v, 3));
2137 int tilex = Int_val (Field (args_v, 4));
2138 int tiley = Int_val (Field (args_v, 5));
2139 const char *s = String_val (ptr_v);
2140 struct tile *tile = parse_pointer (__func__, s);
2141 int slicey, firstslice;
2142 struct slice *slice;
2143 GLfloat *texcoords = state.texcoords;
2144 GLfloat *vertices = state.vertices;
2146 firstslice = tiley / tile->sliceheight;
2147 slice = &tile->slices[firstslice];
2148 slicey = tiley % tile->sliceheight;
2150 while (disph > 0) {
2151 int dh;
2153 dh = slice->h - slicey;
2154 dh = fz_mini (disph, dh);
2155 uploadslice (tile, slice);
2157 texcoords[0] = tilex; texcoords[1] = slicey;
2158 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2159 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2160 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2162 vertices[0] = dispx; vertices[1] = dispy;
2163 vertices[2] = dispx+dispw; vertices[3] = dispy;
2164 vertices[4] = dispx; vertices[5] = dispy+dh;
2165 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2167 #if TEXT_TYPE == GL_TEXTURE_2D
2168 for (int i = 0; i < 8; ++i) {
2169 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2171 #endif
2173 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2174 dispy += dh;
2175 disph -= dh;
2176 slice++;
2177 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2178 slicey = 0;
2180 CAMLreturn0;
2183 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2185 fz_matrix ctm;
2186 fz_point p1, p2, p3, p4;
2187 GLfloat *vertices = state.vertices;
2189 xoff -= state.pagedims[page->pdimno].bounds.x0;
2190 yoff -= state.pagedims[page->pdimno].bounds.y0;
2191 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2193 glEnable (GL_BLEND);
2194 glVertexPointer (2, GL_FLOAT, 0, vertices);
2196 glColor4d (
2197 Double_array_field (rects_v, 0),
2198 Double_array_field (rects_v, 1),
2199 Double_array_field (rects_v, 2),
2200 Double_array_field (rects_v, 3)
2202 p1.x = (float) Double_array_field (rects_v, 4);
2203 p1.y = (float) Double_array_field (rects_v, 5);
2205 p2.x = (float) Double_array_field (rects_v, 6);
2206 p2.y = p1.y;
2208 p3.x = p2.x;
2209 p3.y = (float) Double_array_field (rects_v, 7);
2211 p4.x = p1.x;
2212 p4.y = p3.y;
2213 solidrect (ctm, p1, p2, p3, p4, vertices);
2214 glDisable (GL_BLEND);
2217 ML (postprocess (value ptr_v, value hlinks_v,
2218 value xoff_v, value yoff_v,
2219 value li_v))
2221 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2222 int xoff = Int_val (xoff_v);
2223 int yoff = Int_val (yoff_v);
2224 int noff = Int_val (Field (li_v, 0));
2225 const char *targ = String_val (Field (li_v, 1));
2226 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2227 int hfsize = Int_val (Field (li_v, 2));
2228 const char *s = String_val (ptr_v);
2229 int hlmask = Int_val (hlinks_v);
2230 struct page *page = parse_pointer (__func__, s);
2232 if (!page->fzpage) {
2233 /* deal with loadpage failed pages */
2234 goto done;
2237 if (trylock (__func__)) {
2238 noff = -1;
2239 goto done;
2242 ensureannots (page);
2243 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2244 if (hlmask & 2) {
2245 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2246 noff = page->slinkcount;
2248 if (page->tgen == state.gen) {
2249 showsel (page, xoff, yoff);
2251 unlock (__func__);
2253 done:
2254 CAMLreturn (Val_int (noff));
2257 ML0 (drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v))
2259 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2260 int xoff = Int_val (xoff_v);
2261 int yoff = Int_val (yoff_v);
2262 const char *s = String_val (ptr_v);
2263 struct page *page = parse_pointer (__func__, s);
2265 drawprect (page, xoff, yoff, rects_v);
2266 CAMLreturn0;
2269 static struct annot *getannot (struct page *page, int x, int y)
2271 fz_point p;
2272 fz_matrix ctm;
2273 const fz_matrix *tctm;
2274 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2276 if (!page->annots) return NULL;
2278 if (pdf) {
2279 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2280 tctm = &state.pagedims[page->pdimno].tctm;
2282 else {
2283 tctm = &fz_identity;
2286 p.x = x;
2287 p.y = y;
2289 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2290 ctm = fz_invert_matrix (ctm);
2291 p = fz_transform_point (p, ctm);
2293 if (pdf) {
2294 for (int i = 0; i < page->annotcount; ++i) {
2295 struct annot *a = &page->annots[i];
2296 fz_rect rect;
2298 rect = pdf_bound_annot (state.ctx, a->annot);
2299 if (p.x >= rect.x0 && p.x <= rect.x1) {
2300 if (p.y >= rect.y0 && p.y <= rect.y1)
2301 return a;
2305 return NULL;
2308 static fz_link *getlink (struct page *page, int x, int y)
2310 fz_point p;
2311 fz_link *link;
2313 ensureslinks (page);
2315 p.x = x;
2316 p.y = y;
2318 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2320 for (link = page->links; link; link = link->next) {
2321 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2322 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2323 return link;
2327 return NULL;
2330 static void ensuretext (struct page *page)
2332 if (state.gen != page->tgen) {
2333 droptext (page);
2334 page->tgen = state.gen;
2336 if (!page->text) {
2337 fz_device *tdev;
2339 page->text = fz_new_stext_page (state.ctx,
2340 state.pagedims[page->pdimno].mediabox);
2341 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2342 fz_run_display_list (state.ctx, page->dlist,
2343 tdev, pagectm (page), fz_infinite_rect, NULL);
2344 fz_close_device (state.ctx, tdev);
2345 fz_drop_device (state.ctx, tdev);
2349 ML (find_page_with_links (value start_page_v, value dir_v))
2351 CAMLparam2 (start_page_v, dir_v);
2352 CAMLlocal1 (ret_v);
2353 int i, dir = Int_val (dir_v);
2354 int start_page = Int_val (start_page_v);
2355 int end_page = dir > 0 ? state.pagecount : -1;
2356 pdf_document *pdf;
2358 fz_var (end_page);
2359 ret_v = Val_int (0);
2360 lock (__func__);
2361 pdf = pdf_specifics (state.ctx, state.doc);
2362 for (i = start_page + dir; i != end_page; i += dir) {
2363 int found;
2365 fz_var (found);
2366 if (pdf) {
2367 pdf_page *page = NULL;
2369 fz_var (page);
2370 fz_try (state.ctx) {
2371 page = pdf_load_page (state.ctx, pdf, i);
2372 found = !!page->links || !!page->annots;
2374 fz_catch (state.ctx) {
2375 found = 0;
2377 if (page) {
2378 fz_drop_page (state.ctx, &page->super);
2381 else {
2382 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2383 fz_link *link = fz_load_links (state.ctx, page);
2384 found = !!link;
2385 fz_drop_link (state.ctx, link);
2386 fz_drop_page (state.ctx, page);
2389 if (found) {
2390 ret_v = caml_alloc_small (1, 1);
2391 Field (ret_v, 0) = Val_int (i);
2392 goto unlock;
2395 unlock:
2396 unlock (__func__);
2397 CAMLreturn (ret_v);
2400 enum { dir_first, dir_last };
2401 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2403 ML (findlink (value ptr_v, value dir_v))
2405 CAMLparam2 (ptr_v, dir_v);
2406 CAMLlocal2 (ret_v, pos_v);
2407 struct page *page;
2408 int dirtag, i, slinkindex;
2409 struct slink *found = NULL ,*slink;
2410 const char *s = String_val (ptr_v);
2412 page = parse_pointer (__func__, s);
2413 ret_v = Val_int (0);
2414 lock (__func__);
2415 ensureslinks (page);
2417 if (Is_block (dir_v)) {
2418 dirtag = Tag_val (dir_v);
2419 switch (dirtag) {
2420 case dir_first_visible:
2422 int x0, y0, dir, first_index, last_index;
2424 pos_v = Field (dir_v, 0);
2425 x0 = Int_val (Field (pos_v, 0));
2426 y0 = Int_val (Field (pos_v, 1));
2427 dir = Int_val (Field (pos_v, 2));
2429 if (dir >= 0) {
2430 dir = 1;
2431 first_index = 0;
2432 last_index = page->slinkcount;
2434 else {
2435 first_index = page->slinkcount - 1;
2436 last_index = -1;
2439 for (i = first_index; i != last_index; i += dir) {
2440 slink = &page->slinks[i];
2441 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2442 found = slink;
2443 break;
2447 break;
2449 case dir_left:
2450 slinkindex = Int_val (Field (dir_v, 0));
2451 found = &page->slinks[slinkindex];
2452 for (i = slinkindex - 1; i >= 0; --i) {
2453 slink = &page->slinks[i];
2454 if (slink->bbox.x0 < found->bbox.x0) {
2455 found = slink;
2456 break;
2459 break;
2461 case dir_right:
2462 slinkindex = Int_val (Field (dir_v, 0));
2463 found = &page->slinks[slinkindex];
2464 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2465 slink = &page->slinks[i];
2466 if (slink->bbox.x0 > found->bbox.x0) {
2467 found = slink;
2468 break;
2471 break;
2473 case dir_down:
2474 slinkindex = Int_val (Field (dir_v, 0));
2475 found = &page->slinks[slinkindex];
2476 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2477 slink = &page->slinks[i];
2478 if (slink->bbox.y0 >= found->bbox.y0) {
2479 found = slink;
2480 break;
2483 break;
2485 case dir_up:
2486 slinkindex = Int_val (Field (dir_v, 0));
2487 found = &page->slinks[slinkindex];
2488 for (i = slinkindex - 1; i >= 0; --i) {
2489 slink = &page->slinks[i];
2490 if (slink->bbox.y0 <= found->bbox.y0) {
2491 found = slink;
2492 break;
2495 break;
2498 else {
2499 dirtag = Int_val (dir_v);
2500 switch (dirtag) {
2501 case dir_first:
2502 found = page->slinks;
2503 break;
2505 case dir_last:
2506 if (page->slinks) {
2507 found = page->slinks + (page->slinkcount - 1);
2509 break;
2512 if (found) {
2513 ret_v = caml_alloc_small (2, 1);
2514 Field (ret_v, 0) = Val_int (found - page->slinks);
2517 unlock (__func__);
2518 CAMLreturn (ret_v);
2521 enum { uuri, utext, uannot };
2523 ML (getlink (value ptr_v, value n_v))
2525 CAMLparam2 (ptr_v, n_v);
2526 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2527 fz_link *link;
2528 struct page *page;
2529 const char *s = String_val (ptr_v);
2530 struct slink *slink;
2532 ret_v = Val_int (0);
2533 page = parse_pointer (__func__, s);
2535 lock (__func__);
2536 ensureslinks (page);
2537 slink = &page->slinks[Int_val (n_v)];
2538 if (slink->tag == SLINK) {
2539 link = slink->u.link;
2540 str_v = caml_copy_string (link->uri);
2541 ret_v = caml_alloc_small (1, uuri);
2542 Field (ret_v, 0) = str_v;
2544 else {
2545 ret_v = caml_alloc_small (1, uannot);
2546 tup_v = caml_alloc_tuple (2);
2547 Field (ret_v, 0) = tup_v;
2548 Field (tup_v, 0) = ptr_v;
2549 Field (tup_v, 1) = n_v;
2551 unlock (__func__);
2553 CAMLreturn (ret_v);
2556 ML (getannotcontents (value ptr_v, value n_v))
2558 CAMLparam2 (ptr_v, n_v);
2559 CAMLlocal1 (ret_v);
2560 pdf_document *pdf;
2561 const char *contents = "";
2563 lock (__func__);
2564 pdf = pdf_specifics (state.ctx, state.doc);
2565 if (pdf) {
2566 const char *s = String_val (ptr_v);
2567 struct page *page;
2568 struct slink *slink;
2570 page = parse_pointer (__func__, s);
2571 slink = &page->slinks[Int_val (n_v)];
2572 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2574 unlock (__func__);
2575 ret_v = caml_copy_string (contents);
2576 CAMLreturn (ret_v);
2579 ML (getlinkcount (value ptr_v))
2581 CAMLparam1 (ptr_v);
2582 struct page *page;
2583 const char *s = String_val (ptr_v);
2585 page = parse_pointer (__func__, s);
2586 CAMLreturn (Val_int (page->slinkcount));
2589 ML (getlinkrect (value ptr_v, value n_v))
2591 CAMLparam2 (ptr_v, n_v);
2592 CAMLlocal1 (ret_v);
2593 struct page *page;
2594 struct slink *slink;
2595 const char *s = String_val (ptr_v);
2597 page = parse_pointer (__func__, s);
2598 ret_v = caml_alloc_tuple (4);
2599 lock (__func__);
2600 ensureslinks (page);
2602 slink = &page->slinks[Int_val (n_v)];
2603 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2604 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2605 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2606 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2607 unlock (__func__);
2608 CAMLreturn (ret_v);
2611 ML (whatsunder (value ptr_v, value x_v, value y_v))
2613 CAMLparam3 (ptr_v, x_v, y_v);
2614 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2615 fz_link *link;
2616 struct annot *annot;
2617 struct page *page;
2618 const char *ptr = String_val (ptr_v);
2619 int x = Int_val (x_v), y = Int_val (y_v);
2620 struct pagedim *pdim;
2622 ret_v = Val_int (0);
2623 if (trylock (__func__)) {
2624 goto done;
2627 page = parse_pointer (__func__, ptr);
2628 pdim = &state.pagedims[page->pdimno];
2629 x += pdim->bounds.x0;
2630 y += pdim->bounds.y0;
2633 annot = getannot (page, x, y);
2634 if (annot) {
2635 int i, n = -1;
2637 ensureslinks (page);
2638 for (i = 0; i < page->slinkcount; ++i) {
2639 if (page->slinks[i].tag == SANNOT
2640 && page->slinks[i].u.annot == annot->annot) {
2641 n = i;
2642 break;
2645 ret_v = caml_alloc_small (1, uannot);
2646 tup_v = caml_alloc_tuple (2);
2647 Field (ret_v, 0) = tup_v;
2648 Field (tup_v, 0) = ptr_v;
2649 Field (tup_v, 1) = Val_int (n);
2650 goto unlock;
2654 link = getlink (page, x, y);
2655 if (link) {
2656 str_v = caml_copy_string (link->uri);
2657 ret_v = caml_alloc_small (1, uuri);
2658 Field (ret_v, 0) = str_v;
2660 else {
2661 fz_rect *b;
2662 fz_stext_block *block;
2664 ensuretext (page);
2666 for (block = page->text->first_block; block; block = block->next) {
2667 fz_stext_line *line;
2669 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2670 b = &block->bbox;
2671 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2672 continue;
2674 for (line = block->u.t.first_line; line; line = line->next) {
2675 fz_stext_char *ch;
2677 b = &line->bbox;
2678 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2679 continue;
2681 for (ch = line->first_char; ch; ch = ch->next) {
2682 fz_quad *q = &ch->quad;
2684 if (x >= q->ul.x && x <= q->ur.x
2685 && y >= q->ul.y && y <= q->ll.y) {
2686 const char *n2 = fz_font_name (state.ctx, ch->font);
2687 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2688 ch->font);
2690 if (!n2) n2 = "<unknown font>";
2692 if (face && face->family_name) {
2693 char *s;
2694 char *n1 = face->family_name;
2695 size_t l1 = strlen (n1);
2696 size_t l2 = strlen (n2);
2698 if (l1 != l2 || memcmp (n1, n2, l1)) {
2699 s = malloc (l1 + l2 + 2);
2700 if (s) {
2701 memcpy (s, n2, l2);
2702 s[l2] = '=';
2703 memcpy (s + l2 + 1, n1, l1 + 1);
2704 str_v = caml_copy_string (s);
2705 free (s);
2709 if (str_v == Val_unit) {
2710 str_v = caml_copy_string (n2);
2712 ret_v = caml_alloc_small (1, utext);
2713 Field (ret_v, 0) = str_v;
2714 goto unlock;
2720 unlock:
2721 unlock (__func__);
2723 done:
2724 CAMLreturn (ret_v);
2727 enum { mark_page, mark_block, mark_line, mark_word };
2729 ML0 (clearmark (value ptr_v))
2731 CAMLparam1 (ptr_v);
2732 const char *s = String_val (ptr_v);
2733 struct page *page;
2735 if (trylock (__func__)) {
2736 goto done;
2739 page = parse_pointer (__func__, s);
2740 page->fmark = NULL;
2741 page->lmark = NULL;
2743 unlock (__func__);
2744 done:
2745 CAMLreturn0;
2748 static int uninteresting (int c)
2750 return isspace (c) || ispunct (c);
2753 ML (markunder (value ptr_v, value x_v, value y_v, value mark_v))
2755 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2756 CAMLlocal1 (ret_v);
2757 fz_rect *b;
2758 struct page *page;
2759 fz_stext_line *line;
2760 fz_stext_block *block;
2761 struct pagedim *pdim;
2762 int mark = Int_val (mark_v);
2763 const char *s = String_val (ptr_v);
2764 int x = Int_val (x_v), y = Int_val (y_v);
2766 ret_v = Val_bool (0);
2767 if (trylock (__func__)) {
2768 goto done;
2771 page = parse_pointer (__func__, s);
2772 pdim = &state.pagedims[page->pdimno];
2774 ensuretext (page);
2776 if (mark == mark_page) {
2777 page->fmark = page->text->first_block->u.t.first_line->first_char;
2778 page->lmark = page->text->last_block->u.t.last_line->last_char;
2779 ret_v = Val_bool (1);
2780 goto unlock;
2783 x += pdim->bounds.x0;
2784 y += pdim->bounds.y0;
2786 for (block = page->text->first_block; block; block = block->next) {
2787 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2788 b = &block->bbox;
2789 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2790 continue;
2792 if (mark == mark_block) {
2793 page->fmark = block->u.t.first_line->first_char;
2794 page->lmark = block->u.t.last_line->last_char;
2795 ret_v = Val_bool (1);
2796 goto unlock;
2799 for (line = block->u.t.first_line; line; line = line->next) {
2800 fz_stext_char *ch;
2802 b = &line->bbox;
2803 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2804 continue;
2806 if (mark == mark_line) {
2807 page->fmark = line->first_char;
2808 page->lmark = line->last_char;
2809 ret_v = Val_bool (1);
2810 goto unlock;
2813 for (ch = line->first_char; ch; ch = ch->next) {
2814 fz_stext_char *ch2, *first = NULL, *last = NULL;
2815 fz_quad *q = &ch->quad;
2816 if (x >= q->ul.x && x <= q->ur.x
2817 && y >= q->ul.y && y <= q->ll.y) {
2818 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2819 if (uninteresting (ch2->c)) first = NULL;
2820 else if (!first) first = ch2;
2822 for (ch2 = ch; ch2; ch2 = ch2->next) {
2823 if (uninteresting (ch2->c)) break;
2824 last = ch2;
2827 page->fmark = first;
2828 page->lmark = last;
2829 ret_v = Val_bool (1);
2830 goto unlock;
2835 unlock:
2836 if (!Bool_val (ret_v)) {
2837 page->fmark = NULL;
2838 page->lmark = NULL;
2840 unlock (__func__);
2842 done:
2843 CAMLreturn (ret_v);
2846 ML (rectofblock (value ptr_v, value x_v, value y_v))
2848 CAMLparam3 (ptr_v, x_v, y_v);
2849 CAMLlocal2 (ret_v, res_v);
2850 fz_rect *b = NULL;
2851 struct page *page;
2852 struct pagedim *pdim;
2853 fz_stext_block *block;
2854 const char *s = String_val (ptr_v);
2855 int x = Int_val (x_v), y = Int_val (y_v);
2857 ret_v = Val_int (0);
2858 if (trylock (__func__)) {
2859 goto done;
2862 page = parse_pointer (__func__, s);
2863 pdim = &state.pagedims[page->pdimno];
2864 x += pdim->bounds.x0;
2865 y += pdim->bounds.y0;
2867 ensuretext (page);
2869 for (block = page->text->first_block; block; block = block->next) {
2870 switch (block->type) {
2871 case FZ_STEXT_BLOCK_TEXT:
2872 b = &block->bbox;
2873 break;
2875 case FZ_STEXT_BLOCK_IMAGE:
2876 b = &block->bbox;
2877 break;
2879 default:
2880 continue;
2883 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2884 break;
2885 b = NULL;
2887 if (b) {
2888 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2889 ret_v = caml_alloc_small (1, 1);
2890 Store_double_field (res_v, 0, (double) b->x0);
2891 Store_double_field (res_v, 1, (double) b->x1);
2892 Store_double_field (res_v, 2, (double) b->y0);
2893 Store_double_field (res_v, 3, (double) b->y1);
2894 Field (ret_v, 0) = res_v;
2896 unlock (__func__);
2898 done:
2899 CAMLreturn (ret_v);
2902 ML0 (seltext (value ptr_v, value rect_v))
2904 CAMLparam2 (ptr_v, rect_v);
2905 struct page *page;
2906 struct pagedim *pdim;
2907 const char *s = String_val (ptr_v);
2908 int x0, x1, y0, y1;
2909 fz_stext_char *ch;
2910 fz_stext_line *line;
2911 fz_stext_block *block;
2912 fz_stext_char *fc, *lc;
2914 if (trylock (__func__)) {
2915 goto done;
2918 page = parse_pointer (__func__, s);
2919 ensuretext (page);
2921 pdim = &state.pagedims[page->pdimno];
2922 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2923 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2924 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2925 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2927 if (y0 > y1) {
2928 int t = y0;
2929 y0 = y1;
2930 y1 = t;
2931 x0 = x1;
2932 x1 = t;
2935 fc = page->fmark;
2936 lc = page->lmark;
2938 for (block = page->text->first_block; block; block = block->next) {
2939 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2940 for (line = block->u.t.first_line; line; line = line->next) {
2941 for (ch = line->first_char; ch; ch = ch->next) {
2942 fz_quad q = ch->quad;
2943 if (x0 >= q.ul.x && x0 <= q.ur.x
2944 && y0 >= q.ul.y && y0 <= q.ll.y) {
2945 fc = ch;
2947 if (x1 >= q.ul.x && x1 <= q.ur.x
2948 && y1 >= q.ul.y && y1 <= q.ll.y) {
2949 lc = ch;
2954 if (x1 < x0 && fc == lc) {
2955 fz_stext_char *t;
2957 t = fc;
2958 fc = lc;
2959 lc = t;
2962 page->fmark = fc;
2963 page->lmark = lc;
2965 unlock (__func__);
2967 done:
2968 CAMLreturn0;
2971 static int pipechar (FILE *f, fz_stext_char *ch)
2973 char buf[4];
2974 int len;
2975 size_t ret;
2977 len = fz_runetochar (buf, ch->c);
2978 ret = fwrite (buf, len, 1, f);
2979 if (ret != 1) {
2980 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
2981 len, ret, errno, strerror (errno));
2982 return -1;
2984 return 0;
2987 ML (spawn (value command_v, value fds_v))
2989 CAMLparam2 (command_v, fds_v);
2990 CAMLlocal2 (l_v, tup_v);
2991 int ret, ret1;
2992 pid_t pid = (pid_t) -1;
2993 char *msg = NULL;
2994 value earg_v = Nothing;
2995 posix_spawnattr_t attr;
2996 posix_spawn_file_actions_t fa;
2997 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
2999 argv[2] = &Byte (command_v, 0);
3000 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3001 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3004 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3005 msg = "posix_spawnattr_init";
3006 goto fail1;
3009 #ifdef POSIX_SPAWN_USEVFORK
3010 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3011 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3012 goto fail;
3014 #endif
3016 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3017 int fd1, fd2;
3019 tup_v = Field (l_v, 0);
3020 fd1 = Int_val (Field (tup_v, 0));
3021 fd2 = Int_val (Field (tup_v, 1));
3022 if (fd2 < 0) {
3023 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3024 msg = "posix_spawn_file_actions_addclose";
3025 earg_v = tup_v;
3026 goto fail;
3029 else {
3030 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3031 msg = "posix_spawn_file_actions_adddup2";
3032 earg_v = tup_v;
3033 goto fail;
3038 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3039 msg = "posix_spawn";
3040 goto fail;
3043 fail:
3044 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3045 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3048 fail1:
3049 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3050 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3051 ret1, strerror (ret1));
3054 if (msg)
3055 unix_error (ret, msg, earg_v);
3057 CAMLreturn (Val_int (pid));
3060 ML (hassel (value ptr_v))
3062 CAMLparam1 (ptr_v);
3063 CAMLlocal1 (ret_v);
3064 struct page *page;
3065 const char *s = String_val (ptr_v);
3067 ret_v = Val_bool (0);
3068 if (trylock (__func__)) {
3069 goto done;
3072 page = parse_pointer (__func__, s);
3073 ret_v = Val_bool (page->fmark && page->lmark);
3074 unlock (__func__);
3075 done:
3076 CAMLreturn (ret_v);
3079 ML0 (copysel (value fd_v, value ptr_v))
3081 CAMLparam2 (fd_v, ptr_v);
3082 FILE *f;
3083 int seen = 0;
3084 struct page *page;
3085 fz_stext_line *line;
3086 fz_stext_block *block;
3087 int fd = Int_val (fd_v);
3088 const char *s = String_val (ptr_v);
3090 if (trylock (__func__)) {
3091 goto done;
3094 page = parse_pointer (__func__, s);
3096 if (!page->fmark || !page->lmark) {
3097 printd ("emsg nothing to copy on page %d", page->pageno);
3098 goto unlock;
3101 f = fdopen (fd, "w");
3102 if (!f) {
3103 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3104 fd, errno, strerror (errno));
3105 f = stdout;
3108 for (block = page->text->first_block; block; block = block->next) {
3109 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3110 for (line = block->u.t.first_line; line; line = line->next) {
3111 fz_stext_char *ch;
3112 for (ch = line->first_char; ch; ch = ch->next) {
3113 if (seen || ch == page->fmark) {
3114 do {
3115 pipechar (f, ch);
3116 if (ch == page->lmark) goto close;
3117 } while ((ch = ch->next));
3118 seen = 1;
3119 break;
3122 if (seen) fputc ('\n', f);
3125 close:
3126 if (f != stdout) {
3127 int ret = fclose (f);
3128 fd = -1;
3129 if (ret == -1) {
3130 if (errno != ECHILD) {
3131 printd ("emsg failed to close sel pipe: %d:%s",
3132 errno, strerror (errno));
3136 unlock:
3137 unlock (__func__);
3139 done:
3140 if (fd >= 0) {
3141 if (close (fd)) {
3142 printd ("emsg failed to close sel pipe: %d:%s",
3143 errno, strerror (errno));
3146 CAMLreturn0;
3149 ML (getpdimrect (value pagedimno_v))
3151 CAMLparam1 (pagedimno_v);
3152 CAMLlocal1 (ret_v);
3153 int pagedimno = Int_val (pagedimno_v);
3154 fz_rect box;
3156 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3157 if (trylock (__func__)) {
3158 box = fz_empty_rect;
3160 else {
3161 box = state.pagedims[pagedimno].mediabox;
3162 unlock (__func__);
3165 Store_double_field (ret_v, 0, (double) box.x0);
3166 Store_double_field (ret_v, 1, (double) box.x1);
3167 Store_double_field (ret_v, 2, (double) box.y0);
3168 Store_double_field (ret_v, 3, (double) box.y1);
3170 CAMLreturn (ret_v);
3173 ML (zoom_for_height (value winw_v, value winh_v, value dw_v, value cols_v))
3175 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3176 CAMLlocal1 (ret_v);
3177 int i;
3178 float zoom = -1.;
3179 float maxh = 0.0;
3180 struct pagedim *p;
3181 float winw = Int_val (winw_v);
3182 float winh = Int_val (winh_v);
3183 float dw = Int_val (dw_v);
3184 float cols = Int_val (cols_v);
3185 float pw = 1.0, ph = 1.0;
3187 if (trylock (__func__)) {
3188 goto done;
3191 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3192 float w = p->pagebox.x1 / cols;
3193 float h = p->pagebox.y1;
3194 if (h > maxh) {
3195 maxh = h;
3196 ph = h;
3197 if (state.fitmodel != FitProportional) pw = w;
3199 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3202 zoom = (((winh / ph) * pw) + dw) / winw;
3203 unlock (__func__);
3204 done:
3205 ret_v = caml_copy_double ((double) zoom);
3206 CAMLreturn (ret_v);
3209 ML (getmaxw (value unit_v))
3211 CAMLparam1 (unit_v);
3212 CAMLlocal1 (ret_v);
3213 int i;
3214 float maxw = -1.;
3215 struct pagedim *p;
3217 if (trylock (__func__)) {
3218 goto done;
3221 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3222 float w = p->pagebox.x1;
3223 maxw = fz_max (maxw, w);
3226 unlock (__func__);
3227 done:
3228 ret_v = caml_copy_double ((double) maxw);
3229 CAMLreturn (ret_v);
3232 ML (draw_string (value pt_v, value x_v, value y_v, value string_v))
3234 CAMLparam4 (pt_v, x_v, y_v, string_v);
3235 CAMLlocal1 (ret_v);
3236 int pt = Int_val(pt_v);
3237 int x = Int_val (x_v);
3238 int y = Int_val (y_v);
3239 float w;
3241 w = draw_string (state.face, pt, x, y, String_val (string_v));
3242 ret_v = caml_copy_double (w);
3243 CAMLreturn (ret_v);
3246 ML (measure_string (value pt_v, value string_v))
3248 CAMLparam2 (pt_v, string_v);
3249 CAMLlocal1 (ret_v);
3250 int pt = Int_val (pt_v);
3251 double w;
3253 w = (double) measure_string (state.face, pt, String_val (string_v));
3254 ret_v = caml_copy_double (w);
3255 CAMLreturn (ret_v);
3258 ML (getpagebox (value opaque_v))
3260 CAMLparam1 (opaque_v);
3261 CAMLlocal1 (ret_v);
3262 fz_rect rect;
3263 fz_irect bbox;
3264 fz_device *dev;
3265 const char *s = String_val (opaque_v);
3266 struct page *page = parse_pointer (__func__, s);
3268 ret_v = caml_alloc_tuple (4);
3269 dev = fz_new_bbox_device (state.ctx, &rect);
3271 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3273 fz_close_device (state.ctx, dev);
3274 fz_drop_device (state.ctx, dev);
3275 bbox = fz_round_rect (rect);
3276 Field (ret_v, 0) = Val_int (bbox.x0);
3277 Field (ret_v, 1) = Val_int (bbox.y0);
3278 Field (ret_v, 2) = Val_int (bbox.x1);
3279 Field (ret_v, 3) = Val_int (bbox.y1);
3281 CAMLreturn (ret_v);
3284 ML0 (setaalevel (value level_v))
3286 CAMLparam1 (level_v);
3288 state.aalevel = Int_val (level_v);
3289 CAMLreturn0;
3292 ML0 (setpapercolor (value rgba_v))
3294 CAMLparam1 (rgba_v);
3296 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3297 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3298 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3299 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3300 CAMLreturn0;
3303 value ml_keysymtoutf8 (value keysym_v);
3304 #ifndef CIDER
3305 value ml_keysymtoutf8 (value keysym_v)
3307 CAMLparam1 (keysym_v);
3308 CAMLlocal1 (str_v);
3309 unsigned short keysym = (unsigned short) Int_val (keysym_v);
3310 Rune rune;
3311 extern long keysym2ucs (unsigned short);
3312 int len;
3313 char buf[5];
3315 rune = (Rune) keysym2ucs (keysym);
3316 len = fz_runetochar (buf, rune);
3317 buf[len] = 0;
3318 str_v = caml_copy_string (buf);
3319 CAMLreturn (str_v);
3321 #else
3322 value ml_keysymtoutf8 (value keysym_v)
3324 CAMLparam1 (keysym_v);
3325 CAMLlocal1 (str_v);
3326 long ucs = Long_val (keysym_v);
3327 int len;
3328 char buf[5];
3330 len = fz_runetochar (buf, (int) ucs);
3331 buf[len] = 0;
3332 str_v = caml_copy_string (buf);
3333 CAMLreturn (str_v);
3335 #endif
3337 enum { piunknown, pilinux, pimacos, pibsd };
3339 ML (platform (value unit_v))
3341 CAMLparam1 (unit_v);
3342 CAMLlocal2 (tup_v, arr_v);
3343 int platid = piunknown;
3344 struct utsname buf;
3346 #if defined __linux__
3347 platid = pilinux;
3348 #elif defined __DragonFly__ || defined __FreeBSD__
3349 || defined __OpenBSD__ || defined __NetBSD__
3350 platid = pibsd;
3351 #elif defined __APPLE__
3352 platid = pimacos;
3353 #endif
3354 if (uname (&buf)) err (1, "uname");
3356 tup_v = caml_alloc_tuple (2);
3358 char const *sar[] = {
3359 buf.sysname,
3360 buf.release,
3361 buf.version,
3362 buf.machine,
3363 NULL
3365 arr_v = caml_copy_string_array (sar);
3367 Field (tup_v, 0) = Val_int (platid);
3368 Field (tup_v, 1) = arr_v;
3369 CAMLreturn (tup_v);
3372 ML0 (cloexec (value fd_v))
3374 CAMLparam1 (fd_v);
3375 int fd = Int_val (fd_v);
3377 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3378 uerror ("fcntl", Nothing);
3380 CAMLreturn0;
3383 ML (getpbo (value w_v, value h_v, value cs_v))
3385 CAMLparam2 (w_v, h_v);
3386 CAMLlocal1 (ret_v);
3387 struct bo *pbo;
3388 int w = Int_val (w_v);
3389 int h = Int_val (h_v);
3390 int cs = Int_val (cs_v);
3392 if (state.bo_usable) {
3393 pbo = calloc (sizeof (*pbo), 1);
3394 if (!pbo) {
3395 err (1, "calloc pbo");
3398 switch (cs) {
3399 case 0:
3400 case 1:
3401 pbo->size = w*h*4;
3402 break;
3403 case 2:
3404 pbo->size = w*h*2;
3405 break;
3406 default:
3407 errx (1, "%s: invalid colorspace %d", __func__, cs);
3410 state.glGenBuffersARB (1, &pbo->id);
3411 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3412 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3413 NULL, GL_STREAM_DRAW);
3414 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3415 GL_READ_WRITE);
3416 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3417 if (!pbo->ptr) {
3418 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3419 state.glDeleteBuffersARB (1, &pbo->id);
3420 free (pbo);
3421 ret_v = caml_copy_string ("0");
3423 else {
3424 int res;
3425 char *s;
3427 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3428 if (res < 0) {
3429 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3431 s = malloc (res+1);
3432 if (!s) {
3433 err (1, "malloc %d bytes failed", res+1);
3435 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3436 if (res < 0) {
3437 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3439 ret_v = caml_copy_string (s);
3440 free (s);
3443 else {
3444 ret_v = caml_copy_string ("0");
3446 CAMLreturn (ret_v);
3449 ML0 (freepbo (value s_v))
3451 CAMLparam1 (s_v);
3452 const char *s = String_val (s_v);
3453 struct tile *tile = parse_pointer (__func__, s);
3455 if (tile->pbo) {
3456 state.glDeleteBuffersARB (1, &tile->pbo->id);
3457 tile->pbo->id = -1;
3458 tile->pbo->ptr = NULL;
3459 tile->pbo->size = -1;
3461 CAMLreturn0;
3464 ML0 (unmappbo (value s_v))
3466 CAMLparam1 (s_v);
3467 const char *s = String_val (s_v);
3468 struct tile *tile = parse_pointer (__func__, s);
3470 if (tile->pbo) {
3471 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3472 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3473 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3475 tile->pbo->ptr = NULL;
3476 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3478 CAMLreturn0;
3481 static void setuppbo (void)
3483 extern void (*wsigladdr (const char *name)) (void);
3484 #pragma GCC diagnostic push
3485 #ifdef __clang__
3486 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3487 #endif
3488 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3489 state.bo_usable = GPA (glBindBufferARB)
3490 && GPA (glUnmapBufferARB)
3491 && GPA (glMapBufferARB)
3492 && GPA (glBufferDataARB)
3493 && GPA (glGenBuffersARB)
3494 && GPA (glDeleteBuffersARB);
3495 #undef GPA
3496 #pragma GCC diagnostic pop
3499 ML (bo_usable (void))
3501 return Val_bool (state.bo_usable);
3504 ML (unproject (value ptr_v, value x_v, value y_v))
3506 CAMLparam3 (ptr_v, x_v, y_v);
3507 CAMLlocal2 (ret_v, tup_v);
3508 struct page *page;
3509 const char *s = String_val (ptr_v);
3510 int x = Int_val (x_v), y = Int_val (y_v);
3511 struct pagedim *pdim;
3512 fz_point p;
3514 page = parse_pointer (__func__, s);
3515 pdim = &state.pagedims[page->pdimno];
3517 ret_v = Val_int (0);
3518 if (trylock (__func__)) {
3519 goto done;
3522 p.x = x + pdim->bounds.x0;
3523 p.y = y + pdim->bounds.y0;
3525 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3526 pdim->ctm)));
3528 tup_v = caml_alloc_tuple (2);
3529 ret_v = caml_alloc_small (1, 1);
3530 Field (tup_v, 0) = Val_int (p.x);
3531 Field (tup_v, 1) = Val_int (p.y);
3532 Field (ret_v, 0) = tup_v;
3534 unlock (__func__);
3535 done:
3536 CAMLreturn (ret_v);
3539 ML (project (value ptr_v, value pageno_v, value pdimno_v, value x_v, value y_v))
3541 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3542 CAMLlocal1 (ret_v);
3543 struct page *page;
3544 const char *s = String_val (ptr_v);
3545 int pageno = Int_val (pageno_v);
3546 int pdimno = Int_val (pdimno_v);
3547 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3548 struct pagedim *pdim;
3549 fz_point p;
3550 fz_matrix ctm;
3552 ret_v = Val_int (0);
3553 lock (__func__);
3555 if (!*s) {
3556 page = loadpage (pageno, pdimno);
3558 else {
3559 page = parse_pointer (__func__, s);
3561 pdim = &state.pagedims[pdimno];
3563 if (pdf_specifics (state.ctx, state.doc)) {
3564 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3565 ctm = state.pagedims[page->pdimno].tctm;
3567 else {
3568 ctm = fz_identity;
3570 p.x = x + pdim->bounds.x0;
3571 p.y = y + pdim->bounds.y0;
3573 ctm = fz_concat (pdim->tctm, pdim->ctm);
3574 p = fz_transform_point (p, ctm);
3576 ret_v = caml_alloc_tuple (2);
3577 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3578 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3580 if (!*s) {
3581 freepage (page);
3583 unlock (__func__);
3584 CAMLreturn (ret_v);
3587 ML0 (addannot (value ptr_v, value x_v, value y_v, value contents_v))
3589 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3590 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3592 if (pdf) {
3593 pdf_annot *annot;
3594 struct page *page;
3595 fz_rect r;
3596 const char *s = String_val (ptr_v);
3598 page = parse_pointer (__func__, s);
3599 annot = pdf_create_annot (state.ctx,
3600 pdf_page_from_fz_page (state.ctx,
3601 page->fzpage),
3602 PDF_ANNOT_TEXT);
3603 r.x0 = Int_val (x_v) - 10;
3604 r.y0 = Int_val (y_v) - 10;
3605 r.x1 = r.x0 + 20;
3606 r.y1 = r.y0 + 20;
3607 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3608 pdf_set_annot_rect (state.ctx, annot, r);
3610 state.dirty = 1;
3612 CAMLreturn0;
3615 ML0 (delannot (value ptr_v, value n_v))
3617 CAMLparam2 (ptr_v, n_v);
3618 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3620 if (pdf) {
3621 struct page *page;
3622 const char *s = String_val (ptr_v);
3623 struct slink *slink;
3625 page = parse_pointer (__func__, s);
3626 slink = &page->slinks[Int_val (n_v)];
3627 pdf_delete_annot (state.ctx,
3628 pdf_page_from_fz_page (state.ctx, page->fzpage),
3629 (pdf_annot *) slink->u.annot);
3630 state.dirty = 1;
3632 CAMLreturn0;
3635 ML0 (modannot (value ptr_v, value n_v, value str_v))
3637 CAMLparam3 (ptr_v, n_v, str_v);
3638 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3640 if (pdf) {
3641 struct page *page;
3642 const char *s = String_val (ptr_v);
3643 struct slink *slink;
3645 page = parse_pointer (__func__, s);
3646 slink = &page->slinks[Int_val (n_v)];
3647 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3648 String_val (str_v));
3649 state.dirty = 1;
3651 CAMLreturn0;
3654 ML (hasunsavedchanges (void))
3656 return Val_bool (state.dirty);
3659 ML0 (savedoc (value path_v))
3661 CAMLparam1 (path_v);
3662 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3664 if (pdf) {
3665 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3667 CAMLreturn0;
3670 static void makestippletex (void)
3672 const char pixels[] = "\xff\xff\0\0";
3673 glGenTextures (1, &state.stid);
3674 glBindTexture (GL_TEXTURE_1D, state.stid);
3675 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3676 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3677 glTexImage1D (
3678 GL_TEXTURE_1D,
3680 GL_ALPHA,
3683 GL_ALPHA,
3684 GL_UNSIGNED_BYTE,
3685 pixels
3689 ML (fz_version (void))
3691 return caml_copy_string (FZ_VERSION);
3694 ML (llpp_version (void))
3696 extern char llpp_version[];
3697 return caml_copy_string (llpp_version);
3700 static void diag_callback (void *user, const char *message)
3702 printd ("emsg %s %s", (char *) user, message);
3705 static fz_font *lsff (fz_context *ctx,int UNUSED_ATTR script,
3706 int UNUSED_ATTR language, int UNUSED_ATTR serif,
3707 int UNUSED_ATTR bold, int UNUSED_ATTR italic)
3709 static fz_font *font;
3710 static int done;
3712 if (!done) {
3713 char *path = getenv ("LLPP_FALLBACK_FONT");
3714 if (path) font = fz_new_font_from_file (ctx, NULL, path, 0, 1);
3715 done = 1;
3717 return font;
3720 ML0 (init (value csock_v, value params_v))
3722 CAMLparam2 (csock_v, params_v);
3723 CAMLlocal2 (trim_v, fuzz_v);
3724 int ret;
3725 int texcount;
3726 const char *fontpath;
3727 int colorspace;
3728 int mustoresize;
3730 state.csock = Int_val (csock_v);
3731 state.rotate = Int_val (Field (params_v, 0));
3732 state.fitmodel = Int_val (Field (params_v, 1));
3733 trim_v = Field (params_v, 2);
3734 texcount = Int_val (Field (params_v, 3));
3735 state.sliceheight = Int_val (Field (params_v, 4));
3736 mustoresize = Int_val (Field (params_v, 5));
3737 colorspace = Int_val (Field (params_v, 6));
3738 fontpath = String_val (Field (params_v, 7));
3740 #ifdef CIDER
3741 state.utf8cs = 1;
3742 #else
3743 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3744 if (setlocale (LC_CTYPE, "")) {
3745 const char *cset = nl_langinfo (CODESET);
3746 state.utf8cs = !strcmp (cset, "UTF-8");
3748 else {
3749 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3751 #endif
3753 if (caml_string_length (Field (params_v, 8)) > 0) {
3754 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3756 if (!state.trimcachepath) {
3757 printd ("emsg failed to strdup trimcachepath: %d:%s",
3758 errno, strerror (errno));
3762 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3763 fz_register_document_handlers (state.ctx);
3764 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3765 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3766 fz_install_load_system_font_funcs (state.ctx, NULL, NULL, lsff);
3768 state.trimmargins = Bool_val (Field (trim_v, 0));
3769 fuzz_v = Field (trim_v, 1);
3770 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3771 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3772 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3773 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3775 set_tex_params (colorspace);
3777 if (*fontpath) {
3778 state.face = load_font (fontpath);
3780 else {
3781 int len;
3782 const unsigned char *data;
3784 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3785 state.face = load_builtin_font (data, len);
3787 if (!state.face) _exit (1);
3789 realloctexts (texcount);
3790 setuppbo ();
3791 makestippletex ();
3793 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3794 if (ret) {
3795 errx (1, "pthread_create: %s", strerror (ret));
3798 CAMLreturn0;
3801 #if FIXME || !FIXME
3802 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3803 #endif