Compress
[llpp.git] / link.c
bloba605e15d39ac21a83f43fa919cd079722c1b6cbc
1 /* lots of code c&p-ed directly from mupdf */
2 #ifdef __clang__
3 #pragma GCC diagnostic error "-Weverything"
4 #pragma GCC diagnostic ignored "-Wpadded"
5 #pragma GCC diagnostic ignored "-Wsign-conversion"
6 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
7 #pragma GCC diagnostic ignored "-Wdocumentation"
8 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
9 #endif
11 #pragma GCC diagnostic ignored "-Wdouble-promotion"
13 extern char **environ;
15 #define CAML_NAME_SPACE
16 #define FIXME 0
18 #include <errno.h>
19 #include <stdio.h>
20 #include <ctype.h>
21 #include <string.h>
22 #include <stdlib.h>
23 #include <signal.h>
25 #include <math.h>
26 #include <wchar.h>
27 #include <locale.h>
28 #include <langinfo.h>
30 #include <unistd.h>
31 #include <pthread.h>
32 #include <sys/uio.h>
33 #include <sys/time.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <sys/types.h>
37 #include <sys/ioctl.h>
38 #include <sys/utsname.h>
40 #include <spawn.h>
42 #include <regex.h>
43 #include <stdarg.h>
44 #include <limits.h>
45 #include <inttypes.h>
47 #ifdef __COCOA__
48 #include <CoreFoundation/CoreFoundation.h>
49 #include <OpenGL/gl.h>
50 #else
51 #include <GL/gl.h>
52 #endif
54 #pragma GCC diagnostic push
55 #ifdef __clang__
56 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
57 #endif
58 #pragma GCC diagnostic ignored "-Wpedantic"
59 #include <caml/fail.h>
60 #include <caml/alloc.h>
61 #include <caml/memory.h>
62 #include <caml/unixsupport.h>
64 #pragma GCC diagnostic push
65 #pragma GCC diagnostic ignored "-Wfloat-equal"
66 #include <mupdf/fitz.h>
67 #include <mupdf/pdf.h>
68 #pragma GCC diagnostic pop
70 #include <ft2build.h>
71 #include FT_FREETYPE_H
72 #pragma GCC diagnostic pop
74 #include "cutils.h"
76 #define PIGGYBACK
77 #define CACHE_PAGEREFS
79 #ifdef USE_NPOT
80 #define TEXT_TYPE GL_TEXTURE_2D
81 #else
82 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
83 #endif
85 #if 0
86 #define lprintf printf
87 #else
88 #define lprintf(...)
89 #endif
91 #define ARSERT(cond) for (;;) { \
92 if (!(cond)) { \
93 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
94 } \
95 break; \
98 struct slice {
99 int h;
100 int texindex;
103 struct tile {
104 int w, h;
105 int slicecount;
106 int sliceheight;
107 struct bo *pbo;
108 fz_pixmap *pixmap;
109 struct slice slices[1];
112 struct pagedim {
113 int pageno;
114 int rotate;
115 int left;
116 int tctmready;
117 fz_irect bounds;
118 fz_rect pagebox;
119 fz_rect mediabox;
120 fz_matrix ctm, zoomctm, tctm;
123 struct slink {
124 enum { SLINK, SANNOT } tag;
125 fz_irect bbox;
126 union {
127 fz_link *link;
128 fz_annot *annot;
129 } u;
132 struct annot {
133 fz_irect bbox;
134 fz_annot *annot;
137 struct page {
138 int tgen;
139 int sgen;
140 int agen;
141 int pageno;
142 int pdimno;
143 fz_stext_page *text;
144 fz_page *fzpage;
145 fz_display_list *dlist;
146 fz_link *links;
147 int slinkcount;
148 struct slink *slinks;
149 int annotcount;
150 struct annot *annots;
151 fz_stext_char *fmark, *lmark;
154 enum { FitWidth, FitProportional, FitPage };
156 static struct {
157 int sliceheight;
158 struct pagedim *pagedims;
159 int pagecount;
160 int pagedimcount;
161 fz_document *doc;
162 fz_context *ctx;
163 int w, h;
165 int texindex;
166 int texcount;
167 GLuint *texids;
169 GLenum texiform;
170 GLenum texform;
171 GLenum texty;
173 fz_colorspace *colorspace;
175 struct {
176 int w, h;
177 struct slice *slice;
178 } *texowners;
180 int rotate;
181 int fitmodel;
182 int trimmargins;
183 int needoutline;
184 int gen;
185 int aalevel;
187 int trimanew;
188 fz_irect trimfuzz;
189 fz_pixmap *pig;
191 pthread_t thread;
192 int csock;
193 FT_Face face;
195 char *trimcachepath;
196 int dirty;
198 GLuint stid;
200 int bo_usable;
201 GLuint boid;
203 void (*glBindBufferARB) (GLenum, GLuint);
204 GLboolean (*glUnmapBufferARB) (GLenum);
205 void *(*glMapBufferARB) (GLenum, GLenum);
206 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
207 void (*glGenBuffersARB) (GLsizei, GLuint *);
208 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
210 GLfloat texcoords[8];
211 GLfloat vertices[16];
213 #ifdef CACHE_PAGEREFS
214 struct {
215 int idx;
216 int count;
217 pdf_obj **objs;
218 pdf_document *pdf;
219 } pdflut;
220 #endif
221 int utf8cs;
222 } state;
224 struct bo {
225 GLuint id;
226 void *ptr;
227 size_t size;
230 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
232 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
235 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
237 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
240 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
242 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
243 m.a, m.b, m.c, m.d, m.e, m.f);
246 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
248 static void lock (const char *cap)
250 int ret = pthread_mutex_lock (&mutex);
251 if (ret) {
252 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
256 static void unlock (const char *cap)
258 int ret = pthread_mutex_unlock (&mutex);
259 if (ret) {
260 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
264 static int trylock (const char *cap)
266 int ret = pthread_mutex_trylock (&mutex);
267 if (ret && ret != EBUSY) {
268 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
270 return ret == EBUSY;
273 static int hasdata (void)
275 int ret, avail;
276 ret = ioctl (state.csock, FIONREAD, &avail);
277 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
278 return avail > 0;
281 CAMLprim value ml_hasdata (value fd_v)
283 CAMLparam1 (fd_v);
284 int ret, avail;
286 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
287 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
288 CAMLreturn (Val_bool (avail > 0));
291 static void readdata (int fd, void *p, int size)
293 ssize_t n;
295 again:
296 n = read (fd, p, size);
297 if (n - size) {
298 if (n < 0 && errno == EINTR) goto again;
299 if (!n) errx (1, "EOF while reading");
300 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
304 static void writedata (int fd, char *p, int size)
306 ssize_t n;
307 uint32_t size4 = size;
308 struct iovec iov[2] = {
309 { .iov_base = &size4, .iov_len = 4 },
310 { .iov_base = p, .iov_len = size }
313 again:
314 n = writev (fd, iov, 2);
315 if (n < 0 && errno == EINTR) goto again;
316 if (n - size - 4) {
317 if (!n) errx (1, "EOF while writing data");
318 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
322 static int readlen (int fd)
324 uint32_t u;
325 readdata (fd, &u, 4);
326 return u;
329 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
331 CAMLparam3 (fd_v, bytes_v, len_v);
332 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
333 CAMLreturn0;
336 CAMLprim value ml_rcmd (value fd_v)
338 CAMLparam1 (fd_v);
339 CAMLlocal1 (strdata_v);
340 int fd = Int_val (fd_v);
341 int len = readlen (fd);
342 strdata_v = caml_alloc_string (len);
343 readdata (fd, String_val (strdata_v), len);
344 CAMLreturn (strdata_v);
347 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
349 char fbuf[64];
350 int size = sizeof (fbuf), len;
351 va_list ap;
352 char *buf = fbuf;
354 for (;;) {
355 va_start (ap, fmt);
356 len = vsnprintf (buf, size, fmt, ap);
357 va_end (ap);
359 if (len > -1) {
360 if (len < size - 4) {
361 writedata (state.csock, buf, len);
362 break;
364 else size = len + 5;
366 else {
367 err (1, "vsnprintf for `%s' failed", fmt);
369 buf = realloc (buf == fbuf ? NULL : buf, size);
370 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
372 if (buf != fbuf) free (buf);
375 static void closedoc (void)
377 #ifdef CACHE_PAGEREFS
378 if (state.pdflut.objs) {
379 for (int i = 0; i < state.pdflut.count; ++i) {
380 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
382 free (state.pdflut.objs);
383 state.pdflut.objs = NULL;
384 state.pdflut.idx = 0;
386 #endif
387 if (state.doc) {
388 fz_drop_document (state.ctx, state.doc);
389 state.doc = NULL;
393 static int openxref (char *filename, char *password, int layouth)
395 for (int i = 0; i < state.texcount; ++i) {
396 state.texowners[i].w = -1;
397 state.texowners[i].slice = NULL;
400 closedoc ();
402 state.dirty = 0;
403 if (state.pagedims) {
404 free (state.pagedims);
405 state.pagedims = NULL;
407 state.pagedimcount = 0;
409 fz_set_aa_level (state.ctx, state.aalevel);
410 state.doc = fz_open_document (state.ctx, filename);
411 if (fz_needs_password (state.ctx, state.doc)) {
412 if (password && !*password) {
413 printd ("pass");
414 return 0;
416 else {
417 int ok = fz_authenticate_password (state.ctx, state.doc, password);
418 if (!ok) {
419 printd ("pass fail");
420 return 0;
424 if (layouth >= 0)
425 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
426 state.pagecount = fz_count_pages (state.ctx, state.doc);
427 return 1;
430 static void docinfo (void)
432 struct { char *tag; char *name; } metatbl[] = {
433 { FZ_META_INFO_TITLE, "Title" },
434 { FZ_META_INFO_AUTHOR, "Author" },
435 { FZ_META_FORMAT, "Format" },
436 { FZ_META_ENCRYPTION, "Encryption" },
437 { "info:Creator", "Creator" },
438 { "info:Producer", "Producer" },
439 { "info:CreationDate", "Creation date" },
441 int len = 0;
442 char *buf = NULL;
444 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
445 int need;
446 again:
447 need = fz_lookup_metadata (state.ctx, state.doc,
448 metatbl[i].tag, buf, len);
449 if (need > 0) {
450 if (need <= len) {
451 printd ("info %s\t%s", metatbl[i].name, buf);
453 else {
454 buf = realloc (buf, need + 1);
455 if (!buf) err (1, "docinfo realloc %d", need + 1);
456 len = need + 1;
457 goto again;
461 free (buf);
463 printd ("infoend");
466 static void unlinktile (struct tile *tile)
468 for (int i = 0; i < tile->slicecount; ++i) {
469 struct slice *s = &tile->slices[i];
471 if (s->texindex != -1) {
472 if (state.texowners[s->texindex].slice == s) {
473 state.texowners[s->texindex].slice = NULL;
479 static void freepage (struct page *page)
481 if (!page) return;
482 if (page->text) {
483 fz_drop_stext_page (state.ctx, page->text);
485 if (page->slinks) {
486 free (page->slinks);
488 fz_drop_display_list (state.ctx, page->dlist);
489 fz_drop_page (state.ctx, page->fzpage);
490 free (page);
493 static void freetile (struct tile *tile)
495 unlinktile (tile);
496 if (!tile->pbo) {
497 #ifndef PIGGYBACK
498 fz_drop_pixmap (state.ctx, tile->pixmap);
499 #else
500 if (state.pig) {
501 fz_drop_pixmap (state.ctx, state.pig);
503 state.pig = tile->pixmap;
504 #endif
506 else {
507 free (tile->pbo);
508 fz_drop_pixmap (state.ctx, tile->pixmap);
510 free (tile);
513 static void trimctm (pdf_page *page, int pindex)
515 fz_matrix ctm;
516 struct pagedim *pdim = &state.pagedims[pindex];
518 if (!page) return;
519 if (!pdim->tctmready) {
520 fz_rect realbox, mediabox;
521 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
523 fz_rotate (&rm, -pdim->rotate);
524 fz_scale (&sm, 1, -1);
525 fz_concat (&ctm, &rm, &sm);
526 realbox = pdim->mediabox;
527 fz_transform_rect (&realbox, &ctm);
528 fz_translate (&tm, -realbox.x0, -realbox.y0);
529 fz_concat (&ctm1, &ctm, &tm);
530 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
531 fz_invert_matrix (&im, &page_ctm);
532 fz_concat (&ctm, &im, &ctm1);
533 pdim->tctm = ctm;
534 pdim->tctmready = 1;
538 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
540 fz_matrix ctm, tm;
541 ptrdiff_t pdimno = pdim - state.pagedims;
543 ARSERT (pdim - state.pagedims < INT_MAX);
544 if (pdf_specifics (state.ctx, state.doc)) {
545 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
546 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
548 else {
549 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
550 fz_concat (&ctm, &tm, &pdim->ctm);
552 return ctm;
555 static fz_matrix pagectm (struct page *page)
557 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
560 static void *loadpage (int pageno, int pindex)
562 fz_device *dev;
563 struct page *page;
565 page = calloc (sizeof (struct page), 1);
566 if (!page) {
567 err (1, "calloc page %d", pageno);
570 page->dlist = fz_new_display_list (state.ctx, NULL);
571 dev = fz_new_list_device (state.ctx, page->dlist);
572 fz_try (state.ctx) {
573 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
574 fz_run_page (state.ctx, page->fzpage, dev,
575 &fz_identity, NULL);
577 fz_catch (state.ctx) {
578 page->fzpage = NULL;
580 fz_close_device (state.ctx, dev);
581 fz_drop_device (state.ctx, dev);
583 page->pdimno = pindex;
584 page->pageno = pageno;
585 page->sgen = state.gen;
586 page->agen = state.gen;
587 page->tgen = state.gen;
588 return page;
591 static struct tile *alloctile (int h)
593 int slicecount;
594 size_t tilesize;
595 struct tile *tile;
597 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
598 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
599 tile = calloc (tilesize, 1);
600 if (!tile) {
601 err (1, "cannot allocate tile (%zu bytes)", tilesize);
603 for (int i = 0; i < slicecount; ++i) {
604 int sh = fz_mini (h, state.sliceheight);
605 tile->slices[i].h = sh;
606 tile->slices[i].texindex = -1;
607 h -= sh;
609 tile->slicecount = slicecount;
610 tile->sliceheight = state.sliceheight;
611 return tile;
614 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
615 struct bo *pbo)
617 fz_rect rect;
618 fz_irect bbox;
619 fz_matrix ctm;
620 fz_device *dev;
621 struct tile *tile;
622 struct pagedim *pdim;
624 tile = alloctile (h);
625 pdim = &state.pagedims[page->pdimno];
627 bbox = pdim->bounds;
628 bbox.x0 += x;
629 bbox.y0 += y;
630 bbox.x1 = bbox.x0 + w;
631 bbox.y1 = bbox.y0 + h;
633 if (state.pig) {
634 if (state.pig->w == w
635 && state.pig->h == h
636 && state.pig->colorspace == state.colorspace) {
637 tile->pixmap = state.pig;
638 tile->pixmap->x = bbox.x0;
639 tile->pixmap->y = bbox.y0;
641 else {
642 fz_drop_pixmap (state.ctx, state.pig);
644 state.pig = NULL;
646 if (!tile->pixmap) {
647 if (pbo) {
648 tile->pixmap =
649 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
650 &bbox, NULL, 1, pbo->ptr);
651 tile->pbo = pbo;
653 else {
654 tile->pixmap =
655 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
656 NULL, 1);
660 tile->w = w;
661 tile->h = h;
662 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
664 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
665 ctm = pagectm (page);
666 fz_rect_from_irect (&rect, &bbox);
667 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
668 fz_close_device (state.ctx, dev);
669 fz_drop_device (state.ctx, dev);
671 return tile;
674 #ifdef CACHE_PAGEREFS
675 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
676 thanks to Robin Watts */
677 static void
678 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
680 fz_context *ctx = state.ctx; /* doc->ctx; */
681 pdf_obj *kids;
682 int len;
684 if (state.pdflut.idx == state.pagecount) return;
686 kids = pdf_dict_gets (ctx, node, "Kids");
687 len = pdf_array_len (ctx, kids);
689 if (len == 0)
690 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
692 if (pdf_mark_obj (ctx, node))
693 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
694 for (int i = 0; i < len; i++) {
695 pdf_obj *kid = pdf_array_get (ctx, kids, i);
696 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
697 if (*type
698 ? !strcmp (type, "Pages")
699 : pdf_dict_gets (ctx, kid, "Kids")
700 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
701 pdf_collect_pages (doc, kid);
703 else {
704 if (*type
705 ? strcmp (type, "Page") != 0
706 : !pdf_dict_gets (ctx, kid, "MediaBox"))
707 fz_warn (ctx, "non-page object in page tree (%s)", type);
708 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
711 pdf_unmark_obj (ctx, node);
714 static void
715 pdf_load_page_objs (pdf_document *doc)
717 pdf_obj *root = pdf_dict_gets (state.ctx,
718 pdf_trailer (state.ctx, doc), "Root");
719 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
721 if (!node)
722 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
724 state.pdflut.idx = 0;
725 pdf_collect_pages (doc, node);
727 #endif
729 static void initpdims (void)
731 double start, end;
732 FILE *trimf = NULL;
733 fz_rect rootmediabox = fz_empty_rect;
734 int pageno, trim, show;
735 int trimw = 0, cxcount;
736 fz_context *ctx = state.ctx;
737 pdf_document *pdf = pdf_specifics (ctx, state.doc);
739 fz_var (trimw);
740 fz_var (trimf);
741 fz_var (cxcount);
742 start = now ();
744 if (state.trimmargins && state.trimcachepath) {
745 trimf = fopen (state.trimcachepath, "rb");
746 if (!trimf) {
747 trimf = fopen (state.trimcachepath, "wb");
748 trimw = 1;
752 if (state.trimmargins || pdf)
753 cxcount = state.pagecount;
754 else
755 cxcount = fz_mini (state.pagecount, 1);
757 if (pdf) {
758 pdf_obj *obj;
759 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
760 "Root/Pages/MediaBox");
761 pdf_to_rect (ctx, obj, &rootmediabox);
764 #ifdef CACHE_PAGEREFS
765 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
766 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
767 if (!state.pdflut.objs) {
768 err (1, "malloc pageobjs %zu %d %zu failed",
769 sizeof (*state.pdflut.objs), cxcount,
770 sizeof (*state.pdflut.objs) * cxcount);
772 state.pdflut.count = cxcount;
773 pdf_load_page_objs (pdf);
774 state.pdflut.pdf = pdf;
776 #endif
778 for (pageno = 0; pageno < cxcount; ++pageno) {
779 int rotate = 0;
780 struct pagedim *p;
781 fz_rect mediabox = fz_empty_rect;
783 fz_var (rotate);
784 if (pdf) {
785 pdf_obj *pageref, *pageobj;
787 #ifdef CACHE_PAGEREFS
788 pageref = state.pdflut.objs[pageno];
789 #else
790 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
791 #endif
792 pageobj = pdf_resolve_indirect (ctx, pageref);
793 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
795 if (state.trimmargins) {
796 pdf_obj *obj;
797 pdf_page *page;
799 fz_try (ctx) {
800 page = pdf_load_page (ctx, pdf, pageno);
801 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
802 trim = state.trimanew || !obj;
803 if (trim) {
804 fz_rect rect;
805 fz_device *dev;
806 fz_matrix ctm, page_ctm;
808 dev = fz_new_bbox_device (ctx, &rect);
809 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
810 fz_invert_matrix (&ctm, &page_ctm);
811 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
812 fz_close_device (ctx, dev);
813 fz_drop_device (ctx, dev);
815 rect.x0 += state.trimfuzz.x0;
816 rect.x1 += state.trimfuzz.x1;
817 rect.y0 += state.trimfuzz.y0;
818 rect.y1 += state.trimfuzz.y1;
819 fz_transform_rect (&rect, &ctm);
820 fz_intersect_rect (&rect, &mediabox);
822 if (!fz_is_empty_rect (&rect)) {
823 mediabox = rect;
826 obj = pdf_new_array (ctx, pdf, 4);
827 pdf_array_push (ctx, obj,
828 pdf_new_real (ctx, mediabox.x0));
829 pdf_array_push (ctx, obj,
830 pdf_new_real (ctx, mediabox.y0));
831 pdf_array_push (ctx, obj,
832 pdf_new_real (ctx, mediabox.x1));
833 pdf_array_push (ctx, obj,
834 pdf_new_real (ctx, mediabox.y1));
835 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
837 else {
838 mediabox.x0 = pdf_to_real (ctx,
839 pdf_array_get (ctx, obj, 0));
840 mediabox.y0 = pdf_to_real (ctx,
841 pdf_array_get (ctx, obj, 1));
842 mediabox.x1 = pdf_to_real (ctx,
843 pdf_array_get (ctx, obj, 2));
844 mediabox.y1 = pdf_to_real (ctx,
845 pdf_array_get (ctx, obj, 3));
848 fz_drop_page (ctx, &page->super);
849 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
850 if (show) {
851 printd ("progress %f Trimming %d",
852 (double) (pageno + 1) / state.pagecount,
853 pageno + 1);
856 fz_catch (ctx) {
857 printd ("emsg failed to load page %d", pageno);
860 else {
861 int empty = 0;
862 fz_rect cropbox;
864 pdf_to_rect (ctx,
865 pdf_dict_gets (ctx, pageobj, "MediaBox"),
866 &mediabox);
867 if (fz_is_empty_rect (&mediabox)) {
868 mediabox.x0 = 0;
869 mediabox.y0 = 0;
870 mediabox.x1 = 612;
871 mediabox.y1 = 792;
872 empty = 1;
875 pdf_to_rect (ctx,
876 pdf_dict_gets (ctx, pageobj, "CropBox"),
877 &cropbox);
878 if (!fz_is_empty_rect (&cropbox)) {
879 if (empty) {
880 mediabox = cropbox;
882 else {
883 fz_intersect_rect (&mediabox, &cropbox);
886 else {
887 if (empty) {
888 if (fz_is_empty_rect (&rootmediabox)) {
889 printd ("emsg cannot find page size for page %d",
890 pageno);
892 else {
893 mediabox = rootmediabox;
899 else {
900 if (state.trimmargins && trimw) {
901 fz_page *page;
903 fz_try (ctx) {
904 page = fz_load_page (ctx, state.doc, pageno);
905 fz_bound_page (ctx, page, &mediabox);
906 if (state.trimmargins) {
907 fz_rect rect;
908 fz_device *dev;
910 dev = fz_new_bbox_device (ctx, &rect);
911 fz_run_page (ctx, page, dev, &fz_identity, NULL);
912 fz_close_device (ctx, dev);
913 fz_drop_device (ctx, dev);
915 rect.x0 += state.trimfuzz.x0;
916 rect.x1 += state.trimfuzz.x1;
917 rect.y0 += state.trimfuzz.y0;
918 rect.y1 += state.trimfuzz.y1;
919 fz_intersect_rect (&rect, &mediabox);
921 if (!fz_is_empty_rect (&rect)) {
922 mediabox = rect;
925 fz_drop_page (ctx, page);
927 fz_catch (ctx) {
929 if (trimf) {
930 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
931 if (n - 1) {
932 err (1, "fwrite trim mediabox");
936 else {
937 if (trimf) {
938 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
939 if (n - 1) {
940 err (1, "fread trim mediabox %d", pageno);
943 else {
944 fz_page *page;
945 fz_try (ctx) {
946 page = fz_load_page (ctx, state.doc, pageno);
947 fz_bound_page (ctx, page, &mediabox);
948 fz_drop_page (ctx, page);
950 show = !state.trimmargins && pageno % 20 == 0;
951 if (show) {
952 printd ("progress %f Gathering dimensions %d",
953 (double) (pageno) / state.pagecount,
954 pageno);
957 fz_catch (ctx) {
958 printd ("emsg failed to load page %d", pageno);
964 if (state.pagedimcount == 0
965 || ((void) (p = &state.pagedims[state.pagedimcount-1])
966 , p->rotate != rotate)
967 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
968 size_t size;
970 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
971 state.pagedims = realloc (state.pagedims, size);
972 if (!state.pagedims) {
973 err (1, "realloc pagedims to %zu (%d elems)",
974 size, state.pagedimcount + 1);
977 p = &state.pagedims[state.pagedimcount++];
978 p->rotate = rotate;
979 p->mediabox = mediabox;
980 p->pageno = pageno;
983 end = now ();
984 printd ("progress 1 %s %d pages in %f seconds",
985 state.trimmargins ? "Trimmed" : "Processed",
986 state.pagecount, end - start);
987 state.trimanew = 0;
988 if (trimf) {
989 if (fclose (trimf)) {
990 err (1, "fclose");
995 static void layout (void)
997 int pindex;
998 fz_rect box;
999 fz_matrix ctm, rm;
1000 struct pagedim *p = NULL;
1001 float zw, w, maxw = 0.0, zoom = 1.0;
1003 if (state.pagedimcount == 0) return;
1005 switch (state.fitmodel) {
1006 case FitProportional:
1007 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1008 float x0, x1;
1010 p = &state.pagedims[pindex];
1011 fz_rotate (&rm, p->rotate + state.rotate);
1012 box = p->mediabox;
1013 fz_transform_rect (&box, &rm);
1015 x0 = fz_min (box.x0, box.x1);
1016 x1 = fz_max (box.x0, box.x1);
1018 w = x1 - x0;
1019 maxw = fz_max (w, maxw);
1020 zoom = state.w / maxw;
1022 break;
1024 case FitPage:
1025 maxw = state.w;
1026 break;
1028 case FitWidth:
1029 break;
1031 default:
1032 ARSERT (0 && state.fitmodel);
1035 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1036 fz_rect rect;
1037 fz_matrix tm, sm;
1039 p = &state.pagedims[pindex];
1040 fz_rotate (&ctm, state.rotate);
1041 fz_rotate (&rm, p->rotate + state.rotate);
1042 box = p->mediabox;
1043 fz_transform_rect (&box, &rm);
1044 w = box.x1 - box.x0;
1045 switch (state.fitmodel) {
1046 case FitProportional:
1047 p->left = (int) (((maxw - w) * zoom) / 2.f);
1048 break;
1049 case FitPage:
1051 float zh, h;
1052 zw = maxw / w;
1053 h = box.y1 - box.y0;
1054 zh = state.h / h;
1055 zoom = fz_min (zw, zh);
1056 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1058 break;
1059 case FitWidth:
1060 p->left = 0;
1061 zoom = state.w / w;
1062 break;
1065 fz_scale (&p->zoomctm, zoom, zoom);
1066 fz_concat (&ctm, &p->zoomctm, &ctm);
1068 fz_rotate (&rm, p->rotate);
1069 p->pagebox = p->mediabox;
1070 fz_transform_rect (&p->pagebox, &rm);
1071 p->pagebox.x1 -= p->pagebox.x0;
1072 p->pagebox.y1 -= p->pagebox.y0;
1073 p->pagebox.x0 = 0;
1074 p->pagebox.y0 = 0;
1075 rect = p->pagebox;
1076 fz_transform_rect (&rect, &ctm);
1077 fz_round_rect (&p->bounds, &rect);
1078 p->ctm = ctm;
1080 fz_translate (&tm, 0, -p->mediabox.y1);
1081 fz_scale (&sm, zoom, -zoom);
1082 fz_concat (&ctm, &tm, &sm);
1084 p->tctmready = 0;
1087 do {
1088 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1089 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1090 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1091 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1092 int boundw = x1 - x0;
1093 int boundh = y1 - y0;
1095 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1096 } while (p-- != state.pagedims);
1099 struct pagedim *pdimofpageno (int pageno)
1101 struct pagedim *pdim = state.pagedims;
1103 for (int i = 0; i < state.pagedimcount; ++i) {
1104 if (state.pagedims[i].pageno > pageno)
1105 break;
1106 pdim = &state.pagedims[i];
1108 return pdim;
1111 static void recurse_outline (fz_outline *outline, int level)
1113 while (outline) {
1114 if (outline->page >= 0) {
1115 fz_point p = {.x = outline->x, .y = outline->y};
1116 struct pagedim *pdim = pdimofpageno (outline->page);
1117 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1118 fz_transform_point (&p, &pdim->ctm);
1119 printd ("o %d %d %d %d %s",
1120 level, outline->page, (int) p.y, h, outline->title);
1122 else {
1123 printd ("on %d %s", level, outline->title);
1125 if (outline->down) {
1126 recurse_outline (outline->down, level + 1);
1128 outline = outline->next;
1132 static void process_outline (void)
1134 fz_outline *outline;
1136 if (!state.needoutline || !state.pagedimcount) return;
1138 state.needoutline = 0;
1139 outline = fz_load_outline (state.ctx, state.doc);
1140 if (outline) {
1141 recurse_outline (outline, 0);
1142 fz_drop_outline (state.ctx, outline);
1146 static char *strofline (fz_stext_line *line)
1148 char *p;
1149 char utf8[10];
1150 fz_stext_char *ch;
1151 size_t size = 0, cap = 80;
1153 p = malloc (cap + 1);
1154 if (!p) return NULL;
1156 for (ch = line->first_char; ch; ch = ch->next) {
1157 int n = fz_runetochar (utf8, ch->c);
1158 if (size + n > cap) {
1159 cap *= 2;
1160 p = realloc (p, cap + 1);
1161 if (!p) return NULL;
1164 memcpy (p + size, utf8, n);
1165 size += n;
1167 p[size] = 0;
1168 return p;
1171 static int matchline (regex_t *re, fz_stext_line *line,
1172 int stop, int pageno, double start)
1174 int ret;
1175 char *p;
1176 regmatch_t rm;
1178 p = strofline (line);
1179 if (!p) return -1;
1181 ret = regexec (re, p, 1, &rm, 0);
1182 if (ret) {
1183 free (p);
1184 if (ret != REG_NOMATCH) {
1185 size_t size;
1186 char errbuf[80];
1187 size = regerror (ret, re, errbuf, sizeof (errbuf));
1188 printd ("msg regexec error `%.*s'",
1189 (int) size, errbuf);
1190 return -1;
1192 return 0;
1194 else {
1195 fz_point p1, p2, p3, p4;
1196 fz_rect s = {0,0,0,0}, e;
1197 fz_stext_char *ch;
1198 int o = 0;
1200 for (ch = line->first_char; ch; ch = ch->next) {
1201 o += fz_runelen (ch->c);
1202 if (o > rm.rm_so) {
1203 s = ch->bbox;
1204 break;
1207 for (;ch; ch = ch->next) {
1208 o += fz_runelen (ch->c);
1209 if (o > rm.rm_eo) break;
1211 e = ch->bbox;
1213 p1.x = s.x0;
1214 p1.y = s.y0;
1215 p2.x = e.x1;
1216 p2.y = s.y0;
1217 p3.x = e.x1;
1218 p3.y = e.y1;
1219 p4.x = s.x0;
1220 p4.y = e.y1;
1222 if (!stop) {
1223 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1224 pageno, 1,
1225 p1.x, p1.y,
1226 p2.x, p2.y,
1227 p3.x, p3.y,
1228 p4.x, p4.y);
1230 printd ("progress 1 found at %d `%.*s' in %f sec",
1231 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1232 now () - start);
1234 else {
1235 printd ("match %d %d %f %f %f %f %f %f %f %f",
1236 pageno, 2,
1237 p1.x, p1.y,
1238 p2.x, p2.y,
1239 p3.x, p3.y,
1240 p4.x, p4.y);
1242 free (p);
1243 return 1;
1247 /* wishful thinking function */
1248 static void search (regex_t *re, int pageno, int y, int forward)
1250 fz_device *tdev;
1251 fz_stext_page *text;
1252 struct pagedim *pdim;
1253 int stop = 0, niters = 0;
1254 double start, end;
1255 fz_page *page;
1256 fz_stext_block *block;
1258 start = now ();
1259 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1260 if (niters++ == 5) {
1261 niters = 0;
1262 if (hasdata ()) {
1263 printd ("progress 1 attention requested aborting search at %d",
1264 pageno);
1265 stop = 1;
1267 else {
1268 printd ("progress %f searching in page %d",
1269 (double) (pageno + 1) / state.pagecount,
1270 pageno);
1273 pdim = pdimofpageno (pageno);
1274 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1275 tdev = fz_new_stext_device (state.ctx, text, 0);
1277 page = fz_load_page (state.ctx, state.doc, pageno);
1279 fz_matrix ctm = pagectm1 (page, pdim);
1280 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1283 fz_close_device (state.ctx, tdev);
1284 fz_drop_device (state.ctx, tdev);
1286 if (forward) {
1287 for (block = text->first_block; block; block = block->next) {
1288 fz_stext_line *line;
1290 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1291 for (line = block->u.t.first_line; line; line = line->next) {
1292 if (line->bbox.y0 < y + 1) continue;
1294 switch (matchline (re, line, stop, pageno, start)) {
1295 case 0: break;
1296 case 1: stop = 1; break;
1297 case -1: stop = 1; goto endloop;
1302 else {
1303 for (block = text->last_block; block; block = block->prev) {
1304 fz_stext_line *line;
1306 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1307 for (line = block->u.t.last_line; line; line = line->prev) {
1308 if (line->bbox.y0 < y + 1) continue;
1310 switch (matchline (re, line, stop, pageno, start)) {
1311 case 0: break;
1312 case 1: stop = 1; break;
1313 case -1: stop = 1; goto endloop;
1319 if (forward) {
1320 pageno += 1;
1321 y = 0;
1323 else {
1324 pageno -= 1;
1325 y = INT_MAX;
1327 endloop:
1328 fz_drop_stext_page (state.ctx, text);
1329 fz_drop_page (state.ctx, page);
1331 end = now ();
1332 if (!stop) {
1333 printd ("progress 1 no matches %f sec", end - start);
1335 printd ("clearrects");
1338 static void set_tex_params (int colorspace)
1340 switch (colorspace) {
1341 case 0:
1342 state.texiform = GL_RGBA8;
1343 state.texform = GL_RGBA;
1344 state.texty = GL_UNSIGNED_BYTE;
1345 state.colorspace = fz_device_rgb (state.ctx);
1346 break;
1347 case 1:
1348 state.texiform = GL_RGBA8;
1349 state.texform = GL_BGRA;
1350 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1351 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1352 #else
1353 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1354 #endif
1355 state.colorspace = fz_device_bgr (state.ctx);
1356 break;
1357 case 2:
1358 state.texiform = GL_LUMINANCE_ALPHA;
1359 state.texform = GL_LUMINANCE_ALPHA;
1360 state.texty = GL_UNSIGNED_BYTE;
1361 state.colorspace = fz_device_gray (state.ctx);
1362 break;
1363 default:
1364 errx (1, "invalid colorspce %d", colorspace);
1368 static void realloctexts (int texcount)
1370 size_t size;
1372 if (texcount == state.texcount) return;
1374 if (texcount < state.texcount) {
1375 glDeleteTextures (state.texcount - texcount,
1376 state.texids + texcount);
1379 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1380 state.texids = realloc (state.texids, size);
1381 if (!state.texids) {
1382 err (1, "realloc texs %zu", size);
1385 state.texowners = (void *) (state.texids + texcount);
1386 if (texcount > state.texcount) {
1387 glGenTextures (texcount - state.texcount,
1388 state.texids + state.texcount);
1389 for (int i = state.texcount; i < texcount; ++i) {
1390 state.texowners[i].w = -1;
1391 state.texowners[i].slice = NULL;
1394 state.texcount = texcount;
1395 state.texindex = 0;
1398 static char *mbtoutf8 (char *s)
1400 char *p, *r;
1401 wchar_t *tmp;
1402 size_t i, ret, len;
1404 if (state.utf8cs) {
1405 return s;
1408 len = mbstowcs (NULL, s, strlen (s));
1409 if (len == 0) {
1410 return s;
1412 else {
1413 if (len == (size_t) -1) {
1414 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1415 return s;
1419 tmp = calloc (len, sizeof (wchar_t));
1420 if (!tmp) {
1421 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1422 len, sizeof (wchar_t), errno, strerror (errno));
1423 return s;
1426 ret = mbstowcs (tmp, s, len);
1427 if (ret == (size_t) -1) {
1428 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1429 len, errno, strerror (errno));
1430 free (tmp);
1431 return s;
1434 len = 0;
1435 for (i = 0; i < ret; ++i) {
1436 len += fz_runelen (tmp[i]);
1439 p = r = malloc (len + 1);
1440 if (!r) {
1441 printd ("emsg mbtoutf8: malloc(%zu)", len);
1442 free (tmp);
1443 return s;
1446 for (i = 0; i < ret; ++i) {
1447 p += fz_runetochar (p, tmp[i]);
1449 *p = 0;
1450 free (tmp);
1451 return r;
1454 CAMLprim value ml_mbtoutf8 (value s_v)
1456 CAMLparam1 (s_v);
1457 CAMLlocal1 (ret_v);
1458 char *s, *r;
1460 s = String_val (s_v);
1461 r = mbtoutf8 (s);
1462 if (r == s) {
1463 ret_v = s_v;
1465 else {
1466 ret_v = caml_copy_string (r);
1467 free (r);
1469 CAMLreturn (ret_v);
1472 static void * mainloop (void UNUSED_ATTR *unused)
1474 char *p = NULL;
1475 int len, ret, oldlen = 0;
1477 fz_var (p);
1478 fz_var (oldlen);
1479 for (;;) {
1480 len = readlen (state.csock);
1481 if (len == 0) {
1482 errx (1, "readlen returned 0");
1485 if (oldlen < len + 1) {
1486 p = realloc (p, len + 1);
1487 if (!p) {
1488 err (1, "realloc %d failed", len + 1);
1490 oldlen = len + 1;
1492 readdata (state.csock, p, len);
1493 p[len] = 0;
1495 if (!strncmp ("open", p, 4)) {
1496 int off, usedoccss, ok = 0, layouth;
1497 char *password;
1498 char *filename;
1499 char *utf8filename;
1500 size_t filenamelen;
1502 fz_var (ok);
1503 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1504 if (ret != 2) {
1505 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1508 filename = p + 5 + off;
1509 filenamelen = strlen (filename);
1510 password = filename + filenamelen + 1;
1512 if (password[strlen (password) + 1]) {
1513 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1516 lock ("open");
1517 fz_set_use_document_css (state.ctx, usedoccss);
1518 fz_try (state.ctx) {
1519 ok = openxref (filename, password, layouth);
1521 fz_catch (state.ctx) {
1522 utf8filename = mbtoutf8 (filename);
1523 printd ("msg Could not open %s", utf8filename);
1524 if (utf8filename != filename) {
1525 free (utf8filename);
1528 if (ok) {
1529 docinfo ();
1530 initpdims ();
1532 unlock ("open");
1534 if (ok) {
1535 utf8filename = mbtoutf8 (filename);
1536 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1537 if (utf8filename != filename) {
1538 free (utf8filename);
1540 state.needoutline = 1;
1543 else if (!strncmp ("cs", p, 2)) {
1544 int i, colorspace;
1546 ret = sscanf (p + 2, " %d", &colorspace);
1547 if (ret != 1) {
1548 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1550 lock ("cs");
1551 set_tex_params (colorspace);
1552 for (i = 0; i < state.texcount; ++i) {
1553 state.texowners[i].w = -1;
1554 state.texowners[i].slice = NULL;
1556 unlock ("cs");
1558 else if (!strncmp ("freepage", p, 8)) {
1559 void *ptr;
1561 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1562 if (ret != 1) {
1563 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1565 lock ("freepage");
1566 freepage (ptr);
1567 unlock ("freepage");
1569 else if (!strncmp ("freetile", p, 8)) {
1570 void *ptr;
1572 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1573 if (ret != 1) {
1574 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1576 lock ("freetile");
1577 freetile (ptr);
1578 unlock ("freetile");
1580 else if (!strncmp ("search", p, 6)) {
1581 int icase, pageno, y, len2, forward;
1582 char *pattern;
1583 regex_t re;
1585 ret = sscanf (p + 6, " %d %d %d %d,%n",
1586 &icase, &pageno, &y, &forward, &len2);
1587 if (ret != 4) {
1588 errx (1, "malformed search `%s' ret=%d", p, ret);
1591 pattern = p + 6 + len2;
1592 ret = regcomp (&re, pattern,
1593 REG_EXTENDED | (icase ? REG_ICASE : 0));
1594 if (ret) {
1595 char errbuf[80];
1596 size_t size;
1598 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1599 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1601 else {
1602 search (&re, pageno, y, forward);
1603 regfree (&re);
1606 else if (!strncmp ("geometry", p, 8)) {
1607 int w, h, fitmodel;
1609 printd ("clear");
1610 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1611 if (ret != 3) {
1612 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1615 lock ("geometry");
1616 state.h = h;
1617 if (w != state.w) {
1618 state.w = w;
1619 for (int i = 0; i < state.texcount; ++i) {
1620 state.texowners[i].slice = NULL;
1623 state.fitmodel = fitmodel;
1624 layout ();
1625 process_outline ();
1627 state.gen++;
1628 unlock ("geometry");
1629 printd ("continue %d", state.pagecount);
1631 else if (!strncmp ("reqlayout", p, 9)) {
1632 char *nameddest;
1633 int rotate, off, h;
1634 int fitmodel;
1635 pdf_document *pdf;
1637 printd ("clear");
1638 ret = sscanf (p + 9, " %d %d %d %n",
1639 &rotate, &fitmodel, &h, &off);
1640 if (ret != 3) {
1641 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1643 lock ("reqlayout");
1644 pdf = pdf_specifics (state.ctx, state.doc);
1645 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1646 state.gen += 1;
1648 state.rotate = rotate;
1649 state.fitmodel = fitmodel;
1650 state.h = h;
1651 layout ();
1652 process_outline ();
1654 nameddest = p + 9 + off;
1655 if (pdf && nameddest && *nameddest) {
1656 fz_point xy;
1657 struct pagedim *pdim;
1658 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1659 &xy.x, &xy.y);
1660 pdim = pdimofpageno (pageno);
1661 fz_transform_point (&xy, &pdim->ctm);
1662 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1665 state.gen++;
1666 unlock ("reqlayout");
1667 printd ("continue %d", state.pagecount);
1669 else if (!strncmp ("page", p, 4)) {
1670 double a, b;
1671 struct page *page;
1672 int pageno, pindex;
1674 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1675 if (ret != 2) {
1676 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1679 lock ("page");
1680 a = now ();
1681 page = loadpage (pageno, pindex);
1682 b = now ();
1683 unlock ("page");
1685 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1687 else if (!strncmp ("tile", p, 4)) {
1688 int x, y, w, h;
1689 struct page *page;
1690 struct tile *tile;
1691 double a, b;
1692 void *data;
1694 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1695 (uintptr_t *) &page, &x, &y, &w, &h,
1696 (uintptr_t *) &data);
1697 if (ret != 6) {
1698 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1701 lock ("tile");
1702 a = now ();
1703 tile = rendertile (page, x, y, w, h, data);
1704 b = now ();
1705 unlock ("tile");
1707 printd ("tile %d %d %" PRIxPTR " %u %f",
1708 x, y, (uintptr_t) (tile),
1709 tile->w * tile->h * tile->pixmap->n,
1710 b - a);
1712 else if (!strncmp ("trimset", p, 7)) {
1713 fz_irect fuzz;
1714 int trimmargins;
1716 ret = sscanf (p + 7, " %d %d %d %d %d",
1717 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1718 if (ret != 5) {
1719 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1721 lock ("trimset");
1722 state.trimmargins = trimmargins;
1723 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1724 state.trimanew = 1;
1725 state.trimfuzz = fuzz;
1727 unlock ("trimset");
1729 else if (!strncmp ("settrim", p, 7)) {
1730 fz_irect fuzz;
1731 int trimmargins;
1733 ret = sscanf (p + 7, " %d %d %d %d %d",
1734 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1735 if (ret != 5) {
1736 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1738 printd ("clear");
1739 lock ("settrim");
1740 state.trimmargins = trimmargins;
1741 state.needoutline = 1;
1742 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1743 state.trimanew = 1;
1744 state.trimfuzz = fuzz;
1746 state.pagedimcount = 0;
1747 free (state.pagedims);
1748 state.pagedims = NULL;
1749 initpdims ();
1750 layout ();
1751 process_outline ();
1752 unlock ("settrim");
1753 printd ("continue %d", state.pagecount);
1755 else if (!strncmp ("sliceh", p, 6)) {
1756 int h;
1758 ret = sscanf (p + 6, " %d", &h);
1759 if (ret != 1) {
1760 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1762 if (h != state.sliceheight) {
1763 state.sliceheight = h;
1764 for (int i = 0; i < state.texcount; ++i) {
1765 state.texowners[i].w = -1;
1766 state.texowners[i].h = -1;
1767 state.texowners[i].slice = NULL;
1771 else if (!strncmp ("interrupt", p, 9)) {
1772 printd ("vmsg interrupted");
1774 else {
1775 errx (1, "unknown command %.*s", len, p);
1778 return 0;
1781 CAMLprim value ml_isexternallink (value uri_v)
1783 CAMLparam1 (uri_v);
1784 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1785 CAMLreturn (Val_bool (ext));
1788 CAMLprim value ml_uritolocation (value uri_v)
1790 CAMLparam1 (uri_v);
1791 CAMLlocal1 (ret_v);
1792 int pageno;
1793 fz_point xy;
1794 struct pagedim *pdim;
1796 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1797 &xy.x, &xy.y);
1798 pdim = pdimofpageno (pageno);
1799 fz_transform_point (&xy, &pdim->ctm);
1800 ret_v = caml_alloc_tuple (3);
1801 Field (ret_v, 0) = Val_int (pageno);
1802 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1803 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1804 CAMLreturn (ret_v);
1807 CAMLprim value ml_realloctexts (value texcount_v)
1809 CAMLparam1 (texcount_v);
1810 int ok;
1812 if (trylock (__func__)) {
1813 ok = 0;
1814 goto done;
1816 realloctexts (Int_val (texcount_v));
1817 ok = 1;
1818 unlock (__func__);
1820 done:
1821 CAMLreturn (Val_bool (ok));
1824 static void recti (int x0, int y0, int x1, int y1)
1826 GLfloat *v = state.vertices;
1828 glVertexPointer (2, GL_FLOAT, 0, v);
1829 v[0] = x0; v[1] = y0;
1830 v[2] = x1; v[3] = y0;
1831 v[4] = x0; v[5] = y1;
1832 v[6] = x1; v[7] = y1;
1833 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1836 static void showsel (struct page *page, int ox, int oy)
1838 fz_irect bbox;
1839 fz_rect rect;
1840 fz_stext_block *block;
1841 int seen = 0;
1842 unsigned char selcolor[] = {15,15,15,140};
1844 if (!page->fmark || !page->lmark) return;
1846 glEnable (GL_BLEND);
1847 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1848 glColor4ubv (selcolor);
1850 ox += state.pagedims[page->pdimno].bounds.x0;
1851 oy += state.pagedims[page->pdimno].bounds.y0;
1853 for (block = page->text->first_block; block; block = block->next) {
1854 fz_stext_line *line;
1856 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1857 for (line = block->u.t.first_line; line; line = line->next) {
1858 fz_stext_char *ch;
1860 rect = fz_empty_rect;
1861 for (ch = line->first_char; ch; ch = ch->next) {
1862 if (ch == page->fmark) seen = 1;
1863 if (seen) fz_union_rect (&rect, &ch->bbox);
1864 if (ch == page->lmark) {
1865 fz_round_rect (&bbox, &rect);
1866 recti (bbox.x0 + ox, bbox.y0 + oy,
1867 bbox.x1 + ox, bbox.y1 + oy);
1868 goto done;
1871 fz_round_rect (&bbox, &rect);
1872 recti (bbox.x0 + ox, bbox.y0 + oy,
1873 bbox.x1 + ox, bbox.y1 + oy);
1876 done:
1877 glDisable (GL_BLEND);
1880 #pragma GCC diagnostic push
1881 #pragma GCC diagnostic ignored "-Wconversion"
1882 #include "glfont.c"
1883 #pragma GCC diagnostic pop
1885 static void stipplerect (fz_matrix *m,
1886 fz_point *p1,
1887 fz_point *p2,
1888 fz_point *p3,
1889 fz_point *p4,
1890 GLfloat *texcoords,
1891 GLfloat *vertices)
1893 fz_transform_point (p1, m);
1894 fz_transform_point (p2, m);
1895 fz_transform_point (p3, m);
1896 fz_transform_point (p4, m);
1898 float w, h, s, t;
1900 w = p2->x - p1->x;
1901 h = p2->y - p1->y;
1902 t = hypotf (w, h) * .25f;
1904 w = p3->x - p2->x;
1905 h = p3->y - p2->y;
1906 s = hypotf (w, h) * .25f;
1908 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
1909 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
1911 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
1912 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
1914 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
1915 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
1917 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
1918 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
1920 glDrawArrays (GL_LINES, 0, 8);
1923 static void solidrect (fz_matrix *m,
1924 fz_point *p1,
1925 fz_point *p2,
1926 fz_point *p3,
1927 fz_point *p4,
1928 GLfloat *vertices)
1930 fz_transform_point (p1, m);
1931 fz_transform_point (p2, m);
1932 fz_transform_point (p3, m);
1933 fz_transform_point (p4, m);
1934 vertices[0] = p1->x; vertices[1] = p1->y;
1935 vertices[2] = p2->x; vertices[3] = p2->y;
1937 vertices[4] = p3->x; vertices[5] = p3->y;
1938 vertices[6] = p4->x; vertices[7] = p4->y;
1939 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1942 static void ensurelinks (struct page *page)
1944 if (!page->links)
1945 page->links = fz_load_links (state.ctx, page->fzpage);
1948 static void highlightlinks (struct page *page, int xoff, int yoff)
1950 fz_matrix ctm, tm, pm;
1951 fz_link *link;
1952 GLfloat *texcoords = state.texcoords;
1953 GLfloat *vertices = state.vertices;
1955 ensurelinks (page);
1957 glEnable (GL_TEXTURE_1D);
1958 glEnable (GL_BLEND);
1959 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1960 glBindTexture (GL_TEXTURE_1D, state.stid);
1962 xoff -= state.pagedims[page->pdimno].bounds.x0;
1963 yoff -= state.pagedims[page->pdimno].bounds.y0;
1964 fz_translate (&tm, xoff, yoff);
1965 pm = pagectm (page);
1966 fz_concat (&ctm, &pm, &tm);
1968 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1969 glVertexPointer (2, GL_FLOAT, 0, vertices);
1971 for (link = page->links; link; link = link->next) {
1972 fz_point p1, p2, p3, p4;
1974 p1.x = link->rect.x0;
1975 p1.y = link->rect.y0;
1977 p2.x = link->rect.x1;
1978 p2.y = link->rect.y0;
1980 p3.x = link->rect.x1;
1981 p3.y = link->rect.y1;
1983 p4.x = link->rect.x0;
1984 p4.y = link->rect.y1;
1986 /* TODO: different colours for different schemes */
1987 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1988 else glColor3ub (255, 0, 0);
1990 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
1993 for (int i = 0; i < page->annotcount; ++i) {
1994 fz_point p1, p2, p3, p4;
1995 struct annot *annot = &page->annots[i];
1997 p1.x = annot->bbox.x0;
1998 p1.y = annot->bbox.y0;
2000 p2.x = annot->bbox.x1;
2001 p2.y = annot->bbox.y0;
2003 p3.x = annot->bbox.x1;
2004 p3.y = annot->bbox.y1;
2006 p4.x = annot->bbox.x0;
2007 p4.y = annot->bbox.y1;
2009 glColor3ub (0, 0, 128);
2010 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2013 glDisable (GL_BLEND);
2014 glDisable (GL_TEXTURE_1D);
2017 static int compareslinks (const void *l, const void *r)
2019 struct slink const *ls = l;
2020 struct slink const *rs = r;
2021 if (ls->bbox.y0 == rs->bbox.y0) {
2022 return rs->bbox.x0 - rs->bbox.x0;
2024 return ls->bbox.y0 - rs->bbox.y0;
2027 static void droptext (struct page *page)
2029 if (page->text) {
2030 fz_drop_stext_page (state.ctx, page->text);
2031 page->fmark = NULL;
2032 page->lmark = NULL;
2033 page->text = NULL;
2037 static void dropannots (struct page *page)
2039 if (page->annots) {
2040 free (page->annots);
2041 page->annots = NULL;
2042 page->annotcount = 0;
2046 static void ensureannots (struct page *page)
2048 int i, count = 0;
2049 size_t annotsize = sizeof (*page->annots);
2050 fz_annot *annot;
2052 if (state.gen != page->agen) {
2053 dropannots (page);
2054 page->agen = state.gen;
2056 if (page->annots) return;
2058 for (annot = fz_first_annot (state.ctx, page->fzpage);
2059 annot;
2060 annot = fz_next_annot (state.ctx, annot)) {
2061 count++;
2064 if (count > 0) {
2065 page->annotcount = count;
2066 page->annots = calloc (count, annotsize);
2067 if (!page->annots) {
2068 err (1, "calloc annots %d", count);
2071 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2072 annot;
2073 annot = fz_next_annot (state.ctx, annot), i++) {
2074 fz_rect rect;
2076 fz_bound_annot (state.ctx, annot, &rect);
2077 page->annots[i].annot = annot;
2078 fz_round_rect (&page->annots[i].bbox, &rect);
2083 static void dropslinks (struct page *page)
2085 if (page->slinks) {
2086 free (page->slinks);
2087 page->slinks = NULL;
2088 page->slinkcount = 0;
2090 if (page->links) {
2091 fz_drop_link (state.ctx, page->links);
2092 page->links = NULL;
2096 static void ensureslinks (struct page *page)
2098 fz_matrix ctm;
2099 int i, count;
2100 size_t slinksize = sizeof (*page->slinks);
2101 fz_link *link;
2103 ensureannots (page);
2104 if (state.gen != page->sgen) {
2105 dropslinks (page);
2106 page->sgen = state.gen;
2108 if (page->slinks) return;
2110 ensurelinks (page);
2111 ctm = pagectm (page);
2113 count = page->annotcount;
2114 for (link = page->links; link; link = link->next) {
2115 count++;
2117 if (count > 0) {
2118 int j;
2120 page->slinkcount = count;
2121 page->slinks = calloc (count, slinksize);
2122 if (!page->slinks) {
2123 err (1, "calloc slinks %d", count);
2126 for (i = 0, link = page->links; link; ++i, link = link->next) {
2127 fz_rect rect;
2129 rect = link->rect;
2130 fz_transform_rect (&rect, &ctm);
2131 page->slinks[i].tag = SLINK;
2132 page->slinks[i].u.link = link;
2133 fz_round_rect (&page->slinks[i].bbox, &rect);
2135 for (j = 0; j < page->annotcount; ++j, ++i) {
2136 fz_rect rect;
2137 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2138 fz_transform_rect (&rect, &ctm);
2139 fz_round_rect (&page->slinks[i].bbox, &rect);
2141 page->slinks[i].tag = SANNOT;
2142 page->slinks[i].u.annot = page->annots[j].annot;
2144 qsort (page->slinks, count, slinksize, compareslinks);
2148 static void highlightslinks (struct page *page, int xoff, int yoff,
2149 int noff, char *targ, mlsize_t tlen, int hfsize)
2151 char buf[40];
2152 struct slink *slink;
2153 float x0, y0, x1, y1, w;
2155 ensureslinks (page);
2156 glColor3ub (0xc3, 0xb0, 0x91);
2157 for (int i = 0; i < page->slinkcount; ++i) {
2158 fmt_linkn (buf, i + noff);
2159 if (!tlen || !strncmp (targ, buf, tlen)) {
2160 slink = &page->slinks[i];
2162 x0 = slink->bbox.x0 + xoff - 5;
2163 y1 = slink->bbox.y0 + yoff - 5;
2164 y0 = y1 + 10 + hfsize;
2165 w = measure_string (state.face, hfsize, buf);
2166 x1 = x0 + w + 10;
2167 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2171 glEnable (GL_BLEND);
2172 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2173 glEnable (GL_TEXTURE_2D);
2174 glColor3ub (0, 0, 0);
2175 for (int i = 0; i < page->slinkcount; ++i) {
2176 fmt_linkn (buf, i + noff);
2177 if (!tlen || !strncmp (targ, buf, tlen)) {
2178 slink = &page->slinks[i];
2180 x0 = slink->bbox.x0 + xoff;
2181 y0 = slink->bbox.y0 + yoff + hfsize;
2182 draw_string (state.face, hfsize, x0, y0, buf);
2185 glDisable (GL_TEXTURE_2D);
2186 glDisable (GL_BLEND);
2189 static void uploadslice (struct tile *tile, struct slice *slice)
2191 int offset;
2192 struct slice *slice1;
2193 unsigned char *texdata;
2195 offset = 0;
2196 for (slice1 = tile->slices; slice != slice1; slice1++) {
2197 offset += slice1->h * tile->w * tile->pixmap->n;
2199 if (slice->texindex != -1 && slice->texindex < state.texcount
2200 && state.texowners[slice->texindex].slice == slice) {
2201 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2203 else {
2204 int subimage = 0;
2205 int texindex = state.texindex++ % state.texcount;
2207 if (state.texowners[texindex].w == tile->w) {
2208 if (state.texowners[texindex].h >= slice->h) {
2209 subimage = 1;
2211 else {
2212 state.texowners[texindex].h = slice->h;
2215 else {
2216 state.texowners[texindex].h = slice->h;
2219 state.texowners[texindex].w = tile->w;
2220 state.texowners[texindex].slice = slice;
2221 slice->texindex = texindex;
2223 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2224 #if TEXT_TYPE == GL_TEXTURE_2D
2225 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2226 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2227 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2228 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2229 #endif
2230 if (tile->pbo) {
2231 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2232 texdata = 0;
2234 else {
2235 texdata = tile->pixmap->samples;
2237 if (subimage) {
2238 glTexSubImage2D (TEXT_TYPE,
2242 tile->w,
2243 slice->h,
2244 state.texform,
2245 state.texty,
2246 texdata+offset
2249 else {
2250 glTexImage2D (TEXT_TYPE,
2252 state.texiform,
2253 tile->w,
2254 slice->h,
2256 state.texform,
2257 state.texty,
2258 texdata+offset
2261 if (tile->pbo) {
2262 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2267 CAMLprim void ml_begintiles (value unit_v)
2269 CAMLparam1 (unit_v);
2270 glEnable (TEXT_TYPE);
2271 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2272 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2273 CAMLreturn0;
2276 CAMLprim void ml_endtiles (value unit_v)
2278 CAMLparam1 (unit_v);
2279 glDisable (TEXT_TYPE);
2280 CAMLreturn0;
2283 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2285 CAMLparam2 (args_v, ptr_v);
2286 int dispx = Int_val (Field (args_v, 0));
2287 int dispy = Int_val (Field (args_v, 1));
2288 int dispw = Int_val (Field (args_v, 2));
2289 int disph = Int_val (Field (args_v, 3));
2290 int tilex = Int_val (Field (args_v, 4));
2291 int tiley = Int_val (Field (args_v, 5));
2292 char *s = String_val (ptr_v);
2293 struct tile *tile = parse_pointer (__func__, s);
2294 int slicey, firstslice;
2295 struct slice *slice;
2296 GLfloat *texcoords = state.texcoords;
2297 GLfloat *vertices = state.vertices;
2299 firstslice = tiley / tile->sliceheight;
2300 slice = &tile->slices[firstslice];
2301 slicey = tiley % tile->sliceheight;
2303 while (disph > 0) {
2304 int dh;
2306 dh = slice->h - slicey;
2307 dh = fz_mini (disph, dh);
2308 uploadslice (tile, slice);
2310 texcoords[0] = tilex; texcoords[1] = slicey;
2311 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2312 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2313 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2315 vertices[0] = dispx; vertices[1] = dispy;
2316 vertices[2] = dispx+dispw; vertices[3] = dispy;
2317 vertices[4] = dispx; vertices[5] = dispy+dh;
2318 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2320 #if TEXT_TYPE == GL_TEXTURE_2D
2321 for (int i = 0; i < 8; ++i) {
2322 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2324 #endif
2326 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2327 dispy += dh;
2328 disph -= dh;
2329 slice++;
2330 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2331 slicey = 0;
2333 CAMLreturn0;
2336 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2338 fz_matrix ctm, tm, pm;
2339 fz_point p1, p2, p3, p4;
2340 GLfloat *vertices = state.vertices;
2341 double *v = (double *) rects_v;
2343 xoff -= state.pagedims[page->pdimno].bounds.x0;
2344 yoff -= state.pagedims[page->pdimno].bounds.y0;
2345 fz_translate (&tm, xoff, yoff);
2346 pm = pagectm (page);
2347 fz_concat (&ctm, &pm, &tm);
2349 glEnable (GL_BLEND);
2350 glVertexPointer (2, GL_FLOAT, 0, vertices);
2352 glColor4dv (v);
2353 p1.x = (float) v[4];
2354 p1.y = (float) v[5];
2356 p2.x = (float) v[6];
2357 p2.y = (float) v[5];
2359 p3.x = (float) v[6];
2360 p3.y = (float) v[7];
2362 p4.x = (float) v[4];
2363 p4.y = (float) v[7];
2364 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2365 glDisable (GL_BLEND);
2368 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2369 value xoff_v, value yoff_v,
2370 value li_v)
2372 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2373 int xoff = Int_val (xoff_v);
2374 int yoff = Int_val (yoff_v);
2375 int noff = Int_val (Field (li_v, 0));
2376 char *targ = String_val (Field (li_v, 1));
2377 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2378 int hfsize = Int_val (Field (li_v, 2));
2379 char *s = String_val (ptr_v);
2380 int hlmask = Int_val (hlinks_v);
2381 struct page *page = parse_pointer (__func__, s);
2383 if (!page->fzpage) {
2384 /* deal with loadpage failed pages */
2385 goto done;
2388 if (trylock (__func__)) {
2389 noff = -1;
2390 goto done;
2393 ensureannots (page);
2394 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2395 if (hlmask & 2) {
2396 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2397 noff = page->slinkcount;
2399 if (page->tgen == state.gen) {
2400 showsel (page, xoff, yoff);
2402 unlock (__func__);
2404 done:
2405 CAMLreturn (Val_int (noff));
2408 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2409 value rects_v)
2411 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2412 int xoff = Int_val (xoff_v);
2413 int yoff = Int_val (yoff_v);
2414 char *s = String_val (ptr_v);
2415 struct page *page = parse_pointer (__func__, s);
2417 drawprect (page, xoff, yoff, rects_v);
2418 CAMLreturn0;
2421 static struct annot *getannot (struct page *page, int x, int y)
2423 fz_point p;
2424 fz_matrix ctm;
2425 const fz_matrix *tctm;
2426 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2428 if (!page->annots) return NULL;
2430 if (pdf) {
2431 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2432 tctm = &state.pagedims[page->pdimno].tctm;
2434 else {
2435 tctm = &fz_identity;
2438 p.x = x;
2439 p.y = y;
2441 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2442 fz_invert_matrix (&ctm, &ctm);
2443 fz_transform_point (&p, &ctm);
2445 if (pdf) {
2446 for (int i = 0; i < page->annotcount; ++i) {
2447 struct annot *a = &page->annots[i];
2448 fz_rect rect;
2450 fz_bound_annot (state.ctx, a->annot, &rect);
2451 if (p.x >= rect.x0 && p.x <= rect.x1) {
2452 if (p.y >= rect.y0 && p.y <= rect.y1)
2453 return a;
2457 return NULL;
2460 static fz_link *getlink (struct page *page, int x, int y)
2462 fz_point p;
2463 fz_matrix ctm;
2464 fz_link *link;
2466 ensureslinks (page);
2468 p.x = x;
2469 p.y = y;
2471 ctm = pagectm (page);
2472 fz_invert_matrix (&ctm, &ctm);
2473 fz_transform_point (&p, &ctm);
2475 for (link = page->links; link; link = link->next) {
2476 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2477 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2478 return link;
2482 return NULL;
2485 static void ensuretext (struct page *page)
2487 if (state.gen != page->tgen) {
2488 droptext (page);
2489 page->tgen = state.gen;
2491 if (!page->text) {
2492 fz_matrix ctm;
2493 fz_device *tdev;
2495 page->text = fz_new_stext_page (state.ctx,
2496 &state.pagedims[page->pdimno].mediabox);
2497 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2498 ctm = pagectm (page);
2499 fz_run_display_list (state.ctx, page->dlist,
2500 tdev, &ctm, &fz_infinite_rect, NULL);
2501 fz_close_device (state.ctx, tdev);
2502 fz_drop_device (state.ctx, tdev);
2506 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2508 CAMLparam2 (start_page_v, dir_v);
2509 CAMLlocal1 (ret_v);
2510 int i, dir = Int_val (dir_v);
2511 int start_page = Int_val (start_page_v);
2512 int end_page = dir > 0 ? state.pagecount : -1;
2513 pdf_document *pdf;
2515 fz_var (end_page);
2516 ret_v = Val_int (0);
2517 lock (__func__);
2518 pdf = pdf_specifics (state.ctx, state.doc);
2519 for (i = start_page + dir; i != end_page; i += dir) {
2520 int found;
2522 fz_var (found);
2523 if (pdf) {
2524 pdf_page *page = NULL;
2526 fz_var (page);
2527 fz_try (state.ctx) {
2528 page = pdf_load_page (state.ctx, pdf, i);
2529 found = !!page->links || !!page->annots;
2531 fz_catch (state.ctx) {
2532 found = 0;
2534 if (page) {
2535 fz_drop_page (state.ctx, &page->super);
2538 else {
2539 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2540 fz_link *link = fz_load_links (state.ctx, page);
2541 found = !!link;
2542 fz_drop_link (state.ctx, link);
2543 fz_drop_page (state.ctx, page);
2546 if (found) {
2547 ret_v = caml_alloc_small (1, 1);
2548 Field (ret_v, 0) = Val_int (i);
2549 goto unlock;
2552 unlock:
2553 unlock (__func__);
2554 CAMLreturn (ret_v);
2557 enum { dir_first, dir_last };
2558 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2560 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2562 CAMLparam2 (ptr_v, dir_v);
2563 CAMLlocal2 (ret_v, pos_v);
2564 struct page *page;
2565 int dirtag, i, slinkindex;
2566 struct slink *found = NULL ,*slink;
2567 char *s = String_val (ptr_v);
2569 page = parse_pointer (__func__, s);
2570 ret_v = Val_int (0);
2571 lock (__func__);
2572 ensureslinks (page);
2574 if (Is_block (dir_v)) {
2575 dirtag = Tag_val (dir_v);
2576 switch (dirtag) {
2577 case dir_first_visible:
2579 int x0, y0, dir, first_index, last_index;
2581 pos_v = Field (dir_v, 0);
2582 x0 = Int_val (Field (pos_v, 0));
2583 y0 = Int_val (Field (pos_v, 1));
2584 dir = Int_val (Field (pos_v, 2));
2586 if (dir >= 0) {
2587 dir = 1;
2588 first_index = 0;
2589 last_index = page->slinkcount;
2591 else {
2592 first_index = page->slinkcount - 1;
2593 last_index = -1;
2596 for (i = first_index; i != last_index; i += dir) {
2597 slink = &page->slinks[i];
2598 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2599 found = slink;
2600 break;
2604 break;
2606 case dir_left:
2607 slinkindex = Int_val (Field (dir_v, 0));
2608 found = &page->slinks[slinkindex];
2609 for (i = slinkindex - 1; i >= 0; --i) {
2610 slink = &page->slinks[i];
2611 if (slink->bbox.x0 < found->bbox.x0) {
2612 found = slink;
2613 break;
2616 break;
2618 case dir_right:
2619 slinkindex = Int_val (Field (dir_v, 0));
2620 found = &page->slinks[slinkindex];
2621 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2622 slink = &page->slinks[i];
2623 if (slink->bbox.x0 > found->bbox.x0) {
2624 found = slink;
2625 break;
2628 break;
2630 case dir_down:
2631 slinkindex = Int_val (Field (dir_v, 0));
2632 found = &page->slinks[slinkindex];
2633 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2634 slink = &page->slinks[i];
2635 if (slink->bbox.y0 >= found->bbox.y0) {
2636 found = slink;
2637 break;
2640 break;
2642 case dir_up:
2643 slinkindex = Int_val (Field (dir_v, 0));
2644 found = &page->slinks[slinkindex];
2645 for (i = slinkindex - 1; i >= 0; --i) {
2646 slink = &page->slinks[i];
2647 if (slink->bbox.y0 <= found->bbox.y0) {
2648 found = slink;
2649 break;
2652 break;
2655 else {
2656 dirtag = Int_val (dir_v);
2657 switch (dirtag) {
2658 case dir_first:
2659 found = page->slinks;
2660 break;
2662 case dir_last:
2663 if (page->slinks) {
2664 found = page->slinks + (page->slinkcount - 1);
2666 break;
2669 if (found) {
2670 ret_v = caml_alloc_small (2, 1);
2671 Field (ret_v, 0) = Val_int (found - page->slinks);
2674 unlock (__func__);
2675 CAMLreturn (ret_v);
2678 enum { uuri, utext, uannot };
2680 CAMLprim value ml_getlink (value ptr_v, value n_v)
2682 CAMLparam2 (ptr_v, n_v);
2683 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2684 fz_link *link;
2685 struct page *page;
2686 char *s = String_val (ptr_v);
2687 struct slink *slink;
2689 ret_v = Val_int (0);
2690 page = parse_pointer (__func__, s);
2692 lock (__func__);
2693 ensureslinks (page);
2694 slink = &page->slinks[Int_val (n_v)];
2695 if (slink->tag == SLINK) {
2696 link = slink->u.link;
2697 str_v = caml_copy_string (link->uri);
2698 ret_v = caml_alloc_small (1, uuri);
2699 Field (ret_v, 0) = str_v;
2701 else {
2702 ret_v = caml_alloc_small (1, uannot);
2703 tup_v = caml_alloc_tuple (2);
2704 Field (ret_v, 0) = tup_v;
2705 Field (tup_v, 0) = ptr_v;
2706 Field (tup_v, 1) = n_v;
2708 unlock (__func__);
2710 CAMLreturn (ret_v);
2713 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2715 CAMLparam2 (ptr_v, n_v);
2716 CAMLlocal1 (ret_v);
2717 pdf_document *pdf;
2718 char *contents = NULL;
2720 lock (__func__);
2721 pdf = pdf_specifics (state.ctx, state.doc);
2722 if (pdf) {
2723 char *s = String_val (ptr_v);
2724 struct page *page;
2725 struct slink *slink;
2727 page = parse_pointer (__func__, s);
2728 slink = &page->slinks[Int_val (n_v)];
2729 contents = pdf_copy_annot_contents (state.ctx,
2730 (pdf_annot *) slink->u.annot);
2732 unlock (__func__);
2733 if (contents) {
2734 ret_v = caml_copy_string (contents);
2735 fz_free (state.ctx, contents);
2737 else {
2738 ret_v = caml_copy_string ("");
2740 CAMLreturn (ret_v);
2743 CAMLprim value ml_getlinkcount (value ptr_v)
2745 CAMLparam1 (ptr_v);
2746 struct page *page;
2747 char *s = String_val (ptr_v);
2749 page = parse_pointer (__func__, s);
2750 CAMLreturn (Val_int (page->slinkcount));
2753 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2755 CAMLparam2 (ptr_v, n_v);
2756 CAMLlocal1 (ret_v);
2757 struct page *page;
2758 struct slink *slink;
2759 char *s = String_val (ptr_v);
2761 page = parse_pointer (__func__, s);
2762 ret_v = caml_alloc_tuple (4);
2763 lock (__func__);
2764 ensureslinks (page);
2766 slink = &page->slinks[Int_val (n_v)];
2767 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2768 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2769 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2770 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2771 unlock (__func__);
2772 CAMLreturn (ret_v);
2775 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2777 CAMLparam3 (ptr_v, x_v, y_v);
2778 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2779 fz_link *link;
2780 struct annot *annot;
2781 struct page *page;
2782 char *ptr = String_val (ptr_v);
2783 int x = Int_val (x_v), y = Int_val (y_v);
2784 struct pagedim *pdim;
2786 ret_v = Val_int (0);
2787 if (trylock (__func__)) {
2788 goto done;
2791 page = parse_pointer (__func__, ptr);
2792 pdim = &state.pagedims[page->pdimno];
2793 x += pdim->bounds.x0;
2794 y += pdim->bounds.y0;
2797 annot = getannot (page, x, y);
2798 if (annot) {
2799 int i, n = -1;
2801 ensureslinks (page);
2802 for (i = 0; i < page->slinkcount; ++i) {
2803 if (page->slinks[i].tag == SANNOT
2804 && page->slinks[i].u.annot == annot->annot) {
2805 n = i;
2806 break;
2809 ret_v = caml_alloc_small (1, uannot);
2810 tup_v = caml_alloc_tuple (2);
2811 Field (ret_v, 0) = tup_v;
2812 Field (tup_v, 0) = ptr_v;
2813 Field (tup_v, 1) = Val_int (n);
2814 goto unlock;
2818 link = getlink (page, x, y);
2819 if (link) {
2820 str_v = caml_copy_string (link->uri);
2821 ret_v = caml_alloc_small (1, uuri);
2822 Field (ret_v, 0) = str_v;
2824 else {
2825 fz_rect *b;
2826 fz_stext_block *block;
2828 ensuretext (page);
2830 for (block = page->text->first_block; block; block = block->next) {
2831 fz_stext_line *line;
2833 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2834 b = &block->bbox;
2835 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2836 continue;
2838 for (line = block->u.t.first_line; line; line = line->next) {
2839 fz_stext_char *ch;
2841 b = &line->bbox;
2842 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2843 continue;
2845 for (ch = line->first_char; ch; ch = ch->next) {
2846 b = &ch->bbox;
2848 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
2849 const char *n2 = fz_font_name (state.ctx, ch->font);
2850 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2851 ch->font);
2853 if (!n2) n2 = "<unknown font>";
2855 if (face && face->family_name) {
2856 char *s;
2857 char *n1 = face->family_name;
2858 size_t l1 = strlen (n1);
2859 size_t l2 = strlen (n2);
2861 if (l1 != l2 || memcmp (n1, n2, l1)) {
2862 s = malloc (l1 + l2 + 2);
2863 if (s) {
2864 memcpy (s, n2, l2);
2865 s[l2] = '=';
2866 memcpy (s + l2 + 1, n1, l1 + 1);
2867 str_v = caml_copy_string (s);
2868 free (s);
2872 if (str_v == Val_unit) {
2873 str_v = caml_copy_string (n2);
2875 ret_v = caml_alloc_small (1, utext);
2876 Field (ret_v, 0) = str_v;
2877 goto unlock;
2883 unlock:
2884 unlock (__func__);
2886 done:
2887 CAMLreturn (ret_v);
2890 enum { mark_page, mark_block, mark_line, mark_word };
2892 CAMLprim void ml_clearmark (value ptr_v)
2894 CAMLparam1 (ptr_v);
2895 char *s = String_val (ptr_v);
2896 struct page *page;
2898 if (trylock (__func__)) {
2899 goto done;
2902 page = parse_pointer (__func__, s);
2903 page->fmark = NULL;
2904 page->lmark = NULL;
2906 unlock (__func__);
2907 done:
2908 CAMLreturn0;
2911 static int uninteresting (int c)
2913 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
2914 || ispunct (c);
2917 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2919 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2920 CAMLlocal1 (ret_v);
2921 fz_rect *b;
2922 struct page *page;
2923 fz_stext_line *line;
2924 fz_stext_block *block;
2925 struct pagedim *pdim;
2926 int mark = Int_val (mark_v);
2927 char *s = String_val (ptr_v);
2928 int x = Int_val (x_v), y = Int_val (y_v);
2930 ret_v = Val_bool (0);
2931 if (trylock (__func__)) {
2932 goto done;
2935 page = parse_pointer (__func__, s);
2936 pdim = &state.pagedims[page->pdimno];
2938 ensuretext (page);
2940 if (mark == mark_page) {
2941 page->fmark = page->text->first_block->u.t.first_line->first_char;
2942 page->lmark = page->text->last_block->u.t.last_line->last_char;
2943 ret_v = Val_bool (1);
2944 goto unlock;
2947 x += pdim->bounds.x0;
2948 y += pdim->bounds.y0;
2950 for (block = page->text->first_block; block; block = block->next) {
2951 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2952 b = &block->bbox;
2953 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2954 continue;
2956 if (mark == mark_block) {
2957 page->fmark = block->u.t.first_line->first_char;
2958 page->lmark = block->u.t.last_line->last_char;
2959 ret_v = Val_bool (1);
2960 goto unlock;
2963 for (line = block->u.t.first_line; line; line = line->next) {
2964 fz_stext_char *ch;
2966 b = &line->bbox;
2967 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2968 continue;
2970 if (mark == mark_line) {
2971 page->fmark = line->first_char;
2972 page->lmark = line->last_char;
2973 ret_v = Val_bool (1);
2974 goto unlock;
2977 for (ch = line->first_char; ch; ch = ch->next) {
2978 fz_stext_char *ch2, *first = NULL, *last = NULL;
2979 b = &ch->bbox;
2980 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
2981 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2982 if (uninteresting (ch2->c)) first = NULL;
2983 else if (!first) first = ch2;
2985 for (ch2 = ch; ch2; ch2 = ch2->next) {
2986 if (uninteresting (ch2->c)) break;
2987 last = ch2;
2990 page->fmark = first;
2991 page->lmark = last;
2992 ret_v = Val_bool (1);
2993 goto unlock;
2998 unlock:
2999 if (!Bool_val (ret_v)) {
3000 page->fmark = NULL;
3001 page->lmark = NULL;
3003 unlock (__func__);
3005 done:
3006 CAMLreturn (ret_v);
3009 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3011 CAMLparam3 (ptr_v, x_v, y_v);
3012 CAMLlocal2 (ret_v, res_v);
3013 fz_rect *b = NULL;
3014 struct page *page;
3015 struct pagedim *pdim;
3016 fz_stext_block *block;
3017 char *s = String_val (ptr_v);
3018 int x = Int_val (x_v), y = Int_val (y_v);
3020 ret_v = Val_int (0);
3021 if (trylock (__func__)) {
3022 goto done;
3025 page = parse_pointer (__func__, s);
3026 pdim = &state.pagedims[page->pdimno];
3027 x += pdim->bounds.x0;
3028 y += pdim->bounds.y0;
3030 ensuretext (page);
3032 for (block = page->text->first_block; block; block = block->next) {
3033 switch (block->type) {
3034 case FZ_STEXT_BLOCK_TEXT:
3035 b = &block->bbox;
3036 break;
3038 case FZ_STEXT_BLOCK_IMAGE:
3039 b = &block->bbox;
3040 break;
3042 default:
3043 continue;
3046 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3047 break;
3048 b = NULL;
3050 if (b) {
3051 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3052 ret_v = caml_alloc_small (1, 1);
3053 Store_double_field (res_v, 0, (double) b->x0);
3054 Store_double_field (res_v, 1, (double) b->x1);
3055 Store_double_field (res_v, 2, (double) b->y0);
3056 Store_double_field (res_v, 3, (double) b->y1);
3057 Field (ret_v, 0) = res_v;
3059 unlock (__func__);
3061 done:
3062 CAMLreturn (ret_v);
3065 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3067 CAMLparam2 (ptr_v, rect_v);
3068 fz_rect b;
3069 struct page *page;
3070 struct pagedim *pdim;
3071 char *s = String_val (ptr_v);
3072 int x0, x1, y0, y1;
3073 fz_stext_char *ch;
3074 fz_stext_line *line;
3075 fz_stext_block *block;
3076 fz_stext_char *fc, *lc;
3078 if (trylock (__func__)) {
3079 goto done;
3082 page = parse_pointer (__func__, s);
3083 ensuretext (page);
3085 pdim = &state.pagedims[page->pdimno];
3086 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3087 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3088 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3089 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3091 if (y0 > y1) {
3092 int t = y0;
3093 y0 = y1;
3094 y1 = t;
3095 x0 = x1;
3096 x1 = t;
3099 fc = page->fmark;
3100 lc = page->lmark;
3102 for (block = page->text->first_block; block; block = block->next) {
3103 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3104 for (line = block->u.t.first_line; line; line = line->next) {
3105 for (ch = line->first_char; ch; ch = ch->next) {
3106 b = ch->bbox;
3107 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3108 fc = ch;
3110 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3111 lc = ch;
3116 if (x1 < x0 && fc == lc) {
3117 fz_stext_char *t;
3119 t = fc;
3120 fc = lc;
3121 lc = t;
3124 page->fmark = fc;
3125 page->lmark = lc;
3127 unlock (__func__);
3129 done:
3130 CAMLreturn0;
3133 static int pipechar (FILE *f, fz_stext_char *ch)
3135 char buf[4];
3136 int len;
3137 size_t ret;
3139 len = fz_runetochar (buf, ch->c);
3140 ret = fwrite (buf, len, 1, f);
3141 if (ret != 1) {
3142 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3143 len, ret, errno, strerror (errno));
3144 return -1;
3146 return 0;
3149 CAMLprim value ml_spawn (value command_v, value fds_v)
3151 CAMLparam2 (command_v, fds_v);
3152 CAMLlocal2 (l_v, tup_v);
3153 int ret, ret1;
3154 pid_t pid = (pid_t) -1;
3155 char *msg = NULL;
3156 value earg_v = Nothing;
3157 posix_spawnattr_t attr;
3158 posix_spawn_file_actions_t fa;
3159 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3161 argv[2] = String_val (command_v);
3163 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3164 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3167 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3168 msg = "posix_spawnattr_init";
3169 goto fail1;
3172 #ifdef POSIX_SPAWN_USEVFORK
3173 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3174 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3175 goto fail;
3177 #endif
3179 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3180 int fd1, fd2;
3182 tup_v = Field (l_v, 0);
3183 fd1 = Int_val (Field (tup_v, 0));
3184 fd2 = Int_val (Field (tup_v, 1));
3185 if (fd2 < 0) {
3186 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3187 msg = "posix_spawn_file_actions_addclose";
3188 earg_v = tup_v;
3189 goto fail;
3192 else {
3193 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3194 msg = "posix_spawn_file_actions_adddup2";
3195 earg_v = tup_v;
3196 goto fail;
3201 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3202 msg = "posix_spawn";
3203 goto fail;
3206 fail:
3207 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3208 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3211 fail1:
3212 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3213 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3214 ret1, strerror (ret1));
3217 if (msg)
3218 unix_error (ret, msg, earg_v);
3220 CAMLreturn (Val_int (pid));
3223 CAMLprim value ml_hassel (value ptr_v)
3225 CAMLparam1 (ptr_v);
3226 CAMLlocal1 (ret_v);
3227 struct page *page;
3228 char *s = String_val (ptr_v);
3230 ret_v = Val_bool (0);
3231 if (trylock (__func__)) {
3232 goto done;
3235 page = parse_pointer (__func__, s);
3236 ret_v = Val_bool (page->fmark && page->lmark);
3237 unlock (__func__);
3238 done:
3239 CAMLreturn (ret_v);
3242 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3244 CAMLparam2 (fd_v, ptr_v);
3245 FILE *f;
3246 int seen = 0;
3247 struct page *page;
3248 fz_stext_line *line;
3249 fz_stext_block *block;
3250 int fd = Int_val (fd_v);
3251 char *s = String_val (ptr_v);
3253 if (trylock (__func__)) {
3254 goto done;
3257 page = parse_pointer (__func__, s);
3259 if (!page->fmark || !page->lmark) {
3260 printd ("emsg nothing to copy on page %d", page->pageno);
3261 goto unlock;
3264 f = fdopen (fd, "w");
3265 if (!f) {
3266 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3267 fd, errno, strerror (errno));
3268 f = stdout;
3271 for (block = page->text->first_block; block; block = block->next) {
3272 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3273 for (line = block->u.t.first_line; line; line = line->next) {
3274 fz_stext_char *ch;
3275 for (ch = line->first_char; ch; ch = ch->next) {
3276 if (seen || ch == page->fmark) {
3277 do {
3278 pipechar (f, ch);
3279 if (ch == page->lmark) goto close;
3280 } while ((ch = ch->next));
3281 seen = 1;
3282 break;
3285 if (seen) fputc ('\n', f);
3288 close:
3289 if (f != stdout) {
3290 int ret = fclose (f);
3291 fd = -1;
3292 if (ret == -1) {
3293 if (errno != ECHILD) {
3294 printd ("emsg failed to close sel pipe: %d:%s",
3295 errno, strerror (errno));
3299 unlock:
3300 unlock (__func__);
3302 done:
3303 if (fd >= 0) {
3304 if (close (fd)) {
3305 printd ("emsg failed to close sel pipe: %d:%s",
3306 errno, strerror (errno));
3309 CAMLreturn0;
3312 CAMLprim value ml_getpdimrect (value pagedimno_v)
3314 CAMLparam1 (pagedimno_v);
3315 CAMLlocal1 (ret_v);
3316 int pagedimno = Int_val (pagedimno_v);
3317 fz_rect box;
3319 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3320 if (trylock (__func__)) {
3321 box = fz_empty_rect;
3323 else {
3324 box = state.pagedims[pagedimno].mediabox;
3325 unlock (__func__);
3328 Store_double_field (ret_v, 0, (double) box.x0);
3329 Store_double_field (ret_v, 1, (double) box.x1);
3330 Store_double_field (ret_v, 2, (double) box.y0);
3331 Store_double_field (ret_v, 3, (double) box.y1);
3333 CAMLreturn (ret_v);
3336 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3337 value dw_v, value cols_v)
3339 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3340 CAMLlocal1 (ret_v);
3341 int i;
3342 float zoom = -1.;
3343 float maxh = 0.0;
3344 struct pagedim *p;
3345 float winw = Int_val (winw_v);
3346 float winh = Int_val (winh_v);
3347 float dw = Int_val (dw_v);
3348 float cols = Int_val (cols_v);
3349 float pw = 1.0, ph = 1.0;
3351 if (trylock (__func__)) {
3352 goto done;
3355 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3356 float w = p->pagebox.x1 / cols;
3357 float h = p->pagebox.y1;
3358 if (h > maxh) {
3359 maxh = h;
3360 ph = h;
3361 if (state.fitmodel != FitProportional) pw = w;
3363 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3366 zoom = (((winh / ph) * pw) + dw) / winw;
3367 unlock (__func__);
3368 done:
3369 ret_v = caml_copy_double ((double) zoom);
3370 CAMLreturn (ret_v);
3373 CAMLprim value ml_getmaxw (value unit_v)
3375 CAMLparam1 (unit_v);
3376 CAMLlocal1 (ret_v);
3377 int i;
3378 float maxw = -1.;
3379 struct pagedim *p;
3381 if (trylock (__func__)) {
3382 goto done;
3385 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3386 float w = p->pagebox.x1;
3387 maxw = fz_max (maxw, w);
3390 unlock (__func__);
3391 done:
3392 ret_v = caml_copy_double ((double) maxw);
3393 CAMLreturn (ret_v);
3396 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3398 CAMLparam4 (pt_v, x_v, y_v, string_v);
3399 CAMLlocal1 (ret_v);
3400 int pt = Int_val(pt_v);
3401 int x = Int_val (x_v);
3402 int y = Int_val (y_v);
3403 double w;
3405 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3406 ret_v = caml_copy_double (w);
3407 CAMLreturn (ret_v);
3410 CAMLprim value ml_measure_string (value pt_v, value string_v)
3412 CAMLparam2 (pt_v, string_v);
3413 CAMLlocal1 (ret_v);
3414 int pt = Int_val (pt_v);
3415 double w;
3417 w = (double) measure_string (state.face, pt, String_val (string_v));
3418 ret_v = caml_copy_double (w);
3419 CAMLreturn (ret_v);
3422 CAMLprim value ml_getpagebox (value opaque_v)
3424 CAMLparam1 (opaque_v);
3425 CAMLlocal1 (ret_v);
3426 fz_rect rect;
3427 fz_irect bbox;
3428 fz_matrix ctm;
3429 fz_device *dev;
3430 char *s = String_val (opaque_v);
3431 struct page *page = parse_pointer (__func__, s);
3433 ret_v = caml_alloc_tuple (4);
3434 dev = fz_new_bbox_device (state.ctx, &rect);
3436 ctm = pagectm (page);
3437 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3439 fz_close_device (state.ctx, dev);
3440 fz_drop_device (state.ctx, dev);
3441 fz_round_rect (&bbox, &rect);
3442 Field (ret_v, 0) = Val_int (bbox.x0);
3443 Field (ret_v, 1) = Val_int (bbox.y0);
3444 Field (ret_v, 2) = Val_int (bbox.x1);
3445 Field (ret_v, 3) = Val_int (bbox.y1);
3447 CAMLreturn (ret_v);
3450 CAMLprim void ml_setaalevel (value level_v)
3452 CAMLparam1 (level_v);
3454 state.aalevel = Int_val (level_v);
3455 CAMLreturn0;
3458 #ifndef __COCOA__
3459 #pragma GCC diagnostic push
3460 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3461 #include <X11/Xlib.h>
3462 #include <X11/cursorfont.h>
3463 #pragma GCC diagnostic pop
3465 #include <GL/glx.h>
3467 static const int shapes[] = {
3468 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3471 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3473 static struct {
3474 Window wid;
3475 Display *dpy;
3476 GLXContext ctx;
3477 XVisualInfo *visual;
3478 Cursor curs[CURS_COUNT];
3479 } glx;
3482 static void initcurs (void)
3484 for (size_t n = 0; n < CURS_COUNT; ++n) {
3485 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3489 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3491 CAMLparam3 (display_v, wid_v, screen_v);
3493 glx.dpy = XOpenDisplay (String_val (display_v));
3494 if (!glx.dpy) {
3495 caml_failwith ("XOpenDisplay");
3498 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3499 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3500 if (!glx.visual) {
3501 XCloseDisplay (glx.dpy);
3502 caml_failwith ("glXChooseVisual");
3505 initcurs ();
3507 glx.wid = Int_val (wid_v);
3508 CAMLreturn (Val_int (glx.visual->visualid));
3511 CAMLprim void ml_glxcompleteinit (value unit_v)
3513 CAMLparam1 (unit_v);
3515 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3516 if (!glx.ctx) {
3517 caml_failwith ("glXCreateContext");
3520 XFree (glx.visual);
3521 glx.visual = NULL;
3523 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3524 glXDestroyContext (glx.dpy, glx.ctx);
3525 glx.ctx = NULL;
3526 caml_failwith ("glXMakeCurrent");
3528 CAMLreturn0;
3531 CAMLprim void ml_setcursor (value cursor_v)
3533 CAMLparam1 (cursor_v);
3534 size_t cursn = Int_val (cursor_v);
3536 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3537 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3538 XFlush (glx.dpy);
3539 CAMLreturn0;
3542 CAMLprim void ml_swapb (value unit_v)
3544 CAMLparam1 (unit_v);
3545 glXSwapBuffers (glx.dpy, glx.wid);
3546 CAMLreturn0;
3549 long keysym2ucs (KeySym);
3550 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3552 CAMLparam1 (keysym_v);
3553 CAMLlocal1 (str_v);
3554 KeySym keysym = Int_val (keysym_v);
3555 Rune rune;
3556 int len;
3557 char buf[5];
3559 rune = (Rune) keysym2ucs (keysym);
3560 len = fz_runetochar (buf, rune);
3561 buf[len] = 0;
3562 str_v = caml_copy_string (buf);
3563 CAMLreturn (str_v);
3565 #else
3566 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3568 CAMLparam1 (keysym_v);
3569 CAMLlocal1 (str_v);
3570 long ucs_v = Long_val (keysym_v);
3571 int len;
3572 char buf[5];
3574 len = fz_runetochar (buf, (int) ucs_v);
3575 buf[len] = 0;
3576 str_v = caml_copy_string (buf);
3577 CAMLreturn (str_v);
3579 #endif
3581 enum { piunknown, pilinux, pimacos, pisun, pibsd };
3583 CAMLprim value ml_platform (value unit_v)
3585 CAMLparam1 (unit_v);
3586 CAMLlocal2 (tup_v, arr_v);
3587 int platid = piunknown;
3588 struct utsname buf;
3590 #if defined __linux__
3591 platid = pilinux;
3592 #elif defined __DragonFly__ || defined __FreeBSD__
3593 || defined __OpenBSD__ || defined __NetBSD__
3594 platid = pibsd;
3595 #elif defined __sun__
3596 platid = pisun;
3597 #elif defined __APPLE__
3598 platid = pimacos;
3599 #endif
3600 if (uname (&buf)) err (1, "uname");
3602 tup_v = caml_alloc_tuple (2);
3604 char const *sar[] = {
3605 buf.sysname,
3606 buf.release,
3607 buf.version,
3608 buf.machine,
3609 NULL
3611 arr_v = caml_copy_string_array (sar);
3613 Field (tup_v, 0) = Val_int (platid);
3614 Field (tup_v, 1) = arr_v;
3615 CAMLreturn (tup_v);
3618 CAMLprim void ml_cloexec (value fd_v)
3620 CAMLparam1 (fd_v);
3621 int fd = Int_val (fd_v);
3623 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3624 uerror ("fcntl", Nothing);
3626 CAMLreturn0;
3629 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3631 CAMLparam2 (w_v, h_v);
3632 CAMLlocal1 (ret_v);
3633 struct bo *pbo;
3634 int w = Int_val (w_v);
3635 int h = Int_val (h_v);
3636 int cs = Int_val (cs_v);
3638 if (state.bo_usable) {
3639 pbo = calloc (sizeof (*pbo), 1);
3640 if (!pbo) {
3641 err (1, "calloc pbo");
3644 switch (cs) {
3645 case 0:
3646 case 1:
3647 pbo->size = w*h*4;
3648 break;
3649 case 2:
3650 pbo->size = w*h*2;
3651 break;
3652 default:
3653 errx (1, "%s: invalid colorspace %d", __func__, cs);
3656 state.glGenBuffersARB (1, &pbo->id);
3657 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3658 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3659 NULL, GL_STREAM_DRAW);
3660 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3661 GL_READ_WRITE);
3662 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3663 if (!pbo->ptr) {
3664 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3665 state.glDeleteBuffersARB (1, &pbo->id);
3666 free (pbo);
3667 ret_v = caml_copy_string ("0");
3669 else {
3670 int res;
3671 char *s;
3673 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3674 if (res < 0) {
3675 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3677 s = malloc (res+1);
3678 if (!s) {
3679 err (1, "malloc %d bytes failed", res+1);
3681 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3682 if (res < 0) {
3683 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3685 ret_v = caml_copy_string (s);
3686 free (s);
3689 else {
3690 ret_v = caml_copy_string ("0");
3692 CAMLreturn (ret_v);
3695 CAMLprim void ml_freepbo (value s_v)
3697 CAMLparam1 (s_v);
3698 char *s = String_val (s_v);
3699 struct tile *tile = parse_pointer (__func__, s);
3701 if (tile->pbo) {
3702 state.glDeleteBuffersARB (1, &tile->pbo->id);
3703 tile->pbo->id = -1;
3704 tile->pbo->ptr = NULL;
3705 tile->pbo->size = -1;
3707 CAMLreturn0;
3710 CAMLprim void ml_unmappbo (value s_v)
3712 CAMLparam1 (s_v);
3713 char *s = String_val (s_v);
3714 struct tile *tile = parse_pointer (__func__, s);
3716 if (tile->pbo) {
3717 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3718 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3719 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3721 tile->pbo->ptr = NULL;
3722 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3724 CAMLreturn0;
3727 static void setuppbo (void)
3729 #ifdef __clang__
3730 #pragma GCC diagnostic ignored "-Wunused-macros"
3731 #endif
3732 #ifdef __COCOA__
3733 static CFBundleRef framework = NULL;
3734 if (framework == NULL)
3735 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3736 #define GGPA(n) \
3737 (*(void (**) (void)) &state.n = \
3738 (void (*) (void)) CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3739 #else
3740 #define GGPA(n) \
3741 (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
3742 #endif
3743 state.bo_usable = GGPA (glBindBufferARB)
3744 && GGPA (glUnmapBufferARB)
3745 && GGPA (glMapBufferARB)
3746 && GGPA (glBufferDataARB)
3747 && GGPA (glGenBuffersARB)
3748 && GGPA (glDeleteBuffersARB);
3749 #undef GGPA
3752 CAMLprim value ml_bo_usable (value unit_v)
3754 CAMLparam1 (unit_v);
3755 CAMLreturn (Val_bool (state.bo_usable));
3758 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3760 CAMLparam3 (ptr_v, x_v, y_v);
3761 CAMLlocal2 (ret_v, tup_v);
3762 struct page *page;
3763 char *s = String_val (ptr_v);
3764 int x = Int_val (x_v), y = Int_val (y_v);
3765 struct pagedim *pdim;
3766 fz_point p;
3767 fz_matrix ctm;
3769 page = parse_pointer (__func__, s);
3770 pdim = &state.pagedims[page->pdimno];
3772 ret_v = Val_int (0);
3773 if (trylock (__func__)) {
3774 goto done;
3777 if (pdf_specifics (state.ctx, state.doc)) {
3778 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3779 ctm = state.pagedims[page->pdimno].tctm;
3781 else {
3782 ctm = fz_identity;
3784 p.x = x + pdim->bounds.x0;
3785 p.y = y + pdim->bounds.y0;
3787 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3788 fz_invert_matrix (&ctm, &ctm);
3789 fz_transform_point (&p, &ctm);
3791 tup_v = caml_alloc_tuple (2);
3792 ret_v = caml_alloc_small (1, 1);
3793 Field (tup_v, 0) = Val_int (p.x);
3794 Field (tup_v, 1) = Val_int (p.y);
3795 Field (ret_v, 0) = tup_v;
3797 unlock (__func__);
3798 done:
3799 CAMLreturn (ret_v);
3802 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3803 value x_v, value y_v)
3805 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3806 CAMLlocal1 (ret_v);
3807 struct page *page;
3808 char *s = String_val (ptr_v);
3809 int pageno = Int_val (pageno_v);
3810 int pdimno = Int_val (pdimno_v);
3811 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3812 struct pagedim *pdim;
3813 fz_point p;
3814 fz_matrix ctm;
3816 ret_v = Val_int (0);
3817 lock (__func__);
3819 if (!*s) {
3820 page = loadpage (pageno, pdimno);
3822 else {
3823 page = parse_pointer (__func__, s);
3825 pdim = &state.pagedims[pdimno];
3827 if (pdf_specifics (state.ctx, state.doc)) {
3828 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3829 ctm = state.pagedims[page->pdimno].tctm;
3831 else {
3832 ctm = fz_identity;
3834 p.x = x + pdim->bounds.x0;
3835 p.y = y + pdim->bounds.y0;
3837 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3838 fz_transform_point (&p, &ctm);
3840 ret_v = caml_alloc_tuple (2);
3841 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3842 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3844 if (!*s) {
3845 freepage (page);
3847 unlock (__func__);
3848 CAMLreturn (ret_v);
3851 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
3852 value contents_v)
3854 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3855 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3857 if (pdf) {
3858 pdf_annot *annot;
3859 struct page *page;
3860 fz_point p;
3861 char *s = String_val (ptr_v);
3863 page = parse_pointer (__func__, s);
3864 annot = pdf_create_annot (state.ctx,
3865 pdf_page_from_fz_page (state.ctx,
3866 page->fzpage),
3867 PDF_ANNOT_TEXT);
3868 p.x = Int_val (x_v);
3869 p.y = Int_val (y_v);
3870 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3871 pdf_set_text_annot_position (state.ctx, annot, p);
3872 state.dirty = 1;
3874 CAMLreturn0;
3877 CAMLprim void ml_delannot (value ptr_v, value n_v)
3879 CAMLparam2 (ptr_v, n_v);
3880 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3882 if (pdf) {
3883 struct page *page;
3884 char *s = String_val (ptr_v);
3885 struct slink *slink;
3887 page = parse_pointer (__func__, s);
3888 slink = &page->slinks[Int_val (n_v)];
3889 pdf_delete_annot (state.ctx,
3890 pdf_page_from_fz_page (state.ctx, page->fzpage),
3891 (pdf_annot *) slink->u.annot);
3892 state.dirty = 1;
3894 CAMLreturn0;
3897 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
3899 CAMLparam3 (ptr_v, n_v, str_v);
3900 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3902 if (pdf) {
3903 struct page *page;
3904 char *s = String_val (ptr_v);
3905 struct slink *slink;
3907 page = parse_pointer (__func__, s);
3908 slink = &page->slinks[Int_val (n_v)];
3909 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3910 String_val (str_v));
3911 state.dirty = 1;
3913 CAMLreturn0;
3916 CAMLprim value ml_hasunsavedchanges (value unit_v)
3918 CAMLparam1 (unit_v);
3919 CAMLreturn (Val_bool (state.dirty));
3922 CAMLprim void ml_savedoc (value path_v)
3924 CAMLparam1 (path_v);
3925 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3927 if (pdf) {
3928 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3930 CAMLreturn0;
3933 static void makestippletex (void)
3935 const char pixels[] = "\xff\xff\0\0";
3936 glGenTextures (1, &state.stid);
3937 glBindTexture (GL_TEXTURE_1D, state.stid);
3938 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3939 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3940 glTexImage1D (
3941 GL_TEXTURE_1D,
3943 GL_ALPHA,
3946 GL_ALPHA,
3947 GL_UNSIGNED_BYTE,
3948 pixels
3952 CAMLprim value ml_fz_version (void)
3954 return caml_copy_string (FZ_VERSION);
3957 CAMLprim value ml_llpp_version (void)
3959 extern char llpp_version[];
3960 return caml_copy_string (llpp_version);
3963 CAMLprim void ml_init (value csock_v, value params_v)
3965 CAMLparam2 (csock_v, params_v);
3966 CAMLlocal2 (trim_v, fuzz_v);
3967 int ret;
3968 int texcount;
3969 char *fontpath;
3970 int colorspace;
3971 int mustoresize;
3972 int haspboext;
3974 state.csock = Int_val (csock_v);
3975 state.rotate = Int_val (Field (params_v, 0));
3976 state.fitmodel = Int_val (Field (params_v, 1));
3977 trim_v = Field (params_v, 2);
3978 texcount = Int_val (Field (params_v, 3));
3979 state.sliceheight = Int_val (Field (params_v, 4));
3980 mustoresize = Int_val (Field (params_v, 5));
3981 colorspace = Int_val (Field (params_v, 6));
3982 fontpath = String_val (Field (params_v, 7));
3984 #ifdef __COCOA__
3985 state.utf8cs = 1;
3986 #else
3987 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3988 if (setlocale (LC_CTYPE, "")) {
3989 const char *cset = nl_langinfo (CODESET);
3990 state.utf8cs = !strcmp (cset, "UTF-8");
3992 else {
3993 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3995 #endif
3997 if (caml_string_length (Field (params_v, 8)) > 0) {
3998 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
4000 if (!state.trimcachepath) {
4001 printd ("emsg failed to strdup trimcachepath: %d:%s",
4002 errno, strerror (errno));
4006 haspboext = Bool_val (Field (params_v, 9));
4008 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4009 fz_register_document_handlers (state.ctx);
4011 state.trimmargins = Bool_val (Field (trim_v, 0));
4012 fuzz_v = Field (trim_v, 1);
4013 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4014 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4015 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4016 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4018 set_tex_params (colorspace);
4020 if (*fontpath) {
4021 state.face = load_font (fontpath);
4023 else {
4024 int len;
4025 const unsigned char *data;
4027 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4028 state.face = load_builtin_font (data, len);
4030 if (!state.face) _exit (1);
4032 realloctexts (texcount);
4034 if (haspboext) {
4035 setuppbo ();
4038 makestippletex ();
4040 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4041 if (ret) {
4042 errx (1, "pthread_create: %s", strerror (ret));
4045 CAMLreturn0;
4048 #if FIXME || !FIXME
4049 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
4050 #endif