Sync with upstream
[llpp.git] / link.c
blob8afbda1feae5c60e3f7b04a41ad086e73e49f382
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
4 #include <errno.h>
5 #include <stdio.h>
6 #include <ctype.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <signal.h>
10 #include <wchar.h>
12 #include <unistd.h>
13 #include <pthread.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/utsname.h>
19 #ifdef __CYGWIN__
20 #include <cygwin/socket.h> /* FIONREAD */
21 #else
22 #include <spawn.h>
23 #endif
25 #include <regex.h>
26 #include <stdarg.h>
27 #include <limits.h>
28 #include <inttypes.h>
30 #include <GL/gl.h>
32 #include <caml/fail.h>
33 #include <caml/alloc.h>
34 #include <caml/memory.h>
35 #include <caml/unixsupport.h>
37 #if __GNUC__ < 5
38 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
39 clobbered diagnostics */
40 #pragma GCC diagnostic ignored "-Wclobbered"
41 #endif
43 #include <mupdf/fitz.h>
44 #include <mupdf/pdf.h>
46 #include <ft2build.h>
47 #include FT_FREETYPE_H
49 #ifdef USE_FONTCONFIG
50 #include <fontconfig/fontconfig.h>
51 #endif
53 #define PIGGYBACK
54 #define CACHE_PAGEREFS
56 #ifndef __USE_GNU
57 extern char **environ;
58 #endif
60 #if defined __GNUC__
61 #define NORETURN_ATTR __attribute__ ((noreturn))
62 #define UNUSED_ATTR __attribute__ ((unused))
63 #if !defined __clang__
64 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
65 #else
66 #define OPTIMIZE_ATTR(n)
67 #endif
68 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
69 #else
70 #define NORETURN_ATTR
71 #define UNUSED_ATTR
72 #define OPTIMIZE_ATTR(n)
73 #define GCC_FMT_ATTR(a, b)
74 #endif
76 #define FMT_s "zu"
78 #define FMT_ptr PRIxPTR
79 #define SCN_ptr SCNxPTR
80 #define FMT_ptr_cast(p) ((uintptr_t) (p))
81 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
83 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
84 err (int exitcode, const char *fmt, ...)
86 va_list ap;
87 int savederrno;
89 savederrno = errno;
90 va_start (ap, fmt);
91 vfprintf (stderr, fmt, ap);
92 va_end (ap);
93 fprintf (stderr, ": %s\n", strerror (savederrno));
94 fflush (stderr);
95 _exit (exitcode);
98 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
99 errx (int exitcode, const char *fmt, ...)
101 va_list ap;
103 va_start (ap, fmt);
104 vfprintf (stderr, fmt, ap);
105 va_end (ap);
106 fputc ('\n', stderr);
107 fflush (stderr);
108 _exit (exitcode);
111 #ifndef GL_TEXTURE_RECTANGLE_ARB
112 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
113 #endif
115 #ifdef USE_NPOT
116 #define TEXT_TYPE GL_TEXTURE_2D
117 #else
118 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
119 #endif
121 #ifndef GL_BGRA
122 #define GL_BGRA 0x80E1
123 #endif
125 #ifndef GL_UNSIGNED_INT_8_8_8_8
126 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
127 #endif
129 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
130 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
131 #endif
133 #if 0
134 #define lprintf printf
135 #else
136 #define lprintf(...)
137 #endif
139 #define ARSERT(cond) for (;;) { \
140 if (!(cond)) { \
141 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
143 break; \
146 struct slice {
147 int h;
148 int texindex;
151 struct tile {
152 int w, h;
153 int slicecount;
154 int sliceheight;
155 struct bo *pbo;
156 fz_pixmap *pixmap;
157 struct slice slices[1];
160 struct pagedim {
161 int pageno;
162 int rotate;
163 int left;
164 int tctmready;
165 fz_irect bounds;
166 fz_rect pagebox;
167 fz_rect mediabox;
168 fz_matrix ctm, zoomctm, lctm, tctm;
171 struct slink {
172 enum { SLINK, SANNOT } tag;
173 fz_irect bbox;
174 union {
175 fz_link *link;
176 fz_annot *annot;
177 } u;
180 struct annot {
181 fz_irect bbox;
182 fz_annot *annot;
185 struct page {
186 int tgen;
187 int sgen;
188 int agen;
189 int pageno;
190 int pdimno;
191 fz_stext_page *text;
192 fz_stext_sheet *sheet;
193 fz_page *fzpage;
194 fz_display_list *dlist;
195 int slinkcount;
196 struct slink *slinks;
197 int annotcount;
198 struct annot *annots;
199 struct mark {
200 int i;
201 fz_stext_span *span;
202 } fmark, lmark;
205 struct {
206 int sliceheight;
207 struct pagedim *pagedims;
208 int pagecount;
209 int pagedimcount;
210 fz_document *doc;
211 fz_context *ctx;
212 int w, h;
214 int texindex;
215 int texcount;
216 GLuint *texids;
218 GLenum texiform;
219 GLenum texform;
220 GLenum texty;
222 fz_colorspace *colorspace;
224 struct {
225 int w, h;
226 struct slice *slice;
227 } *texowners;
229 int rotate;
230 enum { FitWidth, FitProportional, FitPage } fitmodel;
231 int trimmargins;
232 int needoutline;
233 int gen;
234 int aalevel;
236 int trimanew;
237 fz_irect trimfuzz;
238 fz_pixmap *pig;
240 pthread_t thread;
241 int csock;
242 FT_Face face;
244 char *trimcachepath;
245 int cxack;
246 int dirty;
248 GLuint stid;
250 int bo_usable;
251 GLuint boid;
253 void (*glBindBufferARB) (GLenum, GLuint);
254 GLboolean (*glUnmapBufferARB) (GLenum);
255 void *(*glMapBufferARB) (GLenum, GLenum);
256 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
257 void (*glGenBuffersARB) (GLsizei, GLuint *);
258 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
260 GLfloat texcoords[8];
261 GLfloat vertices[16];
263 #ifdef CACHE_PAGEREFS
264 struct {
265 int idx;
266 int count;
267 pdf_obj **objs;
268 pdf_document *pdf;
269 } pdflut;
270 #endif
271 } state;
273 struct bo {
274 GLuint id;
275 void *ptr;
276 size_t size;
279 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
281 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
284 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
286 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
289 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
291 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
292 m.a, m.b, m.c, m.d, m.e, m.f);
295 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
297 static void lock (const char *cap)
299 int ret = pthread_mutex_lock (&mutex);
300 if (ret) {
301 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
305 static void unlock (const char *cap)
307 int ret = pthread_mutex_unlock (&mutex);
308 if (ret) {
309 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
313 static int trylock (const char *cap)
315 int ret = pthread_mutex_trylock (&mutex);
316 if (ret && ret != EBUSY) {
317 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
319 return ret == EBUSY;
322 static void *parse_pointer (const char *cap, const char *s)
324 int ret;
325 void *ptr;
327 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
328 if (ret != 1) {
329 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
331 return ptr;
334 static double now (void)
336 struct timeval tv;
338 if (gettimeofday (&tv, NULL)) {
339 err (1, "gettimeofday");
341 return tv.tv_sec + tv.tv_usec*1e-6;
344 static int hasdata (void)
346 int ret, avail;
347 ret = ioctl (state.csock, FIONREAD, &avail);
348 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
349 return avail > 0;
352 CAMLprim value ml_hasdata (value fd_v)
354 CAMLparam1 (fd_v);
355 int ret, avail;
357 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
358 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
359 CAMLreturn (Val_bool (avail > 0));
362 static void readdata (int fd, void *p, int size)
364 ssize_t n;
366 again:
367 n = read (fd, p, size);
368 if (n < 0) {
369 if (errno == EINTR) goto again;
370 err (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
372 if (n - size) {
373 if (!n) errx (1, "EOF while reading");
374 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
378 static void writedata (int fd, char *p, int size)
380 ssize_t n;
382 /* One should lookup type punning/strict aliasing etc in standard,DRs,Web to
383 convince herself that this is:
384 a. safe
385 b. practically the only way to achieve the result
386 (union puns notwithstanding) */
387 memcpy (p, &size, 4);
388 n = write (fd, p, size + 4);
389 if (n - size - 4) {
390 if (!n) errx (1, "EOF while writing data");
391 err (1, "write (fd %d, req %d, ret %zd)", fd, size + 4, n);
395 static int readlen (int fd)
397 /* Type punned unions here. Why? Less code (Adjusted by more comments).
398 https://en.wikipedia.org/wiki/Type_punning */
399 union { int len; char raw[4]; } buf;
400 readdata (fd, buf.raw, 4);
401 return buf.len;
404 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
406 CAMLparam3 (fd_v, bytes_v, len_v);
407 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
408 CAMLreturn0;
411 CAMLprim value ml_rcmd (value fd_v)
413 CAMLparam1 (fd_v);
414 CAMLlocal1 (strdata_v);
415 int fd = Int_val (fd_v);
416 int len = readlen (fd);
417 strdata_v = caml_alloc_string (len);
418 readdata (fd, String_val (strdata_v), len);
419 CAMLreturn (strdata_v);
422 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
424 int size = 200, len;
425 va_list ap;
426 char *buf;
428 buf = malloc (size);
429 for (;;) {
430 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
432 va_start (ap, fmt);
433 len = vsnprintf (buf + 4, size - 4, fmt, ap);
434 va_end (ap);
436 if (len > -1) {
437 if (len < size - 4) {
438 writedata (state.csock, buf, len);
439 break;
441 else size = len + 5;
443 else {
444 err (1, "vsnprintf for `%s' failed", fmt);
446 buf = realloc (buf, size);
448 free (buf);
451 static void closedoc (void)
453 #ifdef CACHE_PAGEREFS
454 if (state.pdflut.objs) {
455 int i;
457 for (i = 0; i < state.pdflut.count; ++i) {
458 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
460 free (state.pdflut.objs);
461 state.pdflut.objs = NULL;
462 state.pdflut.idx = 0;
464 #endif
465 if (state.doc) {
466 fz_drop_document (state.ctx, state.doc);
467 state.doc = NULL;
471 static int openxref (char *filename, char *password)
473 int i;
475 for (i = 0; i < state.texcount; ++i) {
476 state.texowners[i].w = -1;
477 state.texowners[i].slice = NULL;
480 closedoc ();
482 state.dirty = 0;
483 if (state.pagedims) {
484 free (state.pagedims);
485 state.pagedims = NULL;
487 state.pagedimcount = 0;
489 fz_set_aa_level (state.ctx, state.aalevel);
490 #ifdef CSS_HACK_TO_READ_EPUBS_COMFORTABLY
491 fz_set_user_css (state.ctx,
492 "body { margin-left: 20%; margin-right: 20%; }");
493 #endif
494 state.doc = fz_open_document (state.ctx, filename);
495 if (fz_needs_password (state.ctx, state.doc)) {
496 if (password && !*password) {
497 printd ("pass");
498 return 0;
500 else {
501 int ok = fz_authenticate_password (state.ctx, state.doc, password);
502 if (!ok) {
503 printd ("pass fail");
504 return 0;
508 state.pagecount = fz_count_pages (state.ctx, state.doc);
509 return 1;
512 static void pdfinfo (void)
514 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
515 if (pdf) {
516 pdf_obj *infoobj;
518 printd ("info PDF version\t%d.%d",
519 pdf->version / 10, pdf->version % 10);
521 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
522 pdf), "Info");
523 if (infoobj) {
524 unsigned int i;
525 char *s;
526 char *items[] = { "Title", "Author", "Creator",
527 "Producer", "CreationDate" };
529 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
530 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
531 s = pdf_to_utf8 (state.ctx, pdf, obj);
532 if (*s) printd ("info %s\t%s", items[i], s);
533 fz_free (state.ctx, s);
536 printd ("infoend");
540 static void unlinktile (struct tile *tile)
542 int i;
544 for (i = 0; i < tile->slicecount; ++i) {
545 struct slice *s = &tile->slices[i];
547 if (s->texindex != -1) {
548 if (state.texowners[s->texindex].slice == s) {
549 state.texowners[s->texindex].slice = NULL;
555 static void freepage (struct page *page)
557 if (!page) return;
558 if (page->text) {
559 fz_drop_stext_page (state.ctx, page->text);
561 if (page->sheet) {
562 fz_drop_stext_sheet (state.ctx, page->sheet);
564 if (page->slinks) {
565 free (page->slinks);
567 fz_drop_display_list (state.ctx, page->dlist);
568 fz_drop_page (state.ctx, page->fzpage);
569 free (page);
572 static void freetile (struct tile *tile)
574 unlinktile (tile);
575 if (!tile->pbo) {
576 #ifndef PIGGYBACK
577 fz_drop_pixmap (state.ctx, tile->pixmap);
578 #else
579 if (state.pig) {
580 fz_drop_pixmap (state.ctx, state.pig);
582 state.pig = tile->pixmap;
583 #endif
585 else {
586 free (tile->pbo);
587 fz_drop_pixmap (state.ctx, tile->pixmap);
589 free (tile);
592 #ifdef __ALTIVEC__
593 #include <stdint.h>
594 #include <altivec.h>
596 static int cacheline32bytes;
598 static void __attribute__ ((constructor)) clcheck (void)
600 char **envp = environ;
601 unsigned long *auxv;
603 while (*envp++);
605 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
606 if (*auxv == 19) {
607 cacheline32bytes = auxv[1] == 32;
608 return;
613 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
615 size_t size = pixmap->w * pixmap->h * pixmap->n;
616 if (cacheline32bytes && size > 32) {
617 intptr_t a1, a2, diff;
618 size_t sizea, i;
619 vector unsigned char v = vec_splat_u8 (-1);
620 vector unsigned char *p;
622 a1 = a2 = (intptr_t) pixmap->samples;
623 a2 = (a1 + 31) & ~31;
624 diff = a2 - a1;
625 sizea = size - diff;
626 p = (void *) a2;
628 while (a1 != a2) *(char *) a1++ = 0xff;
629 for (i = 0; i < (sizea & ~31); i += 32) {
630 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
631 vec_st (v, i, p);
632 vec_st (v, i + 16, p);
634 while (i < sizea) *((char *) a1 + i++) = 0xff;
636 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
638 #else
639 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
640 #endif
642 static void trimctm (pdf_page *page, int pindex)
644 fz_matrix ctm;
645 struct pagedim *pdim = &state.pagedims[pindex];
647 if (!pdim->tctmready) {
648 if (state.trimmargins) {
649 fz_rect realbox, 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);
663 else {
664 ctm = fz_identity;
666 pdim->tctm = ctm;
667 pdim->tctmready = 1;
671 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
673 fz_matrix ctm, tm;
674 int pdimno = pdim - state.pagedims;
676 if (pdf_specifics (state.ctx, state.doc)) {
677 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
678 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
680 else {
681 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
682 fz_concat (&ctm, &tm, &pdim->ctm);
684 return ctm;
687 static fz_matrix pagectm (struct page *page)
689 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
692 static void *loadpage (int pageno, int pindex)
694 fz_device *dev;
695 struct page *page;
697 page = calloc (sizeof (struct page), 1);
698 if (!page) {
699 err (1, "calloc page %d", pageno);
702 page->dlist = fz_new_display_list (state.ctx, NULL);
703 dev = fz_new_list_device (state.ctx, page->dlist);
704 fz_try (state.ctx) {
705 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
706 fz_run_page (state.ctx, page->fzpage, dev,
707 &fz_identity, NULL);
709 fz_catch (state.ctx) {
710 page->fzpage = NULL;
712 fz_close_device (state.ctx, dev);
713 fz_drop_device (state.ctx, dev);
715 page->pdimno = pindex;
716 page->pageno = pageno;
717 page->sgen = state.gen;
718 page->agen = state.gen;
719 page->tgen = state.gen;
720 return page;
723 static struct tile *alloctile (int h)
725 int i;
726 int slicecount;
727 size_t tilesize;
728 struct tile *tile;
730 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
731 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
732 tile = calloc (tilesize, 1);
733 if (!tile) {
734 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
736 for (i = 0; i < slicecount; ++i) {
737 int sh = fz_mini (h, state.sliceheight);
738 tile->slices[i].h = sh;
739 tile->slices[i].texindex = -1;
740 h -= sh;
742 tile->slicecount = slicecount;
743 tile->sliceheight = state.sliceheight;
744 return tile;
747 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
748 struct bo *pbo)
750 fz_rect rect;
751 fz_irect bbox;
752 fz_matrix ctm;
753 fz_device *dev;
754 struct tile *tile;
755 struct pagedim *pdim;
757 tile = alloctile (h);
758 pdim = &state.pagedims[page->pdimno];
760 bbox = pdim->bounds;
761 bbox.x0 += x;
762 bbox.y0 += y;
763 bbox.x1 = bbox.x0 + w;
764 bbox.y1 = bbox.y0 + h;
766 if (state.pig) {
767 if (state.pig->w == w
768 && state.pig->h == h
769 && state.pig->colorspace == state.colorspace) {
770 tile->pixmap = state.pig;
771 tile->pixmap->x = bbox.x0;
772 tile->pixmap->y = bbox.y0;
774 else {
775 fz_drop_pixmap (state.ctx, state.pig);
777 state.pig = NULL;
779 if (!tile->pixmap) {
780 if (pbo) {
781 tile->pixmap =
782 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
783 &bbox, 1, pbo->ptr);
784 tile->pbo = pbo;
786 else {
787 tile->pixmap =
788 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
792 tile->w = w;
793 tile->h = h;
794 clearpixmap (tile->pixmap);
796 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
797 ctm = pagectm (page);
798 fz_rect_from_irect (&rect, &bbox);
799 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
800 fz_close_device (state.ctx, dev);
801 fz_drop_device (state.ctx, dev);
803 return tile;
806 #ifdef CACHE_PAGEREFS
807 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
808 thanks to Robin Watts */
809 static void
810 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
812 fz_context *ctx = state.ctx; /* doc->ctx; */
813 pdf_obj *kids;
814 int i, len;
816 if (state.pdflut.idx == state.pagecount) return;
818 kids = pdf_dict_gets (ctx, node, "Kids");
819 len = pdf_array_len (ctx, kids);
821 if (len == 0)
822 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
824 if (pdf_mark_obj (ctx, node))
825 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
826 for (i = 0; i < len; i++) {
827 pdf_obj *kid = pdf_array_get (ctx, kids, i);
828 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
829 if (*type
830 ? !strcmp (type, "Pages")
831 : pdf_dict_gets (ctx, kid, "Kids")
832 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
833 pdf_collect_pages (doc, kid);
835 else {
836 if (*type
837 ? strcmp (type, "Page") != 0
838 : !pdf_dict_gets (ctx, kid, "MediaBox"))
839 fz_warn (ctx, "non-page object in page tree (%s)", type);
840 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
843 pdf_unmark_obj (ctx, node);
846 static void
847 pdf_load_page_objs (pdf_document *doc)
849 pdf_obj *root = pdf_dict_gets (state.ctx,
850 pdf_trailer (state.ctx, doc), "Root");
851 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
853 if (!node)
854 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
856 state.pdflut.idx = 0;
857 pdf_collect_pages (doc, node);
859 #endif
861 static void initpdims (int wthack)
863 double start, end;
864 FILE *trimf = NULL;
865 fz_rect rootmediabox;
866 int pageno, trim, show;
867 int trimw = 0, cxcount;
868 fz_context *ctx = state.ctx;
869 pdf_document *pdf = pdf_specifics (ctx, state.doc);
871 fz_var (trimw);
872 fz_var (trimf);
873 fz_var (cxcount);
874 start = now ();
876 if (state.trimmargins && state.trimcachepath) {
877 trimf = fopen (state.trimcachepath, "rb");
878 if (!trimf) {
879 trimf = fopen (state.trimcachepath, "wb");
880 trimw = 1;
884 if (state.trimmargins || pdf || !state.cxack)
885 cxcount = state.pagecount;
886 else
887 cxcount = fz_mini (state.pagecount, 1);
889 if (pdf) {
890 pdf_obj *obj;
891 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
892 "Root/Pages/MediaBox");
893 pdf_to_rect (ctx, obj, &rootmediabox);
896 #ifdef CACHE_PAGEREFS
897 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
898 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
899 if (!state.pdflut.objs) {
900 err (1, "malloc pageobjs %zu %d %zu failed",
901 sizeof (*state.pdflut.objs), cxcount,
902 sizeof (*state.pdflut.objs) * cxcount);
904 state.pdflut.count = cxcount;
905 pdf_load_page_objs (pdf);
906 state.pdflut.pdf = pdf;
908 #endif
910 for (pageno = 0; pageno < cxcount; ++pageno) {
911 int rotate;
912 struct pagedim *p;
913 fz_rect mediabox;
915 fz_var (rotate);
916 if (pdf) {
917 pdf_obj *pageref, *pageobj;
919 #ifdef CACHE_PAGEREFS
920 pageref = state.pdflut.objs[pageno];
921 #else
922 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
923 #endif
924 pageobj = pdf_resolve_indirect (ctx, pageref);
925 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
927 if (state.trimmargins) {
928 pdf_obj *obj;
929 pdf_page *page;
931 fz_try (ctx) {
932 page = pdf_load_page (ctx, pdf, pageno);
933 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
934 trim = state.trimanew || !obj;
935 if (trim) {
936 fz_rect rect;
937 fz_device *dev;
938 fz_matrix ctm, page_ctm;
940 dev = fz_new_bbox_device (ctx, &rect);
941 dev->hints |= FZ_IGNORE_SHADE;
942 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
943 fz_invert_matrix (&ctm, &page_ctm);
944 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
945 fz_close_device (state.ctx, dev);
946 fz_drop_device (ctx, dev);
948 rect.x0 += state.trimfuzz.x0;
949 rect.x1 += state.trimfuzz.x1;
950 rect.y0 += state.trimfuzz.y0;
951 rect.y1 += state.trimfuzz.y1;
952 fz_transform_rect (&rect, &ctm);
953 fz_intersect_rect (&rect, &mediabox);
955 if (!fz_is_empty_rect (&rect)) {
956 mediabox = rect;
959 obj = pdf_new_array (ctx, pdf, 4);
960 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
961 mediabox.x0));
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.y0));
964 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
965 mediabox.x1));
966 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
967 mediabox.y1));
968 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
970 else {
971 mediabox.x0 = pdf_to_real (ctx,
972 pdf_array_get (ctx, obj, 0));
973 mediabox.y0 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 1));
975 mediabox.x1 = pdf_to_real (ctx,
976 pdf_array_get (ctx, obj, 2));
977 mediabox.y1 = pdf_to_real (ctx,
978 pdf_array_get (ctx, obj, 3));
981 fz_drop_page (ctx, &page->super);
982 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
983 if (show) {
984 printd ("progress %f Trimming %d",
985 (double) (pageno + 1) / state.pagecount,
986 pageno + 1);
989 fz_catch (ctx) {
990 fprintf (stderr, "failed to load page %d\n", pageno+1);
993 else {
994 int empty = 0;
995 fz_rect cropbox;
997 pdf_to_rect (ctx,
998 pdf_dict_gets (ctx, pageobj, "MediaBox"),
999 &mediabox);
1000 if (fz_is_empty_rect (&mediabox)) {
1001 mediabox.x0 = 0;
1002 mediabox.y0 = 0;
1003 mediabox.x1 = 612;
1004 mediabox.y1 = 792;
1005 empty = 1;
1008 pdf_to_rect (ctx,
1009 pdf_dict_gets (ctx, pageobj, "CropBox"),
1010 &cropbox);
1011 if (!fz_is_empty_rect (&cropbox)) {
1012 if (empty) {
1013 mediabox = cropbox;
1015 else {
1016 fz_intersect_rect (&mediabox, &cropbox);
1019 else {
1020 if (empty) {
1021 if (fz_is_empty_rect (&rootmediabox)) {
1022 fprintf (stderr,
1023 "cannot find page size for page %d\n",
1024 pageno+1);
1026 else {
1027 mediabox = rootmediabox;
1033 else {
1034 if (state.trimmargins && trimw) {
1035 fz_page *page;
1037 fz_try (ctx) {
1038 page = fz_load_page (ctx, state.doc, pageno);
1039 fz_bound_page (ctx, page, &mediabox);
1040 rotate = 0;
1041 if (state.trimmargins) {
1042 fz_rect rect;
1043 fz_device *dev;
1045 dev = fz_new_bbox_device (ctx, &rect);
1046 dev->hints |= FZ_IGNORE_SHADE;
1047 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1048 fz_close_device (state.ctx, dev);
1049 fz_drop_device (ctx, dev);
1051 rect.x0 += state.trimfuzz.x0;
1052 rect.x1 += state.trimfuzz.x1;
1053 rect.y0 += state.trimfuzz.y0;
1054 rect.y1 += state.trimfuzz.y1;
1055 fz_intersect_rect (&rect, &mediabox);
1057 if (!fz_is_empty_rect (&rect)) {
1058 mediabox = rect;
1061 fz_drop_page (ctx, page);
1062 if (!state.cxack) {
1063 printd ("progress %f loading %d",
1064 (double) (pageno + 1) / state.pagecount,
1065 pageno + 1);
1068 fz_catch (ctx) {
1070 if (trimf) {
1071 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1072 if (n - 1) {
1073 err (1, "fwrite trim mediabox");
1077 else {
1078 if (trimf) {
1079 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1080 if (n - 1) {
1081 err (1, "fread trim mediabox %d", pageno);
1084 else {
1085 fz_page *page;
1086 fz_try (ctx) {
1087 page = fz_load_page (ctx, state.doc, pageno);
1088 fz_bound_page (ctx, page, &mediabox);
1089 fz_drop_page (ctx, page);
1091 show = !state.trimmargins && pageno % 20 == 0;
1092 if (show) {
1093 printd ("progress %f Gathering dimensions %d",
1094 (double) (pageno) / state.pagecount,
1095 pageno);
1098 fz_catch (ctx) {
1099 fprintf (stderr, "failed to load page %d\n", pageno);
1105 if (state.pagedimcount == 0
1106 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1107 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1108 size_t size;
1110 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1111 state.pagedims = realloc (state.pagedims, size);
1112 if (!state.pagedims) {
1113 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1114 size, state.pagedimcount + 1);
1117 p = &state.pagedims[state.pagedimcount++];
1118 p->rotate = rotate;
1119 p->mediabox = mediabox;
1120 p->pageno = pageno;
1123 end = now ();
1124 if (!wthack) {
1125 printd ("progress 1 %s %d pages in %f seconds",
1126 state.trimmargins ? "Trimmed" : "Processed",
1127 state.pagecount, end - start);
1129 state.trimanew = 0;
1130 if (trimf) {
1131 if (fclose (trimf)) {
1132 err (1, "fclose");
1137 static void layout (void)
1139 int pindex;
1140 fz_rect box;
1141 fz_matrix ctm, rm;
1142 struct pagedim *p = p;
1143 double zw, w, maxw = 0.0, zoom = zoom;
1145 if (state.pagedimcount == 0) return;
1147 switch (state.fitmodel) {
1148 case FitProportional:
1149 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1150 double x0, x1;
1152 p = &state.pagedims[pindex];
1153 fz_rotate (&rm, p->rotate + state.rotate);
1154 box = p->mediabox;
1155 fz_transform_rect (&box, &rm);
1157 x0 = fz_min (box.x0, box.x1);
1158 x1 = fz_max (box.x0, box.x1);
1160 w = x1 - x0;
1161 maxw = fz_max (w, maxw);
1162 zoom = state.w / maxw;
1164 break;
1166 case FitPage:
1167 maxw = state.w;
1168 break;
1170 case FitWidth:
1171 break;
1173 default:
1174 ARSERT (0 && state.fitmodel);
1177 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1178 fz_rect rect;
1179 fz_matrix tm, sm;
1181 p = &state.pagedims[pindex];
1182 fz_rotate (&ctm, state.rotate);
1183 fz_rotate (&rm, p->rotate + state.rotate);
1184 box = p->mediabox;
1185 fz_transform_rect (&box, &rm);
1186 w = box.x1 - box.x0;
1187 switch (state.fitmodel) {
1188 case FitProportional:
1189 p->left = ((maxw - w) * zoom) / 2.0;
1190 break;
1191 case FitPage:
1193 double zh, h;
1194 zw = maxw / w;
1195 h = box.y1 - box.y0;
1196 zh = state.h / h;
1197 zoom = fz_min (zw, zh);
1198 p->left = (maxw - (w * zoom)) / 2.0;
1200 break;
1201 case FitWidth:
1202 p->left = 0;
1203 zoom = state.w / w;
1204 break;
1207 fz_scale (&p->zoomctm, zoom, zoom);
1208 fz_concat (&ctm, &p->zoomctm, &ctm);
1210 fz_rotate (&rm, p->rotate);
1211 p->pagebox = p->mediabox;
1212 fz_transform_rect (&p->pagebox, &rm);
1213 p->pagebox.x1 -= p->pagebox.x0;
1214 p->pagebox.y1 -= p->pagebox.y0;
1215 p->pagebox.x0 = 0;
1216 p->pagebox.y0 = 0;
1217 rect = p->pagebox;
1218 fz_transform_rect (&rect, &ctm);
1219 fz_round_rect (&p->bounds, &rect);
1220 p->ctm = ctm;
1222 fz_translate (&tm, 0, -p->mediabox.y1);
1223 fz_scale (&sm, zoom, -zoom);
1224 fz_concat (&ctm, &tm, &sm);
1225 fz_concat (&p->lctm, &ctm, &rm);
1227 p->tctmready = 0;
1230 do {
1231 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1232 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1233 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1234 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1235 int boundw = x1 - x0;
1236 int boundh = y1 - y0;
1238 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1239 } while (p-- != state.pagedims);
1242 static
1243 struct anchor { int n; int x; int y; int w; int h; }
1244 desttoanchor (fz_link_dest *dest)
1246 int i;
1247 struct anchor a;
1248 struct pagedim *pdim = state.pagedims;
1250 a.n = -1;
1251 a.x = 0;
1252 a.y = 0;
1253 for (i = 0; i < state.pagedimcount; ++i) {
1254 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1255 break;
1256 pdim = &state.pagedims[i];
1258 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1259 fz_point p;
1260 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1261 p.x = dest->ld.gotor.lt.x;
1262 else
1263 p.x = 0.0;
1264 p.y = dest->ld.gotor.lt.y;
1265 fz_transform_point (&p, &pdim->lctm);
1266 a.x = p.x;
1267 a.y = p.y;
1269 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1270 double x0, x1, y0, y1;
1272 x0 = fz_min (pdim->bounds.x0, pdim->bounds.x1);
1273 x1 = fz_max (pdim->bounds.x0, pdim->bounds.x1);
1274 a.w = x1 - x0;
1275 y0 = fz_min (pdim->bounds.y0, pdim->bounds.y1);
1276 y1 = fz_max (pdim->bounds.y0, pdim->bounds.y1);
1277 a.h = y1 - y0;
1278 a.n = dest->ld.gotor.page;
1280 return a;
1283 static void recurse_outline (fz_outline *outline, int level)
1285 while (outline) {
1286 switch (outline->dest.kind) {
1287 case FZ_LINK_GOTO:
1289 struct anchor a = desttoanchor (&outline->dest);
1291 if (a.n >= 0) {
1292 printd ("o %d %d %d %d %s",
1293 level, a.n, a.y, a.h, outline->title);
1296 break;
1298 case FZ_LINK_URI:
1299 printd ("ou %d %" FMT_s " %s %s", level,
1300 strlen (outline->title), outline->title,
1301 outline->dest.ld.uri.uri);
1302 break;
1304 case FZ_LINK_NONE:
1305 printd ("on %d %s", level, outline->title);
1306 break;
1308 default:
1309 printd ("emsg Unhandled outline kind %d for %s\n",
1310 outline->dest.kind, outline->title);
1311 break;
1313 if (outline->down) {
1314 recurse_outline (outline->down, level + 1);
1316 outline = outline->next;
1320 static void process_outline (void)
1322 fz_outline *outline;
1324 if (!state.needoutline || !state.pagedimcount) return;
1326 state.needoutline = 0;
1327 outline = fz_load_outline (state.ctx, state.doc);
1328 if (outline) {
1329 recurse_outline (outline, 0);
1330 fz_drop_outline (state.ctx, outline);
1334 static char *strofspan (fz_stext_span *span)
1336 char *p;
1337 char utf8[10];
1338 fz_stext_char *ch;
1339 size_t size = 0, cap = 80;
1341 p = malloc (cap + 1);
1342 if (!p) return NULL;
1344 for (ch = span->text; ch < span->text + span->len; ++ch) {
1345 int n = fz_runetochar (utf8, ch->c);
1346 if (size + n > cap) {
1347 cap *= 2;
1348 p = realloc (p, cap + 1);
1349 if (!p) return NULL;
1352 memcpy (p + size, utf8, n);
1353 size += n;
1355 p[size] = 0;
1356 return p;
1359 static int matchspan (regex_t *re, fz_stext_span *span,
1360 int stop, int pageno, double start)
1362 int ret;
1363 char *p;
1364 regmatch_t rm;
1365 int a, b, c;
1366 fz_rect sb, eb;
1367 fz_point p1, p2, p3, p4;
1369 p = strofspan (span);
1370 if (!p) return -1;
1372 ret = regexec (re, p, 1, &rm, 0);
1373 if (ret) {
1374 free (p);
1375 if (ret != REG_NOMATCH) {
1376 size_t size;
1377 char errbuf[80];
1378 size = regerror (ret, re, errbuf, sizeof (errbuf));
1379 printd ("msg regexec error `%.*s'",
1380 (int) size, errbuf);
1381 return -1;
1383 return 0;
1385 else {
1386 int l = span->len;
1388 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1389 c += fz_runelen (span->text[a].c);
1391 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1392 c += fz_runelen (span->text[b].c);
1395 if (fz_runelen (span->text[b].c) > 1) {
1396 b = fz_maxi (0, b-1);
1399 fz_stext_char_bbox (state.ctx, &sb, span, a);
1400 fz_stext_char_bbox (state.ctx, &eb, span, b);
1402 p1.x = sb.x0;
1403 p1.y = sb.y0;
1404 p2.x = eb.x1;
1405 p2.y = sb.y0;
1406 p3.x = eb.x1;
1407 p3.y = eb.y1;
1408 p4.x = sb.x0;
1409 p4.y = eb.y1;
1411 if (!stop) {
1412 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1413 pageno, 1,
1414 p1.x, p1.y,
1415 p2.x, p2.y,
1416 p3.x, p3.y,
1417 p4.x, p4.y);
1419 printd ("progress 1 found at %d `%.*s' in %f sec",
1420 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1421 now () - start);
1423 else {
1424 printd ("match %d %d %f %f %f %f %f %f %f %f",
1425 pageno, 2,
1426 p1.x, p1.y,
1427 p2.x, p2.y,
1428 p3.x, p3.y,
1429 p4.x, p4.y);
1431 free (p);
1432 return 1;
1436 static int compareblocks (const void *l, const void *r)
1438 fz_stext_block const *ls = l;
1439 fz_stext_block const *rs = r;
1440 return ls->bbox.y0 - rs->bbox.y0;
1443 /* wishful thinking function */
1444 static void search (regex_t *re, int pageno, int y, int forward)
1446 int i, j;
1447 fz_device *tdev;
1448 fz_stext_page *text;
1449 fz_stext_sheet *sheet;
1450 struct pagedim *pdim, *pdimprev;
1451 int stop = 0, niters = 0;
1452 double start, end;
1453 fz_page *page;
1455 start = now ();
1456 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1457 if (niters++ == 5) {
1458 niters = 0;
1459 if (hasdata ()) {
1460 printd ("progress 1 attention requested aborting search at %d",
1461 pageno);
1462 stop = 1;
1464 else {
1465 printd ("progress %f searching in page %d",
1466 (double) (pageno + 1) / state.pagecount,
1467 pageno);
1470 pdimprev = NULL;
1471 for (i = 0; i < state.pagedimcount; ++i) {
1472 pdim = &state.pagedims[i];
1473 if (pdim->pageno == pageno) {
1474 goto found;
1476 if (pdim->pageno > pageno) {
1477 pdim = pdimprev;
1478 goto found;
1480 pdimprev = pdim;
1482 pdim = pdimprev;
1483 found:
1485 sheet = fz_new_stext_sheet (state.ctx);
1486 text = fz_new_stext_page (state.ctx);
1487 tdev = fz_new_stext_device (state.ctx, sheet, text);
1489 page = fz_load_page (state.ctx, state.doc, pageno);
1491 fz_matrix ctm = pagectm1 (page, pdim);
1492 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1495 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1496 fz_close_device (state.ctx, tdev);
1497 fz_drop_device (state.ctx, tdev);
1499 for (j = 0; j < text->len; ++j) {
1500 int k;
1501 fz_page_block *pb;
1502 fz_stext_block *block;
1504 pb = &text->blocks[forward ? j : text->len - 1 - j];
1505 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1506 block = pb->u.text;
1508 for (k = 0; k < block->len; ++k) {
1509 fz_stext_line *line;
1510 fz_stext_span *span;
1512 if (forward) {
1513 line = &block->lines[k];
1514 if (line->bbox.y0 < y + 1) continue;
1516 else {
1517 line = &block->lines[block->len - 1 - k];
1518 if (line->bbox.y0 > y - 1) continue;
1521 for (span = line->first_span; span; span = span->next) {
1522 switch (matchspan (re, span, stop, pageno, start)) {
1523 case 0: break;
1524 case 1: stop = 1; break;
1525 case -1: stop = 1; goto endloop;
1530 if (forward) {
1531 pageno += 1;
1532 y = 0;
1534 else {
1535 pageno -= 1;
1536 y = INT_MAX;
1538 endloop:
1539 fz_drop_stext_page (state.ctx, text);
1540 fz_drop_stext_sheet (state.ctx, sheet);
1541 fz_drop_page (state.ctx, page);
1543 end = now ();
1544 if (!stop) {
1545 printd ("progress 1 no matches %f sec", end - start);
1547 printd ("clearrects");
1550 static void set_tex_params (int colorspace)
1552 union {
1553 unsigned char b;
1554 unsigned int s;
1555 } endianness = {1};
1557 switch (colorspace) {
1558 case 0:
1559 state.texiform = GL_RGBA8;
1560 state.texform = GL_RGBA;
1561 state.texty = GL_UNSIGNED_BYTE;
1562 state.colorspace = fz_device_rgb (state.ctx);
1563 break;
1564 case 1:
1565 state.texiform = GL_RGBA8;
1566 state.texform = GL_BGRA;
1567 state.texty = endianness.s > 1
1568 ? GL_UNSIGNED_INT_8_8_8_8
1569 : GL_UNSIGNED_INT_8_8_8_8_REV;
1570 state.colorspace = fz_device_bgr (state.ctx);
1571 break;
1572 case 2:
1573 state.texiform = GL_LUMINANCE_ALPHA;
1574 state.texform = GL_LUMINANCE_ALPHA;
1575 state.texty = GL_UNSIGNED_BYTE;
1576 state.colorspace = fz_device_gray (state.ctx);
1577 break;
1578 default:
1579 errx (1, "invalid colorspce %d", colorspace);
1583 static void realloctexts (int texcount)
1585 size_t size;
1587 if (texcount == state.texcount) return;
1589 if (texcount < state.texcount) {
1590 glDeleteTextures (state.texcount - texcount,
1591 state.texids + texcount);
1594 size = texcount * sizeof (*state.texids);
1595 state.texids = realloc (state.texids, size);
1596 if (!state.texids) {
1597 err (1, "realloc texids %" FMT_s, size);
1600 size = texcount * sizeof (*state.texowners);
1601 state.texowners = realloc (state.texowners, size);
1602 if (!state.texowners) {
1603 err (1, "realloc texowners %" FMT_s, size);
1605 if (texcount > state.texcount) {
1606 int i;
1608 glGenTextures (texcount - state.texcount,
1609 state.texids + state.texcount);
1610 for (i = state.texcount; i < texcount; ++i) {
1611 state.texowners[i].w = -1;
1612 state.texowners[i].slice = NULL;
1615 state.texcount = texcount;
1616 state.texindex = 0;
1619 static char *mbtoutf8 (char *s)
1621 char *p, *r;
1622 wchar_t *tmp;
1623 size_t i, ret, len;
1625 len = mbstowcs (NULL, s, strlen (s));
1626 if (len == 0) {
1627 return s;
1629 else {
1630 if (len == (size_t) -1) {
1631 return s;
1635 tmp = malloc (len * sizeof (wchar_t));
1636 if (!tmp) {
1637 return s;
1640 ret = mbstowcs (tmp, s, len);
1641 if (ret == (size_t) -1) {
1642 free (tmp);
1643 return s;
1646 len = 0;
1647 for (i = 0; i < ret; ++i) {
1648 len += fz_runelen (tmp[i]);
1651 p = r = malloc (len + 1);
1652 if (!r) {
1653 free (tmp);
1654 return s;
1657 for (i = 0; i < ret; ++i) {
1658 p += fz_runetochar (p, tmp[i]);
1660 *p = 0;
1661 free (tmp);
1662 return r;
1665 CAMLprim value ml_mbtoutf8 (value s_v)
1667 CAMLparam1 (s_v);
1668 CAMLlocal1 (ret_v);
1669 char *s, *r;
1671 s = String_val (s_v);
1672 r = mbtoutf8 (s);
1673 if (r == s) {
1674 ret_v = s_v;
1676 else {
1677 ret_v = caml_copy_string (r);
1678 free (r);
1680 CAMLreturn (ret_v);
1683 static void * mainloop (void UNUSED_ATTR *unused)
1685 char *p = NULL;
1686 int len, ret, oldlen = 0;
1688 fz_var (p);
1689 fz_var (oldlen);
1690 for (;;) {
1691 len = readlen (state.csock);
1692 if (len == 0) {
1693 errx (1, "readlen returned 0");
1696 if (oldlen < len + 1) {
1697 p = realloc (p, len + 1);
1698 if (!p) {
1699 err (1, "realloc %d failed", len + 1);
1701 oldlen = len + 1;
1703 readdata (state.csock, p, len);
1704 p[len] = 0;
1706 if (!strncmp ("open", p, 4)) {
1707 int wthack, off, ok = 0;
1708 char *password;
1709 char *filename;
1710 char *utf8filename;
1711 size_t filenamelen;
1713 fz_var (ok);
1714 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1715 if (ret != 2) {
1716 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1719 filename = p + 5 + off;
1720 filenamelen = strlen (filename);
1721 password = filename + filenamelen + 1;
1723 lock ("open");
1724 fz_try (state.ctx) {
1725 ok = openxref (filename, password);
1727 fz_catch (state.ctx) {
1728 utf8filename = mbtoutf8 (filename);
1729 printd ("msg Could not open %s", utf8filename);
1731 if (ok) {
1732 pdfinfo ();
1733 initpdims (wthack);
1735 unlock ("open");
1737 if (ok) {
1738 if (!wthack) {
1739 utf8filename = mbtoutf8 (filename);
1740 printd ("msg Opened %s (press h/F1 to get help)",
1741 utf8filename);
1742 if (utf8filename != filename) {
1743 free (utf8filename);
1746 state.needoutline = 1;
1749 else if (!strncmp ("cs", p, 2)) {
1750 int i, colorspace;
1752 ret = sscanf (p + 2, " %d", &colorspace);
1753 if (ret != 1) {
1754 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1756 lock ("cs");
1757 set_tex_params (colorspace);
1758 for (i = 0; i < state.texcount; ++i) {
1759 state.texowners[i].w = -1;
1760 state.texowners[i].slice = NULL;
1762 unlock ("cs");
1764 else if (!strncmp ("freepage", p, 8)) {
1765 void *ptr;
1767 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1768 if (ret != 1) {
1769 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1771 freepage (ptr);
1773 else if (!strncmp ("freetile", p, 8)) {
1774 void *ptr;
1776 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1777 if (ret != 1) {
1778 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1780 freetile (ptr);
1782 else if (!strncmp ("search", p, 6)) {
1783 int icase, pageno, y, len2, forward;
1784 char *pattern;
1785 regex_t re;
1787 ret = sscanf (p + 6, " %d %d %d %d,%n",
1788 &icase, &pageno, &y, &forward, &len2);
1789 if (ret != 4) {
1790 errx (1, "malformed search `%s' ret=%d", p, ret);
1793 pattern = p + 6 + len2;
1794 ret = regcomp (&re, pattern,
1795 REG_EXTENDED | (icase ? REG_ICASE : 0));
1796 if (ret) {
1797 char errbuf[80];
1798 size_t size;
1800 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1801 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1803 else {
1804 search (&re, pageno, y, forward);
1805 regfree (&re);
1808 else if (!strncmp ("geometry", p, 8)) {
1809 int w, h, fitmodel;
1811 printd ("clear");
1812 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1813 if (ret != 3) {
1814 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1817 lock ("geometry");
1818 state.h = h;
1819 if (w != state.w) {
1820 int i;
1821 state.w = w;
1822 for (i = 0; i < state.texcount; ++i) {
1823 state.texowners[i].slice = NULL;
1826 state.fitmodel = fitmodel;
1827 layout ();
1828 process_outline ();
1830 state.gen++;
1831 unlock ("geometry");
1832 printd ("continue %d", state.pagecount);
1834 else if (!strncmp ("reqlayout", p, 9)) {
1835 char *nameddest;
1836 int rotate, off, h;
1837 unsigned int fitmodel;
1838 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1840 printd ("clear");
1841 ret = sscanf (p + 9, " %d %u %d %n",
1842 &rotate, &fitmodel, &h, &off);
1843 if (ret != 3) {
1844 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1846 lock ("reqlayout");
1847 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1848 state.gen += 1;
1850 state.rotate = rotate;
1851 state.fitmodel = fitmodel;
1852 state.h = h;
1853 layout ();
1854 process_outline ();
1856 nameddest = p + 9 + off;
1857 if (pdf && nameddest && *nameddest) {
1858 struct anchor a;
1859 fz_link_dest dest;
1860 pdf_obj *needle, *obj;
1862 needle = pdf_new_string (state.ctx, pdf, nameddest,
1863 strlen (nameddest));
1864 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1865 if (obj) {
1866 dest = pdf_parse_link_dest (state.ctx, pdf,
1867 FZ_LINK_GOTO, obj);
1869 a = desttoanchor (&dest);
1870 if (a.n >= 0) {
1871 printd ("a %d %d %d", a.n, a.x, a.y);
1873 else {
1874 printd ("emsg failed to parse destination `%s'\n",
1875 nameddest);
1878 else {
1879 printd ("emsg destination `%s' not found\n",
1880 nameddest);
1882 pdf_drop_obj (state.ctx, needle);
1885 state.gen++;
1886 unlock ("reqlayout");
1887 printd ("continue %d", state.pagecount);
1889 else if (!strncmp ("page", p, 4)) {
1890 double a, b;
1891 struct page *page;
1892 int pageno, pindex;
1894 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1895 if (ret != 2) {
1896 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1899 lock ("page");
1900 a = now ();
1901 page = loadpage (pageno, pindex);
1902 b = now ();
1903 unlock ("page");
1905 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1907 else if (!strncmp ("tile", p, 4)) {
1908 int x, y, w, h;
1909 struct page *page;
1910 struct tile *tile;
1911 double a, b;
1912 void *data;
1914 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1915 SCN_ptr_cast (&page), &x, &y, &w, &h,
1916 SCN_ptr_cast (&data));
1917 if (ret != 6) {
1918 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1921 lock ("tile");
1922 a = now ();
1923 tile = rendertile (page, x, y, w, h, data);
1924 b = now ();
1925 unlock ("tile");
1927 printd ("tile %d %d %" FMT_ptr " %u %f",
1928 x, y,
1929 FMT_ptr_cast (tile),
1930 tile->w * tile->h * tile->pixmap->n,
1931 b - a);
1933 else if (!strncmp ("trimset", p, 7)) {
1934 fz_irect fuzz;
1935 int trimmargins;
1937 ret = sscanf (p + 7, " %d %d %d %d %d",
1938 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1939 if (ret != 5) {
1940 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1942 lock ("trimset");
1943 state.trimmargins = trimmargins;
1944 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1945 state.trimanew = 1;
1946 state.trimfuzz = fuzz;
1948 unlock ("trimset");
1950 else if (!strncmp ("settrim", p, 7)) {
1951 fz_irect fuzz;
1952 int trimmargins;
1954 ret = sscanf (p + 7, " %d %d %d %d %d",
1955 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1956 if (ret != 5) {
1957 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1959 printd ("clear");
1960 lock ("settrim");
1961 state.trimmargins = trimmargins;
1962 state.needoutline = 1;
1963 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1964 state.trimanew = 1;
1965 state.trimfuzz = fuzz;
1967 state.pagedimcount = 0;
1968 free (state.pagedims);
1969 state.pagedims = NULL;
1970 initpdims (0);
1971 layout ();
1972 process_outline ();
1973 unlock ("settrim");
1974 printd ("continue %d", state.pagecount);
1976 else if (!strncmp ("sliceh", p, 6)) {
1977 int h;
1979 ret = sscanf (p + 6, " %d", &h);
1980 if (ret != 1) {
1981 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1983 if (h != state.sliceheight) {
1984 int i;
1986 state.sliceheight = h;
1987 for (i = 0; i < state.texcount; ++i) {
1988 state.texowners[i].w = -1;
1989 state.texowners[i].h = -1;
1990 state.texowners[i].slice = NULL;
1994 else if (!strncmp ("interrupt", p, 9)) {
1995 printd ("vmsg interrupted");
1997 else {
1998 errx (1, "unknown command %.*s", len, p);
2001 return 0;
2004 CAMLprim value ml_realloctexts (value texcount_v)
2006 CAMLparam1 (texcount_v);
2007 int ok;
2009 if (trylock (__func__)) {
2010 ok = 0;
2011 goto done;
2013 realloctexts (Int_val (texcount_v));
2014 ok = 1;
2015 unlock (__func__);
2017 done:
2018 CAMLreturn (Val_bool (ok));
2021 static void recti (int x0, int y0, int x1, int y1)
2023 GLfloat *v = state.vertices;
2025 glVertexPointer (2, GL_FLOAT, 0, v);
2026 v[0] = x0; v[1] = y0;
2027 v[2] = x1; v[3] = y0;
2028 v[4] = x0; v[5] = y1;
2029 v[6] = x1; v[7] = y1;
2030 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2033 static void showsel (struct page *page, int ox, int oy)
2035 int seen = 0;
2036 fz_irect bbox;
2037 fz_rect rect;
2038 fz_stext_line *line;
2039 fz_page_block *pageb;
2040 fz_stext_block *block;
2041 struct mark first, last;
2042 unsigned char selcolor[] = {15,15,15,140};
2044 first = page->fmark;
2045 last = page->lmark;
2047 if (!first.span || !last.span) return;
2049 glEnable (GL_BLEND);
2050 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2051 glColor4ubv (selcolor);
2053 ox += state.pagedims[page->pdimno].bounds.x0;
2054 oy += state.pagedims[page->pdimno].bounds.y0;
2055 for (pageb = page->text->blocks;
2056 pageb < page->text->blocks + page->text->len;
2057 ++pageb) {
2058 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2059 block = pageb->u.text;
2061 for (line = block->lines;
2062 line < block->lines + block->len;
2063 ++line) {
2064 fz_stext_span *span;
2065 rect = fz_empty_rect;
2067 for (span = line->first_span; span; span = span->next) {
2068 int i, j, k;
2069 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2071 j = 0;
2072 k = span->len - 1;
2074 if (span == page->fmark.span && span == page->lmark.span) {
2075 seen = 1;
2076 j = fz_mini (first.i, last.i);
2077 k = fz_maxi (first.i, last.i);
2079 else {
2080 if (span == first.span) {
2081 seen = 1;
2082 j = first.i;
2084 else if (span == last.span) {
2085 seen = 1;
2086 k = last.i;
2090 if (seen) {
2091 for (i = j; i <= k; ++i) {
2092 fz_rect bbox1;
2093 fz_union_rect (&rect,
2094 fz_stext_char_bbox (state.ctx, &bbox1,
2095 span, i));
2097 fz_round_rect (&bbox, &rect);
2098 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2099 bbox.x0,
2100 bbox.y0,
2101 bbox.x1,
2102 bbox.y1,
2103 oy, ox);
2105 recti (bbox.x0 + ox, bbox.y0 + oy,
2106 bbox.x1 + ox, bbox.y1 + oy);
2107 if (span == last.span) {
2108 goto done;
2110 rect = fz_empty_rect;
2115 done:
2116 glDisable (GL_BLEND);
2119 #include "glfont.c"
2121 static void stipplerect (fz_matrix *m,
2122 fz_point *p1,
2123 fz_point *p2,
2124 fz_point *p3,
2125 fz_point *p4,
2126 GLfloat *texcoords,
2127 GLfloat *vertices)
2129 fz_transform_point (p1, m);
2130 fz_transform_point (p2, m);
2131 fz_transform_point (p3, m);
2132 fz_transform_point (p4, m);
2134 float w, h, s, t;
2136 w = p2->x - p1->x;
2137 h = p2->y - p1->y;
2138 t = sqrtf (w*w + h*h) * .25f;
2140 w = p3->x - p2->x;
2141 h = p3->y - p2->y;
2142 s = sqrtf (w*w + h*h) * .25f;
2144 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2145 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2147 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2148 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2150 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2151 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2153 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2154 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2156 glDrawArrays (GL_LINES, 0, 8);
2159 static void solidrect (fz_matrix *m,
2160 fz_point *p1,
2161 fz_point *p2,
2162 fz_point *p3,
2163 fz_point *p4,
2164 GLfloat *vertices)
2166 fz_transform_point (p1, m);
2167 fz_transform_point (p2, m);
2168 fz_transform_point (p3, m);
2169 fz_transform_point (p4, m);
2170 vertices[0] = p1->x; vertices[1] = p1->y;
2171 vertices[2] = p2->x; vertices[3] = p2->y;
2173 vertices[4] = p3->x; vertices[5] = p3->y;
2174 vertices[6] = p4->x; vertices[7] = p4->y;
2175 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2178 static void highlightlinks (struct page *page, int xoff, int yoff)
2180 int i;
2181 fz_matrix ctm, tm, pm;
2182 fz_link *link, *links;
2183 GLfloat *texcoords = state.texcoords;
2184 GLfloat *vertices = state.vertices;
2186 links = fz_load_links (state.ctx, page->fzpage);
2188 glEnable (GL_TEXTURE_1D);
2189 glEnable (GL_BLEND);
2190 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2191 glBindTexture (GL_TEXTURE_1D, state.stid);
2193 xoff -= state.pagedims[page->pdimno].bounds.x0;
2194 yoff -= state.pagedims[page->pdimno].bounds.y0;
2195 fz_translate (&tm, xoff, yoff);
2196 pm = pagectm (page);
2197 fz_concat (&ctm, &pm, &tm);
2199 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2200 glVertexPointer (2, GL_FLOAT, 0, vertices);
2202 for (link = links; link; link = link->next) {
2203 fz_point p1, p2, p3, p4;
2205 p1.x = link->rect.x0;
2206 p1.y = link->rect.y0;
2208 p2.x = link->rect.x1;
2209 p2.y = link->rect.y0;
2211 p3.x = link->rect.x1;
2212 p3.y = link->rect.y1;
2214 p4.x = link->rect.x0;
2215 p4.y = link->rect.y1;
2217 switch (link->dest.kind) {
2218 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2219 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2220 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2221 default: glColor3ub (0, 0, 0); break;
2223 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2226 for (i = 0; i < page->annotcount; ++i) {
2227 fz_point p1, p2, p3, p4;
2228 struct annot *annot = &page->annots[i];
2230 p1.x = annot->bbox.x0;
2231 p1.y = annot->bbox.y0;
2233 p2.x = annot->bbox.x1;
2234 p2.y = annot->bbox.y0;
2236 p3.x = annot->bbox.x1;
2237 p3.y = annot->bbox.y1;
2239 p4.x = annot->bbox.x0;
2240 p4.y = annot->bbox.y1;
2242 glColor3ub (0, 0, 128);
2243 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2246 glDisable (GL_BLEND);
2247 glDisable (GL_TEXTURE_1D);
2250 static int compareslinks (const void *l, const void *r)
2252 struct slink const *ls = l;
2253 struct slink const *rs = r;
2254 if (ls->bbox.y0 == rs->bbox.y0) {
2255 return rs->bbox.x0 - rs->bbox.x0;
2257 return ls->bbox.y0 - rs->bbox.y0;
2260 static void droptext (struct page *page)
2262 if (page->text) {
2263 fz_drop_stext_page (state.ctx, page->text);
2264 page->fmark.i = -1;
2265 page->lmark.i = -1;
2266 page->fmark.span = NULL;
2267 page->lmark.span = NULL;
2268 page->text = NULL;
2270 if (page->sheet) {
2271 fz_drop_stext_sheet (state.ctx, page->sheet);
2272 page->sheet = NULL;
2276 static void dropannots (struct page *page)
2278 if (page->annots) {
2279 free (page->annots);
2280 page->annots = NULL;
2281 page->annotcount = 0;
2285 static void ensureannots (struct page *page)
2287 int i, count = 0;
2288 size_t annotsize = sizeof (*page->annots);
2289 fz_annot *annot;
2291 if (state.gen != page->agen) {
2292 dropannots (page);
2293 page->agen = state.gen;
2295 if (page->annots) return;
2297 for (annot = fz_first_annot (state.ctx, page->fzpage);
2298 annot;
2299 annot = fz_next_annot (state.ctx, annot)) {
2300 count++;
2303 if (count > 0) {
2304 page->annotcount = count;
2305 page->annots = calloc (count, annotsize);
2306 if (!page->annots) {
2307 err (1, "calloc annots %d", count);
2310 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2311 annot;
2312 annot = fz_next_annot (state.ctx, annot), i++) {
2313 fz_rect rect;
2315 fz_bound_annot (state.ctx, annot, &rect);
2316 page->annots[i].annot = annot;
2317 fz_round_rect (&page->annots[i].bbox, &rect);
2322 static void dropslinks (struct page *page)
2324 if (page->slinks) {
2325 free (page->slinks);
2326 page->slinks = NULL;
2327 page->slinkcount = 0;
2331 static void ensureslinks (struct page *page)
2333 fz_matrix ctm;
2334 int i, count;
2335 size_t slinksize = sizeof (*page->slinks);
2336 fz_link *link, *links;
2338 ensureannots (page);
2339 if (state.gen != page->sgen) {
2340 dropslinks (page);
2341 page->sgen = state.gen;
2343 if (page->slinks) return;
2345 links = fz_load_links (state.ctx, page->fzpage);
2346 ctm = pagectm (page);
2348 count = page->annotcount;
2349 for (link = links; link; link = link->next) {
2350 count++;
2352 if (count > 0) {
2353 int j;
2355 page->slinkcount = count;
2356 page->slinks = calloc (count, slinksize);
2357 if (!page->slinks) {
2358 err (1, "calloc slinks %d", count);
2361 for (i = 0, link = links; link; ++i, link = link->next) {
2362 fz_rect rect;
2364 rect = link->rect;
2365 fz_transform_rect (&rect, &ctm);
2366 page->slinks[i].tag = SLINK;
2367 page->slinks[i].u.link = link;
2368 fz_round_rect (&page->slinks[i].bbox, &rect);
2370 for (j = 0; j < page->annotcount; ++j, ++i) {
2371 fz_rect rect;
2372 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2373 fz_transform_rect (&rect, &ctm);
2374 fz_round_rect (&page->slinks[i].bbox, &rect);
2376 page->slinks[i].tag = SANNOT;
2377 page->slinks[i].u.annot = page->annots[j].annot;
2379 qsort (page->slinks, count, slinksize, compareslinks);
2383 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2384 static void fmt_linkn (char *s, unsigned int u)
2386 unsigned int len; unsigned int q;
2387 unsigned int zma = 'z' - 'a' + 1;
2388 len = 1; q = u;
2389 while (q > zma - 1) { ++len; q /= zma; }
2390 if (s) {
2391 s += len;
2392 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2393 /* handles u == 0 */
2395 s[len] = 0;
2398 static void highlightslinks (struct page *page, int xoff, int yoff,
2399 int noff, char *targ, int tlen, int hfsize)
2401 int i;
2402 char buf[40];
2403 struct slink *slink;
2404 double x0, y0, x1, y1, w;
2406 ensureslinks (page);
2407 glColor3ub (0xc3, 0xb0, 0x91);
2408 for (i = 0; i < page->slinkcount; ++i) {
2409 fmt_linkn (buf, i + noff);
2410 if (!tlen || !strncmp (targ, buf, tlen)) {
2411 slink = &page->slinks[i];
2413 x0 = slink->bbox.x0 + xoff - 5;
2414 y1 = slink->bbox.y0 + yoff - 5;
2415 y0 = y1 + 10 + hfsize;
2416 w = measure_string (state.face, hfsize, buf);
2417 x1 = x0 + w + 10;
2418 recti (x0, y0, x1, y1);
2422 glEnable (GL_BLEND);
2423 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2424 glEnable (GL_TEXTURE_2D);
2425 glColor3ub (0, 0, 0);
2426 for (i = 0; i < page->slinkcount; ++i) {
2427 fmt_linkn (buf, i + noff);
2428 if (!tlen || !strncmp (targ, buf, tlen)) {
2429 slink = &page->slinks[i];
2431 x0 = slink->bbox.x0 + xoff;
2432 y0 = slink->bbox.y0 + yoff + hfsize;
2433 draw_string (state.face, hfsize, x0, y0, buf);
2436 glDisable (GL_TEXTURE_2D);
2437 glDisable (GL_BLEND);
2440 static void uploadslice (struct tile *tile, struct slice *slice)
2442 int offset;
2443 struct slice *slice1;
2444 unsigned char *texdata;
2446 offset = 0;
2447 for (slice1 = tile->slices; slice != slice1; slice1++) {
2448 offset += slice1->h * tile->w * tile->pixmap->n;
2450 if (slice->texindex != -1 && slice->texindex < state.texcount
2451 && state.texowners[slice->texindex].slice == slice) {
2452 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2454 else {
2455 int subimage = 0;
2456 int texindex = state.texindex++ % state.texcount;
2458 if (state.texowners[texindex].w == tile->w) {
2459 if (state.texowners[texindex].h >= slice->h) {
2460 subimage = 1;
2462 else {
2463 state.texowners[texindex].h = slice->h;
2466 else {
2467 state.texowners[texindex].h = slice->h;
2470 state.texowners[texindex].w = tile->w;
2471 state.texowners[texindex].slice = slice;
2472 slice->texindex = texindex;
2474 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2475 #if TEXT_TYPE == GL_TEXTURE_2D
2476 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2477 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2478 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2479 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2480 #endif
2481 if (tile->pbo) {
2482 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2483 texdata = 0;
2485 else {
2486 texdata = tile->pixmap->samples;
2488 if (subimage) {
2489 glTexSubImage2D (TEXT_TYPE,
2493 tile->w,
2494 slice->h,
2495 state.texform,
2496 state.texty,
2497 texdata+offset
2500 else {
2501 glTexImage2D (TEXT_TYPE,
2503 state.texiform,
2504 tile->w,
2505 slice->h,
2507 state.texform,
2508 state.texty,
2509 texdata+offset
2512 if (tile->pbo) {
2513 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2518 CAMLprim value ml_begintiles (value unit_v)
2520 CAMLparam1 (unit_v);
2521 glEnable (TEXT_TYPE);
2522 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2523 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2524 CAMLreturn (unit_v);
2527 CAMLprim value ml_endtiles (value unit_v)
2529 CAMLparam1 (unit_v);
2530 glDisable (TEXT_TYPE);
2531 CAMLreturn (unit_v);
2534 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2536 CAMLparam2 (args_v, ptr_v);
2537 int dispx = Int_val (Field (args_v, 0));
2538 int dispy = Int_val (Field (args_v, 1));
2539 int dispw = Int_val (Field (args_v, 2));
2540 int disph = Int_val (Field (args_v, 3));
2541 int tilex = Int_val (Field (args_v, 4));
2542 int tiley = Int_val (Field (args_v, 5));
2543 char *s = String_val (ptr_v);
2544 struct tile *tile = parse_pointer (__func__, s);
2545 int slicey, firstslice;
2546 struct slice *slice;
2547 GLfloat *texcoords = state.texcoords;
2548 GLfloat *vertices = state.vertices;
2550 firstslice = tiley / tile->sliceheight;
2551 slice = &tile->slices[firstslice];
2552 slicey = tiley % tile->sliceheight;
2554 while (disph > 0) {
2555 int dh;
2557 dh = slice->h - slicey;
2558 dh = fz_mini (disph, dh);
2559 uploadslice (tile, slice);
2561 texcoords[0] = tilex; texcoords[1] = slicey;
2562 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2563 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2564 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2566 vertices[0] = dispx; vertices[1] = dispy;
2567 vertices[2] = dispx+dispw; vertices[3] = dispy;
2568 vertices[4] = dispx; vertices[5] = dispy+dh;
2569 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2571 #if TEXT_TYPE == GL_TEXTURE_2D
2572 for (int i = 0; i < 8; ++i) {
2573 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2575 #endif
2577 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2578 dispy += dh;
2579 disph -= dh;
2580 slice++;
2581 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2582 slicey = 0;
2584 CAMLreturn (Val_unit);
2587 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2589 fz_matrix ctm, tm, pm;
2590 fz_point p1, p2, p3, p4;
2591 GLfloat *vertices = state.vertices;
2592 double *v = (double *) rects_v;
2594 xoff -= state.pagedims[page->pdimno].bounds.x0;
2595 yoff -= state.pagedims[page->pdimno].bounds.y0;
2596 fz_translate (&tm, xoff, yoff);
2597 pm = pagectm (page);
2598 fz_concat (&ctm, &pm, &tm);
2600 glEnable (GL_BLEND);
2601 glVertexPointer (2, GL_FLOAT, 0, vertices);
2603 glColor4dv (v);
2604 p1.x = v[4];
2605 p1.y = v[5];
2607 p2.x = v[6];
2608 p2.y = v[5];
2610 p3.x = v[6];
2611 p3.y = v[7];
2613 p4.x = v[4];
2614 p4.y = v[7];
2615 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2616 glDisable (GL_BLEND);
2619 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2620 value xoff_v, value yoff_v,
2621 value li_v)
2623 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2624 int xoff = Int_val (xoff_v);
2625 int yoff = Int_val (yoff_v);
2626 int noff = Int_val (Field (li_v, 0));
2627 char *targ = String_val (Field (li_v, 1));
2628 int tlen = caml_string_length (Field (li_v, 1));
2629 int hfsize = Int_val (Field (li_v, 2));
2630 char *s = String_val (ptr_v);
2631 int hlmask = Int_val (hlinks_v);
2632 struct page *page = parse_pointer (__func__, s);
2634 if (!page->fzpage) {
2635 /* deal with loadpage failed pages */
2636 goto done;
2639 ensureannots (page);
2641 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2642 if (trylock (__func__)) {
2643 noff = 0;
2644 goto done;
2646 if (hlmask & 2) {
2647 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2648 noff = page->slinkcount;
2650 if (page->tgen == state.gen) {
2651 showsel (page, xoff, yoff);
2653 unlock (__func__);
2655 done:
2656 CAMLreturn (Val_int (noff));
2659 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2660 value rects_v)
2662 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2663 int xoff = Int_val (xoff_v);
2664 int yoff = Int_val (yoff_v);
2665 char *s = String_val (ptr_v);
2666 struct page *page = parse_pointer (__func__, s);
2668 drawprect (page, xoff, yoff, rects_v);
2669 CAMLreturn (Val_unit);
2672 static struct annot *getannot (struct page *page, int x, int y)
2674 int i;
2675 fz_point p;
2676 fz_matrix ctm;
2677 const fz_matrix *tctm;
2678 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2680 if (!page->annots) return NULL;
2682 if (pdf) {
2683 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2684 tctm = &state.pagedims[page->pdimno].tctm;
2686 else {
2687 tctm = &fz_identity;
2690 p.x = x;
2691 p.y = y;
2693 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2694 fz_invert_matrix (&ctm, &ctm);
2695 fz_transform_point (&p, &ctm);
2697 if (pdf) {
2698 for (i = 0; i < page->annotcount; ++i) {
2699 struct annot *a = &page->annots[i];
2700 fz_rect rect;
2702 fz_bound_annot (state.ctx, a->annot, &rect);
2703 if (p.x >= rect.x0 && p.x <= rect.x1) {
2704 if (p.y >= rect.y0 && p.y <= rect.y1) {
2705 return a;
2710 return NULL;
2713 static fz_link *getlink (struct page *page, int x, int y)
2715 fz_point p;
2716 fz_matrix ctm;
2717 fz_link *link, *links;
2719 links = fz_load_links (state.ctx, page->fzpage);
2721 p.x = x;
2722 p.y = y;
2724 ctm = pagectm (page);
2725 fz_invert_matrix (&ctm, &ctm);
2726 fz_transform_point (&p, &ctm);
2728 for (link = links; link; link = link->next) {
2729 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2730 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2731 return link;
2735 return NULL;
2738 static void ensuretext (struct page *page)
2740 if (state.gen != page->tgen) {
2741 droptext (page);
2742 page->tgen = state.gen;
2744 if (!page->text) {
2745 fz_matrix ctm;
2746 fz_device *tdev;
2748 page->text = fz_new_stext_page (state.ctx);
2749 page->sheet = fz_new_stext_sheet (state.ctx);
2750 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2751 ctm = pagectm (page);
2752 fz_run_display_list (state.ctx, page->dlist,
2753 tdev, &ctm, &fz_infinite_rect, NULL);
2754 qsort (page->text->blocks, page->text->len,
2755 sizeof (*page->text->blocks), compareblocks);
2756 fz_close_device (state.ctx, tdev);
2757 fz_drop_device (state.ctx, tdev);
2761 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2763 CAMLparam2 (start_page_v, dir_v);
2764 CAMLlocal1 (ret_v);
2765 int i, dir = Int_val (dir_v);
2766 int start_page = Int_val (start_page_v);
2767 int end_page = dir > 0 ? state.pagecount : -1;
2768 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2770 fz_var (end_page);
2771 ret_v = Val_int (0);
2772 lock (__func__);
2773 for (i = start_page + dir; i != end_page; i += dir) {
2774 int found;
2776 fz_var (found);
2777 if (pdf) {
2778 pdf_page *page = NULL;
2780 fz_var (page);
2781 fz_try (state.ctx) {
2782 page = pdf_load_page (state.ctx, pdf, i);
2783 found = !!page->links || !!page->annots;
2785 fz_catch (state.ctx) {
2786 found = 0;
2788 if (page) {
2789 fz_drop_page (state.ctx, &page->super);
2792 else {
2793 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2794 found = !!fz_load_links (state.ctx, page);
2795 fz_drop_page (state.ctx, page);
2798 if (found) {
2799 ret_v = caml_alloc_small (1, 1);
2800 Field (ret_v, 0) = Val_int (i);
2801 goto unlock;
2804 unlock:
2805 unlock (__func__);
2806 CAMLreturn (ret_v);
2809 enum { dir_first, dir_last };
2810 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2812 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2814 CAMLparam2 (ptr_v, dir_v);
2815 CAMLlocal2 (ret_v, pos_v);
2816 struct page *page;
2817 int dirtag, i, slinkindex;
2818 struct slink *found = NULL ,*slink;
2819 char *s = String_val (ptr_v);
2821 page = parse_pointer (__func__, s);
2822 ret_v = Val_int (0);
2823 /* This is scary we are not taking locks here ensureslinks does
2824 not modify state and given that we obtained the page it can not
2825 disappear under us either */
2826 lock (__func__);
2827 ensureslinks (page);
2829 if (Is_block (dir_v)) {
2830 dirtag = Tag_val (dir_v);
2831 switch (dirtag) {
2832 case dir_first_visible:
2834 int x0, y0, dir, first_index, last_index;
2836 pos_v = Field (dir_v, 0);
2837 x0 = Int_val (Field (pos_v, 0));
2838 y0 = Int_val (Field (pos_v, 1));
2839 dir = Int_val (Field (pos_v, 2));
2841 if (dir >= 0) {
2842 dir = 1;
2843 first_index = 0;
2844 last_index = page->slinkcount;
2846 else {
2847 first_index = page->slinkcount - 1;
2848 last_index = -1;
2851 for (i = first_index; i != last_index; i += dir) {
2852 slink = &page->slinks[i];
2853 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2854 found = slink;
2855 break;
2859 break;
2861 case dir_left:
2862 slinkindex = Int_val (Field (dir_v, 0));
2863 found = &page->slinks[slinkindex];
2864 for (i = slinkindex - 1; i >= 0; --i) {
2865 slink = &page->slinks[i];
2866 if (slink->bbox.x0 < found->bbox.x0) {
2867 found = slink;
2868 break;
2871 break;
2873 case dir_right:
2874 slinkindex = Int_val (Field (dir_v, 0));
2875 found = &page->slinks[slinkindex];
2876 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2877 slink = &page->slinks[i];
2878 if (slink->bbox.x0 > found->bbox.x0) {
2879 found = slink;
2880 break;
2883 break;
2885 case dir_down:
2886 slinkindex = Int_val (Field (dir_v, 0));
2887 found = &page->slinks[slinkindex];
2888 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2889 slink = &page->slinks[i];
2890 if (slink->bbox.y0 >= found->bbox.y0) {
2891 found = slink;
2892 break;
2895 break;
2897 case dir_up:
2898 slinkindex = Int_val (Field (dir_v, 0));
2899 found = &page->slinks[slinkindex];
2900 for (i = slinkindex - 1; i >= 0; --i) {
2901 slink = &page->slinks[i];
2902 if (slink->bbox.y0 <= found->bbox.y0) {
2903 found = slink;
2904 break;
2907 break;
2910 else {
2911 dirtag = Int_val (dir_v);
2912 switch (dirtag) {
2913 case dir_first:
2914 found = page->slinks;
2915 break;
2917 case dir_last:
2918 if (page->slinks) {
2919 found = page->slinks + (page->slinkcount - 1);
2921 break;
2924 if (found) {
2925 ret_v = caml_alloc_small (2, 1);
2926 Field (ret_v, 0) = Val_int (found - page->slinks);
2929 unlock (__func__);
2930 CAMLreturn (ret_v);
2933 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2934 unamed, uremote, uremotedest, uannot };
2936 #define LINKTOVAL \
2938 int pageno; \
2940 switch (link->dest.kind) { \
2941 case FZ_LINK_GOTO: \
2943 fz_point p; \
2945 pageno = link->dest.ld.gotor.page; \
2946 p.x = 0; \
2947 p.y = 0; \
2949 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2950 p.y = link->dest.ld.gotor.lt.y; \
2951 fz_transform_point (&p, &pdim->lctm); \
2952 if (p.y < 0) p.y = 0; \
2954 tup_v = caml_alloc_tuple (2); \
2955 ret_v = caml_alloc_small (1, ugoto); \
2956 Field (tup_v, 0) = Val_int (pageno); \
2957 Field (tup_v, 1) = Val_int (p.y); \
2958 Field (ret_v, 0) = tup_v; \
2960 break; \
2962 case FZ_LINK_URI: \
2963 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2964 ret_v = caml_alloc_small (1, uuri); \
2965 Field (ret_v, 0) = str_v; \
2966 break; \
2968 case FZ_LINK_LAUNCH: \
2969 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2970 ret_v = caml_alloc_small (1, ulaunch); \
2971 Field (ret_v, 0) = str_v; \
2972 break; \
2974 case FZ_LINK_NAMED: \
2975 str_v = caml_copy_string (link->dest.ld.named.named); \
2976 ret_v = caml_alloc_small (1, unamed); \
2977 Field (ret_v, 0) = str_v; \
2978 break; \
2980 case FZ_LINK_GOTOR: \
2982 int rty; \
2984 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2985 pageno = link->dest.ld.gotor.page; \
2986 if (pageno == -1) { \
2987 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2988 rty = uremotedest; \
2990 else { \
2991 gr_v = Val_int (pageno); \
2992 rty = uremote; \
2994 tup_v = caml_alloc_tuple (2); \
2995 ret_v = caml_alloc_small (1, rty); \
2996 Field (tup_v, 0) = str_v; \
2997 Field (tup_v, 1) = gr_v; \
2998 Field (ret_v, 0) = tup_v; \
3000 break; \
3002 default: \
3004 char buf[80]; \
3006 snprintf (buf, sizeof (buf), \
3007 "unhandled link kind %d", link->dest.kind); \
3008 str_v = caml_copy_string (buf); \
3009 ret_v = caml_alloc_small (1, uunexpected); \
3010 Field (ret_v, 0) = str_v; \
3012 break; \
3016 CAMLprim value ml_getlink (value ptr_v, value n_v)
3018 CAMLparam2 (ptr_v, n_v);
3019 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3020 fz_link *link;
3021 struct page *page;
3022 struct pagedim *pdim;
3023 char *s = String_val (ptr_v);
3024 struct slink *slink;
3026 /* See ml_findlink for caveat */
3028 ret_v = Val_int (0);
3029 page = parse_pointer (__func__, s);
3030 ensureslinks (page);
3031 pdim = &state.pagedims[page->pdimno];
3032 slink = &page->slinks[Int_val (n_v)];
3033 if (slink->tag == SLINK) {
3034 link = slink->u.link;
3035 LINKTOVAL;
3037 else {
3038 ret_v = caml_alloc_small (1, uannot);
3039 tup_v = caml_alloc_tuple (2);
3040 Field (ret_v, 0) = tup_v;
3041 Field (tup_v, 0) = ptr_v;
3042 Field (tup_v, 1) = n_v;
3045 CAMLreturn (ret_v);
3048 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3050 CAMLparam2 (ptr_v, n_v);
3051 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3052 if (pdf) {
3053 char *s = String_val (ptr_v);
3054 struct page *page;
3055 struct slink *slink;
3057 page = parse_pointer (__func__, s);
3058 slink = &page->slinks[Int_val (n_v)];
3059 CAMLreturn (caml_copy_string (
3060 pdf_annot_contents (state.ctx,
3061 (pdf_annot *) slink->u.annot)));
3063 else {
3064 CAMLreturn (caml_copy_string (""));
3068 CAMLprim value ml_getlinkcount (value ptr_v)
3070 CAMLparam1 (ptr_v);
3071 struct page *page;
3072 char *s = String_val (ptr_v);
3074 page = parse_pointer (__func__, s);
3075 CAMLreturn (Val_int (page->slinkcount));
3078 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3080 CAMLparam2 (ptr_v, n_v);
3081 CAMLlocal1 (ret_v);
3082 struct page *page;
3083 struct slink *slink;
3084 char *s = String_val (ptr_v);
3085 /* See ml_findlink for caveat */
3087 page = parse_pointer (__func__, s);
3088 ret_v = caml_alloc_tuple (4);
3089 ensureslinks (page);
3091 slink = &page->slinks[Int_val (n_v)];
3092 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3093 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3094 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3095 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3096 unlock (__func__);
3097 CAMLreturn (ret_v);
3100 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3102 CAMLparam3 (ptr_v, x_v, y_v);
3103 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3104 fz_link *link;
3105 struct annot *annot;
3106 struct page *page;
3107 char *ptr = String_val (ptr_v);
3108 int x = Int_val (x_v), y = Int_val (y_v);
3109 struct pagedim *pdim;
3111 ret_v = Val_int (0);
3112 if (trylock (__func__)) {
3113 goto done;
3116 page = parse_pointer (__func__, ptr);
3117 pdim = &state.pagedims[page->pdimno];
3118 x += pdim->bounds.x0;
3119 y += pdim->bounds.y0;
3122 annot = getannot (page, x, y);
3123 if (annot) {
3124 int i, n = -1;
3126 ensureslinks (page);
3127 for (i = 0; i < page->slinkcount; ++i) {
3128 if (page->slinks[i].tag == SANNOT
3129 && page->slinks[i].u.annot == annot->annot) {
3130 n = i;
3131 break;
3134 ret_v = caml_alloc_small (1, uannot);
3135 tup_v = caml_alloc_tuple (2);
3136 Field (ret_v, 0) = tup_v;
3137 Field (tup_v, 0) = ptr_v;
3138 Field (tup_v, 1) = Val_int (n);
3139 goto unlock;
3143 link = getlink (page, x, y);
3144 if (link) {
3145 LINKTOVAL;
3147 else {
3148 fz_rect *b;
3149 fz_page_block *pageb;
3150 fz_stext_block *block;
3152 ensuretext (page);
3153 for (pageb = page->text->blocks;
3154 pageb < page->text->blocks + page->text->len;
3155 ++pageb) {
3156 fz_stext_line *line;
3157 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3158 block = pageb->u.text;
3160 b = &block->bbox;
3161 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3162 continue;
3164 for (line = block->lines;
3165 line < block->lines + block->len;
3166 ++line) {
3167 fz_stext_span *span;
3169 b = &line->bbox;
3170 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3171 continue;
3173 for (span = line->first_span; span; span = span->next) {
3174 int charnum;
3176 b = &span->bbox;
3177 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3178 continue;
3180 for (charnum = 0; charnum < span->len; ++charnum) {
3181 fz_rect bbox;
3182 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3183 b = &bbox;
3185 if (x >= b->x0 && x <= b->x1
3186 && y >= b->y0 && y <= b->y1) {
3187 fz_stext_style *style = span->text->style;
3188 const char *n2 =
3189 style->font
3190 ? style->font->name
3191 : "Span has no font name"
3193 FT_FaceRec *face = style->font->ft_face;
3194 if (face && face->family_name) {
3195 char *s;
3196 char *n1 = face->family_name;
3197 size_t l1 = strlen (n1);
3198 size_t l2 = strlen (n2);
3200 if (l1 != l2 || memcmp (n1, n2, l1)) {
3201 s = malloc (l1 + l2 + 2);
3202 if (s) {
3203 memcpy (s, n2, l2);
3204 s[l2] = '=';
3205 memcpy (s + l2 + 1, n1, l1 + 1);
3206 str_v = caml_copy_string (s);
3207 free (s);
3211 if (str_v == Val_unit) {
3212 str_v = caml_copy_string (n2);
3214 ret_v = caml_alloc_small (1, utext);
3215 Field (ret_v, 0) = str_v;
3216 goto unlock;
3223 unlock:
3224 unlock (__func__);
3226 done:
3227 CAMLreturn (ret_v);
3230 enum { mark_page, mark_block, mark_line, mark_word };
3232 static int uninteresting (int c)
3234 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3235 || ispunct (c);
3238 CAMLprim value ml_clearmark (value ptr_v)
3240 CAMLparam1 (ptr_v);
3241 char *s = String_val (ptr_v);
3242 struct page *page;
3244 if (trylock (__func__)) {
3245 goto done;
3248 page = parse_pointer (__func__, s);
3249 page->fmark.span = NULL;
3250 page->lmark.span = NULL;
3251 page->fmark.i = 0;
3252 page->lmark.i = 0;
3254 unlock (__func__);
3255 done:
3256 CAMLreturn (Val_unit);
3259 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3261 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3262 CAMLlocal1 (ret_v);
3263 fz_rect *b;
3264 struct page *page;
3265 fz_stext_line *line;
3266 fz_page_block *pageb;
3267 fz_stext_block *block;
3268 struct pagedim *pdim;
3269 int mark = Int_val (mark_v);
3270 char *s = String_val (ptr_v);
3271 int x = Int_val (x_v), y = Int_val (y_v);
3273 ret_v = Val_bool (0);
3274 if (trylock (__func__)) {
3275 goto done;
3278 page = parse_pointer (__func__, s);
3279 pdim = &state.pagedims[page->pdimno];
3281 ensuretext (page);
3283 if (mark == mark_page) {
3284 int i;
3285 fz_page_block *pb1 = NULL, *pb2 = NULL;
3287 for (i = 0; i < page->text->len; ++i) {
3288 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3289 pb1 = &page->text->blocks[i];
3290 break;
3293 if (!pb1) goto unlock;
3295 for (i = page->text->len - 1; i >= 0; --i) {
3296 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3297 pb2 = &page->text->blocks[i];
3298 break;
3301 if (!pb2) goto unlock;
3303 block = pb1->u.text;
3305 page->fmark.i = 0;
3306 page->fmark.span = block->lines->first_span;
3308 block = pb2->u.text;
3309 line = &block->lines[block->len - 1];
3310 page->lmark.i = line->last_span->len - 1;
3311 page->lmark.span = line->last_span;
3312 ret_v = Val_bool (1);
3313 goto unlock;
3316 x += pdim->bounds.x0;
3317 y += pdim->bounds.y0;
3319 for (pageb = page->text->blocks;
3320 pageb < page->text->blocks + page->text->len;
3321 ++pageb) {
3322 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3323 block = pageb->u.text;
3325 b = &block->bbox;
3326 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3327 continue;
3329 if (mark == mark_block) {
3330 page->fmark.i = 0;
3331 page->fmark.span = block->lines->first_span;
3333 line = &block->lines[block->len - 1];
3334 page->lmark.i = line->last_span->len - 1;
3335 page->lmark.span = line->last_span;
3336 ret_v = Val_bool (1);
3337 goto unlock;
3340 for (line = block->lines;
3341 line < block->lines + block->len;
3342 ++line) {
3343 fz_stext_span *span;
3345 b = &line->bbox;
3346 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3347 continue;
3349 if (mark == mark_line) {
3350 page->fmark.i = 0;
3351 page->fmark.span = line->first_span;
3353 page->lmark.i = line->last_span->len - 1;
3354 page->lmark.span = line->last_span;
3355 ret_v = Val_bool (1);
3356 goto unlock;
3359 for (span = line->first_span; span; span = span->next) {
3360 int charnum;
3362 b = &span->bbox;
3363 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3364 continue;
3366 for (charnum = 0; charnum < span->len; ++charnum) {
3367 fz_rect bbox;
3368 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3369 b = &bbox;
3371 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3372 /* unicode ftw */
3373 int charnum2, charnum3 = -1, charnum4 = -1;
3375 if (uninteresting (span->text[charnum].c)) goto unlock;
3377 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3378 if (uninteresting (span->text[charnum2].c)) {
3379 charnum3 = charnum2 + 1;
3380 break;
3383 if (charnum3 == -1) charnum3 = 0;
3385 charnum4 = charnum;
3386 for (charnum2 = charnum + 1;
3387 charnum2 < span->len;
3388 ++charnum2) {
3389 if (uninteresting (span->text[charnum2].c)) break;
3390 charnum4 = charnum2;
3393 page->fmark.i = charnum3;
3394 page->fmark.span = span;
3396 page->lmark.i = charnum4;
3397 page->lmark.span = span;
3398 ret_v = Val_bool (1);
3399 goto unlock;
3405 unlock:
3406 if (!Bool_val (ret_v)) {
3407 page->fmark.span = NULL;
3408 page->lmark.span = NULL;
3409 page->fmark.i = 0;
3410 page->lmark.i = 0;
3412 unlock (__func__);
3414 done:
3415 CAMLreturn (ret_v);
3418 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3420 CAMLparam3 (ptr_v, x_v, y_v);
3421 CAMLlocal2 (ret_v, res_v);
3422 fz_rect *b = NULL;
3423 struct page *page;
3424 fz_page_block *pageb;
3425 struct pagedim *pdim;
3426 char *s = String_val (ptr_v);
3427 int x = Int_val (x_v), y = Int_val (y_v);
3429 ret_v = Val_int (0);
3430 if (trylock (__func__)) {
3431 goto done;
3434 page = parse_pointer (__func__, s);
3435 pdim = &state.pagedims[page->pdimno];
3436 x += pdim->bounds.x0;
3437 y += pdim->bounds.y0;
3439 ensuretext (page);
3441 for (pageb = page->text->blocks;
3442 pageb < page->text->blocks + page->text->len;
3443 ++pageb) {
3444 switch (pageb->type) {
3445 case FZ_PAGE_BLOCK_TEXT:
3446 b = &pageb->u.text->bbox;
3447 break;
3449 case FZ_PAGE_BLOCK_IMAGE:
3450 b = &pageb->u.image->bbox;
3451 break;
3453 default:
3454 continue;
3457 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3458 break;
3459 b = NULL;
3461 if (b) {
3462 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3463 ret_v = caml_alloc_small (1, 1);
3464 Store_double_field (res_v, 0, b->x0);
3465 Store_double_field (res_v, 1, b->x1);
3466 Store_double_field (res_v, 2, b->y0);
3467 Store_double_field (res_v, 3, b->y1);
3468 Field (ret_v, 0) = res_v;
3470 unlock (__func__);
3472 done:
3473 CAMLreturn (ret_v);
3476 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3478 CAMLparam2 (ptr_v, rect_v);
3479 fz_rect b;
3480 struct page *page;
3481 struct pagedim *pdim;
3482 char *s = String_val (ptr_v);
3483 int i, x0, x1, y0, y1, fi, li;
3484 fz_stext_line *line;
3485 fz_page_block *pageb;
3486 fz_stext_block *block;
3487 fz_stext_span *span, *fspan, *lspan;
3489 if (trylock (__func__)) {
3490 goto done;
3493 page = parse_pointer (__func__, s);
3494 ensuretext (page);
3496 pdim = &state.pagedims[page->pdimno];
3497 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3498 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3499 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3500 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3502 if (y0 > y1) {
3503 int t = y0;
3504 y0 = y1;
3505 y1 = t;
3506 x0 = x1;
3507 x1 = t;
3510 fi = page->fmark.i;
3511 fspan = page->fmark.span;
3513 li = page->lmark.i;
3514 lspan = page->lmark.span;
3516 for (pageb = page->text->blocks;
3517 pageb < page->text->blocks + page->text->len;
3518 ++pageb) {
3519 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3520 block = pageb->u.text;
3521 for (line = block->lines;
3522 line < block->lines + block->len;
3523 ++line) {
3525 for (span = line->first_span; span; span = span->next) {
3526 for (i = 0; i < span->len; ++i) {
3527 fz_stext_char_bbox (state.ctx, &b, span, i);
3529 if (x0 >= b.x0 && x0 <= b.x1
3530 && y0 >= b.y0 && y0 <= b.y1) {
3531 fspan = span;
3532 fi = i;
3534 if (x1 >= b.x0 && x1 <= b.x1
3535 && y1 >= b.y0 && y1 <= b.y1) {
3536 lspan = span;
3537 li = i;
3543 if (x1 < x0 && fspan == lspan) {
3544 i = fi;
3545 span = fspan;
3547 fi = li;
3548 fspan = lspan;
3550 li = i;
3551 lspan = span;
3554 page->fmark.i = fi;
3555 page->fmark.span = fspan;
3557 page->lmark.i = li;
3558 page->lmark.span = lspan;
3560 unlock (__func__);
3562 done:
3563 CAMLreturn (Val_unit);
3566 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3568 char buf[4];
3569 int i, len, ret;
3571 for (i = a; i <= b; ++i) {
3572 len = fz_runetochar (buf, span->text[i].c);
3573 ret = fwrite (buf, len, 1, f);
3575 if (ret != 1) {
3576 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3577 len, ret, strerror (errno));
3578 return -1;
3581 return 0;
3584 #ifdef __CYGWIN__
3585 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3587 caml_failwith ("ml_popen not implemented under Cygwin");
3589 #else
3590 CAMLprim value ml_spawn (value command_v, value fds_v)
3592 CAMLparam2 (command_v, fds_v);
3593 CAMLlocal2 (l_v, tup_v);
3594 int ret, ret1;
3595 pid_t pid;
3596 char *msg = NULL;
3597 value earg_v = Nothing;
3598 posix_spawnattr_t attr;
3599 posix_spawn_file_actions_t fa;
3600 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3602 argv[2] = String_val (command_v);
3604 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3605 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3608 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3609 msg = "posix_spawnattr_init";
3610 goto fail1;
3613 #ifdef POSIX_SPAWN_USEVFORK
3614 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3615 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3616 goto fail;
3618 #endif
3620 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3621 int fd1, fd2;
3623 tup_v = Field (l_v, 0);
3624 fd1 = Int_val (Field (tup_v, 0));
3625 fd2 = Int_val (Field (tup_v, 1));
3626 if (fd2 < 0) {
3627 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3628 msg = "posix_spawn_file_actions_addclose";
3629 earg_v = tup_v;
3630 goto fail;
3633 else {
3634 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3635 msg = "posix_spawn_file_actions_adddup2";
3636 earg_v = tup_v;
3637 goto fail;
3642 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3643 msg = "posix_spawn";
3644 goto fail;
3647 fail:
3648 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3649 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3652 fail1:
3653 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3654 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3655 strerror (ret1));
3658 if (msg)
3659 unix_error (ret, msg, earg_v);
3661 CAMLreturn (Val_int (pid));
3663 #endif
3665 CAMLprim value ml_hassel (value ptr_v)
3667 CAMLparam1 (ptr_v);
3668 CAMLlocal1 (ret_v);
3669 struct page *page;
3670 char *s = String_val (ptr_v);
3672 ret_v = Val_bool (0);
3673 if (trylock (__func__)) {
3674 goto done;
3677 page = parse_pointer (__func__, s);
3678 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3679 unlock (__func__);
3680 done:
3681 CAMLreturn (ret_v);
3684 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3686 CAMLparam2 (fd_v, ptr_v);
3687 FILE *f;
3688 int seen = 0;
3689 struct page *page;
3690 fz_stext_line *line;
3691 fz_page_block *pageb;
3692 fz_stext_block *block;
3693 int fd = Int_val (fd_v);
3694 char *s = String_val (ptr_v);
3696 if (trylock (__func__)) {
3697 goto done;
3700 page = parse_pointer (__func__, s);
3702 if (!page->fmark.span || !page->lmark.span) {
3703 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3704 goto unlock;
3707 f = fdopen (fd, "w");
3708 if (!f) {
3709 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3710 fd, strerror (errno));
3711 f = stdout;
3714 for (pageb = page->text->blocks;
3715 pageb < page->text->blocks + page->text->len;
3716 ++pageb) {
3717 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3718 block = pageb->u.text;
3719 for (line = block->lines;
3720 line < block->lines + block->len;
3721 ++line) {
3722 fz_stext_span *span;
3724 for (span = line->first_span; span; span = span->next) {
3725 int a, b;
3727 seen |= span == page->fmark.span || span == page->lmark.span;
3728 a = span == page->fmark.span ? page->fmark.i : 0;
3729 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3731 if (seen) {
3732 if (pipespan (f, span, a, b)) {
3733 goto close;
3735 if (span == page->lmark.span) {
3736 goto close;
3738 if (span == line->last_span) {
3739 if (putc ('\n', f) == EOF) {
3740 fprintf (stderr,
3741 "failed break line on sel pipe: %s\n",
3742 strerror (errno));
3743 goto close;
3750 close:
3751 if (f != stdout) {
3752 int ret = fclose (f);
3753 fd = -1;
3754 if (ret == -1) {
3755 if (errno != ECHILD) {
3756 fprintf (stderr, "failed to close sel pipe: %s\n",
3757 strerror (errno));
3761 unlock:
3762 unlock (__func__);
3764 done:
3765 if (fd >= 0) {
3766 if (close (fd)) {
3767 fprintf (stderr, "failed to close sel pipe: %s\n",
3768 strerror (errno));
3771 CAMLreturn (Val_unit);
3774 CAMLprim value ml_getpdimrect (value pagedimno_v)
3776 CAMLparam1 (pagedimno_v);
3777 CAMLlocal1 (ret_v);
3778 int pagedimno = Int_val (pagedimno_v);
3779 fz_rect box;
3781 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3782 if (trylock (__func__)) {
3783 box = fz_empty_rect;
3785 else {
3786 box = state.pagedims[pagedimno].mediabox;
3787 unlock (__func__);
3790 Store_double_field (ret_v, 0, box.x0);
3791 Store_double_field (ret_v, 1, box.x1);
3792 Store_double_field (ret_v, 2, box.y0);
3793 Store_double_field (ret_v, 3, box.y1);
3795 CAMLreturn (ret_v);
3798 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3799 value dw_v, value cols_v)
3801 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3802 CAMLlocal1 (ret_v);
3803 int i;
3804 double zoom = -1.;
3805 double maxh = 0.0;
3806 struct pagedim *p;
3807 double winw = Int_val (winw_v);
3808 double winh = Int_val (winh_v);
3809 double dw = Int_val (dw_v);
3810 double cols = Int_val (cols_v);
3811 double pw = 1.0, ph = 1.0;
3813 if (trylock (__func__)) {
3814 goto done;
3817 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3818 double w = p->pagebox.x1 / cols;
3819 double h = p->pagebox.y1;
3820 if (h > maxh) {
3821 maxh = h;
3822 ph = h;
3823 if (state.fitmodel != FitProportional) pw = w;
3825 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3828 zoom = (((winh / ph) * pw) + dw) / winw;
3829 unlock (__func__);
3830 done:
3831 ret_v = caml_copy_double (zoom);
3832 CAMLreturn (ret_v);
3835 CAMLprim value ml_getmaxw (value unit_v)
3837 CAMLparam1 (unit_v);
3838 CAMLlocal1 (ret_v);
3839 int i;
3840 double maxw = -1.;
3841 struct pagedim *p;
3843 if (trylock (__func__)) {
3844 goto done;
3847 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3848 double w = p->pagebox.x1;
3849 maxw = fz_max (maxw, w);
3852 unlock (__func__);
3853 done:
3854 ret_v = caml_copy_double (maxw);
3855 CAMLreturn (ret_v);
3858 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3860 CAMLparam4 (pt_v, x_v, y_v, string_v);
3861 CAMLlocal1 (ret_v);
3862 int pt = Int_val(pt_v);
3863 int x = Int_val (x_v);
3864 int y = Int_val (y_v);
3865 double w;
3867 w = draw_string (state.face, pt, x, y, String_val (string_v));
3868 ret_v = caml_copy_double (w);
3869 CAMLreturn (ret_v);
3872 CAMLprim value ml_measure_string (value pt_v, value string_v)
3874 CAMLparam2 (pt_v, string_v);
3875 CAMLlocal1 (ret_v);
3876 int pt = Int_val (pt_v);
3877 double w;
3879 w = measure_string (state.face, pt, String_val (string_v));
3880 ret_v = caml_copy_double (w);
3881 CAMLreturn (ret_v);
3884 CAMLprim value ml_getpagebox (value opaque_v)
3886 CAMLparam1 (opaque_v);
3887 CAMLlocal1 (ret_v);
3888 fz_rect rect;
3889 fz_irect bbox;
3890 fz_matrix ctm;
3891 fz_device *dev;
3892 char *s = String_val (opaque_v);
3893 struct page *page = parse_pointer (__func__, s);
3895 ret_v = caml_alloc_tuple (4);
3896 dev = fz_new_bbox_device (state.ctx, &rect);
3897 dev->hints |= FZ_IGNORE_SHADE;
3899 ctm = pagectm (page);
3900 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3902 fz_close_device (state.ctx, dev);
3903 fz_drop_device (state.ctx, dev);
3904 fz_round_rect (&bbox, &rect);
3905 Field (ret_v, 0) = Val_int (bbox.x0);
3906 Field (ret_v, 1) = Val_int (bbox.y0);
3907 Field (ret_v, 2) = Val_int (bbox.x1);
3908 Field (ret_v, 3) = Val_int (bbox.y1);
3910 CAMLreturn (ret_v);
3913 CAMLprim value ml_setaalevel (value level_v)
3915 CAMLparam1 (level_v);
3917 state.aalevel = Int_val (level_v);
3918 CAMLreturn (Val_unit);
3921 #pragma GCC diagnostic push
3922 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3923 #include <X11/Xlib.h>
3924 #include <X11/cursorfont.h>
3925 #pragma GCC diagnostic pop
3927 #ifdef USE_EGL
3928 #include <EGL/egl.h>
3929 #else
3930 #include <GL/glx.h>
3931 #endif
3933 static const int shapes[] = {
3934 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3937 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3939 static struct {
3940 Window wid;
3941 Display *dpy;
3942 #ifdef USE_EGL
3943 EGLContext ctx;
3944 EGLConfig conf;
3945 EGLSurface win;
3946 EGLDisplay *edpy;
3947 #else
3948 GLXContext ctx;
3949 #endif
3950 XVisualInfo *visual;
3951 Cursor curs[CURS_COUNT];
3952 } glx;
3954 #ifdef VISAVIS
3955 static VisualID initvisual (void)
3957 /* On this system with: `Haswell-ULT Integrated Graphics
3958 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3959 using glX chosen visual and auto scrolling some document in
3960 fullscreen the power/energy-gpu is more than 1 joule bigger
3961 than when using hand picked visual that stands alone in glxinfo
3962 output: it's dead last in the list and it's the only one with
3963 `visual dep' (sic) of 32
3965 No clue what's going on here...
3967 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3969 XVisualInfo info;
3970 int ret = 1;
3972 info.depth = 32;
3973 info.class = TrueColor;
3974 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3975 &info, &ret);
3976 if (!ret || !glx.visual) {
3977 XCloseDisplay (glx.dpy);
3978 caml_failwith ("XGetVisualInfo");
3980 return glx.visual->visualid;
3982 #endif
3984 static void initcurs (void)
3986 for (size_t n = 0; n < CURS_COUNT; ++n) {
3987 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3991 CAMLprim void ml_setbgcol (value color_v)
3993 CAMLparam1 (color_v);
3994 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3995 CAMLreturn0;
3998 #ifdef USE_EGL
3999 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4001 CAMLparam3 (display_v, wid_v, screen_v);
4002 int major, minor;
4003 int num_conf;
4004 EGLint visid;
4005 EGLint attribs[] = {
4006 #ifdef VISAVIS
4007 EGL_NATIVE_VISUAL_ID, 0,
4008 #else
4009 EGL_DEPTH_SIZE, 24,
4010 #endif
4011 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
4012 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
4013 EGL_NONE
4015 EGLConfig conf;
4017 glx.dpy = XOpenDisplay (String_val (display_v));
4018 if (!glx.dpy) {
4019 caml_failwith ("XOpenDisplay");
4022 eglBindAPI (EGL_OPENGL_API);
4024 glx.edpy = eglGetDisplay (glx.dpy);
4025 if (glx.edpy == EGL_NO_DISPLAY) {
4026 caml_failwith ("eglGetDisplay");
4029 if (!eglInitialize (glx.edpy, &major, &minor)) {
4030 caml_failwith ("eglInitialize");
4033 #ifdef VISAVIS
4034 attribs[1] = visid = initvisual ();
4035 #endif
4037 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4038 !num_conf) {
4039 caml_failwith ("eglChooseConfig");
4042 glx.conf = conf;
4043 #ifndef VISAVIS
4044 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4045 EGL_NATIVE_VISUAL_ID, &visid)) {
4046 caml_failwith ("eglGetConfigAttrib");
4048 #endif
4049 initcurs ();
4051 glx.wid = Int_val (wid_v);
4052 CAMLreturn (Val_int (visid));
4055 CAMLprim value ml_glxcompleteinit (value unit_v)
4057 CAMLparam1 (unit_v);
4059 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4060 if (!glx.ctx) {
4061 caml_failwith ("eglCreateContext");
4064 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4065 glx.wid, NULL);
4066 if (glx.win == EGL_NO_SURFACE) {
4067 caml_failwith ("eglCreateWindowSurface");
4070 XFree (glx.visual);
4071 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4072 glx.ctx = NULL;
4073 caml_failwith ("eglMakeCurrent");
4075 CAMLreturn (Val_unit);
4077 #else
4078 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4080 CAMLparam3 (display_v, wid_v, screen_v);
4082 glx.dpy = XOpenDisplay (String_val (display_v));
4083 if (!glx.dpy) {
4084 caml_failwith ("XOpenDisplay");
4087 #ifdef VISAVIS
4088 initvisual ();
4089 #else
4090 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4091 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4092 if (!glx.visual) {
4093 XCloseDisplay (glx.dpy);
4094 caml_failwith ("glXChooseVisual");
4096 #endif
4097 initcurs ();
4099 glx.wid = Int_val (wid_v);
4100 CAMLreturn (Val_int (glx.visual->visualid));
4103 CAMLprim value ml_glxcompleteinit (value unit_v)
4105 CAMLparam1 (unit_v);
4107 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4108 if (!glx.ctx) {
4109 caml_failwith ("glXCreateContext");
4112 XFree (glx.visual);
4113 glx.visual = NULL;
4115 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4116 glXDestroyContext (glx.dpy, glx.ctx);
4117 glx.ctx = NULL;
4118 caml_failwith ("glXMakeCurrent");
4120 CAMLreturn (Val_unit);
4122 #endif
4124 CAMLprim value ml_setcursor (value cursor_v)
4126 CAMLparam1 (cursor_v);
4127 size_t cursn = Int_val (cursor_v);
4129 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4130 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4131 XFlush (glx.dpy);
4132 CAMLreturn (Val_unit);
4135 CAMLprim value ml_swapb (value unit_v)
4137 CAMLparam1 (unit_v);
4138 #ifdef USE_EGL
4139 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4140 caml_failwith ("eglSwapBuffers");
4142 #else
4143 glXSwapBuffers (glx.dpy, glx.wid);
4144 #endif
4145 CAMLreturn (Val_unit);
4148 #include "keysym2ucs.c"
4150 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4152 CAMLparam1 (keysym_v);
4153 CAMLlocal1 (str_v);
4154 KeySym keysym = Int_val (keysym_v);
4155 Rune rune;
4156 int len;
4157 char buf[5];
4159 rune = keysym2ucs (keysym);
4160 len = fz_runetochar (buf, rune);
4161 buf[len] = 0;
4162 str_v = caml_copy_string (buf);
4163 CAMLreturn (str_v);
4166 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4168 CAMLprim value ml_platform (value unit_v)
4170 CAMLparam1 (unit_v);
4171 CAMLlocal2 (tup_v, arr_v);
4172 int platid = piunknown;
4173 struct utsname buf;
4175 #if defined __linux__
4176 platid = pilinux;
4177 #elif defined __CYGWIN__
4178 platid = picygwin;
4179 #elif defined __DragonFly__ || defined __FreeBSD__
4180 || defined __OpenBSD__ || defined __NetBSD__
4181 platid = pibsd;
4182 #elif defined __sun__
4183 platid = pisun;
4184 #elif defined __APPLE__
4185 platid = piosx;
4186 #endif
4187 if (uname (&buf)) err (1, "uname");
4189 tup_v = caml_alloc_tuple (2);
4191 char const *sar[] = {
4192 buf.sysname,
4193 buf.release,
4194 buf.version,
4195 buf.machine,
4196 NULL
4198 arr_v = caml_copy_string_array (sar);
4200 Field (tup_v, 0) = Val_int (platid);
4201 Field (tup_v, 1) = arr_v;
4202 CAMLreturn (tup_v);
4205 CAMLprim value ml_cloexec (value fd_v)
4207 CAMLparam1 (fd_v);
4208 int fd = Int_val (fd_v);
4210 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4211 uerror ("fcntl", Nothing);
4213 CAMLreturn (Val_unit);
4216 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4218 CAMLparam2 (w_v, h_v);
4219 CAMLlocal1 (ret_v);
4220 struct bo *pbo;
4221 int w = Int_val (w_v);
4222 int h = Int_val (h_v);
4223 int cs = Int_val (cs_v);
4225 if (state.bo_usable) {
4226 pbo = calloc (sizeof (*pbo), 1);
4227 if (!pbo) {
4228 err (1, "calloc pbo");
4231 switch (cs) {
4232 case 0:
4233 case 1:
4234 pbo->size = w*h*4;
4235 break;
4236 case 2:
4237 pbo->size = w*h*2;
4238 break;
4239 default:
4240 errx (1, "%s: invalid colorspace %d", __func__, cs);
4243 state.glGenBuffersARB (1, &pbo->id);
4244 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4245 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4246 NULL, GL_STREAM_DRAW);
4247 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4248 GL_READ_WRITE);
4249 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4250 if (!pbo->ptr) {
4251 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4252 state.glDeleteBuffersARB (1, &pbo->id);
4253 free (pbo);
4254 ret_v = caml_copy_string ("0");
4256 else {
4257 int res;
4258 char *s;
4260 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4261 if (res < 0) {
4262 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4264 s = malloc (res+1);
4265 if (!s) {
4266 err (1, "malloc %d bytes failed", res+1);
4268 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4269 if (res < 0) {
4270 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4272 ret_v = caml_copy_string (s);
4273 free (s);
4276 else {
4277 ret_v = caml_copy_string ("0");
4279 CAMLreturn (ret_v);
4282 CAMLprim value ml_freepbo (value s_v)
4284 CAMLparam1 (s_v);
4285 char *s = String_val (s_v);
4286 struct tile *tile = parse_pointer (__func__, s);
4288 if (tile->pbo) {
4289 state.glDeleteBuffersARB (1, &tile->pbo->id);
4290 tile->pbo->id = -1;
4291 tile->pbo->ptr = NULL;
4292 tile->pbo->size = -1;
4294 CAMLreturn (Val_unit);
4297 CAMLprim value ml_unmappbo (value s_v)
4299 CAMLparam1 (s_v);
4300 char *s = String_val (s_v);
4301 struct tile *tile = parse_pointer (__func__, s);
4303 if (tile->pbo) {
4304 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4305 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4306 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4308 tile->pbo->ptr = NULL;
4309 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4311 CAMLreturn (Val_unit);
4314 static void setuppbo (void)
4316 #ifdef USE_EGL
4317 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4318 #else
4319 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4320 #endif
4321 state.bo_usable = GGPA (glBindBufferARB)
4322 && GGPA (glUnmapBufferARB)
4323 && GGPA (glMapBufferARB)
4324 && GGPA (glBufferDataARB)
4325 && GGPA (glGenBuffersARB)
4326 && GGPA (glDeleteBuffersARB);
4327 #undef GGPA
4330 CAMLprim value ml_bo_usable (value unit_v)
4332 CAMLparam1 (unit_v);
4333 CAMLreturn (Val_bool (state.bo_usable));
4336 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4338 CAMLparam3 (ptr_v, x_v, y_v);
4339 CAMLlocal2 (ret_v, tup_v);
4340 struct page *page;
4341 char *s = String_val (ptr_v);
4342 int x = Int_val (x_v), y = Int_val (y_v);
4343 struct pagedim *pdim;
4344 fz_point p;
4345 fz_matrix ctm;
4347 page = parse_pointer (__func__, s);
4348 pdim = &state.pagedims[page->pdimno];
4350 ret_v = Val_int (0);
4351 if (trylock (__func__)) {
4352 goto done;
4355 if (pdf_specifics (state.ctx, state.doc)) {
4356 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4357 ctm = state.pagedims[page->pdimno].tctm;
4359 else {
4360 ctm = fz_identity;
4362 p.x = x + pdim->bounds.x0;
4363 p.y = y + pdim->bounds.y0;
4365 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4366 fz_invert_matrix (&ctm, &ctm);
4367 fz_transform_point (&p, &ctm);
4369 tup_v = caml_alloc_tuple (2);
4370 ret_v = caml_alloc_small (1, 1);
4371 Field (tup_v, 0) = Val_int (p.x);
4372 Field (tup_v, 1) = Val_int (p.y);
4373 Field (ret_v, 0) = tup_v;
4375 unlock (__func__);
4376 done:
4377 CAMLreturn (ret_v);
4380 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4381 value x_v, value y_v)
4383 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4384 CAMLlocal1 (ret_v);
4385 struct page *page;
4386 char *s = String_val (ptr_v);
4387 int pageno = Int_val (pageno_v);
4388 int pdimno = Int_val (pdimno_v);
4389 double x = Double_val (x_v), y = Double_val (y_v);
4390 struct pagedim *pdim;
4391 fz_point p;
4392 fz_matrix ctm;
4394 ret_v = Val_int (0);
4395 lock (__func__);
4397 if (!*s) {
4398 page = loadpage (pageno, pdimno);
4400 else {
4401 page = parse_pointer (__func__, s);
4403 pdim = &state.pagedims[pdimno];
4405 if (pdf_specifics (state.ctx, state.doc)) {
4406 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4407 ctm = state.pagedims[page->pdimno].tctm;
4409 else {
4410 ctm = fz_identity;
4412 p.x = x + pdim->bounds.x0;
4413 p.y = y + pdim->bounds.y0;
4415 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4416 fz_transform_point (&p, &ctm);
4418 ret_v = caml_alloc_tuple (2);
4419 Field (ret_v, 0) = caml_copy_double (p.x);
4420 Field (ret_v, 1) = caml_copy_double (p.y);
4422 if (!*s) {
4423 freepage (page);
4425 unlock (__func__);
4426 CAMLreturn (ret_v);
4429 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4430 value contents_v)
4432 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4433 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4435 if (pdf) {
4436 pdf_annot *annot;
4437 struct page *page;
4438 fz_point p;
4439 char *s = String_val (ptr_v);
4441 page = parse_pointer (__func__, s);
4442 annot = pdf_create_annot (state.ctx, pdf,
4443 pdf_page_from_fz_page (state.ctx,
4444 page->fzpage),
4445 FZ_ANNOT_TEXT);
4446 p.x = Int_val (x_v);
4447 p.y = Int_val (y_v);
4448 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4449 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4450 state.dirty = 1;
4452 CAMLreturn (Val_unit);
4455 CAMLprim value ml_delannot (value ptr_v, value n_v)
4457 CAMLparam2 (ptr_v, n_v);
4458 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4460 if (pdf) {
4461 struct page *page;
4462 char *s = String_val (ptr_v);
4463 struct slink *slink;
4465 page = parse_pointer (__func__, s);
4466 slink = &page->slinks[Int_val (n_v)];
4467 pdf_delete_annot (state.ctx, pdf,
4468 pdf_page_from_fz_page (state.ctx, page->fzpage),
4469 (pdf_annot *) slink->u.annot);
4470 state.dirty = 1;
4472 CAMLreturn (Val_unit);
4475 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4477 CAMLparam3 (ptr_v, n_v, str_v);
4478 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4480 if (pdf) {
4481 struct page *page;
4482 char *s = String_val (ptr_v);
4483 struct slink *slink;
4485 page = parse_pointer (__func__, s);
4486 slink = &page->slinks[Int_val (n_v)];
4487 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4488 String_val (str_v));
4489 state.dirty = 1;
4491 CAMLreturn (Val_unit);
4494 CAMLprim value ml_hasunsavedchanges (value unit_v)
4496 CAMLparam1 (unit_v);
4497 CAMLreturn (Val_bool (state.dirty));
4500 CAMLprim value ml_savedoc (value path_v)
4502 CAMLparam1 (path_v);
4503 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4505 if (pdf) {
4506 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4508 CAMLreturn (Val_unit);
4511 static void makestippletex (void)
4513 const char pixels[] = "\xff\xff\0\0";
4514 glGenTextures (1, &state.stid);
4515 glBindTexture (GL_TEXTURE_1D, state.stid);
4516 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4517 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4518 glTexImage1D (
4519 GL_TEXTURE_1D,
4521 GL_ALPHA,
4524 GL_ALPHA,
4525 GL_UNSIGNED_BYTE,
4526 pixels
4530 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4532 return caml_copy_string (FZ_VERSION);
4535 #ifdef USE_FONTCONFIG
4536 static struct {
4537 int inited;
4538 FcConfig *config;
4539 } fc;
4541 static fz_font *fc_load_system_font_func (fz_context *ctx,
4542 const char *name,
4543 int bold,
4544 int italic,
4545 int UNUSED_ATTR needs_exact_metrics)
4547 char *buf;
4548 size_t i, size;
4549 fz_font *font;
4550 FcChar8 *path;
4551 FcResult result;
4552 FcPattern *pat, *pat1;
4554 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4555 name, bold, italic, needs_exact_metrics);
4556 if (!fc.inited) {
4557 fc.inited = 1;
4558 fc.config = FcInitLoadConfigAndFonts ();
4559 if (!fc.config) {
4560 lprintf ("FcInitLoadConfigAndFonts failed\n");
4561 return NULL;
4564 if (!fc.config) return NULL;
4566 size = strlen (name);
4567 if (bold) size += sizeof (":bold") - 1;
4568 if (italic) size += sizeof (":italic") - 1;
4569 size += 1;
4571 buf = malloc (size);
4572 if (!buf) {
4573 err (1, "malloc %zu failed", size);
4576 strcpy (buf, name);
4577 if (bold && italic) {
4578 strcat (buf, ":bold:italic");
4580 else {
4581 if (bold) strcat (buf, ":bold");
4582 if (italic) strcat (buf, ":italic");
4584 for (i = 0; i < size; ++i) {
4585 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4588 lprintf ("fcbuf=%s\n", buf);
4589 pat = FcNameParse ((FcChar8 *) buf);
4590 if (!pat) {
4591 printd ("emsg FcNameParse failed\n");
4592 free (buf);
4593 return NULL;
4596 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4597 printd ("emsg FcConfigSubstitute failed\n");
4598 free (buf);
4599 return NULL;
4601 FcDefaultSubstitute (pat);
4603 pat1 = FcFontMatch (fc.config, pat, &result);
4604 if (!pat1) {
4605 printd ("emsg FcFontMatch failed\n");
4606 FcPatternDestroy (pat);
4607 free (buf);
4608 return NULL;
4611 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4612 printd ("emsg FcPatternGetString failed\n");
4613 FcPatternDestroy (pat);
4614 FcPatternDestroy (pat1);
4615 free (buf);
4616 return NULL;
4619 #if 0
4620 printd ("emsg name=%s path=%s\n", name, path);
4621 #endif
4622 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4623 FcPatternDestroy (pat);
4624 FcPatternDestroy (pat1);
4625 free (buf);
4626 return font;
4628 #endif
4630 CAMLprim value ml_init (value csock_v, value params_v)
4632 CAMLparam2 (csock_v, params_v);
4633 CAMLlocal2 (trim_v, fuzz_v);
4634 int ret;
4635 int texcount;
4636 char *fontpath;
4637 int colorspace;
4638 int mustoresize;
4639 int haspboext;
4641 state.csock = Int_val (csock_v);
4642 state.rotate = Int_val (Field (params_v, 0));
4643 state.fitmodel = Int_val (Field (params_v, 1));
4644 trim_v = Field (params_v, 2);
4645 texcount = Int_val (Field (params_v, 3));
4646 state.sliceheight = Int_val (Field (params_v, 4));
4647 mustoresize = Int_val (Field (params_v, 5));
4648 colorspace = Int_val (Field (params_v, 6));
4649 fontpath = String_val (Field (params_v, 7));
4651 if (caml_string_length (Field (params_v, 8)) > 0) {
4652 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4654 if (!state.trimcachepath) {
4655 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4656 strerror (errno));
4659 haspboext = Bool_val (Field (params_v, 9));
4661 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4662 fz_register_document_handlers (state.ctx);
4664 #ifdef USE_FONTCONFIG
4665 if (Bool_val (Field (params_v, 10))) {
4666 fz_install_load_system_font_funcs (
4667 state.ctx, fc_load_system_font_func, NULL
4670 #endif
4672 state.trimmargins = Bool_val (Field (trim_v, 0));
4673 fuzz_v = Field (trim_v, 1);
4674 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4675 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4676 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4677 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4679 set_tex_params (colorspace);
4681 if (*fontpath) {
4682 #ifndef USE_FONTCONFIG
4683 state.face = load_font (fontpath);
4684 #else
4685 FcChar8 *path;
4686 FcResult result;
4687 char *buf = fontpath;
4688 FcPattern *pat, *pat1;
4690 fc.inited = 1;
4691 fc.config = FcInitLoadConfigAndFonts ();
4692 if (!fc.config) {
4693 errx (1, "FcInitLoadConfigAndFonts failed");
4696 pat = FcNameParse ((FcChar8 *) buf);
4697 if (!pat) {
4698 errx (1, "FcNameParse failed");
4701 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4702 errx (1, "FcConfigSubstitute failed");
4704 FcDefaultSubstitute (pat);
4706 pat1 = FcFontMatch (fc.config, pat, &result);
4707 if (!pat1) {
4708 errx (1, "FcFontMatch failed");
4711 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4712 errx (1, "FcPatternGetString failed");
4715 state.face = load_font ((char *) path);
4716 FcPatternDestroy (pat);
4717 FcPatternDestroy (pat1);
4718 #endif
4720 else {
4721 int len;
4722 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4723 0, 0, &len);
4724 state.face = load_builtin_font (data, len);
4726 if (!state.face) _exit (1);
4728 realloctexts (texcount);
4730 if (haspboext) {
4731 setuppbo ();
4734 makestippletex ();
4736 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4737 if (ret) {
4738 errx (1, "pthread_create: %s", strerror (ret));
4741 CAMLreturn (Val_unit);