Remove CACHE_PAGEREFS "optimization"
[llpp.git] / link.c
blob6dd48aceb3ee30a6826020727d81d6a6bbf4f4e5
1 /* lots of code c&p-ed directly from mupdf */
2 #define FIXME 0
4 #ifdef __clang__
5 #pragma GCC diagnostic error "-Weverything"
6 #pragma GCC diagnostic ignored "-Wpadded"
7 #pragma GCC diagnostic ignored "-Wsign-conversion"
8 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
9 #pragma GCC diagnostic ignored "-Wdocumentation"
10 #pragma GCC diagnostic ignored "-Wdouble-promotion"
11 #endif
13 extern char **environ;
15 #include <errno.h>
16 #include <stdio.h>
17 #include <ctype.h>
18 #include <string.h>
19 #include <stdlib.h>
20 #include <signal.h>
22 #include <math.h>
23 #include <wchar.h>
24 #include <locale.h>
25 #include <langinfo.h>
27 #include <unistd.h>
28 #include <pthread.h>
29 #include <sys/uio.h>
30 #include <sys/time.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/utsname.h>
37 #include <spawn.h>
39 #include <regex.h>
40 #include <stdarg.h>
41 #include <limits.h>
42 #include <inttypes.h>
44 #ifdef CIDER
45 #include <OpenGL/gl.h>
46 #else
47 #include <GL/gl.h>
48 #endif
50 #pragma GCC diagnostic push
51 #ifdef __clang__
52 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
53 #endif
54 #pragma GCC diagnostic ignored "-Wpedantic"
55 #define CAML_NAME_SPACE
56 #include <caml/fail.h>
57 #include <caml/alloc.h>
58 #include <caml/memory.h>
59 #include <caml/unixsupport.h>
61 #pragma GCC diagnostic push
62 #pragma GCC diagnostic ignored "-Wfloat-equal"
63 #include <mupdf/fitz.h>
64 #include <mupdf/pdf.h>
65 #pragma GCC diagnostic pop
67 #include <ft2build.h>
68 #include FT_FREETYPE_H
69 #pragma GCC diagnostic pop
71 #include "cutils.h"
73 #ifdef USE_NPOT
74 #define TEXT_TYPE GL_TEXTURE_2D
75 #else
76 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
77 #endif
79 #if 0
80 #define lprintf printf
81 #else
82 #define lprintf(...)
83 #endif
85 #define ARSERT(cond) for (;;) { \
86 if (!(cond)) { \
87 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
88 } \
89 break; \
92 struct slice {
93 int h;
94 int texindex;
97 struct tile {
98 int w, h;
99 int slicecount;
100 int sliceheight;
101 struct bo *pbo;
102 fz_pixmap *pixmap;
103 struct slice slices[1];
106 struct pagedim {
107 int pageno;
108 int rotate;
109 int left;
110 int tctmready;
111 fz_irect bounds;
112 fz_rect pagebox;
113 fz_rect mediabox;
114 fz_matrix ctm, zoomctm, tctm;
117 struct slink {
118 enum { SLINK, SANNOT } tag;
119 fz_irect bbox;
120 union {
121 fz_link *link;
122 pdf_annot *annot;
123 } u;
126 struct annot {
127 fz_irect bbox;
128 pdf_annot *annot;
131 struct page {
132 int tgen;
133 int sgen;
134 int agen;
135 int pageno;
136 int pdimno;
137 fz_stext_page *text;
138 fz_page *fzpage;
139 fz_display_list *dlist;
140 fz_link *links;
141 int slinkcount;
142 struct slink *slinks;
143 int annotcount;
144 struct annot *annots;
145 fz_stext_char *fmark, *lmark;
148 enum { FitWidth, FitProportional, FitPage };
150 static struct {
151 int sliceheight;
152 struct pagedim *pagedims;
153 int pagecount;
154 int pagedimcount;
155 fz_document *doc;
156 fz_context *ctx;
157 int w, h;
159 int texindex;
160 int texcount;
161 GLuint *texids;
163 GLenum texiform;
164 GLenum texform;
165 GLenum texty;
167 fz_colorspace *colorspace;
169 struct {
170 int w, h;
171 struct slice *slice;
172 } *texowners;
174 int rotate;
175 int fitmodel;
176 int trimmargins;
177 int needoutline;
178 int gen;
179 int aalevel;
181 int trimanew;
182 fz_irect trimfuzz;
183 fz_pixmap *pig;
185 pthread_t thread;
186 int csock;
187 FT_Face face;
189 char *trimcachepath;
190 int dirty;
192 GLuint stid;
194 int bo_usable;
195 GLuint boid;
197 void (*glBindBufferARB) (GLenum, GLuint);
198 GLboolean (*glUnmapBufferARB) (GLenum);
199 void *(*glMapBufferARB) (GLenum, GLenum);
200 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
201 void (*glGenBuffersARB) (GLsizei, GLuint *);
202 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
204 GLfloat texcoords[8];
205 GLfloat vertices[16];
207 int utf8cs;
208 } state;
210 struct bo {
211 GLuint id;
212 void *ptr;
213 size_t size;
216 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
218 static void lock (const char *cap)
220 int ret = pthread_mutex_lock (&mutex);
221 if (ret) {
222 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
226 static void unlock (const char *cap)
228 int ret = pthread_mutex_unlock (&mutex);
229 if (ret) {
230 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
234 static int trylock (const char *cap)
236 int ret = pthread_mutex_trylock (&mutex);
237 if (ret && ret != EBUSY) {
238 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
240 return ret == EBUSY;
243 static int hasdata (void)
245 int ret, avail;
246 ret = ioctl (state.csock, FIONREAD, &avail);
247 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
248 return avail > 0;
251 value ml_hasdata (value fd_v);
252 value ml_hasdata (value fd_v)
254 CAMLparam1 (fd_v);
255 int ret, avail;
257 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
258 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
259 CAMLreturn (Val_bool (avail > 0));
262 static void readdata (int fd, void *p, int size)
264 ssize_t n;
266 again:
267 n = read (fd, p, size);
268 if (n - size) {
269 if (n < 0 && errno == EINTR) goto again;
270 if (!n) errx (1, "EOF while reading");
271 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
275 static void writedata (int fd, char *p, int size)
277 ssize_t n;
278 uint32_t size4 = size;
279 struct iovec iov[2] = {
280 { .iov_base = &size4, .iov_len = 4 },
281 { .iov_base = p, .iov_len = size }
284 again:
285 n = writev (fd, iov, 2);
286 if (n < 0 && errno == EINTR) goto again;
287 if (n - size - 4) {
288 if (!n) errx (1, "EOF while writing data");
289 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
293 static int readlen (int fd)
295 uint32_t u;
296 readdata (fd, &u, 4);
297 return u;
300 void ml_wcmd (value fd_v, value bytes_v, value len_v);
301 void ml_wcmd (value fd_v, value bytes_v, value len_v)
303 CAMLparam3 (fd_v, bytes_v, len_v);
304 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
305 CAMLreturn0;
308 value ml_rcmd (value fd_v);
309 value ml_rcmd (value fd_v)
311 CAMLparam1 (fd_v);
312 CAMLlocal1 (strdata_v);
313 int fd = Int_val (fd_v);
314 int len = readlen (fd);
315 strdata_v = caml_alloc_string (len);
316 readdata (fd, String_val (strdata_v), len);
317 CAMLreturn (strdata_v);
320 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
322 char fbuf[64];
323 int size = sizeof (fbuf), len;
324 va_list ap;
325 char *buf = fbuf;
327 for (;;) {
328 va_start (ap, fmt);
329 len = vsnprintf (buf, size, fmt, ap);
330 va_end (ap);
332 if (len > -1) {
333 if (len < size - 4) {
334 writedata (state.csock, buf, len);
335 break;
337 else size = len + 5;
339 else {
340 err (1, "vsnprintf for `%s' failed", fmt);
342 buf = realloc (buf == fbuf ? NULL : buf, size);
343 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
345 if (buf != fbuf) free (buf);
348 static void closedoc (void)
350 if (state.doc) {
351 fz_drop_document (state.ctx, state.doc);
352 state.doc = NULL;
356 static int openxref (char *filename, char *password, int layouth)
358 for (int i = 0; i < state.texcount; ++i) {
359 state.texowners[i].w = -1;
360 state.texowners[i].slice = NULL;
363 closedoc ();
365 state.dirty = 0;
366 if (state.pagedims) {
367 free (state.pagedims);
368 state.pagedims = NULL;
370 state.pagedimcount = 0;
372 fz_set_aa_level (state.ctx, state.aalevel);
373 state.doc = fz_open_document (state.ctx, filename);
374 if (fz_needs_password (state.ctx, state.doc)) {
375 if (password && !*password) {
376 printd ("pass");
377 return 0;
379 else {
380 int ok = fz_authenticate_password (state.ctx, state.doc, password);
381 if (!ok) {
382 printd ("pass fail");
383 return 0;
387 if (layouth >= 0)
388 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
389 state.pagecount = fz_count_pages (state.ctx, state.doc);
390 return 1;
393 static void docinfo (void)
395 struct { char *tag; char *name; } metatbl[] = {
396 { FZ_META_INFO_TITLE, "Title" },
397 { FZ_META_INFO_AUTHOR, "Author" },
398 { FZ_META_FORMAT, "Format" },
399 { FZ_META_ENCRYPTION, "Encryption" },
400 { "info:Creator", "Creator" },
401 { "info:Producer", "Producer" },
402 { "info:CreationDate", "Creation date" },
404 int len = 0;
405 char *buf = NULL;
407 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
408 int need;
409 again:
410 need = fz_lookup_metadata (state.ctx, state.doc,
411 metatbl[i].tag, buf, len);
412 if (need > 0) {
413 if (need <= len) {
414 printd ("info %s\t%s", metatbl[i].name, buf);
416 else {
417 buf = realloc (buf, need + 1);
418 if (!buf) err (1, "docinfo realloc %d", need + 1);
419 len = need + 1;
420 goto again;
424 free (buf);
426 printd ("infoend");
429 static void unlinktile (struct tile *tile)
431 for (int i = 0; i < tile->slicecount; ++i) {
432 struct slice *s = &tile->slices[i];
434 if (s->texindex != -1) {
435 if (state.texowners[s->texindex].slice == s) {
436 state.texowners[s->texindex].slice = NULL;
442 static void freepage (struct page *page)
444 if (!page) return;
445 if (page->text) {
446 fz_drop_stext_page (state.ctx, page->text);
448 if (page->slinks) {
449 free (page->slinks);
451 fz_drop_display_list (state.ctx, page->dlist);
452 fz_drop_page (state.ctx, page->fzpage);
453 free (page);
456 static void freetile (struct tile *tile)
458 unlinktile (tile);
459 if (!tile->pbo) {
460 #if 0
461 fz_drop_pixmap (state.ctx, tile->pixmap);
462 #else /* piggyback */
463 if (state.pig) {
464 fz_drop_pixmap (state.ctx, state.pig);
466 state.pig = tile->pixmap;
467 #endif
469 else {
470 free (tile->pbo);
471 fz_drop_pixmap (state.ctx, tile->pixmap);
473 free (tile);
476 static void trimctm (pdf_page *page, int pindex)
478 struct pagedim *pdim = &state.pagedims[pindex];
480 if (!page) return;
481 if (!pdim->tctmready) {
482 fz_rect realbox, mediabox;
483 fz_matrix page_ctm, ctm;
485 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
486 realbox = fz_transform_rect (pdim->mediabox, ctm);
487 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
488 pdim->tctm = fz_concat (
489 fz_invert_matrix (page_ctm),
490 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
491 pdim->tctmready = 1;
495 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
497 fz_matrix ctm;
498 ptrdiff_t pdimno = pdim - state.pagedims;
500 ARSERT (pdim - state.pagedims < INT_MAX);
501 if (pdf_specifics (state.ctx, state.doc)) {
502 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
503 ctm = fz_concat (pdim->tctm, pdim->ctm);
505 else {
506 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
507 pdim->ctm);
509 return ctm;
512 static fz_matrix pagectm (struct page *page)
514 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
517 static void *loadpage (int pageno, int pindex)
519 fz_device *dev;
520 struct page *page;
522 page = calloc (sizeof (struct page), 1);
523 if (!page) {
524 err (1, "calloc page %d", pageno);
527 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
528 dev = fz_new_list_device (state.ctx, page->dlist);
529 fz_try (state.ctx) {
530 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
531 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
533 fz_catch (state.ctx) {
534 page->fzpage = NULL;
536 fz_close_device (state.ctx, dev);
537 fz_drop_device (state.ctx, dev);
539 page->pdimno = pindex;
540 page->pageno = pageno;
541 page->sgen = state.gen;
542 page->agen = state.gen;
543 page->tgen = state.gen;
544 return page;
547 static struct tile *alloctile (int h)
549 int slicecount;
550 size_t tilesize;
551 struct tile *tile;
553 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
554 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
555 tile = calloc (tilesize, 1);
556 if (!tile) {
557 err (1, "cannot allocate tile (%zu bytes)", tilesize);
559 for (int i = 0; i < slicecount; ++i) {
560 int sh = fz_mini (h, state.sliceheight);
561 tile->slices[i].h = sh;
562 tile->slices[i].texindex = -1;
563 h -= sh;
565 tile->slicecount = slicecount;
566 tile->sliceheight = state.sliceheight;
567 return tile;
570 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
571 struct bo *pbo)
573 fz_irect bbox;
574 fz_matrix ctm;
575 fz_device *dev;
576 struct tile *tile;
577 struct pagedim *pdim;
579 tile = alloctile (h);
580 pdim = &state.pagedims[page->pdimno];
582 bbox = pdim->bounds;
583 bbox.x0 += x;
584 bbox.y0 += y;
585 bbox.x1 = bbox.x0 + w;
586 bbox.y1 = bbox.y0 + h;
588 if (state.pig) {
589 if (state.pig->w == w
590 && state.pig->h == h
591 && state.pig->colorspace == state.colorspace) {
592 tile->pixmap = state.pig;
593 tile->pixmap->x = bbox.x0;
594 tile->pixmap->y = bbox.y0;
596 else {
597 fz_drop_pixmap (state.ctx, state.pig);
599 state.pig = NULL;
601 if (!tile->pixmap) {
602 if (pbo) {
603 tile->pixmap =
604 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
605 bbox, NULL, 1, pbo->ptr);
606 tile->pbo = pbo;
608 else {
609 tile->pixmap =
610 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
611 NULL, 1);
615 tile->w = w;
616 tile->h = h;
617 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
619 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
620 ctm = pagectm (page);
621 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
622 fz_rect_from_irect (bbox), NULL);
623 fz_close_device (state.ctx, dev);
624 fz_drop_device (state.ctx, dev);
626 return tile;
629 static void initpdims (void)
631 double start, end;
632 FILE *trimf = NULL;
633 fz_rect rootmediabox = fz_empty_rect;
634 int pageno, trim, show;
635 int trimw = 0, cxcount;
636 fz_context *ctx = state.ctx;
637 pdf_document *pdf = pdf_specifics (ctx, state.doc);
639 fz_var (trimw);
640 fz_var (trimf);
641 fz_var (cxcount);
642 start = now ();
644 if (state.trimmargins && state.trimcachepath) {
645 trimf = fopen (state.trimcachepath, "rb");
646 if (!trimf) {
647 trimf = fopen (state.trimcachepath, "wb");
648 trimw = 1;
652 cxcount = state.pagecount;
653 if (pdf) {
654 pdf_obj *obj;
655 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
656 "Root/Pages/MediaBox");
657 rootmediabox = pdf_to_rect (ctx, obj);
658 pdf_load_page_tree (state.ctx, pdf);
661 for (pageno = 0; pageno < cxcount; ++pageno) {
662 int rotate = 0;
663 struct pagedim *p;
664 fz_rect mediabox = fz_empty_rect;
666 fz_var (rotate);
667 if (pdf) {
668 pdf_obj *pageobj = pdf_get_xref_entry (
669 state.ctx, pdf, pdf->rev_page_map[pageno].object
670 )->obj;
672 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
674 if (state.trimmargins) {
675 pdf_obj *obj;
676 pdf_page *page;
678 fz_try (ctx) {
679 page = pdf_load_page (ctx, pdf, pageno);
680 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
681 trim = state.trimanew || !obj;
682 if (trim) {
683 fz_rect rect;
684 fz_device *dev;
685 fz_matrix ctm, page_ctm;
687 dev = fz_new_bbox_device (ctx, &rect);
688 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
689 ctm = fz_invert_matrix (page_ctm);
690 pdf_run_page (ctx, page, dev, fz_identity, NULL);
691 fz_close_device (ctx, dev);
692 fz_drop_device (ctx, dev);
694 rect.x0 += state.trimfuzz.x0;
695 rect.x1 += state.trimfuzz.x1;
696 rect.y0 += state.trimfuzz.y0;
697 rect.y1 += state.trimfuzz.y1;
698 rect = fz_transform_rect (rect, ctm);
699 rect = fz_intersect_rect (rect, mediabox);
701 if (!fz_is_empty_rect (rect)) {
702 mediabox = rect;
705 obj = pdf_new_array (ctx, pdf, 4);
706 pdf_array_push (ctx, obj,
707 pdf_new_real (ctx, mediabox.x0));
708 pdf_array_push (ctx, obj,
709 pdf_new_real (ctx, mediabox.y0));
710 pdf_array_push (ctx, obj,
711 pdf_new_real (ctx, mediabox.x1));
712 pdf_array_push (ctx, obj,
713 pdf_new_real (ctx, mediabox.y1));
714 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
716 else {
717 mediabox.x0 = pdf_to_real (ctx,
718 pdf_array_get (ctx, obj, 0));
719 mediabox.y0 = pdf_to_real (ctx,
720 pdf_array_get (ctx, obj, 1));
721 mediabox.x1 = pdf_to_real (ctx,
722 pdf_array_get (ctx, obj, 2));
723 mediabox.y1 = pdf_to_real (ctx,
724 pdf_array_get (ctx, obj, 3));
727 fz_drop_page (ctx, &page->super);
728 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
729 if (show) {
730 printd ("progress %f Trimming %d",
731 (double) (pageno + 1) / state.pagecount,
732 pageno + 1);
735 fz_catch (ctx) {
736 printd ("emsg failed to load page %d", pageno);
739 else {
740 int empty = 0;
741 fz_rect cropbox;
743 mediabox =
744 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "MediaBox"));
745 if (fz_is_empty_rect (mediabox)) {
746 mediabox.x0 = 0;
747 mediabox.y0 = 0;
748 mediabox.x1 = 612;
749 mediabox.y1 = 792;
750 empty = 1;
753 cropbox =
754 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
755 if (!fz_is_empty_rect (cropbox)) {
756 if (empty) {
757 mediabox = cropbox;
759 else {
760 mediabox = fz_intersect_rect (mediabox, cropbox);
763 else {
764 if (empty) {
765 if (fz_is_empty_rect (rootmediabox)) {
766 printd ("emsg cannot find page size for page %d",
767 pageno);
769 else {
770 mediabox = rootmediabox;
776 else {
777 if (state.trimmargins && trimw) {
778 fz_page *page;
780 fz_try (ctx) {
781 page = fz_load_page (ctx, state.doc, pageno);
782 mediabox = fz_bound_page (ctx, page);
783 if (state.trimmargins) {
784 fz_rect rect;
785 fz_device *dev;
787 dev = fz_new_bbox_device (ctx, &rect);
788 fz_run_page (ctx, page, dev, fz_identity, NULL);
789 fz_close_device (ctx, dev);
790 fz_drop_device (ctx, dev);
792 rect.x0 += state.trimfuzz.x0;
793 rect.x1 += state.trimfuzz.x1;
794 rect.y0 += state.trimfuzz.y0;
795 rect.y1 += state.trimfuzz.y1;
796 rect = fz_intersect_rect (rect, mediabox);
798 if (!fz_is_empty_rect (rect)) {
799 mediabox = rect;
802 fz_drop_page (ctx, page);
804 fz_catch (ctx) {
806 if (trimf) {
807 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
808 if (n - 1) {
809 err (1, "fwrite trim mediabox");
813 else {
814 if (trimf) {
815 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
816 if (n - 1) {
817 err (1, "fread trim mediabox %d", pageno);
820 else {
821 fz_page *page;
822 fz_try (ctx) {
823 page = fz_load_page (ctx, state.doc, pageno);
824 mediabox = fz_bound_page (ctx, page);
825 fz_drop_page (ctx, page);
827 show = !state.trimmargins && pageno % 20 == 0;
828 if (show) {
829 printd ("progress %f Gathering dimensions %d",
830 (double) (pageno) / state.pagecount,
831 pageno);
834 fz_catch (ctx) {
835 printd ("emsg failed to load page %d", pageno);
841 if (state.pagedimcount == 0
842 || ((void) (p = &state.pagedims[state.pagedimcount-1])
843 , p->rotate != rotate)
844 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
845 size_t size;
847 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
848 state.pagedims = realloc (state.pagedims, size);
849 if (!state.pagedims) {
850 err (1, "realloc pagedims to %zu (%d elems)",
851 size, state.pagedimcount + 1);
854 p = &state.pagedims[state.pagedimcount++];
855 p->rotate = rotate;
856 p->mediabox = mediabox;
857 p->pageno = pageno;
860 end = now ();
861 printd ("progress 1 %s %d pages in %f seconds",
862 state.trimmargins ? "Trimmed" : "Processed",
863 state.pagecount, end - start);
864 state.trimanew = 0;
865 if (trimf) {
866 if (fclose (trimf)) {
867 err (1, "fclose");
872 static void layout (void)
874 int pindex;
875 fz_rect box;
876 fz_matrix ctm;
877 struct pagedim *p = NULL;
878 float zw, w, maxw = 0.0, zoom = 1.0;
880 if (state.pagedimcount == 0) return;
882 switch (state.fitmodel) {
883 case FitProportional:
884 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
885 float x0, x1;
887 p = &state.pagedims[pindex];
888 box = fz_transform_rect (p->mediabox,
889 fz_rotate (p->rotate + state.rotate));
891 x0 = fz_min (box.x0, box.x1);
892 x1 = fz_max (box.x0, box.x1);
894 w = x1 - x0;
895 maxw = fz_max (w, maxw);
896 zoom = state.w / maxw;
898 break;
900 case FitPage:
901 maxw = state.w;
902 break;
904 case FitWidth:
905 break;
907 default:
908 ARSERT (0 && state.fitmodel);
911 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
912 p = &state.pagedims[pindex];
913 ctm = fz_rotate (state.rotate);
914 box = fz_transform_rect (p->mediabox,
915 fz_rotate (p->rotate + state.rotate));
916 w = box.x1 - box.x0;
917 switch (state.fitmodel) {
918 case FitProportional:
919 p->left = (int) (((maxw - w) * zoom) / 2.f);
920 break;
921 case FitPage:
923 float zh, h;
924 zw = maxw / w;
925 h = box.y1 - box.y0;
926 zh = state.h / h;
927 zoom = fz_min (zw, zh);
928 p->left = (int) ((maxw - (w * zoom)) / 2.f);
930 break;
931 case FitWidth:
932 p->left = 0;
933 zoom = state.w / w;
934 break;
937 p->zoomctm = fz_scale (zoom, zoom);
938 ctm = fz_concat (p->zoomctm, ctm);
940 p->pagebox = p->mediabox;
941 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
942 p->pagebox.x1 -= p->pagebox.x0;
943 p->pagebox.y1 -= p->pagebox.y0;
944 p->pagebox.x0 = 0;
945 p->pagebox.y0 = 0;
946 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
947 p->ctm = ctm;
949 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
950 fz_scale (zoom, -zoom));
951 p->tctmready = 0;
954 do {
955 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
956 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
957 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
958 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
959 int boundw = x1 - x0;
960 int boundh = y1 - y0;
962 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
963 } while (p-- != state.pagedims);
966 static struct pagedim *pdimofpageno (int pageno)
968 struct pagedim *pdim = state.pagedims;
970 for (int i = 0; i < state.pagedimcount; ++i) {
971 if (state.pagedims[i].pageno > pageno)
972 break;
973 pdim = &state.pagedims[i];
975 return pdim;
978 static void recurse_outline (fz_outline *outline, int level)
980 while (outline) {
981 if (outline->page >= 0) {
982 fz_point p = {.x = outline->x, .y = outline->y};
983 struct pagedim *pdim = pdimofpageno (outline->page);
984 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
985 p = fz_transform_point (p, pdim->ctm);
986 printd ("o %d %d %d %d %s",
987 level, outline->page, (int) p.y, h, outline->title);
989 else {
990 printd ("on %d %s", level, outline->title);
992 if (outline->down) {
993 recurse_outline (outline->down, level + 1);
995 outline = outline->next;
999 static void process_outline (void)
1001 fz_outline *outline;
1003 if (!state.needoutline || !state.pagedimcount) return;
1005 state.needoutline = 0;
1006 outline = fz_load_outline (state.ctx, state.doc);
1007 if (outline) {
1008 recurse_outline (outline, 0);
1009 fz_drop_outline (state.ctx, outline);
1013 static char *strofline (fz_stext_line *line)
1015 char *p;
1016 char utf8[10];
1017 fz_stext_char *ch;
1018 size_t size = 0, cap = 80;
1020 p = malloc (cap + 1);
1021 if (!p) return NULL;
1023 for (ch = line->first_char; ch; ch = ch->next) {
1024 int n = fz_runetochar (utf8, ch->c);
1025 if (size + n > cap) {
1026 cap *= 2;
1027 p = realloc (p, cap + 1);
1028 if (!p) return NULL;
1031 memcpy (p + size, utf8, n);
1032 size += n;
1034 p[size] = 0;
1035 return p;
1038 static int matchline (regex_t *re, fz_stext_line *line,
1039 int stop, int pageno, double start)
1041 int ret;
1042 char *p;
1043 regmatch_t rm;
1045 p = strofline (line);
1046 if (!p) return -1;
1048 ret = regexec (re, p, 1, &rm, 0);
1049 if (ret) {
1050 free (p);
1051 if (ret != REG_NOMATCH) {
1052 size_t size;
1053 char errbuf[80];
1054 size = regerror (ret, re, errbuf, sizeof (errbuf));
1055 printd ("msg regexec error `%.*s'",
1056 (int) size, errbuf);
1057 return -1;
1059 return 0;
1061 else {
1062 fz_quad s, e;
1063 fz_stext_char *ch;
1064 int o = 0;
1066 for (ch = line->first_char; ch; ch = ch->next) {
1067 o += fz_runelen (ch->c);
1068 if (o > rm.rm_so) {
1069 s = ch->quad;
1070 break;
1073 for (;ch; ch = ch->next) {
1074 o += fz_runelen (ch->c);
1075 if (o > rm.rm_eo) break;
1077 e = ch->quad;
1079 if (!stop) {
1080 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1081 pageno, 1,
1082 s.ul.x, s.ul.y,
1083 e.ur.x, s.ul.y,
1084 e.lr.x, e.lr.y,
1085 s.ul.x, e.lr.y);
1087 printd ("progress 1 found at %d `%.*s' in %f sec",
1088 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1089 now () - start);
1091 else {
1092 printd ("match %d %d %f %f %f %f %f %f %f %f",
1093 pageno, 2,
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 free (p);
1100 return 1;
1104 /* wishful thinking function */
1105 static void search (regex_t *re, int pageno, int y, int forward)
1107 fz_device *tdev;
1108 fz_stext_page *text;
1109 struct pagedim *pdim;
1110 int stop = 0, niters = 0;
1111 double start, end;
1112 fz_page *page;
1113 fz_stext_block *block;
1115 start = now ();
1116 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1117 if (niters++ == 5) {
1118 niters = 0;
1119 if (hasdata ()) {
1120 printd ("progress 1 attention requested aborting search at %d",
1121 pageno);
1122 stop = 1;
1124 else {
1125 printd ("progress %f searching in page %d",
1126 (double) (pageno + 1) / state.pagecount,
1127 pageno);
1130 pdim = pdimofpageno (pageno);
1131 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1132 tdev = fz_new_stext_device (state.ctx, text, 0);
1134 page = fz_load_page (state.ctx, state.doc, pageno);
1135 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1137 fz_close_device (state.ctx, tdev);
1138 fz_drop_device (state.ctx, tdev);
1140 if (forward) {
1141 for (block = text->first_block; block; block = block->next) {
1142 fz_stext_line *line;
1144 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1145 for (line = block->u.t.first_line; line; line = line->next) {
1146 if (line->bbox.y0 < y + 1) continue;
1148 switch (matchline (re, line, stop, pageno, start)) {
1149 case 0: break;
1150 case 1: stop = 1; break;
1151 case -1: stop = 1; goto endloop;
1156 else {
1157 for (block = text->last_block; block; block = block->prev) {
1158 fz_stext_line *line;
1160 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1161 for (line = block->u.t.last_line; line; line = line->prev) {
1162 if (line->bbox.y0 < y + 1) continue;
1164 switch (matchline (re, line, stop, pageno, start)) {
1165 case 0: break;
1166 case 1: stop = 1; break;
1167 case -1: stop = 1; goto endloop;
1173 if (forward) {
1174 pageno += 1;
1175 y = 0;
1177 else {
1178 pageno -= 1;
1179 y = INT_MAX;
1181 endloop:
1182 fz_drop_stext_page (state.ctx, text);
1183 fz_drop_page (state.ctx, page);
1185 end = now ();
1186 if (!stop) {
1187 printd ("progress 1 no matches %f sec", end - start);
1189 printd ("clearrects");
1192 static void set_tex_params (int colorspace)
1194 switch (colorspace) {
1195 case 0:
1196 state.texiform = GL_RGBA8;
1197 state.texform = GL_RGBA;
1198 state.texty = GL_UNSIGNED_BYTE;
1199 state.colorspace = fz_device_rgb (state.ctx);
1200 break;
1201 case 1:
1202 state.texiform = GL_LUMINANCE_ALPHA;
1203 state.texform = GL_LUMINANCE_ALPHA;
1204 state.texty = GL_UNSIGNED_BYTE;
1205 state.colorspace = fz_device_gray (state.ctx);
1206 break;
1207 default:
1208 errx (1, "invalid colorspce %d", colorspace);
1212 static void realloctexts (int texcount)
1214 size_t size;
1216 if (texcount == state.texcount) return;
1218 if (texcount < state.texcount) {
1219 glDeleteTextures (state.texcount - texcount,
1220 state.texids + texcount);
1223 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1224 state.texids = realloc (state.texids, size);
1225 if (!state.texids) {
1226 err (1, "realloc texs %zu", size);
1229 state.texowners = (void *) (state.texids + texcount);
1230 if (texcount > state.texcount) {
1231 glGenTextures (texcount - state.texcount,
1232 state.texids + state.texcount);
1233 for (int i = state.texcount; i < texcount; ++i) {
1234 state.texowners[i].w = -1;
1235 state.texowners[i].slice = NULL;
1238 state.texcount = texcount;
1239 state.texindex = 0;
1242 static char *mbtoutf8 (char *s)
1244 char *p, *r;
1245 wchar_t *tmp;
1246 size_t i, ret, len;
1248 if (state.utf8cs) {
1249 return s;
1252 len = mbstowcs (NULL, s, strlen (s));
1253 if (len == 0 || len == (size_t) -1) {
1254 if (len)
1255 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1256 return s;
1259 tmp = calloc (len, sizeof (wchar_t));
1260 if (!tmp) {
1261 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1262 len, sizeof (wchar_t), errno, strerror (errno));
1263 return s;
1266 ret = mbstowcs (tmp, s, len);
1267 if (ret == (size_t) -1) {
1268 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1269 len, errno, strerror (errno));
1270 free (tmp);
1271 return s;
1274 len = 0;
1275 for (i = 0; i < ret; ++i) {
1276 len += fz_runelen (tmp[i]);
1279 p = r = malloc (len + 1);
1280 if (!r) {
1281 printd ("emsg mbtoutf8: malloc(%zu)", len);
1282 free (tmp);
1283 return s;
1286 for (i = 0; i < ret; ++i) {
1287 p += fz_runetochar (p, tmp[i]);
1289 *p = 0;
1290 free (tmp);
1291 return r;
1294 value ml_mbtoutf8 (value s_v);
1295 value ml_mbtoutf8 (value s_v)
1297 CAMLparam1 (s_v);
1298 CAMLlocal1 (ret_v);
1299 char *s, *r;
1301 s = String_val (s_v);
1302 r = mbtoutf8 (s);
1303 if (r == s) {
1304 ret_v = s_v;
1306 else {
1307 ret_v = caml_copy_string (r);
1308 free (r);
1310 CAMLreturn (ret_v);
1313 static void * mainloop (void UNUSED_ATTR *unused)
1315 char *p = NULL;
1316 int len, ret, oldlen = 0;
1318 fz_var (p);
1319 fz_var (oldlen);
1320 for (;;) {
1321 len = readlen (state.csock);
1322 if (len == 0) {
1323 errx (1, "readlen returned 0");
1326 if (oldlen < len + 1) {
1327 p = realloc (p, len + 1);
1328 if (!p) {
1329 err (1, "realloc %d failed", len + 1);
1331 oldlen = len + 1;
1333 readdata (state.csock, p, len);
1334 p[len] = 0;
1336 if (!strncmp ("open", p, 4)) {
1337 int off, usedoccss, ok = 0, layouth;
1338 char *password;
1339 char *filename;
1340 char *utf8filename;
1341 size_t filenamelen;
1343 fz_var (ok);
1344 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1345 if (ret != 2) {
1346 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1349 filename = p + 5 + off;
1350 filenamelen = strlen (filename);
1351 password = filename + filenamelen + 1;
1353 if (password[strlen (password) + 1]) {
1354 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1357 lock ("open");
1358 fz_set_use_document_css (state.ctx, usedoccss);
1359 fz_try (state.ctx) {
1360 ok = openxref (filename, password, layouth);
1362 fz_catch (state.ctx) {
1363 utf8filename = mbtoutf8 (filename);
1364 printd ("msg Could not open %s", utf8filename);
1365 if (utf8filename != filename) {
1366 free (utf8filename);
1369 if (ok) {
1370 docinfo ();
1371 initpdims ();
1373 unlock ("open");
1375 if (ok) {
1376 utf8filename = mbtoutf8 (filename);
1377 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1378 if (utf8filename != filename) {
1379 free (utf8filename);
1381 state.needoutline = 1;
1384 else if (!strncmp ("cs", p, 2)) {
1385 int i, colorspace;
1387 ret = sscanf (p + 2, " %d", &colorspace);
1388 if (ret != 1) {
1389 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1391 lock ("cs");
1392 set_tex_params (colorspace);
1393 for (i = 0; i < state.texcount; ++i) {
1394 state.texowners[i].w = -1;
1395 state.texowners[i].slice = NULL;
1397 unlock ("cs");
1399 else if (!strncmp ("freepage", p, 8)) {
1400 void *ptr;
1402 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1403 if (ret != 1) {
1404 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1406 lock ("freepage");
1407 freepage (ptr);
1408 unlock ("freepage");
1410 else if (!strncmp ("freetile", p, 8)) {
1411 void *ptr;
1413 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1414 if (ret != 1) {
1415 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1417 lock ("freetile");
1418 freetile (ptr);
1419 unlock ("freetile");
1421 else if (!strncmp ("search", p, 6)) {
1422 int icase, pageno, y, len2, forward;
1423 char *pattern;
1424 regex_t re;
1426 ret = sscanf (p + 6, " %d %d %d %d,%n",
1427 &icase, &pageno, &y, &forward, &len2);
1428 if (ret != 4) {
1429 errx (1, "malformed search `%s' ret=%d", p, ret);
1432 pattern = p + 6 + len2;
1433 ret = regcomp (&re, pattern,
1434 REG_EXTENDED | (icase ? REG_ICASE : 0));
1435 if (ret) {
1436 char errbuf[80];
1437 size_t size;
1439 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1440 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1442 else {
1443 lock ("search");
1444 search (&re, pageno, y, forward);
1445 unlock ("search");
1446 regfree (&re);
1449 else if (!strncmp ("geometry", p, 8)) {
1450 int w, h, fitmodel;
1452 printd ("clear");
1453 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1454 if (ret != 3) {
1455 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1458 lock ("geometry");
1459 state.h = h;
1460 if (w != state.w) {
1461 state.w = w;
1462 for (int i = 0; i < state.texcount; ++i) {
1463 state.texowners[i].slice = NULL;
1466 state.fitmodel = fitmodel;
1467 layout ();
1468 process_outline ();
1470 state.gen++;
1471 unlock ("geometry");
1472 printd ("continue %d", state.pagecount);
1474 else if (!strncmp ("reqlayout", p, 9)) {
1475 char *nameddest;
1476 int rotate, off, h;
1477 int fitmodel;
1478 pdf_document *pdf;
1480 printd ("clear");
1481 ret = sscanf (p + 9, " %d %d %d %n",
1482 &rotate, &fitmodel, &h, &off);
1483 if (ret != 3) {
1484 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1486 lock ("reqlayout");
1487 pdf = pdf_specifics (state.ctx, state.doc);
1488 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1489 state.gen += 1;
1491 state.rotate = rotate;
1492 state.fitmodel = fitmodel;
1493 state.h = h;
1494 layout ();
1495 process_outline ();
1497 nameddest = p + 9 + off;
1498 if (pdf && nameddest && *nameddest) {
1499 fz_point xy;
1500 struct pagedim *pdim;
1501 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1502 &xy.x, &xy.y);
1503 pdim = pdimofpageno (pageno);
1504 xy = fz_transform_point (xy, pdim->ctm);
1505 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1508 state.gen++;
1509 unlock ("reqlayout");
1510 printd ("continue %d", state.pagecount);
1512 else if (!strncmp ("page", p, 4)) {
1513 double a, b;
1514 struct page *page;
1515 int pageno, pindex;
1517 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1518 if (ret != 2) {
1519 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1522 lock ("page");
1523 a = now ();
1524 page = loadpage (pageno, pindex);
1525 b = now ();
1526 unlock ("page");
1528 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1530 else if (!strncmp ("tile", p, 4)) {
1531 int x, y, w, h;
1532 struct page *page;
1533 struct tile *tile;
1534 double a, b;
1535 void *data;
1537 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1538 (uintptr_t *) &page, &x, &y, &w, &h,
1539 (uintptr_t *) &data);
1540 if (ret != 6) {
1541 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1544 lock ("tile");
1545 a = now ();
1546 tile = rendertile (page, x, y, w, h, data);
1547 b = now ();
1548 unlock ("tile");
1550 printd ("tile %d %d %" PRIxPTR " %u %f",
1551 x, y, (uintptr_t) (tile),
1552 tile->w * tile->h * tile->pixmap->n,
1553 b - a);
1555 else if (!strncmp ("trimset", p, 7)) {
1556 fz_irect fuzz;
1557 int trimmargins;
1559 ret = sscanf (p + 7, " %d %d %d %d %d",
1560 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1561 if (ret != 5) {
1562 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1564 lock ("trimset");
1565 state.trimmargins = trimmargins;
1566 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1567 state.trimanew = 1;
1568 state.trimfuzz = fuzz;
1570 unlock ("trimset");
1572 else if (!strncmp ("settrim", p, 7)) {
1573 fz_irect fuzz;
1574 int trimmargins;
1576 ret = sscanf (p + 7, " %d %d %d %d %d",
1577 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1578 if (ret != 5) {
1579 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1581 printd ("clear");
1582 lock ("settrim");
1583 state.trimmargins = trimmargins;
1584 state.needoutline = 1;
1585 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1586 state.trimanew = 1;
1587 state.trimfuzz = fuzz;
1589 state.pagedimcount = 0;
1590 free (state.pagedims);
1591 state.pagedims = NULL;
1592 initpdims ();
1593 layout ();
1594 process_outline ();
1595 unlock ("settrim");
1596 printd ("continue %d", state.pagecount);
1598 else if (!strncmp ("sliceh", p, 6)) {
1599 int h;
1601 ret = sscanf (p + 6, " %d", &h);
1602 if (ret != 1) {
1603 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1605 if (h != state.sliceheight) {
1606 state.sliceheight = h;
1607 for (int i = 0; i < state.texcount; ++i) {
1608 state.texowners[i].w = -1;
1609 state.texowners[i].h = -1;
1610 state.texowners[i].slice = NULL;
1614 else if (!strncmp ("interrupt", p, 9)) {
1615 printd ("vmsg interrupted");
1617 else {
1618 errx (1, "unknown command %.*s", len, p);
1621 return 0;
1624 value ml_isexternallink (value uri_v);
1625 value 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 value ml_uritolocation (value uri_v);
1633 value ml_uritolocation (value uri_v)
1635 CAMLparam1 (uri_v);
1636 CAMLlocal1 (ret_v);
1637 int pageno;
1638 fz_point xy;
1639 struct pagedim *pdim;
1641 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1642 &xy.x, &xy.y);
1643 pdim = pdimofpageno (pageno);
1644 xy = fz_transform_point (xy, pdim->ctm);
1645 ret_v = caml_alloc_tuple (3);
1646 Field (ret_v, 0) = Val_int (pageno);
1647 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1648 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1649 CAMLreturn (ret_v);
1652 value ml_realloctexts (value texcount_v);
1653 value ml_realloctexts (value texcount_v)
1655 CAMLparam1 (texcount_v);
1656 int ok;
1658 if (trylock (__func__)) {
1659 ok = 0;
1660 goto done;
1662 realloctexts (Int_val (texcount_v));
1663 ok = 1;
1664 unlock (__func__);
1666 done:
1667 CAMLreturn (Val_bool (ok));
1670 static void recti (int x0, int y0, int x1, int y1)
1672 GLfloat *v = state.vertices;
1674 glVertexPointer (2, GL_FLOAT, 0, v);
1675 v[0] = x0; v[1] = y0;
1676 v[2] = x1; v[3] = y0;
1677 v[4] = x0; v[5] = y1;
1678 v[6] = x1; v[7] = y1;
1679 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1682 static void showsel (struct page *page, int ox, int oy)
1684 fz_irect bbox;
1685 fz_rect rect;
1686 fz_stext_block *block;
1687 int seen = 0;
1688 unsigned char selcolor[] = {15,15,15,140};
1690 if (!page->fmark || !page->lmark) return;
1692 glEnable (GL_BLEND);
1693 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1694 glColor4ubv (selcolor);
1696 ox += state.pagedims[page->pdimno].bounds.x0;
1697 oy += state.pagedims[page->pdimno].bounds.y0;
1699 for (block = page->text->first_block; block; block = block->next) {
1700 fz_stext_line *line;
1702 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1703 for (line = block->u.t.first_line; line; line = line->next) {
1704 fz_stext_char *ch;
1706 rect = fz_empty_rect;
1707 for (ch = line->first_char; ch; ch = ch->next) {
1708 fz_rect r;
1709 if (ch == page->fmark) seen = 1;
1710 r = fz_rect_from_quad (ch->quad);
1711 if (seen) rect = fz_union_rect (rect, r);
1712 if (ch == page->lmark) {
1713 bbox = fz_round_rect (rect);
1714 recti (bbox.x0 + ox, bbox.y0 + oy,
1715 bbox.x1 + ox, bbox.y1 + oy);
1716 goto done;
1719 bbox = fz_round_rect (rect);
1720 recti (bbox.x0 + ox, bbox.y0 + oy,
1721 bbox.x1 + ox, bbox.y1 + oy);
1724 done:
1725 glDisable (GL_BLEND);
1728 #pragma GCC diagnostic push
1729 #pragma GCC diagnostic ignored "-Wconversion"
1730 #include "glfont.c"
1731 #pragma GCC diagnostic pop
1733 static void stipplerect (fz_matrix m,
1734 fz_point p1,
1735 fz_point p2,
1736 fz_point p3,
1737 fz_point p4,
1738 GLfloat *texcoords,
1739 GLfloat *vertices)
1741 p1 = fz_transform_point (p1, m);
1742 p2 = fz_transform_point (p2, m);
1743 p3 = fz_transform_point (p3, m);
1744 p4 = fz_transform_point (p4, m);
1746 float w, h, s, t;
1748 w = p2.x - p1.x;
1749 h = p2.y - p1.y;
1750 t = hypotf (w, h) * .25f;
1752 w = p3.x - p2.x;
1753 h = p3.y - p2.y;
1754 s = hypotf (w, h) * .25f;
1756 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1757 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1759 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1760 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1762 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1763 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1765 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1766 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1768 glDrawArrays (GL_LINES, 0, 8);
1771 static void solidrect (fz_matrix m,
1772 fz_point p1,
1773 fz_point p2,
1774 fz_point p3,
1775 fz_point p4,
1776 GLfloat *vertices)
1778 p1 = fz_transform_point (p1, m);
1779 p2 = fz_transform_point (p2, m);
1780 p3 = fz_transform_point (p3, m);
1781 p4 = fz_transform_point (p4, m);
1782 vertices[0] = p1.x; vertices[1] = p1.y;
1783 vertices[2] = p2.x; vertices[3] = p2.y;
1785 vertices[4] = p3.x; vertices[5] = p3.y;
1786 vertices[6] = p4.x; vertices[7] = p4.y;
1787 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1790 static void ensurelinks (struct page *page)
1792 if (!page->links)
1793 page->links = fz_load_links (state.ctx, page->fzpage);
1796 static void highlightlinks (struct page *page, int xoff, int yoff)
1798 fz_matrix ctm;
1799 fz_link *link;
1800 GLfloat *texcoords = state.texcoords;
1801 GLfloat *vertices = state.vertices;
1803 ensurelinks (page);
1805 glEnable (GL_TEXTURE_1D);
1806 glEnable (GL_BLEND);
1807 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1808 glBindTexture (GL_TEXTURE_1D, state.stid);
1810 xoff -= state.pagedims[page->pdimno].bounds.x0;
1811 yoff -= state.pagedims[page->pdimno].bounds.y0;
1812 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1814 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1815 glVertexPointer (2, GL_FLOAT, 0, vertices);
1817 for (link = page->links; link; link = link->next) {
1818 fz_point p1, p2, p3, p4;
1820 p1.x = link->rect.x0;
1821 p1.y = link->rect.y0;
1823 p2.x = link->rect.x1;
1824 p2.y = link->rect.y0;
1826 p3.x = link->rect.x1;
1827 p3.y = link->rect.y1;
1829 p4.x = link->rect.x0;
1830 p4.y = link->rect.y1;
1832 /* TODO: different colours for different schemes */
1833 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1834 else glColor3ub (255, 0, 0);
1836 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1839 for (int i = 0; i < page->annotcount; ++i) {
1840 fz_point p1, p2, p3, p4;
1841 struct annot *annot = &page->annots[i];
1843 p1.x = annot->bbox.x0;
1844 p1.y = annot->bbox.y0;
1846 p2.x = annot->bbox.x1;
1847 p2.y = annot->bbox.y0;
1849 p3.x = annot->bbox.x1;
1850 p3.y = annot->bbox.y1;
1852 p4.x = annot->bbox.x0;
1853 p4.y = annot->bbox.y1;
1855 glColor3ub (0, 0, 128);
1856 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1859 glDisable (GL_BLEND);
1860 glDisable (GL_TEXTURE_1D);
1863 static int compareslinks (const void *l, const void *r)
1865 struct slink const *ls = l;
1866 struct slink const *rs = r;
1867 if (ls->bbox.y0 == rs->bbox.y0) {
1868 return rs->bbox.x0 - rs->bbox.x0;
1870 return ls->bbox.y0 - rs->bbox.y0;
1873 static void droptext (struct page *page)
1875 if (page->text) {
1876 fz_drop_stext_page (state.ctx, page->text);
1877 page->fmark = NULL;
1878 page->lmark = NULL;
1879 page->text = NULL;
1883 static void dropannots (struct page *page)
1885 if (page->annots) {
1886 free (page->annots);
1887 page->annots = NULL;
1888 page->annotcount = 0;
1892 static void ensureannots (struct page *page)
1894 int i, count = 0;
1895 size_t annotsize = sizeof (*page->annots);
1896 pdf_annot *annot;
1897 pdf_document *pdf;
1898 pdf_page *pdfpage;
1900 pdf = pdf_specifics (state.ctx, state.doc);
1901 if (!pdf) return;
1903 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1904 if (state.gen != page->agen) {
1905 dropannots (page);
1906 page->agen = state.gen;
1908 if (page->annots) return;
1910 for (annot = pdf_first_annot (state.ctx, pdfpage);
1911 annot;
1912 annot = pdf_next_annot (state.ctx, annot)) {
1913 count++;
1916 if (count > 0) {
1917 page->annotcount = count;
1918 page->annots = calloc (count, annotsize);
1919 if (!page->annots) {
1920 err (1, "calloc annots %d", count);
1923 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1924 annot;
1925 annot = pdf_next_annot (state.ctx, annot), i++) {
1926 fz_rect rect;
1928 rect = pdf_bound_annot (state.ctx, annot);
1929 page->annots[i].annot = annot;
1930 page->annots[i].bbox = fz_round_rect (rect);
1935 static void dropslinks (struct page *page)
1937 if (page->slinks) {
1938 free (page->slinks);
1939 page->slinks = NULL;
1940 page->slinkcount = 0;
1942 if (page->links) {
1943 fz_drop_link (state.ctx, page->links);
1944 page->links = NULL;
1948 static void ensureslinks (struct page *page)
1950 fz_matrix ctm;
1951 int i, count;
1952 size_t slinksize = sizeof (*page->slinks);
1953 fz_link *link;
1955 ensureannots (page);
1956 if (state.gen != page->sgen) {
1957 dropslinks (page);
1958 page->sgen = state.gen;
1960 if (page->slinks) return;
1962 ensurelinks (page);
1963 ctm = pagectm (page);
1965 count = page->annotcount;
1966 for (link = page->links; link; link = link->next) {
1967 count++;
1969 if (count > 0) {
1970 int j;
1972 page->slinkcount = count;
1973 page->slinks = calloc (count, slinksize);
1974 if (!page->slinks) {
1975 err (1, "calloc slinks %d", count);
1978 for (i = 0, link = page->links; link; ++i, link = link->next) {
1979 fz_rect rect;
1981 rect = link->rect;
1982 rect = fz_transform_rect (rect, ctm);
1983 page->slinks[i].tag = SLINK;
1984 page->slinks[i].u.link = link;
1985 page->slinks[i].bbox = fz_round_rect (rect);
1987 for (j = 0; j < page->annotcount; ++j, ++i) {
1988 fz_rect rect;
1989 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1990 rect = fz_transform_rect (rect, ctm);
1991 page->slinks[i].bbox = fz_round_rect (rect);
1993 page->slinks[i].tag = SANNOT;
1994 page->slinks[i].u.annot = page->annots[j].annot;
1996 qsort (page->slinks, count, slinksize, compareslinks);
2000 static void highlightslinks (struct page *page, int xoff, int yoff,
2001 int noff, char *targ, mlsize_t tlen, int hfsize)
2003 char buf[40];
2004 struct slink *slink;
2005 float x0, y0, x1, y1, w;
2007 ensureslinks (page);
2008 glColor3ub (0xc3, 0xb0, 0x91);
2009 for (int i = 0; i < page->slinkcount; ++i) {
2010 fmt_linkn (buf, i + noff);
2011 if (!tlen || !strncmp (targ, buf, tlen)) {
2012 slink = &page->slinks[i];
2014 x0 = slink->bbox.x0 + xoff - 5;
2015 y1 = slink->bbox.y0 + yoff - 5;
2016 y0 = y1 + 10 + hfsize;
2017 w = measure_string (state.face, hfsize, buf);
2018 x1 = x0 + w + 10;
2019 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2023 glEnable (GL_BLEND);
2024 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2025 glEnable (GL_TEXTURE_2D);
2026 glColor3ub (0, 0, 0);
2027 for (int i = 0; i < page->slinkcount; ++i) {
2028 fmt_linkn (buf, i + noff);
2029 if (!tlen || !strncmp (targ, buf, tlen)) {
2030 slink = &page->slinks[i];
2032 x0 = slink->bbox.x0 + xoff;
2033 y0 = slink->bbox.y0 + yoff + hfsize;
2034 draw_string (state.face, hfsize, x0, y0, buf);
2037 glDisable (GL_TEXTURE_2D);
2038 glDisable (GL_BLEND);
2041 static void uploadslice (struct tile *tile, struct slice *slice)
2043 int offset;
2044 struct slice *slice1;
2045 unsigned char *texdata;
2047 offset = 0;
2048 for (slice1 = tile->slices; slice != slice1; slice1++) {
2049 offset += slice1->h * tile->w * tile->pixmap->n;
2051 if (slice->texindex != -1 && slice->texindex < state.texcount
2052 && state.texowners[slice->texindex].slice == slice) {
2053 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2055 else {
2056 int subimage = 0;
2057 int texindex = state.texindex++ % state.texcount;
2059 if (state.texowners[texindex].w == tile->w) {
2060 if (state.texowners[texindex].h >= slice->h) {
2061 subimage = 1;
2063 else {
2064 state.texowners[texindex].h = slice->h;
2067 else {
2068 state.texowners[texindex].h = slice->h;
2071 state.texowners[texindex].w = tile->w;
2072 state.texowners[texindex].slice = slice;
2073 slice->texindex = texindex;
2075 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2076 #if TEXT_TYPE == GL_TEXTURE_2D
2077 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2078 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2079 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2080 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2081 #endif
2082 if (tile->pbo) {
2083 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2084 texdata = 0;
2086 else {
2087 texdata = tile->pixmap->samples;
2089 if (subimage) {
2090 glTexSubImage2D (TEXT_TYPE,
2094 tile->w,
2095 slice->h,
2096 state.texform,
2097 state.texty,
2098 texdata+offset
2101 else {
2102 glTexImage2D (TEXT_TYPE,
2104 state.texiform,
2105 tile->w,
2106 slice->h,
2108 state.texform,
2109 state.texty,
2110 texdata+offset
2113 if (tile->pbo) {
2114 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2119 void ml_begintiles (void);
2120 void ml_begintiles (void)
2122 glEnable (TEXT_TYPE);
2123 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2124 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2127 void ml_endtiles (void);
2128 void ml_endtiles (void)
2130 glDisable (TEXT_TYPE);
2133 void ml_drawtile (value args_v, value ptr_v);
2134 void ml_drawtile (value args_v, value ptr_v)
2136 CAMLparam2 (args_v, ptr_v);
2137 int dispx = Int_val (Field (args_v, 0));
2138 int dispy = Int_val (Field (args_v, 1));
2139 int dispw = Int_val (Field (args_v, 2));
2140 int disph = Int_val (Field (args_v, 3));
2141 int tilex = Int_val (Field (args_v, 4));
2142 int tiley = Int_val (Field (args_v, 5));
2143 char *s = String_val (ptr_v);
2144 struct tile *tile = parse_pointer (__func__, s);
2145 int slicey, firstslice;
2146 struct slice *slice;
2147 GLfloat *texcoords = state.texcoords;
2148 GLfloat *vertices = state.vertices;
2150 firstslice = tiley / tile->sliceheight;
2151 slice = &tile->slices[firstslice];
2152 slicey = tiley % tile->sliceheight;
2154 while (disph > 0) {
2155 int dh;
2157 dh = slice->h - slicey;
2158 dh = fz_mini (disph, dh);
2159 uploadslice (tile, slice);
2161 texcoords[0] = tilex; texcoords[1] = slicey;
2162 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2163 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2164 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2166 vertices[0] = dispx; vertices[1] = dispy;
2167 vertices[2] = dispx+dispw; vertices[3] = dispy;
2168 vertices[4] = dispx; vertices[5] = dispy+dh;
2169 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2171 #if TEXT_TYPE == GL_TEXTURE_2D
2172 for (int i = 0; i < 8; ++i) {
2173 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2175 #endif
2177 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2178 dispy += dh;
2179 disph -= dh;
2180 slice++;
2181 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2182 slicey = 0;
2184 CAMLreturn0;
2187 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2189 fz_matrix ctm;
2190 fz_point p1, p2, p3, p4;
2191 GLfloat *vertices = state.vertices;
2193 xoff -= state.pagedims[page->pdimno].bounds.x0;
2194 yoff -= state.pagedims[page->pdimno].bounds.y0;
2195 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2197 glEnable (GL_BLEND);
2198 glVertexPointer (2, GL_FLOAT, 0, vertices);
2200 glColor4d (
2201 Double_array_field (rects_v, 0),
2202 Double_array_field (rects_v, 1),
2203 Double_array_field (rects_v, 2),
2204 Double_array_field (rects_v, 3)
2206 p1.x = (float) Double_array_field (rects_v, 4);
2207 p1.y = (float) Double_array_field (rects_v, 5);
2209 p2.x = (float) Double_array_field (rects_v, 6);
2210 p2.y = p1.y;
2212 p3.x = p2.x;
2213 p3.y = (float) Double_array_field (rects_v, 7);
2215 p4.x = p1.x;
2216 p4.y = p3.y;
2217 solidrect (ctm, p1, p2, p3, p4, vertices);
2218 glDisable (GL_BLEND);
2221 value ml_postprocess (value ptr_v, value hlinks_v,
2222 value xoff_v, value yoff_v,
2223 value li_v);
2224 value ml_postprocess (value ptr_v, value hlinks_v,
2225 value xoff_v, value yoff_v,
2226 value li_v)
2228 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2229 int xoff = Int_val (xoff_v);
2230 int yoff = Int_val (yoff_v);
2231 int noff = Int_val (Field (li_v, 0));
2232 char *targ = String_val (Field (li_v, 1));
2233 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2234 int hfsize = Int_val (Field (li_v, 2));
2235 char *s = String_val (ptr_v);
2236 int hlmask = Int_val (hlinks_v);
2237 struct page *page = parse_pointer (__func__, s);
2239 if (!page->fzpage) {
2240 /* deal with loadpage failed pages */
2241 goto done;
2244 if (trylock (__func__)) {
2245 noff = -1;
2246 goto done;
2249 ensureannots (page);
2250 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2251 if (hlmask & 2) {
2252 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2253 noff = page->slinkcount;
2255 if (page->tgen == state.gen) {
2256 showsel (page, xoff, yoff);
2258 unlock (__func__);
2260 done:
2261 CAMLreturn (Val_int (noff));
2264 void ml_drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v);
2265 void ml_drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v)
2267 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2268 int xoff = Int_val (xoff_v);
2269 int yoff = Int_val (yoff_v);
2270 char *s = String_val (ptr_v);
2271 struct page *page = parse_pointer (__func__, s);
2273 drawprect (page, xoff, yoff, rects_v);
2274 CAMLreturn0;
2277 static struct annot *getannot (struct page *page, int x, int y)
2279 fz_point p;
2280 fz_matrix ctm;
2281 const fz_matrix *tctm;
2282 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2284 if (!page->annots) return NULL;
2286 if (pdf) {
2287 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2288 tctm = &state.pagedims[page->pdimno].tctm;
2290 else {
2291 tctm = &fz_identity;
2294 p.x = x;
2295 p.y = y;
2297 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2298 ctm = fz_invert_matrix (ctm);
2299 p = fz_transform_point (p, ctm);
2301 if (pdf) {
2302 for (int i = 0; i < page->annotcount; ++i) {
2303 struct annot *a = &page->annots[i];
2304 fz_rect rect;
2306 rect = pdf_bound_annot (state.ctx, a->annot);
2307 if (p.x >= rect.x0 && p.x <= rect.x1) {
2308 if (p.y >= rect.y0 && p.y <= rect.y1)
2309 return a;
2313 return NULL;
2316 static fz_link *getlink (struct page *page, int x, int y)
2318 fz_point p;
2319 fz_link *link;
2321 ensureslinks (page);
2323 p.x = x;
2324 p.y = y;
2326 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2328 for (link = page->links; link; link = link->next) {
2329 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2330 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2331 return link;
2335 return NULL;
2338 static void ensuretext (struct page *page)
2340 if (state.gen != page->tgen) {
2341 droptext (page);
2342 page->tgen = state.gen;
2344 if (!page->text) {
2345 fz_device *tdev;
2347 page->text = fz_new_stext_page (state.ctx,
2348 state.pagedims[page->pdimno].mediabox);
2349 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2350 fz_run_display_list (state.ctx, page->dlist,
2351 tdev, pagectm (page), fz_infinite_rect, NULL);
2352 fz_close_device (state.ctx, tdev);
2353 fz_drop_device (state.ctx, tdev);
2357 value ml_find_page_with_links (value start_page_v, value dir_v);
2358 value ml_find_page_with_links (value start_page_v, value dir_v)
2360 CAMLparam2 (start_page_v, dir_v);
2361 CAMLlocal1 (ret_v);
2362 int i, dir = Int_val (dir_v);
2363 int start_page = Int_val (start_page_v);
2364 int end_page = dir > 0 ? state.pagecount : -1;
2365 pdf_document *pdf;
2367 fz_var (end_page);
2368 ret_v = Val_int (0);
2369 lock (__func__);
2370 pdf = pdf_specifics (state.ctx, state.doc);
2371 for (i = start_page + dir; i != end_page; i += dir) {
2372 int found;
2374 fz_var (found);
2375 if (pdf) {
2376 pdf_page *page = NULL;
2378 fz_var (page);
2379 fz_try (state.ctx) {
2380 page = pdf_load_page (state.ctx, pdf, i);
2381 found = !!page->links || !!page->annots;
2383 fz_catch (state.ctx) {
2384 found = 0;
2386 if (page) {
2387 fz_drop_page (state.ctx, &page->super);
2390 else {
2391 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2392 fz_link *link = fz_load_links (state.ctx, page);
2393 found = !!link;
2394 fz_drop_link (state.ctx, link);
2395 fz_drop_page (state.ctx, page);
2398 if (found) {
2399 ret_v = caml_alloc_small (1, 1);
2400 Field (ret_v, 0) = Val_int (i);
2401 goto unlock;
2404 unlock:
2405 unlock (__func__);
2406 CAMLreturn (ret_v);
2409 enum { dir_first, dir_last };
2410 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2412 value ml_findlink (value ptr_v, value dir_v);
2413 value ml_findlink (value ptr_v, value dir_v)
2415 CAMLparam2 (ptr_v, dir_v);
2416 CAMLlocal2 (ret_v, pos_v);
2417 struct page *page;
2418 int dirtag, i, slinkindex;
2419 struct slink *found = NULL ,*slink;
2420 char *s = String_val (ptr_v);
2422 page = parse_pointer (__func__, s);
2423 ret_v = Val_int (0);
2424 lock (__func__);
2425 ensureslinks (page);
2427 if (Is_block (dir_v)) {
2428 dirtag = Tag_val (dir_v);
2429 switch (dirtag) {
2430 case dir_first_visible:
2432 int x0, y0, dir, first_index, last_index;
2434 pos_v = Field (dir_v, 0);
2435 x0 = Int_val (Field (pos_v, 0));
2436 y0 = Int_val (Field (pos_v, 1));
2437 dir = Int_val (Field (pos_v, 2));
2439 if (dir >= 0) {
2440 dir = 1;
2441 first_index = 0;
2442 last_index = page->slinkcount;
2444 else {
2445 first_index = page->slinkcount - 1;
2446 last_index = -1;
2449 for (i = first_index; i != last_index; i += dir) {
2450 slink = &page->slinks[i];
2451 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2452 found = slink;
2453 break;
2457 break;
2459 case dir_left:
2460 slinkindex = Int_val (Field (dir_v, 0));
2461 found = &page->slinks[slinkindex];
2462 for (i = slinkindex - 1; i >= 0; --i) {
2463 slink = &page->slinks[i];
2464 if (slink->bbox.x0 < found->bbox.x0) {
2465 found = slink;
2466 break;
2469 break;
2471 case dir_right:
2472 slinkindex = Int_val (Field (dir_v, 0));
2473 found = &page->slinks[slinkindex];
2474 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2475 slink = &page->slinks[i];
2476 if (slink->bbox.x0 > found->bbox.x0) {
2477 found = slink;
2478 break;
2481 break;
2483 case dir_down:
2484 slinkindex = Int_val (Field (dir_v, 0));
2485 found = &page->slinks[slinkindex];
2486 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2487 slink = &page->slinks[i];
2488 if (slink->bbox.y0 >= found->bbox.y0) {
2489 found = slink;
2490 break;
2493 break;
2495 case dir_up:
2496 slinkindex = Int_val (Field (dir_v, 0));
2497 found = &page->slinks[slinkindex];
2498 for (i = slinkindex - 1; i >= 0; --i) {
2499 slink = &page->slinks[i];
2500 if (slink->bbox.y0 <= found->bbox.y0) {
2501 found = slink;
2502 break;
2505 break;
2508 else {
2509 dirtag = Int_val (dir_v);
2510 switch (dirtag) {
2511 case dir_first:
2512 found = page->slinks;
2513 break;
2515 case dir_last:
2516 if (page->slinks) {
2517 found = page->slinks + (page->slinkcount - 1);
2519 break;
2522 if (found) {
2523 ret_v = caml_alloc_small (2, 1);
2524 Field (ret_v, 0) = Val_int (found - page->slinks);
2527 unlock (__func__);
2528 CAMLreturn (ret_v);
2531 enum { uuri, utext, uannot };
2533 value ml_getlink (value ptr_v, value n_v);
2534 value ml_getlink (value ptr_v, value n_v)
2536 CAMLparam2 (ptr_v, n_v);
2537 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2538 fz_link *link;
2539 struct page *page;
2540 char *s = String_val (ptr_v);
2541 struct slink *slink;
2543 ret_v = Val_int (0);
2544 page = parse_pointer (__func__, s);
2546 lock (__func__);
2547 ensureslinks (page);
2548 slink = &page->slinks[Int_val (n_v)];
2549 if (slink->tag == SLINK) {
2550 link = slink->u.link;
2551 str_v = caml_copy_string (link->uri);
2552 ret_v = caml_alloc_small (1, uuri);
2553 Field (ret_v, 0) = str_v;
2555 else {
2556 ret_v = caml_alloc_small (1, uannot);
2557 tup_v = caml_alloc_tuple (2);
2558 Field (ret_v, 0) = tup_v;
2559 Field (tup_v, 0) = ptr_v;
2560 Field (tup_v, 1) = n_v;
2562 unlock (__func__);
2564 CAMLreturn (ret_v);
2567 value ml_getannotcontents (value ptr_v, value n_v);
2568 value ml_getannotcontents (value ptr_v, value n_v)
2570 CAMLparam2 (ptr_v, n_v);
2571 CAMLlocal1 (ret_v);
2572 pdf_document *pdf;
2573 const char *contents = "";
2575 lock (__func__);
2576 pdf = pdf_specifics (state.ctx, state.doc);
2577 if (pdf) {
2578 char *s = String_val (ptr_v);
2579 struct page *page;
2580 struct slink *slink;
2582 page = parse_pointer (__func__, s);
2583 slink = &page->slinks[Int_val (n_v)];
2584 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2586 unlock (__func__);
2587 ret_v = caml_copy_string (contents);
2588 CAMLreturn (ret_v);
2591 value ml_getlinkcount (value ptr_v);
2592 value ml_getlinkcount (value ptr_v)
2594 CAMLparam1 (ptr_v);
2595 struct page *page;
2596 char *s = String_val (ptr_v);
2598 page = parse_pointer (__func__, s);
2599 CAMLreturn (Val_int (page->slinkcount));
2602 value ml_getlinkrect (value ptr_v, value n_v);
2603 value ml_getlinkrect (value ptr_v, value n_v)
2605 CAMLparam2 (ptr_v, n_v);
2606 CAMLlocal1 (ret_v);
2607 struct page *page;
2608 struct slink *slink;
2609 char *s = String_val (ptr_v);
2611 page = parse_pointer (__func__, s);
2612 ret_v = caml_alloc_tuple (4);
2613 lock (__func__);
2614 ensureslinks (page);
2616 slink = &page->slinks[Int_val (n_v)];
2617 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2618 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2619 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2620 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2621 unlock (__func__);
2622 CAMLreturn (ret_v);
2625 value ml_whatsunder (value ptr_v, value x_v, value y_v);
2626 value ml_whatsunder (value ptr_v, value x_v, value y_v)
2628 CAMLparam3 (ptr_v, x_v, y_v);
2629 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2630 fz_link *link;
2631 struct annot *annot;
2632 struct page *page;
2633 char *ptr = String_val (ptr_v);
2634 int x = Int_val (x_v), y = Int_val (y_v);
2635 struct pagedim *pdim;
2637 ret_v = Val_int (0);
2638 if (trylock (__func__)) {
2639 goto done;
2642 page = parse_pointer (__func__, ptr);
2643 pdim = &state.pagedims[page->pdimno];
2644 x += pdim->bounds.x0;
2645 y += pdim->bounds.y0;
2648 annot = getannot (page, x, y);
2649 if (annot) {
2650 int i, n = -1;
2652 ensureslinks (page);
2653 for (i = 0; i < page->slinkcount; ++i) {
2654 if (page->slinks[i].tag == SANNOT
2655 && page->slinks[i].u.annot == annot->annot) {
2656 n = i;
2657 break;
2660 ret_v = caml_alloc_small (1, uannot);
2661 tup_v = caml_alloc_tuple (2);
2662 Field (ret_v, 0) = tup_v;
2663 Field (tup_v, 0) = ptr_v;
2664 Field (tup_v, 1) = Val_int (n);
2665 goto unlock;
2669 link = getlink (page, x, y);
2670 if (link) {
2671 str_v = caml_copy_string (link->uri);
2672 ret_v = caml_alloc_small (1, uuri);
2673 Field (ret_v, 0) = str_v;
2675 else {
2676 fz_rect *b;
2677 fz_stext_block *block;
2679 ensuretext (page);
2681 for (block = page->text->first_block; block; block = block->next) {
2682 fz_stext_line *line;
2684 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2685 b = &block->bbox;
2686 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2687 continue;
2689 for (line = block->u.t.first_line; line; line = line->next) {
2690 fz_stext_char *ch;
2692 b = &line->bbox;
2693 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2694 continue;
2696 for (ch = line->first_char; ch; ch = ch->next) {
2697 fz_quad *q = &ch->quad;
2699 if (x >= q->ul.x && x <= q->ur.x
2700 && y >= q->ul.y && y <= q->ll.y) {
2701 const char *n2 = fz_font_name (state.ctx, ch->font);
2702 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2703 ch->font);
2705 if (!n2) n2 = "<unknown font>";
2707 if (face && face->family_name) {
2708 char *s;
2709 char *n1 = face->family_name;
2710 size_t l1 = strlen (n1);
2711 size_t l2 = strlen (n2);
2713 if (l1 != l2 || memcmp (n1, n2, l1)) {
2714 s = malloc (l1 + l2 + 2);
2715 if (s) {
2716 memcpy (s, n2, l2);
2717 s[l2] = '=';
2718 memcpy (s + l2 + 1, n1, l1 + 1);
2719 str_v = caml_copy_string (s);
2720 free (s);
2724 if (str_v == Val_unit) {
2725 str_v = caml_copy_string (n2);
2727 ret_v = caml_alloc_small (1, utext);
2728 Field (ret_v, 0) = str_v;
2729 goto unlock;
2735 unlock:
2736 unlock (__func__);
2738 done:
2739 CAMLreturn (ret_v);
2742 enum { mark_page, mark_block, mark_line, mark_word };
2744 void ml_clearmark (value ptr_v);
2745 void ml_clearmark (value ptr_v)
2747 CAMLparam1 (ptr_v);
2748 char *s = String_val (ptr_v);
2749 struct page *page;
2751 if (trylock (__func__)) {
2752 goto done;
2755 page = parse_pointer (__func__, s);
2756 page->fmark = NULL;
2757 page->lmark = NULL;
2759 unlock (__func__);
2760 done:
2761 CAMLreturn0;
2764 static int uninteresting (int c)
2766 return isspace (c) || ispunct (c);
2769 value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v);
2770 value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2772 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2773 CAMLlocal1 (ret_v);
2774 fz_rect *b;
2775 struct page *page;
2776 fz_stext_line *line;
2777 fz_stext_block *block;
2778 struct pagedim *pdim;
2779 int mark = Int_val (mark_v);
2780 char *s = String_val (ptr_v);
2781 int x = Int_val (x_v), y = Int_val (y_v);
2783 ret_v = Val_bool (0);
2784 if (trylock (__func__)) {
2785 goto done;
2788 page = parse_pointer (__func__, s);
2789 pdim = &state.pagedims[page->pdimno];
2791 ensuretext (page);
2793 if (mark == mark_page) {
2794 page->fmark = page->text->first_block->u.t.first_line->first_char;
2795 page->lmark = page->text->last_block->u.t.last_line->last_char;
2796 ret_v = Val_bool (1);
2797 goto unlock;
2800 x += pdim->bounds.x0;
2801 y += pdim->bounds.y0;
2803 for (block = page->text->first_block; block; block = block->next) {
2804 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2805 b = &block->bbox;
2806 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2807 continue;
2809 if (mark == mark_block) {
2810 page->fmark = block->u.t.first_line->first_char;
2811 page->lmark = block->u.t.last_line->last_char;
2812 ret_v = Val_bool (1);
2813 goto unlock;
2816 for (line = block->u.t.first_line; line; line = line->next) {
2817 fz_stext_char *ch;
2819 b = &line->bbox;
2820 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2821 continue;
2823 if (mark == mark_line) {
2824 page->fmark = line->first_char;
2825 page->lmark = line->last_char;
2826 ret_v = Val_bool (1);
2827 goto unlock;
2830 for (ch = line->first_char; ch; ch = ch->next) {
2831 fz_stext_char *ch2, *first = NULL, *last = NULL;
2832 fz_quad *q = &ch->quad;
2833 if (x >= q->ul.x && x <= q->ur.x
2834 && y >= q->ul.y && y <= q->ll.y) {
2835 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2836 if (uninteresting (ch2->c)) first = NULL;
2837 else if (!first) first = ch2;
2839 for (ch2 = ch; ch2; ch2 = ch2->next) {
2840 if (uninteresting (ch2->c)) break;
2841 last = ch2;
2844 page->fmark = first;
2845 page->lmark = last;
2846 ret_v = Val_bool (1);
2847 goto unlock;
2852 unlock:
2853 if (!Bool_val (ret_v)) {
2854 page->fmark = NULL;
2855 page->lmark = NULL;
2857 unlock (__func__);
2859 done:
2860 CAMLreturn (ret_v);
2863 value ml_rectofblock (value ptr_v, value x_v, value y_v);
2864 value ml_rectofblock (value ptr_v, value x_v, value y_v)
2866 CAMLparam3 (ptr_v, x_v, y_v);
2867 CAMLlocal2 (ret_v, res_v);
2868 fz_rect *b = NULL;
2869 struct page *page;
2870 struct pagedim *pdim;
2871 fz_stext_block *block;
2872 char *s = String_val (ptr_v);
2873 int x = Int_val (x_v), y = Int_val (y_v);
2875 ret_v = Val_int (0);
2876 if (trylock (__func__)) {
2877 goto done;
2880 page = parse_pointer (__func__, s);
2881 pdim = &state.pagedims[page->pdimno];
2882 x += pdim->bounds.x0;
2883 y += pdim->bounds.y0;
2885 ensuretext (page);
2887 for (block = page->text->first_block; block; block = block->next) {
2888 switch (block->type) {
2889 case FZ_STEXT_BLOCK_TEXT:
2890 b = &block->bbox;
2891 break;
2893 case FZ_STEXT_BLOCK_IMAGE:
2894 b = &block->bbox;
2895 break;
2897 default:
2898 continue;
2901 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2902 break;
2903 b = NULL;
2905 if (b) {
2906 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2907 ret_v = caml_alloc_small (1, 1);
2908 Store_double_field (res_v, 0, (double) b->x0);
2909 Store_double_field (res_v, 1, (double) b->x1);
2910 Store_double_field (res_v, 2, (double) b->y0);
2911 Store_double_field (res_v, 3, (double) b->y1);
2912 Field (ret_v, 0) = res_v;
2914 unlock (__func__);
2916 done:
2917 CAMLreturn (ret_v);
2920 void ml_seltext (value ptr_v, value rect_v);
2921 void ml_seltext (value ptr_v, value rect_v)
2923 CAMLparam2 (ptr_v, rect_v);
2924 struct page *page;
2925 struct pagedim *pdim;
2926 char *s = String_val (ptr_v);
2927 int x0, x1, y0, y1;
2928 fz_stext_char *ch;
2929 fz_stext_line *line;
2930 fz_stext_block *block;
2931 fz_stext_char *fc, *lc;
2933 if (trylock (__func__)) {
2934 goto done;
2937 page = parse_pointer (__func__, s);
2938 ensuretext (page);
2940 pdim = &state.pagedims[page->pdimno];
2941 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2942 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2943 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2944 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2946 if (y0 > y1) {
2947 int t = y0;
2948 y0 = y1;
2949 y1 = t;
2950 x0 = x1;
2951 x1 = t;
2954 fc = page->fmark;
2955 lc = page->lmark;
2957 for (block = page->text->first_block; block; block = block->next) {
2958 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2959 for (line = block->u.t.first_line; line; line = line->next) {
2960 for (ch = line->first_char; ch; ch = ch->next) {
2961 fz_quad q = ch->quad;
2962 if (x0 >= q.ul.x && x0 <= q.ur.x
2963 && y0 >= q.ul.y && y0 <= q.ll.y) {
2964 fc = ch;
2966 if (x1 >= q.ul.x && x1 <= q.ur.x
2967 && y1 >= q.ul.y && y1 <= q.ll.y) {
2968 lc = ch;
2973 if (x1 < x0 && fc == lc) {
2974 fz_stext_char *t;
2976 t = fc;
2977 fc = lc;
2978 lc = t;
2981 page->fmark = fc;
2982 page->lmark = lc;
2984 unlock (__func__);
2986 done:
2987 CAMLreturn0;
2990 static int pipechar (FILE *f, fz_stext_char *ch)
2992 char buf[4];
2993 int len;
2994 size_t ret;
2996 len = fz_runetochar (buf, ch->c);
2997 ret = fwrite (buf, len, 1, f);
2998 if (ret != 1) {
2999 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3000 len, ret, errno, strerror (errno));
3001 return -1;
3003 return 0;
3006 value ml_spawn (value command_v, value fds_v);
3007 value ml_spawn (value command_v, value fds_v)
3009 CAMLparam2 (command_v, fds_v);
3010 CAMLlocal2 (l_v, tup_v);
3011 int ret, ret1;
3012 pid_t pid = (pid_t) -1;
3013 char *msg = NULL;
3014 value earg_v = Nothing;
3015 posix_spawnattr_t attr;
3016 posix_spawn_file_actions_t fa;
3017 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3019 argv[2] = String_val (command_v);
3021 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3022 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3025 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3026 msg = "posix_spawnattr_init";
3027 goto fail1;
3030 #ifdef POSIX_SPAWN_USEVFORK
3031 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3032 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3033 goto fail;
3035 #endif
3037 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3038 int fd1, fd2;
3040 tup_v = Field (l_v, 0);
3041 fd1 = Int_val (Field (tup_v, 0));
3042 fd2 = Int_val (Field (tup_v, 1));
3043 if (fd2 < 0) {
3044 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3045 msg = "posix_spawn_file_actions_addclose";
3046 earg_v = tup_v;
3047 goto fail;
3050 else {
3051 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3052 msg = "posix_spawn_file_actions_adddup2";
3053 earg_v = tup_v;
3054 goto fail;
3059 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3060 msg = "posix_spawn";
3061 goto fail;
3064 fail:
3065 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3066 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3069 fail1:
3070 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3071 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3072 ret1, strerror (ret1));
3075 if (msg)
3076 unix_error (ret, msg, earg_v);
3078 CAMLreturn (Val_int (pid));
3081 value ml_hassel (value ptr_v);
3082 value ml_hassel (value ptr_v)
3084 CAMLparam1 (ptr_v);
3085 CAMLlocal1 (ret_v);
3086 struct page *page;
3087 char *s = String_val (ptr_v);
3089 ret_v = Val_bool (0);
3090 if (trylock (__func__)) {
3091 goto done;
3094 page = parse_pointer (__func__, s);
3095 ret_v = Val_bool (page->fmark && page->lmark);
3096 unlock (__func__);
3097 done:
3098 CAMLreturn (ret_v);
3101 void ml_copysel (value fd_v, value ptr_v);
3102 void ml_copysel (value fd_v, value ptr_v)
3104 CAMLparam2 (fd_v, ptr_v);
3105 FILE *f;
3106 int seen = 0;
3107 struct page *page;
3108 fz_stext_line *line;
3109 fz_stext_block *block;
3110 int fd = Int_val (fd_v);
3111 char *s = String_val (ptr_v);
3113 if (trylock (__func__)) {
3114 goto done;
3117 page = parse_pointer (__func__, s);
3119 if (!page->fmark || !page->lmark) {
3120 printd ("emsg nothing to copy on page %d", page->pageno);
3121 goto unlock;
3124 f = fdopen (fd, "w");
3125 if (!f) {
3126 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3127 fd, errno, strerror (errno));
3128 f = stdout;
3131 for (block = page->text->first_block; block; block = block->next) {
3132 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3133 for (line = block->u.t.first_line; line; line = line->next) {
3134 fz_stext_char *ch;
3135 for (ch = line->first_char; ch; ch = ch->next) {
3136 if (seen || ch == page->fmark) {
3137 do {
3138 pipechar (f, ch);
3139 if (ch == page->lmark) goto close;
3140 } while ((ch = ch->next));
3141 seen = 1;
3142 break;
3145 if (seen) fputc ('\n', f);
3148 close:
3149 if (f != stdout) {
3150 int ret = fclose (f);
3151 fd = -1;
3152 if (ret == -1) {
3153 if (errno != ECHILD) {
3154 printd ("emsg failed to close sel pipe: %d:%s",
3155 errno, strerror (errno));
3159 unlock:
3160 unlock (__func__);
3162 done:
3163 if (fd >= 0) {
3164 if (close (fd)) {
3165 printd ("emsg failed to close sel pipe: %d:%s",
3166 errno, strerror (errno));
3169 CAMLreturn0;
3172 value ml_getpdimrect (value pagedimno_v);
3173 value ml_getpdimrect (value pagedimno_v)
3175 CAMLparam1 (pagedimno_v);
3176 CAMLlocal1 (ret_v);
3177 int pagedimno = Int_val (pagedimno_v);
3178 fz_rect box;
3180 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3181 if (trylock (__func__)) {
3182 box = fz_empty_rect;
3184 else {
3185 box = state.pagedims[pagedimno].mediabox;
3186 unlock (__func__);
3189 Store_double_field (ret_v, 0, (double) box.x0);
3190 Store_double_field (ret_v, 1, (double) box.x1);
3191 Store_double_field (ret_v, 2, (double) box.y0);
3192 Store_double_field (ret_v, 3, (double) box.y1);
3194 CAMLreturn (ret_v);
3197 value ml_zoom_for_height (value winw_v, value winh_v,
3198 value dw_v, value cols_v);
3199 value ml_zoom_for_height (value winw_v, value winh_v,
3200 value dw_v, value cols_v)
3202 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3203 CAMLlocal1 (ret_v);
3204 int i;
3205 float zoom = -1.;
3206 float maxh = 0.0;
3207 struct pagedim *p;
3208 float winw = Int_val (winw_v);
3209 float winh = Int_val (winh_v);
3210 float dw = Int_val (dw_v);
3211 float cols = Int_val (cols_v);
3212 float pw = 1.0, ph = 1.0;
3214 if (trylock (__func__)) {
3215 goto done;
3218 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3219 float w = p->pagebox.x1 / cols;
3220 float h = p->pagebox.y1;
3221 if (h > maxh) {
3222 maxh = h;
3223 ph = h;
3224 if (state.fitmodel != FitProportional) pw = w;
3226 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3229 zoom = (((winh / ph) * pw) + dw) / winw;
3230 unlock (__func__);
3231 done:
3232 ret_v = caml_copy_double ((double) zoom);
3233 CAMLreturn (ret_v);
3236 value ml_getmaxw (value unit_v);
3237 value ml_getmaxw (value unit_v)
3239 CAMLparam1 (unit_v);
3240 CAMLlocal1 (ret_v);
3241 int i;
3242 float maxw = -1.;
3243 struct pagedim *p;
3245 if (trylock (__func__)) {
3246 goto done;
3249 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3250 float w = p->pagebox.x1;
3251 maxw = fz_max (maxw, w);
3254 unlock (__func__);
3255 done:
3256 ret_v = caml_copy_double ((double) maxw);
3257 CAMLreturn (ret_v);
3260 value ml_draw_string (value pt_v, value x_v,
3261 value y_v, value string_v);
3262 value ml_draw_string (value pt_v, value x_v,
3263 value y_v, value string_v)
3265 CAMLparam4 (pt_v, x_v, y_v, string_v);
3266 CAMLlocal1 (ret_v);
3267 int pt = Int_val(pt_v);
3268 int x = Int_val (x_v);
3269 int y = Int_val (y_v);
3270 float w;
3272 w = draw_string (state.face, pt, x, y, String_val (string_v));
3273 ret_v = caml_copy_double (w);
3274 CAMLreturn (ret_v);
3277 value ml_measure_string (value pt_v, value string_v);
3278 value ml_measure_string (value pt_v, value string_v)
3280 CAMLparam2 (pt_v, string_v);
3281 CAMLlocal1 (ret_v);
3282 int pt = Int_val (pt_v);
3283 double w;
3285 w = (double) measure_string (state.face, pt, String_val (string_v));
3286 ret_v = caml_copy_double (w);
3287 CAMLreturn (ret_v);
3290 value ml_getpagebox (value opaque_v);
3291 value ml_getpagebox (value opaque_v)
3293 CAMLparam1 (opaque_v);
3294 CAMLlocal1 (ret_v);
3295 fz_rect rect;
3296 fz_irect bbox;
3297 fz_device *dev;
3298 char *s = String_val (opaque_v);
3299 struct page *page = parse_pointer (__func__, s);
3301 ret_v = caml_alloc_tuple (4);
3302 dev = fz_new_bbox_device (state.ctx, &rect);
3304 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3306 fz_close_device (state.ctx, dev);
3307 fz_drop_device (state.ctx, dev);
3308 bbox = fz_round_rect (rect);
3309 Field (ret_v, 0) = Val_int (bbox.x0);
3310 Field (ret_v, 1) = Val_int (bbox.y0);
3311 Field (ret_v, 2) = Val_int (bbox.x1);
3312 Field (ret_v, 3) = Val_int (bbox.y1);
3314 CAMLreturn (ret_v);
3317 void ml_setaalevel (value level_v);
3318 void ml_setaalevel (value level_v)
3320 CAMLparam1 (level_v);
3322 state.aalevel = Int_val (level_v);
3323 CAMLreturn0;
3326 value ml_keysymtoutf8 (value keysym_v);
3327 #ifndef CIDER
3328 value ml_keysymtoutf8 (value keysym_v)
3330 CAMLparam1 (keysym_v);
3331 CAMLlocal1 (str_v);
3332 KeySym keysym = Int_val (keysym_v);
3333 Rune rune;
3334 extern long keysym2ucs (KeySym);
3335 int len;
3336 char buf[5];
3338 rune = (Rune) keysym2ucs (keysym);
3339 len = fz_runetochar (buf, rune);
3340 buf[len] = 0;
3341 str_v = caml_copy_string (buf);
3342 CAMLreturn (str_v);
3344 #else
3345 value ml_keysymtoutf8 (value keysym_v)
3347 CAMLparam1 (keysym_v);
3348 CAMLlocal1 (str_v);
3349 long ucs = Long_val (keysym_v);
3350 int len;
3351 char buf[5];
3353 len = fz_runetochar (buf, (int) ucs);
3354 buf[len] = 0;
3355 str_v = caml_copy_string (buf);
3356 CAMLreturn (str_v);
3358 #endif
3360 enum { piunknown, pilinux, pimacos, pibsd };
3362 value ml_platform (value unit_v);
3363 value ml_platform (value unit_v)
3365 CAMLparam1 (unit_v);
3366 CAMLlocal2 (tup_v, arr_v);
3367 int platid = piunknown;
3368 struct utsname buf;
3370 #if defined __linux__
3371 platid = pilinux;
3372 #elif defined __DragonFly__ || defined __FreeBSD__
3373 || defined __OpenBSD__ || defined __NetBSD__
3374 platid = pibsd;
3375 #elif defined __APPLE__
3376 platid = pimacos;
3377 #endif
3378 if (uname (&buf)) err (1, "uname");
3380 tup_v = caml_alloc_tuple (2);
3382 char const *sar[] = {
3383 buf.sysname,
3384 buf.release,
3385 buf.version,
3386 buf.machine,
3387 NULL
3389 arr_v = caml_copy_string_array (sar);
3391 Field (tup_v, 0) = Val_int (platid);
3392 Field (tup_v, 1) = arr_v;
3393 CAMLreturn (tup_v);
3396 void ml_cloexec (value fd_v);
3397 void ml_cloexec (value fd_v)
3399 CAMLparam1 (fd_v);
3400 int fd = Int_val (fd_v);
3402 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3403 uerror ("fcntl", Nothing);
3405 CAMLreturn0;
3408 value ml_getpbo (value w_v, value h_v, value cs_v);
3409 value ml_getpbo (value w_v, value h_v, value cs_v)
3411 CAMLparam2 (w_v, h_v);
3412 CAMLlocal1 (ret_v);
3413 struct bo *pbo;
3414 int w = Int_val (w_v);
3415 int h = Int_val (h_v);
3416 int cs = Int_val (cs_v);
3418 if (state.bo_usable) {
3419 pbo = calloc (sizeof (*pbo), 1);
3420 if (!pbo) {
3421 err (1, "calloc pbo");
3424 switch (cs) {
3425 case 0:
3426 case 1:
3427 pbo->size = w*h*4;
3428 break;
3429 case 2:
3430 pbo->size = w*h*2;
3431 break;
3432 default:
3433 errx (1, "%s: invalid colorspace %d", __func__, cs);
3436 state.glGenBuffersARB (1, &pbo->id);
3437 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3438 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3439 NULL, GL_STREAM_DRAW);
3440 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3441 GL_READ_WRITE);
3442 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3443 if (!pbo->ptr) {
3444 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3445 state.glDeleteBuffersARB (1, &pbo->id);
3446 free (pbo);
3447 ret_v = caml_copy_string ("0");
3449 else {
3450 int res;
3451 char *s;
3453 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3454 if (res < 0) {
3455 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3457 s = malloc (res+1);
3458 if (!s) {
3459 err (1, "malloc %d bytes failed", res+1);
3461 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3462 if (res < 0) {
3463 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3465 ret_v = caml_copy_string (s);
3466 free (s);
3469 else {
3470 ret_v = caml_copy_string ("0");
3472 CAMLreturn (ret_v);
3475 void ml_freepbo (value s_v);
3476 void ml_freepbo (value s_v)
3478 CAMLparam1 (s_v);
3479 char *s = String_val (s_v);
3480 struct tile *tile = parse_pointer (__func__, s);
3482 if (tile->pbo) {
3483 state.glDeleteBuffersARB (1, &tile->pbo->id);
3484 tile->pbo->id = -1;
3485 tile->pbo->ptr = NULL;
3486 tile->pbo->size = -1;
3488 CAMLreturn0;
3491 void ml_unmappbo (value s_v);
3492 void ml_unmappbo (value s_v)
3494 CAMLparam1 (s_v);
3495 char *s = String_val (s_v);
3496 struct tile *tile = parse_pointer (__func__, s);
3498 if (tile->pbo) {
3499 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3500 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3501 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3503 tile->pbo->ptr = NULL;
3504 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3506 CAMLreturn0;
3509 static void setuppbo (void)
3511 extern void (*wsigladdr (const char *name)) (void);
3512 #pragma GCC diagnostic push
3513 #ifdef __clang__
3514 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3515 #endif
3516 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3517 state.bo_usable = GPA (glBindBufferARB)
3518 && GPA (glUnmapBufferARB)
3519 && GPA (glMapBufferARB)
3520 && GPA (glBufferDataARB)
3521 && GPA (glGenBuffersARB)
3522 && GPA (glDeleteBuffersARB);
3523 #undef GPA
3524 #pragma GCC diagnostic pop
3527 value ml_bo_usable (void);
3528 value ml_bo_usable (void)
3530 return Val_bool (state.bo_usable);
3533 value ml_unproject (value ptr_v, value x_v, value y_v);
3534 value ml_unproject (value ptr_v, value x_v, value y_v)
3536 CAMLparam3 (ptr_v, x_v, y_v);
3537 CAMLlocal2 (ret_v, tup_v);
3538 struct page *page;
3539 char *s = String_val (ptr_v);
3540 int x = Int_val (x_v), y = Int_val (y_v);
3541 struct pagedim *pdim;
3542 fz_point p;
3544 page = parse_pointer (__func__, s);
3545 pdim = &state.pagedims[page->pdimno];
3547 ret_v = Val_int (0);
3548 if (trylock (__func__)) {
3549 goto done;
3552 p.x = x + pdim->bounds.x0;
3553 p.y = y + pdim->bounds.y0;
3555 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3556 pdim->ctm)));
3558 tup_v = caml_alloc_tuple (2);
3559 ret_v = caml_alloc_small (1, 1);
3560 Field (tup_v, 0) = Val_int (p.x);
3561 Field (tup_v, 1) = Val_int (p.y);
3562 Field (ret_v, 0) = tup_v;
3564 unlock (__func__);
3565 done:
3566 CAMLreturn (ret_v);
3569 value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3570 value x_v, value y_v);
3571 value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3572 value x_v, value y_v)
3574 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3575 CAMLlocal1 (ret_v);
3576 struct page *page;
3577 char *s = String_val (ptr_v);
3578 int pageno = Int_val (pageno_v);
3579 int pdimno = Int_val (pdimno_v);
3580 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3581 struct pagedim *pdim;
3582 fz_point p;
3583 fz_matrix ctm;
3585 ret_v = Val_int (0);
3586 lock (__func__);
3588 if (!*s) {
3589 page = loadpage (pageno, pdimno);
3591 else {
3592 page = parse_pointer (__func__, s);
3594 pdim = &state.pagedims[pdimno];
3596 if (pdf_specifics (state.ctx, state.doc)) {
3597 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3598 ctm = state.pagedims[page->pdimno].tctm;
3600 else {
3601 ctm = fz_identity;
3603 p.x = x + pdim->bounds.x0;
3604 p.y = y + pdim->bounds.y0;
3606 ctm = fz_concat (pdim->tctm, pdim->ctm);
3607 p = fz_transform_point (p, ctm);
3609 ret_v = caml_alloc_tuple (2);
3610 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3611 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3613 if (!*s) {
3614 freepage (page);
3616 unlock (__func__);
3617 CAMLreturn (ret_v);
3620 void ml_addannot (value ptr_v, value x_v, value y_v, value contents_v);
3621 void ml_addannot (value ptr_v, value x_v, value y_v, value contents_v)
3623 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3624 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3626 if (pdf) {
3627 pdf_annot *annot;
3628 struct page *page;
3629 fz_rect r;
3630 char *s = String_val (ptr_v);
3632 page = parse_pointer (__func__, s);
3633 annot = pdf_create_annot (state.ctx,
3634 pdf_page_from_fz_page (state.ctx,
3635 page->fzpage),
3636 PDF_ANNOT_TEXT);
3637 r.x0 = Int_val (x_v) - 10;
3638 r.y0 = Int_val (y_v) - 10;
3639 r.x1 = r.x0 + 20;
3640 r.y1 = r.y0 + 20;
3641 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3642 pdf_set_annot_rect (state.ctx, annot, r);
3644 state.dirty = 1;
3646 CAMLreturn0;
3649 void ml_delannot (value ptr_v, value n_v);
3650 void ml_delannot (value ptr_v, value n_v)
3652 CAMLparam2 (ptr_v, n_v);
3653 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3655 if (pdf) {
3656 struct page *page;
3657 char *s = String_val (ptr_v);
3658 struct slink *slink;
3660 page = parse_pointer (__func__, s);
3661 slink = &page->slinks[Int_val (n_v)];
3662 pdf_delete_annot (state.ctx,
3663 pdf_page_from_fz_page (state.ctx, page->fzpage),
3664 (pdf_annot *) slink->u.annot);
3665 state.dirty = 1;
3667 CAMLreturn0;
3670 void ml_modannot (value ptr_v, value n_v, value str_v);
3671 void ml_modannot (value ptr_v, value n_v, value str_v)
3673 CAMLparam3 (ptr_v, n_v, str_v);
3674 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3676 if (pdf) {
3677 struct page *page;
3678 char *s = String_val (ptr_v);
3679 struct slink *slink;
3681 page = parse_pointer (__func__, s);
3682 slink = &page->slinks[Int_val (n_v)];
3683 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3684 String_val (str_v));
3685 state.dirty = 1;
3687 CAMLreturn0;
3690 value ml_hasunsavedchanges (void);
3691 value ml_hasunsavedchanges (void)
3693 return Val_bool (state.dirty);
3696 void ml_savedoc (value path_v);
3697 void ml_savedoc (value path_v)
3699 CAMLparam1 (path_v);
3700 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3702 if (pdf) {
3703 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3705 CAMLreturn0;
3708 static void makestippletex (void)
3710 const char pixels[] = "\xff\xff\0\0";
3711 glGenTextures (1, &state.stid);
3712 glBindTexture (GL_TEXTURE_1D, state.stid);
3713 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3714 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3715 glTexImage1D (
3716 GL_TEXTURE_1D,
3718 GL_ALPHA,
3721 GL_ALPHA,
3722 GL_UNSIGNED_BYTE,
3723 pixels
3727 value ml_fz_version (void);
3728 value ml_fz_version (void)
3730 return caml_copy_string (FZ_VERSION);
3733 value ml_llpp_version (void);
3734 value ml_llpp_version (void)
3736 extern char llpp_version[];
3737 return caml_copy_string (llpp_version);
3740 void ml_init (value csock_v, value params_v);
3741 void ml_init (value csock_v, value params_v)
3743 CAMLparam2 (csock_v, params_v);
3744 CAMLlocal2 (trim_v, fuzz_v);
3745 int ret;
3746 int texcount;
3747 char *fontpath;
3748 int colorspace;
3749 int mustoresize;
3751 state.csock = Int_val (csock_v);
3752 state.rotate = Int_val (Field (params_v, 0));
3753 state.fitmodel = Int_val (Field (params_v, 1));
3754 trim_v = Field (params_v, 2);
3755 texcount = Int_val (Field (params_v, 3));
3756 state.sliceheight = Int_val (Field (params_v, 4));
3757 mustoresize = Int_val (Field (params_v, 5));
3758 colorspace = Int_val (Field (params_v, 6));
3759 fontpath = String_val (Field (params_v, 7));
3761 #ifdef CIDER
3762 state.utf8cs = 1;
3763 #else
3764 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3765 if (setlocale (LC_CTYPE, "")) {
3766 const char *cset = nl_langinfo (CODESET);
3767 state.utf8cs = !strcmp (cset, "UTF-8");
3769 else {
3770 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3772 #endif
3774 if (caml_string_length (Field (params_v, 8)) > 0) {
3775 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3777 if (!state.trimcachepath) {
3778 printd ("emsg failed to strdup trimcachepath: %d:%s",
3779 errno, strerror (errno));
3783 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3784 fz_register_document_handlers (state.ctx);
3786 state.trimmargins = Bool_val (Field (trim_v, 0));
3787 fuzz_v = Field (trim_v, 1);
3788 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3789 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3790 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3791 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3793 set_tex_params (colorspace);
3795 if (*fontpath) {
3796 state.face = load_font (fontpath);
3798 else {
3799 int len;
3800 const unsigned char *data;
3802 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3803 state.face = load_builtin_font (data, len);
3805 if (!state.face) _exit (1);
3807 realloctexts (texcount);
3808 setuppbo ();
3809 makestippletex ();
3811 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3812 if (ret) {
3813 errx (1, "pthread_create: %s", strerror (ret));
3816 CAMLreturn0;
3819 #if FIXME || !FIXME
3820 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3821 #endif