Update
[llpp.git] / link.c
blob3c2a0a59916dda919cf509043e375ed659a3cdbc
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 #ifdef USE_NPOT
77 #define TEXT_TYPE GL_TEXTURE_2D
78 #else
79 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
80 #endif
82 #if 0
83 #define lprintf printf
84 #else
85 #define lprintf(...)
86 #endif
88 #define ARSERT(cond) for (;;) { \
89 if (!(cond)) { \
90 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
91 } \
92 break; \
95 struct slice {
96 int h;
97 int texindex;
100 struct tile {
101 int w, h;
102 int slicecount;
103 int sliceheight;
104 struct bo *pbo;
105 fz_pixmap *pixmap;
106 struct slice slices[1];
109 struct pagedim {
110 int pageno;
111 int rotate;
112 int left;
113 int tctmready;
114 fz_irect bounds;
115 fz_rect pagebox;
116 fz_rect mediabox;
117 fz_matrix ctm, zoomctm, tctm;
120 struct slink {
121 enum { SLINK, SANNOT } tag;
122 fz_irect bbox;
123 union {
124 fz_link *link;
125 fz_annot *annot;
126 } u;
129 struct annot {
130 fz_irect bbox;
131 fz_annot *annot;
134 struct page {
135 int tgen;
136 int sgen;
137 int agen;
138 int pageno;
139 int pdimno;
140 fz_stext_page *text;
141 fz_page *fzpage;
142 fz_display_list *dlist;
143 fz_link *links;
144 int slinkcount;
145 struct slink *slinks;
146 int annotcount;
147 struct annot *annots;
148 fz_stext_char *fmark, *lmark;
151 enum { FitWidth, FitProportional, FitPage };
153 static struct {
154 int sliceheight;
155 struct pagedim *pagedims;
156 int pagecount;
157 int pagedimcount;
158 fz_document *doc;
159 fz_context *ctx;
160 int w, h;
162 int texindex;
163 int texcount;
164 GLuint *texids;
166 GLenum texiform;
167 GLenum texform;
168 GLenum texty;
170 fz_colorspace *colorspace;
172 struct {
173 int w, h;
174 struct slice *slice;
175 } *texowners;
177 int rotate;
178 int fitmodel;
179 int trimmargins;
180 int needoutline;
181 int gen;
182 int aalevel;
184 int trimanew;
185 fz_irect trimfuzz;
186 fz_pixmap *pig;
188 pthread_t thread;
189 int csock;
190 FT_Face face;
192 char *trimcachepath;
193 int dirty;
195 GLuint stid;
197 int bo_usable;
198 GLuint boid;
200 void (*glBindBufferARB) (GLenum, GLuint);
201 GLboolean (*glUnmapBufferARB) (GLenum);
202 void *(*glMapBufferARB) (GLenum, GLenum);
203 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
204 void (*glGenBuffersARB) (GLsizei, GLuint *);
205 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
207 GLfloat texcoords[8];
208 GLfloat vertices[16];
210 #ifdef CACHE_PAGEREFS
211 struct {
212 int idx;
213 int count;
214 pdf_obj **objs;
215 pdf_document *pdf;
216 } pdflut;
217 #endif
218 int utf8cs;
219 } state;
221 struct bo {
222 GLuint id;
223 void *ptr;
224 size_t size;
227 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
229 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
232 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
234 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
237 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
239 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
240 m.a, m.b, m.c, m.d, m.e, m.f);
243 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
245 static void lock (const char *cap)
247 int ret = pthread_mutex_lock (&mutex);
248 if (ret) {
249 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
253 static void unlock (const char *cap)
255 int ret = pthread_mutex_unlock (&mutex);
256 if (ret) {
257 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
261 static int trylock (const char *cap)
263 int ret = pthread_mutex_trylock (&mutex);
264 if (ret && ret != EBUSY) {
265 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
267 return ret == EBUSY;
270 static int hasdata (void)
272 int ret, avail;
273 ret = ioctl (state.csock, FIONREAD, &avail);
274 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
275 return avail > 0;
278 CAMLprim value ml_hasdata (value fd_v)
280 CAMLparam1 (fd_v);
281 int ret, avail;
283 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
284 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
285 CAMLreturn (Val_bool (avail > 0));
288 static void readdata (int fd, void *p, int size)
290 ssize_t n;
292 again:
293 n = read (fd, p, size);
294 if (n - size) {
295 if (n < 0 && errno == EINTR) goto again;
296 if (!n) errx (1, "EOF while reading");
297 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
301 static void writedata (int fd, char *p, int size)
303 ssize_t n;
304 uint32_t size4 = size;
305 struct iovec iov[2] = {
306 { .iov_base = &size4, .iov_len = 4 },
307 { .iov_base = p, .iov_len = size }
310 again:
311 n = writev (fd, iov, 2);
312 if (n < 0 && errno == EINTR) goto again;
313 if (n - size - 4) {
314 if (!n) errx (1, "EOF while writing data");
315 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
319 static int readlen (int fd)
321 uint32_t u;
322 readdata (fd, &u, 4);
323 return u;
326 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
328 CAMLparam3 (fd_v, bytes_v, len_v);
329 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
330 CAMLreturn0;
333 CAMLprim value ml_rcmd (value fd_v)
335 CAMLparam1 (fd_v);
336 CAMLlocal1 (strdata_v);
337 int fd = Int_val (fd_v);
338 int len = readlen (fd);
339 strdata_v = caml_alloc_string (len);
340 readdata (fd, String_val (strdata_v), len);
341 CAMLreturn (strdata_v);
344 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
346 char fbuf[64];
347 int size = sizeof (fbuf), len;
348 va_list ap;
349 char *buf = fbuf;
351 for (;;) {
352 va_start (ap, fmt);
353 len = vsnprintf (buf, size, fmt, ap);
354 va_end (ap);
356 if (len > -1) {
357 if (len < size - 4) {
358 writedata (state.csock, buf, len);
359 break;
361 else size = len + 5;
363 else {
364 err (1, "vsnprintf for `%s' failed", fmt);
366 buf = realloc (buf == fbuf ? NULL : buf, size);
367 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
369 if (buf != fbuf) free (buf);
372 static void closedoc (void)
374 #ifdef CACHE_PAGEREFS
375 if (state.pdflut.objs) {
376 for (int i = 0; i < state.pdflut.count; ++i) {
377 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
379 free (state.pdflut.objs);
380 state.pdflut.objs = NULL;
381 state.pdflut.idx = 0;
383 #endif
384 if (state.doc) {
385 fz_drop_document (state.ctx, state.doc);
386 state.doc = NULL;
390 static int openxref (char *filename, char *password, int layouth)
392 for (int i = 0; i < state.texcount; ++i) {
393 state.texowners[i].w = -1;
394 state.texowners[i].slice = NULL;
397 closedoc ();
399 state.dirty = 0;
400 if (state.pagedims) {
401 free (state.pagedims);
402 state.pagedims = NULL;
404 state.pagedimcount = 0;
406 fz_set_aa_level (state.ctx, state.aalevel);
407 state.doc = fz_open_document (state.ctx, filename);
408 if (fz_needs_password (state.ctx, state.doc)) {
409 if (password && !*password) {
410 printd ("pass");
411 return 0;
413 else {
414 int ok = fz_authenticate_password (state.ctx, state.doc, password);
415 if (!ok) {
416 printd ("pass fail");
417 return 0;
421 if (layouth >= 0)
422 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
423 state.pagecount = fz_count_pages (state.ctx, state.doc);
424 return 1;
427 static void docinfo (void)
429 struct { char *tag; char *name; } metatbl[] = {
430 { FZ_META_INFO_TITLE, "Title" },
431 { FZ_META_INFO_AUTHOR, "Author" },
432 { FZ_META_FORMAT, "Format" },
433 { FZ_META_ENCRYPTION, "Encryption" },
434 { "info:Creator", "Creator" },
435 { "info:Producer", "Producer" },
436 { "info:CreationDate", "Creation date" },
438 int len = 0;
439 char *buf = NULL;
441 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
442 int need;
443 again:
444 need = fz_lookup_metadata (state.ctx, state.doc,
445 metatbl[i].tag, buf, len);
446 if (need > 0) {
447 if (need <= len) {
448 printd ("info %s\t%s", metatbl[i].name, buf);
450 else {
451 buf = realloc (buf, need + 1);
452 if (!buf) err (1, "docinfo realloc %d", need + 1);
453 len = need + 1;
454 goto again;
458 free (buf);
460 printd ("infoend");
463 static void unlinktile (struct tile *tile)
465 for (int i = 0; i < tile->slicecount; ++i) {
466 struct slice *s = &tile->slices[i];
468 if (s->texindex != -1) {
469 if (state.texowners[s->texindex].slice == s) {
470 state.texowners[s->texindex].slice = NULL;
476 static void freepage (struct page *page)
478 if (!page) return;
479 if (page->text) {
480 fz_drop_stext_page (state.ctx, page->text);
482 if (page->slinks) {
483 free (page->slinks);
485 fz_drop_display_list (state.ctx, page->dlist);
486 fz_drop_page (state.ctx, page->fzpage);
487 free (page);
490 static void freetile (struct tile *tile)
492 unlinktile (tile);
493 if (!tile->pbo) {
494 #if 0 /* piggyback */
495 fz_drop_pixmap (state.ctx, tile->pixmap);
496 #else
497 if (state.pig) {
498 fz_drop_pixmap (state.ctx, state.pig);
500 state.pig = tile->pixmap;
501 #endif
503 else {
504 free (tile->pbo);
505 fz_drop_pixmap (state.ctx, tile->pixmap);
507 free (tile);
510 static void trimctm (pdf_page *page, int pindex)
512 fz_matrix ctm;
513 struct pagedim *pdim = &state.pagedims[pindex];
515 if (!page) return;
516 if (!pdim->tctmready) {
517 fz_rect realbox, mediabox;
518 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
520 fz_rotate (&rm, -pdim->rotate);
521 fz_scale (&sm, 1, -1);
522 fz_concat (&ctm, &rm, &sm);
523 realbox = pdim->mediabox;
524 fz_transform_rect (&realbox, &ctm);
525 fz_translate (&tm, -realbox.x0, -realbox.y0);
526 fz_concat (&ctm1, &ctm, &tm);
527 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
528 fz_invert_matrix (&im, &page_ctm);
529 fz_concat (&ctm, &im, &ctm1);
530 pdim->tctm = ctm;
531 pdim->tctmready = 1;
535 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
537 fz_matrix ctm, tm;
538 ptrdiff_t pdimno = pdim - state.pagedims;
540 ARSERT (pdim - state.pagedims < INT_MAX);
541 if (pdf_specifics (state.ctx, state.doc)) {
542 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
543 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
545 else {
546 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
547 fz_concat (&ctm, &tm, &pdim->ctm);
549 return ctm;
552 static fz_matrix pagectm (struct page *page)
554 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
557 static void *loadpage (int pageno, int pindex)
559 fz_device *dev;
560 struct page *page;
562 page = calloc (sizeof (struct page), 1);
563 if (!page) {
564 err (1, "calloc page %d", pageno);
567 page->dlist = fz_new_display_list (state.ctx, NULL);
568 dev = fz_new_list_device (state.ctx, page->dlist);
569 fz_try (state.ctx) {
570 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
571 fz_run_page (state.ctx, page->fzpage, dev,
572 &fz_identity, NULL);
574 fz_catch (state.ctx) {
575 page->fzpage = NULL;
577 fz_close_device (state.ctx, dev);
578 fz_drop_device (state.ctx, dev);
580 page->pdimno = pindex;
581 page->pageno = pageno;
582 page->sgen = state.gen;
583 page->agen = state.gen;
584 page->tgen = state.gen;
585 return page;
588 static struct tile *alloctile (int h)
590 int slicecount;
591 size_t tilesize;
592 struct tile *tile;
594 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
595 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
596 tile = calloc (tilesize, 1);
597 if (!tile) {
598 err (1, "cannot allocate tile (%zu bytes)", tilesize);
600 for (int i = 0; i < slicecount; ++i) {
601 int sh = fz_mini (h, state.sliceheight);
602 tile->slices[i].h = sh;
603 tile->slices[i].texindex = -1;
604 h -= sh;
606 tile->slicecount = slicecount;
607 tile->sliceheight = state.sliceheight;
608 return tile;
611 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
612 struct bo *pbo)
614 fz_rect rect;
615 fz_irect bbox;
616 fz_matrix ctm;
617 fz_device *dev;
618 struct tile *tile;
619 struct pagedim *pdim;
621 tile = alloctile (h);
622 pdim = &state.pagedims[page->pdimno];
624 bbox = pdim->bounds;
625 bbox.x0 += x;
626 bbox.y0 += y;
627 bbox.x1 = bbox.x0 + w;
628 bbox.y1 = bbox.y0 + h;
630 if (state.pig) {
631 if (state.pig->w == w
632 && state.pig->h == h
633 && state.pig->colorspace == state.colorspace) {
634 tile->pixmap = state.pig;
635 tile->pixmap->x = bbox.x0;
636 tile->pixmap->y = bbox.y0;
638 else {
639 fz_drop_pixmap (state.ctx, state.pig);
641 state.pig = NULL;
643 if (!tile->pixmap) {
644 if (pbo) {
645 tile->pixmap =
646 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
647 &bbox, NULL, 1, pbo->ptr);
648 tile->pbo = pbo;
650 else {
651 tile->pixmap =
652 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
653 NULL, 1);
657 tile->w = w;
658 tile->h = h;
659 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
661 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
662 ctm = pagectm (page);
663 fz_rect_from_irect (&rect, &bbox);
664 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
665 fz_close_device (state.ctx, dev);
666 fz_drop_device (state.ctx, dev);
668 return tile;
671 #ifdef CACHE_PAGEREFS
672 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
673 thanks to Robin Watts */
674 static void
675 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
677 fz_context *ctx = state.ctx; /* doc->ctx; */
678 pdf_obj *kids;
679 int len;
681 if (state.pdflut.idx == state.pagecount) return;
683 kids = pdf_dict_gets (ctx, node, "Kids");
684 len = pdf_array_len (ctx, kids);
686 if (len == 0)
687 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
689 if (pdf_mark_obj (ctx, node))
690 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
691 for (int i = 0; i < len; i++) {
692 pdf_obj *kid = pdf_array_get (ctx, kids, i);
693 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
694 if (*type
695 ? !strcmp (type, "Pages")
696 : pdf_dict_gets (ctx, kid, "Kids")
697 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
698 pdf_collect_pages (doc, kid);
700 else {
701 if (*type
702 ? strcmp (type, "Page") != 0
703 : !pdf_dict_gets (ctx, kid, "MediaBox"))
704 fz_warn (ctx, "non-page object in page tree (%s)", type);
705 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
708 pdf_unmark_obj (ctx, node);
711 static void
712 pdf_load_page_objs (pdf_document *doc)
714 pdf_obj *root = pdf_dict_gets (state.ctx,
715 pdf_trailer (state.ctx, doc), "Root");
716 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
718 if (!node)
719 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
721 state.pdflut.idx = 0;
722 pdf_collect_pages (doc, node);
724 #endif
726 static void initpdims (void)
728 double start, end;
729 FILE *trimf = NULL;
730 fz_rect rootmediabox = fz_empty_rect;
731 int pageno, trim, show;
732 int trimw = 0, cxcount;
733 fz_context *ctx = state.ctx;
734 pdf_document *pdf = pdf_specifics (ctx, state.doc);
736 fz_var (trimw);
737 fz_var (trimf);
738 fz_var (cxcount);
739 start = now ();
741 if (state.trimmargins && state.trimcachepath) {
742 trimf = fopen (state.trimcachepath, "rb");
743 if (!trimf) {
744 trimf = fopen (state.trimcachepath, "wb");
745 trimw = 1;
749 if (state.trimmargins || pdf)
750 cxcount = state.pagecount;
751 else
752 cxcount = fz_mini (state.pagecount, 1);
754 if (pdf) {
755 pdf_obj *obj;
756 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
757 "Root/Pages/MediaBox");
758 pdf_to_rect (ctx, obj, &rootmediabox);
761 #ifdef CACHE_PAGEREFS
762 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
763 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
764 if (!state.pdflut.objs) {
765 err (1, "malloc pageobjs %zu %d %zu failed",
766 sizeof (*state.pdflut.objs), cxcount,
767 sizeof (*state.pdflut.objs) * cxcount);
769 state.pdflut.count = cxcount;
770 pdf_load_page_objs (pdf);
771 state.pdflut.pdf = pdf;
773 #endif
775 for (pageno = 0; pageno < cxcount; ++pageno) {
776 int rotate = 0;
777 struct pagedim *p;
778 fz_rect mediabox = fz_empty_rect;
780 fz_var (rotate);
781 if (pdf) {
782 pdf_obj *pageref, *pageobj;
784 #ifdef CACHE_PAGEREFS
785 pageref = state.pdflut.objs[pageno];
786 #else
787 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
788 #endif
789 pageobj = pdf_resolve_indirect (ctx, pageref);
790 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
792 if (state.trimmargins) {
793 pdf_obj *obj;
794 pdf_page *page;
796 fz_try (ctx) {
797 page = pdf_load_page (ctx, pdf, pageno);
798 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
799 trim = state.trimanew || !obj;
800 if (trim) {
801 fz_rect rect;
802 fz_device *dev;
803 fz_matrix ctm, page_ctm;
805 dev = fz_new_bbox_device (ctx, &rect);
806 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
807 fz_invert_matrix (&ctm, &page_ctm);
808 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
809 fz_close_device (ctx, dev);
810 fz_drop_device (ctx, dev);
812 rect.x0 += state.trimfuzz.x0;
813 rect.x1 += state.trimfuzz.x1;
814 rect.y0 += state.trimfuzz.y0;
815 rect.y1 += state.trimfuzz.y1;
816 fz_transform_rect (&rect, &ctm);
817 fz_intersect_rect (&rect, &mediabox);
819 if (!fz_is_empty_rect (&rect)) {
820 mediabox = rect;
823 obj = pdf_new_array (ctx, pdf, 4);
824 pdf_array_push (ctx, obj,
825 pdf_new_real (ctx, mediabox.x0));
826 pdf_array_push (ctx, obj,
827 pdf_new_real (ctx, mediabox.y0));
828 pdf_array_push (ctx, obj,
829 pdf_new_real (ctx, mediabox.x1));
830 pdf_array_push (ctx, obj,
831 pdf_new_real (ctx, mediabox.y1));
832 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
834 else {
835 mediabox.x0 = pdf_to_real (ctx,
836 pdf_array_get (ctx, obj, 0));
837 mediabox.y0 = pdf_to_real (ctx,
838 pdf_array_get (ctx, obj, 1));
839 mediabox.x1 = pdf_to_real (ctx,
840 pdf_array_get (ctx, obj, 2));
841 mediabox.y1 = pdf_to_real (ctx,
842 pdf_array_get (ctx, obj, 3));
845 fz_drop_page (ctx, &page->super);
846 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
847 if (show) {
848 printd ("progress %f Trimming %d",
849 (double) (pageno + 1) / state.pagecount,
850 pageno + 1);
853 fz_catch (ctx) {
854 printd ("emsg failed to load page %d", pageno);
857 else {
858 int empty = 0;
859 fz_rect cropbox;
861 pdf_to_rect (ctx,
862 pdf_dict_gets (ctx, pageobj, "MediaBox"),
863 &mediabox);
864 if (fz_is_empty_rect (&mediabox)) {
865 mediabox.x0 = 0;
866 mediabox.y0 = 0;
867 mediabox.x1 = 612;
868 mediabox.y1 = 792;
869 empty = 1;
872 pdf_to_rect (ctx,
873 pdf_dict_gets (ctx, pageobj, "CropBox"),
874 &cropbox);
875 if (!fz_is_empty_rect (&cropbox)) {
876 if (empty) {
877 mediabox = cropbox;
879 else {
880 fz_intersect_rect (&mediabox, &cropbox);
883 else {
884 if (empty) {
885 if (fz_is_empty_rect (&rootmediabox)) {
886 printd ("emsg cannot find page size for page %d",
887 pageno);
889 else {
890 mediabox = rootmediabox;
896 else {
897 if (state.trimmargins && trimw) {
898 fz_page *page;
900 fz_try (ctx) {
901 page = fz_load_page (ctx, state.doc, pageno);
902 fz_bound_page (ctx, page, &mediabox);
903 if (state.trimmargins) {
904 fz_rect rect;
905 fz_device *dev;
907 dev = fz_new_bbox_device (ctx, &rect);
908 fz_run_page (ctx, page, dev, &fz_identity, NULL);
909 fz_close_device (ctx, dev);
910 fz_drop_device (ctx, dev);
912 rect.x0 += state.trimfuzz.x0;
913 rect.x1 += state.trimfuzz.x1;
914 rect.y0 += state.trimfuzz.y0;
915 rect.y1 += state.trimfuzz.y1;
916 fz_intersect_rect (&rect, &mediabox);
918 if (!fz_is_empty_rect (&rect)) {
919 mediabox = rect;
922 fz_drop_page (ctx, page);
924 fz_catch (ctx) {
926 if (trimf) {
927 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
928 if (n - 1) {
929 err (1, "fwrite trim mediabox");
933 else {
934 if (trimf) {
935 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
936 if (n - 1) {
937 err (1, "fread trim mediabox %d", pageno);
940 else {
941 fz_page *page;
942 fz_try (ctx) {
943 page = fz_load_page (ctx, state.doc, pageno);
944 fz_bound_page (ctx, page, &mediabox);
945 fz_drop_page (ctx, page);
947 show = !state.trimmargins && pageno % 20 == 0;
948 if (show) {
949 printd ("progress %f Gathering dimensions %d",
950 (double) (pageno) / state.pagecount,
951 pageno);
954 fz_catch (ctx) {
955 printd ("emsg failed to load page %d", pageno);
961 if (state.pagedimcount == 0
962 || ((void) (p = &state.pagedims[state.pagedimcount-1])
963 , p->rotate != rotate)
964 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
965 size_t size;
967 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
968 state.pagedims = realloc (state.pagedims, size);
969 if (!state.pagedims) {
970 err (1, "realloc pagedims to %zu (%d elems)",
971 size, state.pagedimcount + 1);
974 p = &state.pagedims[state.pagedimcount++];
975 p->rotate = rotate;
976 p->mediabox = mediabox;
977 p->pageno = pageno;
980 end = now ();
981 printd ("progress 1 %s %d pages in %f seconds",
982 state.trimmargins ? "Trimmed" : "Processed",
983 state.pagecount, end - start);
984 state.trimanew = 0;
985 if (trimf) {
986 if (fclose (trimf)) {
987 err (1, "fclose");
992 static void layout (void)
994 int pindex;
995 fz_rect box;
996 fz_matrix ctm, rm;
997 struct pagedim *p = NULL;
998 float zw, w, maxw = 0.0, zoom = 1.0;
1000 if (state.pagedimcount == 0) return;
1002 switch (state.fitmodel) {
1003 case FitProportional:
1004 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1005 float x0, x1;
1007 p = &state.pagedims[pindex];
1008 fz_rotate (&rm, p->rotate + state.rotate);
1009 box = p->mediabox;
1010 fz_transform_rect (&box, &rm);
1012 x0 = fz_min (box.x0, box.x1);
1013 x1 = fz_max (box.x0, box.x1);
1015 w = x1 - x0;
1016 maxw = fz_max (w, maxw);
1017 zoom = state.w / maxw;
1019 break;
1021 case FitPage:
1022 maxw = state.w;
1023 break;
1025 case FitWidth:
1026 break;
1028 default:
1029 ARSERT (0 && state.fitmodel);
1032 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1033 fz_rect rect;
1034 fz_matrix tm, sm;
1036 p = &state.pagedims[pindex];
1037 fz_rotate (&ctm, state.rotate);
1038 fz_rotate (&rm, p->rotate + state.rotate);
1039 box = p->mediabox;
1040 fz_transform_rect (&box, &rm);
1041 w = box.x1 - box.x0;
1042 switch (state.fitmodel) {
1043 case FitProportional:
1044 p->left = (int) (((maxw - w) * zoom) / 2.f);
1045 break;
1046 case FitPage:
1048 float zh, h;
1049 zw = maxw / w;
1050 h = box.y1 - box.y0;
1051 zh = state.h / h;
1052 zoom = fz_min (zw, zh);
1053 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1055 break;
1056 case FitWidth:
1057 p->left = 0;
1058 zoom = state.w / w;
1059 break;
1062 fz_scale (&p->zoomctm, zoom, zoom);
1063 fz_concat (&ctm, &p->zoomctm, &ctm);
1065 fz_rotate (&rm, p->rotate);
1066 p->pagebox = p->mediabox;
1067 fz_transform_rect (&p->pagebox, &rm);
1068 p->pagebox.x1 -= p->pagebox.x0;
1069 p->pagebox.y1 -= p->pagebox.y0;
1070 p->pagebox.x0 = 0;
1071 p->pagebox.y0 = 0;
1072 rect = p->pagebox;
1073 fz_transform_rect (&rect, &ctm);
1074 fz_round_rect (&p->bounds, &rect);
1075 p->ctm = ctm;
1077 fz_translate (&tm, 0, -p->mediabox.y1);
1078 fz_scale (&sm, zoom, -zoom);
1079 fz_concat (&ctm, &tm, &sm);
1081 p->tctmready = 0;
1084 do {
1085 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1086 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1087 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1088 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1089 int boundw = x1 - x0;
1090 int boundh = y1 - y0;
1092 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1093 } while (p-- != state.pagedims);
1096 struct pagedim *pdimofpageno (int pageno)
1098 struct pagedim *pdim = state.pagedims;
1100 for (int i = 0; i < state.pagedimcount; ++i) {
1101 if (state.pagedims[i].pageno > pageno)
1102 break;
1103 pdim = &state.pagedims[i];
1105 return pdim;
1108 static void recurse_outline (fz_outline *outline, int level)
1110 while (outline) {
1111 if (outline->page >= 0) {
1112 fz_point p = {.x = outline->x, .y = outline->y};
1113 struct pagedim *pdim = pdimofpageno (outline->page);
1114 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1115 fz_transform_point (&p, &pdim->ctm);
1116 printd ("o %d %d %d %d %s",
1117 level, outline->page, (int) p.y, h, outline->title);
1119 else {
1120 printd ("on %d %s", level, outline->title);
1122 if (outline->down) {
1123 recurse_outline (outline->down, level + 1);
1125 outline = outline->next;
1129 static void process_outline (void)
1131 fz_outline *outline;
1133 if (!state.needoutline || !state.pagedimcount) return;
1135 state.needoutline = 0;
1136 outline = fz_load_outline (state.ctx, state.doc);
1137 if (outline) {
1138 recurse_outline (outline, 0);
1139 fz_drop_outline (state.ctx, outline);
1143 static char *strofline (fz_stext_line *line)
1145 char *p;
1146 char utf8[10];
1147 fz_stext_char *ch;
1148 size_t size = 0, cap = 80;
1150 p = malloc (cap + 1);
1151 if (!p) return NULL;
1153 for (ch = line->first_char; ch; ch = ch->next) {
1154 int n = fz_runetochar (utf8, ch->c);
1155 if (size + n > cap) {
1156 cap *= 2;
1157 p = realloc (p, cap + 1);
1158 if (!p) return NULL;
1161 memcpy (p + size, utf8, n);
1162 size += n;
1164 p[size] = 0;
1165 return p;
1168 static int matchline (regex_t *re, fz_stext_line *line,
1169 int stop, int pageno, double start)
1171 int ret;
1172 char *p;
1173 regmatch_t rm;
1175 p = strofline (line);
1176 if (!p) return -1;
1178 ret = regexec (re, p, 1, &rm, 0);
1179 if (ret) {
1180 free (p);
1181 if (ret != REG_NOMATCH) {
1182 size_t size;
1183 char errbuf[80];
1184 size = regerror (ret, re, errbuf, sizeof (errbuf));
1185 printd ("msg regexec error `%.*s'",
1186 (int) size, errbuf);
1187 return -1;
1189 return 0;
1191 else {
1192 fz_point p1, p2, p3, p4;
1193 fz_rect s = {0,0,0,0}, e;
1194 fz_stext_char *ch;
1195 int o = 0;
1197 for (ch = line->first_char; ch; ch = ch->next) {
1198 o += fz_runelen (ch->c);
1199 if (o > rm.rm_so) {
1200 s = ch->bbox;
1201 break;
1204 for (;ch; ch = ch->next) {
1205 o += fz_runelen (ch->c);
1206 if (o > rm.rm_eo) break;
1208 e = ch->bbox;
1210 p1.x = s.x0;
1211 p1.y = s.y0;
1212 p2.x = e.x1;
1213 p2.y = s.y0;
1214 p3.x = e.x1;
1215 p3.y = e.y1;
1216 p4.x = s.x0;
1217 p4.y = e.y1;
1219 if (!stop) {
1220 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1221 pageno, 1,
1222 p1.x, p1.y,
1223 p2.x, p2.y,
1224 p3.x, p3.y,
1225 p4.x, p4.y);
1227 printd ("progress 1 found at %d `%.*s' in %f sec",
1228 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1229 now () - start);
1231 else {
1232 printd ("match %d %d %f %f %f %f %f %f %f %f",
1233 pageno, 2,
1234 p1.x, p1.y,
1235 p2.x, p2.y,
1236 p3.x, p3.y,
1237 p4.x, p4.y);
1239 free (p);
1240 return 1;
1244 /* wishful thinking function */
1245 static void search (regex_t *re, int pageno, int y, int forward)
1247 fz_device *tdev;
1248 fz_stext_page *text;
1249 struct pagedim *pdim;
1250 int stop = 0, niters = 0;
1251 double start, end;
1252 fz_page *page;
1253 fz_stext_block *block;
1255 start = now ();
1256 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1257 if (niters++ == 5) {
1258 niters = 0;
1259 if (hasdata ()) {
1260 printd ("progress 1 attention requested aborting search at %d",
1261 pageno);
1262 stop = 1;
1264 else {
1265 printd ("progress %f searching in page %d",
1266 (double) (pageno + 1) / state.pagecount,
1267 pageno);
1270 pdim = pdimofpageno (pageno);
1271 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1272 tdev = fz_new_stext_device (state.ctx, text, 0);
1274 page = fz_load_page (state.ctx, state.doc, pageno);
1276 fz_matrix ctm = pagectm1 (page, pdim);
1277 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1280 fz_close_device (state.ctx, tdev);
1281 fz_drop_device (state.ctx, tdev);
1283 if (forward) {
1284 for (block = text->first_block; block; block = block->next) {
1285 fz_stext_line *line;
1287 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1288 for (line = block->u.t.first_line; line; line = line->next) {
1289 if (line->bbox.y0 < y + 1) continue;
1291 switch (matchline (re, line, stop, pageno, start)) {
1292 case 0: break;
1293 case 1: stop = 1; break;
1294 case -1: stop = 1; goto endloop;
1299 else {
1300 for (block = text->last_block; block; block = block->prev) {
1301 fz_stext_line *line;
1303 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1304 for (line = block->u.t.last_line; line; line = line->prev) {
1305 if (line->bbox.y0 < y + 1) continue;
1307 switch (matchline (re, line, stop, pageno, start)) {
1308 case 0: break;
1309 case 1: stop = 1; break;
1310 case -1: stop = 1; goto endloop;
1316 if (forward) {
1317 pageno += 1;
1318 y = 0;
1320 else {
1321 pageno -= 1;
1322 y = INT_MAX;
1324 endloop:
1325 fz_drop_stext_page (state.ctx, text);
1326 fz_drop_page (state.ctx, page);
1328 end = now ();
1329 if (!stop) {
1330 printd ("progress 1 no matches %f sec", end - start);
1332 printd ("clearrects");
1335 static void set_tex_params (int colorspace)
1337 switch (colorspace) {
1338 case 0:
1339 state.texiform = GL_RGBA8;
1340 state.texform = GL_RGBA;
1341 state.texty = GL_UNSIGNED_BYTE;
1342 state.colorspace = fz_device_rgb (state.ctx);
1343 break;
1344 case 1:
1345 state.texiform = GL_RGBA8;
1346 state.texform = GL_BGRA;
1347 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1348 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1349 #else
1350 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1351 #endif
1352 state.colorspace = fz_device_bgr (state.ctx);
1353 break;
1354 case 2:
1355 state.texiform = GL_LUMINANCE_ALPHA;
1356 state.texform = GL_LUMINANCE_ALPHA;
1357 state.texty = GL_UNSIGNED_BYTE;
1358 state.colorspace = fz_device_gray (state.ctx);
1359 break;
1360 default:
1361 errx (1, "invalid colorspce %d", colorspace);
1365 static void realloctexts (int texcount)
1367 size_t size;
1369 if (texcount == state.texcount) return;
1371 if (texcount < state.texcount) {
1372 glDeleteTextures (state.texcount - texcount,
1373 state.texids + texcount);
1376 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1377 state.texids = realloc (state.texids, size);
1378 if (!state.texids) {
1379 err (1, "realloc texs %zu", size);
1382 state.texowners = (void *) (state.texids + texcount);
1383 if (texcount > state.texcount) {
1384 glGenTextures (texcount - state.texcount,
1385 state.texids + state.texcount);
1386 for (int i = state.texcount; i < texcount; ++i) {
1387 state.texowners[i].w = -1;
1388 state.texowners[i].slice = NULL;
1391 state.texcount = texcount;
1392 state.texindex = 0;
1395 static char *mbtoutf8 (char *s)
1397 char *p, *r;
1398 wchar_t *tmp;
1399 size_t i, ret, len;
1401 if (state.utf8cs) {
1402 return s;
1405 len = mbstowcs (NULL, s, strlen (s));
1406 if (len == 0) {
1407 return s;
1409 else {
1410 if (len == (size_t) -1) {
1411 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1412 return s;
1416 tmp = calloc (len, sizeof (wchar_t));
1417 if (!tmp) {
1418 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1419 len, sizeof (wchar_t), errno, strerror (errno));
1420 return s;
1423 ret = mbstowcs (tmp, s, len);
1424 if (ret == (size_t) -1) {
1425 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1426 len, errno, strerror (errno));
1427 free (tmp);
1428 return s;
1431 len = 0;
1432 for (i = 0; i < ret; ++i) {
1433 len += fz_runelen (tmp[i]);
1436 p = r = malloc (len + 1);
1437 if (!r) {
1438 printd ("emsg mbtoutf8: malloc(%zu)", len);
1439 free (tmp);
1440 return s;
1443 for (i = 0; i < ret; ++i) {
1444 p += fz_runetochar (p, tmp[i]);
1446 *p = 0;
1447 free (tmp);
1448 return r;
1451 CAMLprim value ml_mbtoutf8 (value s_v)
1453 CAMLparam1 (s_v);
1454 CAMLlocal1 (ret_v);
1455 char *s, *r;
1457 s = String_val (s_v);
1458 r = mbtoutf8 (s);
1459 if (r == s) {
1460 ret_v = s_v;
1462 else {
1463 ret_v = caml_copy_string (r);
1464 free (r);
1466 CAMLreturn (ret_v);
1469 static void * mainloop (void UNUSED_ATTR *unused)
1471 char *p = NULL;
1472 int len, ret, oldlen = 0;
1474 fz_var (p);
1475 fz_var (oldlen);
1476 for (;;) {
1477 len = readlen (state.csock);
1478 if (len == 0) {
1479 errx (1, "readlen returned 0");
1482 if (oldlen < len + 1) {
1483 p = realloc (p, len + 1);
1484 if (!p) {
1485 err (1, "realloc %d failed", len + 1);
1487 oldlen = len + 1;
1489 readdata (state.csock, p, len);
1490 p[len] = 0;
1492 if (!strncmp ("open", p, 4)) {
1493 int off, usedoccss, ok = 0, layouth;
1494 char *password;
1495 char *filename;
1496 char *utf8filename;
1497 size_t filenamelen;
1499 fz_var (ok);
1500 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1501 if (ret != 2) {
1502 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1505 filename = p + 5 + off;
1506 filenamelen = strlen (filename);
1507 password = filename + filenamelen + 1;
1509 if (password[strlen (password) + 1]) {
1510 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1513 lock ("open");
1514 fz_set_use_document_css (state.ctx, usedoccss);
1515 fz_try (state.ctx) {
1516 ok = openxref (filename, password, layouth);
1518 fz_catch (state.ctx) {
1519 utf8filename = mbtoutf8 (filename);
1520 printd ("msg Could not open %s", utf8filename);
1521 if (utf8filename != filename) {
1522 free (utf8filename);
1525 if (ok) {
1526 docinfo ();
1527 initpdims ();
1529 unlock ("open");
1531 if (ok) {
1532 utf8filename = mbtoutf8 (filename);
1533 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1534 if (utf8filename != filename) {
1535 free (utf8filename);
1537 state.needoutline = 1;
1540 else if (!strncmp ("cs", p, 2)) {
1541 int i, colorspace;
1543 ret = sscanf (p + 2, " %d", &colorspace);
1544 if (ret != 1) {
1545 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1547 lock ("cs");
1548 set_tex_params (colorspace);
1549 for (i = 0; i < state.texcount; ++i) {
1550 state.texowners[i].w = -1;
1551 state.texowners[i].slice = NULL;
1553 unlock ("cs");
1555 else if (!strncmp ("freepage", p, 8)) {
1556 void *ptr;
1558 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1559 if (ret != 1) {
1560 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1562 lock ("freepage");
1563 freepage (ptr);
1564 unlock ("freepage");
1566 else if (!strncmp ("freetile", p, 8)) {
1567 void *ptr;
1569 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1570 if (ret != 1) {
1571 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1573 lock ("freetile");
1574 freetile (ptr);
1575 unlock ("freetile");
1577 else if (!strncmp ("search", p, 6)) {
1578 int icase, pageno, y, len2, forward;
1579 char *pattern;
1580 regex_t re;
1582 ret = sscanf (p + 6, " %d %d %d %d,%n",
1583 &icase, &pageno, &y, &forward, &len2);
1584 if (ret != 4) {
1585 errx (1, "malformed search `%s' ret=%d", p, ret);
1588 pattern = p + 6 + len2;
1589 ret = regcomp (&re, pattern,
1590 REG_EXTENDED | (icase ? REG_ICASE : 0));
1591 if (ret) {
1592 char errbuf[80];
1593 size_t size;
1595 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1596 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1598 else {
1599 search (&re, pageno, y, forward);
1600 regfree (&re);
1603 else if (!strncmp ("geometry", p, 8)) {
1604 int w, h, fitmodel;
1606 printd ("clear");
1607 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1608 if (ret != 3) {
1609 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1612 lock ("geometry");
1613 state.h = h;
1614 if (w != state.w) {
1615 state.w = w;
1616 for (int i = 0; i < state.texcount; ++i) {
1617 state.texowners[i].slice = NULL;
1620 state.fitmodel = fitmodel;
1621 layout ();
1622 process_outline ();
1624 state.gen++;
1625 unlock ("geometry");
1626 printd ("continue %d", state.pagecount);
1628 else if (!strncmp ("reqlayout", p, 9)) {
1629 char *nameddest;
1630 int rotate, off, h;
1631 int fitmodel;
1632 pdf_document *pdf;
1634 printd ("clear");
1635 ret = sscanf (p + 9, " %d %d %d %n",
1636 &rotate, &fitmodel, &h, &off);
1637 if (ret != 3) {
1638 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1640 lock ("reqlayout");
1641 pdf = pdf_specifics (state.ctx, state.doc);
1642 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1643 state.gen += 1;
1645 state.rotate = rotate;
1646 state.fitmodel = fitmodel;
1647 state.h = h;
1648 layout ();
1649 process_outline ();
1651 nameddest = p + 9 + off;
1652 if (pdf && nameddest && *nameddest) {
1653 fz_point xy;
1654 struct pagedim *pdim;
1655 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1656 &xy.x, &xy.y);
1657 pdim = pdimofpageno (pageno);
1658 fz_transform_point (&xy, &pdim->ctm);
1659 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1662 state.gen++;
1663 unlock ("reqlayout");
1664 printd ("continue %d", state.pagecount);
1666 else if (!strncmp ("page", p, 4)) {
1667 double a, b;
1668 struct page *page;
1669 int pageno, pindex;
1671 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1672 if (ret != 2) {
1673 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1676 lock ("page");
1677 a = now ();
1678 page = loadpage (pageno, pindex);
1679 b = now ();
1680 unlock ("page");
1682 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1684 else if (!strncmp ("tile", p, 4)) {
1685 int x, y, w, h;
1686 struct page *page;
1687 struct tile *tile;
1688 double a, b;
1689 void *data;
1691 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1692 (uintptr_t *) &page, &x, &y, &w, &h,
1693 (uintptr_t *) &data);
1694 if (ret != 6) {
1695 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1698 lock ("tile");
1699 a = now ();
1700 tile = rendertile (page, x, y, w, h, data);
1701 b = now ();
1702 unlock ("tile");
1704 printd ("tile %d %d %" PRIxPTR " %u %f",
1705 x, y, (uintptr_t) (tile),
1706 tile->w * tile->h * tile->pixmap->n,
1707 b - a);
1709 else if (!strncmp ("trimset", p, 7)) {
1710 fz_irect fuzz;
1711 int trimmargins;
1713 ret = sscanf (p + 7, " %d %d %d %d %d",
1714 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1715 if (ret != 5) {
1716 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1718 lock ("trimset");
1719 state.trimmargins = trimmargins;
1720 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1721 state.trimanew = 1;
1722 state.trimfuzz = fuzz;
1724 unlock ("trimset");
1726 else if (!strncmp ("settrim", p, 7)) {
1727 fz_irect fuzz;
1728 int trimmargins;
1730 ret = sscanf (p + 7, " %d %d %d %d %d",
1731 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1732 if (ret != 5) {
1733 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1735 printd ("clear");
1736 lock ("settrim");
1737 state.trimmargins = trimmargins;
1738 state.needoutline = 1;
1739 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1740 state.trimanew = 1;
1741 state.trimfuzz = fuzz;
1743 state.pagedimcount = 0;
1744 free (state.pagedims);
1745 state.pagedims = NULL;
1746 initpdims ();
1747 layout ();
1748 process_outline ();
1749 unlock ("settrim");
1750 printd ("continue %d", state.pagecount);
1752 else if (!strncmp ("sliceh", p, 6)) {
1753 int h;
1755 ret = sscanf (p + 6, " %d", &h);
1756 if (ret != 1) {
1757 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1759 if (h != state.sliceheight) {
1760 state.sliceheight = h;
1761 for (int i = 0; i < state.texcount; ++i) {
1762 state.texowners[i].w = -1;
1763 state.texowners[i].h = -1;
1764 state.texowners[i].slice = NULL;
1768 else if (!strncmp ("interrupt", p, 9)) {
1769 printd ("vmsg interrupted");
1771 else {
1772 errx (1, "unknown command %.*s", len, p);
1775 return 0;
1778 CAMLprim value ml_isexternallink (value uri_v)
1780 CAMLparam1 (uri_v);
1781 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1782 CAMLreturn (Val_bool (ext));
1785 CAMLprim value ml_uritolocation (value uri_v)
1787 CAMLparam1 (uri_v);
1788 CAMLlocal1 (ret_v);
1789 int pageno;
1790 fz_point xy;
1791 struct pagedim *pdim;
1793 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1794 &xy.x, &xy.y);
1795 pdim = pdimofpageno (pageno);
1796 fz_transform_point (&xy, &pdim->ctm);
1797 ret_v = caml_alloc_tuple (3);
1798 Field (ret_v, 0) = Val_int (pageno);
1799 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1800 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1801 CAMLreturn (ret_v);
1804 CAMLprim value ml_realloctexts (value texcount_v)
1806 CAMLparam1 (texcount_v);
1807 int ok;
1809 if (trylock (__func__)) {
1810 ok = 0;
1811 goto done;
1813 realloctexts (Int_val (texcount_v));
1814 ok = 1;
1815 unlock (__func__);
1817 done:
1818 CAMLreturn (Val_bool (ok));
1821 static void recti (int x0, int y0, int x1, int y1)
1823 GLfloat *v = state.vertices;
1825 glVertexPointer (2, GL_FLOAT, 0, v);
1826 v[0] = x0; v[1] = y0;
1827 v[2] = x1; v[3] = y0;
1828 v[4] = x0; v[5] = y1;
1829 v[6] = x1; v[7] = y1;
1830 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1833 static void showsel (struct page *page, int ox, int oy)
1835 fz_irect bbox;
1836 fz_rect rect;
1837 fz_stext_block *block;
1838 int seen = 0;
1839 unsigned char selcolor[] = {15,15,15,140};
1841 if (!page->fmark || !page->lmark) return;
1843 glEnable (GL_BLEND);
1844 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1845 glColor4ubv (selcolor);
1847 ox += state.pagedims[page->pdimno].bounds.x0;
1848 oy += state.pagedims[page->pdimno].bounds.y0;
1850 for (block = page->text->first_block; block; block = block->next) {
1851 fz_stext_line *line;
1853 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1854 for (line = block->u.t.first_line; line; line = line->next) {
1855 fz_stext_char *ch;
1857 rect = fz_empty_rect;
1858 for (ch = line->first_char; ch; ch = ch->next) {
1859 if (ch == page->fmark) seen = 1;
1860 if (seen) fz_union_rect (&rect, &ch->bbox);
1861 if (ch == page->lmark) {
1862 fz_round_rect (&bbox, &rect);
1863 recti (bbox.x0 + ox, bbox.y0 + oy,
1864 bbox.x1 + ox, bbox.y1 + oy);
1865 goto done;
1868 fz_round_rect (&bbox, &rect);
1869 recti (bbox.x0 + ox, bbox.y0 + oy,
1870 bbox.x1 + ox, bbox.y1 + oy);
1873 done:
1874 glDisable (GL_BLEND);
1877 #pragma GCC diagnostic push
1878 #pragma GCC diagnostic ignored "-Wconversion"
1879 #include "glfont.c"
1880 #pragma GCC diagnostic pop
1882 static void stipplerect (fz_matrix *m,
1883 fz_point *p1,
1884 fz_point *p2,
1885 fz_point *p3,
1886 fz_point *p4,
1887 GLfloat *texcoords,
1888 GLfloat *vertices)
1890 fz_transform_point (p1, m);
1891 fz_transform_point (p2, m);
1892 fz_transform_point (p3, m);
1893 fz_transform_point (p4, m);
1895 float w, h, s, t;
1897 w = p2->x - p1->x;
1898 h = p2->y - p1->y;
1899 t = hypotf (w, h) * .25f;
1901 w = p3->x - p2->x;
1902 h = p3->y - p2->y;
1903 s = hypotf (w, h) * .25f;
1905 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
1906 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
1908 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
1909 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
1911 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
1912 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
1914 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
1915 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
1917 glDrawArrays (GL_LINES, 0, 8);
1920 static void solidrect (fz_matrix *m,
1921 fz_point *p1,
1922 fz_point *p2,
1923 fz_point *p3,
1924 fz_point *p4,
1925 GLfloat *vertices)
1927 fz_transform_point (p1, m);
1928 fz_transform_point (p2, m);
1929 fz_transform_point (p3, m);
1930 fz_transform_point (p4, m);
1931 vertices[0] = p1->x; vertices[1] = p1->y;
1932 vertices[2] = p2->x; vertices[3] = p2->y;
1934 vertices[4] = p3->x; vertices[5] = p3->y;
1935 vertices[6] = p4->x; vertices[7] = p4->y;
1936 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1939 static void ensurelinks (struct page *page)
1941 if (!page->links)
1942 page->links = fz_load_links (state.ctx, page->fzpage);
1945 static void highlightlinks (struct page *page, int xoff, int yoff)
1947 fz_matrix ctm, tm, pm;
1948 fz_link *link;
1949 GLfloat *texcoords = state.texcoords;
1950 GLfloat *vertices = state.vertices;
1952 ensurelinks (page);
1954 glEnable (GL_TEXTURE_1D);
1955 glEnable (GL_BLEND);
1956 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1957 glBindTexture (GL_TEXTURE_1D, state.stid);
1959 xoff -= state.pagedims[page->pdimno].bounds.x0;
1960 yoff -= state.pagedims[page->pdimno].bounds.y0;
1961 fz_translate (&tm, xoff, yoff);
1962 pm = pagectm (page);
1963 fz_concat (&ctm, &pm, &tm);
1965 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1966 glVertexPointer (2, GL_FLOAT, 0, vertices);
1968 for (link = page->links; link; link = link->next) {
1969 fz_point p1, p2, p3, p4;
1971 p1.x = link->rect.x0;
1972 p1.y = link->rect.y0;
1974 p2.x = link->rect.x1;
1975 p2.y = link->rect.y0;
1977 p3.x = link->rect.x1;
1978 p3.y = link->rect.y1;
1980 p4.x = link->rect.x0;
1981 p4.y = link->rect.y1;
1983 /* TODO: different colours for different schemes */
1984 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1985 else glColor3ub (255, 0, 0);
1987 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
1990 for (int i = 0; i < page->annotcount; ++i) {
1991 fz_point p1, p2, p3, p4;
1992 struct annot *annot = &page->annots[i];
1994 p1.x = annot->bbox.x0;
1995 p1.y = annot->bbox.y0;
1997 p2.x = annot->bbox.x1;
1998 p2.y = annot->bbox.y0;
2000 p3.x = annot->bbox.x1;
2001 p3.y = annot->bbox.y1;
2003 p4.x = annot->bbox.x0;
2004 p4.y = annot->bbox.y1;
2006 glColor3ub (0, 0, 128);
2007 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2010 glDisable (GL_BLEND);
2011 glDisable (GL_TEXTURE_1D);
2014 static int compareslinks (const void *l, const void *r)
2016 struct slink const *ls = l;
2017 struct slink const *rs = r;
2018 if (ls->bbox.y0 == rs->bbox.y0) {
2019 return rs->bbox.x0 - rs->bbox.x0;
2021 return ls->bbox.y0 - rs->bbox.y0;
2024 static void droptext (struct page *page)
2026 if (page->text) {
2027 fz_drop_stext_page (state.ctx, page->text);
2028 page->fmark = NULL;
2029 page->lmark = NULL;
2030 page->text = NULL;
2034 static void dropannots (struct page *page)
2036 if (page->annots) {
2037 free (page->annots);
2038 page->annots = NULL;
2039 page->annotcount = 0;
2043 static void ensureannots (struct page *page)
2045 int i, count = 0;
2046 size_t annotsize = sizeof (*page->annots);
2047 fz_annot *annot;
2049 if (state.gen != page->agen) {
2050 dropannots (page);
2051 page->agen = state.gen;
2053 if (page->annots) return;
2055 for (annot = fz_first_annot (state.ctx, page->fzpage);
2056 annot;
2057 annot = fz_next_annot (state.ctx, annot)) {
2058 count++;
2061 if (count > 0) {
2062 page->annotcount = count;
2063 page->annots = calloc (count, annotsize);
2064 if (!page->annots) {
2065 err (1, "calloc annots %d", count);
2068 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2069 annot;
2070 annot = fz_next_annot (state.ctx, annot), i++) {
2071 fz_rect rect;
2073 fz_bound_annot (state.ctx, annot, &rect);
2074 page->annots[i].annot = annot;
2075 fz_round_rect (&page->annots[i].bbox, &rect);
2080 static void dropslinks (struct page *page)
2082 if (page->slinks) {
2083 free (page->slinks);
2084 page->slinks = NULL;
2085 page->slinkcount = 0;
2087 if (page->links) {
2088 fz_drop_link (state.ctx, page->links);
2089 page->links = NULL;
2093 static void ensureslinks (struct page *page)
2095 fz_matrix ctm;
2096 int i, count;
2097 size_t slinksize = sizeof (*page->slinks);
2098 fz_link *link;
2100 ensureannots (page);
2101 if (state.gen != page->sgen) {
2102 dropslinks (page);
2103 page->sgen = state.gen;
2105 if (page->slinks) return;
2107 ensurelinks (page);
2108 ctm = pagectm (page);
2110 count = page->annotcount;
2111 for (link = page->links; link; link = link->next) {
2112 count++;
2114 if (count > 0) {
2115 int j;
2117 page->slinkcount = count;
2118 page->slinks = calloc (count, slinksize);
2119 if (!page->slinks) {
2120 err (1, "calloc slinks %d", count);
2123 for (i = 0, link = page->links; link; ++i, link = link->next) {
2124 fz_rect rect;
2126 rect = link->rect;
2127 fz_transform_rect (&rect, &ctm);
2128 page->slinks[i].tag = SLINK;
2129 page->slinks[i].u.link = link;
2130 fz_round_rect (&page->slinks[i].bbox, &rect);
2132 for (j = 0; j < page->annotcount; ++j, ++i) {
2133 fz_rect rect;
2134 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2135 fz_transform_rect (&rect, &ctm);
2136 fz_round_rect (&page->slinks[i].bbox, &rect);
2138 page->slinks[i].tag = SANNOT;
2139 page->slinks[i].u.annot = page->annots[j].annot;
2141 qsort (page->slinks, count, slinksize, compareslinks);
2145 static void highlightslinks (struct page *page, int xoff, int yoff,
2146 int noff, char *targ, mlsize_t tlen, int hfsize)
2148 char buf[40];
2149 struct slink *slink;
2150 float x0, y0, x1, y1, w;
2152 ensureslinks (page);
2153 glColor3ub (0xc3, 0xb0, 0x91);
2154 for (int i = 0; i < page->slinkcount; ++i) {
2155 fmt_linkn (buf, i + noff);
2156 if (!tlen || !strncmp (targ, buf, tlen)) {
2157 slink = &page->slinks[i];
2159 x0 = slink->bbox.x0 + xoff - 5;
2160 y1 = slink->bbox.y0 + yoff - 5;
2161 y0 = y1 + 10 + hfsize;
2162 w = measure_string (state.face, hfsize, buf);
2163 x1 = x0 + w + 10;
2164 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2168 glEnable (GL_BLEND);
2169 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2170 glEnable (GL_TEXTURE_2D);
2171 glColor3ub (0, 0, 0);
2172 for (int i = 0; i < page->slinkcount; ++i) {
2173 fmt_linkn (buf, i + noff);
2174 if (!tlen || !strncmp (targ, buf, tlen)) {
2175 slink = &page->slinks[i];
2177 x0 = slink->bbox.x0 + xoff;
2178 y0 = slink->bbox.y0 + yoff + hfsize;
2179 draw_string (state.face, hfsize, x0, y0, buf);
2182 glDisable (GL_TEXTURE_2D);
2183 glDisable (GL_BLEND);
2186 static void uploadslice (struct tile *tile, struct slice *slice)
2188 int offset;
2189 struct slice *slice1;
2190 unsigned char *texdata;
2192 offset = 0;
2193 for (slice1 = tile->slices; slice != slice1; slice1++) {
2194 offset += slice1->h * tile->w * tile->pixmap->n;
2196 if (slice->texindex != -1 && slice->texindex < state.texcount
2197 && state.texowners[slice->texindex].slice == slice) {
2198 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2200 else {
2201 int subimage = 0;
2202 int texindex = state.texindex++ % state.texcount;
2204 if (state.texowners[texindex].w == tile->w) {
2205 if (state.texowners[texindex].h >= slice->h) {
2206 subimage = 1;
2208 else {
2209 state.texowners[texindex].h = slice->h;
2212 else {
2213 state.texowners[texindex].h = slice->h;
2216 state.texowners[texindex].w = tile->w;
2217 state.texowners[texindex].slice = slice;
2218 slice->texindex = texindex;
2220 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2221 #if TEXT_TYPE == GL_TEXTURE_2D
2222 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2223 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2224 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2225 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2226 #endif
2227 if (tile->pbo) {
2228 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2229 texdata = 0;
2231 else {
2232 texdata = tile->pixmap->samples;
2234 if (subimage) {
2235 glTexSubImage2D (TEXT_TYPE,
2239 tile->w,
2240 slice->h,
2241 state.texform,
2242 state.texty,
2243 texdata+offset
2246 else {
2247 glTexImage2D (TEXT_TYPE,
2249 state.texiform,
2250 tile->w,
2251 slice->h,
2253 state.texform,
2254 state.texty,
2255 texdata+offset
2258 if (tile->pbo) {
2259 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2264 CAMLprim void ml_begintiles (value unit_v)
2266 CAMLparam1 (unit_v);
2267 glEnable (TEXT_TYPE);
2268 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2269 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2270 CAMLreturn0;
2273 CAMLprim void ml_endtiles (value unit_v)
2275 CAMLparam1 (unit_v);
2276 glDisable (TEXT_TYPE);
2277 CAMLreturn0;
2280 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2282 CAMLparam2 (args_v, ptr_v);
2283 int dispx = Int_val (Field (args_v, 0));
2284 int dispy = Int_val (Field (args_v, 1));
2285 int dispw = Int_val (Field (args_v, 2));
2286 int disph = Int_val (Field (args_v, 3));
2287 int tilex = Int_val (Field (args_v, 4));
2288 int tiley = Int_val (Field (args_v, 5));
2289 char *s = String_val (ptr_v);
2290 struct tile *tile = parse_pointer (__func__, s);
2291 int slicey, firstslice;
2292 struct slice *slice;
2293 GLfloat *texcoords = state.texcoords;
2294 GLfloat *vertices = state.vertices;
2296 firstslice = tiley / tile->sliceheight;
2297 slice = &tile->slices[firstslice];
2298 slicey = tiley % tile->sliceheight;
2300 while (disph > 0) {
2301 int dh;
2303 dh = slice->h - slicey;
2304 dh = fz_mini (disph, dh);
2305 uploadslice (tile, slice);
2307 texcoords[0] = tilex; texcoords[1] = slicey;
2308 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2309 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2310 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2312 vertices[0] = dispx; vertices[1] = dispy;
2313 vertices[2] = dispx+dispw; vertices[3] = dispy;
2314 vertices[4] = dispx; vertices[5] = dispy+dh;
2315 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2317 #if TEXT_TYPE == GL_TEXTURE_2D
2318 for (int i = 0; i < 8; ++i) {
2319 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2321 #endif
2323 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2324 dispy += dh;
2325 disph -= dh;
2326 slice++;
2327 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2328 slicey = 0;
2330 CAMLreturn0;
2333 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2335 fz_matrix ctm, tm, pm;
2336 fz_point p1, p2, p3, p4;
2337 GLfloat *vertices = state.vertices;
2338 double *v = (double *) rects_v;
2340 xoff -= state.pagedims[page->pdimno].bounds.x0;
2341 yoff -= state.pagedims[page->pdimno].bounds.y0;
2342 fz_translate (&tm, xoff, yoff);
2343 pm = pagectm (page);
2344 fz_concat (&ctm, &pm, &tm);
2346 glEnable (GL_BLEND);
2347 glVertexPointer (2, GL_FLOAT, 0, vertices);
2349 glColor4dv (v);
2350 p1.x = (float) v[4];
2351 p1.y = (float) v[5];
2353 p2.x = (float) v[6];
2354 p2.y = (float) v[5];
2356 p3.x = (float) v[6];
2357 p3.y = (float) v[7];
2359 p4.x = (float) v[4];
2360 p4.y = (float) v[7];
2361 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2362 glDisable (GL_BLEND);
2365 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2366 value xoff_v, value yoff_v,
2367 value li_v)
2369 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2370 int xoff = Int_val (xoff_v);
2371 int yoff = Int_val (yoff_v);
2372 int noff = Int_val (Field (li_v, 0));
2373 char *targ = String_val (Field (li_v, 1));
2374 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2375 int hfsize = Int_val (Field (li_v, 2));
2376 char *s = String_val (ptr_v);
2377 int hlmask = Int_val (hlinks_v);
2378 struct page *page = parse_pointer (__func__, s);
2380 if (!page->fzpage) {
2381 /* deal with loadpage failed pages */
2382 goto done;
2385 if (trylock (__func__)) {
2386 noff = -1;
2387 goto done;
2390 ensureannots (page);
2391 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2392 if (hlmask & 2) {
2393 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2394 noff = page->slinkcount;
2396 if (page->tgen == state.gen) {
2397 showsel (page, xoff, yoff);
2399 unlock (__func__);
2401 done:
2402 CAMLreturn (Val_int (noff));
2405 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2406 value rects_v)
2408 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2409 int xoff = Int_val (xoff_v);
2410 int yoff = Int_val (yoff_v);
2411 char *s = String_val (ptr_v);
2412 struct page *page = parse_pointer (__func__, s);
2414 drawprect (page, xoff, yoff, rects_v);
2415 CAMLreturn0;
2418 static struct annot *getannot (struct page *page, int x, int y)
2420 fz_point p;
2421 fz_matrix ctm;
2422 const fz_matrix *tctm;
2423 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2425 if (!page->annots) return NULL;
2427 if (pdf) {
2428 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2429 tctm = &state.pagedims[page->pdimno].tctm;
2431 else {
2432 tctm = &fz_identity;
2435 p.x = x;
2436 p.y = y;
2438 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2439 fz_invert_matrix (&ctm, &ctm);
2440 fz_transform_point (&p, &ctm);
2442 if (pdf) {
2443 for (int i = 0; i < page->annotcount; ++i) {
2444 struct annot *a = &page->annots[i];
2445 fz_rect rect;
2447 fz_bound_annot (state.ctx, a->annot, &rect);
2448 if (p.x >= rect.x0 && p.x <= rect.x1) {
2449 if (p.y >= rect.y0 && p.y <= rect.y1)
2450 return a;
2454 return NULL;
2457 static fz_link *getlink (struct page *page, int x, int y)
2459 fz_point p;
2460 fz_matrix ctm;
2461 fz_link *link;
2463 ensureslinks (page);
2465 p.x = x;
2466 p.y = y;
2468 ctm = pagectm (page);
2469 fz_invert_matrix (&ctm, &ctm);
2470 fz_transform_point (&p, &ctm);
2472 for (link = page->links; link; link = link->next) {
2473 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2474 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2475 return link;
2479 return NULL;
2482 static void ensuretext (struct page *page)
2484 if (state.gen != page->tgen) {
2485 droptext (page);
2486 page->tgen = state.gen;
2488 if (!page->text) {
2489 fz_matrix ctm;
2490 fz_device *tdev;
2492 page->text = fz_new_stext_page (state.ctx,
2493 &state.pagedims[page->pdimno].mediabox);
2494 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2495 ctm = pagectm (page);
2496 fz_run_display_list (state.ctx, page->dlist,
2497 tdev, &ctm, &fz_infinite_rect, NULL);
2498 fz_close_device (state.ctx, tdev);
2499 fz_drop_device (state.ctx, tdev);
2503 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2505 CAMLparam2 (start_page_v, dir_v);
2506 CAMLlocal1 (ret_v);
2507 int i, dir = Int_val (dir_v);
2508 int start_page = Int_val (start_page_v);
2509 int end_page = dir > 0 ? state.pagecount : -1;
2510 pdf_document *pdf;
2512 fz_var (end_page);
2513 ret_v = Val_int (0);
2514 lock (__func__);
2515 pdf = pdf_specifics (state.ctx, state.doc);
2516 for (i = start_page + dir; i != end_page; i += dir) {
2517 int found;
2519 fz_var (found);
2520 if (pdf) {
2521 pdf_page *page = NULL;
2523 fz_var (page);
2524 fz_try (state.ctx) {
2525 page = pdf_load_page (state.ctx, pdf, i);
2526 found = !!page->links || !!page->annots;
2528 fz_catch (state.ctx) {
2529 found = 0;
2531 if (page) {
2532 fz_drop_page (state.ctx, &page->super);
2535 else {
2536 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2537 fz_link *link = fz_load_links (state.ctx, page);
2538 found = !!link;
2539 fz_drop_link (state.ctx, link);
2540 fz_drop_page (state.ctx, page);
2543 if (found) {
2544 ret_v = caml_alloc_small (1, 1);
2545 Field (ret_v, 0) = Val_int (i);
2546 goto unlock;
2549 unlock:
2550 unlock (__func__);
2551 CAMLreturn (ret_v);
2554 enum { dir_first, dir_last };
2555 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2557 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2559 CAMLparam2 (ptr_v, dir_v);
2560 CAMLlocal2 (ret_v, pos_v);
2561 struct page *page;
2562 int dirtag, i, slinkindex;
2563 struct slink *found = NULL ,*slink;
2564 char *s = String_val (ptr_v);
2566 page = parse_pointer (__func__, s);
2567 ret_v = Val_int (0);
2568 lock (__func__);
2569 ensureslinks (page);
2571 if (Is_block (dir_v)) {
2572 dirtag = Tag_val (dir_v);
2573 switch (dirtag) {
2574 case dir_first_visible:
2576 int x0, y0, dir, first_index, last_index;
2578 pos_v = Field (dir_v, 0);
2579 x0 = Int_val (Field (pos_v, 0));
2580 y0 = Int_val (Field (pos_v, 1));
2581 dir = Int_val (Field (pos_v, 2));
2583 if (dir >= 0) {
2584 dir = 1;
2585 first_index = 0;
2586 last_index = page->slinkcount;
2588 else {
2589 first_index = page->slinkcount - 1;
2590 last_index = -1;
2593 for (i = first_index; i != last_index; i += dir) {
2594 slink = &page->slinks[i];
2595 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2596 found = slink;
2597 break;
2601 break;
2603 case dir_left:
2604 slinkindex = Int_val (Field (dir_v, 0));
2605 found = &page->slinks[slinkindex];
2606 for (i = slinkindex - 1; i >= 0; --i) {
2607 slink = &page->slinks[i];
2608 if (slink->bbox.x0 < found->bbox.x0) {
2609 found = slink;
2610 break;
2613 break;
2615 case dir_right:
2616 slinkindex = Int_val (Field (dir_v, 0));
2617 found = &page->slinks[slinkindex];
2618 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2619 slink = &page->slinks[i];
2620 if (slink->bbox.x0 > found->bbox.x0) {
2621 found = slink;
2622 break;
2625 break;
2627 case dir_down:
2628 slinkindex = Int_val (Field (dir_v, 0));
2629 found = &page->slinks[slinkindex];
2630 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2631 slink = &page->slinks[i];
2632 if (slink->bbox.y0 >= found->bbox.y0) {
2633 found = slink;
2634 break;
2637 break;
2639 case dir_up:
2640 slinkindex = Int_val (Field (dir_v, 0));
2641 found = &page->slinks[slinkindex];
2642 for (i = slinkindex - 1; i >= 0; --i) {
2643 slink = &page->slinks[i];
2644 if (slink->bbox.y0 <= found->bbox.y0) {
2645 found = slink;
2646 break;
2649 break;
2652 else {
2653 dirtag = Int_val (dir_v);
2654 switch (dirtag) {
2655 case dir_first:
2656 found = page->slinks;
2657 break;
2659 case dir_last:
2660 if (page->slinks) {
2661 found = page->slinks + (page->slinkcount - 1);
2663 break;
2666 if (found) {
2667 ret_v = caml_alloc_small (2, 1);
2668 Field (ret_v, 0) = Val_int (found - page->slinks);
2671 unlock (__func__);
2672 CAMLreturn (ret_v);
2675 enum { uuri, utext, uannot };
2677 CAMLprim value ml_getlink (value ptr_v, value n_v)
2679 CAMLparam2 (ptr_v, n_v);
2680 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2681 fz_link *link;
2682 struct page *page;
2683 char *s = String_val (ptr_v);
2684 struct slink *slink;
2686 ret_v = Val_int (0);
2687 page = parse_pointer (__func__, s);
2689 lock (__func__);
2690 ensureslinks (page);
2691 slink = &page->slinks[Int_val (n_v)];
2692 if (slink->tag == SLINK) {
2693 link = slink->u.link;
2694 str_v = caml_copy_string (link->uri);
2695 ret_v = caml_alloc_small (1, uuri);
2696 Field (ret_v, 0) = str_v;
2698 else {
2699 ret_v = caml_alloc_small (1, uannot);
2700 tup_v = caml_alloc_tuple (2);
2701 Field (ret_v, 0) = tup_v;
2702 Field (tup_v, 0) = ptr_v;
2703 Field (tup_v, 1) = n_v;
2705 unlock (__func__);
2707 CAMLreturn (ret_v);
2710 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2712 CAMLparam2 (ptr_v, n_v);
2713 CAMLlocal1 (ret_v);
2714 pdf_document *pdf;
2715 char *contents = NULL;
2717 lock (__func__);
2718 pdf = pdf_specifics (state.ctx, state.doc);
2719 if (pdf) {
2720 char *s = String_val (ptr_v);
2721 struct page *page;
2722 struct slink *slink;
2724 page = parse_pointer (__func__, s);
2725 slink = &page->slinks[Int_val (n_v)];
2726 contents = pdf_copy_annot_contents (state.ctx,
2727 (pdf_annot *) slink->u.annot);
2729 unlock (__func__);
2730 if (contents) {
2731 ret_v = caml_copy_string (contents);
2732 fz_free (state.ctx, contents);
2734 else {
2735 ret_v = caml_copy_string ("");
2737 CAMLreturn (ret_v);
2740 CAMLprim value ml_getlinkcount (value ptr_v)
2742 CAMLparam1 (ptr_v);
2743 struct page *page;
2744 char *s = String_val (ptr_v);
2746 page = parse_pointer (__func__, s);
2747 CAMLreturn (Val_int (page->slinkcount));
2750 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2752 CAMLparam2 (ptr_v, n_v);
2753 CAMLlocal1 (ret_v);
2754 struct page *page;
2755 struct slink *slink;
2756 char *s = String_val (ptr_v);
2758 page = parse_pointer (__func__, s);
2759 ret_v = caml_alloc_tuple (4);
2760 lock (__func__);
2761 ensureslinks (page);
2763 slink = &page->slinks[Int_val (n_v)];
2764 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2765 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2766 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2767 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2768 unlock (__func__);
2769 CAMLreturn (ret_v);
2772 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2774 CAMLparam3 (ptr_v, x_v, y_v);
2775 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2776 fz_link *link;
2777 struct annot *annot;
2778 struct page *page;
2779 char *ptr = String_val (ptr_v);
2780 int x = Int_val (x_v), y = Int_val (y_v);
2781 struct pagedim *pdim;
2783 ret_v = Val_int (0);
2784 if (trylock (__func__)) {
2785 goto done;
2788 page = parse_pointer (__func__, ptr);
2789 pdim = &state.pagedims[page->pdimno];
2790 x += pdim->bounds.x0;
2791 y += pdim->bounds.y0;
2794 annot = getannot (page, x, y);
2795 if (annot) {
2796 int i, n = -1;
2798 ensureslinks (page);
2799 for (i = 0; i < page->slinkcount; ++i) {
2800 if (page->slinks[i].tag == SANNOT
2801 && page->slinks[i].u.annot == annot->annot) {
2802 n = i;
2803 break;
2806 ret_v = caml_alloc_small (1, uannot);
2807 tup_v = caml_alloc_tuple (2);
2808 Field (ret_v, 0) = tup_v;
2809 Field (tup_v, 0) = ptr_v;
2810 Field (tup_v, 1) = Val_int (n);
2811 goto unlock;
2815 link = getlink (page, x, y);
2816 if (link) {
2817 str_v = caml_copy_string (link->uri);
2818 ret_v = caml_alloc_small (1, uuri);
2819 Field (ret_v, 0) = str_v;
2821 else {
2822 fz_rect *b;
2823 fz_stext_block *block;
2825 ensuretext (page);
2827 for (block = page->text->first_block; block; block = block->next) {
2828 fz_stext_line *line;
2830 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2831 b = &block->bbox;
2832 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2833 continue;
2835 for (line = block->u.t.first_line; line; line = line->next) {
2836 fz_stext_char *ch;
2838 b = &line->bbox;
2839 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2840 continue;
2842 for (ch = line->first_char; ch; ch = ch->next) {
2843 b = &ch->bbox;
2845 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
2846 const char *n2 = fz_font_name (state.ctx, ch->font);
2847 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2848 ch->font);
2850 if (!n2) n2 = "<unknown font>";
2852 if (face && face->family_name) {
2853 char *s;
2854 char *n1 = face->family_name;
2855 size_t l1 = strlen (n1);
2856 size_t l2 = strlen (n2);
2858 if (l1 != l2 || memcmp (n1, n2, l1)) {
2859 s = malloc (l1 + l2 + 2);
2860 if (s) {
2861 memcpy (s, n2, l2);
2862 s[l2] = '=';
2863 memcpy (s + l2 + 1, n1, l1 + 1);
2864 str_v = caml_copy_string (s);
2865 free (s);
2869 if (str_v == Val_unit) {
2870 str_v = caml_copy_string (n2);
2872 ret_v = caml_alloc_small (1, utext);
2873 Field (ret_v, 0) = str_v;
2874 goto unlock;
2880 unlock:
2881 unlock (__func__);
2883 done:
2884 CAMLreturn (ret_v);
2887 enum { mark_page, mark_block, mark_line, mark_word };
2889 CAMLprim void ml_clearmark (value ptr_v)
2891 CAMLparam1 (ptr_v);
2892 char *s = String_val (ptr_v);
2893 struct page *page;
2895 if (trylock (__func__)) {
2896 goto done;
2899 page = parse_pointer (__func__, s);
2900 page->fmark = NULL;
2901 page->lmark = NULL;
2903 unlock (__func__);
2904 done:
2905 CAMLreturn0;
2908 static int uninteresting (int c)
2910 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
2911 || ispunct (c);
2914 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2916 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2917 CAMLlocal1 (ret_v);
2918 fz_rect *b;
2919 struct page *page;
2920 fz_stext_line *line;
2921 fz_stext_block *block;
2922 struct pagedim *pdim;
2923 int mark = Int_val (mark_v);
2924 char *s = String_val (ptr_v);
2925 int x = Int_val (x_v), y = Int_val (y_v);
2927 ret_v = Val_bool (0);
2928 if (trylock (__func__)) {
2929 goto done;
2932 page = parse_pointer (__func__, s);
2933 pdim = &state.pagedims[page->pdimno];
2935 ensuretext (page);
2937 if (mark == mark_page) {
2938 page->fmark = page->text->first_block->u.t.first_line->first_char;
2939 page->lmark = page->text->last_block->u.t.last_line->last_char;
2940 ret_v = Val_bool (1);
2941 goto unlock;
2944 x += pdim->bounds.x0;
2945 y += pdim->bounds.y0;
2947 for (block = page->text->first_block; block; block = block->next) {
2948 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2949 b = &block->bbox;
2950 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2951 continue;
2953 if (mark == mark_block) {
2954 page->fmark = block->u.t.first_line->first_char;
2955 page->lmark = block->u.t.last_line->last_char;
2956 ret_v = Val_bool (1);
2957 goto unlock;
2960 for (line = block->u.t.first_line; line; line = line->next) {
2961 fz_stext_char *ch;
2963 b = &line->bbox;
2964 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2965 continue;
2967 if (mark == mark_line) {
2968 page->fmark = line->first_char;
2969 page->lmark = line->last_char;
2970 ret_v = Val_bool (1);
2971 goto unlock;
2974 for (ch = line->first_char; ch; ch = ch->next) {
2975 fz_stext_char *ch2, *first = NULL, *last = NULL;
2976 b = &ch->bbox;
2977 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
2978 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2979 if (uninteresting (ch2->c)) first = NULL;
2980 else if (!first) first = ch2;
2982 for (ch2 = ch; ch2; ch2 = ch2->next) {
2983 if (uninteresting (ch2->c)) break;
2984 last = ch2;
2987 page->fmark = first;
2988 page->lmark = last;
2989 ret_v = Val_bool (1);
2990 goto unlock;
2995 unlock:
2996 if (!Bool_val (ret_v)) {
2997 page->fmark = NULL;
2998 page->lmark = NULL;
3000 unlock (__func__);
3002 done:
3003 CAMLreturn (ret_v);
3006 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3008 CAMLparam3 (ptr_v, x_v, y_v);
3009 CAMLlocal2 (ret_v, res_v);
3010 fz_rect *b = NULL;
3011 struct page *page;
3012 struct pagedim *pdim;
3013 fz_stext_block *block;
3014 char *s = String_val (ptr_v);
3015 int x = Int_val (x_v), y = Int_val (y_v);
3017 ret_v = Val_int (0);
3018 if (trylock (__func__)) {
3019 goto done;
3022 page = parse_pointer (__func__, s);
3023 pdim = &state.pagedims[page->pdimno];
3024 x += pdim->bounds.x0;
3025 y += pdim->bounds.y0;
3027 ensuretext (page);
3029 for (block = page->text->first_block; block; block = block->next) {
3030 switch (block->type) {
3031 case FZ_STEXT_BLOCK_TEXT:
3032 b = &block->bbox;
3033 break;
3035 case FZ_STEXT_BLOCK_IMAGE:
3036 b = &block->bbox;
3037 break;
3039 default:
3040 continue;
3043 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3044 break;
3045 b = NULL;
3047 if (b) {
3048 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3049 ret_v = caml_alloc_small (1, 1);
3050 Store_double_field (res_v, 0, (double) b->x0);
3051 Store_double_field (res_v, 1, (double) b->x1);
3052 Store_double_field (res_v, 2, (double) b->y0);
3053 Store_double_field (res_v, 3, (double) b->y1);
3054 Field (ret_v, 0) = res_v;
3056 unlock (__func__);
3058 done:
3059 CAMLreturn (ret_v);
3062 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3064 CAMLparam2 (ptr_v, rect_v);
3065 fz_rect b;
3066 struct page *page;
3067 struct pagedim *pdim;
3068 char *s = String_val (ptr_v);
3069 int x0, x1, y0, y1;
3070 fz_stext_char *ch;
3071 fz_stext_line *line;
3072 fz_stext_block *block;
3073 fz_stext_char *fc, *lc;
3075 if (trylock (__func__)) {
3076 goto done;
3079 page = parse_pointer (__func__, s);
3080 ensuretext (page);
3082 pdim = &state.pagedims[page->pdimno];
3083 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3084 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3085 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3086 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3088 if (y0 > y1) {
3089 int t = y0;
3090 y0 = y1;
3091 y1 = t;
3092 x0 = x1;
3093 x1 = t;
3096 fc = page->fmark;
3097 lc = page->lmark;
3099 for (block = page->text->first_block; block; block = block->next) {
3100 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3101 for (line = block->u.t.first_line; line; line = line->next) {
3102 for (ch = line->first_char; ch; ch = ch->next) {
3103 b = ch->bbox;
3104 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3105 fc = ch;
3107 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3108 lc = ch;
3113 if (x1 < x0 && fc == lc) {
3114 fz_stext_char *t;
3116 t = fc;
3117 fc = lc;
3118 lc = t;
3121 page->fmark = fc;
3122 page->lmark = lc;
3124 unlock (__func__);
3126 done:
3127 CAMLreturn0;
3130 static int pipechar (FILE *f, fz_stext_char *ch)
3132 char buf[4];
3133 int len;
3134 size_t ret;
3136 len = fz_runetochar (buf, ch->c);
3137 ret = fwrite (buf, len, 1, f);
3138 if (ret != 1) {
3139 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3140 len, ret, errno, strerror (errno));
3141 return -1;
3143 return 0;
3146 CAMLprim value ml_spawn (value command_v, value fds_v)
3148 CAMLparam2 (command_v, fds_v);
3149 CAMLlocal2 (l_v, tup_v);
3150 int ret, ret1;
3151 pid_t pid = (pid_t) -1;
3152 char *msg = NULL;
3153 value earg_v = Nothing;
3154 posix_spawnattr_t attr;
3155 posix_spawn_file_actions_t fa;
3156 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3158 argv[2] = String_val (command_v);
3160 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3161 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3164 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3165 msg = "posix_spawnattr_init";
3166 goto fail1;
3169 #ifdef POSIX_SPAWN_USEVFORK
3170 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3171 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3172 goto fail;
3174 #endif
3176 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3177 int fd1, fd2;
3179 tup_v = Field (l_v, 0);
3180 fd1 = Int_val (Field (tup_v, 0));
3181 fd2 = Int_val (Field (tup_v, 1));
3182 if (fd2 < 0) {
3183 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3184 msg = "posix_spawn_file_actions_addclose";
3185 earg_v = tup_v;
3186 goto fail;
3189 else {
3190 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3191 msg = "posix_spawn_file_actions_adddup2";
3192 earg_v = tup_v;
3193 goto fail;
3198 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3199 msg = "posix_spawn";
3200 goto fail;
3203 fail:
3204 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3205 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3208 fail1:
3209 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3210 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3211 ret1, strerror (ret1));
3214 if (msg)
3215 unix_error (ret, msg, earg_v);
3217 CAMLreturn (Val_int (pid));
3220 CAMLprim value ml_hassel (value ptr_v)
3222 CAMLparam1 (ptr_v);
3223 CAMLlocal1 (ret_v);
3224 struct page *page;
3225 char *s = String_val (ptr_v);
3227 ret_v = Val_bool (0);
3228 if (trylock (__func__)) {
3229 goto done;
3232 page = parse_pointer (__func__, s);
3233 ret_v = Val_bool (page->fmark && page->lmark);
3234 unlock (__func__);
3235 done:
3236 CAMLreturn (ret_v);
3239 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3241 CAMLparam2 (fd_v, ptr_v);
3242 FILE *f;
3243 int seen = 0;
3244 struct page *page;
3245 fz_stext_line *line;
3246 fz_stext_block *block;
3247 int fd = Int_val (fd_v);
3248 char *s = String_val (ptr_v);
3250 if (trylock (__func__)) {
3251 goto done;
3254 page = parse_pointer (__func__, s);
3256 if (!page->fmark || !page->lmark) {
3257 printd ("emsg nothing to copy on page %d", page->pageno);
3258 goto unlock;
3261 f = fdopen (fd, "w");
3262 if (!f) {
3263 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3264 fd, errno, strerror (errno));
3265 f = stdout;
3268 for (block = page->text->first_block; block; block = block->next) {
3269 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3270 for (line = block->u.t.first_line; line; line = line->next) {
3271 fz_stext_char *ch;
3272 for (ch = line->first_char; ch; ch = ch->next) {
3273 if (seen || ch == page->fmark) {
3274 do {
3275 pipechar (f, ch);
3276 if (ch == page->lmark) goto close;
3277 } while ((ch = ch->next));
3278 seen = 1;
3279 break;
3282 if (seen) fputc ('\n', f);
3285 close:
3286 if (f != stdout) {
3287 int ret = fclose (f);
3288 fd = -1;
3289 if (ret == -1) {
3290 if (errno != ECHILD) {
3291 printd ("emsg failed to close sel pipe: %d:%s",
3292 errno, strerror (errno));
3296 unlock:
3297 unlock (__func__);
3299 done:
3300 if (fd >= 0) {
3301 if (close (fd)) {
3302 printd ("emsg failed to close sel pipe: %d:%s",
3303 errno, strerror (errno));
3306 CAMLreturn0;
3309 CAMLprim value ml_getpdimrect (value pagedimno_v)
3311 CAMLparam1 (pagedimno_v);
3312 CAMLlocal1 (ret_v);
3313 int pagedimno = Int_val (pagedimno_v);
3314 fz_rect box;
3316 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3317 if (trylock (__func__)) {
3318 box = fz_empty_rect;
3320 else {
3321 box = state.pagedims[pagedimno].mediabox;
3322 unlock (__func__);
3325 Store_double_field (ret_v, 0, (double) box.x0);
3326 Store_double_field (ret_v, 1, (double) box.x1);
3327 Store_double_field (ret_v, 2, (double) box.y0);
3328 Store_double_field (ret_v, 3, (double) box.y1);
3330 CAMLreturn (ret_v);
3333 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3334 value dw_v, value cols_v)
3336 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3337 CAMLlocal1 (ret_v);
3338 int i;
3339 float zoom = -1.;
3340 float maxh = 0.0;
3341 struct pagedim *p;
3342 float winw = Int_val (winw_v);
3343 float winh = Int_val (winh_v);
3344 float dw = Int_val (dw_v);
3345 float cols = Int_val (cols_v);
3346 float pw = 1.0, ph = 1.0;
3348 if (trylock (__func__)) {
3349 goto done;
3352 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3353 float w = p->pagebox.x1 / cols;
3354 float h = p->pagebox.y1;
3355 if (h > maxh) {
3356 maxh = h;
3357 ph = h;
3358 if (state.fitmodel != FitProportional) pw = w;
3360 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3363 zoom = (((winh / ph) * pw) + dw) / winw;
3364 unlock (__func__);
3365 done:
3366 ret_v = caml_copy_double ((double) zoom);
3367 CAMLreturn (ret_v);
3370 CAMLprim value ml_getmaxw (value unit_v)
3372 CAMLparam1 (unit_v);
3373 CAMLlocal1 (ret_v);
3374 int i;
3375 float maxw = -1.;
3376 struct pagedim *p;
3378 if (trylock (__func__)) {
3379 goto done;
3382 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3383 float w = p->pagebox.x1;
3384 maxw = fz_max (maxw, w);
3387 unlock (__func__);
3388 done:
3389 ret_v = caml_copy_double ((double) maxw);
3390 CAMLreturn (ret_v);
3393 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3395 CAMLparam4 (pt_v, x_v, y_v, string_v);
3396 CAMLlocal1 (ret_v);
3397 int pt = Int_val(pt_v);
3398 int x = Int_val (x_v);
3399 int y = Int_val (y_v);
3400 double w;
3402 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3403 ret_v = caml_copy_double (w);
3404 CAMLreturn (ret_v);
3407 CAMLprim value ml_measure_string (value pt_v, value string_v)
3409 CAMLparam2 (pt_v, string_v);
3410 CAMLlocal1 (ret_v);
3411 int pt = Int_val (pt_v);
3412 double w;
3414 w = (double) measure_string (state.face, pt, String_val (string_v));
3415 ret_v = caml_copy_double (w);
3416 CAMLreturn (ret_v);
3419 CAMLprim value ml_getpagebox (value opaque_v)
3421 CAMLparam1 (opaque_v);
3422 CAMLlocal1 (ret_v);
3423 fz_rect rect;
3424 fz_irect bbox;
3425 fz_matrix ctm;
3426 fz_device *dev;
3427 char *s = String_val (opaque_v);
3428 struct page *page = parse_pointer (__func__, s);
3430 ret_v = caml_alloc_tuple (4);
3431 dev = fz_new_bbox_device (state.ctx, &rect);
3433 ctm = pagectm (page);
3434 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3436 fz_close_device (state.ctx, dev);
3437 fz_drop_device (state.ctx, dev);
3438 fz_round_rect (&bbox, &rect);
3439 Field (ret_v, 0) = Val_int (bbox.x0);
3440 Field (ret_v, 1) = Val_int (bbox.y0);
3441 Field (ret_v, 2) = Val_int (bbox.x1);
3442 Field (ret_v, 3) = Val_int (bbox.y1);
3444 CAMLreturn (ret_v);
3447 CAMLprim void ml_setaalevel (value level_v)
3449 CAMLparam1 (level_v);
3451 state.aalevel = Int_val (level_v);
3452 CAMLreturn0;
3455 #ifndef __COCOA__
3456 #pragma GCC diagnostic push
3457 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3458 #include <X11/Xlib.h>
3459 #include <X11/cursorfont.h>
3460 #pragma GCC diagnostic pop
3462 #include <GL/glx.h>
3464 static const int shapes[] = {
3465 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3468 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3470 static struct {
3471 Window wid;
3472 Display *dpy;
3473 GLXContext ctx;
3474 XVisualInfo *visual;
3475 Cursor curs[CURS_COUNT];
3476 } glx;
3479 static void initcurs (void)
3481 for (size_t n = 0; n < CURS_COUNT; ++n) {
3482 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3486 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3488 CAMLparam3 (display_v, wid_v, screen_v);
3490 glx.dpy = XOpenDisplay (String_val (display_v));
3491 if (!glx.dpy) {
3492 caml_failwith ("XOpenDisplay");
3495 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3496 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3497 if (!glx.visual) {
3498 XCloseDisplay (glx.dpy);
3499 caml_failwith ("glXChooseVisual");
3502 initcurs ();
3504 glx.wid = Int_val (wid_v);
3505 CAMLreturn (Val_int (glx.visual->visualid));
3508 CAMLprim void ml_glxcompleteinit (value unit_v)
3510 CAMLparam1 (unit_v);
3512 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3513 if (!glx.ctx) {
3514 caml_failwith ("glXCreateContext");
3517 XFree (glx.visual);
3518 glx.visual = NULL;
3520 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3521 glXDestroyContext (glx.dpy, glx.ctx);
3522 glx.ctx = NULL;
3523 caml_failwith ("glXMakeCurrent");
3525 CAMLreturn0;
3528 CAMLprim void ml_setcursor (value cursor_v)
3530 CAMLparam1 (cursor_v);
3531 size_t cursn = Int_val (cursor_v);
3533 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3534 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3535 XFlush (glx.dpy);
3536 CAMLreturn0;
3539 CAMLprim void ml_swapb (value unit_v)
3541 CAMLparam1 (unit_v);
3542 glXSwapBuffers (glx.dpy, glx.wid);
3543 CAMLreturn0;
3546 long keysym2ucs (KeySym);
3547 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3549 CAMLparam1 (keysym_v);
3550 CAMLlocal1 (str_v);
3551 KeySym keysym = Int_val (keysym_v);
3552 Rune rune;
3553 int len;
3554 char buf[5];
3556 rune = (Rune) keysym2ucs (keysym);
3557 len = fz_runetochar (buf, rune);
3558 buf[len] = 0;
3559 str_v = caml_copy_string (buf);
3560 CAMLreturn (str_v);
3562 #else
3563 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3565 CAMLparam1 (keysym_v);
3566 CAMLlocal1 (str_v);
3567 long ucs_v = Long_val (keysym_v);
3568 int len;
3569 char buf[5];
3571 len = fz_runetochar (buf, (int) ucs_v);
3572 buf[len] = 0;
3573 str_v = caml_copy_string (buf);
3574 CAMLreturn (str_v);
3576 #endif
3578 enum { piunknown, pilinux, pimacos, pisun, pibsd };
3580 CAMLprim value ml_platform (value unit_v)
3582 CAMLparam1 (unit_v);
3583 CAMLlocal2 (tup_v, arr_v);
3584 int platid = piunknown;
3585 struct utsname buf;
3587 #if defined __linux__
3588 platid = pilinux;
3589 #elif defined __DragonFly__ || defined __FreeBSD__
3590 || defined __OpenBSD__ || defined __NetBSD__
3591 platid = pibsd;
3592 #elif defined __sun__
3593 platid = pisun;
3594 #elif defined __APPLE__
3595 platid = pimacos;
3596 #endif
3597 if (uname (&buf)) err (1, "uname");
3599 tup_v = caml_alloc_tuple (2);
3601 char const *sar[] = {
3602 buf.sysname,
3603 buf.release,
3604 buf.version,
3605 buf.machine,
3606 NULL
3608 arr_v = caml_copy_string_array (sar);
3610 Field (tup_v, 0) = Val_int (platid);
3611 Field (tup_v, 1) = arr_v;
3612 CAMLreturn (tup_v);
3615 CAMLprim void ml_cloexec (value fd_v)
3617 CAMLparam1 (fd_v);
3618 int fd = Int_val (fd_v);
3620 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3621 uerror ("fcntl", Nothing);
3623 CAMLreturn0;
3626 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3628 CAMLparam2 (w_v, h_v);
3629 CAMLlocal1 (ret_v);
3630 struct bo *pbo;
3631 int w = Int_val (w_v);
3632 int h = Int_val (h_v);
3633 int cs = Int_val (cs_v);
3635 if (state.bo_usable) {
3636 pbo = calloc (sizeof (*pbo), 1);
3637 if (!pbo) {
3638 err (1, "calloc pbo");
3641 switch (cs) {
3642 case 0:
3643 case 1:
3644 pbo->size = w*h*4;
3645 break;
3646 case 2:
3647 pbo->size = w*h*2;
3648 break;
3649 default:
3650 errx (1, "%s: invalid colorspace %d", __func__, cs);
3653 state.glGenBuffersARB (1, &pbo->id);
3654 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3655 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3656 NULL, GL_STREAM_DRAW);
3657 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3658 GL_READ_WRITE);
3659 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3660 if (!pbo->ptr) {
3661 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3662 state.glDeleteBuffersARB (1, &pbo->id);
3663 free (pbo);
3664 ret_v = caml_copy_string ("0");
3666 else {
3667 int res;
3668 char *s;
3670 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3671 if (res < 0) {
3672 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3674 s = malloc (res+1);
3675 if (!s) {
3676 err (1, "malloc %d bytes failed", res+1);
3678 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3679 if (res < 0) {
3680 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3682 ret_v = caml_copy_string (s);
3683 free (s);
3686 else {
3687 ret_v = caml_copy_string ("0");
3689 CAMLreturn (ret_v);
3692 CAMLprim void ml_freepbo (value s_v)
3694 CAMLparam1 (s_v);
3695 char *s = String_val (s_v);
3696 struct tile *tile = parse_pointer (__func__, s);
3698 if (tile->pbo) {
3699 state.glDeleteBuffersARB (1, &tile->pbo->id);
3700 tile->pbo->id = -1;
3701 tile->pbo->ptr = NULL;
3702 tile->pbo->size = -1;
3704 CAMLreturn0;
3707 CAMLprim void ml_unmappbo (value s_v)
3709 CAMLparam1 (s_v);
3710 char *s = String_val (s_v);
3711 struct tile *tile = parse_pointer (__func__, s);
3713 if (tile->pbo) {
3714 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3715 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3716 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3718 tile->pbo->ptr = NULL;
3719 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3721 CAMLreturn0;
3724 static void setuppbo (void)
3726 #ifdef __clang__
3727 #pragma GCC diagnostic ignored "-Wunused-macros"
3728 #endif
3729 #ifdef __COCOA__
3730 static CFBundleRef framework = NULL;
3731 if (framework == NULL)
3732 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3733 #define GGPA(n) \
3734 (*(void (**) (void)) &state.n = \
3735 (void (*) (void)) CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3736 #else
3737 #define GGPA(n) \
3738 (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
3739 #endif
3740 state.bo_usable = GGPA (glBindBufferARB)
3741 && GGPA (glUnmapBufferARB)
3742 && GGPA (glMapBufferARB)
3743 && GGPA (glBufferDataARB)
3744 && GGPA (glGenBuffersARB)
3745 && GGPA (glDeleteBuffersARB);
3746 #undef GGPA
3749 CAMLprim value ml_bo_usable (value unit_v)
3751 CAMLparam1 (unit_v);
3752 CAMLreturn (Val_bool (state.bo_usable));
3755 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3757 CAMLparam3 (ptr_v, x_v, y_v);
3758 CAMLlocal2 (ret_v, tup_v);
3759 struct page *page;
3760 char *s = String_val (ptr_v);
3761 int x = Int_val (x_v), y = Int_val (y_v);
3762 struct pagedim *pdim;
3763 fz_point p;
3764 fz_matrix ctm;
3766 page = parse_pointer (__func__, s);
3767 pdim = &state.pagedims[page->pdimno];
3769 ret_v = Val_int (0);
3770 if (trylock (__func__)) {
3771 goto done;
3774 if (pdf_specifics (state.ctx, state.doc)) {
3775 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3776 ctm = state.pagedims[page->pdimno].tctm;
3778 else {
3779 ctm = fz_identity;
3781 p.x = x + pdim->bounds.x0;
3782 p.y = y + pdim->bounds.y0;
3784 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3785 fz_invert_matrix (&ctm, &ctm);
3786 fz_transform_point (&p, &ctm);
3788 tup_v = caml_alloc_tuple (2);
3789 ret_v = caml_alloc_small (1, 1);
3790 Field (tup_v, 0) = Val_int (p.x);
3791 Field (tup_v, 1) = Val_int (p.y);
3792 Field (ret_v, 0) = tup_v;
3794 unlock (__func__);
3795 done:
3796 CAMLreturn (ret_v);
3799 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3800 value x_v, value y_v)
3802 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3803 CAMLlocal1 (ret_v);
3804 struct page *page;
3805 char *s = String_val (ptr_v);
3806 int pageno = Int_val (pageno_v);
3807 int pdimno = Int_val (pdimno_v);
3808 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3809 struct pagedim *pdim;
3810 fz_point p;
3811 fz_matrix ctm;
3813 ret_v = Val_int (0);
3814 lock (__func__);
3816 if (!*s) {
3817 page = loadpage (pageno, pdimno);
3819 else {
3820 page = parse_pointer (__func__, s);
3822 pdim = &state.pagedims[pdimno];
3824 if (pdf_specifics (state.ctx, state.doc)) {
3825 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3826 ctm = state.pagedims[page->pdimno].tctm;
3828 else {
3829 ctm = fz_identity;
3831 p.x = x + pdim->bounds.x0;
3832 p.y = y + pdim->bounds.y0;
3834 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3835 fz_transform_point (&p, &ctm);
3837 ret_v = caml_alloc_tuple (2);
3838 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3839 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3841 if (!*s) {
3842 freepage (page);
3844 unlock (__func__);
3845 CAMLreturn (ret_v);
3848 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
3849 value contents_v)
3851 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3852 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3854 if (pdf) {
3855 pdf_annot *annot;
3856 struct page *page;
3857 fz_point p;
3858 char *s = String_val (ptr_v);
3860 page = parse_pointer (__func__, s);
3861 annot = pdf_create_annot (state.ctx,
3862 pdf_page_from_fz_page (state.ctx,
3863 page->fzpage),
3864 PDF_ANNOT_TEXT);
3865 p.x = Int_val (x_v);
3866 p.y = Int_val (y_v);
3867 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3868 pdf_set_text_annot_position (state.ctx, annot, p);
3869 state.dirty = 1;
3871 CAMLreturn0;
3874 CAMLprim void ml_delannot (value ptr_v, value n_v)
3876 CAMLparam2 (ptr_v, n_v);
3877 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3879 if (pdf) {
3880 struct page *page;
3881 char *s = String_val (ptr_v);
3882 struct slink *slink;
3884 page = parse_pointer (__func__, s);
3885 slink = &page->slinks[Int_val (n_v)];
3886 pdf_delete_annot (state.ctx,
3887 pdf_page_from_fz_page (state.ctx, page->fzpage),
3888 (pdf_annot *) slink->u.annot);
3889 state.dirty = 1;
3891 CAMLreturn0;
3894 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
3896 CAMLparam3 (ptr_v, n_v, str_v);
3897 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3899 if (pdf) {
3900 struct page *page;
3901 char *s = String_val (ptr_v);
3902 struct slink *slink;
3904 page = parse_pointer (__func__, s);
3905 slink = &page->slinks[Int_val (n_v)];
3906 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3907 String_val (str_v));
3908 state.dirty = 1;
3910 CAMLreturn0;
3913 CAMLprim value ml_hasunsavedchanges (value unit_v)
3915 CAMLparam1 (unit_v);
3916 CAMLreturn (Val_bool (state.dirty));
3919 CAMLprim void ml_savedoc (value path_v)
3921 CAMLparam1 (path_v);
3922 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3924 if (pdf) {
3925 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3927 CAMLreturn0;
3930 static void makestippletex (void)
3932 const char pixels[] = "\xff\xff\0\0";
3933 glGenTextures (1, &state.stid);
3934 glBindTexture (GL_TEXTURE_1D, state.stid);
3935 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3936 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3937 glTexImage1D (
3938 GL_TEXTURE_1D,
3940 GL_ALPHA,
3943 GL_ALPHA,
3944 GL_UNSIGNED_BYTE,
3945 pixels
3949 CAMLprim value ml_fz_version (void)
3951 return caml_copy_string (FZ_VERSION);
3954 CAMLprim value ml_llpp_version (void)
3956 extern char llpp_version[];
3957 return caml_copy_string (llpp_version);
3960 CAMLprim void ml_init (value csock_v, value params_v)
3962 CAMLparam2 (csock_v, params_v);
3963 CAMLlocal2 (trim_v, fuzz_v);
3964 int ret;
3965 int texcount;
3966 char *fontpath;
3967 int colorspace;
3968 int mustoresize;
3969 int haspboext;
3971 state.csock = Int_val (csock_v);
3972 state.rotate = Int_val (Field (params_v, 0));
3973 state.fitmodel = Int_val (Field (params_v, 1));
3974 trim_v = Field (params_v, 2);
3975 texcount = Int_val (Field (params_v, 3));
3976 state.sliceheight = Int_val (Field (params_v, 4));
3977 mustoresize = Int_val (Field (params_v, 5));
3978 colorspace = Int_val (Field (params_v, 6));
3979 fontpath = String_val (Field (params_v, 7));
3981 #ifdef __COCOA__
3982 state.utf8cs = 1;
3983 #else
3984 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3985 if (setlocale (LC_CTYPE, "")) {
3986 const char *cset = nl_langinfo (CODESET);
3987 state.utf8cs = !strcmp (cset, "UTF-8");
3989 else {
3990 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3992 #endif
3994 if (caml_string_length (Field (params_v, 8)) > 0) {
3995 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3997 if (!state.trimcachepath) {
3998 printd ("emsg failed to strdup trimcachepath: %d:%s",
3999 errno, strerror (errno));
4003 haspboext = Bool_val (Field (params_v, 9));
4005 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4006 fz_register_document_handlers (state.ctx);
4008 state.trimmargins = Bool_val (Field (trim_v, 0));
4009 fuzz_v = Field (trim_v, 1);
4010 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4011 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4012 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4013 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4015 set_tex_params (colorspace);
4017 if (*fontpath) {
4018 state.face = load_font (fontpath);
4020 else {
4021 int len;
4022 const unsigned char *data;
4024 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4025 state.face = load_builtin_font (data, len);
4027 if (!state.face) _exit (1);
4029 realloctexts (texcount);
4031 if (haspboext) {
4032 setuppbo ();
4035 makestippletex ();
4037 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4038 if (ret) {
4039 errx (1, "pthread_create: %s", strerror (ret));
4042 CAMLreturn0;
4045 #if FIXME || !FIXME
4046 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
4047 #endif