Do not hardcode xclip
[llpp.git] / link.c
blob179936c51a133a63cc68a9c7c96fee422b76cc82
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 "-Wmissing-prototypes"
11 #pragma GCC diagnostic ignored "-Wdouble-promotion"
12 #endif
14 extern char **environ;
16 #include <errno.h>
17 #include <stdio.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <signal.h>
23 #include <math.h>
24 #include <wchar.h>
25 #include <locale.h>
26 #include <langinfo.h>
28 #include <unistd.h>
29 #include <pthread.h>
30 #include <sys/uio.h>
31 #include <sys/time.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/utsname.h>
38 #include <spawn.h>
40 #include <regex.h>
41 #include <stdarg.h>
42 #include <limits.h>
43 #include <inttypes.h>
45 #ifdef CIDER
46 #include <OpenGL/gl.h>
47 #else
48 #include <GL/gl.h>
49 #endif
51 #pragma GCC diagnostic push
52 #ifdef __clang__
53 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
54 #endif
55 #pragma GCC diagnostic ignored "-Wpedantic"
56 #define CAML_NAME_SPACE
57 #include <caml/fail.h>
58 #include <caml/alloc.h>
59 #include <caml/memory.h>
60 #include <caml/unixsupport.h>
62 #pragma GCC diagnostic push
63 #pragma GCC diagnostic ignored "-Wfloat-equal"
64 #include <mupdf/fitz.h>
65 #include <mupdf/pdf.h>
66 #pragma GCC diagnostic pop
68 #include <ft2build.h>
69 #include FT_FREETYPE_H
70 #pragma GCC diagnostic pop
72 #include "cutils.h"
74 #ifdef USE_NPOT
75 #define TEXT_TYPE GL_TEXTURE_2D
76 #else
77 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
78 #endif
80 #if 0
81 #define lprintf printf
82 #else
83 #define lprintf(...)
84 #endif
86 #define ARSERT(cond) for (;;) { \
87 if (!(cond)) { \
88 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
89 } \
90 break; \
93 struct slice {
94 int h;
95 int texindex;
98 struct tile {
99 int w, h;
100 int slicecount;
101 int sliceheight;
102 struct bo *pbo;
103 fz_pixmap *pixmap;
104 struct slice slices[1];
107 struct pagedim {
108 int pageno;
109 int rotate;
110 int left;
111 int tctmready;
112 fz_irect bounds;
113 fz_rect pagebox;
114 fz_rect mediabox;
115 fz_matrix ctm, zoomctm, tctm;
118 struct slink {
119 enum { SLINK, SANNOT } tag;
120 fz_irect bbox;
121 union {
122 fz_link *link;
123 fz_annot *annot;
124 } u;
127 struct annot {
128 fz_irect bbox;
129 fz_annot *annot;
132 struct page {
133 int tgen;
134 int sgen;
135 int agen;
136 int pageno;
137 int pdimno;
138 fz_stext_page *text;
139 fz_page *fzpage;
140 fz_display_list *dlist;
141 fz_link *links;
142 int slinkcount;
143 struct slink *slinks;
144 int annotcount;
145 struct annot *annots;
146 fz_stext_char *fmark, *lmark;
149 enum { FitWidth, FitProportional, FitPage };
151 static struct {
152 int sliceheight;
153 struct pagedim *pagedims;
154 int pagecount;
155 int pagedimcount;
156 fz_document *doc;
157 fz_context *ctx;
158 int w, h;
160 int texindex;
161 int texcount;
162 GLuint *texids;
164 GLenum texiform;
165 GLenum texform;
166 GLenum texty;
168 fz_colorspace *colorspace;
170 struct {
171 int w, h;
172 struct slice *slice;
173 } *texowners;
175 int rotate;
176 int fitmodel;
177 int trimmargins;
178 int needoutline;
179 int gen;
180 int aalevel;
182 int trimanew;
183 fz_irect trimfuzz;
184 fz_pixmap *pig;
186 pthread_t thread;
187 int csock;
188 FT_Face face;
190 char *trimcachepath;
191 int dirty;
193 GLuint stid;
195 int bo_usable;
196 GLuint boid;
198 void (*glBindBufferARB) (GLenum, GLuint);
199 GLboolean (*glUnmapBufferARB) (GLenum);
200 void *(*glMapBufferARB) (GLenum, GLenum);
201 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
202 void (*glGenBuffersARB) (GLsizei, GLuint *);
203 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
205 GLfloat texcoords[8];
206 GLfloat vertices[16];
208 #ifdef CACHE_PAGEREFS
209 struct {
210 int idx;
211 int count;
212 pdf_obj **objs;
213 pdf_document *pdf;
214 } pdflut;
215 #endif
216 int utf8cs;
217 } state;
219 struct bo {
220 GLuint id;
221 void *ptr;
222 size_t size;
225 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
227 static void lock (const char *cap)
229 int ret = pthread_mutex_lock (&mutex);
230 if (ret) {
231 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
235 static void unlock (const char *cap)
237 int ret = pthread_mutex_unlock (&mutex);
238 if (ret) {
239 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
243 static int trylock (const char *cap)
245 int ret = pthread_mutex_trylock (&mutex);
246 if (ret && ret != EBUSY) {
247 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
249 return ret == EBUSY;
252 static int hasdata (void)
254 int ret, avail;
255 ret = ioctl (state.csock, FIONREAD, &avail);
256 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
257 return avail > 0;
260 CAMLprim 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 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
310 CAMLparam3 (fd_v, bytes_v, len_v);
311 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
312 CAMLreturn0;
315 CAMLprim value ml_rcmd (value fd_v)
317 CAMLparam1 (fd_v);
318 CAMLlocal1 (strdata_v);
319 int fd = Int_val (fd_v);
320 int len = readlen (fd);
321 strdata_v = caml_alloc_string (len);
322 readdata (fd, String_val (strdata_v), len);
323 CAMLreturn (strdata_v);
326 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
328 char fbuf[64];
329 int size = sizeof (fbuf), len;
330 va_list ap;
331 char *buf = fbuf;
333 for (;;) {
334 va_start (ap, fmt);
335 len = vsnprintf (buf, size, fmt, ap);
336 va_end (ap);
338 if (len > -1) {
339 if (len < size - 4) {
340 writedata (state.csock, buf, len);
341 break;
343 else size = len + 5;
345 else {
346 err (1, "vsnprintf for `%s' failed", fmt);
348 buf = realloc (buf == fbuf ? NULL : buf, size);
349 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
351 if (buf != fbuf) free (buf);
354 static void closedoc (void)
356 #ifdef CACHE_PAGEREFS
357 if (state.pdflut.objs) {
358 for (int i = 0; i < state.pdflut.count; ++i) {
359 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
361 free (state.pdflut.objs);
362 state.pdflut.objs = NULL;
363 state.pdflut.idx = 0;
365 #endif
366 if (state.doc) {
367 fz_drop_document (state.ctx, state.doc);
368 state.doc = NULL;
372 static int openxref (char *filename, char *password, int layouth)
374 for (int i = 0; i < state.texcount; ++i) {
375 state.texowners[i].w = -1;
376 state.texowners[i].slice = NULL;
379 closedoc ();
381 state.dirty = 0;
382 if (state.pagedims) {
383 free (state.pagedims);
384 state.pagedims = NULL;
386 state.pagedimcount = 0;
388 fz_set_aa_level (state.ctx, state.aalevel);
389 state.doc = fz_open_document (state.ctx, filename);
390 if (fz_needs_password (state.ctx, state.doc)) {
391 if (password && !*password) {
392 printd ("pass");
393 return 0;
395 else {
396 int ok = fz_authenticate_password (state.ctx, state.doc, password);
397 if (!ok) {
398 printd ("pass fail");
399 return 0;
403 if (layouth >= 0)
404 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
405 state.pagecount = fz_count_pages (state.ctx, state.doc);
406 return 1;
409 static void docinfo (void)
411 struct { char *tag; char *name; } metatbl[] = {
412 { FZ_META_INFO_TITLE, "Title" },
413 { FZ_META_INFO_AUTHOR, "Author" },
414 { FZ_META_FORMAT, "Format" },
415 { FZ_META_ENCRYPTION, "Encryption" },
416 { "info:Creator", "Creator" },
417 { "info:Producer", "Producer" },
418 { "info:CreationDate", "Creation date" },
420 int len = 0;
421 char *buf = NULL;
423 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
424 int need;
425 again:
426 need = fz_lookup_metadata (state.ctx, state.doc,
427 metatbl[i].tag, buf, len);
428 if (need > 0) {
429 if (need <= len) {
430 printd ("info %s\t%s", metatbl[i].name, buf);
432 else {
433 buf = realloc (buf, need + 1);
434 if (!buf) err (1, "docinfo realloc %d", need + 1);
435 len = need + 1;
436 goto again;
440 free (buf);
442 printd ("infoend");
445 static void unlinktile (struct tile *tile)
447 for (int i = 0; i < tile->slicecount; ++i) {
448 struct slice *s = &tile->slices[i];
450 if (s->texindex != -1) {
451 if (state.texowners[s->texindex].slice == s) {
452 state.texowners[s->texindex].slice = NULL;
458 static void freepage (struct page *page)
460 if (!page) return;
461 if (page->text) {
462 fz_drop_stext_page (state.ctx, page->text);
464 if (page->slinks) {
465 free (page->slinks);
467 fz_drop_display_list (state.ctx, page->dlist);
468 fz_drop_page (state.ctx, page->fzpage);
469 free (page);
472 static void freetile (struct tile *tile)
474 unlinktile (tile);
475 if (!tile->pbo) {
476 #if 0
477 fz_drop_pixmap (state.ctx, tile->pixmap);
478 #else /* piggyback */
479 if (state.pig) {
480 fz_drop_pixmap (state.ctx, state.pig);
482 state.pig = tile->pixmap;
483 #endif
485 else {
486 free (tile->pbo);
487 fz_drop_pixmap (state.ctx, tile->pixmap);
489 free (tile);
492 static void trimctm (pdf_page *page, int pindex)
494 struct pagedim *pdim = &state.pagedims[pindex];
496 if (!page) return;
497 if (!pdim->tctmready) {
498 fz_rect realbox, mediabox;
499 fz_matrix page_ctm, ctm;
501 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
502 realbox = fz_transform_rect (pdim->mediabox, ctm);
503 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
504 pdim->tctm = fz_concat (
505 fz_invert_matrix (page_ctm),
506 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
507 pdim->tctmready = 1;
511 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
513 fz_matrix ctm;
514 ptrdiff_t pdimno = pdim - state.pagedims;
516 ARSERT (pdim - state.pagedims < INT_MAX);
517 if (pdf_specifics (state.ctx, state.doc)) {
518 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
519 ctm = fz_concat (pdim->tctm, pdim->ctm);
521 else {
522 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
523 pdim->ctm);
525 return ctm;
528 static fz_matrix pagectm (struct page *page)
530 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
533 static void *loadpage (int pageno, int pindex)
535 fz_device *dev;
536 struct page *page;
538 page = calloc (sizeof (struct page), 1);
539 if (!page) {
540 err (1, "calloc page %d", pageno);
543 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
544 dev = fz_new_list_device (state.ctx, page->dlist);
545 fz_try (state.ctx) {
546 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
547 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
549 fz_catch (state.ctx) {
550 page->fzpage = NULL;
552 fz_close_device (state.ctx, dev);
553 fz_drop_device (state.ctx, dev);
555 page->pdimno = pindex;
556 page->pageno = pageno;
557 page->sgen = state.gen;
558 page->agen = state.gen;
559 page->tgen = state.gen;
560 return page;
563 static struct tile *alloctile (int h)
565 int slicecount;
566 size_t tilesize;
567 struct tile *tile;
569 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
570 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
571 tile = calloc (tilesize, 1);
572 if (!tile) {
573 err (1, "cannot allocate tile (%zu bytes)", tilesize);
575 for (int i = 0; i < slicecount; ++i) {
576 int sh = fz_mini (h, state.sliceheight);
577 tile->slices[i].h = sh;
578 tile->slices[i].texindex = -1;
579 h -= sh;
581 tile->slicecount = slicecount;
582 tile->sliceheight = state.sliceheight;
583 return tile;
586 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
587 struct bo *pbo)
589 fz_irect bbox;
590 fz_matrix ctm;
591 fz_device *dev;
592 struct tile *tile;
593 struct pagedim *pdim;
595 tile = alloctile (h);
596 pdim = &state.pagedims[page->pdimno];
598 bbox = pdim->bounds;
599 bbox.x0 += x;
600 bbox.y0 += y;
601 bbox.x1 = bbox.x0 + w;
602 bbox.y1 = bbox.y0 + h;
604 if (state.pig) {
605 if (state.pig->w == w
606 && state.pig->h == h
607 && state.pig->colorspace == state.colorspace) {
608 tile->pixmap = state.pig;
609 tile->pixmap->x = bbox.x0;
610 tile->pixmap->y = bbox.y0;
612 else {
613 fz_drop_pixmap (state.ctx, state.pig);
615 state.pig = NULL;
617 if (!tile->pixmap) {
618 if (pbo) {
619 tile->pixmap =
620 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
621 bbox, NULL, 1, pbo->ptr);
622 tile->pbo = pbo;
624 else {
625 tile->pixmap =
626 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
627 NULL, 1);
631 tile->w = w;
632 tile->h = h;
633 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
635 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
636 ctm = pagectm (page);
637 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
638 fz_rect_from_irect (bbox), NULL);
639 fz_close_device (state.ctx, dev);
640 fz_drop_device (state.ctx, dev);
642 return tile;
645 #ifdef CACHE_PAGEREFS
646 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
647 thanks to Robin Watts */
648 static void
649 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
651 fz_context *ctx = state.ctx; /* doc->ctx; */
652 pdf_obj *kids;
653 int len;
655 if (state.pdflut.idx == state.pagecount) return;
657 kids = pdf_dict_gets (ctx, node, "Kids");
658 len = pdf_array_len (ctx, kids);
660 if (len == 0)
661 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
663 if (pdf_mark_obj (ctx, node))
664 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
665 for (int i = 0; i < len; i++) {
666 pdf_obj *kid = pdf_array_get (ctx, kids, i);
667 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
668 if (*type
669 ? !strcmp (type, "Pages")
670 : pdf_dict_gets (ctx, kid, "Kids")
671 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
672 pdf_collect_pages (doc, kid);
674 else {
675 if (*type
676 ? strcmp (type, "Page") != 0
677 : !pdf_dict_gets (ctx, kid, "MediaBox"))
678 fz_warn (ctx, "non-page object in page tree (%s)", type);
679 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
682 pdf_unmark_obj (ctx, node);
685 static void
686 pdf_load_page_objs (pdf_document *doc)
688 pdf_obj *root = pdf_dict_gets (state.ctx,
689 pdf_trailer (state.ctx, doc), "Root");
690 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
692 if (!node)
693 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
695 state.pdflut.idx = 0;
696 pdf_collect_pages (doc, node);
698 #endif
700 static void initpdims (void)
702 double start, end;
703 FILE *trimf = NULL;
704 fz_rect rootmediabox = fz_empty_rect;
705 int pageno, trim, show;
706 int trimw = 0, cxcount;
707 fz_context *ctx = state.ctx;
708 pdf_document *pdf = pdf_specifics (ctx, state.doc);
710 fz_var (trimw);
711 fz_var (trimf);
712 fz_var (cxcount);
713 start = now ();
715 if (state.trimmargins && state.trimcachepath) {
716 trimf = fopen (state.trimcachepath, "rb");
717 if (!trimf) {
718 trimf = fopen (state.trimcachepath, "wb");
719 trimw = 1;
723 if (state.trimmargins || pdf)
724 cxcount = state.pagecount;
725 else
726 cxcount = fz_mini (state.pagecount, 1);
728 if (pdf) {
729 pdf_obj *obj;
730 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
731 "Root/Pages/MediaBox");
732 rootmediabox = pdf_to_rect (ctx, obj);
735 #ifdef CACHE_PAGEREFS
736 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
737 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
738 if (!state.pdflut.objs) {
739 err (1, "malloc pageobjs %zu %d %zu failed",
740 sizeof (*state.pdflut.objs), cxcount,
741 sizeof (*state.pdflut.objs) * cxcount);
743 state.pdflut.count = cxcount;
744 pdf_load_page_objs (pdf);
745 state.pdflut.pdf = pdf;
747 #endif
749 for (pageno = 0; pageno < cxcount; ++pageno) {
750 int rotate = 0;
751 struct pagedim *p;
752 fz_rect mediabox = fz_empty_rect;
754 fz_var (rotate);
755 if (pdf) {
756 pdf_obj *pageref, *pageobj;
758 #ifdef CACHE_PAGEREFS
759 pageref = state.pdflut.objs[pageno];
760 #else
761 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
762 #endif
763 pageobj = pdf_resolve_indirect (ctx, pageref);
764 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
766 if (state.trimmargins) {
767 pdf_obj *obj;
768 pdf_page *page;
770 fz_try (ctx) {
771 page = pdf_load_page (ctx, pdf, pageno);
772 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
773 trim = state.trimanew || !obj;
774 if (trim) {
775 fz_rect rect;
776 fz_device *dev;
777 fz_matrix ctm, page_ctm;
779 dev = fz_new_bbox_device (ctx, &rect);
780 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
781 ctm = fz_invert_matrix (page_ctm);
782 pdf_run_page (ctx, page, dev, fz_identity, NULL);
783 fz_close_device (ctx, dev);
784 fz_drop_device (ctx, dev);
786 rect.x0 += state.trimfuzz.x0;
787 rect.x1 += state.trimfuzz.x1;
788 rect.y0 += state.trimfuzz.y0;
789 rect.y1 += state.trimfuzz.y1;
790 rect = fz_transform_rect (rect, ctm);
791 rect = fz_intersect_rect (rect, mediabox);
793 if (!fz_is_empty_rect (rect)) {
794 mediabox = rect;
797 obj = pdf_new_array (ctx, pdf, 4);
798 pdf_array_push (ctx, obj,
799 pdf_new_real (ctx, mediabox.x0));
800 pdf_array_push (ctx, obj,
801 pdf_new_real (ctx, mediabox.y0));
802 pdf_array_push (ctx, obj,
803 pdf_new_real (ctx, mediabox.x1));
804 pdf_array_push (ctx, obj,
805 pdf_new_real (ctx, mediabox.y1));
806 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
808 else {
809 mediabox.x0 = pdf_to_real (ctx,
810 pdf_array_get (ctx, obj, 0));
811 mediabox.y0 = pdf_to_real (ctx,
812 pdf_array_get (ctx, obj, 1));
813 mediabox.x1 = pdf_to_real (ctx,
814 pdf_array_get (ctx, obj, 2));
815 mediabox.y1 = pdf_to_real (ctx,
816 pdf_array_get (ctx, obj, 3));
819 fz_drop_page (ctx, &page->super);
820 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
821 if (show) {
822 printd ("progress %f Trimming %d",
823 (double) (pageno + 1) / state.pagecount,
824 pageno + 1);
827 fz_catch (ctx) {
828 printd ("emsg failed to load page %d", pageno);
831 else {
832 int empty = 0;
833 fz_rect cropbox;
835 mediabox =
836 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "MediaBox"));
837 if (fz_is_empty_rect (mediabox)) {
838 mediabox.x0 = 0;
839 mediabox.y0 = 0;
840 mediabox.x1 = 612;
841 mediabox.y1 = 792;
842 empty = 1;
845 cropbox =
846 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
847 if (!fz_is_empty_rect (cropbox)) {
848 if (empty) {
849 mediabox = cropbox;
851 else {
852 mediabox = fz_intersect_rect (mediabox, cropbox);
855 else {
856 if (empty) {
857 if (fz_is_empty_rect (rootmediabox)) {
858 printd ("emsg cannot find page size for page %d",
859 pageno);
861 else {
862 mediabox = rootmediabox;
868 else {
869 if (state.trimmargins && trimw) {
870 fz_page *page;
872 fz_try (ctx) {
873 page = fz_load_page (ctx, state.doc, pageno);
874 mediabox = fz_bound_page (ctx, page);
875 if (state.trimmargins) {
876 fz_rect rect;
877 fz_device *dev;
879 dev = fz_new_bbox_device (ctx, &rect);
880 fz_run_page (ctx, page, dev, fz_identity, NULL);
881 fz_close_device (ctx, dev);
882 fz_drop_device (ctx, dev);
884 rect.x0 += state.trimfuzz.x0;
885 rect.x1 += state.trimfuzz.x1;
886 rect.y0 += state.trimfuzz.y0;
887 rect.y1 += state.trimfuzz.y1;
888 rect = fz_intersect_rect (rect, mediabox);
890 if (!fz_is_empty_rect (rect)) {
891 mediabox = rect;
894 fz_drop_page (ctx, page);
896 fz_catch (ctx) {
898 if (trimf) {
899 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
900 if (n - 1) {
901 err (1, "fwrite trim mediabox");
905 else {
906 if (trimf) {
907 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
908 if (n - 1) {
909 err (1, "fread trim mediabox %d", pageno);
912 else {
913 fz_page *page;
914 fz_try (ctx) {
915 page = fz_load_page (ctx, state.doc, pageno);
916 mediabox = fz_bound_page (ctx, page);
917 fz_drop_page (ctx, page);
919 show = !state.trimmargins && pageno % 20 == 0;
920 if (show) {
921 printd ("progress %f Gathering dimensions %d",
922 (double) (pageno) / state.pagecount,
923 pageno);
926 fz_catch (ctx) {
927 printd ("emsg failed to load page %d", pageno);
933 if (state.pagedimcount == 0
934 || ((void) (p = &state.pagedims[state.pagedimcount-1])
935 , p->rotate != rotate)
936 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
937 size_t size;
939 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
940 state.pagedims = realloc (state.pagedims, size);
941 if (!state.pagedims) {
942 err (1, "realloc pagedims to %zu (%d elems)",
943 size, state.pagedimcount + 1);
946 p = &state.pagedims[state.pagedimcount++];
947 p->rotate = rotate;
948 p->mediabox = mediabox;
949 p->pageno = pageno;
952 end = now ();
953 printd ("progress 1 %s %d pages in %f seconds",
954 state.trimmargins ? "Trimmed" : "Processed",
955 state.pagecount, end - start);
956 state.trimanew = 0;
957 if (trimf) {
958 if (fclose (trimf)) {
959 err (1, "fclose");
964 static void layout (void)
966 int pindex;
967 fz_rect box;
968 fz_matrix ctm;
969 struct pagedim *p = NULL;
970 float zw, w, maxw = 0.0, zoom = 1.0;
972 if (state.pagedimcount == 0) return;
974 switch (state.fitmodel) {
975 case FitProportional:
976 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
977 float x0, x1;
979 p = &state.pagedims[pindex];
980 box = fz_transform_rect (p->mediabox,
981 fz_rotate (p->rotate + state.rotate));
983 x0 = fz_min (box.x0, box.x1);
984 x1 = fz_max (box.x0, box.x1);
986 w = x1 - x0;
987 maxw = fz_max (w, maxw);
988 zoom = state.w / maxw;
990 break;
992 case FitPage:
993 maxw = state.w;
994 break;
996 case FitWidth:
997 break;
999 default:
1000 ARSERT (0 && state.fitmodel);
1003 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1004 p = &state.pagedims[pindex];
1005 ctm = fz_rotate (state.rotate);
1006 box = fz_transform_rect (p->mediabox,
1007 fz_rotate (p->rotate + state.rotate));
1008 w = box.x1 - box.x0;
1009 switch (state.fitmodel) {
1010 case FitProportional:
1011 p->left = (int) (((maxw - w) * zoom) / 2.f);
1012 break;
1013 case FitPage:
1015 float zh, h;
1016 zw = maxw / w;
1017 h = box.y1 - box.y0;
1018 zh = state.h / h;
1019 zoom = fz_min (zw, zh);
1020 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1022 break;
1023 case FitWidth:
1024 p->left = 0;
1025 zoom = state.w / w;
1026 break;
1029 p->zoomctm = fz_scale (zoom, zoom);
1030 ctm = fz_concat (p->zoomctm, ctm);
1032 p->pagebox = p->mediabox;
1033 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
1034 p->pagebox.x1 -= p->pagebox.x0;
1035 p->pagebox.y1 -= p->pagebox.y0;
1036 p->pagebox.x0 = 0;
1037 p->pagebox.y0 = 0;
1038 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
1039 p->ctm = ctm;
1041 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
1042 fz_scale (zoom, -zoom));
1043 p->tctmready = 0;
1046 do {
1047 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1048 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1049 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1050 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1051 int boundw = x1 - x0;
1052 int boundh = y1 - y0;
1054 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1055 } while (p-- != state.pagedims);
1058 struct pagedim *pdimofpageno (int pageno)
1060 struct pagedim *pdim = state.pagedims;
1062 for (int i = 0; i < state.pagedimcount; ++i) {
1063 if (state.pagedims[i].pageno > pageno)
1064 break;
1065 pdim = &state.pagedims[i];
1067 return pdim;
1070 static void recurse_outline (fz_outline *outline, int level)
1072 while (outline) {
1073 if (outline->page >= 0) {
1074 fz_point p = {.x = outline->x, .y = outline->y};
1075 struct pagedim *pdim = pdimofpageno (outline->page);
1076 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1077 p = fz_transform_point (p, pdim->ctm);
1078 printd ("o %d %d %d %d %s",
1079 level, outline->page, (int) p.y, h, outline->title);
1081 else {
1082 printd ("on %d %s", level, outline->title);
1084 if (outline->down) {
1085 recurse_outline (outline->down, level + 1);
1087 outline = outline->next;
1091 static void process_outline (void)
1093 fz_outline *outline;
1095 if (!state.needoutline || !state.pagedimcount) return;
1097 state.needoutline = 0;
1098 outline = fz_load_outline (state.ctx, state.doc);
1099 if (outline) {
1100 recurse_outline (outline, 0);
1101 fz_drop_outline (state.ctx, outline);
1105 static char *strofline (fz_stext_line *line)
1107 char *p;
1108 char utf8[10];
1109 fz_stext_char *ch;
1110 size_t size = 0, cap = 80;
1112 p = malloc (cap + 1);
1113 if (!p) return NULL;
1115 for (ch = line->first_char; ch; ch = ch->next) {
1116 int n = fz_runetochar (utf8, ch->c);
1117 if (size + n > cap) {
1118 cap *= 2;
1119 p = realloc (p, cap + 1);
1120 if (!p) return NULL;
1123 memcpy (p + size, utf8, n);
1124 size += n;
1126 p[size] = 0;
1127 return p;
1130 static int matchline (regex_t *re, fz_stext_line *line,
1131 int stop, int pageno, double start)
1133 int ret;
1134 char *p;
1135 regmatch_t rm;
1137 p = strofline (line);
1138 if (!p) return -1;
1140 ret = regexec (re, p, 1, &rm, 0);
1141 if (ret) {
1142 free (p);
1143 if (ret != REG_NOMATCH) {
1144 size_t size;
1145 char errbuf[80];
1146 size = regerror (ret, re, errbuf, sizeof (errbuf));
1147 printd ("msg regexec error `%.*s'",
1148 (int) size, errbuf);
1149 return -1;
1151 return 0;
1153 else {
1154 fz_quad s, e;
1155 fz_stext_char *ch;
1156 int o = 0;
1158 for (ch = line->first_char; ch; ch = ch->next) {
1159 o += fz_runelen (ch->c);
1160 if (o > rm.rm_so) {
1161 s = ch->quad;
1162 break;
1165 for (;ch; ch = ch->next) {
1166 o += fz_runelen (ch->c);
1167 if (o > rm.rm_eo) break;
1169 e = ch->quad;
1171 if (!stop) {
1172 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1173 pageno, 1,
1174 s.ul.x, s.ul.y,
1175 e.ur.x, s.ul.y,
1176 e.lr.x, e.lr.y,
1177 s.ul.x, e.lr.y);
1179 printd ("progress 1 found at %d `%.*s' in %f sec",
1180 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1181 now () - start);
1183 else {
1184 printd ("match %d %d %f %f %f %f %f %f %f %f",
1185 pageno, 2,
1186 s.ul.x, s.ul.y,
1187 e.ur.x, s.ul.y,
1188 e.lr.x, e.lr.y,
1189 s.ul.x, e.lr.y);
1191 free (p);
1192 return 1;
1196 /* wishful thinking function */
1197 static void search (regex_t *re, int pageno, int y, int forward)
1199 fz_device *tdev;
1200 fz_stext_page *text;
1201 struct pagedim *pdim;
1202 int stop = 0, niters = 0;
1203 double start, end;
1204 fz_page *page;
1205 fz_stext_block *block;
1207 start = now ();
1208 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1209 if (niters++ == 5) {
1210 niters = 0;
1211 if (hasdata ()) {
1212 printd ("progress 1 attention requested aborting search at %d",
1213 pageno);
1214 stop = 1;
1216 else {
1217 printd ("progress %f searching in page %d",
1218 (double) (pageno + 1) / state.pagecount,
1219 pageno);
1222 pdim = pdimofpageno (pageno);
1223 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1224 tdev = fz_new_stext_device (state.ctx, text, 0);
1226 page = fz_load_page (state.ctx, state.doc, pageno);
1227 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1229 fz_close_device (state.ctx, tdev);
1230 fz_drop_device (state.ctx, tdev);
1232 if (forward) {
1233 for (block = text->first_block; block; block = block->next) {
1234 fz_stext_line *line;
1236 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1237 for (line = block->u.t.first_line; line; line = line->next) {
1238 if (line->bbox.y0 < y + 1) continue;
1240 switch (matchline (re, line, stop, pageno, start)) {
1241 case 0: break;
1242 case 1: stop = 1; break;
1243 case -1: stop = 1; goto endloop;
1248 else {
1249 for (block = text->last_block; block; block = block->prev) {
1250 fz_stext_line *line;
1252 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1253 for (line = block->u.t.last_line; line; line = line->prev) {
1254 if (line->bbox.y0 < y + 1) continue;
1256 switch (matchline (re, line, stop, pageno, start)) {
1257 case 0: break;
1258 case 1: stop = 1; break;
1259 case -1: stop = 1; goto endloop;
1265 if (forward) {
1266 pageno += 1;
1267 y = 0;
1269 else {
1270 pageno -= 1;
1271 y = INT_MAX;
1273 endloop:
1274 fz_drop_stext_page (state.ctx, text);
1275 fz_drop_page (state.ctx, page);
1277 end = now ();
1278 if (!stop) {
1279 printd ("progress 1 no matches %f sec", end - start);
1281 printd ("clearrects");
1284 static void set_tex_params (int colorspace)
1286 switch (colorspace) {
1287 case 0:
1288 state.texiform = GL_RGBA8;
1289 state.texform = GL_RGBA;
1290 state.texty = GL_UNSIGNED_BYTE;
1291 state.colorspace = fz_device_rgb (state.ctx);
1292 break;
1293 case 1:
1294 state.texiform = GL_LUMINANCE_ALPHA;
1295 state.texform = GL_LUMINANCE_ALPHA;
1296 state.texty = GL_UNSIGNED_BYTE;
1297 state.colorspace = fz_device_gray (state.ctx);
1298 break;
1299 default:
1300 errx (1, "invalid colorspce %d", colorspace);
1304 static void realloctexts (int texcount)
1306 size_t size;
1308 if (texcount == state.texcount) return;
1310 if (texcount < state.texcount) {
1311 glDeleteTextures (state.texcount - texcount,
1312 state.texids + texcount);
1315 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1316 state.texids = realloc (state.texids, size);
1317 if (!state.texids) {
1318 err (1, "realloc texs %zu", size);
1321 state.texowners = (void *) (state.texids + texcount);
1322 if (texcount > state.texcount) {
1323 glGenTextures (texcount - state.texcount,
1324 state.texids + state.texcount);
1325 for (int i = state.texcount; i < texcount; ++i) {
1326 state.texowners[i].w = -1;
1327 state.texowners[i].slice = NULL;
1330 state.texcount = texcount;
1331 state.texindex = 0;
1334 static char *mbtoutf8 (char *s)
1336 char *p, *r;
1337 wchar_t *tmp;
1338 size_t i, ret, len;
1340 if (state.utf8cs) {
1341 return s;
1344 len = mbstowcs (NULL, s, strlen (s));
1345 if (len == 0 || len == (size_t) -1) {
1346 if (len)
1347 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1348 return s;
1351 tmp = calloc (len, sizeof (wchar_t));
1352 if (!tmp) {
1353 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1354 len, sizeof (wchar_t), errno, strerror (errno));
1355 return s;
1358 ret = mbstowcs (tmp, s, len);
1359 if (ret == (size_t) -1) {
1360 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1361 len, errno, strerror (errno));
1362 free (tmp);
1363 return s;
1366 len = 0;
1367 for (i = 0; i < ret; ++i) {
1368 len += fz_runelen (tmp[i]);
1371 p = r = malloc (len + 1);
1372 if (!r) {
1373 printd ("emsg mbtoutf8: malloc(%zu)", len);
1374 free (tmp);
1375 return s;
1378 for (i = 0; i < ret; ++i) {
1379 p += fz_runetochar (p, tmp[i]);
1381 *p = 0;
1382 free (tmp);
1383 return r;
1386 CAMLprim value ml_mbtoutf8 (value s_v)
1388 CAMLparam1 (s_v);
1389 CAMLlocal1 (ret_v);
1390 char *s, *r;
1392 s = String_val (s_v);
1393 r = mbtoutf8 (s);
1394 if (r == s) {
1395 ret_v = s_v;
1397 else {
1398 ret_v = caml_copy_string (r);
1399 free (r);
1401 CAMLreturn (ret_v);
1404 static void * mainloop (void UNUSED_ATTR *unused)
1406 char *p = NULL;
1407 int len, ret, oldlen = 0;
1409 fz_var (p);
1410 fz_var (oldlen);
1411 for (;;) {
1412 len = readlen (state.csock);
1413 if (len == 0) {
1414 errx (1, "readlen returned 0");
1417 if (oldlen < len + 1) {
1418 p = realloc (p, len + 1);
1419 if (!p) {
1420 err (1, "realloc %d failed", len + 1);
1422 oldlen = len + 1;
1424 readdata (state.csock, p, len);
1425 p[len] = 0;
1427 if (!strncmp ("open", p, 4)) {
1428 int off, usedoccss, ok = 0, layouth;
1429 char *password;
1430 char *filename;
1431 char *utf8filename;
1432 size_t filenamelen;
1434 fz_var (ok);
1435 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1436 if (ret != 2) {
1437 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1440 filename = p + 5 + off;
1441 filenamelen = strlen (filename);
1442 password = filename + filenamelen + 1;
1444 if (password[strlen (password) + 1]) {
1445 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1448 lock ("open");
1449 fz_set_use_document_css (state.ctx, usedoccss);
1450 fz_try (state.ctx) {
1451 ok = openxref (filename, password, layouth);
1453 fz_catch (state.ctx) {
1454 utf8filename = mbtoutf8 (filename);
1455 printd ("msg Could not open %s", utf8filename);
1456 if (utf8filename != filename) {
1457 free (utf8filename);
1460 if (ok) {
1461 docinfo ();
1462 initpdims ();
1464 unlock ("open");
1466 if (ok) {
1467 utf8filename = mbtoutf8 (filename);
1468 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1469 if (utf8filename != filename) {
1470 free (utf8filename);
1472 state.needoutline = 1;
1475 else if (!strncmp ("cs", p, 2)) {
1476 int i, colorspace;
1478 ret = sscanf (p + 2, " %d", &colorspace);
1479 if (ret != 1) {
1480 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1482 lock ("cs");
1483 set_tex_params (colorspace);
1484 for (i = 0; i < state.texcount; ++i) {
1485 state.texowners[i].w = -1;
1486 state.texowners[i].slice = NULL;
1488 unlock ("cs");
1490 else if (!strncmp ("freepage", p, 8)) {
1491 void *ptr;
1493 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1494 if (ret != 1) {
1495 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1497 lock ("freepage");
1498 freepage (ptr);
1499 unlock ("freepage");
1501 else if (!strncmp ("freetile", p, 8)) {
1502 void *ptr;
1504 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1505 if (ret != 1) {
1506 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1508 lock ("freetile");
1509 freetile (ptr);
1510 unlock ("freetile");
1512 else if (!strncmp ("search", p, 6)) {
1513 int icase, pageno, y, len2, forward;
1514 char *pattern;
1515 regex_t re;
1517 ret = sscanf (p + 6, " %d %d %d %d,%n",
1518 &icase, &pageno, &y, &forward, &len2);
1519 if (ret != 4) {
1520 errx (1, "malformed search `%s' ret=%d", p, ret);
1523 pattern = p + 6 + len2;
1524 ret = regcomp (&re, pattern,
1525 REG_EXTENDED | (icase ? REG_ICASE : 0));
1526 if (ret) {
1527 char errbuf[80];
1528 size_t size;
1530 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1531 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1533 else {
1534 search (&re, pageno, y, forward);
1535 regfree (&re);
1538 else if (!strncmp ("geometry", p, 8)) {
1539 int w, h, fitmodel;
1541 printd ("clear");
1542 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1543 if (ret != 3) {
1544 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1547 lock ("geometry");
1548 state.h = h;
1549 if (w != state.w) {
1550 state.w = w;
1551 for (int i = 0; i < state.texcount; ++i) {
1552 state.texowners[i].slice = NULL;
1555 state.fitmodel = fitmodel;
1556 layout ();
1557 process_outline ();
1559 state.gen++;
1560 unlock ("geometry");
1561 printd ("continue %d", state.pagecount);
1563 else if (!strncmp ("reqlayout", p, 9)) {
1564 char *nameddest;
1565 int rotate, off, h;
1566 int fitmodel;
1567 pdf_document *pdf;
1569 printd ("clear");
1570 ret = sscanf (p + 9, " %d %d %d %n",
1571 &rotate, &fitmodel, &h, &off);
1572 if (ret != 3) {
1573 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1575 lock ("reqlayout");
1576 pdf = pdf_specifics (state.ctx, state.doc);
1577 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1578 state.gen += 1;
1580 state.rotate = rotate;
1581 state.fitmodel = fitmodel;
1582 state.h = h;
1583 layout ();
1584 process_outline ();
1586 nameddest = p + 9 + off;
1587 if (pdf && nameddest && *nameddest) {
1588 fz_point xy;
1589 struct pagedim *pdim;
1590 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1591 &xy.x, &xy.y);
1592 pdim = pdimofpageno (pageno);
1593 xy = fz_transform_point (xy, pdim->ctm);
1594 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1597 state.gen++;
1598 unlock ("reqlayout");
1599 printd ("continue %d", state.pagecount);
1601 else if (!strncmp ("page", p, 4)) {
1602 double a, b;
1603 struct page *page;
1604 int pageno, pindex;
1606 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1607 if (ret != 2) {
1608 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1611 lock ("page");
1612 a = now ();
1613 page = loadpage (pageno, pindex);
1614 b = now ();
1615 unlock ("page");
1617 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1619 else if (!strncmp ("tile", p, 4)) {
1620 int x, y, w, h;
1621 struct page *page;
1622 struct tile *tile;
1623 double a, b;
1624 void *data;
1626 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1627 (uintptr_t *) &page, &x, &y, &w, &h,
1628 (uintptr_t *) &data);
1629 if (ret != 6) {
1630 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1633 lock ("tile");
1634 a = now ();
1635 tile = rendertile (page, x, y, w, h, data);
1636 b = now ();
1637 unlock ("tile");
1639 printd ("tile %d %d %" PRIxPTR " %u %f",
1640 x, y, (uintptr_t) (tile),
1641 tile->w * tile->h * tile->pixmap->n,
1642 b - a);
1644 else if (!strncmp ("trimset", p, 7)) {
1645 fz_irect fuzz;
1646 int trimmargins;
1648 ret = sscanf (p + 7, " %d %d %d %d %d",
1649 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1650 if (ret != 5) {
1651 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1653 lock ("trimset");
1654 state.trimmargins = trimmargins;
1655 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1656 state.trimanew = 1;
1657 state.trimfuzz = fuzz;
1659 unlock ("trimset");
1661 else if (!strncmp ("settrim", p, 7)) {
1662 fz_irect fuzz;
1663 int trimmargins;
1665 ret = sscanf (p + 7, " %d %d %d %d %d",
1666 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1667 if (ret != 5) {
1668 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1670 printd ("clear");
1671 lock ("settrim");
1672 state.trimmargins = trimmargins;
1673 state.needoutline = 1;
1674 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1675 state.trimanew = 1;
1676 state.trimfuzz = fuzz;
1678 state.pagedimcount = 0;
1679 free (state.pagedims);
1680 state.pagedims = NULL;
1681 initpdims ();
1682 layout ();
1683 process_outline ();
1684 unlock ("settrim");
1685 printd ("continue %d", state.pagecount);
1687 else if (!strncmp ("sliceh", p, 6)) {
1688 int h;
1690 ret = sscanf (p + 6, " %d", &h);
1691 if (ret != 1) {
1692 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1694 if (h != state.sliceheight) {
1695 state.sliceheight = h;
1696 for (int i = 0; i < state.texcount; ++i) {
1697 state.texowners[i].w = -1;
1698 state.texowners[i].h = -1;
1699 state.texowners[i].slice = NULL;
1703 else if (!strncmp ("interrupt", p, 9)) {
1704 printd ("vmsg interrupted");
1706 else {
1707 errx (1, "unknown command %.*s", len, p);
1710 return 0;
1713 CAMLprim 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 CAMLprim value ml_uritolocation (value uri_v)
1722 CAMLparam1 (uri_v);
1723 CAMLlocal1 (ret_v);
1724 int pageno;
1725 fz_point xy;
1726 struct pagedim *pdim;
1728 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1729 &xy.x, &xy.y);
1730 pdim = pdimofpageno (pageno);
1731 xy = fz_transform_point (xy, pdim->ctm);
1732 ret_v = caml_alloc_tuple (3);
1733 Field (ret_v, 0) = Val_int (pageno);
1734 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1735 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1736 CAMLreturn (ret_v);
1739 CAMLprim value ml_realloctexts (value texcount_v)
1741 CAMLparam1 (texcount_v);
1742 int ok;
1744 if (trylock (__func__)) {
1745 ok = 0;
1746 goto done;
1748 realloctexts (Int_val (texcount_v));
1749 ok = 1;
1750 unlock (__func__);
1752 done:
1753 CAMLreturn (Val_bool (ok));
1756 static void recti (int x0, int y0, int x1, int y1)
1758 GLfloat *v = state.vertices;
1760 glVertexPointer (2, GL_FLOAT, 0, v);
1761 v[0] = x0; v[1] = y0;
1762 v[2] = x1; v[3] = y0;
1763 v[4] = x0; v[5] = y1;
1764 v[6] = x1; v[7] = y1;
1765 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1768 static void showsel (struct page *page, int ox, int oy)
1770 fz_irect bbox;
1771 fz_rect rect;
1772 fz_stext_block *block;
1773 int seen = 0;
1774 unsigned char selcolor[] = {15,15,15,140};
1776 if (!page->fmark || !page->lmark) return;
1778 glEnable (GL_BLEND);
1779 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1780 glColor4ubv (selcolor);
1782 ox += state.pagedims[page->pdimno].bounds.x0;
1783 oy += state.pagedims[page->pdimno].bounds.y0;
1785 for (block = page->text->first_block; block; block = block->next) {
1786 fz_stext_line *line;
1788 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1789 for (line = block->u.t.first_line; line; line = line->next) {
1790 fz_stext_char *ch;
1792 rect = fz_empty_rect;
1793 for (ch = line->first_char; ch; ch = ch->next) {
1794 fz_rect r;
1795 if (ch == page->fmark) seen = 1;
1796 r = fz_rect_from_quad (ch->quad);
1797 if (seen) rect = fz_union_rect (rect, r);
1798 if (ch == page->lmark) {
1799 bbox = fz_round_rect (rect);
1800 recti (bbox.x0 + ox, bbox.y0 + oy,
1801 bbox.x1 + ox, bbox.y1 + oy);
1802 goto done;
1805 bbox = fz_round_rect (rect);
1806 recti (bbox.x0 + ox, bbox.y0 + oy,
1807 bbox.x1 + ox, bbox.y1 + oy);
1810 done:
1811 glDisable (GL_BLEND);
1814 #pragma GCC diagnostic push
1815 #pragma GCC diagnostic ignored "-Wconversion"
1816 #include "glfont.c"
1817 #pragma GCC diagnostic pop
1819 static void stipplerect (fz_matrix m,
1820 fz_point p1,
1821 fz_point p2,
1822 fz_point p3,
1823 fz_point p4,
1824 GLfloat *texcoords,
1825 GLfloat *vertices)
1827 p1 = fz_transform_point (p1, m);
1828 p2 = fz_transform_point (p2, m);
1829 p3 = fz_transform_point (p3, m);
1830 p4 = fz_transform_point (p4, m);
1832 float w, h, s, t;
1834 w = p2.x - p1.x;
1835 h = p2.y - p1.y;
1836 t = hypotf (w, h) * .25f;
1838 w = p3.x - p2.x;
1839 h = p3.y - p2.y;
1840 s = hypotf (w, h) * .25f;
1842 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1843 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1845 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1846 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1848 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1849 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1851 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1852 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1854 glDrawArrays (GL_LINES, 0, 8);
1857 static void solidrect (fz_matrix m,
1858 fz_point p1,
1859 fz_point p2,
1860 fz_point p3,
1861 fz_point p4,
1862 GLfloat *vertices)
1864 p1 = fz_transform_point (p1, m);
1865 p2 = fz_transform_point (p2, m);
1866 p3 = fz_transform_point (p3, m);
1867 p4 = fz_transform_point (p4, m);
1868 vertices[0] = p1.x; vertices[1] = p1.y;
1869 vertices[2] = p2.x; vertices[3] = p2.y;
1871 vertices[4] = p3.x; vertices[5] = p3.y;
1872 vertices[6] = p4.x; vertices[7] = p4.y;
1873 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1876 static void ensurelinks (struct page *page)
1878 if (!page->links)
1879 page->links = fz_load_links (state.ctx, page->fzpage);
1882 static void highlightlinks (struct page *page, int xoff, int yoff)
1884 fz_matrix ctm;
1885 fz_link *link;
1886 GLfloat *texcoords = state.texcoords;
1887 GLfloat *vertices = state.vertices;
1889 ensurelinks (page);
1891 glEnable (GL_TEXTURE_1D);
1892 glEnable (GL_BLEND);
1893 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1894 glBindTexture (GL_TEXTURE_1D, state.stid);
1896 xoff -= state.pagedims[page->pdimno].bounds.x0;
1897 yoff -= state.pagedims[page->pdimno].bounds.y0;
1898 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1900 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1901 glVertexPointer (2, GL_FLOAT, 0, vertices);
1903 for (link = page->links; link; link = link->next) {
1904 fz_point p1, p2, p3, p4;
1906 p1.x = link->rect.x0;
1907 p1.y = link->rect.y0;
1909 p2.x = link->rect.x1;
1910 p2.y = link->rect.y0;
1912 p3.x = link->rect.x1;
1913 p3.y = link->rect.y1;
1915 p4.x = link->rect.x0;
1916 p4.y = link->rect.y1;
1918 /* TODO: different colours for different schemes */
1919 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1920 else glColor3ub (255, 0, 0);
1922 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1925 for (int i = 0; i < page->annotcount; ++i) {
1926 fz_point p1, p2, p3, p4;
1927 struct annot *annot = &page->annots[i];
1929 p1.x = annot->bbox.x0;
1930 p1.y = annot->bbox.y0;
1932 p2.x = annot->bbox.x1;
1933 p2.y = annot->bbox.y0;
1935 p3.x = annot->bbox.x1;
1936 p3.y = annot->bbox.y1;
1938 p4.x = annot->bbox.x0;
1939 p4.y = annot->bbox.y1;
1941 glColor3ub (0, 0, 128);
1942 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1945 glDisable (GL_BLEND);
1946 glDisable (GL_TEXTURE_1D);
1949 static int compareslinks (const void *l, const void *r)
1951 struct slink const *ls = l;
1952 struct slink const *rs = r;
1953 if (ls->bbox.y0 == rs->bbox.y0) {
1954 return rs->bbox.x0 - rs->bbox.x0;
1956 return ls->bbox.y0 - rs->bbox.y0;
1959 static void droptext (struct page *page)
1961 if (page->text) {
1962 fz_drop_stext_page (state.ctx, page->text);
1963 page->fmark = NULL;
1964 page->lmark = NULL;
1965 page->text = NULL;
1969 static void dropannots (struct page *page)
1971 if (page->annots) {
1972 free (page->annots);
1973 page->annots = NULL;
1974 page->annotcount = 0;
1978 static void ensureannots (struct page *page)
1980 int i, count = 0;
1981 size_t annotsize = sizeof (*page->annots);
1982 fz_annot *annot;
1984 if (state.gen != page->agen) {
1985 dropannots (page);
1986 page->agen = state.gen;
1988 if (page->annots) return;
1990 for (annot = fz_first_annot (state.ctx, page->fzpage);
1991 annot;
1992 annot = fz_next_annot (state.ctx, annot)) {
1993 count++;
1996 if (count > 0) {
1997 page->annotcount = count;
1998 page->annots = calloc (count, annotsize);
1999 if (!page->annots) {
2000 err (1, "calloc annots %d", count);
2003 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2004 annot;
2005 annot = fz_next_annot (state.ctx, annot), i++) {
2006 fz_rect rect;
2008 rect = fz_bound_annot (state.ctx, annot);
2009 page->annots[i].annot = annot;
2010 page->annots[i].bbox = fz_round_rect (rect);
2015 static void dropslinks (struct page *page)
2017 if (page->slinks) {
2018 free (page->slinks);
2019 page->slinks = NULL;
2020 page->slinkcount = 0;
2022 if (page->links) {
2023 fz_drop_link (state.ctx, page->links);
2024 page->links = NULL;
2028 static void ensureslinks (struct page *page)
2030 fz_matrix ctm;
2031 int i, count;
2032 size_t slinksize = sizeof (*page->slinks);
2033 fz_link *link;
2035 ensureannots (page);
2036 if (state.gen != page->sgen) {
2037 dropslinks (page);
2038 page->sgen = state.gen;
2040 if (page->slinks) return;
2042 ensurelinks (page);
2043 ctm = pagectm (page);
2045 count = page->annotcount;
2046 for (link = page->links; link; link = link->next) {
2047 count++;
2049 if (count > 0) {
2050 int j;
2052 page->slinkcount = count;
2053 page->slinks = calloc (count, slinksize);
2054 if (!page->slinks) {
2055 err (1, "calloc slinks %d", count);
2058 for (i = 0, link = page->links; link; ++i, link = link->next) {
2059 fz_rect rect;
2061 rect = link->rect;
2062 rect = fz_transform_rect (rect, ctm);
2063 page->slinks[i].tag = SLINK;
2064 page->slinks[i].u.link = link;
2065 page->slinks[i].bbox = fz_round_rect (rect);
2067 for (j = 0; j < page->annotcount; ++j, ++i) {
2068 fz_rect rect;
2069 rect = fz_bound_annot (state.ctx, page->annots[j].annot);
2070 rect = fz_transform_rect (rect, ctm);
2071 page->slinks[i].bbox = fz_round_rect (rect);
2073 page->slinks[i].tag = SANNOT;
2074 page->slinks[i].u.annot = page->annots[j].annot;
2076 qsort (page->slinks, count, slinksize, compareslinks);
2080 static void highlightslinks (struct page *page, int xoff, int yoff,
2081 int noff, char *targ, mlsize_t tlen, int hfsize)
2083 char buf[40];
2084 struct slink *slink;
2085 float x0, y0, x1, y1, w;
2087 ensureslinks (page);
2088 glColor3ub (0xc3, 0xb0, 0x91);
2089 for (int i = 0; i < page->slinkcount; ++i) {
2090 fmt_linkn (buf, i + noff);
2091 if (!tlen || !strncmp (targ, buf, tlen)) {
2092 slink = &page->slinks[i];
2094 x0 = slink->bbox.x0 + xoff - 5;
2095 y1 = slink->bbox.y0 + yoff - 5;
2096 y0 = y1 + 10 + hfsize;
2097 w = measure_string (state.face, hfsize, buf);
2098 x1 = x0 + w + 10;
2099 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2103 glEnable (GL_BLEND);
2104 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2105 glEnable (GL_TEXTURE_2D);
2106 glColor3ub (0, 0, 0);
2107 for (int i = 0; i < page->slinkcount; ++i) {
2108 fmt_linkn (buf, i + noff);
2109 if (!tlen || !strncmp (targ, buf, tlen)) {
2110 slink = &page->slinks[i];
2112 x0 = slink->bbox.x0 + xoff;
2113 y0 = slink->bbox.y0 + yoff + hfsize;
2114 draw_string (state.face, hfsize, x0, y0, buf);
2117 glDisable (GL_TEXTURE_2D);
2118 glDisable (GL_BLEND);
2121 static void uploadslice (struct tile *tile, struct slice *slice)
2123 int offset;
2124 struct slice *slice1;
2125 unsigned char *texdata;
2127 offset = 0;
2128 for (slice1 = tile->slices; slice != slice1; slice1++) {
2129 offset += slice1->h * tile->w * tile->pixmap->n;
2131 if (slice->texindex != -1 && slice->texindex < state.texcount
2132 && state.texowners[slice->texindex].slice == slice) {
2133 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2135 else {
2136 int subimage = 0;
2137 int texindex = state.texindex++ % state.texcount;
2139 if (state.texowners[texindex].w == tile->w) {
2140 if (state.texowners[texindex].h >= slice->h) {
2141 subimage = 1;
2143 else {
2144 state.texowners[texindex].h = slice->h;
2147 else {
2148 state.texowners[texindex].h = slice->h;
2151 state.texowners[texindex].w = tile->w;
2152 state.texowners[texindex].slice = slice;
2153 slice->texindex = texindex;
2155 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2156 #if TEXT_TYPE == GL_TEXTURE_2D
2157 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2158 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2159 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2160 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2161 #endif
2162 if (tile->pbo) {
2163 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2164 texdata = 0;
2166 else {
2167 texdata = tile->pixmap->samples;
2169 if (subimage) {
2170 glTexSubImage2D (TEXT_TYPE,
2174 tile->w,
2175 slice->h,
2176 state.texform,
2177 state.texty,
2178 texdata+offset
2181 else {
2182 glTexImage2D (TEXT_TYPE,
2184 state.texiform,
2185 tile->w,
2186 slice->h,
2188 state.texform,
2189 state.texty,
2190 texdata+offset
2193 if (tile->pbo) {
2194 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2199 CAMLprim void ml_begintiles (void)
2201 glEnable (TEXT_TYPE);
2202 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2203 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2206 CAMLprim void ml_endtiles (void)
2208 glDisable (TEXT_TYPE);
2211 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2213 CAMLparam2 (args_v, ptr_v);
2214 int dispx = Int_val (Field (args_v, 0));
2215 int dispy = Int_val (Field (args_v, 1));
2216 int dispw = Int_val (Field (args_v, 2));
2217 int disph = Int_val (Field (args_v, 3));
2218 int tilex = Int_val (Field (args_v, 4));
2219 int tiley = Int_val (Field (args_v, 5));
2220 char *s = String_val (ptr_v);
2221 struct tile *tile = parse_pointer (__func__, s);
2222 int slicey, firstslice;
2223 struct slice *slice;
2224 GLfloat *texcoords = state.texcoords;
2225 GLfloat *vertices = state.vertices;
2227 firstslice = tiley / tile->sliceheight;
2228 slice = &tile->slices[firstslice];
2229 slicey = tiley % tile->sliceheight;
2231 while (disph > 0) {
2232 int dh;
2234 dh = slice->h - slicey;
2235 dh = fz_mini (disph, dh);
2236 uploadslice (tile, slice);
2238 texcoords[0] = tilex; texcoords[1] = slicey;
2239 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2240 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2241 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2243 vertices[0] = dispx; vertices[1] = dispy;
2244 vertices[2] = dispx+dispw; vertices[3] = dispy;
2245 vertices[4] = dispx; vertices[5] = dispy+dh;
2246 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2248 #if TEXT_TYPE == GL_TEXTURE_2D
2249 for (int i = 0; i < 8; ++i) {
2250 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2252 #endif
2254 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2255 dispy += dh;
2256 disph -= dh;
2257 slice++;
2258 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2259 slicey = 0;
2261 CAMLreturn0;
2264 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2266 fz_matrix ctm;
2267 fz_point p1, p2, p3, p4;
2268 GLfloat *vertices = state.vertices;
2269 double *v = (double *) rects_v;
2271 xoff -= state.pagedims[page->pdimno].bounds.x0;
2272 yoff -= state.pagedims[page->pdimno].bounds.y0;
2273 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2275 glEnable (GL_BLEND);
2276 glVertexPointer (2, GL_FLOAT, 0, vertices);
2278 glColor4dv (v);
2279 p1.x = (float) v[4];
2280 p1.y = (float) v[5];
2282 p2.x = (float) v[6];
2283 p2.y = (float) v[5];
2285 p3.x = (float) v[6];
2286 p3.y = (float) v[7];
2288 p4.x = (float) v[4];
2289 p4.y = (float) v[7];
2290 solidrect (ctm, p1, p2, p3, p4, vertices);
2291 glDisable (GL_BLEND);
2294 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2295 value xoff_v, value yoff_v,
2296 value li_v)
2298 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2299 int xoff = Int_val (xoff_v);
2300 int yoff = Int_val (yoff_v);
2301 int noff = Int_val (Field (li_v, 0));
2302 char *targ = String_val (Field (li_v, 1));
2303 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2304 int hfsize = Int_val (Field (li_v, 2));
2305 char *s = String_val (ptr_v);
2306 int hlmask = Int_val (hlinks_v);
2307 struct page *page = parse_pointer (__func__, s);
2309 if (!page->fzpage) {
2310 /* deal with loadpage failed pages */
2311 goto done;
2314 if (trylock (__func__)) {
2315 noff = -1;
2316 goto done;
2319 ensureannots (page);
2320 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2321 if (hlmask & 2) {
2322 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2323 noff = page->slinkcount;
2325 if (page->tgen == state.gen) {
2326 showsel (page, xoff, yoff);
2328 unlock (__func__);
2330 done:
2331 CAMLreturn (Val_int (noff));
2334 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2335 value rects_v)
2337 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2338 int xoff = Int_val (xoff_v);
2339 int yoff = Int_val (yoff_v);
2340 char *s = String_val (ptr_v);
2341 struct page *page = parse_pointer (__func__, s);
2343 drawprect (page, xoff, yoff, rects_v);
2344 CAMLreturn0;
2347 static struct annot *getannot (struct page *page, int x, int y)
2349 fz_point p;
2350 fz_matrix ctm;
2351 const fz_matrix *tctm;
2352 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2354 if (!page->annots) return NULL;
2356 if (pdf) {
2357 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2358 tctm = &state.pagedims[page->pdimno].tctm;
2360 else {
2361 tctm = &fz_identity;
2364 p.x = x;
2365 p.y = y;
2367 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2368 ctm = fz_invert_matrix (ctm);
2369 p = fz_transform_point (p, ctm);
2371 if (pdf) {
2372 for (int i = 0; i < page->annotcount; ++i) {
2373 struct annot *a = &page->annots[i];
2374 fz_rect rect;
2376 rect = fz_bound_annot (state.ctx, a->annot);
2377 if (p.x >= rect.x0 && p.x <= rect.x1) {
2378 if (p.y >= rect.y0 && p.y <= rect.y1)
2379 return a;
2383 return NULL;
2386 static fz_link *getlink (struct page *page, int x, int y)
2388 fz_point p;
2389 fz_link *link;
2391 ensureslinks (page);
2393 p.x = x;
2394 p.y = y;
2396 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2398 for (link = page->links; link; link = link->next) {
2399 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2400 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2401 return link;
2405 return NULL;
2408 static void ensuretext (struct page *page)
2410 if (state.gen != page->tgen) {
2411 droptext (page);
2412 page->tgen = state.gen;
2414 if (!page->text) {
2415 fz_device *tdev;
2417 page->text = fz_new_stext_page (state.ctx,
2418 state.pagedims[page->pdimno].mediabox);
2419 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2420 fz_run_display_list (state.ctx, page->dlist,
2421 tdev, pagectm (page), fz_infinite_rect, NULL);
2422 fz_close_device (state.ctx, tdev);
2423 fz_drop_device (state.ctx, tdev);
2427 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2429 CAMLparam2 (start_page_v, dir_v);
2430 CAMLlocal1 (ret_v);
2431 int i, dir = Int_val (dir_v);
2432 int start_page = Int_val (start_page_v);
2433 int end_page = dir > 0 ? state.pagecount : -1;
2434 pdf_document *pdf;
2436 fz_var (end_page);
2437 ret_v = Val_int (0);
2438 lock (__func__);
2439 pdf = pdf_specifics (state.ctx, state.doc);
2440 for (i = start_page + dir; i != end_page; i += dir) {
2441 int found;
2443 fz_var (found);
2444 if (pdf) {
2445 pdf_page *page = NULL;
2447 fz_var (page);
2448 fz_try (state.ctx) {
2449 page = pdf_load_page (state.ctx, pdf, i);
2450 found = !!page->links || !!page->annots;
2452 fz_catch (state.ctx) {
2453 found = 0;
2455 if (page) {
2456 fz_drop_page (state.ctx, &page->super);
2459 else {
2460 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2461 fz_link *link = fz_load_links (state.ctx, page);
2462 found = !!link;
2463 fz_drop_link (state.ctx, link);
2464 fz_drop_page (state.ctx, page);
2467 if (found) {
2468 ret_v = caml_alloc_small (1, 1);
2469 Field (ret_v, 0) = Val_int (i);
2470 goto unlock;
2473 unlock:
2474 unlock (__func__);
2475 CAMLreturn (ret_v);
2478 enum { dir_first, dir_last };
2479 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2481 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2483 CAMLparam2 (ptr_v, dir_v);
2484 CAMLlocal2 (ret_v, pos_v);
2485 struct page *page;
2486 int dirtag, i, slinkindex;
2487 struct slink *found = NULL ,*slink;
2488 char *s = String_val (ptr_v);
2490 page = parse_pointer (__func__, s);
2491 ret_v = Val_int (0);
2492 lock (__func__);
2493 ensureslinks (page);
2495 if (Is_block (dir_v)) {
2496 dirtag = Tag_val (dir_v);
2497 switch (dirtag) {
2498 case dir_first_visible:
2500 int x0, y0, dir, first_index, last_index;
2502 pos_v = Field (dir_v, 0);
2503 x0 = Int_val (Field (pos_v, 0));
2504 y0 = Int_val (Field (pos_v, 1));
2505 dir = Int_val (Field (pos_v, 2));
2507 if (dir >= 0) {
2508 dir = 1;
2509 first_index = 0;
2510 last_index = page->slinkcount;
2512 else {
2513 first_index = page->slinkcount - 1;
2514 last_index = -1;
2517 for (i = first_index; i != last_index; i += dir) {
2518 slink = &page->slinks[i];
2519 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2520 found = slink;
2521 break;
2525 break;
2527 case dir_left:
2528 slinkindex = Int_val (Field (dir_v, 0));
2529 found = &page->slinks[slinkindex];
2530 for (i = slinkindex - 1; i >= 0; --i) {
2531 slink = &page->slinks[i];
2532 if (slink->bbox.x0 < found->bbox.x0) {
2533 found = slink;
2534 break;
2537 break;
2539 case dir_right:
2540 slinkindex = Int_val (Field (dir_v, 0));
2541 found = &page->slinks[slinkindex];
2542 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2543 slink = &page->slinks[i];
2544 if (slink->bbox.x0 > found->bbox.x0) {
2545 found = slink;
2546 break;
2549 break;
2551 case dir_down:
2552 slinkindex = Int_val (Field (dir_v, 0));
2553 found = &page->slinks[slinkindex];
2554 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2555 slink = &page->slinks[i];
2556 if (slink->bbox.y0 >= found->bbox.y0) {
2557 found = slink;
2558 break;
2561 break;
2563 case dir_up:
2564 slinkindex = Int_val (Field (dir_v, 0));
2565 found = &page->slinks[slinkindex];
2566 for (i = slinkindex - 1; i >= 0; --i) {
2567 slink = &page->slinks[i];
2568 if (slink->bbox.y0 <= found->bbox.y0) {
2569 found = slink;
2570 break;
2573 break;
2576 else {
2577 dirtag = Int_val (dir_v);
2578 switch (dirtag) {
2579 case dir_first:
2580 found = page->slinks;
2581 break;
2583 case dir_last:
2584 if (page->slinks) {
2585 found = page->slinks + (page->slinkcount - 1);
2587 break;
2590 if (found) {
2591 ret_v = caml_alloc_small (2, 1);
2592 Field (ret_v, 0) = Val_int (found - page->slinks);
2595 unlock (__func__);
2596 CAMLreturn (ret_v);
2599 enum { uuri, utext, uannot };
2601 CAMLprim value ml_getlink (value ptr_v, value n_v)
2603 CAMLparam2 (ptr_v, n_v);
2604 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2605 fz_link *link;
2606 struct page *page;
2607 char *s = String_val (ptr_v);
2608 struct slink *slink;
2610 ret_v = Val_int (0);
2611 page = parse_pointer (__func__, s);
2613 lock (__func__);
2614 ensureslinks (page);
2615 slink = &page->slinks[Int_val (n_v)];
2616 if (slink->tag == SLINK) {
2617 link = slink->u.link;
2618 str_v = caml_copy_string (link->uri);
2619 ret_v = caml_alloc_small (1, uuri);
2620 Field (ret_v, 0) = str_v;
2622 else {
2623 ret_v = caml_alloc_small (1, uannot);
2624 tup_v = caml_alloc_tuple (2);
2625 Field (ret_v, 0) = tup_v;
2626 Field (tup_v, 0) = ptr_v;
2627 Field (tup_v, 1) = n_v;
2629 unlock (__func__);
2631 CAMLreturn (ret_v);
2634 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2636 CAMLparam2 (ptr_v, n_v);
2637 CAMLlocal1 (ret_v);
2638 pdf_document *pdf;
2639 const char *contents = "";
2641 lock (__func__);
2642 pdf = pdf_specifics (state.ctx, state.doc);
2643 if (pdf) {
2644 char *s = String_val (ptr_v);
2645 struct page *page;
2646 struct slink *slink;
2648 page = parse_pointer (__func__, s);
2649 slink = &page->slinks[Int_val (n_v)];
2650 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2652 unlock (__func__);
2653 ret_v = caml_copy_string (contents);
2654 CAMLreturn (ret_v);
2657 CAMLprim value ml_getlinkcount (value ptr_v)
2659 CAMLparam1 (ptr_v);
2660 struct page *page;
2661 char *s = String_val (ptr_v);
2663 page = parse_pointer (__func__, s);
2664 CAMLreturn (Val_int (page->slinkcount));
2667 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2669 CAMLparam2 (ptr_v, n_v);
2670 CAMLlocal1 (ret_v);
2671 struct page *page;
2672 struct slink *slink;
2673 char *s = String_val (ptr_v);
2675 page = parse_pointer (__func__, s);
2676 ret_v = caml_alloc_tuple (4);
2677 lock (__func__);
2678 ensureslinks (page);
2680 slink = &page->slinks[Int_val (n_v)];
2681 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2682 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2683 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2684 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2685 unlock (__func__);
2686 CAMLreturn (ret_v);
2689 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2691 CAMLparam3 (ptr_v, x_v, y_v);
2692 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2693 fz_link *link;
2694 struct annot *annot;
2695 struct page *page;
2696 char *ptr = String_val (ptr_v);
2697 int x = Int_val (x_v), y = Int_val (y_v);
2698 struct pagedim *pdim;
2700 ret_v = Val_int (0);
2701 if (trylock (__func__)) {
2702 goto done;
2705 page = parse_pointer (__func__, ptr);
2706 pdim = &state.pagedims[page->pdimno];
2707 x += pdim->bounds.x0;
2708 y += pdim->bounds.y0;
2711 annot = getannot (page, x, y);
2712 if (annot) {
2713 int i, n = -1;
2715 ensureslinks (page);
2716 for (i = 0; i < page->slinkcount; ++i) {
2717 if (page->slinks[i].tag == SANNOT
2718 && page->slinks[i].u.annot == annot->annot) {
2719 n = i;
2720 break;
2723 ret_v = caml_alloc_small (1, uannot);
2724 tup_v = caml_alloc_tuple (2);
2725 Field (ret_v, 0) = tup_v;
2726 Field (tup_v, 0) = ptr_v;
2727 Field (tup_v, 1) = Val_int (n);
2728 goto unlock;
2732 link = getlink (page, x, y);
2733 if (link) {
2734 str_v = caml_copy_string (link->uri);
2735 ret_v = caml_alloc_small (1, uuri);
2736 Field (ret_v, 0) = str_v;
2738 else {
2739 fz_rect *b;
2740 fz_stext_block *block;
2742 ensuretext (page);
2744 for (block = page->text->first_block; block; block = block->next) {
2745 fz_stext_line *line;
2747 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2748 b = &block->bbox;
2749 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2750 continue;
2752 for (line = block->u.t.first_line; line; line = line->next) {
2753 fz_stext_char *ch;
2755 b = &line->bbox;
2756 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2757 continue;
2759 for (ch = line->first_char; ch; ch = ch->next) {
2760 fz_quad *q = &ch->quad;
2762 if (x >= q->ul.x && x <= q->ur.x
2763 && y >= q->ul.y && y <= q->ll.y) {
2764 const char *n2 = fz_font_name (state.ctx, ch->font);
2765 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2766 ch->font);
2768 if (!n2) n2 = "<unknown font>";
2770 if (face && face->family_name) {
2771 char *s;
2772 char *n1 = face->family_name;
2773 size_t l1 = strlen (n1);
2774 size_t l2 = strlen (n2);
2776 if (l1 != l2 || memcmp (n1, n2, l1)) {
2777 s = malloc (l1 + l2 + 2);
2778 if (s) {
2779 memcpy (s, n2, l2);
2780 s[l2] = '=';
2781 memcpy (s + l2 + 1, n1, l1 + 1);
2782 str_v = caml_copy_string (s);
2783 free (s);
2787 if (str_v == Val_unit) {
2788 str_v = caml_copy_string (n2);
2790 ret_v = caml_alloc_small (1, utext);
2791 Field (ret_v, 0) = str_v;
2792 goto unlock;
2798 unlock:
2799 unlock (__func__);
2801 done:
2802 CAMLreturn (ret_v);
2805 enum { mark_page, mark_block, mark_line, mark_word };
2807 CAMLprim void ml_clearmark (value ptr_v)
2809 CAMLparam1 (ptr_v);
2810 char *s = String_val (ptr_v);
2811 struct page *page;
2813 if (trylock (__func__)) {
2814 goto done;
2817 page = parse_pointer (__func__, s);
2818 page->fmark = NULL;
2819 page->lmark = NULL;
2821 unlock (__func__);
2822 done:
2823 CAMLreturn0;
2826 static int uninteresting (int c)
2828 return isspace (c) || ispunct (c);
2831 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2833 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2834 CAMLlocal1 (ret_v);
2835 fz_rect *b;
2836 struct page *page;
2837 fz_stext_line *line;
2838 fz_stext_block *block;
2839 struct pagedim *pdim;
2840 int mark = Int_val (mark_v);
2841 char *s = String_val (ptr_v);
2842 int x = Int_val (x_v), y = Int_val (y_v);
2844 ret_v = Val_bool (0);
2845 if (trylock (__func__)) {
2846 goto done;
2849 page = parse_pointer (__func__, s);
2850 pdim = &state.pagedims[page->pdimno];
2852 ensuretext (page);
2854 if (mark == mark_page) {
2855 page->fmark = page->text->first_block->u.t.first_line->first_char;
2856 page->lmark = page->text->last_block->u.t.last_line->last_char;
2857 ret_v = Val_bool (1);
2858 goto unlock;
2861 x += pdim->bounds.x0;
2862 y += pdim->bounds.y0;
2864 for (block = page->text->first_block; block; block = block->next) {
2865 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2866 b = &block->bbox;
2867 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2868 continue;
2870 if (mark == mark_block) {
2871 page->fmark = block->u.t.first_line->first_char;
2872 page->lmark = block->u.t.last_line->last_char;
2873 ret_v = Val_bool (1);
2874 goto unlock;
2877 for (line = block->u.t.first_line; line; line = line->next) {
2878 fz_stext_char *ch;
2880 b = &line->bbox;
2881 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2882 continue;
2884 if (mark == mark_line) {
2885 page->fmark = line->first_char;
2886 page->lmark = line->last_char;
2887 ret_v = Val_bool (1);
2888 goto unlock;
2891 for (ch = line->first_char; ch; ch = ch->next) {
2892 fz_stext_char *ch2, *first = NULL, *last = NULL;
2893 fz_quad *q = &ch->quad;
2894 if (x >= q->ul.x && x <= q->ur.x
2895 && y >= q->ul.y && y <= q->ll.y) {
2896 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2897 if (uninteresting (ch2->c)) first = NULL;
2898 else if (!first) first = ch2;
2900 for (ch2 = ch; ch2; ch2 = ch2->next) {
2901 if (uninteresting (ch2->c)) break;
2902 last = ch2;
2905 page->fmark = first;
2906 page->lmark = last;
2907 ret_v = Val_bool (1);
2908 goto unlock;
2913 unlock:
2914 if (!Bool_val (ret_v)) {
2915 page->fmark = NULL;
2916 page->lmark = NULL;
2918 unlock (__func__);
2920 done:
2921 CAMLreturn (ret_v);
2924 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
2926 CAMLparam3 (ptr_v, x_v, y_v);
2927 CAMLlocal2 (ret_v, res_v);
2928 fz_rect *b = NULL;
2929 struct page *page;
2930 struct pagedim *pdim;
2931 fz_stext_block *block;
2932 char *s = String_val (ptr_v);
2933 int x = Int_val (x_v), y = Int_val (y_v);
2935 ret_v = Val_int (0);
2936 if (trylock (__func__)) {
2937 goto done;
2940 page = parse_pointer (__func__, s);
2941 pdim = &state.pagedims[page->pdimno];
2942 x += pdim->bounds.x0;
2943 y += pdim->bounds.y0;
2945 ensuretext (page);
2947 for (block = page->text->first_block; block; block = block->next) {
2948 switch (block->type) {
2949 case FZ_STEXT_BLOCK_TEXT:
2950 b = &block->bbox;
2951 break;
2953 case FZ_STEXT_BLOCK_IMAGE:
2954 b = &block->bbox;
2955 break;
2957 default:
2958 continue;
2961 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2962 break;
2963 b = NULL;
2965 if (b) {
2966 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2967 ret_v = caml_alloc_small (1, 1);
2968 Store_double_field (res_v, 0, (double) b->x0);
2969 Store_double_field (res_v, 1, (double) b->x1);
2970 Store_double_field (res_v, 2, (double) b->y0);
2971 Store_double_field (res_v, 3, (double) b->y1);
2972 Field (ret_v, 0) = res_v;
2974 unlock (__func__);
2976 done:
2977 CAMLreturn (ret_v);
2980 CAMLprim void ml_seltext (value ptr_v, value rect_v)
2982 CAMLparam2 (ptr_v, rect_v);
2983 struct page *page;
2984 struct pagedim *pdim;
2985 char *s = String_val (ptr_v);
2986 int x0, x1, y0, y1;
2987 fz_stext_char *ch;
2988 fz_stext_line *line;
2989 fz_stext_block *block;
2990 fz_stext_char *fc, *lc;
2992 if (trylock (__func__)) {
2993 goto done;
2996 page = parse_pointer (__func__, s);
2997 ensuretext (page);
2999 pdim = &state.pagedims[page->pdimno];
3000 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3001 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3002 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3003 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3005 if (y0 > y1) {
3006 int t = y0;
3007 y0 = y1;
3008 y1 = t;
3009 x0 = x1;
3010 x1 = t;
3013 fc = page->fmark;
3014 lc = page->lmark;
3016 for (block = page->text->first_block; block; block = block->next) {
3017 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3018 for (line = block->u.t.first_line; line; line = line->next) {
3019 for (ch = line->first_char; ch; ch = ch->next) {
3020 fz_quad q = ch->quad;
3021 if (x0 >= q.ul.x && x0 <= q.ur.x
3022 && y0 >= q.ul.y && y0 <= q.ll.y) {
3023 fc = ch;
3025 if (x1 >= q.ul.x && x1 <= q.ur.x
3026 && y1 >= q.ul.y && y1 <= q.ll.y) {
3027 lc = ch;
3032 if (x1 < x0 && fc == lc) {
3033 fz_stext_char *t;
3035 t = fc;
3036 fc = lc;
3037 lc = t;
3040 page->fmark = fc;
3041 page->lmark = lc;
3043 unlock (__func__);
3045 done:
3046 CAMLreturn0;
3049 static int pipechar (FILE *f, fz_stext_char *ch)
3051 char buf[4];
3052 int len;
3053 size_t ret;
3055 len = fz_runetochar (buf, ch->c);
3056 ret = fwrite (buf, len, 1, f);
3057 if (ret != 1) {
3058 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3059 len, ret, errno, strerror (errno));
3060 return -1;
3062 return 0;
3065 CAMLprim value ml_spawn (value command_v, value fds_v)
3067 CAMLparam2 (command_v, fds_v);
3068 CAMLlocal2 (l_v, tup_v);
3069 int ret, ret1;
3070 pid_t pid = (pid_t) -1;
3071 char *msg = NULL;
3072 value earg_v = Nothing;
3073 posix_spawnattr_t attr;
3074 posix_spawn_file_actions_t fa;
3075 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3077 argv[2] = String_val (command_v);
3079 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3080 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3083 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3084 msg = "posix_spawnattr_init";
3085 goto fail1;
3088 #ifdef POSIX_SPAWN_USEVFORK
3089 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3090 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3091 goto fail;
3093 #endif
3095 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3096 int fd1, fd2;
3098 tup_v = Field (l_v, 0);
3099 fd1 = Int_val (Field (tup_v, 0));
3100 fd2 = Int_val (Field (tup_v, 1));
3101 if (fd2 < 0) {
3102 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3103 msg = "posix_spawn_file_actions_addclose";
3104 earg_v = tup_v;
3105 goto fail;
3108 else {
3109 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3110 msg = "posix_spawn_file_actions_adddup2";
3111 earg_v = tup_v;
3112 goto fail;
3117 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3118 msg = "posix_spawn";
3119 goto fail;
3122 fail:
3123 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3124 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3127 fail1:
3128 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3129 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3130 ret1, strerror (ret1));
3133 if (msg)
3134 unix_error (ret, msg, earg_v);
3136 CAMLreturn (Val_int (pid));
3139 CAMLprim value ml_hassel (value ptr_v)
3141 CAMLparam1 (ptr_v);
3142 CAMLlocal1 (ret_v);
3143 struct page *page;
3144 char *s = String_val (ptr_v);
3146 ret_v = Val_bool (0);
3147 if (trylock (__func__)) {
3148 goto done;
3151 page = parse_pointer (__func__, s);
3152 ret_v = Val_bool (page->fmark && page->lmark);
3153 unlock (__func__);
3154 done:
3155 CAMLreturn (ret_v);
3158 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3160 CAMLparam2 (fd_v, ptr_v);
3161 FILE *f;
3162 int seen = 0;
3163 struct page *page;
3164 fz_stext_line *line;
3165 fz_stext_block *block;
3166 int fd = Int_val (fd_v);
3167 char *s = String_val (ptr_v);
3169 if (trylock (__func__)) {
3170 goto done;
3173 page = parse_pointer (__func__, s);
3175 if (!page->fmark || !page->lmark) {
3176 printd ("emsg nothing to copy on page %d", page->pageno);
3177 goto unlock;
3180 f = fdopen (fd, "w");
3181 if (!f) {
3182 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3183 fd, errno, strerror (errno));
3184 f = stdout;
3187 for (block = page->text->first_block; block; block = block->next) {
3188 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3189 for (line = block->u.t.first_line; line; line = line->next) {
3190 fz_stext_char *ch;
3191 for (ch = line->first_char; ch; ch = ch->next) {
3192 if (seen || ch == page->fmark) {
3193 do {
3194 pipechar (f, ch);
3195 if (ch == page->lmark) goto close;
3196 } while ((ch = ch->next));
3197 seen = 1;
3198 break;
3201 if (seen) fputc ('\n', f);
3204 close:
3205 if (f != stdout) {
3206 int ret = fclose (f);
3207 fd = -1;
3208 if (ret == -1) {
3209 if (errno != ECHILD) {
3210 printd ("emsg failed to close sel pipe: %d:%s",
3211 errno, strerror (errno));
3215 unlock:
3216 unlock (__func__);
3218 done:
3219 if (fd >= 0) {
3220 if (close (fd)) {
3221 printd ("emsg failed to close sel pipe: %d:%s",
3222 errno, strerror (errno));
3225 CAMLreturn0;
3228 CAMLprim value ml_getpdimrect (value pagedimno_v)
3230 CAMLparam1 (pagedimno_v);
3231 CAMLlocal1 (ret_v);
3232 int pagedimno = Int_val (pagedimno_v);
3233 fz_rect box;
3235 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3236 if (trylock (__func__)) {
3237 box = fz_empty_rect;
3239 else {
3240 box = state.pagedims[pagedimno].mediabox;
3241 unlock (__func__);
3244 Store_double_field (ret_v, 0, (double) box.x0);
3245 Store_double_field (ret_v, 1, (double) box.x1);
3246 Store_double_field (ret_v, 2, (double) box.y0);
3247 Store_double_field (ret_v, 3, (double) box.y1);
3249 CAMLreturn (ret_v);
3252 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3253 value dw_v, value cols_v)
3255 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3256 CAMLlocal1 (ret_v);
3257 int i;
3258 float zoom = -1.;
3259 float maxh = 0.0;
3260 struct pagedim *p;
3261 float winw = Int_val (winw_v);
3262 float winh = Int_val (winh_v);
3263 float dw = Int_val (dw_v);
3264 float cols = Int_val (cols_v);
3265 float pw = 1.0, ph = 1.0;
3267 if (trylock (__func__)) {
3268 goto done;
3271 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3272 float w = p->pagebox.x1 / cols;
3273 float h = p->pagebox.y1;
3274 if (h > maxh) {
3275 maxh = h;
3276 ph = h;
3277 if (state.fitmodel != FitProportional) pw = w;
3279 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3282 zoom = (((winh / ph) * pw) + dw) / winw;
3283 unlock (__func__);
3284 done:
3285 ret_v = caml_copy_double ((double) zoom);
3286 CAMLreturn (ret_v);
3289 CAMLprim value ml_getmaxw (value unit_v)
3291 CAMLparam1 (unit_v);
3292 CAMLlocal1 (ret_v);
3293 int i;
3294 float maxw = -1.;
3295 struct pagedim *p;
3297 if (trylock (__func__)) {
3298 goto done;
3301 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3302 float w = p->pagebox.x1;
3303 maxw = fz_max (maxw, w);
3306 unlock (__func__);
3307 done:
3308 ret_v = caml_copy_double ((double) maxw);
3309 CAMLreturn (ret_v);
3312 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3314 CAMLparam4 (pt_v, x_v, y_v, string_v);
3315 CAMLlocal1 (ret_v);
3316 int pt = Int_val(pt_v);
3317 int x = Int_val (x_v);
3318 int y = Int_val (y_v);
3319 double w;
3321 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3322 ret_v = caml_copy_double (w);
3323 CAMLreturn (ret_v);
3326 CAMLprim value ml_measure_string (value pt_v, value string_v)
3328 CAMLparam2 (pt_v, string_v);
3329 CAMLlocal1 (ret_v);
3330 int pt = Int_val (pt_v);
3331 double w;
3333 w = (double) measure_string (state.face, pt, String_val (string_v));
3334 ret_v = caml_copy_double (w);
3335 CAMLreturn (ret_v);
3338 CAMLprim value ml_getpagebox (value opaque_v)
3340 CAMLparam1 (opaque_v);
3341 CAMLlocal1 (ret_v);
3342 fz_rect rect;
3343 fz_irect bbox;
3344 fz_device *dev;
3345 char *s = String_val (opaque_v);
3346 struct page *page = parse_pointer (__func__, s);
3348 ret_v = caml_alloc_tuple (4);
3349 dev = fz_new_bbox_device (state.ctx, &rect);
3351 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3353 fz_close_device (state.ctx, dev);
3354 fz_drop_device (state.ctx, dev);
3355 bbox = fz_round_rect (rect);
3356 Field (ret_v, 0) = Val_int (bbox.x0);
3357 Field (ret_v, 1) = Val_int (bbox.y0);
3358 Field (ret_v, 2) = Val_int (bbox.x1);
3359 Field (ret_v, 3) = Val_int (bbox.y1);
3361 CAMLreturn (ret_v);
3364 CAMLprim void ml_setaalevel (value level_v)
3366 CAMLparam1 (level_v);
3368 state.aalevel = Int_val (level_v);
3369 CAMLreturn0;
3372 #ifndef CIDER
3373 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3375 CAMLparam1 (keysym_v);
3376 CAMLlocal1 (str_v);
3377 KeySym keysym = Int_val (keysym_v);
3378 Rune rune;
3379 extern long keysym2ucs (KeySym);
3380 int len;
3381 char buf[5];
3383 rune = (Rune) keysym2ucs (keysym);
3384 len = fz_runetochar (buf, rune);
3385 buf[len] = 0;
3386 str_v = caml_copy_string (buf);
3387 CAMLreturn (str_v);
3389 #else
3390 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3392 CAMLparam1 (keysym_v);
3393 CAMLlocal1 (str_v);
3394 long ucs_v = Long_val (keysym_v);
3395 int len;
3396 char buf[5];
3398 len = fz_runetochar (buf, (int) ucs_v);
3399 buf[len] = 0;
3400 str_v = caml_copy_string (buf);
3401 CAMLreturn (str_v);
3403 #endif
3405 enum { piunknown, pilinux, pimacos, pibsd };
3407 CAMLprim value ml_platform (value unit_v)
3409 CAMLparam1 (unit_v);
3410 CAMLlocal2 (tup_v, arr_v);
3411 int platid = piunknown;
3412 struct utsname buf;
3414 #if defined __linux__
3415 platid = pilinux;
3416 #elif defined __DragonFly__ || defined __FreeBSD__
3417 || defined __OpenBSD__ || defined __NetBSD__
3418 platid = pibsd;
3419 #elif defined __APPLE__
3420 platid = pimacos;
3421 #endif
3422 if (uname (&buf)) err (1, "uname");
3424 tup_v = caml_alloc_tuple (2);
3426 char const *sar[] = {
3427 buf.sysname,
3428 buf.release,
3429 buf.version,
3430 buf.machine,
3431 NULL
3433 arr_v = caml_copy_string_array (sar);
3435 Field (tup_v, 0) = Val_int (platid);
3436 Field (tup_v, 1) = arr_v;
3437 CAMLreturn (tup_v);
3440 CAMLprim void ml_cloexec (value fd_v)
3442 CAMLparam1 (fd_v);
3443 int fd = Int_val (fd_v);
3445 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3446 uerror ("fcntl", Nothing);
3448 CAMLreturn0;
3451 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3453 CAMLparam2 (w_v, h_v);
3454 CAMLlocal1 (ret_v);
3455 struct bo *pbo;
3456 int w = Int_val (w_v);
3457 int h = Int_val (h_v);
3458 int cs = Int_val (cs_v);
3460 if (state.bo_usable) {
3461 pbo = calloc (sizeof (*pbo), 1);
3462 if (!pbo) {
3463 err (1, "calloc pbo");
3466 switch (cs) {
3467 case 0:
3468 case 1:
3469 pbo->size = w*h*4;
3470 break;
3471 case 2:
3472 pbo->size = w*h*2;
3473 break;
3474 default:
3475 errx (1, "%s: invalid colorspace %d", __func__, cs);
3478 state.glGenBuffersARB (1, &pbo->id);
3479 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3480 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3481 NULL, GL_STREAM_DRAW);
3482 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3483 GL_READ_WRITE);
3484 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3485 if (!pbo->ptr) {
3486 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3487 state.glDeleteBuffersARB (1, &pbo->id);
3488 free (pbo);
3489 ret_v = caml_copy_string ("0");
3491 else {
3492 int res;
3493 char *s;
3495 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3496 if (res < 0) {
3497 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3499 s = malloc (res+1);
3500 if (!s) {
3501 err (1, "malloc %d bytes failed", res+1);
3503 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3504 if (res < 0) {
3505 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3507 ret_v = caml_copy_string (s);
3508 free (s);
3511 else {
3512 ret_v = caml_copy_string ("0");
3514 CAMLreturn (ret_v);
3517 CAMLprim void ml_freepbo (value s_v)
3519 CAMLparam1 (s_v);
3520 char *s = String_val (s_v);
3521 struct tile *tile = parse_pointer (__func__, s);
3523 if (tile->pbo) {
3524 state.glDeleteBuffersARB (1, &tile->pbo->id);
3525 tile->pbo->id = -1;
3526 tile->pbo->ptr = NULL;
3527 tile->pbo->size = -1;
3529 CAMLreturn0;
3532 CAMLprim void ml_unmappbo (value s_v)
3534 CAMLparam1 (s_v);
3535 char *s = String_val (s_v);
3536 struct tile *tile = parse_pointer (__func__, s);
3538 if (tile->pbo) {
3539 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3540 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3541 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3543 tile->pbo->ptr = NULL;
3544 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3546 CAMLreturn0;
3549 static void setuppbo (void)
3551 extern void (*wsigladdr (const char *name)) (void);
3552 #pragma GCC diagnostic push
3553 #ifdef __clang__
3554 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3555 #endif
3556 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3557 state.bo_usable = GPA (glBindBufferARB)
3558 && GPA (glUnmapBufferARB)
3559 && GPA (glMapBufferARB)
3560 && GPA (glBufferDataARB)
3561 && GPA (glGenBuffersARB)
3562 && GPA (glDeleteBuffersARB);
3563 #undef GPA
3564 #pragma GCC diagnostic pop
3567 CAMLprim value ml_bo_usable (void)
3569 return Val_bool (state.bo_usable);
3572 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3574 CAMLparam3 (ptr_v, x_v, y_v);
3575 CAMLlocal2 (ret_v, tup_v);
3576 struct page *page;
3577 char *s = String_val (ptr_v);
3578 int x = Int_val (x_v), y = Int_val (y_v);
3579 struct pagedim *pdim;
3580 fz_point p;
3582 page = parse_pointer (__func__, s);
3583 pdim = &state.pagedims[page->pdimno];
3585 ret_v = Val_int (0);
3586 if (trylock (__func__)) {
3587 goto done;
3590 p.x = x + pdim->bounds.x0;
3591 p.y = y + pdim->bounds.y0;
3593 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3594 pdim->ctm)));
3596 tup_v = caml_alloc_tuple (2);
3597 ret_v = caml_alloc_small (1, 1);
3598 Field (tup_v, 0) = Val_int (p.x);
3599 Field (tup_v, 1) = Val_int (p.y);
3600 Field (ret_v, 0) = tup_v;
3602 unlock (__func__);
3603 done:
3604 CAMLreturn (ret_v);
3607 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3608 value x_v, value y_v)
3610 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3611 CAMLlocal1 (ret_v);
3612 struct page *page;
3613 char *s = String_val (ptr_v);
3614 int pageno = Int_val (pageno_v);
3615 int pdimno = Int_val (pdimno_v);
3616 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3617 struct pagedim *pdim;
3618 fz_point p;
3619 fz_matrix ctm;
3621 ret_v = Val_int (0);
3622 lock (__func__);
3624 if (!*s) {
3625 page = loadpage (pageno, pdimno);
3627 else {
3628 page = parse_pointer (__func__, s);
3630 pdim = &state.pagedims[pdimno];
3632 if (pdf_specifics (state.ctx, state.doc)) {
3633 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3634 ctm = state.pagedims[page->pdimno].tctm;
3636 else {
3637 ctm = fz_identity;
3639 p.x = x + pdim->bounds.x0;
3640 p.y = y + pdim->bounds.y0;
3642 ctm = fz_concat (pdim->tctm, pdim->ctm);
3643 p = fz_transform_point (p, ctm);
3645 ret_v = caml_alloc_tuple (2);
3646 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3647 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3649 if (!*s) {
3650 freepage (page);
3652 unlock (__func__);
3653 CAMLreturn (ret_v);
3656 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
3657 value contents_v)
3659 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3660 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3662 if (pdf) {
3663 pdf_annot *annot;
3664 struct page *page;
3665 fz_point p;
3666 char *s = String_val (ptr_v);
3668 page = parse_pointer (__func__, s);
3669 annot = pdf_create_annot (state.ctx,
3670 pdf_page_from_fz_page (state.ctx,
3671 page->fzpage),
3672 PDF_ANNOT_TEXT);
3673 p.x = Int_val (x_v);
3674 p.y = Int_val (y_v);
3675 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3676 pdf_set_text_annot_position (state.ctx, annot, p);
3677 state.dirty = 1;
3679 CAMLreturn0;
3682 CAMLprim void ml_delannot (value ptr_v, value n_v)
3684 CAMLparam2 (ptr_v, n_v);
3685 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3687 if (pdf) {
3688 struct page *page;
3689 char *s = String_val (ptr_v);
3690 struct slink *slink;
3692 page = parse_pointer (__func__, s);
3693 slink = &page->slinks[Int_val (n_v)];
3694 pdf_delete_annot (state.ctx,
3695 pdf_page_from_fz_page (state.ctx, page->fzpage),
3696 (pdf_annot *) slink->u.annot);
3697 state.dirty = 1;
3699 CAMLreturn0;
3702 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
3704 CAMLparam3 (ptr_v, n_v, str_v);
3705 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3707 if (pdf) {
3708 struct page *page;
3709 char *s = String_val (ptr_v);
3710 struct slink *slink;
3712 page = parse_pointer (__func__, s);
3713 slink = &page->slinks[Int_val (n_v)];
3714 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3715 String_val (str_v));
3716 state.dirty = 1;
3718 CAMLreturn0;
3721 CAMLprim value ml_hasunsavedchanges (void)
3723 return Val_bool (state.dirty);
3726 CAMLprim void ml_savedoc (value path_v)
3728 CAMLparam1 (path_v);
3729 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3731 if (pdf) {
3732 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3734 CAMLreturn0;
3737 static void makestippletex (void)
3739 const char pixels[] = "\xff\xff\0\0";
3740 glGenTextures (1, &state.stid);
3741 glBindTexture (GL_TEXTURE_1D, state.stid);
3742 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3743 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3744 glTexImage1D (
3745 GL_TEXTURE_1D,
3747 GL_ALPHA,
3750 GL_ALPHA,
3751 GL_UNSIGNED_BYTE,
3752 pixels
3756 CAMLprim value ml_fz_version (void)
3758 return caml_copy_string (FZ_VERSION);
3761 CAMLprim value ml_llpp_version (void)
3763 extern char llpp_version[];
3764 return caml_copy_string (llpp_version);
3767 CAMLprim void ml_init (value csock_v, value params_v)
3769 CAMLparam2 (csock_v, params_v);
3770 CAMLlocal2 (trim_v, fuzz_v);
3771 int ret;
3772 int texcount;
3773 char *fontpath;
3774 int colorspace;
3775 int mustoresize;
3777 state.csock = Int_val (csock_v);
3778 state.rotate = Int_val (Field (params_v, 0));
3779 state.fitmodel = Int_val (Field (params_v, 1));
3780 trim_v = Field (params_v, 2);
3781 texcount = Int_val (Field (params_v, 3));
3782 state.sliceheight = Int_val (Field (params_v, 4));
3783 mustoresize = Int_val (Field (params_v, 5));
3784 colorspace = Int_val (Field (params_v, 6));
3785 fontpath = String_val (Field (params_v, 7));
3787 #ifdef CIDER
3788 state.utf8cs = 1;
3789 #else
3790 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3791 if (setlocale (LC_CTYPE, "")) {
3792 const char *cset = nl_langinfo (CODESET);
3793 state.utf8cs = !strcmp (cset, "UTF-8");
3795 else {
3796 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3798 #endif
3800 if (caml_string_length (Field (params_v, 8)) > 0) {
3801 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3803 if (!state.trimcachepath) {
3804 printd ("emsg failed to strdup trimcachepath: %d:%s",
3805 errno, strerror (errno));
3809 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3810 fz_register_document_handlers (state.ctx);
3812 state.trimmargins = Bool_val (Field (trim_v, 0));
3813 fuzz_v = Field (trim_v, 1);
3814 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3815 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3816 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3817 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3819 set_tex_params (colorspace);
3821 if (*fontpath) {
3822 state.face = load_font (fontpath);
3824 else {
3825 int len;
3826 const unsigned char *data;
3828 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3829 state.face = load_builtin_font (data, len);
3831 if (!state.face) _exit (1);
3833 realloctexts (texcount);
3834 setuppbo ();
3835 makestippletex ();
3837 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3838 if (ret) {
3839 errx (1, "pthread_create: %s", strerror (ret));
3842 CAMLreturn0;
3845 #if FIXME || !FIXME
3846 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3847 #endif