More Philosopher umlaut trema fun :(
[llpp.git] / link.c
bloba8c7bdcca4a04501f04512238ab73e3333d6d664
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 void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
227 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
230 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
232 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
235 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
237 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
238 m.a, m.b, m.c, m.d, m.e, m.f);
241 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
243 static void lock (const char *cap)
245 int ret = pthread_mutex_lock (&mutex);
246 if (ret) {
247 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
251 static void unlock (const char *cap)
253 int ret = pthread_mutex_unlock (&mutex);
254 if (ret) {
255 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
259 static int trylock (const char *cap)
261 int ret = pthread_mutex_trylock (&mutex);
262 if (ret && ret != EBUSY) {
263 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
265 return ret == EBUSY;
268 static int hasdata (void)
270 int ret, avail;
271 ret = ioctl (state.csock, FIONREAD, &avail);
272 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
273 return avail > 0;
276 CAMLprim value ml_hasdata (value fd_v)
278 CAMLparam1 (fd_v);
279 int ret, avail;
281 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
282 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
283 CAMLreturn (Val_bool (avail > 0));
286 static void readdata (int fd, void *p, int size)
288 ssize_t n;
290 again:
291 n = read (fd, p, size);
292 if (n - size) {
293 if (n < 0 && errno == EINTR) goto again;
294 if (!n) errx (1, "EOF while reading");
295 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
299 static void writedata (int fd, char *p, int size)
301 ssize_t n;
302 uint32_t size4 = size;
303 struct iovec iov[2] = {
304 { .iov_base = &size4, .iov_len = 4 },
305 { .iov_base = p, .iov_len = size }
308 again:
309 n = writev (fd, iov, 2);
310 if (n < 0 && errno == EINTR) goto again;
311 if (n - size - 4) {
312 if (!n) errx (1, "EOF while writing data");
313 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
317 static int readlen (int fd)
319 uint32_t u;
320 readdata (fd, &u, 4);
321 return u;
324 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
326 CAMLparam3 (fd_v, bytes_v, len_v);
327 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
328 CAMLreturn0;
331 CAMLprim value ml_rcmd (value fd_v)
333 CAMLparam1 (fd_v);
334 CAMLlocal1 (strdata_v);
335 int fd = Int_val (fd_v);
336 int len = readlen (fd);
337 strdata_v = caml_alloc_string (len);
338 readdata (fd, String_val (strdata_v), len);
339 CAMLreturn (strdata_v);
342 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
344 char fbuf[64];
345 int size = sizeof (fbuf), len;
346 va_list ap;
347 char *buf = fbuf;
349 for (;;) {
350 va_start (ap, fmt);
351 len = vsnprintf (buf, size, fmt, ap);
352 va_end (ap);
354 if (len > -1) {
355 if (len < size - 4) {
356 writedata (state.csock, buf, len);
357 break;
359 else size = len + 5;
361 else {
362 err (1, "vsnprintf for `%s' failed", fmt);
364 buf = realloc (buf == fbuf ? NULL : buf, size);
365 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
367 if (buf != fbuf) free (buf);
370 static void closedoc (void)
372 #ifdef CACHE_PAGEREFS
373 if (state.pdflut.objs) {
374 for (int i = 0; i < state.pdflut.count; ++i) {
375 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
377 free (state.pdflut.objs);
378 state.pdflut.objs = NULL;
379 state.pdflut.idx = 0;
381 #endif
382 if (state.doc) {
383 fz_drop_document (state.ctx, state.doc);
384 state.doc = NULL;
388 static int openxref (char *filename, char *password, int layouth)
390 for (int i = 0; i < state.texcount; ++i) {
391 state.texowners[i].w = -1;
392 state.texowners[i].slice = NULL;
395 closedoc ();
397 state.dirty = 0;
398 if (state.pagedims) {
399 free (state.pagedims);
400 state.pagedims = NULL;
402 state.pagedimcount = 0;
404 fz_set_aa_level (state.ctx, state.aalevel);
405 state.doc = fz_open_document (state.ctx, filename);
406 if (fz_needs_password (state.ctx, state.doc)) {
407 if (password && !*password) {
408 printd ("pass");
409 return 0;
411 else {
412 int ok = fz_authenticate_password (state.ctx, state.doc, password);
413 if (!ok) {
414 printd ("pass fail");
415 return 0;
419 if (layouth >= 0)
420 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
421 state.pagecount = fz_count_pages (state.ctx, state.doc);
422 return 1;
425 static void docinfo (void)
427 struct { char *tag; char *name; } metatbl[] = {
428 { FZ_META_INFO_TITLE, "Title" },
429 { FZ_META_INFO_AUTHOR, "Author" },
430 { FZ_META_FORMAT, "Format" },
431 { FZ_META_ENCRYPTION, "Encryption" },
432 { "info:Creator", "Creator" },
433 { "info:Producer", "Producer" },
434 { "info:CreationDate", "Creation date" },
436 int len = 0;
437 char *buf = NULL;
439 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
440 int need;
441 again:
442 need = fz_lookup_metadata (state.ctx, state.doc,
443 metatbl[i].tag, buf, len);
444 if (need > 0) {
445 if (need <= len) {
446 printd ("info %s\t%s", metatbl[i].name, buf);
448 else {
449 buf = realloc (buf, need + 1);
450 if (!buf) err (1, "docinfo realloc %d", need + 1);
451 len = need + 1;
452 goto again;
456 free (buf);
458 printd ("infoend");
461 static void unlinktile (struct tile *tile)
463 for (int i = 0; i < tile->slicecount; ++i) {
464 struct slice *s = &tile->slices[i];
466 if (s->texindex != -1) {
467 if (state.texowners[s->texindex].slice == s) {
468 state.texowners[s->texindex].slice = NULL;
474 static void freepage (struct page *page)
476 if (!page) return;
477 if (page->text) {
478 fz_drop_stext_page (state.ctx, page->text);
480 if (page->slinks) {
481 free (page->slinks);
483 fz_drop_display_list (state.ctx, page->dlist);
484 fz_drop_page (state.ctx, page->fzpage);
485 free (page);
488 static void freetile (struct tile *tile)
490 unlinktile (tile);
491 if (!tile->pbo) {
492 #if 0
493 fz_drop_pixmap (state.ctx, tile->pixmap);
494 #else /* piggyback */
495 if (state.pig) {
496 fz_drop_pixmap (state.ctx, state.pig);
498 state.pig = tile->pixmap;
499 #endif
501 else {
502 free (tile->pbo);
503 fz_drop_pixmap (state.ctx, tile->pixmap);
505 free (tile);
508 static void trimctm (pdf_page *page, int pindex)
510 struct pagedim *pdim = &state.pagedims[pindex];
512 if (!page) return;
513 if (!pdim->tctmready) {
514 fz_rect realbox, mediabox;
515 fz_matrix page_ctm, ctm;
517 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
518 realbox = fz_transform_rect (pdim->mediabox, ctm);
519 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
520 pdim->tctm = fz_concat (
521 fz_invert_matrix (page_ctm),
522 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
523 pdim->tctmready = 1;
527 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
529 fz_matrix ctm;
530 ptrdiff_t pdimno = pdim - state.pagedims;
532 ARSERT (pdim - state.pagedims < INT_MAX);
533 if (pdf_specifics (state.ctx, state.doc)) {
534 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
535 ctm = fz_concat (pdim->tctm, pdim->ctm);
537 else {
538 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
539 pdim->ctm);
541 return ctm;
544 static fz_matrix pagectm (struct page *page)
546 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
549 static void *loadpage (int pageno, int pindex)
551 fz_device *dev;
552 struct page *page;
554 page = calloc (sizeof (struct page), 1);
555 if (!page) {
556 err (1, "calloc page %d", pageno);
559 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
560 dev = fz_new_list_device (state.ctx, page->dlist);
561 fz_try (state.ctx) {
562 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
563 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
565 fz_catch (state.ctx) {
566 page->fzpage = NULL;
568 fz_close_device (state.ctx, dev);
569 fz_drop_device (state.ctx, dev);
571 page->pdimno = pindex;
572 page->pageno = pageno;
573 page->sgen = state.gen;
574 page->agen = state.gen;
575 page->tgen = state.gen;
576 return page;
579 static struct tile *alloctile (int h)
581 int slicecount;
582 size_t tilesize;
583 struct tile *tile;
585 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
586 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
587 tile = calloc (tilesize, 1);
588 if (!tile) {
589 err (1, "cannot allocate tile (%zu bytes)", tilesize);
591 for (int i = 0; i < slicecount; ++i) {
592 int sh = fz_mini (h, state.sliceheight);
593 tile->slices[i].h = sh;
594 tile->slices[i].texindex = -1;
595 h -= sh;
597 tile->slicecount = slicecount;
598 tile->sliceheight = state.sliceheight;
599 return tile;
602 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
603 struct bo *pbo)
605 fz_irect bbox;
606 fz_matrix ctm;
607 fz_device *dev;
608 struct tile *tile;
609 struct pagedim *pdim;
611 tile = alloctile (h);
612 pdim = &state.pagedims[page->pdimno];
614 bbox = pdim->bounds;
615 bbox.x0 += x;
616 bbox.y0 += y;
617 bbox.x1 = bbox.x0 + w;
618 bbox.y1 = bbox.y0 + h;
620 if (state.pig) {
621 if (state.pig->w == w
622 && state.pig->h == h
623 && state.pig->colorspace == state.colorspace) {
624 tile->pixmap = state.pig;
625 tile->pixmap->x = bbox.x0;
626 tile->pixmap->y = bbox.y0;
628 else {
629 fz_drop_pixmap (state.ctx, state.pig);
631 state.pig = NULL;
633 if (!tile->pixmap) {
634 if (pbo) {
635 tile->pixmap =
636 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
637 bbox, NULL, 1, pbo->ptr);
638 tile->pbo = pbo;
640 else {
641 tile->pixmap =
642 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
643 NULL, 1);
647 tile->w = w;
648 tile->h = h;
649 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
651 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
652 ctm = pagectm (page);
653 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
654 fz_rect_from_irect (bbox), NULL);
655 fz_close_device (state.ctx, dev);
656 fz_drop_device (state.ctx, dev);
658 return tile;
661 #ifdef CACHE_PAGEREFS
662 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
663 thanks to Robin Watts */
664 static void
665 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
667 fz_context *ctx = state.ctx; /* doc->ctx; */
668 pdf_obj *kids;
669 int len;
671 if (state.pdflut.idx == state.pagecount) return;
673 kids = pdf_dict_gets (ctx, node, "Kids");
674 len = pdf_array_len (ctx, kids);
676 if (len == 0)
677 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
679 if (pdf_mark_obj (ctx, node))
680 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
681 for (int i = 0; i < len; i++) {
682 pdf_obj *kid = pdf_array_get (ctx, kids, i);
683 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
684 if (*type
685 ? !strcmp (type, "Pages")
686 : pdf_dict_gets (ctx, kid, "Kids")
687 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
688 pdf_collect_pages (doc, kid);
690 else {
691 if (*type
692 ? strcmp (type, "Page") != 0
693 : !pdf_dict_gets (ctx, kid, "MediaBox"))
694 fz_warn (ctx, "non-page object in page tree (%s)", type);
695 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
698 pdf_unmark_obj (ctx, node);
701 static void
702 pdf_load_page_objs (pdf_document *doc)
704 pdf_obj *root = pdf_dict_gets (state.ctx,
705 pdf_trailer (state.ctx, doc), "Root");
706 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
708 if (!node)
709 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
711 state.pdflut.idx = 0;
712 pdf_collect_pages (doc, node);
714 #endif
716 static void initpdims (void)
718 double start, end;
719 FILE *trimf = NULL;
720 fz_rect rootmediabox = fz_empty_rect;
721 int pageno, trim, show;
722 int trimw = 0, cxcount;
723 fz_context *ctx = state.ctx;
724 pdf_document *pdf = pdf_specifics (ctx, state.doc);
726 fz_var (trimw);
727 fz_var (trimf);
728 fz_var (cxcount);
729 start = now ();
731 if (state.trimmargins && state.trimcachepath) {
732 trimf = fopen (state.trimcachepath, "rb");
733 if (!trimf) {
734 trimf = fopen (state.trimcachepath, "wb");
735 trimw = 1;
739 if (state.trimmargins || pdf)
740 cxcount = state.pagecount;
741 else
742 cxcount = fz_mini (state.pagecount, 1);
744 if (pdf) {
745 pdf_obj *obj;
746 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
747 "Root/Pages/MediaBox");
748 rootmediabox = pdf_to_rect (ctx, obj);
751 #ifdef CACHE_PAGEREFS
752 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
753 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
754 if (!state.pdflut.objs) {
755 err (1, "malloc pageobjs %zu %d %zu failed",
756 sizeof (*state.pdflut.objs), cxcount,
757 sizeof (*state.pdflut.objs) * cxcount);
759 state.pdflut.count = cxcount;
760 pdf_load_page_objs (pdf);
761 state.pdflut.pdf = pdf;
763 #endif
765 for (pageno = 0; pageno < cxcount; ++pageno) {
766 int rotate = 0;
767 struct pagedim *p;
768 fz_rect mediabox = fz_empty_rect;
770 fz_var (rotate);
771 if (pdf) {
772 pdf_obj *pageref, *pageobj;
774 #ifdef CACHE_PAGEREFS
775 pageref = state.pdflut.objs[pageno];
776 #else
777 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
778 #endif
779 pageobj = pdf_resolve_indirect (ctx, pageref);
780 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
782 if (state.trimmargins) {
783 pdf_obj *obj;
784 pdf_page *page;
786 fz_try (ctx) {
787 page = pdf_load_page (ctx, pdf, pageno);
788 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
789 trim = state.trimanew || !obj;
790 if (trim) {
791 fz_rect rect;
792 fz_device *dev;
793 fz_matrix ctm, page_ctm;
795 dev = fz_new_bbox_device (ctx, &rect);
796 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
797 ctm = fz_invert_matrix (page_ctm);
798 pdf_run_page (ctx, page, dev, fz_identity, NULL);
799 fz_close_device (ctx, dev);
800 fz_drop_device (ctx, dev);
802 rect.x0 += state.trimfuzz.x0;
803 rect.x1 += state.trimfuzz.x1;
804 rect.y0 += state.trimfuzz.y0;
805 rect.y1 += state.trimfuzz.y1;
806 rect = fz_transform_rect (rect, ctm);
807 rect = fz_intersect_rect (rect, mediabox);
809 if (!fz_is_empty_rect (rect)) {
810 mediabox = rect;
813 obj = pdf_new_array (ctx, pdf, 4);
814 pdf_array_push (ctx, obj,
815 pdf_new_real (ctx, mediabox.x0));
816 pdf_array_push (ctx, obj,
817 pdf_new_real (ctx, mediabox.y0));
818 pdf_array_push (ctx, obj,
819 pdf_new_real (ctx, mediabox.x1));
820 pdf_array_push (ctx, obj,
821 pdf_new_real (ctx, mediabox.y1));
822 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
824 else {
825 mediabox.x0 = pdf_to_real (ctx,
826 pdf_array_get (ctx, obj, 0));
827 mediabox.y0 = pdf_to_real (ctx,
828 pdf_array_get (ctx, obj, 1));
829 mediabox.x1 = pdf_to_real (ctx,
830 pdf_array_get (ctx, obj, 2));
831 mediabox.y1 = pdf_to_real (ctx,
832 pdf_array_get (ctx, obj, 3));
835 fz_drop_page (ctx, &page->super);
836 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
837 if (show) {
838 printd ("progress %f Trimming %d",
839 (double) (pageno + 1) / state.pagecount,
840 pageno + 1);
843 fz_catch (ctx) {
844 printd ("emsg failed to load page %d", pageno);
847 else {
848 int empty = 0;
849 fz_rect cropbox;
851 mediabox =
852 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "MediaBox"));
853 if (fz_is_empty_rect (mediabox)) {
854 mediabox.x0 = 0;
855 mediabox.y0 = 0;
856 mediabox.x1 = 612;
857 mediabox.y1 = 792;
858 empty = 1;
861 cropbox =
862 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
863 if (!fz_is_empty_rect (cropbox)) {
864 if (empty) {
865 mediabox = cropbox;
867 else {
868 mediabox = fz_intersect_rect (mediabox, cropbox);
871 else {
872 if (empty) {
873 if (fz_is_empty_rect (rootmediabox)) {
874 printd ("emsg cannot find page size for page %d",
875 pageno);
877 else {
878 mediabox = rootmediabox;
884 else {
885 if (state.trimmargins && trimw) {
886 fz_page *page;
888 fz_try (ctx) {
889 page = fz_load_page (ctx, state.doc, pageno);
890 mediabox = fz_bound_page (ctx, page);
891 if (state.trimmargins) {
892 fz_rect rect;
893 fz_device *dev;
895 dev = fz_new_bbox_device (ctx, &rect);
896 fz_run_page (ctx, page, dev, fz_identity, NULL);
897 fz_close_device (ctx, dev);
898 fz_drop_device (ctx, dev);
900 rect.x0 += state.trimfuzz.x0;
901 rect.x1 += state.trimfuzz.x1;
902 rect.y0 += state.trimfuzz.y0;
903 rect.y1 += state.trimfuzz.y1;
904 rect = fz_intersect_rect (rect, mediabox);
906 if (!fz_is_empty_rect (rect)) {
907 mediabox = rect;
910 fz_drop_page (ctx, page);
912 fz_catch (ctx) {
914 if (trimf) {
915 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
916 if (n - 1) {
917 err (1, "fwrite trim mediabox");
921 else {
922 if (trimf) {
923 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
924 if (n - 1) {
925 err (1, "fread trim mediabox %d", pageno);
928 else {
929 fz_page *page;
930 fz_try (ctx) {
931 page = fz_load_page (ctx, state.doc, pageno);
932 mediabox = fz_bound_page (ctx, page);
933 fz_drop_page (ctx, page);
935 show = !state.trimmargins && pageno % 20 == 0;
936 if (show) {
937 printd ("progress %f Gathering dimensions %d",
938 (double) (pageno) / state.pagecount,
939 pageno);
942 fz_catch (ctx) {
943 printd ("emsg failed to load page %d", pageno);
949 if (state.pagedimcount == 0
950 || ((void) (p = &state.pagedims[state.pagedimcount-1])
951 , p->rotate != rotate)
952 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
953 size_t size;
955 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
956 state.pagedims = realloc (state.pagedims, size);
957 if (!state.pagedims) {
958 err (1, "realloc pagedims to %zu (%d elems)",
959 size, state.pagedimcount + 1);
962 p = &state.pagedims[state.pagedimcount++];
963 p->rotate = rotate;
964 p->mediabox = mediabox;
965 p->pageno = pageno;
968 end = now ();
969 printd ("progress 1 %s %d pages in %f seconds",
970 state.trimmargins ? "Trimmed" : "Processed",
971 state.pagecount, end - start);
972 state.trimanew = 0;
973 if (trimf) {
974 if (fclose (trimf)) {
975 err (1, "fclose");
980 static void layout (void)
982 int pindex;
983 fz_rect box;
984 fz_matrix ctm;
985 struct pagedim *p = NULL;
986 float zw, w, maxw = 0.0, zoom = 1.0;
988 if (state.pagedimcount == 0) return;
990 switch (state.fitmodel) {
991 case FitProportional:
992 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
993 float x0, x1;
995 p = &state.pagedims[pindex];
996 box = fz_transform_rect (p->mediabox,
997 fz_rotate (p->rotate + state.rotate));
999 x0 = fz_min (box.x0, box.x1);
1000 x1 = fz_max (box.x0, box.x1);
1002 w = x1 - x0;
1003 maxw = fz_max (w, maxw);
1004 zoom = state.w / maxw;
1006 break;
1008 case FitPage:
1009 maxw = state.w;
1010 break;
1012 case FitWidth:
1013 break;
1015 default:
1016 ARSERT (0 && state.fitmodel);
1019 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1020 p = &state.pagedims[pindex];
1021 ctm = fz_rotate (state.rotate);
1022 box = fz_transform_rect (p->mediabox,
1023 fz_rotate (p->rotate + state.rotate));
1024 w = box.x1 - box.x0;
1025 switch (state.fitmodel) {
1026 case FitProportional:
1027 p->left = (int) (((maxw - w) * zoom) / 2.f);
1028 break;
1029 case FitPage:
1031 float zh, h;
1032 zw = maxw / w;
1033 h = box.y1 - box.y0;
1034 zh = state.h / h;
1035 zoom = fz_min (zw, zh);
1036 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1038 break;
1039 case FitWidth:
1040 p->left = 0;
1041 zoom = state.w / w;
1042 break;
1045 p->zoomctm = fz_scale (zoom, zoom);
1046 ctm = fz_concat (p->zoomctm, ctm);
1048 p->pagebox = p->mediabox;
1049 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
1050 p->pagebox.x1 -= p->pagebox.x0;
1051 p->pagebox.y1 -= p->pagebox.y0;
1052 p->pagebox.x0 = 0;
1053 p->pagebox.y0 = 0;
1054 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
1055 p->ctm = ctm;
1057 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
1058 fz_scale (zoom, -zoom));
1059 p->tctmready = 0;
1062 do {
1063 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1064 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1065 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1066 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1067 int boundw = x1 - x0;
1068 int boundh = y1 - y0;
1070 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1071 } while (p-- != state.pagedims);
1074 struct pagedim *pdimofpageno (int pageno)
1076 struct pagedim *pdim = state.pagedims;
1078 for (int i = 0; i < state.pagedimcount; ++i) {
1079 if (state.pagedims[i].pageno > pageno)
1080 break;
1081 pdim = &state.pagedims[i];
1083 return pdim;
1086 static void recurse_outline (fz_outline *outline, int level)
1088 while (outline) {
1089 if (outline->page >= 0) {
1090 fz_point p = {.x = outline->x, .y = outline->y};
1091 struct pagedim *pdim = pdimofpageno (outline->page);
1092 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1093 p = fz_transform_point (p, pdim->ctm);
1094 printd ("o %d %d %d %d %s",
1095 level, outline->page, (int) p.y, h, outline->title);
1097 else {
1098 printd ("on %d %s", level, outline->title);
1100 if (outline->down) {
1101 recurse_outline (outline->down, level + 1);
1103 outline = outline->next;
1107 static void process_outline (void)
1109 fz_outline *outline;
1111 if (!state.needoutline || !state.pagedimcount) return;
1113 state.needoutline = 0;
1114 outline = fz_load_outline (state.ctx, state.doc);
1115 if (outline) {
1116 recurse_outline (outline, 0);
1117 fz_drop_outline (state.ctx, outline);
1121 static char *strofline (fz_stext_line *line)
1123 char *p;
1124 char utf8[10];
1125 fz_stext_char *ch;
1126 size_t size = 0, cap = 80;
1128 p = malloc (cap + 1);
1129 if (!p) return NULL;
1131 for (ch = line->first_char; ch; ch = ch->next) {
1132 int n = fz_runetochar (utf8, ch->c);
1133 if (size + n > cap) {
1134 cap *= 2;
1135 p = realloc (p, cap + 1);
1136 if (!p) return NULL;
1139 memcpy (p + size, utf8, n);
1140 size += n;
1142 p[size] = 0;
1143 return p;
1146 static int matchline (regex_t *re, fz_stext_line *line,
1147 int stop, int pageno, double start)
1149 int ret;
1150 char *p;
1151 regmatch_t rm;
1153 p = strofline (line);
1154 if (!p) return -1;
1156 ret = regexec (re, p, 1, &rm, 0);
1157 if (ret) {
1158 free (p);
1159 if (ret != REG_NOMATCH) {
1160 size_t size;
1161 char errbuf[80];
1162 size = regerror (ret, re, errbuf, sizeof (errbuf));
1163 printd ("msg regexec error `%.*s'",
1164 (int) size, errbuf);
1165 return -1;
1167 return 0;
1169 else {
1170 fz_quad s, e;
1171 fz_stext_char *ch;
1172 int o = 0;
1174 for (ch = line->first_char; ch; ch = ch->next) {
1175 o += fz_runelen (ch->c);
1176 if (o > rm.rm_so) {
1177 s = ch->quad;
1178 break;
1181 for (;ch; ch = ch->next) {
1182 o += fz_runelen (ch->c);
1183 if (o > rm.rm_eo) break;
1185 e = ch->quad;
1187 if (!stop) {
1188 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1189 pageno, 1,
1190 s.ul.x, s.ul.y,
1191 e.ur.x, s.ul.y,
1192 e.lr.x, e.lr.y,
1193 s.ul.x, e.lr.y);
1195 printd ("progress 1 found at %d `%.*s' in %f sec",
1196 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1197 now () - start);
1199 else {
1200 printd ("match %d %d %f %f %f %f %f %f %f %f",
1201 pageno, 2,
1202 s.ul.x, s.ul.y,
1203 e.ur.x, s.ul.y,
1204 e.lr.x, e.lr.y,
1205 s.ul.x, e.lr.y);
1207 free (p);
1208 return 1;
1212 /* wishful thinking function */
1213 static void search (regex_t *re, int pageno, int y, int forward)
1215 fz_device *tdev;
1216 fz_stext_page *text;
1217 struct pagedim *pdim;
1218 int stop = 0, niters = 0;
1219 double start, end;
1220 fz_page *page;
1221 fz_stext_block *block;
1223 start = now ();
1224 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1225 if (niters++ == 5) {
1226 niters = 0;
1227 if (hasdata ()) {
1228 printd ("progress 1 attention requested aborting search at %d",
1229 pageno);
1230 stop = 1;
1232 else {
1233 printd ("progress %f searching in page %d",
1234 (double) (pageno + 1) / state.pagecount,
1235 pageno);
1238 pdim = pdimofpageno (pageno);
1239 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1240 tdev = fz_new_stext_device (state.ctx, text, 0);
1242 page = fz_load_page (state.ctx, state.doc, pageno);
1243 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1245 fz_close_device (state.ctx, tdev);
1246 fz_drop_device (state.ctx, tdev);
1248 if (forward) {
1249 for (block = text->first_block; block; block = block->next) {
1250 fz_stext_line *line;
1252 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1253 for (line = block->u.t.first_line; line; line = line->next) {
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;
1264 else {
1265 for (block = text->last_block; block; block = block->prev) {
1266 fz_stext_line *line;
1268 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1269 for (line = block->u.t.last_line; line; line = line->prev) {
1270 if (line->bbox.y0 < y + 1) continue;
1272 switch (matchline (re, line, stop, pageno, start)) {
1273 case 0: break;
1274 case 1: stop = 1; break;
1275 case -1: stop = 1; goto endloop;
1281 if (forward) {
1282 pageno += 1;
1283 y = 0;
1285 else {
1286 pageno -= 1;
1287 y = INT_MAX;
1289 endloop:
1290 fz_drop_stext_page (state.ctx, text);
1291 fz_drop_page (state.ctx, page);
1293 end = now ();
1294 if (!stop) {
1295 printd ("progress 1 no matches %f sec", end - start);
1297 printd ("clearrects");
1300 static void set_tex_params (int colorspace)
1302 switch (colorspace) {
1303 case 0:
1304 state.texiform = GL_RGBA8;
1305 state.texform = GL_RGBA;
1306 state.texty = GL_UNSIGNED_BYTE;
1307 state.colorspace = fz_device_rgb (state.ctx);
1308 break;
1309 case 1:
1310 state.texiform = GL_LUMINANCE_ALPHA;
1311 state.texform = GL_LUMINANCE_ALPHA;
1312 state.texty = GL_UNSIGNED_BYTE;
1313 state.colorspace = fz_device_gray (state.ctx);
1314 break;
1315 default:
1316 errx (1, "invalid colorspce %d", colorspace);
1320 static void realloctexts (int texcount)
1322 size_t size;
1324 if (texcount == state.texcount) return;
1326 if (texcount < state.texcount) {
1327 glDeleteTextures (state.texcount - texcount,
1328 state.texids + texcount);
1331 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1332 state.texids = realloc (state.texids, size);
1333 if (!state.texids) {
1334 err (1, "realloc texs %zu", size);
1337 state.texowners = (void *) (state.texids + texcount);
1338 if (texcount > state.texcount) {
1339 glGenTextures (texcount - state.texcount,
1340 state.texids + state.texcount);
1341 for (int i = state.texcount; i < texcount; ++i) {
1342 state.texowners[i].w = -1;
1343 state.texowners[i].slice = NULL;
1346 state.texcount = texcount;
1347 state.texindex = 0;
1350 static char *mbtoutf8 (char *s)
1352 char *p, *r;
1353 wchar_t *tmp;
1354 size_t i, ret, len;
1356 if (state.utf8cs) {
1357 return s;
1360 len = mbstowcs (NULL, s, strlen (s));
1361 if (len == 0 || len == (size_t) -1) {
1362 if (len)
1363 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1364 return s;
1367 tmp = calloc (len, sizeof (wchar_t));
1368 if (!tmp) {
1369 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1370 len, sizeof (wchar_t), errno, strerror (errno));
1371 return s;
1374 ret = mbstowcs (tmp, s, len);
1375 if (ret == (size_t) -1) {
1376 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1377 len, errno, strerror (errno));
1378 free (tmp);
1379 return s;
1382 len = 0;
1383 for (i = 0; i < ret; ++i) {
1384 len += fz_runelen (tmp[i]);
1387 p = r = malloc (len + 1);
1388 if (!r) {
1389 printd ("emsg mbtoutf8: malloc(%zu)", len);
1390 free (tmp);
1391 return s;
1394 for (i = 0; i < ret; ++i) {
1395 p += fz_runetochar (p, tmp[i]);
1397 *p = 0;
1398 free (tmp);
1399 return r;
1402 CAMLprim value ml_mbtoutf8 (value s_v)
1404 CAMLparam1 (s_v);
1405 CAMLlocal1 (ret_v);
1406 char *s, *r;
1408 s = String_val (s_v);
1409 r = mbtoutf8 (s);
1410 if (r == s) {
1411 ret_v = s_v;
1413 else {
1414 ret_v = caml_copy_string (r);
1415 free (r);
1417 CAMLreturn (ret_v);
1420 static void * mainloop (void UNUSED_ATTR *unused)
1422 char *p = NULL;
1423 int len, ret, oldlen = 0;
1425 fz_var (p);
1426 fz_var (oldlen);
1427 for (;;) {
1428 len = readlen (state.csock);
1429 if (len == 0) {
1430 errx (1, "readlen returned 0");
1433 if (oldlen < len + 1) {
1434 p = realloc (p, len + 1);
1435 if (!p) {
1436 err (1, "realloc %d failed", len + 1);
1438 oldlen = len + 1;
1440 readdata (state.csock, p, len);
1441 p[len] = 0;
1443 if (!strncmp ("open", p, 4)) {
1444 int off, usedoccss, ok = 0, layouth;
1445 char *password;
1446 char *filename;
1447 char *utf8filename;
1448 size_t filenamelen;
1450 fz_var (ok);
1451 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1452 if (ret != 2) {
1453 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1456 filename = p + 5 + off;
1457 filenamelen = strlen (filename);
1458 password = filename + filenamelen + 1;
1460 if (password[strlen (password) + 1]) {
1461 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1464 lock ("open");
1465 fz_set_use_document_css (state.ctx, usedoccss);
1466 fz_try (state.ctx) {
1467 ok = openxref (filename, password, layouth);
1469 fz_catch (state.ctx) {
1470 utf8filename = mbtoutf8 (filename);
1471 printd ("msg Could not open %s", utf8filename);
1472 if (utf8filename != filename) {
1473 free (utf8filename);
1476 if (ok) {
1477 docinfo ();
1478 initpdims ();
1480 unlock ("open");
1482 if (ok) {
1483 utf8filename = mbtoutf8 (filename);
1484 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1485 if (utf8filename != filename) {
1486 free (utf8filename);
1488 state.needoutline = 1;
1491 else if (!strncmp ("cs", p, 2)) {
1492 int i, colorspace;
1494 ret = sscanf (p + 2, " %d", &colorspace);
1495 if (ret != 1) {
1496 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1498 lock ("cs");
1499 set_tex_params (colorspace);
1500 for (i = 0; i < state.texcount; ++i) {
1501 state.texowners[i].w = -1;
1502 state.texowners[i].slice = NULL;
1504 unlock ("cs");
1506 else if (!strncmp ("freepage", p, 8)) {
1507 void *ptr;
1509 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1510 if (ret != 1) {
1511 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1513 lock ("freepage");
1514 freepage (ptr);
1515 unlock ("freepage");
1517 else if (!strncmp ("freetile", p, 8)) {
1518 void *ptr;
1520 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1521 if (ret != 1) {
1522 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1524 lock ("freetile");
1525 freetile (ptr);
1526 unlock ("freetile");
1528 else if (!strncmp ("search", p, 6)) {
1529 int icase, pageno, y, len2, forward;
1530 char *pattern;
1531 regex_t re;
1533 ret = sscanf (p + 6, " %d %d %d %d,%n",
1534 &icase, &pageno, &y, &forward, &len2);
1535 if (ret != 4) {
1536 errx (1, "malformed search `%s' ret=%d", p, ret);
1539 pattern = p + 6 + len2;
1540 ret = regcomp (&re, pattern,
1541 REG_EXTENDED | (icase ? REG_ICASE : 0));
1542 if (ret) {
1543 char errbuf[80];
1544 size_t size;
1546 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1547 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1549 else {
1550 search (&re, pageno, y, forward);
1551 regfree (&re);
1554 else if (!strncmp ("geometry", p, 8)) {
1555 int w, h, fitmodel;
1557 printd ("clear");
1558 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1559 if (ret != 3) {
1560 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1563 lock ("geometry");
1564 state.h = h;
1565 if (w != state.w) {
1566 state.w = w;
1567 for (int i = 0; i < state.texcount; ++i) {
1568 state.texowners[i].slice = NULL;
1571 state.fitmodel = fitmodel;
1572 layout ();
1573 process_outline ();
1575 state.gen++;
1576 unlock ("geometry");
1577 printd ("continue %d", state.pagecount);
1579 else if (!strncmp ("reqlayout", p, 9)) {
1580 char *nameddest;
1581 int rotate, off, h;
1582 int fitmodel;
1583 pdf_document *pdf;
1585 printd ("clear");
1586 ret = sscanf (p + 9, " %d %d %d %n",
1587 &rotate, &fitmodel, &h, &off);
1588 if (ret != 3) {
1589 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1591 lock ("reqlayout");
1592 pdf = pdf_specifics (state.ctx, state.doc);
1593 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1594 state.gen += 1;
1596 state.rotate = rotate;
1597 state.fitmodel = fitmodel;
1598 state.h = h;
1599 layout ();
1600 process_outline ();
1602 nameddest = p + 9 + off;
1603 if (pdf && nameddest && *nameddest) {
1604 fz_point xy;
1605 struct pagedim *pdim;
1606 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1607 &xy.x, &xy.y);
1608 pdim = pdimofpageno (pageno);
1609 xy = fz_transform_point (xy, pdim->ctm);
1610 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1613 state.gen++;
1614 unlock ("reqlayout");
1615 printd ("continue %d", state.pagecount);
1617 else if (!strncmp ("page", p, 4)) {
1618 double a, b;
1619 struct page *page;
1620 int pageno, pindex;
1622 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1623 if (ret != 2) {
1624 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1627 lock ("page");
1628 a = now ();
1629 page = loadpage (pageno, pindex);
1630 b = now ();
1631 unlock ("page");
1633 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1635 else if (!strncmp ("tile", p, 4)) {
1636 int x, y, w, h;
1637 struct page *page;
1638 struct tile *tile;
1639 double a, b;
1640 void *data;
1642 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1643 (uintptr_t *) &page, &x, &y, &w, &h,
1644 (uintptr_t *) &data);
1645 if (ret != 6) {
1646 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1649 lock ("tile");
1650 a = now ();
1651 tile = rendertile (page, x, y, w, h, data);
1652 b = now ();
1653 unlock ("tile");
1655 printd ("tile %d %d %" PRIxPTR " %u %f",
1656 x, y, (uintptr_t) (tile),
1657 tile->w * tile->h * tile->pixmap->n,
1658 b - a);
1660 else if (!strncmp ("trimset", p, 7)) {
1661 fz_irect fuzz;
1662 int trimmargins;
1664 ret = sscanf (p + 7, " %d %d %d %d %d",
1665 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1666 if (ret != 5) {
1667 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1669 lock ("trimset");
1670 state.trimmargins = trimmargins;
1671 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1672 state.trimanew = 1;
1673 state.trimfuzz = fuzz;
1675 unlock ("trimset");
1677 else if (!strncmp ("settrim", p, 7)) {
1678 fz_irect fuzz;
1679 int trimmargins;
1681 ret = sscanf (p + 7, " %d %d %d %d %d",
1682 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1683 if (ret != 5) {
1684 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1686 printd ("clear");
1687 lock ("settrim");
1688 state.trimmargins = trimmargins;
1689 state.needoutline = 1;
1690 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1691 state.trimanew = 1;
1692 state.trimfuzz = fuzz;
1694 state.pagedimcount = 0;
1695 free (state.pagedims);
1696 state.pagedims = NULL;
1697 initpdims ();
1698 layout ();
1699 process_outline ();
1700 unlock ("settrim");
1701 printd ("continue %d", state.pagecount);
1703 else if (!strncmp ("sliceh", p, 6)) {
1704 int h;
1706 ret = sscanf (p + 6, " %d", &h);
1707 if (ret != 1) {
1708 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1710 if (h != state.sliceheight) {
1711 state.sliceheight = h;
1712 for (int i = 0; i < state.texcount; ++i) {
1713 state.texowners[i].w = -1;
1714 state.texowners[i].h = -1;
1715 state.texowners[i].slice = NULL;
1719 else if (!strncmp ("interrupt", p, 9)) {
1720 printd ("vmsg interrupted");
1722 else {
1723 errx (1, "unknown command %.*s", len, p);
1726 return 0;
1729 CAMLprim value ml_isexternallink (value uri_v)
1731 CAMLparam1 (uri_v);
1732 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1733 CAMLreturn (Val_bool (ext));
1736 CAMLprim value ml_uritolocation (value uri_v)
1738 CAMLparam1 (uri_v);
1739 CAMLlocal1 (ret_v);
1740 int pageno;
1741 fz_point xy;
1742 struct pagedim *pdim;
1744 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1745 &xy.x, &xy.y);
1746 pdim = pdimofpageno (pageno);
1747 xy = fz_transform_point (xy, pdim->ctm);
1748 ret_v = caml_alloc_tuple (3);
1749 Field (ret_v, 0) = Val_int (pageno);
1750 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1751 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1752 CAMLreturn (ret_v);
1755 CAMLprim value ml_realloctexts (value texcount_v)
1757 CAMLparam1 (texcount_v);
1758 int ok;
1760 if (trylock (__func__)) {
1761 ok = 0;
1762 goto done;
1764 realloctexts (Int_val (texcount_v));
1765 ok = 1;
1766 unlock (__func__);
1768 done:
1769 CAMLreturn (Val_bool (ok));
1772 static void recti (int x0, int y0, int x1, int y1)
1774 GLfloat *v = state.vertices;
1776 glVertexPointer (2, GL_FLOAT, 0, v);
1777 v[0] = x0; v[1] = y0;
1778 v[2] = x1; v[3] = y0;
1779 v[4] = x0; v[5] = y1;
1780 v[6] = x1; v[7] = y1;
1781 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1784 static void showsel (struct page *page, int ox, int oy)
1786 fz_irect bbox;
1787 fz_rect rect;
1788 fz_stext_block *block;
1789 int seen = 0;
1790 unsigned char selcolor[] = {15,15,15,140};
1792 if (!page->fmark || !page->lmark) return;
1794 glEnable (GL_BLEND);
1795 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1796 glColor4ubv (selcolor);
1798 ox += state.pagedims[page->pdimno].bounds.x0;
1799 oy += state.pagedims[page->pdimno].bounds.y0;
1801 for (block = page->text->first_block; block; block = block->next) {
1802 fz_stext_line *line;
1804 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1805 for (line = block->u.t.first_line; line; line = line->next) {
1806 fz_stext_char *ch;
1808 rect = fz_empty_rect;
1809 for (ch = line->first_char; ch; ch = ch->next) {
1810 fz_rect r;
1811 if (ch == page->fmark) seen = 1;
1812 r = fz_rect_from_quad (ch->quad);
1813 if (seen) rect = fz_union_rect (rect, r);
1814 if (ch == page->lmark) {
1815 bbox = fz_round_rect (rect);
1816 recti (bbox.x0 + ox, bbox.y0 + oy,
1817 bbox.x1 + ox, bbox.y1 + oy);
1818 goto done;
1821 bbox = fz_round_rect (rect);
1822 recti (bbox.x0 + ox, bbox.y0 + oy,
1823 bbox.x1 + ox, bbox.y1 + oy);
1826 done:
1827 glDisable (GL_BLEND);
1830 #pragma GCC diagnostic push
1831 #pragma GCC diagnostic ignored "-Wconversion"
1832 #include "glfont.c"
1833 #pragma GCC diagnostic pop
1835 static void stipplerect (fz_matrix m,
1836 fz_point p1,
1837 fz_point p2,
1838 fz_point p3,
1839 fz_point p4,
1840 GLfloat *texcoords,
1841 GLfloat *vertices)
1843 p1 = fz_transform_point (p1, m);
1844 p2 = fz_transform_point (p2, m);
1845 p3 = fz_transform_point (p3, m);
1846 p4 = fz_transform_point (p4, m);
1848 float w, h, s, t;
1850 w = p2.x - p1.x;
1851 h = p2.y - p1.y;
1852 t = hypotf (w, h) * .25f;
1854 w = p3.x - p2.x;
1855 h = p3.y - p2.y;
1856 s = hypotf (w, h) * .25f;
1858 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1859 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1861 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1862 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1864 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1865 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1867 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1868 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1870 glDrawArrays (GL_LINES, 0, 8);
1873 static void solidrect (fz_matrix m,
1874 fz_point p1,
1875 fz_point p2,
1876 fz_point p3,
1877 fz_point p4,
1878 GLfloat *vertices)
1880 p1 = fz_transform_point (p1, m);
1881 p2 = fz_transform_point (p2, m);
1882 p3 = fz_transform_point (p3, m);
1883 p4 = fz_transform_point (p4, m);
1884 vertices[0] = p1.x; vertices[1] = p1.y;
1885 vertices[2] = p2.x; vertices[3] = p2.y;
1887 vertices[4] = p3.x; vertices[5] = p3.y;
1888 vertices[6] = p4.x; vertices[7] = p4.y;
1889 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1892 static void ensurelinks (struct page *page)
1894 if (!page->links)
1895 page->links = fz_load_links (state.ctx, page->fzpage);
1898 static void highlightlinks (struct page *page, int xoff, int yoff)
1900 fz_matrix ctm;
1901 fz_link *link;
1902 GLfloat *texcoords = state.texcoords;
1903 GLfloat *vertices = state.vertices;
1905 ensurelinks (page);
1907 glEnable (GL_TEXTURE_1D);
1908 glEnable (GL_BLEND);
1909 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1910 glBindTexture (GL_TEXTURE_1D, state.stid);
1912 xoff -= state.pagedims[page->pdimno].bounds.x0;
1913 yoff -= state.pagedims[page->pdimno].bounds.y0;
1914 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1916 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1917 glVertexPointer (2, GL_FLOAT, 0, vertices);
1919 for (link = page->links; link; link = link->next) {
1920 fz_point p1, p2, p3, p4;
1922 p1.x = link->rect.x0;
1923 p1.y = link->rect.y0;
1925 p2.x = link->rect.x1;
1926 p2.y = link->rect.y0;
1928 p3.x = link->rect.x1;
1929 p3.y = link->rect.y1;
1931 p4.x = link->rect.x0;
1932 p4.y = link->rect.y1;
1934 /* TODO: different colours for different schemes */
1935 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1936 else glColor3ub (255, 0, 0);
1938 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1941 for (int i = 0; i < page->annotcount; ++i) {
1942 fz_point p1, p2, p3, p4;
1943 struct annot *annot = &page->annots[i];
1945 p1.x = annot->bbox.x0;
1946 p1.y = annot->bbox.y0;
1948 p2.x = annot->bbox.x1;
1949 p2.y = annot->bbox.y0;
1951 p3.x = annot->bbox.x1;
1952 p3.y = annot->bbox.y1;
1954 p4.x = annot->bbox.x0;
1955 p4.y = annot->bbox.y1;
1957 glColor3ub (0, 0, 128);
1958 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1961 glDisable (GL_BLEND);
1962 glDisable (GL_TEXTURE_1D);
1965 static int compareslinks (const void *l, const void *r)
1967 struct slink const *ls = l;
1968 struct slink const *rs = r;
1969 if (ls->bbox.y0 == rs->bbox.y0) {
1970 return rs->bbox.x0 - rs->bbox.x0;
1972 return ls->bbox.y0 - rs->bbox.y0;
1975 static void droptext (struct page *page)
1977 if (page->text) {
1978 fz_drop_stext_page (state.ctx, page->text);
1979 page->fmark = NULL;
1980 page->lmark = NULL;
1981 page->text = NULL;
1985 static void dropannots (struct page *page)
1987 if (page->annots) {
1988 free (page->annots);
1989 page->annots = NULL;
1990 page->annotcount = 0;
1994 static void ensureannots (struct page *page)
1996 int i, count = 0;
1997 size_t annotsize = sizeof (*page->annots);
1998 fz_annot *annot;
2000 if (state.gen != page->agen) {
2001 dropannots (page);
2002 page->agen = state.gen;
2004 if (page->annots) return;
2006 for (annot = fz_first_annot (state.ctx, page->fzpage);
2007 annot;
2008 annot = fz_next_annot (state.ctx, annot)) {
2009 count++;
2012 if (count > 0) {
2013 page->annotcount = count;
2014 page->annots = calloc (count, annotsize);
2015 if (!page->annots) {
2016 err (1, "calloc annots %d", count);
2019 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2020 annot;
2021 annot = fz_next_annot (state.ctx, annot), i++) {
2022 fz_rect rect;
2024 rect = fz_bound_annot (state.ctx, annot);
2025 page->annots[i].annot = annot;
2026 page->annots[i].bbox = fz_round_rect (rect);
2031 static void dropslinks (struct page *page)
2033 if (page->slinks) {
2034 free (page->slinks);
2035 page->slinks = NULL;
2036 page->slinkcount = 0;
2038 if (page->links) {
2039 fz_drop_link (state.ctx, page->links);
2040 page->links = NULL;
2044 static void ensureslinks (struct page *page)
2046 fz_matrix ctm;
2047 int i, count;
2048 size_t slinksize = sizeof (*page->slinks);
2049 fz_link *link;
2051 ensureannots (page);
2052 if (state.gen != page->sgen) {
2053 dropslinks (page);
2054 page->sgen = state.gen;
2056 if (page->slinks) return;
2058 ensurelinks (page);
2059 ctm = pagectm (page);
2061 count = page->annotcount;
2062 for (link = page->links; link; link = link->next) {
2063 count++;
2065 if (count > 0) {
2066 int j;
2068 page->slinkcount = count;
2069 page->slinks = calloc (count, slinksize);
2070 if (!page->slinks) {
2071 err (1, "calloc slinks %d", count);
2074 for (i = 0, link = page->links; link; ++i, link = link->next) {
2075 fz_rect rect;
2077 rect = link->rect;
2078 rect = fz_transform_rect (rect, ctm);
2079 page->slinks[i].tag = SLINK;
2080 page->slinks[i].u.link = link;
2081 page->slinks[i].bbox = fz_round_rect (rect);
2083 for (j = 0; j < page->annotcount; ++j, ++i) {
2084 fz_rect rect;
2085 rect = fz_bound_annot (state.ctx, page->annots[j].annot);
2086 rect = fz_transform_rect (rect, ctm);
2087 page->slinks[i].bbox = fz_round_rect (rect);
2089 page->slinks[i].tag = SANNOT;
2090 page->slinks[i].u.annot = page->annots[j].annot;
2092 qsort (page->slinks, count, slinksize, compareslinks);
2096 static void highlightslinks (struct page *page, int xoff, int yoff,
2097 int noff, char *targ, mlsize_t tlen, int hfsize)
2099 char buf[40];
2100 struct slink *slink;
2101 float x0, y0, x1, y1, w;
2103 ensureslinks (page);
2104 glColor3ub (0xc3, 0xb0, 0x91);
2105 for (int i = 0; i < page->slinkcount; ++i) {
2106 fmt_linkn (buf, i + noff);
2107 if (!tlen || !strncmp (targ, buf, tlen)) {
2108 slink = &page->slinks[i];
2110 x0 = slink->bbox.x0 + xoff - 5;
2111 y1 = slink->bbox.y0 + yoff - 5;
2112 y0 = y1 + 10 + hfsize;
2113 w = measure_string (state.face, hfsize, buf);
2114 x1 = x0 + w + 10;
2115 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2119 glEnable (GL_BLEND);
2120 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2121 glEnable (GL_TEXTURE_2D);
2122 glColor3ub (0, 0, 0);
2123 for (int i = 0; i < page->slinkcount; ++i) {
2124 fmt_linkn (buf, i + noff);
2125 if (!tlen || !strncmp (targ, buf, tlen)) {
2126 slink = &page->slinks[i];
2128 x0 = slink->bbox.x0 + xoff;
2129 y0 = slink->bbox.y0 + yoff + hfsize;
2130 draw_string (state.face, hfsize, x0, y0, buf);
2133 glDisable (GL_TEXTURE_2D);
2134 glDisable (GL_BLEND);
2137 static void uploadslice (struct tile *tile, struct slice *slice)
2139 int offset;
2140 struct slice *slice1;
2141 unsigned char *texdata;
2143 offset = 0;
2144 for (slice1 = tile->slices; slice != slice1; slice1++) {
2145 offset += slice1->h * tile->w * tile->pixmap->n;
2147 if (slice->texindex != -1 && slice->texindex < state.texcount
2148 && state.texowners[slice->texindex].slice == slice) {
2149 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2151 else {
2152 int subimage = 0;
2153 int texindex = state.texindex++ % state.texcount;
2155 if (state.texowners[texindex].w == tile->w) {
2156 if (state.texowners[texindex].h >= slice->h) {
2157 subimage = 1;
2159 else {
2160 state.texowners[texindex].h = slice->h;
2163 else {
2164 state.texowners[texindex].h = slice->h;
2167 state.texowners[texindex].w = tile->w;
2168 state.texowners[texindex].slice = slice;
2169 slice->texindex = texindex;
2171 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2172 #if TEXT_TYPE == GL_TEXTURE_2D
2173 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2174 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2175 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2176 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2177 #endif
2178 if (tile->pbo) {
2179 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2180 texdata = 0;
2182 else {
2183 texdata = tile->pixmap->samples;
2185 if (subimage) {
2186 glTexSubImage2D (TEXT_TYPE,
2190 tile->w,
2191 slice->h,
2192 state.texform,
2193 state.texty,
2194 texdata+offset
2197 else {
2198 glTexImage2D (TEXT_TYPE,
2200 state.texiform,
2201 tile->w,
2202 slice->h,
2204 state.texform,
2205 state.texty,
2206 texdata+offset
2209 if (tile->pbo) {
2210 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2215 CAMLprim void ml_begintiles (void)
2217 glEnable (TEXT_TYPE);
2218 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2219 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2222 CAMLprim void ml_endtiles (void)
2224 glDisable (TEXT_TYPE);
2227 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2229 CAMLparam2 (args_v, ptr_v);
2230 int dispx = Int_val (Field (args_v, 0));
2231 int dispy = Int_val (Field (args_v, 1));
2232 int dispw = Int_val (Field (args_v, 2));
2233 int disph = Int_val (Field (args_v, 3));
2234 int tilex = Int_val (Field (args_v, 4));
2235 int tiley = Int_val (Field (args_v, 5));
2236 char *s = String_val (ptr_v);
2237 struct tile *tile = parse_pointer (__func__, s);
2238 int slicey, firstslice;
2239 struct slice *slice;
2240 GLfloat *texcoords = state.texcoords;
2241 GLfloat *vertices = state.vertices;
2243 firstslice = tiley / tile->sliceheight;
2244 slice = &tile->slices[firstslice];
2245 slicey = tiley % tile->sliceheight;
2247 while (disph > 0) {
2248 int dh;
2250 dh = slice->h - slicey;
2251 dh = fz_mini (disph, dh);
2252 uploadslice (tile, slice);
2254 texcoords[0] = tilex; texcoords[1] = slicey;
2255 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2256 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2257 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2259 vertices[0] = dispx; vertices[1] = dispy;
2260 vertices[2] = dispx+dispw; vertices[3] = dispy;
2261 vertices[4] = dispx; vertices[5] = dispy+dh;
2262 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2264 #if TEXT_TYPE == GL_TEXTURE_2D
2265 for (int i = 0; i < 8; ++i) {
2266 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2268 #endif
2270 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2271 dispy += dh;
2272 disph -= dh;
2273 slice++;
2274 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2275 slicey = 0;
2277 CAMLreturn0;
2280 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2282 fz_matrix ctm;
2283 fz_point p1, p2, p3, p4;
2284 GLfloat *vertices = state.vertices;
2285 double *v = (double *) rects_v;
2287 xoff -= state.pagedims[page->pdimno].bounds.x0;
2288 yoff -= state.pagedims[page->pdimno].bounds.y0;
2289 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2291 glEnable (GL_BLEND);
2292 glVertexPointer (2, GL_FLOAT, 0, vertices);
2294 glColor4dv (v);
2295 p1.x = (float) v[4];
2296 p1.y = (float) v[5];
2298 p2.x = (float) v[6];
2299 p2.y = (float) v[5];
2301 p3.x = (float) v[6];
2302 p3.y = (float) v[7];
2304 p4.x = (float) v[4];
2305 p4.y = (float) v[7];
2306 solidrect (ctm, p1, p2, p3, p4, vertices);
2307 glDisable (GL_BLEND);
2310 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2311 value xoff_v, value yoff_v,
2312 value li_v)
2314 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2315 int xoff = Int_val (xoff_v);
2316 int yoff = Int_val (yoff_v);
2317 int noff = Int_val (Field (li_v, 0));
2318 char *targ = String_val (Field (li_v, 1));
2319 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2320 int hfsize = Int_val (Field (li_v, 2));
2321 char *s = String_val (ptr_v);
2322 int hlmask = Int_val (hlinks_v);
2323 struct page *page = parse_pointer (__func__, s);
2325 if (!page->fzpage) {
2326 /* deal with loadpage failed pages */
2327 goto done;
2330 if (trylock (__func__)) {
2331 noff = -1;
2332 goto done;
2335 ensureannots (page);
2336 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2337 if (hlmask & 2) {
2338 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2339 noff = page->slinkcount;
2341 if (page->tgen == state.gen) {
2342 showsel (page, xoff, yoff);
2344 unlock (__func__);
2346 done:
2347 CAMLreturn (Val_int (noff));
2350 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2351 value rects_v)
2353 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2354 int xoff = Int_val (xoff_v);
2355 int yoff = Int_val (yoff_v);
2356 char *s = String_val (ptr_v);
2357 struct page *page = parse_pointer (__func__, s);
2359 drawprect (page, xoff, yoff, rects_v);
2360 CAMLreturn0;
2363 static struct annot *getannot (struct page *page, int x, int y)
2365 fz_point p;
2366 fz_matrix ctm;
2367 const fz_matrix *tctm;
2368 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2370 if (!page->annots) return NULL;
2372 if (pdf) {
2373 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2374 tctm = &state.pagedims[page->pdimno].tctm;
2376 else {
2377 tctm = &fz_identity;
2380 p.x = x;
2381 p.y = y;
2383 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2384 ctm = fz_invert_matrix (ctm);
2385 p = fz_transform_point (p, ctm);
2387 if (pdf) {
2388 for (int i = 0; i < page->annotcount; ++i) {
2389 struct annot *a = &page->annots[i];
2390 fz_rect rect;
2392 rect = fz_bound_annot (state.ctx, a->annot);
2393 if (p.x >= rect.x0 && p.x <= rect.x1) {
2394 if (p.y >= rect.y0 && p.y <= rect.y1)
2395 return a;
2399 return NULL;
2402 static fz_link *getlink (struct page *page, int x, int y)
2404 fz_point p;
2405 fz_link *link;
2407 ensureslinks (page);
2409 p.x = x;
2410 p.y = y;
2412 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2414 for (link = page->links; link; link = link->next) {
2415 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2416 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2417 return link;
2421 return NULL;
2424 static void ensuretext (struct page *page)
2426 if (state.gen != page->tgen) {
2427 droptext (page);
2428 page->tgen = state.gen;
2430 if (!page->text) {
2431 fz_device *tdev;
2433 page->text = fz_new_stext_page (state.ctx,
2434 state.pagedims[page->pdimno].mediabox);
2435 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2436 fz_run_display_list (state.ctx, page->dlist,
2437 tdev, pagectm (page), fz_infinite_rect, NULL);
2438 fz_close_device (state.ctx, tdev);
2439 fz_drop_device (state.ctx, tdev);
2443 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2445 CAMLparam2 (start_page_v, dir_v);
2446 CAMLlocal1 (ret_v);
2447 int i, dir = Int_val (dir_v);
2448 int start_page = Int_val (start_page_v);
2449 int end_page = dir > 0 ? state.pagecount : -1;
2450 pdf_document *pdf;
2452 fz_var (end_page);
2453 ret_v = Val_int (0);
2454 lock (__func__);
2455 pdf = pdf_specifics (state.ctx, state.doc);
2456 for (i = start_page + dir; i != end_page; i += dir) {
2457 int found;
2459 fz_var (found);
2460 if (pdf) {
2461 pdf_page *page = NULL;
2463 fz_var (page);
2464 fz_try (state.ctx) {
2465 page = pdf_load_page (state.ctx, pdf, i);
2466 found = !!page->links || !!page->annots;
2468 fz_catch (state.ctx) {
2469 found = 0;
2471 if (page) {
2472 fz_drop_page (state.ctx, &page->super);
2475 else {
2476 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2477 fz_link *link = fz_load_links (state.ctx, page);
2478 found = !!link;
2479 fz_drop_link (state.ctx, link);
2480 fz_drop_page (state.ctx, page);
2483 if (found) {
2484 ret_v = caml_alloc_small (1, 1);
2485 Field (ret_v, 0) = Val_int (i);
2486 goto unlock;
2489 unlock:
2490 unlock (__func__);
2491 CAMLreturn (ret_v);
2494 enum { dir_first, dir_last };
2495 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2497 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2499 CAMLparam2 (ptr_v, dir_v);
2500 CAMLlocal2 (ret_v, pos_v);
2501 struct page *page;
2502 int dirtag, i, slinkindex;
2503 struct slink *found = NULL ,*slink;
2504 char *s = String_val (ptr_v);
2506 page = parse_pointer (__func__, s);
2507 ret_v = Val_int (0);
2508 lock (__func__);
2509 ensureslinks (page);
2511 if (Is_block (dir_v)) {
2512 dirtag = Tag_val (dir_v);
2513 switch (dirtag) {
2514 case dir_first_visible:
2516 int x0, y0, dir, first_index, last_index;
2518 pos_v = Field (dir_v, 0);
2519 x0 = Int_val (Field (pos_v, 0));
2520 y0 = Int_val (Field (pos_v, 1));
2521 dir = Int_val (Field (pos_v, 2));
2523 if (dir >= 0) {
2524 dir = 1;
2525 first_index = 0;
2526 last_index = page->slinkcount;
2528 else {
2529 first_index = page->slinkcount - 1;
2530 last_index = -1;
2533 for (i = first_index; i != last_index; i += dir) {
2534 slink = &page->slinks[i];
2535 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2536 found = slink;
2537 break;
2541 break;
2543 case dir_left:
2544 slinkindex = Int_val (Field (dir_v, 0));
2545 found = &page->slinks[slinkindex];
2546 for (i = slinkindex - 1; i >= 0; --i) {
2547 slink = &page->slinks[i];
2548 if (slink->bbox.x0 < found->bbox.x0) {
2549 found = slink;
2550 break;
2553 break;
2555 case dir_right:
2556 slinkindex = Int_val (Field (dir_v, 0));
2557 found = &page->slinks[slinkindex];
2558 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2559 slink = &page->slinks[i];
2560 if (slink->bbox.x0 > found->bbox.x0) {
2561 found = slink;
2562 break;
2565 break;
2567 case dir_down:
2568 slinkindex = Int_val (Field (dir_v, 0));
2569 found = &page->slinks[slinkindex];
2570 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2571 slink = &page->slinks[i];
2572 if (slink->bbox.y0 >= found->bbox.y0) {
2573 found = slink;
2574 break;
2577 break;
2579 case dir_up:
2580 slinkindex = Int_val (Field (dir_v, 0));
2581 found = &page->slinks[slinkindex];
2582 for (i = slinkindex - 1; i >= 0; --i) {
2583 slink = &page->slinks[i];
2584 if (slink->bbox.y0 <= found->bbox.y0) {
2585 found = slink;
2586 break;
2589 break;
2592 else {
2593 dirtag = Int_val (dir_v);
2594 switch (dirtag) {
2595 case dir_first:
2596 found = page->slinks;
2597 break;
2599 case dir_last:
2600 if (page->slinks) {
2601 found = page->slinks + (page->slinkcount - 1);
2603 break;
2606 if (found) {
2607 ret_v = caml_alloc_small (2, 1);
2608 Field (ret_v, 0) = Val_int (found - page->slinks);
2611 unlock (__func__);
2612 CAMLreturn (ret_v);
2615 enum { uuri, utext, uannot };
2617 CAMLprim value ml_getlink (value ptr_v, value n_v)
2619 CAMLparam2 (ptr_v, n_v);
2620 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2621 fz_link *link;
2622 struct page *page;
2623 char *s = String_val (ptr_v);
2624 struct slink *slink;
2626 ret_v = Val_int (0);
2627 page = parse_pointer (__func__, s);
2629 lock (__func__);
2630 ensureslinks (page);
2631 slink = &page->slinks[Int_val (n_v)];
2632 if (slink->tag == SLINK) {
2633 link = slink->u.link;
2634 str_v = caml_copy_string (link->uri);
2635 ret_v = caml_alloc_small (1, uuri);
2636 Field (ret_v, 0) = str_v;
2638 else {
2639 ret_v = caml_alloc_small (1, uannot);
2640 tup_v = caml_alloc_tuple (2);
2641 Field (ret_v, 0) = tup_v;
2642 Field (tup_v, 0) = ptr_v;
2643 Field (tup_v, 1) = n_v;
2645 unlock (__func__);
2647 CAMLreturn (ret_v);
2650 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2652 CAMLparam2 (ptr_v, n_v);
2653 CAMLlocal1 (ret_v);
2654 pdf_document *pdf;
2655 const char *contents = "";
2657 lock (__func__);
2658 pdf = pdf_specifics (state.ctx, state.doc);
2659 if (pdf) {
2660 char *s = String_val (ptr_v);
2661 struct page *page;
2662 struct slink *slink;
2664 page = parse_pointer (__func__, s);
2665 slink = &page->slinks[Int_val (n_v)];
2666 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2668 unlock (__func__);
2669 ret_v = caml_copy_string (contents);
2670 CAMLreturn (ret_v);
2673 CAMLprim value ml_getlinkcount (value ptr_v)
2675 CAMLparam1 (ptr_v);
2676 struct page *page;
2677 char *s = String_val (ptr_v);
2679 page = parse_pointer (__func__, s);
2680 CAMLreturn (Val_int (page->slinkcount));
2683 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2685 CAMLparam2 (ptr_v, n_v);
2686 CAMLlocal1 (ret_v);
2687 struct page *page;
2688 struct slink *slink;
2689 char *s = String_val (ptr_v);
2691 page = parse_pointer (__func__, s);
2692 ret_v = caml_alloc_tuple (4);
2693 lock (__func__);
2694 ensureslinks (page);
2696 slink = &page->slinks[Int_val (n_v)];
2697 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2698 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2699 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2700 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2701 unlock (__func__);
2702 CAMLreturn (ret_v);
2705 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2707 CAMLparam3 (ptr_v, x_v, y_v);
2708 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2709 fz_link *link;
2710 struct annot *annot;
2711 struct page *page;
2712 char *ptr = String_val (ptr_v);
2713 int x = Int_val (x_v), y = Int_val (y_v);
2714 struct pagedim *pdim;
2716 ret_v = Val_int (0);
2717 if (trylock (__func__)) {
2718 goto done;
2721 page = parse_pointer (__func__, ptr);
2722 pdim = &state.pagedims[page->pdimno];
2723 x += pdim->bounds.x0;
2724 y += pdim->bounds.y0;
2727 annot = getannot (page, x, y);
2728 if (annot) {
2729 int i, n = -1;
2731 ensureslinks (page);
2732 for (i = 0; i < page->slinkcount; ++i) {
2733 if (page->slinks[i].tag == SANNOT
2734 && page->slinks[i].u.annot == annot->annot) {
2735 n = i;
2736 break;
2739 ret_v = caml_alloc_small (1, uannot);
2740 tup_v = caml_alloc_tuple (2);
2741 Field (ret_v, 0) = tup_v;
2742 Field (tup_v, 0) = ptr_v;
2743 Field (tup_v, 1) = Val_int (n);
2744 goto unlock;
2748 link = getlink (page, x, y);
2749 if (link) {
2750 str_v = caml_copy_string (link->uri);
2751 ret_v = caml_alloc_small (1, uuri);
2752 Field (ret_v, 0) = str_v;
2754 else {
2755 fz_rect *b;
2756 fz_stext_block *block;
2758 ensuretext (page);
2760 for (block = page->text->first_block; block; block = block->next) {
2761 fz_stext_line *line;
2763 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2764 b = &block->bbox;
2765 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2766 continue;
2768 for (line = block->u.t.first_line; line; line = line->next) {
2769 fz_stext_char *ch;
2771 b = &line->bbox;
2772 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2773 continue;
2775 for (ch = line->first_char; ch; ch = ch->next) {
2776 fz_quad *q = &ch->quad;
2778 if (x >= q->ul.x && x <= q->ur.x
2779 && y >= q->ul.y && y <= q->ll.y) {
2780 const char *n2 = fz_font_name (state.ctx, ch->font);
2781 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2782 ch->font);
2784 if (!n2) n2 = "<unknown font>";
2786 if (face && face->family_name) {
2787 char *s;
2788 char *n1 = face->family_name;
2789 size_t l1 = strlen (n1);
2790 size_t l2 = strlen (n2);
2792 if (l1 != l2 || memcmp (n1, n2, l1)) {
2793 s = malloc (l1 + l2 + 2);
2794 if (s) {
2795 memcpy (s, n2, l2);
2796 s[l2] = '=';
2797 memcpy (s + l2 + 1, n1, l1 + 1);
2798 str_v = caml_copy_string (s);
2799 free (s);
2803 if (str_v == Val_unit) {
2804 str_v = caml_copy_string (n2);
2806 ret_v = caml_alloc_small (1, utext);
2807 Field (ret_v, 0) = str_v;
2808 goto unlock;
2814 unlock:
2815 unlock (__func__);
2817 done:
2818 CAMLreturn (ret_v);
2821 enum { mark_page, mark_block, mark_line, mark_word };
2823 CAMLprim void ml_clearmark (value ptr_v)
2825 CAMLparam1 (ptr_v);
2826 char *s = String_val (ptr_v);
2827 struct page *page;
2829 if (trylock (__func__)) {
2830 goto done;
2833 page = parse_pointer (__func__, s);
2834 page->fmark = NULL;
2835 page->lmark = NULL;
2837 unlock (__func__);
2838 done:
2839 CAMLreturn0;
2842 static int uninteresting (int c)
2844 return isspace (c) || ispunct (c);
2847 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2849 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2850 CAMLlocal1 (ret_v);
2851 fz_rect *b;
2852 struct page *page;
2853 fz_stext_line *line;
2854 fz_stext_block *block;
2855 struct pagedim *pdim;
2856 int mark = Int_val (mark_v);
2857 char *s = String_val (ptr_v);
2858 int x = Int_val (x_v), y = Int_val (y_v);
2860 ret_v = Val_bool (0);
2861 if (trylock (__func__)) {
2862 goto done;
2865 page = parse_pointer (__func__, s);
2866 pdim = &state.pagedims[page->pdimno];
2868 ensuretext (page);
2870 if (mark == mark_page) {
2871 page->fmark = page->text->first_block->u.t.first_line->first_char;
2872 page->lmark = page->text->last_block->u.t.last_line->last_char;
2873 ret_v = Val_bool (1);
2874 goto unlock;
2877 x += pdim->bounds.x0;
2878 y += pdim->bounds.y0;
2880 for (block = page->text->first_block; block; block = block->next) {
2881 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2882 b = &block->bbox;
2883 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2884 continue;
2886 if (mark == mark_block) {
2887 page->fmark = block->u.t.first_line->first_char;
2888 page->lmark = block->u.t.last_line->last_char;
2889 ret_v = Val_bool (1);
2890 goto unlock;
2893 for (line = block->u.t.first_line; line; line = line->next) {
2894 fz_stext_char *ch;
2896 b = &line->bbox;
2897 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2898 continue;
2900 if (mark == mark_line) {
2901 page->fmark = line->first_char;
2902 page->lmark = line->last_char;
2903 ret_v = Val_bool (1);
2904 goto unlock;
2907 for (ch = line->first_char; ch; ch = ch->next) {
2908 fz_stext_char *ch2, *first = NULL, *last = NULL;
2909 fz_quad *q = &ch->quad;
2910 if (x >= q->ul.x && x <= q->ur.x
2911 && y >= q->ul.y && y <= q->ll.y) {
2912 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2913 if (uninteresting (ch2->c)) first = NULL;
2914 else if (!first) first = ch2;
2916 for (ch2 = ch; ch2; ch2 = ch2->next) {
2917 if (uninteresting (ch2->c)) break;
2918 last = ch2;
2921 page->fmark = first;
2922 page->lmark = last;
2923 ret_v = Val_bool (1);
2924 goto unlock;
2929 unlock:
2930 if (!Bool_val (ret_v)) {
2931 page->fmark = NULL;
2932 page->lmark = NULL;
2934 unlock (__func__);
2936 done:
2937 CAMLreturn (ret_v);
2940 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
2942 CAMLparam3 (ptr_v, x_v, y_v);
2943 CAMLlocal2 (ret_v, res_v);
2944 fz_rect *b = NULL;
2945 struct page *page;
2946 struct pagedim *pdim;
2947 fz_stext_block *block;
2948 char *s = String_val (ptr_v);
2949 int x = Int_val (x_v), y = Int_val (y_v);
2951 ret_v = Val_int (0);
2952 if (trylock (__func__)) {
2953 goto done;
2956 page = parse_pointer (__func__, s);
2957 pdim = &state.pagedims[page->pdimno];
2958 x += pdim->bounds.x0;
2959 y += pdim->bounds.y0;
2961 ensuretext (page);
2963 for (block = page->text->first_block; block; block = block->next) {
2964 switch (block->type) {
2965 case FZ_STEXT_BLOCK_TEXT:
2966 b = &block->bbox;
2967 break;
2969 case FZ_STEXT_BLOCK_IMAGE:
2970 b = &block->bbox;
2971 break;
2973 default:
2974 continue;
2977 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2978 break;
2979 b = NULL;
2981 if (b) {
2982 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2983 ret_v = caml_alloc_small (1, 1);
2984 Store_double_field (res_v, 0, (double) b->x0);
2985 Store_double_field (res_v, 1, (double) b->x1);
2986 Store_double_field (res_v, 2, (double) b->y0);
2987 Store_double_field (res_v, 3, (double) b->y1);
2988 Field (ret_v, 0) = res_v;
2990 unlock (__func__);
2992 done:
2993 CAMLreturn (ret_v);
2996 CAMLprim void ml_seltext (value ptr_v, value rect_v)
2998 CAMLparam2 (ptr_v, rect_v);
2999 struct page *page;
3000 struct pagedim *pdim;
3001 char *s = String_val (ptr_v);
3002 int x0, x1, y0, y1;
3003 fz_stext_char *ch;
3004 fz_stext_line *line;
3005 fz_stext_block *block;
3006 fz_stext_char *fc, *lc;
3008 if (trylock (__func__)) {
3009 goto done;
3012 page = parse_pointer (__func__, s);
3013 ensuretext (page);
3015 pdim = &state.pagedims[page->pdimno];
3016 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3017 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3018 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3019 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3021 if (y0 > y1) {
3022 int t = y0;
3023 y0 = y1;
3024 y1 = t;
3025 x0 = x1;
3026 x1 = t;
3029 fc = page->fmark;
3030 lc = page->lmark;
3032 for (block = page->text->first_block; block; block = block->next) {
3033 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3034 for (line = block->u.t.first_line; line; line = line->next) {
3035 for (ch = line->first_char; ch; ch = ch->next) {
3036 fz_quad q = ch->quad;
3037 if (x0 >= q.ul.x && x0 <= q.ur.x
3038 && y0 >= q.ul.y && y0 <= q.ll.y) {
3039 fc = ch;
3041 if (x1 >= q.ul.x && x1 <= q.ur.x
3042 && y1 >= q.ul.y && y1 <= q.ll.y) {
3043 lc = ch;
3048 if (x1 < x0 && fc == lc) {
3049 fz_stext_char *t;
3051 t = fc;
3052 fc = lc;
3053 lc = t;
3056 page->fmark = fc;
3057 page->lmark = lc;
3059 unlock (__func__);
3061 done:
3062 CAMLreturn0;
3065 static int pipechar (FILE *f, fz_stext_char *ch)
3067 char buf[4];
3068 int len;
3069 size_t ret;
3071 len = fz_runetochar (buf, ch->c);
3072 ret = fwrite (buf, len, 1, f);
3073 if (ret != 1) {
3074 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3075 len, ret, errno, strerror (errno));
3076 return -1;
3078 return 0;
3081 CAMLprim value ml_spawn (value command_v, value fds_v)
3083 CAMLparam2 (command_v, fds_v);
3084 CAMLlocal2 (l_v, tup_v);
3085 int ret, ret1;
3086 pid_t pid = (pid_t) -1;
3087 char *msg = NULL;
3088 value earg_v = Nothing;
3089 posix_spawnattr_t attr;
3090 posix_spawn_file_actions_t fa;
3091 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3093 argv[2] = String_val (command_v);
3095 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3096 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3099 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3100 msg = "posix_spawnattr_init";
3101 goto fail1;
3104 #ifdef POSIX_SPAWN_USEVFORK
3105 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3106 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3107 goto fail;
3109 #endif
3111 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3112 int fd1, fd2;
3114 tup_v = Field (l_v, 0);
3115 fd1 = Int_val (Field (tup_v, 0));
3116 fd2 = Int_val (Field (tup_v, 1));
3117 if (fd2 < 0) {
3118 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3119 msg = "posix_spawn_file_actions_addclose";
3120 earg_v = tup_v;
3121 goto fail;
3124 else {
3125 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3126 msg = "posix_spawn_file_actions_adddup2";
3127 earg_v = tup_v;
3128 goto fail;
3133 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3134 msg = "posix_spawn";
3135 goto fail;
3138 fail:
3139 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3140 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3143 fail1:
3144 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3145 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3146 ret1, strerror (ret1));
3149 if (msg)
3150 unix_error (ret, msg, earg_v);
3152 CAMLreturn (Val_int (pid));
3155 CAMLprim value ml_hassel (value ptr_v)
3157 CAMLparam1 (ptr_v);
3158 CAMLlocal1 (ret_v);
3159 struct page *page;
3160 char *s = String_val (ptr_v);
3162 ret_v = Val_bool (0);
3163 if (trylock (__func__)) {
3164 goto done;
3167 page = parse_pointer (__func__, s);
3168 ret_v = Val_bool (page->fmark && page->lmark);
3169 unlock (__func__);
3170 done:
3171 CAMLreturn (ret_v);
3174 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3176 CAMLparam2 (fd_v, ptr_v);
3177 FILE *f;
3178 int seen = 0;
3179 struct page *page;
3180 fz_stext_line *line;
3181 fz_stext_block *block;
3182 int fd = Int_val (fd_v);
3183 char *s = String_val (ptr_v);
3185 if (trylock (__func__)) {
3186 goto done;
3189 page = parse_pointer (__func__, s);
3191 if (!page->fmark || !page->lmark) {
3192 printd ("emsg nothing to copy on page %d", page->pageno);
3193 goto unlock;
3196 f = fdopen (fd, "w");
3197 if (!f) {
3198 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3199 fd, errno, strerror (errno));
3200 f = stdout;
3203 for (block = page->text->first_block; block; block = block->next) {
3204 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3205 for (line = block->u.t.first_line; line; line = line->next) {
3206 fz_stext_char *ch;
3207 for (ch = line->first_char; ch; ch = ch->next) {
3208 if (seen || ch == page->fmark) {
3209 do {
3210 pipechar (f, ch);
3211 if (ch == page->lmark) goto close;
3212 } while ((ch = ch->next));
3213 seen = 1;
3214 break;
3217 if (seen) fputc ('\n', f);
3220 close:
3221 if (f != stdout) {
3222 int ret = fclose (f);
3223 fd = -1;
3224 if (ret == -1) {
3225 if (errno != ECHILD) {
3226 printd ("emsg failed to close sel pipe: %d:%s",
3227 errno, strerror (errno));
3231 unlock:
3232 unlock (__func__);
3234 done:
3235 if (fd >= 0) {
3236 if (close (fd)) {
3237 printd ("emsg failed to close sel pipe: %d:%s",
3238 errno, strerror (errno));
3241 CAMLreturn0;
3244 CAMLprim value ml_getpdimrect (value pagedimno_v)
3246 CAMLparam1 (pagedimno_v);
3247 CAMLlocal1 (ret_v);
3248 int pagedimno = Int_val (pagedimno_v);
3249 fz_rect box;
3251 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3252 if (trylock (__func__)) {
3253 box = fz_empty_rect;
3255 else {
3256 box = state.pagedims[pagedimno].mediabox;
3257 unlock (__func__);
3260 Store_double_field (ret_v, 0, (double) box.x0);
3261 Store_double_field (ret_v, 1, (double) box.x1);
3262 Store_double_field (ret_v, 2, (double) box.y0);
3263 Store_double_field (ret_v, 3, (double) box.y1);
3265 CAMLreturn (ret_v);
3268 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3269 value dw_v, value cols_v)
3271 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3272 CAMLlocal1 (ret_v);
3273 int i;
3274 float zoom = -1.;
3275 float maxh = 0.0;
3276 struct pagedim *p;
3277 float winw = Int_val (winw_v);
3278 float winh = Int_val (winh_v);
3279 float dw = Int_val (dw_v);
3280 float cols = Int_val (cols_v);
3281 float pw = 1.0, ph = 1.0;
3283 if (trylock (__func__)) {
3284 goto done;
3287 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3288 float w = p->pagebox.x1 / cols;
3289 float h = p->pagebox.y1;
3290 if (h > maxh) {
3291 maxh = h;
3292 ph = h;
3293 if (state.fitmodel != FitProportional) pw = w;
3295 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3298 zoom = (((winh / ph) * pw) + dw) / winw;
3299 unlock (__func__);
3300 done:
3301 ret_v = caml_copy_double ((double) zoom);
3302 CAMLreturn (ret_v);
3305 CAMLprim value ml_getmaxw (value unit_v)
3307 CAMLparam1 (unit_v);
3308 CAMLlocal1 (ret_v);
3309 int i;
3310 float maxw = -1.;
3311 struct pagedim *p;
3313 if (trylock (__func__)) {
3314 goto done;
3317 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3318 float w = p->pagebox.x1;
3319 maxw = fz_max (maxw, w);
3322 unlock (__func__);
3323 done:
3324 ret_v = caml_copy_double ((double) maxw);
3325 CAMLreturn (ret_v);
3328 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3330 CAMLparam4 (pt_v, x_v, y_v, string_v);
3331 CAMLlocal1 (ret_v);
3332 int pt = Int_val(pt_v);
3333 int x = Int_val (x_v);
3334 int y = Int_val (y_v);
3335 double w;
3337 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3338 ret_v = caml_copy_double (w);
3339 CAMLreturn (ret_v);
3342 CAMLprim value ml_measure_string (value pt_v, value string_v)
3344 CAMLparam2 (pt_v, string_v);
3345 CAMLlocal1 (ret_v);
3346 int pt = Int_val (pt_v);
3347 double w;
3349 w = (double) measure_string (state.face, pt, String_val (string_v));
3350 ret_v = caml_copy_double (w);
3351 CAMLreturn (ret_v);
3354 CAMLprim value ml_getpagebox (value opaque_v)
3356 CAMLparam1 (opaque_v);
3357 CAMLlocal1 (ret_v);
3358 fz_rect rect;
3359 fz_irect bbox;
3360 fz_device *dev;
3361 char *s = String_val (opaque_v);
3362 struct page *page = parse_pointer (__func__, s);
3364 ret_v = caml_alloc_tuple (4);
3365 dev = fz_new_bbox_device (state.ctx, &rect);
3367 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3369 fz_close_device (state.ctx, dev);
3370 fz_drop_device (state.ctx, dev);
3371 bbox = fz_round_rect (rect);
3372 Field (ret_v, 0) = Val_int (bbox.x0);
3373 Field (ret_v, 1) = Val_int (bbox.y0);
3374 Field (ret_v, 2) = Val_int (bbox.x1);
3375 Field (ret_v, 3) = Val_int (bbox.y1);
3377 CAMLreturn (ret_v);
3380 CAMLprim void ml_setaalevel (value level_v)
3382 CAMLparam1 (level_v);
3384 state.aalevel = Int_val (level_v);
3385 CAMLreturn0;
3388 #ifndef CIDER
3389 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3391 CAMLparam1 (keysym_v);
3392 CAMLlocal1 (str_v);
3393 KeySym keysym = Int_val (keysym_v);
3394 Rune rune;
3395 extern long keysym2ucs (KeySym);
3396 int len;
3397 char buf[5];
3399 rune = (Rune) keysym2ucs (keysym);
3400 len = fz_runetochar (buf, rune);
3401 buf[len] = 0;
3402 str_v = caml_copy_string (buf);
3403 CAMLreturn (str_v);
3405 #else
3406 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3408 CAMLparam1 (keysym_v);
3409 CAMLlocal1 (str_v);
3410 long ucs_v = Long_val (keysym_v);
3411 int len;
3412 char buf[5];
3414 len = fz_runetochar (buf, (int) ucs_v);
3415 buf[len] = 0;
3416 str_v = caml_copy_string (buf);
3417 CAMLreturn (str_v);
3419 #endif
3421 enum { piunknown, pilinux, pimacos, pibsd };
3423 CAMLprim value ml_platform (value unit_v)
3425 CAMLparam1 (unit_v);
3426 CAMLlocal2 (tup_v, arr_v);
3427 int platid = piunknown;
3428 struct utsname buf;
3430 #if defined __linux__
3431 platid = pilinux;
3432 #elif defined __DragonFly__ || defined __FreeBSD__
3433 || defined __OpenBSD__ || defined __NetBSD__
3434 platid = pibsd;
3435 #elif defined __APPLE__
3436 platid = pimacos;
3437 #endif
3438 if (uname (&buf)) err (1, "uname");
3440 tup_v = caml_alloc_tuple (2);
3442 char const *sar[] = {
3443 buf.sysname,
3444 buf.release,
3445 buf.version,
3446 buf.machine,
3447 NULL
3449 arr_v = caml_copy_string_array (sar);
3451 Field (tup_v, 0) = Val_int (platid);
3452 Field (tup_v, 1) = arr_v;
3453 CAMLreturn (tup_v);
3456 CAMLprim void ml_cloexec (value fd_v)
3458 CAMLparam1 (fd_v);
3459 int fd = Int_val (fd_v);
3461 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3462 uerror ("fcntl", Nothing);
3464 CAMLreturn0;
3467 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3469 CAMLparam2 (w_v, h_v);
3470 CAMLlocal1 (ret_v);
3471 struct bo *pbo;
3472 int w = Int_val (w_v);
3473 int h = Int_val (h_v);
3474 int cs = Int_val (cs_v);
3476 if (state.bo_usable) {
3477 pbo = calloc (sizeof (*pbo), 1);
3478 if (!pbo) {
3479 err (1, "calloc pbo");
3482 switch (cs) {
3483 case 0:
3484 case 1:
3485 pbo->size = w*h*4;
3486 break;
3487 case 2:
3488 pbo->size = w*h*2;
3489 break;
3490 default:
3491 errx (1, "%s: invalid colorspace %d", __func__, cs);
3494 state.glGenBuffersARB (1, &pbo->id);
3495 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3496 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3497 NULL, GL_STREAM_DRAW);
3498 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3499 GL_READ_WRITE);
3500 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3501 if (!pbo->ptr) {
3502 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3503 state.glDeleteBuffersARB (1, &pbo->id);
3504 free (pbo);
3505 ret_v = caml_copy_string ("0");
3507 else {
3508 int res;
3509 char *s;
3511 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3512 if (res < 0) {
3513 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3515 s = malloc (res+1);
3516 if (!s) {
3517 err (1, "malloc %d bytes failed", res+1);
3519 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3520 if (res < 0) {
3521 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3523 ret_v = caml_copy_string (s);
3524 free (s);
3527 else {
3528 ret_v = caml_copy_string ("0");
3530 CAMLreturn (ret_v);
3533 CAMLprim void ml_freepbo (value s_v)
3535 CAMLparam1 (s_v);
3536 char *s = String_val (s_v);
3537 struct tile *tile = parse_pointer (__func__, s);
3539 if (tile->pbo) {
3540 state.glDeleteBuffersARB (1, &tile->pbo->id);
3541 tile->pbo->id = -1;
3542 tile->pbo->ptr = NULL;
3543 tile->pbo->size = -1;
3545 CAMLreturn0;
3548 CAMLprim void ml_unmappbo (value s_v)
3550 CAMLparam1 (s_v);
3551 char *s = String_val (s_v);
3552 struct tile *tile = parse_pointer (__func__, s);
3554 if (tile->pbo) {
3555 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3556 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3557 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3559 tile->pbo->ptr = NULL;
3560 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3562 CAMLreturn0;
3565 static void setuppbo (void)
3567 extern void (*wsigladdr (const char *name)) (void);
3568 #pragma GCC diagnostic push
3569 #ifdef __clang__
3570 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3571 #endif
3572 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3573 state.bo_usable = GPA (glBindBufferARB)
3574 && GPA (glUnmapBufferARB)
3575 && GPA (glMapBufferARB)
3576 && GPA (glBufferDataARB)
3577 && GPA (glGenBuffersARB)
3578 && GPA (glDeleteBuffersARB);
3579 #undef GPA
3580 #pragma GCC diagnostic pop
3583 CAMLprim value ml_bo_usable (void)
3585 return Val_bool (state.bo_usable);
3588 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3590 CAMLparam3 (ptr_v, x_v, y_v);
3591 CAMLlocal2 (ret_v, tup_v);
3592 struct page *page;
3593 char *s = String_val (ptr_v);
3594 int x = Int_val (x_v), y = Int_val (y_v);
3595 struct pagedim *pdim;
3596 fz_point p;
3598 page = parse_pointer (__func__, s);
3599 pdim = &state.pagedims[page->pdimno];
3601 ret_v = Val_int (0);
3602 if (trylock (__func__)) {
3603 goto done;
3606 p.x = x + pdim->bounds.x0;
3607 p.y = y + pdim->bounds.y0;
3609 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3610 pdim->ctm)));
3612 tup_v = caml_alloc_tuple (2);
3613 ret_v = caml_alloc_small (1, 1);
3614 Field (tup_v, 0) = Val_int (p.x);
3615 Field (tup_v, 1) = Val_int (p.y);
3616 Field (ret_v, 0) = tup_v;
3618 unlock (__func__);
3619 done:
3620 CAMLreturn (ret_v);
3623 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3624 value x_v, value y_v)
3626 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3627 CAMLlocal1 (ret_v);
3628 struct page *page;
3629 char *s = String_val (ptr_v);
3630 int pageno = Int_val (pageno_v);
3631 int pdimno = Int_val (pdimno_v);
3632 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3633 struct pagedim *pdim;
3634 fz_point p;
3635 fz_matrix ctm;
3637 ret_v = Val_int (0);
3638 lock (__func__);
3640 if (!*s) {
3641 page = loadpage (pageno, pdimno);
3643 else {
3644 page = parse_pointer (__func__, s);
3646 pdim = &state.pagedims[pdimno];
3648 if (pdf_specifics (state.ctx, state.doc)) {
3649 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3650 ctm = state.pagedims[page->pdimno].tctm;
3652 else {
3653 ctm = fz_identity;
3655 p.x = x + pdim->bounds.x0;
3656 p.y = y + pdim->bounds.y0;
3658 ctm = fz_concat (pdim->tctm, pdim->ctm);
3659 p = fz_transform_point (p, ctm);
3661 ret_v = caml_alloc_tuple (2);
3662 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3663 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3665 if (!*s) {
3666 freepage (page);
3668 unlock (__func__);
3669 CAMLreturn (ret_v);
3672 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
3673 value contents_v)
3675 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3676 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3678 if (pdf) {
3679 pdf_annot *annot;
3680 struct page *page;
3681 fz_point p;
3682 char *s = String_val (ptr_v);
3684 page = parse_pointer (__func__, s);
3685 annot = pdf_create_annot (state.ctx,
3686 pdf_page_from_fz_page (state.ctx,
3687 page->fzpage),
3688 PDF_ANNOT_TEXT);
3689 p.x = Int_val (x_v);
3690 p.y = Int_val (y_v);
3691 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3692 pdf_set_text_annot_position (state.ctx, annot, p);
3693 state.dirty = 1;
3695 CAMLreturn0;
3698 CAMLprim void ml_delannot (value ptr_v, value n_v)
3700 CAMLparam2 (ptr_v, n_v);
3701 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3703 if (pdf) {
3704 struct page *page;
3705 char *s = String_val (ptr_v);
3706 struct slink *slink;
3708 page = parse_pointer (__func__, s);
3709 slink = &page->slinks[Int_val (n_v)];
3710 pdf_delete_annot (state.ctx,
3711 pdf_page_from_fz_page (state.ctx, page->fzpage),
3712 (pdf_annot *) slink->u.annot);
3713 state.dirty = 1;
3715 CAMLreturn0;
3718 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
3720 CAMLparam3 (ptr_v, n_v, str_v);
3721 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3723 if (pdf) {
3724 struct page *page;
3725 char *s = String_val (ptr_v);
3726 struct slink *slink;
3728 page = parse_pointer (__func__, s);
3729 slink = &page->slinks[Int_val (n_v)];
3730 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3731 String_val (str_v));
3732 state.dirty = 1;
3734 CAMLreturn0;
3737 CAMLprim value ml_hasunsavedchanges (void)
3739 return Val_bool (state.dirty);
3742 CAMLprim void ml_savedoc (value path_v)
3744 CAMLparam1 (path_v);
3745 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3747 if (pdf) {
3748 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3750 CAMLreturn0;
3753 static void makestippletex (void)
3755 const char pixels[] = "\xff\xff\0\0";
3756 glGenTextures (1, &state.stid);
3757 glBindTexture (GL_TEXTURE_1D, state.stid);
3758 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3759 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3760 glTexImage1D (
3761 GL_TEXTURE_1D,
3763 GL_ALPHA,
3766 GL_ALPHA,
3767 GL_UNSIGNED_BYTE,
3768 pixels
3772 CAMLprim value ml_fz_version (void)
3774 return caml_copy_string (FZ_VERSION);
3777 CAMLprim value ml_llpp_version (void)
3779 extern char llpp_version[];
3780 return caml_copy_string (llpp_version);
3783 CAMLprim void ml_init (value csock_v, value params_v)
3785 CAMLparam2 (csock_v, params_v);
3786 CAMLlocal2 (trim_v, fuzz_v);
3787 int ret;
3788 int texcount;
3789 char *fontpath;
3790 int colorspace;
3791 int mustoresize;
3793 state.csock = Int_val (csock_v);
3794 state.rotate = Int_val (Field (params_v, 0));
3795 state.fitmodel = Int_val (Field (params_v, 1));
3796 trim_v = Field (params_v, 2);
3797 texcount = Int_val (Field (params_v, 3));
3798 state.sliceheight = Int_val (Field (params_v, 4));
3799 mustoresize = Int_val (Field (params_v, 5));
3800 colorspace = Int_val (Field (params_v, 6));
3801 fontpath = String_val (Field (params_v, 7));
3803 #ifdef CIDER
3804 state.utf8cs = 1;
3805 #else
3806 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3807 if (setlocale (LC_CTYPE, "")) {
3808 const char *cset = nl_langinfo (CODESET);
3809 state.utf8cs = !strcmp (cset, "UTF-8");
3811 else {
3812 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3814 #endif
3816 if (caml_string_length (Field (params_v, 8)) > 0) {
3817 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3819 if (!state.trimcachepath) {
3820 printd ("emsg failed to strdup trimcachepath: %d:%s",
3821 errno, strerror (errno));
3825 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3826 fz_register_document_handlers (state.ctx);
3828 state.trimmargins = Bool_val (Field (trim_v, 0));
3829 fuzz_v = Field (trim_v, 1);
3830 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3831 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3832 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3833 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3835 set_tex_params (colorspace);
3837 if (*fontpath) {
3838 state.face = load_font (fontpath);
3840 else {
3841 int len;
3842 const unsigned char *data;
3844 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3845 state.face = load_builtin_font (data, len);
3847 if (!state.face) _exit (1);
3849 realloctexts (texcount);
3850 setuppbo ();
3851 makestippletex ();
3853 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3854 if (ret) {
3855 errx (1, "pthread_create: %s", strerror (ret));
3858 CAMLreturn0;
3861 #if FIXME || !FIXME
3862 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3863 #endif