Simplify
[llpp.git] / link.c
blobf2e5d215f25899a8d10c5e37e82a614469d3aa7d
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 #define WithProto(...) extern __VA_ARGS__; __VA_ARGS__
261 WithProto (value ml_hasdata (value fd_v))
263 CAMLparam1 (fd_v);
264 int ret, avail;
266 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
267 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
268 CAMLreturn (Val_bool (avail > 0));
271 static void readdata (int fd, void *p, int size)
273 ssize_t n;
275 again:
276 n = read (fd, p, size);
277 if (n - size) {
278 if (n < 0 && errno == EINTR) goto again;
279 if (!n) errx (1, "EOF while reading");
280 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
284 static void writedata (int fd, char *p, int size)
286 ssize_t n;
287 uint32_t size4 = size;
288 struct iovec iov[2] = {
289 { .iov_base = &size4, .iov_len = 4 },
290 { .iov_base = p, .iov_len = size }
293 again:
294 n = writev (fd, iov, 2);
295 if (n < 0 && errno == EINTR) goto again;
296 if (n - size - 4) {
297 if (!n) errx (1, "EOF while writing data");
298 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
302 static int readlen (int fd)
304 uint32_t u;
305 readdata (fd, &u, 4);
306 return u;
309 WithProto (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 WithProto (value ml_rcmd (value fd_v))
318 CAMLparam1 (fd_v);
319 CAMLlocal1 (strdata_v);
320 int fd = Int_val (fd_v);
321 int len = readlen (fd);
322 strdata_v = caml_alloc_string (len);
323 readdata (fd, String_val (strdata_v), len);
324 CAMLreturn (strdata_v);
327 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
329 char fbuf[64];
330 int size = sizeof (fbuf), len;
331 va_list ap;
332 char *buf = fbuf;
334 for (;;) {
335 va_start (ap, fmt);
336 len = vsnprintf (buf, size, fmt, ap);
337 va_end (ap);
339 if (len > -1) {
340 if (len < size - 4) {
341 writedata (state.csock, buf, len);
342 break;
344 else size = len + 5;
346 else {
347 err (1, "vsnprintf for `%s' failed", fmt);
349 buf = realloc (buf == fbuf ? NULL : buf, size);
350 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
352 if (buf != fbuf) free (buf);
355 static void closedoc (void)
357 #ifdef CACHE_PAGEREFS
358 if (state.pdflut.objs) {
359 for (int i = 0; i < state.pdflut.count; ++i) {
360 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
362 free (state.pdflut.objs);
363 state.pdflut.objs = NULL;
364 state.pdflut.idx = 0;
366 #endif
367 if (state.doc) {
368 fz_drop_document (state.ctx, state.doc);
369 state.doc = NULL;
373 static int openxref (char *filename, char *password, int layouth)
375 for (int i = 0; i < state.texcount; ++i) {
376 state.texowners[i].w = -1;
377 state.texowners[i].slice = NULL;
380 closedoc ();
382 state.dirty = 0;
383 if (state.pagedims) {
384 free (state.pagedims);
385 state.pagedims = NULL;
387 state.pagedimcount = 0;
389 fz_set_aa_level (state.ctx, state.aalevel);
390 state.doc = fz_open_document (state.ctx, filename);
391 if (fz_needs_password (state.ctx, state.doc)) {
392 if (password && !*password) {
393 printd ("pass");
394 return 0;
396 else {
397 int ok = fz_authenticate_password (state.ctx, state.doc, password);
398 if (!ok) {
399 printd ("pass fail");
400 return 0;
404 if (layouth >= 0)
405 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
406 state.pagecount = fz_count_pages (state.ctx, state.doc);
407 return 1;
410 static void docinfo (void)
412 struct { char *tag; char *name; } metatbl[] = {
413 { FZ_META_INFO_TITLE, "Title" },
414 { FZ_META_INFO_AUTHOR, "Author" },
415 { FZ_META_FORMAT, "Format" },
416 { FZ_META_ENCRYPTION, "Encryption" },
417 { "info:Creator", "Creator" },
418 { "info:Producer", "Producer" },
419 { "info:CreationDate", "Creation date" },
421 int len = 0;
422 char *buf = NULL;
424 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
425 int need;
426 again:
427 need = fz_lookup_metadata (state.ctx, state.doc,
428 metatbl[i].tag, buf, len);
429 if (need > 0) {
430 if (need <= len) {
431 printd ("info %s\t%s", metatbl[i].name, buf);
433 else {
434 buf = realloc (buf, need + 1);
435 if (!buf) err (1, "docinfo realloc %d", need + 1);
436 len = need + 1;
437 goto again;
441 free (buf);
443 printd ("infoend");
446 static void unlinktile (struct tile *tile)
448 for (int i = 0; i < tile->slicecount; ++i) {
449 struct slice *s = &tile->slices[i];
451 if (s->texindex != -1) {
452 if (state.texowners[s->texindex].slice == s) {
453 state.texowners[s->texindex].slice = NULL;
459 static void freepage (struct page *page)
461 if (!page) return;
462 if (page->text) {
463 fz_drop_stext_page (state.ctx, page->text);
465 if (page->slinks) {
466 free (page->slinks);
468 fz_drop_display_list (state.ctx, page->dlist);
469 fz_drop_page (state.ctx, page->fzpage);
470 free (page);
473 static void freetile (struct tile *tile)
475 unlinktile (tile);
476 if (!tile->pbo) {
477 #if 0
478 fz_drop_pixmap (state.ctx, tile->pixmap);
479 #else /* piggyback */
480 if (state.pig) {
481 fz_drop_pixmap (state.ctx, state.pig);
483 state.pig = tile->pixmap;
484 #endif
486 else {
487 free (tile->pbo);
488 fz_drop_pixmap (state.ctx, tile->pixmap);
490 free (tile);
493 static void trimctm (pdf_page *page, int pindex)
495 struct pagedim *pdim = &state.pagedims[pindex];
497 if (!page) return;
498 if (!pdim->tctmready) {
499 fz_rect realbox, mediabox;
500 fz_matrix page_ctm, ctm;
502 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
503 realbox = fz_transform_rect (pdim->mediabox, ctm);
504 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
505 pdim->tctm = fz_concat (
506 fz_invert_matrix (page_ctm),
507 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
508 pdim->tctmready = 1;
512 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
514 fz_matrix ctm;
515 ptrdiff_t pdimno = pdim - state.pagedims;
517 ARSERT (pdim - state.pagedims < INT_MAX);
518 if (pdf_specifics (state.ctx, state.doc)) {
519 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
520 ctm = fz_concat (pdim->tctm, pdim->ctm);
522 else {
523 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
524 pdim->ctm);
526 return ctm;
529 static fz_matrix pagectm (struct page *page)
531 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
534 static void *loadpage (int pageno, int pindex)
536 fz_device *dev;
537 struct page *page;
539 page = calloc (sizeof (struct page), 1);
540 if (!page) {
541 err (1, "calloc page %d", pageno);
544 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
545 dev = fz_new_list_device (state.ctx, page->dlist);
546 fz_try (state.ctx) {
547 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
548 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
550 fz_catch (state.ctx) {
551 page->fzpage = NULL;
553 fz_close_device (state.ctx, dev);
554 fz_drop_device (state.ctx, dev);
556 page->pdimno = pindex;
557 page->pageno = pageno;
558 page->sgen = state.gen;
559 page->agen = state.gen;
560 page->tgen = state.gen;
561 return page;
564 static struct tile *alloctile (int h)
566 int slicecount;
567 size_t tilesize;
568 struct tile *tile;
570 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
571 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
572 tile = calloc (tilesize, 1);
573 if (!tile) {
574 err (1, "cannot allocate tile (%zu bytes)", tilesize);
576 for (int i = 0; i < slicecount; ++i) {
577 int sh = fz_mini (h, state.sliceheight);
578 tile->slices[i].h = sh;
579 tile->slices[i].texindex = -1;
580 h -= sh;
582 tile->slicecount = slicecount;
583 tile->sliceheight = state.sliceheight;
584 return tile;
587 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
588 struct bo *pbo)
590 fz_irect bbox;
591 fz_matrix ctm;
592 fz_device *dev;
593 struct tile *tile;
594 struct pagedim *pdim;
596 tile = alloctile (h);
597 pdim = &state.pagedims[page->pdimno];
599 bbox = pdim->bounds;
600 bbox.x0 += x;
601 bbox.y0 += y;
602 bbox.x1 = bbox.x0 + w;
603 bbox.y1 = bbox.y0 + h;
605 if (state.pig) {
606 if (state.pig->w == w
607 && state.pig->h == h
608 && state.pig->colorspace == state.colorspace) {
609 tile->pixmap = state.pig;
610 tile->pixmap->x = bbox.x0;
611 tile->pixmap->y = bbox.y0;
613 else {
614 fz_drop_pixmap (state.ctx, state.pig);
616 state.pig = NULL;
618 if (!tile->pixmap) {
619 if (pbo) {
620 tile->pixmap =
621 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
622 bbox, NULL, 1, pbo->ptr);
623 tile->pbo = pbo;
625 else {
626 tile->pixmap =
627 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
628 NULL, 1);
632 tile->w = w;
633 tile->h = h;
634 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
636 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
637 ctm = pagectm (page);
638 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
639 fz_rect_from_irect (bbox), NULL);
640 fz_close_device (state.ctx, dev);
641 fz_drop_device (state.ctx, dev);
643 return tile;
646 #ifdef CACHE_PAGEREFS
647 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
648 thanks to Robin Watts */
649 static void
650 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
652 fz_context *ctx = state.ctx; /* doc->ctx; */
653 pdf_obj *kids;
654 int len;
656 if (state.pdflut.idx == state.pagecount) return;
658 kids = pdf_dict_gets (ctx, node, "Kids");
659 len = pdf_array_len (ctx, kids);
661 if (len == 0)
662 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
664 if (pdf_mark_obj (ctx, node))
665 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
666 for (int i = 0; i < len; i++) {
667 pdf_obj *kid = pdf_array_get (ctx, kids, i);
668 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
669 if (*type
670 ? !strcmp (type, "Pages")
671 : pdf_dict_gets (ctx, kid, "Kids")
672 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
673 pdf_collect_pages (doc, kid);
675 else {
676 if (*type
677 ? strcmp (type, "Page") != 0
678 : !pdf_dict_gets (ctx, kid, "MediaBox"))
679 fz_warn (ctx, "non-page object in page tree (%s)", type);
680 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
683 pdf_unmark_obj (ctx, node);
686 static void
687 pdf_load_page_objs (pdf_document *doc)
689 pdf_obj *root = pdf_dict_gets (state.ctx,
690 pdf_trailer (state.ctx, doc), "Root");
691 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
693 if (!node)
694 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
696 state.pdflut.idx = 0;
697 pdf_collect_pages (doc, node);
699 #endif
701 static void initpdims (void)
703 double start, end;
704 FILE *trimf = NULL;
705 fz_rect rootmediabox = fz_empty_rect;
706 int pageno, trim, show;
707 int trimw = 0, cxcount;
708 fz_context *ctx = state.ctx;
709 pdf_document *pdf = pdf_specifics (ctx, state.doc);
711 fz_var (trimw);
712 fz_var (trimf);
713 fz_var (cxcount);
714 start = now ();
716 if (state.trimmargins && state.trimcachepath) {
717 trimf = fopen (state.trimcachepath, "rb");
718 if (!trimf) {
719 trimf = fopen (state.trimcachepath, "wb");
720 trimw = 1;
724 if (state.trimmargins || pdf)
725 cxcount = state.pagecount;
726 else
727 cxcount = fz_mini (state.pagecount, 1);
729 if (pdf) {
730 pdf_obj *obj;
731 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
732 "Root/Pages/MediaBox");
733 rootmediabox = pdf_to_rect (ctx, obj);
736 #ifdef CACHE_PAGEREFS
737 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
738 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
739 if (!state.pdflut.objs) {
740 err (1, "malloc pageobjs %zu %d %zu failed",
741 sizeof (*state.pdflut.objs), cxcount,
742 sizeof (*state.pdflut.objs) * cxcount);
744 state.pdflut.count = cxcount;
745 pdf_load_page_objs (pdf);
746 state.pdflut.pdf = pdf;
748 #endif
750 for (pageno = 0; pageno < cxcount; ++pageno) {
751 int rotate = 0;
752 struct pagedim *p;
753 fz_rect mediabox = fz_empty_rect;
755 fz_var (rotate);
756 if (pdf) {
757 pdf_obj *pageref, *pageobj;
759 #ifdef CACHE_PAGEREFS
760 pageref = state.pdflut.objs[pageno];
761 #else
762 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
763 #endif
764 pageobj = pdf_resolve_indirect (ctx, pageref);
765 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
767 if (state.trimmargins) {
768 pdf_obj *obj;
769 pdf_page *page;
771 fz_try (ctx) {
772 page = pdf_load_page (ctx, pdf, pageno);
773 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
774 trim = state.trimanew || !obj;
775 if (trim) {
776 fz_rect rect;
777 fz_device *dev;
778 fz_matrix ctm, page_ctm;
780 dev = fz_new_bbox_device (ctx, &rect);
781 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
782 ctm = fz_invert_matrix (page_ctm);
783 pdf_run_page (ctx, page, dev, fz_identity, NULL);
784 fz_close_device (ctx, dev);
785 fz_drop_device (ctx, dev);
787 rect.x0 += state.trimfuzz.x0;
788 rect.x1 += state.trimfuzz.x1;
789 rect.y0 += state.trimfuzz.y0;
790 rect.y1 += state.trimfuzz.y1;
791 rect = fz_transform_rect (rect, ctm);
792 rect = fz_intersect_rect (rect, mediabox);
794 if (!fz_is_empty_rect (rect)) {
795 mediabox = rect;
798 obj = pdf_new_array (ctx, pdf, 4);
799 pdf_array_push (ctx, obj,
800 pdf_new_real (ctx, mediabox.x0));
801 pdf_array_push (ctx, obj,
802 pdf_new_real (ctx, mediabox.y0));
803 pdf_array_push (ctx, obj,
804 pdf_new_real (ctx, mediabox.x1));
805 pdf_array_push (ctx, obj,
806 pdf_new_real (ctx, mediabox.y1));
807 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
809 else {
810 mediabox.x0 = pdf_to_real (ctx,
811 pdf_array_get (ctx, obj, 0));
812 mediabox.y0 = pdf_to_real (ctx,
813 pdf_array_get (ctx, obj, 1));
814 mediabox.x1 = pdf_to_real (ctx,
815 pdf_array_get (ctx, obj, 2));
816 mediabox.y1 = pdf_to_real (ctx,
817 pdf_array_get (ctx, obj, 3));
820 fz_drop_page (ctx, &page->super);
821 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
822 if (show) {
823 printd ("progress %f Trimming %d",
824 (double) (pageno + 1) / state.pagecount,
825 pageno + 1);
828 fz_catch (ctx) {
829 printd ("emsg failed to load page %d", pageno);
832 else {
833 int empty = 0;
834 fz_rect cropbox;
836 mediabox =
837 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "MediaBox"));
838 if (fz_is_empty_rect (mediabox)) {
839 mediabox.x0 = 0;
840 mediabox.y0 = 0;
841 mediabox.x1 = 612;
842 mediabox.y1 = 792;
843 empty = 1;
846 cropbox =
847 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
848 if (!fz_is_empty_rect (cropbox)) {
849 if (empty) {
850 mediabox = cropbox;
852 else {
853 mediabox = fz_intersect_rect (mediabox, cropbox);
856 else {
857 if (empty) {
858 if (fz_is_empty_rect (rootmediabox)) {
859 printd ("emsg cannot find page size for page %d",
860 pageno);
862 else {
863 mediabox = rootmediabox;
869 else {
870 if (state.trimmargins && trimw) {
871 fz_page *page;
873 fz_try (ctx) {
874 page = fz_load_page (ctx, state.doc, pageno);
875 mediabox = fz_bound_page (ctx, page);
876 if (state.trimmargins) {
877 fz_rect rect;
878 fz_device *dev;
880 dev = fz_new_bbox_device (ctx, &rect);
881 fz_run_page (ctx, page, dev, fz_identity, NULL);
882 fz_close_device (ctx, dev);
883 fz_drop_device (ctx, dev);
885 rect.x0 += state.trimfuzz.x0;
886 rect.x1 += state.trimfuzz.x1;
887 rect.y0 += state.trimfuzz.y0;
888 rect.y1 += state.trimfuzz.y1;
889 rect = fz_intersect_rect (rect, mediabox);
891 if (!fz_is_empty_rect (rect)) {
892 mediabox = rect;
895 fz_drop_page (ctx, page);
897 fz_catch (ctx) {
899 if (trimf) {
900 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
901 if (n - 1) {
902 err (1, "fwrite trim mediabox");
906 else {
907 if (trimf) {
908 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
909 if (n - 1) {
910 err (1, "fread trim mediabox %d", pageno);
913 else {
914 fz_page *page;
915 fz_try (ctx) {
916 page = fz_load_page (ctx, state.doc, pageno);
917 mediabox = fz_bound_page (ctx, page);
918 fz_drop_page (ctx, page);
920 show = !state.trimmargins && pageno % 20 == 0;
921 if (show) {
922 printd ("progress %f Gathering dimensions %d",
923 (double) (pageno) / state.pagecount,
924 pageno);
927 fz_catch (ctx) {
928 printd ("emsg failed to load page %d", pageno);
934 if (state.pagedimcount == 0
935 || ((void) (p = &state.pagedims[state.pagedimcount-1])
936 , p->rotate != rotate)
937 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
938 size_t size;
940 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
941 state.pagedims = realloc (state.pagedims, size);
942 if (!state.pagedims) {
943 err (1, "realloc pagedims to %zu (%d elems)",
944 size, state.pagedimcount + 1);
947 p = &state.pagedims[state.pagedimcount++];
948 p->rotate = rotate;
949 p->mediabox = mediabox;
950 p->pageno = pageno;
953 end = now ();
954 printd ("progress 1 %s %d pages in %f seconds",
955 state.trimmargins ? "Trimmed" : "Processed",
956 state.pagecount, end - start);
957 state.trimanew = 0;
958 if (trimf) {
959 if (fclose (trimf)) {
960 err (1, "fclose");
965 static void layout (void)
967 int pindex;
968 fz_rect box;
969 fz_matrix ctm;
970 struct pagedim *p = NULL;
971 float zw, w, maxw = 0.0, zoom = 1.0;
973 if (state.pagedimcount == 0) return;
975 switch (state.fitmodel) {
976 case FitProportional:
977 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
978 float x0, x1;
980 p = &state.pagedims[pindex];
981 box = fz_transform_rect (p->mediabox,
982 fz_rotate (p->rotate + state.rotate));
984 x0 = fz_min (box.x0, box.x1);
985 x1 = fz_max (box.x0, box.x1);
987 w = x1 - x0;
988 maxw = fz_max (w, maxw);
989 zoom = state.w / maxw;
991 break;
993 case FitPage:
994 maxw = state.w;
995 break;
997 case FitWidth:
998 break;
1000 default:
1001 ARSERT (0 && state.fitmodel);
1004 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1005 p = &state.pagedims[pindex];
1006 ctm = fz_rotate (state.rotate);
1007 box = fz_transform_rect (p->mediabox,
1008 fz_rotate (p->rotate + state.rotate));
1009 w = box.x1 - box.x0;
1010 switch (state.fitmodel) {
1011 case FitProportional:
1012 p->left = (int) (((maxw - w) * zoom) / 2.f);
1013 break;
1014 case FitPage:
1016 float zh, h;
1017 zw = maxw / w;
1018 h = box.y1 - box.y0;
1019 zh = state.h / h;
1020 zoom = fz_min (zw, zh);
1021 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1023 break;
1024 case FitWidth:
1025 p->left = 0;
1026 zoom = state.w / w;
1027 break;
1030 p->zoomctm = fz_scale (zoom, zoom);
1031 ctm = fz_concat (p->zoomctm, ctm);
1033 p->pagebox = p->mediabox;
1034 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
1035 p->pagebox.x1 -= p->pagebox.x0;
1036 p->pagebox.y1 -= p->pagebox.y0;
1037 p->pagebox.x0 = 0;
1038 p->pagebox.y0 = 0;
1039 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
1040 p->ctm = ctm;
1042 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
1043 fz_scale (zoom, -zoom));
1044 p->tctmready = 0;
1047 do {
1048 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1049 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1050 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1051 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1052 int boundw = x1 - x0;
1053 int boundh = y1 - y0;
1055 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1056 } while (p-- != state.pagedims);
1059 static struct pagedim *pdimofpageno (int pageno)
1061 struct pagedim *pdim = state.pagedims;
1063 for (int i = 0; i < state.pagedimcount; ++i) {
1064 if (state.pagedims[i].pageno > pageno)
1065 break;
1066 pdim = &state.pagedims[i];
1068 return pdim;
1071 static void recurse_outline (fz_outline *outline, int level)
1073 while (outline) {
1074 if (outline->page >= 0) {
1075 fz_point p = {.x = outline->x, .y = outline->y};
1076 struct pagedim *pdim = pdimofpageno (outline->page);
1077 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1078 p = fz_transform_point (p, pdim->ctm);
1079 printd ("o %d %d %d %d %s",
1080 level, outline->page, (int) p.y, h, outline->title);
1082 else {
1083 printd ("on %d %s", level, outline->title);
1085 if (outline->down) {
1086 recurse_outline (outline->down, level + 1);
1088 outline = outline->next;
1092 static void process_outline (void)
1094 fz_outline *outline;
1096 if (!state.needoutline || !state.pagedimcount) return;
1098 state.needoutline = 0;
1099 outline = fz_load_outline (state.ctx, state.doc);
1100 if (outline) {
1101 recurse_outline (outline, 0);
1102 fz_drop_outline (state.ctx, outline);
1106 static char *strofline (fz_stext_line *line)
1108 char *p;
1109 char utf8[10];
1110 fz_stext_char *ch;
1111 size_t size = 0, cap = 80;
1113 p = malloc (cap + 1);
1114 if (!p) return NULL;
1116 for (ch = line->first_char; ch; ch = ch->next) {
1117 int n = fz_runetochar (utf8, ch->c);
1118 if (size + n > cap) {
1119 cap *= 2;
1120 p = realloc (p, cap + 1);
1121 if (!p) return NULL;
1124 memcpy (p + size, utf8, n);
1125 size += n;
1127 p[size] = 0;
1128 return p;
1131 static int matchline (regex_t *re, fz_stext_line *line,
1132 int stop, int pageno, double start)
1134 int ret;
1135 char *p;
1136 regmatch_t rm;
1138 p = strofline (line);
1139 if (!p) return -1;
1141 ret = regexec (re, p, 1, &rm, 0);
1142 if (ret) {
1143 free (p);
1144 if (ret != REG_NOMATCH) {
1145 size_t size;
1146 char errbuf[80];
1147 size = regerror (ret, re, errbuf, sizeof (errbuf));
1148 printd ("msg regexec error `%.*s'",
1149 (int) size, errbuf);
1150 return -1;
1152 return 0;
1154 else {
1155 fz_quad s, e;
1156 fz_stext_char *ch;
1157 int o = 0;
1159 for (ch = line->first_char; ch; ch = ch->next) {
1160 o += fz_runelen (ch->c);
1161 if (o > rm.rm_so) {
1162 s = ch->quad;
1163 break;
1166 for (;ch; ch = ch->next) {
1167 o += fz_runelen (ch->c);
1168 if (o > rm.rm_eo) break;
1170 e = ch->quad;
1172 if (!stop) {
1173 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1174 pageno, 1,
1175 s.ul.x, s.ul.y,
1176 e.ur.x, s.ul.y,
1177 e.lr.x, e.lr.y,
1178 s.ul.x, e.lr.y);
1180 printd ("progress 1 found at %d `%.*s' in %f sec",
1181 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1182 now () - start);
1184 else {
1185 printd ("match %d %d %f %f %f %f %f %f %f %f",
1186 pageno, 2,
1187 s.ul.x, s.ul.y,
1188 e.ur.x, s.ul.y,
1189 e.lr.x, e.lr.y,
1190 s.ul.x, e.lr.y);
1192 free (p);
1193 return 1;
1197 /* wishful thinking function */
1198 static void search (regex_t *re, int pageno, int y, int forward)
1200 fz_device *tdev;
1201 fz_stext_page *text;
1202 struct pagedim *pdim;
1203 int stop = 0, niters = 0;
1204 double start, end;
1205 fz_page *page;
1206 fz_stext_block *block;
1208 start = now ();
1209 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1210 if (niters++ == 5) {
1211 niters = 0;
1212 if (hasdata ()) {
1213 printd ("progress 1 attention requested aborting search at %d",
1214 pageno);
1215 stop = 1;
1217 else {
1218 printd ("progress %f searching in page %d",
1219 (double) (pageno + 1) / state.pagecount,
1220 pageno);
1223 pdim = pdimofpageno (pageno);
1224 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1225 tdev = fz_new_stext_device (state.ctx, text, 0);
1227 page = fz_load_page (state.ctx, state.doc, pageno);
1228 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1230 fz_close_device (state.ctx, tdev);
1231 fz_drop_device (state.ctx, tdev);
1233 if (forward) {
1234 for (block = text->first_block; block; block = block->next) {
1235 fz_stext_line *line;
1237 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1238 for (line = block->u.t.first_line; line; line = line->next) {
1239 if (line->bbox.y0 < y + 1) continue;
1241 switch (matchline (re, line, stop, pageno, start)) {
1242 case 0: break;
1243 case 1: stop = 1; break;
1244 case -1: stop = 1; goto endloop;
1249 else {
1250 for (block = text->last_block; block; block = block->prev) {
1251 fz_stext_line *line;
1253 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1254 for (line = block->u.t.last_line; line; line = line->prev) {
1255 if (line->bbox.y0 < y + 1) continue;
1257 switch (matchline (re, line, stop, pageno, start)) {
1258 case 0: break;
1259 case 1: stop = 1; break;
1260 case -1: stop = 1; goto endloop;
1266 if (forward) {
1267 pageno += 1;
1268 y = 0;
1270 else {
1271 pageno -= 1;
1272 y = INT_MAX;
1274 endloop:
1275 fz_drop_stext_page (state.ctx, text);
1276 fz_drop_page (state.ctx, page);
1278 end = now ();
1279 if (!stop) {
1280 printd ("progress 1 no matches %f sec", end - start);
1282 printd ("clearrects");
1285 static void set_tex_params (int colorspace)
1287 switch (colorspace) {
1288 case 0:
1289 state.texiform = GL_RGBA8;
1290 state.texform = GL_RGBA;
1291 state.texty = GL_UNSIGNED_BYTE;
1292 state.colorspace = fz_device_rgb (state.ctx);
1293 break;
1294 case 1:
1295 state.texiform = GL_LUMINANCE_ALPHA;
1296 state.texform = GL_LUMINANCE_ALPHA;
1297 state.texty = GL_UNSIGNED_BYTE;
1298 state.colorspace = fz_device_gray (state.ctx);
1299 break;
1300 default:
1301 errx (1, "invalid colorspce %d", colorspace);
1305 static void realloctexts (int texcount)
1307 size_t size;
1309 if (texcount == state.texcount) return;
1311 if (texcount < state.texcount) {
1312 glDeleteTextures (state.texcount - texcount,
1313 state.texids + texcount);
1316 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1317 state.texids = realloc (state.texids, size);
1318 if (!state.texids) {
1319 err (1, "realloc texs %zu", size);
1322 state.texowners = (void *) (state.texids + texcount);
1323 if (texcount > state.texcount) {
1324 glGenTextures (texcount - state.texcount,
1325 state.texids + state.texcount);
1326 for (int i = state.texcount; i < texcount; ++i) {
1327 state.texowners[i].w = -1;
1328 state.texowners[i].slice = NULL;
1331 state.texcount = texcount;
1332 state.texindex = 0;
1335 static char *mbtoutf8 (char *s)
1337 char *p, *r;
1338 wchar_t *tmp;
1339 size_t i, ret, len;
1341 if (state.utf8cs) {
1342 return s;
1345 len = mbstowcs (NULL, s, strlen (s));
1346 if (len == 0 || len == (size_t) -1) {
1347 if (len)
1348 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1349 return s;
1352 tmp = calloc (len, sizeof (wchar_t));
1353 if (!tmp) {
1354 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1355 len, sizeof (wchar_t), errno, strerror (errno));
1356 return s;
1359 ret = mbstowcs (tmp, s, len);
1360 if (ret == (size_t) -1) {
1361 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1362 len, errno, strerror (errno));
1363 free (tmp);
1364 return s;
1367 len = 0;
1368 for (i = 0; i < ret; ++i) {
1369 len += fz_runelen (tmp[i]);
1372 p = r = malloc (len + 1);
1373 if (!r) {
1374 printd ("emsg mbtoutf8: malloc(%zu)", len);
1375 free (tmp);
1376 return s;
1379 for (i = 0; i < ret; ++i) {
1380 p += fz_runetochar (p, tmp[i]);
1382 *p = 0;
1383 free (tmp);
1384 return r;
1387 WithProto (value ml_mbtoutf8 (value s_v))
1389 CAMLparam1 (s_v);
1390 CAMLlocal1 (ret_v);
1391 char *s, *r;
1393 s = String_val (s_v);
1394 r = mbtoutf8 (s);
1395 if (r == s) {
1396 ret_v = s_v;
1398 else {
1399 ret_v = caml_copy_string (r);
1400 free (r);
1402 CAMLreturn (ret_v);
1405 static void * mainloop (void UNUSED_ATTR *unused)
1407 char *p = NULL;
1408 int len, ret, oldlen = 0;
1410 fz_var (p);
1411 fz_var (oldlen);
1412 for (;;) {
1413 len = readlen (state.csock);
1414 if (len == 0) {
1415 errx (1, "readlen returned 0");
1418 if (oldlen < len + 1) {
1419 p = realloc (p, len + 1);
1420 if (!p) {
1421 err (1, "realloc %d failed", len + 1);
1423 oldlen = len + 1;
1425 readdata (state.csock, p, len);
1426 p[len] = 0;
1428 if (!strncmp ("open", p, 4)) {
1429 int off, usedoccss, ok = 0, layouth;
1430 char *password;
1431 char *filename;
1432 char *utf8filename;
1433 size_t filenamelen;
1435 fz_var (ok);
1436 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1437 if (ret != 2) {
1438 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1441 filename = p + 5 + off;
1442 filenamelen = strlen (filename);
1443 password = filename + filenamelen + 1;
1445 if (password[strlen (password) + 1]) {
1446 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1449 lock ("open");
1450 fz_set_use_document_css (state.ctx, usedoccss);
1451 fz_try (state.ctx) {
1452 ok = openxref (filename, password, layouth);
1454 fz_catch (state.ctx) {
1455 utf8filename = mbtoutf8 (filename);
1456 printd ("msg Could not open %s", utf8filename);
1457 if (utf8filename != filename) {
1458 free (utf8filename);
1461 if (ok) {
1462 docinfo ();
1463 initpdims ();
1465 unlock ("open");
1467 if (ok) {
1468 utf8filename = mbtoutf8 (filename);
1469 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1470 if (utf8filename != filename) {
1471 free (utf8filename);
1473 state.needoutline = 1;
1476 else if (!strncmp ("cs", p, 2)) {
1477 int i, colorspace;
1479 ret = sscanf (p + 2, " %d", &colorspace);
1480 if (ret != 1) {
1481 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1483 lock ("cs");
1484 set_tex_params (colorspace);
1485 for (i = 0; i < state.texcount; ++i) {
1486 state.texowners[i].w = -1;
1487 state.texowners[i].slice = NULL;
1489 unlock ("cs");
1491 else if (!strncmp ("freepage", p, 8)) {
1492 void *ptr;
1494 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1495 if (ret != 1) {
1496 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1498 lock ("freepage");
1499 freepage (ptr);
1500 unlock ("freepage");
1502 else if (!strncmp ("freetile", p, 8)) {
1503 void *ptr;
1505 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1506 if (ret != 1) {
1507 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1509 lock ("freetile");
1510 freetile (ptr);
1511 unlock ("freetile");
1513 else if (!strncmp ("search", p, 6)) {
1514 int icase, pageno, y, len2, forward;
1515 char *pattern;
1516 regex_t re;
1518 ret = sscanf (p + 6, " %d %d %d %d,%n",
1519 &icase, &pageno, &y, &forward, &len2);
1520 if (ret != 4) {
1521 errx (1, "malformed search `%s' ret=%d", p, ret);
1524 pattern = p + 6 + len2;
1525 ret = regcomp (&re, pattern,
1526 REG_EXTENDED | (icase ? REG_ICASE : 0));
1527 if (ret) {
1528 char errbuf[80];
1529 size_t size;
1531 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1532 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1534 else {
1535 search (&re, pageno, y, forward);
1536 regfree (&re);
1539 else if (!strncmp ("geometry", p, 8)) {
1540 int w, h, fitmodel;
1542 printd ("clear");
1543 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1544 if (ret != 3) {
1545 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1548 lock ("geometry");
1549 state.h = h;
1550 if (w != state.w) {
1551 state.w = w;
1552 for (int i = 0; i < state.texcount; ++i) {
1553 state.texowners[i].slice = NULL;
1556 state.fitmodel = fitmodel;
1557 layout ();
1558 process_outline ();
1560 state.gen++;
1561 unlock ("geometry");
1562 printd ("continue %d", state.pagecount);
1564 else if (!strncmp ("reqlayout", p, 9)) {
1565 char *nameddest;
1566 int rotate, off, h;
1567 int fitmodel;
1568 pdf_document *pdf;
1570 printd ("clear");
1571 ret = sscanf (p + 9, " %d %d %d %n",
1572 &rotate, &fitmodel, &h, &off);
1573 if (ret != 3) {
1574 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1576 lock ("reqlayout");
1577 pdf = pdf_specifics (state.ctx, state.doc);
1578 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1579 state.gen += 1;
1581 state.rotate = rotate;
1582 state.fitmodel = fitmodel;
1583 state.h = h;
1584 layout ();
1585 process_outline ();
1587 nameddest = p + 9 + off;
1588 if (pdf && nameddest && *nameddest) {
1589 fz_point xy;
1590 struct pagedim *pdim;
1591 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1592 &xy.x, &xy.y);
1593 pdim = pdimofpageno (pageno);
1594 xy = fz_transform_point (xy, pdim->ctm);
1595 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1598 state.gen++;
1599 unlock ("reqlayout");
1600 printd ("continue %d", state.pagecount);
1602 else if (!strncmp ("page", p, 4)) {
1603 double a, b;
1604 struct page *page;
1605 int pageno, pindex;
1607 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1608 if (ret != 2) {
1609 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1612 lock ("page");
1613 a = now ();
1614 page = loadpage (pageno, pindex);
1615 b = now ();
1616 unlock ("page");
1618 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1620 else if (!strncmp ("tile", p, 4)) {
1621 int x, y, w, h;
1622 struct page *page;
1623 struct tile *tile;
1624 double a, b;
1625 void *data;
1627 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1628 (uintptr_t *) &page, &x, &y, &w, &h,
1629 (uintptr_t *) &data);
1630 if (ret != 6) {
1631 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1634 lock ("tile");
1635 a = now ();
1636 tile = rendertile (page, x, y, w, h, data);
1637 b = now ();
1638 unlock ("tile");
1640 printd ("tile %d %d %" PRIxPTR " %u %f",
1641 x, y, (uintptr_t) (tile),
1642 tile->w * tile->h * tile->pixmap->n,
1643 b - a);
1645 else if (!strncmp ("trimset", p, 7)) {
1646 fz_irect fuzz;
1647 int trimmargins;
1649 ret = sscanf (p + 7, " %d %d %d %d %d",
1650 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1651 if (ret != 5) {
1652 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1654 lock ("trimset");
1655 state.trimmargins = trimmargins;
1656 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1657 state.trimanew = 1;
1658 state.trimfuzz = fuzz;
1660 unlock ("trimset");
1662 else if (!strncmp ("settrim", p, 7)) {
1663 fz_irect fuzz;
1664 int trimmargins;
1666 ret = sscanf (p + 7, " %d %d %d %d %d",
1667 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1668 if (ret != 5) {
1669 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1671 printd ("clear");
1672 lock ("settrim");
1673 state.trimmargins = trimmargins;
1674 state.needoutline = 1;
1675 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1676 state.trimanew = 1;
1677 state.trimfuzz = fuzz;
1679 state.pagedimcount = 0;
1680 free (state.pagedims);
1681 state.pagedims = NULL;
1682 initpdims ();
1683 layout ();
1684 process_outline ();
1685 unlock ("settrim");
1686 printd ("continue %d", state.pagecount);
1688 else if (!strncmp ("sliceh", p, 6)) {
1689 int h;
1691 ret = sscanf (p + 6, " %d", &h);
1692 if (ret != 1) {
1693 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1695 if (h != state.sliceheight) {
1696 state.sliceheight = h;
1697 for (int i = 0; i < state.texcount; ++i) {
1698 state.texowners[i].w = -1;
1699 state.texowners[i].h = -1;
1700 state.texowners[i].slice = NULL;
1704 else if (!strncmp ("interrupt", p, 9)) {
1705 printd ("vmsg interrupted");
1707 else {
1708 errx (1, "unknown command %.*s", len, p);
1711 return 0;
1714 WithProto (value ml_isexternallink (value uri_v))
1716 CAMLparam1 (uri_v);
1717 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1718 CAMLreturn (Val_bool (ext));
1721 WithProto (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 WithProto (value ml_realloctexts (value texcount_v))
1742 CAMLparam1 (texcount_v);
1743 int ok;
1745 if (trylock (__func__)) {
1746 ok = 0;
1747 goto done;
1749 realloctexts (Int_val (texcount_v));
1750 ok = 1;
1751 unlock (__func__);
1753 done:
1754 CAMLreturn (Val_bool (ok));
1757 static void recti (int x0, int y0, int x1, int y1)
1759 GLfloat *v = state.vertices;
1761 glVertexPointer (2, GL_FLOAT, 0, v);
1762 v[0] = x0; v[1] = y0;
1763 v[2] = x1; v[3] = y0;
1764 v[4] = x0; v[5] = y1;
1765 v[6] = x1; v[7] = y1;
1766 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1769 static void showsel (struct page *page, int ox, int oy)
1771 fz_irect bbox;
1772 fz_rect rect;
1773 fz_stext_block *block;
1774 int seen = 0;
1775 unsigned char selcolor[] = {15,15,15,140};
1777 if (!page->fmark || !page->lmark) return;
1779 glEnable (GL_BLEND);
1780 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1781 glColor4ubv (selcolor);
1783 ox += state.pagedims[page->pdimno].bounds.x0;
1784 oy += state.pagedims[page->pdimno].bounds.y0;
1786 for (block = page->text->first_block; block; block = block->next) {
1787 fz_stext_line *line;
1789 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1790 for (line = block->u.t.first_line; line; line = line->next) {
1791 fz_stext_char *ch;
1793 rect = fz_empty_rect;
1794 for (ch = line->first_char; ch; ch = ch->next) {
1795 fz_rect r;
1796 if (ch == page->fmark) seen = 1;
1797 r = fz_rect_from_quad (ch->quad);
1798 if (seen) rect = fz_union_rect (rect, r);
1799 if (ch == page->lmark) {
1800 bbox = fz_round_rect (rect);
1801 recti (bbox.x0 + ox, bbox.y0 + oy,
1802 bbox.x1 + ox, bbox.y1 + oy);
1803 goto done;
1806 bbox = fz_round_rect (rect);
1807 recti (bbox.x0 + ox, bbox.y0 + oy,
1808 bbox.x1 + ox, bbox.y1 + oy);
1811 done:
1812 glDisable (GL_BLEND);
1815 #pragma GCC diagnostic push
1816 #pragma GCC diagnostic ignored "-Wconversion"
1817 #include "glfont.c"
1818 #pragma GCC diagnostic pop
1820 static void stipplerect (fz_matrix m,
1821 fz_point p1,
1822 fz_point p2,
1823 fz_point p3,
1824 fz_point p4,
1825 GLfloat *texcoords,
1826 GLfloat *vertices)
1828 p1 = fz_transform_point (p1, m);
1829 p2 = fz_transform_point (p2, m);
1830 p3 = fz_transform_point (p3, m);
1831 p4 = fz_transform_point (p4, m);
1833 float w, h, s, t;
1835 w = p2.x - p1.x;
1836 h = p2.y - p1.y;
1837 t = hypotf (w, h) * .25f;
1839 w = p3.x - p2.x;
1840 h = p3.y - p2.y;
1841 s = hypotf (w, h) * .25f;
1843 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1844 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1846 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1847 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1849 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1850 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1852 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1853 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1855 glDrawArrays (GL_LINES, 0, 8);
1858 static void solidrect (fz_matrix m,
1859 fz_point p1,
1860 fz_point p2,
1861 fz_point p3,
1862 fz_point p4,
1863 GLfloat *vertices)
1865 p1 = fz_transform_point (p1, m);
1866 p2 = fz_transform_point (p2, m);
1867 p3 = fz_transform_point (p3, m);
1868 p4 = fz_transform_point (p4, m);
1869 vertices[0] = p1.x; vertices[1] = p1.y;
1870 vertices[2] = p2.x; vertices[3] = p2.y;
1872 vertices[4] = p3.x; vertices[5] = p3.y;
1873 vertices[6] = p4.x; vertices[7] = p4.y;
1874 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1877 static void ensurelinks (struct page *page)
1879 if (!page->links)
1880 page->links = fz_load_links (state.ctx, page->fzpage);
1883 static void highlightlinks (struct page *page, int xoff, int yoff)
1885 fz_matrix ctm;
1886 fz_link *link;
1887 GLfloat *texcoords = state.texcoords;
1888 GLfloat *vertices = state.vertices;
1890 ensurelinks (page);
1892 glEnable (GL_TEXTURE_1D);
1893 glEnable (GL_BLEND);
1894 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1895 glBindTexture (GL_TEXTURE_1D, state.stid);
1897 xoff -= state.pagedims[page->pdimno].bounds.x0;
1898 yoff -= state.pagedims[page->pdimno].bounds.y0;
1899 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1901 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1902 glVertexPointer (2, GL_FLOAT, 0, vertices);
1904 for (link = page->links; link; link = link->next) {
1905 fz_point p1, p2, p3, p4;
1907 p1.x = link->rect.x0;
1908 p1.y = link->rect.y0;
1910 p2.x = link->rect.x1;
1911 p2.y = link->rect.y0;
1913 p3.x = link->rect.x1;
1914 p3.y = link->rect.y1;
1916 p4.x = link->rect.x0;
1917 p4.y = link->rect.y1;
1919 /* TODO: different colours for different schemes */
1920 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1921 else glColor3ub (255, 0, 0);
1923 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1926 for (int i = 0; i < page->annotcount; ++i) {
1927 fz_point p1, p2, p3, p4;
1928 struct annot *annot = &page->annots[i];
1930 p1.x = annot->bbox.x0;
1931 p1.y = annot->bbox.y0;
1933 p2.x = annot->bbox.x1;
1934 p2.y = annot->bbox.y0;
1936 p3.x = annot->bbox.x1;
1937 p3.y = annot->bbox.y1;
1939 p4.x = annot->bbox.x0;
1940 p4.y = annot->bbox.y1;
1942 glColor3ub (0, 0, 128);
1943 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1946 glDisable (GL_BLEND);
1947 glDisable (GL_TEXTURE_1D);
1950 static int compareslinks (const void *l, const void *r)
1952 struct slink const *ls = l;
1953 struct slink const *rs = r;
1954 if (ls->bbox.y0 == rs->bbox.y0) {
1955 return rs->bbox.x0 - rs->bbox.x0;
1957 return ls->bbox.y0 - rs->bbox.y0;
1960 static void droptext (struct page *page)
1962 if (page->text) {
1963 fz_drop_stext_page (state.ctx, page->text);
1964 page->fmark = NULL;
1965 page->lmark = NULL;
1966 page->text = NULL;
1970 static void dropannots (struct page *page)
1972 if (page->annots) {
1973 free (page->annots);
1974 page->annots = NULL;
1975 page->annotcount = 0;
1979 static void ensureannots (struct page *page)
1981 int i, count = 0;
1982 size_t annotsize = sizeof (*page->annots);
1983 fz_annot *annot;
1985 if (state.gen != page->agen) {
1986 dropannots (page);
1987 page->agen = state.gen;
1989 if (page->annots) return;
1991 for (annot = fz_first_annot (state.ctx, page->fzpage);
1992 annot;
1993 annot = fz_next_annot (state.ctx, annot)) {
1994 count++;
1997 if (count > 0) {
1998 page->annotcount = count;
1999 page->annots = calloc (count, annotsize);
2000 if (!page->annots) {
2001 err (1, "calloc annots %d", count);
2004 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2005 annot;
2006 annot = fz_next_annot (state.ctx, annot), i++) {
2007 fz_rect rect;
2009 rect = fz_bound_annot (state.ctx, annot);
2010 page->annots[i].annot = annot;
2011 page->annots[i].bbox = fz_round_rect (rect);
2016 static void dropslinks (struct page *page)
2018 if (page->slinks) {
2019 free (page->slinks);
2020 page->slinks = NULL;
2021 page->slinkcount = 0;
2023 if (page->links) {
2024 fz_drop_link (state.ctx, page->links);
2025 page->links = NULL;
2029 static void ensureslinks (struct page *page)
2031 fz_matrix ctm;
2032 int i, count;
2033 size_t slinksize = sizeof (*page->slinks);
2034 fz_link *link;
2036 ensureannots (page);
2037 if (state.gen != page->sgen) {
2038 dropslinks (page);
2039 page->sgen = state.gen;
2041 if (page->slinks) return;
2043 ensurelinks (page);
2044 ctm = pagectm (page);
2046 count = page->annotcount;
2047 for (link = page->links; link; link = link->next) {
2048 count++;
2050 if (count > 0) {
2051 int j;
2053 page->slinkcount = count;
2054 page->slinks = calloc (count, slinksize);
2055 if (!page->slinks) {
2056 err (1, "calloc slinks %d", count);
2059 for (i = 0, link = page->links; link; ++i, link = link->next) {
2060 fz_rect rect;
2062 rect = link->rect;
2063 rect = fz_transform_rect (rect, ctm);
2064 page->slinks[i].tag = SLINK;
2065 page->slinks[i].u.link = link;
2066 page->slinks[i].bbox = fz_round_rect (rect);
2068 for (j = 0; j < page->annotcount; ++j, ++i) {
2069 fz_rect rect;
2070 rect = fz_bound_annot (state.ctx, page->annots[j].annot);
2071 rect = fz_transform_rect (rect, ctm);
2072 page->slinks[i].bbox = fz_round_rect (rect);
2074 page->slinks[i].tag = SANNOT;
2075 page->slinks[i].u.annot = page->annots[j].annot;
2077 qsort (page->slinks, count, slinksize, compareslinks);
2081 static void highlightslinks (struct page *page, int xoff, int yoff,
2082 int noff, char *targ, mlsize_t tlen, int hfsize)
2084 char buf[40];
2085 struct slink *slink;
2086 float x0, y0, x1, y1, w;
2088 ensureslinks (page);
2089 glColor3ub (0xc3, 0xb0, 0x91);
2090 for (int i = 0; i < page->slinkcount; ++i) {
2091 fmt_linkn (buf, i + noff);
2092 if (!tlen || !strncmp (targ, buf, tlen)) {
2093 slink = &page->slinks[i];
2095 x0 = slink->bbox.x0 + xoff - 5;
2096 y1 = slink->bbox.y0 + yoff - 5;
2097 y0 = y1 + 10 + hfsize;
2098 w = measure_string (state.face, hfsize, buf);
2099 x1 = x0 + w + 10;
2100 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2104 glEnable (GL_BLEND);
2105 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2106 glEnable (GL_TEXTURE_2D);
2107 glColor3ub (0, 0, 0);
2108 for (int i = 0; i < page->slinkcount; ++i) {
2109 fmt_linkn (buf, i + noff);
2110 if (!tlen || !strncmp (targ, buf, tlen)) {
2111 slink = &page->slinks[i];
2113 x0 = slink->bbox.x0 + xoff;
2114 y0 = slink->bbox.y0 + yoff + hfsize;
2115 draw_string (state.face, hfsize, x0, y0, buf);
2118 glDisable (GL_TEXTURE_2D);
2119 glDisable (GL_BLEND);
2122 static void uploadslice (struct tile *tile, struct slice *slice)
2124 int offset;
2125 struct slice *slice1;
2126 unsigned char *texdata;
2128 offset = 0;
2129 for (slice1 = tile->slices; slice != slice1; slice1++) {
2130 offset += slice1->h * tile->w * tile->pixmap->n;
2132 if (slice->texindex != -1 && slice->texindex < state.texcount
2133 && state.texowners[slice->texindex].slice == slice) {
2134 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2136 else {
2137 int subimage = 0;
2138 int texindex = state.texindex++ % state.texcount;
2140 if (state.texowners[texindex].w == tile->w) {
2141 if (state.texowners[texindex].h >= slice->h) {
2142 subimage = 1;
2144 else {
2145 state.texowners[texindex].h = slice->h;
2148 else {
2149 state.texowners[texindex].h = slice->h;
2152 state.texowners[texindex].w = tile->w;
2153 state.texowners[texindex].slice = slice;
2154 slice->texindex = texindex;
2156 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2157 #if TEXT_TYPE == GL_TEXTURE_2D
2158 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2159 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2160 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2161 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2162 #endif
2163 if (tile->pbo) {
2164 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2165 texdata = 0;
2167 else {
2168 texdata = tile->pixmap->samples;
2170 if (subimage) {
2171 glTexSubImage2D (TEXT_TYPE,
2175 tile->w,
2176 slice->h,
2177 state.texform,
2178 state.texty,
2179 texdata+offset
2182 else {
2183 glTexImage2D (TEXT_TYPE,
2185 state.texiform,
2186 tile->w,
2187 slice->h,
2189 state.texform,
2190 state.texty,
2191 texdata+offset
2194 if (tile->pbo) {
2195 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2200 WithProto (void ml_begintiles (void))
2202 glEnable (TEXT_TYPE);
2203 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2204 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2207 WithProto (void ml_endtiles (void))
2209 glDisable (TEXT_TYPE);
2212 WithProto (void ml_drawtile (value args_v, value ptr_v))
2214 CAMLparam2 (args_v, ptr_v);
2215 int dispx = Int_val (Field (args_v, 0));
2216 int dispy = Int_val (Field (args_v, 1));
2217 int dispw = Int_val (Field (args_v, 2));
2218 int disph = Int_val (Field (args_v, 3));
2219 int tilex = Int_val (Field (args_v, 4));
2220 int tiley = Int_val (Field (args_v, 5));
2221 char *s = String_val (ptr_v);
2222 struct tile *tile = parse_pointer (__func__, s);
2223 int slicey, firstslice;
2224 struct slice *slice;
2225 GLfloat *texcoords = state.texcoords;
2226 GLfloat *vertices = state.vertices;
2228 firstslice = tiley / tile->sliceheight;
2229 slice = &tile->slices[firstslice];
2230 slicey = tiley % tile->sliceheight;
2232 while (disph > 0) {
2233 int dh;
2235 dh = slice->h - slicey;
2236 dh = fz_mini (disph, dh);
2237 uploadslice (tile, slice);
2239 texcoords[0] = tilex; texcoords[1] = slicey;
2240 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2241 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2242 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2244 vertices[0] = dispx; vertices[1] = dispy;
2245 vertices[2] = dispx+dispw; vertices[3] = dispy;
2246 vertices[4] = dispx; vertices[5] = dispy+dh;
2247 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2249 #if TEXT_TYPE == GL_TEXTURE_2D
2250 for (int i = 0; i < 8; ++i) {
2251 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2253 #endif
2255 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2256 dispy += dh;
2257 disph -= dh;
2258 slice++;
2259 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2260 slicey = 0;
2262 CAMLreturn0;
2265 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2267 fz_matrix ctm;
2268 fz_point p1, p2, p3, p4;
2269 GLfloat *vertices = state.vertices;
2270 double *v = (double *) rects_v;
2272 xoff -= state.pagedims[page->pdimno].bounds.x0;
2273 yoff -= state.pagedims[page->pdimno].bounds.y0;
2274 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2276 glEnable (GL_BLEND);
2277 glVertexPointer (2, GL_FLOAT, 0, vertices);
2279 glColor4dv (v);
2280 p1.x = (float) v[4];
2281 p1.y = (float) v[5];
2283 p2.x = (float) v[6];
2284 p2.y = (float) v[5];
2286 p3.x = (float) v[6];
2287 p3.y = (float) v[7];
2289 p4.x = (float) v[4];
2290 p4.y = (float) v[7];
2291 solidrect (ctm, p1, p2, p3, p4, vertices);
2292 glDisable (GL_BLEND);
2295 WithProto (value ml_postprocess (value ptr_v, value hlinks_v,
2296 value xoff_v, value yoff_v,
2297 value li_v))
2299 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2300 int xoff = Int_val (xoff_v);
2301 int yoff = Int_val (yoff_v);
2302 int noff = Int_val (Field (li_v, 0));
2303 char *targ = String_val (Field (li_v, 1));
2304 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2305 int hfsize = Int_val (Field (li_v, 2));
2306 char *s = String_val (ptr_v);
2307 int hlmask = Int_val (hlinks_v);
2308 struct page *page = parse_pointer (__func__, s);
2310 if (!page->fzpage) {
2311 /* deal with loadpage failed pages */
2312 goto done;
2315 if (trylock (__func__)) {
2316 noff = -1;
2317 goto done;
2320 ensureannots (page);
2321 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2322 if (hlmask & 2) {
2323 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2324 noff = page->slinkcount;
2326 if (page->tgen == state.gen) {
2327 showsel (page, xoff, yoff);
2329 unlock (__func__);
2331 done:
2332 CAMLreturn (Val_int (noff));
2335 WithProto (void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2336 value rects_v))
2338 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2339 int xoff = Int_val (xoff_v);
2340 int yoff = Int_val (yoff_v);
2341 char *s = String_val (ptr_v);
2342 struct page *page = parse_pointer (__func__, s);
2344 drawprect (page, xoff, yoff, rects_v);
2345 CAMLreturn0;
2348 static struct annot *getannot (struct page *page, int x, int y)
2350 fz_point p;
2351 fz_matrix ctm;
2352 const fz_matrix *tctm;
2353 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2355 if (!page->annots) return NULL;
2357 if (pdf) {
2358 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2359 tctm = &state.pagedims[page->pdimno].tctm;
2361 else {
2362 tctm = &fz_identity;
2365 p.x = x;
2366 p.y = y;
2368 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2369 ctm = fz_invert_matrix (ctm);
2370 p = fz_transform_point (p, ctm);
2372 if (pdf) {
2373 for (int i = 0; i < page->annotcount; ++i) {
2374 struct annot *a = &page->annots[i];
2375 fz_rect rect;
2377 rect = fz_bound_annot (state.ctx, a->annot);
2378 if (p.x >= rect.x0 && p.x <= rect.x1) {
2379 if (p.y >= rect.y0 && p.y <= rect.y1)
2380 return a;
2384 return NULL;
2387 static fz_link *getlink (struct page *page, int x, int y)
2389 fz_point p;
2390 fz_link *link;
2392 ensureslinks (page);
2394 p.x = x;
2395 p.y = y;
2397 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2399 for (link = page->links; link; link = link->next) {
2400 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2401 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2402 return link;
2406 return NULL;
2409 static void ensuretext (struct page *page)
2411 if (state.gen != page->tgen) {
2412 droptext (page);
2413 page->tgen = state.gen;
2415 if (!page->text) {
2416 fz_device *tdev;
2418 page->text = fz_new_stext_page (state.ctx,
2419 state.pagedims[page->pdimno].mediabox);
2420 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2421 fz_run_display_list (state.ctx, page->dlist,
2422 tdev, pagectm (page), fz_infinite_rect, NULL);
2423 fz_close_device (state.ctx, tdev);
2424 fz_drop_device (state.ctx, tdev);
2428 WithProto (value ml_find_page_with_links (value start_page_v, value dir_v))
2430 CAMLparam2 (start_page_v, dir_v);
2431 CAMLlocal1 (ret_v);
2432 int i, dir = Int_val (dir_v);
2433 int start_page = Int_val (start_page_v);
2434 int end_page = dir > 0 ? state.pagecount : -1;
2435 pdf_document *pdf;
2437 fz_var (end_page);
2438 ret_v = Val_int (0);
2439 lock (__func__);
2440 pdf = pdf_specifics (state.ctx, state.doc);
2441 for (i = start_page + dir; i != end_page; i += dir) {
2442 int found;
2444 fz_var (found);
2445 if (pdf) {
2446 pdf_page *page = NULL;
2448 fz_var (page);
2449 fz_try (state.ctx) {
2450 page = pdf_load_page (state.ctx, pdf, i);
2451 found = !!page->links || !!page->annots;
2453 fz_catch (state.ctx) {
2454 found = 0;
2456 if (page) {
2457 fz_drop_page (state.ctx, &page->super);
2460 else {
2461 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2462 fz_link *link = fz_load_links (state.ctx, page);
2463 found = !!link;
2464 fz_drop_link (state.ctx, link);
2465 fz_drop_page (state.ctx, page);
2468 if (found) {
2469 ret_v = caml_alloc_small (1, 1);
2470 Field (ret_v, 0) = Val_int (i);
2471 goto unlock;
2474 unlock:
2475 unlock (__func__);
2476 CAMLreturn (ret_v);
2479 enum { dir_first, dir_last };
2480 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2482 WithProto (value ml_findlink (value ptr_v, value dir_v))
2484 CAMLparam2 (ptr_v, dir_v);
2485 CAMLlocal2 (ret_v, pos_v);
2486 struct page *page;
2487 int dirtag, i, slinkindex;
2488 struct slink *found = NULL ,*slink;
2489 char *s = String_val (ptr_v);
2491 page = parse_pointer (__func__, s);
2492 ret_v = Val_int (0);
2493 lock (__func__);
2494 ensureslinks (page);
2496 if (Is_block (dir_v)) {
2497 dirtag = Tag_val (dir_v);
2498 switch (dirtag) {
2499 case dir_first_visible:
2501 int x0, y0, dir, first_index, last_index;
2503 pos_v = Field (dir_v, 0);
2504 x0 = Int_val (Field (pos_v, 0));
2505 y0 = Int_val (Field (pos_v, 1));
2506 dir = Int_val (Field (pos_v, 2));
2508 if (dir >= 0) {
2509 dir = 1;
2510 first_index = 0;
2511 last_index = page->slinkcount;
2513 else {
2514 first_index = page->slinkcount - 1;
2515 last_index = -1;
2518 for (i = first_index; i != last_index; i += dir) {
2519 slink = &page->slinks[i];
2520 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2521 found = slink;
2522 break;
2526 break;
2528 case dir_left:
2529 slinkindex = Int_val (Field (dir_v, 0));
2530 found = &page->slinks[slinkindex];
2531 for (i = slinkindex - 1; i >= 0; --i) {
2532 slink = &page->slinks[i];
2533 if (slink->bbox.x0 < found->bbox.x0) {
2534 found = slink;
2535 break;
2538 break;
2540 case dir_right:
2541 slinkindex = Int_val (Field (dir_v, 0));
2542 found = &page->slinks[slinkindex];
2543 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2544 slink = &page->slinks[i];
2545 if (slink->bbox.x0 > found->bbox.x0) {
2546 found = slink;
2547 break;
2550 break;
2552 case dir_down:
2553 slinkindex = Int_val (Field (dir_v, 0));
2554 found = &page->slinks[slinkindex];
2555 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2556 slink = &page->slinks[i];
2557 if (slink->bbox.y0 >= found->bbox.y0) {
2558 found = slink;
2559 break;
2562 break;
2564 case dir_up:
2565 slinkindex = Int_val (Field (dir_v, 0));
2566 found = &page->slinks[slinkindex];
2567 for (i = slinkindex - 1; i >= 0; --i) {
2568 slink = &page->slinks[i];
2569 if (slink->bbox.y0 <= found->bbox.y0) {
2570 found = slink;
2571 break;
2574 break;
2577 else {
2578 dirtag = Int_val (dir_v);
2579 switch (dirtag) {
2580 case dir_first:
2581 found = page->slinks;
2582 break;
2584 case dir_last:
2585 if (page->slinks) {
2586 found = page->slinks + (page->slinkcount - 1);
2588 break;
2591 if (found) {
2592 ret_v = caml_alloc_small (2, 1);
2593 Field (ret_v, 0) = Val_int (found - page->slinks);
2596 unlock (__func__);
2597 CAMLreturn (ret_v);
2600 enum { uuri, utext, uannot };
2602 WithProto (value ml_getlink (value ptr_v, value n_v))
2604 CAMLparam2 (ptr_v, n_v);
2605 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2606 fz_link *link;
2607 struct page *page;
2608 char *s = String_val (ptr_v);
2609 struct slink *slink;
2611 ret_v = Val_int (0);
2612 page = parse_pointer (__func__, s);
2614 lock (__func__);
2615 ensureslinks (page);
2616 slink = &page->slinks[Int_val (n_v)];
2617 if (slink->tag == SLINK) {
2618 link = slink->u.link;
2619 str_v = caml_copy_string (link->uri);
2620 ret_v = caml_alloc_small (1, uuri);
2621 Field (ret_v, 0) = str_v;
2623 else {
2624 ret_v = caml_alloc_small (1, uannot);
2625 tup_v = caml_alloc_tuple (2);
2626 Field (ret_v, 0) = tup_v;
2627 Field (tup_v, 0) = ptr_v;
2628 Field (tup_v, 1) = n_v;
2630 unlock (__func__);
2632 CAMLreturn (ret_v);
2635 WithProto (value ml_getannotcontents (value ptr_v, value n_v))
2637 CAMLparam2 (ptr_v, n_v);
2638 CAMLlocal1 (ret_v);
2639 pdf_document *pdf;
2640 const char *contents = "";
2642 lock (__func__);
2643 pdf = pdf_specifics (state.ctx, state.doc);
2644 if (pdf) {
2645 char *s = String_val (ptr_v);
2646 struct page *page;
2647 struct slink *slink;
2649 page = parse_pointer (__func__, s);
2650 slink = &page->slinks[Int_val (n_v)];
2651 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2653 unlock (__func__);
2654 ret_v = caml_copy_string (contents);
2655 CAMLreturn (ret_v);
2658 WithProto (value ml_getlinkcount (value ptr_v))
2660 CAMLparam1 (ptr_v);
2661 struct page *page;
2662 char *s = String_val (ptr_v);
2664 page = parse_pointer (__func__, s);
2665 CAMLreturn (Val_int (page->slinkcount));
2668 WithProto (value ml_getlinkrect (value ptr_v, value n_v))
2670 CAMLparam2 (ptr_v, n_v);
2671 CAMLlocal1 (ret_v);
2672 struct page *page;
2673 struct slink *slink;
2674 char *s = String_val (ptr_v);
2676 page = parse_pointer (__func__, s);
2677 ret_v = caml_alloc_tuple (4);
2678 lock (__func__);
2679 ensureslinks (page);
2681 slink = &page->slinks[Int_val (n_v)];
2682 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2683 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2684 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2685 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2686 unlock (__func__);
2687 CAMLreturn (ret_v);
2690 WithProto (value ml_whatsunder (value ptr_v, value x_v, value y_v))
2692 CAMLparam3 (ptr_v, x_v, y_v);
2693 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2694 fz_link *link;
2695 struct annot *annot;
2696 struct page *page;
2697 char *ptr = String_val (ptr_v);
2698 int x = Int_val (x_v), y = Int_val (y_v);
2699 struct pagedim *pdim;
2701 ret_v = Val_int (0);
2702 if (trylock (__func__)) {
2703 goto done;
2706 page = parse_pointer (__func__, ptr);
2707 pdim = &state.pagedims[page->pdimno];
2708 x += pdim->bounds.x0;
2709 y += pdim->bounds.y0;
2712 annot = getannot (page, x, y);
2713 if (annot) {
2714 int i, n = -1;
2716 ensureslinks (page);
2717 for (i = 0; i < page->slinkcount; ++i) {
2718 if (page->slinks[i].tag == SANNOT
2719 && page->slinks[i].u.annot == annot->annot) {
2720 n = i;
2721 break;
2724 ret_v = caml_alloc_small (1, uannot);
2725 tup_v = caml_alloc_tuple (2);
2726 Field (ret_v, 0) = tup_v;
2727 Field (tup_v, 0) = ptr_v;
2728 Field (tup_v, 1) = Val_int (n);
2729 goto unlock;
2733 link = getlink (page, x, y);
2734 if (link) {
2735 str_v = caml_copy_string (link->uri);
2736 ret_v = caml_alloc_small (1, uuri);
2737 Field (ret_v, 0) = str_v;
2739 else {
2740 fz_rect *b;
2741 fz_stext_block *block;
2743 ensuretext (page);
2745 for (block = page->text->first_block; block; block = block->next) {
2746 fz_stext_line *line;
2748 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2749 b = &block->bbox;
2750 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2751 continue;
2753 for (line = block->u.t.first_line; line; line = line->next) {
2754 fz_stext_char *ch;
2756 b = &line->bbox;
2757 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2758 continue;
2760 for (ch = line->first_char; ch; ch = ch->next) {
2761 fz_quad *q = &ch->quad;
2763 if (x >= q->ul.x && x <= q->ur.x
2764 && y >= q->ul.y && y <= q->ll.y) {
2765 const char *n2 = fz_font_name (state.ctx, ch->font);
2766 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2767 ch->font);
2769 if (!n2) n2 = "<unknown font>";
2771 if (face && face->family_name) {
2772 char *s;
2773 char *n1 = face->family_name;
2774 size_t l1 = strlen (n1);
2775 size_t l2 = strlen (n2);
2777 if (l1 != l2 || memcmp (n1, n2, l1)) {
2778 s = malloc (l1 + l2 + 2);
2779 if (s) {
2780 memcpy (s, n2, l2);
2781 s[l2] = '=';
2782 memcpy (s + l2 + 1, n1, l1 + 1);
2783 str_v = caml_copy_string (s);
2784 free (s);
2788 if (str_v == Val_unit) {
2789 str_v = caml_copy_string (n2);
2791 ret_v = caml_alloc_small (1, utext);
2792 Field (ret_v, 0) = str_v;
2793 goto unlock;
2799 unlock:
2800 unlock (__func__);
2802 done:
2803 CAMLreturn (ret_v);
2806 enum { mark_page, mark_block, mark_line, mark_word };
2808 WithProto (void ml_clearmark (value ptr_v))
2810 CAMLparam1 (ptr_v);
2811 char *s = String_val (ptr_v);
2812 struct page *page;
2814 if (trylock (__func__)) {
2815 goto done;
2818 page = parse_pointer (__func__, s);
2819 page->fmark = NULL;
2820 page->lmark = NULL;
2822 unlock (__func__);
2823 done:
2824 CAMLreturn0;
2827 static int uninteresting (int c)
2829 return isspace (c) || ispunct (c);
2832 WithProto (value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v))
2834 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2835 CAMLlocal1 (ret_v);
2836 fz_rect *b;
2837 struct page *page;
2838 fz_stext_line *line;
2839 fz_stext_block *block;
2840 struct pagedim *pdim;
2841 int mark = Int_val (mark_v);
2842 char *s = String_val (ptr_v);
2843 int x = Int_val (x_v), y = Int_val (y_v);
2845 ret_v = Val_bool (0);
2846 if (trylock (__func__)) {
2847 goto done;
2850 page = parse_pointer (__func__, s);
2851 pdim = &state.pagedims[page->pdimno];
2853 ensuretext (page);
2855 if (mark == mark_page) {
2856 page->fmark = page->text->first_block->u.t.first_line->first_char;
2857 page->lmark = page->text->last_block->u.t.last_line->last_char;
2858 ret_v = Val_bool (1);
2859 goto unlock;
2862 x += pdim->bounds.x0;
2863 y += pdim->bounds.y0;
2865 for (block = page->text->first_block; block; block = block->next) {
2866 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2867 b = &block->bbox;
2868 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2869 continue;
2871 if (mark == mark_block) {
2872 page->fmark = block->u.t.first_line->first_char;
2873 page->lmark = block->u.t.last_line->last_char;
2874 ret_v = Val_bool (1);
2875 goto unlock;
2878 for (line = block->u.t.first_line; line; line = line->next) {
2879 fz_stext_char *ch;
2881 b = &line->bbox;
2882 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2883 continue;
2885 if (mark == mark_line) {
2886 page->fmark = line->first_char;
2887 page->lmark = line->last_char;
2888 ret_v = Val_bool (1);
2889 goto unlock;
2892 for (ch = line->first_char; ch; ch = ch->next) {
2893 fz_stext_char *ch2, *first = NULL, *last = NULL;
2894 fz_quad *q = &ch->quad;
2895 if (x >= q->ul.x && x <= q->ur.x
2896 && y >= q->ul.y && y <= q->ll.y) {
2897 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2898 if (uninteresting (ch2->c)) first = NULL;
2899 else if (!first) first = ch2;
2901 for (ch2 = ch; ch2; ch2 = ch2->next) {
2902 if (uninteresting (ch2->c)) break;
2903 last = ch2;
2906 page->fmark = first;
2907 page->lmark = last;
2908 ret_v = Val_bool (1);
2909 goto unlock;
2914 unlock:
2915 if (!Bool_val (ret_v)) {
2916 page->fmark = NULL;
2917 page->lmark = NULL;
2919 unlock (__func__);
2921 done:
2922 CAMLreturn (ret_v);
2925 WithProto (value ml_rectofblock (value ptr_v, value x_v, value y_v))
2927 CAMLparam3 (ptr_v, x_v, y_v);
2928 CAMLlocal2 (ret_v, res_v);
2929 fz_rect *b = NULL;
2930 struct page *page;
2931 struct pagedim *pdim;
2932 fz_stext_block *block;
2933 char *s = String_val (ptr_v);
2934 int x = Int_val (x_v), y = Int_val (y_v);
2936 ret_v = Val_int (0);
2937 if (trylock (__func__)) {
2938 goto done;
2941 page = parse_pointer (__func__, s);
2942 pdim = &state.pagedims[page->pdimno];
2943 x += pdim->bounds.x0;
2944 y += pdim->bounds.y0;
2946 ensuretext (page);
2948 for (block = page->text->first_block; block; block = block->next) {
2949 switch (block->type) {
2950 case FZ_STEXT_BLOCK_TEXT:
2951 b = &block->bbox;
2952 break;
2954 case FZ_STEXT_BLOCK_IMAGE:
2955 b = &block->bbox;
2956 break;
2958 default:
2959 continue;
2962 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2963 break;
2964 b = NULL;
2966 if (b) {
2967 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2968 ret_v = caml_alloc_small (1, 1);
2969 Store_double_field (res_v, 0, (double) b->x0);
2970 Store_double_field (res_v, 1, (double) b->x1);
2971 Store_double_field (res_v, 2, (double) b->y0);
2972 Store_double_field (res_v, 3, (double) b->y1);
2973 Field (ret_v, 0) = res_v;
2975 unlock (__func__);
2977 done:
2978 CAMLreturn (ret_v);
2981 WithProto (void ml_seltext (value ptr_v, value rect_v))
2983 CAMLparam2 (ptr_v, rect_v);
2984 struct page *page;
2985 struct pagedim *pdim;
2986 char *s = String_val (ptr_v);
2987 int x0, x1, y0, y1;
2988 fz_stext_char *ch;
2989 fz_stext_line *line;
2990 fz_stext_block *block;
2991 fz_stext_char *fc, *lc;
2993 if (trylock (__func__)) {
2994 goto done;
2997 page = parse_pointer (__func__, s);
2998 ensuretext (page);
3000 pdim = &state.pagedims[page->pdimno];
3001 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3002 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3003 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3004 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3006 if (y0 > y1) {
3007 int t = y0;
3008 y0 = y1;
3009 y1 = t;
3010 x0 = x1;
3011 x1 = t;
3014 fc = page->fmark;
3015 lc = page->lmark;
3017 for (block = page->text->first_block; block; block = block->next) {
3018 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3019 for (line = block->u.t.first_line; line; line = line->next) {
3020 for (ch = line->first_char; ch; ch = ch->next) {
3021 fz_quad q = ch->quad;
3022 if (x0 >= q.ul.x && x0 <= q.ur.x
3023 && y0 >= q.ul.y && y0 <= q.ll.y) {
3024 fc = ch;
3026 if (x1 >= q.ul.x && x1 <= q.ur.x
3027 && y1 >= q.ul.y && y1 <= q.ll.y) {
3028 lc = ch;
3033 if (x1 < x0 && fc == lc) {
3034 fz_stext_char *t;
3036 t = fc;
3037 fc = lc;
3038 lc = t;
3041 page->fmark = fc;
3042 page->lmark = lc;
3044 unlock (__func__);
3046 done:
3047 CAMLreturn0;
3050 static int pipechar (FILE *f, fz_stext_char *ch)
3052 char buf[4];
3053 int len;
3054 size_t ret;
3056 len = fz_runetochar (buf, ch->c);
3057 ret = fwrite (buf, len, 1, f);
3058 if (ret != 1) {
3059 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3060 len, ret, errno, strerror (errno));
3061 return -1;
3063 return 0;
3066 WithProto (value ml_spawn (value command_v, value fds_v))
3068 CAMLparam2 (command_v, fds_v);
3069 CAMLlocal2 (l_v, tup_v);
3070 int ret, ret1;
3071 pid_t pid = (pid_t) -1;
3072 char *msg = NULL;
3073 value earg_v = Nothing;
3074 posix_spawnattr_t attr;
3075 posix_spawn_file_actions_t fa;
3076 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3078 argv[2] = String_val (command_v);
3080 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3081 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3084 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3085 msg = "posix_spawnattr_init";
3086 goto fail1;
3089 #ifdef POSIX_SPAWN_USEVFORK
3090 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3091 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3092 goto fail;
3094 #endif
3096 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3097 int fd1, fd2;
3099 tup_v = Field (l_v, 0);
3100 fd1 = Int_val (Field (tup_v, 0));
3101 fd2 = Int_val (Field (tup_v, 1));
3102 if (fd2 < 0) {
3103 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3104 msg = "posix_spawn_file_actions_addclose";
3105 earg_v = tup_v;
3106 goto fail;
3109 else {
3110 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3111 msg = "posix_spawn_file_actions_adddup2";
3112 earg_v = tup_v;
3113 goto fail;
3118 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3119 msg = "posix_spawn";
3120 goto fail;
3123 fail:
3124 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3125 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3128 fail1:
3129 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3130 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3131 ret1, strerror (ret1));
3134 if (msg)
3135 unix_error (ret, msg, earg_v);
3137 CAMLreturn (Val_int (pid));
3140 WithProto (value ml_hassel (value ptr_v))
3142 CAMLparam1 (ptr_v);
3143 CAMLlocal1 (ret_v);
3144 struct page *page;
3145 char *s = String_val (ptr_v);
3147 ret_v = Val_bool (0);
3148 if (trylock (__func__)) {
3149 goto done;
3152 page = parse_pointer (__func__, s);
3153 ret_v = Val_bool (page->fmark && page->lmark);
3154 unlock (__func__);
3155 done:
3156 CAMLreturn (ret_v);
3159 WithProto (void ml_copysel (value fd_v, value ptr_v))
3161 CAMLparam2 (fd_v, ptr_v);
3162 FILE *f;
3163 int seen = 0;
3164 struct page *page;
3165 fz_stext_line *line;
3166 fz_stext_block *block;
3167 int fd = Int_val (fd_v);
3168 char *s = String_val (ptr_v);
3170 if (trylock (__func__)) {
3171 goto done;
3174 page = parse_pointer (__func__, s);
3176 if (!page->fmark || !page->lmark) {
3177 printd ("emsg nothing to copy on page %d", page->pageno);
3178 goto unlock;
3181 f = fdopen (fd, "w");
3182 if (!f) {
3183 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3184 fd, errno, strerror (errno));
3185 f = stdout;
3188 for (block = page->text->first_block; block; block = block->next) {
3189 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3190 for (line = block->u.t.first_line; line; line = line->next) {
3191 fz_stext_char *ch;
3192 for (ch = line->first_char; ch; ch = ch->next) {
3193 if (seen || ch == page->fmark) {
3194 do {
3195 pipechar (f, ch);
3196 if (ch == page->lmark) goto close;
3197 } while ((ch = ch->next));
3198 seen = 1;
3199 break;
3202 if (seen) fputc ('\n', f);
3205 close:
3206 if (f != stdout) {
3207 int ret = fclose (f);
3208 fd = -1;
3209 if (ret == -1) {
3210 if (errno != ECHILD) {
3211 printd ("emsg failed to close sel pipe: %d:%s",
3212 errno, strerror (errno));
3216 unlock:
3217 unlock (__func__);
3219 done:
3220 if (fd >= 0) {
3221 if (close (fd)) {
3222 printd ("emsg failed to close sel pipe: %d:%s",
3223 errno, strerror (errno));
3226 CAMLreturn0;
3229 WithProto (value ml_getpdimrect (value pagedimno_v))
3231 CAMLparam1 (pagedimno_v);
3232 CAMLlocal1 (ret_v);
3233 int pagedimno = Int_val (pagedimno_v);
3234 fz_rect box;
3236 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3237 if (trylock (__func__)) {
3238 box = fz_empty_rect;
3240 else {
3241 box = state.pagedims[pagedimno].mediabox;
3242 unlock (__func__);
3245 Store_double_field (ret_v, 0, (double) box.x0);
3246 Store_double_field (ret_v, 1, (double) box.x1);
3247 Store_double_field (ret_v, 2, (double) box.y0);
3248 Store_double_field (ret_v, 3, (double) box.y1);
3250 CAMLreturn (ret_v);
3253 WithProto (value ml_zoom_for_height (value winw_v, value winh_v,
3254 value dw_v, value cols_v))
3256 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3257 CAMLlocal1 (ret_v);
3258 int i;
3259 float zoom = -1.;
3260 float maxh = 0.0;
3261 struct pagedim *p;
3262 float winw = Int_val (winw_v);
3263 float winh = Int_val (winh_v);
3264 float dw = Int_val (dw_v);
3265 float cols = Int_val (cols_v);
3266 float pw = 1.0, ph = 1.0;
3268 if (trylock (__func__)) {
3269 goto done;
3272 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3273 float w = p->pagebox.x1 / cols;
3274 float h = p->pagebox.y1;
3275 if (h > maxh) {
3276 maxh = h;
3277 ph = h;
3278 if (state.fitmodel != FitProportional) pw = w;
3280 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3283 zoom = (((winh / ph) * pw) + dw) / winw;
3284 unlock (__func__);
3285 done:
3286 ret_v = caml_copy_double ((double) zoom);
3287 CAMLreturn (ret_v);
3290 WithProto (value ml_getmaxw (value unit_v))
3292 CAMLparam1 (unit_v);
3293 CAMLlocal1 (ret_v);
3294 int i;
3295 float maxw = -1.;
3296 struct pagedim *p;
3298 if (trylock (__func__)) {
3299 goto done;
3302 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3303 float w = p->pagebox.x1;
3304 maxw = fz_max (maxw, w);
3307 unlock (__func__);
3308 done:
3309 ret_v = caml_copy_double ((double) maxw);
3310 CAMLreturn (ret_v);
3313 WithProto (value ml_draw_string (value pt_v, value x_v,
3314 value y_v, value string_v))
3316 CAMLparam4 (pt_v, x_v, y_v, string_v);
3317 CAMLlocal1 (ret_v);
3318 int pt = Int_val(pt_v);
3319 int x = Int_val (x_v);
3320 int y = Int_val (y_v);
3321 float w;
3323 w = draw_string (state.face, pt, x, y, String_val (string_v));
3324 ret_v = caml_copy_double (w);
3325 CAMLreturn (ret_v);
3328 WithProto (value ml_measure_string (value pt_v, value string_v))
3330 CAMLparam2 (pt_v, string_v);
3331 CAMLlocal1 (ret_v);
3332 int pt = Int_val (pt_v);
3333 double w;
3335 w = (double) measure_string (state.face, pt, String_val (string_v));
3336 ret_v = caml_copy_double (w);
3337 CAMLreturn (ret_v);
3340 WithProto (value ml_getpagebox (value opaque_v))
3342 CAMLparam1 (opaque_v);
3343 CAMLlocal1 (ret_v);
3344 fz_rect rect;
3345 fz_irect bbox;
3346 fz_device *dev;
3347 char *s = String_val (opaque_v);
3348 struct page *page = parse_pointer (__func__, s);
3350 ret_v = caml_alloc_tuple (4);
3351 dev = fz_new_bbox_device (state.ctx, &rect);
3353 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3355 fz_close_device (state.ctx, dev);
3356 fz_drop_device (state.ctx, dev);
3357 bbox = fz_round_rect (rect);
3358 Field (ret_v, 0) = Val_int (bbox.x0);
3359 Field (ret_v, 1) = Val_int (bbox.y0);
3360 Field (ret_v, 2) = Val_int (bbox.x1);
3361 Field (ret_v, 3) = Val_int (bbox.y1);
3363 CAMLreturn (ret_v);
3366 WithProto (void ml_setaalevel (value level_v))
3368 CAMLparam1 (level_v);
3370 state.aalevel = Int_val (level_v);
3371 CAMLreturn0;
3374 #ifndef CIDER
3375 WithProto (value ml_keysymtoutf8 (value keysym_v))
3377 CAMLparam1 (keysym_v);
3378 CAMLlocal1 (str_v);
3379 KeySym keysym = Int_val (keysym_v);
3380 Rune rune;
3381 extern long keysym2ucs (KeySym);
3382 int len;
3383 char buf[5];
3385 rune = (Rune) keysym2ucs (keysym);
3386 len = fz_runetochar (buf, rune);
3387 buf[len] = 0;
3388 str_v = caml_copy_string (buf);
3389 CAMLreturn (str_v);
3391 #else
3392 WithProto (value ml_keysymtoutf8 (value keysym_v))
3394 CAMLparam1 (keysym_v);
3395 CAMLlocal1 (str_v);
3396 long ucs_v = Long_val (keysym_v);
3397 int len;
3398 char buf[5];
3400 len = fz_runetochar (buf, (int) ucs_v);
3401 buf[len] = 0;
3402 str_v = caml_copy_string (buf);
3403 CAMLreturn (str_v);
3405 #endif
3407 enum { piunknown, pilinux, pimacos, pibsd };
3409 WithProto (value ml_platform (value unit_v))
3411 CAMLparam1 (unit_v);
3412 CAMLlocal2 (tup_v, arr_v);
3413 int platid = piunknown;
3414 struct utsname buf;
3416 #if defined __linux__
3417 platid = pilinux;
3418 #elif defined __DragonFly__ || defined __FreeBSD__
3419 || defined __OpenBSD__ || defined __NetBSD__
3420 platid = pibsd;
3421 #elif defined __APPLE__
3422 platid = pimacos;
3423 #endif
3424 if (uname (&buf)) err (1, "uname");
3426 tup_v = caml_alloc_tuple (2);
3428 char const *sar[] = {
3429 buf.sysname,
3430 buf.release,
3431 buf.version,
3432 buf.machine,
3433 NULL
3435 arr_v = caml_copy_string_array (sar);
3437 Field (tup_v, 0) = Val_int (platid);
3438 Field (tup_v, 1) = arr_v;
3439 CAMLreturn (tup_v);
3442 WithProto (void ml_cloexec (value fd_v))
3444 CAMLparam1 (fd_v);
3445 int fd = Int_val (fd_v);
3447 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3448 uerror ("fcntl", Nothing);
3450 CAMLreturn0;
3453 WithProto (value ml_getpbo (value w_v, value h_v, value cs_v))
3455 CAMLparam2 (w_v, h_v);
3456 CAMLlocal1 (ret_v);
3457 struct bo *pbo;
3458 int w = Int_val (w_v);
3459 int h = Int_val (h_v);
3460 int cs = Int_val (cs_v);
3462 if (state.bo_usable) {
3463 pbo = calloc (sizeof (*pbo), 1);
3464 if (!pbo) {
3465 err (1, "calloc pbo");
3468 switch (cs) {
3469 case 0:
3470 case 1:
3471 pbo->size = w*h*4;
3472 break;
3473 case 2:
3474 pbo->size = w*h*2;
3475 break;
3476 default:
3477 errx (1, "%s: invalid colorspace %d", __func__, cs);
3480 state.glGenBuffersARB (1, &pbo->id);
3481 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3482 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3483 NULL, GL_STREAM_DRAW);
3484 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3485 GL_READ_WRITE);
3486 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3487 if (!pbo->ptr) {
3488 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3489 state.glDeleteBuffersARB (1, &pbo->id);
3490 free (pbo);
3491 ret_v = caml_copy_string ("0");
3493 else {
3494 int res;
3495 char *s;
3497 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3498 if (res < 0) {
3499 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3501 s = malloc (res+1);
3502 if (!s) {
3503 err (1, "malloc %d bytes failed", res+1);
3505 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3506 if (res < 0) {
3507 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3509 ret_v = caml_copy_string (s);
3510 free (s);
3513 else {
3514 ret_v = caml_copy_string ("0");
3516 CAMLreturn (ret_v);
3519 WithProto (void ml_freepbo (value s_v))
3521 CAMLparam1 (s_v);
3522 char *s = String_val (s_v);
3523 struct tile *tile = parse_pointer (__func__, s);
3525 if (tile->pbo) {
3526 state.glDeleteBuffersARB (1, &tile->pbo->id);
3527 tile->pbo->id = -1;
3528 tile->pbo->ptr = NULL;
3529 tile->pbo->size = -1;
3531 CAMLreturn0;
3534 WithProto (void ml_unmappbo (value s_v))
3536 CAMLparam1 (s_v);
3537 char *s = String_val (s_v);
3538 struct tile *tile = parse_pointer (__func__, s);
3540 if (tile->pbo) {
3541 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3542 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3543 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3545 tile->pbo->ptr = NULL;
3546 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3548 CAMLreturn0;
3551 static void setuppbo (void)
3553 extern void (*wsigladdr (const char *name)) (void);
3554 #pragma GCC diagnostic push
3555 #ifdef __clang__
3556 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3557 #endif
3558 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3559 state.bo_usable = GPA (glBindBufferARB)
3560 && GPA (glUnmapBufferARB)
3561 && GPA (glMapBufferARB)
3562 && GPA (glBufferDataARB)
3563 && GPA (glGenBuffersARB)
3564 && GPA (glDeleteBuffersARB);
3565 #undef GPA
3566 #pragma GCC diagnostic pop
3569 WithProto (value ml_bo_usable (void))
3571 return Val_bool (state.bo_usable);
3574 WithProto (value ml_unproject (value ptr_v, value x_v, value y_v))
3576 CAMLparam3 (ptr_v, x_v, y_v);
3577 CAMLlocal2 (ret_v, tup_v);
3578 struct page *page;
3579 char *s = String_val (ptr_v);
3580 int x = Int_val (x_v), y = Int_val (y_v);
3581 struct pagedim *pdim;
3582 fz_point p;
3584 page = parse_pointer (__func__, s);
3585 pdim = &state.pagedims[page->pdimno];
3587 ret_v = Val_int (0);
3588 if (trylock (__func__)) {
3589 goto done;
3592 p.x = x + pdim->bounds.x0;
3593 p.y = y + pdim->bounds.y0;
3595 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3596 pdim->ctm)));
3598 tup_v = caml_alloc_tuple (2);
3599 ret_v = caml_alloc_small (1, 1);
3600 Field (tup_v, 0) = Val_int (p.x);
3601 Field (tup_v, 1) = Val_int (p.y);
3602 Field (ret_v, 0) = tup_v;
3604 unlock (__func__);
3605 done:
3606 CAMLreturn (ret_v);
3609 WithProto (value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3610 value x_v, value y_v))
3612 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3613 CAMLlocal1 (ret_v);
3614 struct page *page;
3615 char *s = String_val (ptr_v);
3616 int pageno = Int_val (pageno_v);
3617 int pdimno = Int_val (pdimno_v);
3618 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3619 struct pagedim *pdim;
3620 fz_point p;
3621 fz_matrix ctm;
3623 ret_v = Val_int (0);
3624 lock (__func__);
3626 if (!*s) {
3627 page = loadpage (pageno, pdimno);
3629 else {
3630 page = parse_pointer (__func__, s);
3632 pdim = &state.pagedims[pdimno];
3634 if (pdf_specifics (state.ctx, state.doc)) {
3635 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3636 ctm = state.pagedims[page->pdimno].tctm;
3638 else {
3639 ctm = fz_identity;
3641 p.x = x + pdim->bounds.x0;
3642 p.y = y + pdim->bounds.y0;
3644 ctm = fz_concat (pdim->tctm, pdim->ctm);
3645 p = fz_transform_point (p, ctm);
3647 ret_v = caml_alloc_tuple (2);
3648 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3649 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3651 if (!*s) {
3652 freepage (page);
3654 unlock (__func__);
3655 CAMLreturn (ret_v);
3658 WithProto (void ml_addannot (value ptr_v, value x_v, value y_v,
3659 value contents_v))
3661 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3662 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3664 if (pdf) {
3665 pdf_annot *annot;
3666 struct page *page;
3667 fz_point p;
3668 char *s = String_val (ptr_v);
3670 page = parse_pointer (__func__, s);
3671 annot = pdf_create_annot (state.ctx,
3672 pdf_page_from_fz_page (state.ctx,
3673 page->fzpage),
3674 PDF_ANNOT_TEXT);
3675 p.x = Int_val (x_v);
3676 p.y = Int_val (y_v);
3677 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3678 pdf_set_text_annot_position (state.ctx, annot, p);
3679 state.dirty = 1;
3681 CAMLreturn0;
3684 WithProto (void ml_delannot (value ptr_v, value n_v))
3686 CAMLparam2 (ptr_v, n_v);
3687 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3689 if (pdf) {
3690 struct page *page;
3691 char *s = String_val (ptr_v);
3692 struct slink *slink;
3694 page = parse_pointer (__func__, s);
3695 slink = &page->slinks[Int_val (n_v)];
3696 pdf_delete_annot (state.ctx,
3697 pdf_page_from_fz_page (state.ctx, page->fzpage),
3698 (pdf_annot *) slink->u.annot);
3699 state.dirty = 1;
3701 CAMLreturn0;
3704 WithProto (void ml_modannot (value ptr_v, value n_v, value str_v))
3706 CAMLparam3 (ptr_v, n_v, str_v);
3707 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3709 if (pdf) {
3710 struct page *page;
3711 char *s = String_val (ptr_v);
3712 struct slink *slink;
3714 page = parse_pointer (__func__, s);
3715 slink = &page->slinks[Int_val (n_v)];
3716 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3717 String_val (str_v));
3718 state.dirty = 1;
3720 CAMLreturn0;
3723 WithProto (value ml_hasunsavedchanges (void))
3725 return Val_bool (state.dirty);
3728 WithProto (void ml_savedoc (value path_v))
3730 CAMLparam1 (path_v);
3731 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3733 if (pdf) {
3734 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3736 CAMLreturn0;
3739 static void makestippletex (void)
3741 const char pixels[] = "\xff\xff\0\0";
3742 glGenTextures (1, &state.stid);
3743 glBindTexture (GL_TEXTURE_1D, state.stid);
3744 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3745 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3746 glTexImage1D (
3747 GL_TEXTURE_1D,
3749 GL_ALPHA,
3752 GL_ALPHA,
3753 GL_UNSIGNED_BYTE,
3754 pixels
3758 WithProto (value ml_fz_version (void))
3760 return caml_copy_string (FZ_VERSION);
3763 WithProto (value ml_llpp_version (void))
3765 extern char llpp_version[];
3766 return caml_copy_string (llpp_version);
3769 WithProto (void ml_init (value csock_v, value params_v))
3771 CAMLparam2 (csock_v, params_v);
3772 CAMLlocal2 (trim_v, fuzz_v);
3773 int ret;
3774 int texcount;
3775 char *fontpath;
3776 int colorspace;
3777 int mustoresize;
3779 state.csock = Int_val (csock_v);
3780 state.rotate = Int_val (Field (params_v, 0));
3781 state.fitmodel = Int_val (Field (params_v, 1));
3782 trim_v = Field (params_v, 2);
3783 texcount = Int_val (Field (params_v, 3));
3784 state.sliceheight = Int_val (Field (params_v, 4));
3785 mustoresize = Int_val (Field (params_v, 5));
3786 colorspace = Int_val (Field (params_v, 6));
3787 fontpath = String_val (Field (params_v, 7));
3789 #ifdef CIDER
3790 state.utf8cs = 1;
3791 #else
3792 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3793 if (setlocale (LC_CTYPE, "")) {
3794 const char *cset = nl_langinfo (CODESET);
3795 state.utf8cs = !strcmp (cset, "UTF-8");
3797 else {
3798 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3800 #endif
3802 if (caml_string_length (Field (params_v, 8)) > 0) {
3803 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3805 if (!state.trimcachepath) {
3806 printd ("emsg failed to strdup trimcachepath: %d:%s",
3807 errno, strerror (errno));
3811 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3812 fz_register_document_handlers (state.ctx);
3814 state.trimmargins = Bool_val (Field (trim_v, 0));
3815 fuzz_v = Field (trim_v, 1);
3816 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3817 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3818 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3819 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3821 set_tex_params (colorspace);
3823 if (*fontpath) {
3824 state.face = load_font (fontpath);
3826 else {
3827 int len;
3828 const unsigned char *data;
3830 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3831 state.face = load_builtin_font (data, len);
3833 if (!state.face) _exit (1);
3835 realloctexts (texcount);
3836 setuppbo ();
3837 makestippletex ();
3839 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3840 if (ret) {
3841 errx (1, "pthread_create: %s", strerror (ret));
3844 CAMLreturn0;
3847 #if FIXME || !FIXME
3848 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3849 #endif