Cosmetics
[llpp.git] / link.c
blob868ac9842d1ef1b14bf3e20ad6187924414e439e
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 #pragma GCC diagnostic ignored "-Wdouble-promotion"
10 #endif
12 extern char **environ;
14 #define CAML_NAME_SPACE
15 #define FIXME 0
17 #include <errno.h>
18 #include <stdio.h>
19 #include <ctype.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include <signal.h>
24 #include <math.h>
25 #include <wchar.h>
26 #include <locale.h>
27 #include <langinfo.h>
29 #include <unistd.h>
30 #include <pthread.h>
31 #include <sys/uio.h>
32 #include <sys/time.h>
33 #include <sys/stat.h>
34 #include <fcntl.h>
35 #include <sys/types.h>
36 #include <sys/ioctl.h>
37 #include <sys/utsname.h>
39 #include <spawn.h>
41 #include <regex.h>
42 #include <stdarg.h>
43 #include <limits.h>
44 #include <inttypes.h>
46 #ifdef __COCOA__
47 #include <CoreFoundation/CoreFoundation.h>
48 #include <OpenGL/gl.h>
49 #else
50 #include <GL/gl.h>
51 #endif
53 #pragma GCC diagnostic push
54 #ifdef __clang__
55 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
56 #endif
57 #pragma GCC diagnostic ignored "-Wpedantic"
58 #include <caml/fail.h>
59 #include <caml/alloc.h>
60 #include <caml/memory.h>
61 #include <caml/unixsupport.h>
63 #pragma GCC diagnostic push
64 #pragma GCC diagnostic ignored "-Wfloat-equal"
65 #include <mupdf/fitz.h>
66 #include <mupdf/pdf.h>
67 #pragma GCC diagnostic pop
69 #include <ft2build.h>
70 #include FT_FREETYPE_H
71 #pragma GCC diagnostic pop
73 #include "cutils.h"
75 #ifdef USE_NPOT
76 #define TEXT_TYPE GL_TEXTURE_2D
77 #else
78 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
79 #endif
81 #if 0
82 #define lprintf printf
83 #else
84 #define lprintf(...)
85 #endif
87 #define ARSERT(cond) for (;;) { \
88 if (!(cond)) { \
89 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
90 } \
91 break; \
94 struct slice {
95 int h;
96 int texindex;
99 struct tile {
100 int w, h;
101 int slicecount;
102 int sliceheight;
103 struct bo *pbo;
104 fz_pixmap *pixmap;
105 struct slice slices[1];
108 struct pagedim {
109 int pageno;
110 int rotate;
111 int left;
112 int tctmready;
113 fz_irect bounds;
114 fz_rect pagebox;
115 fz_rect mediabox;
116 fz_matrix ctm, zoomctm, tctm;
119 struct slink {
120 enum { SLINK, SANNOT } tag;
121 fz_irect bbox;
122 union {
123 fz_link *link;
124 fz_annot *annot;
125 } u;
128 struct annot {
129 fz_irect bbox;
130 fz_annot *annot;
133 struct page {
134 int tgen;
135 int sgen;
136 int agen;
137 int pageno;
138 int pdimno;
139 fz_stext_page *text;
140 fz_page *fzpage;
141 fz_display_list *dlist;
142 fz_link *links;
143 int slinkcount;
144 struct slink *slinks;
145 int annotcount;
146 struct annot *annots;
147 fz_stext_char *fmark, *lmark;
150 enum { FitWidth, FitProportional, FitPage };
152 static struct {
153 int sliceheight;
154 struct pagedim *pagedims;
155 int pagecount;
156 int pagedimcount;
157 fz_document *doc;
158 fz_context *ctx;
159 int w, h;
161 int texindex;
162 int texcount;
163 GLuint *texids;
165 GLenum texiform;
166 GLenum texform;
167 GLenum texty;
169 fz_colorspace *colorspace;
171 struct {
172 int w, h;
173 struct slice *slice;
174 } *texowners;
176 int rotate;
177 int fitmodel;
178 int trimmargins;
179 int needoutline;
180 int gen;
181 int aalevel;
183 int trimanew;
184 fz_irect trimfuzz;
185 fz_pixmap *pig;
187 pthread_t thread;
188 int csock;
189 FT_Face face;
191 char *trimcachepath;
192 int dirty;
194 GLuint stid;
196 int bo_usable;
197 GLuint boid;
199 void (*glBindBufferARB) (GLenum, GLuint);
200 GLboolean (*glUnmapBufferARB) (GLenum);
201 void *(*glMapBufferARB) (GLenum, GLenum);
202 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
203 void (*glGenBuffersARB) (GLsizei, GLuint *);
204 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
206 GLfloat texcoords[8];
207 GLfloat vertices[16];
209 #ifdef CACHE_PAGEREFS
210 struct {
211 int idx;
212 int count;
213 pdf_obj **objs;
214 pdf_document *pdf;
215 } pdflut;
216 #endif
217 int utf8cs;
218 } state;
220 struct bo {
221 GLuint id;
222 void *ptr;
223 size_t size;
226 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
228 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
231 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
233 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
236 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
238 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
239 m.a, m.b, m.c, m.d, m.e, m.f);
242 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
244 static void lock (const char *cap)
246 int ret = pthread_mutex_lock (&mutex);
247 if (ret) {
248 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
252 static void unlock (const char *cap)
254 int ret = pthread_mutex_unlock (&mutex);
255 if (ret) {
256 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
260 static int trylock (const char *cap)
262 int ret = pthread_mutex_trylock (&mutex);
263 if (ret && ret != EBUSY) {
264 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
266 return ret == EBUSY;
269 static int hasdata (void)
271 int ret, avail;
272 ret = ioctl (state.csock, FIONREAD, &avail);
273 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
274 return avail > 0;
277 CAMLprim value ml_hasdata (value fd_v)
279 CAMLparam1 (fd_v);
280 int ret, avail;
282 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
283 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
284 CAMLreturn (Val_bool (avail > 0));
287 static void readdata (int fd, void *p, int size)
289 ssize_t n;
291 again:
292 n = read (fd, p, size);
293 if (n - size) {
294 if (n < 0 && errno == EINTR) goto again;
295 if (!n) errx (1, "EOF while reading");
296 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
300 static void writedata (int fd, char *p, int size)
302 ssize_t n;
303 uint32_t size4 = size;
304 struct iovec iov[2] = {
305 { .iov_base = &size4, .iov_len = 4 },
306 { .iov_base = p, .iov_len = size }
309 again:
310 n = writev (fd, iov, 2);
311 if (n < 0 && errno == EINTR) goto again;
312 if (n - size - 4) {
313 if (!n) errx (1, "EOF while writing data");
314 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
318 static int readlen (int fd)
320 uint32_t u;
321 readdata (fd, &u, 4);
322 return u;
325 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
327 CAMLparam3 (fd_v, bytes_v, len_v);
328 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
329 CAMLreturn0;
332 CAMLprim value ml_rcmd (value fd_v)
334 CAMLparam1 (fd_v);
335 CAMLlocal1 (strdata_v);
336 int fd = Int_val (fd_v);
337 int len = readlen (fd);
338 strdata_v = caml_alloc_string (len);
339 readdata (fd, String_val (strdata_v), len);
340 CAMLreturn (strdata_v);
343 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
345 char fbuf[64];
346 int size = sizeof (fbuf), len;
347 va_list ap;
348 char *buf = fbuf;
350 for (;;) {
351 va_start (ap, fmt);
352 len = vsnprintf (buf, size, fmt, ap);
353 va_end (ap);
355 if (len > -1) {
356 if (len < size - 4) {
357 writedata (state.csock, buf, len);
358 break;
360 else size = len + 5;
362 else {
363 err (1, "vsnprintf for `%s' failed", fmt);
365 buf = realloc (buf == fbuf ? NULL : buf, size);
366 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
368 if (buf != fbuf) free (buf);
371 static void closedoc (void)
373 #ifdef CACHE_PAGEREFS
374 if (state.pdflut.objs) {
375 for (int i = 0; i < state.pdflut.count; ++i) {
376 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
378 free (state.pdflut.objs);
379 state.pdflut.objs = NULL;
380 state.pdflut.idx = 0;
382 #endif
383 if (state.doc) {
384 fz_drop_document (state.ctx, state.doc);
385 state.doc = NULL;
389 static int openxref (char *filename, char *password, int layouth)
391 for (int i = 0; i < state.texcount; ++i) {
392 state.texowners[i].w = -1;
393 state.texowners[i].slice = NULL;
396 closedoc ();
398 state.dirty = 0;
399 if (state.pagedims) {
400 free (state.pagedims);
401 state.pagedims = NULL;
403 state.pagedimcount = 0;
405 fz_set_aa_level (state.ctx, state.aalevel);
406 state.doc = fz_open_document (state.ctx, filename);
407 if (fz_needs_password (state.ctx, state.doc)) {
408 if (password && !*password) {
409 printd ("pass");
410 return 0;
412 else {
413 int ok = fz_authenticate_password (state.ctx, state.doc, password);
414 if (!ok) {
415 printd ("pass fail");
416 return 0;
420 if (layouth >= 0)
421 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
422 state.pagecount = fz_count_pages (state.ctx, state.doc);
423 return 1;
426 static void docinfo (void)
428 struct { char *tag; char *name; } metatbl[] = {
429 { FZ_META_INFO_TITLE, "Title" },
430 { FZ_META_INFO_AUTHOR, "Author" },
431 { FZ_META_FORMAT, "Format" },
432 { FZ_META_ENCRYPTION, "Encryption" },
433 { "info:Creator", "Creator" },
434 { "info:Producer", "Producer" },
435 { "info:CreationDate", "Creation date" },
437 int len = 0;
438 char *buf = NULL;
440 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
441 int need;
442 again:
443 need = fz_lookup_metadata (state.ctx, state.doc,
444 metatbl[i].tag, buf, len);
445 if (need > 0) {
446 if (need <= len) {
447 printd ("info %s\t%s", metatbl[i].name, buf);
449 else {
450 buf = realloc (buf, need + 1);
451 if (!buf) err (1, "docinfo realloc %d", need + 1);
452 len = need + 1;
453 goto again;
457 free (buf);
459 printd ("infoend");
462 static void unlinktile (struct tile *tile)
464 for (int i = 0; i < tile->slicecount; ++i) {
465 struct slice *s = &tile->slices[i];
467 if (s->texindex != -1) {
468 if (state.texowners[s->texindex].slice == s) {
469 state.texowners[s->texindex].slice = NULL;
475 static void freepage (struct page *page)
477 if (!page) return;
478 if (page->text) {
479 fz_drop_stext_page (state.ctx, page->text);
481 if (page->slinks) {
482 free (page->slinks);
484 fz_drop_display_list (state.ctx, page->dlist);
485 fz_drop_page (state.ctx, page->fzpage);
486 free (page);
489 static void freetile (struct tile *tile)
491 unlinktile (tile);
492 if (!tile->pbo) {
493 #if 0
494 fz_drop_pixmap (state.ctx, tile->pixmap);
495 #else /* piggyback */
496 if (state.pig) {
497 fz_drop_pixmap (state.ctx, state.pig);
499 state.pig = tile->pixmap;
500 #endif
502 else {
503 free (tile->pbo);
504 fz_drop_pixmap (state.ctx, tile->pixmap);
506 free (tile);
509 static void trimctm (pdf_page *page, int pindex)
511 fz_matrix ctm;
512 struct pagedim *pdim = &state.pagedims[pindex];
514 if (!page) return;
515 if (!pdim->tctmready) {
516 fz_rect realbox, mediabox;
517 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
519 fz_rotate (&rm, -pdim->rotate);
520 fz_scale (&sm, 1, -1);
521 fz_concat (&ctm, &rm, &sm);
522 realbox = pdim->mediabox;
523 fz_transform_rect (&realbox, &ctm);
524 fz_translate (&tm, -realbox.x0, -realbox.y0);
525 fz_concat (&ctm1, &ctm, &tm);
526 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
527 fz_invert_matrix (&im, &page_ctm);
528 fz_concat (&ctm, &im, &ctm1);
529 pdim->tctm = ctm;
530 pdim->tctmready = 1;
534 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
536 fz_matrix ctm, tm;
537 ptrdiff_t pdimno = pdim - state.pagedims;
539 ARSERT (pdim - state.pagedims < INT_MAX);
540 if (pdf_specifics (state.ctx, state.doc)) {
541 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
542 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
544 else {
545 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
546 fz_concat (&ctm, &tm, &pdim->ctm);
548 return ctm;
551 static fz_matrix pagectm (struct page *page)
553 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
556 static void *loadpage (int pageno, int pindex)
558 fz_device *dev;
559 struct page *page;
561 page = calloc (sizeof (struct page), 1);
562 if (!page) {
563 err (1, "calloc page %d", pageno);
566 page->dlist = fz_new_display_list (state.ctx, NULL);
567 dev = fz_new_list_device (state.ctx, page->dlist);
568 fz_try (state.ctx) {
569 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
570 fz_run_page (state.ctx, page->fzpage, dev,
571 &fz_identity, NULL);
573 fz_catch (state.ctx) {
574 page->fzpage = NULL;
576 fz_close_device (state.ctx, dev);
577 fz_drop_device (state.ctx, dev);
579 page->pdimno = pindex;
580 page->pageno = pageno;
581 page->sgen = state.gen;
582 page->agen = state.gen;
583 page->tgen = state.gen;
584 return page;
587 static struct tile *alloctile (int h)
589 int slicecount;
590 size_t tilesize;
591 struct tile *tile;
593 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
594 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
595 tile = calloc (tilesize, 1);
596 if (!tile) {
597 err (1, "cannot allocate tile (%zu bytes)", tilesize);
599 for (int i = 0; i < slicecount; ++i) {
600 int sh = fz_mini (h, state.sliceheight);
601 tile->slices[i].h = sh;
602 tile->slices[i].texindex = -1;
603 h -= sh;
605 tile->slicecount = slicecount;
606 tile->sliceheight = state.sliceheight;
607 return tile;
610 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
611 struct bo *pbo)
613 fz_rect rect;
614 fz_irect bbox;
615 fz_matrix ctm;
616 fz_device *dev;
617 struct tile *tile;
618 struct pagedim *pdim;
620 tile = alloctile (h);
621 pdim = &state.pagedims[page->pdimno];
623 bbox = pdim->bounds;
624 bbox.x0 += x;
625 bbox.y0 += y;
626 bbox.x1 = bbox.x0 + w;
627 bbox.y1 = bbox.y0 + h;
629 if (state.pig) {
630 if (state.pig->w == w
631 && state.pig->h == h
632 && state.pig->colorspace == state.colorspace) {
633 tile->pixmap = state.pig;
634 tile->pixmap->x = bbox.x0;
635 tile->pixmap->y = bbox.y0;
637 else {
638 fz_drop_pixmap (state.ctx, state.pig);
640 state.pig = NULL;
642 if (!tile->pixmap) {
643 if (pbo) {
644 tile->pixmap =
645 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
646 &bbox, NULL, 1, pbo->ptr);
647 tile->pbo = pbo;
649 else {
650 tile->pixmap =
651 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
652 NULL, 1);
656 tile->w = w;
657 tile->h = h;
658 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
660 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
661 ctm = pagectm (page);
662 fz_rect_from_irect (&rect, &bbox);
663 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
664 fz_close_device (state.ctx, dev);
665 fz_drop_device (state.ctx, dev);
667 return tile;
670 #ifdef CACHE_PAGEREFS
671 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
672 thanks to Robin Watts */
673 static void
674 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
676 fz_context *ctx = state.ctx; /* doc->ctx; */
677 pdf_obj *kids;
678 int len;
680 if (state.pdflut.idx == state.pagecount) return;
682 kids = pdf_dict_gets (ctx, node, "Kids");
683 len = pdf_array_len (ctx, kids);
685 if (len == 0)
686 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
688 if (pdf_mark_obj (ctx, node))
689 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
690 for (int i = 0; i < len; i++) {
691 pdf_obj *kid = pdf_array_get (ctx, kids, i);
692 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
693 if (*type
694 ? !strcmp (type, "Pages")
695 : pdf_dict_gets (ctx, kid, "Kids")
696 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
697 pdf_collect_pages (doc, kid);
699 else {
700 if (*type
701 ? strcmp (type, "Page") != 0
702 : !pdf_dict_gets (ctx, kid, "MediaBox"))
703 fz_warn (ctx, "non-page object in page tree (%s)", type);
704 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
707 pdf_unmark_obj (ctx, node);
710 static void
711 pdf_load_page_objs (pdf_document *doc)
713 pdf_obj *root = pdf_dict_gets (state.ctx,
714 pdf_trailer (state.ctx, doc), "Root");
715 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
717 if (!node)
718 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
720 state.pdflut.idx = 0;
721 pdf_collect_pages (doc, node);
723 #endif
725 static void initpdims (void)
727 double start, end;
728 FILE *trimf = NULL;
729 fz_rect rootmediabox = fz_empty_rect;
730 int pageno, trim, show;
731 int trimw = 0, cxcount;
732 fz_context *ctx = state.ctx;
733 pdf_document *pdf = pdf_specifics (ctx, state.doc);
735 fz_var (trimw);
736 fz_var (trimf);
737 fz_var (cxcount);
738 start = now ();
740 if (state.trimmargins && state.trimcachepath) {
741 trimf = fopen (state.trimcachepath, "rb");
742 if (!trimf) {
743 trimf = fopen (state.trimcachepath, "wb");
744 trimw = 1;
748 if (state.trimmargins || pdf)
749 cxcount = state.pagecount;
750 else
751 cxcount = fz_mini (state.pagecount, 1);
753 if (pdf) {
754 pdf_obj *obj;
755 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
756 "Root/Pages/MediaBox");
757 pdf_to_rect (ctx, obj, &rootmediabox);
760 #ifdef CACHE_PAGEREFS
761 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
762 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
763 if (!state.pdflut.objs) {
764 err (1, "malloc pageobjs %zu %d %zu failed",
765 sizeof (*state.pdflut.objs), cxcount,
766 sizeof (*state.pdflut.objs) * cxcount);
768 state.pdflut.count = cxcount;
769 pdf_load_page_objs (pdf);
770 state.pdflut.pdf = pdf;
772 #endif
774 for (pageno = 0; pageno < cxcount; ++pageno) {
775 int rotate = 0;
776 struct pagedim *p;
777 fz_rect mediabox = fz_empty_rect;
779 fz_var (rotate);
780 if (pdf) {
781 pdf_obj *pageref, *pageobj;
783 #ifdef CACHE_PAGEREFS
784 pageref = state.pdflut.objs[pageno];
785 #else
786 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
787 #endif
788 pageobj = pdf_resolve_indirect (ctx, pageref);
789 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
791 if (state.trimmargins) {
792 pdf_obj *obj;
793 pdf_page *page;
795 fz_try (ctx) {
796 page = pdf_load_page (ctx, pdf, pageno);
797 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
798 trim = state.trimanew || !obj;
799 if (trim) {
800 fz_rect rect;
801 fz_device *dev;
802 fz_matrix ctm, page_ctm;
804 dev = fz_new_bbox_device (ctx, &rect);
805 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
806 fz_invert_matrix (&ctm, &page_ctm);
807 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
808 fz_close_device (ctx, dev);
809 fz_drop_device (ctx, dev);
811 rect.x0 += state.trimfuzz.x0;
812 rect.x1 += state.trimfuzz.x1;
813 rect.y0 += state.trimfuzz.y0;
814 rect.y1 += state.trimfuzz.y1;
815 fz_transform_rect (&rect, &ctm);
816 fz_intersect_rect (&rect, &mediabox);
818 if (!fz_is_empty_rect (&rect)) {
819 mediabox = rect;
822 obj = pdf_new_array (ctx, pdf, 4);
823 pdf_array_push (ctx, obj,
824 pdf_new_real (ctx, mediabox.x0));
825 pdf_array_push (ctx, obj,
826 pdf_new_real (ctx, mediabox.y0));
827 pdf_array_push (ctx, obj,
828 pdf_new_real (ctx, mediabox.x1));
829 pdf_array_push (ctx, obj,
830 pdf_new_real (ctx, mediabox.y1));
831 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
833 else {
834 mediabox.x0 = pdf_to_real (ctx,
835 pdf_array_get (ctx, obj, 0));
836 mediabox.y0 = pdf_to_real (ctx,
837 pdf_array_get (ctx, obj, 1));
838 mediabox.x1 = pdf_to_real (ctx,
839 pdf_array_get (ctx, obj, 2));
840 mediabox.y1 = pdf_to_real (ctx,
841 pdf_array_get (ctx, obj, 3));
844 fz_drop_page (ctx, &page->super);
845 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
846 if (show) {
847 printd ("progress %f Trimming %d",
848 (double) (pageno + 1) / state.pagecount,
849 pageno + 1);
852 fz_catch (ctx) {
853 printd ("emsg failed to load page %d", pageno);
856 else {
857 int empty = 0;
858 fz_rect cropbox;
860 pdf_to_rect (ctx,
861 pdf_dict_gets (ctx, pageobj, "MediaBox"),
862 &mediabox);
863 if (fz_is_empty_rect (&mediabox)) {
864 mediabox.x0 = 0;
865 mediabox.y0 = 0;
866 mediabox.x1 = 612;
867 mediabox.y1 = 792;
868 empty = 1;
871 pdf_to_rect (ctx,
872 pdf_dict_gets (ctx, pageobj, "CropBox"),
873 &cropbox);
874 if (!fz_is_empty_rect (&cropbox)) {
875 if (empty) {
876 mediabox = cropbox;
878 else {
879 fz_intersect_rect (&mediabox, &cropbox);
882 else {
883 if (empty) {
884 if (fz_is_empty_rect (&rootmediabox)) {
885 printd ("emsg cannot find page size for page %d",
886 pageno);
888 else {
889 mediabox = rootmediabox;
895 else {
896 if (state.trimmargins && trimw) {
897 fz_page *page;
899 fz_try (ctx) {
900 page = fz_load_page (ctx, state.doc, pageno);
901 fz_bound_page (ctx, page, &mediabox);
902 if (state.trimmargins) {
903 fz_rect rect;
904 fz_device *dev;
906 dev = fz_new_bbox_device (ctx, &rect);
907 fz_run_page (ctx, page, dev, &fz_identity, NULL);
908 fz_close_device (ctx, dev);
909 fz_drop_device (ctx, dev);
911 rect.x0 += state.trimfuzz.x0;
912 rect.x1 += state.trimfuzz.x1;
913 rect.y0 += state.trimfuzz.y0;
914 rect.y1 += state.trimfuzz.y1;
915 fz_intersect_rect (&rect, &mediabox);
917 if (!fz_is_empty_rect (&rect)) {
918 mediabox = rect;
921 fz_drop_page (ctx, page);
923 fz_catch (ctx) {
925 if (trimf) {
926 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
927 if (n - 1) {
928 err (1, "fwrite trim mediabox");
932 else {
933 if (trimf) {
934 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
935 if (n - 1) {
936 err (1, "fread trim mediabox %d", pageno);
939 else {
940 fz_page *page;
941 fz_try (ctx) {
942 page = fz_load_page (ctx, state.doc, pageno);
943 fz_bound_page (ctx, page, &mediabox);
944 fz_drop_page (ctx, page);
946 show = !state.trimmargins && pageno % 20 == 0;
947 if (show) {
948 printd ("progress %f Gathering dimensions %d",
949 (double) (pageno) / state.pagecount,
950 pageno);
953 fz_catch (ctx) {
954 printd ("emsg failed to load page %d", pageno);
960 if (state.pagedimcount == 0
961 || ((void) (p = &state.pagedims[state.pagedimcount-1])
962 , p->rotate != rotate)
963 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
964 size_t size;
966 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
967 state.pagedims = realloc (state.pagedims, size);
968 if (!state.pagedims) {
969 err (1, "realloc pagedims to %zu (%d elems)",
970 size, state.pagedimcount + 1);
973 p = &state.pagedims[state.pagedimcount++];
974 p->rotate = rotate;
975 p->mediabox = mediabox;
976 p->pageno = pageno;
979 end = now ();
980 printd ("progress 1 %s %d pages in %f seconds",
981 state.trimmargins ? "Trimmed" : "Processed",
982 state.pagecount, end - start);
983 state.trimanew = 0;
984 if (trimf) {
985 if (fclose (trimf)) {
986 err (1, "fclose");
991 static void layout (void)
993 int pindex;
994 fz_rect box;
995 fz_matrix ctm, rm;
996 struct pagedim *p = NULL;
997 float zw, w, maxw = 0.0, zoom = 1.0;
999 if (state.pagedimcount == 0) return;
1001 switch (state.fitmodel) {
1002 case FitProportional:
1003 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1004 float x0, x1;
1006 p = &state.pagedims[pindex];
1007 fz_rotate (&rm, p->rotate + state.rotate);
1008 box = p->mediabox;
1009 fz_transform_rect (&box, &rm);
1011 x0 = fz_min (box.x0, box.x1);
1012 x1 = fz_max (box.x0, box.x1);
1014 w = x1 - x0;
1015 maxw = fz_max (w, maxw);
1016 zoom = state.w / maxw;
1018 break;
1020 case FitPage:
1021 maxw = state.w;
1022 break;
1024 case FitWidth:
1025 break;
1027 default:
1028 ARSERT (0 && state.fitmodel);
1031 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1032 fz_rect rect;
1033 fz_matrix tm, sm;
1035 p = &state.pagedims[pindex];
1036 fz_rotate (&ctm, state.rotate);
1037 fz_rotate (&rm, p->rotate + state.rotate);
1038 box = p->mediabox;
1039 fz_transform_rect (&box, &rm);
1040 w = box.x1 - box.x0;
1041 switch (state.fitmodel) {
1042 case FitProportional:
1043 p->left = (int) (((maxw - w) * zoom) / 2.f);
1044 break;
1045 case FitPage:
1047 float zh, h;
1048 zw = maxw / w;
1049 h = box.y1 - box.y0;
1050 zh = state.h / h;
1051 zoom = fz_min (zw, zh);
1052 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1054 break;
1055 case FitWidth:
1056 p->left = 0;
1057 zoom = state.w / w;
1058 break;
1061 fz_scale (&p->zoomctm, zoom, zoom);
1062 fz_concat (&ctm, &p->zoomctm, &ctm);
1064 fz_rotate (&rm, p->rotate);
1065 p->pagebox = p->mediabox;
1066 fz_transform_rect (&p->pagebox, &rm);
1067 p->pagebox.x1 -= p->pagebox.x0;
1068 p->pagebox.y1 -= p->pagebox.y0;
1069 p->pagebox.x0 = 0;
1070 p->pagebox.y0 = 0;
1071 rect = p->pagebox;
1072 fz_transform_rect (&rect, &ctm);
1073 fz_round_rect (&p->bounds, &rect);
1074 p->ctm = ctm;
1076 fz_translate (&tm, 0, -p->mediabox.y1);
1077 fz_scale (&sm, zoom, -zoom);
1078 fz_concat (&ctm, &tm, &sm);
1080 p->tctmready = 0;
1083 do {
1084 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1085 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1086 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1087 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1088 int boundw = x1 - x0;
1089 int boundh = y1 - y0;
1091 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1092 } while (p-- != state.pagedims);
1095 struct pagedim *pdimofpageno (int pageno)
1097 struct pagedim *pdim = state.pagedims;
1099 for (int i = 0; i < state.pagedimcount; ++i) {
1100 if (state.pagedims[i].pageno > pageno)
1101 break;
1102 pdim = &state.pagedims[i];
1104 return pdim;
1107 static void recurse_outline (fz_outline *outline, int level)
1109 while (outline) {
1110 if (outline->page >= 0) {
1111 fz_point p = {.x = outline->x, .y = outline->y};
1112 struct pagedim *pdim = pdimofpageno (outline->page);
1113 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1114 fz_transform_point (&p, &pdim->ctm);
1115 printd ("o %d %d %d %d %s",
1116 level, outline->page, (int) p.y, h, outline->title);
1118 else {
1119 printd ("on %d %s", level, outline->title);
1121 if (outline->down) {
1122 recurse_outline (outline->down, level + 1);
1124 outline = outline->next;
1128 static void process_outline (void)
1130 fz_outline *outline;
1132 if (!state.needoutline || !state.pagedimcount) return;
1134 state.needoutline = 0;
1135 outline = fz_load_outline (state.ctx, state.doc);
1136 if (outline) {
1137 recurse_outline (outline, 0);
1138 fz_drop_outline (state.ctx, outline);
1142 static char *strofline (fz_stext_line *line)
1144 char *p;
1145 char utf8[10];
1146 fz_stext_char *ch;
1147 size_t size = 0, cap = 80;
1149 p = malloc (cap + 1);
1150 if (!p) return NULL;
1152 for (ch = line->first_char; ch; ch = ch->next) {
1153 int n = fz_runetochar (utf8, ch->c);
1154 if (size + n > cap) {
1155 cap *= 2;
1156 p = realloc (p, cap + 1);
1157 if (!p) return NULL;
1160 memcpy (p + size, utf8, n);
1161 size += n;
1163 p[size] = 0;
1164 return p;
1167 static int matchline (regex_t *re, fz_stext_line *line,
1168 int stop, int pageno, double start)
1170 int ret;
1171 char *p;
1172 regmatch_t rm;
1174 p = strofline (line);
1175 if (!p) return -1;
1177 ret = regexec (re, p, 1, &rm, 0);
1178 if (ret) {
1179 free (p);
1180 if (ret != REG_NOMATCH) {
1181 size_t size;
1182 char errbuf[80];
1183 size = regerror (ret, re, errbuf, sizeof (errbuf));
1184 printd ("msg regexec error `%.*s'",
1185 (int) size, errbuf);
1186 return -1;
1188 return 0;
1190 else {
1191 fz_point p1, p2, p3, p4;
1192 fz_rect s = {0,0,0,0}, e;
1193 fz_stext_char *ch;
1194 int o = 0;
1196 for (ch = line->first_char; ch; ch = ch->next) {
1197 o += fz_runelen (ch->c);
1198 if (o > rm.rm_so) {
1199 s = ch->bbox;
1200 break;
1203 for (;ch; ch = ch->next) {
1204 o += fz_runelen (ch->c);
1205 if (o > rm.rm_eo) break;
1207 e = ch->bbox;
1209 p1.x = s.x0;
1210 p1.y = s.y0;
1211 p2.x = e.x1;
1212 p2.y = s.y0;
1213 p3.x = e.x1;
1214 p3.y = e.y1;
1215 p4.x = s.x0;
1216 p4.y = e.y1;
1218 if (!stop) {
1219 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1220 pageno, 1,
1221 p1.x, p1.y,
1222 p2.x, p2.y,
1223 p3.x, p3.y,
1224 p4.x, p4.y);
1226 printd ("progress 1 found at %d `%.*s' in %f sec",
1227 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1228 now () - start);
1230 else {
1231 printd ("match %d %d %f %f %f %f %f %f %f %f",
1232 pageno, 2,
1233 p1.x, p1.y,
1234 p2.x, p2.y,
1235 p3.x, p3.y,
1236 p4.x, p4.y);
1238 free (p);
1239 return 1;
1243 /* wishful thinking function */
1244 static void search (regex_t *re, int pageno, int y, int forward)
1246 fz_device *tdev;
1247 fz_stext_page *text;
1248 struct pagedim *pdim;
1249 int stop = 0, niters = 0;
1250 double start, end;
1251 fz_page *page;
1252 fz_stext_block *block;
1254 start = now ();
1255 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1256 if (niters++ == 5) {
1257 niters = 0;
1258 if (hasdata ()) {
1259 printd ("progress 1 attention requested aborting search at %d",
1260 pageno);
1261 stop = 1;
1263 else {
1264 printd ("progress %f searching in page %d",
1265 (double) (pageno + 1) / state.pagecount,
1266 pageno);
1269 pdim = pdimofpageno (pageno);
1270 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1271 tdev = fz_new_stext_device (state.ctx, text, 0);
1273 page = fz_load_page (state.ctx, state.doc, pageno);
1275 fz_matrix ctm = pagectm1 (page, pdim);
1276 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1279 fz_close_device (state.ctx, tdev);
1280 fz_drop_device (state.ctx, tdev);
1282 if (forward) {
1283 for (block = text->first_block; block; block = block->next) {
1284 fz_stext_line *line;
1286 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1287 for (line = block->u.t.first_line; line; line = line->next) {
1288 if (line->bbox.y0 < y + 1) continue;
1290 switch (matchline (re, line, stop, pageno, start)) {
1291 case 0: break;
1292 case 1: stop = 1; break;
1293 case -1: stop = 1; goto endloop;
1298 else {
1299 for (block = text->last_block; block; block = block->prev) {
1300 fz_stext_line *line;
1302 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1303 for (line = block->u.t.last_line; line; line = line->prev) {
1304 if (line->bbox.y0 < y + 1) continue;
1306 switch (matchline (re, line, stop, pageno, start)) {
1307 case 0: break;
1308 case 1: stop = 1; break;
1309 case -1: stop = 1; goto endloop;
1315 if (forward) {
1316 pageno += 1;
1317 y = 0;
1319 else {
1320 pageno -= 1;
1321 y = INT_MAX;
1323 endloop:
1324 fz_drop_stext_page (state.ctx, text);
1325 fz_drop_page (state.ctx, page);
1327 end = now ();
1328 if (!stop) {
1329 printd ("progress 1 no matches %f sec", end - start);
1331 printd ("clearrects");
1334 static void set_tex_params (int colorspace)
1336 switch (colorspace) {
1337 case 0:
1338 state.texiform = GL_RGBA8;
1339 state.texform = GL_RGBA;
1340 state.texty = GL_UNSIGNED_BYTE;
1341 state.colorspace = fz_device_rgb (state.ctx);
1342 break;
1343 case 1:
1344 state.texiform = GL_RGBA8;
1345 state.texform = GL_BGRA;
1346 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1347 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1348 #else
1349 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1350 #endif
1351 state.colorspace = fz_device_bgr (state.ctx);
1352 break;
1353 case 2:
1354 state.texiform = GL_LUMINANCE_ALPHA;
1355 state.texform = GL_LUMINANCE_ALPHA;
1356 state.texty = GL_UNSIGNED_BYTE;
1357 state.colorspace = fz_device_gray (state.ctx);
1358 break;
1359 default:
1360 errx (1, "invalid colorspce %d", colorspace);
1364 static void realloctexts (int texcount)
1366 size_t size;
1368 if (texcount == state.texcount) return;
1370 if (texcount < state.texcount) {
1371 glDeleteTextures (state.texcount - texcount,
1372 state.texids + texcount);
1375 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1376 state.texids = realloc (state.texids, size);
1377 if (!state.texids) {
1378 err (1, "realloc texs %zu", size);
1381 state.texowners = (void *) (state.texids + texcount);
1382 if (texcount > state.texcount) {
1383 glGenTextures (texcount - state.texcount,
1384 state.texids + state.texcount);
1385 for (int i = state.texcount; i < texcount; ++i) {
1386 state.texowners[i].w = -1;
1387 state.texowners[i].slice = NULL;
1390 state.texcount = texcount;
1391 state.texindex = 0;
1394 static char *mbtoutf8 (char *s)
1396 char *p, *r;
1397 wchar_t *tmp;
1398 size_t i, ret, len;
1400 if (state.utf8cs) {
1401 return s;
1404 len = mbstowcs (NULL, s, strlen (s));
1405 if (len == 0) {
1406 return s;
1408 else {
1409 if (len == (size_t) -1) {
1410 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1411 return s;
1415 tmp = calloc (len, sizeof (wchar_t));
1416 if (!tmp) {
1417 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1418 len, sizeof (wchar_t), errno, strerror (errno));
1419 return s;
1422 ret = mbstowcs (tmp, s, len);
1423 if (ret == (size_t) -1) {
1424 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1425 len, errno, strerror (errno));
1426 free (tmp);
1427 return s;
1430 len = 0;
1431 for (i = 0; i < ret; ++i) {
1432 len += fz_runelen (tmp[i]);
1435 p = r = malloc (len + 1);
1436 if (!r) {
1437 printd ("emsg mbtoutf8: malloc(%zu)", len);
1438 free (tmp);
1439 return s;
1442 for (i = 0; i < ret; ++i) {
1443 p += fz_runetochar (p, tmp[i]);
1445 *p = 0;
1446 free (tmp);
1447 return r;
1450 CAMLprim value ml_mbtoutf8 (value s_v)
1452 CAMLparam1 (s_v);
1453 CAMLlocal1 (ret_v);
1454 char *s, *r;
1456 s = String_val (s_v);
1457 r = mbtoutf8 (s);
1458 if (r == s) {
1459 ret_v = s_v;
1461 else {
1462 ret_v = caml_copy_string (r);
1463 free (r);
1465 CAMLreturn (ret_v);
1468 static void * mainloop (void UNUSED_ATTR *unused)
1470 char *p = NULL;
1471 int len, ret, oldlen = 0;
1473 fz_var (p);
1474 fz_var (oldlen);
1475 for (;;) {
1476 len = readlen (state.csock);
1477 if (len == 0) {
1478 errx (1, "readlen returned 0");
1481 if (oldlen < len + 1) {
1482 p = realloc (p, len + 1);
1483 if (!p) {
1484 err (1, "realloc %d failed", len + 1);
1486 oldlen = len + 1;
1488 readdata (state.csock, p, len);
1489 p[len] = 0;
1491 if (!strncmp ("open", p, 4)) {
1492 int off, usedoccss, ok = 0, layouth;
1493 char *password;
1494 char *filename;
1495 char *utf8filename;
1496 size_t filenamelen;
1498 fz_var (ok);
1499 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1500 if (ret != 2) {
1501 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1504 filename = p + 5 + off;
1505 filenamelen = strlen (filename);
1506 password = filename + filenamelen + 1;
1508 if (password[strlen (password) + 1]) {
1509 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1512 lock ("open");
1513 fz_set_use_document_css (state.ctx, usedoccss);
1514 fz_try (state.ctx) {
1515 ok = openxref (filename, password, layouth);
1517 fz_catch (state.ctx) {
1518 utf8filename = mbtoutf8 (filename);
1519 printd ("msg Could not open %s", utf8filename);
1520 if (utf8filename != filename) {
1521 free (utf8filename);
1524 if (ok) {
1525 docinfo ();
1526 initpdims ();
1528 unlock ("open");
1530 if (ok) {
1531 utf8filename = mbtoutf8 (filename);
1532 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1533 if (utf8filename != filename) {
1534 free (utf8filename);
1536 state.needoutline = 1;
1539 else if (!strncmp ("cs", p, 2)) {
1540 int i, colorspace;
1542 ret = sscanf (p + 2, " %d", &colorspace);
1543 if (ret != 1) {
1544 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1546 lock ("cs");
1547 set_tex_params (colorspace);
1548 for (i = 0; i < state.texcount; ++i) {
1549 state.texowners[i].w = -1;
1550 state.texowners[i].slice = NULL;
1552 unlock ("cs");
1554 else if (!strncmp ("freepage", p, 8)) {
1555 void *ptr;
1557 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1558 if (ret != 1) {
1559 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1561 lock ("freepage");
1562 freepage (ptr);
1563 unlock ("freepage");
1565 else if (!strncmp ("freetile", p, 8)) {
1566 void *ptr;
1568 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1569 if (ret != 1) {
1570 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1572 lock ("freetile");
1573 freetile (ptr);
1574 unlock ("freetile");
1576 else if (!strncmp ("search", p, 6)) {
1577 int icase, pageno, y, len2, forward;
1578 char *pattern;
1579 regex_t re;
1581 ret = sscanf (p + 6, " %d %d %d %d,%n",
1582 &icase, &pageno, &y, &forward, &len2);
1583 if (ret != 4) {
1584 errx (1, "malformed search `%s' ret=%d", p, ret);
1587 pattern = p + 6 + len2;
1588 ret = regcomp (&re, pattern,
1589 REG_EXTENDED | (icase ? REG_ICASE : 0));
1590 if (ret) {
1591 char errbuf[80];
1592 size_t size;
1594 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1595 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1597 else {
1598 search (&re, pageno, y, forward);
1599 regfree (&re);
1602 else if (!strncmp ("geometry", p, 8)) {
1603 int w, h, fitmodel;
1605 printd ("clear");
1606 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1607 if (ret != 3) {
1608 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1611 lock ("geometry");
1612 state.h = h;
1613 if (w != state.w) {
1614 state.w = w;
1615 for (int i = 0; i < state.texcount; ++i) {
1616 state.texowners[i].slice = NULL;
1619 state.fitmodel = fitmodel;
1620 layout ();
1621 process_outline ();
1623 state.gen++;
1624 unlock ("geometry");
1625 printd ("continue %d", state.pagecount);
1627 else if (!strncmp ("reqlayout", p, 9)) {
1628 char *nameddest;
1629 int rotate, off, h;
1630 int fitmodel;
1631 pdf_document *pdf;
1633 printd ("clear");
1634 ret = sscanf (p + 9, " %d %d %d %n",
1635 &rotate, &fitmodel, &h, &off);
1636 if (ret != 3) {
1637 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1639 lock ("reqlayout");
1640 pdf = pdf_specifics (state.ctx, state.doc);
1641 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1642 state.gen += 1;
1644 state.rotate = rotate;
1645 state.fitmodel = fitmodel;
1646 state.h = h;
1647 layout ();
1648 process_outline ();
1650 nameddest = p + 9 + off;
1651 if (pdf && nameddest && *nameddest) {
1652 fz_point xy;
1653 struct pagedim *pdim;
1654 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1655 &xy.x, &xy.y);
1656 pdim = pdimofpageno (pageno);
1657 fz_transform_point (&xy, &pdim->ctm);
1658 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1661 state.gen++;
1662 unlock ("reqlayout");
1663 printd ("continue %d", state.pagecount);
1665 else if (!strncmp ("page", p, 4)) {
1666 double a, b;
1667 struct page *page;
1668 int pageno, pindex;
1670 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1671 if (ret != 2) {
1672 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1675 lock ("page");
1676 a = now ();
1677 page = loadpage (pageno, pindex);
1678 b = now ();
1679 unlock ("page");
1681 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1683 else if (!strncmp ("tile", p, 4)) {
1684 int x, y, w, h;
1685 struct page *page;
1686 struct tile *tile;
1687 double a, b;
1688 void *data;
1690 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1691 (uintptr_t *) &page, &x, &y, &w, &h,
1692 (uintptr_t *) &data);
1693 if (ret != 6) {
1694 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1697 lock ("tile");
1698 a = now ();
1699 tile = rendertile (page, x, y, w, h, data);
1700 b = now ();
1701 unlock ("tile");
1703 printd ("tile %d %d %" PRIxPTR " %u %f",
1704 x, y, (uintptr_t) (tile),
1705 tile->w * tile->h * tile->pixmap->n,
1706 b - a);
1708 else if (!strncmp ("trimset", p, 7)) {
1709 fz_irect fuzz;
1710 int trimmargins;
1712 ret = sscanf (p + 7, " %d %d %d %d %d",
1713 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1714 if (ret != 5) {
1715 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1717 lock ("trimset");
1718 state.trimmargins = trimmargins;
1719 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1720 state.trimanew = 1;
1721 state.trimfuzz = fuzz;
1723 unlock ("trimset");
1725 else if (!strncmp ("settrim", p, 7)) {
1726 fz_irect fuzz;
1727 int trimmargins;
1729 ret = sscanf (p + 7, " %d %d %d %d %d",
1730 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1731 if (ret != 5) {
1732 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1734 printd ("clear");
1735 lock ("settrim");
1736 state.trimmargins = trimmargins;
1737 state.needoutline = 1;
1738 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1739 state.trimanew = 1;
1740 state.trimfuzz = fuzz;
1742 state.pagedimcount = 0;
1743 free (state.pagedims);
1744 state.pagedims = NULL;
1745 initpdims ();
1746 layout ();
1747 process_outline ();
1748 unlock ("settrim");
1749 printd ("continue %d", state.pagecount);
1751 else if (!strncmp ("sliceh", p, 6)) {
1752 int h;
1754 ret = sscanf (p + 6, " %d", &h);
1755 if (ret != 1) {
1756 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1758 if (h != state.sliceheight) {
1759 state.sliceheight = h;
1760 for (int i = 0; i < state.texcount; ++i) {
1761 state.texowners[i].w = -1;
1762 state.texowners[i].h = -1;
1763 state.texowners[i].slice = NULL;
1767 else if (!strncmp ("interrupt", p, 9)) {
1768 printd ("vmsg interrupted");
1770 else {
1771 errx (1, "unknown command %.*s", len, p);
1774 return 0;
1777 CAMLprim value ml_isexternallink (value uri_v)
1779 CAMLparam1 (uri_v);
1780 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1781 CAMLreturn (Val_bool (ext));
1784 CAMLprim value ml_uritolocation (value uri_v)
1786 CAMLparam1 (uri_v);
1787 CAMLlocal1 (ret_v);
1788 int pageno;
1789 fz_point xy;
1790 struct pagedim *pdim;
1792 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1793 &xy.x, &xy.y);
1794 pdim = pdimofpageno (pageno);
1795 fz_transform_point (&xy, &pdim->ctm);
1796 ret_v = caml_alloc_tuple (3);
1797 Field (ret_v, 0) = Val_int (pageno);
1798 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1799 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1800 CAMLreturn (ret_v);
1803 CAMLprim value ml_realloctexts (value texcount_v)
1805 CAMLparam1 (texcount_v);
1806 int ok;
1808 if (trylock (__func__)) {
1809 ok = 0;
1810 goto done;
1812 realloctexts (Int_val (texcount_v));
1813 ok = 1;
1814 unlock (__func__);
1816 done:
1817 CAMLreturn (Val_bool (ok));
1820 static void recti (int x0, int y0, int x1, int y1)
1822 GLfloat *v = state.vertices;
1824 glVertexPointer (2, GL_FLOAT, 0, v);
1825 v[0] = x0; v[1] = y0;
1826 v[2] = x1; v[3] = y0;
1827 v[4] = x0; v[5] = y1;
1828 v[6] = x1; v[7] = y1;
1829 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1832 static void showsel (struct page *page, int ox, int oy)
1834 fz_irect bbox;
1835 fz_rect rect;
1836 fz_stext_block *block;
1837 int seen = 0;
1838 unsigned char selcolor[] = {15,15,15,140};
1840 if (!page->fmark || !page->lmark) return;
1842 glEnable (GL_BLEND);
1843 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1844 glColor4ubv (selcolor);
1846 ox += state.pagedims[page->pdimno].bounds.x0;
1847 oy += state.pagedims[page->pdimno].bounds.y0;
1849 for (block = page->text->first_block; block; block = block->next) {
1850 fz_stext_line *line;
1852 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1853 for (line = block->u.t.first_line; line; line = line->next) {
1854 fz_stext_char *ch;
1856 rect = fz_empty_rect;
1857 for (ch = line->first_char; ch; ch = ch->next) {
1858 if (ch == page->fmark) seen = 1;
1859 if (seen) fz_union_rect (&rect, &ch->bbox);
1860 if (ch == page->lmark) {
1861 fz_round_rect (&bbox, &rect);
1862 recti (bbox.x0 + ox, bbox.y0 + oy,
1863 bbox.x1 + ox, bbox.y1 + oy);
1864 goto done;
1867 fz_round_rect (&bbox, &rect);
1868 recti (bbox.x0 + ox, bbox.y0 + oy,
1869 bbox.x1 + ox, bbox.y1 + oy);
1872 done:
1873 glDisable (GL_BLEND);
1876 #pragma GCC diagnostic push
1877 #pragma GCC diagnostic ignored "-Wconversion"
1878 #include "glfont.c"
1879 #pragma GCC diagnostic pop
1881 static void stipplerect (fz_matrix *m,
1882 fz_point *p1,
1883 fz_point *p2,
1884 fz_point *p3,
1885 fz_point *p4,
1886 GLfloat *texcoords,
1887 GLfloat *vertices)
1889 fz_transform_point (p1, m);
1890 fz_transform_point (p2, m);
1891 fz_transform_point (p3, m);
1892 fz_transform_point (p4, m);
1894 float w, h, s, t;
1896 w = p2->x - p1->x;
1897 h = p2->y - p1->y;
1898 t = hypotf (w, h) * .25f;
1900 w = p3->x - p2->x;
1901 h = p3->y - p2->y;
1902 s = hypotf (w, h) * .25f;
1904 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
1905 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
1907 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
1908 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
1910 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
1911 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
1913 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
1914 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
1916 glDrawArrays (GL_LINES, 0, 8);
1919 static void solidrect (fz_matrix *m,
1920 fz_point *p1,
1921 fz_point *p2,
1922 fz_point *p3,
1923 fz_point *p4,
1924 GLfloat *vertices)
1926 fz_transform_point (p1, m);
1927 fz_transform_point (p2, m);
1928 fz_transform_point (p3, m);
1929 fz_transform_point (p4, m);
1930 vertices[0] = p1->x; vertices[1] = p1->y;
1931 vertices[2] = p2->x; vertices[3] = p2->y;
1933 vertices[4] = p3->x; vertices[5] = p3->y;
1934 vertices[6] = p4->x; vertices[7] = p4->y;
1935 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1938 static void ensurelinks (struct page *page)
1940 if (!page->links)
1941 page->links = fz_load_links (state.ctx, page->fzpage);
1944 static void highlightlinks (struct page *page, int xoff, int yoff)
1946 fz_matrix ctm, tm, pm;
1947 fz_link *link;
1948 GLfloat *texcoords = state.texcoords;
1949 GLfloat *vertices = state.vertices;
1951 ensurelinks (page);
1953 glEnable (GL_TEXTURE_1D);
1954 glEnable (GL_BLEND);
1955 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1956 glBindTexture (GL_TEXTURE_1D, state.stid);
1958 xoff -= state.pagedims[page->pdimno].bounds.x0;
1959 yoff -= state.pagedims[page->pdimno].bounds.y0;
1960 fz_translate (&tm, xoff, yoff);
1961 pm = pagectm (page);
1962 fz_concat (&ctm, &pm, &tm);
1964 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1965 glVertexPointer (2, GL_FLOAT, 0, vertices);
1967 for (link = page->links; link; link = link->next) {
1968 fz_point p1, p2, p3, p4;
1970 p1.x = link->rect.x0;
1971 p1.y = link->rect.y0;
1973 p2.x = link->rect.x1;
1974 p2.y = link->rect.y0;
1976 p3.x = link->rect.x1;
1977 p3.y = link->rect.y1;
1979 p4.x = link->rect.x0;
1980 p4.y = link->rect.y1;
1982 /* TODO: different colours for different schemes */
1983 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1984 else glColor3ub (255, 0, 0);
1986 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
1989 for (int i = 0; i < page->annotcount; ++i) {
1990 fz_point p1, p2, p3, p4;
1991 struct annot *annot = &page->annots[i];
1993 p1.x = annot->bbox.x0;
1994 p1.y = annot->bbox.y0;
1996 p2.x = annot->bbox.x1;
1997 p2.y = annot->bbox.y0;
1999 p3.x = annot->bbox.x1;
2000 p3.y = annot->bbox.y1;
2002 p4.x = annot->bbox.x0;
2003 p4.y = annot->bbox.y1;
2005 glColor3ub (0, 0, 128);
2006 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2009 glDisable (GL_BLEND);
2010 glDisable (GL_TEXTURE_1D);
2013 static int compareslinks (const void *l, const void *r)
2015 struct slink const *ls = l;
2016 struct slink const *rs = r;
2017 if (ls->bbox.y0 == rs->bbox.y0) {
2018 return rs->bbox.x0 - rs->bbox.x0;
2020 return ls->bbox.y0 - rs->bbox.y0;
2023 static void droptext (struct page *page)
2025 if (page->text) {
2026 fz_drop_stext_page (state.ctx, page->text);
2027 page->fmark = NULL;
2028 page->lmark = NULL;
2029 page->text = NULL;
2033 static void dropannots (struct page *page)
2035 if (page->annots) {
2036 free (page->annots);
2037 page->annots = NULL;
2038 page->annotcount = 0;
2042 static void ensureannots (struct page *page)
2044 int i, count = 0;
2045 size_t annotsize = sizeof (*page->annots);
2046 fz_annot *annot;
2048 if (state.gen != page->agen) {
2049 dropannots (page);
2050 page->agen = state.gen;
2052 if (page->annots) return;
2054 for (annot = fz_first_annot (state.ctx, page->fzpage);
2055 annot;
2056 annot = fz_next_annot (state.ctx, annot)) {
2057 count++;
2060 if (count > 0) {
2061 page->annotcount = count;
2062 page->annots = calloc (count, annotsize);
2063 if (!page->annots) {
2064 err (1, "calloc annots %d", count);
2067 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2068 annot;
2069 annot = fz_next_annot (state.ctx, annot), i++) {
2070 fz_rect rect;
2072 fz_bound_annot (state.ctx, annot, &rect);
2073 page->annots[i].annot = annot;
2074 fz_round_rect (&page->annots[i].bbox, &rect);
2079 static void dropslinks (struct page *page)
2081 if (page->slinks) {
2082 free (page->slinks);
2083 page->slinks = NULL;
2084 page->slinkcount = 0;
2086 if (page->links) {
2087 fz_drop_link (state.ctx, page->links);
2088 page->links = NULL;
2092 static void ensureslinks (struct page *page)
2094 fz_matrix ctm;
2095 int i, count;
2096 size_t slinksize = sizeof (*page->slinks);
2097 fz_link *link;
2099 ensureannots (page);
2100 if (state.gen != page->sgen) {
2101 dropslinks (page);
2102 page->sgen = state.gen;
2104 if (page->slinks) return;
2106 ensurelinks (page);
2107 ctm = pagectm (page);
2109 count = page->annotcount;
2110 for (link = page->links; link; link = link->next) {
2111 count++;
2113 if (count > 0) {
2114 int j;
2116 page->slinkcount = count;
2117 page->slinks = calloc (count, slinksize);
2118 if (!page->slinks) {
2119 err (1, "calloc slinks %d", count);
2122 for (i = 0, link = page->links; link; ++i, link = link->next) {
2123 fz_rect rect;
2125 rect = link->rect;
2126 fz_transform_rect (&rect, &ctm);
2127 page->slinks[i].tag = SLINK;
2128 page->slinks[i].u.link = link;
2129 fz_round_rect (&page->slinks[i].bbox, &rect);
2131 for (j = 0; j < page->annotcount; ++j, ++i) {
2132 fz_rect rect;
2133 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2134 fz_transform_rect (&rect, &ctm);
2135 fz_round_rect (&page->slinks[i].bbox, &rect);
2137 page->slinks[i].tag = SANNOT;
2138 page->slinks[i].u.annot = page->annots[j].annot;
2140 qsort (page->slinks, count, slinksize, compareslinks);
2144 static void highlightslinks (struct page *page, int xoff, int yoff,
2145 int noff, char *targ, mlsize_t tlen, int hfsize)
2147 char buf[40];
2148 struct slink *slink;
2149 float x0, y0, x1, y1, w;
2151 ensureslinks (page);
2152 glColor3ub (0xc3, 0xb0, 0x91);
2153 for (int i = 0; i < page->slinkcount; ++i) {
2154 fmt_linkn (buf, i + noff);
2155 if (!tlen || !strncmp (targ, buf, tlen)) {
2156 slink = &page->slinks[i];
2158 x0 = slink->bbox.x0 + xoff - 5;
2159 y1 = slink->bbox.y0 + yoff - 5;
2160 y0 = y1 + 10 + hfsize;
2161 w = measure_string (state.face, hfsize, buf);
2162 x1 = x0 + w + 10;
2163 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2167 glEnable (GL_BLEND);
2168 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2169 glEnable (GL_TEXTURE_2D);
2170 glColor3ub (0, 0, 0);
2171 for (int i = 0; i < page->slinkcount; ++i) {
2172 fmt_linkn (buf, i + noff);
2173 if (!tlen || !strncmp (targ, buf, tlen)) {
2174 slink = &page->slinks[i];
2176 x0 = slink->bbox.x0 + xoff;
2177 y0 = slink->bbox.y0 + yoff + hfsize;
2178 draw_string (state.face, hfsize, x0, y0, buf);
2181 glDisable (GL_TEXTURE_2D);
2182 glDisable (GL_BLEND);
2185 static void uploadslice (struct tile *tile, struct slice *slice)
2187 int offset;
2188 struct slice *slice1;
2189 unsigned char *texdata;
2191 offset = 0;
2192 for (slice1 = tile->slices; slice != slice1; slice1++) {
2193 offset += slice1->h * tile->w * tile->pixmap->n;
2195 if (slice->texindex != -1 && slice->texindex < state.texcount
2196 && state.texowners[slice->texindex].slice == slice) {
2197 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2199 else {
2200 int subimage = 0;
2201 int texindex = state.texindex++ % state.texcount;
2203 if (state.texowners[texindex].w == tile->w) {
2204 if (state.texowners[texindex].h >= slice->h) {
2205 subimage = 1;
2207 else {
2208 state.texowners[texindex].h = slice->h;
2211 else {
2212 state.texowners[texindex].h = slice->h;
2215 state.texowners[texindex].w = tile->w;
2216 state.texowners[texindex].slice = slice;
2217 slice->texindex = texindex;
2219 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2220 #if TEXT_TYPE == GL_TEXTURE_2D
2221 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2222 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2223 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2224 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2225 #endif
2226 if (tile->pbo) {
2227 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2228 texdata = 0;
2230 else {
2231 texdata = tile->pixmap->samples;
2233 if (subimage) {
2234 glTexSubImage2D (TEXT_TYPE,
2238 tile->w,
2239 slice->h,
2240 state.texform,
2241 state.texty,
2242 texdata+offset
2245 else {
2246 glTexImage2D (TEXT_TYPE,
2248 state.texiform,
2249 tile->w,
2250 slice->h,
2252 state.texform,
2253 state.texty,
2254 texdata+offset
2257 if (tile->pbo) {
2258 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2263 CAMLprim void ml_begintiles (value unit_v)
2265 CAMLparam1 (unit_v);
2266 glEnable (TEXT_TYPE);
2267 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2268 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2269 CAMLreturn0;
2272 CAMLprim void ml_endtiles (value unit_v)
2274 CAMLparam1 (unit_v);
2275 glDisable (TEXT_TYPE);
2276 CAMLreturn0;
2279 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2281 CAMLparam2 (args_v, ptr_v);
2282 int dispx = Int_val (Field (args_v, 0));
2283 int dispy = Int_val (Field (args_v, 1));
2284 int dispw = Int_val (Field (args_v, 2));
2285 int disph = Int_val (Field (args_v, 3));
2286 int tilex = Int_val (Field (args_v, 4));
2287 int tiley = Int_val (Field (args_v, 5));
2288 char *s = String_val (ptr_v);
2289 struct tile *tile = parse_pointer (__func__, s);
2290 int slicey, firstslice;
2291 struct slice *slice;
2292 GLfloat *texcoords = state.texcoords;
2293 GLfloat *vertices = state.vertices;
2295 firstslice = tiley / tile->sliceheight;
2296 slice = &tile->slices[firstslice];
2297 slicey = tiley % tile->sliceheight;
2299 while (disph > 0) {
2300 int dh;
2302 dh = slice->h - slicey;
2303 dh = fz_mini (disph, dh);
2304 uploadslice (tile, slice);
2306 texcoords[0] = tilex; texcoords[1] = slicey;
2307 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2308 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2309 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2311 vertices[0] = dispx; vertices[1] = dispy;
2312 vertices[2] = dispx+dispw; vertices[3] = dispy;
2313 vertices[4] = dispx; vertices[5] = dispy+dh;
2314 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2316 #if TEXT_TYPE == GL_TEXTURE_2D
2317 for (int i = 0; i < 8; ++i) {
2318 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2320 #endif
2322 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2323 dispy += dh;
2324 disph -= dh;
2325 slice++;
2326 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2327 slicey = 0;
2329 CAMLreturn0;
2332 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2334 fz_matrix ctm, tm, pm;
2335 fz_point p1, p2, p3, p4;
2336 GLfloat *vertices = state.vertices;
2337 double *v = (double *) rects_v;
2339 xoff -= state.pagedims[page->pdimno].bounds.x0;
2340 yoff -= state.pagedims[page->pdimno].bounds.y0;
2341 fz_translate (&tm, xoff, yoff);
2342 pm = pagectm (page);
2343 fz_concat (&ctm, &pm, &tm);
2345 glEnable (GL_BLEND);
2346 glVertexPointer (2, GL_FLOAT, 0, vertices);
2348 glColor4dv (v);
2349 p1.x = (float) v[4];
2350 p1.y = (float) v[5];
2352 p2.x = (float) v[6];
2353 p2.y = (float) v[5];
2355 p3.x = (float) v[6];
2356 p3.y = (float) v[7];
2358 p4.x = (float) v[4];
2359 p4.y = (float) v[7];
2360 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2361 glDisable (GL_BLEND);
2364 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2365 value xoff_v, value yoff_v,
2366 value li_v)
2368 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2369 int xoff = Int_val (xoff_v);
2370 int yoff = Int_val (yoff_v);
2371 int noff = Int_val (Field (li_v, 0));
2372 char *targ = String_val (Field (li_v, 1));
2373 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2374 int hfsize = Int_val (Field (li_v, 2));
2375 char *s = String_val (ptr_v);
2376 int hlmask = Int_val (hlinks_v);
2377 struct page *page = parse_pointer (__func__, s);
2379 if (!page->fzpage) {
2380 /* deal with loadpage failed pages */
2381 goto done;
2384 if (trylock (__func__)) {
2385 noff = -1;
2386 goto done;
2389 ensureannots (page);
2390 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2391 if (hlmask & 2) {
2392 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2393 noff = page->slinkcount;
2395 if (page->tgen == state.gen) {
2396 showsel (page, xoff, yoff);
2398 unlock (__func__);
2400 done:
2401 CAMLreturn (Val_int (noff));
2404 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2405 value rects_v)
2407 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2408 int xoff = Int_val (xoff_v);
2409 int yoff = Int_val (yoff_v);
2410 char *s = String_val (ptr_v);
2411 struct page *page = parse_pointer (__func__, s);
2413 drawprect (page, xoff, yoff, rects_v);
2414 CAMLreturn0;
2417 static struct annot *getannot (struct page *page, int x, int y)
2419 fz_point p;
2420 fz_matrix ctm;
2421 const fz_matrix *tctm;
2422 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2424 if (!page->annots) return NULL;
2426 if (pdf) {
2427 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2428 tctm = &state.pagedims[page->pdimno].tctm;
2430 else {
2431 tctm = &fz_identity;
2434 p.x = x;
2435 p.y = y;
2437 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2438 fz_invert_matrix (&ctm, &ctm);
2439 fz_transform_point (&p, &ctm);
2441 if (pdf) {
2442 for (int i = 0; i < page->annotcount; ++i) {
2443 struct annot *a = &page->annots[i];
2444 fz_rect rect;
2446 fz_bound_annot (state.ctx, a->annot, &rect);
2447 if (p.x >= rect.x0 && p.x <= rect.x1) {
2448 if (p.y >= rect.y0 && p.y <= rect.y1)
2449 return a;
2453 return NULL;
2456 static fz_link *getlink (struct page *page, int x, int y)
2458 fz_point p;
2459 fz_matrix ctm;
2460 fz_link *link;
2462 ensureslinks (page);
2464 p.x = x;
2465 p.y = y;
2467 ctm = pagectm (page);
2468 fz_invert_matrix (&ctm, &ctm);
2469 fz_transform_point (&p, &ctm);
2471 for (link = page->links; link; link = link->next) {
2472 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2473 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2474 return link;
2478 return NULL;
2481 static void ensuretext (struct page *page)
2483 if (state.gen != page->tgen) {
2484 droptext (page);
2485 page->tgen = state.gen;
2487 if (!page->text) {
2488 fz_matrix ctm;
2489 fz_device *tdev;
2491 page->text = fz_new_stext_page (state.ctx,
2492 &state.pagedims[page->pdimno].mediabox);
2493 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2494 ctm = pagectm (page);
2495 fz_run_display_list (state.ctx, page->dlist,
2496 tdev, &ctm, &fz_infinite_rect, NULL);
2497 fz_close_device (state.ctx, tdev);
2498 fz_drop_device (state.ctx, tdev);
2502 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2504 CAMLparam2 (start_page_v, dir_v);
2505 CAMLlocal1 (ret_v);
2506 int i, dir = Int_val (dir_v);
2507 int start_page = Int_val (start_page_v);
2508 int end_page = dir > 0 ? state.pagecount : -1;
2509 pdf_document *pdf;
2511 fz_var (end_page);
2512 ret_v = Val_int (0);
2513 lock (__func__);
2514 pdf = pdf_specifics (state.ctx, state.doc);
2515 for (i = start_page + dir; i != end_page; i += dir) {
2516 int found;
2518 fz_var (found);
2519 if (pdf) {
2520 pdf_page *page = NULL;
2522 fz_var (page);
2523 fz_try (state.ctx) {
2524 page = pdf_load_page (state.ctx, pdf, i);
2525 found = !!page->links || !!page->annots;
2527 fz_catch (state.ctx) {
2528 found = 0;
2530 if (page) {
2531 fz_drop_page (state.ctx, &page->super);
2534 else {
2535 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2536 fz_link *link = fz_load_links (state.ctx, page);
2537 found = !!link;
2538 fz_drop_link (state.ctx, link);
2539 fz_drop_page (state.ctx, page);
2542 if (found) {
2543 ret_v = caml_alloc_small (1, 1);
2544 Field (ret_v, 0) = Val_int (i);
2545 goto unlock;
2548 unlock:
2549 unlock (__func__);
2550 CAMLreturn (ret_v);
2553 enum { dir_first, dir_last };
2554 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2556 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2558 CAMLparam2 (ptr_v, dir_v);
2559 CAMLlocal2 (ret_v, pos_v);
2560 struct page *page;
2561 int dirtag, i, slinkindex;
2562 struct slink *found = NULL ,*slink;
2563 char *s = String_val (ptr_v);
2565 page = parse_pointer (__func__, s);
2566 ret_v = Val_int (0);
2567 lock (__func__);
2568 ensureslinks (page);
2570 if (Is_block (dir_v)) {
2571 dirtag = Tag_val (dir_v);
2572 switch (dirtag) {
2573 case dir_first_visible:
2575 int x0, y0, dir, first_index, last_index;
2577 pos_v = Field (dir_v, 0);
2578 x0 = Int_val (Field (pos_v, 0));
2579 y0 = Int_val (Field (pos_v, 1));
2580 dir = Int_val (Field (pos_v, 2));
2582 if (dir >= 0) {
2583 dir = 1;
2584 first_index = 0;
2585 last_index = page->slinkcount;
2587 else {
2588 first_index = page->slinkcount - 1;
2589 last_index = -1;
2592 for (i = first_index; i != last_index; i += dir) {
2593 slink = &page->slinks[i];
2594 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2595 found = slink;
2596 break;
2600 break;
2602 case dir_left:
2603 slinkindex = Int_val (Field (dir_v, 0));
2604 found = &page->slinks[slinkindex];
2605 for (i = slinkindex - 1; i >= 0; --i) {
2606 slink = &page->slinks[i];
2607 if (slink->bbox.x0 < found->bbox.x0) {
2608 found = slink;
2609 break;
2612 break;
2614 case dir_right:
2615 slinkindex = Int_val (Field (dir_v, 0));
2616 found = &page->slinks[slinkindex];
2617 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2618 slink = &page->slinks[i];
2619 if (slink->bbox.x0 > found->bbox.x0) {
2620 found = slink;
2621 break;
2624 break;
2626 case dir_down:
2627 slinkindex = Int_val (Field (dir_v, 0));
2628 found = &page->slinks[slinkindex];
2629 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2630 slink = &page->slinks[i];
2631 if (slink->bbox.y0 >= found->bbox.y0) {
2632 found = slink;
2633 break;
2636 break;
2638 case dir_up:
2639 slinkindex = Int_val (Field (dir_v, 0));
2640 found = &page->slinks[slinkindex];
2641 for (i = slinkindex - 1; i >= 0; --i) {
2642 slink = &page->slinks[i];
2643 if (slink->bbox.y0 <= found->bbox.y0) {
2644 found = slink;
2645 break;
2648 break;
2651 else {
2652 dirtag = Int_val (dir_v);
2653 switch (dirtag) {
2654 case dir_first:
2655 found = page->slinks;
2656 break;
2658 case dir_last:
2659 if (page->slinks) {
2660 found = page->slinks + (page->slinkcount - 1);
2662 break;
2665 if (found) {
2666 ret_v = caml_alloc_small (2, 1);
2667 Field (ret_v, 0) = Val_int (found - page->slinks);
2670 unlock (__func__);
2671 CAMLreturn (ret_v);
2674 enum { uuri, utext, uannot };
2676 CAMLprim value ml_getlink (value ptr_v, value n_v)
2678 CAMLparam2 (ptr_v, n_v);
2679 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2680 fz_link *link;
2681 struct page *page;
2682 char *s = String_val (ptr_v);
2683 struct slink *slink;
2685 ret_v = Val_int (0);
2686 page = parse_pointer (__func__, s);
2688 lock (__func__);
2689 ensureslinks (page);
2690 slink = &page->slinks[Int_val (n_v)];
2691 if (slink->tag == SLINK) {
2692 link = slink->u.link;
2693 str_v = caml_copy_string (link->uri);
2694 ret_v = caml_alloc_small (1, uuri);
2695 Field (ret_v, 0) = str_v;
2697 else {
2698 ret_v = caml_alloc_small (1, uannot);
2699 tup_v = caml_alloc_tuple (2);
2700 Field (ret_v, 0) = tup_v;
2701 Field (tup_v, 0) = ptr_v;
2702 Field (tup_v, 1) = n_v;
2704 unlock (__func__);
2706 CAMLreturn (ret_v);
2709 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2711 CAMLparam2 (ptr_v, n_v);
2712 CAMLlocal1 (ret_v);
2713 pdf_document *pdf;
2714 char *contents = NULL;
2716 lock (__func__);
2717 pdf = pdf_specifics (state.ctx, state.doc);
2718 if (pdf) {
2719 char *s = String_val (ptr_v);
2720 struct page *page;
2721 struct slink *slink;
2723 page = parse_pointer (__func__, s);
2724 slink = &page->slinks[Int_val (n_v)];
2725 contents = pdf_copy_annot_contents (state.ctx,
2726 (pdf_annot *) slink->u.annot);
2728 unlock (__func__);
2729 if (contents) {
2730 ret_v = caml_copy_string (contents);
2731 fz_free (state.ctx, contents);
2733 else {
2734 ret_v = caml_copy_string ("");
2736 CAMLreturn (ret_v);
2739 CAMLprim value ml_getlinkcount (value ptr_v)
2741 CAMLparam1 (ptr_v);
2742 struct page *page;
2743 char *s = String_val (ptr_v);
2745 page = parse_pointer (__func__, s);
2746 CAMLreturn (Val_int (page->slinkcount));
2749 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2751 CAMLparam2 (ptr_v, n_v);
2752 CAMLlocal1 (ret_v);
2753 struct page *page;
2754 struct slink *slink;
2755 char *s = String_val (ptr_v);
2757 page = parse_pointer (__func__, s);
2758 ret_v = caml_alloc_tuple (4);
2759 lock (__func__);
2760 ensureslinks (page);
2762 slink = &page->slinks[Int_val (n_v)];
2763 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2764 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2765 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2766 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2767 unlock (__func__);
2768 CAMLreturn (ret_v);
2771 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2773 CAMLparam3 (ptr_v, x_v, y_v);
2774 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2775 fz_link *link;
2776 struct annot *annot;
2777 struct page *page;
2778 char *ptr = String_val (ptr_v);
2779 int x = Int_val (x_v), y = Int_val (y_v);
2780 struct pagedim *pdim;
2782 ret_v = Val_int (0);
2783 if (trylock (__func__)) {
2784 goto done;
2787 page = parse_pointer (__func__, ptr);
2788 pdim = &state.pagedims[page->pdimno];
2789 x += pdim->bounds.x0;
2790 y += pdim->bounds.y0;
2793 annot = getannot (page, x, y);
2794 if (annot) {
2795 int i, n = -1;
2797 ensureslinks (page);
2798 for (i = 0; i < page->slinkcount; ++i) {
2799 if (page->slinks[i].tag == SANNOT
2800 && page->slinks[i].u.annot == annot->annot) {
2801 n = i;
2802 break;
2805 ret_v = caml_alloc_small (1, uannot);
2806 tup_v = caml_alloc_tuple (2);
2807 Field (ret_v, 0) = tup_v;
2808 Field (tup_v, 0) = ptr_v;
2809 Field (tup_v, 1) = Val_int (n);
2810 goto unlock;
2814 link = getlink (page, x, y);
2815 if (link) {
2816 str_v = caml_copy_string (link->uri);
2817 ret_v = caml_alloc_small (1, uuri);
2818 Field (ret_v, 0) = str_v;
2820 else {
2821 fz_rect *b;
2822 fz_stext_block *block;
2824 ensuretext (page);
2826 for (block = page->text->first_block; block; block = block->next) {
2827 fz_stext_line *line;
2829 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2830 b = &block->bbox;
2831 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2832 continue;
2834 for (line = block->u.t.first_line; line; line = line->next) {
2835 fz_stext_char *ch;
2837 b = &line->bbox;
2838 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2839 continue;
2841 for (ch = line->first_char; ch; ch = ch->next) {
2842 b = &ch->bbox;
2844 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
2845 const char *n2 = fz_font_name (state.ctx, ch->font);
2846 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2847 ch->font);
2849 if (!n2) n2 = "<unknown font>";
2851 if (face && face->family_name) {
2852 char *s;
2853 char *n1 = face->family_name;
2854 size_t l1 = strlen (n1);
2855 size_t l2 = strlen (n2);
2857 if (l1 != l2 || memcmp (n1, n2, l1)) {
2858 s = malloc (l1 + l2 + 2);
2859 if (s) {
2860 memcpy (s, n2, l2);
2861 s[l2] = '=';
2862 memcpy (s + l2 + 1, n1, l1 + 1);
2863 str_v = caml_copy_string (s);
2864 free (s);
2868 if (str_v == Val_unit) {
2869 str_v = caml_copy_string (n2);
2871 ret_v = caml_alloc_small (1, utext);
2872 Field (ret_v, 0) = str_v;
2873 goto unlock;
2879 unlock:
2880 unlock (__func__);
2882 done:
2883 CAMLreturn (ret_v);
2886 enum { mark_page, mark_block, mark_line, mark_word };
2888 CAMLprim void ml_clearmark (value ptr_v)
2890 CAMLparam1 (ptr_v);
2891 char *s = String_val (ptr_v);
2892 struct page *page;
2894 if (trylock (__func__)) {
2895 goto done;
2898 page = parse_pointer (__func__, s);
2899 page->fmark = NULL;
2900 page->lmark = NULL;
2902 unlock (__func__);
2903 done:
2904 CAMLreturn0;
2907 static int uninteresting (int c)
2909 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
2910 || ispunct (c);
2913 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2915 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2916 CAMLlocal1 (ret_v);
2917 fz_rect *b;
2918 struct page *page;
2919 fz_stext_line *line;
2920 fz_stext_block *block;
2921 struct pagedim *pdim;
2922 int mark = Int_val (mark_v);
2923 char *s = String_val (ptr_v);
2924 int x = Int_val (x_v), y = Int_val (y_v);
2926 ret_v = Val_bool (0);
2927 if (trylock (__func__)) {
2928 goto done;
2931 page = parse_pointer (__func__, s);
2932 pdim = &state.pagedims[page->pdimno];
2934 ensuretext (page);
2936 if (mark == mark_page) {
2937 page->fmark = page->text->first_block->u.t.first_line->first_char;
2938 page->lmark = page->text->last_block->u.t.last_line->last_char;
2939 ret_v = Val_bool (1);
2940 goto unlock;
2943 x += pdim->bounds.x0;
2944 y += pdim->bounds.y0;
2946 for (block = page->text->first_block; block; block = block->next) {
2947 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2948 b = &block->bbox;
2949 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2950 continue;
2952 if (mark == mark_block) {
2953 page->fmark = block->u.t.first_line->first_char;
2954 page->lmark = block->u.t.last_line->last_char;
2955 ret_v = Val_bool (1);
2956 goto unlock;
2959 for (line = block->u.t.first_line; line; line = line->next) {
2960 fz_stext_char *ch;
2962 b = &line->bbox;
2963 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2964 continue;
2966 if (mark == mark_line) {
2967 page->fmark = line->first_char;
2968 page->lmark = line->last_char;
2969 ret_v = Val_bool (1);
2970 goto unlock;
2973 for (ch = line->first_char; ch; ch = ch->next) {
2974 fz_stext_char *ch2, *first = NULL, *last = NULL;
2975 b = &ch->bbox;
2976 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
2977 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2978 if (uninteresting (ch2->c)) first = NULL;
2979 else if (!first) first = ch2;
2981 for (ch2 = ch; ch2; ch2 = ch2->next) {
2982 if (uninteresting (ch2->c)) break;
2983 last = ch2;
2986 page->fmark = first;
2987 page->lmark = last;
2988 ret_v = Val_bool (1);
2989 goto unlock;
2994 unlock:
2995 if (!Bool_val (ret_v)) {
2996 page->fmark = NULL;
2997 page->lmark = NULL;
2999 unlock (__func__);
3001 done:
3002 CAMLreturn (ret_v);
3005 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3007 CAMLparam3 (ptr_v, x_v, y_v);
3008 CAMLlocal2 (ret_v, res_v);
3009 fz_rect *b = NULL;
3010 struct page *page;
3011 struct pagedim *pdim;
3012 fz_stext_block *block;
3013 char *s = String_val (ptr_v);
3014 int x = Int_val (x_v), y = Int_val (y_v);
3016 ret_v = Val_int (0);
3017 if (trylock (__func__)) {
3018 goto done;
3021 page = parse_pointer (__func__, s);
3022 pdim = &state.pagedims[page->pdimno];
3023 x += pdim->bounds.x0;
3024 y += pdim->bounds.y0;
3026 ensuretext (page);
3028 for (block = page->text->first_block; block; block = block->next) {
3029 switch (block->type) {
3030 case FZ_STEXT_BLOCK_TEXT:
3031 b = &block->bbox;
3032 break;
3034 case FZ_STEXT_BLOCK_IMAGE:
3035 b = &block->bbox;
3036 break;
3038 default:
3039 continue;
3042 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3043 break;
3044 b = NULL;
3046 if (b) {
3047 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3048 ret_v = caml_alloc_small (1, 1);
3049 Store_double_field (res_v, 0, (double) b->x0);
3050 Store_double_field (res_v, 1, (double) b->x1);
3051 Store_double_field (res_v, 2, (double) b->y0);
3052 Store_double_field (res_v, 3, (double) b->y1);
3053 Field (ret_v, 0) = res_v;
3055 unlock (__func__);
3057 done:
3058 CAMLreturn (ret_v);
3061 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3063 CAMLparam2 (ptr_v, rect_v);
3064 fz_rect b;
3065 struct page *page;
3066 struct pagedim *pdim;
3067 char *s = String_val (ptr_v);
3068 int x0, x1, y0, y1;
3069 fz_stext_char *ch;
3070 fz_stext_line *line;
3071 fz_stext_block *block;
3072 fz_stext_char *fc, *lc;
3074 if (trylock (__func__)) {
3075 goto done;
3078 page = parse_pointer (__func__, s);
3079 ensuretext (page);
3081 pdim = &state.pagedims[page->pdimno];
3082 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3083 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3084 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3085 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3087 if (y0 > y1) {
3088 int t = y0;
3089 y0 = y1;
3090 y1 = t;
3091 x0 = x1;
3092 x1 = t;
3095 fc = page->fmark;
3096 lc = page->lmark;
3098 for (block = page->text->first_block; block; block = block->next) {
3099 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3100 for (line = block->u.t.first_line; line; line = line->next) {
3101 for (ch = line->first_char; ch; ch = ch->next) {
3102 b = ch->bbox;
3103 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3104 fc = ch;
3106 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3107 lc = ch;
3112 if (x1 < x0 && fc == lc) {
3113 fz_stext_char *t;
3115 t = fc;
3116 fc = lc;
3117 lc = t;
3120 page->fmark = fc;
3121 page->lmark = lc;
3123 unlock (__func__);
3125 done:
3126 CAMLreturn0;
3129 static int pipechar (FILE *f, fz_stext_char *ch)
3131 char buf[4];
3132 int len;
3133 size_t ret;
3135 len = fz_runetochar (buf, ch->c);
3136 ret = fwrite (buf, len, 1, f);
3137 if (ret != 1) {
3138 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3139 len, ret, errno, strerror (errno));
3140 return -1;
3142 return 0;
3145 CAMLprim value ml_spawn (value command_v, value fds_v)
3147 CAMLparam2 (command_v, fds_v);
3148 CAMLlocal2 (l_v, tup_v);
3149 int ret, ret1;
3150 pid_t pid = (pid_t) -1;
3151 char *msg = NULL;
3152 value earg_v = Nothing;
3153 posix_spawnattr_t attr;
3154 posix_spawn_file_actions_t fa;
3155 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3157 argv[2] = String_val (command_v);
3159 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3160 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3163 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3164 msg = "posix_spawnattr_init";
3165 goto fail1;
3168 #ifdef POSIX_SPAWN_USEVFORK
3169 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3170 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3171 goto fail;
3173 #endif
3175 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3176 int fd1, fd2;
3178 tup_v = Field (l_v, 0);
3179 fd1 = Int_val (Field (tup_v, 0));
3180 fd2 = Int_val (Field (tup_v, 1));
3181 if (fd2 < 0) {
3182 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3183 msg = "posix_spawn_file_actions_addclose";
3184 earg_v = tup_v;
3185 goto fail;
3188 else {
3189 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3190 msg = "posix_spawn_file_actions_adddup2";
3191 earg_v = tup_v;
3192 goto fail;
3197 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3198 msg = "posix_spawn";
3199 goto fail;
3202 fail:
3203 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3204 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3207 fail1:
3208 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3209 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3210 ret1, strerror (ret1));
3213 if (msg)
3214 unix_error (ret, msg, earg_v);
3216 CAMLreturn (Val_int (pid));
3219 CAMLprim value ml_hassel (value ptr_v)
3221 CAMLparam1 (ptr_v);
3222 CAMLlocal1 (ret_v);
3223 struct page *page;
3224 char *s = String_val (ptr_v);
3226 ret_v = Val_bool (0);
3227 if (trylock (__func__)) {
3228 goto done;
3231 page = parse_pointer (__func__, s);
3232 ret_v = Val_bool (page->fmark && page->lmark);
3233 unlock (__func__);
3234 done:
3235 CAMLreturn (ret_v);
3238 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3240 CAMLparam2 (fd_v, ptr_v);
3241 FILE *f;
3242 int seen = 0;
3243 struct page *page;
3244 fz_stext_line *line;
3245 fz_stext_block *block;
3246 int fd = Int_val (fd_v);
3247 char *s = String_val (ptr_v);
3249 if (trylock (__func__)) {
3250 goto done;
3253 page = parse_pointer (__func__, s);
3255 if (!page->fmark || !page->lmark) {
3256 printd ("emsg nothing to copy on page %d", page->pageno);
3257 goto unlock;
3260 f = fdopen (fd, "w");
3261 if (!f) {
3262 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3263 fd, errno, strerror (errno));
3264 f = stdout;
3267 for (block = page->text->first_block; block; block = block->next) {
3268 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3269 for (line = block->u.t.first_line; line; line = line->next) {
3270 fz_stext_char *ch;
3271 for (ch = line->first_char; ch; ch = ch->next) {
3272 if (seen || ch == page->fmark) {
3273 do {
3274 pipechar (f, ch);
3275 if (ch == page->lmark) goto close;
3276 } while ((ch = ch->next));
3277 seen = 1;
3278 break;
3281 if (seen) fputc ('\n', f);
3284 close:
3285 if (f != stdout) {
3286 int ret = fclose (f);
3287 fd = -1;
3288 if (ret == -1) {
3289 if (errno != ECHILD) {
3290 printd ("emsg failed to close sel pipe: %d:%s",
3291 errno, strerror (errno));
3295 unlock:
3296 unlock (__func__);
3298 done:
3299 if (fd >= 0) {
3300 if (close (fd)) {
3301 printd ("emsg failed to close sel pipe: %d:%s",
3302 errno, strerror (errno));
3305 CAMLreturn0;
3308 CAMLprim value ml_getpdimrect (value pagedimno_v)
3310 CAMLparam1 (pagedimno_v);
3311 CAMLlocal1 (ret_v);
3312 int pagedimno = Int_val (pagedimno_v);
3313 fz_rect box;
3315 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3316 if (trylock (__func__)) {
3317 box = fz_empty_rect;
3319 else {
3320 box = state.pagedims[pagedimno].mediabox;
3321 unlock (__func__);
3324 Store_double_field (ret_v, 0, (double) box.x0);
3325 Store_double_field (ret_v, 1, (double) box.x1);
3326 Store_double_field (ret_v, 2, (double) box.y0);
3327 Store_double_field (ret_v, 3, (double) box.y1);
3329 CAMLreturn (ret_v);
3332 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3333 value dw_v, value cols_v)
3335 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3336 CAMLlocal1 (ret_v);
3337 int i;
3338 float zoom = -1.;
3339 float maxh = 0.0;
3340 struct pagedim *p;
3341 float winw = Int_val (winw_v);
3342 float winh = Int_val (winh_v);
3343 float dw = Int_val (dw_v);
3344 float cols = Int_val (cols_v);
3345 float pw = 1.0, ph = 1.0;
3347 if (trylock (__func__)) {
3348 goto done;
3351 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3352 float w = p->pagebox.x1 / cols;
3353 float h = p->pagebox.y1;
3354 if (h > maxh) {
3355 maxh = h;
3356 ph = h;
3357 if (state.fitmodel != FitProportional) pw = w;
3359 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3362 zoom = (((winh / ph) * pw) + dw) / winw;
3363 unlock (__func__);
3364 done:
3365 ret_v = caml_copy_double ((double) zoom);
3366 CAMLreturn (ret_v);
3369 CAMLprim value ml_getmaxw (value unit_v)
3371 CAMLparam1 (unit_v);
3372 CAMLlocal1 (ret_v);
3373 int i;
3374 float maxw = -1.;
3375 struct pagedim *p;
3377 if (trylock (__func__)) {
3378 goto done;
3381 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3382 float w = p->pagebox.x1;
3383 maxw = fz_max (maxw, w);
3386 unlock (__func__);
3387 done:
3388 ret_v = caml_copy_double ((double) maxw);
3389 CAMLreturn (ret_v);
3392 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3394 CAMLparam4 (pt_v, x_v, y_v, string_v);
3395 CAMLlocal1 (ret_v);
3396 int pt = Int_val(pt_v);
3397 int x = Int_val (x_v);
3398 int y = Int_val (y_v);
3399 double w;
3401 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3402 ret_v = caml_copy_double (w);
3403 CAMLreturn (ret_v);
3406 CAMLprim value ml_measure_string (value pt_v, value string_v)
3408 CAMLparam2 (pt_v, string_v);
3409 CAMLlocal1 (ret_v);
3410 int pt = Int_val (pt_v);
3411 double w;
3413 w = (double) measure_string (state.face, pt, String_val (string_v));
3414 ret_v = caml_copy_double (w);
3415 CAMLreturn (ret_v);
3418 CAMLprim value ml_getpagebox (value opaque_v)
3420 CAMLparam1 (opaque_v);
3421 CAMLlocal1 (ret_v);
3422 fz_rect rect;
3423 fz_irect bbox;
3424 fz_matrix ctm;
3425 fz_device *dev;
3426 char *s = String_val (opaque_v);
3427 struct page *page = parse_pointer (__func__, s);
3429 ret_v = caml_alloc_tuple (4);
3430 dev = fz_new_bbox_device (state.ctx, &rect);
3432 ctm = pagectm (page);
3433 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3435 fz_close_device (state.ctx, dev);
3436 fz_drop_device (state.ctx, dev);
3437 fz_round_rect (&bbox, &rect);
3438 Field (ret_v, 0) = Val_int (bbox.x0);
3439 Field (ret_v, 1) = Val_int (bbox.y0);
3440 Field (ret_v, 2) = Val_int (bbox.x1);
3441 Field (ret_v, 3) = Val_int (bbox.y1);
3443 CAMLreturn (ret_v);
3446 CAMLprim void ml_setaalevel (value level_v)
3448 CAMLparam1 (level_v);
3450 state.aalevel = Int_val (level_v);
3451 CAMLreturn0;
3454 #ifndef __COCOA__
3455 #pragma GCC diagnostic push
3456 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3457 #include <X11/Xlib.h>
3458 #include <X11/cursorfont.h>
3459 #pragma GCC diagnostic pop
3461 #include <GL/glx.h>
3463 static const int shapes[] = {
3464 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3467 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3469 static struct {
3470 Window wid;
3471 Display *dpy;
3472 GLXContext ctx;
3473 XVisualInfo *visual;
3474 Cursor curs[CURS_COUNT];
3475 } glx;
3478 static void initcurs (void)
3480 for (size_t n = 0; n < CURS_COUNT; ++n) {
3481 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3485 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3487 CAMLparam3 (display_v, wid_v, screen_v);
3489 glx.dpy = XOpenDisplay (String_val (display_v));
3490 if (!glx.dpy) {
3491 caml_failwith ("XOpenDisplay");
3494 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3495 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3496 if (!glx.visual) {
3497 XCloseDisplay (glx.dpy);
3498 caml_failwith ("glXChooseVisual");
3501 initcurs ();
3503 glx.wid = Int_val (wid_v);
3504 CAMLreturn (Val_int (glx.visual->visualid));
3507 CAMLprim void ml_glxcompleteinit (value unit_v)
3509 CAMLparam1 (unit_v);
3511 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3512 if (!glx.ctx) {
3513 caml_failwith ("glXCreateContext");
3516 XFree (glx.visual);
3517 glx.visual = NULL;
3519 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3520 glXDestroyContext (glx.dpy, glx.ctx);
3521 glx.ctx = NULL;
3522 caml_failwith ("glXMakeCurrent");
3524 CAMLreturn0;
3527 CAMLprim void ml_setcursor (value cursor_v)
3529 CAMLparam1 (cursor_v);
3530 size_t cursn = Int_val (cursor_v);
3532 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3533 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3534 XFlush (glx.dpy);
3535 CAMLreturn0;
3538 CAMLprim void ml_swapb (value unit_v)
3540 CAMLparam1 (unit_v);
3541 glXSwapBuffers (glx.dpy, glx.wid);
3542 CAMLreturn0;
3545 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3547 CAMLparam1 (keysym_v);
3548 CAMLlocal1 (str_v);
3549 KeySym keysym = Int_val (keysym_v);
3550 Rune rune;
3551 extern long keysym2ucs (KeySym);
3552 int len;
3553 char buf[5];
3555 rune = (Rune) keysym2ucs (keysym);
3556 len = fz_runetochar (buf, rune);
3557 buf[len] = 0;
3558 str_v = caml_copy_string (buf);
3559 CAMLreturn (str_v);
3561 #else
3562 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3564 CAMLparam1 (keysym_v);
3565 CAMLlocal1 (str_v);
3566 long ucs_v = Long_val (keysym_v);
3567 int len;
3568 char buf[5];
3570 len = fz_runetochar (buf, (int) ucs_v);
3571 buf[len] = 0;
3572 str_v = caml_copy_string (buf);
3573 CAMLreturn (str_v);
3575 #endif
3577 enum { piunknown, pilinux, pimacos, pibsd };
3579 CAMLprim value ml_platform (value unit_v)
3581 CAMLparam1 (unit_v);
3582 CAMLlocal2 (tup_v, arr_v);
3583 int platid = piunknown;
3584 struct utsname buf;
3586 #if defined __linux__
3587 platid = pilinux;
3588 #elif defined __DragonFly__ || defined __FreeBSD__
3589 || defined __OpenBSD__ || defined __NetBSD__
3590 platid = pibsd;
3591 #elif defined __APPLE__
3592 platid = pimacos;
3593 #endif
3594 if (uname (&buf)) err (1, "uname");
3596 tup_v = caml_alloc_tuple (2);
3598 char const *sar[] = {
3599 buf.sysname,
3600 buf.release,
3601 buf.version,
3602 buf.machine,
3603 NULL
3605 arr_v = caml_copy_string_array (sar);
3607 Field (tup_v, 0) = Val_int (platid);
3608 Field (tup_v, 1) = arr_v;
3609 CAMLreturn (tup_v);
3612 CAMLprim void ml_cloexec (value fd_v)
3614 CAMLparam1 (fd_v);
3615 int fd = Int_val (fd_v);
3617 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3618 uerror ("fcntl", Nothing);
3620 CAMLreturn0;
3623 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3625 CAMLparam2 (w_v, h_v);
3626 CAMLlocal1 (ret_v);
3627 struct bo *pbo;
3628 int w = Int_val (w_v);
3629 int h = Int_val (h_v);
3630 int cs = Int_val (cs_v);
3632 if (state.bo_usable) {
3633 pbo = calloc (sizeof (*pbo), 1);
3634 if (!pbo) {
3635 err (1, "calloc pbo");
3638 switch (cs) {
3639 case 0:
3640 case 1:
3641 pbo->size = w*h*4;
3642 break;
3643 case 2:
3644 pbo->size = w*h*2;
3645 break;
3646 default:
3647 errx (1, "%s: invalid colorspace %d", __func__, cs);
3650 state.glGenBuffersARB (1, &pbo->id);
3651 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3652 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3653 NULL, GL_STREAM_DRAW);
3654 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3655 GL_READ_WRITE);
3656 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3657 if (!pbo->ptr) {
3658 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3659 state.glDeleteBuffersARB (1, &pbo->id);
3660 free (pbo);
3661 ret_v = caml_copy_string ("0");
3663 else {
3664 int res;
3665 char *s;
3667 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3668 if (res < 0) {
3669 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3671 s = malloc (res+1);
3672 if (!s) {
3673 err (1, "malloc %d bytes failed", res+1);
3675 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3676 if (res < 0) {
3677 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3679 ret_v = caml_copy_string (s);
3680 free (s);
3683 else {
3684 ret_v = caml_copy_string ("0");
3686 CAMLreturn (ret_v);
3689 CAMLprim void ml_freepbo (value s_v)
3691 CAMLparam1 (s_v);
3692 char *s = String_val (s_v);
3693 struct tile *tile = parse_pointer (__func__, s);
3695 if (tile->pbo) {
3696 state.glDeleteBuffersARB (1, &tile->pbo->id);
3697 tile->pbo->id = -1;
3698 tile->pbo->ptr = NULL;
3699 tile->pbo->size = -1;
3701 CAMLreturn0;
3704 CAMLprim void ml_unmappbo (value s_v)
3706 CAMLparam1 (s_v);
3707 char *s = String_val (s_v);
3708 struct tile *tile = parse_pointer (__func__, s);
3710 if (tile->pbo) {
3711 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3712 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3713 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3715 tile->pbo->ptr = NULL;
3716 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3718 CAMLreturn0;
3721 static void setuppbo (void)
3723 extern void (*wsigladdr (const char *name)) (void);
3724 state.bo_usable = wsigladdr ("glBindBufferARB")
3725 && wsigladdr ("glUnmapBufferARB")
3726 && wsigladdr ("glMapBufferARB")
3727 && wsigladdr ("glBufferDataARB")
3728 && wsigladdr ("glGenBuffersARB")
3729 && wsigladdr ("glDeleteBuffersARB");
3732 CAMLprim value ml_bo_usable (value unit_v)
3734 CAMLparam1 (unit_v);
3735 CAMLreturn (Val_bool (state.bo_usable));
3738 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3740 CAMLparam3 (ptr_v, x_v, y_v);
3741 CAMLlocal2 (ret_v, tup_v);
3742 struct page *page;
3743 char *s = String_val (ptr_v);
3744 int x = Int_val (x_v), y = Int_val (y_v);
3745 struct pagedim *pdim;
3746 fz_point p;
3747 fz_matrix ctm;
3749 page = parse_pointer (__func__, s);
3750 pdim = &state.pagedims[page->pdimno];
3752 ret_v = Val_int (0);
3753 if (trylock (__func__)) {
3754 goto done;
3757 if (pdf_specifics (state.ctx, state.doc)) {
3758 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3759 ctm = state.pagedims[page->pdimno].tctm;
3761 else {
3762 ctm = fz_identity;
3764 p.x = x + pdim->bounds.x0;
3765 p.y = y + pdim->bounds.y0;
3767 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3768 fz_invert_matrix (&ctm, &ctm);
3769 fz_transform_point (&p, &ctm);
3771 tup_v = caml_alloc_tuple (2);
3772 ret_v = caml_alloc_small (1, 1);
3773 Field (tup_v, 0) = Val_int (p.x);
3774 Field (tup_v, 1) = Val_int (p.y);
3775 Field (ret_v, 0) = tup_v;
3777 unlock (__func__);
3778 done:
3779 CAMLreturn (ret_v);
3782 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3783 value x_v, value y_v)
3785 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3786 CAMLlocal1 (ret_v);
3787 struct page *page;
3788 char *s = String_val (ptr_v);
3789 int pageno = Int_val (pageno_v);
3790 int pdimno = Int_val (pdimno_v);
3791 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3792 struct pagedim *pdim;
3793 fz_point p;
3794 fz_matrix ctm;
3796 ret_v = Val_int (0);
3797 lock (__func__);
3799 if (!*s) {
3800 page = loadpage (pageno, pdimno);
3802 else {
3803 page = parse_pointer (__func__, s);
3805 pdim = &state.pagedims[pdimno];
3807 if (pdf_specifics (state.ctx, state.doc)) {
3808 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3809 ctm = state.pagedims[page->pdimno].tctm;
3811 else {
3812 ctm = fz_identity;
3814 p.x = x + pdim->bounds.x0;
3815 p.y = y + pdim->bounds.y0;
3817 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3818 fz_transform_point (&p, &ctm);
3820 ret_v = caml_alloc_tuple (2);
3821 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3822 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3824 if (!*s) {
3825 freepage (page);
3827 unlock (__func__);
3828 CAMLreturn (ret_v);
3831 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
3832 value contents_v)
3834 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3835 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3837 if (pdf) {
3838 pdf_annot *annot;
3839 struct page *page;
3840 fz_point p;
3841 char *s = String_val (ptr_v);
3843 page = parse_pointer (__func__, s);
3844 annot = pdf_create_annot (state.ctx,
3845 pdf_page_from_fz_page (state.ctx,
3846 page->fzpage),
3847 PDF_ANNOT_TEXT);
3848 p.x = Int_val (x_v);
3849 p.y = Int_val (y_v);
3850 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3851 pdf_set_text_annot_position (state.ctx, annot, p);
3852 state.dirty = 1;
3854 CAMLreturn0;
3857 CAMLprim void ml_delannot (value ptr_v, value n_v)
3859 CAMLparam2 (ptr_v, n_v);
3860 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3862 if (pdf) {
3863 struct page *page;
3864 char *s = String_val (ptr_v);
3865 struct slink *slink;
3867 page = parse_pointer (__func__, s);
3868 slink = &page->slinks[Int_val (n_v)];
3869 pdf_delete_annot (state.ctx,
3870 pdf_page_from_fz_page (state.ctx, page->fzpage),
3871 (pdf_annot *) slink->u.annot);
3872 state.dirty = 1;
3874 CAMLreturn0;
3877 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
3879 CAMLparam3 (ptr_v, n_v, str_v);
3880 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3882 if (pdf) {
3883 struct page *page;
3884 char *s = String_val (ptr_v);
3885 struct slink *slink;
3887 page = parse_pointer (__func__, s);
3888 slink = &page->slinks[Int_val (n_v)];
3889 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3890 String_val (str_v));
3891 state.dirty = 1;
3893 CAMLreturn0;
3896 CAMLprim value ml_hasunsavedchanges (value unit_v)
3898 CAMLparam1 (unit_v);
3899 CAMLreturn (Val_bool (state.dirty));
3902 CAMLprim void ml_savedoc (value path_v)
3904 CAMLparam1 (path_v);
3905 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3907 if (pdf) {
3908 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3910 CAMLreturn0;
3913 static void makestippletex (void)
3915 const char pixels[] = "\xff\xff\0\0";
3916 glGenTextures (1, &state.stid);
3917 glBindTexture (GL_TEXTURE_1D, state.stid);
3918 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3919 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3920 glTexImage1D (
3921 GL_TEXTURE_1D,
3923 GL_ALPHA,
3926 GL_ALPHA,
3927 GL_UNSIGNED_BYTE,
3928 pixels
3932 CAMLprim value ml_fz_version (void)
3934 return caml_copy_string (FZ_VERSION);
3937 CAMLprim value ml_llpp_version (void)
3939 extern char llpp_version[];
3940 return caml_copy_string (llpp_version);
3943 CAMLprim void ml_init (value csock_v, value params_v)
3945 CAMLparam2 (csock_v, params_v);
3946 CAMLlocal2 (trim_v, fuzz_v);
3947 int ret;
3948 int texcount;
3949 char *fontpath;
3950 int colorspace;
3951 int mustoresize;
3952 int haspboext;
3954 state.csock = Int_val (csock_v);
3955 state.rotate = Int_val (Field (params_v, 0));
3956 state.fitmodel = Int_val (Field (params_v, 1));
3957 trim_v = Field (params_v, 2);
3958 texcount = Int_val (Field (params_v, 3));
3959 state.sliceheight = Int_val (Field (params_v, 4));
3960 mustoresize = Int_val (Field (params_v, 5));
3961 colorspace = Int_val (Field (params_v, 6));
3962 fontpath = String_val (Field (params_v, 7));
3964 #ifdef __COCOA__
3965 state.utf8cs = 1;
3966 #else
3967 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3968 if (setlocale (LC_CTYPE, "")) {
3969 const char *cset = nl_langinfo (CODESET);
3970 state.utf8cs = !strcmp (cset, "UTF-8");
3972 else {
3973 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3975 #endif
3977 if (caml_string_length (Field (params_v, 8)) > 0) {
3978 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3980 if (!state.trimcachepath) {
3981 printd ("emsg failed to strdup trimcachepath: %d:%s",
3982 errno, strerror (errno));
3986 haspboext = Bool_val (Field (params_v, 9));
3988 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3989 fz_register_document_handlers (state.ctx);
3991 state.trimmargins = Bool_val (Field (trim_v, 0));
3992 fuzz_v = Field (trim_v, 1);
3993 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3994 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3995 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3996 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3998 set_tex_params (colorspace);
4000 if (*fontpath) {
4001 state.face = load_font (fontpath);
4003 else {
4004 int len;
4005 const unsigned char *data;
4007 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4008 state.face = load_builtin_font (data, len);
4010 if (!state.face) _exit (1);
4012 realloctexts (texcount);
4014 if (haspboext) {
4015 setuppbo ();
4018 makestippletex ();
4020 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4021 if (ret) {
4022 errx (1, "pthread_create: %s", strerror (ret));
4025 CAMLreturn0;
4028 #if FIXME || !FIXME
4029 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
4030 #endif