Sync with upstream
[llpp.git] / link.c
blob2abc894773df8c0fa2c384a3ee6f06db26fc40fe
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
4 #include <errno.h>
5 #include <stdio.h>
6 #include <ctype.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <signal.h>
10 #include <wchar.h>
12 #include <unistd.h>
13 #include <pthread.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/utsname.h>
19 #ifdef __CYGWIN__
20 #include <cygwin/socket.h> /* FIONREAD */
21 #else
22 #include <spawn.h>
23 #endif
25 #include <regex.h>
26 #include <stdarg.h>
27 #include <limits.h>
28 #include <inttypes.h>
30 #include <GL/gl.h>
32 #include <caml/fail.h>
33 #include <caml/alloc.h>
34 #include <caml/memory.h>
35 #include <caml/unixsupport.h>
37 #if __GNUC__ < 5
38 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
39 clobbered diagnostics */
40 #pragma GCC diagnostic ignored "-Wclobbered"
41 #endif
43 #pragma GCC diagnostic push
44 #pragma GCC diagnostic ignored "-Wunused-parameter"
45 #pragma GCC diagnostic ignored "-Wshadow"
46 #include <mupdf/fitz.h>
47 #pragma GCC diagnostic pop
48 #include <mupdf/pdf.h>
50 #include <ft2build.h>
51 #include FT_FREETYPE_H
53 #ifdef USE_FONTCONFIG
54 #include <fontconfig/fontconfig.h>
55 #endif
57 #define PIGGYBACK
58 #define CACHE_PAGEREFS
60 #ifndef __USE_GNU
61 extern char **environ;
62 #endif
64 #define MIN(a,b) ((a) < (b) ? (a) : (b))
65 #define MAX(a,b) ((a) > (b) ? (a) : (b))
67 #if defined __GNUC__
68 #define NORETURN_ATTR __attribute__ ((noreturn))
69 #define UNUSED_ATTR __attribute__ ((unused))
70 #if !defined __clang__
71 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
72 #else
73 #define OPTIMIZE_ATTR(n)
74 #endif
75 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
76 #else
77 #define NORETURN_ATTR
78 #define UNUSED_ATTR
79 #define OPTIMIZE_ATTR(n)
80 #define GCC_FMT_ATTR(a, b)
81 #endif
83 #define FMT_s "zu"
85 #define FMT_ptr PRIxPTR
86 #define SCN_ptr SCNxPTR
87 #define FMT_ptr_cast(p) ((uintptr_t) (p))
88 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
90 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
91 err (int exitcode, const char *fmt, ...)
93 va_list ap;
94 int savederrno;
96 savederrno = errno;
97 va_start (ap, fmt);
98 vfprintf (stderr, fmt, ap);
99 va_end (ap);
100 fprintf (stderr, ": %s\n", strerror (savederrno));
101 fflush (stderr);
102 _exit (exitcode);
105 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
106 errx (int exitcode, const char *fmt, ...)
108 va_list ap;
110 va_start (ap, fmt);
111 vfprintf (stderr, fmt, ap);
112 va_end (ap);
113 fputc ('\n', stderr);
114 fflush (stderr);
115 _exit (exitcode);
118 #ifndef GL_TEXTURE_RECTANGLE_ARB
119 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
120 #endif
122 #ifdef USE_NPOT
123 #define TEXT_TYPE GL_TEXTURE_2D
124 #else
125 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
126 #endif
128 #ifndef GL_BGRA
129 #define GL_BGRA 0x80E1
130 #endif
132 #ifndef GL_UNSIGNED_INT_8_8_8_8
133 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
134 #endif
136 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
137 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
138 #endif
140 #if 0
141 #define lprintf printf
142 #else
143 #define lprintf(...)
144 #endif
146 #define ARSERT(cond) for (;;) { \
147 if (!(cond)) { \
148 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
150 break; \
153 struct slice {
154 int h;
155 int texindex;
158 struct tile {
159 int w, h;
160 int slicecount;
161 int sliceheight;
162 struct pbo *pbo;
163 fz_pixmap *pixmap;
164 struct slice slices[1];
167 struct pagedim {
168 int pageno;
169 int rotate;
170 int left;
171 int tctmready;
172 fz_irect bounds;
173 fz_rect pagebox;
174 fz_rect mediabox;
175 fz_matrix ctm, zoomctm, lctm, tctm;
178 struct slink {
179 enum { SLINK, SANNOT } tag;
180 fz_irect bbox;
181 union {
182 fz_link *link;
183 fz_annot *annot;
184 } u;
187 struct annot {
188 fz_irect bbox;
189 fz_annot *annot;
192 struct page {
193 int tgen;
194 int sgen;
195 int agen;
196 int pageno;
197 int pdimno;
198 fz_stext_page *text;
199 fz_stext_sheet *sheet;
200 fz_page *fzpage;
201 fz_display_list *dlist;
202 int slinkcount;
203 struct slink *slinks;
204 int annotcount;
205 struct annot *annots;
206 struct mark {
207 int i;
208 fz_stext_span *span;
209 } fmark, lmark;
212 struct {
213 int sliceheight;
214 struct pagedim *pagedims;
215 int pagecount;
216 int pagedimcount;
217 fz_document *doc;
218 fz_context *ctx;
219 int w, h;
221 int texindex;
222 int texcount;
223 GLuint *texids;
225 GLenum texiform;
226 GLenum texform;
227 GLenum texty;
229 fz_colorspace *colorspace;
231 struct {
232 int w, h;
233 struct slice *slice;
234 } *texowners;
236 int rotate;
237 enum { FitWidth, FitProportional, FitPage } fitmodel;
238 int trimmargins;
239 int needoutline;
240 int gen;
241 int aalevel;
243 int trimanew;
244 fz_irect trimfuzz;
245 fz_pixmap *pig;
247 pthread_t thread;
248 int csock;
249 FT_Face face;
251 char *trimcachepath;
252 int cxack;
253 int dirty;
255 GLuint stid;
257 int pbo_usable;
258 void (*glBindBufferARB) (GLenum, GLuint);
259 GLboolean (*glUnmapBufferARB) (GLenum);
260 void *(*glMapBufferARB) (GLenum, GLenum);
261 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
262 void (*glGenBuffersARB) (GLsizei, GLuint *);
263 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
265 GLfloat texcoords[8];
266 GLfloat vertices[16];
268 #ifdef CACHE_PAGEREFS
269 struct {
270 int idx;
271 int count;
272 pdf_obj **objs;
273 pdf_document *pdf;
274 } pdflut;
275 #endif
276 } state;
278 struct pbo {
279 GLuint id;
280 void *ptr;
281 size_t size;
284 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
286 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
289 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
291 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
294 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
296 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
297 m.a, m.b, m.c, m.d, m.e, m.f);
300 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
302 static void lock (const char *cap)
304 int ret = pthread_mutex_lock (&mutex);
305 if (ret) {
306 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
310 static void unlock (const char *cap)
312 int ret = pthread_mutex_unlock (&mutex);
313 if (ret) {
314 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
318 static int trylock (const char *cap)
320 int ret = pthread_mutex_trylock (&mutex);
321 if (ret && ret != EBUSY) {
322 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
324 return ret == EBUSY;
327 static void *parse_pointer (const char *cap, const char *s)
329 int ret;
330 void *ptr;
332 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
333 if (ret != 1) {
334 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
336 return ptr;
339 static double now (void)
341 struct timeval tv;
343 if (gettimeofday (&tv, NULL)) {
344 err (1, "gettimeofday");
346 return tv.tv_sec + tv.tv_usec*1e-6;
349 static int hasdata (void)
351 int ret, avail;
352 ret = ioctl (state.csock, FIONREAD, &avail);
353 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
354 return avail > 0;
357 CAMLprim value ml_hasdata (value fd_v)
359 CAMLparam1 (fd_v);
360 int ret, avail;
362 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
363 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
364 CAMLreturn (Val_bool (avail > 0));
367 static void readdata (void *p, int size)
369 ssize_t n;
371 again:
372 n = read (state.csock, p, size);
373 if (n < 0) {
374 if (errno == EINTR) goto again;
375 err (1, "read (req %d, ret %zd)", size, n);
377 if (n - size) {
378 if (!n) errx (1, "EOF while reading");
379 errx (1, "read (req %d, ret %zd)", size, n);
383 static void writedata (char *p, int size)
385 ssize_t n;
387 p[0] = (size >> 24) & 0xff;
388 p[1] = (size >> 16) & 0xff;
389 p[2] = (size >> 8) & 0xff;
390 p[3] = (size >> 0) & 0xff;
392 n = write (state.csock, p, size + 4);
393 if (n - size - 4) {
394 if (!n) errx (1, "EOF while writing data");
395 err (1, "write (req %d, ret %zd)", size + 4, n);
399 static int readlen (void)
401 unsigned char p[4];
403 readdata (p, 4);
404 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
407 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
409 int size = 200, len;
410 va_list ap;
411 char *buf;
413 buf = malloc (size);
414 for (;;) {
415 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
417 va_start (ap, fmt);
418 len = vsnprintf (buf + 4, size - 4, fmt, ap);
419 va_end (ap);
421 if (len > -1) {
422 if (len < size - 4) {
423 writedata (buf, len);
424 break;
426 else size = len + 5;
428 else {
429 err (1, "vsnprintf for `%s' failed", fmt);
431 buf = realloc (buf, size);
433 free (buf);
436 static void closedoc (void)
438 #ifdef CACHE_PAGEREFS
439 if (state.pdflut.objs) {
440 int i;
442 for (i = 0; i < state.pdflut.count; ++i) {
443 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
445 free (state.pdflut.objs);
446 state.pdflut.objs = NULL;
447 state.pdflut.idx = 0;
449 #endif
450 if (state.doc) {
451 fz_drop_document (state.ctx, state.doc);
452 state.doc = NULL;
456 static int openxref (char *filename, char *password)
458 int i;
460 for (i = 0; i < state.texcount; ++i) {
461 state.texowners[i].w = -1;
462 state.texowners[i].slice = NULL;
465 closedoc ();
467 state.dirty = 0;
468 if (state.pagedims) {
469 free (state.pagedims);
470 state.pagedims = NULL;
472 state.pagedimcount = 0;
474 fz_set_aa_level (state.ctx, state.aalevel);
475 state.doc = fz_open_document (state.ctx, filename);
476 if (fz_needs_password (state.ctx, state.doc)) {
477 if (password && !*password) {
478 printd ("pass");
479 return 0;
481 else {
482 int ok = fz_authenticate_password (state.ctx, state.doc, password);
483 if (!ok) {
484 printd ("pass fail");
485 return 0;
489 state.pagecount = fz_count_pages (state.ctx, state.doc);
490 return 1;
493 static void pdfinfo (void)
495 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
496 if (pdf) {
497 pdf_obj *infoobj;
499 printd ("info PDF version\t%d.%d",
500 pdf->version / 10, pdf->version % 10);
502 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
503 pdf), "Info");
504 if (infoobj) {
505 unsigned int i;
506 char *s;
507 char *items[] = { "Title", "Author", "Creator",
508 "Producer", "CreationDate" };
510 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
511 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
512 s = pdf_to_utf8 (state.ctx, pdf, obj);
513 if (*s) printd ("info %s\t%s", items[i], s);
514 fz_free (state.ctx, s);
517 printd ("infoend");
521 static void unlinktile (struct tile *tile)
523 int i;
525 for (i = 0; i < tile->slicecount; ++i) {
526 struct slice *s = &tile->slices[i];
528 if (s->texindex != -1) {
529 if (state.texowners[s->texindex].slice == s) {
530 state.texowners[s->texindex].slice = NULL;
536 static void freepage (struct page *page)
538 if (!page) return;
539 if (page->text) {
540 fz_drop_stext_page (state.ctx, page->text);
542 if (page->sheet) {
543 fz_drop_stext_sheet (state.ctx, page->sheet);
545 if (page->slinks) {
546 free (page->slinks);
548 fz_drop_display_list (state.ctx, page->dlist);
549 fz_drop_page (state.ctx, page->fzpage);
550 free (page);
553 static void freetile (struct tile *tile)
555 unlinktile (tile);
556 if (!tile->pbo) {
557 #ifndef PIGGYBACK
558 fz_drop_pixmap (state.ctx, tile->pixmap);
559 #else
560 if (state.pig) {
561 fz_drop_pixmap (state.ctx, state.pig);
563 state.pig = tile->pixmap;
564 #endif
566 else {
567 free (tile->pbo);
568 fz_drop_pixmap (state.ctx, tile->pixmap);
570 free (tile);
573 #ifdef __ALTIVEC__
574 #include <stdint.h>
575 #include <altivec.h>
577 static int cacheline32bytes;
579 static void __attribute__ ((constructor)) clcheck (void)
581 char **envp = environ;
582 unsigned long *auxv;
584 while (*envp++);
586 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
587 if (*auxv == 19) {
588 cacheline32bytes = auxv[1] == 32;
589 return;
594 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
596 size_t size = pixmap->w * pixmap->h * pixmap->n;
597 if (cacheline32bytes && size > 32) {
598 intptr_t a1, a2, diff;
599 size_t sizea, i;
600 vector unsigned char v = vec_splat_u8 (-1);
601 vector unsigned char *p;
603 a1 = a2 = (intptr_t) pixmap->samples;
604 a2 = (a1 + 31) & ~31;
605 diff = a2 - a1;
606 sizea = size - diff;
607 p = (void *) a2;
609 while (a1 != a2) *(char *) a1++ = 0xff;
610 for (i = 0; i < (sizea & ~31); i += 32) {
611 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
612 vec_st (v, i, p);
613 vec_st (v, i + 16, p);
615 while (i < sizea) *((char *) a1 + i++) = 0xff;
617 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
619 #else
620 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
621 #endif
623 static void trimctm (pdf_page *page, int pindex)
625 fz_matrix ctm;
626 struct pagedim *pdim = &state.pagedims[pindex];
628 if (!pdim->tctmready) {
629 if (state.trimmargins) {
630 fz_rect realbox;
631 fz_matrix rm, sm, tm, im, ctm1;
633 fz_rotate (&rm, -pdim->rotate);
634 fz_scale (&sm, 1, -1);
635 fz_concat (&ctm, &rm, &sm);
636 realbox = pdim->mediabox;
637 fz_transform_rect (&realbox, &ctm);
638 fz_translate (&tm, -realbox.x0, -realbox.y0);
639 fz_concat (&ctm1, &ctm, &tm);
640 fz_invert_matrix (&im, &page->ctm);
641 fz_concat (&ctm, &im, &ctm1);
643 else {
644 ctm = fz_identity;
646 pdim->tctm = ctm;
647 pdim->tctmready = 1;
651 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
653 fz_matrix ctm, tm;
654 int pdimno = pdim - state.pagedims;
656 if (pdf_specifics (state.ctx, state.doc)) {
657 trimctm ((pdf_page *) fzpage, pdimno);
658 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
660 else {
661 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
662 fz_concat (&ctm, &tm, &pdim->ctm);
664 return ctm;
667 static fz_matrix pagectm (struct page *page)
669 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
672 static void *loadpage (int pageno, int pindex)
674 fz_device *dev;
675 struct page *page;
677 page = calloc (sizeof (struct page), 1);
678 if (!page) {
679 err (1, "calloc page %d", pageno);
682 page->dlist = fz_new_display_list (state.ctx);
683 dev = fz_new_list_device (state.ctx, page->dlist);
684 fz_try (state.ctx) {
685 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
686 fz_run_page (state.ctx, page->fzpage, dev,
687 &fz_identity, NULL);
689 fz_catch (state.ctx) {
690 page->fzpage = NULL;
692 fz_drop_device (state.ctx, dev);
694 page->pdimno = pindex;
695 page->pageno = pageno;
696 page->sgen = state.gen;
697 page->agen = state.gen;
698 page->tgen = state.gen;
699 return page;
702 static struct tile *alloctile (int h)
704 int i;
705 int slicecount;
706 size_t tilesize;
707 struct tile *tile;
709 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
710 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
711 tile = calloc (tilesize, 1);
712 if (!tile) {
713 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
715 for (i = 0; i < slicecount; ++i) {
716 int sh = MIN (h, state.sliceheight);
717 tile->slices[i].h = sh;
718 tile->slices[i].texindex = -1;
719 h -= sh;
721 tile->slicecount = slicecount;
722 tile->sliceheight = state.sliceheight;
723 return tile;
726 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
727 struct pbo *pbo)
729 fz_rect rect;
730 fz_irect bbox;
731 fz_matrix ctm;
732 fz_device *dev;
733 struct tile *tile;
734 struct pagedim *pdim;
736 tile = alloctile (h);
737 pdim = &state.pagedims[page->pdimno];
739 bbox = pdim->bounds;
740 bbox.x0 += x;
741 bbox.y0 += y;
742 bbox.x1 = bbox.x0 + w;
743 bbox.y1 = bbox.y0 + h;
745 if (state.pig) {
746 if (state.pig->w == w
747 && state.pig->h == h
748 && state.pig->colorspace == state.colorspace) {
749 tile->pixmap = state.pig;
750 tile->pixmap->x = bbox.x0;
751 tile->pixmap->y = bbox.y0;
753 else {
754 fz_drop_pixmap (state.ctx, state.pig);
756 state.pig = NULL;
758 if (!tile->pixmap) {
759 if (pbo) {
760 tile->pixmap =
761 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
762 &bbox, pbo->ptr);
763 tile->pbo = pbo;
765 else {
766 tile->pixmap =
767 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
771 tile->w = w;
772 tile->h = h;
773 clearpixmap (tile->pixmap);
775 dev = fz_new_draw_device (state.ctx, tile->pixmap);
776 ctm = pagectm (page);
777 fz_rect_from_irect (&rect, &bbox);
778 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
779 fz_drop_device (state.ctx, dev);
781 return tile;
784 #ifdef CACHE_PAGEREFS
785 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
786 thanks to Robin Watts */
787 static void
788 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
790 fz_context *ctx = state.ctx; /* doc->ctx; */
791 pdf_obj *kids;
792 int i, len;
794 if (state.pdflut.idx == state.pagecount) return;
796 kids = pdf_dict_gets (ctx, node, "Kids");
797 len = pdf_array_len (ctx, kids);
799 if (len == 0)
800 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
802 if (pdf_mark_obj (ctx, node))
803 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
804 for (i = 0; i < len; i++) {
805 pdf_obj *kid = pdf_array_get (ctx, kids, i);
806 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
807 if (*type
808 ? !strcmp (type, "Pages")
809 : pdf_dict_gets (ctx, kid, "Kids")
810 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
811 pdf_collect_pages (doc, kid);
813 else {
814 if (*type
815 ? strcmp (type, "Page") != 0
816 : !pdf_dict_gets (ctx, kid, "MediaBox"))
817 fz_warn (ctx, "non-page object in page tree (%s)", type);
818 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
821 pdf_unmark_obj (ctx, node);
824 static void
825 pdf_load_page_objs (pdf_document *doc)
827 pdf_obj *root = pdf_dict_gets (state.ctx,
828 pdf_trailer (state.ctx, doc), "Root");
829 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
831 if (!node)
832 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
834 state.pdflut.idx = 0;
835 pdf_collect_pages (doc, node);
837 #endif
839 static void initpdims (int wthack)
841 double start, end;
842 FILE *trimf = NULL;
843 fz_rect rootmediabox;
844 int pageno, trim, show;
845 int trimw = 0, cxcount;
846 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
848 fz_var (trimw);
849 fz_var (cxcount);
850 start = now ();
852 if (state.trimmargins && state.trimcachepath) {
853 trimf = fopen (state.trimcachepath, "rb");
854 if (!trimf) {
855 trimf = fopen (state.trimcachepath, "wb");
856 trimw = 1;
860 if (state.trimmargins || pdf || !state.cxack)
861 cxcount = state.pagecount;
862 else
863 cxcount = MIN (state.pagecount, 1);
865 if (pdf) {
866 pdf_obj *obj;
867 obj = pdf_dict_getp (state.ctx, pdf_trailer (state.ctx, pdf),
868 "Root/Pages/MediaBox");
869 pdf_to_rect (state.ctx, obj, &rootmediabox);
872 #ifdef CACHE_PAGEREFS
873 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
874 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
875 if (!state.pdflut.objs) {
876 err (1, "malloc pageobjs %zu %d %zu failed",
877 sizeof (*state.pdflut.objs), cxcount,
878 sizeof (*state.pdflut.objs) * cxcount);
880 state.pdflut.count = cxcount;
881 pdf_load_page_objs (pdf);
882 state.pdflut.pdf = pdf;
884 #endif
886 for (pageno = 0; pageno < cxcount; ++pageno) {
887 int rotate = 0;
888 struct pagedim *p;
889 fz_rect mediabox;
891 if (pdf) {
892 pdf_obj *pageref, *pageobj;
894 #ifdef CACHE_PAGEREFS
895 pageref = state.pdflut.objs[pageno];
896 #else
897 pageref = pdf_lookup_page_obj (state.ctx, pdf, pageno);
898 #endif
899 pageobj = pdf_resolve_indirect (state.ctx, pageref);
901 if (state.trimmargins) {
902 fz_context *ctx = state.ctx;
903 pdf_obj *obj;
904 pdf_page *page;
906 fz_try (state.ctx) {
907 page = pdf_load_page (ctx, pdf, pageno);
908 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
909 trim = state.trimanew || !obj;
910 if (trim) {
911 fz_rect rect;
912 fz_matrix ctm;
913 fz_device *dev;
915 dev = fz_new_bbox_device (ctx, &rect);
916 dev->hints |= FZ_IGNORE_SHADE;
917 fz_invert_matrix (&ctm, &page->ctm);
918 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
919 fz_drop_device (ctx, dev);
921 rect.x0 += state.trimfuzz.x0;
922 rect.x1 += state.trimfuzz.x1;
923 rect.y0 += state.trimfuzz.y0;
924 rect.y1 += state.trimfuzz.y1;
925 fz_transform_rect (&rect, &ctm);
926 fz_intersect_rect (&rect, &page->mediabox);
928 if (fz_is_empty_rect (&rect)) {
929 mediabox = page->mediabox;
931 else {
932 mediabox = rect;
935 obj = pdf_new_array (ctx, pdf, 4);
936 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
937 mediabox.x0));
938 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
939 mediabox.y0));
940 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
941 mediabox.x1));
942 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
943 mediabox.y1));
944 pdf_dict_puts (state.ctx, pageobj, "llpp.TrimBox", obj);
946 else {
947 mediabox.x0 = pdf_to_real (ctx,
948 pdf_array_get (ctx, obj, 0));
949 mediabox.y0 = pdf_to_real (ctx,
950 pdf_array_get (ctx, obj, 1));
951 mediabox.x1 = pdf_to_real (ctx,
952 pdf_array_get (ctx, obj, 2));
953 mediabox.y1 = pdf_to_real (ctx,
954 pdf_array_get (ctx, obj, 3));
957 rotate = page->rotate;
958 fz_drop_page (ctx, &page->super);
960 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
961 if (show) {
962 printd ("progress %f Trimming %d",
963 (double) (pageno + 1) / state.pagecount,
964 pageno + 1);
967 fz_catch (state.ctx) {
968 fprintf (stderr, "failed to load page %d\n", pageno+1);
971 else {
972 int empty = 0;
973 fz_rect cropbox;
975 pdf_to_rect (state.ctx,
976 pdf_dict_gets (state.ctx, pageobj, "MediaBox"),
977 &mediabox);
978 if (fz_is_empty_rect (&mediabox)) {
979 mediabox.x0 = 0;
980 mediabox.y0 = 0;
981 mediabox.x1 = 612;
982 mediabox.y1 = 792;
983 empty = 1;
986 pdf_to_rect (state.ctx,
987 pdf_dict_gets (state.ctx, pageobj, "CropBox"),
988 &cropbox);
989 if (!fz_is_empty_rect (&cropbox)) {
990 if (empty) {
991 mediabox = cropbox;
993 else {
994 fz_intersect_rect (&mediabox, &cropbox);
997 else {
998 if (empty) {
999 if (fz_is_empty_rect (&rootmediabox)) {
1000 fprintf (stderr,
1001 "cannot find page size for page %d\n",
1002 pageno+1);
1004 else {
1005 mediabox = rootmediabox;
1009 rotate = pdf_to_int (state.ctx,
1010 pdf_dict_gets (state.ctx,
1011 pageobj, "Rotate"));
1014 else {
1015 if (state.trimmargins && trimw) {
1016 fz_page *page;
1018 fz_try (state.ctx) {
1019 page = fz_load_page (state.ctx, state.doc, pageno);
1020 fz_bound_page (state.ctx, page, &mediabox);
1021 rotate = 0;
1022 if (state.trimmargins) {
1023 fz_rect rect;
1024 fz_device *dev;
1026 dev = fz_new_bbox_device (state.ctx, &rect);
1027 dev->hints |= FZ_IGNORE_SHADE;
1028 fz_run_page (state.ctx, page, dev,
1029 &fz_identity, NULL);
1030 fz_drop_device (state.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 (state.ctx, page);
1043 if (!state.cxack) {
1044 printd ("progress %f loading %d",
1045 (double) (pageno + 1) / state.pagecount,
1046 pageno + 1);
1049 fz_catch (state.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 (state.ctx) {
1068 page = fz_load_page (state.ctx,
1069 state.doc, pageno);
1070 fz_bound_page (state.ctx, page, &mediabox);
1071 fz_drop_page (state.ctx, page);
1073 show = !state.trimmargins && pageno % 20 == 0;
1074 if (show) {
1075 printd ("progress %f Gathering dimensions %d",
1076 (double) (pageno) / state.pagecount,
1077 pageno);
1080 fz_catch (state.ctx) {
1081 fprintf (stderr, "failed to load page %d\n", pageno);
1087 if (state.pagedimcount == 0
1088 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1089 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1090 size_t size;
1092 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1093 state.pagedims = realloc (state.pagedims, size);
1094 if (!state.pagedims) {
1095 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1096 size, state.pagedimcount + 1);
1099 p = &state.pagedims[state.pagedimcount++];
1100 p->rotate = rotate;
1101 p->mediabox = mediabox;
1102 p->pageno = pageno;
1105 end = now ();
1106 if (!wthack) {
1107 printd ("progress 1 %s %d pages in %f seconds",
1108 state.trimmargins ? "Trimmed" : "Processed",
1109 state.pagecount, end - start);
1111 state.trimanew = 0;
1112 if (trimf) {
1113 if (fclose (trimf)) {
1114 err (1, "fclose");
1119 static void layout (void)
1121 int pindex;
1122 fz_rect box;
1123 fz_matrix ctm, rm;
1124 struct pagedim *p = p;
1125 double zw, w, maxw = 0.0, zoom = zoom;
1127 if (state.pagedimcount == 0) return;
1129 switch (state.fitmodel) {
1130 case FitProportional:
1131 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1132 double x0, x1;
1134 p = &state.pagedims[pindex];
1135 fz_rotate (&rm, p->rotate + state.rotate);
1136 box = p->mediabox;
1137 fz_transform_rect (&box, &rm);
1139 x0 = MIN (box.x0, box.x1);
1140 x1 = MAX (box.x0, box.x1);
1142 w = x1 - x0;
1143 maxw = MAX (w, maxw);
1144 zoom = state.w / maxw;
1146 break;
1148 case FitPage:
1149 maxw = state.w;
1150 break;
1152 case FitWidth:
1153 break;
1155 default:
1156 ARSERT (0 && state.fitmodel);
1159 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1160 fz_rect rect;
1161 fz_matrix tm, sm;
1163 p = &state.pagedims[pindex];
1164 fz_rotate (&ctm, state.rotate);
1165 fz_rotate (&rm, p->rotate + state.rotate);
1166 box = p->mediabox;
1167 fz_transform_rect (&box, &rm);
1168 w = box.x1 - box.x0;
1169 switch (state.fitmodel) {
1170 case FitProportional:
1171 p->left = ((maxw - w) * zoom) / 2.0;
1172 break;
1173 case FitPage:
1175 double zh, h;
1176 zw = maxw / w;
1177 h = box.y1 - box.y0;
1178 zh = state.h / h;
1179 zoom = MIN (zw, zh);
1180 p->left = (maxw - (w * zoom)) / 2.0;
1182 break;
1183 case FitWidth:
1184 p->left = 0;
1185 zoom = state.w / w;
1186 break;
1189 fz_scale (&p->zoomctm, zoom, zoom);
1190 fz_concat (&ctm, &p->zoomctm, &ctm);
1192 fz_rotate (&rm, p->rotate);
1193 p->pagebox = p->mediabox;
1194 fz_transform_rect (&p->pagebox, &rm);
1195 p->pagebox.x1 -= p->pagebox.x0;
1196 p->pagebox.y1 -= p->pagebox.y0;
1197 p->pagebox.x0 = 0;
1198 p->pagebox.y0 = 0;
1199 rect = p->pagebox;
1200 fz_transform_rect (&rect, &ctm);
1201 fz_round_rect (&p->bounds, &rect);
1202 p->ctm = ctm;
1204 fz_translate (&tm, 0, -p->mediabox.y1);
1205 fz_scale (&sm, zoom, -zoom);
1206 fz_concat (&ctm, &tm, &sm);
1207 fz_concat (&p->lctm, &ctm, &rm);
1209 p->tctmready = 0;
1212 do {
1213 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1214 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1215 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1216 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1217 int boundw = x1 - x0;
1218 int boundh = y1 - y0;
1220 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1221 } while (p-- != state.pagedims);
1224 static
1225 struct anchor { int n; int x; int y; int w; int h; }
1226 desttoanchor (fz_link_dest *dest)
1228 int i;
1229 struct anchor a;
1230 struct pagedim *pdim = state.pagedims;
1232 a.n = -1;
1233 a.x = 0;
1234 a.y = 0;
1235 for (i = 0; i < state.pagedimcount; ++i) {
1236 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1237 break;
1238 pdim = &state.pagedims[i];
1240 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1241 fz_point p;
1242 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1243 p.x = dest->ld.gotor.lt.x;
1244 else
1245 p.x = 0.0;
1246 p.y = dest->ld.gotor.lt.y;
1247 fz_transform_point (&p, &pdim->lctm);
1248 a.x = p.x;
1249 a.y = p.y;
1251 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1252 double x0, x1, y0, y1;
1254 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1255 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1256 a.w = x1 - x0;
1257 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1258 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1259 a.h = y1 - y0;
1260 a.n = dest->ld.gotor.page;
1262 return a;
1265 static void recurse_outline (fz_outline *outline, int level)
1267 while (outline) {
1268 switch (outline->dest.kind) {
1269 case FZ_LINK_GOTO:
1271 struct anchor a = desttoanchor (&outline->dest);
1273 if (a.n >= 0) {
1274 printd ("o %d %d %d %d %s",
1275 level, a.n, a.y, a.h, outline->title);
1278 break;
1280 case FZ_LINK_URI:
1281 printd ("ou %d %" FMT_s " %s %s", level,
1282 strlen (outline->title), outline->title,
1283 outline->dest.ld.uri.uri);
1284 break;
1286 case FZ_LINK_NONE:
1287 printd ("on %d %s", level, outline->title);
1288 break;
1290 default:
1291 printd ("emsg Unhandled outline kind %d for %s\n",
1292 outline->dest.kind, outline->title);
1293 break;
1295 if (outline->down) {
1296 recurse_outline (outline->down, level + 1);
1298 outline = outline->next;
1302 static void process_outline (void)
1304 fz_outline *outline;
1306 if (!state.needoutline || !state.pagedimcount) return;
1308 state.needoutline = 0;
1309 outline = fz_load_outline (state.ctx, state.doc);
1310 if (outline) {
1311 recurse_outline (outline, 0);
1312 fz_drop_outline (state.ctx, outline);
1316 static char *strofspan (fz_stext_span *span)
1318 char *p;
1319 char utf8[10];
1320 fz_stext_char *ch;
1321 size_t size = 0, cap = 80;
1323 p = malloc (cap + 1);
1324 if (!p) return NULL;
1326 for (ch = span->text; ch < span->text + span->len; ++ch) {
1327 int n = fz_runetochar (utf8, ch->c);
1328 if (size + n > cap) {
1329 cap *= 2;
1330 p = realloc (p, cap + 1);
1331 if (!p) return NULL;
1334 memcpy (p + size, utf8, n);
1335 size += n;
1337 p[size] = 0;
1338 return p;
1341 static int matchspan (regex_t *re, fz_stext_span *span,
1342 int stop, int pageno, double start)
1344 int ret;
1345 char *p;
1346 regmatch_t rm;
1347 int a, b, c;
1348 fz_rect sb, eb;
1349 fz_point p1, p2, p3, p4;
1351 p = strofspan (span);
1352 if (!p) return -1;
1354 ret = regexec (re, p, 1, &rm, 0);
1355 if (ret) {
1356 free (p);
1357 if (ret != REG_NOMATCH) {
1358 size_t size;
1359 char errbuf[80];
1360 size = regerror (ret, re, errbuf, sizeof (errbuf));
1361 printd ("msg regexec error `%.*s'",
1362 (int) size, errbuf);
1363 return -1;
1365 return 0;
1367 else {
1368 int l = span->len;
1370 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1371 c += fz_runelen (span->text[a].c);
1373 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1374 c += fz_runelen (span->text[b].c);
1377 if (fz_runelen (span->text[b].c) > 1) {
1378 b = MAX (0, b-1);
1381 fz_stext_char_bbox (state.ctx, &sb, span, a);
1382 fz_stext_char_bbox (state.ctx, &eb, span, b);
1384 p1.x = sb.x0;
1385 p1.y = sb.y0;
1386 p2.x = eb.x1;
1387 p2.y = sb.y0;
1388 p3.x = eb.x1;
1389 p3.y = eb.y1;
1390 p4.x = sb.x0;
1391 p4.y = eb.y1;
1393 if (!stop) {
1394 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1395 pageno, 1,
1396 p1.x, p1.y,
1397 p2.x, p2.y,
1398 p3.x, p3.y,
1399 p4.x, p4.y);
1401 printd ("progress 1 found at %d `%.*s' in %f sec",
1402 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1403 now () - start);
1405 else {
1406 printd ("match %d %d %f %f %f %f %f %f %f %f",
1407 pageno, 2,
1408 p1.x, p1.y,
1409 p2.x, p2.y,
1410 p3.x, p3.y,
1411 p4.x, p4.y);
1413 free (p);
1414 return 1;
1418 static int compareblocks (const void *l, const void *r)
1420 fz_stext_block const *ls = l;
1421 fz_stext_block const *rs = r;
1422 return ls->bbox.y0 - rs->bbox.y0;
1425 /* wishful thinking function */
1426 static void search (regex_t *re, int pageno, int y, int forward)
1428 int i, j;
1429 fz_device *tdev;
1430 fz_stext_page *text;
1431 fz_stext_sheet *sheet;
1432 struct pagedim *pdim, *pdimprev;
1433 int stop = 0, niters = 0;
1434 double start, end;
1435 fz_page *page;
1437 start = now ();
1438 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1439 if (niters++ == 5) {
1440 niters = 0;
1441 if (hasdata ()) {
1442 printd ("progress 1 attention requested aborting search at %d",
1443 pageno);
1444 stop = 1;
1446 else {
1447 printd ("progress %f searching in page %d",
1448 (double) (pageno + 1) / state.pagecount,
1449 pageno);
1452 pdimprev = NULL;
1453 for (i = 0; i < state.pagedimcount; ++i) {
1454 pdim = &state.pagedims[i];
1455 if (pdim->pageno == pageno) {
1456 goto found;
1458 if (pdim->pageno > pageno) {
1459 pdim = pdimprev;
1460 goto found;
1462 pdimprev = pdim;
1464 pdim = pdimprev;
1465 found:
1467 sheet = fz_new_stext_sheet (state.ctx);
1468 text = fz_new_stext_page (state.ctx);
1469 tdev = fz_new_stext_device (state.ctx, sheet, text);
1471 page = fz_load_page (state.ctx, state.doc, pageno);
1473 fz_matrix ctm = pagectm1 (page, pdim);
1474 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1477 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1478 fz_drop_device (state.ctx, tdev);
1480 for (j = 0; j < text->len; ++j) {
1481 int k;
1482 fz_page_block *pb;
1483 fz_stext_block *block;
1485 pb = &text->blocks[forward ? j : text->len - 1 - j];
1486 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1487 block = pb->u.text;
1489 for (k = 0; k < block->len; ++k) {
1490 fz_stext_line *line;
1491 fz_stext_span *span;
1493 if (forward) {
1494 line = &block->lines[k];
1495 if (line->bbox.y0 < y + 1) continue;
1497 else {
1498 line = &block->lines[block->len - 1 - k];
1499 if (line->bbox.y0 > y - 1) continue;
1502 for (span = line->first_span; span; span = span->next) {
1503 switch (matchspan (re, span, stop, pageno, start)) {
1504 case 0: break;
1505 case 1: stop = 1; break;
1506 case -1: stop = 1; goto endloop;
1511 if (forward) {
1512 pageno += 1;
1513 y = 0;
1515 else {
1516 pageno -= 1;
1517 y = INT_MAX;
1519 endloop:
1520 fz_drop_stext_page (state.ctx, text);
1521 fz_drop_stext_sheet (state.ctx, sheet);
1522 fz_drop_page (state.ctx, page);
1524 end = now ();
1525 if (!stop) {
1526 printd ("progress 1 no matches %f sec", end - start);
1528 printd ("clearrects");
1531 static void set_tex_params (int colorspace)
1533 union {
1534 unsigned char b;
1535 unsigned int s;
1536 } endianness = {1};
1538 switch (colorspace) {
1539 case 0:
1540 state.texiform = GL_RGBA8;
1541 state.texform = GL_RGBA;
1542 state.texty = GL_UNSIGNED_BYTE;
1543 state.colorspace = fz_device_rgb (state.ctx);
1544 break;
1545 case 1:
1546 state.texiform = GL_RGBA8;
1547 state.texform = GL_BGRA;
1548 state.texty = endianness.s > 1
1549 ? GL_UNSIGNED_INT_8_8_8_8
1550 : GL_UNSIGNED_INT_8_8_8_8_REV;
1551 state.colorspace = fz_device_bgr (state.ctx);
1552 break;
1553 case 2:
1554 state.texiform = GL_LUMINANCE_ALPHA;
1555 state.texform = GL_LUMINANCE_ALPHA;
1556 state.texty = GL_UNSIGNED_BYTE;
1557 state.colorspace = fz_device_gray (state.ctx);
1558 break;
1559 default:
1560 errx (1, "invalid colorspce %d", colorspace);
1564 static void realloctexts (int texcount)
1566 size_t size;
1568 if (texcount == state.texcount) return;
1570 if (texcount < state.texcount) {
1571 glDeleteTextures (state.texcount - texcount,
1572 state.texids + texcount);
1575 size = texcount * sizeof (*state.texids);
1576 state.texids = realloc (state.texids, size);
1577 if (!state.texids) {
1578 err (1, "realloc texids %" FMT_s, size);
1581 size = texcount * sizeof (*state.texowners);
1582 state.texowners = realloc (state.texowners, size);
1583 if (!state.texowners) {
1584 err (1, "realloc texowners %" FMT_s, size);
1586 if (texcount > state.texcount) {
1587 int i;
1589 glGenTextures (texcount - state.texcount,
1590 state.texids + state.texcount);
1591 for (i = state.texcount; i < texcount; ++i) {
1592 state.texowners[i].w = -1;
1593 state.texowners[i].slice = NULL;
1596 state.texcount = texcount;
1597 state.texindex = 0;
1600 static char *mbtoutf8 (char *s)
1602 char *p, *r;
1603 wchar_t *tmp;
1604 size_t i, ret, len;
1606 len = mbstowcs (NULL, s, strlen (s));
1607 if (len == 0) {
1608 return s;
1610 else {
1611 if (len == (size_t) -1) {
1612 return s;
1616 tmp = malloc (len * sizeof (wchar_t));
1617 if (!tmp) {
1618 return s;
1621 ret = mbstowcs (tmp, s, len);
1622 if (ret == (size_t) -1) {
1623 free (tmp);
1624 return s;
1627 len = 0;
1628 for (i = 0; i < ret; ++i) {
1629 len += fz_runelen (tmp[i]);
1632 p = r = malloc (len + 1);
1633 if (!r) {
1634 free (tmp);
1635 return s;
1638 for (i = 0; i < ret; ++i) {
1639 p += fz_runetochar (p, tmp[i]);
1641 *p = 0;
1642 free (tmp);
1643 return r;
1646 CAMLprim value ml_mbtoutf8 (value s_v)
1648 CAMLparam1 (s_v);
1649 CAMLlocal1 (ret_v);
1650 char *s, *r;
1652 s = String_val (s_v);
1653 r = mbtoutf8 (s);
1654 if (r == s) {
1655 ret_v = s_v;
1657 else {
1658 ret_v = caml_copy_string (r);
1659 free (r);
1661 CAMLreturn (ret_v);
1664 static void * mainloop (void UNUSED_ATTR *unused)
1666 char *p = NULL;
1667 int len, ret, oldlen = 0;
1669 fz_var (p);
1670 fz_var (oldlen);
1671 for (;;) {
1672 len = readlen ();
1673 if (len == 0) {
1674 errx (1, "readlen returned 0");
1677 if (oldlen < len + 1) {
1678 p = realloc (p, len + 1);
1679 if (!p) {
1680 err (1, "realloc %d failed", len + 1);
1682 oldlen = len + 1;
1684 readdata (p, len);
1685 p[len] = 0;
1687 if (!strncmp ("open", p, 4)) {
1688 int wthack, off, ok = 0;
1689 char *password;
1690 char *filename;
1691 char *utf8filename;
1692 size_t filenamelen;
1694 fz_var (ok);
1695 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1696 if (ret != 2) {
1697 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1700 filename = p + 5 + off;
1701 filenamelen = strlen (filename);
1702 password = filename + filenamelen + 1;
1704 lock ("open");
1705 fz_try (state.ctx) {
1706 ok = openxref (filename, password);
1708 fz_catch (state.ctx) {
1709 utf8filename = mbtoutf8 (filename);
1710 printd ("msg Could not open %s", utf8filename);
1712 if (ok) {
1713 pdfinfo ();
1714 initpdims (wthack);
1716 unlock ("open");
1718 if (ok) {
1719 if (!wthack) {
1720 utf8filename = mbtoutf8 (filename);
1721 printd ("msg Opened %s (press h/F1 to get help)",
1722 utf8filename);
1723 if (utf8filename != filename) {
1724 free (utf8filename);
1727 state.needoutline = 1;
1730 else if (!strncmp ("cs", p, 2)) {
1731 int i, colorspace;
1733 ret = sscanf (p + 2, " %d", &colorspace);
1734 if (ret != 1) {
1735 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1737 lock ("cs");
1738 set_tex_params (colorspace);
1739 for (i = 0; i < state.texcount; ++i) {
1740 state.texowners[i].w = -1;
1741 state.texowners[i].slice = NULL;
1743 unlock ("cs");
1745 else if (!strncmp ("freepage", p, 8)) {
1746 void *ptr;
1748 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1749 if (ret != 1) {
1750 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1752 freepage (ptr);
1754 else if (!strncmp ("freetile", p, 8)) {
1755 void *ptr;
1757 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1758 if (ret != 1) {
1759 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1761 freetile (ptr);
1763 else if (!strncmp ("search", p, 6)) {
1764 int icase, pageno, y, len2, forward;
1765 char *pattern;
1766 regex_t re;
1768 ret = sscanf (p + 6, " %d %d %d %d,%n",
1769 &icase, &pageno, &y, &forward, &len2);
1770 if (ret != 4) {
1771 errx (1, "malformed search `%s' ret=%d", p, ret);
1774 pattern = p + 6 + len2;
1775 ret = regcomp (&re, pattern,
1776 REG_EXTENDED | (icase ? REG_ICASE : 0));
1777 if (ret) {
1778 char errbuf[80];
1779 size_t size;
1781 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1782 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1784 else {
1785 search (&re, pageno, y, forward);
1786 regfree (&re);
1789 else if (!strncmp ("geometry", p, 8)) {
1790 int w, h, fitmodel;
1792 printd ("clear");
1793 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1794 if (ret != 3) {
1795 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1798 lock ("geometry");
1799 state.h = h;
1800 if (w != state.w) {
1801 int i;
1802 state.w = w;
1803 for (i = 0; i < state.texcount; ++i) {
1804 state.texowners[i].slice = NULL;
1807 state.fitmodel = fitmodel;
1808 layout ();
1809 process_outline ();
1811 state.gen++;
1812 unlock ("geometry");
1813 printd ("continue %d", state.pagecount);
1815 else if (!strncmp ("reqlayout", p, 9)) {
1816 char *nameddest;
1817 int rotate, off, h;
1818 unsigned int fitmodel;
1819 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1821 printd ("clear");
1822 ret = sscanf (p + 9, " %d %u %d %n",
1823 &rotate, &fitmodel, &h, &off);
1824 if (ret != 3) {
1825 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1827 lock ("reqlayout");
1828 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1829 state.gen += 1;
1831 state.rotate = rotate;
1832 state.fitmodel = fitmodel;
1833 state.h = h;
1834 layout ();
1835 process_outline ();
1837 nameddest = p + 9 + off;
1838 if (pdf && nameddest && *nameddest) {
1839 struct anchor a;
1840 fz_link_dest dest;
1841 pdf_obj *needle, *obj;
1843 needle = pdf_new_string (state.ctx, pdf, nameddest,
1844 strlen (nameddest));
1845 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1846 if (obj) {
1847 dest = pdf_parse_link_dest (state.ctx, pdf,
1848 FZ_LINK_GOTO, obj);
1850 a = desttoanchor (&dest);
1851 if (a.n >= 0) {
1852 printd ("a %d %d %d", a.n, a.x, a.y);
1854 else {
1855 printd ("emsg failed to parse destination `%s'\n",
1856 nameddest);
1859 else {
1860 printd ("emsg destination `%s' not found\n",
1861 nameddest);
1863 pdf_drop_obj (state.ctx, needle);
1866 state.gen++;
1867 unlock ("reqlayout");
1868 printd ("continue %d", state.pagecount);
1870 else if (!strncmp ("page", p, 4)) {
1871 double a, b;
1872 struct page *page;
1873 int pageno, pindex;
1875 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1876 if (ret != 2) {
1877 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1880 lock ("page");
1881 a = now ();
1882 page = loadpage (pageno, pindex);
1883 b = now ();
1884 unlock ("page");
1886 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1888 else if (!strncmp ("tile", p, 4)) {
1889 int x, y, w, h;
1890 struct page *page;
1891 struct tile *tile;
1892 double a, b;
1893 void *data;
1895 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1896 SCN_ptr_cast (&page), &x, &y, &w, &h,
1897 SCN_ptr_cast (&data));
1898 if (ret != 6) {
1899 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1902 lock ("tile");
1903 a = now ();
1904 tile = rendertile (page, x, y, w, h, data);
1905 b = now ();
1906 unlock ("tile");
1908 printd ("tile %d %d %" FMT_ptr " %u %f",
1909 x, y,
1910 FMT_ptr_cast (tile),
1911 tile->w * tile->h * tile->pixmap->n,
1912 b - a);
1914 else if (!strncmp ("trimset", p, 7)) {
1915 fz_irect fuzz;
1916 int trimmargins;
1918 ret = sscanf (p + 7, " %d %d %d %d %d",
1919 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1920 if (ret != 5) {
1921 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1923 lock ("trimset");
1924 state.trimmargins = trimmargins;
1925 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1926 state.trimanew = 1;
1927 state.trimfuzz = fuzz;
1929 unlock ("trimset");
1931 else if (!strncmp ("settrim", p, 7)) {
1932 fz_irect fuzz;
1933 int trimmargins;
1935 ret = sscanf (p + 7, " %d %d %d %d %d",
1936 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1937 if (ret != 5) {
1938 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1940 printd ("clear");
1941 lock ("settrim");
1942 state.trimmargins = trimmargins;
1943 state.needoutline = 1;
1944 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1945 state.trimanew = 1;
1946 state.trimfuzz = fuzz;
1948 state.pagedimcount = 0;
1949 free (state.pagedims);
1950 state.pagedims = NULL;
1951 initpdims (0);
1952 layout ();
1953 process_outline ();
1954 unlock ("settrim");
1955 printd ("continue %d", state.pagecount);
1957 else if (!strncmp ("sliceh", p, 6)) {
1958 int h;
1960 ret = sscanf (p + 6, " %d", &h);
1961 if (ret != 1) {
1962 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1964 if (h != state.sliceheight) {
1965 int i;
1967 state.sliceheight = h;
1968 for (i = 0; i < state.texcount; ++i) {
1969 state.texowners[i].w = -1;
1970 state.texowners[i].h = -1;
1971 state.texowners[i].slice = NULL;
1975 else if (!strncmp ("interrupt", p, 9)) {
1976 printd ("vmsg interrupted");
1978 else {
1979 errx (1, "unknown command %.*s", len, p);
1982 return 0;
1985 CAMLprim value ml_realloctexts (value texcount_v)
1987 CAMLparam1 (texcount_v);
1988 int ok;
1990 if (trylock (__func__)) {
1991 ok = 0;
1992 goto done;
1994 realloctexts (Int_val (texcount_v));
1995 ok = 1;
1996 unlock (__func__);
1998 done:
1999 CAMLreturn (Val_bool (ok));
2002 static void recti (int x0, int y0, int x1, int y1)
2004 GLfloat *v = state.vertices;
2006 glVertexPointer (2, GL_FLOAT, 0, v);
2007 v[0] = x0; v[1] = y0;
2008 v[2] = x1; v[3] = y0;
2009 v[4] = x0; v[5] = y1;
2010 v[6] = x1; v[7] = y1;
2011 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2014 static void showsel (struct page *page, int ox, int oy)
2016 int seen = 0;
2017 fz_irect bbox;
2018 fz_rect rect;
2019 fz_stext_line *line;
2020 fz_page_block *pageb;
2021 fz_stext_block *block;
2022 struct mark first, last;
2023 unsigned char selcolor[] = {15,15,15,140};
2025 first = page->fmark;
2026 last = page->lmark;
2028 if (!first.span || !last.span) return;
2030 glEnable (GL_BLEND);
2031 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2032 glColor4ubv (selcolor);
2034 ox += state.pagedims[page->pdimno].bounds.x0;
2035 oy += state.pagedims[page->pdimno].bounds.y0;
2036 for (pageb = page->text->blocks;
2037 pageb < page->text->blocks + page->text->len;
2038 ++pageb) {
2039 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2040 block = pageb->u.text;
2042 for (line = block->lines;
2043 line < block->lines + block->len;
2044 ++line) {
2045 fz_stext_span *span;
2046 rect = fz_empty_rect;
2048 for (span = line->first_span; span; span = span->next) {
2049 int i, j, k;
2050 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2052 j = 0;
2053 k = span->len - 1;
2055 if (span == page->fmark.span && span == page->lmark.span) {
2056 seen = 1;
2057 j = MIN (first.i, last.i);
2058 k = MAX (first.i, last.i);
2060 else {
2061 if (span == first.span) {
2062 seen = 1;
2063 j = first.i;
2065 else if (span == last.span) {
2066 seen = 1;
2067 k = last.i;
2071 if (seen) {
2072 for (i = j; i <= k; ++i) {
2073 fz_rect bbox1;
2074 fz_union_rect (&rect,
2075 fz_stext_char_bbox (state.ctx, &bbox1,
2076 span, i));
2078 fz_round_rect (&bbox, &rect);
2079 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2080 bbox.x0,
2081 bbox.y0,
2082 bbox.x1,
2083 bbox.y1,
2084 oy, ox);
2086 recti (bbox.x0 + ox, bbox.y0 + oy,
2087 bbox.x1 + ox, bbox.y1 + oy);
2088 if (span == last.span) {
2089 goto done;
2091 rect = fz_empty_rect;
2096 done:
2097 glDisable (GL_BLEND);
2100 #include "glfont.c"
2102 static void stipplerect (fz_matrix *m,
2103 fz_point *p1,
2104 fz_point *p2,
2105 fz_point *p3,
2106 fz_point *p4,
2107 GLfloat *texcoords,
2108 GLfloat *vertices)
2110 fz_transform_point (p1, m);
2111 fz_transform_point (p2, m);
2112 fz_transform_point (p3, m);
2113 fz_transform_point (p4, m);
2115 float w, h, s, t;
2117 w = p2->x - p1->x;
2118 h = p2->y - p1->y;
2119 t = sqrtf (w*w + h*h) * .25f;
2121 w = p3->x - p2->x;
2122 h = p3->y - p2->y;
2123 s = sqrtf (w*w + h*h) * .25f;
2125 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2126 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2128 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2129 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2131 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2132 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2134 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2135 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2137 glDrawArrays (GL_LINES, 0, 8);
2140 static void solidrect (fz_matrix *m,
2141 fz_point *p1,
2142 fz_point *p2,
2143 fz_point *p3,
2144 fz_point *p4,
2145 GLfloat *vertices)
2147 fz_transform_point (p1, m);
2148 fz_transform_point (p2, m);
2149 fz_transform_point (p3, m);
2150 fz_transform_point (p4, m);
2151 vertices[0] = p1->x; vertices[1] = p1->y;
2152 vertices[2] = p2->x; vertices[3] = p2->y;
2154 vertices[4] = p3->x; vertices[5] = p3->y;
2155 vertices[6] = p4->x; vertices[7] = p4->y;
2156 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2159 static void highlightlinks (struct page *page, int xoff, int yoff)
2161 int i;
2162 fz_matrix ctm, tm, pm;
2163 fz_link *link, *links;
2164 GLfloat *texcoords = state.texcoords;
2165 GLfloat *vertices = state.vertices;
2167 links = fz_load_links (state.ctx, page->fzpage);
2169 glEnable (GL_TEXTURE_1D);
2170 glEnable (GL_BLEND);
2171 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2172 glBindTexture (GL_TEXTURE_1D, state.stid);
2174 xoff -= state.pagedims[page->pdimno].bounds.x0;
2175 yoff -= state.pagedims[page->pdimno].bounds.y0;
2176 fz_translate (&tm, xoff, yoff);
2177 pm = pagectm (page);
2178 fz_concat (&ctm, &pm, &tm);
2180 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2181 glVertexPointer (2, GL_FLOAT, 0, vertices);
2183 for (link = links; link; link = link->next) {
2184 fz_point p1, p2, p3, p4;
2186 p1.x = link->rect.x0;
2187 p1.y = link->rect.y0;
2189 p2.x = link->rect.x1;
2190 p2.y = link->rect.y0;
2192 p3.x = link->rect.x1;
2193 p3.y = link->rect.y1;
2195 p4.x = link->rect.x0;
2196 p4.y = link->rect.y1;
2198 switch (link->dest.kind) {
2199 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2200 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2201 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2202 default: glColor3ub (0, 0, 0); break;
2204 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2207 for (i = 0; i < page->annotcount; ++i) {
2208 fz_point p1, p2, p3, p4;
2209 struct annot *annot = &page->annots[i];
2211 p1.x = annot->bbox.x0;
2212 p1.y = annot->bbox.y0;
2214 p2.x = annot->bbox.x1;
2215 p2.y = annot->bbox.y0;
2217 p3.x = annot->bbox.x1;
2218 p3.y = annot->bbox.y1;
2220 p4.x = annot->bbox.x0;
2221 p4.y = annot->bbox.y1;
2223 glColor3ub (0, 0, 128);
2224 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2227 glDisable (GL_BLEND);
2228 glDisable (GL_TEXTURE_1D);
2231 static int compareslinks (const void *l, const void *r)
2233 struct slink const *ls = l;
2234 struct slink const *rs = r;
2235 if (ls->bbox.y0 == rs->bbox.y0) {
2236 return rs->bbox.x0 - rs->bbox.x0;
2238 return ls->bbox.y0 - rs->bbox.y0;
2241 static void droptext (struct page *page)
2243 if (page->text) {
2244 fz_drop_stext_page (state.ctx, page->text);
2245 page->fmark.i = -1;
2246 page->lmark.i = -1;
2247 page->fmark.span = NULL;
2248 page->lmark.span = NULL;
2249 page->text = NULL;
2251 if (page->sheet) {
2252 fz_drop_stext_sheet (state.ctx, page->sheet);
2253 page->sheet = NULL;
2257 static void dropannots (struct page *page)
2259 if (page->annots) {
2260 free (page->annots);
2261 page->annots = NULL;
2262 page->annotcount = 0;
2266 static void ensureannots (struct page *page)
2268 int i, count = 0;
2269 size_t annotsize = sizeof (*page->annots);
2270 fz_annot *annot;
2272 if (state.gen != page->agen) {
2273 dropannots (page);
2274 page->agen = state.gen;
2276 if (page->annots) return;
2278 for (annot = fz_first_annot (state.ctx, page->fzpage);
2279 annot;
2280 annot = fz_next_annot (state.ctx, page->fzpage, annot)) {
2281 count++;
2284 if (count > 0) {
2285 page->annotcount = count;
2286 page->annots = calloc (count, annotsize);
2287 if (!page->annots) {
2288 err (1, "calloc annots %d", count);
2291 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2292 annot;
2293 annot = fz_next_annot (state.ctx, page->fzpage, annot), i++) {
2294 fz_rect rect;
2296 fz_bound_annot (state.ctx, page->fzpage, annot, &rect);
2297 page->annots[i].annot = annot;
2298 fz_round_rect (&page->annots[i].bbox, &rect);
2303 static void dropslinks (struct page *page)
2305 if (page->slinks) {
2306 free (page->slinks);
2307 page->slinks = NULL;
2308 page->slinkcount = 0;
2312 static void ensureslinks (struct page *page)
2314 fz_matrix ctm;
2315 int i, count;
2316 size_t slinksize = sizeof (*page->slinks);
2317 fz_link *link, *links;
2319 ensureannots (page);
2320 if (state.gen != page->sgen) {
2321 dropslinks (page);
2322 page->sgen = state.gen;
2324 if (page->slinks) return;
2326 links = fz_load_links (state.ctx, page->fzpage);
2327 ctm = state.pagedims[page->pdimno].ctm;
2329 count = page->annotcount;
2330 for (link = links; link; link = link->next) {
2331 count++;
2333 if (count > 0) {
2334 int j;
2336 page->slinkcount = count;
2337 page->slinks = calloc (count, slinksize);
2338 if (!page->slinks) {
2339 err (1, "calloc slinks %d", count);
2342 for (i = 0, link = links; link; ++i, link = link->next) {
2343 fz_rect rect;
2345 rect = link->rect;
2346 fz_transform_rect (&rect, &ctm);
2347 page->slinks[i].tag = SLINK;
2348 page->slinks[i].u.link = link;
2349 fz_round_rect (&page->slinks[i].bbox, &rect);
2351 for (j = 0; j < page->annotcount; ++j, ++i) {
2352 fz_rect rect;
2353 fz_bound_annot (state.ctx,
2354 page->fzpage,
2355 page->annots[j].annot,
2356 &rect);
2357 fz_transform_rect (&rect, &ctm);
2358 fz_round_rect (&page->slinks[i].bbox, &rect);
2360 page->slinks[i].tag = SANNOT;
2361 page->slinks[i].u.annot = page->annots[j].annot;
2363 qsort (page->slinks, count, slinksize, compareslinks);
2367 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2368 static void fmt_linkn (char *s, unsigned int u)
2370 unsigned int len; unsigned int q;
2371 unsigned int zma = 'z' - 'a' + 1;
2372 len = 1; q = u;
2373 while (q > zma - 1) { ++len; q /= zma; }
2374 if (s) {
2375 s += len;
2376 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2377 /* handles u == 0 */
2379 s[len] = 0;
2382 static void highlightslinks (struct page *page, int xoff, int yoff,
2383 int noff, char *targ, int tlen, int hfsize)
2385 int i;
2386 char buf[40];
2387 struct slink *slink;
2388 double x0, y0, x1, y1, w;
2390 ensureslinks (page);
2391 glColor3ub (0xc3, 0xb0, 0x91);
2392 for (i = 0; i < page->slinkcount; ++i) {
2393 fmt_linkn (buf, i + noff);
2394 if (!tlen || !strncmp (targ, buf, tlen)) {
2395 slink = &page->slinks[i];
2397 x0 = slink->bbox.x0 + xoff - 5;
2398 y1 = slink->bbox.y0 + yoff - 5;
2399 y0 = y1 + 10 + hfsize;
2400 w = measure_string (state.face, hfsize, buf);
2401 x1 = x0 + w + 10;
2402 recti (x0, y0, x1, y1);
2406 glEnable (GL_BLEND);
2407 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2408 glEnable (GL_TEXTURE_2D);
2409 glColor3ub (0, 0, 0);
2410 for (i = 0; i < page->slinkcount; ++i) {
2411 fmt_linkn (buf, i + noff);
2412 if (!tlen || !strncmp (targ, buf, tlen)) {
2413 slink = &page->slinks[i];
2415 x0 = slink->bbox.x0 + xoff;
2416 y0 = slink->bbox.y0 + yoff + hfsize;
2417 draw_string (state.face, hfsize, x0, y0, buf);
2420 glDisable (GL_TEXTURE_2D);
2421 glDisable (GL_BLEND);
2424 static void uploadslice (struct tile *tile, struct slice *slice)
2426 int offset;
2427 struct slice *slice1;
2428 unsigned char *texdata;
2430 offset = 0;
2431 for (slice1 = tile->slices; slice != slice1; slice1++) {
2432 offset += slice1->h * tile->w * tile->pixmap->n;
2434 if (slice->texindex != -1 && slice->texindex < state.texcount
2435 && state.texowners[slice->texindex].slice == slice) {
2436 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2438 else {
2439 int subimage = 0;
2440 int texindex = state.texindex++ % state.texcount;
2442 if (state.texowners[texindex].w == tile->w) {
2443 if (state.texowners[texindex].h >= slice->h) {
2444 subimage = 1;
2446 else {
2447 state.texowners[texindex].h = slice->h;
2450 else {
2451 state.texowners[texindex].h = slice->h;
2454 state.texowners[texindex].w = tile->w;
2455 state.texowners[texindex].slice = slice;
2456 slice->texindex = texindex;
2458 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2459 #if TEXT_TYPE == GL_TEXTURE_2D
2460 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2461 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2462 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2463 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2464 #endif
2465 if (tile->pbo) {
2466 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2467 texdata = 0;
2469 else {
2470 texdata = tile->pixmap->samples;
2472 if (subimage) {
2473 glTexSubImage2D (TEXT_TYPE,
2477 tile->w,
2478 slice->h,
2479 state.texform,
2480 state.texty,
2481 texdata+offset
2484 else {
2485 glTexImage2D (TEXT_TYPE,
2487 state.texiform,
2488 tile->w,
2489 slice->h,
2491 state.texform,
2492 state.texty,
2493 texdata+offset
2496 if (tile->pbo) {
2497 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2502 CAMLprim value ml_begintiles (value unit_v)
2504 CAMLparam1 (unit_v);
2505 glEnable (TEXT_TYPE);
2506 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2507 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2508 CAMLreturn (unit_v);
2511 CAMLprim value ml_endtiles (value unit_v)
2513 CAMLparam1 (unit_v);
2514 glDisable (TEXT_TYPE);
2515 CAMLreturn (unit_v);
2518 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2520 CAMLparam2 (args_v, ptr_v);
2521 int dispx = Int_val (Field (args_v, 0));
2522 int dispy = Int_val (Field (args_v, 1));
2523 int dispw = Int_val (Field (args_v, 2));
2524 int disph = Int_val (Field (args_v, 3));
2525 int tilex = Int_val (Field (args_v, 4));
2526 int tiley = Int_val (Field (args_v, 5));
2527 char *s = String_val (ptr_v);
2528 struct tile *tile = parse_pointer (__func__, s);
2529 int slicey, firstslice;
2530 struct slice *slice;
2531 GLfloat *texcoords = state.texcoords;
2532 GLfloat *vertices = state.vertices;
2534 firstslice = tiley / tile->sliceheight;
2535 slice = &tile->slices[firstslice];
2536 slicey = tiley % tile->sliceheight;
2538 while (disph > 0) {
2539 int dh;
2541 dh = slice->h - slicey;
2542 dh = MIN (disph, dh);
2543 uploadslice (tile, slice);
2545 texcoords[0] = tilex; texcoords[1] = slicey;
2546 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2547 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2548 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2550 vertices[0] = dispx; vertices[1] = dispy;
2551 vertices[2] = dispx+dispw; vertices[3] = dispy;
2552 vertices[4] = dispx; vertices[5] = dispy+dh;
2553 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2555 #if TEXT_TYPE == GL_TEXTURE_2D
2556 for (int i = 0; i < 8; ++i) {
2557 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2559 #endif
2561 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2562 dispy += dh;
2563 disph -= dh;
2564 slice++;
2565 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2566 slicey = 0;
2568 CAMLreturn (Val_unit);
2571 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2573 fz_matrix ctm, tm, pm;
2574 fz_point p1, p2, p3, p4;
2575 GLfloat *vertices = state.vertices;
2576 double *v = (double *) rects_v;
2578 xoff -= state.pagedims[page->pdimno].bounds.x0;
2579 yoff -= state.pagedims[page->pdimno].bounds.y0;
2580 fz_translate (&tm, xoff, yoff);
2581 pm = pagectm (page);
2582 fz_concat (&ctm, &pm, &tm);
2584 glEnable (GL_BLEND);
2585 glVertexPointer (2, GL_FLOAT, 0, vertices);
2587 glColor4dv (v);
2588 p1.x = v[4];
2589 p1.y = v[5];
2591 p2.x = v[6];
2592 p2.y = v[5];
2594 p3.x = v[6];
2595 p3.y = v[7];
2597 p4.x = v[4];
2598 p4.y = v[7];
2599 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2600 glDisable (GL_BLEND);
2603 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2604 value xoff_v, value yoff_v,
2605 value li_v)
2607 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2608 int xoff = Int_val (xoff_v);
2609 int yoff = Int_val (yoff_v);
2610 int noff = Int_val (Field (li_v, 0));
2611 char *targ = String_val (Field (li_v, 1));
2612 int tlen = caml_string_length (Field (li_v, 1));
2613 int hfsize = Int_val (Field (li_v, 2));
2614 char *s = String_val (ptr_v);
2615 int hlmask = Int_val (hlinks_v);
2616 struct page *page = parse_pointer (__func__, s);
2618 if (!page->fzpage) {
2619 /* deal with loadpage failed pages */
2620 goto done;
2623 ensureannots (page);
2625 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2626 if (trylock (__func__)) {
2627 noff = 0;
2628 goto done;
2630 if (hlmask & 2) {
2631 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2632 noff = page->slinkcount;
2634 if (page->tgen == state.gen) {
2635 showsel (page, xoff, yoff);
2637 unlock (__func__);
2639 done:
2640 CAMLreturn (Val_int (noff));
2643 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2644 value rects_v)
2646 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2647 int xoff = Int_val (xoff_v);
2648 int yoff = Int_val (yoff_v);
2649 char *s = String_val (ptr_v);
2650 struct page *page = parse_pointer (__func__, s);
2652 drawprect (page, xoff, yoff, rects_v);
2653 CAMLreturn (Val_unit);
2656 static struct annot *getannot (struct page *page, int x, int y)
2658 int i;
2659 fz_point p;
2660 fz_matrix ctm;
2661 const fz_matrix *tctm;
2662 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2664 if (!page->annots) return NULL;
2666 if (pdf) {
2667 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2668 tctm = &state.pagedims[page->pdimno].tctm;
2670 else {
2671 tctm = &fz_identity;
2674 p.x = x;
2675 p.y = y;
2677 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2678 fz_invert_matrix (&ctm, &ctm);
2679 fz_transform_point (&p, &ctm);
2681 if (pdf) {
2682 for (i = 0; i < page->annotcount; ++i) {
2683 struct annot *a = &page->annots[i];
2684 pdf_annot *annot = (pdf_annot *) a->annot;
2685 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2686 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2687 return a;
2692 return NULL;
2695 static fz_link *getlink (struct page *page, int x, int y)
2697 fz_point p;
2698 fz_matrix ctm;
2699 const fz_matrix *tctm;
2700 fz_link *link, *links;
2702 tctm = &fz_identity;
2703 links = fz_load_links (state.ctx, page->fzpage);
2705 p.x = x;
2706 p.y = y;
2708 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2709 fz_invert_matrix (&ctm, &ctm);
2710 fz_transform_point (&p, &ctm);
2712 for (link = links; link; link = link->next) {
2713 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2714 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2715 return link;
2719 return NULL;
2722 static void ensuretext (struct page *page)
2724 if (state.gen != page->tgen) {
2725 droptext (page);
2726 page->tgen = state.gen;
2728 if (!page->text) {
2729 fz_matrix ctm;
2730 fz_device *tdev;
2732 page->text = fz_new_stext_page (state.ctx);
2733 page->sheet = fz_new_stext_sheet (state.ctx);
2734 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2735 ctm = pagectm (page);
2736 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2737 fz_run_display_list (state.ctx, page->dlist,
2738 tdev, &ctm, &fz_infinite_rect, NULL);
2739 qsort (page->text->blocks, page->text->len,
2740 sizeof (*page->text->blocks), compareblocks);
2741 fz_end_page (state.ctx, tdev);
2742 fz_drop_device (state.ctx, tdev);
2746 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2748 CAMLparam2 (start_page_v, dir_v);
2749 CAMLlocal1 (ret_v);
2750 int i, dir = Int_val (dir_v);
2751 int start_page = Int_val (start_page_v);
2752 int end_page = dir > 0 ? state.pagecount : -1;
2753 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2755 fz_var (end_page);
2756 ret_v = Val_int (0);
2757 lock (__func__);
2758 for (i = start_page + dir; i != end_page; i += dir) {
2759 int found;
2761 fz_var (found);
2762 if (pdf) {
2763 pdf_page *page = NULL;
2765 fz_try (state.ctx) {
2766 page = pdf_load_page (state.ctx, pdf, i);
2767 found = !!page->links || !!page->annots;
2769 fz_catch (state.ctx) {
2770 found = 0;
2772 if (page) {
2773 fz_drop_page (state.ctx, &page->super);
2776 else {
2777 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2778 found = !!fz_load_links (state.ctx, page);
2779 fz_drop_page (state.ctx, page);
2782 if (found) {
2783 ret_v = caml_alloc_small (1, 1);
2784 Field (ret_v, 0) = Val_int (i);
2785 goto unlock;
2788 unlock:
2789 unlock (__func__);
2790 CAMLreturn (ret_v);
2793 enum { dir_first, dir_last };
2794 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2796 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2798 CAMLparam2 (ptr_v, dir_v);
2799 CAMLlocal2 (ret_v, pos_v);
2800 struct page *page;
2801 int dirtag, i, slinkindex;
2802 struct slink *found = NULL ,*slink;
2803 char *s = String_val (ptr_v);
2805 page = parse_pointer (__func__, s);
2806 ret_v = Val_int (0);
2807 /* This is scary we are not taking locks here ensureslinks does
2808 not modify state and given that we obtained the page it can not
2809 disappear under us either */
2810 lock (__func__);
2811 ensureslinks (page);
2813 if (Is_block (dir_v)) {
2814 dirtag = Tag_val (dir_v);
2815 switch (dirtag) {
2816 case dir_first_visible:
2818 int x0, y0, dir, first_index, last_index;
2820 pos_v = Field (dir_v, 0);
2821 x0 = Int_val (Field (pos_v, 0));
2822 y0 = Int_val (Field (pos_v, 1));
2823 dir = Int_val (Field (pos_v, 2));
2825 if (dir >= 0) {
2826 dir = 1;
2827 first_index = 0;
2828 last_index = page->slinkcount;
2830 else {
2831 first_index = page->slinkcount - 1;
2832 last_index = -1;
2835 for (i = first_index; i != last_index; i += dir) {
2836 slink = &page->slinks[i];
2837 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2838 found = slink;
2839 break;
2843 break;
2845 case dir_left:
2846 slinkindex = Int_val (Field (dir_v, 0));
2847 found = &page->slinks[slinkindex];
2848 for (i = slinkindex - 1; i >= 0; --i) {
2849 slink = &page->slinks[i];
2850 if (slink->bbox.x0 < found->bbox.x0) {
2851 found = slink;
2852 break;
2855 break;
2857 case dir_right:
2858 slinkindex = Int_val (Field (dir_v, 0));
2859 found = &page->slinks[slinkindex];
2860 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2861 slink = &page->slinks[i];
2862 if (slink->bbox.x0 > found->bbox.x0) {
2863 found = slink;
2864 break;
2867 break;
2869 case dir_down:
2870 slinkindex = Int_val (Field (dir_v, 0));
2871 found = &page->slinks[slinkindex];
2872 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2873 slink = &page->slinks[i];
2874 if (slink->bbox.y0 >= found->bbox.y0) {
2875 found = slink;
2876 break;
2879 break;
2881 case dir_up:
2882 slinkindex = Int_val (Field (dir_v, 0));
2883 found = &page->slinks[slinkindex];
2884 for (i = slinkindex - 1; i >= 0; --i) {
2885 slink = &page->slinks[i];
2886 if (slink->bbox.y0 <= found->bbox.y0) {
2887 found = slink;
2888 break;
2891 break;
2894 else {
2895 dirtag = Int_val (dir_v);
2896 switch (dirtag) {
2897 case dir_first:
2898 found = page->slinks;
2899 break;
2901 case dir_last:
2902 if (page->slinks) {
2903 found = page->slinks + (page->slinkcount - 1);
2905 break;
2908 if (found) {
2909 ret_v = caml_alloc_small (2, 1);
2910 Field (ret_v, 0) = Val_int (found - page->slinks);
2913 unlock (__func__);
2914 CAMLreturn (ret_v);
2917 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2918 unamed, uremote, uremotedest, uannot };
2920 #define LINKTOVAL \
2922 int pageno; \
2924 switch (link->dest.kind) { \
2925 case FZ_LINK_GOTO: \
2927 fz_point p; \
2929 pageno = link->dest.ld.gotor.page; \
2930 p.x = 0; \
2931 p.y = 0; \
2933 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2934 p.y = link->dest.ld.gotor.lt.y; \
2935 fz_transform_point (&p, &pdim->lctm); \
2936 if (p.y < 0) p.y = 0; \
2938 tup_v = caml_alloc_tuple (2); \
2939 ret_v = caml_alloc_small (1, ugoto); \
2940 Field (tup_v, 0) = Val_int (pageno); \
2941 Field (tup_v, 1) = Val_int (p.y); \
2942 Field (ret_v, 0) = tup_v; \
2944 break; \
2946 case FZ_LINK_URI: \
2947 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2948 ret_v = caml_alloc_small (1, uuri); \
2949 Field (ret_v, 0) = str_v; \
2950 break; \
2952 case FZ_LINK_LAUNCH: \
2953 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2954 ret_v = caml_alloc_small (1, ulaunch); \
2955 Field (ret_v, 0) = str_v; \
2956 break; \
2958 case FZ_LINK_NAMED: \
2959 str_v = caml_copy_string (link->dest.ld.named.named); \
2960 ret_v = caml_alloc_small (1, unamed); \
2961 Field (ret_v, 0) = str_v; \
2962 break; \
2964 case FZ_LINK_GOTOR: \
2966 int rty; \
2968 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2969 pageno = link->dest.ld.gotor.page; \
2970 if (pageno == -1) { \
2971 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2972 rty = uremotedest; \
2974 else { \
2975 gr_v = Val_int (pageno); \
2976 rty = uremote; \
2978 tup_v = caml_alloc_tuple (2); \
2979 ret_v = caml_alloc_small (1, rty); \
2980 Field (tup_v, 0) = str_v; \
2981 Field (tup_v, 1) = gr_v; \
2982 Field (ret_v, 0) = tup_v; \
2984 break; \
2986 default: \
2988 char buf[80]; \
2990 snprintf (buf, sizeof (buf), \
2991 "unhandled link kind %d", link->dest.kind); \
2992 str_v = caml_copy_string (buf); \
2993 ret_v = caml_alloc_small (1, uunexpected); \
2994 Field (ret_v, 0) = str_v; \
2996 break; \
3000 CAMLprim value ml_getlink (value ptr_v, value n_v)
3002 CAMLparam2 (ptr_v, n_v);
3003 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3004 fz_link *link;
3005 struct page *page;
3006 struct pagedim *pdim;
3007 char *s = String_val (ptr_v);
3008 struct slink *slink;
3010 /* See ml_findlink for caveat */
3012 ret_v = Val_int (0);
3013 page = parse_pointer (__func__, s);
3014 ensureslinks (page);
3015 pdim = &state.pagedims[page->pdimno];
3016 slink = &page->slinks[Int_val (n_v)];
3017 if (slink->tag == SLINK) {
3018 link = slink->u.link;
3019 LINKTOVAL;
3021 else {
3022 ret_v = caml_alloc_small (1, uannot);
3023 tup_v = caml_alloc_tuple (2);
3024 Field (ret_v, 0) = tup_v;
3025 Field (tup_v, 0) = ptr_v;
3026 Field (tup_v, 1) = n_v;
3029 CAMLreturn (ret_v);
3032 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3034 CAMLparam2 (ptr_v, n_v);
3035 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3036 if (pdf) {
3037 char *s = String_val (ptr_v);
3038 struct page *page;
3039 struct slink *slink;
3041 page = parse_pointer (__func__, s);
3042 slink = &page->slinks[Int_val (n_v)];
3043 CAMLreturn (caml_copy_string (
3044 pdf_annot_contents (state.ctx, pdf,
3045 (pdf_annot *) slink->u.annot)));
3047 else {
3048 CAMLreturn (caml_copy_string (""));
3052 CAMLprim value ml_getlinkcount (value ptr_v)
3054 CAMLparam1 (ptr_v);
3055 struct page *page;
3056 char *s = String_val (ptr_v);
3058 page = parse_pointer (__func__, s);
3059 CAMLreturn (Val_int (page->slinkcount));
3062 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3064 CAMLparam2 (ptr_v, n_v);
3065 CAMLlocal1 (ret_v);
3066 struct page *page;
3067 struct slink *slink;
3068 char *s = String_val (ptr_v);
3069 /* See ml_findlink for caveat */
3071 page = parse_pointer (__func__, s);
3072 ret_v = caml_alloc_tuple (4);
3073 ensureslinks (page);
3075 slink = &page->slinks[Int_val (n_v)];
3076 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3077 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3078 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3079 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3080 unlock (__func__);
3081 CAMLreturn (ret_v);
3084 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3086 CAMLparam3 (ptr_v, x_v, y_v);
3087 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3088 fz_link *link;
3089 struct annot *annot;
3090 struct page *page;
3091 char *ptr = String_val (ptr_v);
3092 int x = Int_val (x_v), y = Int_val (y_v);
3093 struct pagedim *pdim;
3095 ret_v = Val_int (0);
3096 if (trylock (__func__)) {
3097 goto done;
3100 page = parse_pointer (__func__, ptr);
3101 pdim = &state.pagedims[page->pdimno];
3102 x += pdim->bounds.x0;
3103 y += pdim->bounds.y0;
3106 annot = getannot (page, x, y);
3107 if (annot) {
3108 int i, n = -1;
3110 ensureslinks (page);
3111 for (i = 0; i < page->slinkcount; ++i) {
3112 if (page->slinks[i].tag == SANNOT
3113 && page->slinks[i].u.annot == annot->annot) {
3114 n = i;
3115 break;
3118 ret_v = caml_alloc_small (1, uannot);
3119 tup_v = caml_alloc_tuple (2);
3120 Field (ret_v, 0) = tup_v;
3121 Field (tup_v, 0) = ptr_v;
3122 Field (tup_v, 1) = Val_int (n);
3123 goto unlock;
3127 link = getlink (page, x, y);
3128 if (link) {
3129 LINKTOVAL;
3131 else {
3132 fz_rect *b;
3133 fz_page_block *pageb;
3134 fz_stext_block *block;
3136 ensuretext (page);
3137 for (pageb = page->text->blocks;
3138 pageb < page->text->blocks + page->text->len;
3139 ++pageb) {
3140 fz_stext_line *line;
3141 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3142 block = pageb->u.text;
3144 b = &block->bbox;
3145 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3146 continue;
3148 for (line = block->lines;
3149 line < block->lines + block->len;
3150 ++line) {
3151 fz_stext_span *span;
3153 b = &line->bbox;
3154 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3155 continue;
3157 for (span = line->first_span; span; span = span->next) {
3158 int charnum;
3160 b = &span->bbox;
3161 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3162 continue;
3164 for (charnum = 0; charnum < span->len; ++charnum) {
3165 fz_rect bbox;
3166 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3167 b = &bbox;
3169 if (x >= b->x0 && x <= b->x1
3170 && y >= b->y0 && y <= b->y1) {
3171 fz_stext_style *style = span->text->style;
3172 const char *n2 =
3173 style->font
3174 ? style->font->name
3175 : "Span has no font name"
3177 FT_FaceRec *face = style->font->ft_face;
3178 if (face && face->family_name) {
3179 char *s;
3180 char *n1 = face->family_name;
3181 size_t l1 = strlen (n1);
3182 size_t l2 = strlen (n2);
3184 if (l1 != l2 || memcmp (n1, n2, l1)) {
3185 s = malloc (l1 + l2 + 2);
3186 if (s) {
3187 memcpy (s, n2, l2);
3188 s[l2] = '=';
3189 memcpy (s + l2 + 1, n1, l1 + 1);
3190 str_v = caml_copy_string (s);
3191 free (s);
3195 if (str_v == Val_unit) {
3196 str_v = caml_copy_string (n2);
3198 ret_v = caml_alloc_small (1, utext);
3199 Field (ret_v, 0) = str_v;
3200 goto unlock;
3207 unlock:
3208 unlock (__func__);
3210 done:
3211 CAMLreturn (ret_v);
3214 enum { mark_page, mark_block, mark_line, mark_word };
3216 static int uninteresting (int c)
3218 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3219 || ispunct (c);
3222 CAMLprim value ml_clearmark (value ptr_v)
3224 CAMLparam1 (ptr_v);
3225 char *s = String_val (ptr_v);
3226 struct page *page;
3228 if (trylock (__func__)) {
3229 goto done;
3232 page = parse_pointer (__func__, s);
3233 page->fmark.span = NULL;
3234 page->lmark.span = NULL;
3235 page->fmark.i = 0;
3236 page->lmark.i = 0;
3238 unlock (__func__);
3239 done:
3240 CAMLreturn (Val_unit);
3243 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3245 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3246 CAMLlocal1 (ret_v);
3247 fz_rect *b;
3248 struct page *page;
3249 fz_stext_line *line;
3250 fz_page_block *pageb;
3251 fz_stext_block *block;
3252 struct pagedim *pdim;
3253 int mark = Int_val (mark_v);
3254 char *s = String_val (ptr_v);
3255 int x = Int_val (x_v), y = Int_val (y_v);
3257 ret_v = Val_bool (0);
3258 if (trylock (__func__)) {
3259 goto done;
3262 page = parse_pointer (__func__, s);
3263 pdim = &state.pagedims[page->pdimno];
3265 ensuretext (page);
3267 if (mark == mark_page) {
3268 int i;
3269 fz_page_block *pb1 = NULL, *pb2 = NULL;
3271 for (i = 0; i < page->text->len; ++i) {
3272 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3273 pb1 = &page->text->blocks[i];
3274 break;
3277 if (!pb1) goto unlock;
3279 for (i = page->text->len - 1; i >= 0; --i) {
3280 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3281 pb2 = &page->text->blocks[i];
3282 break;
3285 if (!pb2) goto unlock;
3287 block = pb1->u.text;
3289 page->fmark.i = 0;
3290 page->fmark.span = block->lines->first_span;
3292 block = pb2->u.text;
3293 line = &block->lines[block->len - 1];
3294 page->lmark.i = line->last_span->len - 1;
3295 page->lmark.span = line->last_span;
3296 ret_v = Val_bool (1);
3297 goto unlock;
3300 x += pdim->bounds.x0;
3301 y += pdim->bounds.y0;
3303 for (pageb = page->text->blocks;
3304 pageb < page->text->blocks + page->text->len;
3305 ++pageb) {
3306 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3307 block = pageb->u.text;
3309 b = &block->bbox;
3310 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3311 continue;
3313 if (mark == mark_block) {
3314 page->fmark.i = 0;
3315 page->fmark.span = block->lines->first_span;
3317 line = &block->lines[block->len - 1];
3318 page->lmark.i = line->last_span->len - 1;
3319 page->lmark.span = line->last_span;
3320 ret_v = Val_bool (1);
3321 goto unlock;
3324 for (line = block->lines;
3325 line < block->lines + block->len;
3326 ++line) {
3327 fz_stext_span *span;
3329 b = &line->bbox;
3330 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3331 continue;
3333 if (mark == mark_line) {
3334 page->fmark.i = 0;
3335 page->fmark.span = line->first_span;
3337 page->lmark.i = line->last_span->len - 1;
3338 page->lmark.span = line->last_span;
3339 ret_v = Val_bool (1);
3340 goto unlock;
3343 for (span = line->first_span; span; span = span->next) {
3344 int charnum;
3346 b = &span->bbox;
3347 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3348 continue;
3350 for (charnum = 0; charnum < span->len; ++charnum) {
3351 fz_rect bbox;
3352 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3353 b = &bbox;
3355 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3356 /* unicode ftw */
3357 int charnum2, charnum3 = -1, charnum4 = -1;
3359 if (uninteresting (span->text[charnum].c)) goto unlock;
3361 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3362 if (uninteresting (span->text[charnum2].c)) {
3363 charnum3 = charnum2 + 1;
3364 break;
3367 if (charnum3 == -1) charnum3 = 0;
3369 for (charnum2 = charnum + 1;
3370 charnum2 < span->len;
3371 ++charnum2) {
3372 if (uninteresting (span->text[charnum2].c)) break;
3373 charnum4 = charnum2;
3375 if (charnum4 == -1) goto unlock;
3377 page->fmark.i = charnum3;
3378 page->fmark.span = span;
3380 page->lmark.i = charnum4;
3381 page->lmark.span = span;
3382 ret_v = Val_bool (1);
3383 goto unlock;
3389 unlock:
3390 if (!Bool_val (ret_v)) {
3391 page->fmark.span = NULL;
3392 page->lmark.span = NULL;
3393 page->fmark.i = 0;
3394 page->lmark.i = 0;
3396 unlock (__func__);
3398 done:
3399 CAMLreturn (ret_v);
3402 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3404 CAMLparam3 (ptr_v, x_v, y_v);
3405 CAMLlocal2 (ret_v, res_v);
3406 fz_rect *b = NULL;
3407 struct page *page;
3408 fz_page_block *pageb;
3409 struct pagedim *pdim;
3410 char *s = String_val (ptr_v);
3411 int x = Int_val (x_v), y = Int_val (y_v);
3413 ret_v = Val_int (0);
3414 if (trylock (__func__)) {
3415 goto done;
3418 page = parse_pointer (__func__, s);
3419 pdim = &state.pagedims[page->pdimno];
3420 x += pdim->bounds.x0;
3421 y += pdim->bounds.y0;
3423 ensuretext (page);
3425 for (pageb = page->text->blocks;
3426 pageb < page->text->blocks + page->text->len;
3427 ++pageb) {
3428 switch (pageb->type) {
3429 case FZ_PAGE_BLOCK_TEXT:
3430 b = &pageb->u.text->bbox;
3431 break;
3433 case FZ_PAGE_BLOCK_IMAGE:
3434 b = &pageb->u.image->bbox;
3435 break;
3437 default:
3438 continue;
3441 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3442 break;
3443 b = NULL;
3445 if (b) {
3446 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3447 ret_v = caml_alloc_small (1, 1);
3448 Store_double_field (res_v, 0, b->x0);
3449 Store_double_field (res_v, 1, b->x1);
3450 Store_double_field (res_v, 2, b->y0);
3451 Store_double_field (res_v, 3, b->y1);
3452 Field (ret_v, 0) = res_v;
3454 unlock (__func__);
3456 done:
3457 CAMLreturn (ret_v);
3460 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3462 CAMLparam2 (ptr_v, rect_v);
3463 fz_rect b;
3464 struct page *page;
3465 struct pagedim *pdim;
3466 char *s = String_val (ptr_v);
3467 int i, x0, x1, y0, y1, fi, li;
3468 fz_stext_line *line;
3469 fz_page_block *pageb;
3470 fz_stext_block *block;
3471 fz_stext_span *span, *fspan, *lspan;
3473 if (trylock (__func__)) {
3474 goto done;
3477 page = parse_pointer (__func__, s);
3478 ensuretext (page);
3480 pdim = &state.pagedims[page->pdimno];
3481 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3482 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3483 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3484 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3486 if (y0 > y1) {
3487 int t = y0;
3488 y0 = y1;
3489 y1 = t;
3490 x0 = x1;
3491 x1 = t;
3494 fi = page->fmark.i;
3495 fspan = page->fmark.span;
3497 li = page->lmark.i;
3498 lspan = page->lmark.span;
3500 for (pageb = page->text->blocks;
3501 pageb < page->text->blocks + page->text->len;
3502 ++pageb) {
3503 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3504 block = pageb->u.text;
3505 for (line = block->lines;
3506 line < block->lines + block->len;
3507 ++line) {
3509 for (span = line->first_span; span; span = span->next) {
3510 for (i = 0; i < span->len; ++i) {
3511 fz_stext_char_bbox (state.ctx, &b, span, i);
3513 if (x0 >= b.x0 && x0 <= b.x1
3514 && y0 >= b.y0 && y0 <= b.y1) {
3515 fspan = span;
3516 fi = i;
3518 if (x1 >= b.x0 && x1 <= b.x1
3519 && y1 >= b.y0 && y1 <= b.y1) {
3520 lspan = span;
3521 li = i;
3527 if (x1 < x0 && fspan == lspan) {
3528 i = fi;
3529 span = fspan;
3531 fi = li;
3532 fspan = lspan;
3534 li = i;
3535 lspan = span;
3538 page->fmark.i = fi;
3539 page->fmark.span = fspan;
3541 page->lmark.i = li;
3542 page->lmark.span = lspan;
3544 unlock (__func__);
3546 done:
3547 CAMLreturn (Val_unit);
3550 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3552 char buf[4];
3553 int i, len, ret;
3555 for (i = a; i <= b; ++i) {
3556 len = fz_runetochar (buf, span->text[i].c);
3557 ret = fwrite (buf, len, 1, f);
3559 if (ret != 1) {
3560 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3561 len, ret, strerror (errno));
3562 return -1;
3565 return 0;
3568 #ifdef __CYGWIN__
3569 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3571 caml_failwith ("ml_popen not implemented under Cygwin");
3573 #else
3574 CAMLprim value ml_spawn (value command_v, value fds_v)
3576 CAMLparam2 (command_v, fds_v);
3577 CAMLlocal2 (l_v, tup_v);
3578 int ret, ret1;
3579 pid_t pid;
3580 char *msg = NULL;
3581 value earg_v = Nothing;
3582 posix_spawnattr_t attr;
3583 posix_spawn_file_actions_t fa;
3584 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3586 argv[2] = String_val (command_v);
3588 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3589 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3592 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3593 msg = "posix_spawnattr_init";
3594 goto fail1;
3597 #ifdef POSIX_SPAWN_USEVFORK
3598 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3599 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3600 goto fail;
3602 #endif
3604 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3605 int fd1, fd2;
3607 tup_v = Field (l_v, 0);
3608 fd1 = Int_val (Field (tup_v, 0));
3609 fd2 = Int_val (Field (tup_v, 1));
3610 if (fd2 < 0) {
3611 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3612 msg = "posix_spawn_file_actions_addclose";
3613 earg_v = tup_v;
3614 goto fail;
3617 else {
3618 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3619 msg = "posix_spawn_file_actions_adddup2";
3620 earg_v = tup_v;
3621 goto fail;
3626 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3627 msg = "posix_spawn";
3628 goto fail;
3631 fail:
3632 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3633 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3636 fail1:
3637 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3638 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3639 strerror (ret1));
3642 if (msg)
3643 unix_error (ret, msg, earg_v);
3645 CAMLreturn (Val_int (pid));
3647 #endif
3649 CAMLprim value ml_hassel (value ptr_v)
3651 CAMLparam1 (ptr_v);
3652 CAMLlocal1 (ret_v);
3653 struct page *page;
3654 char *s = String_val (ptr_v);
3656 ret_v = Val_bool (0);
3657 if (trylock (__func__)) {
3658 goto done;
3661 page = parse_pointer (__func__, s);
3662 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3663 unlock (__func__);
3664 done:
3665 CAMLreturn (ret_v);
3668 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3670 CAMLparam2 (fd_v, ptr_v);
3671 FILE *f;
3672 int seen = 0;
3673 struct page *page;
3674 fz_stext_line *line;
3675 fz_page_block *pageb;
3676 fz_stext_block *block;
3677 int fd = Int_val (fd_v);
3678 char *s = String_val (ptr_v);
3680 if (trylock (__func__)) {
3681 goto done;
3684 page = parse_pointer (__func__, s);
3686 if (!page->fmark.span || !page->lmark.span) {
3687 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3688 goto unlock;
3691 f = fdopen (fd, "w");
3692 if (!f) {
3693 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3694 fd, strerror (errno));
3695 f = stdout;
3698 for (pageb = page->text->blocks;
3699 pageb < page->text->blocks + page->text->len;
3700 ++pageb) {
3701 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3702 block = pageb->u.text;
3703 for (line = block->lines;
3704 line < block->lines + block->len;
3705 ++line) {
3706 fz_stext_span *span;
3708 for (span = line->first_span; span; span = span->next) {
3709 int a, b;
3711 seen |= span == page->fmark.span || span == page->lmark.span;
3712 a = span == page->fmark.span ? page->fmark.i : 0;
3713 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3715 if (seen) {
3716 if (pipespan (f, span, a, b)) {
3717 goto close;
3719 if (span == page->lmark.span) {
3720 goto close;
3722 if (span == line->last_span) {
3723 if (putc ('\n', f) == EOF) {
3724 fprintf (stderr,
3725 "failed break line on sel pipe: %s\n",
3726 strerror (errno));
3727 goto close;
3734 close:
3735 if (f != stdout) {
3736 int ret = fclose (f);
3737 fd = -1;
3738 if (ret == -1) {
3739 if (errno != ECHILD) {
3740 fprintf (stderr, "failed to close sel pipe: %s\n",
3741 strerror (errno));
3745 unlock:
3746 unlock (__func__);
3748 done:
3749 if (fd >= 0) {
3750 if (close (fd)) {
3751 fprintf (stderr, "failed to close sel pipe: %s\n",
3752 strerror (errno));
3755 CAMLreturn (Val_unit);
3758 CAMLprim value ml_getpdimrect (value pagedimno_v)
3760 CAMLparam1 (pagedimno_v);
3761 CAMLlocal1 (ret_v);
3762 int pagedimno = Int_val (pagedimno_v);
3763 fz_rect box;
3765 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3766 if (trylock (__func__)) {
3767 box = fz_empty_rect;
3769 else {
3770 box = state.pagedims[pagedimno].mediabox;
3771 unlock (__func__);
3774 Store_double_field (ret_v, 0, box.x0);
3775 Store_double_field (ret_v, 1, box.x1);
3776 Store_double_field (ret_v, 2, box.y0);
3777 Store_double_field (ret_v, 3, box.y1);
3779 CAMLreturn (ret_v);
3782 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3783 value dw_v, value cols_v)
3785 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3786 CAMLlocal1 (ret_v);
3787 int i;
3788 double zoom = -1.;
3789 double maxh = 0.0;
3790 struct pagedim *p;
3791 double winw = Int_val (winw_v);
3792 double winh = Int_val (winh_v);
3793 double dw = Int_val (dw_v);
3794 double cols = Int_val (cols_v);
3795 double pw = 1.0, ph = 1.0;
3797 if (trylock (__func__)) {
3798 goto done;
3801 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3802 double w = p->pagebox.x1 / cols;
3803 double h = p->pagebox.y1;
3804 if (h > maxh) {
3805 maxh = h;
3806 ph = h;
3807 if (state.fitmodel != FitProportional) pw = w;
3809 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3812 zoom = (((winh / ph) * pw) + dw) / winw;
3813 unlock (__func__);
3814 done:
3815 ret_v = caml_copy_double (zoom);
3816 CAMLreturn (ret_v);
3819 CAMLprim value ml_getmaxw (value unit_v)
3821 CAMLparam1 (unit_v);
3822 CAMLlocal1 (ret_v);
3823 int i;
3824 double maxw = -1.;
3825 struct pagedim *p;
3827 if (trylock (__func__)) {
3828 goto done;
3831 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3832 double w = p->pagebox.x1;
3833 maxw = MAX (maxw, w);
3836 unlock (__func__);
3837 done:
3838 ret_v = caml_copy_double (maxw);
3839 CAMLreturn (ret_v);
3842 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3844 CAMLparam4 (pt_v, x_v, y_v, string_v);
3845 CAMLlocal1 (ret_v);
3846 int pt = Int_val(pt_v);
3847 int x = Int_val (x_v);
3848 int y = Int_val (y_v);
3849 double w;
3851 w = draw_string (state.face, pt, x, y, String_val (string_v));
3852 ret_v = caml_copy_double (w);
3853 CAMLreturn (ret_v);
3856 CAMLprim value ml_measure_string (value pt_v, value string_v)
3858 CAMLparam2 (pt_v, string_v);
3859 CAMLlocal1 (ret_v);
3860 int pt = Int_val (pt_v);
3861 double w;
3863 w = measure_string (state.face, pt, String_val (string_v));
3864 ret_v = caml_copy_double (w);
3865 CAMLreturn (ret_v);
3868 CAMLprim value ml_getpagebox (value opaque_v)
3870 CAMLparam1 (opaque_v);
3871 CAMLlocal1 (ret_v);
3872 fz_rect rect;
3873 fz_irect bbox;
3874 fz_matrix ctm;
3875 fz_device *dev;
3876 char *s = String_val (opaque_v);
3877 struct page *page = parse_pointer (__func__, s);
3879 ret_v = caml_alloc_tuple (4);
3880 dev = fz_new_bbox_device (state.ctx, &rect);
3881 dev->hints |= FZ_IGNORE_SHADE;
3883 ctm = pagectm (page);
3884 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3886 fz_drop_device (state.ctx, dev);
3887 fz_round_rect (&bbox, &rect);
3888 Field (ret_v, 0) = Val_int (bbox.x0);
3889 Field (ret_v, 1) = Val_int (bbox.y0);
3890 Field (ret_v, 2) = Val_int (bbox.x1);
3891 Field (ret_v, 3) = Val_int (bbox.y1);
3893 CAMLreturn (ret_v);
3896 CAMLprim value ml_setaalevel (value level_v)
3898 CAMLparam1 (level_v);
3900 state.aalevel = Int_val (level_v);
3901 CAMLreturn (Val_unit);
3904 #pragma GCC diagnostic push
3905 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3906 #include <X11/Xlib.h>
3907 #include <X11/cursorfont.h>
3908 #pragma GCC diagnostic pop
3910 #ifdef USE_EGL
3911 #include <EGL/egl.h>
3912 #else
3913 #include <GL/glx.h>
3914 #endif
3916 static const int shapes[] = {
3917 XC_arrow, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3920 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3922 static struct {
3923 Window wid;
3924 Display *dpy;
3925 #ifdef USE_EGL
3926 EGLContext ctx;
3927 EGLConfig conf;
3928 EGLSurface win;
3929 EGLDisplay *edpy;
3930 #else
3931 GLXContext ctx;
3932 #endif
3933 XVisualInfo *visual;
3934 Cursor curs[CURS_COUNT];
3935 } glx;
3937 #ifdef VISAVIS
3938 static VisualID initvisual (void)
3940 /* On this system with: `Haswell-ULT Integrated Graphics
3941 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3942 using glX chosen visual and auto scrolling some document in
3943 fullscreen the power/energy-gpu is more than 1 joule bigger
3944 than when using hand picked visual that stands alone in glxinfo
3945 output: it's dead last in the list and it's the only one with
3946 `visual dep' (sic) of 32
3948 No clue what's going on here...
3950 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3952 XVisualInfo info;
3953 int ret = 1;
3955 info.depth = 32;
3956 info.class = TrueColor;
3957 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3958 &info, &ret);
3959 if (!ret || !glx.visual) {
3960 XCloseDisplay (glx.dpy);
3961 caml_failwith ("XGetVisualInfo");
3963 return glx.visual->visualid;
3965 #endif
3967 static void initcurs (void)
3969 for (size_t n = 0; n < CURS_COUNT; ++n) {
3970 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3974 CAMLprim void ml_setbgcol (value color_v)
3976 CAMLparam1 (color_v);
3977 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3978 CAMLreturn0;
3981 #ifdef USE_EGL
3982 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3984 CAMLparam3 (display_v, wid_v, screen_v);
3985 int major, minor;
3986 int num_conf;
3987 EGLint visid;
3988 EGLint attribs[] = {
3989 #ifdef VISAVIS
3990 EGL_NATIVE_VISUAL_ID, 0,
3991 #else
3992 EGL_DEPTH_SIZE, 24,
3993 #endif
3994 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3995 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3996 EGL_NONE
3998 EGLConfig conf;
4000 glx.dpy = XOpenDisplay (String_val (display_v));
4001 if (!glx.dpy) {
4002 caml_failwith ("XOpenDisplay");
4005 eglBindAPI (EGL_OPENGL_API);
4007 glx.edpy = eglGetDisplay (glx.dpy);
4008 if (glx.dpy == EGL_NO_DISPLAY) {
4009 caml_failwith ("eglGetDisplay");
4012 if (!eglInitialize (glx.edpy, &major, &minor)) {
4013 caml_failwith ("eglInitialize");
4016 #ifdef VISAVIS
4017 attribs[1] = visid = initvisual ();
4018 #endif
4020 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4021 !num_conf) {
4022 caml_failwith ("eglChooseConfig");
4025 glx.conf = conf;
4026 #ifndef VISAVIS
4027 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4028 EGL_NATIVE_VISUAL_ID, &visid)) {
4029 caml_failwith ("eglGetConfigAttrib");
4031 #endif
4032 initcurs ();
4034 glx.wid = Int_val (wid_v);
4035 CAMLreturn (Val_int (visid));
4038 CAMLprim value ml_glxcompleteinit (value unit_v)
4040 CAMLparam1 (unit_v);
4042 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4043 if (!glx.ctx) {
4044 caml_failwith ("eglCreateContext");
4047 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4048 glx.wid, NULL);
4049 if (glx.win == EGL_NO_SURFACE) {
4050 caml_failwith ("eglCreateWindowSurface");
4053 XFree (glx.visual);
4054 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4055 glx.ctx = NULL;
4056 caml_failwith ("eglMakeCurrent");
4058 CAMLreturn (Val_unit);
4060 #else
4061 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4063 CAMLparam3 (display_v, wid_v, screen_v);
4065 glx.dpy = XOpenDisplay (String_val (display_v));
4066 if (!glx.dpy) {
4067 caml_failwith ("XOpenDisplay");
4070 #ifdef VISAVIS
4071 initvisual ();
4072 #else
4073 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4074 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4075 if (!glx.visual) {
4076 XCloseDisplay (glx.dpy);
4077 caml_failwith ("glXChooseVisual");
4079 #endif
4080 initcurs ();
4082 glx.wid = Int_val (wid_v);
4083 CAMLreturn (Val_int (glx.visual->visualid));
4086 CAMLprim value ml_glxcompleteinit (value unit_v)
4088 CAMLparam1 (unit_v);
4090 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4091 if (!glx.ctx) {
4092 caml_failwith ("glXCreateContext");
4095 XFree (glx.visual);
4096 glx.visual = NULL;
4098 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4099 glXDestroyContext (glx.dpy, glx.ctx);
4100 glx.ctx = NULL;
4101 caml_failwith ("glXMakeCurrent");
4103 CAMLreturn (Val_unit);
4105 #endif
4107 CAMLprim value ml_setcursor (value cursor_v)
4109 CAMLparam1 (cursor_v);
4110 size_t cursn = Int_val (cursor_v);
4111 XSetWindowAttributes wa;
4113 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4114 wa.cursor = glx.curs[cursn];
4115 XChangeWindowAttributes (glx.dpy, glx.wid, CWCursor, &wa);
4116 XFlush (glx.dpy);
4117 CAMLreturn (Val_unit);
4120 CAMLprim value ml_swapb (value unit_v)
4122 CAMLparam1 (unit_v);
4123 #ifdef USE_EGL
4124 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4125 caml_failwith ("eglSwapBuffers");
4127 #else
4128 glXSwapBuffers (glx.dpy, glx.wid);
4129 #endif
4130 CAMLreturn (Val_unit);
4133 #include "keysym2ucs.c"
4135 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4137 CAMLparam1 (keysym_v);
4138 CAMLlocal1 (str_v);
4139 KeySym keysym = Int_val (keysym_v);
4140 Rune rune;
4141 int len;
4142 char buf[5];
4144 rune = keysym2ucs (keysym);
4145 len = fz_runetochar (buf, rune);
4146 buf[len] = 0;
4147 str_v = caml_copy_string (buf);
4148 CAMLreturn (str_v);
4151 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4153 CAMLprim value ml_platform (value unit_v)
4155 CAMLparam1 (unit_v);
4156 CAMLlocal2 (tup_v, arr_v);
4157 int platid = piunknown;
4158 struct utsname buf;
4160 #if defined __linux__
4161 platid = pilinux;
4162 #elif defined __CYGWIN__
4163 platid = picygwin;
4164 #elif defined __DragonFly__ || defined __FreeBSD__
4165 || defined __OpenBSD__ || defined __NetBSD__
4166 platid = pibsd;
4167 #elif defined __sun__
4168 platid = pisun;
4169 #elif defined __APPLE__
4170 platid = piosx;
4171 #endif
4172 if (uname (&buf)) err (1, "uname");
4174 tup_v = caml_alloc_tuple (2);
4176 char const *sar[] = {
4177 buf.sysname,
4178 buf.release,
4179 buf.version,
4180 buf.machine,
4181 NULL
4183 arr_v = caml_copy_string_array (sar);
4185 Field (tup_v, 0) = Val_int (platid);
4186 Field (tup_v, 1) = arr_v;
4187 CAMLreturn (tup_v);
4190 CAMLprim value ml_cloexec (value fd_v)
4192 CAMLparam1 (fd_v);
4193 int fd = Int_val (fd_v);
4195 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4196 uerror ("fcntl", Nothing);
4198 CAMLreturn (Val_unit);
4201 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4203 CAMLparam2 (w_v, h_v);
4204 CAMLlocal1 (ret_v);
4205 struct pbo *pbo;
4206 int w = Int_val (w_v);
4207 int h = Int_val (h_v);
4208 int cs = Int_val (cs_v);
4210 if (state.pbo_usable) {
4211 pbo = calloc (sizeof (*pbo), 1);
4212 if (!pbo) {
4213 err (1, "calloc pbo");
4216 switch (cs) {
4217 case 0:
4218 case 1:
4219 pbo->size = w*h*4;
4220 break;
4221 case 2:
4222 pbo->size = w*h*2;
4223 break;
4224 default:
4225 errx (1, "%s: invalid colorspace %d", __func__, cs);
4228 state.glGenBuffersARB (1, &pbo->id);
4229 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4230 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4231 NULL, GL_STREAM_DRAW);
4232 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4233 GL_READ_WRITE);
4234 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4235 if (!pbo->ptr) {
4236 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4237 state.glDeleteBuffersARB (1, &pbo->id);
4238 free (pbo);
4239 ret_v = caml_copy_string ("0");
4241 else {
4242 int res;
4243 char *s;
4245 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4246 if (res < 0) {
4247 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4249 s = malloc (res+1);
4250 if (!s) {
4251 err (1, "malloc %d bytes failed", res+1);
4253 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4254 if (res < 0) {
4255 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4257 ret_v = caml_copy_string (s);
4258 free (s);
4261 else {
4262 ret_v = caml_copy_string ("0");
4264 CAMLreturn (ret_v);
4267 CAMLprim value ml_freepbo (value s_v)
4269 CAMLparam1 (s_v);
4270 char *s = String_val (s_v);
4271 struct tile *tile = parse_pointer (__func__, s);
4273 if (tile->pbo) {
4274 state.glDeleteBuffersARB (1, &tile->pbo->id);
4275 tile->pbo->id = -1;
4276 tile->pbo->ptr = NULL;
4277 tile->pbo->size = -1;
4279 CAMLreturn (Val_unit);
4282 CAMLprim value ml_unmappbo (value s_v)
4284 CAMLparam1 (s_v);
4285 char *s = String_val (s_v);
4286 struct tile *tile = parse_pointer (__func__, s);
4288 if (tile->pbo) {
4289 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4290 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4291 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4293 tile->pbo->ptr = NULL;
4294 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4296 CAMLreturn (Val_unit);
4299 static void setuppbo (void)
4301 #ifdef USE_EGL
4302 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4303 #else
4304 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4305 #endif
4306 state.pbo_usable = GGPA (glBindBufferARB)
4307 && GGPA (glUnmapBufferARB)
4308 && GGPA (glMapBufferARB)
4309 && GGPA (glBufferDataARB)
4310 && GGPA (glGenBuffersARB)
4311 && GGPA (glDeleteBuffersARB);
4312 #undef GGPA
4315 CAMLprim value ml_pbo_usable (value unit_v)
4317 CAMLparam1 (unit_v);
4318 CAMLreturn (Val_bool (state.pbo_usable));
4321 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4323 CAMLparam3 (ptr_v, x_v, y_v);
4324 CAMLlocal2 (ret_v, tup_v);
4325 struct page *page;
4326 char *s = String_val (ptr_v);
4327 int x = Int_val (x_v), y = Int_val (y_v);
4328 struct pagedim *pdim;
4329 fz_point p;
4330 fz_matrix ctm;
4332 page = parse_pointer (__func__, s);
4333 pdim = &state.pagedims[page->pdimno];
4335 ret_v = Val_int (0);
4336 if (trylock (__func__)) {
4337 goto done;
4340 if (pdf_specifics (state.ctx, state.doc)) {
4341 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4342 ctm = state.pagedims[page->pdimno].tctm;
4344 else {
4345 ctm = fz_identity;
4347 p.x = x + pdim->bounds.x0;
4348 p.y = y + pdim->bounds.y0;
4350 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4351 fz_invert_matrix (&ctm, &ctm);
4352 fz_transform_point (&p, &ctm);
4354 tup_v = caml_alloc_tuple (2);
4355 ret_v = caml_alloc_small (1, 1);
4356 Field (tup_v, 0) = Val_int (p.x);
4357 Field (tup_v, 1) = Val_int (p.y);
4358 Field (ret_v, 0) = tup_v;
4360 unlock (__func__);
4361 done:
4362 CAMLreturn (ret_v);
4365 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4366 value x_v, value y_v)
4368 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4369 CAMLlocal1 (ret_v);
4370 struct page *page;
4371 char *s = String_val (ptr_v);
4372 int pageno = Int_val (pageno_v);
4373 int pdimno = Int_val (pdimno_v);
4374 double x = Double_val (x_v), y = Double_val (y_v);
4375 struct pagedim *pdim;
4376 fz_point p;
4377 fz_matrix ctm;
4379 ret_v = Val_int (0);
4380 lock (__func__);
4382 if (!*s) {
4383 page = loadpage (pageno, pdimno);
4385 else {
4386 page = parse_pointer (__func__, s);
4388 pdim = &state.pagedims[pdimno];
4390 if (pdf_specifics (state.ctx, state.doc)) {
4391 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4392 ctm = state.pagedims[page->pdimno].tctm;
4394 else {
4395 ctm = fz_identity;
4397 p.x = x + pdim->bounds.x0;
4398 p.y = y + pdim->bounds.y0;
4400 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4401 fz_transform_point (&p, &ctm);
4403 ret_v = caml_alloc_tuple (2);
4404 Field (ret_v, 0) = caml_copy_double (p.x);
4405 Field (ret_v, 1) = caml_copy_double (p.y);
4407 if (!*s) {
4408 freepage (page);
4410 unlock (__func__);
4411 CAMLreturn (ret_v);
4414 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4415 value contents_v)
4417 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4418 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4420 if (pdf) {
4421 pdf_annot *annot;
4422 struct page *page;
4423 fz_point p;
4424 char *s = String_val (ptr_v);
4426 page = parse_pointer (__func__, s);
4427 annot = pdf_create_annot (state.ctx, pdf,
4428 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4429 p.x = Int_val (x_v);
4430 p.y = Int_val (y_v);
4431 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4432 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4433 state.dirty = 1;
4435 CAMLreturn (Val_unit);
4438 CAMLprim value ml_delannot (value ptr_v, value n_v)
4440 CAMLparam2 (ptr_v, n_v);
4441 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4443 if (pdf) {
4444 struct page *page;
4445 char *s = String_val (ptr_v);
4446 struct slink *slink;
4448 page = parse_pointer (__func__, s);
4449 slink = &page->slinks[Int_val (n_v)];
4450 pdf_delete_annot (state.ctx, pdf,
4451 (pdf_page *) page->fzpage,
4452 (pdf_annot *) slink->u.annot);
4453 state.dirty = 1;
4455 CAMLreturn (Val_unit);
4458 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4460 CAMLparam3 (ptr_v, n_v, str_v);
4461 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4463 if (pdf) {
4464 struct page *page;
4465 char *s = String_val (ptr_v);
4466 struct slink *slink;
4468 page = parse_pointer (__func__, s);
4469 slink = &page->slinks[Int_val (n_v)];
4470 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4471 String_val (str_v));
4472 state.dirty = 1;
4474 CAMLreturn (Val_unit);
4477 CAMLprim value ml_hasunsavedchanges (value unit_v)
4479 CAMLparam1 (unit_v);
4480 CAMLreturn (Val_bool (state.dirty));
4483 CAMLprim value ml_savedoc (value path_v)
4485 CAMLparam1 (path_v);
4486 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4488 if (pdf) {
4489 pdf_write_document (state.ctx, pdf, String_val (path_v), NULL);
4491 CAMLreturn (Val_unit);
4494 static void makestippletex (void)
4496 const char pixels[] = "\xff\xff\0\0";
4497 glGenTextures (1, &state.stid);
4498 glBindTexture (GL_TEXTURE_1D, state.stid);
4499 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4500 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4501 glTexImage1D (
4502 GL_TEXTURE_1D,
4504 GL_ALPHA,
4507 GL_ALPHA,
4508 GL_UNSIGNED_BYTE,
4509 pixels
4513 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4515 return caml_copy_string (FZ_VERSION);
4518 #ifdef USE_FONTCONFIG
4519 static struct {
4520 int inited;
4521 FcConfig *config;
4522 } fc;
4524 static fz_font *fc_load_system_font_func (fz_context *ctx,
4525 const char *name,
4526 int bold,
4527 int italic,
4528 int UNUSED_ATTR needs_exact_metrics)
4530 char *buf;
4531 size_t i, size;
4532 fz_font *font;
4533 FcChar8 *path;
4534 FcResult result;
4535 FcPattern *pat, *pat1;
4537 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4538 name, bold, italic, needs_exact_metrics);
4539 if (!fc.inited) {
4540 fc.inited = 1;
4541 fc.config = FcInitLoadConfigAndFonts ();
4542 if (!fc.config) {
4543 lprintf ("FcInitLoadConfigAndFonts failed\n");
4544 return NULL;
4547 if (!fc.config) return NULL;
4549 size = strlen (name);
4550 if (bold) size += sizeof (":bold") - 1;
4551 if (italic) size += sizeof (":italic") - 1;
4552 size += 1;
4554 buf = malloc (size);
4555 if (!buf) {
4556 err (1, "malloc %zu failed", size);
4559 strcpy (buf, name);
4560 if (bold && italic) {
4561 strcat (buf, ":bold:italic");
4563 else {
4564 if (bold) strcat (buf, ":bold");
4565 if (italic) strcat (buf, ":italic");
4567 for (i = 0; i < size; ++i) {
4568 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4571 lprintf ("fcbuf=%s\n", buf);
4572 pat = FcNameParse ((FcChar8 *) buf);
4573 if (!pat) {
4574 printd ("emsg FcNameParse failed\n");
4575 free (buf);
4576 return NULL;
4579 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4580 printd ("emsg FcConfigSubstitute failed\n");
4581 free (buf);
4582 return NULL;
4584 FcDefaultSubstitute (pat);
4586 pat1 = FcFontMatch (fc.config, pat, &result);
4587 if (!pat1) {
4588 printd ("emsg FcFontMatch failed\n");
4589 FcPatternDestroy (pat);
4590 free (buf);
4591 return NULL;
4594 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4595 printd ("emsg FcPatternGetString failed\n");
4596 FcPatternDestroy (pat);
4597 FcPatternDestroy (pat1);
4598 free (buf);
4599 return NULL;
4602 #if 0
4603 printd ("emsg name=%s path=%s\n", name, path);
4604 #endif
4605 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4606 FcPatternDestroy (pat);
4607 FcPatternDestroy (pat1);
4608 free (buf);
4609 return font;
4611 #endif
4613 CAMLprim value ml_init (value csock_v, value params_v)
4615 CAMLparam2 (csock_v, params_v);
4616 CAMLlocal2 (trim_v, fuzz_v);
4617 int ret;
4618 int texcount;
4619 char *fontpath;
4620 int colorspace;
4621 int mustoresize;
4622 int haspboext;
4624 state.csock = Int_val (csock_v);
4625 state.rotate = Int_val (Field (params_v, 0));
4626 state.fitmodel = Int_val (Field (params_v, 1));
4627 trim_v = Field (params_v, 2);
4628 texcount = Int_val (Field (params_v, 3));
4629 state.sliceheight = Int_val (Field (params_v, 4));
4630 mustoresize = Int_val (Field (params_v, 5));
4631 colorspace = Int_val (Field (params_v, 6));
4632 fontpath = String_val (Field (params_v, 7));
4634 if (caml_string_length (Field (params_v, 8)) > 0) {
4635 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4637 if (!state.trimcachepath) {
4638 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4639 strerror (errno));
4642 haspboext = Bool_val (Field (params_v, 9));
4644 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4645 fz_register_document_handlers (state.ctx);
4647 #ifdef USE_FONTCONFIG
4648 if (Bool_val (Field (params_v, 10))) {
4649 fz_install_load_system_font_funcs (
4650 state.ctx, fc_load_system_font_func, NULL
4653 #endif
4655 state.trimmargins = Bool_val (Field (trim_v, 0));
4656 fuzz_v = Field (trim_v, 1);
4657 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4658 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4659 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4660 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4662 set_tex_params (colorspace);
4664 if (*fontpath) {
4665 #ifndef USE_FONTCONFIG
4666 state.face = load_font (fontpath);
4667 #else
4668 FcChar8 *path;
4669 FcResult result;
4670 char *buf = fontpath;
4671 FcPattern *pat, *pat1;
4673 fc.inited = 1;
4674 fc.config = FcInitLoadConfigAndFonts ();
4675 if (!fc.config) {
4676 errx (1, "FcInitLoadConfigAndFonts failed");
4679 pat = FcNameParse ((FcChar8 *) buf);
4680 if (!pat) {
4681 errx (1, "FcNameParse failed");
4684 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4685 errx (1, "FcConfigSubstitute failed");
4687 FcDefaultSubstitute (pat);
4689 pat1 = FcFontMatch (fc.config, pat, &result);
4690 if (!pat1) {
4691 errx (1, "FcFontMatch failed");
4694 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4695 errx (1, "FcPatternGetString failed");
4698 state.face = load_font ((char *) path);
4699 FcPatternDestroy (pat);
4700 FcPatternDestroy (pat1);
4701 #endif
4703 else {
4704 unsigned int len;
4705 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4707 state.face = load_builtin_font (base, len);
4709 if (!state.face) _exit (1);
4711 realloctexts (texcount);
4713 if (haspboext) {
4714 setuppbo ();
4717 makestippletex ();
4719 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4720 if (ret) {
4721 errx (1, "pthread_create: %s", strerror (ret));
4724 CAMLreturn (Val_unit);