Fix vertical positioning with pivot zooming
[llpp.git] / link.c
blob621f8040cd3a32218da559f3fe930efc79f52034
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 && !defined __clang__
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 (!page) return;
648 if (!pdim->tctmready) {
649 fz_rect realbox, mediabox;
650 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
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 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
660 fz_invert_matrix (&im, &page_ctm);
661 fz_concat (&ctm, &im, &ctm1);
662 pdim->tctm = ctm;
663 pdim->tctmready = 1;
667 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
669 fz_matrix ctm, tm;
670 int pdimno = pdim - state.pagedims;
672 if (pdf_specifics (state.ctx, state.doc)) {
673 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
674 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
676 else {
677 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
678 fz_concat (&ctm, &tm, &pdim->ctm);
680 return ctm;
683 static fz_matrix pagectm (struct page *page)
685 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
688 static void *loadpage (int pageno, int pindex)
690 fz_device *dev;
691 struct page *page;
693 page = calloc (sizeof (struct page), 1);
694 if (!page) {
695 err (1, "calloc page %d", pageno);
698 page->dlist = fz_new_display_list (state.ctx, NULL);
699 dev = fz_new_list_device (state.ctx, page->dlist);
700 fz_try (state.ctx) {
701 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
702 fz_run_page (state.ctx, page->fzpage, dev,
703 &fz_identity, NULL);
705 fz_catch (state.ctx) {
706 page->fzpage = NULL;
708 fz_close_device (state.ctx, dev);
709 fz_drop_device (state.ctx, dev);
711 page->pdimno = pindex;
712 page->pageno = pageno;
713 page->sgen = state.gen;
714 page->agen = state.gen;
715 page->tgen = state.gen;
716 return page;
719 static struct tile *alloctile (int h)
721 int i;
722 int slicecount;
723 size_t tilesize;
724 struct tile *tile;
726 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
727 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
728 tile = calloc (tilesize, 1);
729 if (!tile) {
730 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
732 for (i = 0; i < slicecount; ++i) {
733 int sh = fz_mini (h, state.sliceheight);
734 tile->slices[i].h = sh;
735 tile->slices[i].texindex = -1;
736 h -= sh;
738 tile->slicecount = slicecount;
739 tile->sliceheight = state.sliceheight;
740 return tile;
743 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
744 struct bo *pbo)
746 fz_rect rect;
747 fz_irect bbox;
748 fz_matrix ctm;
749 fz_device *dev;
750 struct tile *tile;
751 struct pagedim *pdim;
753 tile = alloctile (h);
754 pdim = &state.pagedims[page->pdimno];
756 bbox = pdim->bounds;
757 bbox.x0 += x;
758 bbox.y0 += y;
759 bbox.x1 = bbox.x0 + w;
760 bbox.y1 = bbox.y0 + h;
762 if (state.pig) {
763 if (state.pig->w == w
764 && state.pig->h == h
765 && state.pig->colorspace == state.colorspace) {
766 tile->pixmap = state.pig;
767 tile->pixmap->x = bbox.x0;
768 tile->pixmap->y = bbox.y0;
770 else {
771 fz_drop_pixmap (state.ctx, state.pig);
773 state.pig = NULL;
775 if (!tile->pixmap) {
776 if (pbo) {
777 tile->pixmap =
778 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
779 &bbox, 1, pbo->ptr);
780 tile->pbo = pbo;
782 else {
783 tile->pixmap =
784 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
788 tile->w = w;
789 tile->h = h;
790 clearpixmap (tile->pixmap);
792 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
793 ctm = pagectm (page);
794 fz_rect_from_irect (&rect, &bbox);
795 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
796 fz_close_device (state.ctx, dev);
797 fz_drop_device (state.ctx, dev);
799 return tile;
802 #ifdef CACHE_PAGEREFS
803 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
804 thanks to Robin Watts */
805 static void
806 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
808 fz_context *ctx = state.ctx; /* doc->ctx; */
809 pdf_obj *kids;
810 int i, len;
812 if (state.pdflut.idx == state.pagecount) return;
814 kids = pdf_dict_gets (ctx, node, "Kids");
815 len = pdf_array_len (ctx, kids);
817 if (len == 0)
818 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
820 if (pdf_mark_obj (ctx, node))
821 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
822 for (i = 0; i < len; i++) {
823 pdf_obj *kid = pdf_array_get (ctx, kids, i);
824 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
825 if (*type
826 ? !strcmp (type, "Pages")
827 : pdf_dict_gets (ctx, kid, "Kids")
828 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
829 pdf_collect_pages (doc, kid);
831 else {
832 if (*type
833 ? strcmp (type, "Page") != 0
834 : !pdf_dict_gets (ctx, kid, "MediaBox"))
835 fz_warn (ctx, "non-page object in page tree (%s)", type);
836 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
839 pdf_unmark_obj (ctx, node);
842 static void
843 pdf_load_page_objs (pdf_document *doc)
845 pdf_obj *root = pdf_dict_gets (state.ctx,
846 pdf_trailer (state.ctx, doc), "Root");
847 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
849 if (!node)
850 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
852 state.pdflut.idx = 0;
853 pdf_collect_pages (doc, node);
855 #endif
857 static void initpdims (int wthack)
859 double start, end;
860 FILE *trimf = NULL;
861 fz_rect rootmediabox;
862 int pageno, trim, show;
863 int trimw = 0, cxcount;
864 fz_context *ctx = state.ctx;
865 pdf_document *pdf = pdf_specifics (ctx, state.doc);
867 fz_var (trimw);
868 fz_var (trimf);
869 fz_var (cxcount);
870 start = now ();
872 if (state.trimmargins && state.trimcachepath) {
873 trimf = fopen (state.trimcachepath, "rb");
874 if (!trimf) {
875 trimf = fopen (state.trimcachepath, "wb");
876 trimw = 1;
880 if (state.trimmargins || pdf || !state.cxack)
881 cxcount = state.pagecount;
882 else
883 cxcount = fz_mini (state.pagecount, 1);
885 if (pdf) {
886 pdf_obj *obj;
887 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
888 "Root/Pages/MediaBox");
889 pdf_to_rect (ctx, obj, &rootmediabox);
892 #ifdef CACHE_PAGEREFS
893 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
894 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
895 if (!state.pdflut.objs) {
896 err (1, "malloc pageobjs %zu %d %zu failed",
897 sizeof (*state.pdflut.objs), cxcount,
898 sizeof (*state.pdflut.objs) * cxcount);
900 state.pdflut.count = cxcount;
901 pdf_load_page_objs (pdf);
902 state.pdflut.pdf = pdf;
904 #endif
906 for (pageno = 0; pageno < cxcount; ++pageno) {
907 int rotate = 0;
908 struct pagedim *p;
909 fz_rect mediabox;
911 fz_var (rotate);
912 if (pdf) {
913 pdf_obj *pageref, *pageobj;
915 #ifdef CACHE_PAGEREFS
916 pageref = state.pdflut.objs[pageno];
917 #else
918 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
919 #endif
920 pageobj = pdf_resolve_indirect (ctx, pageref);
921 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
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_device *dev;
934 fz_matrix ctm, page_ctm;
936 dev = fz_new_bbox_device (ctx, &rect);
937 dev->hints |= FZ_IGNORE_SHADE;
938 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
939 fz_invert_matrix (&ctm, &page_ctm);
940 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
941 fz_close_device (ctx, dev);
942 fz_drop_device (ctx, dev);
944 rect.x0 += state.trimfuzz.x0;
945 rect.x1 += state.trimfuzz.x1;
946 rect.y0 += state.trimfuzz.y0;
947 rect.y1 += state.trimfuzz.y1;
948 fz_transform_rect (&rect, &ctm);
949 fz_intersect_rect (&rect, &mediabox);
951 if (!fz_is_empty_rect (&rect)) {
952 mediabox = rect;
955 obj = pdf_new_array (ctx, pdf, 4);
956 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
957 mediabox.x0));
958 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
959 mediabox.y0));
960 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
961 mediabox.x1));
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.y1));
964 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
966 else {
967 mediabox.x0 = pdf_to_real (ctx,
968 pdf_array_get (ctx, obj, 0));
969 mediabox.y0 = pdf_to_real (ctx,
970 pdf_array_get (ctx, obj, 1));
971 mediabox.x1 = pdf_to_real (ctx,
972 pdf_array_get (ctx, obj, 2));
973 mediabox.y1 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 3));
977 fz_drop_page (ctx, &page->super);
978 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
979 if (show) {
980 printd ("progress %f Trimming %d",
981 (double) (pageno + 1) / state.pagecount,
982 pageno + 1);
985 fz_catch (ctx) {
986 fprintf (stderr, "failed to load page %d\n", pageno+1);
989 else {
990 int empty = 0;
991 fz_rect cropbox;
993 pdf_to_rect (ctx,
994 pdf_dict_gets (ctx, pageobj, "MediaBox"),
995 &mediabox);
996 if (fz_is_empty_rect (&mediabox)) {
997 mediabox.x0 = 0;
998 mediabox.y0 = 0;
999 mediabox.x1 = 612;
1000 mediabox.y1 = 792;
1001 empty = 1;
1004 pdf_to_rect (ctx,
1005 pdf_dict_gets (ctx, pageobj, "CropBox"),
1006 &cropbox);
1007 if (!fz_is_empty_rect (&cropbox)) {
1008 if (empty) {
1009 mediabox = cropbox;
1011 else {
1012 fz_intersect_rect (&mediabox, &cropbox);
1015 else {
1016 if (empty) {
1017 if (fz_is_empty_rect (&rootmediabox)) {
1018 fprintf (stderr,
1019 "cannot find page size for page %d\n",
1020 pageno+1);
1022 else {
1023 mediabox = rootmediabox;
1029 else {
1030 if (state.trimmargins && trimw) {
1031 fz_page *page;
1033 fz_try (ctx) {
1034 page = fz_load_page (ctx, state.doc, pageno);
1035 fz_bound_page (ctx, page, &mediabox);
1036 if (state.trimmargins) {
1037 fz_rect rect;
1038 fz_device *dev;
1040 dev = fz_new_bbox_device (ctx, &rect);
1041 dev->hints |= FZ_IGNORE_SHADE;
1042 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1043 fz_close_device (ctx, dev);
1044 fz_drop_device (ctx, dev);
1046 rect.x0 += state.trimfuzz.x0;
1047 rect.x1 += state.trimfuzz.x1;
1048 rect.y0 += state.trimfuzz.y0;
1049 rect.y1 += state.trimfuzz.y1;
1050 fz_intersect_rect (&rect, &mediabox);
1052 if (!fz_is_empty_rect (&rect)) {
1053 mediabox = rect;
1056 fz_drop_page (ctx, page);
1057 if (!state.cxack) {
1058 printd ("progress %f loading %d",
1059 (double) (pageno + 1) / state.pagecount,
1060 pageno + 1);
1063 fz_catch (ctx) {
1065 if (trimf) {
1066 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1067 if (n - 1) {
1068 err (1, "fwrite trim mediabox");
1072 else {
1073 if (trimf) {
1074 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1075 if (n - 1) {
1076 err (1, "fread trim mediabox %d", pageno);
1079 else {
1080 fz_page *page;
1081 fz_try (ctx) {
1082 page = fz_load_page (ctx, state.doc, pageno);
1083 fz_bound_page (ctx, page, &mediabox);
1084 fz_drop_page (ctx, page);
1086 show = !state.trimmargins && pageno % 20 == 0;
1087 if (show) {
1088 printd ("progress %f Gathering dimensions %d",
1089 (double) (pageno) / state.pagecount,
1090 pageno);
1093 fz_catch (ctx) {
1094 fprintf (stderr, "failed to load page %d\n", pageno);
1100 if (state.pagedimcount == 0
1101 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1102 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1103 size_t size;
1105 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1106 state.pagedims = realloc (state.pagedims, size);
1107 if (!state.pagedims) {
1108 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1109 size, state.pagedimcount + 1);
1112 p = &state.pagedims[state.pagedimcount++];
1113 p->rotate = rotate;
1114 p->mediabox = mediabox;
1115 p->pageno = pageno;
1118 end = now ();
1119 if (!wthack) {
1120 printd ("progress 1 %s %d pages in %f seconds",
1121 state.trimmargins ? "Trimmed" : "Processed",
1122 state.pagecount, end - start);
1124 state.trimanew = 0;
1125 if (trimf) {
1126 if (fclose (trimf)) {
1127 err (1, "fclose");
1132 static void layout (void)
1134 int pindex;
1135 fz_rect box;
1136 fz_matrix ctm, rm;
1137 struct pagedim *p = p;
1138 double zw, w, maxw = 0.0, zoom = zoom;
1140 if (state.pagedimcount == 0) return;
1142 switch (state.fitmodel) {
1143 case FitProportional:
1144 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1145 double x0, x1;
1147 p = &state.pagedims[pindex];
1148 fz_rotate (&rm, p->rotate + state.rotate);
1149 box = p->mediabox;
1150 fz_transform_rect (&box, &rm);
1152 x0 = fz_min (box.x0, box.x1);
1153 x1 = fz_max (box.x0, box.x1);
1155 w = x1 - x0;
1156 maxw = fz_max (w, maxw);
1157 zoom = state.w / maxw;
1159 break;
1161 case FitPage:
1162 maxw = state.w;
1163 break;
1165 case FitWidth:
1166 break;
1168 default:
1169 ARSERT (0 && state.fitmodel);
1172 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1173 fz_rect rect;
1174 fz_matrix tm, sm;
1176 p = &state.pagedims[pindex];
1177 fz_rotate (&ctm, state.rotate);
1178 fz_rotate (&rm, p->rotate + state.rotate);
1179 box = p->mediabox;
1180 fz_transform_rect (&box, &rm);
1181 w = box.x1 - box.x0;
1182 switch (state.fitmodel) {
1183 case FitProportional:
1184 p->left = ((maxw - w) * zoom) / 2.0;
1185 break;
1186 case FitPage:
1188 double zh, h;
1189 zw = maxw / w;
1190 h = box.y1 - box.y0;
1191 zh = state.h / h;
1192 zoom = fz_min (zw, zh);
1193 p->left = (maxw - (w * zoom)) / 2.0;
1195 break;
1196 case FitWidth:
1197 p->left = 0;
1198 zoom = state.w / w;
1199 break;
1202 fz_scale (&p->zoomctm, zoom, zoom);
1203 fz_concat (&ctm, &p->zoomctm, &ctm);
1205 fz_rotate (&rm, p->rotate);
1206 p->pagebox = p->mediabox;
1207 fz_transform_rect (&p->pagebox, &rm);
1208 p->pagebox.x1 -= p->pagebox.x0;
1209 p->pagebox.y1 -= p->pagebox.y0;
1210 p->pagebox.x0 = 0;
1211 p->pagebox.y0 = 0;
1212 rect = p->pagebox;
1213 fz_transform_rect (&rect, &ctm);
1214 fz_round_rect (&p->bounds, &rect);
1215 p->ctm = ctm;
1217 fz_translate (&tm, 0, -p->mediabox.y1);
1218 fz_scale (&sm, zoom, -zoom);
1219 fz_concat (&ctm, &tm, &sm);
1220 fz_concat (&p->lctm, &ctm, &rm);
1222 p->tctmready = 0;
1225 do {
1226 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1227 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1228 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1229 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1230 int boundw = x1 - x0;
1231 int boundh = y1 - y0;
1233 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1234 } while (p-- != state.pagedims);
1237 static
1238 struct anchor { int n; int x; int y; int w; int h; }
1239 desttoanchor (fz_link_dest *dest)
1241 int i;
1242 struct anchor a;
1243 struct pagedim *pdim = state.pagedims;
1245 a.n = -1;
1246 a.x = 0;
1247 a.y = 0;
1248 for (i = 0; i < state.pagedimcount; ++i) {
1249 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1250 break;
1251 pdim = &state.pagedims[i];
1253 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1254 fz_point p;
1255 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1256 p.x = dest->ld.gotor.lt.x;
1257 else
1258 p.x = 0.0;
1259 p.y = dest->ld.gotor.lt.y;
1260 fz_transform_point (&p, &pdim->lctm);
1261 a.x = p.x;
1262 a.y = p.y;
1264 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1265 double x0, x1, y0, y1;
1267 x0 = fz_min (pdim->bounds.x0, pdim->bounds.x1);
1268 x1 = fz_max (pdim->bounds.x0, pdim->bounds.x1);
1269 a.w = x1 - x0;
1270 y0 = fz_min (pdim->bounds.y0, pdim->bounds.y1);
1271 y1 = fz_max (pdim->bounds.y0, pdim->bounds.y1);
1272 a.h = y1 - y0;
1273 a.n = dest->ld.gotor.page;
1275 return a;
1278 static void recurse_outline (fz_outline *outline, int level)
1280 while (outline) {
1281 switch (outline->dest.kind) {
1282 case FZ_LINK_GOTO:
1284 struct anchor a = desttoanchor (&outline->dest);
1286 if (a.n >= 0) {
1287 printd ("o %d %d %d %d %s",
1288 level, a.n, a.y, a.h, outline->title);
1291 break;
1293 case FZ_LINK_URI:
1294 printd ("ou %d %" FMT_s " %s %s", level,
1295 strlen (outline->title), outline->title,
1296 outline->dest.ld.uri.uri);
1297 break;
1299 case FZ_LINK_NONE:
1300 printd ("on %d %s", level, outline->title);
1301 break;
1303 default:
1304 printd ("emsg Unhandled outline kind %d for %s\n",
1305 outline->dest.kind, outline->title);
1306 break;
1308 if (outline->down) {
1309 recurse_outline (outline->down, level + 1);
1311 outline = outline->next;
1315 static void process_outline (void)
1317 fz_outline *outline;
1319 if (!state.needoutline || !state.pagedimcount) return;
1321 state.needoutline = 0;
1322 outline = fz_load_outline (state.ctx, state.doc);
1323 if (outline) {
1324 recurse_outline (outline, 0);
1325 fz_drop_outline (state.ctx, outline);
1329 static char *strofspan (fz_stext_span *span)
1331 char *p;
1332 char utf8[10];
1333 fz_stext_char *ch;
1334 size_t size = 0, cap = 80;
1336 p = malloc (cap + 1);
1337 if (!p) return NULL;
1339 for (ch = span->text; ch < span->text + span->len; ++ch) {
1340 int n = fz_runetochar (utf8, ch->c);
1341 if (size + n > cap) {
1342 cap *= 2;
1343 p = realloc (p, cap + 1);
1344 if (!p) return NULL;
1347 memcpy (p + size, utf8, n);
1348 size += n;
1350 p[size] = 0;
1351 return p;
1354 static int matchspan (regex_t *re, fz_stext_span *span,
1355 int stop, int pageno, double start)
1357 int ret;
1358 char *p;
1359 regmatch_t rm;
1360 int a, b, c;
1361 fz_rect sb, eb;
1362 fz_point p1, p2, p3, p4;
1364 p = strofspan (span);
1365 if (!p) return -1;
1367 ret = regexec (re, p, 1, &rm, 0);
1368 if (ret) {
1369 free (p);
1370 if (ret != REG_NOMATCH) {
1371 size_t size;
1372 char errbuf[80];
1373 size = regerror (ret, re, errbuf, sizeof (errbuf));
1374 printd ("msg regexec error `%.*s'",
1375 (int) size, errbuf);
1376 return -1;
1378 return 0;
1380 else {
1381 int l = span->len;
1383 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1384 c += fz_runelen (span->text[a].c);
1386 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1387 c += fz_runelen (span->text[b].c);
1390 if (fz_runelen (span->text[b].c) > 1) {
1391 b = fz_maxi (0, b-1);
1394 fz_stext_char_bbox (state.ctx, &sb, span, a);
1395 fz_stext_char_bbox (state.ctx, &eb, span, b);
1397 p1.x = sb.x0;
1398 p1.y = sb.y0;
1399 p2.x = eb.x1;
1400 p2.y = sb.y0;
1401 p3.x = eb.x1;
1402 p3.y = eb.y1;
1403 p4.x = sb.x0;
1404 p4.y = eb.y1;
1406 if (!stop) {
1407 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1408 pageno, 1,
1409 p1.x, p1.y,
1410 p2.x, p2.y,
1411 p3.x, p3.y,
1412 p4.x, p4.y);
1414 printd ("progress 1 found at %d `%.*s' in %f sec",
1415 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1416 now () - start);
1418 else {
1419 printd ("match %d %d %f %f %f %f %f %f %f %f",
1420 pageno, 2,
1421 p1.x, p1.y,
1422 p2.x, p2.y,
1423 p3.x, p3.y,
1424 p4.x, p4.y);
1426 free (p);
1427 return 1;
1431 static int compareblocks (const void *l, const void *r)
1433 fz_stext_block const *ls = l;
1434 fz_stext_block const *rs = r;
1435 return ls->bbox.y0 - rs->bbox.y0;
1438 /* wishful thinking function */
1439 static void search (regex_t *re, int pageno, int y, int forward)
1441 int i, j;
1442 fz_device *tdev;
1443 fz_stext_page *text;
1444 fz_stext_sheet *sheet;
1445 struct pagedim *pdim, *pdimprev;
1446 int stop = 0, niters = 0;
1447 double start, end;
1448 fz_page *page;
1450 start = now ();
1451 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1452 if (niters++ == 5) {
1453 niters = 0;
1454 if (hasdata ()) {
1455 printd ("progress 1 attention requested aborting search at %d",
1456 pageno);
1457 stop = 1;
1459 else {
1460 printd ("progress %f searching in page %d",
1461 (double) (pageno + 1) / state.pagecount,
1462 pageno);
1465 pdimprev = NULL;
1466 for (i = 0; i < state.pagedimcount; ++i) {
1467 pdim = &state.pagedims[i];
1468 if (pdim->pageno == pageno) {
1469 goto found;
1471 if (pdim->pageno > pageno) {
1472 pdim = pdimprev;
1473 goto found;
1475 pdimprev = pdim;
1477 pdim = pdimprev;
1478 found:
1480 sheet = fz_new_stext_sheet (state.ctx);
1481 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1482 tdev = fz_new_stext_device (state.ctx, sheet, text);
1484 page = fz_load_page (state.ctx, state.doc, pageno);
1486 fz_matrix ctm = pagectm1 (page, pdim);
1487 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1490 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1491 fz_close_device (state.ctx, tdev);
1492 fz_drop_device (state.ctx, tdev);
1494 for (j = 0; j < text->len; ++j) {
1495 int k;
1496 fz_page_block *pb;
1497 fz_stext_block *block;
1499 pb = &text->blocks[forward ? j : text->len - 1 - j];
1500 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1501 block = pb->u.text;
1503 for (k = 0; k < block->len; ++k) {
1504 fz_stext_line *line;
1505 fz_stext_span *span;
1507 if (forward) {
1508 line = &block->lines[k];
1509 if (line->bbox.y0 < y + 1) continue;
1511 else {
1512 line = &block->lines[block->len - 1 - k];
1513 if (line->bbox.y0 > y - 1) continue;
1516 for (span = line->first_span; span; span = span->next) {
1517 switch (matchspan (re, span, stop, pageno, start)) {
1518 case 0: break;
1519 case 1: stop = 1; break;
1520 case -1: stop = 1; goto endloop;
1525 if (forward) {
1526 pageno += 1;
1527 y = 0;
1529 else {
1530 pageno -= 1;
1531 y = INT_MAX;
1533 endloop:
1534 fz_drop_stext_page (state.ctx, text);
1535 fz_drop_stext_sheet (state.ctx, sheet);
1536 fz_drop_page (state.ctx, page);
1538 end = now ();
1539 if (!stop) {
1540 printd ("progress 1 no matches %f sec", end - start);
1542 printd ("clearrects");
1545 static void set_tex_params (int colorspace)
1547 union {
1548 unsigned char b;
1549 unsigned int s;
1550 } endianness = {1};
1552 switch (colorspace) {
1553 case 0:
1554 state.texiform = GL_RGBA8;
1555 state.texform = GL_RGBA;
1556 state.texty = GL_UNSIGNED_BYTE;
1557 state.colorspace = fz_device_rgb (state.ctx);
1558 break;
1559 case 1:
1560 state.texiform = GL_RGBA8;
1561 state.texform = GL_BGRA;
1562 state.texty = endianness.s > 1
1563 ? GL_UNSIGNED_INT_8_8_8_8
1564 : GL_UNSIGNED_INT_8_8_8_8_REV;
1565 state.colorspace = fz_device_bgr (state.ctx);
1566 break;
1567 case 2:
1568 state.texiform = GL_LUMINANCE_ALPHA;
1569 state.texform = GL_LUMINANCE_ALPHA;
1570 state.texty = GL_UNSIGNED_BYTE;
1571 state.colorspace = fz_device_gray (state.ctx);
1572 break;
1573 default:
1574 errx (1, "invalid colorspce %d", colorspace);
1578 static void realloctexts (int texcount)
1580 size_t size;
1582 if (texcount == state.texcount) return;
1584 if (texcount < state.texcount) {
1585 glDeleteTextures (state.texcount - texcount,
1586 state.texids + texcount);
1589 size = texcount * sizeof (*state.texids);
1590 state.texids = realloc (state.texids, size);
1591 if (!state.texids) {
1592 err (1, "realloc texids %" FMT_s, size);
1595 size = texcount * sizeof (*state.texowners);
1596 state.texowners = realloc (state.texowners, size);
1597 if (!state.texowners) {
1598 err (1, "realloc texowners %" FMT_s, size);
1600 if (texcount > state.texcount) {
1601 int i;
1603 glGenTextures (texcount - state.texcount,
1604 state.texids + state.texcount);
1605 for (i = state.texcount; i < texcount; ++i) {
1606 state.texowners[i].w = -1;
1607 state.texowners[i].slice = NULL;
1610 state.texcount = texcount;
1611 state.texindex = 0;
1614 static char *mbtoutf8 (char *s)
1616 char *p, *r;
1617 wchar_t *tmp;
1618 size_t i, ret, len;
1620 len = mbstowcs (NULL, s, strlen (s));
1621 if (len == 0) {
1622 return s;
1624 else {
1625 if (len == (size_t) -1) {
1626 return s;
1630 tmp = malloc (len * sizeof (wchar_t));
1631 if (!tmp) {
1632 return s;
1635 ret = mbstowcs (tmp, s, len);
1636 if (ret == (size_t) -1) {
1637 free (tmp);
1638 return s;
1641 len = 0;
1642 for (i = 0; i < ret; ++i) {
1643 len += fz_runelen (tmp[i]);
1646 p = r = malloc (len + 1);
1647 if (!r) {
1648 free (tmp);
1649 return s;
1652 for (i = 0; i < ret; ++i) {
1653 p += fz_runetochar (p, tmp[i]);
1655 *p = 0;
1656 free (tmp);
1657 return r;
1660 CAMLprim value ml_mbtoutf8 (value s_v)
1662 CAMLparam1 (s_v);
1663 CAMLlocal1 (ret_v);
1664 char *s, *r;
1666 s = String_val (s_v);
1667 r = mbtoutf8 (s);
1668 if (r == s) {
1669 ret_v = s_v;
1671 else {
1672 ret_v = caml_copy_string (r);
1673 free (r);
1675 CAMLreturn (ret_v);
1678 static void * mainloop (void UNUSED_ATTR *unused)
1680 char *p = NULL;
1681 int len, ret, oldlen = 0;
1683 fz_var (p);
1684 fz_var (oldlen);
1685 for (;;) {
1686 len = readlen (state.csock);
1687 if (len == 0) {
1688 errx (1, "readlen returned 0");
1691 if (oldlen < len + 1) {
1692 p = realloc (p, len + 1);
1693 if (!p) {
1694 err (1, "realloc %d failed", len + 1);
1696 oldlen = len + 1;
1698 readdata (state.csock, p, len);
1699 p[len] = 0;
1701 if (!strncmp ("open", p, 4)) {
1702 int wthack, off, ok = 0;
1703 char *password;
1704 char *filename;
1705 char *utf8filename;
1706 size_t filenamelen;
1708 fz_var (ok);
1709 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1710 if (ret != 2) {
1711 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1714 filename = p + 5 + off;
1715 filenamelen = strlen (filename);
1716 password = filename + filenamelen + 1;
1718 lock ("open");
1719 fz_try (state.ctx) {
1720 ok = openxref (filename, password);
1722 fz_catch (state.ctx) {
1723 utf8filename = mbtoutf8 (filename);
1724 printd ("msg Could not open %s", utf8filename);
1726 if (ok) {
1727 pdfinfo ();
1728 initpdims (wthack);
1730 unlock ("open");
1732 if (ok) {
1733 if (!wthack) {
1734 utf8filename = mbtoutf8 (filename);
1735 printd ("msg Opened %s (press h/F1 to get help)",
1736 utf8filename);
1737 if (utf8filename != filename) {
1738 free (utf8filename);
1741 state.needoutline = 1;
1744 else if (!strncmp ("cs", p, 2)) {
1745 int i, colorspace;
1747 ret = sscanf (p + 2, " %d", &colorspace);
1748 if (ret != 1) {
1749 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1751 lock ("cs");
1752 set_tex_params (colorspace);
1753 for (i = 0; i < state.texcount; ++i) {
1754 state.texowners[i].w = -1;
1755 state.texowners[i].slice = NULL;
1757 unlock ("cs");
1759 else if (!strncmp ("freepage", p, 8)) {
1760 void *ptr;
1762 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1763 if (ret != 1) {
1764 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1766 freepage (ptr);
1768 else if (!strncmp ("freetile", p, 8)) {
1769 void *ptr;
1771 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1772 if (ret != 1) {
1773 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1775 freetile (ptr);
1777 else if (!strncmp ("search", p, 6)) {
1778 int icase, pageno, y, len2, forward;
1779 char *pattern;
1780 regex_t re;
1782 ret = sscanf (p + 6, " %d %d %d %d,%n",
1783 &icase, &pageno, &y, &forward, &len2);
1784 if (ret != 4) {
1785 errx (1, "malformed search `%s' ret=%d", p, ret);
1788 pattern = p + 6 + len2;
1789 ret = regcomp (&re, pattern,
1790 REG_EXTENDED | (icase ? REG_ICASE : 0));
1791 if (ret) {
1792 char errbuf[80];
1793 size_t size;
1795 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1796 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1798 else {
1799 search (&re, pageno, y, forward);
1800 regfree (&re);
1803 else if (!strncmp ("geometry", p, 8)) {
1804 int w, h, fitmodel;
1806 printd ("clear");
1807 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1808 if (ret != 3) {
1809 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1812 lock ("geometry");
1813 state.h = h;
1814 if (w != state.w) {
1815 int i;
1816 state.w = w;
1817 for (i = 0; i < state.texcount; ++i) {
1818 state.texowners[i].slice = NULL;
1821 state.fitmodel = fitmodel;
1822 layout ();
1823 process_outline ();
1825 state.gen++;
1826 unlock ("geometry");
1827 printd ("continue %d", state.pagecount);
1829 else if (!strncmp ("reqlayout", p, 9)) {
1830 char *nameddest;
1831 int rotate, off, h;
1832 unsigned int fitmodel;
1833 pdf_document *pdf;
1835 printd ("clear");
1836 ret = sscanf (p + 9, " %d %u %d %n",
1837 &rotate, &fitmodel, &h, &off);
1838 if (ret != 3) {
1839 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1841 lock ("reqlayout");
1842 pdf = pdf_specifics (state.ctx, state.doc);
1843 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1844 state.gen += 1;
1846 state.rotate = rotate;
1847 state.fitmodel = fitmodel;
1848 state.h = h;
1849 layout ();
1850 process_outline ();
1852 nameddest = p + 9 + off;
1853 if (pdf && nameddest && *nameddest) {
1854 struct anchor a;
1855 fz_link_dest dest;
1856 pdf_obj *needle, *obj;
1858 needle = pdf_new_string (state.ctx, pdf, nameddest,
1859 strlen (nameddest));
1860 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1861 if (obj) {
1862 dest = pdf_parse_link_dest (state.ctx, pdf,
1863 FZ_LINK_GOTO, obj);
1865 a = desttoanchor (&dest);
1866 if (a.n >= 0) {
1867 printd ("a %d %d %d", a.n, a.x, a.y);
1869 else {
1870 printd ("emsg failed to parse destination `%s'\n",
1871 nameddest);
1874 else {
1875 printd ("emsg destination `%s' not found\n",
1876 nameddest);
1878 pdf_drop_obj (state.ctx, needle);
1881 state.gen++;
1882 unlock ("reqlayout");
1883 printd ("continue %d", state.pagecount);
1885 else if (!strncmp ("page", p, 4)) {
1886 double a, b;
1887 struct page *page;
1888 int pageno, pindex;
1890 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1891 if (ret != 2) {
1892 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1895 lock ("page");
1896 a = now ();
1897 page = loadpage (pageno, pindex);
1898 b = now ();
1899 unlock ("page");
1901 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1903 else if (!strncmp ("tile", p, 4)) {
1904 int x, y, w, h;
1905 struct page *page;
1906 struct tile *tile;
1907 double a, b;
1908 void *data;
1910 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1911 SCN_ptr_cast (&page), &x, &y, &w, &h,
1912 SCN_ptr_cast (&data));
1913 if (ret != 6) {
1914 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1917 lock ("tile");
1918 a = now ();
1919 tile = rendertile (page, x, y, w, h, data);
1920 b = now ();
1921 unlock ("tile");
1923 printd ("tile %d %d %" FMT_ptr " %u %f",
1924 x, y,
1925 FMT_ptr_cast (tile),
1926 tile->w * tile->h * tile->pixmap->n,
1927 b - a);
1929 else if (!strncmp ("trimset", p, 7)) {
1930 fz_irect fuzz;
1931 int trimmargins;
1933 ret = sscanf (p + 7, " %d %d %d %d %d",
1934 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1935 if (ret != 5) {
1936 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1938 lock ("trimset");
1939 state.trimmargins = trimmargins;
1940 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1941 state.trimanew = 1;
1942 state.trimfuzz = fuzz;
1944 unlock ("trimset");
1946 else if (!strncmp ("settrim", p, 7)) {
1947 fz_irect fuzz;
1948 int trimmargins;
1950 ret = sscanf (p + 7, " %d %d %d %d %d",
1951 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1952 if (ret != 5) {
1953 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1955 printd ("clear");
1956 lock ("settrim");
1957 state.trimmargins = trimmargins;
1958 state.needoutline = 1;
1959 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1960 state.trimanew = 1;
1961 state.trimfuzz = fuzz;
1963 state.pagedimcount = 0;
1964 free (state.pagedims);
1965 state.pagedims = NULL;
1966 initpdims (0);
1967 layout ();
1968 process_outline ();
1969 unlock ("settrim");
1970 printd ("continue %d", state.pagecount);
1972 else if (!strncmp ("sliceh", p, 6)) {
1973 int h;
1975 ret = sscanf (p + 6, " %d", &h);
1976 if (ret != 1) {
1977 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1979 if (h != state.sliceheight) {
1980 int i;
1982 state.sliceheight = h;
1983 for (i = 0; i < state.texcount; ++i) {
1984 state.texowners[i].w = -1;
1985 state.texowners[i].h = -1;
1986 state.texowners[i].slice = NULL;
1990 else if (!strncmp ("interrupt", p, 9)) {
1991 printd ("vmsg interrupted");
1993 else {
1994 errx (1, "unknown command %.*s", len, p);
1997 return 0;
2000 CAMLprim value ml_realloctexts (value texcount_v)
2002 CAMLparam1 (texcount_v);
2003 int ok;
2005 if (trylock (__func__)) {
2006 ok = 0;
2007 goto done;
2009 realloctexts (Int_val (texcount_v));
2010 ok = 1;
2011 unlock (__func__);
2013 done:
2014 CAMLreturn (Val_bool (ok));
2017 static void recti (int x0, int y0, int x1, int y1)
2019 GLfloat *v = state.vertices;
2021 glVertexPointer (2, GL_FLOAT, 0, v);
2022 v[0] = x0; v[1] = y0;
2023 v[2] = x1; v[3] = y0;
2024 v[4] = x0; v[5] = y1;
2025 v[6] = x1; v[7] = y1;
2026 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2029 static void showsel (struct page *page, int ox, int oy)
2031 int seen = 0;
2032 fz_irect bbox;
2033 fz_rect rect;
2034 fz_stext_line *line;
2035 fz_page_block *pageb;
2036 fz_stext_block *block;
2037 struct mark first, last;
2038 unsigned char selcolor[] = {15,15,15,140};
2040 first = page->fmark;
2041 last = page->lmark;
2043 if (!first.span || !last.span) return;
2045 glEnable (GL_BLEND);
2046 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2047 glColor4ubv (selcolor);
2049 ox += state.pagedims[page->pdimno].bounds.x0;
2050 oy += state.pagedims[page->pdimno].bounds.y0;
2051 for (pageb = page->text->blocks;
2052 pageb < page->text->blocks + page->text->len;
2053 ++pageb) {
2054 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2055 block = pageb->u.text;
2057 for (line = block->lines;
2058 line < block->lines + block->len;
2059 ++line) {
2060 fz_stext_span *span;
2061 rect = fz_empty_rect;
2063 for (span = line->first_span; span; span = span->next) {
2064 int i, j, k;
2065 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2067 j = 0;
2068 k = span->len - 1;
2070 if (span == page->fmark.span && span == page->lmark.span) {
2071 seen = 1;
2072 j = fz_mini (first.i, last.i);
2073 k = fz_maxi (first.i, last.i);
2075 else {
2076 if (span == first.span) {
2077 seen = 1;
2078 j = first.i;
2080 else if (span == last.span) {
2081 seen = 1;
2082 k = last.i;
2086 if (seen) {
2087 for (i = j; i <= k; ++i) {
2088 fz_rect bbox1;
2089 fz_union_rect (&rect,
2090 fz_stext_char_bbox (state.ctx, &bbox1,
2091 span, i));
2093 fz_round_rect (&bbox, &rect);
2094 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2095 bbox.x0,
2096 bbox.y0,
2097 bbox.x1,
2098 bbox.y1,
2099 oy, ox);
2101 recti (bbox.x0 + ox, bbox.y0 + oy,
2102 bbox.x1 + ox, bbox.y1 + oy);
2103 if (span == last.span) {
2104 goto done;
2106 rect = fz_empty_rect;
2111 done:
2112 glDisable (GL_BLEND);
2115 #include "glfont.c"
2117 static void stipplerect (fz_matrix *m,
2118 fz_point *p1,
2119 fz_point *p2,
2120 fz_point *p3,
2121 fz_point *p4,
2122 GLfloat *texcoords,
2123 GLfloat *vertices)
2125 fz_transform_point (p1, m);
2126 fz_transform_point (p2, m);
2127 fz_transform_point (p3, m);
2128 fz_transform_point (p4, m);
2130 float w, h, s, t;
2132 w = p2->x - p1->x;
2133 h = p2->y - p1->y;
2134 t = hypotf (w, h) * .25f;
2136 w = p3->x - p2->x;
2137 h = p3->y - p2->y;
2138 s = hypotf (w, h) * .25f;
2140 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2141 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2143 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2144 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2146 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2147 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2149 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2150 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2152 glDrawArrays (GL_LINES, 0, 8);
2155 static void solidrect (fz_matrix *m,
2156 fz_point *p1,
2157 fz_point *p2,
2158 fz_point *p3,
2159 fz_point *p4,
2160 GLfloat *vertices)
2162 fz_transform_point (p1, m);
2163 fz_transform_point (p2, m);
2164 fz_transform_point (p3, m);
2165 fz_transform_point (p4, m);
2166 vertices[0] = p1->x; vertices[1] = p1->y;
2167 vertices[2] = p2->x; vertices[3] = p2->y;
2169 vertices[4] = p3->x; vertices[5] = p3->y;
2170 vertices[6] = p4->x; vertices[7] = p4->y;
2171 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2174 static void highlightlinks (struct page *page, int xoff, int yoff)
2176 int i;
2177 fz_matrix ctm, tm, pm;
2178 fz_link *link, *links;
2179 GLfloat *texcoords = state.texcoords;
2180 GLfloat *vertices = state.vertices;
2182 links = fz_load_links (state.ctx, page->fzpage);
2184 glEnable (GL_TEXTURE_1D);
2185 glEnable (GL_BLEND);
2186 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2187 glBindTexture (GL_TEXTURE_1D, state.stid);
2189 xoff -= state.pagedims[page->pdimno].bounds.x0;
2190 yoff -= state.pagedims[page->pdimno].bounds.y0;
2191 fz_translate (&tm, xoff, yoff);
2192 pm = pagectm (page);
2193 fz_concat (&ctm, &pm, &tm);
2195 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2196 glVertexPointer (2, GL_FLOAT, 0, vertices);
2198 for (link = links; link; link = link->next) {
2199 fz_point p1, p2, p3, p4;
2201 p1.x = link->rect.x0;
2202 p1.y = link->rect.y0;
2204 p2.x = link->rect.x1;
2205 p2.y = link->rect.y0;
2207 p3.x = link->rect.x1;
2208 p3.y = link->rect.y1;
2210 p4.x = link->rect.x0;
2211 p4.y = link->rect.y1;
2213 switch (link->dest.kind) {
2214 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2215 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2216 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2217 default: glColor3ub (0, 0, 0); break;
2219 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2222 for (i = 0; i < page->annotcount; ++i) {
2223 fz_point p1, p2, p3, p4;
2224 struct annot *annot = &page->annots[i];
2226 p1.x = annot->bbox.x0;
2227 p1.y = annot->bbox.y0;
2229 p2.x = annot->bbox.x1;
2230 p2.y = annot->bbox.y0;
2232 p3.x = annot->bbox.x1;
2233 p3.y = annot->bbox.y1;
2235 p4.x = annot->bbox.x0;
2236 p4.y = annot->bbox.y1;
2238 glColor3ub (0, 0, 128);
2239 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2242 glDisable (GL_BLEND);
2243 glDisable (GL_TEXTURE_1D);
2246 static int compareslinks (const void *l, const void *r)
2248 struct slink const *ls = l;
2249 struct slink const *rs = r;
2250 if (ls->bbox.y0 == rs->bbox.y0) {
2251 return rs->bbox.x0 - rs->bbox.x0;
2253 return ls->bbox.y0 - rs->bbox.y0;
2256 static void droptext (struct page *page)
2258 if (page->text) {
2259 fz_drop_stext_page (state.ctx, page->text);
2260 page->fmark.i = -1;
2261 page->lmark.i = -1;
2262 page->fmark.span = NULL;
2263 page->lmark.span = NULL;
2264 page->text = NULL;
2266 if (page->sheet) {
2267 fz_drop_stext_sheet (state.ctx, page->sheet);
2268 page->sheet = NULL;
2272 static void dropannots (struct page *page)
2274 if (page->annots) {
2275 free (page->annots);
2276 page->annots = NULL;
2277 page->annotcount = 0;
2281 static void ensureannots (struct page *page)
2283 int i, count = 0;
2284 size_t annotsize = sizeof (*page->annots);
2285 fz_annot *annot;
2287 if (state.gen != page->agen) {
2288 dropannots (page);
2289 page->agen = state.gen;
2291 if (page->annots) return;
2293 for (annot = fz_first_annot (state.ctx, page->fzpage);
2294 annot;
2295 annot = fz_next_annot (state.ctx, annot)) {
2296 count++;
2299 if (count > 0) {
2300 page->annotcount = count;
2301 page->annots = calloc (count, annotsize);
2302 if (!page->annots) {
2303 err (1, "calloc annots %d", count);
2306 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2307 annot;
2308 annot = fz_next_annot (state.ctx, annot), i++) {
2309 fz_rect rect;
2311 fz_bound_annot (state.ctx, annot, &rect);
2312 page->annots[i].annot = annot;
2313 fz_round_rect (&page->annots[i].bbox, &rect);
2318 static void dropslinks (struct page *page)
2320 if (page->slinks) {
2321 free (page->slinks);
2322 page->slinks = NULL;
2323 page->slinkcount = 0;
2327 static void ensureslinks (struct page *page)
2329 fz_matrix ctm;
2330 int i, count;
2331 size_t slinksize = sizeof (*page->slinks);
2332 fz_link *link, *links;
2334 ensureannots (page);
2335 if (state.gen != page->sgen) {
2336 dropslinks (page);
2337 page->sgen = state.gen;
2339 if (page->slinks) return;
2341 links = fz_load_links (state.ctx, page->fzpage);
2342 ctm = pagectm (page);
2344 count = page->annotcount;
2345 for (link = links; link; link = link->next) {
2346 count++;
2348 if (count > 0) {
2349 int j;
2351 page->slinkcount = count;
2352 page->slinks = calloc (count, slinksize);
2353 if (!page->slinks) {
2354 err (1, "calloc slinks %d", count);
2357 for (i = 0, link = links; link; ++i, link = link->next) {
2358 fz_rect rect;
2360 rect = link->rect;
2361 fz_transform_rect (&rect, &ctm);
2362 page->slinks[i].tag = SLINK;
2363 page->slinks[i].u.link = link;
2364 fz_round_rect (&page->slinks[i].bbox, &rect);
2366 for (j = 0; j < page->annotcount; ++j, ++i) {
2367 fz_rect rect;
2368 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2369 fz_transform_rect (&rect, &ctm);
2370 fz_round_rect (&page->slinks[i].bbox, &rect);
2372 page->slinks[i].tag = SANNOT;
2373 page->slinks[i].u.annot = page->annots[j].annot;
2375 qsort (page->slinks, count, slinksize, compareslinks);
2379 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2380 static void fmt_linkn (char *s, unsigned int u)
2382 unsigned int len; unsigned int q;
2383 unsigned int zma = 'z' - 'a' + 1;
2384 len = 1; q = u;
2385 while (q > zma - 1) { ++len; q /= zma; }
2386 if (s) {
2387 s += len;
2388 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2389 /* handles u == 0 */
2391 s[len] = 0;
2394 static void highlightslinks (struct page *page, int xoff, int yoff,
2395 int noff, char *targ, int tlen, int hfsize)
2397 int i;
2398 char buf[40];
2399 struct slink *slink;
2400 double x0, y0, x1, y1, w;
2402 ensureslinks (page);
2403 glColor3ub (0xc3, 0xb0, 0x91);
2404 for (i = 0; i < page->slinkcount; ++i) {
2405 fmt_linkn (buf, i + noff);
2406 if (!tlen || !strncmp (targ, buf, tlen)) {
2407 slink = &page->slinks[i];
2409 x0 = slink->bbox.x0 + xoff - 5;
2410 y1 = slink->bbox.y0 + yoff - 5;
2411 y0 = y1 + 10 + hfsize;
2412 w = measure_string (state.face, hfsize, buf);
2413 x1 = x0 + w + 10;
2414 recti (x0, y0, x1, y1);
2418 glEnable (GL_BLEND);
2419 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2420 glEnable (GL_TEXTURE_2D);
2421 glColor3ub (0, 0, 0);
2422 for (i = 0; i < page->slinkcount; ++i) {
2423 fmt_linkn (buf, i + noff);
2424 if (!tlen || !strncmp (targ, buf, tlen)) {
2425 slink = &page->slinks[i];
2427 x0 = slink->bbox.x0 + xoff;
2428 y0 = slink->bbox.y0 + yoff + hfsize;
2429 draw_string (state.face, hfsize, x0, y0, buf);
2432 glDisable (GL_TEXTURE_2D);
2433 glDisable (GL_BLEND);
2436 static void uploadslice (struct tile *tile, struct slice *slice)
2438 int offset;
2439 struct slice *slice1;
2440 unsigned char *texdata;
2442 offset = 0;
2443 for (slice1 = tile->slices; slice != slice1; slice1++) {
2444 offset += slice1->h * tile->w * tile->pixmap->n;
2446 if (slice->texindex != -1 && slice->texindex < state.texcount
2447 && state.texowners[slice->texindex].slice == slice) {
2448 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2450 else {
2451 int subimage = 0;
2452 int texindex = state.texindex++ % state.texcount;
2454 if (state.texowners[texindex].w == tile->w) {
2455 if (state.texowners[texindex].h >= slice->h) {
2456 subimage = 1;
2458 else {
2459 state.texowners[texindex].h = slice->h;
2462 else {
2463 state.texowners[texindex].h = slice->h;
2466 state.texowners[texindex].w = tile->w;
2467 state.texowners[texindex].slice = slice;
2468 slice->texindex = texindex;
2470 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2471 #if TEXT_TYPE == GL_TEXTURE_2D
2472 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2473 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2474 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2475 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2476 #endif
2477 if (tile->pbo) {
2478 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2479 texdata = 0;
2481 else {
2482 texdata = tile->pixmap->samples;
2484 if (subimage) {
2485 glTexSubImage2D (TEXT_TYPE,
2489 tile->w,
2490 slice->h,
2491 state.texform,
2492 state.texty,
2493 texdata+offset
2496 else {
2497 glTexImage2D (TEXT_TYPE,
2499 state.texiform,
2500 tile->w,
2501 slice->h,
2503 state.texform,
2504 state.texty,
2505 texdata+offset
2508 if (tile->pbo) {
2509 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2514 CAMLprim value ml_begintiles (value unit_v)
2516 CAMLparam1 (unit_v);
2517 glEnable (TEXT_TYPE);
2518 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2519 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2520 CAMLreturn (unit_v);
2523 CAMLprim value ml_endtiles (value unit_v)
2525 CAMLparam1 (unit_v);
2526 glDisable (TEXT_TYPE);
2527 CAMLreturn (unit_v);
2530 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2532 CAMLparam2 (args_v, ptr_v);
2533 int dispx = Int_val (Field (args_v, 0));
2534 int dispy = Int_val (Field (args_v, 1));
2535 int dispw = Int_val (Field (args_v, 2));
2536 int disph = Int_val (Field (args_v, 3));
2537 int tilex = Int_val (Field (args_v, 4));
2538 int tiley = Int_val (Field (args_v, 5));
2539 char *s = String_val (ptr_v);
2540 struct tile *tile = parse_pointer (__func__, s);
2541 int slicey, firstslice;
2542 struct slice *slice;
2543 GLfloat *texcoords = state.texcoords;
2544 GLfloat *vertices = state.vertices;
2546 firstslice = tiley / tile->sliceheight;
2547 slice = &tile->slices[firstslice];
2548 slicey = tiley % tile->sliceheight;
2550 while (disph > 0) {
2551 int dh;
2553 dh = slice->h - slicey;
2554 dh = fz_mini (disph, dh);
2555 uploadslice (tile, slice);
2557 texcoords[0] = tilex; texcoords[1] = slicey;
2558 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2559 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2560 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2562 vertices[0] = dispx; vertices[1] = dispy;
2563 vertices[2] = dispx+dispw; vertices[3] = dispy;
2564 vertices[4] = dispx; vertices[5] = dispy+dh;
2565 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2567 #if TEXT_TYPE == GL_TEXTURE_2D
2568 for (int i = 0; i < 8; ++i) {
2569 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2571 #endif
2573 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2574 dispy += dh;
2575 disph -= dh;
2576 slice++;
2577 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2578 slicey = 0;
2580 CAMLreturn (Val_unit);
2583 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2585 fz_matrix ctm, tm, pm;
2586 fz_point p1, p2, p3, p4;
2587 GLfloat *vertices = state.vertices;
2588 double *v = (double *) rects_v;
2590 xoff -= state.pagedims[page->pdimno].bounds.x0;
2591 yoff -= state.pagedims[page->pdimno].bounds.y0;
2592 fz_translate (&tm, xoff, yoff);
2593 pm = pagectm (page);
2594 fz_concat (&ctm, &pm, &tm);
2596 glEnable (GL_BLEND);
2597 glVertexPointer (2, GL_FLOAT, 0, vertices);
2599 glColor4dv (v);
2600 p1.x = v[4];
2601 p1.y = v[5];
2603 p2.x = v[6];
2604 p2.y = v[5];
2606 p3.x = v[6];
2607 p3.y = v[7];
2609 p4.x = v[4];
2610 p4.y = v[7];
2611 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2612 glDisable (GL_BLEND);
2615 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2616 value xoff_v, value yoff_v,
2617 value li_v)
2619 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2620 int xoff = Int_val (xoff_v);
2621 int yoff = Int_val (yoff_v);
2622 int noff = Int_val (Field (li_v, 0));
2623 char *targ = String_val (Field (li_v, 1));
2624 int tlen = caml_string_length (Field (li_v, 1));
2625 int hfsize = Int_val (Field (li_v, 2));
2626 char *s = String_val (ptr_v);
2627 int hlmask = Int_val (hlinks_v);
2628 struct page *page = parse_pointer (__func__, s);
2630 if (!page->fzpage) {
2631 /* deal with loadpage failed pages */
2632 goto done;
2635 if (trylock (__func__)) {
2636 noff = -1;
2637 goto done;
2640 ensureannots (page);
2641 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2642 if (hlmask & 2) {
2643 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2644 noff = page->slinkcount;
2646 if (page->tgen == state.gen) {
2647 showsel (page, xoff, yoff);
2649 unlock (__func__);
2651 done:
2652 CAMLreturn (Val_int (noff));
2655 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2656 value rects_v)
2658 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2659 int xoff = Int_val (xoff_v);
2660 int yoff = Int_val (yoff_v);
2661 char *s = String_val (ptr_v);
2662 struct page *page = parse_pointer (__func__, s);
2664 drawprect (page, xoff, yoff, rects_v);
2665 CAMLreturn (Val_unit);
2668 static struct annot *getannot (struct page *page, int x, int y)
2670 int i;
2671 fz_point p;
2672 fz_matrix ctm;
2673 const fz_matrix *tctm;
2674 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2676 if (!page->annots) return NULL;
2678 if (pdf) {
2679 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2680 tctm = &state.pagedims[page->pdimno].tctm;
2682 else {
2683 tctm = &fz_identity;
2686 p.x = x;
2687 p.y = y;
2689 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2690 fz_invert_matrix (&ctm, &ctm);
2691 fz_transform_point (&p, &ctm);
2693 if (pdf) {
2694 for (i = 0; i < page->annotcount; ++i) {
2695 struct annot *a = &page->annots[i];
2696 fz_rect rect;
2698 fz_bound_annot (state.ctx, a->annot, &rect);
2699 if (p.x >= rect.x0 && p.x <= rect.x1) {
2700 if (p.y >= rect.y0 && p.y <= rect.y1)
2701 return a;
2705 return NULL;
2708 static fz_link *getlink (struct page *page, int x, int y)
2710 fz_point p;
2711 fz_matrix ctm;
2712 fz_link *link, *links;
2714 links = fz_load_links (state.ctx, page->fzpage);
2716 p.x = x;
2717 p.y = y;
2719 ctm = pagectm (page);
2720 fz_invert_matrix (&ctm, &ctm);
2721 fz_transform_point (&p, &ctm);
2723 for (link = links; link; link = link->next) {
2724 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2725 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2726 return link;
2730 return NULL;
2733 static void ensuretext (struct page *page)
2735 if (state.gen != page->tgen) {
2736 droptext (page);
2737 page->tgen = state.gen;
2739 if (!page->text) {
2740 fz_matrix ctm;
2741 fz_device *tdev;
2743 page->text = fz_new_stext_page (state.ctx,
2744 &state.pagedims[page->pdimno].mediabox);
2745 page->sheet = fz_new_stext_sheet (state.ctx);
2746 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2747 ctm = pagectm (page);
2748 fz_run_display_list (state.ctx, page->dlist,
2749 tdev, &ctm, &fz_infinite_rect, NULL);
2750 qsort (page->text->blocks, page->text->len,
2751 sizeof (*page->text->blocks), compareblocks);
2752 fz_close_device (state.ctx, tdev);
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;
2766 fz_var (end_page);
2767 ret_v = Val_int (0);
2768 lock (__func__);
2769 pdf = pdf_specifics (state.ctx, state.doc);
2770 for (i = start_page + dir; i != end_page; i += dir) {
2771 int found;
2773 fz_var (found);
2774 if (pdf) {
2775 pdf_page *page = NULL;
2777 fz_var (page);
2778 fz_try (state.ctx) {
2779 page = pdf_load_page (state.ctx, pdf, i);
2780 found = !!page->links || !!page->annots;
2782 fz_catch (state.ctx) {
2783 found = 0;
2785 if (page) {
2786 fz_drop_page (state.ctx, &page->super);
2789 else {
2790 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2791 found = !!fz_load_links (state.ctx, page);
2792 fz_drop_page (state.ctx, page);
2795 if (found) {
2796 ret_v = caml_alloc_small (1, 1);
2797 Field (ret_v, 0) = Val_int (i);
2798 goto unlock;
2801 unlock:
2802 unlock (__func__);
2803 CAMLreturn (ret_v);
2806 enum { dir_first, dir_last };
2807 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2809 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2811 CAMLparam2 (ptr_v, dir_v);
2812 CAMLlocal2 (ret_v, pos_v);
2813 struct page *page;
2814 int dirtag, i, slinkindex;
2815 struct slink *found = NULL ,*slink;
2816 char *s = String_val (ptr_v);
2818 page = parse_pointer (__func__, s);
2819 ret_v = Val_int (0);
2820 lock (__func__);
2821 ensureslinks (page);
2823 if (Is_block (dir_v)) {
2824 dirtag = Tag_val (dir_v);
2825 switch (dirtag) {
2826 case dir_first_visible:
2828 int x0, y0, dir, first_index, last_index;
2830 pos_v = Field (dir_v, 0);
2831 x0 = Int_val (Field (pos_v, 0));
2832 y0 = Int_val (Field (pos_v, 1));
2833 dir = Int_val (Field (pos_v, 2));
2835 if (dir >= 0) {
2836 dir = 1;
2837 first_index = 0;
2838 last_index = page->slinkcount;
2840 else {
2841 first_index = page->slinkcount - 1;
2842 last_index = -1;
2845 for (i = first_index; i != last_index; i += dir) {
2846 slink = &page->slinks[i];
2847 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2848 found = slink;
2849 break;
2853 break;
2855 case dir_left:
2856 slinkindex = Int_val (Field (dir_v, 0));
2857 found = &page->slinks[slinkindex];
2858 for (i = slinkindex - 1; i >= 0; --i) {
2859 slink = &page->slinks[i];
2860 if (slink->bbox.x0 < found->bbox.x0) {
2861 found = slink;
2862 break;
2865 break;
2867 case dir_right:
2868 slinkindex = Int_val (Field (dir_v, 0));
2869 found = &page->slinks[slinkindex];
2870 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2871 slink = &page->slinks[i];
2872 if (slink->bbox.x0 > found->bbox.x0) {
2873 found = slink;
2874 break;
2877 break;
2879 case dir_down:
2880 slinkindex = Int_val (Field (dir_v, 0));
2881 found = &page->slinks[slinkindex];
2882 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2883 slink = &page->slinks[i];
2884 if (slink->bbox.y0 >= found->bbox.y0) {
2885 found = slink;
2886 break;
2889 break;
2891 case dir_up:
2892 slinkindex = Int_val (Field (dir_v, 0));
2893 found = &page->slinks[slinkindex];
2894 for (i = slinkindex - 1; i >= 0; --i) {
2895 slink = &page->slinks[i];
2896 if (slink->bbox.y0 <= found->bbox.y0) {
2897 found = slink;
2898 break;
2901 break;
2904 else {
2905 dirtag = Int_val (dir_v);
2906 switch (dirtag) {
2907 case dir_first:
2908 found = page->slinks;
2909 break;
2911 case dir_last:
2912 if (page->slinks) {
2913 found = page->slinks + (page->slinkcount - 1);
2915 break;
2918 if (found) {
2919 ret_v = caml_alloc_small (2, 1);
2920 Field (ret_v, 0) = Val_int (found - page->slinks);
2923 unlock (__func__);
2924 CAMLreturn (ret_v);
2927 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2928 unamed, uremote, uremotedest, uannot };
2930 #define LINKTOVAL \
2932 int pageno; \
2934 switch (link->dest.kind) { \
2935 case FZ_LINK_GOTO: \
2937 fz_point p; \
2939 pageno = link->dest.ld.gotor.page; \
2940 p.x = 0; \
2941 p.y = 0; \
2943 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2944 p.y = link->dest.ld.gotor.lt.y; \
2945 fz_transform_point (&p, &pdim->lctm); \
2946 if (p.y < 0) p.y = 0; \
2948 tup_v = caml_alloc_tuple (2); \
2949 ret_v = caml_alloc_small (1, ugoto); \
2950 Field (tup_v, 0) = Val_int (pageno); \
2951 Field (tup_v, 1) = Val_int (p.y); \
2952 Field (ret_v, 0) = tup_v; \
2954 break; \
2956 case FZ_LINK_URI: \
2957 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2958 ret_v = caml_alloc_small (1, uuri); \
2959 Field (ret_v, 0) = str_v; \
2960 break; \
2962 case FZ_LINK_LAUNCH: \
2963 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2964 ret_v = caml_alloc_small (1, ulaunch); \
2965 Field (ret_v, 0) = str_v; \
2966 break; \
2968 case FZ_LINK_NAMED: \
2969 str_v = caml_copy_string (link->dest.ld.named.named); \
2970 ret_v = caml_alloc_small (1, unamed); \
2971 Field (ret_v, 0) = str_v; \
2972 break; \
2974 case FZ_LINK_GOTOR: \
2976 int rty; \
2978 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2979 pageno = link->dest.ld.gotor.page; \
2980 if (pageno == -1) { \
2981 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2982 rty = uremotedest; \
2984 else { \
2985 gr_v = Val_int (pageno); \
2986 rty = uremote; \
2988 tup_v = caml_alloc_tuple (2); \
2989 ret_v = caml_alloc_small (1, rty); \
2990 Field (tup_v, 0) = str_v; \
2991 Field (tup_v, 1) = gr_v; \
2992 Field (ret_v, 0) = tup_v; \
2994 break; \
2996 default: \
2998 char buf[80]; \
3000 snprintf (buf, sizeof (buf), \
3001 "unhandled link kind %d", link->dest.kind); \
3002 str_v = caml_copy_string (buf); \
3003 ret_v = caml_alloc_small (1, uunexpected); \
3004 Field (ret_v, 0) = str_v; \
3006 break; \
3010 CAMLprim value ml_getlink (value ptr_v, value n_v)
3012 CAMLparam2 (ptr_v, n_v);
3013 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3014 fz_link *link;
3015 struct page *page;
3016 struct pagedim *pdim;
3017 char *s = String_val (ptr_v);
3018 struct slink *slink;
3020 ret_v = Val_int (0);
3021 page = parse_pointer (__func__, s);
3023 lock (__func__);
3024 ensureslinks (page);
3025 pdim = &state.pagedims[page->pdimno];
3026 slink = &page->slinks[Int_val (n_v)];
3027 if (slink->tag == SLINK) {
3028 link = slink->u.link;
3029 LINKTOVAL;
3031 else {
3032 ret_v = caml_alloc_small (1, uannot);
3033 tup_v = caml_alloc_tuple (2);
3034 Field (ret_v, 0) = tup_v;
3035 Field (tup_v, 0) = ptr_v;
3036 Field (tup_v, 1) = n_v;
3038 unlock (__func__);
3040 CAMLreturn (ret_v);
3043 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3045 CAMLparam2 (ptr_v, n_v);
3046 pdf_document *pdf;
3047 const char *contents = "";
3049 lock (__func__);
3050 pdf = pdf_specifics (state.ctx, state.doc);
3051 if (pdf) {
3052 char *s = String_val (ptr_v);
3053 struct page *page;
3054 struct slink *slink;
3056 page = parse_pointer (__func__, s);
3057 slink = &page->slinks[Int_val (n_v)];
3058 contents = pdf_annot_contents (state.ctx,
3059 (pdf_annot *) slink->u.annot);
3061 unlock (__func__);
3062 CAMLreturn (caml_copy_string (contents));
3065 CAMLprim value ml_getlinkcount (value ptr_v)
3067 CAMLparam1 (ptr_v);
3068 struct page *page;
3069 char *s = String_val (ptr_v);
3071 page = parse_pointer (__func__, s);
3072 CAMLreturn (Val_int (page->slinkcount));
3075 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3077 CAMLparam2 (ptr_v, n_v);
3078 CAMLlocal1 (ret_v);
3079 struct page *page;
3080 struct slink *slink;
3081 char *s = String_val (ptr_v);
3083 page = parse_pointer (__func__, s);
3084 ret_v = caml_alloc_tuple (4);
3085 lock (__func__);
3086 ensureslinks (page);
3088 slink = &page->slinks[Int_val (n_v)];
3089 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3090 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3091 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3092 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3093 unlock (__func__);
3094 CAMLreturn (ret_v);
3097 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3099 CAMLparam3 (ptr_v, x_v, y_v);
3100 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3101 fz_link *link;
3102 struct annot *annot;
3103 struct page *page;
3104 char *ptr = String_val (ptr_v);
3105 int x = Int_val (x_v), y = Int_val (y_v);
3106 struct pagedim *pdim;
3108 ret_v = Val_int (0);
3109 if (trylock (__func__)) {
3110 goto done;
3113 page = parse_pointer (__func__, ptr);
3114 pdim = &state.pagedims[page->pdimno];
3115 x += pdim->bounds.x0;
3116 y += pdim->bounds.y0;
3119 annot = getannot (page, x, y);
3120 if (annot) {
3121 int i, n = -1;
3123 ensureslinks (page);
3124 for (i = 0; i < page->slinkcount; ++i) {
3125 if (page->slinks[i].tag == SANNOT
3126 && page->slinks[i].u.annot == annot->annot) {
3127 n = i;
3128 break;
3131 ret_v = caml_alloc_small (1, uannot);
3132 tup_v = caml_alloc_tuple (2);
3133 Field (ret_v, 0) = tup_v;
3134 Field (tup_v, 0) = ptr_v;
3135 Field (tup_v, 1) = Val_int (n);
3136 goto unlock;
3140 link = getlink (page, x, y);
3141 if (link) {
3142 LINKTOVAL;
3144 else {
3145 fz_rect *b;
3146 fz_page_block *pageb;
3147 fz_stext_block *block;
3149 ensuretext (page);
3150 for (pageb = page->text->blocks;
3151 pageb < page->text->blocks + page->text->len;
3152 ++pageb) {
3153 fz_stext_line *line;
3154 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3155 block = pageb->u.text;
3157 b = &block->bbox;
3158 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3159 continue;
3161 for (line = block->lines;
3162 line < block->lines + block->len;
3163 ++line) {
3164 fz_stext_span *span;
3166 b = &line->bbox;
3167 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3168 continue;
3170 for (span = line->first_span; span; span = span->next) {
3171 int charnum;
3173 b = &span->bbox;
3174 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3175 continue;
3177 for (charnum = 0; charnum < span->len; ++charnum) {
3178 fz_rect bbox;
3179 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3180 b = &bbox;
3182 if (x >= b->x0 && x <= b->x1
3183 && y >= b->y0 && y <= b->y1) {
3184 fz_stext_style *style = span->text->style;
3185 const char *n2 =
3186 style->font
3187 ? style->font->name
3188 : "Span has no font name"
3190 FT_FaceRec *face = style->font->ft_face;
3191 if (face && face->family_name) {
3192 char *s;
3193 char *n1 = face->family_name;
3194 size_t l1 = strlen (n1);
3195 size_t l2 = strlen (n2);
3197 if (l1 != l2 || memcmp (n1, n2, l1)) {
3198 s = malloc (l1 + l2 + 2);
3199 if (s) {
3200 memcpy (s, n2, l2);
3201 s[l2] = '=';
3202 memcpy (s + l2 + 1, n1, l1 + 1);
3203 str_v = caml_copy_string (s);
3204 free (s);
3208 if (str_v == Val_unit) {
3209 str_v = caml_copy_string (n2);
3211 ret_v = caml_alloc_small (1, utext);
3212 Field (ret_v, 0) = str_v;
3213 goto unlock;
3220 unlock:
3221 unlock (__func__);
3223 done:
3224 CAMLreturn (ret_v);
3227 enum { mark_page, mark_block, mark_line, mark_word };
3229 static int uninteresting (int c)
3231 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3232 || ispunct (c);
3235 CAMLprim value ml_clearmark (value ptr_v)
3237 CAMLparam1 (ptr_v);
3238 char *s = String_val (ptr_v);
3239 struct page *page;
3241 if (trylock (__func__)) {
3242 goto done;
3245 page = parse_pointer (__func__, s);
3246 page->fmark.span = NULL;
3247 page->lmark.span = NULL;
3248 page->fmark.i = 0;
3249 page->lmark.i = 0;
3251 unlock (__func__);
3252 done:
3253 CAMLreturn (Val_unit);
3256 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3258 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3259 CAMLlocal1 (ret_v);
3260 fz_rect *b;
3261 struct page *page;
3262 fz_stext_line *line;
3263 fz_page_block *pageb;
3264 fz_stext_block *block;
3265 struct pagedim *pdim;
3266 int mark = Int_val (mark_v);
3267 char *s = String_val (ptr_v);
3268 int x = Int_val (x_v), y = Int_val (y_v);
3270 ret_v = Val_bool (0);
3271 if (trylock (__func__)) {
3272 goto done;
3275 page = parse_pointer (__func__, s);
3276 pdim = &state.pagedims[page->pdimno];
3278 ensuretext (page);
3280 if (mark == mark_page) {
3281 int i;
3282 fz_page_block *pb1 = NULL, *pb2 = NULL;
3284 for (i = 0; i < page->text->len; ++i) {
3285 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3286 pb1 = &page->text->blocks[i];
3287 break;
3290 if (!pb1) goto unlock;
3292 for (i = page->text->len - 1; i >= 0; --i) {
3293 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3294 pb2 = &page->text->blocks[i];
3295 break;
3298 if (!pb2) goto unlock;
3300 block = pb1->u.text;
3302 page->fmark.i = 0;
3303 page->fmark.span = block->lines->first_span;
3305 block = pb2->u.text;
3306 line = &block->lines[block->len - 1];
3307 page->lmark.i = line->last_span->len - 1;
3308 page->lmark.span = line->last_span;
3309 ret_v = Val_bool (1);
3310 goto unlock;
3313 x += pdim->bounds.x0;
3314 y += pdim->bounds.y0;
3316 for (pageb = page->text->blocks;
3317 pageb < page->text->blocks + page->text->len;
3318 ++pageb) {
3319 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3320 block = pageb->u.text;
3322 b = &block->bbox;
3323 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3324 continue;
3326 if (mark == mark_block) {
3327 page->fmark.i = 0;
3328 page->fmark.span = block->lines->first_span;
3330 line = &block->lines[block->len - 1];
3331 page->lmark.i = line->last_span->len - 1;
3332 page->lmark.span = line->last_span;
3333 ret_v = Val_bool (1);
3334 goto unlock;
3337 for (line = block->lines;
3338 line < block->lines + block->len;
3339 ++line) {
3340 fz_stext_span *span;
3342 b = &line->bbox;
3343 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3344 continue;
3346 if (mark == mark_line) {
3347 page->fmark.i = 0;
3348 page->fmark.span = line->first_span;
3350 page->lmark.i = line->last_span->len - 1;
3351 page->lmark.span = line->last_span;
3352 ret_v = Val_bool (1);
3353 goto unlock;
3356 for (span = line->first_span; span; span = span->next) {
3357 int charnum;
3359 b = &span->bbox;
3360 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3361 continue;
3363 for (charnum = 0; charnum < span->len; ++charnum) {
3364 fz_rect bbox;
3365 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3366 b = &bbox;
3368 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3369 /* unicode ftw */
3370 int charnum2, charnum3 = -1, charnum4 = -1;
3372 if (uninteresting (span->text[charnum].c)) goto unlock;
3374 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3375 if (uninteresting (span->text[charnum2].c)) {
3376 charnum3 = charnum2 + 1;
3377 break;
3380 if (charnum3 == -1) charnum3 = 0;
3382 charnum4 = charnum;
3383 for (charnum2 = charnum + 1;
3384 charnum2 < span->len;
3385 ++charnum2) {
3386 if (uninteresting (span->text[charnum2].c)) break;
3387 charnum4 = charnum2;
3390 page->fmark.i = charnum3;
3391 page->fmark.span = span;
3393 page->lmark.i = charnum4;
3394 page->lmark.span = span;
3395 ret_v = Val_bool (1);
3396 goto unlock;
3402 unlock:
3403 if (!Bool_val (ret_v)) {
3404 page->fmark.span = NULL;
3405 page->lmark.span = NULL;
3406 page->fmark.i = 0;
3407 page->lmark.i = 0;
3409 unlock (__func__);
3411 done:
3412 CAMLreturn (ret_v);
3415 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3417 CAMLparam3 (ptr_v, x_v, y_v);
3418 CAMLlocal2 (ret_v, res_v);
3419 fz_rect *b = NULL;
3420 struct page *page;
3421 fz_page_block *pageb;
3422 struct pagedim *pdim;
3423 char *s = String_val (ptr_v);
3424 int x = Int_val (x_v), y = Int_val (y_v);
3426 ret_v = Val_int (0);
3427 if (trylock (__func__)) {
3428 goto done;
3431 page = parse_pointer (__func__, s);
3432 pdim = &state.pagedims[page->pdimno];
3433 x += pdim->bounds.x0;
3434 y += pdim->bounds.y0;
3436 ensuretext (page);
3438 for (pageb = page->text->blocks;
3439 pageb < page->text->blocks + page->text->len;
3440 ++pageb) {
3441 switch (pageb->type) {
3442 case FZ_PAGE_BLOCK_TEXT:
3443 b = &pageb->u.text->bbox;
3444 break;
3446 case FZ_PAGE_BLOCK_IMAGE:
3447 b = &pageb->u.image->bbox;
3448 break;
3450 default:
3451 continue;
3454 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3455 break;
3456 b = NULL;
3458 if (b) {
3459 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3460 ret_v = caml_alloc_small (1, 1);
3461 Store_double_field (res_v, 0, b->x0);
3462 Store_double_field (res_v, 1, b->x1);
3463 Store_double_field (res_v, 2, b->y0);
3464 Store_double_field (res_v, 3, b->y1);
3465 Field (ret_v, 0) = res_v;
3467 unlock (__func__);
3469 done:
3470 CAMLreturn (ret_v);
3473 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3475 CAMLparam2 (ptr_v, rect_v);
3476 fz_rect b;
3477 struct page *page;
3478 struct pagedim *pdim;
3479 char *s = String_val (ptr_v);
3480 int i, x0, x1, y0, y1, fi, li;
3481 fz_stext_line *line;
3482 fz_page_block *pageb;
3483 fz_stext_block *block;
3484 fz_stext_span *span, *fspan, *lspan;
3486 if (trylock (__func__)) {
3487 goto done;
3490 page = parse_pointer (__func__, s);
3491 ensuretext (page);
3493 pdim = &state.pagedims[page->pdimno];
3494 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3495 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3496 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3497 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3499 if (y0 > y1) {
3500 int t = y0;
3501 y0 = y1;
3502 y1 = t;
3503 x0 = x1;
3504 x1 = t;
3507 fi = page->fmark.i;
3508 fspan = page->fmark.span;
3510 li = page->lmark.i;
3511 lspan = page->lmark.span;
3513 for (pageb = page->text->blocks;
3514 pageb < page->text->blocks + page->text->len;
3515 ++pageb) {
3516 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3517 block = pageb->u.text;
3518 for (line = block->lines;
3519 line < block->lines + block->len;
3520 ++line) {
3522 for (span = line->first_span; span; span = span->next) {
3523 for (i = 0; i < span->len; ++i) {
3524 fz_stext_char_bbox (state.ctx, &b, span, i);
3526 if (x0 >= b.x0 && x0 <= b.x1
3527 && y0 >= b.y0 && y0 <= b.y1) {
3528 fspan = span;
3529 fi = i;
3531 if (x1 >= b.x0 && x1 <= b.x1
3532 && y1 >= b.y0 && y1 <= b.y1) {
3533 lspan = span;
3534 li = i;
3540 if (x1 < x0 && fspan == lspan) {
3541 i = fi;
3542 span = fspan;
3544 fi = li;
3545 fspan = lspan;
3547 li = i;
3548 lspan = span;
3551 page->fmark.i = fi;
3552 page->fmark.span = fspan;
3554 page->lmark.i = li;
3555 page->lmark.span = lspan;
3557 unlock (__func__);
3559 done:
3560 CAMLreturn (Val_unit);
3563 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3565 char buf[4];
3566 int i, len, ret;
3568 for (i = a; i <= b; ++i) {
3569 len = fz_runetochar (buf, span->text[i].c);
3570 ret = fwrite (buf, len, 1, f);
3572 if (ret != 1) {
3573 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3574 len, ret, strerror (errno));
3575 return -1;
3578 return 0;
3581 #ifdef __CYGWIN__
3582 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3584 caml_failwith ("ml_popen not implemented under Cygwin");
3586 #else
3587 CAMLprim value ml_spawn (value command_v, value fds_v)
3589 CAMLparam2 (command_v, fds_v);
3590 CAMLlocal2 (l_v, tup_v);
3591 int ret, ret1;
3592 pid_t pid;
3593 char *msg = NULL;
3594 value earg_v = Nothing;
3595 posix_spawnattr_t attr;
3596 posix_spawn_file_actions_t fa;
3597 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3599 argv[2] = String_val (command_v);
3601 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3602 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3605 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3606 msg = "posix_spawnattr_init";
3607 goto fail1;
3610 #ifdef POSIX_SPAWN_USEVFORK
3611 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3612 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3613 goto fail;
3615 #endif
3617 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3618 int fd1, fd2;
3620 tup_v = Field (l_v, 0);
3621 fd1 = Int_val (Field (tup_v, 0));
3622 fd2 = Int_val (Field (tup_v, 1));
3623 if (fd2 < 0) {
3624 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3625 msg = "posix_spawn_file_actions_addclose";
3626 earg_v = tup_v;
3627 goto fail;
3630 else {
3631 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3632 msg = "posix_spawn_file_actions_adddup2";
3633 earg_v = tup_v;
3634 goto fail;
3639 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3640 msg = "posix_spawn";
3641 goto fail;
3644 fail:
3645 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3646 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3649 fail1:
3650 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3651 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3652 strerror (ret1));
3655 if (msg)
3656 unix_error (ret, msg, earg_v);
3658 CAMLreturn (Val_int (pid));
3660 #endif
3662 CAMLprim value ml_hassel (value ptr_v)
3664 CAMLparam1 (ptr_v);
3665 CAMLlocal1 (ret_v);
3666 struct page *page;
3667 char *s = String_val (ptr_v);
3669 ret_v = Val_bool (0);
3670 if (trylock (__func__)) {
3671 goto done;
3674 page = parse_pointer (__func__, s);
3675 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3676 unlock (__func__);
3677 done:
3678 CAMLreturn (ret_v);
3681 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3683 CAMLparam2 (fd_v, ptr_v);
3684 FILE *f;
3685 int seen = 0;
3686 struct page *page;
3687 fz_stext_line *line;
3688 fz_page_block *pageb;
3689 fz_stext_block *block;
3690 int fd = Int_val (fd_v);
3691 char *s = String_val (ptr_v);
3693 if (trylock (__func__)) {
3694 goto done;
3697 page = parse_pointer (__func__, s);
3699 if (!page->fmark.span || !page->lmark.span) {
3700 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3701 goto unlock;
3704 f = fdopen (fd, "w");
3705 if (!f) {
3706 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3707 fd, strerror (errno));
3708 f = stdout;
3711 for (pageb = page->text->blocks;
3712 pageb < page->text->blocks + page->text->len;
3713 ++pageb) {
3714 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3715 block = pageb->u.text;
3716 for (line = block->lines;
3717 line < block->lines + block->len;
3718 ++line) {
3719 fz_stext_span *span;
3721 for (span = line->first_span; span; span = span->next) {
3722 int a, b;
3724 seen |= span == page->fmark.span || span == page->lmark.span;
3725 a = span == page->fmark.span ? page->fmark.i : 0;
3726 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3728 if (seen) {
3729 if (pipespan (f, span, a, b)) {
3730 goto close;
3732 if (span == page->lmark.span) {
3733 goto close;
3735 if (span == line->last_span) {
3736 if (putc ('\n', f) == EOF) {
3737 fprintf (stderr,
3738 "failed break line on sel pipe: %s\n",
3739 strerror (errno));
3740 goto close;
3747 close:
3748 if (f != stdout) {
3749 int ret = fclose (f);
3750 fd = -1;
3751 if (ret == -1) {
3752 if (errno != ECHILD) {
3753 fprintf (stderr, "failed to close sel pipe: %s\n",
3754 strerror (errno));
3758 unlock:
3759 unlock (__func__);
3761 done:
3762 if (fd >= 0) {
3763 if (close (fd)) {
3764 fprintf (stderr, "failed to close sel pipe: %s\n",
3765 strerror (errno));
3768 CAMLreturn (Val_unit);
3771 CAMLprim value ml_getpdimrect (value pagedimno_v)
3773 CAMLparam1 (pagedimno_v);
3774 CAMLlocal1 (ret_v);
3775 int pagedimno = Int_val (pagedimno_v);
3776 fz_rect box;
3778 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3779 if (trylock (__func__)) {
3780 box = fz_empty_rect;
3782 else {
3783 box = state.pagedims[pagedimno].mediabox;
3784 unlock (__func__);
3787 Store_double_field (ret_v, 0, box.x0);
3788 Store_double_field (ret_v, 1, box.x1);
3789 Store_double_field (ret_v, 2, box.y0);
3790 Store_double_field (ret_v, 3, box.y1);
3792 CAMLreturn (ret_v);
3795 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3796 value dw_v, value cols_v)
3798 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3799 CAMLlocal1 (ret_v);
3800 int i;
3801 double zoom = -1.;
3802 double maxh = 0.0;
3803 struct pagedim *p;
3804 double winw = Int_val (winw_v);
3805 double winh = Int_val (winh_v);
3806 double dw = Int_val (dw_v);
3807 double cols = Int_val (cols_v);
3808 double pw = 1.0, ph = 1.0;
3810 if (trylock (__func__)) {
3811 goto done;
3814 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3815 double w = p->pagebox.x1 / cols;
3816 double h = p->pagebox.y1;
3817 if (h > maxh) {
3818 maxh = h;
3819 ph = h;
3820 if (state.fitmodel != FitProportional) pw = w;
3822 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3825 zoom = (((winh / ph) * pw) + dw) / winw;
3826 unlock (__func__);
3827 done:
3828 ret_v = caml_copy_double (zoom);
3829 CAMLreturn (ret_v);
3832 CAMLprim value ml_getmaxw (value unit_v)
3834 CAMLparam1 (unit_v);
3835 CAMLlocal1 (ret_v);
3836 int i;
3837 double maxw = -1.;
3838 struct pagedim *p;
3840 if (trylock (__func__)) {
3841 goto done;
3844 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3845 double w = p->pagebox.x1;
3846 maxw = fz_max (maxw, w);
3849 unlock (__func__);
3850 done:
3851 ret_v = caml_copy_double (maxw);
3852 CAMLreturn (ret_v);
3855 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3857 CAMLparam4 (pt_v, x_v, y_v, string_v);
3858 CAMLlocal1 (ret_v);
3859 int pt = Int_val(pt_v);
3860 int x = Int_val (x_v);
3861 int y = Int_val (y_v);
3862 double w;
3864 w = draw_string (state.face, pt, x, y, String_val (string_v));
3865 ret_v = caml_copy_double (w);
3866 CAMLreturn (ret_v);
3869 CAMLprim value ml_measure_string (value pt_v, value string_v)
3871 CAMLparam2 (pt_v, string_v);
3872 CAMLlocal1 (ret_v);
3873 int pt = Int_val (pt_v);
3874 double w;
3876 w = measure_string (state.face, pt, String_val (string_v));
3877 ret_v = caml_copy_double (w);
3878 CAMLreturn (ret_v);
3881 CAMLprim value ml_getpagebox (value opaque_v)
3883 CAMLparam1 (opaque_v);
3884 CAMLlocal1 (ret_v);
3885 fz_rect rect;
3886 fz_irect bbox;
3887 fz_matrix ctm;
3888 fz_device *dev;
3889 char *s = String_val (opaque_v);
3890 struct page *page = parse_pointer (__func__, s);
3892 ret_v = caml_alloc_tuple (4);
3893 dev = fz_new_bbox_device (state.ctx, &rect);
3894 dev->hints |= FZ_IGNORE_SHADE;
3896 ctm = pagectm (page);
3897 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3899 fz_close_device (state.ctx, dev);
3900 fz_drop_device (state.ctx, dev);
3901 fz_round_rect (&bbox, &rect);
3902 Field (ret_v, 0) = Val_int (bbox.x0);
3903 Field (ret_v, 1) = Val_int (bbox.y0);
3904 Field (ret_v, 2) = Val_int (bbox.x1);
3905 Field (ret_v, 3) = Val_int (bbox.y1);
3907 CAMLreturn (ret_v);
3910 CAMLprim value ml_setaalevel (value level_v)
3912 CAMLparam1 (level_v);
3914 state.aalevel = Int_val (level_v);
3915 CAMLreturn (Val_unit);
3918 #pragma GCC diagnostic push
3919 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3920 #include <X11/Xlib.h>
3921 #include <X11/cursorfont.h>
3922 #pragma GCC diagnostic pop
3924 #ifdef USE_EGL
3925 #include <EGL/egl.h>
3926 #else
3927 #include <GL/glx.h>
3928 #endif
3930 static const int shapes[] = {
3931 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3934 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3936 static struct {
3937 Window wid;
3938 Display *dpy;
3939 #ifdef USE_EGL
3940 EGLContext ctx;
3941 EGLConfig conf;
3942 EGLSurface win;
3943 EGLDisplay *edpy;
3944 #else
3945 GLXContext ctx;
3946 #endif
3947 XVisualInfo *visual;
3948 Cursor curs[CURS_COUNT];
3949 } glx;
3951 #ifdef VISAVIS
3952 static VisualID initvisual (void)
3954 /* On this system with: `Haswell-ULT Integrated Graphics
3955 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3956 using glX chosen visual and auto scrolling some document in
3957 fullscreen the power/energy-gpu is more than 1 joule bigger
3958 than when using hand picked visual that stands alone in glxinfo
3959 output: it's dead last in the list and it's the only one with
3960 `visual dep' (sic) of 32
3962 No clue what's going on here...
3964 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3966 XVisualInfo info;
3967 int ret = 1;
3969 info.depth = 32;
3970 info.class = TrueColor;
3971 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3972 &info, &ret);
3973 if (!ret || !glx.visual) {
3974 XCloseDisplay (glx.dpy);
3975 caml_failwith ("XGetVisualInfo");
3977 return glx.visual->visualid;
3979 #endif
3981 static void initcurs (void)
3983 for (size_t n = 0; n < CURS_COUNT; ++n) {
3984 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3988 CAMLprim void ml_setbgcol (value color_v)
3990 CAMLparam1 (color_v);
3991 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3992 CAMLreturn0;
3995 #ifdef USE_EGL
3996 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3998 CAMLparam3 (display_v, wid_v, screen_v);
3999 int major, minor;
4000 int num_conf;
4001 EGLint visid;
4002 EGLint attribs[] = {
4003 #ifdef VISAVIS
4004 EGL_NATIVE_VISUAL_ID, 0,
4005 #else
4006 EGL_DEPTH_SIZE, 24,
4007 #endif
4008 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
4009 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
4010 EGL_NONE
4012 EGLConfig conf;
4014 glx.dpy = XOpenDisplay (String_val (display_v));
4015 if (!glx.dpy) {
4016 caml_failwith ("XOpenDisplay");
4019 eglBindAPI (EGL_OPENGL_API);
4021 glx.edpy = eglGetDisplay (glx.dpy);
4022 if (glx.edpy == EGL_NO_DISPLAY) {
4023 caml_failwith ("eglGetDisplay");
4026 if (!eglInitialize (glx.edpy, &major, &minor)) {
4027 caml_failwith ("eglInitialize");
4030 #ifdef VISAVIS
4031 attribs[1] = visid = initvisual ();
4032 #endif
4034 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4035 !num_conf) {
4036 caml_failwith ("eglChooseConfig");
4039 glx.conf = conf;
4040 #ifndef VISAVIS
4041 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4042 EGL_NATIVE_VISUAL_ID, &visid)) {
4043 caml_failwith ("eglGetConfigAttrib");
4045 #endif
4046 initcurs ();
4048 glx.wid = Int_val (wid_v);
4049 CAMLreturn (Val_int (visid));
4052 CAMLprim value ml_glxcompleteinit (value unit_v)
4054 CAMLparam1 (unit_v);
4056 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4057 if (!glx.ctx) {
4058 caml_failwith ("eglCreateContext");
4061 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4062 glx.wid, NULL);
4063 if (glx.win == EGL_NO_SURFACE) {
4064 caml_failwith ("eglCreateWindowSurface");
4067 XFree (glx.visual);
4068 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4069 glx.ctx = NULL;
4070 caml_failwith ("eglMakeCurrent");
4072 CAMLreturn (Val_unit);
4074 #else
4075 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4077 CAMLparam3 (display_v, wid_v, screen_v);
4079 glx.dpy = XOpenDisplay (String_val (display_v));
4080 if (!glx.dpy) {
4081 caml_failwith ("XOpenDisplay");
4084 #ifdef VISAVIS
4085 initvisual ();
4086 #else
4087 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4088 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4089 if (!glx.visual) {
4090 XCloseDisplay (glx.dpy);
4091 caml_failwith ("glXChooseVisual");
4093 #endif
4094 initcurs ();
4096 glx.wid = Int_val (wid_v);
4097 CAMLreturn (Val_int (glx.visual->visualid));
4100 CAMLprim value ml_glxcompleteinit (value unit_v)
4102 CAMLparam1 (unit_v);
4104 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4105 if (!glx.ctx) {
4106 caml_failwith ("glXCreateContext");
4109 XFree (glx.visual);
4110 glx.visual = NULL;
4112 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4113 glXDestroyContext (glx.dpy, glx.ctx);
4114 glx.ctx = NULL;
4115 caml_failwith ("glXMakeCurrent");
4117 CAMLreturn (Val_unit);
4119 #endif
4121 CAMLprim value ml_setcursor (value cursor_v)
4123 CAMLparam1 (cursor_v);
4124 size_t cursn = Int_val (cursor_v);
4126 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4127 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4128 XFlush (glx.dpy);
4129 CAMLreturn (Val_unit);
4132 CAMLprim value ml_swapb (value unit_v)
4134 CAMLparam1 (unit_v);
4135 #ifdef USE_EGL
4136 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4137 caml_failwith ("eglSwapBuffers");
4139 #else
4140 glXSwapBuffers (glx.dpy, glx.wid);
4141 #endif
4142 CAMLreturn (Val_unit);
4145 #include "keysym2ucs.c"
4147 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4149 CAMLparam1 (keysym_v);
4150 CAMLlocal1 (str_v);
4151 KeySym keysym = Int_val (keysym_v);
4152 Rune rune;
4153 int len;
4154 char buf[5];
4156 rune = keysym2ucs (keysym);
4157 len = fz_runetochar (buf, rune);
4158 buf[len] = 0;
4159 str_v = caml_copy_string (buf);
4160 CAMLreturn (str_v);
4163 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4165 CAMLprim value ml_platform (value unit_v)
4167 CAMLparam1 (unit_v);
4168 CAMLlocal2 (tup_v, arr_v);
4169 int platid = piunknown;
4170 struct utsname buf;
4172 #if defined __linux__
4173 platid = pilinux;
4174 #elif defined __CYGWIN__
4175 platid = picygwin;
4176 #elif defined __DragonFly__ || defined __FreeBSD__
4177 || defined __OpenBSD__ || defined __NetBSD__
4178 platid = pibsd;
4179 #elif defined __sun__
4180 platid = pisun;
4181 #elif defined __APPLE__
4182 platid = piosx;
4183 #endif
4184 if (uname (&buf)) err (1, "uname");
4186 tup_v = caml_alloc_tuple (2);
4188 char const *sar[] = {
4189 buf.sysname,
4190 buf.release,
4191 buf.version,
4192 buf.machine,
4193 NULL
4195 arr_v = caml_copy_string_array (sar);
4197 Field (tup_v, 0) = Val_int (platid);
4198 Field (tup_v, 1) = arr_v;
4199 CAMLreturn (tup_v);
4202 CAMLprim value ml_cloexec (value fd_v)
4204 CAMLparam1 (fd_v);
4205 int fd = Int_val (fd_v);
4207 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4208 uerror ("fcntl", Nothing);
4210 CAMLreturn (Val_unit);
4213 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4215 CAMLparam2 (w_v, h_v);
4216 CAMLlocal1 (ret_v);
4217 struct bo *pbo;
4218 int w = Int_val (w_v);
4219 int h = Int_val (h_v);
4220 int cs = Int_val (cs_v);
4222 if (state.bo_usable) {
4223 pbo = calloc (sizeof (*pbo), 1);
4224 if (!pbo) {
4225 err (1, "calloc pbo");
4228 switch (cs) {
4229 case 0:
4230 case 1:
4231 pbo->size = w*h*4;
4232 break;
4233 case 2:
4234 pbo->size = w*h*2;
4235 break;
4236 default:
4237 errx (1, "%s: invalid colorspace %d", __func__, cs);
4240 state.glGenBuffersARB (1, &pbo->id);
4241 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4242 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4243 NULL, GL_STREAM_DRAW);
4244 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4245 GL_READ_WRITE);
4246 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4247 if (!pbo->ptr) {
4248 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4249 state.glDeleteBuffersARB (1, &pbo->id);
4250 free (pbo);
4251 ret_v = caml_copy_string ("0");
4253 else {
4254 int res;
4255 char *s;
4257 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4258 if (res < 0) {
4259 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4261 s = malloc (res+1);
4262 if (!s) {
4263 err (1, "malloc %d bytes failed", res+1);
4265 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4266 if (res < 0) {
4267 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4269 ret_v = caml_copy_string (s);
4270 free (s);
4273 else {
4274 ret_v = caml_copy_string ("0");
4276 CAMLreturn (ret_v);
4279 CAMLprim value ml_freepbo (value s_v)
4281 CAMLparam1 (s_v);
4282 char *s = String_val (s_v);
4283 struct tile *tile = parse_pointer (__func__, s);
4285 if (tile->pbo) {
4286 state.glDeleteBuffersARB (1, &tile->pbo->id);
4287 tile->pbo->id = -1;
4288 tile->pbo->ptr = NULL;
4289 tile->pbo->size = -1;
4291 CAMLreturn (Val_unit);
4294 CAMLprim value ml_unmappbo (value s_v)
4296 CAMLparam1 (s_v);
4297 char *s = String_val (s_v);
4298 struct tile *tile = parse_pointer (__func__, s);
4300 if (tile->pbo) {
4301 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4302 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4303 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4305 tile->pbo->ptr = NULL;
4306 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4308 CAMLreturn (Val_unit);
4311 static void setuppbo (void)
4313 #ifdef USE_EGL
4314 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4315 #else
4316 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4317 #endif
4318 state.bo_usable = GGPA (glBindBufferARB)
4319 && GGPA (glUnmapBufferARB)
4320 && GGPA (glMapBufferARB)
4321 && GGPA (glBufferDataARB)
4322 && GGPA (glGenBuffersARB)
4323 && GGPA (glDeleteBuffersARB);
4324 #undef GGPA
4327 CAMLprim value ml_bo_usable (value unit_v)
4329 CAMLparam1 (unit_v);
4330 CAMLreturn (Val_bool (state.bo_usable));
4333 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4335 CAMLparam3 (ptr_v, x_v, y_v);
4336 CAMLlocal2 (ret_v, tup_v);
4337 struct page *page;
4338 char *s = String_val (ptr_v);
4339 int x = Int_val (x_v), y = Int_val (y_v);
4340 struct pagedim *pdim;
4341 fz_point p;
4342 fz_matrix ctm;
4344 page = parse_pointer (__func__, s);
4345 pdim = &state.pagedims[page->pdimno];
4347 ret_v = Val_int (0);
4348 if (trylock (__func__)) {
4349 goto done;
4352 if (pdf_specifics (state.ctx, state.doc)) {
4353 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4354 ctm = state.pagedims[page->pdimno].tctm;
4356 else {
4357 ctm = fz_identity;
4359 p.x = x + pdim->bounds.x0;
4360 p.y = y + pdim->bounds.y0;
4362 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4363 fz_invert_matrix (&ctm, &ctm);
4364 fz_transform_point (&p, &ctm);
4366 tup_v = caml_alloc_tuple (2);
4367 ret_v = caml_alloc_small (1, 1);
4368 Field (tup_v, 0) = Val_int (p.x);
4369 Field (tup_v, 1) = Val_int (p.y);
4370 Field (ret_v, 0) = tup_v;
4372 unlock (__func__);
4373 done:
4374 CAMLreturn (ret_v);
4377 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4378 value x_v, value y_v)
4380 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4381 CAMLlocal1 (ret_v);
4382 struct page *page;
4383 char *s = String_val (ptr_v);
4384 int pageno = Int_val (pageno_v);
4385 int pdimno = Int_val (pdimno_v);
4386 double x = Double_val (x_v), y = Double_val (y_v);
4387 struct pagedim *pdim;
4388 fz_point p;
4389 fz_matrix ctm;
4391 ret_v = Val_int (0);
4392 lock (__func__);
4394 if (!*s) {
4395 page = loadpage (pageno, pdimno);
4397 else {
4398 page = parse_pointer (__func__, s);
4400 pdim = &state.pagedims[pdimno];
4402 if (pdf_specifics (state.ctx, state.doc)) {
4403 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4404 ctm = state.pagedims[page->pdimno].tctm;
4406 else {
4407 ctm = fz_identity;
4409 p.x = x + pdim->bounds.x0;
4410 p.y = y + pdim->bounds.y0;
4412 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4413 fz_transform_point (&p, &ctm);
4415 ret_v = caml_alloc_tuple (2);
4416 Field (ret_v, 0) = caml_copy_double (p.x);
4417 Field (ret_v, 1) = caml_copy_double (p.y);
4419 if (!*s) {
4420 freepage (page);
4422 unlock (__func__);
4423 CAMLreturn (ret_v);
4426 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4427 value contents_v)
4429 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4430 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4432 if (pdf) {
4433 pdf_annot *annot;
4434 struct page *page;
4435 fz_point p;
4436 char *s = String_val (ptr_v);
4438 page = parse_pointer (__func__, s);
4439 annot = pdf_create_annot (state.ctx, pdf,
4440 pdf_page_from_fz_page (state.ctx,
4441 page->fzpage),
4442 FZ_ANNOT_TEXT);
4443 p.x = Int_val (x_v);
4444 p.y = Int_val (y_v);
4445 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4446 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4447 state.dirty = 1;
4449 CAMLreturn (Val_unit);
4452 CAMLprim value ml_delannot (value ptr_v, value n_v)
4454 CAMLparam2 (ptr_v, n_v);
4455 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4457 if (pdf) {
4458 struct page *page;
4459 char *s = String_val (ptr_v);
4460 struct slink *slink;
4462 page = parse_pointer (__func__, s);
4463 slink = &page->slinks[Int_val (n_v)];
4464 pdf_delete_annot (state.ctx, pdf,
4465 pdf_page_from_fz_page (state.ctx, page->fzpage),
4466 (pdf_annot *) slink->u.annot);
4467 state.dirty = 1;
4469 CAMLreturn (Val_unit);
4472 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4474 CAMLparam3 (ptr_v, n_v, str_v);
4475 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4477 if (pdf) {
4478 struct page *page;
4479 char *s = String_val (ptr_v);
4480 struct slink *slink;
4482 page = parse_pointer (__func__, s);
4483 slink = &page->slinks[Int_val (n_v)];
4484 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4485 String_val (str_v));
4486 state.dirty = 1;
4488 CAMLreturn (Val_unit);
4491 CAMLprim value ml_hasunsavedchanges (value unit_v)
4493 CAMLparam1 (unit_v);
4494 CAMLreturn (Val_bool (state.dirty));
4497 CAMLprim value ml_savedoc (value path_v)
4499 CAMLparam1 (path_v);
4500 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4502 if (pdf) {
4503 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4505 CAMLreturn (Val_unit);
4508 static void makestippletex (void)
4510 const char pixels[] = "\xff\xff\0\0";
4511 glGenTextures (1, &state.stid);
4512 glBindTexture (GL_TEXTURE_1D, state.stid);
4513 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4514 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4515 glTexImage1D (
4516 GL_TEXTURE_1D,
4518 GL_ALPHA,
4521 GL_ALPHA,
4522 GL_UNSIGNED_BYTE,
4523 pixels
4527 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4529 return caml_copy_string (FZ_VERSION);
4532 #ifdef USE_FONTCONFIG
4533 static struct {
4534 int inited;
4535 FcConfig *config;
4536 } fc;
4538 static fz_font *fc_load_system_font_func (fz_context *ctx,
4539 const char *name,
4540 int bold,
4541 int italic,
4542 int UNUSED_ATTR needs_exact_metrics)
4544 char *buf;
4545 size_t i, size;
4546 fz_font *font;
4547 FcChar8 *path;
4548 FcResult result;
4549 FcPattern *pat, *pat1;
4551 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4552 name, bold, italic, needs_exact_metrics);
4553 if (!fc.inited) {
4554 fc.inited = 1;
4555 fc.config = FcInitLoadConfigAndFonts ();
4556 if (!fc.config) {
4557 lprintf ("FcInitLoadConfigAndFonts failed\n");
4558 return NULL;
4561 if (!fc.config) return NULL;
4563 size = strlen (name);
4564 if (bold) size += sizeof (":bold") - 1;
4565 if (italic) size += sizeof (":italic") - 1;
4566 size += 1;
4568 buf = malloc (size);
4569 if (!buf) {
4570 err (1, "malloc %zu failed", size);
4573 strcpy (buf, name);
4574 if (bold && italic) {
4575 strcat (buf, ":bold:italic");
4577 else {
4578 if (bold) strcat (buf, ":bold");
4579 if (italic) strcat (buf, ":italic");
4581 for (i = 0; i < size; ++i) {
4582 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4585 lprintf ("fcbuf=%s\n", buf);
4586 pat = FcNameParse ((FcChar8 *) buf);
4587 if (!pat) {
4588 printd ("emsg FcNameParse failed\n");
4589 free (buf);
4590 return NULL;
4593 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4594 printd ("emsg FcConfigSubstitute failed\n");
4595 free (buf);
4596 return NULL;
4598 FcDefaultSubstitute (pat);
4600 pat1 = FcFontMatch (fc.config, pat, &result);
4601 if (!pat1) {
4602 printd ("emsg FcFontMatch failed\n");
4603 FcPatternDestroy (pat);
4604 free (buf);
4605 return NULL;
4608 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4609 printd ("emsg FcPatternGetString failed\n");
4610 FcPatternDestroy (pat);
4611 FcPatternDestroy (pat1);
4612 free (buf);
4613 return NULL;
4616 #if 0
4617 printd ("emsg name=%s path=%s\n", name, path);
4618 #endif
4619 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4620 FcPatternDestroy (pat);
4621 FcPatternDestroy (pat1);
4622 free (buf);
4623 return font;
4625 #endif
4627 CAMLprim value ml_init (value csock_v, value params_v)
4629 CAMLparam2 (csock_v, params_v);
4630 CAMLlocal2 (trim_v, fuzz_v);
4631 int ret;
4632 int texcount;
4633 char *fontpath;
4634 int colorspace;
4635 int mustoresize;
4636 int haspboext;
4638 state.csock = Int_val (csock_v);
4639 state.rotate = Int_val (Field (params_v, 0));
4640 state.fitmodel = Int_val (Field (params_v, 1));
4641 trim_v = Field (params_v, 2);
4642 texcount = Int_val (Field (params_v, 3));
4643 state.sliceheight = Int_val (Field (params_v, 4));
4644 mustoresize = Int_val (Field (params_v, 5));
4645 colorspace = Int_val (Field (params_v, 6));
4646 fontpath = String_val (Field (params_v, 7));
4648 if (caml_string_length (Field (params_v, 8)) > 0) {
4649 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4651 if (!state.trimcachepath) {
4652 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4653 strerror (errno));
4656 haspboext = Bool_val (Field (params_v, 9));
4658 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4659 fz_register_document_handlers (state.ctx);
4661 #ifdef USE_FONTCONFIG
4662 if (Bool_val (Field (params_v, 10))) {
4663 fz_install_load_system_font_funcs (
4664 state.ctx, fc_load_system_font_func, NULL
4667 #endif
4669 state.trimmargins = Bool_val (Field (trim_v, 0));
4670 fuzz_v = Field (trim_v, 1);
4671 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4672 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4673 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4674 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4676 set_tex_params (colorspace);
4678 if (*fontpath) {
4679 #ifndef USE_FONTCONFIG
4680 state.face = load_font (fontpath);
4681 #else
4682 FcChar8 *path;
4683 FcResult result;
4684 char *buf = fontpath;
4685 FcPattern *pat, *pat1;
4687 fc.inited = 1;
4688 fc.config = FcInitLoadConfigAndFonts ();
4689 if (!fc.config) {
4690 errx (1, "FcInitLoadConfigAndFonts failed");
4693 pat = FcNameParse ((FcChar8 *) buf);
4694 if (!pat) {
4695 errx (1, "FcNameParse failed");
4698 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4699 errx (1, "FcConfigSubstitute failed");
4701 FcDefaultSubstitute (pat);
4703 pat1 = FcFontMatch (fc.config, pat, &result);
4704 if (!pat1) {
4705 errx (1, "FcFontMatch failed");
4708 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4709 errx (1, "FcPatternGetString failed");
4712 state.face = load_font ((char *) path);
4713 FcPatternDestroy (pat);
4714 FcPatternDestroy (pat1);
4715 #endif
4717 else {
4718 int len;
4719 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4720 0, 0, &len);
4721 state.face = load_builtin_font (data, len);
4723 if (!state.face) _exit (1);
4725 realloctexts (texcount);
4727 if (haspboext) {
4728 setuppbo ();
4731 makestippletex ();
4733 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4734 if (ret) {
4735 errx (1, "pthread_create: %s", strerror (ret));
4738 CAMLreturn (Val_unit);