Reload flicker avoidance
[llpp.git] / link.c
blobc35a5d6d25513d5b60b5b19ab02650f0ecdeb098
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 fz_annot *annot;
123 } u;
126 struct annot {
127 fz_irect bbox;
128 fz_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 #ifdef CACHE_PAGEREFS
208 struct {
209 int idx;
210 int count;
211 pdf_obj **objs;
212 pdf_document *pdf;
213 } pdflut;
214 #endif
215 int utf8cs;
216 } state;
218 struct bo {
219 GLuint id;
220 void *ptr;
221 size_t size;
224 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
226 static void lock (const char *cap)
228 int ret = pthread_mutex_lock (&mutex);
229 if (ret) {
230 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
234 static void unlock (const char *cap)
236 int ret = pthread_mutex_unlock (&mutex);
237 if (ret) {
238 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
242 static int trylock (const char *cap)
244 int ret = pthread_mutex_trylock (&mutex);
245 if (ret && ret != EBUSY) {
246 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
248 return ret == EBUSY;
251 static int hasdata (void)
253 int ret, avail;
254 ret = ioctl (state.csock, FIONREAD, &avail);
255 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
256 return avail > 0;
259 value ml_hasdata (value fd_v);
260 value ml_hasdata (value fd_v)
262 CAMLparam1 (fd_v);
263 int ret, avail;
265 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
266 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
267 CAMLreturn (Val_bool (avail > 0));
270 static void readdata (int fd, void *p, int size)
272 ssize_t n;
274 again:
275 n = read (fd, p, size);
276 if (n - size) {
277 if (n < 0 && errno == EINTR) goto again;
278 if (!n) errx (1, "EOF while reading");
279 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
283 static void writedata (int fd, char *p, int size)
285 ssize_t n;
286 uint32_t size4 = size;
287 struct iovec iov[2] = {
288 { .iov_base = &size4, .iov_len = 4 },
289 { .iov_base = p, .iov_len = size }
292 again:
293 n = writev (fd, iov, 2);
294 if (n < 0 && errno == EINTR) goto again;
295 if (n - size - 4) {
296 if (!n) errx (1, "EOF while writing data");
297 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
301 static int readlen (int fd)
303 uint32_t u;
304 readdata (fd, &u, 4);
305 return u;
308 void ml_wcmd (value fd_v, value bytes_v, value len_v);
309 void ml_wcmd (value fd_v, value bytes_v, value len_v)
311 CAMLparam3 (fd_v, bytes_v, len_v);
312 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
313 CAMLreturn0;
316 value ml_rcmd (value fd_v);
317 value ml_rcmd (value fd_v)
319 CAMLparam1 (fd_v);
320 CAMLlocal1 (strdata_v);
321 int fd = Int_val (fd_v);
322 int len = readlen (fd);
323 strdata_v = caml_alloc_string (len);
324 readdata (fd, String_val (strdata_v), len);
325 CAMLreturn (strdata_v);
328 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
330 char fbuf[64];
331 int size = sizeof (fbuf), len;
332 va_list ap;
333 char *buf = fbuf;
335 for (;;) {
336 va_start (ap, fmt);
337 len = vsnprintf (buf, size, fmt, ap);
338 va_end (ap);
340 if (len > -1) {
341 if (len < size - 4) {
342 writedata (state.csock, buf, len);
343 break;
345 else size = len + 5;
347 else {
348 err (1, "vsnprintf for `%s' failed", fmt);
350 buf = realloc (buf == fbuf ? NULL : buf, size);
351 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
353 if (buf != fbuf) free (buf);
356 static void closedoc (void)
358 #ifdef CACHE_PAGEREFS
359 if (state.pdflut.objs) {
360 for (int i = 0; i < state.pdflut.count; ++i) {
361 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
363 free (state.pdflut.objs);
364 state.pdflut.objs = NULL;
365 state.pdflut.idx = 0;
367 #endif
368 if (state.doc) {
369 fz_drop_document (state.ctx, state.doc);
370 state.doc = NULL;
374 static int openxref (char *filename, char *password, int layouth)
376 for (int i = 0; i < state.texcount; ++i) {
377 state.texowners[i].w = -1;
378 state.texowners[i].slice = NULL;
381 closedoc ();
383 state.dirty = 0;
384 if (state.pagedims) {
385 free (state.pagedims);
386 state.pagedims = NULL;
388 state.pagedimcount = 0;
390 fz_set_aa_level (state.ctx, state.aalevel);
391 state.doc = fz_open_document (state.ctx, filename);
392 if (fz_needs_password (state.ctx, state.doc)) {
393 if (password && !*password) {
394 printd ("pass");
395 return 0;
397 else {
398 int ok = fz_authenticate_password (state.ctx, state.doc, password);
399 if (!ok) {
400 printd ("pass fail");
401 return 0;
405 if (layouth >= 0)
406 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
407 state.pagecount = fz_count_pages (state.ctx, state.doc);
408 return 1;
411 static void docinfo (void)
413 struct { char *tag; char *name; } metatbl[] = {
414 { FZ_META_INFO_TITLE, "Title" },
415 { FZ_META_INFO_AUTHOR, "Author" },
416 { FZ_META_FORMAT, "Format" },
417 { FZ_META_ENCRYPTION, "Encryption" },
418 { "info:Creator", "Creator" },
419 { "info:Producer", "Producer" },
420 { "info:CreationDate", "Creation date" },
422 int len = 0;
423 char *buf = NULL;
425 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
426 int need;
427 again:
428 need = fz_lookup_metadata (state.ctx, state.doc,
429 metatbl[i].tag, buf, len);
430 if (need > 0) {
431 if (need <= len) {
432 printd ("info %s\t%s", metatbl[i].name, buf);
434 else {
435 buf = realloc (buf, need + 1);
436 if (!buf) err (1, "docinfo realloc %d", need + 1);
437 len = need + 1;
438 goto again;
442 free (buf);
444 printd ("infoend");
447 static void unlinktile (struct tile *tile)
449 for (int i = 0; i < tile->slicecount; ++i) {
450 struct slice *s = &tile->slices[i];
452 if (s->texindex != -1) {
453 if (state.texowners[s->texindex].slice == s) {
454 state.texowners[s->texindex].slice = NULL;
460 static void freepage (struct page *page)
462 if (!page) return;
463 if (page->text) {
464 fz_drop_stext_page (state.ctx, page->text);
466 if (page->slinks) {
467 free (page->slinks);
469 fz_drop_display_list (state.ctx, page->dlist);
470 fz_drop_page (state.ctx, page->fzpage);
471 free (page);
474 static void freetile (struct tile *tile)
476 unlinktile (tile);
477 if (!tile->pbo) {
478 #if 0
479 fz_drop_pixmap (state.ctx, tile->pixmap);
480 #else /* piggyback */
481 if (state.pig) {
482 fz_drop_pixmap (state.ctx, state.pig);
484 state.pig = tile->pixmap;
485 #endif
487 else {
488 free (tile->pbo);
489 fz_drop_pixmap (state.ctx, tile->pixmap);
491 free (tile);
494 static void trimctm (pdf_page *page, int pindex)
496 struct pagedim *pdim = &state.pagedims[pindex];
498 if (!page) return;
499 if (!pdim->tctmready) {
500 fz_rect realbox, mediabox;
501 fz_matrix page_ctm, ctm;
503 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
504 realbox = fz_transform_rect (pdim->mediabox, ctm);
505 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
506 pdim->tctm = fz_concat (
507 fz_invert_matrix (page_ctm),
508 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
509 pdim->tctmready = 1;
513 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
515 fz_matrix ctm;
516 ptrdiff_t pdimno = pdim - state.pagedims;
518 ARSERT (pdim - state.pagedims < INT_MAX);
519 if (pdf_specifics (state.ctx, state.doc)) {
520 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
521 ctm = fz_concat (pdim->tctm, pdim->ctm);
523 else {
524 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
525 pdim->ctm);
527 return ctm;
530 static fz_matrix pagectm (struct page *page)
532 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
535 static void *loadpage (int pageno, int pindex)
537 fz_device *dev;
538 struct page *page;
540 page = calloc (sizeof (struct page), 1);
541 if (!page) {
542 err (1, "calloc page %d", pageno);
545 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
546 dev = fz_new_list_device (state.ctx, page->dlist);
547 fz_try (state.ctx) {
548 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
549 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
551 fz_catch (state.ctx) {
552 page->fzpage = NULL;
554 fz_close_device (state.ctx, dev);
555 fz_drop_device (state.ctx, dev);
557 page->pdimno = pindex;
558 page->pageno = pageno;
559 page->sgen = state.gen;
560 page->agen = state.gen;
561 page->tgen = state.gen;
562 return page;
565 static struct tile *alloctile (int h)
567 int slicecount;
568 size_t tilesize;
569 struct tile *tile;
571 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
572 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
573 tile = calloc (tilesize, 1);
574 if (!tile) {
575 err (1, "cannot allocate tile (%zu bytes)", tilesize);
577 for (int i = 0; i < slicecount; ++i) {
578 int sh = fz_mini (h, state.sliceheight);
579 tile->slices[i].h = sh;
580 tile->slices[i].texindex = -1;
581 h -= sh;
583 tile->slicecount = slicecount;
584 tile->sliceheight = state.sliceheight;
585 return tile;
588 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
589 struct bo *pbo)
591 fz_irect bbox;
592 fz_matrix ctm;
593 fz_device *dev;
594 struct tile *tile;
595 struct pagedim *pdim;
597 tile = alloctile (h);
598 pdim = &state.pagedims[page->pdimno];
600 bbox = pdim->bounds;
601 bbox.x0 += x;
602 bbox.y0 += y;
603 bbox.x1 = bbox.x0 + w;
604 bbox.y1 = bbox.y0 + h;
606 if (state.pig) {
607 if (state.pig->w == w
608 && state.pig->h == h
609 && state.pig->colorspace == state.colorspace) {
610 tile->pixmap = state.pig;
611 tile->pixmap->x = bbox.x0;
612 tile->pixmap->y = bbox.y0;
614 else {
615 fz_drop_pixmap (state.ctx, state.pig);
617 state.pig = NULL;
619 if (!tile->pixmap) {
620 if (pbo) {
621 tile->pixmap =
622 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
623 bbox, NULL, 1, pbo->ptr);
624 tile->pbo = pbo;
626 else {
627 tile->pixmap =
628 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
629 NULL, 1);
633 tile->w = w;
634 tile->h = h;
635 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
637 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
638 ctm = pagectm (page);
639 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
640 fz_rect_from_irect (bbox), NULL);
641 fz_close_device (state.ctx, dev);
642 fz_drop_device (state.ctx, dev);
644 return tile;
647 #ifdef CACHE_PAGEREFS
648 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
649 thanks to Robin Watts */
650 static void
651 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
653 fz_context *ctx = state.ctx; /* doc->ctx; */
654 pdf_obj *kids;
655 int len;
657 if (state.pdflut.idx == state.pagecount) return;
659 kids = pdf_dict_gets (ctx, node, "Kids");
660 len = pdf_array_len (ctx, kids);
662 if (len == 0)
663 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
665 if (pdf_mark_obj (ctx, node))
666 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
667 for (int i = 0; i < len; i++) {
668 pdf_obj *kid = pdf_array_get (ctx, kids, i);
669 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
670 if (*type
671 ? !strcmp (type, "Pages")
672 : pdf_dict_gets (ctx, kid, "Kids")
673 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
674 pdf_collect_pages (doc, kid);
676 else {
677 if (*type
678 ? strcmp (type, "Page") != 0
679 : !pdf_dict_gets (ctx, kid, "MediaBox"))
680 fz_warn (ctx, "non-page object in page tree (%s)", type);
681 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
684 pdf_unmark_obj (ctx, node);
687 static void
688 pdf_load_page_objs (pdf_document *doc)
690 pdf_obj *root = pdf_dict_gets (state.ctx,
691 pdf_trailer (state.ctx, doc), "Root");
692 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
694 if (!node)
695 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
697 state.pdflut.idx = 0;
698 pdf_collect_pages (doc, node);
700 #endif
702 static void initpdims (void)
704 double start, end;
705 FILE *trimf = NULL;
706 fz_rect rootmediabox = fz_empty_rect;
707 int pageno, trim, show;
708 int trimw = 0, cxcount;
709 fz_context *ctx = state.ctx;
710 pdf_document *pdf = pdf_specifics (ctx, state.doc);
712 fz_var (trimw);
713 fz_var (trimf);
714 fz_var (cxcount);
715 start = now ();
717 if (state.trimmargins && state.trimcachepath) {
718 trimf = fopen (state.trimcachepath, "rb");
719 if (!trimf) {
720 trimf = fopen (state.trimcachepath, "wb");
721 trimw = 1;
725 cxcount = state.pagecount;
726 if (pdf) {
727 pdf_obj *obj;
728 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
729 "Root/Pages/MediaBox");
730 rootmediabox = pdf_to_rect (ctx, obj);
733 #ifdef CACHE_PAGEREFS
734 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
735 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
736 if (!state.pdflut.objs) {
737 err (1, "malloc pageobjs %zu %d %zu failed",
738 sizeof (*state.pdflut.objs), cxcount,
739 sizeof (*state.pdflut.objs) * cxcount);
741 state.pdflut.count = cxcount;
742 pdf_load_page_objs (pdf);
743 state.pdflut.pdf = pdf;
745 #endif
747 for (pageno = 0; pageno < cxcount; ++pageno) {
748 int rotate = 0;
749 struct pagedim *p;
750 fz_rect mediabox = fz_empty_rect;
752 fz_var (rotate);
753 if (pdf) {
754 pdf_obj *pageref, *pageobj;
756 #ifdef CACHE_PAGEREFS
757 pageref = state.pdflut.objs[pageno];
758 #else
759 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
760 #endif
761 pageobj = pdf_resolve_indirect (ctx, pageref);
762 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
764 if (state.trimmargins) {
765 pdf_obj *obj;
766 pdf_page *page;
768 fz_try (ctx) {
769 page = pdf_load_page (ctx, pdf, pageno);
770 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
771 trim = state.trimanew || !obj;
772 if (trim) {
773 fz_rect rect;
774 fz_device *dev;
775 fz_matrix ctm, page_ctm;
777 dev = fz_new_bbox_device (ctx, &rect);
778 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
779 ctm = fz_invert_matrix (page_ctm);
780 pdf_run_page (ctx, page, dev, fz_identity, NULL);
781 fz_close_device (ctx, dev);
782 fz_drop_device (ctx, dev);
784 rect.x0 += state.trimfuzz.x0;
785 rect.x1 += state.trimfuzz.x1;
786 rect.y0 += state.trimfuzz.y0;
787 rect.y1 += state.trimfuzz.y1;
788 rect = fz_transform_rect (rect, ctm);
789 rect = fz_intersect_rect (rect, mediabox);
791 if (!fz_is_empty_rect (rect)) {
792 mediabox = rect;
795 obj = pdf_new_array (ctx, pdf, 4);
796 pdf_array_push (ctx, obj,
797 pdf_new_real (ctx, mediabox.x0));
798 pdf_array_push (ctx, obj,
799 pdf_new_real (ctx, mediabox.y0));
800 pdf_array_push (ctx, obj,
801 pdf_new_real (ctx, mediabox.x1));
802 pdf_array_push (ctx, obj,
803 pdf_new_real (ctx, mediabox.y1));
804 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
806 else {
807 mediabox.x0 = pdf_to_real (ctx,
808 pdf_array_get (ctx, obj, 0));
809 mediabox.y0 = pdf_to_real (ctx,
810 pdf_array_get (ctx, obj, 1));
811 mediabox.x1 = pdf_to_real (ctx,
812 pdf_array_get (ctx, obj, 2));
813 mediabox.y1 = pdf_to_real (ctx,
814 pdf_array_get (ctx, obj, 3));
817 fz_drop_page (ctx, &page->super);
818 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
819 if (show) {
820 printd ("progress %f Trimming %d",
821 (double) (pageno + 1) / state.pagecount,
822 pageno + 1);
825 fz_catch (ctx) {
826 printd ("emsg failed to load page %d", pageno);
829 else {
830 int empty = 0;
831 fz_rect cropbox;
833 mediabox =
834 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "MediaBox"));
835 if (fz_is_empty_rect (mediabox)) {
836 mediabox.x0 = 0;
837 mediabox.y0 = 0;
838 mediabox.x1 = 612;
839 mediabox.y1 = 792;
840 empty = 1;
843 cropbox =
844 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
845 if (!fz_is_empty_rect (cropbox)) {
846 if (empty) {
847 mediabox = cropbox;
849 else {
850 mediabox = fz_intersect_rect (mediabox, cropbox);
853 else {
854 if (empty) {
855 if (fz_is_empty_rect (rootmediabox)) {
856 printd ("emsg cannot find page size for page %d",
857 pageno);
859 else {
860 mediabox = rootmediabox;
866 else {
867 if (state.trimmargins && trimw) {
868 fz_page *page;
870 fz_try (ctx) {
871 page = fz_load_page (ctx, state.doc, pageno);
872 mediabox = fz_bound_page (ctx, page);
873 if (state.trimmargins) {
874 fz_rect rect;
875 fz_device *dev;
877 dev = fz_new_bbox_device (ctx, &rect);
878 fz_run_page (ctx, page, dev, fz_identity, NULL);
879 fz_close_device (ctx, dev);
880 fz_drop_device (ctx, dev);
882 rect.x0 += state.trimfuzz.x0;
883 rect.x1 += state.trimfuzz.x1;
884 rect.y0 += state.trimfuzz.y0;
885 rect.y1 += state.trimfuzz.y1;
886 rect = fz_intersect_rect (rect, mediabox);
888 if (!fz_is_empty_rect (rect)) {
889 mediabox = rect;
892 fz_drop_page (ctx, page);
894 fz_catch (ctx) {
896 if (trimf) {
897 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
898 if (n - 1) {
899 err (1, "fwrite trim mediabox");
903 else {
904 if (trimf) {
905 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
906 if (n - 1) {
907 err (1, "fread trim mediabox %d", pageno);
910 else {
911 fz_page *page;
912 fz_try (ctx) {
913 page = fz_load_page (ctx, state.doc, pageno);
914 mediabox = fz_bound_page (ctx, page);
915 fz_drop_page (ctx, page);
917 show = !state.trimmargins && pageno % 20 == 0;
918 if (show) {
919 printd ("progress %f Gathering dimensions %d",
920 (double) (pageno) / state.pagecount,
921 pageno);
924 fz_catch (ctx) {
925 printd ("emsg failed to load page %d", pageno);
931 if (state.pagedimcount == 0
932 || ((void) (p = &state.pagedims[state.pagedimcount-1])
933 , p->rotate != rotate)
934 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
935 size_t size;
937 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
938 state.pagedims = realloc (state.pagedims, size);
939 if (!state.pagedims) {
940 err (1, "realloc pagedims to %zu (%d elems)",
941 size, state.pagedimcount + 1);
944 p = &state.pagedims[state.pagedimcount++];
945 p->rotate = rotate;
946 p->mediabox = mediabox;
947 p->pageno = pageno;
950 end = now ();
951 printd ("progress 1 %s %d pages in %f seconds",
952 state.trimmargins ? "Trimmed" : "Processed",
953 state.pagecount, end - start);
954 state.trimanew = 0;
955 if (trimf) {
956 if (fclose (trimf)) {
957 err (1, "fclose");
962 static void layout (void)
964 int pindex;
965 fz_rect box;
966 fz_matrix ctm;
967 struct pagedim *p = NULL;
968 float zw, w, maxw = 0.0, zoom = 1.0;
970 if (state.pagedimcount == 0) return;
972 switch (state.fitmodel) {
973 case FitProportional:
974 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
975 float x0, x1;
977 p = &state.pagedims[pindex];
978 box = fz_transform_rect (p->mediabox,
979 fz_rotate (p->rotate + state.rotate));
981 x0 = fz_min (box.x0, box.x1);
982 x1 = fz_max (box.x0, box.x1);
984 w = x1 - x0;
985 maxw = fz_max (w, maxw);
986 zoom = state.w / maxw;
988 break;
990 case FitPage:
991 maxw = state.w;
992 break;
994 case FitWidth:
995 break;
997 default:
998 ARSERT (0 && state.fitmodel);
1001 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1002 p = &state.pagedims[pindex];
1003 ctm = fz_rotate (state.rotate);
1004 box = fz_transform_rect (p->mediabox,
1005 fz_rotate (p->rotate + state.rotate));
1006 w = box.x1 - box.x0;
1007 switch (state.fitmodel) {
1008 case FitProportional:
1009 p->left = (int) (((maxw - w) * zoom) / 2.f);
1010 break;
1011 case FitPage:
1013 float zh, h;
1014 zw = maxw / w;
1015 h = box.y1 - box.y0;
1016 zh = state.h / h;
1017 zoom = fz_min (zw, zh);
1018 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1020 break;
1021 case FitWidth:
1022 p->left = 0;
1023 zoom = state.w / w;
1024 break;
1027 p->zoomctm = fz_scale (zoom, zoom);
1028 ctm = fz_concat (p->zoomctm, ctm);
1030 p->pagebox = p->mediabox;
1031 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
1032 p->pagebox.x1 -= p->pagebox.x0;
1033 p->pagebox.y1 -= p->pagebox.y0;
1034 p->pagebox.x0 = 0;
1035 p->pagebox.y0 = 0;
1036 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
1037 p->ctm = ctm;
1039 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
1040 fz_scale (zoom, -zoom));
1041 p->tctmready = 0;
1044 do {
1045 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1046 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1047 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1048 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1049 int boundw = x1 - x0;
1050 int boundh = y1 - y0;
1052 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1053 } while (p-- != state.pagedims);
1056 static struct pagedim *pdimofpageno (int pageno)
1058 struct pagedim *pdim = state.pagedims;
1060 for (int i = 0; i < state.pagedimcount; ++i) {
1061 if (state.pagedims[i].pageno > pageno)
1062 break;
1063 pdim = &state.pagedims[i];
1065 return pdim;
1068 static void recurse_outline (fz_outline *outline, int level)
1070 while (outline) {
1071 if (outline->page >= 0) {
1072 fz_point p = {.x = outline->x, .y = outline->y};
1073 struct pagedim *pdim = pdimofpageno (outline->page);
1074 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1075 p = fz_transform_point (p, pdim->ctm);
1076 printd ("o %d %d %d %d %s",
1077 level, outline->page, (int) p.y, h, outline->title);
1079 else {
1080 printd ("on %d %s", level, outline->title);
1082 if (outline->down) {
1083 recurse_outline (outline->down, level + 1);
1085 outline = outline->next;
1089 static void process_outline (void)
1091 fz_outline *outline;
1093 if (!state.needoutline || !state.pagedimcount) return;
1095 state.needoutline = 0;
1096 outline = fz_load_outline (state.ctx, state.doc);
1097 if (outline) {
1098 recurse_outline (outline, 0);
1099 fz_drop_outline (state.ctx, outline);
1103 static char *strofline (fz_stext_line *line)
1105 char *p;
1106 char utf8[10];
1107 fz_stext_char *ch;
1108 size_t size = 0, cap = 80;
1110 p = malloc (cap + 1);
1111 if (!p) return NULL;
1113 for (ch = line->first_char; ch; ch = ch->next) {
1114 int n = fz_runetochar (utf8, ch->c);
1115 if (size + n > cap) {
1116 cap *= 2;
1117 p = realloc (p, cap + 1);
1118 if (!p) return NULL;
1121 memcpy (p + size, utf8, n);
1122 size += n;
1124 p[size] = 0;
1125 return p;
1128 static int matchline (regex_t *re, fz_stext_line *line,
1129 int stop, int pageno, double start)
1131 int ret;
1132 char *p;
1133 regmatch_t rm;
1135 p = strofline (line);
1136 if (!p) return -1;
1138 ret = regexec (re, p, 1, &rm, 0);
1139 if (ret) {
1140 free (p);
1141 if (ret != REG_NOMATCH) {
1142 size_t size;
1143 char errbuf[80];
1144 size = regerror (ret, re, errbuf, sizeof (errbuf));
1145 printd ("msg regexec error `%.*s'",
1146 (int) size, errbuf);
1147 return -1;
1149 return 0;
1151 else {
1152 fz_quad s, e;
1153 fz_stext_char *ch;
1154 int o = 0;
1156 for (ch = line->first_char; ch; ch = ch->next) {
1157 o += fz_runelen (ch->c);
1158 if (o > rm.rm_so) {
1159 s = ch->quad;
1160 break;
1163 for (;ch; ch = ch->next) {
1164 o += fz_runelen (ch->c);
1165 if (o > rm.rm_eo) break;
1167 e = ch->quad;
1169 if (!stop) {
1170 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1171 pageno, 1,
1172 s.ul.x, s.ul.y,
1173 e.ur.x, s.ul.y,
1174 e.lr.x, e.lr.y,
1175 s.ul.x, e.lr.y);
1177 printd ("progress 1 found at %d `%.*s' in %f sec",
1178 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1179 now () - start);
1181 else {
1182 printd ("match %d %d %f %f %f %f %f %f %f %f",
1183 pageno, 2,
1184 s.ul.x, s.ul.y,
1185 e.ur.x, s.ul.y,
1186 e.lr.x, e.lr.y,
1187 s.ul.x, e.lr.y);
1189 free (p);
1190 return 1;
1194 /* wishful thinking function */
1195 static void search (regex_t *re, int pageno, int y, int forward)
1197 fz_device *tdev;
1198 fz_stext_page *text;
1199 struct pagedim *pdim;
1200 int stop = 0, niters = 0;
1201 double start, end;
1202 fz_page *page;
1203 fz_stext_block *block;
1205 start = now ();
1206 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1207 if (niters++ == 5) {
1208 niters = 0;
1209 if (hasdata ()) {
1210 printd ("progress 1 attention requested aborting search at %d",
1211 pageno);
1212 stop = 1;
1214 else {
1215 printd ("progress %f searching in page %d",
1216 (double) (pageno + 1) / state.pagecount,
1217 pageno);
1220 pdim = pdimofpageno (pageno);
1221 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1222 tdev = fz_new_stext_device (state.ctx, text, 0);
1224 page = fz_load_page (state.ctx, state.doc, pageno);
1225 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1227 fz_close_device (state.ctx, tdev);
1228 fz_drop_device (state.ctx, tdev);
1230 if (forward) {
1231 for (block = text->first_block; block; block = block->next) {
1232 fz_stext_line *line;
1234 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1235 for (line = block->u.t.first_line; line; line = line->next) {
1236 if (line->bbox.y0 < y + 1) continue;
1238 switch (matchline (re, line, stop, pageno, start)) {
1239 case 0: break;
1240 case 1: stop = 1; break;
1241 case -1: stop = 1; goto endloop;
1246 else {
1247 for (block = text->last_block; block; block = block->prev) {
1248 fz_stext_line *line;
1250 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1251 for (line = block->u.t.last_line; line; line = line->prev) {
1252 if (line->bbox.y0 < y + 1) continue;
1254 switch (matchline (re, line, stop, pageno, start)) {
1255 case 0: break;
1256 case 1: stop = 1; break;
1257 case -1: stop = 1; goto endloop;
1263 if (forward) {
1264 pageno += 1;
1265 y = 0;
1267 else {
1268 pageno -= 1;
1269 y = INT_MAX;
1271 endloop:
1272 fz_drop_stext_page (state.ctx, text);
1273 fz_drop_page (state.ctx, page);
1275 end = now ();
1276 if (!stop) {
1277 printd ("progress 1 no matches %f sec", end - start);
1279 printd ("clearrects");
1282 static void set_tex_params (int colorspace)
1284 switch (colorspace) {
1285 case 0:
1286 state.texiform = GL_RGBA8;
1287 state.texform = GL_RGBA;
1288 state.texty = GL_UNSIGNED_BYTE;
1289 state.colorspace = fz_device_rgb (state.ctx);
1290 break;
1291 case 1:
1292 state.texiform = GL_LUMINANCE_ALPHA;
1293 state.texform = GL_LUMINANCE_ALPHA;
1294 state.texty = GL_UNSIGNED_BYTE;
1295 state.colorspace = fz_device_gray (state.ctx);
1296 break;
1297 default:
1298 errx (1, "invalid colorspce %d", colorspace);
1302 static void realloctexts (int texcount)
1304 size_t size;
1306 if (texcount == state.texcount) return;
1308 if (texcount < state.texcount) {
1309 glDeleteTextures (state.texcount - texcount,
1310 state.texids + texcount);
1313 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1314 state.texids = realloc (state.texids, size);
1315 if (!state.texids) {
1316 err (1, "realloc texs %zu", size);
1319 state.texowners = (void *) (state.texids + texcount);
1320 if (texcount > state.texcount) {
1321 glGenTextures (texcount - state.texcount,
1322 state.texids + state.texcount);
1323 for (int i = state.texcount; i < texcount; ++i) {
1324 state.texowners[i].w = -1;
1325 state.texowners[i].slice = NULL;
1328 state.texcount = texcount;
1329 state.texindex = 0;
1332 static char *mbtoutf8 (char *s)
1334 char *p, *r;
1335 wchar_t *tmp;
1336 size_t i, ret, len;
1338 if (state.utf8cs) {
1339 return s;
1342 len = mbstowcs (NULL, s, strlen (s));
1343 if (len == 0 || len == (size_t) -1) {
1344 if (len)
1345 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1346 return s;
1349 tmp = calloc (len, sizeof (wchar_t));
1350 if (!tmp) {
1351 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1352 len, sizeof (wchar_t), errno, strerror (errno));
1353 return s;
1356 ret = mbstowcs (tmp, s, len);
1357 if (ret == (size_t) -1) {
1358 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1359 len, errno, strerror (errno));
1360 free (tmp);
1361 return s;
1364 len = 0;
1365 for (i = 0; i < ret; ++i) {
1366 len += fz_runelen (tmp[i]);
1369 p = r = malloc (len + 1);
1370 if (!r) {
1371 printd ("emsg mbtoutf8: malloc(%zu)", len);
1372 free (tmp);
1373 return s;
1376 for (i = 0; i < ret; ++i) {
1377 p += fz_runetochar (p, tmp[i]);
1379 *p = 0;
1380 free (tmp);
1381 return r;
1384 value ml_mbtoutf8 (value s_v);
1385 value ml_mbtoutf8 (value s_v)
1387 CAMLparam1 (s_v);
1388 CAMLlocal1 (ret_v);
1389 char *s, *r;
1391 s = String_val (s_v);
1392 r = mbtoutf8 (s);
1393 if (r == s) {
1394 ret_v = s_v;
1396 else {
1397 ret_v = caml_copy_string (r);
1398 free (r);
1400 CAMLreturn (ret_v);
1403 static void * mainloop (void UNUSED_ATTR *unused)
1405 char *p = NULL;
1406 int len, ret, oldlen = 0;
1408 fz_var (p);
1409 fz_var (oldlen);
1410 for (;;) {
1411 len = readlen (state.csock);
1412 if (len == 0) {
1413 errx (1, "readlen returned 0");
1416 if (oldlen < len + 1) {
1417 p = realloc (p, len + 1);
1418 if (!p) {
1419 err (1, "realloc %d failed", len + 1);
1421 oldlen = len + 1;
1423 readdata (state.csock, p, len);
1424 p[len] = 0;
1426 if (!strncmp ("open", p, 4)) {
1427 int off, usedoccss, ok = 0, layouth;
1428 char *password;
1429 char *filename;
1430 char *utf8filename;
1431 size_t filenamelen;
1433 fz_var (ok);
1434 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1435 if (ret != 2) {
1436 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1439 filename = p + 5 + off;
1440 filenamelen = strlen (filename);
1441 password = filename + filenamelen + 1;
1443 if (password[strlen (password) + 1]) {
1444 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1447 lock ("open");
1448 fz_set_use_document_css (state.ctx, usedoccss);
1449 fz_try (state.ctx) {
1450 ok = openxref (filename, password, layouth);
1452 fz_catch (state.ctx) {
1453 utf8filename = mbtoutf8 (filename);
1454 printd ("msg Could not open %s", utf8filename);
1455 if (utf8filename != filename) {
1456 free (utf8filename);
1459 if (ok) {
1460 docinfo ();
1461 initpdims ();
1463 unlock ("open");
1465 if (ok) {
1466 utf8filename = mbtoutf8 (filename);
1467 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1468 if (utf8filename != filename) {
1469 free (utf8filename);
1471 state.needoutline = 1;
1474 else if (!strncmp ("cs", p, 2)) {
1475 int i, colorspace;
1477 ret = sscanf (p + 2, " %d", &colorspace);
1478 if (ret != 1) {
1479 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1481 lock ("cs");
1482 set_tex_params (colorspace);
1483 for (i = 0; i < state.texcount; ++i) {
1484 state.texowners[i].w = -1;
1485 state.texowners[i].slice = NULL;
1487 unlock ("cs");
1489 else if (!strncmp ("freepage", p, 8)) {
1490 void *ptr;
1492 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1493 if (ret != 1) {
1494 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1496 lock ("freepage");
1497 freepage (ptr);
1498 unlock ("freepage");
1500 else if (!strncmp ("freetile", p, 8)) {
1501 void *ptr;
1503 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1504 if (ret != 1) {
1505 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1507 lock ("freetile");
1508 freetile (ptr);
1509 unlock ("freetile");
1511 else if (!strncmp ("search", p, 6)) {
1512 int icase, pageno, y, len2, forward;
1513 char *pattern;
1514 regex_t re;
1516 ret = sscanf (p + 6, " %d %d %d %d,%n",
1517 &icase, &pageno, &y, &forward, &len2);
1518 if (ret != 4) {
1519 errx (1, "malformed search `%s' ret=%d", p, ret);
1522 pattern = p + 6 + len2;
1523 ret = regcomp (&re, pattern,
1524 REG_EXTENDED | (icase ? REG_ICASE : 0));
1525 if (ret) {
1526 char errbuf[80];
1527 size_t size;
1529 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1530 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1532 else {
1533 search (&re, pageno, y, forward);
1534 regfree (&re);
1537 else if (!strncmp ("geometry", p, 8)) {
1538 int w, h, fitmodel;
1540 printd ("clear");
1541 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1542 if (ret != 3) {
1543 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1546 lock ("geometry");
1547 state.h = h;
1548 if (w != state.w) {
1549 state.w = w;
1550 for (int i = 0; i < state.texcount; ++i) {
1551 state.texowners[i].slice = NULL;
1554 state.fitmodel = fitmodel;
1555 layout ();
1556 process_outline ();
1558 state.gen++;
1559 unlock ("geometry");
1560 printd ("continue %d", state.pagecount);
1562 else if (!strncmp ("reqlayout", p, 9)) {
1563 char *nameddest;
1564 int rotate, off, h;
1565 int fitmodel;
1566 pdf_document *pdf;
1568 printd ("clear");
1569 ret = sscanf (p + 9, " %d %d %d %n",
1570 &rotate, &fitmodel, &h, &off);
1571 if (ret != 3) {
1572 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1574 lock ("reqlayout");
1575 pdf = pdf_specifics (state.ctx, state.doc);
1576 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1577 state.gen += 1;
1579 state.rotate = rotate;
1580 state.fitmodel = fitmodel;
1581 state.h = h;
1582 layout ();
1583 process_outline ();
1585 nameddest = p + 9 + off;
1586 if (pdf && nameddest && *nameddest) {
1587 fz_point xy;
1588 struct pagedim *pdim;
1589 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1590 &xy.x, &xy.y);
1591 pdim = pdimofpageno (pageno);
1592 xy = fz_transform_point (xy, pdim->ctm);
1593 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1596 state.gen++;
1597 unlock ("reqlayout");
1598 printd ("continue %d", state.pagecount);
1600 else if (!strncmp ("page", p, 4)) {
1601 double a, b;
1602 struct page *page;
1603 int pageno, pindex;
1605 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1606 if (ret != 2) {
1607 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1610 lock ("page");
1611 a = now ();
1612 page = loadpage (pageno, pindex);
1613 b = now ();
1614 unlock ("page");
1616 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1618 else if (!strncmp ("tile", p, 4)) {
1619 int x, y, w, h;
1620 struct page *page;
1621 struct tile *tile;
1622 double a, b;
1623 void *data;
1625 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1626 (uintptr_t *) &page, &x, &y, &w, &h,
1627 (uintptr_t *) &data);
1628 if (ret != 6) {
1629 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1632 lock ("tile");
1633 a = now ();
1634 tile = rendertile (page, x, y, w, h, data);
1635 b = now ();
1636 unlock ("tile");
1638 printd ("tile %d %d %" PRIxPTR " %u %f",
1639 x, y, (uintptr_t) (tile),
1640 tile->w * tile->h * tile->pixmap->n,
1641 b - a);
1643 else if (!strncmp ("trimset", p, 7)) {
1644 fz_irect fuzz;
1645 int trimmargins;
1647 ret = sscanf (p + 7, " %d %d %d %d %d",
1648 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1649 if (ret != 5) {
1650 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1652 lock ("trimset");
1653 state.trimmargins = trimmargins;
1654 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1655 state.trimanew = 1;
1656 state.trimfuzz = fuzz;
1658 unlock ("trimset");
1660 else if (!strncmp ("settrim", p, 7)) {
1661 fz_irect fuzz;
1662 int trimmargins;
1664 ret = sscanf (p + 7, " %d %d %d %d %d",
1665 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1666 if (ret != 5) {
1667 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1669 printd ("clear");
1670 lock ("settrim");
1671 state.trimmargins = trimmargins;
1672 state.needoutline = 1;
1673 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1674 state.trimanew = 1;
1675 state.trimfuzz = fuzz;
1677 state.pagedimcount = 0;
1678 free (state.pagedims);
1679 state.pagedims = NULL;
1680 initpdims ();
1681 layout ();
1682 process_outline ();
1683 unlock ("settrim");
1684 printd ("continue %d", state.pagecount);
1686 else if (!strncmp ("sliceh", p, 6)) {
1687 int h;
1689 ret = sscanf (p + 6, " %d", &h);
1690 if (ret != 1) {
1691 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1693 if (h != state.sliceheight) {
1694 state.sliceheight = h;
1695 for (int i = 0; i < state.texcount; ++i) {
1696 state.texowners[i].w = -1;
1697 state.texowners[i].h = -1;
1698 state.texowners[i].slice = NULL;
1702 else if (!strncmp ("interrupt", p, 9)) {
1703 printd ("vmsg interrupted");
1705 else {
1706 errx (1, "unknown command %.*s", len, p);
1709 return 0;
1712 value ml_isexternallink (value uri_v);
1713 value ml_isexternallink (value uri_v)
1715 CAMLparam1 (uri_v);
1716 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1717 CAMLreturn (Val_bool (ext));
1720 value ml_uritolocation (value uri_v);
1721 value ml_uritolocation (value uri_v)
1723 CAMLparam1 (uri_v);
1724 CAMLlocal1 (ret_v);
1725 int pageno;
1726 fz_point xy;
1727 struct pagedim *pdim;
1729 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1730 &xy.x, &xy.y);
1731 pdim = pdimofpageno (pageno);
1732 xy = fz_transform_point (xy, pdim->ctm);
1733 ret_v = caml_alloc_tuple (3);
1734 Field (ret_v, 0) = Val_int (pageno);
1735 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1736 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1737 CAMLreturn (ret_v);
1740 value ml_realloctexts (value texcount_v);
1741 value ml_realloctexts (value texcount_v)
1743 CAMLparam1 (texcount_v);
1744 int ok;
1746 if (trylock (__func__)) {
1747 ok = 0;
1748 goto done;
1750 realloctexts (Int_val (texcount_v));
1751 ok = 1;
1752 unlock (__func__);
1754 done:
1755 CAMLreturn (Val_bool (ok));
1758 static void recti (int x0, int y0, int x1, int y1)
1760 GLfloat *v = state.vertices;
1762 glVertexPointer (2, GL_FLOAT, 0, v);
1763 v[0] = x0; v[1] = y0;
1764 v[2] = x1; v[3] = y0;
1765 v[4] = x0; v[5] = y1;
1766 v[6] = x1; v[7] = y1;
1767 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1770 static void showsel (struct page *page, int ox, int oy)
1772 fz_irect bbox;
1773 fz_rect rect;
1774 fz_stext_block *block;
1775 int seen = 0;
1776 unsigned char selcolor[] = {15,15,15,140};
1778 if (!page->fmark || !page->lmark) return;
1780 glEnable (GL_BLEND);
1781 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1782 glColor4ubv (selcolor);
1784 ox += state.pagedims[page->pdimno].bounds.x0;
1785 oy += state.pagedims[page->pdimno].bounds.y0;
1787 for (block = page->text->first_block; block; block = block->next) {
1788 fz_stext_line *line;
1790 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1791 for (line = block->u.t.first_line; line; line = line->next) {
1792 fz_stext_char *ch;
1794 rect = fz_empty_rect;
1795 for (ch = line->first_char; ch; ch = ch->next) {
1796 fz_rect r;
1797 if (ch == page->fmark) seen = 1;
1798 r = fz_rect_from_quad (ch->quad);
1799 if (seen) rect = fz_union_rect (rect, r);
1800 if (ch == page->lmark) {
1801 bbox = fz_round_rect (rect);
1802 recti (bbox.x0 + ox, bbox.y0 + oy,
1803 bbox.x1 + ox, bbox.y1 + oy);
1804 goto done;
1807 bbox = fz_round_rect (rect);
1808 recti (bbox.x0 + ox, bbox.y0 + oy,
1809 bbox.x1 + ox, bbox.y1 + oy);
1812 done:
1813 glDisable (GL_BLEND);
1816 #pragma GCC diagnostic push
1817 #pragma GCC diagnostic ignored "-Wconversion"
1818 #include "glfont.c"
1819 #pragma GCC diagnostic pop
1821 static void stipplerect (fz_matrix m,
1822 fz_point p1,
1823 fz_point p2,
1824 fz_point p3,
1825 fz_point p4,
1826 GLfloat *texcoords,
1827 GLfloat *vertices)
1829 p1 = fz_transform_point (p1, m);
1830 p2 = fz_transform_point (p2, m);
1831 p3 = fz_transform_point (p3, m);
1832 p4 = fz_transform_point (p4, m);
1834 float w, h, s, t;
1836 w = p2.x - p1.x;
1837 h = p2.y - p1.y;
1838 t = hypotf (w, h) * .25f;
1840 w = p3.x - p2.x;
1841 h = p3.y - p2.y;
1842 s = hypotf (w, h) * .25f;
1844 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1845 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1847 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1848 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1850 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1851 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1853 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1854 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1856 glDrawArrays (GL_LINES, 0, 8);
1859 static void solidrect (fz_matrix m,
1860 fz_point p1,
1861 fz_point p2,
1862 fz_point p3,
1863 fz_point p4,
1864 GLfloat *vertices)
1866 p1 = fz_transform_point (p1, m);
1867 p2 = fz_transform_point (p2, m);
1868 p3 = fz_transform_point (p3, m);
1869 p4 = fz_transform_point (p4, m);
1870 vertices[0] = p1.x; vertices[1] = p1.y;
1871 vertices[2] = p2.x; vertices[3] = p2.y;
1873 vertices[4] = p3.x; vertices[5] = p3.y;
1874 vertices[6] = p4.x; vertices[7] = p4.y;
1875 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1878 static void ensurelinks (struct page *page)
1880 if (!page->links)
1881 page->links = fz_load_links (state.ctx, page->fzpage);
1884 static void highlightlinks (struct page *page, int xoff, int yoff)
1886 fz_matrix ctm;
1887 fz_link *link;
1888 GLfloat *texcoords = state.texcoords;
1889 GLfloat *vertices = state.vertices;
1891 ensurelinks (page);
1893 glEnable (GL_TEXTURE_1D);
1894 glEnable (GL_BLEND);
1895 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1896 glBindTexture (GL_TEXTURE_1D, state.stid);
1898 xoff -= state.pagedims[page->pdimno].bounds.x0;
1899 yoff -= state.pagedims[page->pdimno].bounds.y0;
1900 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1902 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1903 glVertexPointer (2, GL_FLOAT, 0, vertices);
1905 for (link = page->links; link; link = link->next) {
1906 fz_point p1, p2, p3, p4;
1908 p1.x = link->rect.x0;
1909 p1.y = link->rect.y0;
1911 p2.x = link->rect.x1;
1912 p2.y = link->rect.y0;
1914 p3.x = link->rect.x1;
1915 p3.y = link->rect.y1;
1917 p4.x = link->rect.x0;
1918 p4.y = link->rect.y1;
1920 /* TODO: different colours for different schemes */
1921 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1922 else glColor3ub (255, 0, 0);
1924 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1927 for (int i = 0; i < page->annotcount; ++i) {
1928 fz_point p1, p2, p3, p4;
1929 struct annot *annot = &page->annots[i];
1931 p1.x = annot->bbox.x0;
1932 p1.y = annot->bbox.y0;
1934 p2.x = annot->bbox.x1;
1935 p2.y = annot->bbox.y0;
1937 p3.x = annot->bbox.x1;
1938 p3.y = annot->bbox.y1;
1940 p4.x = annot->bbox.x0;
1941 p4.y = annot->bbox.y1;
1943 glColor3ub (0, 0, 128);
1944 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1947 glDisable (GL_BLEND);
1948 glDisable (GL_TEXTURE_1D);
1951 static int compareslinks (const void *l, const void *r)
1953 struct slink const *ls = l;
1954 struct slink const *rs = r;
1955 if (ls->bbox.y0 == rs->bbox.y0) {
1956 return rs->bbox.x0 - rs->bbox.x0;
1958 return ls->bbox.y0 - rs->bbox.y0;
1961 static void droptext (struct page *page)
1963 if (page->text) {
1964 fz_drop_stext_page (state.ctx, page->text);
1965 page->fmark = NULL;
1966 page->lmark = NULL;
1967 page->text = NULL;
1971 static void dropannots (struct page *page)
1973 if (page->annots) {
1974 free (page->annots);
1975 page->annots = NULL;
1976 page->annotcount = 0;
1980 static void ensureannots (struct page *page)
1982 int i, count = 0;
1983 size_t annotsize = sizeof (*page->annots);
1984 fz_annot *annot;
1986 if (state.gen != page->agen) {
1987 dropannots (page);
1988 page->agen = state.gen;
1990 if (page->annots) return;
1992 for (annot = fz_first_annot (state.ctx, page->fzpage);
1993 annot;
1994 annot = fz_next_annot (state.ctx, annot)) {
1995 count++;
1998 if (count > 0) {
1999 page->annotcount = count;
2000 page->annots = calloc (count, annotsize);
2001 if (!page->annots) {
2002 err (1, "calloc annots %d", count);
2005 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2006 annot;
2007 annot = fz_next_annot (state.ctx, annot), i++) {
2008 fz_rect rect;
2010 rect = fz_bound_annot (state.ctx, annot);
2011 page->annots[i].annot = annot;
2012 page->annots[i].bbox = fz_round_rect (rect);
2017 static void dropslinks (struct page *page)
2019 if (page->slinks) {
2020 free (page->slinks);
2021 page->slinks = NULL;
2022 page->slinkcount = 0;
2024 if (page->links) {
2025 fz_drop_link (state.ctx, page->links);
2026 page->links = NULL;
2030 static void ensureslinks (struct page *page)
2032 fz_matrix ctm;
2033 int i, count;
2034 size_t slinksize = sizeof (*page->slinks);
2035 fz_link *link;
2037 ensureannots (page);
2038 if (state.gen != page->sgen) {
2039 dropslinks (page);
2040 page->sgen = state.gen;
2042 if (page->slinks) return;
2044 ensurelinks (page);
2045 ctm = pagectm (page);
2047 count = page->annotcount;
2048 for (link = page->links; link; link = link->next) {
2049 count++;
2051 if (count > 0) {
2052 int j;
2054 page->slinkcount = count;
2055 page->slinks = calloc (count, slinksize);
2056 if (!page->slinks) {
2057 err (1, "calloc slinks %d", count);
2060 for (i = 0, link = page->links; link; ++i, link = link->next) {
2061 fz_rect rect;
2063 rect = link->rect;
2064 rect = fz_transform_rect (rect, ctm);
2065 page->slinks[i].tag = SLINK;
2066 page->slinks[i].u.link = link;
2067 page->slinks[i].bbox = fz_round_rect (rect);
2069 for (j = 0; j < page->annotcount; ++j, ++i) {
2070 fz_rect rect;
2071 rect = fz_bound_annot (state.ctx, page->annots[j].annot);
2072 rect = fz_transform_rect (rect, ctm);
2073 page->slinks[i].bbox = fz_round_rect (rect);
2075 page->slinks[i].tag = SANNOT;
2076 page->slinks[i].u.annot = page->annots[j].annot;
2078 qsort (page->slinks, count, slinksize, compareslinks);
2082 static void highlightslinks (struct page *page, int xoff, int yoff,
2083 int noff, char *targ, mlsize_t tlen, int hfsize)
2085 char buf[40];
2086 struct slink *slink;
2087 float x0, y0, x1, y1, w;
2089 ensureslinks (page);
2090 glColor3ub (0xc3, 0xb0, 0x91);
2091 for (int i = 0; i < page->slinkcount; ++i) {
2092 fmt_linkn (buf, i + noff);
2093 if (!tlen || !strncmp (targ, buf, tlen)) {
2094 slink = &page->slinks[i];
2096 x0 = slink->bbox.x0 + xoff - 5;
2097 y1 = slink->bbox.y0 + yoff - 5;
2098 y0 = y1 + 10 + hfsize;
2099 w = measure_string (state.face, hfsize, buf);
2100 x1 = x0 + w + 10;
2101 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2105 glEnable (GL_BLEND);
2106 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2107 glEnable (GL_TEXTURE_2D);
2108 glColor3ub (0, 0, 0);
2109 for (int i = 0; i < page->slinkcount; ++i) {
2110 fmt_linkn (buf, i + noff);
2111 if (!tlen || !strncmp (targ, buf, tlen)) {
2112 slink = &page->slinks[i];
2114 x0 = slink->bbox.x0 + xoff;
2115 y0 = slink->bbox.y0 + yoff + hfsize;
2116 draw_string (state.face, hfsize, x0, y0, buf);
2119 glDisable (GL_TEXTURE_2D);
2120 glDisable (GL_BLEND);
2123 static void uploadslice (struct tile *tile, struct slice *slice)
2125 int offset;
2126 struct slice *slice1;
2127 unsigned char *texdata;
2129 offset = 0;
2130 for (slice1 = tile->slices; slice != slice1; slice1++) {
2131 offset += slice1->h * tile->w * tile->pixmap->n;
2133 if (slice->texindex != -1 && slice->texindex < state.texcount
2134 && state.texowners[slice->texindex].slice == slice) {
2135 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2137 else {
2138 int subimage = 0;
2139 int texindex = state.texindex++ % state.texcount;
2141 if (state.texowners[texindex].w == tile->w) {
2142 if (state.texowners[texindex].h >= slice->h) {
2143 subimage = 1;
2145 else {
2146 state.texowners[texindex].h = slice->h;
2149 else {
2150 state.texowners[texindex].h = slice->h;
2153 state.texowners[texindex].w = tile->w;
2154 state.texowners[texindex].slice = slice;
2155 slice->texindex = texindex;
2157 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2158 #if TEXT_TYPE == GL_TEXTURE_2D
2159 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2160 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2161 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2162 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2163 #endif
2164 if (tile->pbo) {
2165 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2166 texdata = 0;
2168 else {
2169 texdata = tile->pixmap->samples;
2171 if (subimage) {
2172 glTexSubImage2D (TEXT_TYPE,
2176 tile->w,
2177 slice->h,
2178 state.texform,
2179 state.texty,
2180 texdata+offset
2183 else {
2184 glTexImage2D (TEXT_TYPE,
2186 state.texiform,
2187 tile->w,
2188 slice->h,
2190 state.texform,
2191 state.texty,
2192 texdata+offset
2195 if (tile->pbo) {
2196 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2201 void ml_begintiles (void);
2202 void ml_begintiles (void)
2204 glEnable (TEXT_TYPE);
2205 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2206 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2209 void ml_endtiles (void);
2210 void ml_endtiles (void)
2212 glDisable (TEXT_TYPE);
2215 void ml_drawtile (value args_v, value ptr_v);
2216 void ml_drawtile (value args_v, value ptr_v)
2218 CAMLparam2 (args_v, ptr_v);
2219 int dispx = Int_val (Field (args_v, 0));
2220 int dispy = Int_val (Field (args_v, 1));
2221 int dispw = Int_val (Field (args_v, 2));
2222 int disph = Int_val (Field (args_v, 3));
2223 int tilex = Int_val (Field (args_v, 4));
2224 int tiley = Int_val (Field (args_v, 5));
2225 char *s = String_val (ptr_v);
2226 struct tile *tile = parse_pointer (__func__, s);
2227 int slicey, firstslice;
2228 struct slice *slice;
2229 GLfloat *texcoords = state.texcoords;
2230 GLfloat *vertices = state.vertices;
2232 firstslice = tiley / tile->sliceheight;
2233 slice = &tile->slices[firstslice];
2234 slicey = tiley % tile->sliceheight;
2236 while (disph > 0) {
2237 int dh;
2239 dh = slice->h - slicey;
2240 dh = fz_mini (disph, dh);
2241 uploadslice (tile, slice);
2243 texcoords[0] = tilex; texcoords[1] = slicey;
2244 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2245 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2246 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2248 vertices[0] = dispx; vertices[1] = dispy;
2249 vertices[2] = dispx+dispw; vertices[3] = dispy;
2250 vertices[4] = dispx; vertices[5] = dispy+dh;
2251 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2253 #if TEXT_TYPE == GL_TEXTURE_2D
2254 for (int i = 0; i < 8; ++i) {
2255 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2257 #endif
2259 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2260 dispy += dh;
2261 disph -= dh;
2262 slice++;
2263 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2264 slicey = 0;
2266 CAMLreturn0;
2269 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2271 fz_matrix ctm;
2272 fz_point p1, p2, p3, p4;
2273 GLfloat *vertices = state.vertices;
2274 double *v = (double *) rects_v;
2276 xoff -= state.pagedims[page->pdimno].bounds.x0;
2277 yoff -= state.pagedims[page->pdimno].bounds.y0;
2278 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2280 glEnable (GL_BLEND);
2281 glVertexPointer (2, GL_FLOAT, 0, vertices);
2283 glColor4dv (v);
2284 p1.x = (float) v[4];
2285 p1.y = (float) v[5];
2287 p2.x = (float) v[6];
2288 p2.y = (float) v[5];
2290 p3.x = (float) v[6];
2291 p3.y = (float) v[7];
2293 p4.x = (float) v[4];
2294 p4.y = (float) v[7];
2295 solidrect (ctm, p1, p2, p3, p4, vertices);
2296 glDisable (GL_BLEND);
2299 value ml_postprocess (value ptr_v, value hlinks_v,
2300 value xoff_v, value yoff_v,
2301 value li_v);
2302 value ml_postprocess (value ptr_v, value hlinks_v,
2303 value xoff_v, value yoff_v,
2304 value li_v)
2306 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2307 int xoff = Int_val (xoff_v);
2308 int yoff = Int_val (yoff_v);
2309 int noff = Int_val (Field (li_v, 0));
2310 char *targ = String_val (Field (li_v, 1));
2311 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2312 int hfsize = Int_val (Field (li_v, 2));
2313 char *s = String_val (ptr_v);
2314 int hlmask = Int_val (hlinks_v);
2315 struct page *page = parse_pointer (__func__, s);
2317 if (!page->fzpage) {
2318 /* deal with loadpage failed pages */
2319 goto done;
2322 if (trylock (__func__)) {
2323 noff = -1;
2324 goto done;
2327 ensureannots (page);
2328 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2329 if (hlmask & 2) {
2330 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2331 noff = page->slinkcount;
2333 if (page->tgen == state.gen) {
2334 showsel (page, xoff, yoff);
2336 unlock (__func__);
2338 done:
2339 CAMLreturn (Val_int (noff));
2342 void ml_drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v);
2343 void ml_drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v)
2345 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2346 int xoff = Int_val (xoff_v);
2347 int yoff = Int_val (yoff_v);
2348 char *s = String_val (ptr_v);
2349 struct page *page = parse_pointer (__func__, s);
2351 drawprect (page, xoff, yoff, rects_v);
2352 CAMLreturn0;
2355 static struct annot *getannot (struct page *page, int x, int y)
2357 fz_point p;
2358 fz_matrix ctm;
2359 const fz_matrix *tctm;
2360 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2362 if (!page->annots) return NULL;
2364 if (pdf) {
2365 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2366 tctm = &state.pagedims[page->pdimno].tctm;
2368 else {
2369 tctm = &fz_identity;
2372 p.x = x;
2373 p.y = y;
2375 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2376 ctm = fz_invert_matrix (ctm);
2377 p = fz_transform_point (p, ctm);
2379 if (pdf) {
2380 for (int i = 0; i < page->annotcount; ++i) {
2381 struct annot *a = &page->annots[i];
2382 fz_rect rect;
2384 rect = fz_bound_annot (state.ctx, a->annot);
2385 if (p.x >= rect.x0 && p.x <= rect.x1) {
2386 if (p.y >= rect.y0 && p.y <= rect.y1)
2387 return a;
2391 return NULL;
2394 static fz_link *getlink (struct page *page, int x, int y)
2396 fz_point p;
2397 fz_link *link;
2399 ensureslinks (page);
2401 p.x = x;
2402 p.y = y;
2404 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2406 for (link = page->links; link; link = link->next) {
2407 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2408 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2409 return link;
2413 return NULL;
2416 static void ensuretext (struct page *page)
2418 if (state.gen != page->tgen) {
2419 droptext (page);
2420 page->tgen = state.gen;
2422 if (!page->text) {
2423 fz_device *tdev;
2425 page->text = fz_new_stext_page (state.ctx,
2426 state.pagedims[page->pdimno].mediabox);
2427 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2428 fz_run_display_list (state.ctx, page->dlist,
2429 tdev, pagectm (page), fz_infinite_rect, NULL);
2430 fz_close_device (state.ctx, tdev);
2431 fz_drop_device (state.ctx, tdev);
2435 value ml_find_page_with_links (value start_page_v, value dir_v);
2436 value ml_find_page_with_links (value start_page_v, value dir_v)
2438 CAMLparam2 (start_page_v, dir_v);
2439 CAMLlocal1 (ret_v);
2440 int i, dir = Int_val (dir_v);
2441 int start_page = Int_val (start_page_v);
2442 int end_page = dir > 0 ? state.pagecount : -1;
2443 pdf_document *pdf;
2445 fz_var (end_page);
2446 ret_v = Val_int (0);
2447 lock (__func__);
2448 pdf = pdf_specifics (state.ctx, state.doc);
2449 for (i = start_page + dir; i != end_page; i += dir) {
2450 int found;
2452 fz_var (found);
2453 if (pdf) {
2454 pdf_page *page = NULL;
2456 fz_var (page);
2457 fz_try (state.ctx) {
2458 page = pdf_load_page (state.ctx, pdf, i);
2459 found = !!page->links || !!page->annots;
2461 fz_catch (state.ctx) {
2462 found = 0;
2464 if (page) {
2465 fz_drop_page (state.ctx, &page->super);
2468 else {
2469 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2470 fz_link *link = fz_load_links (state.ctx, page);
2471 found = !!link;
2472 fz_drop_link (state.ctx, link);
2473 fz_drop_page (state.ctx, page);
2476 if (found) {
2477 ret_v = caml_alloc_small (1, 1);
2478 Field (ret_v, 0) = Val_int (i);
2479 goto unlock;
2482 unlock:
2483 unlock (__func__);
2484 CAMLreturn (ret_v);
2487 enum { dir_first, dir_last };
2488 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2490 value ml_findlink (value ptr_v, value dir_v);
2491 value ml_findlink (value ptr_v, value dir_v)
2493 CAMLparam2 (ptr_v, dir_v);
2494 CAMLlocal2 (ret_v, pos_v);
2495 struct page *page;
2496 int dirtag, i, slinkindex;
2497 struct slink *found = NULL ,*slink;
2498 char *s = String_val (ptr_v);
2500 page = parse_pointer (__func__, s);
2501 ret_v = Val_int (0);
2502 lock (__func__);
2503 ensureslinks (page);
2505 if (Is_block (dir_v)) {
2506 dirtag = Tag_val (dir_v);
2507 switch (dirtag) {
2508 case dir_first_visible:
2510 int x0, y0, dir, first_index, last_index;
2512 pos_v = Field (dir_v, 0);
2513 x0 = Int_val (Field (pos_v, 0));
2514 y0 = Int_val (Field (pos_v, 1));
2515 dir = Int_val (Field (pos_v, 2));
2517 if (dir >= 0) {
2518 dir = 1;
2519 first_index = 0;
2520 last_index = page->slinkcount;
2522 else {
2523 first_index = page->slinkcount - 1;
2524 last_index = -1;
2527 for (i = first_index; i != last_index; i += dir) {
2528 slink = &page->slinks[i];
2529 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2530 found = slink;
2531 break;
2535 break;
2537 case dir_left:
2538 slinkindex = Int_val (Field (dir_v, 0));
2539 found = &page->slinks[slinkindex];
2540 for (i = slinkindex - 1; i >= 0; --i) {
2541 slink = &page->slinks[i];
2542 if (slink->bbox.x0 < found->bbox.x0) {
2543 found = slink;
2544 break;
2547 break;
2549 case dir_right:
2550 slinkindex = Int_val (Field (dir_v, 0));
2551 found = &page->slinks[slinkindex];
2552 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2553 slink = &page->slinks[i];
2554 if (slink->bbox.x0 > found->bbox.x0) {
2555 found = slink;
2556 break;
2559 break;
2561 case dir_down:
2562 slinkindex = Int_val (Field (dir_v, 0));
2563 found = &page->slinks[slinkindex];
2564 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2565 slink = &page->slinks[i];
2566 if (slink->bbox.y0 >= found->bbox.y0) {
2567 found = slink;
2568 break;
2571 break;
2573 case dir_up:
2574 slinkindex = Int_val (Field (dir_v, 0));
2575 found = &page->slinks[slinkindex];
2576 for (i = slinkindex - 1; i >= 0; --i) {
2577 slink = &page->slinks[i];
2578 if (slink->bbox.y0 <= found->bbox.y0) {
2579 found = slink;
2580 break;
2583 break;
2586 else {
2587 dirtag = Int_val (dir_v);
2588 switch (dirtag) {
2589 case dir_first:
2590 found = page->slinks;
2591 break;
2593 case dir_last:
2594 if (page->slinks) {
2595 found = page->slinks + (page->slinkcount - 1);
2597 break;
2600 if (found) {
2601 ret_v = caml_alloc_small (2, 1);
2602 Field (ret_v, 0) = Val_int (found - page->slinks);
2605 unlock (__func__);
2606 CAMLreturn (ret_v);
2609 enum { uuri, utext, uannot };
2611 value ml_getlink (value ptr_v, value n_v);
2612 value ml_getlink (value ptr_v, value n_v)
2614 CAMLparam2 (ptr_v, n_v);
2615 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2616 fz_link *link;
2617 struct page *page;
2618 char *s = String_val (ptr_v);
2619 struct slink *slink;
2621 ret_v = Val_int (0);
2622 page = parse_pointer (__func__, s);
2624 lock (__func__);
2625 ensureslinks (page);
2626 slink = &page->slinks[Int_val (n_v)];
2627 if (slink->tag == SLINK) {
2628 link = slink->u.link;
2629 str_v = caml_copy_string (link->uri);
2630 ret_v = caml_alloc_small (1, uuri);
2631 Field (ret_v, 0) = str_v;
2633 else {
2634 ret_v = caml_alloc_small (1, uannot);
2635 tup_v = caml_alloc_tuple (2);
2636 Field (ret_v, 0) = tup_v;
2637 Field (tup_v, 0) = ptr_v;
2638 Field (tup_v, 1) = n_v;
2640 unlock (__func__);
2642 CAMLreturn (ret_v);
2645 value ml_getannotcontents (value ptr_v, value n_v);
2646 value ml_getannotcontents (value ptr_v, value n_v)
2648 CAMLparam2 (ptr_v, n_v);
2649 CAMLlocal1 (ret_v);
2650 pdf_document *pdf;
2651 const char *contents = "";
2653 lock (__func__);
2654 pdf = pdf_specifics (state.ctx, state.doc);
2655 if (pdf) {
2656 char *s = String_val (ptr_v);
2657 struct page *page;
2658 struct slink *slink;
2660 page = parse_pointer (__func__, s);
2661 slink = &page->slinks[Int_val (n_v)];
2662 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2664 unlock (__func__);
2665 ret_v = caml_copy_string (contents);
2666 CAMLreturn (ret_v);
2669 value ml_getlinkcount (value ptr_v);
2670 value ml_getlinkcount (value ptr_v)
2672 CAMLparam1 (ptr_v);
2673 struct page *page;
2674 char *s = String_val (ptr_v);
2676 page = parse_pointer (__func__, s);
2677 CAMLreturn (Val_int (page->slinkcount));
2680 value ml_getlinkrect (value ptr_v, value n_v);
2681 value ml_getlinkrect (value ptr_v, value n_v)
2683 CAMLparam2 (ptr_v, n_v);
2684 CAMLlocal1 (ret_v);
2685 struct page *page;
2686 struct slink *slink;
2687 char *s = String_val (ptr_v);
2689 page = parse_pointer (__func__, s);
2690 ret_v = caml_alloc_tuple (4);
2691 lock (__func__);
2692 ensureslinks (page);
2694 slink = &page->slinks[Int_val (n_v)];
2695 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2696 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2697 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2698 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2699 unlock (__func__);
2700 CAMLreturn (ret_v);
2703 value ml_whatsunder (value ptr_v, value x_v, value y_v);
2704 value ml_whatsunder (value ptr_v, value x_v, value y_v)
2706 CAMLparam3 (ptr_v, x_v, y_v);
2707 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2708 fz_link *link;
2709 struct annot *annot;
2710 struct page *page;
2711 char *ptr = String_val (ptr_v);
2712 int x = Int_val (x_v), y = Int_val (y_v);
2713 struct pagedim *pdim;
2715 ret_v = Val_int (0);
2716 if (trylock (__func__)) {
2717 goto done;
2720 page = parse_pointer (__func__, ptr);
2721 pdim = &state.pagedims[page->pdimno];
2722 x += pdim->bounds.x0;
2723 y += pdim->bounds.y0;
2726 annot = getannot (page, x, y);
2727 if (annot) {
2728 int i, n = -1;
2730 ensureslinks (page);
2731 for (i = 0; i < page->slinkcount; ++i) {
2732 if (page->slinks[i].tag == SANNOT
2733 && page->slinks[i].u.annot == annot->annot) {
2734 n = i;
2735 break;
2738 ret_v = caml_alloc_small (1, uannot);
2739 tup_v = caml_alloc_tuple (2);
2740 Field (ret_v, 0) = tup_v;
2741 Field (tup_v, 0) = ptr_v;
2742 Field (tup_v, 1) = Val_int (n);
2743 goto unlock;
2747 link = getlink (page, x, y);
2748 if (link) {
2749 str_v = caml_copy_string (link->uri);
2750 ret_v = caml_alloc_small (1, uuri);
2751 Field (ret_v, 0) = str_v;
2753 else {
2754 fz_rect *b;
2755 fz_stext_block *block;
2757 ensuretext (page);
2759 for (block = page->text->first_block; block; block = block->next) {
2760 fz_stext_line *line;
2762 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2763 b = &block->bbox;
2764 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2765 continue;
2767 for (line = block->u.t.first_line; line; line = line->next) {
2768 fz_stext_char *ch;
2770 b = &line->bbox;
2771 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2772 continue;
2774 for (ch = line->first_char; ch; ch = ch->next) {
2775 fz_quad *q = &ch->quad;
2777 if (x >= q->ul.x && x <= q->ur.x
2778 && y >= q->ul.y && y <= q->ll.y) {
2779 const char *n2 = fz_font_name (state.ctx, ch->font);
2780 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2781 ch->font);
2783 if (!n2) n2 = "<unknown font>";
2785 if (face && face->family_name) {
2786 char *s;
2787 char *n1 = face->family_name;
2788 size_t l1 = strlen (n1);
2789 size_t l2 = strlen (n2);
2791 if (l1 != l2 || memcmp (n1, n2, l1)) {
2792 s = malloc (l1 + l2 + 2);
2793 if (s) {
2794 memcpy (s, n2, l2);
2795 s[l2] = '=';
2796 memcpy (s + l2 + 1, n1, l1 + 1);
2797 str_v = caml_copy_string (s);
2798 free (s);
2802 if (str_v == Val_unit) {
2803 str_v = caml_copy_string (n2);
2805 ret_v = caml_alloc_small (1, utext);
2806 Field (ret_v, 0) = str_v;
2807 goto unlock;
2813 unlock:
2814 unlock (__func__);
2816 done:
2817 CAMLreturn (ret_v);
2820 enum { mark_page, mark_block, mark_line, mark_word };
2822 void ml_clearmark (value ptr_v);
2823 void ml_clearmark (value ptr_v)
2825 CAMLparam1 (ptr_v);
2826 char *s = String_val (ptr_v);
2827 struct page *page;
2829 if (trylock (__func__)) {
2830 goto done;
2833 page = parse_pointer (__func__, s);
2834 page->fmark = NULL;
2835 page->lmark = NULL;
2837 unlock (__func__);
2838 done:
2839 CAMLreturn0;
2842 static int uninteresting (int c)
2844 return isspace (c) || ispunct (c);
2847 value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v);
2848 value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2850 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2851 CAMLlocal1 (ret_v);
2852 fz_rect *b;
2853 struct page *page;
2854 fz_stext_line *line;
2855 fz_stext_block *block;
2856 struct pagedim *pdim;
2857 int mark = Int_val (mark_v);
2858 char *s = String_val (ptr_v);
2859 int x = Int_val (x_v), y = Int_val (y_v);
2861 ret_v = Val_bool (0);
2862 if (trylock (__func__)) {
2863 goto done;
2866 page = parse_pointer (__func__, s);
2867 pdim = &state.pagedims[page->pdimno];
2869 ensuretext (page);
2871 if (mark == mark_page) {
2872 page->fmark = page->text->first_block->u.t.first_line->first_char;
2873 page->lmark = page->text->last_block->u.t.last_line->last_char;
2874 ret_v = Val_bool (1);
2875 goto unlock;
2878 x += pdim->bounds.x0;
2879 y += pdim->bounds.y0;
2881 for (block = page->text->first_block; block; block = block->next) {
2882 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2883 b = &block->bbox;
2884 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2885 continue;
2887 if (mark == mark_block) {
2888 page->fmark = block->u.t.first_line->first_char;
2889 page->lmark = block->u.t.last_line->last_char;
2890 ret_v = Val_bool (1);
2891 goto unlock;
2894 for (line = block->u.t.first_line; line; line = line->next) {
2895 fz_stext_char *ch;
2897 b = &line->bbox;
2898 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2899 continue;
2901 if (mark == mark_line) {
2902 page->fmark = line->first_char;
2903 page->lmark = line->last_char;
2904 ret_v = Val_bool (1);
2905 goto unlock;
2908 for (ch = line->first_char; ch; ch = ch->next) {
2909 fz_stext_char *ch2, *first = NULL, *last = NULL;
2910 fz_quad *q = &ch->quad;
2911 if (x >= q->ul.x && x <= q->ur.x
2912 && y >= q->ul.y && y <= q->ll.y) {
2913 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2914 if (uninteresting (ch2->c)) first = NULL;
2915 else if (!first) first = ch2;
2917 for (ch2 = ch; ch2; ch2 = ch2->next) {
2918 if (uninteresting (ch2->c)) break;
2919 last = ch2;
2922 page->fmark = first;
2923 page->lmark = last;
2924 ret_v = Val_bool (1);
2925 goto unlock;
2930 unlock:
2931 if (!Bool_val (ret_v)) {
2932 page->fmark = NULL;
2933 page->lmark = NULL;
2935 unlock (__func__);
2937 done:
2938 CAMLreturn (ret_v);
2941 value ml_rectofblock (value ptr_v, value x_v, value y_v);
2942 value ml_rectofblock (value ptr_v, value x_v, value y_v)
2944 CAMLparam3 (ptr_v, x_v, y_v);
2945 CAMLlocal2 (ret_v, res_v);
2946 fz_rect *b = NULL;
2947 struct page *page;
2948 struct pagedim *pdim;
2949 fz_stext_block *block;
2950 char *s = String_val (ptr_v);
2951 int x = Int_val (x_v), y = Int_val (y_v);
2953 ret_v = Val_int (0);
2954 if (trylock (__func__)) {
2955 goto done;
2958 page = parse_pointer (__func__, s);
2959 pdim = &state.pagedims[page->pdimno];
2960 x += pdim->bounds.x0;
2961 y += pdim->bounds.y0;
2963 ensuretext (page);
2965 for (block = page->text->first_block; block; block = block->next) {
2966 switch (block->type) {
2967 case FZ_STEXT_BLOCK_TEXT:
2968 b = &block->bbox;
2969 break;
2971 case FZ_STEXT_BLOCK_IMAGE:
2972 b = &block->bbox;
2973 break;
2975 default:
2976 continue;
2979 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2980 break;
2981 b = NULL;
2983 if (b) {
2984 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2985 ret_v = caml_alloc_small (1, 1);
2986 Store_double_field (res_v, 0, (double) b->x0);
2987 Store_double_field (res_v, 1, (double) b->x1);
2988 Store_double_field (res_v, 2, (double) b->y0);
2989 Store_double_field (res_v, 3, (double) b->y1);
2990 Field (ret_v, 0) = res_v;
2992 unlock (__func__);
2994 done:
2995 CAMLreturn (ret_v);
2998 void ml_seltext (value ptr_v, value rect_v);
2999 void ml_seltext (value ptr_v, value rect_v)
3001 CAMLparam2 (ptr_v, rect_v);
3002 struct page *page;
3003 struct pagedim *pdim;
3004 char *s = String_val (ptr_v);
3005 int x0, x1, y0, y1;
3006 fz_stext_char *ch;
3007 fz_stext_line *line;
3008 fz_stext_block *block;
3009 fz_stext_char *fc, *lc;
3011 if (trylock (__func__)) {
3012 goto done;
3015 page = parse_pointer (__func__, s);
3016 ensuretext (page);
3018 pdim = &state.pagedims[page->pdimno];
3019 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3020 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3021 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3022 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3024 if (y0 > y1) {
3025 int t = y0;
3026 y0 = y1;
3027 y1 = t;
3028 x0 = x1;
3029 x1 = t;
3032 fc = page->fmark;
3033 lc = page->lmark;
3035 for (block = page->text->first_block; block; block = block->next) {
3036 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3037 for (line = block->u.t.first_line; line; line = line->next) {
3038 for (ch = line->first_char; ch; ch = ch->next) {
3039 fz_quad q = ch->quad;
3040 if (x0 >= q.ul.x && x0 <= q.ur.x
3041 && y0 >= q.ul.y && y0 <= q.ll.y) {
3042 fc = ch;
3044 if (x1 >= q.ul.x && x1 <= q.ur.x
3045 && y1 >= q.ul.y && y1 <= q.ll.y) {
3046 lc = ch;
3051 if (x1 < x0 && fc == lc) {
3052 fz_stext_char *t;
3054 t = fc;
3055 fc = lc;
3056 lc = t;
3059 page->fmark = fc;
3060 page->lmark = lc;
3062 unlock (__func__);
3064 done:
3065 CAMLreturn0;
3068 static int pipechar (FILE *f, fz_stext_char *ch)
3070 char buf[4];
3071 int len;
3072 size_t ret;
3074 len = fz_runetochar (buf, ch->c);
3075 ret = fwrite (buf, len, 1, f);
3076 if (ret != 1) {
3077 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3078 len, ret, errno, strerror (errno));
3079 return -1;
3081 return 0;
3084 value ml_spawn (value command_v, value fds_v);
3085 value ml_spawn (value command_v, value fds_v)
3087 CAMLparam2 (command_v, fds_v);
3088 CAMLlocal2 (l_v, tup_v);
3089 int ret, ret1;
3090 pid_t pid = (pid_t) -1;
3091 char *msg = NULL;
3092 value earg_v = Nothing;
3093 posix_spawnattr_t attr;
3094 posix_spawn_file_actions_t fa;
3095 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3097 argv[2] = String_val (command_v);
3099 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3100 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3103 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3104 msg = "posix_spawnattr_init";
3105 goto fail1;
3108 #ifdef POSIX_SPAWN_USEVFORK
3109 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3110 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3111 goto fail;
3113 #endif
3115 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3116 int fd1, fd2;
3118 tup_v = Field (l_v, 0);
3119 fd1 = Int_val (Field (tup_v, 0));
3120 fd2 = Int_val (Field (tup_v, 1));
3121 if (fd2 < 0) {
3122 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3123 msg = "posix_spawn_file_actions_addclose";
3124 earg_v = tup_v;
3125 goto fail;
3128 else {
3129 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3130 msg = "posix_spawn_file_actions_adddup2";
3131 earg_v = tup_v;
3132 goto fail;
3137 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3138 msg = "posix_spawn";
3139 goto fail;
3142 fail:
3143 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3144 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3147 fail1:
3148 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3149 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3150 ret1, strerror (ret1));
3153 if (msg)
3154 unix_error (ret, msg, earg_v);
3156 CAMLreturn (Val_int (pid));
3159 value ml_hassel (value ptr_v);
3160 value ml_hassel (value ptr_v)
3162 CAMLparam1 (ptr_v);
3163 CAMLlocal1 (ret_v);
3164 struct page *page;
3165 char *s = String_val (ptr_v);
3167 ret_v = Val_bool (0);
3168 if (trylock (__func__)) {
3169 goto done;
3172 page = parse_pointer (__func__, s);
3173 ret_v = Val_bool (page->fmark && page->lmark);
3174 unlock (__func__);
3175 done:
3176 CAMLreturn (ret_v);
3179 void ml_copysel (value fd_v, value ptr_v);
3180 void ml_copysel (value fd_v, value ptr_v)
3182 CAMLparam2 (fd_v, ptr_v);
3183 FILE *f;
3184 int seen = 0;
3185 struct page *page;
3186 fz_stext_line *line;
3187 fz_stext_block *block;
3188 int fd = Int_val (fd_v);
3189 char *s = String_val (ptr_v);
3191 if (trylock (__func__)) {
3192 goto done;
3195 page = parse_pointer (__func__, s);
3197 if (!page->fmark || !page->lmark) {
3198 printd ("emsg nothing to copy on page %d", page->pageno);
3199 goto unlock;
3202 f = fdopen (fd, "w");
3203 if (!f) {
3204 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3205 fd, errno, strerror (errno));
3206 f = stdout;
3209 for (block = page->text->first_block; block; block = block->next) {
3210 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3211 for (line = block->u.t.first_line; line; line = line->next) {
3212 fz_stext_char *ch;
3213 for (ch = line->first_char; ch; ch = ch->next) {
3214 if (seen || ch == page->fmark) {
3215 do {
3216 pipechar (f, ch);
3217 if (ch == page->lmark) goto close;
3218 } while ((ch = ch->next));
3219 seen = 1;
3220 break;
3223 if (seen) fputc ('\n', f);
3226 close:
3227 if (f != stdout) {
3228 int ret = fclose (f);
3229 fd = -1;
3230 if (ret == -1) {
3231 if (errno != ECHILD) {
3232 printd ("emsg failed to close sel pipe: %d:%s",
3233 errno, strerror (errno));
3237 unlock:
3238 unlock (__func__);
3240 done:
3241 if (fd >= 0) {
3242 if (close (fd)) {
3243 printd ("emsg failed to close sel pipe: %d:%s",
3244 errno, strerror (errno));
3247 CAMLreturn0;
3250 value ml_getpdimrect (value pagedimno_v);
3251 value ml_getpdimrect (value pagedimno_v)
3253 CAMLparam1 (pagedimno_v);
3254 CAMLlocal1 (ret_v);
3255 int pagedimno = Int_val (pagedimno_v);
3256 fz_rect box;
3258 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3259 if (trylock (__func__)) {
3260 box = fz_empty_rect;
3262 else {
3263 box = state.pagedims[pagedimno].mediabox;
3264 unlock (__func__);
3267 Store_double_field (ret_v, 0, (double) box.x0);
3268 Store_double_field (ret_v, 1, (double) box.x1);
3269 Store_double_field (ret_v, 2, (double) box.y0);
3270 Store_double_field (ret_v, 3, (double) box.y1);
3272 CAMLreturn (ret_v);
3275 value ml_zoom_for_height (value winw_v, value winh_v,
3276 value dw_v, value cols_v);
3277 value ml_zoom_for_height (value winw_v, value winh_v,
3278 value dw_v, value cols_v)
3280 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3281 CAMLlocal1 (ret_v);
3282 int i;
3283 float zoom = -1.;
3284 float maxh = 0.0;
3285 struct pagedim *p;
3286 float winw = Int_val (winw_v);
3287 float winh = Int_val (winh_v);
3288 float dw = Int_val (dw_v);
3289 float cols = Int_val (cols_v);
3290 float pw = 1.0, ph = 1.0;
3292 if (trylock (__func__)) {
3293 goto done;
3296 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3297 float w = p->pagebox.x1 / cols;
3298 float h = p->pagebox.y1;
3299 if (h > maxh) {
3300 maxh = h;
3301 ph = h;
3302 if (state.fitmodel != FitProportional) pw = w;
3304 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3307 zoom = (((winh / ph) * pw) + dw) / winw;
3308 unlock (__func__);
3309 done:
3310 ret_v = caml_copy_double ((double) zoom);
3311 CAMLreturn (ret_v);
3314 value ml_getmaxw (value unit_v);
3315 value ml_getmaxw (value unit_v)
3317 CAMLparam1 (unit_v);
3318 CAMLlocal1 (ret_v);
3319 int i;
3320 float maxw = -1.;
3321 struct pagedim *p;
3323 if (trylock (__func__)) {
3324 goto done;
3327 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3328 float w = p->pagebox.x1;
3329 maxw = fz_max (maxw, w);
3332 unlock (__func__);
3333 done:
3334 ret_v = caml_copy_double ((double) maxw);
3335 CAMLreturn (ret_v);
3338 value ml_draw_string (value pt_v, value x_v,
3339 value y_v, value string_v);
3340 value ml_draw_string (value pt_v, value x_v,
3341 value y_v, value string_v)
3343 CAMLparam4 (pt_v, x_v, y_v, string_v);
3344 CAMLlocal1 (ret_v);
3345 int pt = Int_val(pt_v);
3346 int x = Int_val (x_v);
3347 int y = Int_val (y_v);
3348 float w;
3350 w = draw_string (state.face, pt, x, y, String_val (string_v));
3351 ret_v = caml_copy_double (w);
3352 CAMLreturn (ret_v);
3355 value ml_measure_string (value pt_v, value string_v);
3356 value ml_measure_string (value pt_v, value string_v)
3358 CAMLparam2 (pt_v, string_v);
3359 CAMLlocal1 (ret_v);
3360 int pt = Int_val (pt_v);
3361 double w;
3363 w = (double) measure_string (state.face, pt, String_val (string_v));
3364 ret_v = caml_copy_double (w);
3365 CAMLreturn (ret_v);
3368 value ml_getpagebox (value opaque_v);
3369 value ml_getpagebox (value opaque_v)
3371 CAMLparam1 (opaque_v);
3372 CAMLlocal1 (ret_v);
3373 fz_rect rect;
3374 fz_irect bbox;
3375 fz_device *dev;
3376 char *s = String_val (opaque_v);
3377 struct page *page = parse_pointer (__func__, s);
3379 ret_v = caml_alloc_tuple (4);
3380 dev = fz_new_bbox_device (state.ctx, &rect);
3382 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3384 fz_close_device (state.ctx, dev);
3385 fz_drop_device (state.ctx, dev);
3386 bbox = fz_round_rect (rect);
3387 Field (ret_v, 0) = Val_int (bbox.x0);
3388 Field (ret_v, 1) = Val_int (bbox.y0);
3389 Field (ret_v, 2) = Val_int (bbox.x1);
3390 Field (ret_v, 3) = Val_int (bbox.y1);
3392 CAMLreturn (ret_v);
3395 void ml_setaalevel (value level_v);
3396 void ml_setaalevel (value level_v)
3398 CAMLparam1 (level_v);
3400 state.aalevel = Int_val (level_v);
3401 CAMLreturn0;
3404 value ml_keysymtoutf8 (value keysym_v);
3405 #ifndef CIDER
3406 value ml_keysymtoutf8 (value keysym_v)
3408 CAMLparam1 (keysym_v);
3409 CAMLlocal1 (str_v);
3410 KeySym keysym = Int_val (keysym_v);
3411 Rune rune;
3412 extern long keysym2ucs (KeySym);
3413 int len;
3414 char buf[5];
3416 rune = (Rune) keysym2ucs (keysym);
3417 len = fz_runetochar (buf, rune);
3418 buf[len] = 0;
3419 str_v = caml_copy_string (buf);
3420 CAMLreturn (str_v);
3422 #else
3423 value ml_keysymtoutf8 (value keysym_v)
3425 CAMLparam1 (keysym_v);
3426 CAMLlocal1 (str_v);
3427 long ucs = Long_val (keysym_v);
3428 int len;
3429 char buf[5];
3431 len = fz_runetochar (buf, (int) ucs);
3432 buf[len] = 0;
3433 str_v = caml_copy_string (buf);
3434 CAMLreturn (str_v);
3436 #endif
3438 enum { piunknown, pilinux, pimacos, pibsd };
3440 value ml_platform (value unit_v);
3441 value ml_platform (value unit_v)
3443 CAMLparam1 (unit_v);
3444 CAMLlocal2 (tup_v, arr_v);
3445 int platid = piunknown;
3446 struct utsname buf;
3448 #if defined __linux__
3449 platid = pilinux;
3450 #elif defined __DragonFly__ || defined __FreeBSD__
3451 || defined __OpenBSD__ || defined __NetBSD__
3452 platid = pibsd;
3453 #elif defined __APPLE__
3454 platid = pimacos;
3455 #endif
3456 if (uname (&buf)) err (1, "uname");
3458 tup_v = caml_alloc_tuple (2);
3460 char const *sar[] = {
3461 buf.sysname,
3462 buf.release,
3463 buf.version,
3464 buf.machine,
3465 NULL
3467 arr_v = caml_copy_string_array (sar);
3469 Field (tup_v, 0) = Val_int (platid);
3470 Field (tup_v, 1) = arr_v;
3471 CAMLreturn (tup_v);
3474 void ml_cloexec (value fd_v);
3475 void ml_cloexec (value fd_v)
3477 CAMLparam1 (fd_v);
3478 int fd = Int_val (fd_v);
3480 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3481 uerror ("fcntl", Nothing);
3483 CAMLreturn0;
3486 value ml_getpbo (value w_v, value h_v, value cs_v);
3487 value ml_getpbo (value w_v, value h_v, value cs_v)
3489 CAMLparam2 (w_v, h_v);
3490 CAMLlocal1 (ret_v);
3491 struct bo *pbo;
3492 int w = Int_val (w_v);
3493 int h = Int_val (h_v);
3494 int cs = Int_val (cs_v);
3496 if (state.bo_usable) {
3497 pbo = calloc (sizeof (*pbo), 1);
3498 if (!pbo) {
3499 err (1, "calloc pbo");
3502 switch (cs) {
3503 case 0:
3504 case 1:
3505 pbo->size = w*h*4;
3506 break;
3507 case 2:
3508 pbo->size = w*h*2;
3509 break;
3510 default:
3511 errx (1, "%s: invalid colorspace %d", __func__, cs);
3514 state.glGenBuffersARB (1, &pbo->id);
3515 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3516 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3517 NULL, GL_STREAM_DRAW);
3518 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3519 GL_READ_WRITE);
3520 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3521 if (!pbo->ptr) {
3522 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3523 state.glDeleteBuffersARB (1, &pbo->id);
3524 free (pbo);
3525 ret_v = caml_copy_string ("0");
3527 else {
3528 int res;
3529 char *s;
3531 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3532 if (res < 0) {
3533 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3535 s = malloc (res+1);
3536 if (!s) {
3537 err (1, "malloc %d bytes failed", res+1);
3539 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3540 if (res < 0) {
3541 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3543 ret_v = caml_copy_string (s);
3544 free (s);
3547 else {
3548 ret_v = caml_copy_string ("0");
3550 CAMLreturn (ret_v);
3553 void ml_freepbo (value s_v);
3554 void ml_freepbo (value s_v)
3556 CAMLparam1 (s_v);
3557 char *s = String_val (s_v);
3558 struct tile *tile = parse_pointer (__func__, s);
3560 if (tile->pbo) {
3561 state.glDeleteBuffersARB (1, &tile->pbo->id);
3562 tile->pbo->id = -1;
3563 tile->pbo->ptr = NULL;
3564 tile->pbo->size = -1;
3566 CAMLreturn0;
3569 void ml_unmappbo (value s_v);
3570 void ml_unmappbo (value s_v)
3572 CAMLparam1 (s_v);
3573 char *s = String_val (s_v);
3574 struct tile *tile = parse_pointer (__func__, s);
3576 if (tile->pbo) {
3577 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3578 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3579 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3581 tile->pbo->ptr = NULL;
3582 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3584 CAMLreturn0;
3587 static void setuppbo (void)
3589 extern void (*wsigladdr (const char *name)) (void);
3590 #pragma GCC diagnostic push
3591 #ifdef __clang__
3592 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3593 #endif
3594 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3595 state.bo_usable = GPA (glBindBufferARB)
3596 && GPA (glUnmapBufferARB)
3597 && GPA (glMapBufferARB)
3598 && GPA (glBufferDataARB)
3599 && GPA (glGenBuffersARB)
3600 && GPA (glDeleteBuffersARB);
3601 #undef GPA
3602 #pragma GCC diagnostic pop
3605 value ml_bo_usable (void);
3606 value ml_bo_usable (void)
3608 return Val_bool (state.bo_usable);
3611 value ml_unproject (value ptr_v, value x_v, value y_v);
3612 value ml_unproject (value ptr_v, value x_v, value y_v)
3614 CAMLparam3 (ptr_v, x_v, y_v);
3615 CAMLlocal2 (ret_v, tup_v);
3616 struct page *page;
3617 char *s = String_val (ptr_v);
3618 int x = Int_val (x_v), y = Int_val (y_v);
3619 struct pagedim *pdim;
3620 fz_point p;
3622 page = parse_pointer (__func__, s);
3623 pdim = &state.pagedims[page->pdimno];
3625 ret_v = Val_int (0);
3626 if (trylock (__func__)) {
3627 goto done;
3630 p.x = x + pdim->bounds.x0;
3631 p.y = y + pdim->bounds.y0;
3633 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3634 pdim->ctm)));
3636 tup_v = caml_alloc_tuple (2);
3637 ret_v = caml_alloc_small (1, 1);
3638 Field (tup_v, 0) = Val_int (p.x);
3639 Field (tup_v, 1) = Val_int (p.y);
3640 Field (ret_v, 0) = tup_v;
3642 unlock (__func__);
3643 done:
3644 CAMLreturn (ret_v);
3647 value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3648 value x_v, value y_v);
3649 value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3650 value x_v, value y_v)
3652 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3653 CAMLlocal1 (ret_v);
3654 struct page *page;
3655 char *s = String_val (ptr_v);
3656 int pageno = Int_val (pageno_v);
3657 int pdimno = Int_val (pdimno_v);
3658 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3659 struct pagedim *pdim;
3660 fz_point p;
3661 fz_matrix ctm;
3663 ret_v = Val_int (0);
3664 lock (__func__);
3666 if (!*s) {
3667 page = loadpage (pageno, pdimno);
3669 else {
3670 page = parse_pointer (__func__, s);
3672 pdim = &state.pagedims[pdimno];
3674 if (pdf_specifics (state.ctx, state.doc)) {
3675 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3676 ctm = state.pagedims[page->pdimno].tctm;
3678 else {
3679 ctm = fz_identity;
3681 p.x = x + pdim->bounds.x0;
3682 p.y = y + pdim->bounds.y0;
3684 ctm = fz_concat (pdim->tctm, pdim->ctm);
3685 p = fz_transform_point (p, ctm);
3687 ret_v = caml_alloc_tuple (2);
3688 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3689 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3691 if (!*s) {
3692 freepage (page);
3694 unlock (__func__);
3695 CAMLreturn (ret_v);
3698 void ml_addannot (value ptr_v, value x_v, value y_v, value contents_v);
3699 void ml_addannot (value ptr_v, value x_v, value y_v, value contents_v)
3701 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3702 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3704 if (pdf) {
3705 pdf_annot *annot;
3706 struct page *page;
3707 fz_point p;
3708 char *s = String_val (ptr_v);
3710 page = parse_pointer (__func__, s);
3711 annot = pdf_create_annot (state.ctx,
3712 pdf_page_from_fz_page (state.ctx,
3713 page->fzpage),
3714 PDF_ANNOT_TEXT);
3715 p.x = Int_val (x_v);
3716 p.y = Int_val (y_v);
3717 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3718 pdf_set_text_annot_position (state.ctx, annot, p);
3719 state.dirty = 1;
3721 CAMLreturn0;
3724 void ml_delannot (value ptr_v, value n_v);
3725 void ml_delannot (value ptr_v, value n_v)
3727 CAMLparam2 (ptr_v, n_v);
3728 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3730 if (pdf) {
3731 struct page *page;
3732 char *s = String_val (ptr_v);
3733 struct slink *slink;
3735 page = parse_pointer (__func__, s);
3736 slink = &page->slinks[Int_val (n_v)];
3737 pdf_delete_annot (state.ctx,
3738 pdf_page_from_fz_page (state.ctx, page->fzpage),
3739 (pdf_annot *) slink->u.annot);
3740 state.dirty = 1;
3742 CAMLreturn0;
3745 void ml_modannot (value ptr_v, value n_v, value str_v);
3746 void ml_modannot (value ptr_v, value n_v, value str_v)
3748 CAMLparam3 (ptr_v, n_v, str_v);
3749 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3751 if (pdf) {
3752 struct page *page;
3753 char *s = String_val (ptr_v);
3754 struct slink *slink;
3756 page = parse_pointer (__func__, s);
3757 slink = &page->slinks[Int_val (n_v)];
3758 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3759 String_val (str_v));
3760 state.dirty = 1;
3762 CAMLreturn0;
3765 value ml_hasunsavedchanges (void);
3766 value ml_hasunsavedchanges (void)
3768 return Val_bool (state.dirty);
3771 void ml_savedoc (value path_v);
3772 void ml_savedoc (value path_v)
3774 CAMLparam1 (path_v);
3775 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3777 if (pdf) {
3778 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3780 CAMLreturn0;
3783 static void makestippletex (void)
3785 const char pixels[] = "\xff\xff\0\0";
3786 glGenTextures (1, &state.stid);
3787 glBindTexture (GL_TEXTURE_1D, state.stid);
3788 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3789 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3790 glTexImage1D (
3791 GL_TEXTURE_1D,
3793 GL_ALPHA,
3796 GL_ALPHA,
3797 GL_UNSIGNED_BYTE,
3798 pixels
3802 value ml_fz_version (void);
3803 value ml_fz_version (void)
3805 return caml_copy_string (FZ_VERSION);
3808 value ml_llpp_version (void);
3809 value ml_llpp_version (void)
3811 extern char llpp_version[];
3812 return caml_copy_string (llpp_version);
3815 void ml_init (value csock_v, value params_v);
3816 void ml_init (value csock_v, value params_v)
3818 CAMLparam2 (csock_v, params_v);
3819 CAMLlocal2 (trim_v, fuzz_v);
3820 int ret;
3821 int texcount;
3822 char *fontpath;
3823 int colorspace;
3824 int mustoresize;
3826 state.csock = Int_val (csock_v);
3827 state.rotate = Int_val (Field (params_v, 0));
3828 state.fitmodel = Int_val (Field (params_v, 1));
3829 trim_v = Field (params_v, 2);
3830 texcount = Int_val (Field (params_v, 3));
3831 state.sliceheight = Int_val (Field (params_v, 4));
3832 mustoresize = Int_val (Field (params_v, 5));
3833 colorspace = Int_val (Field (params_v, 6));
3834 fontpath = String_val (Field (params_v, 7));
3836 #ifdef CIDER
3837 state.utf8cs = 1;
3838 #else
3839 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3840 if (setlocale (LC_CTYPE, "")) {
3841 const char *cset = nl_langinfo (CODESET);
3842 state.utf8cs = !strcmp (cset, "UTF-8");
3844 else {
3845 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3847 #endif
3849 if (caml_string_length (Field (params_v, 8)) > 0) {
3850 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3852 if (!state.trimcachepath) {
3853 printd ("emsg failed to strdup trimcachepath: %d:%s",
3854 errno, strerror (errno));
3858 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3859 fz_register_document_handlers (state.ctx);
3861 state.trimmargins = Bool_val (Field (trim_v, 0));
3862 fuzz_v = Field (trim_v, 1);
3863 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3864 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3865 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3866 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3868 set_tex_params (colorspace);
3870 if (*fontpath) {
3871 state.face = load_font (fontpath);
3873 else {
3874 int len;
3875 const unsigned char *data;
3877 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3878 state.face = load_builtin_font (data, len);
3880 if (!state.face) _exit (1);
3882 realloctexts (texcount);
3883 setuppbo ();
3884 makestippletex ();
3886 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3887 if (ret) {
3888 errx (1, "pthread_create: %s", strerror (ret));
3891 CAMLreturn0;
3894 #if FIXME || !FIXME
3895 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3896 #endif