Cosmetics
[llpp.git] / link.c
blob90a8bfe363f3a0dc31ebc0c72e55c86c6ec223ac
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
4 #include <errno.h>
5 #include <stdio.h>
6 #include <ctype.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <signal.h>
10 #include <wchar.h>
12 #include <unistd.h>
13 #include <pthread.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/utsname.h>
19 #ifdef __CYGWIN__
20 #include <cygwin/socket.h> /* FIONREAD */
21 #else
22 #include <spawn.h>
23 #endif
25 #include <regex.h>
26 #include <stdarg.h>
27 #include <limits.h>
28 #include <inttypes.h>
30 #include <GL/gl.h>
32 #include <caml/fail.h>
33 #include <caml/alloc.h>
34 #include <caml/memory.h>
35 #include <caml/unixsupport.h>
37 #if __GNUC__ < 5
38 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
39 clobbered diagnostics */
40 #pragma GCC diagnostic ignored "-Wclobbered"
41 #endif
43 #pragma GCC diagnostic push
44 #pragma GCC diagnostic ignored "-Wunused-parameter"
45 #pragma GCC diagnostic ignored "-Wshadow"
46 #include <mupdf/fitz.h>
47 #pragma GCC diagnostic pop
48 #include <mupdf/pdf.h>
50 #include <ft2build.h>
51 #include FT_FREETYPE_H
53 #ifdef USE_FONTCONFIG
54 #include <fontconfig/fontconfig.h>
55 #endif
57 #define PIGGYBACK
58 #define CACHE_PAGEREFS
60 #ifndef __USE_GNU
61 extern char **environ;
62 #endif
64 #define MIN(a,b) ((a) < (b) ? (a) : (b))
65 #define MAX(a,b) ((a) > (b) ? (a) : (b))
67 #if defined __GNUC__
68 #define NORETURN_ATTR __attribute__ ((noreturn))
69 #define UNUSED_ATTR __attribute__ ((unused))
70 #if !defined __clang__
71 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
72 #else
73 #define OPTIMIZE_ATTR(n)
74 #endif
75 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
76 #else
77 #define NORETURN_ATTR
78 #define UNUSED_ATTR
79 #define OPTIMIZE_ATTR(n)
80 #define GCC_FMT_ATTR(a, b)
81 #endif
83 #define FMT_s "zu"
85 #define FMT_ptr PRIxPTR
86 #define SCN_ptr SCNxPTR
87 #define FMT_ptr_cast(p) ((uintptr_t) (p))
88 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
90 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
91 err (int exitcode, const char *fmt, ...)
93 va_list ap;
94 int savederrno;
96 savederrno = errno;
97 va_start (ap, fmt);
98 vfprintf (stderr, fmt, ap);
99 va_end (ap);
100 fprintf (stderr, ": %s\n", strerror (savederrno));
101 fflush (stderr);
102 _exit (exitcode);
105 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
106 errx (int exitcode, const char *fmt, ...)
108 va_list ap;
110 va_start (ap, fmt);
111 vfprintf (stderr, fmt, ap);
112 va_end (ap);
113 fputc ('\n', stderr);
114 fflush (stderr);
115 _exit (exitcode);
118 #ifndef GL_TEXTURE_RECTANGLE_ARB
119 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
120 #endif
122 #ifdef USE_NPOT
123 #define TEXT_TYPE GL_TEXTURE_2D
124 #else
125 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
126 #endif
128 #ifndef GL_BGRA
129 #define GL_BGRA 0x80E1
130 #endif
132 #ifndef GL_UNSIGNED_INT_8_8_8_8
133 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
134 #endif
136 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
137 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
138 #endif
140 #if 0
141 #define lprintf printf
142 #else
143 #define lprintf(...)
144 #endif
146 #define ARSERT(cond) for (;;) { \
147 if (!(cond)) { \
148 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
150 break; \
153 struct slice {
154 int h;
155 int texindex;
158 struct tile {
159 int w, h;
160 int slicecount;
161 int sliceheight;
162 struct pbo *pbo;
163 fz_pixmap *pixmap;
164 struct slice slices[1];
167 struct pagedim {
168 int pageno;
169 int rotate;
170 int left;
171 int tctmready;
172 fz_irect bounds;
173 fz_rect pagebox;
174 fz_rect mediabox;
175 fz_matrix ctm, zoomctm, lctm, tctm;
178 struct slink {
179 enum { SLINK, SANNOT } tag;
180 fz_irect bbox;
181 union {
182 fz_link *link;
183 fz_annot *annot;
184 } u;
187 struct annot {
188 fz_irect bbox;
189 fz_annot *annot;
192 struct page {
193 int tgen;
194 int sgen;
195 int agen;
196 int pageno;
197 int pdimno;
198 fz_stext_page *text;
199 fz_stext_sheet *sheet;
200 fz_page *fzpage;
201 fz_display_list *dlist;
202 int slinkcount;
203 struct slink *slinks;
204 int annotcount;
205 struct annot *annots;
206 struct mark {
207 int i;
208 fz_stext_span *span;
209 } fmark, lmark;
212 struct {
213 int sliceheight;
214 struct pagedim *pagedims;
215 int pagecount;
216 int pagedimcount;
217 fz_document *doc;
218 fz_context *ctx;
219 int w, h;
221 int texindex;
222 int texcount;
223 GLuint *texids;
225 GLenum texiform;
226 GLenum texform;
227 GLenum texty;
229 fz_colorspace *colorspace;
231 struct {
232 int w, h;
233 struct slice *slice;
234 } *texowners;
236 int rotate;
237 enum { FitWidth, FitProportional, FitPage } fitmodel;
238 int trimmargins;
239 int needoutline;
240 int gen;
241 int aalevel;
243 int trimanew;
244 fz_irect trimfuzz;
245 fz_pixmap *pig;
247 pthread_t thread;
248 int csock;
249 FT_Face face;
251 char *trimcachepath;
252 int cxack;
253 int dirty;
255 GLuint stid;
257 int pbo_usable;
258 void (*glBindBufferARB) (GLenum, GLuint);
259 GLboolean (*glUnmapBufferARB) (GLenum);
260 void *(*glMapBufferARB) (GLenum, GLenum);
261 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
262 void (*glGenBuffersARB) (GLsizei, GLuint *);
263 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
265 GLfloat texcoords[8];
266 GLfloat vertices[16];
268 #ifdef CACHE_PAGEREFS
269 struct {
270 int idx;
271 int count;
272 pdf_obj **objs;
273 pdf_document *pdf;
274 } pdflut;
275 #endif
276 } state;
278 struct pbo {
279 GLuint id;
280 void *ptr;
281 size_t size;
284 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
286 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
289 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
291 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
294 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
296 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
297 m.a, m.b, m.c, m.d, m.e, m.f);
300 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
302 static void lock (const char *cap)
304 int ret = pthread_mutex_lock (&mutex);
305 if (ret) {
306 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
310 static void unlock (const char *cap)
312 int ret = pthread_mutex_unlock (&mutex);
313 if (ret) {
314 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
318 static int trylock (const char *cap)
320 int ret = pthread_mutex_trylock (&mutex);
321 if (ret && ret != EBUSY) {
322 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
324 return ret == EBUSY;
327 static void *parse_pointer (const char *cap, const char *s)
329 int ret;
330 void *ptr;
332 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
333 if (ret != 1) {
334 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
336 return ptr;
339 static double now (void)
341 struct timeval tv;
343 if (gettimeofday (&tv, NULL)) {
344 err (1, "gettimeofday");
346 return tv.tv_sec + tv.tv_usec*1e-6;
349 static int hasdata (void)
351 int ret, avail;
352 ret = ioctl (state.csock, FIONREAD, &avail);
353 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
354 return avail > 0;
357 CAMLprim value ml_hasdata (value fd_v)
359 CAMLparam1 (fd_v);
360 int ret, avail;
362 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
363 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
364 CAMLreturn (Val_bool (avail > 0));
367 static void readdata (void *p, int size)
369 ssize_t n;
371 again:
372 n = read (state.csock, p, size);
373 if (n < 0) {
374 if (errno == EINTR) goto again;
375 err (1, "read (req %d, ret %zd)", size, n);
377 if (n - size) {
378 if (!n) errx (1, "EOF while reading");
379 errx (1, "read (req %d, ret %zd)", size, n);
383 static void writedata (char *p, int size)
385 ssize_t n;
387 p[0] = (size >> 24) & 0xff;
388 p[1] = (size >> 16) & 0xff;
389 p[2] = (size >> 8) & 0xff;
390 p[3] = (size >> 0) & 0xff;
392 n = write (state.csock, p, size + 4);
393 if (n - size - 4) {
394 if (!n) errx (1, "EOF while writing data");
395 err (1, "write (req %d, ret %zd)", size + 4, n);
399 static int readlen (void)
401 unsigned char p[4];
403 readdata (p, 4);
404 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
407 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
409 int size = 200, len;
410 va_list ap;
411 char *buf;
413 buf = malloc (size);
414 for (;;) {
415 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
417 va_start (ap, fmt);
418 len = vsnprintf (buf + 4, size - 4, fmt, ap);
419 va_end (ap);
421 if (len > -1) {
422 if (len < size - 4) {
423 writedata (buf, len);
424 break;
426 else size = len + 5;
428 else {
429 err (1, "vsnprintf for `%s' failed", fmt);
431 buf = realloc (buf, size);
433 free (buf);
436 static void closedoc (void)
438 #ifdef CACHE_PAGEREFS
439 if (state.pdflut.objs) {
440 int i;
442 for (i = 0; i < state.pdflut.count; ++i) {
443 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
445 free (state.pdflut.objs);
446 state.pdflut.objs = NULL;
447 state.pdflut.idx = 0;
449 #endif
450 if (state.doc) {
451 fz_drop_document (state.ctx, state.doc);
452 state.doc = NULL;
456 static int openxref (char *filename, char *password)
458 int i;
460 for (i = 0; i < state.texcount; ++i) {
461 state.texowners[i].w = -1;
462 state.texowners[i].slice = NULL;
465 closedoc ();
467 state.dirty = 0;
468 if (state.pagedims) {
469 free (state.pagedims);
470 state.pagedims = NULL;
472 state.pagedimcount = 0;
474 fz_set_aa_level (state.ctx, state.aalevel);
475 state.doc = fz_open_document (state.ctx, filename);
476 if (fz_needs_password (state.ctx, state.doc)) {
477 if (password && !*password) {
478 printd ("pass");
479 return 0;
481 else {
482 int ok = fz_authenticate_password (state.ctx, state.doc, password);
483 if (!ok) {
484 printd ("pass fail");
485 return 0;
489 state.pagecount = fz_count_pages (state.ctx, state.doc);
490 return 1;
493 static void pdfinfo (void)
495 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
496 if (pdf) {
497 pdf_obj *infoobj;
499 printd ("info PDF version\t%d.%d",
500 pdf->version / 10, pdf->version % 10);
502 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
503 pdf), "Info");
504 if (infoobj) {
505 unsigned int i;
506 char *s;
507 char *items[] = { "Title", "Author", "Creator",
508 "Producer", "CreationDate" };
510 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
511 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
512 s = pdf_to_utf8 (state.ctx, pdf, obj);
513 if (*s) printd ("info %s\t%s", items[i], s);
514 fz_free (state.ctx, s);
517 printd ("infoend");
521 static void unlinktile (struct tile *tile)
523 int i;
525 for (i = 0; i < tile->slicecount; ++i) {
526 struct slice *s = &tile->slices[i];
528 if (s->texindex != -1) {
529 if (state.texowners[s->texindex].slice == s) {
530 state.texowners[s->texindex].slice = NULL;
536 static void freepage (struct page *page)
538 if (!page) return;
539 if (page->text) {
540 fz_drop_stext_page (state.ctx, page->text);
542 if (page->sheet) {
543 fz_drop_stext_sheet (state.ctx, page->sheet);
545 if (page->slinks) {
546 free (page->slinks);
548 fz_drop_display_list (state.ctx, page->dlist);
549 fz_drop_page (state.ctx, page->fzpage);
550 free (page);
553 static void freetile (struct tile *tile)
555 unlinktile (tile);
556 if (!tile->pbo) {
557 #ifndef PIGGYBACK
558 fz_drop_pixmap (state.ctx, tile->pixmap);
559 #else
560 if (state.pig) {
561 fz_drop_pixmap (state.ctx, state.pig);
563 state.pig = tile->pixmap;
564 #endif
566 else {
567 free (tile->pbo);
568 fz_drop_pixmap (state.ctx, tile->pixmap);
570 free (tile);
573 #ifdef __ALTIVEC__
574 #include <stdint.h>
575 #include <altivec.h>
577 static int cacheline32bytes;
579 static void __attribute__ ((constructor)) clcheck (void)
581 char **envp = environ;
582 unsigned long *auxv;
584 while (*envp++);
586 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
587 if (*auxv == 19) {
588 cacheline32bytes = auxv[1] == 32;
589 return;
594 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
596 size_t size = pixmap->w * pixmap->h * pixmap->n;
597 if (cacheline32bytes && size > 32) {
598 intptr_t a1, a2, diff;
599 size_t sizea, i;
600 vector unsigned char v = vec_splat_u8 (-1);
601 vector unsigned char *p;
603 a1 = a2 = (intptr_t) pixmap->samples;
604 a2 = (a1 + 31) & ~31;
605 diff = a2 - a1;
606 sizea = size - diff;
607 p = (void *) a2;
609 while (a1 != a2) *(char *) a1++ = 0xff;
610 for (i = 0; i < (sizea & ~31); i += 32) {
611 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
612 vec_st (v, i, p);
613 vec_st (v, i + 16, p);
615 while (i < sizea) *((char *) a1 + i++) = 0xff;
617 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
619 #else
620 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
621 #endif
623 static void trimctm (pdf_page *page, int pindex)
625 fz_matrix ctm;
626 struct pagedim *pdim = &state.pagedims[pindex];
628 if (!pdim->tctmready) {
629 if (state.trimmargins) {
630 fz_rect realbox;
631 fz_matrix rm, sm, tm, im, ctm1;
633 fz_rotate (&rm, -pdim->rotate);
634 fz_scale (&sm, 1, -1);
635 fz_concat (&ctm, &rm, &sm);
636 realbox = pdim->mediabox;
637 fz_transform_rect (&realbox, &ctm);
638 fz_translate (&tm, -realbox.x0, -realbox.y0);
639 fz_concat (&ctm1, &ctm, &tm);
640 fz_invert_matrix (&im, &page->ctm);
641 fz_concat (&ctm, &im, &ctm1);
643 else {
644 ctm = fz_identity;
646 pdim->tctm = ctm;
647 pdim->tctmready = 1;
651 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
653 fz_matrix ctm, tm;
654 int pdimno = pdim - state.pagedims;
656 if (pdf_specifics (state.ctx, state.doc)) {
657 trimctm ((pdf_page *) fzpage, pdimno);
658 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
660 else {
661 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
662 fz_concat (&ctm, &tm, &pdim->ctm);
664 return ctm;
667 static fz_matrix pagectm (struct page *page)
669 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
672 static void *loadpage (int pageno, int pindex)
674 fz_device *dev;
675 struct page *page;
677 page = calloc (sizeof (struct page), 1);
678 if (!page) {
679 err (1, "calloc page %d", pageno);
682 page->dlist = fz_new_display_list (state.ctx);
683 dev = fz_new_list_device (state.ctx, page->dlist);
684 fz_try (state.ctx) {
685 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
686 fz_run_page (state.ctx, page->fzpage, dev,
687 &fz_identity, NULL);
689 fz_catch (state.ctx) {
690 page->fzpage = NULL;
692 fz_drop_device (state.ctx, dev);
694 page->pdimno = pindex;
695 page->pageno = pageno;
696 page->sgen = state.gen;
697 page->agen = state.gen;
698 page->tgen = state.gen;
699 return page;
702 static struct tile *alloctile (int h)
704 int i;
705 int slicecount;
706 size_t tilesize;
707 struct tile *tile;
709 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
710 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
711 tile = calloc (tilesize, 1);
712 if (!tile) {
713 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
715 for (i = 0; i < slicecount; ++i) {
716 int sh = MIN (h, state.sliceheight);
717 tile->slices[i].h = sh;
718 tile->slices[i].texindex = -1;
719 h -= sh;
721 tile->slicecount = slicecount;
722 tile->sliceheight = state.sliceheight;
723 return tile;
726 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
727 struct pbo *pbo)
729 fz_rect rect;
730 fz_irect bbox;
731 fz_matrix ctm;
732 fz_device *dev;
733 struct tile *tile;
734 struct pagedim *pdim;
736 tile = alloctile (h);
737 pdim = &state.pagedims[page->pdimno];
739 bbox = pdim->bounds;
740 bbox.x0 += x;
741 bbox.y0 += y;
742 bbox.x1 = bbox.x0 + w;
743 bbox.y1 = bbox.y0 + h;
745 if (state.pig) {
746 if (state.pig->w == w
747 && state.pig->h == h
748 && state.pig->colorspace == state.colorspace) {
749 tile->pixmap = state.pig;
750 tile->pixmap->x = bbox.x0;
751 tile->pixmap->y = bbox.y0;
753 else {
754 fz_drop_pixmap (state.ctx, state.pig);
756 state.pig = NULL;
758 if (!tile->pixmap) {
759 if (pbo) {
760 tile->pixmap =
761 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
762 &bbox, pbo->ptr);
763 tile->pbo = pbo;
765 else {
766 tile->pixmap =
767 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
771 tile->w = w;
772 tile->h = h;
773 clearpixmap (tile->pixmap);
775 dev = fz_new_draw_device (state.ctx, tile->pixmap);
776 ctm = pagectm (page);
777 fz_rect_from_irect (&rect, &bbox);
778 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
779 fz_drop_device (state.ctx, dev);
781 return tile;
784 #ifdef CACHE_PAGEREFS
785 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
786 thanks to Robin Watts */
787 static void
788 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
790 fz_context *ctx = state.ctx; /* doc->ctx; */
791 pdf_obj *kids;
792 int i, len;
794 if (state.pdflut.idx == state.pagecount) return;
796 kids = pdf_dict_gets (ctx, node, "Kids");
797 len = pdf_array_len (ctx, kids);
799 if (len == 0)
800 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
802 if (pdf_mark_obj (ctx, node))
803 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
804 for (i = 0; i < len; i++) {
805 pdf_obj *kid = pdf_array_get (ctx, kids, i);
806 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
807 if (*type
808 ? !strcmp (type, "Pages")
809 : pdf_dict_gets (ctx, kid, "Kids")
810 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
811 pdf_collect_pages (doc, kid);
813 else {
814 if (*type
815 ? strcmp (type, "Page") != 0
816 : !pdf_dict_gets (ctx, kid, "MediaBox"))
817 fz_warn (ctx, "non-page object in page tree (%s)", type);
818 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
821 pdf_unmark_obj (ctx, node);
824 static void
825 pdf_load_page_objs (pdf_document *doc)
827 pdf_obj *root = pdf_dict_gets (state.ctx,
828 pdf_trailer (state.ctx, doc), "Root");
829 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
831 if (!node)
832 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
834 state.pdflut.idx = 0;
835 pdf_collect_pages (doc, node);
837 #endif
839 static void initpdims (int wthack)
841 double start, end;
842 FILE *trimf = NULL;
843 fz_rect rootmediabox;
844 int pageno, trim, show;
845 int trimw = 0, cxcount;
846 fz_context *ctx = state.ctx;
847 pdf_document *pdf = pdf_specifics (ctx, state.doc);
849 fz_var (trimw);
850 fz_var (cxcount);
851 start = now ();
853 if (state.trimmargins && state.trimcachepath) {
854 trimf = fopen (state.trimcachepath, "rb");
855 if (!trimf) {
856 trimf = fopen (state.trimcachepath, "wb");
857 trimw = 1;
861 if (state.trimmargins || pdf || !state.cxack)
862 cxcount = state.pagecount;
863 else
864 cxcount = MIN (state.pagecount, 1);
866 if (pdf) {
867 pdf_obj *obj;
868 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
869 "Root/Pages/MediaBox");
870 pdf_to_rect (ctx, obj, &rootmediabox);
873 #ifdef CACHE_PAGEREFS
874 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
875 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
876 if (!state.pdflut.objs) {
877 err (1, "malloc pageobjs %zu %d %zu failed",
878 sizeof (*state.pdflut.objs), cxcount,
879 sizeof (*state.pdflut.objs) * cxcount);
881 state.pdflut.count = cxcount;
882 pdf_load_page_objs (pdf);
883 state.pdflut.pdf = pdf;
885 #endif
887 for (pageno = 0; pageno < cxcount; ++pageno) {
888 int rotate = 0;
889 struct pagedim *p;
890 fz_rect mediabox;
892 if (pdf) {
893 pdf_obj *pageref, *pageobj;
895 #ifdef CACHE_PAGEREFS
896 pageref = state.pdflut.objs[pageno];
897 #else
898 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
899 #endif
900 pageobj = pdf_resolve_indirect (ctx, pageref);
902 if (state.trimmargins) {
903 pdf_obj *obj;
904 pdf_page *page;
906 fz_try (ctx) {
907 page = pdf_load_page (ctx, pdf, pageno);
908 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
909 trim = state.trimanew || !obj;
910 if (trim) {
911 fz_rect rect;
912 fz_matrix ctm;
913 fz_device *dev;
915 dev = fz_new_bbox_device (ctx, &rect);
916 dev->hints |= FZ_IGNORE_SHADE;
917 fz_invert_matrix (&ctm, &page->ctm);
918 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
919 fz_drop_device (ctx, dev);
921 rect.x0 += state.trimfuzz.x0;
922 rect.x1 += state.trimfuzz.x1;
923 rect.y0 += state.trimfuzz.y0;
924 rect.y1 += state.trimfuzz.y1;
925 fz_transform_rect (&rect, &ctm);
926 fz_intersect_rect (&rect, &page->mediabox);
928 if (fz_is_empty_rect (&rect)) {
929 mediabox = page->mediabox;
931 else {
932 mediabox = rect;
935 obj = pdf_new_array (ctx, pdf, 4);
936 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
937 mediabox.x0));
938 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
939 mediabox.y0));
940 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
941 mediabox.x1));
942 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
943 mediabox.y1));
944 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
946 else {
947 mediabox.x0 = pdf_to_real (ctx,
948 pdf_array_get (ctx, obj, 0));
949 mediabox.y0 = pdf_to_real (ctx,
950 pdf_array_get (ctx, obj, 1));
951 mediabox.x1 = pdf_to_real (ctx,
952 pdf_array_get (ctx, obj, 2));
953 mediabox.y1 = pdf_to_real (ctx,
954 pdf_array_get (ctx, obj, 3));
957 rotate = page->rotate;
958 fz_drop_page (ctx, &page->super);
960 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
961 if (show) {
962 printd ("progress %f Trimming %d",
963 (double) (pageno + 1) / state.pagecount,
964 pageno + 1);
967 fz_catch (ctx) {
968 fprintf (stderr, "failed to load page %d\n", pageno+1);
971 else {
972 int empty = 0;
973 fz_rect cropbox;
975 pdf_to_rect (ctx,
976 pdf_dict_gets (ctx, pageobj, "MediaBox"),
977 &mediabox);
978 if (fz_is_empty_rect (&mediabox)) {
979 mediabox.x0 = 0;
980 mediabox.y0 = 0;
981 mediabox.x1 = 612;
982 mediabox.y1 = 792;
983 empty = 1;
986 pdf_to_rect (ctx,
987 pdf_dict_gets (ctx, pageobj, "CropBox"),
988 &cropbox);
989 if (!fz_is_empty_rect (&cropbox)) {
990 if (empty) {
991 mediabox = cropbox;
993 else {
994 fz_intersect_rect (&mediabox, &cropbox);
997 else {
998 if (empty) {
999 if (fz_is_empty_rect (&rootmediabox)) {
1000 fprintf (stderr,
1001 "cannot find page size for page %d\n",
1002 pageno+1);
1004 else {
1005 mediabox = rootmediabox;
1009 rotate = pdf_to_int (ctx,
1010 pdf_dict_gets (ctx, pageobj, "Rotate"));
1013 else {
1014 if (state.trimmargins && trimw) {
1015 fz_page *page;
1017 fz_try (ctx) {
1018 page = fz_load_page (ctx, state.doc, pageno);
1019 fz_bound_page (ctx, page, &mediabox);
1020 rotate = 0;
1021 if (state.trimmargins) {
1022 fz_rect rect;
1023 fz_device *dev;
1025 dev = fz_new_bbox_device (ctx, &rect);
1026 dev->hints |= FZ_IGNORE_SHADE;
1027 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1028 fz_drop_device (ctx, dev);
1030 rect.x0 += state.trimfuzz.x0;
1031 rect.x1 += state.trimfuzz.x1;
1032 rect.y0 += state.trimfuzz.y0;
1033 rect.y1 += state.trimfuzz.y1;
1034 fz_intersect_rect (&rect, &mediabox);
1036 if (!fz_is_empty_rect (&rect)) {
1037 mediabox = rect;
1040 fz_drop_page (ctx, page);
1041 if (!state.cxack) {
1042 printd ("progress %f loading %d",
1043 (double) (pageno + 1) / state.pagecount,
1044 pageno + 1);
1047 fz_catch (ctx) {
1049 if (trimf) {
1050 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1051 if (n - 1) {
1052 err (1, "fwrite trim mediabox");
1056 else {
1057 if (trimf) {
1058 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1059 if (n - 1) {
1060 err (1, "fread trim mediabox %d", pageno);
1063 else {
1064 fz_page *page;
1065 fz_try (ctx) {
1066 page = fz_load_page (ctx, state.doc, pageno);
1067 fz_bound_page (ctx, page, &mediabox);
1068 fz_drop_page (ctx, page);
1070 show = !state.trimmargins && pageno % 20 == 0;
1071 if (show) {
1072 printd ("progress %f Gathering dimensions %d",
1073 (double) (pageno) / state.pagecount,
1074 pageno);
1077 fz_catch (ctx) {
1078 fprintf (stderr, "failed to load page %d\n", pageno);
1084 if (state.pagedimcount == 0
1085 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1086 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1087 size_t size;
1089 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1090 state.pagedims = realloc (state.pagedims, size);
1091 if (!state.pagedims) {
1092 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1093 size, state.pagedimcount + 1);
1096 p = &state.pagedims[state.pagedimcount++];
1097 p->rotate = rotate;
1098 p->mediabox = mediabox;
1099 p->pageno = pageno;
1102 end = now ();
1103 if (!wthack) {
1104 printd ("progress 1 %s %d pages in %f seconds",
1105 state.trimmargins ? "Trimmed" : "Processed",
1106 state.pagecount, end - start);
1108 state.trimanew = 0;
1109 if (trimf) {
1110 if (fclose (trimf)) {
1111 err (1, "fclose");
1116 static void layout (void)
1118 int pindex;
1119 fz_rect box;
1120 fz_matrix ctm, rm;
1121 struct pagedim *p = p;
1122 double zw, w, maxw = 0.0, zoom = zoom;
1124 if (state.pagedimcount == 0) return;
1126 switch (state.fitmodel) {
1127 case FitProportional:
1128 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1129 double x0, x1;
1131 p = &state.pagedims[pindex];
1132 fz_rotate (&rm, p->rotate + state.rotate);
1133 box = p->mediabox;
1134 fz_transform_rect (&box, &rm);
1136 x0 = MIN (box.x0, box.x1);
1137 x1 = MAX (box.x0, box.x1);
1139 w = x1 - x0;
1140 maxw = MAX (w, maxw);
1141 zoom = state.w / maxw;
1143 break;
1145 case FitPage:
1146 maxw = state.w;
1147 break;
1149 case FitWidth:
1150 break;
1152 default:
1153 ARSERT (0 && state.fitmodel);
1156 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1157 fz_rect rect;
1158 fz_matrix tm, sm;
1160 p = &state.pagedims[pindex];
1161 fz_rotate (&ctm, state.rotate);
1162 fz_rotate (&rm, p->rotate + state.rotate);
1163 box = p->mediabox;
1164 fz_transform_rect (&box, &rm);
1165 w = box.x1 - box.x0;
1166 switch (state.fitmodel) {
1167 case FitProportional:
1168 p->left = ((maxw - w) * zoom) / 2.0;
1169 break;
1170 case FitPage:
1172 double zh, h;
1173 zw = maxw / w;
1174 h = box.y1 - box.y0;
1175 zh = state.h / h;
1176 zoom = MIN (zw, zh);
1177 p->left = (maxw - (w * zoom)) / 2.0;
1179 break;
1180 case FitWidth:
1181 p->left = 0;
1182 zoom = state.w / w;
1183 break;
1186 fz_scale (&p->zoomctm, zoom, zoom);
1187 fz_concat (&ctm, &p->zoomctm, &ctm);
1189 fz_rotate (&rm, p->rotate);
1190 p->pagebox = p->mediabox;
1191 fz_transform_rect (&p->pagebox, &rm);
1192 p->pagebox.x1 -= p->pagebox.x0;
1193 p->pagebox.y1 -= p->pagebox.y0;
1194 p->pagebox.x0 = 0;
1195 p->pagebox.y0 = 0;
1196 rect = p->pagebox;
1197 fz_transform_rect (&rect, &ctm);
1198 fz_round_rect (&p->bounds, &rect);
1199 p->ctm = ctm;
1201 fz_translate (&tm, 0, -p->mediabox.y1);
1202 fz_scale (&sm, zoom, -zoom);
1203 fz_concat (&ctm, &tm, &sm);
1204 fz_concat (&p->lctm, &ctm, &rm);
1206 p->tctmready = 0;
1209 do {
1210 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1211 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1212 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1213 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1214 int boundw = x1 - x0;
1215 int boundh = y1 - y0;
1217 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1218 } while (p-- != state.pagedims);
1221 static
1222 struct anchor { int n; int x; int y; int w; int h; }
1223 desttoanchor (fz_link_dest *dest)
1225 int i;
1226 struct anchor a;
1227 struct pagedim *pdim = state.pagedims;
1229 a.n = -1;
1230 a.x = 0;
1231 a.y = 0;
1232 for (i = 0; i < state.pagedimcount; ++i) {
1233 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1234 break;
1235 pdim = &state.pagedims[i];
1237 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1238 fz_point p;
1239 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1240 p.x = dest->ld.gotor.lt.x;
1241 else
1242 p.x = 0.0;
1243 p.y = dest->ld.gotor.lt.y;
1244 fz_transform_point (&p, &pdim->lctm);
1245 a.x = p.x;
1246 a.y = p.y;
1248 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1249 double x0, x1, y0, y1;
1251 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1252 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1253 a.w = x1 - x0;
1254 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1255 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1256 a.h = y1 - y0;
1257 a.n = dest->ld.gotor.page;
1259 return a;
1262 static void recurse_outline (fz_outline *outline, int level)
1264 while (outline) {
1265 switch (outline->dest.kind) {
1266 case FZ_LINK_GOTO:
1268 struct anchor a = desttoanchor (&outline->dest);
1270 if (a.n >= 0) {
1271 printd ("o %d %d %d %d %s",
1272 level, a.n, a.y, a.h, outline->title);
1275 break;
1277 case FZ_LINK_URI:
1278 printd ("ou %d %" FMT_s " %s %s", level,
1279 strlen (outline->title), outline->title,
1280 outline->dest.ld.uri.uri);
1281 break;
1283 case FZ_LINK_NONE:
1284 printd ("on %d %s", level, outline->title);
1285 break;
1287 default:
1288 printd ("emsg Unhandled outline kind %d for %s\n",
1289 outline->dest.kind, outline->title);
1290 break;
1292 if (outline->down) {
1293 recurse_outline (outline->down, level + 1);
1295 outline = outline->next;
1299 static void process_outline (void)
1301 fz_outline *outline;
1303 if (!state.needoutline || !state.pagedimcount) return;
1305 state.needoutline = 0;
1306 outline = fz_load_outline (state.ctx, state.doc);
1307 if (outline) {
1308 recurse_outline (outline, 0);
1309 fz_drop_outline (state.ctx, outline);
1313 static char *strofspan (fz_stext_span *span)
1315 char *p;
1316 char utf8[10];
1317 fz_stext_char *ch;
1318 size_t size = 0, cap = 80;
1320 p = malloc (cap + 1);
1321 if (!p) return NULL;
1323 for (ch = span->text; ch < span->text + span->len; ++ch) {
1324 int n = fz_runetochar (utf8, ch->c);
1325 if (size + n > cap) {
1326 cap *= 2;
1327 p = realloc (p, cap + 1);
1328 if (!p) return NULL;
1331 memcpy (p + size, utf8, n);
1332 size += n;
1334 p[size] = 0;
1335 return p;
1338 static int matchspan (regex_t *re, fz_stext_span *span,
1339 int stop, int pageno, double start)
1341 int ret;
1342 char *p;
1343 regmatch_t rm;
1344 int a, b, c;
1345 fz_rect sb, eb;
1346 fz_point p1, p2, p3, p4;
1348 p = strofspan (span);
1349 if (!p) return -1;
1351 ret = regexec (re, p, 1, &rm, 0);
1352 if (ret) {
1353 free (p);
1354 if (ret != REG_NOMATCH) {
1355 size_t size;
1356 char errbuf[80];
1357 size = regerror (ret, re, errbuf, sizeof (errbuf));
1358 printd ("msg regexec error `%.*s'",
1359 (int) size, errbuf);
1360 return -1;
1362 return 0;
1364 else {
1365 int l = span->len;
1367 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1368 c += fz_runelen (span->text[a].c);
1370 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1371 c += fz_runelen (span->text[b].c);
1374 if (fz_runelen (span->text[b].c) > 1) {
1375 b = MAX (0, b-1);
1378 fz_stext_char_bbox (state.ctx, &sb, span, a);
1379 fz_stext_char_bbox (state.ctx, &eb, span, b);
1381 p1.x = sb.x0;
1382 p1.y = sb.y0;
1383 p2.x = eb.x1;
1384 p2.y = sb.y0;
1385 p3.x = eb.x1;
1386 p3.y = eb.y1;
1387 p4.x = sb.x0;
1388 p4.y = eb.y1;
1390 if (!stop) {
1391 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1392 pageno, 1,
1393 p1.x, p1.y,
1394 p2.x, p2.y,
1395 p3.x, p3.y,
1396 p4.x, p4.y);
1398 printd ("progress 1 found at %d `%.*s' in %f sec",
1399 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1400 now () - start);
1402 else {
1403 printd ("match %d %d %f %f %f %f %f %f %f %f",
1404 pageno, 2,
1405 p1.x, p1.y,
1406 p2.x, p2.y,
1407 p3.x, p3.y,
1408 p4.x, p4.y);
1410 free (p);
1411 return 1;
1415 static int compareblocks (const void *l, const void *r)
1417 fz_stext_block const *ls = l;
1418 fz_stext_block const *rs = r;
1419 return ls->bbox.y0 - rs->bbox.y0;
1422 /* wishful thinking function */
1423 static void search (regex_t *re, int pageno, int y, int forward)
1425 int i, j;
1426 fz_device *tdev;
1427 fz_stext_page *text;
1428 fz_stext_sheet *sheet;
1429 struct pagedim *pdim, *pdimprev;
1430 int stop = 0, niters = 0;
1431 double start, end;
1432 fz_page *page;
1434 start = now ();
1435 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1436 if (niters++ == 5) {
1437 niters = 0;
1438 if (hasdata ()) {
1439 printd ("progress 1 attention requested aborting search at %d",
1440 pageno);
1441 stop = 1;
1443 else {
1444 printd ("progress %f searching in page %d",
1445 (double) (pageno + 1) / state.pagecount,
1446 pageno);
1449 pdimprev = NULL;
1450 for (i = 0; i < state.pagedimcount; ++i) {
1451 pdim = &state.pagedims[i];
1452 if (pdim->pageno == pageno) {
1453 goto found;
1455 if (pdim->pageno > pageno) {
1456 pdim = pdimprev;
1457 goto found;
1459 pdimprev = pdim;
1461 pdim = pdimprev;
1462 found:
1464 sheet = fz_new_stext_sheet (state.ctx);
1465 text = fz_new_stext_page (state.ctx);
1466 tdev = fz_new_stext_device (state.ctx, sheet, text);
1468 page = fz_load_page (state.ctx, state.doc, pageno);
1470 fz_matrix ctm = pagectm1 (page, pdim);
1471 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1474 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1475 fz_drop_device (state.ctx, tdev);
1477 for (j = 0; j < text->len; ++j) {
1478 int k;
1479 fz_page_block *pb;
1480 fz_stext_block *block;
1482 pb = &text->blocks[forward ? j : text->len - 1 - j];
1483 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1484 block = pb->u.text;
1486 for (k = 0; k < block->len; ++k) {
1487 fz_stext_line *line;
1488 fz_stext_span *span;
1490 if (forward) {
1491 line = &block->lines[k];
1492 if (line->bbox.y0 < y + 1) continue;
1494 else {
1495 line = &block->lines[block->len - 1 - k];
1496 if (line->bbox.y0 > y - 1) continue;
1499 for (span = line->first_span; span; span = span->next) {
1500 switch (matchspan (re, span, stop, pageno, start)) {
1501 case 0: break;
1502 case 1: stop = 1; break;
1503 case -1: stop = 1; goto endloop;
1508 if (forward) {
1509 pageno += 1;
1510 y = 0;
1512 else {
1513 pageno -= 1;
1514 y = INT_MAX;
1516 endloop:
1517 fz_drop_stext_page (state.ctx, text);
1518 fz_drop_stext_sheet (state.ctx, sheet);
1519 fz_drop_page (state.ctx, page);
1521 end = now ();
1522 if (!stop) {
1523 printd ("progress 1 no matches %f sec", end - start);
1525 printd ("clearrects");
1528 static void set_tex_params (int colorspace)
1530 union {
1531 unsigned char b;
1532 unsigned int s;
1533 } endianness = {1};
1535 switch (colorspace) {
1536 case 0:
1537 state.texiform = GL_RGBA8;
1538 state.texform = GL_RGBA;
1539 state.texty = GL_UNSIGNED_BYTE;
1540 state.colorspace = fz_device_rgb (state.ctx);
1541 break;
1542 case 1:
1543 state.texiform = GL_RGBA8;
1544 state.texform = GL_BGRA;
1545 state.texty = endianness.s > 1
1546 ? GL_UNSIGNED_INT_8_8_8_8
1547 : GL_UNSIGNED_INT_8_8_8_8_REV;
1548 state.colorspace = fz_device_bgr (state.ctx);
1549 break;
1550 case 2:
1551 state.texiform = GL_LUMINANCE_ALPHA;
1552 state.texform = GL_LUMINANCE_ALPHA;
1553 state.texty = GL_UNSIGNED_BYTE;
1554 state.colorspace = fz_device_gray (state.ctx);
1555 break;
1556 default:
1557 errx (1, "invalid colorspce %d", colorspace);
1561 static void realloctexts (int texcount)
1563 size_t size;
1565 if (texcount == state.texcount) return;
1567 if (texcount < state.texcount) {
1568 glDeleteTextures (state.texcount - texcount,
1569 state.texids + texcount);
1572 size = texcount * sizeof (*state.texids);
1573 state.texids = realloc (state.texids, size);
1574 if (!state.texids) {
1575 err (1, "realloc texids %" FMT_s, size);
1578 size = texcount * sizeof (*state.texowners);
1579 state.texowners = realloc (state.texowners, size);
1580 if (!state.texowners) {
1581 err (1, "realloc texowners %" FMT_s, size);
1583 if (texcount > state.texcount) {
1584 int i;
1586 glGenTextures (texcount - state.texcount,
1587 state.texids + state.texcount);
1588 for (i = state.texcount; i < texcount; ++i) {
1589 state.texowners[i].w = -1;
1590 state.texowners[i].slice = NULL;
1593 state.texcount = texcount;
1594 state.texindex = 0;
1597 static char *mbtoutf8 (char *s)
1599 char *p, *r;
1600 wchar_t *tmp;
1601 size_t i, ret, len;
1603 len = mbstowcs (NULL, s, strlen (s));
1604 if (len == 0) {
1605 return s;
1607 else {
1608 if (len == (size_t) -1) {
1609 return s;
1613 tmp = malloc (len * sizeof (wchar_t));
1614 if (!tmp) {
1615 return s;
1618 ret = mbstowcs (tmp, s, len);
1619 if (ret == (size_t) -1) {
1620 free (tmp);
1621 return s;
1624 len = 0;
1625 for (i = 0; i < ret; ++i) {
1626 len += fz_runelen (tmp[i]);
1629 p = r = malloc (len + 1);
1630 if (!r) {
1631 free (tmp);
1632 return s;
1635 for (i = 0; i < ret; ++i) {
1636 p += fz_runetochar (p, tmp[i]);
1638 *p = 0;
1639 free (tmp);
1640 return r;
1643 CAMLprim value ml_mbtoutf8 (value s_v)
1645 CAMLparam1 (s_v);
1646 CAMLlocal1 (ret_v);
1647 char *s, *r;
1649 s = String_val (s_v);
1650 r = mbtoutf8 (s);
1651 if (r == s) {
1652 ret_v = s_v;
1654 else {
1655 ret_v = caml_copy_string (r);
1656 free (r);
1658 CAMLreturn (ret_v);
1661 static void * mainloop (void UNUSED_ATTR *unused)
1663 char *p = NULL;
1664 int len, ret, oldlen = 0;
1666 fz_var (p);
1667 fz_var (oldlen);
1668 for (;;) {
1669 len = readlen ();
1670 if (len == 0) {
1671 errx (1, "readlen returned 0");
1674 if (oldlen < len + 1) {
1675 p = realloc (p, len + 1);
1676 if (!p) {
1677 err (1, "realloc %d failed", len + 1);
1679 oldlen = len + 1;
1681 readdata (p, len);
1682 p[len] = 0;
1684 if (!strncmp ("open", p, 4)) {
1685 int wthack, off, ok = 0;
1686 char *password;
1687 char *filename;
1688 char *utf8filename;
1689 size_t filenamelen;
1691 fz_var (ok);
1692 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1693 if (ret != 2) {
1694 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1697 filename = p + 5 + off;
1698 filenamelen = strlen (filename);
1699 password = filename + filenamelen + 1;
1701 lock ("open");
1702 fz_try (state.ctx) {
1703 ok = openxref (filename, password);
1705 fz_catch (state.ctx) {
1706 utf8filename = mbtoutf8 (filename);
1707 printd ("msg Could not open %s", utf8filename);
1709 if (ok) {
1710 pdfinfo ();
1711 initpdims (wthack);
1713 unlock ("open");
1715 if (ok) {
1716 if (!wthack) {
1717 utf8filename = mbtoutf8 (filename);
1718 printd ("msg Opened %s (press h/F1 to get help)",
1719 utf8filename);
1720 if (utf8filename != filename) {
1721 free (utf8filename);
1724 state.needoutline = 1;
1727 else if (!strncmp ("cs", p, 2)) {
1728 int i, colorspace;
1730 ret = sscanf (p + 2, " %d", &colorspace);
1731 if (ret != 1) {
1732 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1734 lock ("cs");
1735 set_tex_params (colorspace);
1736 for (i = 0; i < state.texcount; ++i) {
1737 state.texowners[i].w = -1;
1738 state.texowners[i].slice = NULL;
1740 unlock ("cs");
1742 else if (!strncmp ("freepage", p, 8)) {
1743 void *ptr;
1745 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1746 if (ret != 1) {
1747 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1749 freepage (ptr);
1751 else if (!strncmp ("freetile", p, 8)) {
1752 void *ptr;
1754 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1755 if (ret != 1) {
1756 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1758 freetile (ptr);
1760 else if (!strncmp ("search", p, 6)) {
1761 int icase, pageno, y, len2, forward;
1762 char *pattern;
1763 regex_t re;
1765 ret = sscanf (p + 6, " %d %d %d %d,%n",
1766 &icase, &pageno, &y, &forward, &len2);
1767 if (ret != 4) {
1768 errx (1, "malformed search `%s' ret=%d", p, ret);
1771 pattern = p + 6 + len2;
1772 ret = regcomp (&re, pattern,
1773 REG_EXTENDED | (icase ? REG_ICASE : 0));
1774 if (ret) {
1775 char errbuf[80];
1776 size_t size;
1778 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1779 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1781 else {
1782 search (&re, pageno, y, forward);
1783 regfree (&re);
1786 else if (!strncmp ("geometry", p, 8)) {
1787 int w, h, fitmodel;
1789 printd ("clear");
1790 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1791 if (ret != 3) {
1792 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1795 lock ("geometry");
1796 state.h = h;
1797 if (w != state.w) {
1798 int i;
1799 state.w = w;
1800 for (i = 0; i < state.texcount; ++i) {
1801 state.texowners[i].slice = NULL;
1804 state.fitmodel = fitmodel;
1805 layout ();
1806 process_outline ();
1808 state.gen++;
1809 unlock ("geometry");
1810 printd ("continue %d", state.pagecount);
1812 else if (!strncmp ("reqlayout", p, 9)) {
1813 char *nameddest;
1814 int rotate, off, h;
1815 unsigned int fitmodel;
1816 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1818 printd ("clear");
1819 ret = sscanf (p + 9, " %d %u %d %n",
1820 &rotate, &fitmodel, &h, &off);
1821 if (ret != 3) {
1822 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1824 lock ("reqlayout");
1825 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1826 state.gen += 1;
1828 state.rotate = rotate;
1829 state.fitmodel = fitmodel;
1830 state.h = h;
1831 layout ();
1832 process_outline ();
1834 nameddest = p + 9 + off;
1835 if (pdf && nameddest && *nameddest) {
1836 struct anchor a;
1837 fz_link_dest dest;
1838 pdf_obj *needle, *obj;
1840 needle = pdf_new_string (state.ctx, pdf, nameddest,
1841 strlen (nameddest));
1842 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1843 if (obj) {
1844 dest = pdf_parse_link_dest (state.ctx, pdf,
1845 FZ_LINK_GOTO, obj);
1847 a = desttoanchor (&dest);
1848 if (a.n >= 0) {
1849 printd ("a %d %d %d", a.n, a.x, a.y);
1851 else {
1852 printd ("emsg failed to parse destination `%s'\n",
1853 nameddest);
1856 else {
1857 printd ("emsg destination `%s' not found\n",
1858 nameddest);
1860 pdf_drop_obj (state.ctx, needle);
1863 state.gen++;
1864 unlock ("reqlayout");
1865 printd ("continue %d", state.pagecount);
1867 else if (!strncmp ("page", p, 4)) {
1868 double a, b;
1869 struct page *page;
1870 int pageno, pindex;
1872 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1873 if (ret != 2) {
1874 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1877 lock ("page");
1878 a = now ();
1879 page = loadpage (pageno, pindex);
1880 b = now ();
1881 unlock ("page");
1883 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1885 else if (!strncmp ("tile", p, 4)) {
1886 int x, y, w, h;
1887 struct page *page;
1888 struct tile *tile;
1889 double a, b;
1890 void *data;
1892 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1893 SCN_ptr_cast (&page), &x, &y, &w, &h,
1894 SCN_ptr_cast (&data));
1895 if (ret != 6) {
1896 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1899 lock ("tile");
1900 a = now ();
1901 tile = rendertile (page, x, y, w, h, data);
1902 b = now ();
1903 unlock ("tile");
1905 printd ("tile %d %d %" FMT_ptr " %u %f",
1906 x, y,
1907 FMT_ptr_cast (tile),
1908 tile->w * tile->h * tile->pixmap->n,
1909 b - a);
1911 else if (!strncmp ("trimset", p, 7)) {
1912 fz_irect fuzz;
1913 int trimmargins;
1915 ret = sscanf (p + 7, " %d %d %d %d %d",
1916 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1917 if (ret != 5) {
1918 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1920 lock ("trimset");
1921 state.trimmargins = trimmargins;
1922 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1923 state.trimanew = 1;
1924 state.trimfuzz = fuzz;
1926 unlock ("trimset");
1928 else if (!strncmp ("settrim", p, 7)) {
1929 fz_irect fuzz;
1930 int trimmargins;
1932 ret = sscanf (p + 7, " %d %d %d %d %d",
1933 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1934 if (ret != 5) {
1935 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1937 printd ("clear");
1938 lock ("settrim");
1939 state.trimmargins = trimmargins;
1940 state.needoutline = 1;
1941 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1942 state.trimanew = 1;
1943 state.trimfuzz = fuzz;
1945 state.pagedimcount = 0;
1946 free (state.pagedims);
1947 state.pagedims = NULL;
1948 initpdims (0);
1949 layout ();
1950 process_outline ();
1951 unlock ("settrim");
1952 printd ("continue %d", state.pagecount);
1954 else if (!strncmp ("sliceh", p, 6)) {
1955 int h;
1957 ret = sscanf (p + 6, " %d", &h);
1958 if (ret != 1) {
1959 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1961 if (h != state.sliceheight) {
1962 int i;
1964 state.sliceheight = h;
1965 for (i = 0; i < state.texcount; ++i) {
1966 state.texowners[i].w = -1;
1967 state.texowners[i].h = -1;
1968 state.texowners[i].slice = NULL;
1972 else if (!strncmp ("interrupt", p, 9)) {
1973 printd ("vmsg interrupted");
1975 else {
1976 errx (1, "unknown command %.*s", len, p);
1979 return 0;
1982 CAMLprim value ml_realloctexts (value texcount_v)
1984 CAMLparam1 (texcount_v);
1985 int ok;
1987 if (trylock (__func__)) {
1988 ok = 0;
1989 goto done;
1991 realloctexts (Int_val (texcount_v));
1992 ok = 1;
1993 unlock (__func__);
1995 done:
1996 CAMLreturn (Val_bool (ok));
1999 static void recti (int x0, int y0, int x1, int y1)
2001 GLfloat *v = state.vertices;
2003 glVertexPointer (2, GL_FLOAT, 0, v);
2004 v[0] = x0; v[1] = y0;
2005 v[2] = x1; v[3] = y0;
2006 v[4] = x0; v[5] = y1;
2007 v[6] = x1; v[7] = y1;
2008 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2011 static void showsel (struct page *page, int ox, int oy)
2013 int seen = 0;
2014 fz_irect bbox;
2015 fz_rect rect;
2016 fz_stext_line *line;
2017 fz_page_block *pageb;
2018 fz_stext_block *block;
2019 struct mark first, last;
2020 unsigned char selcolor[] = {15,15,15,140};
2022 first = page->fmark;
2023 last = page->lmark;
2025 if (!first.span || !last.span) return;
2027 glEnable (GL_BLEND);
2028 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2029 glColor4ubv (selcolor);
2031 ox += state.pagedims[page->pdimno].bounds.x0;
2032 oy += state.pagedims[page->pdimno].bounds.y0;
2033 for (pageb = page->text->blocks;
2034 pageb < page->text->blocks + page->text->len;
2035 ++pageb) {
2036 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2037 block = pageb->u.text;
2039 for (line = block->lines;
2040 line < block->lines + block->len;
2041 ++line) {
2042 fz_stext_span *span;
2043 rect = fz_empty_rect;
2045 for (span = line->first_span; span; span = span->next) {
2046 int i, j, k;
2047 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2049 j = 0;
2050 k = span->len - 1;
2052 if (span == page->fmark.span && span == page->lmark.span) {
2053 seen = 1;
2054 j = MIN (first.i, last.i);
2055 k = MAX (first.i, last.i);
2057 else {
2058 if (span == first.span) {
2059 seen = 1;
2060 j = first.i;
2062 else if (span == last.span) {
2063 seen = 1;
2064 k = last.i;
2068 if (seen) {
2069 for (i = j; i <= k; ++i) {
2070 fz_rect bbox1;
2071 fz_union_rect (&rect,
2072 fz_stext_char_bbox (state.ctx, &bbox1,
2073 span, i));
2075 fz_round_rect (&bbox, &rect);
2076 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2077 bbox.x0,
2078 bbox.y0,
2079 bbox.x1,
2080 bbox.y1,
2081 oy, ox);
2083 recti (bbox.x0 + ox, bbox.y0 + oy,
2084 bbox.x1 + ox, bbox.y1 + oy);
2085 if (span == last.span) {
2086 goto done;
2088 rect = fz_empty_rect;
2093 done:
2094 glDisable (GL_BLEND);
2097 #include "glfont.c"
2099 static void stipplerect (fz_matrix *m,
2100 fz_point *p1,
2101 fz_point *p2,
2102 fz_point *p3,
2103 fz_point *p4,
2104 GLfloat *texcoords,
2105 GLfloat *vertices)
2107 fz_transform_point (p1, m);
2108 fz_transform_point (p2, m);
2109 fz_transform_point (p3, m);
2110 fz_transform_point (p4, m);
2112 float w, h, s, t;
2114 w = p2->x - p1->x;
2115 h = p2->y - p1->y;
2116 t = sqrtf (w*w + h*h) * .25f;
2118 w = p3->x - p2->x;
2119 h = p3->y - p2->y;
2120 s = sqrtf (w*w + h*h) * .25f;
2122 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2123 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2125 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2126 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2128 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2129 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2131 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2132 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2134 glDrawArrays (GL_LINES, 0, 8);
2137 static void solidrect (fz_matrix *m,
2138 fz_point *p1,
2139 fz_point *p2,
2140 fz_point *p3,
2141 fz_point *p4,
2142 GLfloat *vertices)
2144 fz_transform_point (p1, m);
2145 fz_transform_point (p2, m);
2146 fz_transform_point (p3, m);
2147 fz_transform_point (p4, m);
2148 vertices[0] = p1->x; vertices[1] = p1->y;
2149 vertices[2] = p2->x; vertices[3] = p2->y;
2151 vertices[4] = p3->x; vertices[5] = p3->y;
2152 vertices[6] = p4->x; vertices[7] = p4->y;
2153 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2156 static void highlightlinks (struct page *page, int xoff, int yoff)
2158 int i;
2159 fz_matrix ctm, tm, pm;
2160 fz_link *link, *links;
2161 GLfloat *texcoords = state.texcoords;
2162 GLfloat *vertices = state.vertices;
2164 links = fz_load_links (state.ctx, page->fzpage);
2166 glEnable (GL_TEXTURE_1D);
2167 glEnable (GL_BLEND);
2168 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2169 glBindTexture (GL_TEXTURE_1D, state.stid);
2171 xoff -= state.pagedims[page->pdimno].bounds.x0;
2172 yoff -= state.pagedims[page->pdimno].bounds.y0;
2173 fz_translate (&tm, xoff, yoff);
2174 pm = pagectm (page);
2175 fz_concat (&ctm, &pm, &tm);
2177 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2178 glVertexPointer (2, GL_FLOAT, 0, vertices);
2180 for (link = links; link; link = link->next) {
2181 fz_point p1, p2, p3, p4;
2183 p1.x = link->rect.x0;
2184 p1.y = link->rect.y0;
2186 p2.x = link->rect.x1;
2187 p2.y = link->rect.y0;
2189 p3.x = link->rect.x1;
2190 p3.y = link->rect.y1;
2192 p4.x = link->rect.x0;
2193 p4.y = link->rect.y1;
2195 switch (link->dest.kind) {
2196 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2197 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2198 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2199 default: glColor3ub (0, 0, 0); break;
2201 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2204 for (i = 0; i < page->annotcount; ++i) {
2205 fz_point p1, p2, p3, p4;
2206 struct annot *annot = &page->annots[i];
2208 p1.x = annot->bbox.x0;
2209 p1.y = annot->bbox.y0;
2211 p2.x = annot->bbox.x1;
2212 p2.y = annot->bbox.y0;
2214 p3.x = annot->bbox.x1;
2215 p3.y = annot->bbox.y1;
2217 p4.x = annot->bbox.x0;
2218 p4.y = annot->bbox.y1;
2220 glColor3ub (0, 0, 128);
2221 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2224 glDisable (GL_BLEND);
2225 glDisable (GL_TEXTURE_1D);
2228 static int compareslinks (const void *l, const void *r)
2230 struct slink const *ls = l;
2231 struct slink const *rs = r;
2232 if (ls->bbox.y0 == rs->bbox.y0) {
2233 return rs->bbox.x0 - rs->bbox.x0;
2235 return ls->bbox.y0 - rs->bbox.y0;
2238 static void droptext (struct page *page)
2240 if (page->text) {
2241 fz_drop_stext_page (state.ctx, page->text);
2242 page->fmark.i = -1;
2243 page->lmark.i = -1;
2244 page->fmark.span = NULL;
2245 page->lmark.span = NULL;
2246 page->text = NULL;
2248 if (page->sheet) {
2249 fz_drop_stext_sheet (state.ctx, page->sheet);
2250 page->sheet = NULL;
2254 static void dropannots (struct page *page)
2256 if (page->annots) {
2257 free (page->annots);
2258 page->annots = NULL;
2259 page->annotcount = 0;
2263 static void ensureannots (struct page *page)
2265 int i, count = 0;
2266 size_t annotsize = sizeof (*page->annots);
2267 fz_annot *annot;
2269 if (state.gen != page->agen) {
2270 dropannots (page);
2271 page->agen = state.gen;
2273 if (page->annots) return;
2275 for (annot = fz_first_annot (state.ctx, page->fzpage);
2276 annot;
2277 annot = fz_next_annot (state.ctx, page->fzpage, annot)) {
2278 count++;
2281 if (count > 0) {
2282 page->annotcount = count;
2283 page->annots = calloc (count, annotsize);
2284 if (!page->annots) {
2285 err (1, "calloc annots %d", count);
2288 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2289 annot;
2290 annot = fz_next_annot (state.ctx, page->fzpage, annot), i++) {
2291 fz_rect rect;
2293 fz_bound_annot (state.ctx, page->fzpage, annot, &rect);
2294 page->annots[i].annot = annot;
2295 fz_round_rect (&page->annots[i].bbox, &rect);
2300 static void dropslinks (struct page *page)
2302 if (page->slinks) {
2303 free (page->slinks);
2304 page->slinks = NULL;
2305 page->slinkcount = 0;
2309 static void ensureslinks (struct page *page)
2311 fz_matrix ctm;
2312 int i, count;
2313 size_t slinksize = sizeof (*page->slinks);
2314 fz_link *link, *links;
2316 ensureannots (page);
2317 if (state.gen != page->sgen) {
2318 dropslinks (page);
2319 page->sgen = state.gen;
2321 if (page->slinks) return;
2323 links = fz_load_links (state.ctx, page->fzpage);
2324 ctm = state.pagedims[page->pdimno].ctm;
2326 count = page->annotcount;
2327 for (link = links; link; link = link->next) {
2328 count++;
2330 if (count > 0) {
2331 int j;
2333 page->slinkcount = count;
2334 page->slinks = calloc (count, slinksize);
2335 if (!page->slinks) {
2336 err (1, "calloc slinks %d", count);
2339 for (i = 0, link = links; link; ++i, link = link->next) {
2340 fz_rect rect;
2342 rect = link->rect;
2343 fz_transform_rect (&rect, &ctm);
2344 page->slinks[i].tag = SLINK;
2345 page->slinks[i].u.link = link;
2346 fz_round_rect (&page->slinks[i].bbox, &rect);
2348 for (j = 0; j < page->annotcount; ++j, ++i) {
2349 fz_rect rect;
2350 fz_bound_annot (state.ctx,
2351 page->fzpage,
2352 page->annots[j].annot,
2353 &rect);
2354 fz_transform_rect (&rect, &ctm);
2355 fz_round_rect (&page->slinks[i].bbox, &rect);
2357 page->slinks[i].tag = SANNOT;
2358 page->slinks[i].u.annot = page->annots[j].annot;
2360 qsort (page->slinks, count, slinksize, compareslinks);
2364 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2365 static void fmt_linkn (char *s, unsigned int u)
2367 unsigned int len; unsigned int q;
2368 unsigned int zma = 'z' - 'a' + 1;
2369 len = 1; q = u;
2370 while (q > zma - 1) { ++len; q /= zma; }
2371 if (s) {
2372 s += len;
2373 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2374 /* handles u == 0 */
2376 s[len] = 0;
2379 static void highlightslinks (struct page *page, int xoff, int yoff,
2380 int noff, char *targ, int tlen, int hfsize)
2382 int i;
2383 char buf[40];
2384 struct slink *slink;
2385 double x0, y0, x1, y1, w;
2387 ensureslinks (page);
2388 glColor3ub (0xc3, 0xb0, 0x91);
2389 for (i = 0; i < page->slinkcount; ++i) {
2390 fmt_linkn (buf, i + noff);
2391 if (!tlen || !strncmp (targ, buf, tlen)) {
2392 slink = &page->slinks[i];
2394 x0 = slink->bbox.x0 + xoff - 5;
2395 y1 = slink->bbox.y0 + yoff - 5;
2396 y0 = y1 + 10 + hfsize;
2397 w = measure_string (state.face, hfsize, buf);
2398 x1 = x0 + w + 10;
2399 recti (x0, y0, x1, y1);
2403 glEnable (GL_BLEND);
2404 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2405 glEnable (GL_TEXTURE_2D);
2406 glColor3ub (0, 0, 0);
2407 for (i = 0; i < page->slinkcount; ++i) {
2408 fmt_linkn (buf, i + noff);
2409 if (!tlen || !strncmp (targ, buf, tlen)) {
2410 slink = &page->slinks[i];
2412 x0 = slink->bbox.x0 + xoff;
2413 y0 = slink->bbox.y0 + yoff + hfsize;
2414 draw_string (state.face, hfsize, x0, y0, buf);
2417 glDisable (GL_TEXTURE_2D);
2418 glDisable (GL_BLEND);
2421 static void uploadslice (struct tile *tile, struct slice *slice)
2423 int offset;
2424 struct slice *slice1;
2425 unsigned char *texdata;
2427 offset = 0;
2428 for (slice1 = tile->slices; slice != slice1; slice1++) {
2429 offset += slice1->h * tile->w * tile->pixmap->n;
2431 if (slice->texindex != -1 && slice->texindex < state.texcount
2432 && state.texowners[slice->texindex].slice == slice) {
2433 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2435 else {
2436 int subimage = 0;
2437 int texindex = state.texindex++ % state.texcount;
2439 if (state.texowners[texindex].w == tile->w) {
2440 if (state.texowners[texindex].h >= slice->h) {
2441 subimage = 1;
2443 else {
2444 state.texowners[texindex].h = slice->h;
2447 else {
2448 state.texowners[texindex].h = slice->h;
2451 state.texowners[texindex].w = tile->w;
2452 state.texowners[texindex].slice = slice;
2453 slice->texindex = texindex;
2455 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2456 #if TEXT_TYPE == GL_TEXTURE_2D
2457 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2458 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2459 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2460 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2461 #endif
2462 if (tile->pbo) {
2463 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2464 texdata = 0;
2466 else {
2467 texdata = tile->pixmap->samples;
2469 if (subimage) {
2470 glTexSubImage2D (TEXT_TYPE,
2474 tile->w,
2475 slice->h,
2476 state.texform,
2477 state.texty,
2478 texdata+offset
2481 else {
2482 glTexImage2D (TEXT_TYPE,
2484 state.texiform,
2485 tile->w,
2486 slice->h,
2488 state.texform,
2489 state.texty,
2490 texdata+offset
2493 if (tile->pbo) {
2494 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2499 CAMLprim value ml_begintiles (value unit_v)
2501 CAMLparam1 (unit_v);
2502 glEnable (TEXT_TYPE);
2503 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2504 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2505 CAMLreturn (unit_v);
2508 CAMLprim value ml_endtiles (value unit_v)
2510 CAMLparam1 (unit_v);
2511 glDisable (TEXT_TYPE);
2512 CAMLreturn (unit_v);
2515 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2517 CAMLparam2 (args_v, ptr_v);
2518 int dispx = Int_val (Field (args_v, 0));
2519 int dispy = Int_val (Field (args_v, 1));
2520 int dispw = Int_val (Field (args_v, 2));
2521 int disph = Int_val (Field (args_v, 3));
2522 int tilex = Int_val (Field (args_v, 4));
2523 int tiley = Int_val (Field (args_v, 5));
2524 char *s = String_val (ptr_v);
2525 struct tile *tile = parse_pointer (__func__, s);
2526 int slicey, firstslice;
2527 struct slice *slice;
2528 GLfloat *texcoords = state.texcoords;
2529 GLfloat *vertices = state.vertices;
2531 firstslice = tiley / tile->sliceheight;
2532 slice = &tile->slices[firstslice];
2533 slicey = tiley % tile->sliceheight;
2535 while (disph > 0) {
2536 int dh;
2538 dh = slice->h - slicey;
2539 dh = MIN (disph, dh);
2540 uploadslice (tile, slice);
2542 texcoords[0] = tilex; texcoords[1] = slicey;
2543 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2544 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2545 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2547 vertices[0] = dispx; vertices[1] = dispy;
2548 vertices[2] = dispx+dispw; vertices[3] = dispy;
2549 vertices[4] = dispx; vertices[5] = dispy+dh;
2550 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2552 #if TEXT_TYPE == GL_TEXTURE_2D
2553 for (int i = 0; i < 8; ++i) {
2554 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2556 #endif
2558 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2559 dispy += dh;
2560 disph -= dh;
2561 slice++;
2562 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2563 slicey = 0;
2565 CAMLreturn (Val_unit);
2568 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2570 fz_matrix ctm, tm, pm;
2571 fz_point p1, p2, p3, p4;
2572 GLfloat *vertices = state.vertices;
2573 double *v = (double *) rects_v;
2575 xoff -= state.pagedims[page->pdimno].bounds.x0;
2576 yoff -= state.pagedims[page->pdimno].bounds.y0;
2577 fz_translate (&tm, xoff, yoff);
2578 pm = pagectm (page);
2579 fz_concat (&ctm, &pm, &tm);
2581 glEnable (GL_BLEND);
2582 glVertexPointer (2, GL_FLOAT, 0, vertices);
2584 glColor4dv (v);
2585 p1.x = v[4];
2586 p1.y = v[5];
2588 p2.x = v[6];
2589 p2.y = v[5];
2591 p3.x = v[6];
2592 p3.y = v[7];
2594 p4.x = v[4];
2595 p4.y = v[7];
2596 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2597 glDisable (GL_BLEND);
2600 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2601 value xoff_v, value yoff_v,
2602 value li_v)
2604 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2605 int xoff = Int_val (xoff_v);
2606 int yoff = Int_val (yoff_v);
2607 int noff = Int_val (Field (li_v, 0));
2608 char *targ = String_val (Field (li_v, 1));
2609 int tlen = caml_string_length (Field (li_v, 1));
2610 int hfsize = Int_val (Field (li_v, 2));
2611 char *s = String_val (ptr_v);
2612 int hlmask = Int_val (hlinks_v);
2613 struct page *page = parse_pointer (__func__, s);
2615 if (!page->fzpage) {
2616 /* deal with loadpage failed pages */
2617 goto done;
2620 ensureannots (page);
2622 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2623 if (trylock (__func__)) {
2624 noff = 0;
2625 goto done;
2627 if (hlmask & 2) {
2628 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2629 noff = page->slinkcount;
2631 if (page->tgen == state.gen) {
2632 showsel (page, xoff, yoff);
2634 unlock (__func__);
2636 done:
2637 CAMLreturn (Val_int (noff));
2640 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2641 value rects_v)
2643 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2644 int xoff = Int_val (xoff_v);
2645 int yoff = Int_val (yoff_v);
2646 char *s = String_val (ptr_v);
2647 struct page *page = parse_pointer (__func__, s);
2649 drawprect (page, xoff, yoff, rects_v);
2650 CAMLreturn (Val_unit);
2653 static struct annot *getannot (struct page *page, int x, int y)
2655 int i;
2656 fz_point p;
2657 fz_matrix ctm;
2658 const fz_matrix *tctm;
2659 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2661 if (!page->annots) return NULL;
2663 if (pdf) {
2664 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2665 tctm = &state.pagedims[page->pdimno].tctm;
2667 else {
2668 tctm = &fz_identity;
2671 p.x = x;
2672 p.y = y;
2674 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2675 fz_invert_matrix (&ctm, &ctm);
2676 fz_transform_point (&p, &ctm);
2678 if (pdf) {
2679 for (i = 0; i < page->annotcount; ++i) {
2680 struct annot *a = &page->annots[i];
2681 pdf_annot *annot = (pdf_annot *) a->annot;
2682 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2683 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2684 return a;
2689 return NULL;
2692 static fz_link *getlink (struct page *page, int x, int y)
2694 fz_point p;
2695 fz_matrix ctm;
2696 const fz_matrix *tctm;
2697 fz_link *link, *links;
2699 tctm = &fz_identity;
2700 links = fz_load_links (state.ctx, page->fzpage);
2702 p.x = x;
2703 p.y = y;
2705 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2706 fz_invert_matrix (&ctm, &ctm);
2707 fz_transform_point (&p, &ctm);
2709 for (link = links; link; link = link->next) {
2710 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2711 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2712 return link;
2716 return NULL;
2719 static void ensuretext (struct page *page)
2721 if (state.gen != page->tgen) {
2722 droptext (page);
2723 page->tgen = state.gen;
2725 if (!page->text) {
2726 fz_matrix ctm;
2727 fz_device *tdev;
2729 page->text = fz_new_stext_page (state.ctx);
2730 page->sheet = fz_new_stext_sheet (state.ctx);
2731 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2732 ctm = pagectm (page);
2733 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2734 fz_run_display_list (state.ctx, page->dlist,
2735 tdev, &ctm, &fz_infinite_rect, NULL);
2736 qsort (page->text->blocks, page->text->len,
2737 sizeof (*page->text->blocks), compareblocks);
2738 fz_end_page (state.ctx, tdev);
2739 fz_drop_device (state.ctx, tdev);
2743 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2745 CAMLparam2 (start_page_v, dir_v);
2746 CAMLlocal1 (ret_v);
2747 int i, dir = Int_val (dir_v);
2748 int start_page = Int_val (start_page_v);
2749 int end_page = dir > 0 ? state.pagecount : -1;
2750 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2752 fz_var (end_page);
2753 ret_v = Val_int (0);
2754 lock (__func__);
2755 for (i = start_page + dir; i != end_page; i += dir) {
2756 int found;
2758 fz_var (found);
2759 if (pdf) {
2760 pdf_page *page = NULL;
2762 fz_try (state.ctx) {
2763 page = pdf_load_page (state.ctx, pdf, i);
2764 found = !!page->links || !!page->annots;
2766 fz_catch (state.ctx) {
2767 found = 0;
2769 if (page) {
2770 fz_drop_page (state.ctx, &page->super);
2773 else {
2774 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2775 found = !!fz_load_links (state.ctx, page);
2776 fz_drop_page (state.ctx, page);
2779 if (found) {
2780 ret_v = caml_alloc_small (1, 1);
2781 Field (ret_v, 0) = Val_int (i);
2782 goto unlock;
2785 unlock:
2786 unlock (__func__);
2787 CAMLreturn (ret_v);
2790 enum { dir_first, dir_last };
2791 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2793 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2795 CAMLparam2 (ptr_v, dir_v);
2796 CAMLlocal2 (ret_v, pos_v);
2797 struct page *page;
2798 int dirtag, i, slinkindex;
2799 struct slink *found = NULL ,*slink;
2800 char *s = String_val (ptr_v);
2802 page = parse_pointer (__func__, s);
2803 ret_v = Val_int (0);
2804 /* This is scary we are not taking locks here ensureslinks does
2805 not modify state and given that we obtained the page it can not
2806 disappear under us either */
2807 lock (__func__);
2808 ensureslinks (page);
2810 if (Is_block (dir_v)) {
2811 dirtag = Tag_val (dir_v);
2812 switch (dirtag) {
2813 case dir_first_visible:
2815 int x0, y0, dir, first_index, last_index;
2817 pos_v = Field (dir_v, 0);
2818 x0 = Int_val (Field (pos_v, 0));
2819 y0 = Int_val (Field (pos_v, 1));
2820 dir = Int_val (Field (pos_v, 2));
2822 if (dir >= 0) {
2823 dir = 1;
2824 first_index = 0;
2825 last_index = page->slinkcount;
2827 else {
2828 first_index = page->slinkcount - 1;
2829 last_index = -1;
2832 for (i = first_index; i != last_index; i += dir) {
2833 slink = &page->slinks[i];
2834 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2835 found = slink;
2836 break;
2840 break;
2842 case dir_left:
2843 slinkindex = Int_val (Field (dir_v, 0));
2844 found = &page->slinks[slinkindex];
2845 for (i = slinkindex - 1; i >= 0; --i) {
2846 slink = &page->slinks[i];
2847 if (slink->bbox.x0 < found->bbox.x0) {
2848 found = slink;
2849 break;
2852 break;
2854 case dir_right:
2855 slinkindex = Int_val (Field (dir_v, 0));
2856 found = &page->slinks[slinkindex];
2857 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2858 slink = &page->slinks[i];
2859 if (slink->bbox.x0 > found->bbox.x0) {
2860 found = slink;
2861 break;
2864 break;
2866 case dir_down:
2867 slinkindex = Int_val (Field (dir_v, 0));
2868 found = &page->slinks[slinkindex];
2869 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2870 slink = &page->slinks[i];
2871 if (slink->bbox.y0 >= found->bbox.y0) {
2872 found = slink;
2873 break;
2876 break;
2878 case dir_up:
2879 slinkindex = Int_val (Field (dir_v, 0));
2880 found = &page->slinks[slinkindex];
2881 for (i = slinkindex - 1; i >= 0; --i) {
2882 slink = &page->slinks[i];
2883 if (slink->bbox.y0 <= found->bbox.y0) {
2884 found = slink;
2885 break;
2888 break;
2891 else {
2892 dirtag = Int_val (dir_v);
2893 switch (dirtag) {
2894 case dir_first:
2895 found = page->slinks;
2896 break;
2898 case dir_last:
2899 if (page->slinks) {
2900 found = page->slinks + (page->slinkcount - 1);
2902 break;
2905 if (found) {
2906 ret_v = caml_alloc_small (2, 1);
2907 Field (ret_v, 0) = Val_int (found - page->slinks);
2910 unlock (__func__);
2911 CAMLreturn (ret_v);
2914 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2915 unamed, uremote, uremotedest, uannot };
2917 #define LINKTOVAL \
2919 int pageno; \
2921 switch (link->dest.kind) { \
2922 case FZ_LINK_GOTO: \
2924 fz_point p; \
2926 pageno = link->dest.ld.gotor.page; \
2927 p.x = 0; \
2928 p.y = 0; \
2930 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2931 p.y = link->dest.ld.gotor.lt.y; \
2932 fz_transform_point (&p, &pdim->lctm); \
2933 if (p.y < 0) p.y = 0; \
2935 tup_v = caml_alloc_tuple (2); \
2936 ret_v = caml_alloc_small (1, ugoto); \
2937 Field (tup_v, 0) = Val_int (pageno); \
2938 Field (tup_v, 1) = Val_int (p.y); \
2939 Field (ret_v, 0) = tup_v; \
2941 break; \
2943 case FZ_LINK_URI: \
2944 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2945 ret_v = caml_alloc_small (1, uuri); \
2946 Field (ret_v, 0) = str_v; \
2947 break; \
2949 case FZ_LINK_LAUNCH: \
2950 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2951 ret_v = caml_alloc_small (1, ulaunch); \
2952 Field (ret_v, 0) = str_v; \
2953 break; \
2955 case FZ_LINK_NAMED: \
2956 str_v = caml_copy_string (link->dest.ld.named.named); \
2957 ret_v = caml_alloc_small (1, unamed); \
2958 Field (ret_v, 0) = str_v; \
2959 break; \
2961 case FZ_LINK_GOTOR: \
2963 int rty; \
2965 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2966 pageno = link->dest.ld.gotor.page; \
2967 if (pageno == -1) { \
2968 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2969 rty = uremotedest; \
2971 else { \
2972 gr_v = Val_int (pageno); \
2973 rty = uremote; \
2975 tup_v = caml_alloc_tuple (2); \
2976 ret_v = caml_alloc_small (1, rty); \
2977 Field (tup_v, 0) = str_v; \
2978 Field (tup_v, 1) = gr_v; \
2979 Field (ret_v, 0) = tup_v; \
2981 break; \
2983 default: \
2985 char buf[80]; \
2987 snprintf (buf, sizeof (buf), \
2988 "unhandled link kind %d", link->dest.kind); \
2989 str_v = caml_copy_string (buf); \
2990 ret_v = caml_alloc_small (1, uunexpected); \
2991 Field (ret_v, 0) = str_v; \
2993 break; \
2997 CAMLprim value ml_getlink (value ptr_v, value n_v)
2999 CAMLparam2 (ptr_v, n_v);
3000 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3001 fz_link *link;
3002 struct page *page;
3003 struct pagedim *pdim;
3004 char *s = String_val (ptr_v);
3005 struct slink *slink;
3007 /* See ml_findlink for caveat */
3009 ret_v = Val_int (0);
3010 page = parse_pointer (__func__, s);
3011 ensureslinks (page);
3012 pdim = &state.pagedims[page->pdimno];
3013 slink = &page->slinks[Int_val (n_v)];
3014 if (slink->tag == SLINK) {
3015 link = slink->u.link;
3016 LINKTOVAL;
3018 else {
3019 ret_v = caml_alloc_small (1, uannot);
3020 tup_v = caml_alloc_tuple (2);
3021 Field (ret_v, 0) = tup_v;
3022 Field (tup_v, 0) = ptr_v;
3023 Field (tup_v, 1) = n_v;
3026 CAMLreturn (ret_v);
3029 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3031 CAMLparam2 (ptr_v, n_v);
3032 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3033 if (pdf) {
3034 char *s = String_val (ptr_v);
3035 struct page *page;
3036 struct slink *slink;
3038 page = parse_pointer (__func__, s);
3039 slink = &page->slinks[Int_val (n_v)];
3040 CAMLreturn (caml_copy_string (
3041 pdf_annot_contents (state.ctx, pdf,
3042 (pdf_annot *) slink->u.annot)));
3044 else {
3045 CAMLreturn (caml_copy_string (""));
3049 CAMLprim value ml_getlinkcount (value ptr_v)
3051 CAMLparam1 (ptr_v);
3052 struct page *page;
3053 char *s = String_val (ptr_v);
3055 page = parse_pointer (__func__, s);
3056 CAMLreturn (Val_int (page->slinkcount));
3059 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3061 CAMLparam2 (ptr_v, n_v);
3062 CAMLlocal1 (ret_v);
3063 struct page *page;
3064 struct slink *slink;
3065 char *s = String_val (ptr_v);
3066 /* See ml_findlink for caveat */
3068 page = parse_pointer (__func__, s);
3069 ret_v = caml_alloc_tuple (4);
3070 ensureslinks (page);
3072 slink = &page->slinks[Int_val (n_v)];
3073 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3074 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3075 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3076 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3077 unlock (__func__);
3078 CAMLreturn (ret_v);
3081 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3083 CAMLparam3 (ptr_v, x_v, y_v);
3084 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3085 fz_link *link;
3086 struct annot *annot;
3087 struct page *page;
3088 char *ptr = String_val (ptr_v);
3089 int x = Int_val (x_v), y = Int_val (y_v);
3090 struct pagedim *pdim;
3092 ret_v = Val_int (0);
3093 if (trylock (__func__)) {
3094 goto done;
3097 page = parse_pointer (__func__, ptr);
3098 pdim = &state.pagedims[page->pdimno];
3099 x += pdim->bounds.x0;
3100 y += pdim->bounds.y0;
3103 annot = getannot (page, x, y);
3104 if (annot) {
3105 int i, n = -1;
3107 ensureslinks (page);
3108 for (i = 0; i < page->slinkcount; ++i) {
3109 if (page->slinks[i].tag == SANNOT
3110 && page->slinks[i].u.annot == annot->annot) {
3111 n = i;
3112 break;
3115 ret_v = caml_alloc_small (1, uannot);
3116 tup_v = caml_alloc_tuple (2);
3117 Field (ret_v, 0) = tup_v;
3118 Field (tup_v, 0) = ptr_v;
3119 Field (tup_v, 1) = Val_int (n);
3120 goto unlock;
3124 link = getlink (page, x, y);
3125 if (link) {
3126 LINKTOVAL;
3128 else {
3129 fz_rect *b;
3130 fz_page_block *pageb;
3131 fz_stext_block *block;
3133 ensuretext (page);
3134 for (pageb = page->text->blocks;
3135 pageb < page->text->blocks + page->text->len;
3136 ++pageb) {
3137 fz_stext_line *line;
3138 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3139 block = pageb->u.text;
3141 b = &block->bbox;
3142 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3143 continue;
3145 for (line = block->lines;
3146 line < block->lines + block->len;
3147 ++line) {
3148 fz_stext_span *span;
3150 b = &line->bbox;
3151 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3152 continue;
3154 for (span = line->first_span; span; span = span->next) {
3155 int charnum;
3157 b = &span->bbox;
3158 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3159 continue;
3161 for (charnum = 0; charnum < span->len; ++charnum) {
3162 fz_rect bbox;
3163 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3164 b = &bbox;
3166 if (x >= b->x0 && x <= b->x1
3167 && y >= b->y0 && y <= b->y1) {
3168 fz_stext_style *style = span->text->style;
3169 const char *n2 =
3170 style->font
3171 ? style->font->name
3172 : "Span has no font name"
3174 FT_FaceRec *face = style->font->ft_face;
3175 if (face && face->family_name) {
3176 char *s;
3177 char *n1 = face->family_name;
3178 size_t l1 = strlen (n1);
3179 size_t l2 = strlen (n2);
3181 if (l1 != l2 || memcmp (n1, n2, l1)) {
3182 s = malloc (l1 + l2 + 2);
3183 if (s) {
3184 memcpy (s, n2, l2);
3185 s[l2] = '=';
3186 memcpy (s + l2 + 1, n1, l1 + 1);
3187 str_v = caml_copy_string (s);
3188 free (s);
3192 if (str_v == Val_unit) {
3193 str_v = caml_copy_string (n2);
3195 ret_v = caml_alloc_small (1, utext);
3196 Field (ret_v, 0) = str_v;
3197 goto unlock;
3204 unlock:
3205 unlock (__func__);
3207 done:
3208 CAMLreturn (ret_v);
3211 enum { mark_page, mark_block, mark_line, mark_word };
3213 static int uninteresting (int c)
3215 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3216 || ispunct (c);
3219 CAMLprim value ml_clearmark (value ptr_v)
3221 CAMLparam1 (ptr_v);
3222 char *s = String_val (ptr_v);
3223 struct page *page;
3225 if (trylock (__func__)) {
3226 goto done;
3229 page = parse_pointer (__func__, s);
3230 page->fmark.span = NULL;
3231 page->lmark.span = NULL;
3232 page->fmark.i = 0;
3233 page->lmark.i = 0;
3235 unlock (__func__);
3236 done:
3237 CAMLreturn (Val_unit);
3240 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3242 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3243 CAMLlocal1 (ret_v);
3244 fz_rect *b;
3245 struct page *page;
3246 fz_stext_line *line;
3247 fz_page_block *pageb;
3248 fz_stext_block *block;
3249 struct pagedim *pdim;
3250 int mark = Int_val (mark_v);
3251 char *s = String_val (ptr_v);
3252 int x = Int_val (x_v), y = Int_val (y_v);
3254 ret_v = Val_bool (0);
3255 if (trylock (__func__)) {
3256 goto done;
3259 page = parse_pointer (__func__, s);
3260 pdim = &state.pagedims[page->pdimno];
3262 ensuretext (page);
3264 if (mark == mark_page) {
3265 int i;
3266 fz_page_block *pb1 = NULL, *pb2 = NULL;
3268 for (i = 0; i < page->text->len; ++i) {
3269 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3270 pb1 = &page->text->blocks[i];
3271 break;
3274 if (!pb1) goto unlock;
3276 for (i = page->text->len - 1; i >= 0; --i) {
3277 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3278 pb2 = &page->text->blocks[i];
3279 break;
3282 if (!pb2) goto unlock;
3284 block = pb1->u.text;
3286 page->fmark.i = 0;
3287 page->fmark.span = block->lines->first_span;
3289 block = pb2->u.text;
3290 line = &block->lines[block->len - 1];
3291 page->lmark.i = line->last_span->len - 1;
3292 page->lmark.span = line->last_span;
3293 ret_v = Val_bool (1);
3294 goto unlock;
3297 x += pdim->bounds.x0;
3298 y += pdim->bounds.y0;
3300 for (pageb = page->text->blocks;
3301 pageb < page->text->blocks + page->text->len;
3302 ++pageb) {
3303 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3304 block = pageb->u.text;
3306 b = &block->bbox;
3307 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3308 continue;
3310 if (mark == mark_block) {
3311 page->fmark.i = 0;
3312 page->fmark.span = block->lines->first_span;
3314 line = &block->lines[block->len - 1];
3315 page->lmark.i = line->last_span->len - 1;
3316 page->lmark.span = line->last_span;
3317 ret_v = Val_bool (1);
3318 goto unlock;
3321 for (line = block->lines;
3322 line < block->lines + block->len;
3323 ++line) {
3324 fz_stext_span *span;
3326 b = &line->bbox;
3327 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3328 continue;
3330 if (mark == mark_line) {
3331 page->fmark.i = 0;
3332 page->fmark.span = line->first_span;
3334 page->lmark.i = line->last_span->len - 1;
3335 page->lmark.span = line->last_span;
3336 ret_v = Val_bool (1);
3337 goto unlock;
3340 for (span = line->first_span; span; span = span->next) {
3341 int charnum;
3343 b = &span->bbox;
3344 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3345 continue;
3347 for (charnum = 0; charnum < span->len; ++charnum) {
3348 fz_rect bbox;
3349 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3350 b = &bbox;
3352 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3353 /* unicode ftw */
3354 int charnum2, charnum3 = -1, charnum4 = -1;
3356 if (uninteresting (span->text[charnum].c)) goto unlock;
3358 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3359 if (uninteresting (span->text[charnum2].c)) {
3360 charnum3 = charnum2 + 1;
3361 break;
3364 if (charnum3 == -1) charnum3 = 0;
3366 for (charnum2 = charnum + 1;
3367 charnum2 < span->len;
3368 ++charnum2) {
3369 if (uninteresting (span->text[charnum2].c)) break;
3370 charnum4 = charnum2;
3372 if (charnum4 == -1) goto unlock;
3374 page->fmark.i = charnum3;
3375 page->fmark.span = span;
3377 page->lmark.i = charnum4;
3378 page->lmark.span = span;
3379 ret_v = Val_bool (1);
3380 goto unlock;
3386 unlock:
3387 if (!Bool_val (ret_v)) {
3388 page->fmark.span = NULL;
3389 page->lmark.span = NULL;
3390 page->fmark.i = 0;
3391 page->lmark.i = 0;
3393 unlock (__func__);
3395 done:
3396 CAMLreturn (ret_v);
3399 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3401 CAMLparam3 (ptr_v, x_v, y_v);
3402 CAMLlocal2 (ret_v, res_v);
3403 fz_rect *b = NULL;
3404 struct page *page;
3405 fz_page_block *pageb;
3406 struct pagedim *pdim;
3407 char *s = String_val (ptr_v);
3408 int x = Int_val (x_v), y = Int_val (y_v);
3410 ret_v = Val_int (0);
3411 if (trylock (__func__)) {
3412 goto done;
3415 page = parse_pointer (__func__, s);
3416 pdim = &state.pagedims[page->pdimno];
3417 x += pdim->bounds.x0;
3418 y += pdim->bounds.y0;
3420 ensuretext (page);
3422 for (pageb = page->text->blocks;
3423 pageb < page->text->blocks + page->text->len;
3424 ++pageb) {
3425 switch (pageb->type) {
3426 case FZ_PAGE_BLOCK_TEXT:
3427 b = &pageb->u.text->bbox;
3428 break;
3430 case FZ_PAGE_BLOCK_IMAGE:
3431 b = &pageb->u.image->bbox;
3432 break;
3434 default:
3435 continue;
3438 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3439 break;
3440 b = NULL;
3442 if (b) {
3443 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3444 ret_v = caml_alloc_small (1, 1);
3445 Store_double_field (res_v, 0, b->x0);
3446 Store_double_field (res_v, 1, b->x1);
3447 Store_double_field (res_v, 2, b->y0);
3448 Store_double_field (res_v, 3, b->y1);
3449 Field (ret_v, 0) = res_v;
3451 unlock (__func__);
3453 done:
3454 CAMLreturn (ret_v);
3457 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3459 CAMLparam2 (ptr_v, rect_v);
3460 fz_rect b;
3461 struct page *page;
3462 struct pagedim *pdim;
3463 char *s = String_val (ptr_v);
3464 int i, x0, x1, y0, y1, fi, li;
3465 fz_stext_line *line;
3466 fz_page_block *pageb;
3467 fz_stext_block *block;
3468 fz_stext_span *span, *fspan, *lspan;
3470 if (trylock (__func__)) {
3471 goto done;
3474 page = parse_pointer (__func__, s);
3475 ensuretext (page);
3477 pdim = &state.pagedims[page->pdimno];
3478 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3479 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3480 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3481 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3483 if (y0 > y1) {
3484 int t = y0;
3485 y0 = y1;
3486 y1 = t;
3487 x0 = x1;
3488 x1 = t;
3491 fi = page->fmark.i;
3492 fspan = page->fmark.span;
3494 li = page->lmark.i;
3495 lspan = page->lmark.span;
3497 for (pageb = page->text->blocks;
3498 pageb < page->text->blocks + page->text->len;
3499 ++pageb) {
3500 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3501 block = pageb->u.text;
3502 for (line = block->lines;
3503 line < block->lines + block->len;
3504 ++line) {
3506 for (span = line->first_span; span; span = span->next) {
3507 for (i = 0; i < span->len; ++i) {
3508 fz_stext_char_bbox (state.ctx, &b, span, i);
3510 if (x0 >= b.x0 && x0 <= b.x1
3511 && y0 >= b.y0 && y0 <= b.y1) {
3512 fspan = span;
3513 fi = i;
3515 if (x1 >= b.x0 && x1 <= b.x1
3516 && y1 >= b.y0 && y1 <= b.y1) {
3517 lspan = span;
3518 li = i;
3524 if (x1 < x0 && fspan == lspan) {
3525 i = fi;
3526 span = fspan;
3528 fi = li;
3529 fspan = lspan;
3531 li = i;
3532 lspan = span;
3535 page->fmark.i = fi;
3536 page->fmark.span = fspan;
3538 page->lmark.i = li;
3539 page->lmark.span = lspan;
3541 unlock (__func__);
3543 done:
3544 CAMLreturn (Val_unit);
3547 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3549 char buf[4];
3550 int i, len, ret;
3552 for (i = a; i <= b; ++i) {
3553 len = fz_runetochar (buf, span->text[i].c);
3554 ret = fwrite (buf, len, 1, f);
3556 if (ret != 1) {
3557 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3558 len, ret, strerror (errno));
3559 return -1;
3562 return 0;
3565 #ifdef __CYGWIN__
3566 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3568 caml_failwith ("ml_popen not implemented under Cygwin");
3570 #else
3571 CAMLprim value ml_spawn (value command_v, value fds_v)
3573 CAMLparam2 (command_v, fds_v);
3574 CAMLlocal2 (l_v, tup_v);
3575 int ret, ret1;
3576 pid_t pid;
3577 char *msg = NULL;
3578 value earg_v = Nothing;
3579 posix_spawnattr_t attr;
3580 posix_spawn_file_actions_t fa;
3581 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3583 argv[2] = String_val (command_v);
3585 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3586 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3589 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3590 msg = "posix_spawnattr_init";
3591 goto fail1;
3594 #ifdef POSIX_SPAWN_USEVFORK
3595 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3596 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3597 goto fail;
3599 #endif
3601 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3602 int fd1, fd2;
3604 tup_v = Field (l_v, 0);
3605 fd1 = Int_val (Field (tup_v, 0));
3606 fd2 = Int_val (Field (tup_v, 1));
3607 if (fd2 < 0) {
3608 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3609 msg = "posix_spawn_file_actions_addclose";
3610 earg_v = tup_v;
3611 goto fail;
3614 else {
3615 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3616 msg = "posix_spawn_file_actions_adddup2";
3617 earg_v = tup_v;
3618 goto fail;
3623 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3624 msg = "posix_spawn";
3625 goto fail;
3628 fail:
3629 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3630 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3633 fail1:
3634 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3635 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3636 strerror (ret1));
3639 if (msg)
3640 unix_error (ret, msg, earg_v);
3642 CAMLreturn (Val_int (pid));
3644 #endif
3646 CAMLprim value ml_hassel (value ptr_v)
3648 CAMLparam1 (ptr_v);
3649 CAMLlocal1 (ret_v);
3650 struct page *page;
3651 char *s = String_val (ptr_v);
3653 ret_v = Val_bool (0);
3654 if (trylock (__func__)) {
3655 goto done;
3658 page = parse_pointer (__func__, s);
3659 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3660 unlock (__func__);
3661 done:
3662 CAMLreturn (ret_v);
3665 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3667 CAMLparam2 (fd_v, ptr_v);
3668 FILE *f;
3669 int seen = 0;
3670 struct page *page;
3671 fz_stext_line *line;
3672 fz_page_block *pageb;
3673 fz_stext_block *block;
3674 int fd = Int_val (fd_v);
3675 char *s = String_val (ptr_v);
3677 if (trylock (__func__)) {
3678 goto done;
3681 page = parse_pointer (__func__, s);
3683 if (!page->fmark.span || !page->lmark.span) {
3684 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3685 goto unlock;
3688 f = fdopen (fd, "w");
3689 if (!f) {
3690 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3691 fd, strerror (errno));
3692 f = stdout;
3695 for (pageb = page->text->blocks;
3696 pageb < page->text->blocks + page->text->len;
3697 ++pageb) {
3698 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3699 block = pageb->u.text;
3700 for (line = block->lines;
3701 line < block->lines + block->len;
3702 ++line) {
3703 fz_stext_span *span;
3705 for (span = line->first_span; span; span = span->next) {
3706 int a, b;
3708 seen |= span == page->fmark.span || span == page->lmark.span;
3709 a = span == page->fmark.span ? page->fmark.i : 0;
3710 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3712 if (seen) {
3713 if (pipespan (f, span, a, b)) {
3714 goto close;
3716 if (span == page->lmark.span) {
3717 goto close;
3719 if (span == line->last_span) {
3720 if (putc ('\n', f) == EOF) {
3721 fprintf (stderr,
3722 "failed break line on sel pipe: %s\n",
3723 strerror (errno));
3724 goto close;
3731 close:
3732 if (f != stdout) {
3733 int ret = fclose (f);
3734 fd = -1;
3735 if (ret == -1) {
3736 if (errno != ECHILD) {
3737 fprintf (stderr, "failed to close sel pipe: %s\n",
3738 strerror (errno));
3742 unlock:
3743 unlock (__func__);
3745 done:
3746 if (fd >= 0) {
3747 if (close (fd)) {
3748 fprintf (stderr, "failed to close sel pipe: %s\n",
3749 strerror (errno));
3752 CAMLreturn (Val_unit);
3755 CAMLprim value ml_getpdimrect (value pagedimno_v)
3757 CAMLparam1 (pagedimno_v);
3758 CAMLlocal1 (ret_v);
3759 int pagedimno = Int_val (pagedimno_v);
3760 fz_rect box;
3762 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3763 if (trylock (__func__)) {
3764 box = fz_empty_rect;
3766 else {
3767 box = state.pagedims[pagedimno].mediabox;
3768 unlock (__func__);
3771 Store_double_field (ret_v, 0, box.x0);
3772 Store_double_field (ret_v, 1, box.x1);
3773 Store_double_field (ret_v, 2, box.y0);
3774 Store_double_field (ret_v, 3, box.y1);
3776 CAMLreturn (ret_v);
3779 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3780 value dw_v, value cols_v)
3782 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3783 CAMLlocal1 (ret_v);
3784 int i;
3785 double zoom = -1.;
3786 double maxh = 0.0;
3787 struct pagedim *p;
3788 double winw = Int_val (winw_v);
3789 double winh = Int_val (winh_v);
3790 double dw = Int_val (dw_v);
3791 double cols = Int_val (cols_v);
3792 double pw = 1.0, ph = 1.0;
3794 if (trylock (__func__)) {
3795 goto done;
3798 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3799 double w = p->pagebox.x1 / cols;
3800 double h = p->pagebox.y1;
3801 if (h > maxh) {
3802 maxh = h;
3803 ph = h;
3804 if (state.fitmodel != FitProportional) pw = w;
3806 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3809 zoom = (((winh / ph) * pw) + dw) / winw;
3810 unlock (__func__);
3811 done:
3812 ret_v = caml_copy_double (zoom);
3813 CAMLreturn (ret_v);
3816 CAMLprim value ml_getmaxw (value unit_v)
3818 CAMLparam1 (unit_v);
3819 CAMLlocal1 (ret_v);
3820 int i;
3821 double maxw = -1.;
3822 struct pagedim *p;
3824 if (trylock (__func__)) {
3825 goto done;
3828 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3829 double w = p->pagebox.x1;
3830 maxw = MAX (maxw, w);
3833 unlock (__func__);
3834 done:
3835 ret_v = caml_copy_double (maxw);
3836 CAMLreturn (ret_v);
3839 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3841 CAMLparam4 (pt_v, x_v, y_v, string_v);
3842 CAMLlocal1 (ret_v);
3843 int pt = Int_val(pt_v);
3844 int x = Int_val (x_v);
3845 int y = Int_val (y_v);
3846 double w;
3848 w = draw_string (state.face, pt, x, y, String_val (string_v));
3849 ret_v = caml_copy_double (w);
3850 CAMLreturn (ret_v);
3853 CAMLprim value ml_measure_string (value pt_v, value string_v)
3855 CAMLparam2 (pt_v, string_v);
3856 CAMLlocal1 (ret_v);
3857 int pt = Int_val (pt_v);
3858 double w;
3860 w = measure_string (state.face, pt, String_val (string_v));
3861 ret_v = caml_copy_double (w);
3862 CAMLreturn (ret_v);
3865 CAMLprim value ml_getpagebox (value opaque_v)
3867 CAMLparam1 (opaque_v);
3868 CAMLlocal1 (ret_v);
3869 fz_rect rect;
3870 fz_irect bbox;
3871 fz_matrix ctm;
3872 fz_device *dev;
3873 char *s = String_val (opaque_v);
3874 struct page *page = parse_pointer (__func__, s);
3876 ret_v = caml_alloc_tuple (4);
3877 dev = fz_new_bbox_device (state.ctx, &rect);
3878 dev->hints |= FZ_IGNORE_SHADE;
3880 ctm = pagectm (page);
3881 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3883 fz_drop_device (state.ctx, dev);
3884 fz_round_rect (&bbox, &rect);
3885 Field (ret_v, 0) = Val_int (bbox.x0);
3886 Field (ret_v, 1) = Val_int (bbox.y0);
3887 Field (ret_v, 2) = Val_int (bbox.x1);
3888 Field (ret_v, 3) = Val_int (bbox.y1);
3890 CAMLreturn (ret_v);
3893 CAMLprim value ml_setaalevel (value level_v)
3895 CAMLparam1 (level_v);
3897 state.aalevel = Int_val (level_v);
3898 CAMLreturn (Val_unit);
3901 #pragma GCC diagnostic push
3902 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3903 #include <X11/Xlib.h>
3904 #include <X11/cursorfont.h>
3905 #pragma GCC diagnostic pop
3907 #ifdef USE_EGL
3908 #include <EGL/egl.h>
3909 #else
3910 #include <GL/glx.h>
3911 #endif
3913 static const int shapes[] = {
3914 XC_arrow, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3917 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3919 static struct {
3920 Window wid;
3921 Display *dpy;
3922 #ifdef USE_EGL
3923 EGLContext ctx;
3924 EGLConfig conf;
3925 EGLSurface win;
3926 EGLDisplay *edpy;
3927 #else
3928 GLXContext ctx;
3929 #endif
3930 XVisualInfo *visual;
3931 Cursor curs[CURS_COUNT];
3932 } glx;
3934 #ifdef VISAVIS
3935 static VisualID initvisual (void)
3937 /* On this system with: `Haswell-ULT Integrated Graphics
3938 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3939 using glX chosen visual and auto scrolling some document in
3940 fullscreen the power/energy-gpu is more than 1 joule bigger
3941 than when using hand picked visual that stands alone in glxinfo
3942 output: it's dead last in the list and it's the only one with
3943 `visual dep' (sic) of 32
3945 No clue what's going on here...
3947 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3949 XVisualInfo info;
3950 int ret = 1;
3952 info.depth = 32;
3953 info.class = TrueColor;
3954 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3955 &info, &ret);
3956 if (!ret || !glx.visual) {
3957 XCloseDisplay (glx.dpy);
3958 caml_failwith ("XGetVisualInfo");
3960 return glx.visual->visualid;
3962 #endif
3964 static void initcurs (void)
3966 for (size_t n = 0; n < CURS_COUNT; ++n) {
3967 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3971 CAMLprim void ml_setbgcol (value color_v)
3973 CAMLparam1 (color_v);
3974 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3975 CAMLreturn0;
3978 #ifdef USE_EGL
3979 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3981 CAMLparam3 (display_v, wid_v, screen_v);
3982 int major, minor;
3983 int num_conf;
3984 EGLint visid;
3985 EGLint attribs[] = {
3986 #ifdef VISAVIS
3987 EGL_NATIVE_VISUAL_ID, 0,
3988 #else
3989 EGL_DEPTH_SIZE, 24,
3990 #endif
3991 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3992 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3993 EGL_NONE
3995 EGLConfig conf;
3997 glx.dpy = XOpenDisplay (String_val (display_v));
3998 if (!glx.dpy) {
3999 caml_failwith ("XOpenDisplay");
4002 eglBindAPI (EGL_OPENGL_API);
4004 glx.edpy = eglGetDisplay (glx.dpy);
4005 if (glx.dpy == EGL_NO_DISPLAY) {
4006 caml_failwith ("eglGetDisplay");
4009 if (!eglInitialize (glx.edpy, &major, &minor)) {
4010 caml_failwith ("eglInitialize");
4013 #ifdef VISAVIS
4014 attribs[1] = visid = initvisual ();
4015 #endif
4017 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4018 !num_conf) {
4019 caml_failwith ("eglChooseConfig");
4022 glx.conf = conf;
4023 #ifndef VISAVIS
4024 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4025 EGL_NATIVE_VISUAL_ID, &visid)) {
4026 caml_failwith ("eglGetConfigAttrib");
4028 #endif
4029 initcurs ();
4031 glx.wid = Int_val (wid_v);
4032 CAMLreturn (Val_int (visid));
4035 CAMLprim value ml_glxcompleteinit (value unit_v)
4037 CAMLparam1 (unit_v);
4039 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4040 if (!glx.ctx) {
4041 caml_failwith ("eglCreateContext");
4044 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4045 glx.wid, NULL);
4046 if (glx.win == EGL_NO_SURFACE) {
4047 caml_failwith ("eglCreateWindowSurface");
4050 XFree (glx.visual);
4051 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4052 glx.ctx = NULL;
4053 caml_failwith ("eglMakeCurrent");
4055 CAMLreturn (Val_unit);
4057 #else
4058 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4060 CAMLparam3 (display_v, wid_v, screen_v);
4062 glx.dpy = XOpenDisplay (String_val (display_v));
4063 if (!glx.dpy) {
4064 caml_failwith ("XOpenDisplay");
4067 #ifdef VISAVIS
4068 initvisual ();
4069 #else
4070 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4071 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4072 if (!glx.visual) {
4073 XCloseDisplay (glx.dpy);
4074 caml_failwith ("glXChooseVisual");
4076 #endif
4077 initcurs ();
4079 glx.wid = Int_val (wid_v);
4080 CAMLreturn (Val_int (glx.visual->visualid));
4083 CAMLprim value ml_glxcompleteinit (value unit_v)
4085 CAMLparam1 (unit_v);
4087 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4088 if (!glx.ctx) {
4089 caml_failwith ("glXCreateContext");
4092 XFree (glx.visual);
4093 glx.visual = NULL;
4095 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4096 glXDestroyContext (glx.dpy, glx.ctx);
4097 glx.ctx = NULL;
4098 caml_failwith ("glXMakeCurrent");
4100 CAMLreturn (Val_unit);
4102 #endif
4104 CAMLprim value ml_setcursor (value cursor_v)
4106 CAMLparam1 (cursor_v);
4107 size_t cursn = Int_val (cursor_v);
4108 XSetWindowAttributes wa;
4110 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4111 wa.cursor = glx.curs[cursn];
4112 XChangeWindowAttributes (glx.dpy, glx.wid, CWCursor, &wa);
4113 XFlush (glx.dpy);
4114 CAMLreturn (Val_unit);
4117 CAMLprim value ml_swapb (value unit_v)
4119 CAMLparam1 (unit_v);
4120 #ifdef USE_EGL
4121 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4122 caml_failwith ("eglSwapBuffers");
4124 #else
4125 glXSwapBuffers (glx.dpy, glx.wid);
4126 #endif
4127 CAMLreturn (Val_unit);
4130 #include "keysym2ucs.c"
4132 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4134 CAMLparam1 (keysym_v);
4135 CAMLlocal1 (str_v);
4136 KeySym keysym = Int_val (keysym_v);
4137 Rune rune;
4138 int len;
4139 char buf[5];
4141 rune = keysym2ucs (keysym);
4142 len = fz_runetochar (buf, rune);
4143 buf[len] = 0;
4144 str_v = caml_copy_string (buf);
4145 CAMLreturn (str_v);
4148 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4150 CAMLprim value ml_platform (value unit_v)
4152 CAMLparam1 (unit_v);
4153 CAMLlocal2 (tup_v, arr_v);
4154 int platid = piunknown;
4155 struct utsname buf;
4157 #if defined __linux__
4158 platid = pilinux;
4159 #elif defined __CYGWIN__
4160 platid = picygwin;
4161 #elif defined __DragonFly__ || defined __FreeBSD__
4162 || defined __OpenBSD__ || defined __NetBSD__
4163 platid = pibsd;
4164 #elif defined __sun__
4165 platid = pisun;
4166 #elif defined __APPLE__
4167 platid = piosx;
4168 #endif
4169 if (uname (&buf)) err (1, "uname");
4171 tup_v = caml_alloc_tuple (2);
4173 char const *sar[] = {
4174 buf.sysname,
4175 buf.release,
4176 buf.version,
4177 buf.machine,
4178 NULL
4180 arr_v = caml_copy_string_array (sar);
4182 Field (tup_v, 0) = Val_int (platid);
4183 Field (tup_v, 1) = arr_v;
4184 CAMLreturn (tup_v);
4187 CAMLprim value ml_cloexec (value fd_v)
4189 CAMLparam1 (fd_v);
4190 int fd = Int_val (fd_v);
4192 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4193 uerror ("fcntl", Nothing);
4195 CAMLreturn (Val_unit);
4198 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4200 CAMLparam2 (w_v, h_v);
4201 CAMLlocal1 (ret_v);
4202 struct pbo *pbo;
4203 int w = Int_val (w_v);
4204 int h = Int_val (h_v);
4205 int cs = Int_val (cs_v);
4207 if (state.pbo_usable) {
4208 pbo = calloc (sizeof (*pbo), 1);
4209 if (!pbo) {
4210 err (1, "calloc pbo");
4213 switch (cs) {
4214 case 0:
4215 case 1:
4216 pbo->size = w*h*4;
4217 break;
4218 case 2:
4219 pbo->size = w*h*2;
4220 break;
4221 default:
4222 errx (1, "%s: invalid colorspace %d", __func__, cs);
4225 state.glGenBuffersARB (1, &pbo->id);
4226 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4227 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4228 NULL, GL_STREAM_DRAW);
4229 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4230 GL_READ_WRITE);
4231 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4232 if (!pbo->ptr) {
4233 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4234 state.glDeleteBuffersARB (1, &pbo->id);
4235 free (pbo);
4236 ret_v = caml_copy_string ("0");
4238 else {
4239 int res;
4240 char *s;
4242 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4243 if (res < 0) {
4244 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4246 s = malloc (res+1);
4247 if (!s) {
4248 err (1, "malloc %d bytes failed", res+1);
4250 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4251 if (res < 0) {
4252 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4254 ret_v = caml_copy_string (s);
4255 free (s);
4258 else {
4259 ret_v = caml_copy_string ("0");
4261 CAMLreturn (ret_v);
4264 CAMLprim value ml_freepbo (value s_v)
4266 CAMLparam1 (s_v);
4267 char *s = String_val (s_v);
4268 struct tile *tile = parse_pointer (__func__, s);
4270 if (tile->pbo) {
4271 state.glDeleteBuffersARB (1, &tile->pbo->id);
4272 tile->pbo->id = -1;
4273 tile->pbo->ptr = NULL;
4274 tile->pbo->size = -1;
4276 CAMLreturn (Val_unit);
4279 CAMLprim value ml_unmappbo (value s_v)
4281 CAMLparam1 (s_v);
4282 char *s = String_val (s_v);
4283 struct tile *tile = parse_pointer (__func__, s);
4285 if (tile->pbo) {
4286 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4287 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4288 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4290 tile->pbo->ptr = NULL;
4291 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4293 CAMLreturn (Val_unit);
4296 static void setuppbo (void)
4298 #ifdef USE_EGL
4299 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4300 #else
4301 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4302 #endif
4303 state.pbo_usable = GGPA (glBindBufferARB)
4304 && GGPA (glUnmapBufferARB)
4305 && GGPA (glMapBufferARB)
4306 && GGPA (glBufferDataARB)
4307 && GGPA (glGenBuffersARB)
4308 && GGPA (glDeleteBuffersARB);
4309 #undef GGPA
4312 CAMLprim value ml_pbo_usable (value unit_v)
4314 CAMLparam1 (unit_v);
4315 CAMLreturn (Val_bool (state.pbo_usable));
4318 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4320 CAMLparam3 (ptr_v, x_v, y_v);
4321 CAMLlocal2 (ret_v, tup_v);
4322 struct page *page;
4323 char *s = String_val (ptr_v);
4324 int x = Int_val (x_v), y = Int_val (y_v);
4325 struct pagedim *pdim;
4326 fz_point p;
4327 fz_matrix ctm;
4329 page = parse_pointer (__func__, s);
4330 pdim = &state.pagedims[page->pdimno];
4332 ret_v = Val_int (0);
4333 if (trylock (__func__)) {
4334 goto done;
4337 if (pdf_specifics (state.ctx, state.doc)) {
4338 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4339 ctm = state.pagedims[page->pdimno].tctm;
4341 else {
4342 ctm = fz_identity;
4344 p.x = x + pdim->bounds.x0;
4345 p.y = y + pdim->bounds.y0;
4347 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4348 fz_invert_matrix (&ctm, &ctm);
4349 fz_transform_point (&p, &ctm);
4351 tup_v = caml_alloc_tuple (2);
4352 ret_v = caml_alloc_small (1, 1);
4353 Field (tup_v, 0) = Val_int (p.x);
4354 Field (tup_v, 1) = Val_int (p.y);
4355 Field (ret_v, 0) = tup_v;
4357 unlock (__func__);
4358 done:
4359 CAMLreturn (ret_v);
4362 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4363 value x_v, value y_v)
4365 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4366 CAMLlocal1 (ret_v);
4367 struct page *page;
4368 char *s = String_val (ptr_v);
4369 int pageno = Int_val (pageno_v);
4370 int pdimno = Int_val (pdimno_v);
4371 double x = Double_val (x_v), y = Double_val (y_v);
4372 struct pagedim *pdim;
4373 fz_point p;
4374 fz_matrix ctm;
4376 ret_v = Val_int (0);
4377 lock (__func__);
4379 if (!*s) {
4380 page = loadpage (pageno, pdimno);
4382 else {
4383 page = parse_pointer (__func__, s);
4385 pdim = &state.pagedims[pdimno];
4387 if (pdf_specifics (state.ctx, state.doc)) {
4388 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4389 ctm = state.pagedims[page->pdimno].tctm;
4391 else {
4392 ctm = fz_identity;
4394 p.x = x + pdim->bounds.x0;
4395 p.y = y + pdim->bounds.y0;
4397 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4398 fz_transform_point (&p, &ctm);
4400 ret_v = caml_alloc_tuple (2);
4401 Field (ret_v, 0) = caml_copy_double (p.x);
4402 Field (ret_v, 1) = caml_copy_double (p.y);
4404 if (!*s) {
4405 freepage (page);
4407 unlock (__func__);
4408 CAMLreturn (ret_v);
4411 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4412 value contents_v)
4414 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4415 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4417 if (pdf) {
4418 pdf_annot *annot;
4419 struct page *page;
4420 fz_point p;
4421 char *s = String_val (ptr_v);
4423 page = parse_pointer (__func__, s);
4424 annot = pdf_create_annot (state.ctx, pdf,
4425 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4426 p.x = Int_val (x_v);
4427 p.y = Int_val (y_v);
4428 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4429 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4430 state.dirty = 1;
4432 CAMLreturn (Val_unit);
4435 CAMLprim value ml_delannot (value ptr_v, value n_v)
4437 CAMLparam2 (ptr_v, n_v);
4438 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4440 if (pdf) {
4441 struct page *page;
4442 char *s = String_val (ptr_v);
4443 struct slink *slink;
4445 page = parse_pointer (__func__, s);
4446 slink = &page->slinks[Int_val (n_v)];
4447 pdf_delete_annot (state.ctx, pdf,
4448 (pdf_page *) page->fzpage,
4449 (pdf_annot *) slink->u.annot);
4450 state.dirty = 1;
4452 CAMLreturn (Val_unit);
4455 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4457 CAMLparam3 (ptr_v, n_v, str_v);
4458 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4460 if (pdf) {
4461 struct page *page;
4462 char *s = String_val (ptr_v);
4463 struct slink *slink;
4465 page = parse_pointer (__func__, s);
4466 slink = &page->slinks[Int_val (n_v)];
4467 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4468 String_val (str_v));
4469 state.dirty = 1;
4471 CAMLreturn (Val_unit);
4474 CAMLprim value ml_hasunsavedchanges (value unit_v)
4476 CAMLparam1 (unit_v);
4477 CAMLreturn (Val_bool (state.dirty));
4480 CAMLprim value ml_savedoc (value path_v)
4482 CAMLparam1 (path_v);
4483 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4485 if (pdf) {
4486 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4488 CAMLreturn (Val_unit);
4491 static void makestippletex (void)
4493 const char pixels[] = "\xff\xff\0\0";
4494 glGenTextures (1, &state.stid);
4495 glBindTexture (GL_TEXTURE_1D, state.stid);
4496 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4497 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4498 glTexImage1D (
4499 GL_TEXTURE_1D,
4501 GL_ALPHA,
4504 GL_ALPHA,
4505 GL_UNSIGNED_BYTE,
4506 pixels
4510 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4512 return caml_copy_string (FZ_VERSION);
4515 #ifdef USE_FONTCONFIG
4516 static struct {
4517 int inited;
4518 FcConfig *config;
4519 } fc;
4521 static fz_font *fc_load_system_font_func (fz_context *ctx,
4522 const char *name,
4523 int bold,
4524 int italic,
4525 int UNUSED_ATTR needs_exact_metrics)
4527 char *buf;
4528 size_t i, size;
4529 fz_font *font;
4530 FcChar8 *path;
4531 FcResult result;
4532 FcPattern *pat, *pat1;
4534 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4535 name, bold, italic, needs_exact_metrics);
4536 if (!fc.inited) {
4537 fc.inited = 1;
4538 fc.config = FcInitLoadConfigAndFonts ();
4539 if (!fc.config) {
4540 lprintf ("FcInitLoadConfigAndFonts failed\n");
4541 return NULL;
4544 if (!fc.config) return NULL;
4546 size = strlen (name);
4547 if (bold) size += sizeof (":bold") - 1;
4548 if (italic) size += sizeof (":italic") - 1;
4549 size += 1;
4551 buf = malloc (size);
4552 if (!buf) {
4553 err (1, "malloc %zu failed", size);
4556 strcpy (buf, name);
4557 if (bold && italic) {
4558 strcat (buf, ":bold:italic");
4560 else {
4561 if (bold) strcat (buf, ":bold");
4562 if (italic) strcat (buf, ":italic");
4564 for (i = 0; i < size; ++i) {
4565 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4568 lprintf ("fcbuf=%s\n", buf);
4569 pat = FcNameParse ((FcChar8 *) buf);
4570 if (!pat) {
4571 printd ("emsg FcNameParse failed\n");
4572 free (buf);
4573 return NULL;
4576 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4577 printd ("emsg FcConfigSubstitute failed\n");
4578 free (buf);
4579 return NULL;
4581 FcDefaultSubstitute (pat);
4583 pat1 = FcFontMatch (fc.config, pat, &result);
4584 if (!pat1) {
4585 printd ("emsg FcFontMatch failed\n");
4586 FcPatternDestroy (pat);
4587 free (buf);
4588 return NULL;
4591 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4592 printd ("emsg FcPatternGetString failed\n");
4593 FcPatternDestroy (pat);
4594 FcPatternDestroy (pat1);
4595 free (buf);
4596 return NULL;
4599 #if 0
4600 printd ("emsg name=%s path=%s\n", name, path);
4601 #endif
4602 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4603 FcPatternDestroy (pat);
4604 FcPatternDestroy (pat1);
4605 free (buf);
4606 return font;
4608 #endif
4610 CAMLprim value ml_init (value csock_v, value params_v)
4612 CAMLparam2 (csock_v, params_v);
4613 CAMLlocal2 (trim_v, fuzz_v);
4614 int ret;
4615 int texcount;
4616 char *fontpath;
4617 int colorspace;
4618 int mustoresize;
4619 int haspboext;
4621 state.csock = Int_val (csock_v);
4622 state.rotate = Int_val (Field (params_v, 0));
4623 state.fitmodel = Int_val (Field (params_v, 1));
4624 trim_v = Field (params_v, 2);
4625 texcount = Int_val (Field (params_v, 3));
4626 state.sliceheight = Int_val (Field (params_v, 4));
4627 mustoresize = Int_val (Field (params_v, 5));
4628 colorspace = Int_val (Field (params_v, 6));
4629 fontpath = String_val (Field (params_v, 7));
4631 if (caml_string_length (Field (params_v, 8)) > 0) {
4632 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4634 if (!state.trimcachepath) {
4635 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4636 strerror (errno));
4639 haspboext = Bool_val (Field (params_v, 9));
4641 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4642 fz_register_document_handlers (state.ctx);
4644 #ifdef USE_FONTCONFIG
4645 if (Bool_val (Field (params_v, 10))) {
4646 fz_install_load_system_font_funcs (
4647 state.ctx, fc_load_system_font_func, NULL
4650 #endif
4652 state.trimmargins = Bool_val (Field (trim_v, 0));
4653 fuzz_v = Field (trim_v, 1);
4654 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4655 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4656 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4657 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4659 set_tex_params (colorspace);
4661 if (*fontpath) {
4662 #ifndef USE_FONTCONFIG
4663 state.face = load_font (fontpath);
4664 #else
4665 FcChar8 *path;
4666 FcResult result;
4667 char *buf = fontpath;
4668 FcPattern *pat, *pat1;
4670 fc.inited = 1;
4671 fc.config = FcInitLoadConfigAndFonts ();
4672 if (!fc.config) {
4673 errx (1, "FcInitLoadConfigAndFonts failed");
4676 pat = FcNameParse ((FcChar8 *) buf);
4677 if (!pat) {
4678 errx (1, "FcNameParse failed");
4681 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4682 errx (1, "FcConfigSubstitute failed");
4684 FcDefaultSubstitute (pat);
4686 pat1 = FcFontMatch (fc.config, pat, &result);
4687 if (!pat1) {
4688 errx (1, "FcFontMatch failed");
4691 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4692 errx (1, "FcPatternGetString failed");
4695 state.face = load_font ((char *) path);
4696 FcPatternDestroy (pat);
4697 FcPatternDestroy (pat1);
4698 #endif
4700 else {
4701 unsigned int len;
4702 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4704 state.face = load_builtin_font (base, len);
4706 if (!state.face) _exit (1);
4708 realloctexts (texcount);
4710 if (haspboext) {
4711 setuppbo ();
4714 makestippletex ();
4716 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4717 if (ret) {
4718 errx (1, "pthread_create: %s", strerror (ret));
4721 CAMLreturn (Val_unit);