Allow specifying CFLAGS value via environment variable
[llpp.git] / link.c
blobd26e851243e6132928fb51229e7b3b809798fcd2
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 bo *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 bo_usable;
258 GLuint boid;
260 void (*glBindBufferARB) (GLenum, GLuint);
261 GLboolean (*glUnmapBufferARB) (GLenum);
262 void *(*glMapBufferARB) (GLenum, GLenum);
263 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
264 void (*glGenBuffersARB) (GLsizei, GLuint *);
265 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
267 GLfloat texcoords[8];
268 GLfloat vertices[16];
270 #ifdef CACHE_PAGEREFS
271 struct {
272 int idx;
273 int count;
274 pdf_obj **objs;
275 pdf_document *pdf;
276 } pdflut;
277 #endif
278 } state;
280 struct bo {
281 GLuint id;
282 void *ptr;
283 size_t size;
286 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
288 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
291 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
293 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
296 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
298 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
299 m.a, m.b, m.c, m.d, m.e, m.f);
302 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
304 static void lock (const char *cap)
306 int ret = pthread_mutex_lock (&mutex);
307 if (ret) {
308 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
312 static void unlock (const char *cap)
314 int ret = pthread_mutex_unlock (&mutex);
315 if (ret) {
316 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
320 static int trylock (const char *cap)
322 int ret = pthread_mutex_trylock (&mutex);
323 if (ret && ret != EBUSY) {
324 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
326 return ret == EBUSY;
329 static void *parse_pointer (const char *cap, const char *s)
331 int ret;
332 void *ptr;
334 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
335 if (ret != 1) {
336 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
338 return ptr;
341 static double now (void)
343 struct timeval tv;
345 if (gettimeofday (&tv, NULL)) {
346 err (1, "gettimeofday");
348 return tv.tv_sec + tv.tv_usec*1e-6;
351 static int hasdata (void)
353 int ret, avail;
354 ret = ioctl (state.csock, FIONREAD, &avail);
355 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
356 return avail > 0;
359 CAMLprim value ml_hasdata (value fd_v)
361 CAMLparam1 (fd_v);
362 int ret, avail;
364 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
365 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
366 CAMLreturn (Val_bool (avail > 0));
369 static void readdata (void *p, int size)
371 ssize_t n;
373 again:
374 n = read (state.csock, p, size);
375 if (n < 0) {
376 if (errno == EINTR) goto again;
377 err (1, "read (req %d, ret %zd)", size, n);
379 if (n - size) {
380 if (!n) errx (1, "EOF while reading");
381 errx (1, "read (req %d, ret %zd)", size, n);
385 static void writedata (char *p, int size)
387 ssize_t n;
389 p[0] = (size >> 24) & 0xff;
390 p[1] = (size >> 16) & 0xff;
391 p[2] = (size >> 8) & 0xff;
392 p[3] = (size >> 0) & 0xff;
394 n = write (state.csock, p, size + 4);
395 if (n - size - 4) {
396 if (!n) errx (1, "EOF while writing data");
397 err (1, "write (req %d, ret %zd)", size + 4, n);
401 static int readlen (void)
403 unsigned char p[4];
405 readdata (p, 4);
406 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
409 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
411 int size = 200, len;
412 va_list ap;
413 char *buf;
415 buf = malloc (size);
416 for (;;) {
417 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
419 va_start (ap, fmt);
420 len = vsnprintf (buf + 4, size - 4, fmt, ap);
421 va_end (ap);
423 if (len > -1) {
424 if (len < size - 4) {
425 writedata (buf, len);
426 break;
428 else size = len + 5;
430 else {
431 err (1, "vsnprintf for `%s' failed", fmt);
433 buf = realloc (buf, size);
435 free (buf);
438 static void closedoc (void)
440 #ifdef CACHE_PAGEREFS
441 if (state.pdflut.objs) {
442 int i;
444 for (i = 0; i < state.pdflut.count; ++i) {
445 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
447 free (state.pdflut.objs);
448 state.pdflut.objs = NULL;
449 state.pdflut.idx = 0;
451 #endif
452 if (state.doc) {
453 fz_drop_document (state.ctx, state.doc);
454 state.doc = NULL;
458 static int openxref (char *filename, char *password)
460 int i;
462 for (i = 0; i < state.texcount; ++i) {
463 state.texowners[i].w = -1;
464 state.texowners[i].slice = NULL;
467 closedoc ();
469 state.dirty = 0;
470 if (state.pagedims) {
471 free (state.pagedims);
472 state.pagedims = NULL;
474 state.pagedimcount = 0;
476 fz_set_aa_level (state.ctx, state.aalevel);
477 state.doc = fz_open_document (state.ctx, filename);
478 if (fz_needs_password (state.ctx, state.doc)) {
479 if (password && !*password) {
480 printd ("pass");
481 return 0;
483 else {
484 int ok = fz_authenticate_password (state.ctx, state.doc, password);
485 if (!ok) {
486 printd ("pass fail");
487 return 0;
491 state.pagecount = fz_count_pages (state.ctx, state.doc);
492 return 1;
495 static void pdfinfo (void)
497 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
498 if (pdf) {
499 pdf_obj *infoobj;
501 printd ("info PDF version\t%d.%d",
502 pdf->version / 10, pdf->version % 10);
504 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
505 pdf), "Info");
506 if (infoobj) {
507 unsigned int i;
508 char *s;
509 char *items[] = { "Title", "Author", "Creator",
510 "Producer", "CreationDate" };
512 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
513 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
514 s = pdf_to_utf8 (state.ctx, pdf, obj);
515 if (*s) printd ("info %s\t%s", items[i], s);
516 fz_free (state.ctx, s);
519 printd ("infoend");
523 static void unlinktile (struct tile *tile)
525 int i;
527 for (i = 0; i < tile->slicecount; ++i) {
528 struct slice *s = &tile->slices[i];
530 if (s->texindex != -1) {
531 if (state.texowners[s->texindex].slice == s) {
532 state.texowners[s->texindex].slice = NULL;
538 static void freepage (struct page *page)
540 if (!page) return;
541 if (page->text) {
542 fz_drop_stext_page (state.ctx, page->text);
544 if (page->sheet) {
545 fz_drop_stext_sheet (state.ctx, page->sheet);
547 if (page->slinks) {
548 free (page->slinks);
550 fz_drop_display_list (state.ctx, page->dlist);
551 fz_drop_page (state.ctx, page->fzpage);
552 free (page);
555 static void freetile (struct tile *tile)
557 unlinktile (tile);
558 if (!tile->pbo) {
559 #ifndef PIGGYBACK
560 fz_drop_pixmap (state.ctx, tile->pixmap);
561 #else
562 if (state.pig) {
563 fz_drop_pixmap (state.ctx, state.pig);
565 state.pig = tile->pixmap;
566 #endif
568 else {
569 free (tile->pbo);
570 fz_drop_pixmap (state.ctx, tile->pixmap);
572 free (tile);
575 #ifdef __ALTIVEC__
576 #include <stdint.h>
577 #include <altivec.h>
579 static int cacheline32bytes;
581 static void __attribute__ ((constructor)) clcheck (void)
583 char **envp = environ;
584 unsigned long *auxv;
586 while (*envp++);
588 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
589 if (*auxv == 19) {
590 cacheline32bytes = auxv[1] == 32;
591 return;
596 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
598 size_t size = pixmap->w * pixmap->h * pixmap->n;
599 if (cacheline32bytes && size > 32) {
600 intptr_t a1, a2, diff;
601 size_t sizea, i;
602 vector unsigned char v = vec_splat_u8 (-1);
603 vector unsigned char *p;
605 a1 = a2 = (intptr_t) pixmap->samples;
606 a2 = (a1 + 31) & ~31;
607 diff = a2 - a1;
608 sizea = size - diff;
609 p = (void *) a2;
611 while (a1 != a2) *(char *) a1++ = 0xff;
612 for (i = 0; i < (sizea & ~31); i += 32) {
613 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
614 vec_st (v, i, p);
615 vec_st (v, i + 16, p);
617 while (i < sizea) *((char *) a1 + i++) = 0xff;
619 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
621 #else
622 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
623 #endif
625 static void trimctm (pdf_page *page, int pindex)
627 fz_matrix ctm;
628 struct pagedim *pdim = &state.pagedims[pindex];
630 if (!pdim->tctmready) {
631 if (state.trimmargins) {
632 fz_rect realbox;
633 fz_matrix rm, sm, tm, im, ctm1;
635 fz_rotate (&rm, -pdim->rotate);
636 fz_scale (&sm, 1, -1);
637 fz_concat (&ctm, &rm, &sm);
638 realbox = pdim->mediabox;
639 fz_transform_rect (&realbox, &ctm);
640 fz_translate (&tm, -realbox.x0, -realbox.y0);
641 fz_concat (&ctm1, &ctm, &tm);
642 fz_invert_matrix (&im, &page->ctm);
643 fz_concat (&ctm, &im, &ctm1);
645 else {
646 ctm = fz_identity;
648 pdim->tctm = ctm;
649 pdim->tctmready = 1;
653 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
655 fz_matrix ctm, tm;
656 int pdimno = pdim - state.pagedims;
658 if (pdf_specifics (state.ctx, state.doc)) {
659 trimctm ((pdf_page *) fzpage, pdimno);
660 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
662 else {
663 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
664 fz_concat (&ctm, &tm, &pdim->ctm);
666 return ctm;
669 static fz_matrix pagectm (struct page *page)
671 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
674 static void *loadpage (int pageno, int pindex)
676 fz_device *dev;
677 struct page *page;
679 page = calloc (sizeof (struct page), 1);
680 if (!page) {
681 err (1, "calloc page %d", pageno);
684 page->dlist = fz_new_display_list (state.ctx);
685 dev = fz_new_list_device (state.ctx, page->dlist);
686 fz_try (state.ctx) {
687 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
688 fz_run_page (state.ctx, page->fzpage, dev,
689 &fz_identity, NULL);
691 fz_catch (state.ctx) {
692 page->fzpage = NULL;
694 fz_drop_device (state.ctx, dev);
696 page->pdimno = pindex;
697 page->pageno = pageno;
698 page->sgen = state.gen;
699 page->agen = state.gen;
700 page->tgen = state.gen;
701 return page;
704 static struct tile *alloctile (int h)
706 int i;
707 int slicecount;
708 size_t tilesize;
709 struct tile *tile;
711 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
712 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
713 tile = calloc (tilesize, 1);
714 if (!tile) {
715 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
717 for (i = 0; i < slicecount; ++i) {
718 int sh = MIN (h, state.sliceheight);
719 tile->slices[i].h = sh;
720 tile->slices[i].texindex = -1;
721 h -= sh;
723 tile->slicecount = slicecount;
724 tile->sliceheight = state.sliceheight;
725 return tile;
728 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
729 struct bo *pbo)
731 fz_rect rect;
732 fz_irect bbox;
733 fz_matrix ctm;
734 fz_device *dev;
735 struct tile *tile;
736 struct pagedim *pdim;
738 tile = alloctile (h);
739 pdim = &state.pagedims[page->pdimno];
741 bbox = pdim->bounds;
742 bbox.x0 += x;
743 bbox.y0 += y;
744 bbox.x1 = bbox.x0 + w;
745 bbox.y1 = bbox.y0 + h;
747 if (state.pig) {
748 if (state.pig->w == w
749 && state.pig->h == h
750 && state.pig->colorspace == state.colorspace) {
751 tile->pixmap = state.pig;
752 tile->pixmap->x = bbox.x0;
753 tile->pixmap->y = bbox.y0;
755 else {
756 fz_drop_pixmap (state.ctx, state.pig);
758 state.pig = NULL;
760 if (!tile->pixmap) {
761 if (pbo) {
762 tile->pixmap =
763 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
764 &bbox, pbo->ptr);
765 tile->pbo = pbo;
767 else {
768 tile->pixmap =
769 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
773 tile->w = w;
774 tile->h = h;
775 clearpixmap (tile->pixmap);
777 dev = fz_new_draw_device (state.ctx, tile->pixmap);
778 ctm = pagectm (page);
779 fz_rect_from_irect (&rect, &bbox);
780 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
781 fz_drop_device (state.ctx, dev);
783 return tile;
786 #ifdef CACHE_PAGEREFS
787 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
788 thanks to Robin Watts */
789 static void
790 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
792 fz_context *ctx = state.ctx; /* doc->ctx; */
793 pdf_obj *kids;
794 int i, len;
796 if (state.pdflut.idx == state.pagecount) return;
798 kids = pdf_dict_gets (ctx, node, "Kids");
799 len = pdf_array_len (ctx, kids);
801 if (len == 0)
802 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
804 if (pdf_mark_obj (ctx, node))
805 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
806 for (i = 0; i < len; i++) {
807 pdf_obj *kid = pdf_array_get (ctx, kids, i);
808 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
809 if (*type
810 ? !strcmp (type, "Pages")
811 : pdf_dict_gets (ctx, kid, "Kids")
812 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
813 pdf_collect_pages (doc, kid);
815 else {
816 if (*type
817 ? strcmp (type, "Page") != 0
818 : !pdf_dict_gets (ctx, kid, "MediaBox"))
819 fz_warn (ctx, "non-page object in page tree (%s)", type);
820 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
823 pdf_unmark_obj (ctx, node);
826 static void
827 pdf_load_page_objs (pdf_document *doc)
829 pdf_obj *root = pdf_dict_gets (state.ctx,
830 pdf_trailer (state.ctx, doc), "Root");
831 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
833 if (!node)
834 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
836 state.pdflut.idx = 0;
837 pdf_collect_pages (doc, node);
839 #endif
841 static void initpdims (int wthack)
843 double start, end;
844 FILE *trimf = NULL;
845 fz_rect rootmediabox;
846 int pageno, trim, show;
847 int trimw = 0, cxcount;
848 fz_context *ctx = state.ctx;
849 pdf_document *pdf = pdf_specifics (ctx, state.doc);
851 fz_var (trimw);
852 fz_var (cxcount);
853 start = now ();
855 if (state.trimmargins && state.trimcachepath) {
856 trimf = fopen (state.trimcachepath, "rb");
857 if (!trimf) {
858 trimf = fopen (state.trimcachepath, "wb");
859 trimw = 1;
863 if (state.trimmargins || pdf || !state.cxack)
864 cxcount = state.pagecount;
865 else
866 cxcount = MIN (state.pagecount, 1);
868 if (pdf) {
869 pdf_obj *obj;
870 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
871 "Root/Pages/MediaBox");
872 pdf_to_rect (ctx, obj, &rootmediabox);
875 #ifdef CACHE_PAGEREFS
876 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
877 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
878 if (!state.pdflut.objs) {
879 err (1, "malloc pageobjs %zu %d %zu failed",
880 sizeof (*state.pdflut.objs), cxcount,
881 sizeof (*state.pdflut.objs) * cxcount);
883 state.pdflut.count = cxcount;
884 pdf_load_page_objs (pdf);
885 state.pdflut.pdf = pdf;
887 #endif
889 for (pageno = 0; pageno < cxcount; ++pageno) {
890 int rotate = 0;
891 struct pagedim *p;
892 fz_rect mediabox;
894 if (pdf) {
895 pdf_obj *pageref, *pageobj;
897 #ifdef CACHE_PAGEREFS
898 pageref = state.pdflut.objs[pageno];
899 #else
900 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
901 #endif
902 pageobj = pdf_resolve_indirect (ctx, pageref);
904 if (state.trimmargins) {
905 pdf_obj *obj;
906 pdf_page *page;
908 fz_try (ctx) {
909 page = pdf_load_page (ctx, pdf, pageno);
910 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
911 trim = state.trimanew || !obj;
912 if (trim) {
913 fz_rect rect;
914 fz_matrix ctm;
915 fz_device *dev;
917 dev = fz_new_bbox_device (ctx, &rect);
918 dev->hints |= FZ_IGNORE_SHADE;
919 fz_invert_matrix (&ctm, &page->ctm);
920 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
921 fz_drop_device (ctx, dev);
923 rect.x0 += state.trimfuzz.x0;
924 rect.x1 += state.trimfuzz.x1;
925 rect.y0 += state.trimfuzz.y0;
926 rect.y1 += state.trimfuzz.y1;
927 fz_transform_rect (&rect, &ctm);
928 fz_intersect_rect (&rect, &page->mediabox);
930 if (fz_is_empty_rect (&rect)) {
931 mediabox = page->mediabox;
933 else {
934 mediabox = rect;
937 obj = pdf_new_array (ctx, pdf, 4);
938 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
939 mediabox.x0));
940 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
941 mediabox.y0));
942 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
943 mediabox.x1));
944 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
945 mediabox.y1));
946 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
948 else {
949 mediabox.x0 = pdf_to_real (ctx,
950 pdf_array_get (ctx, obj, 0));
951 mediabox.y0 = pdf_to_real (ctx,
952 pdf_array_get (ctx, obj, 1));
953 mediabox.x1 = pdf_to_real (ctx,
954 pdf_array_get (ctx, obj, 2));
955 mediabox.y1 = pdf_to_real (ctx,
956 pdf_array_get (ctx, obj, 3));
959 rotate = page->rotate;
960 fz_drop_page (ctx, &page->super);
962 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
963 if (show) {
964 printd ("progress %f Trimming %d",
965 (double) (pageno + 1) / state.pagecount,
966 pageno + 1);
969 fz_catch (ctx) {
970 fprintf (stderr, "failed to load page %d\n", pageno+1);
973 else {
974 int empty = 0;
975 fz_rect cropbox;
977 pdf_to_rect (ctx,
978 pdf_dict_gets (ctx, pageobj, "MediaBox"),
979 &mediabox);
980 if (fz_is_empty_rect (&mediabox)) {
981 mediabox.x0 = 0;
982 mediabox.y0 = 0;
983 mediabox.x1 = 612;
984 mediabox.y1 = 792;
985 empty = 1;
988 pdf_to_rect (ctx,
989 pdf_dict_gets (ctx, pageobj, "CropBox"),
990 &cropbox);
991 if (!fz_is_empty_rect (&cropbox)) {
992 if (empty) {
993 mediabox = cropbox;
995 else {
996 fz_intersect_rect (&mediabox, &cropbox);
999 else {
1000 if (empty) {
1001 if (fz_is_empty_rect (&rootmediabox)) {
1002 fprintf (stderr,
1003 "cannot find page size for page %d\n",
1004 pageno+1);
1006 else {
1007 mediabox = rootmediabox;
1011 rotate = pdf_to_int (ctx,
1012 pdf_dict_gets (ctx, pageobj, "Rotate"));
1015 else {
1016 if (state.trimmargins && trimw) {
1017 fz_page *page;
1019 fz_try (ctx) {
1020 page = fz_load_page (ctx, state.doc, pageno);
1021 fz_bound_page (ctx, page, &mediabox);
1022 rotate = 0;
1023 if (state.trimmargins) {
1024 fz_rect rect;
1025 fz_device *dev;
1027 dev = fz_new_bbox_device (ctx, &rect);
1028 dev->hints |= FZ_IGNORE_SHADE;
1029 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1030 fz_drop_device (ctx, dev);
1032 rect.x0 += state.trimfuzz.x0;
1033 rect.x1 += state.trimfuzz.x1;
1034 rect.y0 += state.trimfuzz.y0;
1035 rect.y1 += state.trimfuzz.y1;
1036 fz_intersect_rect (&rect, &mediabox);
1038 if (!fz_is_empty_rect (&rect)) {
1039 mediabox = rect;
1042 fz_drop_page (ctx, page);
1043 if (!state.cxack) {
1044 printd ("progress %f loading %d",
1045 (double) (pageno + 1) / state.pagecount,
1046 pageno + 1);
1049 fz_catch (ctx) {
1051 if (trimf) {
1052 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1053 if (n - 1) {
1054 err (1, "fwrite trim mediabox");
1058 else {
1059 if (trimf) {
1060 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1061 if (n - 1) {
1062 err (1, "fread trim mediabox %d", pageno);
1065 else {
1066 fz_page *page;
1067 fz_try (ctx) {
1068 page = fz_load_page (ctx, state.doc, pageno);
1069 fz_bound_page (ctx, page, &mediabox);
1070 fz_drop_page (ctx, page);
1072 show = !state.trimmargins && pageno % 20 == 0;
1073 if (show) {
1074 printd ("progress %f Gathering dimensions %d",
1075 (double) (pageno) / state.pagecount,
1076 pageno);
1079 fz_catch (ctx) {
1080 fprintf (stderr, "failed to load page %d\n", pageno);
1086 if (state.pagedimcount == 0
1087 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1088 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1089 size_t size;
1091 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1092 state.pagedims = realloc (state.pagedims, size);
1093 if (!state.pagedims) {
1094 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1095 size, state.pagedimcount + 1);
1098 p = &state.pagedims[state.pagedimcount++];
1099 p->rotate = rotate;
1100 p->mediabox = mediabox;
1101 p->pageno = pageno;
1104 end = now ();
1105 if (!wthack) {
1106 printd ("progress 1 %s %d pages in %f seconds",
1107 state.trimmargins ? "Trimmed" : "Processed",
1108 state.pagecount, end - start);
1110 state.trimanew = 0;
1111 if (trimf) {
1112 if (fclose (trimf)) {
1113 err (1, "fclose");
1118 static void layout (void)
1120 int pindex;
1121 fz_rect box;
1122 fz_matrix ctm, rm;
1123 struct pagedim *p = p;
1124 double zw, w, maxw = 0.0, zoom = zoom;
1126 if (state.pagedimcount == 0) return;
1128 switch (state.fitmodel) {
1129 case FitProportional:
1130 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1131 double x0, x1;
1133 p = &state.pagedims[pindex];
1134 fz_rotate (&rm, p->rotate + state.rotate);
1135 box = p->mediabox;
1136 fz_transform_rect (&box, &rm);
1138 x0 = MIN (box.x0, box.x1);
1139 x1 = MAX (box.x0, box.x1);
1141 w = x1 - x0;
1142 maxw = MAX (w, maxw);
1143 zoom = state.w / maxw;
1145 break;
1147 case FitPage:
1148 maxw = state.w;
1149 break;
1151 case FitWidth:
1152 break;
1154 default:
1155 ARSERT (0 && state.fitmodel);
1158 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1159 fz_rect rect;
1160 fz_matrix tm, sm;
1162 p = &state.pagedims[pindex];
1163 fz_rotate (&ctm, state.rotate);
1164 fz_rotate (&rm, p->rotate + state.rotate);
1165 box = p->mediabox;
1166 fz_transform_rect (&box, &rm);
1167 w = box.x1 - box.x0;
1168 switch (state.fitmodel) {
1169 case FitProportional:
1170 p->left = ((maxw - w) * zoom) / 2.0;
1171 break;
1172 case FitPage:
1174 double zh, h;
1175 zw = maxw / w;
1176 h = box.y1 - box.y0;
1177 zh = state.h / h;
1178 zoom = MIN (zw, zh);
1179 p->left = (maxw - (w * zoom)) / 2.0;
1181 break;
1182 case FitWidth:
1183 p->left = 0;
1184 zoom = state.w / w;
1185 break;
1188 fz_scale (&p->zoomctm, zoom, zoom);
1189 fz_concat (&ctm, &p->zoomctm, &ctm);
1191 fz_rotate (&rm, p->rotate);
1192 p->pagebox = p->mediabox;
1193 fz_transform_rect (&p->pagebox, &rm);
1194 p->pagebox.x1 -= p->pagebox.x0;
1195 p->pagebox.y1 -= p->pagebox.y0;
1196 p->pagebox.x0 = 0;
1197 p->pagebox.y0 = 0;
1198 rect = p->pagebox;
1199 fz_transform_rect (&rect, &ctm);
1200 fz_round_rect (&p->bounds, &rect);
1201 p->ctm = ctm;
1203 fz_translate (&tm, 0, -p->mediabox.y1);
1204 fz_scale (&sm, zoom, -zoom);
1205 fz_concat (&ctm, &tm, &sm);
1206 fz_concat (&p->lctm, &ctm, &rm);
1208 p->tctmready = 0;
1211 do {
1212 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1213 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1214 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1215 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1216 int boundw = x1 - x0;
1217 int boundh = y1 - y0;
1219 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1220 } while (p-- != state.pagedims);
1223 static
1224 struct anchor { int n; int x; int y; int w; int h; }
1225 desttoanchor (fz_link_dest *dest)
1227 int i;
1228 struct anchor a;
1229 struct pagedim *pdim = state.pagedims;
1231 a.n = -1;
1232 a.x = 0;
1233 a.y = 0;
1234 for (i = 0; i < state.pagedimcount; ++i) {
1235 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1236 break;
1237 pdim = &state.pagedims[i];
1239 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1240 fz_point p;
1241 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1242 p.x = dest->ld.gotor.lt.x;
1243 else
1244 p.x = 0.0;
1245 p.y = dest->ld.gotor.lt.y;
1246 fz_transform_point (&p, &pdim->lctm);
1247 a.x = p.x;
1248 a.y = p.y;
1250 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1251 double x0, x1, y0, y1;
1253 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1254 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1255 a.w = x1 - x0;
1256 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1257 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1258 a.h = y1 - y0;
1259 a.n = dest->ld.gotor.page;
1261 return a;
1264 static void recurse_outline (fz_outline *outline, int level)
1266 while (outline) {
1267 switch (outline->dest.kind) {
1268 case FZ_LINK_GOTO:
1270 struct anchor a = desttoanchor (&outline->dest);
1272 if (a.n >= 0) {
1273 printd ("o %d %d %d %d %s",
1274 level, a.n, a.y, a.h, outline->title);
1277 break;
1279 case FZ_LINK_URI:
1280 printd ("ou %d %" FMT_s " %s %s", level,
1281 strlen (outline->title), outline->title,
1282 outline->dest.ld.uri.uri);
1283 break;
1285 case FZ_LINK_NONE:
1286 printd ("on %d %s", level, outline->title);
1287 break;
1289 default:
1290 printd ("emsg Unhandled outline kind %d for %s\n",
1291 outline->dest.kind, outline->title);
1292 break;
1294 if (outline->down) {
1295 recurse_outline (outline->down, level + 1);
1297 outline = outline->next;
1301 static void process_outline (void)
1303 fz_outline *outline;
1305 if (!state.needoutline || !state.pagedimcount) return;
1307 state.needoutline = 0;
1308 outline = fz_load_outline (state.ctx, state.doc);
1309 if (outline) {
1310 recurse_outline (outline, 0);
1311 fz_drop_outline (state.ctx, outline);
1315 static char *strofspan (fz_stext_span *span)
1317 char *p;
1318 char utf8[10];
1319 fz_stext_char *ch;
1320 size_t size = 0, cap = 80;
1322 p = malloc (cap + 1);
1323 if (!p) return NULL;
1325 for (ch = span->text; ch < span->text + span->len; ++ch) {
1326 int n = fz_runetochar (utf8, ch->c);
1327 if (size + n > cap) {
1328 cap *= 2;
1329 p = realloc (p, cap + 1);
1330 if (!p) return NULL;
1333 memcpy (p + size, utf8, n);
1334 size += n;
1336 p[size] = 0;
1337 return p;
1340 static int matchspan (regex_t *re, fz_stext_span *span,
1341 int stop, int pageno, double start)
1343 int ret;
1344 char *p;
1345 regmatch_t rm;
1346 int a, b, c;
1347 fz_rect sb, eb;
1348 fz_point p1, p2, p3, p4;
1350 p = strofspan (span);
1351 if (!p) return -1;
1353 ret = regexec (re, p, 1, &rm, 0);
1354 if (ret) {
1355 free (p);
1356 if (ret != REG_NOMATCH) {
1357 size_t size;
1358 char errbuf[80];
1359 size = regerror (ret, re, errbuf, sizeof (errbuf));
1360 printd ("msg regexec error `%.*s'",
1361 (int) size, errbuf);
1362 return -1;
1364 return 0;
1366 else {
1367 int l = span->len;
1369 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1370 c += fz_runelen (span->text[a].c);
1372 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1373 c += fz_runelen (span->text[b].c);
1376 if (fz_runelen (span->text[b].c) > 1) {
1377 b = MAX (0, b-1);
1380 fz_stext_char_bbox (state.ctx, &sb, span, a);
1381 fz_stext_char_bbox (state.ctx, &eb, span, b);
1383 p1.x = sb.x0;
1384 p1.y = sb.y0;
1385 p2.x = eb.x1;
1386 p2.y = sb.y0;
1387 p3.x = eb.x1;
1388 p3.y = eb.y1;
1389 p4.x = sb.x0;
1390 p4.y = eb.y1;
1392 if (!stop) {
1393 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1394 pageno, 1,
1395 p1.x, p1.y,
1396 p2.x, p2.y,
1397 p3.x, p3.y,
1398 p4.x, p4.y);
1400 printd ("progress 1 found at %d `%.*s' in %f sec",
1401 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1402 now () - start);
1404 else {
1405 printd ("match %d %d %f %f %f %f %f %f %f %f",
1406 pageno, 2,
1407 p1.x, p1.y,
1408 p2.x, p2.y,
1409 p3.x, p3.y,
1410 p4.x, p4.y);
1412 free (p);
1413 return 1;
1417 static int compareblocks (const void *l, const void *r)
1419 fz_stext_block const *ls = l;
1420 fz_stext_block const *rs = r;
1421 return ls->bbox.y0 - rs->bbox.y0;
1424 /* wishful thinking function */
1425 static void search (regex_t *re, int pageno, int y, int forward)
1427 int i, j;
1428 fz_device *tdev;
1429 fz_stext_page *text;
1430 fz_stext_sheet *sheet;
1431 struct pagedim *pdim, *pdimprev;
1432 int stop = 0, niters = 0;
1433 double start, end;
1434 fz_page *page;
1436 start = now ();
1437 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1438 if (niters++ == 5) {
1439 niters = 0;
1440 if (hasdata ()) {
1441 printd ("progress 1 attention requested aborting search at %d",
1442 pageno);
1443 stop = 1;
1445 else {
1446 printd ("progress %f searching in page %d",
1447 (double) (pageno + 1) / state.pagecount,
1448 pageno);
1451 pdimprev = NULL;
1452 for (i = 0; i < state.pagedimcount; ++i) {
1453 pdim = &state.pagedims[i];
1454 if (pdim->pageno == pageno) {
1455 goto found;
1457 if (pdim->pageno > pageno) {
1458 pdim = pdimprev;
1459 goto found;
1461 pdimprev = pdim;
1463 pdim = pdimprev;
1464 found:
1466 sheet = fz_new_stext_sheet (state.ctx);
1467 text = fz_new_stext_page (state.ctx);
1468 tdev = fz_new_stext_device (state.ctx, sheet, text);
1470 page = fz_load_page (state.ctx, state.doc, pageno);
1472 fz_matrix ctm = pagectm1 (page, pdim);
1473 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1476 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1477 fz_drop_device (state.ctx, tdev);
1479 for (j = 0; j < text->len; ++j) {
1480 int k;
1481 fz_page_block *pb;
1482 fz_stext_block *block;
1484 pb = &text->blocks[forward ? j : text->len - 1 - j];
1485 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1486 block = pb->u.text;
1488 for (k = 0; k < block->len; ++k) {
1489 fz_stext_line *line;
1490 fz_stext_span *span;
1492 if (forward) {
1493 line = &block->lines[k];
1494 if (line->bbox.y0 < y + 1) continue;
1496 else {
1497 line = &block->lines[block->len - 1 - k];
1498 if (line->bbox.y0 > y - 1) continue;
1501 for (span = line->first_span; span; span = span->next) {
1502 switch (matchspan (re, span, stop, pageno, start)) {
1503 case 0: break;
1504 case 1: stop = 1; break;
1505 case -1: stop = 1; goto endloop;
1510 if (forward) {
1511 pageno += 1;
1512 y = 0;
1514 else {
1515 pageno -= 1;
1516 y = INT_MAX;
1518 endloop:
1519 fz_drop_stext_page (state.ctx, text);
1520 fz_drop_stext_sheet (state.ctx, sheet);
1521 fz_drop_page (state.ctx, page);
1523 end = now ();
1524 if (!stop) {
1525 printd ("progress 1 no matches %f sec", end - start);
1527 printd ("clearrects");
1530 static void set_tex_params (int colorspace)
1532 union {
1533 unsigned char b;
1534 unsigned int s;
1535 } endianness = {1};
1537 switch (colorspace) {
1538 case 0:
1539 state.texiform = GL_RGBA8;
1540 state.texform = GL_RGBA;
1541 state.texty = GL_UNSIGNED_BYTE;
1542 state.colorspace = fz_device_rgb (state.ctx);
1543 break;
1544 case 1:
1545 state.texiform = GL_RGBA8;
1546 state.texform = GL_BGRA;
1547 state.texty = endianness.s > 1
1548 ? GL_UNSIGNED_INT_8_8_8_8
1549 : GL_UNSIGNED_INT_8_8_8_8_REV;
1550 state.colorspace = fz_device_bgr (state.ctx);
1551 break;
1552 case 2:
1553 state.texiform = GL_LUMINANCE_ALPHA;
1554 state.texform = GL_LUMINANCE_ALPHA;
1555 state.texty = GL_UNSIGNED_BYTE;
1556 state.colorspace = fz_device_gray (state.ctx);
1557 break;
1558 default:
1559 errx (1, "invalid colorspce %d", colorspace);
1563 static void realloctexts (int texcount)
1565 size_t size;
1567 if (texcount == state.texcount) return;
1569 if (texcount < state.texcount) {
1570 glDeleteTextures (state.texcount - texcount,
1571 state.texids + texcount);
1574 size = texcount * sizeof (*state.texids);
1575 state.texids = realloc (state.texids, size);
1576 if (!state.texids) {
1577 err (1, "realloc texids %" FMT_s, size);
1580 size = texcount * sizeof (*state.texowners);
1581 state.texowners = realloc (state.texowners, size);
1582 if (!state.texowners) {
1583 err (1, "realloc texowners %" FMT_s, size);
1585 if (texcount > state.texcount) {
1586 int i;
1588 glGenTextures (texcount - state.texcount,
1589 state.texids + state.texcount);
1590 for (i = state.texcount; i < texcount; ++i) {
1591 state.texowners[i].w = -1;
1592 state.texowners[i].slice = NULL;
1595 state.texcount = texcount;
1596 state.texindex = 0;
1599 static char *mbtoutf8 (char *s)
1601 char *p, *r;
1602 wchar_t *tmp;
1603 size_t i, ret, len;
1605 len = mbstowcs (NULL, s, strlen (s));
1606 if (len == 0) {
1607 return s;
1609 else {
1610 if (len == (size_t) -1) {
1611 return s;
1615 tmp = malloc (len * sizeof (wchar_t));
1616 if (!tmp) {
1617 return s;
1620 ret = mbstowcs (tmp, s, len);
1621 if (ret == (size_t) -1) {
1622 free (tmp);
1623 return s;
1626 len = 0;
1627 for (i = 0; i < ret; ++i) {
1628 len += fz_runelen (tmp[i]);
1631 p = r = malloc (len + 1);
1632 if (!r) {
1633 free (tmp);
1634 return s;
1637 for (i = 0; i < ret; ++i) {
1638 p += fz_runetochar (p, tmp[i]);
1640 *p = 0;
1641 free (tmp);
1642 return r;
1645 CAMLprim value ml_mbtoutf8 (value s_v)
1647 CAMLparam1 (s_v);
1648 CAMLlocal1 (ret_v);
1649 char *s, *r;
1651 s = String_val (s_v);
1652 r = mbtoutf8 (s);
1653 if (r == s) {
1654 ret_v = s_v;
1656 else {
1657 ret_v = caml_copy_string (r);
1658 free (r);
1660 CAMLreturn (ret_v);
1663 static void * mainloop (void UNUSED_ATTR *unused)
1665 char *p = NULL;
1666 int len, ret, oldlen = 0;
1668 fz_var (p);
1669 fz_var (oldlen);
1670 for (;;) {
1671 len = readlen ();
1672 if (len == 0) {
1673 errx (1, "readlen returned 0");
1676 if (oldlen < len + 1) {
1677 p = realloc (p, len + 1);
1678 if (!p) {
1679 err (1, "realloc %d failed", len + 1);
1681 oldlen = len + 1;
1683 readdata (p, len);
1684 p[len] = 0;
1686 if (!strncmp ("open", p, 4)) {
1687 int wthack, off, ok = 0;
1688 char *password;
1689 char *filename;
1690 char *utf8filename;
1691 size_t filenamelen;
1693 fz_var (ok);
1694 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1695 if (ret != 2) {
1696 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1699 filename = p + 5 + off;
1700 filenamelen = strlen (filename);
1701 password = filename + filenamelen + 1;
1703 lock ("open");
1704 fz_try (state.ctx) {
1705 ok = openxref (filename, password);
1707 fz_catch (state.ctx) {
1708 utf8filename = mbtoutf8 (filename);
1709 printd ("msg Could not open %s", utf8filename);
1711 if (ok) {
1712 pdfinfo ();
1713 initpdims (wthack);
1715 unlock ("open");
1717 if (ok) {
1718 if (!wthack) {
1719 utf8filename = mbtoutf8 (filename);
1720 printd ("msg Opened %s (press h/F1 to get help)",
1721 utf8filename);
1722 if (utf8filename != filename) {
1723 free (utf8filename);
1726 state.needoutline = 1;
1729 else if (!strncmp ("cs", p, 2)) {
1730 int i, colorspace;
1732 ret = sscanf (p + 2, " %d", &colorspace);
1733 if (ret != 1) {
1734 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1736 lock ("cs");
1737 set_tex_params (colorspace);
1738 for (i = 0; i < state.texcount; ++i) {
1739 state.texowners[i].w = -1;
1740 state.texowners[i].slice = NULL;
1742 unlock ("cs");
1744 else if (!strncmp ("freepage", p, 8)) {
1745 void *ptr;
1747 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1748 if (ret != 1) {
1749 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1751 freepage (ptr);
1753 else if (!strncmp ("freetile", p, 8)) {
1754 void *ptr;
1756 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1757 if (ret != 1) {
1758 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1760 freetile (ptr);
1762 else if (!strncmp ("search", p, 6)) {
1763 int icase, pageno, y, len2, forward;
1764 char *pattern;
1765 regex_t re;
1767 ret = sscanf (p + 6, " %d %d %d %d,%n",
1768 &icase, &pageno, &y, &forward, &len2);
1769 if (ret != 4) {
1770 errx (1, "malformed search `%s' ret=%d", p, ret);
1773 pattern = p + 6 + len2;
1774 ret = regcomp (&re, pattern,
1775 REG_EXTENDED | (icase ? REG_ICASE : 0));
1776 if (ret) {
1777 char errbuf[80];
1778 size_t size;
1780 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1781 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1783 else {
1784 search (&re, pageno, y, forward);
1785 regfree (&re);
1788 else if (!strncmp ("geometry", p, 8)) {
1789 int w, h, fitmodel;
1791 printd ("clear");
1792 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1793 if (ret != 3) {
1794 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1797 lock ("geometry");
1798 state.h = h;
1799 if (w != state.w) {
1800 int i;
1801 state.w = w;
1802 for (i = 0; i < state.texcount; ++i) {
1803 state.texowners[i].slice = NULL;
1806 state.fitmodel = fitmodel;
1807 layout ();
1808 process_outline ();
1810 state.gen++;
1811 unlock ("geometry");
1812 printd ("continue %d", state.pagecount);
1814 else if (!strncmp ("reqlayout", p, 9)) {
1815 char *nameddest;
1816 int rotate, off, h;
1817 unsigned int fitmodel;
1818 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1820 printd ("clear");
1821 ret = sscanf (p + 9, " %d %u %d %n",
1822 &rotate, &fitmodel, &h, &off);
1823 if (ret != 3) {
1824 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1826 lock ("reqlayout");
1827 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1828 state.gen += 1;
1830 state.rotate = rotate;
1831 state.fitmodel = fitmodel;
1832 state.h = h;
1833 layout ();
1834 process_outline ();
1836 nameddest = p + 9 + off;
1837 if (pdf && nameddest && *nameddest) {
1838 struct anchor a;
1839 fz_link_dest dest;
1840 pdf_obj *needle, *obj;
1842 needle = pdf_new_string (state.ctx, pdf, nameddest,
1843 strlen (nameddest));
1844 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1845 if (obj) {
1846 dest = pdf_parse_link_dest (state.ctx, pdf,
1847 FZ_LINK_GOTO, obj);
1849 a = desttoanchor (&dest);
1850 if (a.n >= 0) {
1851 printd ("a %d %d %d", a.n, a.x, a.y);
1853 else {
1854 printd ("emsg failed to parse destination `%s'\n",
1855 nameddest);
1858 else {
1859 printd ("emsg destination `%s' not found\n",
1860 nameddest);
1862 pdf_drop_obj (state.ctx, needle);
1865 state.gen++;
1866 unlock ("reqlayout");
1867 printd ("continue %d", state.pagecount);
1869 else if (!strncmp ("page", p, 4)) {
1870 double a, b;
1871 struct page *page;
1872 int pageno, pindex;
1874 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1875 if (ret != 2) {
1876 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1879 lock ("page");
1880 a = now ();
1881 page = loadpage (pageno, pindex);
1882 b = now ();
1883 unlock ("page");
1885 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1887 else if (!strncmp ("tile", p, 4)) {
1888 int x, y, w, h;
1889 struct page *page;
1890 struct tile *tile;
1891 double a, b;
1892 void *data;
1894 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1895 SCN_ptr_cast (&page), &x, &y, &w, &h,
1896 SCN_ptr_cast (&data));
1897 if (ret != 6) {
1898 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1901 lock ("tile");
1902 a = now ();
1903 tile = rendertile (page, x, y, w, h, data);
1904 b = now ();
1905 unlock ("tile");
1907 printd ("tile %d %d %" FMT_ptr " %u %f",
1908 x, y,
1909 FMT_ptr_cast (tile),
1910 tile->w * tile->h * tile->pixmap->n,
1911 b - a);
1913 else if (!strncmp ("trimset", p, 7)) {
1914 fz_irect fuzz;
1915 int trimmargins;
1917 ret = sscanf (p + 7, " %d %d %d %d %d",
1918 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1919 if (ret != 5) {
1920 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1922 lock ("trimset");
1923 state.trimmargins = trimmargins;
1924 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1925 state.trimanew = 1;
1926 state.trimfuzz = fuzz;
1928 unlock ("trimset");
1930 else if (!strncmp ("settrim", p, 7)) {
1931 fz_irect fuzz;
1932 int trimmargins;
1934 ret = sscanf (p + 7, " %d %d %d %d %d",
1935 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1936 if (ret != 5) {
1937 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1939 printd ("clear");
1940 lock ("settrim");
1941 state.trimmargins = trimmargins;
1942 state.needoutline = 1;
1943 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1944 state.trimanew = 1;
1945 state.trimfuzz = fuzz;
1947 state.pagedimcount = 0;
1948 free (state.pagedims);
1949 state.pagedims = NULL;
1950 initpdims (0);
1951 layout ();
1952 process_outline ();
1953 unlock ("settrim");
1954 printd ("continue %d", state.pagecount);
1956 else if (!strncmp ("sliceh", p, 6)) {
1957 int h;
1959 ret = sscanf (p + 6, " %d", &h);
1960 if (ret != 1) {
1961 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1963 if (h != state.sliceheight) {
1964 int i;
1966 state.sliceheight = h;
1967 for (i = 0; i < state.texcount; ++i) {
1968 state.texowners[i].w = -1;
1969 state.texowners[i].h = -1;
1970 state.texowners[i].slice = NULL;
1974 else if (!strncmp ("interrupt", p, 9)) {
1975 printd ("vmsg interrupted");
1977 else {
1978 errx (1, "unknown command %.*s", len, p);
1981 return 0;
1984 CAMLprim value ml_realloctexts (value texcount_v)
1986 CAMLparam1 (texcount_v);
1987 int ok;
1989 if (trylock (__func__)) {
1990 ok = 0;
1991 goto done;
1993 realloctexts (Int_val (texcount_v));
1994 ok = 1;
1995 unlock (__func__);
1997 done:
1998 CAMLreturn (Val_bool (ok));
2001 static void recti (int x0, int y0, int x1, int y1)
2003 GLfloat *v = state.vertices;
2005 glVertexPointer (2, GL_FLOAT, 0, v);
2006 v[0] = x0; v[1] = y0;
2007 v[2] = x1; v[3] = y0;
2008 v[4] = x0; v[5] = y1;
2009 v[6] = x1; v[7] = y1;
2010 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2013 static void showsel (struct page *page, int ox, int oy)
2015 int seen = 0;
2016 fz_irect bbox;
2017 fz_rect rect;
2018 fz_stext_line *line;
2019 fz_page_block *pageb;
2020 fz_stext_block *block;
2021 struct mark first, last;
2022 unsigned char selcolor[] = {15,15,15,140};
2024 first = page->fmark;
2025 last = page->lmark;
2027 if (!first.span || !last.span) return;
2029 glEnable (GL_BLEND);
2030 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2031 glColor4ubv (selcolor);
2033 ox += state.pagedims[page->pdimno].bounds.x0;
2034 oy += state.pagedims[page->pdimno].bounds.y0;
2035 for (pageb = page->text->blocks;
2036 pageb < page->text->blocks + page->text->len;
2037 ++pageb) {
2038 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2039 block = pageb->u.text;
2041 for (line = block->lines;
2042 line < block->lines + block->len;
2043 ++line) {
2044 fz_stext_span *span;
2045 rect = fz_empty_rect;
2047 for (span = line->first_span; span; span = span->next) {
2048 int i, j, k;
2049 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2051 j = 0;
2052 k = span->len - 1;
2054 if (span == page->fmark.span && span == page->lmark.span) {
2055 seen = 1;
2056 j = MIN (first.i, last.i);
2057 k = MAX (first.i, last.i);
2059 else {
2060 if (span == first.span) {
2061 seen = 1;
2062 j = first.i;
2064 else if (span == last.span) {
2065 seen = 1;
2066 k = last.i;
2070 if (seen) {
2071 for (i = j; i <= k; ++i) {
2072 fz_rect bbox1;
2073 fz_union_rect (&rect,
2074 fz_stext_char_bbox (state.ctx, &bbox1,
2075 span, i));
2077 fz_round_rect (&bbox, &rect);
2078 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2079 bbox.x0,
2080 bbox.y0,
2081 bbox.x1,
2082 bbox.y1,
2083 oy, ox);
2085 recti (bbox.x0 + ox, bbox.y0 + oy,
2086 bbox.x1 + ox, bbox.y1 + oy);
2087 if (span == last.span) {
2088 goto done;
2090 rect = fz_empty_rect;
2095 done:
2096 glDisable (GL_BLEND);
2099 #include "glfont.c"
2101 static void stipplerect (fz_matrix *m,
2102 fz_point *p1,
2103 fz_point *p2,
2104 fz_point *p3,
2105 fz_point *p4,
2106 GLfloat *texcoords,
2107 GLfloat *vertices)
2109 fz_transform_point (p1, m);
2110 fz_transform_point (p2, m);
2111 fz_transform_point (p3, m);
2112 fz_transform_point (p4, m);
2114 float w, h, s, t;
2116 w = p2->x - p1->x;
2117 h = p2->y - p1->y;
2118 t = sqrtf (w*w + h*h) * .25f;
2120 w = p3->x - p2->x;
2121 h = p3->y - p2->y;
2122 s = sqrtf (w*w + h*h) * .25f;
2124 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2125 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2127 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2128 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2130 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2131 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2133 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2134 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2136 glDrawArrays (GL_LINES, 0, 8);
2139 static void solidrect (fz_matrix *m,
2140 fz_point *p1,
2141 fz_point *p2,
2142 fz_point *p3,
2143 fz_point *p4,
2144 GLfloat *vertices)
2146 fz_transform_point (p1, m);
2147 fz_transform_point (p2, m);
2148 fz_transform_point (p3, m);
2149 fz_transform_point (p4, m);
2150 vertices[0] = p1->x; vertices[1] = p1->y;
2151 vertices[2] = p2->x; vertices[3] = p2->y;
2153 vertices[4] = p3->x; vertices[5] = p3->y;
2154 vertices[6] = p4->x; vertices[7] = p4->y;
2155 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2158 static void highlightlinks (struct page *page, int xoff, int yoff)
2160 int i;
2161 fz_matrix ctm, tm, pm;
2162 fz_link *link, *links;
2163 GLfloat *texcoords = state.texcoords;
2164 GLfloat *vertices = state.vertices;
2166 links = fz_load_links (state.ctx, page->fzpage);
2168 glEnable (GL_TEXTURE_1D);
2169 glEnable (GL_BLEND);
2170 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2171 glBindTexture (GL_TEXTURE_1D, state.stid);
2173 xoff -= state.pagedims[page->pdimno].bounds.x0;
2174 yoff -= state.pagedims[page->pdimno].bounds.y0;
2175 fz_translate (&tm, xoff, yoff);
2176 pm = pagectm (page);
2177 fz_concat (&ctm, &pm, &tm);
2179 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2180 glVertexPointer (2, GL_FLOAT, 0, vertices);
2182 for (link = links; link; link = link->next) {
2183 fz_point p1, p2, p3, p4;
2185 p1.x = link->rect.x0;
2186 p1.y = link->rect.y0;
2188 p2.x = link->rect.x1;
2189 p2.y = link->rect.y0;
2191 p3.x = link->rect.x1;
2192 p3.y = link->rect.y1;
2194 p4.x = link->rect.x0;
2195 p4.y = link->rect.y1;
2197 switch (link->dest.kind) {
2198 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2199 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2200 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2201 default: glColor3ub (0, 0, 0); break;
2203 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2206 for (i = 0; i < page->annotcount; ++i) {
2207 fz_point p1, p2, p3, p4;
2208 struct annot *annot = &page->annots[i];
2210 p1.x = annot->bbox.x0;
2211 p1.y = annot->bbox.y0;
2213 p2.x = annot->bbox.x1;
2214 p2.y = annot->bbox.y0;
2216 p3.x = annot->bbox.x1;
2217 p3.y = annot->bbox.y1;
2219 p4.x = annot->bbox.x0;
2220 p4.y = annot->bbox.y1;
2222 glColor3ub (0, 0, 128);
2223 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2226 glDisable (GL_BLEND);
2227 glDisable (GL_TEXTURE_1D);
2230 static int compareslinks (const void *l, const void *r)
2232 struct slink const *ls = l;
2233 struct slink const *rs = r;
2234 if (ls->bbox.y0 == rs->bbox.y0) {
2235 return rs->bbox.x0 - rs->bbox.x0;
2237 return ls->bbox.y0 - rs->bbox.y0;
2240 static void droptext (struct page *page)
2242 if (page->text) {
2243 fz_drop_stext_page (state.ctx, page->text);
2244 page->fmark.i = -1;
2245 page->lmark.i = -1;
2246 page->fmark.span = NULL;
2247 page->lmark.span = NULL;
2248 page->text = NULL;
2250 if (page->sheet) {
2251 fz_drop_stext_sheet (state.ctx, page->sheet);
2252 page->sheet = NULL;
2256 static void dropannots (struct page *page)
2258 if (page->annots) {
2259 free (page->annots);
2260 page->annots = NULL;
2261 page->annotcount = 0;
2265 static void ensureannots (struct page *page)
2267 int i, count = 0;
2268 size_t annotsize = sizeof (*page->annots);
2269 fz_annot *annot;
2271 if (state.gen != page->agen) {
2272 dropannots (page);
2273 page->agen = state.gen;
2275 if (page->annots) return;
2277 for (annot = fz_first_annot (state.ctx, page->fzpage);
2278 annot;
2279 annot = fz_next_annot (state.ctx, page->fzpage, annot)) {
2280 count++;
2283 if (count > 0) {
2284 page->annotcount = count;
2285 page->annots = calloc (count, annotsize);
2286 if (!page->annots) {
2287 err (1, "calloc annots %d", count);
2290 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2291 annot;
2292 annot = fz_next_annot (state.ctx, page->fzpage, annot), i++) {
2293 fz_rect rect;
2295 fz_bound_annot (state.ctx, page->fzpage, annot, &rect);
2296 page->annots[i].annot = annot;
2297 fz_round_rect (&page->annots[i].bbox, &rect);
2302 static void dropslinks (struct page *page)
2304 if (page->slinks) {
2305 free (page->slinks);
2306 page->slinks = NULL;
2307 page->slinkcount = 0;
2311 static void ensureslinks (struct page *page)
2313 fz_matrix ctm;
2314 int i, count;
2315 size_t slinksize = sizeof (*page->slinks);
2316 fz_link *link, *links;
2318 ensureannots (page);
2319 if (state.gen != page->sgen) {
2320 dropslinks (page);
2321 page->sgen = state.gen;
2323 if (page->slinks) return;
2325 links = fz_load_links (state.ctx, page->fzpage);
2326 ctm = pagectm (page);
2328 count = page->annotcount;
2329 for (link = links; link; link = link->next) {
2330 count++;
2332 if (count > 0) {
2333 int j;
2335 page->slinkcount = count;
2336 page->slinks = calloc (count, slinksize);
2337 if (!page->slinks) {
2338 err (1, "calloc slinks %d", count);
2341 for (i = 0, link = links; link; ++i, link = link->next) {
2342 fz_rect rect;
2344 rect = link->rect;
2345 fz_transform_rect (&rect, &ctm);
2346 page->slinks[i].tag = SLINK;
2347 page->slinks[i].u.link = link;
2348 fz_round_rect (&page->slinks[i].bbox, &rect);
2350 for (j = 0; j < page->annotcount; ++j, ++i) {
2351 fz_rect rect;
2352 fz_bound_annot (state.ctx,
2353 page->fzpage,
2354 page->annots[j].annot,
2355 &rect);
2356 fz_transform_rect (&rect, &ctm);
2357 fz_round_rect (&page->slinks[i].bbox, &rect);
2359 page->slinks[i].tag = SANNOT;
2360 page->slinks[i].u.annot = page->annots[j].annot;
2362 qsort (page->slinks, count, slinksize, compareslinks);
2366 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2367 static void fmt_linkn (char *s, unsigned int u)
2369 unsigned int len; unsigned int q;
2370 unsigned int zma = 'z' - 'a' + 1;
2371 len = 1; q = u;
2372 while (q > zma - 1) { ++len; q /= zma; }
2373 if (s) {
2374 s += len;
2375 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2376 /* handles u == 0 */
2378 s[len] = 0;
2381 static void highlightslinks (struct page *page, int xoff, int yoff,
2382 int noff, char *targ, int tlen, int hfsize)
2384 int i;
2385 char buf[40];
2386 struct slink *slink;
2387 double x0, y0, x1, y1, w;
2389 ensureslinks (page);
2390 glColor3ub (0xc3, 0xb0, 0x91);
2391 for (i = 0; i < page->slinkcount; ++i) {
2392 fmt_linkn (buf, i + noff);
2393 if (!tlen || !strncmp (targ, buf, tlen)) {
2394 slink = &page->slinks[i];
2396 x0 = slink->bbox.x0 + xoff - 5;
2397 y1 = slink->bbox.y0 + yoff - 5;
2398 y0 = y1 + 10 + hfsize;
2399 w = measure_string (state.face, hfsize, buf);
2400 x1 = x0 + w + 10;
2401 recti (x0, y0, x1, y1);
2405 glEnable (GL_BLEND);
2406 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2407 glEnable (GL_TEXTURE_2D);
2408 glColor3ub (0, 0, 0);
2409 for (i = 0; i < page->slinkcount; ++i) {
2410 fmt_linkn (buf, i + noff);
2411 if (!tlen || !strncmp (targ, buf, tlen)) {
2412 slink = &page->slinks[i];
2414 x0 = slink->bbox.x0 + xoff;
2415 y0 = slink->bbox.y0 + yoff + hfsize;
2416 draw_string (state.face, hfsize, x0, y0, buf);
2419 glDisable (GL_TEXTURE_2D);
2420 glDisable (GL_BLEND);
2423 static void uploadslice (struct tile *tile, struct slice *slice)
2425 int offset;
2426 struct slice *slice1;
2427 unsigned char *texdata;
2429 offset = 0;
2430 for (slice1 = tile->slices; slice != slice1; slice1++) {
2431 offset += slice1->h * tile->w * tile->pixmap->n;
2433 if (slice->texindex != -1 && slice->texindex < state.texcount
2434 && state.texowners[slice->texindex].slice == slice) {
2435 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2437 else {
2438 int subimage = 0;
2439 int texindex = state.texindex++ % state.texcount;
2441 if (state.texowners[texindex].w == tile->w) {
2442 if (state.texowners[texindex].h >= slice->h) {
2443 subimage = 1;
2445 else {
2446 state.texowners[texindex].h = slice->h;
2449 else {
2450 state.texowners[texindex].h = slice->h;
2453 state.texowners[texindex].w = tile->w;
2454 state.texowners[texindex].slice = slice;
2455 slice->texindex = texindex;
2457 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2458 #if TEXT_TYPE == GL_TEXTURE_2D
2459 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2460 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2461 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2462 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2463 #endif
2464 if (tile->pbo) {
2465 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2466 texdata = 0;
2468 else {
2469 texdata = tile->pixmap->samples;
2471 if (subimage) {
2472 glTexSubImage2D (TEXT_TYPE,
2476 tile->w,
2477 slice->h,
2478 state.texform,
2479 state.texty,
2480 texdata+offset
2483 else {
2484 glTexImage2D (TEXT_TYPE,
2486 state.texiform,
2487 tile->w,
2488 slice->h,
2490 state.texform,
2491 state.texty,
2492 texdata+offset
2495 if (tile->pbo) {
2496 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2501 CAMLprim value ml_begintiles (value unit_v)
2503 CAMLparam1 (unit_v);
2504 glEnable (TEXT_TYPE);
2505 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2506 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2507 CAMLreturn (unit_v);
2510 CAMLprim value ml_endtiles (value unit_v)
2512 CAMLparam1 (unit_v);
2513 glDisable (TEXT_TYPE);
2514 CAMLreturn (unit_v);
2517 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2519 CAMLparam2 (args_v, ptr_v);
2520 int dispx = Int_val (Field (args_v, 0));
2521 int dispy = Int_val (Field (args_v, 1));
2522 int dispw = Int_val (Field (args_v, 2));
2523 int disph = Int_val (Field (args_v, 3));
2524 int tilex = Int_val (Field (args_v, 4));
2525 int tiley = Int_val (Field (args_v, 5));
2526 char *s = String_val (ptr_v);
2527 struct tile *tile = parse_pointer (__func__, s);
2528 int slicey, firstslice;
2529 struct slice *slice;
2530 GLfloat *texcoords = state.texcoords;
2531 GLfloat *vertices = state.vertices;
2533 firstslice = tiley / tile->sliceheight;
2534 slice = &tile->slices[firstslice];
2535 slicey = tiley % tile->sliceheight;
2537 while (disph > 0) {
2538 int dh;
2540 dh = slice->h - slicey;
2541 dh = MIN (disph, dh);
2542 uploadslice (tile, slice);
2544 texcoords[0] = tilex; texcoords[1] = slicey;
2545 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2546 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2547 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2549 vertices[0] = dispx; vertices[1] = dispy;
2550 vertices[2] = dispx+dispw; vertices[3] = dispy;
2551 vertices[4] = dispx; vertices[5] = dispy+dh;
2552 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2554 #if TEXT_TYPE == GL_TEXTURE_2D
2555 for (int i = 0; i < 8; ++i) {
2556 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2558 #endif
2560 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2561 dispy += dh;
2562 disph -= dh;
2563 slice++;
2564 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2565 slicey = 0;
2567 CAMLreturn (Val_unit);
2570 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2572 fz_matrix ctm, tm, pm;
2573 fz_point p1, p2, p3, p4;
2574 GLfloat *vertices = state.vertices;
2575 double *v = (double *) rects_v;
2577 xoff -= state.pagedims[page->pdimno].bounds.x0;
2578 yoff -= state.pagedims[page->pdimno].bounds.y0;
2579 fz_translate (&tm, xoff, yoff);
2580 pm = pagectm (page);
2581 fz_concat (&ctm, &pm, &tm);
2583 glEnable (GL_BLEND);
2584 glVertexPointer (2, GL_FLOAT, 0, vertices);
2586 glColor4dv (v);
2587 p1.x = v[4];
2588 p1.y = v[5];
2590 p2.x = v[6];
2591 p2.y = v[5];
2593 p3.x = v[6];
2594 p3.y = v[7];
2596 p4.x = v[4];
2597 p4.y = v[7];
2598 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2599 glDisable (GL_BLEND);
2602 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2603 value xoff_v, value yoff_v,
2604 value li_v)
2606 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2607 int xoff = Int_val (xoff_v);
2608 int yoff = Int_val (yoff_v);
2609 int noff = Int_val (Field (li_v, 0));
2610 char *targ = String_val (Field (li_v, 1));
2611 int tlen = caml_string_length (Field (li_v, 1));
2612 int hfsize = Int_val (Field (li_v, 2));
2613 char *s = String_val (ptr_v);
2614 int hlmask = Int_val (hlinks_v);
2615 struct page *page = parse_pointer (__func__, s);
2617 if (!page->fzpage) {
2618 /* deal with loadpage failed pages */
2619 goto done;
2622 ensureannots (page);
2624 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2625 if (trylock (__func__)) {
2626 noff = 0;
2627 goto done;
2629 if (hlmask & 2) {
2630 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2631 noff = page->slinkcount;
2633 if (page->tgen == state.gen) {
2634 showsel (page, xoff, yoff);
2636 unlock (__func__);
2638 done:
2639 CAMLreturn (Val_int (noff));
2642 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2643 value rects_v)
2645 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2646 int xoff = Int_val (xoff_v);
2647 int yoff = Int_val (yoff_v);
2648 char *s = String_val (ptr_v);
2649 struct page *page = parse_pointer (__func__, s);
2651 drawprect (page, xoff, yoff, rects_v);
2652 CAMLreturn (Val_unit);
2655 static struct annot *getannot (struct page *page, int x, int y)
2657 int i;
2658 fz_point p;
2659 fz_matrix ctm;
2660 const fz_matrix *tctm;
2661 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2663 if (!page->annots) return NULL;
2665 if (pdf) {
2666 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2667 tctm = &state.pagedims[page->pdimno].tctm;
2669 else {
2670 tctm = &fz_identity;
2673 p.x = x;
2674 p.y = y;
2676 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2677 fz_invert_matrix (&ctm, &ctm);
2678 fz_transform_point (&p, &ctm);
2680 if (pdf) {
2681 for (i = 0; i < page->annotcount; ++i) {
2682 struct annot *a = &page->annots[i];
2683 pdf_annot *annot = (pdf_annot *) a->annot;
2684 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2685 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2686 return a;
2691 return NULL;
2694 static fz_link *getlink (struct page *page, int x, int y)
2696 fz_point p;
2697 fz_matrix ctm;
2698 const fz_matrix *tctm;
2699 fz_link *link, *links;
2701 tctm = &fz_identity;
2702 links = fz_load_links (state.ctx, page->fzpage);
2704 p.x = x;
2705 p.y = y;
2707 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2708 fz_invert_matrix (&ctm, &ctm);
2709 fz_transform_point (&p, &ctm);
2711 for (link = links; link; link = link->next) {
2712 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2713 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2714 return link;
2718 return NULL;
2721 static void ensuretext (struct page *page)
2723 if (state.gen != page->tgen) {
2724 droptext (page);
2725 page->tgen = state.gen;
2727 if (!page->text) {
2728 fz_matrix ctm;
2729 fz_device *tdev;
2731 page->text = fz_new_stext_page (state.ctx);
2732 page->sheet = fz_new_stext_sheet (state.ctx);
2733 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2734 ctm = pagectm (page);
2735 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2736 fz_run_display_list (state.ctx, page->dlist,
2737 tdev, &ctm, &fz_infinite_rect, NULL);
2738 qsort (page->text->blocks, page->text->len,
2739 sizeof (*page->text->blocks), compareblocks);
2740 fz_end_page (state.ctx, tdev);
2741 fz_drop_device (state.ctx, tdev);
2745 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2747 CAMLparam2 (start_page_v, dir_v);
2748 CAMLlocal1 (ret_v);
2749 int i, dir = Int_val (dir_v);
2750 int start_page = Int_val (start_page_v);
2751 int end_page = dir > 0 ? state.pagecount : -1;
2752 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2754 fz_var (end_page);
2755 ret_v = Val_int (0);
2756 lock (__func__);
2757 for (i = start_page + dir; i != end_page; i += dir) {
2758 int found;
2760 fz_var (found);
2761 if (pdf) {
2762 pdf_page *page = NULL;
2764 fz_try (state.ctx) {
2765 page = pdf_load_page (state.ctx, pdf, i);
2766 found = !!page->links || !!page->annots;
2768 fz_catch (state.ctx) {
2769 found = 0;
2771 if (page) {
2772 fz_drop_page (state.ctx, &page->super);
2775 else {
2776 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2777 found = !!fz_load_links (state.ctx, page);
2778 fz_drop_page (state.ctx, page);
2781 if (found) {
2782 ret_v = caml_alloc_small (1, 1);
2783 Field (ret_v, 0) = Val_int (i);
2784 goto unlock;
2787 unlock:
2788 unlock (__func__);
2789 CAMLreturn (ret_v);
2792 enum { dir_first, dir_last };
2793 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2795 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2797 CAMLparam2 (ptr_v, dir_v);
2798 CAMLlocal2 (ret_v, pos_v);
2799 struct page *page;
2800 int dirtag, i, slinkindex;
2801 struct slink *found = NULL ,*slink;
2802 char *s = String_val (ptr_v);
2804 page = parse_pointer (__func__, s);
2805 ret_v = Val_int (0);
2806 /* This is scary we are not taking locks here ensureslinks does
2807 not modify state and given that we obtained the page it can not
2808 disappear under us either */
2809 lock (__func__);
2810 ensureslinks (page);
2812 if (Is_block (dir_v)) {
2813 dirtag = Tag_val (dir_v);
2814 switch (dirtag) {
2815 case dir_first_visible:
2817 int x0, y0, dir, first_index, last_index;
2819 pos_v = Field (dir_v, 0);
2820 x0 = Int_val (Field (pos_v, 0));
2821 y0 = Int_val (Field (pos_v, 1));
2822 dir = Int_val (Field (pos_v, 2));
2824 if (dir >= 0) {
2825 dir = 1;
2826 first_index = 0;
2827 last_index = page->slinkcount;
2829 else {
2830 first_index = page->slinkcount - 1;
2831 last_index = -1;
2834 for (i = first_index; i != last_index; i += dir) {
2835 slink = &page->slinks[i];
2836 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2837 found = slink;
2838 break;
2842 break;
2844 case dir_left:
2845 slinkindex = Int_val (Field (dir_v, 0));
2846 found = &page->slinks[slinkindex];
2847 for (i = slinkindex - 1; i >= 0; --i) {
2848 slink = &page->slinks[i];
2849 if (slink->bbox.x0 < found->bbox.x0) {
2850 found = slink;
2851 break;
2854 break;
2856 case dir_right:
2857 slinkindex = Int_val (Field (dir_v, 0));
2858 found = &page->slinks[slinkindex];
2859 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2860 slink = &page->slinks[i];
2861 if (slink->bbox.x0 > found->bbox.x0) {
2862 found = slink;
2863 break;
2866 break;
2868 case dir_down:
2869 slinkindex = Int_val (Field (dir_v, 0));
2870 found = &page->slinks[slinkindex];
2871 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2872 slink = &page->slinks[i];
2873 if (slink->bbox.y0 >= found->bbox.y0) {
2874 found = slink;
2875 break;
2878 break;
2880 case dir_up:
2881 slinkindex = Int_val (Field (dir_v, 0));
2882 found = &page->slinks[slinkindex];
2883 for (i = slinkindex - 1; i >= 0; --i) {
2884 slink = &page->slinks[i];
2885 if (slink->bbox.y0 <= found->bbox.y0) {
2886 found = slink;
2887 break;
2890 break;
2893 else {
2894 dirtag = Int_val (dir_v);
2895 switch (dirtag) {
2896 case dir_first:
2897 found = page->slinks;
2898 break;
2900 case dir_last:
2901 if (page->slinks) {
2902 found = page->slinks + (page->slinkcount - 1);
2904 break;
2907 if (found) {
2908 ret_v = caml_alloc_small (2, 1);
2909 Field (ret_v, 0) = Val_int (found - page->slinks);
2912 unlock (__func__);
2913 CAMLreturn (ret_v);
2916 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2917 unamed, uremote, uremotedest, uannot };
2919 #define LINKTOVAL \
2921 int pageno; \
2923 switch (link->dest.kind) { \
2924 case FZ_LINK_GOTO: \
2926 fz_point p; \
2928 pageno = link->dest.ld.gotor.page; \
2929 p.x = 0; \
2930 p.y = 0; \
2932 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2933 p.y = link->dest.ld.gotor.lt.y; \
2934 fz_transform_point (&p, &pdim->lctm); \
2935 if (p.y < 0) p.y = 0; \
2937 tup_v = caml_alloc_tuple (2); \
2938 ret_v = caml_alloc_small (1, ugoto); \
2939 Field (tup_v, 0) = Val_int (pageno); \
2940 Field (tup_v, 1) = Val_int (p.y); \
2941 Field (ret_v, 0) = tup_v; \
2943 break; \
2945 case FZ_LINK_URI: \
2946 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2947 ret_v = caml_alloc_small (1, uuri); \
2948 Field (ret_v, 0) = str_v; \
2949 break; \
2951 case FZ_LINK_LAUNCH: \
2952 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2953 ret_v = caml_alloc_small (1, ulaunch); \
2954 Field (ret_v, 0) = str_v; \
2955 break; \
2957 case FZ_LINK_NAMED: \
2958 str_v = caml_copy_string (link->dest.ld.named.named); \
2959 ret_v = caml_alloc_small (1, unamed); \
2960 Field (ret_v, 0) = str_v; \
2961 break; \
2963 case FZ_LINK_GOTOR: \
2965 int rty; \
2967 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2968 pageno = link->dest.ld.gotor.page; \
2969 if (pageno == -1) { \
2970 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2971 rty = uremotedest; \
2973 else { \
2974 gr_v = Val_int (pageno); \
2975 rty = uremote; \
2977 tup_v = caml_alloc_tuple (2); \
2978 ret_v = caml_alloc_small (1, rty); \
2979 Field (tup_v, 0) = str_v; \
2980 Field (tup_v, 1) = gr_v; \
2981 Field (ret_v, 0) = tup_v; \
2983 break; \
2985 default: \
2987 char buf[80]; \
2989 snprintf (buf, sizeof (buf), \
2990 "unhandled link kind %d", link->dest.kind); \
2991 str_v = caml_copy_string (buf); \
2992 ret_v = caml_alloc_small (1, uunexpected); \
2993 Field (ret_v, 0) = str_v; \
2995 break; \
2999 CAMLprim value ml_getlink (value ptr_v, value n_v)
3001 CAMLparam2 (ptr_v, n_v);
3002 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3003 fz_link *link;
3004 struct page *page;
3005 struct pagedim *pdim;
3006 char *s = String_val (ptr_v);
3007 struct slink *slink;
3009 /* See ml_findlink for caveat */
3011 ret_v = Val_int (0);
3012 page = parse_pointer (__func__, s);
3013 ensureslinks (page);
3014 pdim = &state.pagedims[page->pdimno];
3015 slink = &page->slinks[Int_val (n_v)];
3016 if (slink->tag == SLINK) {
3017 link = slink->u.link;
3018 LINKTOVAL;
3020 else {
3021 ret_v = caml_alloc_small (1, uannot);
3022 tup_v = caml_alloc_tuple (2);
3023 Field (ret_v, 0) = tup_v;
3024 Field (tup_v, 0) = ptr_v;
3025 Field (tup_v, 1) = n_v;
3028 CAMLreturn (ret_v);
3031 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3033 CAMLparam2 (ptr_v, n_v);
3034 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3035 if (pdf) {
3036 char *s = String_val (ptr_v);
3037 struct page *page;
3038 struct slink *slink;
3040 page = parse_pointer (__func__, s);
3041 slink = &page->slinks[Int_val (n_v)];
3042 CAMLreturn (caml_copy_string (
3043 pdf_annot_contents (state.ctx, pdf,
3044 (pdf_annot *) slink->u.annot)));
3046 else {
3047 CAMLreturn (caml_copy_string (""));
3051 CAMLprim value ml_getlinkcount (value ptr_v)
3053 CAMLparam1 (ptr_v);
3054 struct page *page;
3055 char *s = String_val (ptr_v);
3057 page = parse_pointer (__func__, s);
3058 CAMLreturn (Val_int (page->slinkcount));
3061 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3063 CAMLparam2 (ptr_v, n_v);
3064 CAMLlocal1 (ret_v);
3065 struct page *page;
3066 struct slink *slink;
3067 char *s = String_val (ptr_v);
3068 /* See ml_findlink for caveat */
3070 page = parse_pointer (__func__, s);
3071 ret_v = caml_alloc_tuple (4);
3072 ensureslinks (page);
3074 slink = &page->slinks[Int_val (n_v)];
3075 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3076 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3077 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3078 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3079 unlock (__func__);
3080 CAMLreturn (ret_v);
3083 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3085 CAMLparam3 (ptr_v, x_v, y_v);
3086 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3087 fz_link *link;
3088 struct annot *annot;
3089 struct page *page;
3090 char *ptr = String_val (ptr_v);
3091 int x = Int_val (x_v), y = Int_val (y_v);
3092 struct pagedim *pdim;
3094 ret_v = Val_int (0);
3095 if (trylock (__func__)) {
3096 goto done;
3099 page = parse_pointer (__func__, ptr);
3100 pdim = &state.pagedims[page->pdimno];
3101 x += pdim->bounds.x0;
3102 y += pdim->bounds.y0;
3105 annot = getannot (page, x, y);
3106 if (annot) {
3107 int i, n = -1;
3109 ensureslinks (page);
3110 for (i = 0; i < page->slinkcount; ++i) {
3111 if (page->slinks[i].tag == SANNOT
3112 && page->slinks[i].u.annot == annot->annot) {
3113 n = i;
3114 break;
3117 ret_v = caml_alloc_small (1, uannot);
3118 tup_v = caml_alloc_tuple (2);
3119 Field (ret_v, 0) = tup_v;
3120 Field (tup_v, 0) = ptr_v;
3121 Field (tup_v, 1) = Val_int (n);
3122 goto unlock;
3126 link = getlink (page, x, y);
3127 if (link) {
3128 LINKTOVAL;
3130 else {
3131 fz_rect *b;
3132 fz_page_block *pageb;
3133 fz_stext_block *block;
3135 ensuretext (page);
3136 for (pageb = page->text->blocks;
3137 pageb < page->text->blocks + page->text->len;
3138 ++pageb) {
3139 fz_stext_line *line;
3140 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3141 block = pageb->u.text;
3143 b = &block->bbox;
3144 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3145 continue;
3147 for (line = block->lines;
3148 line < block->lines + block->len;
3149 ++line) {
3150 fz_stext_span *span;
3152 b = &line->bbox;
3153 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3154 continue;
3156 for (span = line->first_span; span; span = span->next) {
3157 int charnum;
3159 b = &span->bbox;
3160 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3161 continue;
3163 for (charnum = 0; charnum < span->len; ++charnum) {
3164 fz_rect bbox;
3165 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3166 b = &bbox;
3168 if (x >= b->x0 && x <= b->x1
3169 && y >= b->y0 && y <= b->y1) {
3170 fz_stext_style *style = span->text->style;
3171 const char *n2 =
3172 style->font
3173 ? style->font->name
3174 : "Span has no font name"
3176 FT_FaceRec *face = style->font->ft_face;
3177 if (face && face->family_name) {
3178 char *s;
3179 char *n1 = face->family_name;
3180 size_t l1 = strlen (n1);
3181 size_t l2 = strlen (n2);
3183 if (l1 != l2 || memcmp (n1, n2, l1)) {
3184 s = malloc (l1 + l2 + 2);
3185 if (s) {
3186 memcpy (s, n2, l2);
3187 s[l2] = '=';
3188 memcpy (s + l2 + 1, n1, l1 + 1);
3189 str_v = caml_copy_string (s);
3190 free (s);
3194 if (str_v == Val_unit) {
3195 str_v = caml_copy_string (n2);
3197 ret_v = caml_alloc_small (1, utext);
3198 Field (ret_v, 0) = str_v;
3199 goto unlock;
3206 unlock:
3207 unlock (__func__);
3209 done:
3210 CAMLreturn (ret_v);
3213 enum { mark_page, mark_block, mark_line, mark_word };
3215 static int uninteresting (int c)
3217 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3218 || ispunct (c);
3221 CAMLprim value ml_clearmark (value ptr_v)
3223 CAMLparam1 (ptr_v);
3224 char *s = String_val (ptr_v);
3225 struct page *page;
3227 if (trylock (__func__)) {
3228 goto done;
3231 page = parse_pointer (__func__, s);
3232 page->fmark.span = NULL;
3233 page->lmark.span = NULL;
3234 page->fmark.i = 0;
3235 page->lmark.i = 0;
3237 unlock (__func__);
3238 done:
3239 CAMLreturn (Val_unit);
3242 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3244 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3245 CAMLlocal1 (ret_v);
3246 fz_rect *b;
3247 struct page *page;
3248 fz_stext_line *line;
3249 fz_page_block *pageb;
3250 fz_stext_block *block;
3251 struct pagedim *pdim;
3252 int mark = Int_val (mark_v);
3253 char *s = String_val (ptr_v);
3254 int x = Int_val (x_v), y = Int_val (y_v);
3256 ret_v = Val_bool (0);
3257 if (trylock (__func__)) {
3258 goto done;
3261 page = parse_pointer (__func__, s);
3262 pdim = &state.pagedims[page->pdimno];
3264 ensuretext (page);
3266 if (mark == mark_page) {
3267 int i;
3268 fz_page_block *pb1 = NULL, *pb2 = NULL;
3270 for (i = 0; i < page->text->len; ++i) {
3271 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3272 pb1 = &page->text->blocks[i];
3273 break;
3276 if (!pb1) goto unlock;
3278 for (i = page->text->len - 1; i >= 0; --i) {
3279 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3280 pb2 = &page->text->blocks[i];
3281 break;
3284 if (!pb2) goto unlock;
3286 block = pb1->u.text;
3288 page->fmark.i = 0;
3289 page->fmark.span = block->lines->first_span;
3291 block = pb2->u.text;
3292 line = &block->lines[block->len - 1];
3293 page->lmark.i = line->last_span->len - 1;
3294 page->lmark.span = line->last_span;
3295 ret_v = Val_bool (1);
3296 goto unlock;
3299 x += pdim->bounds.x0;
3300 y += pdim->bounds.y0;
3302 for (pageb = page->text->blocks;
3303 pageb < page->text->blocks + page->text->len;
3304 ++pageb) {
3305 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3306 block = pageb->u.text;
3308 b = &block->bbox;
3309 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3310 continue;
3312 if (mark == mark_block) {
3313 page->fmark.i = 0;
3314 page->fmark.span = block->lines->first_span;
3316 line = &block->lines[block->len - 1];
3317 page->lmark.i = line->last_span->len - 1;
3318 page->lmark.span = line->last_span;
3319 ret_v = Val_bool (1);
3320 goto unlock;
3323 for (line = block->lines;
3324 line < block->lines + block->len;
3325 ++line) {
3326 fz_stext_span *span;
3328 b = &line->bbox;
3329 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3330 continue;
3332 if (mark == mark_line) {
3333 page->fmark.i = 0;
3334 page->fmark.span = line->first_span;
3336 page->lmark.i = line->last_span->len - 1;
3337 page->lmark.span = line->last_span;
3338 ret_v = Val_bool (1);
3339 goto unlock;
3342 for (span = line->first_span; span; span = span->next) {
3343 int charnum;
3345 b = &span->bbox;
3346 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3347 continue;
3349 for (charnum = 0; charnum < span->len; ++charnum) {
3350 fz_rect bbox;
3351 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3352 b = &bbox;
3354 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3355 /* unicode ftw */
3356 int charnum2, charnum3 = -1, charnum4 = -1;
3358 if (uninteresting (span->text[charnum].c)) goto unlock;
3360 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3361 if (uninteresting (span->text[charnum2].c)) {
3362 charnum3 = charnum2 + 1;
3363 break;
3366 if (charnum3 == -1) charnum3 = 0;
3368 for (charnum2 = charnum + 1;
3369 charnum2 < span->len;
3370 ++charnum2) {
3371 if (uninteresting (span->text[charnum2].c)) break;
3372 charnum4 = charnum2;
3374 if (charnum4 == -1) goto unlock;
3376 page->fmark.i = charnum3;
3377 page->fmark.span = span;
3379 page->lmark.i = charnum4;
3380 page->lmark.span = span;
3381 ret_v = Val_bool (1);
3382 goto unlock;
3388 unlock:
3389 if (!Bool_val (ret_v)) {
3390 page->fmark.span = NULL;
3391 page->lmark.span = NULL;
3392 page->fmark.i = 0;
3393 page->lmark.i = 0;
3395 unlock (__func__);
3397 done:
3398 CAMLreturn (ret_v);
3401 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3403 CAMLparam3 (ptr_v, x_v, y_v);
3404 CAMLlocal2 (ret_v, res_v);
3405 fz_rect *b = NULL;
3406 struct page *page;
3407 fz_page_block *pageb;
3408 struct pagedim *pdim;
3409 char *s = String_val (ptr_v);
3410 int x = Int_val (x_v), y = Int_val (y_v);
3412 ret_v = Val_int (0);
3413 if (trylock (__func__)) {
3414 goto done;
3417 page = parse_pointer (__func__, s);
3418 pdim = &state.pagedims[page->pdimno];
3419 x += pdim->bounds.x0;
3420 y += pdim->bounds.y0;
3422 ensuretext (page);
3424 for (pageb = page->text->blocks;
3425 pageb < page->text->blocks + page->text->len;
3426 ++pageb) {
3427 switch (pageb->type) {
3428 case FZ_PAGE_BLOCK_TEXT:
3429 b = &pageb->u.text->bbox;
3430 break;
3432 case FZ_PAGE_BLOCK_IMAGE:
3433 b = &pageb->u.image->bbox;
3434 break;
3436 default:
3437 continue;
3440 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3441 break;
3442 b = NULL;
3444 if (b) {
3445 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3446 ret_v = caml_alloc_small (1, 1);
3447 Store_double_field (res_v, 0, b->x0);
3448 Store_double_field (res_v, 1, b->x1);
3449 Store_double_field (res_v, 2, b->y0);
3450 Store_double_field (res_v, 3, b->y1);
3451 Field (ret_v, 0) = res_v;
3453 unlock (__func__);
3455 done:
3456 CAMLreturn (ret_v);
3459 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3461 CAMLparam2 (ptr_v, rect_v);
3462 fz_rect b;
3463 struct page *page;
3464 struct pagedim *pdim;
3465 char *s = String_val (ptr_v);
3466 int i, x0, x1, y0, y1, fi, li;
3467 fz_stext_line *line;
3468 fz_page_block *pageb;
3469 fz_stext_block *block;
3470 fz_stext_span *span, *fspan, *lspan;
3472 if (trylock (__func__)) {
3473 goto done;
3476 page = parse_pointer (__func__, s);
3477 ensuretext (page);
3479 pdim = &state.pagedims[page->pdimno];
3480 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3481 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3482 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3483 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3485 if (y0 > y1) {
3486 int t = y0;
3487 y0 = y1;
3488 y1 = t;
3489 x0 = x1;
3490 x1 = t;
3493 fi = page->fmark.i;
3494 fspan = page->fmark.span;
3496 li = page->lmark.i;
3497 lspan = page->lmark.span;
3499 for (pageb = page->text->blocks;
3500 pageb < page->text->blocks + page->text->len;
3501 ++pageb) {
3502 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3503 block = pageb->u.text;
3504 for (line = block->lines;
3505 line < block->lines + block->len;
3506 ++line) {
3508 for (span = line->first_span; span; span = span->next) {
3509 for (i = 0; i < span->len; ++i) {
3510 fz_stext_char_bbox (state.ctx, &b, span, i);
3512 if (x0 >= b.x0 && x0 <= b.x1
3513 && y0 >= b.y0 && y0 <= b.y1) {
3514 fspan = span;
3515 fi = i;
3517 if (x1 >= b.x0 && x1 <= b.x1
3518 && y1 >= b.y0 && y1 <= b.y1) {
3519 lspan = span;
3520 li = i;
3526 if (x1 < x0 && fspan == lspan) {
3527 i = fi;
3528 span = fspan;
3530 fi = li;
3531 fspan = lspan;
3533 li = i;
3534 lspan = span;
3537 page->fmark.i = fi;
3538 page->fmark.span = fspan;
3540 page->lmark.i = li;
3541 page->lmark.span = lspan;
3543 unlock (__func__);
3545 done:
3546 CAMLreturn (Val_unit);
3549 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3551 char buf[4];
3552 int i, len, ret;
3554 for (i = a; i <= b; ++i) {
3555 len = fz_runetochar (buf, span->text[i].c);
3556 ret = fwrite (buf, len, 1, f);
3558 if (ret != 1) {
3559 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3560 len, ret, strerror (errno));
3561 return -1;
3564 return 0;
3567 #ifdef __CYGWIN__
3568 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3570 caml_failwith ("ml_popen not implemented under Cygwin");
3572 #else
3573 CAMLprim value ml_spawn (value command_v, value fds_v)
3575 CAMLparam2 (command_v, fds_v);
3576 CAMLlocal2 (l_v, tup_v);
3577 int ret, ret1;
3578 pid_t pid;
3579 char *msg = NULL;
3580 value earg_v = Nothing;
3581 posix_spawnattr_t attr;
3582 posix_spawn_file_actions_t fa;
3583 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3585 argv[2] = String_val (command_v);
3587 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3588 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3591 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3592 msg = "posix_spawnattr_init";
3593 goto fail1;
3596 #ifdef POSIX_SPAWN_USEVFORK
3597 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3598 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3599 goto fail;
3601 #endif
3603 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3604 int fd1, fd2;
3606 tup_v = Field (l_v, 0);
3607 fd1 = Int_val (Field (tup_v, 0));
3608 fd2 = Int_val (Field (tup_v, 1));
3609 if (fd2 < 0) {
3610 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3611 msg = "posix_spawn_file_actions_addclose";
3612 earg_v = tup_v;
3613 goto fail;
3616 else {
3617 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3618 msg = "posix_spawn_file_actions_adddup2";
3619 earg_v = tup_v;
3620 goto fail;
3625 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3626 msg = "posix_spawn";
3627 goto fail;
3630 fail:
3631 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3632 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3635 fail1:
3636 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3637 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3638 strerror (ret1));
3641 if (msg)
3642 unix_error (ret, msg, earg_v);
3644 CAMLreturn (Val_int (pid));
3646 #endif
3648 CAMLprim value ml_hassel (value ptr_v)
3650 CAMLparam1 (ptr_v);
3651 CAMLlocal1 (ret_v);
3652 struct page *page;
3653 char *s = String_val (ptr_v);
3655 ret_v = Val_bool (0);
3656 if (trylock (__func__)) {
3657 goto done;
3660 page = parse_pointer (__func__, s);
3661 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3662 unlock (__func__);
3663 done:
3664 CAMLreturn (ret_v);
3667 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3669 CAMLparam2 (fd_v, ptr_v);
3670 FILE *f;
3671 int seen = 0;
3672 struct page *page;
3673 fz_stext_line *line;
3674 fz_page_block *pageb;
3675 fz_stext_block *block;
3676 int fd = Int_val (fd_v);
3677 char *s = String_val (ptr_v);
3679 if (trylock (__func__)) {
3680 goto done;
3683 page = parse_pointer (__func__, s);
3685 if (!page->fmark.span || !page->lmark.span) {
3686 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3687 goto unlock;
3690 f = fdopen (fd, "w");
3691 if (!f) {
3692 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3693 fd, strerror (errno));
3694 f = stdout;
3697 for (pageb = page->text->blocks;
3698 pageb < page->text->blocks + page->text->len;
3699 ++pageb) {
3700 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3701 block = pageb->u.text;
3702 for (line = block->lines;
3703 line < block->lines + block->len;
3704 ++line) {
3705 fz_stext_span *span;
3707 for (span = line->first_span; span; span = span->next) {
3708 int a, b;
3710 seen |= span == page->fmark.span || span == page->lmark.span;
3711 a = span == page->fmark.span ? page->fmark.i : 0;
3712 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3714 if (seen) {
3715 if (pipespan (f, span, a, b)) {
3716 goto close;
3718 if (span == page->lmark.span) {
3719 goto close;
3721 if (span == line->last_span) {
3722 if (putc ('\n', f) == EOF) {
3723 fprintf (stderr,
3724 "failed break line on sel pipe: %s\n",
3725 strerror (errno));
3726 goto close;
3733 close:
3734 if (f != stdout) {
3735 int ret = fclose (f);
3736 fd = -1;
3737 if (ret == -1) {
3738 if (errno != ECHILD) {
3739 fprintf (stderr, "failed to close sel pipe: %s\n",
3740 strerror (errno));
3744 unlock:
3745 unlock (__func__);
3747 done:
3748 if (fd >= 0) {
3749 if (close (fd)) {
3750 fprintf (stderr, "failed to close sel pipe: %s\n",
3751 strerror (errno));
3754 CAMLreturn (Val_unit);
3757 CAMLprim value ml_getpdimrect (value pagedimno_v)
3759 CAMLparam1 (pagedimno_v);
3760 CAMLlocal1 (ret_v);
3761 int pagedimno = Int_val (pagedimno_v);
3762 fz_rect box;
3764 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3765 if (trylock (__func__)) {
3766 box = fz_empty_rect;
3768 else {
3769 box = state.pagedims[pagedimno].mediabox;
3770 unlock (__func__);
3773 Store_double_field (ret_v, 0, box.x0);
3774 Store_double_field (ret_v, 1, box.x1);
3775 Store_double_field (ret_v, 2, box.y0);
3776 Store_double_field (ret_v, 3, box.y1);
3778 CAMLreturn (ret_v);
3781 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3782 value dw_v, value cols_v)
3784 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3785 CAMLlocal1 (ret_v);
3786 int i;
3787 double zoom = -1.;
3788 double maxh = 0.0;
3789 struct pagedim *p;
3790 double winw = Int_val (winw_v);
3791 double winh = Int_val (winh_v);
3792 double dw = Int_val (dw_v);
3793 double cols = Int_val (cols_v);
3794 double pw = 1.0, ph = 1.0;
3796 if (trylock (__func__)) {
3797 goto done;
3800 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3801 double w = p->pagebox.x1 / cols;
3802 double h = p->pagebox.y1;
3803 if (h > maxh) {
3804 maxh = h;
3805 ph = h;
3806 if (state.fitmodel != FitProportional) pw = w;
3808 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3811 zoom = (((winh / ph) * pw) + dw) / winw;
3812 unlock (__func__);
3813 done:
3814 ret_v = caml_copy_double (zoom);
3815 CAMLreturn (ret_v);
3818 CAMLprim value ml_getmaxw (value unit_v)
3820 CAMLparam1 (unit_v);
3821 CAMLlocal1 (ret_v);
3822 int i;
3823 double maxw = -1.;
3824 struct pagedim *p;
3826 if (trylock (__func__)) {
3827 goto done;
3830 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3831 double w = p->pagebox.x1;
3832 maxw = MAX (maxw, w);
3835 unlock (__func__);
3836 done:
3837 ret_v = caml_copy_double (maxw);
3838 CAMLreturn (ret_v);
3841 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3843 CAMLparam4 (pt_v, x_v, y_v, string_v);
3844 CAMLlocal1 (ret_v);
3845 int pt = Int_val(pt_v);
3846 int x = Int_val (x_v);
3847 int y = Int_val (y_v);
3848 double w;
3850 w = draw_string (state.face, pt, x, y, String_val (string_v));
3851 ret_v = caml_copy_double (w);
3852 CAMLreturn (ret_v);
3855 CAMLprim value ml_measure_string (value pt_v, value string_v)
3857 CAMLparam2 (pt_v, string_v);
3858 CAMLlocal1 (ret_v);
3859 int pt = Int_val (pt_v);
3860 double w;
3862 w = measure_string (state.face, pt, String_val (string_v));
3863 ret_v = caml_copy_double (w);
3864 CAMLreturn (ret_v);
3867 CAMLprim value ml_getpagebox (value opaque_v)
3869 CAMLparam1 (opaque_v);
3870 CAMLlocal1 (ret_v);
3871 fz_rect rect;
3872 fz_irect bbox;
3873 fz_matrix ctm;
3874 fz_device *dev;
3875 char *s = String_val (opaque_v);
3876 struct page *page = parse_pointer (__func__, s);
3878 ret_v = caml_alloc_tuple (4);
3879 dev = fz_new_bbox_device (state.ctx, &rect);
3880 dev->hints |= FZ_IGNORE_SHADE;
3882 ctm = pagectm (page);
3883 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3885 fz_drop_device (state.ctx, dev);
3886 fz_round_rect (&bbox, &rect);
3887 Field (ret_v, 0) = Val_int (bbox.x0);
3888 Field (ret_v, 1) = Val_int (bbox.y0);
3889 Field (ret_v, 2) = Val_int (bbox.x1);
3890 Field (ret_v, 3) = Val_int (bbox.y1);
3892 CAMLreturn (ret_v);
3895 CAMLprim value ml_setaalevel (value level_v)
3897 CAMLparam1 (level_v);
3899 state.aalevel = Int_val (level_v);
3900 CAMLreturn (Val_unit);
3903 #pragma GCC diagnostic push
3904 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3905 #include <X11/Xlib.h>
3906 #include <X11/cursorfont.h>
3907 #pragma GCC diagnostic pop
3909 #ifdef USE_EGL
3910 #include <EGL/egl.h>
3911 #else
3912 #include <GL/glx.h>
3913 #endif
3915 static const int shapes[] = {
3916 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3919 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3921 static struct {
3922 Window wid;
3923 Display *dpy;
3924 #ifdef USE_EGL
3925 EGLContext ctx;
3926 EGLConfig conf;
3927 EGLSurface win;
3928 EGLDisplay *edpy;
3929 #else
3930 GLXContext ctx;
3931 #endif
3932 XVisualInfo *visual;
3933 Cursor curs[CURS_COUNT];
3934 } glx;
3936 #ifdef VISAVIS
3937 static VisualID initvisual (void)
3939 /* On this system with: `Haswell-ULT Integrated Graphics
3940 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3941 using glX chosen visual and auto scrolling some document in
3942 fullscreen the power/energy-gpu is more than 1 joule bigger
3943 than when using hand picked visual that stands alone in glxinfo
3944 output: it's dead last in the list and it's the only one with
3945 `visual dep' (sic) of 32
3947 No clue what's going on here...
3949 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3951 XVisualInfo info;
3952 int ret = 1;
3954 info.depth = 32;
3955 info.class = TrueColor;
3956 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3957 &info, &ret);
3958 if (!ret || !glx.visual) {
3959 XCloseDisplay (glx.dpy);
3960 caml_failwith ("XGetVisualInfo");
3962 return glx.visual->visualid;
3964 #endif
3966 static void initcurs (void)
3968 for (size_t n = 0; n < CURS_COUNT; ++n) {
3969 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3973 CAMLprim void ml_setbgcol (value color_v)
3975 CAMLparam1 (color_v);
3976 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3977 CAMLreturn0;
3980 #ifdef USE_EGL
3981 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3983 CAMLparam3 (display_v, wid_v, screen_v);
3984 int major, minor;
3985 int num_conf;
3986 EGLint visid;
3987 EGLint attribs[] = {
3988 #ifdef VISAVIS
3989 EGL_NATIVE_VISUAL_ID, 0,
3990 #else
3991 EGL_DEPTH_SIZE, 24,
3992 #endif
3993 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3994 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3995 EGL_NONE
3997 EGLConfig conf;
3999 glx.dpy = XOpenDisplay (String_val (display_v));
4000 if (!glx.dpy) {
4001 caml_failwith ("XOpenDisplay");
4004 eglBindAPI (EGL_OPENGL_API);
4006 glx.edpy = eglGetDisplay (glx.dpy);
4007 if (glx.dpy == EGL_NO_DISPLAY) {
4008 caml_failwith ("eglGetDisplay");
4011 if (!eglInitialize (glx.edpy, &major, &minor)) {
4012 caml_failwith ("eglInitialize");
4015 #ifdef VISAVIS
4016 attribs[1] = visid = initvisual ();
4017 #endif
4019 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4020 !num_conf) {
4021 caml_failwith ("eglChooseConfig");
4024 glx.conf = conf;
4025 #ifndef VISAVIS
4026 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4027 EGL_NATIVE_VISUAL_ID, &visid)) {
4028 caml_failwith ("eglGetConfigAttrib");
4030 #endif
4031 initcurs ();
4033 glx.wid = Int_val (wid_v);
4034 CAMLreturn (Val_int (visid));
4037 CAMLprim value ml_glxcompleteinit (value unit_v)
4039 CAMLparam1 (unit_v);
4041 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4042 if (!glx.ctx) {
4043 caml_failwith ("eglCreateContext");
4046 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4047 glx.wid, NULL);
4048 if (glx.win == EGL_NO_SURFACE) {
4049 caml_failwith ("eglCreateWindowSurface");
4052 XFree (glx.visual);
4053 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4054 glx.ctx = NULL;
4055 caml_failwith ("eglMakeCurrent");
4057 CAMLreturn (Val_unit);
4059 #else
4060 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4062 CAMLparam3 (display_v, wid_v, screen_v);
4064 glx.dpy = XOpenDisplay (String_val (display_v));
4065 if (!glx.dpy) {
4066 caml_failwith ("XOpenDisplay");
4069 #ifdef VISAVIS
4070 initvisual ();
4071 #else
4072 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4073 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4074 if (!glx.visual) {
4075 XCloseDisplay (glx.dpy);
4076 caml_failwith ("glXChooseVisual");
4078 #endif
4079 initcurs ();
4081 glx.wid = Int_val (wid_v);
4082 CAMLreturn (Val_int (glx.visual->visualid));
4085 CAMLprim value ml_glxcompleteinit (value unit_v)
4087 CAMLparam1 (unit_v);
4089 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4090 if (!glx.ctx) {
4091 caml_failwith ("glXCreateContext");
4094 XFree (glx.visual);
4095 glx.visual = NULL;
4097 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4098 glXDestroyContext (glx.dpy, glx.ctx);
4099 glx.ctx = NULL;
4100 caml_failwith ("glXMakeCurrent");
4102 CAMLreturn (Val_unit);
4104 #endif
4106 CAMLprim value ml_setcursor (value cursor_v)
4108 CAMLparam1 (cursor_v);
4109 size_t cursn = Int_val (cursor_v);
4111 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4112 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
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 bo *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.bo_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.bo_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_bo_usable (value unit_v)
4314 CAMLparam1 (unit_v);
4315 CAMLreturn (Val_bool (state.bo_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);