Remove diagnostic pragmas around fitz/mupdf headers
[llpp.git] / link.c
blob5f9ab0b5e45839a81322c9ebbc9ea8803ef06c4e
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 #include <mupdf/fitz.h>
44 #include <mupdf/pdf.h>
46 #include <ft2build.h>
47 #include FT_FREETYPE_H
49 #ifdef USE_FONTCONFIG
50 #include <fontconfig/fontconfig.h>
51 #endif
53 #define PIGGYBACK
54 #define CACHE_PAGEREFS
56 #ifndef __USE_GNU
57 extern char **environ;
58 #endif
60 #if defined __GNUC__
61 #define NORETURN_ATTR __attribute__ ((noreturn))
62 #define UNUSED_ATTR __attribute__ ((unused))
63 #if !defined __clang__
64 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
65 #else
66 #define OPTIMIZE_ATTR(n)
67 #endif
68 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
69 #else
70 #define NORETURN_ATTR
71 #define UNUSED_ATTR
72 #define OPTIMIZE_ATTR(n)
73 #define GCC_FMT_ATTR(a, b)
74 #endif
76 #define FMT_s "zu"
78 #define FMT_ptr PRIxPTR
79 #define SCN_ptr SCNxPTR
80 #define FMT_ptr_cast(p) ((uintptr_t) (p))
81 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
83 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
84 err (int exitcode, const char *fmt, ...)
86 va_list ap;
87 int savederrno;
89 savederrno = errno;
90 va_start (ap, fmt);
91 vfprintf (stderr, fmt, ap);
92 va_end (ap);
93 fprintf (stderr, ": %s\n", strerror (savederrno));
94 fflush (stderr);
95 _exit (exitcode);
98 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
99 errx (int exitcode, const char *fmt, ...)
101 va_list ap;
103 va_start (ap, fmt);
104 vfprintf (stderr, fmt, ap);
105 va_end (ap);
106 fputc ('\n', stderr);
107 fflush (stderr);
108 _exit (exitcode);
111 #ifndef GL_TEXTURE_RECTANGLE_ARB
112 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
113 #endif
115 #ifdef USE_NPOT
116 #define TEXT_TYPE GL_TEXTURE_2D
117 #else
118 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
119 #endif
121 #ifndef GL_BGRA
122 #define GL_BGRA 0x80E1
123 #endif
125 #ifndef GL_UNSIGNED_INT_8_8_8_8
126 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
127 #endif
129 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
130 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
131 #endif
133 #if 0
134 #define lprintf printf
135 #else
136 #define lprintf(...)
137 #endif
139 #define ARSERT(cond) for (;;) { \
140 if (!(cond)) { \
141 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
143 break; \
146 struct slice {
147 int h;
148 int texindex;
151 struct tile {
152 int w, h;
153 int slicecount;
154 int sliceheight;
155 struct bo *pbo;
156 fz_pixmap *pixmap;
157 struct slice slices[1];
160 struct pagedim {
161 int pageno;
162 int rotate;
163 int left;
164 int tctmready;
165 fz_irect bounds;
166 fz_rect pagebox;
167 fz_rect mediabox;
168 fz_matrix ctm, zoomctm, lctm, tctm;
171 struct slink {
172 enum { SLINK, SANNOT } tag;
173 fz_irect bbox;
174 union {
175 fz_link *link;
176 fz_annot *annot;
177 } u;
180 struct annot {
181 fz_irect bbox;
182 fz_annot *annot;
185 struct page {
186 int tgen;
187 int sgen;
188 int agen;
189 int pageno;
190 int pdimno;
191 fz_stext_page *text;
192 fz_stext_sheet *sheet;
193 fz_page *fzpage;
194 fz_display_list *dlist;
195 int slinkcount;
196 struct slink *slinks;
197 int annotcount;
198 struct annot *annots;
199 struct mark {
200 int i;
201 fz_stext_span *span;
202 } fmark, lmark;
205 struct {
206 int sliceheight;
207 struct pagedim *pagedims;
208 int pagecount;
209 int pagedimcount;
210 fz_document *doc;
211 fz_context *ctx;
212 int w, h;
214 int texindex;
215 int texcount;
216 GLuint *texids;
218 GLenum texiform;
219 GLenum texform;
220 GLenum texty;
222 fz_colorspace *colorspace;
224 struct {
225 int w, h;
226 struct slice *slice;
227 } *texowners;
229 int rotate;
230 enum { FitWidth, FitProportional, FitPage } fitmodel;
231 int trimmargins;
232 int needoutline;
233 int gen;
234 int aalevel;
236 int trimanew;
237 fz_irect trimfuzz;
238 fz_pixmap *pig;
240 pthread_t thread;
241 int csock;
242 FT_Face face;
244 char *trimcachepath;
245 int cxack;
246 int dirty;
248 GLuint stid;
250 int bo_usable;
251 GLuint boid;
253 void (*glBindBufferARB) (GLenum, GLuint);
254 GLboolean (*glUnmapBufferARB) (GLenum);
255 void *(*glMapBufferARB) (GLenum, GLenum);
256 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
257 void (*glGenBuffersARB) (GLsizei, GLuint *);
258 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
260 GLfloat texcoords[8];
261 GLfloat vertices[16];
263 #ifdef CACHE_PAGEREFS
264 struct {
265 int idx;
266 int count;
267 pdf_obj **objs;
268 pdf_document *pdf;
269 } pdflut;
270 #endif
271 } state;
273 struct bo {
274 GLuint id;
275 void *ptr;
276 size_t size;
279 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
281 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
284 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
286 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
289 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
291 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
292 m.a, m.b, m.c, m.d, m.e, m.f);
295 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
297 static void lock (const char *cap)
299 int ret = pthread_mutex_lock (&mutex);
300 if (ret) {
301 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
305 static void unlock (const char *cap)
307 int ret = pthread_mutex_unlock (&mutex);
308 if (ret) {
309 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
313 static int trylock (const char *cap)
315 int ret = pthread_mutex_trylock (&mutex);
316 if (ret && ret != EBUSY) {
317 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
319 return ret == EBUSY;
322 static void *parse_pointer (const char *cap, const char *s)
324 int ret;
325 void *ptr;
327 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
328 if (ret != 1) {
329 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
331 return ptr;
334 static double now (void)
336 struct timeval tv;
338 if (gettimeofday (&tv, NULL)) {
339 err (1, "gettimeofday");
341 return tv.tv_sec + tv.tv_usec*1e-6;
344 static int hasdata (void)
346 int ret, avail;
347 ret = ioctl (state.csock, FIONREAD, &avail);
348 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
349 return avail > 0;
352 CAMLprim value ml_hasdata (value fd_v)
354 CAMLparam1 (fd_v);
355 int ret, avail;
357 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
358 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
359 CAMLreturn (Val_bool (avail > 0));
362 static void readdata (int fd, void *p, int size)
364 ssize_t n;
366 again:
367 n = read (fd, p, size);
368 if (n < 0) {
369 if (errno == EINTR) goto again;
370 err (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
372 if (n - size) {
373 if (!n) errx (1, "EOF while reading");
374 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
378 static void writedata (int fd, char *p, int size)
380 ssize_t n;
382 /* One should lookup type punning/strict aliasing etc in standard,DRs,Web to
383 convince herself that this is:
384 a. safe
385 b. practically the only way to achieve the result
386 (union puns notwithstanding) */
387 memcpy (p, &size, 4);
388 n = write (fd, p, size + 4);
389 if (n - size - 4) {
390 if (!n) errx (1, "EOF while writing data");
391 err (1, "write (fd %d, req %d, ret %zd)", fd, size + 4, n);
395 static int readlen (int fd)
397 /* Type punned unions here. Why? Less code (Adjusted by more comments).
398 https://en.wikipedia.org/wiki/Type_punning */
399 union { int len; char raw[4]; } buf;
400 readdata (fd, buf.raw, 4);
401 return buf.len;
404 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
406 CAMLparam3 (fd_v, bytes_v, len_v);
407 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
408 CAMLreturn0;
411 CAMLprim value ml_rcmd (value fd_v)
413 CAMLparam1 (fd_v);
414 CAMLlocal1 (strdata_v);
415 int fd = Int_val (fd_v);
416 int len = readlen (fd);
417 strdata_v = caml_alloc_string (len);
418 readdata (fd, String_val (strdata_v), len);
419 CAMLreturn (strdata_v);
422 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
424 int size = 200, len;
425 va_list ap;
426 char *buf;
428 buf = malloc (size);
429 for (;;) {
430 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
432 va_start (ap, fmt);
433 len = vsnprintf (buf + 4, size - 4, fmt, ap);
434 va_end (ap);
436 if (len > -1) {
437 if (len < size - 4) {
438 writedata (state.csock, buf, len);
439 break;
441 else size = len + 5;
443 else {
444 err (1, "vsnprintf for `%s' failed", fmt);
446 buf = realloc (buf, size);
448 free (buf);
451 static void closedoc (void)
453 #ifdef CACHE_PAGEREFS
454 if (state.pdflut.objs) {
455 int i;
457 for (i = 0; i < state.pdflut.count; ++i) {
458 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
460 free (state.pdflut.objs);
461 state.pdflut.objs = NULL;
462 state.pdflut.idx = 0;
464 #endif
465 if (state.doc) {
466 fz_drop_document (state.ctx, state.doc);
467 state.doc = NULL;
471 static int openxref (char *filename, char *password)
473 int i;
475 for (i = 0; i < state.texcount; ++i) {
476 state.texowners[i].w = -1;
477 state.texowners[i].slice = NULL;
480 closedoc ();
482 state.dirty = 0;
483 if (state.pagedims) {
484 free (state.pagedims);
485 state.pagedims = NULL;
487 state.pagedimcount = 0;
489 fz_set_aa_level (state.ctx, state.aalevel);
490 #ifdef CSS_HACK_TO_READ_EPUBS_COMFORTABLY
491 fz_set_user_css (state.ctx,
492 "body { margin-left: 20%; margin-right: 20%; }");
493 #endif
494 state.doc = fz_open_document (state.ctx, filename);
495 if (fz_needs_password (state.ctx, state.doc)) {
496 if (password && !*password) {
497 printd ("pass");
498 return 0;
500 else {
501 int ok = fz_authenticate_password (state.ctx, state.doc, password);
502 if (!ok) {
503 printd ("pass fail");
504 return 0;
508 state.pagecount = fz_count_pages (state.ctx, state.doc);
509 return 1;
512 static void pdfinfo (void)
514 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
515 if (pdf) {
516 pdf_obj *infoobj;
518 printd ("info PDF version\t%d.%d",
519 pdf->version / 10, pdf->version % 10);
521 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
522 pdf), "Info");
523 if (infoobj) {
524 unsigned int i;
525 char *s;
526 char *items[] = { "Title", "Author", "Creator",
527 "Producer", "CreationDate" };
529 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
530 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
531 s = pdf_to_utf8 (state.ctx, pdf, obj);
532 if (*s) printd ("info %s\t%s", items[i], s);
533 fz_free (state.ctx, s);
536 printd ("infoend");
540 static void unlinktile (struct tile *tile)
542 int i;
544 for (i = 0; i < tile->slicecount; ++i) {
545 struct slice *s = &tile->slices[i];
547 if (s->texindex != -1) {
548 if (state.texowners[s->texindex].slice == s) {
549 state.texowners[s->texindex].slice = NULL;
555 static void freepage (struct page *page)
557 if (!page) return;
558 if (page->text) {
559 fz_drop_stext_page (state.ctx, page->text);
561 if (page->sheet) {
562 fz_drop_stext_sheet (state.ctx, page->sheet);
564 if (page->slinks) {
565 free (page->slinks);
567 fz_drop_display_list (state.ctx, page->dlist);
568 fz_drop_page (state.ctx, page->fzpage);
569 free (page);
572 static void freetile (struct tile *tile)
574 unlinktile (tile);
575 if (!tile->pbo) {
576 #ifndef PIGGYBACK
577 fz_drop_pixmap (state.ctx, tile->pixmap);
578 #else
579 if (state.pig) {
580 fz_drop_pixmap (state.ctx, state.pig);
582 state.pig = tile->pixmap;
583 #endif
585 else {
586 free (tile->pbo);
587 fz_drop_pixmap (state.ctx, tile->pixmap);
589 free (tile);
592 #ifdef __ALTIVEC__
593 #include <stdint.h>
594 #include <altivec.h>
596 static int cacheline32bytes;
598 static void __attribute__ ((constructor)) clcheck (void)
600 char **envp = environ;
601 unsigned long *auxv;
603 while (*envp++);
605 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
606 if (*auxv == 19) {
607 cacheline32bytes = auxv[1] == 32;
608 return;
613 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
615 size_t size = pixmap->w * pixmap->h * pixmap->n;
616 if (cacheline32bytes && size > 32) {
617 intptr_t a1, a2, diff;
618 size_t sizea, i;
619 vector unsigned char v = vec_splat_u8 (-1);
620 vector unsigned char *p;
622 a1 = a2 = (intptr_t) pixmap->samples;
623 a2 = (a1 + 31) & ~31;
624 diff = a2 - a1;
625 sizea = size - diff;
626 p = (void *) a2;
628 while (a1 != a2) *(char *) a1++ = 0xff;
629 for (i = 0; i < (sizea & ~31); i += 32) {
630 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
631 vec_st (v, i, p);
632 vec_st (v, i + 16, p);
634 while (i < sizea) *((char *) a1 + i++) = 0xff;
636 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
638 #else
639 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
640 #endif
642 static void trimctm (pdf_page *page, int pindex)
644 fz_matrix ctm;
645 struct pagedim *pdim = &state.pagedims[pindex];
647 if (!pdim->tctmready) {
648 if (state.trimmargins) {
649 fz_rect realbox;
650 fz_matrix rm, sm, tm, im, ctm1;
652 fz_rotate (&rm, -pdim->rotate);
653 fz_scale (&sm, 1, -1);
654 fz_concat (&ctm, &rm, &sm);
655 realbox = pdim->mediabox;
656 fz_transform_rect (&realbox, &ctm);
657 fz_translate (&tm, -realbox.x0, -realbox.y0);
658 fz_concat (&ctm1, &ctm, &tm);
659 fz_invert_matrix (&im, &page->ctm);
660 fz_concat (&ctm, &im, &ctm1);
662 else {
663 ctm = fz_identity;
665 pdim->tctm = ctm;
666 pdim->tctmready = 1;
670 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
672 fz_matrix ctm, tm;
673 int pdimno = pdim - state.pagedims;
675 if (pdf_specifics (state.ctx, state.doc)) {
676 trimctm ((pdf_page *) fzpage, pdimno);
677 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
679 else {
680 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
681 fz_concat (&ctm, &tm, &pdim->ctm);
683 return ctm;
686 static fz_matrix pagectm (struct page *page)
688 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
691 static void *loadpage (int pageno, int pindex)
693 fz_device *dev;
694 struct page *page;
696 page = calloc (sizeof (struct page), 1);
697 if (!page) {
698 err (1, "calloc page %d", pageno);
701 page->dlist = fz_new_display_list (state.ctx, NULL);
702 dev = fz_new_list_device (state.ctx, page->dlist);
703 fz_try (state.ctx) {
704 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
705 fz_run_page (state.ctx, page->fzpage, dev,
706 &fz_identity, NULL);
708 fz_catch (state.ctx) {
709 page->fzpage = NULL;
711 fz_drop_device (state.ctx, dev);
713 page->pdimno = pindex;
714 page->pageno = pageno;
715 page->sgen = state.gen;
716 page->agen = state.gen;
717 page->tgen = state.gen;
718 return page;
721 static struct tile *alloctile (int h)
723 int i;
724 int slicecount;
725 size_t tilesize;
726 struct tile *tile;
728 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
729 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
730 tile = calloc (tilesize, 1);
731 if (!tile) {
732 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
734 for (i = 0; i < slicecount; ++i) {
735 int sh = fz_mini (h, state.sliceheight);
736 tile->slices[i].h = sh;
737 tile->slices[i].texindex = -1;
738 h -= sh;
740 tile->slicecount = slicecount;
741 tile->sliceheight = state.sliceheight;
742 return tile;
745 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
746 struct bo *pbo)
748 fz_rect rect;
749 fz_irect bbox;
750 fz_matrix ctm;
751 fz_device *dev;
752 struct tile *tile;
753 struct pagedim *pdim;
755 tile = alloctile (h);
756 pdim = &state.pagedims[page->pdimno];
758 bbox = pdim->bounds;
759 bbox.x0 += x;
760 bbox.y0 += y;
761 bbox.x1 = bbox.x0 + w;
762 bbox.y1 = bbox.y0 + h;
764 if (state.pig) {
765 if (state.pig->w == w
766 && state.pig->h == h
767 && state.pig->colorspace == state.colorspace) {
768 tile->pixmap = state.pig;
769 tile->pixmap->x = bbox.x0;
770 tile->pixmap->y = bbox.y0;
772 else {
773 fz_drop_pixmap (state.ctx, state.pig);
775 state.pig = NULL;
777 if (!tile->pixmap) {
778 if (pbo) {
779 tile->pixmap =
780 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
781 &bbox, 1, pbo->ptr);
782 tile->pbo = pbo;
784 else {
785 tile->pixmap =
786 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
790 tile->w = w;
791 tile->h = h;
792 clearpixmap (tile->pixmap);
794 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
795 ctm = pagectm (page);
796 fz_rect_from_irect (&rect, &bbox);
797 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
798 fz_drop_device (state.ctx, dev);
800 return tile;
803 #ifdef CACHE_PAGEREFS
804 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
805 thanks to Robin Watts */
806 static void
807 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
809 fz_context *ctx = state.ctx; /* doc->ctx; */
810 pdf_obj *kids;
811 int i, len;
813 if (state.pdflut.idx == state.pagecount) return;
815 kids = pdf_dict_gets (ctx, node, "Kids");
816 len = pdf_array_len (ctx, kids);
818 if (len == 0)
819 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
821 if (pdf_mark_obj (ctx, node))
822 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
823 for (i = 0; i < len; i++) {
824 pdf_obj *kid = pdf_array_get (ctx, kids, i);
825 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
826 if (*type
827 ? !strcmp (type, "Pages")
828 : pdf_dict_gets (ctx, kid, "Kids")
829 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
830 pdf_collect_pages (doc, kid);
832 else {
833 if (*type
834 ? strcmp (type, "Page") != 0
835 : !pdf_dict_gets (ctx, kid, "MediaBox"))
836 fz_warn (ctx, "non-page object in page tree (%s)", type);
837 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
840 pdf_unmark_obj (ctx, node);
843 static void
844 pdf_load_page_objs (pdf_document *doc)
846 pdf_obj *root = pdf_dict_gets (state.ctx,
847 pdf_trailer (state.ctx, doc), "Root");
848 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
850 if (!node)
851 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
853 state.pdflut.idx = 0;
854 pdf_collect_pages (doc, node);
856 #endif
858 static void initpdims (int wthack)
860 double start, end;
861 FILE *trimf = NULL;
862 fz_rect rootmediabox;
863 int pageno, trim, show;
864 int trimw = 0, cxcount;
865 fz_context *ctx = state.ctx;
866 pdf_document *pdf = pdf_specifics (ctx, state.doc);
868 fz_var (trimw);
869 fz_var (trimf);
870 fz_var (cxcount);
871 start = now ();
873 if (state.trimmargins && state.trimcachepath) {
874 trimf = fopen (state.trimcachepath, "rb");
875 if (!trimf) {
876 trimf = fopen (state.trimcachepath, "wb");
877 trimw = 1;
881 if (state.trimmargins || pdf || !state.cxack)
882 cxcount = state.pagecount;
883 else
884 cxcount = fz_mini (state.pagecount, 1);
886 if (pdf) {
887 pdf_obj *obj;
888 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
889 "Root/Pages/MediaBox");
890 pdf_to_rect (ctx, obj, &rootmediabox);
893 #ifdef CACHE_PAGEREFS
894 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
895 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
896 if (!state.pdflut.objs) {
897 err (1, "malloc pageobjs %zu %d %zu failed",
898 sizeof (*state.pdflut.objs), cxcount,
899 sizeof (*state.pdflut.objs) * cxcount);
901 state.pdflut.count = cxcount;
902 pdf_load_page_objs (pdf);
903 state.pdflut.pdf = pdf;
905 #endif
907 for (pageno = 0; pageno < cxcount; ++pageno) {
908 int rotate = 0;
909 struct pagedim *p;
910 fz_rect mediabox;
912 fz_var (rotate);
913 if (pdf) {
914 pdf_obj *pageref, *pageobj;
916 #ifdef CACHE_PAGEREFS
917 pageref = state.pdflut.objs[pageno];
918 #else
919 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
920 #endif
921 pageobj = pdf_resolve_indirect (ctx, pageref);
923 if (state.trimmargins) {
924 pdf_obj *obj;
925 pdf_page *page;
927 fz_try (ctx) {
928 page = pdf_load_page (ctx, pdf, pageno);
929 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
930 trim = state.trimanew || !obj;
931 if (trim) {
932 fz_rect rect;
933 fz_matrix ctm;
934 fz_device *dev;
936 dev = fz_new_bbox_device (ctx, &rect);
937 dev->hints |= FZ_IGNORE_SHADE;
938 fz_invert_matrix (&ctm, &page->ctm);
939 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
940 fz_drop_device (ctx, dev);
942 rect.x0 += state.trimfuzz.x0;
943 rect.x1 += state.trimfuzz.x1;
944 rect.y0 += state.trimfuzz.y0;
945 rect.y1 += state.trimfuzz.y1;
946 fz_transform_rect (&rect, &ctm);
947 fz_intersect_rect (&rect, &page->mediabox);
949 if (fz_is_empty_rect (&rect)) {
950 mediabox = page->mediabox;
952 else {
953 mediabox = rect;
956 obj = pdf_new_array (ctx, pdf, 4);
957 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
958 mediabox.x0));
959 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
960 mediabox.y0));
961 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
962 mediabox.x1));
963 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
964 mediabox.y1));
965 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
967 else {
968 mediabox.x0 = pdf_to_real (ctx,
969 pdf_array_get (ctx, obj, 0));
970 mediabox.y0 = pdf_to_real (ctx,
971 pdf_array_get (ctx, obj, 1));
972 mediabox.x1 = pdf_to_real (ctx,
973 pdf_array_get (ctx, obj, 2));
974 mediabox.y1 = pdf_to_real (ctx,
975 pdf_array_get (ctx, obj, 3));
978 rotate = page->rotate;
979 fz_drop_page (ctx, &page->super);
981 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
982 if (show) {
983 printd ("progress %f Trimming %d",
984 (double) (pageno + 1) / state.pagecount,
985 pageno + 1);
988 fz_catch (ctx) {
989 fprintf (stderr, "failed to load page %d\n", pageno+1);
992 else {
993 int empty = 0;
994 fz_rect cropbox;
996 pdf_to_rect (ctx,
997 pdf_dict_gets (ctx, pageobj, "MediaBox"),
998 &mediabox);
999 if (fz_is_empty_rect (&mediabox)) {
1000 mediabox.x0 = 0;
1001 mediabox.y0 = 0;
1002 mediabox.x1 = 612;
1003 mediabox.y1 = 792;
1004 empty = 1;
1007 pdf_to_rect (ctx,
1008 pdf_dict_gets (ctx, pageobj, "CropBox"),
1009 &cropbox);
1010 if (!fz_is_empty_rect (&cropbox)) {
1011 if (empty) {
1012 mediabox = cropbox;
1014 else {
1015 fz_intersect_rect (&mediabox, &cropbox);
1018 else {
1019 if (empty) {
1020 if (fz_is_empty_rect (&rootmediabox)) {
1021 fprintf (stderr,
1022 "cannot find page size for page %d\n",
1023 pageno+1);
1025 else {
1026 mediabox = rootmediabox;
1030 rotate = pdf_to_int (ctx,
1031 pdf_dict_gets (ctx, pageobj, "Rotate"));
1034 else {
1035 if (state.trimmargins && trimw) {
1036 fz_page *page;
1038 fz_try (ctx) {
1039 page = fz_load_page (ctx, state.doc, pageno);
1040 fz_bound_page (ctx, page, &mediabox);
1041 rotate = 0;
1042 if (state.trimmargins) {
1043 fz_rect rect;
1044 fz_device *dev;
1046 dev = fz_new_bbox_device (ctx, &rect);
1047 dev->hints |= FZ_IGNORE_SHADE;
1048 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1049 fz_drop_device (ctx, dev);
1051 rect.x0 += state.trimfuzz.x0;
1052 rect.x1 += state.trimfuzz.x1;
1053 rect.y0 += state.trimfuzz.y0;
1054 rect.y1 += state.trimfuzz.y1;
1055 fz_intersect_rect (&rect, &mediabox);
1057 if (!fz_is_empty_rect (&rect)) {
1058 mediabox = rect;
1061 fz_drop_page (ctx, page);
1062 if (!state.cxack) {
1063 printd ("progress %f loading %d",
1064 (double) (pageno + 1) / state.pagecount,
1065 pageno + 1);
1068 fz_catch (ctx) {
1070 if (trimf) {
1071 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1072 if (n - 1) {
1073 err (1, "fwrite trim mediabox");
1077 else {
1078 if (trimf) {
1079 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1080 if (n - 1) {
1081 err (1, "fread trim mediabox %d", pageno);
1084 else {
1085 fz_page *page;
1086 fz_try (ctx) {
1087 page = fz_load_page (ctx, state.doc, pageno);
1088 fz_bound_page (ctx, page, &mediabox);
1089 fz_drop_page (ctx, page);
1091 show = !state.trimmargins && pageno % 20 == 0;
1092 if (show) {
1093 printd ("progress %f Gathering dimensions %d",
1094 (double) (pageno) / state.pagecount,
1095 pageno);
1098 fz_catch (ctx) {
1099 fprintf (stderr, "failed to load page %d\n", pageno);
1105 if (state.pagedimcount == 0
1106 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1107 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1108 size_t size;
1110 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1111 state.pagedims = realloc (state.pagedims, size);
1112 if (!state.pagedims) {
1113 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1114 size, state.pagedimcount + 1);
1117 p = &state.pagedims[state.pagedimcount++];
1118 p->rotate = rotate;
1119 p->mediabox = mediabox;
1120 p->pageno = pageno;
1123 end = now ();
1124 if (!wthack) {
1125 printd ("progress 1 %s %d pages in %f seconds",
1126 state.trimmargins ? "Trimmed" : "Processed",
1127 state.pagecount, end - start);
1129 state.trimanew = 0;
1130 if (trimf) {
1131 if (fclose (trimf)) {
1132 err (1, "fclose");
1137 static void layout (void)
1139 int pindex;
1140 fz_rect box;
1141 fz_matrix ctm, rm;
1142 struct pagedim *p = p;
1143 double zw, w, maxw = 0.0, zoom = zoom;
1145 if (state.pagedimcount == 0) return;
1147 switch (state.fitmodel) {
1148 case FitProportional:
1149 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1150 double x0, x1;
1152 p = &state.pagedims[pindex];
1153 fz_rotate (&rm, p->rotate + state.rotate);
1154 box = p->mediabox;
1155 fz_transform_rect (&box, &rm);
1157 x0 = fz_min (box.x0, box.x1);
1158 x1 = fz_max (box.x0, box.x1);
1160 w = x1 - x0;
1161 maxw = fz_max (w, maxw);
1162 zoom = state.w / maxw;
1164 break;
1166 case FitPage:
1167 maxw = state.w;
1168 break;
1170 case FitWidth:
1171 break;
1173 default:
1174 ARSERT (0 && state.fitmodel);
1177 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1178 fz_rect rect;
1179 fz_matrix tm, sm;
1181 p = &state.pagedims[pindex];
1182 fz_rotate (&ctm, state.rotate);
1183 fz_rotate (&rm, p->rotate + state.rotate);
1184 box = p->mediabox;
1185 fz_transform_rect (&box, &rm);
1186 w = box.x1 - box.x0;
1187 switch (state.fitmodel) {
1188 case FitProportional:
1189 p->left = ((maxw - w) * zoom) / 2.0;
1190 break;
1191 case FitPage:
1193 double zh, h;
1194 zw = maxw / w;
1195 h = box.y1 - box.y0;
1196 zh = state.h / h;
1197 zoom = fz_min (zw, zh);
1198 p->left = (maxw - (w * zoom)) / 2.0;
1200 break;
1201 case FitWidth:
1202 p->left = 0;
1203 zoom = state.w / w;
1204 break;
1207 fz_scale (&p->zoomctm, zoom, zoom);
1208 fz_concat (&ctm, &p->zoomctm, &ctm);
1210 fz_rotate (&rm, p->rotate);
1211 p->pagebox = p->mediabox;
1212 fz_transform_rect (&p->pagebox, &rm);
1213 p->pagebox.x1 -= p->pagebox.x0;
1214 p->pagebox.y1 -= p->pagebox.y0;
1215 p->pagebox.x0 = 0;
1216 p->pagebox.y0 = 0;
1217 rect = p->pagebox;
1218 fz_transform_rect (&rect, &ctm);
1219 fz_round_rect (&p->bounds, &rect);
1220 p->ctm = ctm;
1222 fz_translate (&tm, 0, -p->mediabox.y1);
1223 fz_scale (&sm, zoom, -zoom);
1224 fz_concat (&ctm, &tm, &sm);
1225 fz_concat (&p->lctm, &ctm, &rm);
1227 p->tctmready = 0;
1230 do {
1231 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1232 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1233 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1234 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1235 int boundw = x1 - x0;
1236 int boundh = y1 - y0;
1238 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1239 } while (p-- != state.pagedims);
1242 static
1243 struct anchor { int n; int x; int y; int w; int h; }
1244 desttoanchor (fz_link_dest *dest)
1246 int i;
1247 struct anchor a;
1248 struct pagedim *pdim = state.pagedims;
1250 a.n = -1;
1251 a.x = 0;
1252 a.y = 0;
1253 for (i = 0; i < state.pagedimcount; ++i) {
1254 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1255 break;
1256 pdim = &state.pagedims[i];
1258 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1259 fz_point p;
1260 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1261 p.x = dest->ld.gotor.lt.x;
1262 else
1263 p.x = 0.0;
1264 p.y = dest->ld.gotor.lt.y;
1265 fz_transform_point (&p, &pdim->lctm);
1266 a.x = p.x;
1267 a.y = p.y;
1269 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1270 double x0, x1, y0, y1;
1272 x0 = fz_min (pdim->bounds.x0, pdim->bounds.x1);
1273 x1 = fz_max (pdim->bounds.x0, pdim->bounds.x1);
1274 a.w = x1 - x0;
1275 y0 = fz_min (pdim->bounds.y0, pdim->bounds.y1);
1276 y1 = fz_max (pdim->bounds.y0, pdim->bounds.y1);
1277 a.h = y1 - y0;
1278 a.n = dest->ld.gotor.page;
1280 return a;
1283 static void recurse_outline (fz_outline *outline, int level)
1285 while (outline) {
1286 switch (outline->dest.kind) {
1287 case FZ_LINK_GOTO:
1289 struct anchor a = desttoanchor (&outline->dest);
1291 if (a.n >= 0) {
1292 printd ("o %d %d %d %d %s",
1293 level, a.n, a.y, a.h, outline->title);
1296 break;
1298 case FZ_LINK_URI:
1299 printd ("ou %d %" FMT_s " %s %s", level,
1300 strlen (outline->title), outline->title,
1301 outline->dest.ld.uri.uri);
1302 break;
1304 case FZ_LINK_NONE:
1305 printd ("on %d %s", level, outline->title);
1306 break;
1308 default:
1309 printd ("emsg Unhandled outline kind %d for %s\n",
1310 outline->dest.kind, outline->title);
1311 break;
1313 if (outline->down) {
1314 recurse_outline (outline->down, level + 1);
1316 outline = outline->next;
1320 static void process_outline (void)
1322 fz_outline *outline;
1324 if (!state.needoutline || !state.pagedimcount) return;
1326 state.needoutline = 0;
1327 outline = fz_load_outline (state.ctx, state.doc);
1328 if (outline) {
1329 recurse_outline (outline, 0);
1330 fz_drop_outline (state.ctx, outline);
1334 static char *strofspan (fz_stext_span *span)
1336 char *p;
1337 char utf8[10];
1338 fz_stext_char *ch;
1339 size_t size = 0, cap = 80;
1341 p = malloc (cap + 1);
1342 if (!p) return NULL;
1344 for (ch = span->text; ch < span->text + span->len; ++ch) {
1345 int n = fz_runetochar (utf8, ch->c);
1346 if (size + n > cap) {
1347 cap *= 2;
1348 p = realloc (p, cap + 1);
1349 if (!p) return NULL;
1352 memcpy (p + size, utf8, n);
1353 size += n;
1355 p[size] = 0;
1356 return p;
1359 static int matchspan (regex_t *re, fz_stext_span *span,
1360 int stop, int pageno, double start)
1362 int ret;
1363 char *p;
1364 regmatch_t rm;
1365 int a, b, c;
1366 fz_rect sb, eb;
1367 fz_point p1, p2, p3, p4;
1369 p = strofspan (span);
1370 if (!p) return -1;
1372 ret = regexec (re, p, 1, &rm, 0);
1373 if (ret) {
1374 free (p);
1375 if (ret != REG_NOMATCH) {
1376 size_t size;
1377 char errbuf[80];
1378 size = regerror (ret, re, errbuf, sizeof (errbuf));
1379 printd ("msg regexec error `%.*s'",
1380 (int) size, errbuf);
1381 return -1;
1383 return 0;
1385 else {
1386 int l = span->len;
1388 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1389 c += fz_runelen (span->text[a].c);
1391 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1392 c += fz_runelen (span->text[b].c);
1395 if (fz_runelen (span->text[b].c) > 1) {
1396 b = fz_maxi (0, b-1);
1399 fz_stext_char_bbox (state.ctx, &sb, span, a);
1400 fz_stext_char_bbox (state.ctx, &eb, span, b);
1402 p1.x = sb.x0;
1403 p1.y = sb.y0;
1404 p2.x = eb.x1;
1405 p2.y = sb.y0;
1406 p3.x = eb.x1;
1407 p3.y = eb.y1;
1408 p4.x = sb.x0;
1409 p4.y = eb.y1;
1411 if (!stop) {
1412 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1413 pageno, 1,
1414 p1.x, p1.y,
1415 p2.x, p2.y,
1416 p3.x, p3.y,
1417 p4.x, p4.y);
1419 printd ("progress 1 found at %d `%.*s' in %f sec",
1420 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1421 now () - start);
1423 else {
1424 printd ("match %d %d %f %f %f %f %f %f %f %f",
1425 pageno, 2,
1426 p1.x, p1.y,
1427 p2.x, p2.y,
1428 p3.x, p3.y,
1429 p4.x, p4.y);
1431 free (p);
1432 return 1;
1436 static int compareblocks (const void *l, const void *r)
1438 fz_stext_block const *ls = l;
1439 fz_stext_block const *rs = r;
1440 return ls->bbox.y0 - rs->bbox.y0;
1443 /* wishful thinking function */
1444 static void search (regex_t *re, int pageno, int y, int forward)
1446 int i, j;
1447 fz_device *tdev;
1448 fz_stext_page *text;
1449 fz_stext_sheet *sheet;
1450 struct pagedim *pdim, *pdimprev;
1451 int stop = 0, niters = 0;
1452 double start, end;
1453 fz_page *page;
1455 start = now ();
1456 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1457 if (niters++ == 5) {
1458 niters = 0;
1459 if (hasdata ()) {
1460 printd ("progress 1 attention requested aborting search at %d",
1461 pageno);
1462 stop = 1;
1464 else {
1465 printd ("progress %f searching in page %d",
1466 (double) (pageno + 1) / state.pagecount,
1467 pageno);
1470 pdimprev = NULL;
1471 for (i = 0; i < state.pagedimcount; ++i) {
1472 pdim = &state.pagedims[i];
1473 if (pdim->pageno == pageno) {
1474 goto found;
1476 if (pdim->pageno > pageno) {
1477 pdim = pdimprev;
1478 goto found;
1480 pdimprev = pdim;
1482 pdim = pdimprev;
1483 found:
1485 sheet = fz_new_stext_sheet (state.ctx);
1486 text = fz_new_stext_page (state.ctx);
1487 tdev = fz_new_stext_device (state.ctx, sheet, text);
1489 page = fz_load_page (state.ctx, state.doc, pageno);
1491 fz_matrix ctm = pagectm1 (page, pdim);
1492 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1495 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1496 fz_drop_device (state.ctx, tdev);
1498 for (j = 0; j < text->len; ++j) {
1499 int k;
1500 fz_page_block *pb;
1501 fz_stext_block *block;
1503 pb = &text->blocks[forward ? j : text->len - 1 - j];
1504 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1505 block = pb->u.text;
1507 for (k = 0; k < block->len; ++k) {
1508 fz_stext_line *line;
1509 fz_stext_span *span;
1511 if (forward) {
1512 line = &block->lines[k];
1513 if (line->bbox.y0 < y + 1) continue;
1515 else {
1516 line = &block->lines[block->len - 1 - k];
1517 if (line->bbox.y0 > y - 1) continue;
1520 for (span = line->first_span; span; span = span->next) {
1521 switch (matchspan (re, span, stop, pageno, start)) {
1522 case 0: break;
1523 case 1: stop = 1; break;
1524 case -1: stop = 1; goto endloop;
1529 if (forward) {
1530 pageno += 1;
1531 y = 0;
1533 else {
1534 pageno -= 1;
1535 y = INT_MAX;
1537 endloop:
1538 fz_drop_stext_page (state.ctx, text);
1539 fz_drop_stext_sheet (state.ctx, sheet);
1540 fz_drop_page (state.ctx, page);
1542 end = now ();
1543 if (!stop) {
1544 printd ("progress 1 no matches %f sec", end - start);
1546 printd ("clearrects");
1549 static void set_tex_params (int colorspace)
1551 union {
1552 unsigned char b;
1553 unsigned int s;
1554 } endianness = {1};
1556 switch (colorspace) {
1557 case 0:
1558 state.texiform = GL_RGBA8;
1559 state.texform = GL_RGBA;
1560 state.texty = GL_UNSIGNED_BYTE;
1561 state.colorspace = fz_device_rgb (state.ctx);
1562 break;
1563 case 1:
1564 state.texiform = GL_RGBA8;
1565 state.texform = GL_BGRA;
1566 state.texty = endianness.s > 1
1567 ? GL_UNSIGNED_INT_8_8_8_8
1568 : GL_UNSIGNED_INT_8_8_8_8_REV;
1569 state.colorspace = fz_device_bgr (state.ctx);
1570 break;
1571 case 2:
1572 state.texiform = GL_LUMINANCE_ALPHA;
1573 state.texform = GL_LUMINANCE_ALPHA;
1574 state.texty = GL_UNSIGNED_BYTE;
1575 state.colorspace = fz_device_gray (state.ctx);
1576 break;
1577 default:
1578 errx (1, "invalid colorspce %d", colorspace);
1582 static void realloctexts (int texcount)
1584 size_t size;
1586 if (texcount == state.texcount) return;
1588 if (texcount < state.texcount) {
1589 glDeleteTextures (state.texcount - texcount,
1590 state.texids + texcount);
1593 size = texcount * sizeof (*state.texids);
1594 state.texids = realloc (state.texids, size);
1595 if (!state.texids) {
1596 err (1, "realloc texids %" FMT_s, size);
1599 size = texcount * sizeof (*state.texowners);
1600 state.texowners = realloc (state.texowners, size);
1601 if (!state.texowners) {
1602 err (1, "realloc texowners %" FMT_s, size);
1604 if (texcount > state.texcount) {
1605 int i;
1607 glGenTextures (texcount - state.texcount,
1608 state.texids + state.texcount);
1609 for (i = state.texcount; i < texcount; ++i) {
1610 state.texowners[i].w = -1;
1611 state.texowners[i].slice = NULL;
1614 state.texcount = texcount;
1615 state.texindex = 0;
1618 static char *mbtoutf8 (char *s)
1620 char *p, *r;
1621 wchar_t *tmp;
1622 size_t i, ret, len;
1624 len = mbstowcs (NULL, s, strlen (s));
1625 if (len == 0) {
1626 return s;
1628 else {
1629 if (len == (size_t) -1) {
1630 return s;
1634 tmp = malloc (len * sizeof (wchar_t));
1635 if (!tmp) {
1636 return s;
1639 ret = mbstowcs (tmp, s, len);
1640 if (ret == (size_t) -1) {
1641 free (tmp);
1642 return s;
1645 len = 0;
1646 for (i = 0; i < ret; ++i) {
1647 len += fz_runelen (tmp[i]);
1650 p = r = malloc (len + 1);
1651 if (!r) {
1652 free (tmp);
1653 return s;
1656 for (i = 0; i < ret; ++i) {
1657 p += fz_runetochar (p, tmp[i]);
1659 *p = 0;
1660 free (tmp);
1661 return r;
1664 CAMLprim value ml_mbtoutf8 (value s_v)
1666 CAMLparam1 (s_v);
1667 CAMLlocal1 (ret_v);
1668 char *s, *r;
1670 s = String_val (s_v);
1671 r = mbtoutf8 (s);
1672 if (r == s) {
1673 ret_v = s_v;
1675 else {
1676 ret_v = caml_copy_string (r);
1677 free (r);
1679 CAMLreturn (ret_v);
1682 static void * mainloop (void UNUSED_ATTR *unused)
1684 char *p = NULL;
1685 int len, ret, oldlen = 0;
1687 fz_var (p);
1688 fz_var (oldlen);
1689 for (;;) {
1690 len = readlen (state.csock);
1691 if (len == 0) {
1692 errx (1, "readlen returned 0");
1695 if (oldlen < len + 1) {
1696 p = realloc (p, len + 1);
1697 if (!p) {
1698 err (1, "realloc %d failed", len + 1);
1700 oldlen = len + 1;
1702 readdata (state.csock, p, len);
1703 p[len] = 0;
1705 if (!strncmp ("open", p, 4)) {
1706 int wthack, off, ok = 0;
1707 char *password;
1708 char *filename;
1709 char *utf8filename;
1710 size_t filenamelen;
1712 fz_var (ok);
1713 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1714 if (ret != 2) {
1715 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1718 filename = p + 5 + off;
1719 filenamelen = strlen (filename);
1720 password = filename + filenamelen + 1;
1722 lock ("open");
1723 fz_try (state.ctx) {
1724 ok = openxref (filename, password);
1726 fz_catch (state.ctx) {
1727 utf8filename = mbtoutf8 (filename);
1728 printd ("msg Could not open %s", utf8filename);
1730 if (ok) {
1731 pdfinfo ();
1732 initpdims (wthack);
1734 unlock ("open");
1736 if (ok) {
1737 if (!wthack) {
1738 utf8filename = mbtoutf8 (filename);
1739 printd ("msg Opened %s (press h/F1 to get help)",
1740 utf8filename);
1741 if (utf8filename != filename) {
1742 free (utf8filename);
1745 state.needoutline = 1;
1748 else if (!strncmp ("cs", p, 2)) {
1749 int i, colorspace;
1751 ret = sscanf (p + 2, " %d", &colorspace);
1752 if (ret != 1) {
1753 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1755 lock ("cs");
1756 set_tex_params (colorspace);
1757 for (i = 0; i < state.texcount; ++i) {
1758 state.texowners[i].w = -1;
1759 state.texowners[i].slice = NULL;
1761 unlock ("cs");
1763 else if (!strncmp ("freepage", p, 8)) {
1764 void *ptr;
1766 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1767 if (ret != 1) {
1768 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1770 freepage (ptr);
1772 else if (!strncmp ("freetile", p, 8)) {
1773 void *ptr;
1775 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1776 if (ret != 1) {
1777 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1779 freetile (ptr);
1781 else if (!strncmp ("search", p, 6)) {
1782 int icase, pageno, y, len2, forward;
1783 char *pattern;
1784 regex_t re;
1786 ret = sscanf (p + 6, " %d %d %d %d,%n",
1787 &icase, &pageno, &y, &forward, &len2);
1788 if (ret != 4) {
1789 errx (1, "malformed search `%s' ret=%d", p, ret);
1792 pattern = p + 6 + len2;
1793 ret = regcomp (&re, pattern,
1794 REG_EXTENDED | (icase ? REG_ICASE : 0));
1795 if (ret) {
1796 char errbuf[80];
1797 size_t size;
1799 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1800 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1802 else {
1803 search (&re, pageno, y, forward);
1804 regfree (&re);
1807 else if (!strncmp ("geometry", p, 8)) {
1808 int w, h, fitmodel;
1810 printd ("clear");
1811 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1812 if (ret != 3) {
1813 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1816 lock ("geometry");
1817 state.h = h;
1818 if (w != state.w) {
1819 int i;
1820 state.w = w;
1821 for (i = 0; i < state.texcount; ++i) {
1822 state.texowners[i].slice = NULL;
1825 state.fitmodel = fitmodel;
1826 layout ();
1827 process_outline ();
1829 state.gen++;
1830 unlock ("geometry");
1831 printd ("continue %d", state.pagecount);
1833 else if (!strncmp ("reqlayout", p, 9)) {
1834 char *nameddest;
1835 int rotate, off, h;
1836 unsigned int fitmodel;
1837 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1839 printd ("clear");
1840 ret = sscanf (p + 9, " %d %u %d %n",
1841 &rotate, &fitmodel, &h, &off);
1842 if (ret != 3) {
1843 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1845 lock ("reqlayout");
1846 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1847 state.gen += 1;
1849 state.rotate = rotate;
1850 state.fitmodel = fitmodel;
1851 state.h = h;
1852 layout ();
1853 process_outline ();
1855 nameddest = p + 9 + off;
1856 if (pdf && nameddest && *nameddest) {
1857 struct anchor a;
1858 fz_link_dest dest;
1859 pdf_obj *needle, *obj;
1861 needle = pdf_new_string (state.ctx, pdf, nameddest,
1862 strlen (nameddest));
1863 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1864 if (obj) {
1865 dest = pdf_parse_link_dest (state.ctx, pdf,
1866 FZ_LINK_GOTO, obj);
1868 a = desttoanchor (&dest);
1869 if (a.n >= 0) {
1870 printd ("a %d %d %d", a.n, a.x, a.y);
1872 else {
1873 printd ("emsg failed to parse destination `%s'\n",
1874 nameddest);
1877 else {
1878 printd ("emsg destination `%s' not found\n",
1879 nameddest);
1881 pdf_drop_obj (state.ctx, needle);
1884 state.gen++;
1885 unlock ("reqlayout");
1886 printd ("continue %d", state.pagecount);
1888 else if (!strncmp ("page", p, 4)) {
1889 double a, b;
1890 struct page *page;
1891 int pageno, pindex;
1893 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1894 if (ret != 2) {
1895 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1898 lock ("page");
1899 a = now ();
1900 page = loadpage (pageno, pindex);
1901 b = now ();
1902 unlock ("page");
1904 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1906 else if (!strncmp ("tile", p, 4)) {
1907 int x, y, w, h;
1908 struct page *page;
1909 struct tile *tile;
1910 double a, b;
1911 void *data;
1913 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1914 SCN_ptr_cast (&page), &x, &y, &w, &h,
1915 SCN_ptr_cast (&data));
1916 if (ret != 6) {
1917 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1920 lock ("tile");
1921 a = now ();
1922 tile = rendertile (page, x, y, w, h, data);
1923 b = now ();
1924 unlock ("tile");
1926 printd ("tile %d %d %" FMT_ptr " %u %f",
1927 x, y,
1928 FMT_ptr_cast (tile),
1929 tile->w * tile->h * tile->pixmap->n,
1930 b - a);
1932 else if (!strncmp ("trimset", p, 7)) {
1933 fz_irect fuzz;
1934 int trimmargins;
1936 ret = sscanf (p + 7, " %d %d %d %d %d",
1937 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1938 if (ret != 5) {
1939 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1941 lock ("trimset");
1942 state.trimmargins = trimmargins;
1943 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1944 state.trimanew = 1;
1945 state.trimfuzz = fuzz;
1947 unlock ("trimset");
1949 else if (!strncmp ("settrim", p, 7)) {
1950 fz_irect fuzz;
1951 int trimmargins;
1953 ret = sscanf (p + 7, " %d %d %d %d %d",
1954 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1955 if (ret != 5) {
1956 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1958 printd ("clear");
1959 lock ("settrim");
1960 state.trimmargins = trimmargins;
1961 state.needoutline = 1;
1962 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1963 state.trimanew = 1;
1964 state.trimfuzz = fuzz;
1966 state.pagedimcount = 0;
1967 free (state.pagedims);
1968 state.pagedims = NULL;
1969 initpdims (0);
1970 layout ();
1971 process_outline ();
1972 unlock ("settrim");
1973 printd ("continue %d", state.pagecount);
1975 else if (!strncmp ("sliceh", p, 6)) {
1976 int h;
1978 ret = sscanf (p + 6, " %d", &h);
1979 if (ret != 1) {
1980 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1982 if (h != state.sliceheight) {
1983 int i;
1985 state.sliceheight = h;
1986 for (i = 0; i < state.texcount; ++i) {
1987 state.texowners[i].w = -1;
1988 state.texowners[i].h = -1;
1989 state.texowners[i].slice = NULL;
1993 else if (!strncmp ("interrupt", p, 9)) {
1994 printd ("vmsg interrupted");
1996 else {
1997 errx (1, "unknown command %.*s", len, p);
2000 return 0;
2003 CAMLprim value ml_realloctexts (value texcount_v)
2005 CAMLparam1 (texcount_v);
2006 int ok;
2008 if (trylock (__func__)) {
2009 ok = 0;
2010 goto done;
2012 realloctexts (Int_val (texcount_v));
2013 ok = 1;
2014 unlock (__func__);
2016 done:
2017 CAMLreturn (Val_bool (ok));
2020 static void recti (int x0, int y0, int x1, int y1)
2022 GLfloat *v = state.vertices;
2024 glVertexPointer (2, GL_FLOAT, 0, v);
2025 v[0] = x0; v[1] = y0;
2026 v[2] = x1; v[3] = y0;
2027 v[4] = x0; v[5] = y1;
2028 v[6] = x1; v[7] = y1;
2029 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2032 static void showsel (struct page *page, int ox, int oy)
2034 int seen = 0;
2035 fz_irect bbox;
2036 fz_rect rect;
2037 fz_stext_line *line;
2038 fz_page_block *pageb;
2039 fz_stext_block *block;
2040 struct mark first, last;
2041 unsigned char selcolor[] = {15,15,15,140};
2043 first = page->fmark;
2044 last = page->lmark;
2046 if (!first.span || !last.span) return;
2048 glEnable (GL_BLEND);
2049 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2050 glColor4ubv (selcolor);
2052 ox += state.pagedims[page->pdimno].bounds.x0;
2053 oy += state.pagedims[page->pdimno].bounds.y0;
2054 for (pageb = page->text->blocks;
2055 pageb < page->text->blocks + page->text->len;
2056 ++pageb) {
2057 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2058 block = pageb->u.text;
2060 for (line = block->lines;
2061 line < block->lines + block->len;
2062 ++line) {
2063 fz_stext_span *span;
2064 rect = fz_empty_rect;
2066 for (span = line->first_span; span; span = span->next) {
2067 int i, j, k;
2068 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2070 j = 0;
2071 k = span->len - 1;
2073 if (span == page->fmark.span && span == page->lmark.span) {
2074 seen = 1;
2075 j = fz_mini (first.i, last.i);
2076 k = fz_maxi (first.i, last.i);
2078 else {
2079 if (span == first.span) {
2080 seen = 1;
2081 j = first.i;
2083 else if (span == last.span) {
2084 seen = 1;
2085 k = last.i;
2089 if (seen) {
2090 for (i = j; i <= k; ++i) {
2091 fz_rect bbox1;
2092 fz_union_rect (&rect,
2093 fz_stext_char_bbox (state.ctx, &bbox1,
2094 span, i));
2096 fz_round_rect (&bbox, &rect);
2097 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2098 bbox.x0,
2099 bbox.y0,
2100 bbox.x1,
2101 bbox.y1,
2102 oy, ox);
2104 recti (bbox.x0 + ox, bbox.y0 + oy,
2105 bbox.x1 + ox, bbox.y1 + oy);
2106 if (span == last.span) {
2107 goto done;
2109 rect = fz_empty_rect;
2114 done:
2115 glDisable (GL_BLEND);
2118 #include "glfont.c"
2120 static void stipplerect (fz_matrix *m,
2121 fz_point *p1,
2122 fz_point *p2,
2123 fz_point *p3,
2124 fz_point *p4,
2125 GLfloat *texcoords,
2126 GLfloat *vertices)
2128 fz_transform_point (p1, m);
2129 fz_transform_point (p2, m);
2130 fz_transform_point (p3, m);
2131 fz_transform_point (p4, m);
2133 float w, h, s, t;
2135 w = p2->x - p1->x;
2136 h = p2->y - p1->y;
2137 t = sqrtf (w*w + h*h) * .25f;
2139 w = p3->x - p2->x;
2140 h = p3->y - p2->y;
2141 s = sqrtf (w*w + h*h) * .25f;
2143 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2144 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2146 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2147 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2149 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2150 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2152 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2153 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2155 glDrawArrays (GL_LINES, 0, 8);
2158 static void solidrect (fz_matrix *m,
2159 fz_point *p1,
2160 fz_point *p2,
2161 fz_point *p3,
2162 fz_point *p4,
2163 GLfloat *vertices)
2165 fz_transform_point (p1, m);
2166 fz_transform_point (p2, m);
2167 fz_transform_point (p3, m);
2168 fz_transform_point (p4, m);
2169 vertices[0] = p1->x; vertices[1] = p1->y;
2170 vertices[2] = p2->x; vertices[3] = p2->y;
2172 vertices[4] = p3->x; vertices[5] = p3->y;
2173 vertices[6] = p4->x; vertices[7] = p4->y;
2174 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2177 static void highlightlinks (struct page *page, int xoff, int yoff)
2179 int i;
2180 fz_matrix ctm, tm, pm;
2181 fz_link *link, *links;
2182 GLfloat *texcoords = state.texcoords;
2183 GLfloat *vertices = state.vertices;
2185 links = fz_load_links (state.ctx, page->fzpage);
2187 glEnable (GL_TEXTURE_1D);
2188 glEnable (GL_BLEND);
2189 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2190 glBindTexture (GL_TEXTURE_1D, state.stid);
2192 xoff -= state.pagedims[page->pdimno].bounds.x0;
2193 yoff -= state.pagedims[page->pdimno].bounds.y0;
2194 fz_translate (&tm, xoff, yoff);
2195 pm = pagectm (page);
2196 fz_concat (&ctm, &pm, &tm);
2198 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2199 glVertexPointer (2, GL_FLOAT, 0, vertices);
2201 for (link = links; link; link = link->next) {
2202 fz_point p1, p2, p3, p4;
2204 p1.x = link->rect.x0;
2205 p1.y = link->rect.y0;
2207 p2.x = link->rect.x1;
2208 p2.y = link->rect.y0;
2210 p3.x = link->rect.x1;
2211 p3.y = link->rect.y1;
2213 p4.x = link->rect.x0;
2214 p4.y = link->rect.y1;
2216 switch (link->dest.kind) {
2217 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2218 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2219 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2220 default: glColor3ub (0, 0, 0); break;
2222 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2225 for (i = 0; i < page->annotcount; ++i) {
2226 fz_point p1, p2, p3, p4;
2227 struct annot *annot = &page->annots[i];
2229 p1.x = annot->bbox.x0;
2230 p1.y = annot->bbox.y0;
2232 p2.x = annot->bbox.x1;
2233 p2.y = annot->bbox.y0;
2235 p3.x = annot->bbox.x1;
2236 p3.y = annot->bbox.y1;
2238 p4.x = annot->bbox.x0;
2239 p4.y = annot->bbox.y1;
2241 glColor3ub (0, 0, 128);
2242 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2245 glDisable (GL_BLEND);
2246 glDisable (GL_TEXTURE_1D);
2249 static int compareslinks (const void *l, const void *r)
2251 struct slink const *ls = l;
2252 struct slink const *rs = r;
2253 if (ls->bbox.y0 == rs->bbox.y0) {
2254 return rs->bbox.x0 - rs->bbox.x0;
2256 return ls->bbox.y0 - rs->bbox.y0;
2259 static void droptext (struct page *page)
2261 if (page->text) {
2262 fz_drop_stext_page (state.ctx, page->text);
2263 page->fmark.i = -1;
2264 page->lmark.i = -1;
2265 page->fmark.span = NULL;
2266 page->lmark.span = NULL;
2267 page->text = NULL;
2269 if (page->sheet) {
2270 fz_drop_stext_sheet (state.ctx, page->sheet);
2271 page->sheet = NULL;
2275 static void dropannots (struct page *page)
2277 if (page->annots) {
2278 free (page->annots);
2279 page->annots = NULL;
2280 page->annotcount = 0;
2284 static void ensureannots (struct page *page)
2286 int i, count = 0;
2287 size_t annotsize = sizeof (*page->annots);
2288 fz_annot *annot;
2290 if (state.gen != page->agen) {
2291 dropannots (page);
2292 page->agen = state.gen;
2294 if (page->annots) return;
2296 for (annot = fz_first_annot (state.ctx, page->fzpage);
2297 annot;
2298 annot = fz_next_annot (state.ctx, annot)) {
2299 count++;
2302 if (count > 0) {
2303 page->annotcount = count;
2304 page->annots = calloc (count, annotsize);
2305 if (!page->annots) {
2306 err (1, "calloc annots %d", count);
2309 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2310 annot;
2311 annot = fz_next_annot (state.ctx, annot), i++) {
2312 fz_rect rect;
2314 fz_bound_annot (state.ctx, annot, &rect);
2315 page->annots[i].annot = annot;
2316 fz_round_rect (&page->annots[i].bbox, &rect);
2321 static void dropslinks (struct page *page)
2323 if (page->slinks) {
2324 free (page->slinks);
2325 page->slinks = NULL;
2326 page->slinkcount = 0;
2330 static void ensureslinks (struct page *page)
2332 fz_matrix ctm;
2333 int i, count;
2334 size_t slinksize = sizeof (*page->slinks);
2335 fz_link *link, *links;
2337 ensureannots (page);
2338 if (state.gen != page->sgen) {
2339 dropslinks (page);
2340 page->sgen = state.gen;
2342 if (page->slinks) return;
2344 links = fz_load_links (state.ctx, page->fzpage);
2345 ctm = pagectm (page);
2347 count = page->annotcount;
2348 for (link = links; link; link = link->next) {
2349 count++;
2351 if (count > 0) {
2352 int j;
2354 page->slinkcount = count;
2355 page->slinks = calloc (count, slinksize);
2356 if (!page->slinks) {
2357 err (1, "calloc slinks %d", count);
2360 for (i = 0, link = links; link; ++i, link = link->next) {
2361 fz_rect rect;
2363 rect = link->rect;
2364 fz_transform_rect (&rect, &ctm);
2365 page->slinks[i].tag = SLINK;
2366 page->slinks[i].u.link = link;
2367 fz_round_rect (&page->slinks[i].bbox, &rect);
2369 for (j = 0; j < page->annotcount; ++j, ++i) {
2370 fz_rect rect;
2371 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2372 fz_transform_rect (&rect, &ctm);
2373 fz_round_rect (&page->slinks[i].bbox, &rect);
2375 page->slinks[i].tag = SANNOT;
2376 page->slinks[i].u.annot = page->annots[j].annot;
2378 qsort (page->slinks, count, slinksize, compareslinks);
2382 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2383 static void fmt_linkn (char *s, unsigned int u)
2385 unsigned int len; unsigned int q;
2386 unsigned int zma = 'z' - 'a' + 1;
2387 len = 1; q = u;
2388 while (q > zma - 1) { ++len; q /= zma; }
2389 if (s) {
2390 s += len;
2391 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2392 /* handles u == 0 */
2394 s[len] = 0;
2397 static void highlightslinks (struct page *page, int xoff, int yoff,
2398 int noff, char *targ, int tlen, int hfsize)
2400 int i;
2401 char buf[40];
2402 struct slink *slink;
2403 double x0, y0, x1, y1, w;
2405 ensureslinks (page);
2406 glColor3ub (0xc3, 0xb0, 0x91);
2407 for (i = 0; i < page->slinkcount; ++i) {
2408 fmt_linkn (buf, i + noff);
2409 if (!tlen || !strncmp (targ, buf, tlen)) {
2410 slink = &page->slinks[i];
2412 x0 = slink->bbox.x0 + xoff - 5;
2413 y1 = slink->bbox.y0 + yoff - 5;
2414 y0 = y1 + 10 + hfsize;
2415 w = measure_string (state.face, hfsize, buf);
2416 x1 = x0 + w + 10;
2417 recti (x0, y0, x1, y1);
2421 glEnable (GL_BLEND);
2422 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2423 glEnable (GL_TEXTURE_2D);
2424 glColor3ub (0, 0, 0);
2425 for (i = 0; i < page->slinkcount; ++i) {
2426 fmt_linkn (buf, i + noff);
2427 if (!tlen || !strncmp (targ, buf, tlen)) {
2428 slink = &page->slinks[i];
2430 x0 = slink->bbox.x0 + xoff;
2431 y0 = slink->bbox.y0 + yoff + hfsize;
2432 draw_string (state.face, hfsize, x0, y0, buf);
2435 glDisable (GL_TEXTURE_2D);
2436 glDisable (GL_BLEND);
2439 static void uploadslice (struct tile *tile, struct slice *slice)
2441 int offset;
2442 struct slice *slice1;
2443 unsigned char *texdata;
2445 offset = 0;
2446 for (slice1 = tile->slices; slice != slice1; slice1++) {
2447 offset += slice1->h * tile->w * tile->pixmap->n;
2449 if (slice->texindex != -1 && slice->texindex < state.texcount
2450 && state.texowners[slice->texindex].slice == slice) {
2451 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2453 else {
2454 int subimage = 0;
2455 int texindex = state.texindex++ % state.texcount;
2457 if (state.texowners[texindex].w == tile->w) {
2458 if (state.texowners[texindex].h >= slice->h) {
2459 subimage = 1;
2461 else {
2462 state.texowners[texindex].h = slice->h;
2465 else {
2466 state.texowners[texindex].h = slice->h;
2469 state.texowners[texindex].w = tile->w;
2470 state.texowners[texindex].slice = slice;
2471 slice->texindex = texindex;
2473 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2474 #if TEXT_TYPE == GL_TEXTURE_2D
2475 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2476 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2477 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2478 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2479 #endif
2480 if (tile->pbo) {
2481 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2482 texdata = 0;
2484 else {
2485 texdata = tile->pixmap->samples;
2487 if (subimage) {
2488 glTexSubImage2D (TEXT_TYPE,
2492 tile->w,
2493 slice->h,
2494 state.texform,
2495 state.texty,
2496 texdata+offset
2499 else {
2500 glTexImage2D (TEXT_TYPE,
2502 state.texiform,
2503 tile->w,
2504 slice->h,
2506 state.texform,
2507 state.texty,
2508 texdata+offset
2511 if (tile->pbo) {
2512 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2517 CAMLprim value ml_begintiles (value unit_v)
2519 CAMLparam1 (unit_v);
2520 glEnable (TEXT_TYPE);
2521 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2522 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2523 CAMLreturn (unit_v);
2526 CAMLprim value ml_endtiles (value unit_v)
2528 CAMLparam1 (unit_v);
2529 glDisable (TEXT_TYPE);
2530 CAMLreturn (unit_v);
2533 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2535 CAMLparam2 (args_v, ptr_v);
2536 int dispx = Int_val (Field (args_v, 0));
2537 int dispy = Int_val (Field (args_v, 1));
2538 int dispw = Int_val (Field (args_v, 2));
2539 int disph = Int_val (Field (args_v, 3));
2540 int tilex = Int_val (Field (args_v, 4));
2541 int tiley = Int_val (Field (args_v, 5));
2542 char *s = String_val (ptr_v);
2543 struct tile *tile = parse_pointer (__func__, s);
2544 int slicey, firstslice;
2545 struct slice *slice;
2546 GLfloat *texcoords = state.texcoords;
2547 GLfloat *vertices = state.vertices;
2549 firstslice = tiley / tile->sliceheight;
2550 slice = &tile->slices[firstslice];
2551 slicey = tiley % tile->sliceheight;
2553 while (disph > 0) {
2554 int dh;
2556 dh = slice->h - slicey;
2557 dh = fz_mini (disph, dh);
2558 uploadslice (tile, slice);
2560 texcoords[0] = tilex; texcoords[1] = slicey;
2561 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2562 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2563 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2565 vertices[0] = dispx; vertices[1] = dispy;
2566 vertices[2] = dispx+dispw; vertices[3] = dispy;
2567 vertices[4] = dispx; vertices[5] = dispy+dh;
2568 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2570 #if TEXT_TYPE == GL_TEXTURE_2D
2571 for (int i = 0; i < 8; ++i) {
2572 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2574 #endif
2576 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2577 dispy += dh;
2578 disph -= dh;
2579 slice++;
2580 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2581 slicey = 0;
2583 CAMLreturn (Val_unit);
2586 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2588 fz_matrix ctm, tm, pm;
2589 fz_point p1, p2, p3, p4;
2590 GLfloat *vertices = state.vertices;
2591 double *v = (double *) rects_v;
2593 xoff -= state.pagedims[page->pdimno].bounds.x0;
2594 yoff -= state.pagedims[page->pdimno].bounds.y0;
2595 fz_translate (&tm, xoff, yoff);
2596 pm = pagectm (page);
2597 fz_concat (&ctm, &pm, &tm);
2599 glEnable (GL_BLEND);
2600 glVertexPointer (2, GL_FLOAT, 0, vertices);
2602 glColor4dv (v);
2603 p1.x = v[4];
2604 p1.y = v[5];
2606 p2.x = v[6];
2607 p2.y = v[5];
2609 p3.x = v[6];
2610 p3.y = v[7];
2612 p4.x = v[4];
2613 p4.y = v[7];
2614 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2615 glDisable (GL_BLEND);
2618 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2619 value xoff_v, value yoff_v,
2620 value li_v)
2622 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2623 int xoff = Int_val (xoff_v);
2624 int yoff = Int_val (yoff_v);
2625 int noff = Int_val (Field (li_v, 0));
2626 char *targ = String_val (Field (li_v, 1));
2627 int tlen = caml_string_length (Field (li_v, 1));
2628 int hfsize = Int_val (Field (li_v, 2));
2629 char *s = String_val (ptr_v);
2630 int hlmask = Int_val (hlinks_v);
2631 struct page *page = parse_pointer (__func__, s);
2633 if (!page->fzpage) {
2634 /* deal with loadpage failed pages */
2635 goto done;
2638 ensureannots (page);
2640 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2641 if (trylock (__func__)) {
2642 noff = 0;
2643 goto done;
2645 if (hlmask & 2) {
2646 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2647 noff = page->slinkcount;
2649 if (page->tgen == state.gen) {
2650 showsel (page, xoff, yoff);
2652 unlock (__func__);
2654 done:
2655 CAMLreturn (Val_int (noff));
2658 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2659 value rects_v)
2661 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2662 int xoff = Int_val (xoff_v);
2663 int yoff = Int_val (yoff_v);
2664 char *s = String_val (ptr_v);
2665 struct page *page = parse_pointer (__func__, s);
2667 drawprect (page, xoff, yoff, rects_v);
2668 CAMLreturn (Val_unit);
2671 static struct annot *getannot (struct page *page, int x, int y)
2673 int i;
2674 fz_point p;
2675 fz_matrix ctm;
2676 const fz_matrix *tctm;
2677 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2679 if (!page->annots) return NULL;
2681 if (pdf) {
2682 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2683 tctm = &state.pagedims[page->pdimno].tctm;
2685 else {
2686 tctm = &fz_identity;
2689 p.x = x;
2690 p.y = y;
2692 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2693 fz_invert_matrix (&ctm, &ctm);
2694 fz_transform_point (&p, &ctm);
2696 if (pdf) {
2697 for (i = 0; i < page->annotcount; ++i) {
2698 struct annot *a = &page->annots[i];
2699 pdf_annot *annot = (pdf_annot *) a->annot;
2700 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2701 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2702 return a;
2707 return NULL;
2710 static fz_link *getlink (struct page *page, int x, int y)
2712 fz_point p;
2713 fz_matrix ctm;
2714 fz_link *link, *links;
2716 links = fz_load_links (state.ctx, page->fzpage);
2718 p.x = x;
2719 p.y = y;
2721 ctm = pagectm (page);
2722 fz_invert_matrix (&ctm, &ctm);
2723 fz_transform_point (&p, &ctm);
2725 for (link = links; link; link = link->next) {
2726 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2727 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2728 return link;
2732 return NULL;
2735 static void ensuretext (struct page *page)
2737 if (state.gen != page->tgen) {
2738 droptext (page);
2739 page->tgen = state.gen;
2741 if (!page->text) {
2742 fz_matrix ctm;
2743 fz_device *tdev;
2745 page->text = fz_new_stext_page (state.ctx);
2746 page->sheet = fz_new_stext_sheet (state.ctx);
2747 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2748 ctm = pagectm (page);
2749 fz_run_display_list (state.ctx, page->dlist,
2750 tdev, &ctm, &fz_infinite_rect, NULL);
2751 qsort (page->text->blocks, page->text->len,
2752 sizeof (*page->text->blocks), compareblocks);
2753 fz_drop_device (state.ctx, tdev);
2757 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2759 CAMLparam2 (start_page_v, dir_v);
2760 CAMLlocal1 (ret_v);
2761 int i, dir = Int_val (dir_v);
2762 int start_page = Int_val (start_page_v);
2763 int end_page = dir > 0 ? state.pagecount : -1;
2764 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2766 fz_var (end_page);
2767 ret_v = Val_int (0);
2768 lock (__func__);
2769 for (i = start_page + dir; i != end_page; i += dir) {
2770 int found;
2772 fz_var (found);
2773 if (pdf) {
2774 pdf_page *page = NULL;
2776 fz_var (page);
2777 fz_try (state.ctx) {
2778 page = pdf_load_page (state.ctx, pdf, i);
2779 found = !!page->links || !!page->annots;
2781 fz_catch (state.ctx) {
2782 found = 0;
2784 if (page) {
2785 fz_drop_page (state.ctx, &page->super);
2788 else {
2789 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2790 found = !!fz_load_links (state.ctx, page);
2791 fz_drop_page (state.ctx, page);
2794 if (found) {
2795 ret_v = caml_alloc_small (1, 1);
2796 Field (ret_v, 0) = Val_int (i);
2797 goto unlock;
2800 unlock:
2801 unlock (__func__);
2802 CAMLreturn (ret_v);
2805 enum { dir_first, dir_last };
2806 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2808 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2810 CAMLparam2 (ptr_v, dir_v);
2811 CAMLlocal2 (ret_v, pos_v);
2812 struct page *page;
2813 int dirtag, i, slinkindex;
2814 struct slink *found = NULL ,*slink;
2815 char *s = String_val (ptr_v);
2817 page = parse_pointer (__func__, s);
2818 ret_v = Val_int (0);
2819 /* This is scary we are not taking locks here ensureslinks does
2820 not modify state and given that we obtained the page it can not
2821 disappear under us either */
2822 lock (__func__);
2823 ensureslinks (page);
2825 if (Is_block (dir_v)) {
2826 dirtag = Tag_val (dir_v);
2827 switch (dirtag) {
2828 case dir_first_visible:
2830 int x0, y0, dir, first_index, last_index;
2832 pos_v = Field (dir_v, 0);
2833 x0 = Int_val (Field (pos_v, 0));
2834 y0 = Int_val (Field (pos_v, 1));
2835 dir = Int_val (Field (pos_v, 2));
2837 if (dir >= 0) {
2838 dir = 1;
2839 first_index = 0;
2840 last_index = page->slinkcount;
2842 else {
2843 first_index = page->slinkcount - 1;
2844 last_index = -1;
2847 for (i = first_index; i != last_index; i += dir) {
2848 slink = &page->slinks[i];
2849 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2850 found = slink;
2851 break;
2855 break;
2857 case dir_left:
2858 slinkindex = Int_val (Field (dir_v, 0));
2859 found = &page->slinks[slinkindex];
2860 for (i = slinkindex - 1; i >= 0; --i) {
2861 slink = &page->slinks[i];
2862 if (slink->bbox.x0 < found->bbox.x0) {
2863 found = slink;
2864 break;
2867 break;
2869 case dir_right:
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.x0 > found->bbox.x0) {
2875 found = slink;
2876 break;
2879 break;
2881 case dir_down:
2882 slinkindex = Int_val (Field (dir_v, 0));
2883 found = &page->slinks[slinkindex];
2884 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2885 slink = &page->slinks[i];
2886 if (slink->bbox.y0 >= found->bbox.y0) {
2887 found = slink;
2888 break;
2891 break;
2893 case dir_up:
2894 slinkindex = Int_val (Field (dir_v, 0));
2895 found = &page->slinks[slinkindex];
2896 for (i = slinkindex - 1; i >= 0; --i) {
2897 slink = &page->slinks[i];
2898 if (slink->bbox.y0 <= found->bbox.y0) {
2899 found = slink;
2900 break;
2903 break;
2906 else {
2907 dirtag = Int_val (dir_v);
2908 switch (dirtag) {
2909 case dir_first:
2910 found = page->slinks;
2911 break;
2913 case dir_last:
2914 if (page->slinks) {
2915 found = page->slinks + (page->slinkcount - 1);
2917 break;
2920 if (found) {
2921 ret_v = caml_alloc_small (2, 1);
2922 Field (ret_v, 0) = Val_int (found - page->slinks);
2925 unlock (__func__);
2926 CAMLreturn (ret_v);
2929 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2930 unamed, uremote, uremotedest, uannot };
2932 #define LINKTOVAL \
2934 int pageno; \
2936 switch (link->dest.kind) { \
2937 case FZ_LINK_GOTO: \
2939 fz_point p; \
2941 pageno = link->dest.ld.gotor.page; \
2942 p.x = 0; \
2943 p.y = 0; \
2945 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2946 p.y = link->dest.ld.gotor.lt.y; \
2947 fz_transform_point (&p, &pdim->lctm); \
2948 if (p.y < 0) p.y = 0; \
2950 tup_v = caml_alloc_tuple (2); \
2951 ret_v = caml_alloc_small (1, ugoto); \
2952 Field (tup_v, 0) = Val_int (pageno); \
2953 Field (tup_v, 1) = Val_int (p.y); \
2954 Field (ret_v, 0) = tup_v; \
2956 break; \
2958 case FZ_LINK_URI: \
2959 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2960 ret_v = caml_alloc_small (1, uuri); \
2961 Field (ret_v, 0) = str_v; \
2962 break; \
2964 case FZ_LINK_LAUNCH: \
2965 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2966 ret_v = caml_alloc_small (1, ulaunch); \
2967 Field (ret_v, 0) = str_v; \
2968 break; \
2970 case FZ_LINK_NAMED: \
2971 str_v = caml_copy_string (link->dest.ld.named.named); \
2972 ret_v = caml_alloc_small (1, unamed); \
2973 Field (ret_v, 0) = str_v; \
2974 break; \
2976 case FZ_LINK_GOTOR: \
2978 int rty; \
2980 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2981 pageno = link->dest.ld.gotor.page; \
2982 if (pageno == -1) { \
2983 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2984 rty = uremotedest; \
2986 else { \
2987 gr_v = Val_int (pageno); \
2988 rty = uremote; \
2990 tup_v = caml_alloc_tuple (2); \
2991 ret_v = caml_alloc_small (1, rty); \
2992 Field (tup_v, 0) = str_v; \
2993 Field (tup_v, 1) = gr_v; \
2994 Field (ret_v, 0) = tup_v; \
2996 break; \
2998 default: \
3000 char buf[80]; \
3002 snprintf (buf, sizeof (buf), \
3003 "unhandled link kind %d", link->dest.kind); \
3004 str_v = caml_copy_string (buf); \
3005 ret_v = caml_alloc_small (1, uunexpected); \
3006 Field (ret_v, 0) = str_v; \
3008 break; \
3012 CAMLprim value ml_getlink (value ptr_v, value n_v)
3014 CAMLparam2 (ptr_v, n_v);
3015 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3016 fz_link *link;
3017 struct page *page;
3018 struct pagedim *pdim;
3019 char *s = String_val (ptr_v);
3020 struct slink *slink;
3022 /* See ml_findlink for caveat */
3024 ret_v = Val_int (0);
3025 page = parse_pointer (__func__, s);
3026 ensureslinks (page);
3027 pdim = &state.pagedims[page->pdimno];
3028 slink = &page->slinks[Int_val (n_v)];
3029 if (slink->tag == SLINK) {
3030 link = slink->u.link;
3031 LINKTOVAL;
3033 else {
3034 ret_v = caml_alloc_small (1, uannot);
3035 tup_v = caml_alloc_tuple (2);
3036 Field (ret_v, 0) = tup_v;
3037 Field (tup_v, 0) = ptr_v;
3038 Field (tup_v, 1) = n_v;
3041 CAMLreturn (ret_v);
3044 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3046 CAMLparam2 (ptr_v, n_v);
3047 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3048 if (pdf) {
3049 char *s = String_val (ptr_v);
3050 struct page *page;
3051 struct slink *slink;
3053 page = parse_pointer (__func__, s);
3054 slink = &page->slinks[Int_val (n_v)];
3055 CAMLreturn (caml_copy_string (
3056 pdf_annot_contents (state.ctx,
3057 (pdf_annot *) slink->u.annot)));
3059 else {
3060 CAMLreturn (caml_copy_string (""));
3064 CAMLprim value ml_getlinkcount (value ptr_v)
3066 CAMLparam1 (ptr_v);
3067 struct page *page;
3068 char *s = String_val (ptr_v);
3070 page = parse_pointer (__func__, s);
3071 CAMLreturn (Val_int (page->slinkcount));
3074 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3076 CAMLparam2 (ptr_v, n_v);
3077 CAMLlocal1 (ret_v);
3078 struct page *page;
3079 struct slink *slink;
3080 char *s = String_val (ptr_v);
3081 /* See ml_findlink for caveat */
3083 page = parse_pointer (__func__, s);
3084 ret_v = caml_alloc_tuple (4);
3085 ensureslinks (page);
3087 slink = &page->slinks[Int_val (n_v)];
3088 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3089 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3090 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3091 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3092 unlock (__func__);
3093 CAMLreturn (ret_v);
3096 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3098 CAMLparam3 (ptr_v, x_v, y_v);
3099 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3100 fz_link *link;
3101 struct annot *annot;
3102 struct page *page;
3103 char *ptr = String_val (ptr_v);
3104 int x = Int_val (x_v), y = Int_val (y_v);
3105 struct pagedim *pdim;
3107 ret_v = Val_int (0);
3108 if (trylock (__func__)) {
3109 goto done;
3112 page = parse_pointer (__func__, ptr);
3113 pdim = &state.pagedims[page->pdimno];
3114 x += pdim->bounds.x0;
3115 y += pdim->bounds.y0;
3118 annot = getannot (page, x, y);
3119 if (annot) {
3120 int i, n = -1;
3122 ensureslinks (page);
3123 for (i = 0; i < page->slinkcount; ++i) {
3124 if (page->slinks[i].tag == SANNOT
3125 && page->slinks[i].u.annot == annot->annot) {
3126 n = i;
3127 break;
3130 ret_v = caml_alloc_small (1, uannot);
3131 tup_v = caml_alloc_tuple (2);
3132 Field (ret_v, 0) = tup_v;
3133 Field (tup_v, 0) = ptr_v;
3134 Field (tup_v, 1) = Val_int (n);
3135 goto unlock;
3139 link = getlink (page, x, y);
3140 if (link) {
3141 LINKTOVAL;
3143 else {
3144 fz_rect *b;
3145 fz_page_block *pageb;
3146 fz_stext_block *block;
3148 ensuretext (page);
3149 for (pageb = page->text->blocks;
3150 pageb < page->text->blocks + page->text->len;
3151 ++pageb) {
3152 fz_stext_line *line;
3153 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3154 block = pageb->u.text;
3156 b = &block->bbox;
3157 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3158 continue;
3160 for (line = block->lines;
3161 line < block->lines + block->len;
3162 ++line) {
3163 fz_stext_span *span;
3165 b = &line->bbox;
3166 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3167 continue;
3169 for (span = line->first_span; span; span = span->next) {
3170 int charnum;
3172 b = &span->bbox;
3173 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3174 continue;
3176 for (charnum = 0; charnum < span->len; ++charnum) {
3177 fz_rect bbox;
3178 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3179 b = &bbox;
3181 if (x >= b->x0 && x <= b->x1
3182 && y >= b->y0 && y <= b->y1) {
3183 fz_stext_style *style = span->text->style;
3184 const char *n2 =
3185 style->font
3186 ? style->font->name
3187 : "Span has no font name"
3189 FT_FaceRec *face = style->font->ft_face;
3190 if (face && face->family_name) {
3191 char *s;
3192 char *n1 = face->family_name;
3193 size_t l1 = strlen (n1);
3194 size_t l2 = strlen (n2);
3196 if (l1 != l2 || memcmp (n1, n2, l1)) {
3197 s = malloc (l1 + l2 + 2);
3198 if (s) {
3199 memcpy (s, n2, l2);
3200 s[l2] = '=';
3201 memcpy (s + l2 + 1, n1, l1 + 1);
3202 str_v = caml_copy_string (s);
3203 free (s);
3207 if (str_v == Val_unit) {
3208 str_v = caml_copy_string (n2);
3210 ret_v = caml_alloc_small (1, utext);
3211 Field (ret_v, 0) = str_v;
3212 goto unlock;
3219 unlock:
3220 unlock (__func__);
3222 done:
3223 CAMLreturn (ret_v);
3226 enum { mark_page, mark_block, mark_line, mark_word };
3228 static int uninteresting (int c)
3230 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3231 || ispunct (c);
3234 CAMLprim value ml_clearmark (value ptr_v)
3236 CAMLparam1 (ptr_v);
3237 char *s = String_val (ptr_v);
3238 struct page *page;
3240 if (trylock (__func__)) {
3241 goto done;
3244 page = parse_pointer (__func__, s);
3245 page->fmark.span = NULL;
3246 page->lmark.span = NULL;
3247 page->fmark.i = 0;
3248 page->lmark.i = 0;
3250 unlock (__func__);
3251 done:
3252 CAMLreturn (Val_unit);
3255 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3257 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3258 CAMLlocal1 (ret_v);
3259 fz_rect *b;
3260 struct page *page;
3261 fz_stext_line *line;
3262 fz_page_block *pageb;
3263 fz_stext_block *block;
3264 struct pagedim *pdim;
3265 int mark = Int_val (mark_v);
3266 char *s = String_val (ptr_v);
3267 int x = Int_val (x_v), y = Int_val (y_v);
3269 ret_v = Val_bool (0);
3270 if (trylock (__func__)) {
3271 goto done;
3274 page = parse_pointer (__func__, s);
3275 pdim = &state.pagedims[page->pdimno];
3277 ensuretext (page);
3279 if (mark == mark_page) {
3280 int i;
3281 fz_page_block *pb1 = NULL, *pb2 = NULL;
3283 for (i = 0; i < page->text->len; ++i) {
3284 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3285 pb1 = &page->text->blocks[i];
3286 break;
3289 if (!pb1) goto unlock;
3291 for (i = page->text->len - 1; i >= 0; --i) {
3292 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3293 pb2 = &page->text->blocks[i];
3294 break;
3297 if (!pb2) goto unlock;
3299 block = pb1->u.text;
3301 page->fmark.i = 0;
3302 page->fmark.span = block->lines->first_span;
3304 block = pb2->u.text;
3305 line = &block->lines[block->len - 1];
3306 page->lmark.i = line->last_span->len - 1;
3307 page->lmark.span = line->last_span;
3308 ret_v = Val_bool (1);
3309 goto unlock;
3312 x += pdim->bounds.x0;
3313 y += pdim->bounds.y0;
3315 for (pageb = page->text->blocks;
3316 pageb < page->text->blocks + page->text->len;
3317 ++pageb) {
3318 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3319 block = pageb->u.text;
3321 b = &block->bbox;
3322 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3323 continue;
3325 if (mark == mark_block) {
3326 page->fmark.i = 0;
3327 page->fmark.span = block->lines->first_span;
3329 line = &block->lines[block->len - 1];
3330 page->lmark.i = line->last_span->len - 1;
3331 page->lmark.span = line->last_span;
3332 ret_v = Val_bool (1);
3333 goto unlock;
3336 for (line = block->lines;
3337 line < block->lines + block->len;
3338 ++line) {
3339 fz_stext_span *span;
3341 b = &line->bbox;
3342 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3343 continue;
3345 if (mark == mark_line) {
3346 page->fmark.i = 0;
3347 page->fmark.span = line->first_span;
3349 page->lmark.i = line->last_span->len - 1;
3350 page->lmark.span = line->last_span;
3351 ret_v = Val_bool (1);
3352 goto unlock;
3355 for (span = line->first_span; span; span = span->next) {
3356 int charnum;
3358 b = &span->bbox;
3359 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3360 continue;
3362 for (charnum = 0; charnum < span->len; ++charnum) {
3363 fz_rect bbox;
3364 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3365 b = &bbox;
3367 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3368 /* unicode ftw */
3369 int charnum2, charnum3 = -1, charnum4 = -1;
3371 if (uninteresting (span->text[charnum].c)) goto unlock;
3373 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3374 if (uninteresting (span->text[charnum2].c)) {
3375 charnum3 = charnum2 + 1;
3376 break;
3379 if (charnum3 == -1) charnum3 = 0;
3381 charnum4 = charnum;
3382 for (charnum2 = charnum + 1;
3383 charnum2 < span->len;
3384 ++charnum2) {
3385 if (uninteresting (span->text[charnum2].c)) break;
3386 charnum4 = charnum2;
3389 page->fmark.i = charnum3;
3390 page->fmark.span = span;
3392 page->lmark.i = charnum4;
3393 page->lmark.span = span;
3394 ret_v = Val_bool (1);
3395 goto unlock;
3401 unlock:
3402 if (!Bool_val (ret_v)) {
3403 page->fmark.span = NULL;
3404 page->lmark.span = NULL;
3405 page->fmark.i = 0;
3406 page->lmark.i = 0;
3408 unlock (__func__);
3410 done:
3411 CAMLreturn (ret_v);
3414 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3416 CAMLparam3 (ptr_v, x_v, y_v);
3417 CAMLlocal2 (ret_v, res_v);
3418 fz_rect *b = NULL;
3419 struct page *page;
3420 fz_page_block *pageb;
3421 struct pagedim *pdim;
3422 char *s = String_val (ptr_v);
3423 int x = Int_val (x_v), y = Int_val (y_v);
3425 ret_v = Val_int (0);
3426 if (trylock (__func__)) {
3427 goto done;
3430 page = parse_pointer (__func__, s);
3431 pdim = &state.pagedims[page->pdimno];
3432 x += pdim->bounds.x0;
3433 y += pdim->bounds.y0;
3435 ensuretext (page);
3437 for (pageb = page->text->blocks;
3438 pageb < page->text->blocks + page->text->len;
3439 ++pageb) {
3440 switch (pageb->type) {
3441 case FZ_PAGE_BLOCK_TEXT:
3442 b = &pageb->u.text->bbox;
3443 break;
3445 case FZ_PAGE_BLOCK_IMAGE:
3446 b = &pageb->u.image->bbox;
3447 break;
3449 default:
3450 continue;
3453 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3454 break;
3455 b = NULL;
3457 if (b) {
3458 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3459 ret_v = caml_alloc_small (1, 1);
3460 Store_double_field (res_v, 0, b->x0);
3461 Store_double_field (res_v, 1, b->x1);
3462 Store_double_field (res_v, 2, b->y0);
3463 Store_double_field (res_v, 3, b->y1);
3464 Field (ret_v, 0) = res_v;
3466 unlock (__func__);
3468 done:
3469 CAMLreturn (ret_v);
3472 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3474 CAMLparam2 (ptr_v, rect_v);
3475 fz_rect b;
3476 struct page *page;
3477 struct pagedim *pdim;
3478 char *s = String_val (ptr_v);
3479 int i, x0, x1, y0, y1, fi, li;
3480 fz_stext_line *line;
3481 fz_page_block *pageb;
3482 fz_stext_block *block;
3483 fz_stext_span *span, *fspan, *lspan;
3485 if (trylock (__func__)) {
3486 goto done;
3489 page = parse_pointer (__func__, s);
3490 ensuretext (page);
3492 pdim = &state.pagedims[page->pdimno];
3493 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3494 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3495 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3496 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3498 if (y0 > y1) {
3499 int t = y0;
3500 y0 = y1;
3501 y1 = t;
3502 x0 = x1;
3503 x1 = t;
3506 fi = page->fmark.i;
3507 fspan = page->fmark.span;
3509 li = page->lmark.i;
3510 lspan = page->lmark.span;
3512 for (pageb = page->text->blocks;
3513 pageb < page->text->blocks + page->text->len;
3514 ++pageb) {
3515 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3516 block = pageb->u.text;
3517 for (line = block->lines;
3518 line < block->lines + block->len;
3519 ++line) {
3521 for (span = line->first_span; span; span = span->next) {
3522 for (i = 0; i < span->len; ++i) {
3523 fz_stext_char_bbox (state.ctx, &b, span, i);
3525 if (x0 >= b.x0 && x0 <= b.x1
3526 && y0 >= b.y0 && y0 <= b.y1) {
3527 fspan = span;
3528 fi = i;
3530 if (x1 >= b.x0 && x1 <= b.x1
3531 && y1 >= b.y0 && y1 <= b.y1) {
3532 lspan = span;
3533 li = i;
3539 if (x1 < x0 && fspan == lspan) {
3540 i = fi;
3541 span = fspan;
3543 fi = li;
3544 fspan = lspan;
3546 li = i;
3547 lspan = span;
3550 page->fmark.i = fi;
3551 page->fmark.span = fspan;
3553 page->lmark.i = li;
3554 page->lmark.span = lspan;
3556 unlock (__func__);
3558 done:
3559 CAMLreturn (Val_unit);
3562 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3564 char buf[4];
3565 int i, len, ret;
3567 for (i = a; i <= b; ++i) {
3568 len = fz_runetochar (buf, span->text[i].c);
3569 ret = fwrite (buf, len, 1, f);
3571 if (ret != 1) {
3572 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3573 len, ret, strerror (errno));
3574 return -1;
3577 return 0;
3580 #ifdef __CYGWIN__
3581 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3583 caml_failwith ("ml_popen not implemented under Cygwin");
3585 #else
3586 CAMLprim value ml_spawn (value command_v, value fds_v)
3588 CAMLparam2 (command_v, fds_v);
3589 CAMLlocal2 (l_v, tup_v);
3590 int ret, ret1;
3591 pid_t pid;
3592 char *msg = NULL;
3593 value earg_v = Nothing;
3594 posix_spawnattr_t attr;
3595 posix_spawn_file_actions_t fa;
3596 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3598 argv[2] = String_val (command_v);
3600 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3601 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3604 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3605 msg = "posix_spawnattr_init";
3606 goto fail1;
3609 #ifdef POSIX_SPAWN_USEVFORK
3610 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3611 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3612 goto fail;
3614 #endif
3616 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3617 int fd1, fd2;
3619 tup_v = Field (l_v, 0);
3620 fd1 = Int_val (Field (tup_v, 0));
3621 fd2 = Int_val (Field (tup_v, 1));
3622 if (fd2 < 0) {
3623 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3624 msg = "posix_spawn_file_actions_addclose";
3625 earg_v = tup_v;
3626 goto fail;
3629 else {
3630 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3631 msg = "posix_spawn_file_actions_adddup2";
3632 earg_v = tup_v;
3633 goto fail;
3638 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3639 msg = "posix_spawn";
3640 goto fail;
3643 fail:
3644 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3645 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3648 fail1:
3649 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3650 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3651 strerror (ret1));
3654 if (msg)
3655 unix_error (ret, msg, earg_v);
3657 CAMLreturn (Val_int (pid));
3659 #endif
3661 CAMLprim value ml_hassel (value ptr_v)
3663 CAMLparam1 (ptr_v);
3664 CAMLlocal1 (ret_v);
3665 struct page *page;
3666 char *s = String_val (ptr_v);
3668 ret_v = Val_bool (0);
3669 if (trylock (__func__)) {
3670 goto done;
3673 page = parse_pointer (__func__, s);
3674 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3675 unlock (__func__);
3676 done:
3677 CAMLreturn (ret_v);
3680 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3682 CAMLparam2 (fd_v, ptr_v);
3683 FILE *f;
3684 int seen = 0;
3685 struct page *page;
3686 fz_stext_line *line;
3687 fz_page_block *pageb;
3688 fz_stext_block *block;
3689 int fd = Int_val (fd_v);
3690 char *s = String_val (ptr_v);
3692 if (trylock (__func__)) {
3693 goto done;
3696 page = parse_pointer (__func__, s);
3698 if (!page->fmark.span || !page->lmark.span) {
3699 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3700 goto unlock;
3703 f = fdopen (fd, "w");
3704 if (!f) {
3705 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3706 fd, strerror (errno));
3707 f = stdout;
3710 for (pageb = page->text->blocks;
3711 pageb < page->text->blocks + page->text->len;
3712 ++pageb) {
3713 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3714 block = pageb->u.text;
3715 for (line = block->lines;
3716 line < block->lines + block->len;
3717 ++line) {
3718 fz_stext_span *span;
3720 for (span = line->first_span; span; span = span->next) {
3721 int a, b;
3723 seen |= span == page->fmark.span || span == page->lmark.span;
3724 a = span == page->fmark.span ? page->fmark.i : 0;
3725 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3727 if (seen) {
3728 if (pipespan (f, span, a, b)) {
3729 goto close;
3731 if (span == page->lmark.span) {
3732 goto close;
3734 if (span == line->last_span) {
3735 if (putc ('\n', f) == EOF) {
3736 fprintf (stderr,
3737 "failed break line on sel pipe: %s\n",
3738 strerror (errno));
3739 goto close;
3746 close:
3747 if (f != stdout) {
3748 int ret = fclose (f);
3749 fd = -1;
3750 if (ret == -1) {
3751 if (errno != ECHILD) {
3752 fprintf (stderr, "failed to close sel pipe: %s\n",
3753 strerror (errno));
3757 unlock:
3758 unlock (__func__);
3760 done:
3761 if (fd >= 0) {
3762 if (close (fd)) {
3763 fprintf (stderr, "failed to close sel pipe: %s\n",
3764 strerror (errno));
3767 CAMLreturn (Val_unit);
3770 CAMLprim value ml_getpdimrect (value pagedimno_v)
3772 CAMLparam1 (pagedimno_v);
3773 CAMLlocal1 (ret_v);
3774 int pagedimno = Int_val (pagedimno_v);
3775 fz_rect box;
3777 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3778 if (trylock (__func__)) {
3779 box = fz_empty_rect;
3781 else {
3782 box = state.pagedims[pagedimno].mediabox;
3783 unlock (__func__);
3786 Store_double_field (ret_v, 0, box.x0);
3787 Store_double_field (ret_v, 1, box.x1);
3788 Store_double_field (ret_v, 2, box.y0);
3789 Store_double_field (ret_v, 3, box.y1);
3791 CAMLreturn (ret_v);
3794 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3795 value dw_v, value cols_v)
3797 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3798 CAMLlocal1 (ret_v);
3799 int i;
3800 double zoom = -1.;
3801 double maxh = 0.0;
3802 struct pagedim *p;
3803 double winw = Int_val (winw_v);
3804 double winh = Int_val (winh_v);
3805 double dw = Int_val (dw_v);
3806 double cols = Int_val (cols_v);
3807 double pw = 1.0, ph = 1.0;
3809 if (trylock (__func__)) {
3810 goto done;
3813 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3814 double w = p->pagebox.x1 / cols;
3815 double h = p->pagebox.y1;
3816 if (h > maxh) {
3817 maxh = h;
3818 ph = h;
3819 if (state.fitmodel != FitProportional) pw = w;
3821 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3824 zoom = (((winh / ph) * pw) + dw) / winw;
3825 unlock (__func__);
3826 done:
3827 ret_v = caml_copy_double (zoom);
3828 CAMLreturn (ret_v);
3831 CAMLprim value ml_getmaxw (value unit_v)
3833 CAMLparam1 (unit_v);
3834 CAMLlocal1 (ret_v);
3835 int i;
3836 double maxw = -1.;
3837 struct pagedim *p;
3839 if (trylock (__func__)) {
3840 goto done;
3843 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3844 double w = p->pagebox.x1;
3845 maxw = fz_max (maxw, w);
3848 unlock (__func__);
3849 done:
3850 ret_v = caml_copy_double (maxw);
3851 CAMLreturn (ret_v);
3854 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3856 CAMLparam4 (pt_v, x_v, y_v, string_v);
3857 CAMLlocal1 (ret_v);
3858 int pt = Int_val(pt_v);
3859 int x = Int_val (x_v);
3860 int y = Int_val (y_v);
3861 double w;
3863 w = draw_string (state.face, pt, x, y, String_val (string_v));
3864 ret_v = caml_copy_double (w);
3865 CAMLreturn (ret_v);
3868 CAMLprim value ml_measure_string (value pt_v, value string_v)
3870 CAMLparam2 (pt_v, string_v);
3871 CAMLlocal1 (ret_v);
3872 int pt = Int_val (pt_v);
3873 double w;
3875 w = measure_string (state.face, pt, String_val (string_v));
3876 ret_v = caml_copy_double (w);
3877 CAMLreturn (ret_v);
3880 CAMLprim value ml_getpagebox (value opaque_v)
3882 CAMLparam1 (opaque_v);
3883 CAMLlocal1 (ret_v);
3884 fz_rect rect;
3885 fz_irect bbox;
3886 fz_matrix ctm;
3887 fz_device *dev;
3888 char *s = String_val (opaque_v);
3889 struct page *page = parse_pointer (__func__, s);
3891 ret_v = caml_alloc_tuple (4);
3892 dev = fz_new_bbox_device (state.ctx, &rect);
3893 dev->hints |= FZ_IGNORE_SHADE;
3895 ctm = pagectm (page);
3896 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3898 fz_drop_device (state.ctx, dev);
3899 fz_round_rect (&bbox, &rect);
3900 Field (ret_v, 0) = Val_int (bbox.x0);
3901 Field (ret_v, 1) = Val_int (bbox.y0);
3902 Field (ret_v, 2) = Val_int (bbox.x1);
3903 Field (ret_v, 3) = Val_int (bbox.y1);
3905 CAMLreturn (ret_v);
3908 CAMLprim value ml_setaalevel (value level_v)
3910 CAMLparam1 (level_v);
3912 state.aalevel = Int_val (level_v);
3913 CAMLreturn (Val_unit);
3916 #pragma GCC diagnostic push
3917 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3918 #include <X11/Xlib.h>
3919 #include <X11/cursorfont.h>
3920 #pragma GCC diagnostic pop
3922 #ifdef USE_EGL
3923 #include <EGL/egl.h>
3924 #else
3925 #include <GL/glx.h>
3926 #endif
3928 static const int shapes[] = {
3929 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3932 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3934 static struct {
3935 Window wid;
3936 Display *dpy;
3937 #ifdef USE_EGL
3938 EGLContext ctx;
3939 EGLConfig conf;
3940 EGLSurface win;
3941 EGLDisplay *edpy;
3942 #else
3943 GLXContext ctx;
3944 #endif
3945 XVisualInfo *visual;
3946 Cursor curs[CURS_COUNT];
3947 } glx;
3949 #ifdef VISAVIS
3950 static VisualID initvisual (void)
3952 /* On this system with: `Haswell-ULT Integrated Graphics
3953 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3954 using glX chosen visual and auto scrolling some document in
3955 fullscreen the power/energy-gpu is more than 1 joule bigger
3956 than when using hand picked visual that stands alone in glxinfo
3957 output: it's dead last in the list and it's the only one with
3958 `visual dep' (sic) of 32
3960 No clue what's going on here...
3962 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3964 XVisualInfo info;
3965 int ret = 1;
3967 info.depth = 32;
3968 info.class = TrueColor;
3969 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3970 &info, &ret);
3971 if (!ret || !glx.visual) {
3972 XCloseDisplay (glx.dpy);
3973 caml_failwith ("XGetVisualInfo");
3975 return glx.visual->visualid;
3977 #endif
3979 static void initcurs (void)
3981 for (size_t n = 0; n < CURS_COUNT; ++n) {
3982 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3986 CAMLprim void ml_setbgcol (value color_v)
3988 CAMLparam1 (color_v);
3989 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3990 CAMLreturn0;
3993 #ifdef USE_EGL
3994 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3996 CAMLparam3 (display_v, wid_v, screen_v);
3997 int major, minor;
3998 int num_conf;
3999 EGLint visid;
4000 EGLint attribs[] = {
4001 #ifdef VISAVIS
4002 EGL_NATIVE_VISUAL_ID, 0,
4003 #else
4004 EGL_DEPTH_SIZE, 24,
4005 #endif
4006 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
4007 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
4008 EGL_NONE
4010 EGLConfig conf;
4012 glx.dpy = XOpenDisplay (String_val (display_v));
4013 if (!glx.dpy) {
4014 caml_failwith ("XOpenDisplay");
4017 eglBindAPI (EGL_OPENGL_API);
4019 glx.edpy = eglGetDisplay (glx.dpy);
4020 if (glx.edpy == EGL_NO_DISPLAY) {
4021 caml_failwith ("eglGetDisplay");
4024 if (!eglInitialize (glx.edpy, &major, &minor)) {
4025 caml_failwith ("eglInitialize");
4028 #ifdef VISAVIS
4029 attribs[1] = visid = initvisual ();
4030 #endif
4032 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4033 !num_conf) {
4034 caml_failwith ("eglChooseConfig");
4037 glx.conf = conf;
4038 #ifndef VISAVIS
4039 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4040 EGL_NATIVE_VISUAL_ID, &visid)) {
4041 caml_failwith ("eglGetConfigAttrib");
4043 #endif
4044 initcurs ();
4046 glx.wid = Int_val (wid_v);
4047 CAMLreturn (Val_int (visid));
4050 CAMLprim value ml_glxcompleteinit (value unit_v)
4052 CAMLparam1 (unit_v);
4054 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4055 if (!glx.ctx) {
4056 caml_failwith ("eglCreateContext");
4059 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4060 glx.wid, NULL);
4061 if (glx.win == EGL_NO_SURFACE) {
4062 caml_failwith ("eglCreateWindowSurface");
4065 XFree (glx.visual);
4066 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4067 glx.ctx = NULL;
4068 caml_failwith ("eglMakeCurrent");
4070 CAMLreturn (Val_unit);
4072 #else
4073 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4075 CAMLparam3 (display_v, wid_v, screen_v);
4077 glx.dpy = XOpenDisplay (String_val (display_v));
4078 if (!glx.dpy) {
4079 caml_failwith ("XOpenDisplay");
4082 #ifdef VISAVIS
4083 initvisual ();
4084 #else
4085 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4086 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4087 if (!glx.visual) {
4088 XCloseDisplay (glx.dpy);
4089 caml_failwith ("glXChooseVisual");
4091 #endif
4092 initcurs ();
4094 glx.wid = Int_val (wid_v);
4095 CAMLreturn (Val_int (glx.visual->visualid));
4098 CAMLprim value ml_glxcompleteinit (value unit_v)
4100 CAMLparam1 (unit_v);
4102 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4103 if (!glx.ctx) {
4104 caml_failwith ("glXCreateContext");
4107 XFree (glx.visual);
4108 glx.visual = NULL;
4110 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4111 glXDestroyContext (glx.dpy, glx.ctx);
4112 glx.ctx = NULL;
4113 caml_failwith ("glXMakeCurrent");
4115 CAMLreturn (Val_unit);
4117 #endif
4119 CAMLprim value ml_setcursor (value cursor_v)
4121 CAMLparam1 (cursor_v);
4122 size_t cursn = Int_val (cursor_v);
4124 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4125 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4126 XFlush (glx.dpy);
4127 CAMLreturn (Val_unit);
4130 CAMLprim value ml_swapb (value unit_v)
4132 CAMLparam1 (unit_v);
4133 #ifdef USE_EGL
4134 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4135 caml_failwith ("eglSwapBuffers");
4137 #else
4138 glXSwapBuffers (glx.dpy, glx.wid);
4139 #endif
4140 CAMLreturn (Val_unit);
4143 #include "keysym2ucs.c"
4145 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4147 CAMLparam1 (keysym_v);
4148 CAMLlocal1 (str_v);
4149 KeySym keysym = Int_val (keysym_v);
4150 Rune rune;
4151 int len;
4152 char buf[5];
4154 rune = keysym2ucs (keysym);
4155 len = fz_runetochar (buf, rune);
4156 buf[len] = 0;
4157 str_v = caml_copy_string (buf);
4158 CAMLreturn (str_v);
4161 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4163 CAMLprim value ml_platform (value unit_v)
4165 CAMLparam1 (unit_v);
4166 CAMLlocal2 (tup_v, arr_v);
4167 int platid = piunknown;
4168 struct utsname buf;
4170 #if defined __linux__
4171 platid = pilinux;
4172 #elif defined __CYGWIN__
4173 platid = picygwin;
4174 #elif defined __DragonFly__ || defined __FreeBSD__
4175 || defined __OpenBSD__ || defined __NetBSD__
4176 platid = pibsd;
4177 #elif defined __sun__
4178 platid = pisun;
4179 #elif defined __APPLE__
4180 platid = piosx;
4181 #endif
4182 if (uname (&buf)) err (1, "uname");
4184 tup_v = caml_alloc_tuple (2);
4186 char const *sar[] = {
4187 buf.sysname,
4188 buf.release,
4189 buf.version,
4190 buf.machine,
4191 NULL
4193 arr_v = caml_copy_string_array (sar);
4195 Field (tup_v, 0) = Val_int (platid);
4196 Field (tup_v, 1) = arr_v;
4197 CAMLreturn (tup_v);
4200 CAMLprim value ml_cloexec (value fd_v)
4202 CAMLparam1 (fd_v);
4203 int fd = Int_val (fd_v);
4205 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4206 uerror ("fcntl", Nothing);
4208 CAMLreturn (Val_unit);
4211 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4213 CAMLparam2 (w_v, h_v);
4214 CAMLlocal1 (ret_v);
4215 struct bo *pbo;
4216 int w = Int_val (w_v);
4217 int h = Int_val (h_v);
4218 int cs = Int_val (cs_v);
4220 if (state.bo_usable) {
4221 pbo = calloc (sizeof (*pbo), 1);
4222 if (!pbo) {
4223 err (1, "calloc pbo");
4226 switch (cs) {
4227 case 0:
4228 case 1:
4229 pbo->size = w*h*4;
4230 break;
4231 case 2:
4232 pbo->size = w*h*2;
4233 break;
4234 default:
4235 errx (1, "%s: invalid colorspace %d", __func__, cs);
4238 state.glGenBuffersARB (1, &pbo->id);
4239 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4240 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4241 NULL, GL_STREAM_DRAW);
4242 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4243 GL_READ_WRITE);
4244 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4245 if (!pbo->ptr) {
4246 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4247 state.glDeleteBuffersARB (1, &pbo->id);
4248 free (pbo);
4249 ret_v = caml_copy_string ("0");
4251 else {
4252 int res;
4253 char *s;
4255 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4256 if (res < 0) {
4257 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4259 s = malloc (res+1);
4260 if (!s) {
4261 err (1, "malloc %d bytes failed", res+1);
4263 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4264 if (res < 0) {
4265 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4267 ret_v = caml_copy_string (s);
4268 free (s);
4271 else {
4272 ret_v = caml_copy_string ("0");
4274 CAMLreturn (ret_v);
4277 CAMLprim value ml_freepbo (value s_v)
4279 CAMLparam1 (s_v);
4280 char *s = String_val (s_v);
4281 struct tile *tile = parse_pointer (__func__, s);
4283 if (tile->pbo) {
4284 state.glDeleteBuffersARB (1, &tile->pbo->id);
4285 tile->pbo->id = -1;
4286 tile->pbo->ptr = NULL;
4287 tile->pbo->size = -1;
4289 CAMLreturn (Val_unit);
4292 CAMLprim value ml_unmappbo (value s_v)
4294 CAMLparam1 (s_v);
4295 char *s = String_val (s_v);
4296 struct tile *tile = parse_pointer (__func__, s);
4298 if (tile->pbo) {
4299 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4300 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4301 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4303 tile->pbo->ptr = NULL;
4304 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4306 CAMLreturn (Val_unit);
4309 static void setuppbo (void)
4311 #ifdef USE_EGL
4312 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4313 #else
4314 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4315 #endif
4316 state.bo_usable = GGPA (glBindBufferARB)
4317 && GGPA (glUnmapBufferARB)
4318 && GGPA (glMapBufferARB)
4319 && GGPA (glBufferDataARB)
4320 && GGPA (glGenBuffersARB)
4321 && GGPA (glDeleteBuffersARB);
4322 #undef GGPA
4325 CAMLprim value ml_bo_usable (value unit_v)
4327 CAMLparam1 (unit_v);
4328 CAMLreturn (Val_bool (state.bo_usable));
4331 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4333 CAMLparam3 (ptr_v, x_v, y_v);
4334 CAMLlocal2 (ret_v, tup_v);
4335 struct page *page;
4336 char *s = String_val (ptr_v);
4337 int x = Int_val (x_v), y = Int_val (y_v);
4338 struct pagedim *pdim;
4339 fz_point p;
4340 fz_matrix ctm;
4342 page = parse_pointer (__func__, s);
4343 pdim = &state.pagedims[page->pdimno];
4345 ret_v = Val_int (0);
4346 if (trylock (__func__)) {
4347 goto done;
4350 if (pdf_specifics (state.ctx, state.doc)) {
4351 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4352 ctm = state.pagedims[page->pdimno].tctm;
4354 else {
4355 ctm = fz_identity;
4357 p.x = x + pdim->bounds.x0;
4358 p.y = y + pdim->bounds.y0;
4360 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4361 fz_invert_matrix (&ctm, &ctm);
4362 fz_transform_point (&p, &ctm);
4364 tup_v = caml_alloc_tuple (2);
4365 ret_v = caml_alloc_small (1, 1);
4366 Field (tup_v, 0) = Val_int (p.x);
4367 Field (tup_v, 1) = Val_int (p.y);
4368 Field (ret_v, 0) = tup_v;
4370 unlock (__func__);
4371 done:
4372 CAMLreturn (ret_v);
4375 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4376 value x_v, value y_v)
4378 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4379 CAMLlocal1 (ret_v);
4380 struct page *page;
4381 char *s = String_val (ptr_v);
4382 int pageno = Int_val (pageno_v);
4383 int pdimno = Int_val (pdimno_v);
4384 double x = Double_val (x_v), y = Double_val (y_v);
4385 struct pagedim *pdim;
4386 fz_point p;
4387 fz_matrix ctm;
4389 ret_v = Val_int (0);
4390 lock (__func__);
4392 if (!*s) {
4393 page = loadpage (pageno, pdimno);
4395 else {
4396 page = parse_pointer (__func__, s);
4398 pdim = &state.pagedims[pdimno];
4400 if (pdf_specifics (state.ctx, state.doc)) {
4401 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4402 ctm = state.pagedims[page->pdimno].tctm;
4404 else {
4405 ctm = fz_identity;
4407 p.x = x + pdim->bounds.x0;
4408 p.y = y + pdim->bounds.y0;
4410 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4411 fz_transform_point (&p, &ctm);
4413 ret_v = caml_alloc_tuple (2);
4414 Field (ret_v, 0) = caml_copy_double (p.x);
4415 Field (ret_v, 1) = caml_copy_double (p.y);
4417 if (!*s) {
4418 freepage (page);
4420 unlock (__func__);
4421 CAMLreturn (ret_v);
4424 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4425 value contents_v)
4427 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4428 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4430 if (pdf) {
4431 pdf_annot *annot;
4432 struct page *page;
4433 fz_point p;
4434 char *s = String_val (ptr_v);
4436 page = parse_pointer (__func__, s);
4437 annot = pdf_create_annot (state.ctx, pdf,
4438 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4439 p.x = Int_val (x_v);
4440 p.y = Int_val (y_v);
4441 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4442 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4443 state.dirty = 1;
4445 CAMLreturn (Val_unit);
4448 CAMLprim value ml_delannot (value ptr_v, value n_v)
4450 CAMLparam2 (ptr_v, n_v);
4451 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4453 if (pdf) {
4454 struct page *page;
4455 char *s = String_val (ptr_v);
4456 struct slink *slink;
4458 page = parse_pointer (__func__, s);
4459 slink = &page->slinks[Int_val (n_v)];
4460 pdf_delete_annot (state.ctx, pdf,
4461 (pdf_page *) page->fzpage,
4462 (pdf_annot *) slink->u.annot);
4463 state.dirty = 1;
4465 CAMLreturn (Val_unit);
4468 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4470 CAMLparam3 (ptr_v, n_v, str_v);
4471 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4473 if (pdf) {
4474 struct page *page;
4475 char *s = String_val (ptr_v);
4476 struct slink *slink;
4478 page = parse_pointer (__func__, s);
4479 slink = &page->slinks[Int_val (n_v)];
4480 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4481 String_val (str_v));
4482 state.dirty = 1;
4484 CAMLreturn (Val_unit);
4487 CAMLprim value ml_hasunsavedchanges (value unit_v)
4489 CAMLparam1 (unit_v);
4490 CAMLreturn (Val_bool (state.dirty));
4493 CAMLprim value ml_savedoc (value path_v)
4495 CAMLparam1 (path_v);
4496 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4498 if (pdf) {
4499 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4501 CAMLreturn (Val_unit);
4504 static void makestippletex (void)
4506 const char pixels[] = "\xff\xff\0\0";
4507 glGenTextures (1, &state.stid);
4508 glBindTexture (GL_TEXTURE_1D, state.stid);
4509 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4510 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4511 glTexImage1D (
4512 GL_TEXTURE_1D,
4514 GL_ALPHA,
4517 GL_ALPHA,
4518 GL_UNSIGNED_BYTE,
4519 pixels
4523 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4525 return caml_copy_string (FZ_VERSION);
4528 #ifdef USE_FONTCONFIG
4529 static struct {
4530 int inited;
4531 FcConfig *config;
4532 } fc;
4534 static fz_font *fc_load_system_font_func (fz_context *ctx,
4535 const char *name,
4536 int bold,
4537 int italic,
4538 int UNUSED_ATTR needs_exact_metrics)
4540 char *buf;
4541 size_t i, size;
4542 fz_font *font;
4543 FcChar8 *path;
4544 FcResult result;
4545 FcPattern *pat, *pat1;
4547 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4548 name, bold, italic, needs_exact_metrics);
4549 if (!fc.inited) {
4550 fc.inited = 1;
4551 fc.config = FcInitLoadConfigAndFonts ();
4552 if (!fc.config) {
4553 lprintf ("FcInitLoadConfigAndFonts failed\n");
4554 return NULL;
4557 if (!fc.config) return NULL;
4559 size = strlen (name);
4560 if (bold) size += sizeof (":bold") - 1;
4561 if (italic) size += sizeof (":italic") - 1;
4562 size += 1;
4564 buf = malloc (size);
4565 if (!buf) {
4566 err (1, "malloc %zu failed", size);
4569 strcpy (buf, name);
4570 if (bold && italic) {
4571 strcat (buf, ":bold:italic");
4573 else {
4574 if (bold) strcat (buf, ":bold");
4575 if (italic) strcat (buf, ":italic");
4577 for (i = 0; i < size; ++i) {
4578 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4581 lprintf ("fcbuf=%s\n", buf);
4582 pat = FcNameParse ((FcChar8 *) buf);
4583 if (!pat) {
4584 printd ("emsg FcNameParse failed\n");
4585 free (buf);
4586 return NULL;
4589 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4590 printd ("emsg FcConfigSubstitute failed\n");
4591 free (buf);
4592 return NULL;
4594 FcDefaultSubstitute (pat);
4596 pat1 = FcFontMatch (fc.config, pat, &result);
4597 if (!pat1) {
4598 printd ("emsg FcFontMatch failed\n");
4599 FcPatternDestroy (pat);
4600 free (buf);
4601 return NULL;
4604 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4605 printd ("emsg FcPatternGetString failed\n");
4606 FcPatternDestroy (pat);
4607 FcPatternDestroy (pat1);
4608 free (buf);
4609 return NULL;
4612 #if 0
4613 printd ("emsg name=%s path=%s\n", name, path);
4614 #endif
4615 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4616 FcPatternDestroy (pat);
4617 FcPatternDestroy (pat1);
4618 free (buf);
4619 return font;
4621 #endif
4623 CAMLprim value ml_init (value csock_v, value params_v)
4625 CAMLparam2 (csock_v, params_v);
4626 CAMLlocal2 (trim_v, fuzz_v);
4627 int ret;
4628 int texcount;
4629 char *fontpath;
4630 int colorspace;
4631 int mustoresize;
4632 int haspboext;
4634 state.csock = Int_val (csock_v);
4635 state.rotate = Int_val (Field (params_v, 0));
4636 state.fitmodel = Int_val (Field (params_v, 1));
4637 trim_v = Field (params_v, 2);
4638 texcount = Int_val (Field (params_v, 3));
4639 state.sliceheight = Int_val (Field (params_v, 4));
4640 mustoresize = Int_val (Field (params_v, 5));
4641 colorspace = Int_val (Field (params_v, 6));
4642 fontpath = String_val (Field (params_v, 7));
4644 if (caml_string_length (Field (params_v, 8)) > 0) {
4645 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4647 if (!state.trimcachepath) {
4648 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4649 strerror (errno));
4652 haspboext = Bool_val (Field (params_v, 9));
4654 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4655 fz_register_document_handlers (state.ctx);
4657 #ifdef USE_FONTCONFIG
4658 if (Bool_val (Field (params_v, 10))) {
4659 fz_install_load_system_font_funcs (
4660 state.ctx, fc_load_system_font_func, NULL
4663 #endif
4665 state.trimmargins = Bool_val (Field (trim_v, 0));
4666 fuzz_v = Field (trim_v, 1);
4667 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4668 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4669 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4670 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4672 set_tex_params (colorspace);
4674 if (*fontpath) {
4675 #ifndef USE_FONTCONFIG
4676 state.face = load_font (fontpath);
4677 #else
4678 FcChar8 *path;
4679 FcResult result;
4680 char *buf = fontpath;
4681 FcPattern *pat, *pat1;
4683 fc.inited = 1;
4684 fc.config = FcInitLoadConfigAndFonts ();
4685 if (!fc.config) {
4686 errx (1, "FcInitLoadConfigAndFonts failed");
4689 pat = FcNameParse ((FcChar8 *) buf);
4690 if (!pat) {
4691 errx (1, "FcNameParse failed");
4694 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4695 errx (1, "FcConfigSubstitute failed");
4697 FcDefaultSubstitute (pat);
4699 pat1 = FcFontMatch (fc.config, pat, &result);
4700 if (!pat1) {
4701 errx (1, "FcFontMatch failed");
4704 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4705 errx (1, "FcPatternGetString failed");
4708 state.face = load_font ((char *) path);
4709 FcPatternDestroy (pat);
4710 FcPatternDestroy (pat1);
4711 #endif
4713 else {
4714 int len;
4715 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4716 0, 0, &len);
4717 state.face = load_builtin_font (data, len);
4719 if (!state.face) _exit (1);
4721 realloctexts (texcount);
4723 if (haspboext) {
4724 setuppbo ();
4727 makestippletex ();
4729 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4730 if (ret) {
4731 errx (1, "pthread_create: %s", strerror (ret));
4734 CAMLreturn (Val_unit);