Fix locking
[llpp.git] / link.c
blob71eb2e3e7711ac9a9feca58af21274f26dbe1bbc
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
4 #include <errno.h>
5 #include <stdio.h>
6 #include <ctype.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <signal.h>
10 #include <wchar.h>
12 #include <unistd.h>
13 #include <pthread.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/utsname.h>
19 #ifdef __CYGWIN__
20 #include <cygwin/socket.h> /* FIONREAD */
21 #else
22 #include <spawn.h>
23 #endif
25 #include <regex.h>
26 #include <stdarg.h>
27 #include <limits.h>
28 #include <inttypes.h>
30 #include <GL/gl.h>
32 #include <caml/fail.h>
33 #include <caml/alloc.h>
34 #include <caml/memory.h>
35 #include <caml/unixsupport.h>
37 #if __GNUC__ < 5 && !defined __clang__
38 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
39 clobbered diagnostics */
40 #pragma GCC diagnostic ignored "-Wclobbered"
41 #endif
43 #include <mupdf/fitz.h>
44 #include <mupdf/pdf.h>
46 #include <ft2build.h>
47 #include FT_FREETYPE_H
49 #ifdef USE_FONTCONFIG
50 #include <fontconfig/fontconfig.h>
51 #endif
53 #define PIGGYBACK
54 #define CACHE_PAGEREFS
56 #ifndef __USE_GNU
57 extern char **environ;
58 #endif
60 #if defined __GNUC__
61 #define NORETURN_ATTR __attribute__ ((noreturn))
62 #define UNUSED_ATTR __attribute__ ((unused))
63 #if !defined __clang__
64 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
65 #else
66 #define OPTIMIZE_ATTR(n)
67 #endif
68 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
69 #else
70 #define NORETURN_ATTR
71 #define UNUSED_ATTR
72 #define OPTIMIZE_ATTR(n)
73 #define GCC_FMT_ATTR(a, b)
74 #endif
76 #define FMT_s "zu"
78 #define FMT_ptr PRIxPTR
79 #define SCN_ptr SCNxPTR
80 #define FMT_ptr_cast(p) ((uintptr_t) (p))
81 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
83 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
84 err (int exitcode, const char *fmt, ...)
86 va_list ap;
87 int savederrno;
89 savederrno = errno;
90 va_start (ap, fmt);
91 vfprintf (stderr, fmt, ap);
92 va_end (ap);
93 fprintf (stderr, ": %s\n", strerror (savederrno));
94 fflush (stderr);
95 _exit (exitcode);
98 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
99 errx (int exitcode, const char *fmt, ...)
101 va_list ap;
103 va_start (ap, fmt);
104 vfprintf (stderr, fmt, ap);
105 va_end (ap);
106 fputc ('\n', stderr);
107 fflush (stderr);
108 _exit (exitcode);
111 #ifndef GL_TEXTURE_RECTANGLE_ARB
112 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
113 #endif
115 #ifdef USE_NPOT
116 #define TEXT_TYPE GL_TEXTURE_2D
117 #else
118 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
119 #endif
121 #ifndef GL_BGRA
122 #define GL_BGRA 0x80E1
123 #endif
125 #ifndef GL_UNSIGNED_INT_8_8_8_8
126 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
127 #endif
129 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
130 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
131 #endif
133 #if 0
134 #define lprintf printf
135 #else
136 #define lprintf(...)
137 #endif
139 #define ARSERT(cond) for (;;) { \
140 if (!(cond)) { \
141 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
143 break; \
146 struct slice {
147 int h;
148 int texindex;
151 struct tile {
152 int w, h;
153 int slicecount;
154 int sliceheight;
155 struct bo *pbo;
156 fz_pixmap *pixmap;
157 struct slice slices[1];
160 struct pagedim {
161 int pageno;
162 int rotate;
163 int left;
164 int tctmready;
165 fz_irect bounds;
166 fz_rect pagebox;
167 fz_rect mediabox;
168 fz_matrix ctm, zoomctm, lctm, tctm;
171 struct slink {
172 enum { SLINK, SANNOT } tag;
173 fz_irect bbox;
174 union {
175 fz_link *link;
176 fz_annot *annot;
177 } u;
180 struct annot {
181 fz_irect bbox;
182 fz_annot *annot;
185 struct page {
186 int tgen;
187 int sgen;
188 int agen;
189 int pageno;
190 int pdimno;
191 fz_stext_page *text;
192 fz_stext_sheet *sheet;
193 fz_page *fzpage;
194 fz_display_list *dlist;
195 int slinkcount;
196 struct slink *slinks;
197 int annotcount;
198 struct annot *annots;
199 struct mark {
200 int i;
201 fz_stext_span *span;
202 } fmark, lmark;
205 struct {
206 int sliceheight;
207 struct pagedim *pagedims;
208 int pagecount;
209 int pagedimcount;
210 fz_document *doc;
211 fz_context *ctx;
212 int w, h;
214 int texindex;
215 int texcount;
216 GLuint *texids;
218 GLenum texiform;
219 GLenum texform;
220 GLenum texty;
222 fz_colorspace *colorspace;
224 struct {
225 int w, h;
226 struct slice *slice;
227 } *texowners;
229 int rotate;
230 enum { FitWidth, FitProportional, FitPage } fitmodel;
231 int trimmargins;
232 int needoutline;
233 int gen;
234 int aalevel;
236 int trimanew;
237 fz_irect trimfuzz;
238 fz_pixmap *pig;
240 pthread_t thread;
241 int csock;
242 FT_Face face;
244 char *trimcachepath;
245 int cxack;
246 int dirty;
248 GLuint stid;
250 int bo_usable;
251 GLuint boid;
253 void (*glBindBufferARB) (GLenum, GLuint);
254 GLboolean (*glUnmapBufferARB) (GLenum);
255 void *(*glMapBufferARB) (GLenum, GLenum);
256 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
257 void (*glGenBuffersARB) (GLsizei, GLuint *);
258 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
260 GLfloat texcoords[8];
261 GLfloat vertices[16];
263 #ifdef CACHE_PAGEREFS
264 struct {
265 int idx;
266 int count;
267 pdf_obj **objs;
268 pdf_document *pdf;
269 } pdflut;
270 #endif
271 } state;
273 struct bo {
274 GLuint id;
275 void *ptr;
276 size_t size;
279 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
281 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
284 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
286 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
289 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
291 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
292 m.a, m.b, m.c, m.d, m.e, m.f);
295 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
297 static void lock (const char *cap)
299 int ret = pthread_mutex_lock (&mutex);
300 if (ret) {
301 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
305 static void unlock (const char *cap)
307 int ret = pthread_mutex_unlock (&mutex);
308 if (ret) {
309 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
313 static int trylock (const char *cap)
315 int ret = pthread_mutex_trylock (&mutex);
316 if (ret && ret != EBUSY) {
317 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
319 return ret == EBUSY;
322 static void *parse_pointer (const char *cap, const char *s)
324 int ret;
325 void *ptr;
327 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
328 if (ret != 1) {
329 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
331 return ptr;
334 static double now (void)
336 struct timeval tv;
338 if (gettimeofday (&tv, NULL)) {
339 err (1, "gettimeofday");
341 return tv.tv_sec + tv.tv_usec*1e-6;
344 static int hasdata (void)
346 int ret, avail;
347 ret = ioctl (state.csock, FIONREAD, &avail);
348 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
349 return avail > 0;
352 CAMLprim value ml_hasdata (value fd_v)
354 CAMLparam1 (fd_v);
355 int ret, avail;
357 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
358 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
359 CAMLreturn (Val_bool (avail > 0));
362 static void readdata (int fd, void *p, int size)
364 ssize_t n;
366 again:
367 n = read (fd, p, size);
368 if (n < 0) {
369 if (errno == EINTR) goto again;
370 err (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
372 if (n - size) {
373 if (!n) errx (1, "EOF while reading");
374 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
378 static void writedata (int fd, char *p, int size)
380 ssize_t n;
382 /* One should lookup type punning/strict aliasing etc in standard,DRs,Web to
383 convince herself that this is:
384 a. safe
385 b. practically the only way to achieve the result
386 (union puns notwithstanding) */
387 memcpy (p, &size, 4);
388 n = write (fd, p, size + 4);
389 if (n - size - 4) {
390 if (!n) errx (1, "EOF while writing data");
391 err (1, "write (fd %d, req %d, ret %zd)", fd, size + 4, n);
395 static int readlen (int fd)
397 /* Type punned unions here. Why? Less code (Adjusted by more comments).
398 https://en.wikipedia.org/wiki/Type_punning */
399 union { int len; char raw[4]; } buf;
400 readdata (fd, buf.raw, 4);
401 return buf.len;
404 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
406 CAMLparam3 (fd_v, bytes_v, len_v);
407 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
408 CAMLreturn0;
411 CAMLprim value ml_rcmd (value fd_v)
413 CAMLparam1 (fd_v);
414 CAMLlocal1 (strdata_v);
415 int fd = Int_val (fd_v);
416 int len = readlen (fd);
417 strdata_v = caml_alloc_string (len);
418 readdata (fd, String_val (strdata_v), len);
419 CAMLreturn (strdata_v);
422 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
424 int size = 200, len;
425 va_list ap;
426 char *buf;
428 buf = malloc (size);
429 for (;;) {
430 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
432 va_start (ap, fmt);
433 len = vsnprintf (buf + 4, size - 4, fmt, ap);
434 va_end (ap);
436 if (len > -1) {
437 if (len < size - 4) {
438 writedata (state.csock, buf, len);
439 break;
441 else size = len + 5;
443 else {
444 err (1, "vsnprintf for `%s' failed", fmt);
446 buf = realloc (buf, size);
448 free (buf);
451 static void closedoc (void)
453 #ifdef CACHE_PAGEREFS
454 if (state.pdflut.objs) {
455 int i;
457 for (i = 0; i < state.pdflut.count; ++i) {
458 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
460 free (state.pdflut.objs);
461 state.pdflut.objs = NULL;
462 state.pdflut.idx = 0;
464 #endif
465 if (state.doc) {
466 fz_drop_document (state.ctx, state.doc);
467 state.doc = NULL;
471 static int openxref (char *filename, char *password)
473 int i;
475 for (i = 0; i < state.texcount; ++i) {
476 state.texowners[i].w = -1;
477 state.texowners[i].slice = NULL;
480 closedoc ();
482 state.dirty = 0;
483 if (state.pagedims) {
484 free (state.pagedims);
485 state.pagedims = NULL;
487 state.pagedimcount = 0;
489 fz_set_aa_level (state.ctx, state.aalevel);
490 #ifdef CSS_HACK_TO_READ_EPUBS_COMFORTABLY
491 fz_set_user_css (state.ctx,
492 "body { margin-left: 20%; margin-right: 20%; }");
493 #endif
494 state.doc = fz_open_document (state.ctx, filename);
495 if (fz_needs_password (state.ctx, state.doc)) {
496 if (password && !*password) {
497 printd ("pass");
498 return 0;
500 else {
501 int ok = fz_authenticate_password (state.ctx, state.doc, password);
502 if (!ok) {
503 printd ("pass fail");
504 return 0;
508 state.pagecount = fz_count_pages (state.ctx, state.doc);
509 return 1;
512 static void pdfinfo (void)
514 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
515 if (pdf) {
516 pdf_obj *infoobj;
518 printd ("info PDF version\t%d.%d",
519 pdf->version / 10, pdf->version % 10);
521 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
522 pdf), "Info");
523 if (infoobj) {
524 unsigned int i;
525 char *s;
526 char *items[] = { "Title", "Author", "Creator",
527 "Producer", "CreationDate" };
529 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
530 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
531 s = pdf_to_utf8 (state.ctx, pdf, obj);
532 if (*s) printd ("info %s\t%s", items[i], s);
533 fz_free (state.ctx, s);
536 printd ("infoend");
540 static void unlinktile (struct tile *tile)
542 int i;
544 for (i = 0; i < tile->slicecount; ++i) {
545 struct slice *s = &tile->slices[i];
547 if (s->texindex != -1) {
548 if (state.texowners[s->texindex].slice == s) {
549 state.texowners[s->texindex].slice = NULL;
555 static void freepage (struct page *page)
557 if (!page) return;
558 if (page->text) {
559 fz_drop_stext_page (state.ctx, page->text);
561 if (page->sheet) {
562 fz_drop_stext_sheet (state.ctx, page->sheet);
564 if (page->slinks) {
565 free (page->slinks);
567 fz_drop_display_list (state.ctx, page->dlist);
568 fz_drop_page (state.ctx, page->fzpage);
569 free (page);
572 static void freetile (struct tile *tile)
574 unlinktile (tile);
575 if (!tile->pbo) {
576 #ifndef PIGGYBACK
577 fz_drop_pixmap (state.ctx, tile->pixmap);
578 #else
579 if (state.pig) {
580 fz_drop_pixmap (state.ctx, state.pig);
582 state.pig = tile->pixmap;
583 #endif
585 else {
586 free (tile->pbo);
587 fz_drop_pixmap (state.ctx, tile->pixmap);
589 free (tile);
592 #ifdef __ALTIVEC__
593 #include <stdint.h>
594 #include <altivec.h>
596 static int cacheline32bytes;
598 static void __attribute__ ((constructor)) clcheck (void)
600 char **envp = environ;
601 unsigned long *auxv;
603 while (*envp++);
605 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
606 if (*auxv == 19) {
607 cacheline32bytes = auxv[1] == 32;
608 return;
613 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
615 size_t size = pixmap->w * pixmap->h * pixmap->n;
616 if (cacheline32bytes && size > 32) {
617 intptr_t a1, a2, diff;
618 size_t sizea, i;
619 vector unsigned char v = vec_splat_u8 (-1);
620 vector unsigned char *p;
622 a1 = a2 = (intptr_t) pixmap->samples;
623 a2 = (a1 + 31) & ~31;
624 diff = a2 - a1;
625 sizea = size - diff;
626 p = (void *) a2;
628 while (a1 != a2) *(char *) a1++ = 0xff;
629 for (i = 0; i < (sizea & ~31); i += 32) {
630 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
631 vec_st (v, i, p);
632 vec_st (v, i + 16, p);
634 while (i < sizea) *((char *) a1 + i++) = 0xff;
636 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
638 #else
639 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
640 #endif
642 static void trimctm (pdf_page *page, int pindex)
644 fz_matrix ctm;
645 struct pagedim *pdim = &state.pagedims[pindex];
647 if (!page) return;
648 if (!pdim->tctmready) {
649 fz_rect realbox, mediabox;
650 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
652 fz_rotate (&rm, -pdim->rotate);
653 fz_scale (&sm, 1, -1);
654 fz_concat (&ctm, &rm, &sm);
655 realbox = pdim->mediabox;
656 fz_transform_rect (&realbox, &ctm);
657 fz_translate (&tm, -realbox.x0, -realbox.y0);
658 fz_concat (&ctm1, &ctm, &tm);
659 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
660 fz_invert_matrix (&im, &page_ctm);
661 fz_concat (&ctm, &im, &ctm1);
662 pdim->tctm = ctm;
663 pdim->tctmready = 1;
667 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
669 fz_matrix ctm, tm;
670 int pdimno = pdim - state.pagedims;
672 if (pdf_specifics (state.ctx, state.doc)) {
673 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
674 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
676 else {
677 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
678 fz_concat (&ctm, &tm, &pdim->ctm);
680 return ctm;
683 static fz_matrix pagectm (struct page *page)
685 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
688 static void *loadpage (int pageno, int pindex)
690 fz_device *dev;
691 struct page *page;
693 page = calloc (sizeof (struct page), 1);
694 if (!page) {
695 err (1, "calloc page %d", pageno);
698 page->dlist = fz_new_display_list (state.ctx, NULL);
699 dev = fz_new_list_device (state.ctx, page->dlist);
700 fz_try (state.ctx) {
701 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
702 fz_run_page (state.ctx, page->fzpage, dev,
703 &fz_identity, NULL);
705 fz_catch (state.ctx) {
706 page->fzpage = NULL;
708 fz_close_device (state.ctx, dev);
709 fz_drop_device (state.ctx, dev);
711 page->pdimno = pindex;
712 page->pageno = pageno;
713 page->sgen = state.gen;
714 page->agen = state.gen;
715 page->tgen = state.gen;
716 return page;
719 static struct tile *alloctile (int h)
721 int i;
722 int slicecount;
723 size_t tilesize;
724 struct tile *tile;
726 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
727 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
728 tile = calloc (tilesize, 1);
729 if (!tile) {
730 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
732 for (i = 0; i < slicecount; ++i) {
733 int sh = fz_mini (h, state.sliceheight);
734 tile->slices[i].h = sh;
735 tile->slices[i].texindex = -1;
736 h -= sh;
738 tile->slicecount = slicecount;
739 tile->sliceheight = state.sliceheight;
740 return tile;
743 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
744 struct bo *pbo)
746 fz_rect rect;
747 fz_irect bbox;
748 fz_matrix ctm;
749 fz_device *dev;
750 struct tile *tile;
751 struct pagedim *pdim;
753 tile = alloctile (h);
754 pdim = &state.pagedims[page->pdimno];
756 bbox = pdim->bounds;
757 bbox.x0 += x;
758 bbox.y0 += y;
759 bbox.x1 = bbox.x0 + w;
760 bbox.y1 = bbox.y0 + h;
762 if (state.pig) {
763 if (state.pig->w == w
764 && state.pig->h == h
765 && state.pig->colorspace == state.colorspace) {
766 tile->pixmap = state.pig;
767 tile->pixmap->x = bbox.x0;
768 tile->pixmap->y = bbox.y0;
770 else {
771 fz_drop_pixmap (state.ctx, state.pig);
773 state.pig = NULL;
775 if (!tile->pixmap) {
776 if (pbo) {
777 tile->pixmap =
778 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
779 &bbox, 1, pbo->ptr);
780 tile->pbo = pbo;
782 else {
783 tile->pixmap =
784 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
788 tile->w = w;
789 tile->h = h;
790 clearpixmap (tile->pixmap);
792 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
793 ctm = pagectm (page);
794 fz_rect_from_irect (&rect, &bbox);
795 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
796 fz_close_device (state.ctx, dev);
797 fz_drop_device (state.ctx, dev);
799 return tile;
802 #ifdef CACHE_PAGEREFS
803 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
804 thanks to Robin Watts */
805 static void
806 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
808 fz_context *ctx = state.ctx; /* doc->ctx; */
809 pdf_obj *kids;
810 int i, len;
812 if (state.pdflut.idx == state.pagecount) return;
814 kids = pdf_dict_gets (ctx, node, "Kids");
815 len = pdf_array_len (ctx, kids);
817 if (len == 0)
818 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
820 if (pdf_mark_obj (ctx, node))
821 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
822 for (i = 0; i < len; i++) {
823 pdf_obj *kid = pdf_array_get (ctx, kids, i);
824 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
825 if (*type
826 ? !strcmp (type, "Pages")
827 : pdf_dict_gets (ctx, kid, "Kids")
828 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
829 pdf_collect_pages (doc, kid);
831 else {
832 if (*type
833 ? strcmp (type, "Page") != 0
834 : !pdf_dict_gets (ctx, kid, "MediaBox"))
835 fz_warn (ctx, "non-page object in page tree (%s)", type);
836 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
839 pdf_unmark_obj (ctx, node);
842 static void
843 pdf_load_page_objs (pdf_document *doc)
845 pdf_obj *root = pdf_dict_gets (state.ctx,
846 pdf_trailer (state.ctx, doc), "Root");
847 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
849 if (!node)
850 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
852 state.pdflut.idx = 0;
853 pdf_collect_pages (doc, node);
855 #endif
857 static void initpdims (int wthack)
859 double start, end;
860 FILE *trimf = NULL;
861 fz_rect rootmediabox;
862 int pageno, trim, show;
863 int trimw = 0, cxcount;
864 fz_context *ctx = state.ctx;
865 pdf_document *pdf = pdf_specifics (ctx, state.doc);
867 fz_var (trimw);
868 fz_var (trimf);
869 fz_var (cxcount);
870 start = now ();
872 if (state.trimmargins && state.trimcachepath) {
873 trimf = fopen (state.trimcachepath, "rb");
874 if (!trimf) {
875 trimf = fopen (state.trimcachepath, "wb");
876 trimw = 1;
880 if (state.trimmargins || pdf || !state.cxack)
881 cxcount = state.pagecount;
882 else
883 cxcount = fz_mini (state.pagecount, 1);
885 if (pdf) {
886 pdf_obj *obj;
887 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
888 "Root/Pages/MediaBox");
889 pdf_to_rect (ctx, obj, &rootmediabox);
892 #ifdef CACHE_PAGEREFS
893 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
894 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
895 if (!state.pdflut.objs) {
896 err (1, "malloc pageobjs %zu %d %zu failed",
897 sizeof (*state.pdflut.objs), cxcount,
898 sizeof (*state.pdflut.objs) * cxcount);
900 state.pdflut.count = cxcount;
901 pdf_load_page_objs (pdf);
902 state.pdflut.pdf = pdf;
904 #endif
906 for (pageno = 0; pageno < cxcount; ++pageno) {
907 int rotate = 0;
908 struct pagedim *p;
909 fz_rect mediabox;
911 fz_var (rotate);
912 if (pdf) {
913 pdf_obj *pageref, *pageobj;
915 #ifdef CACHE_PAGEREFS
916 pageref = state.pdflut.objs[pageno];
917 #else
918 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
919 #endif
920 pageobj = pdf_resolve_indirect (ctx, pageref);
921 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
923 if (state.trimmargins) {
924 pdf_obj *obj;
925 pdf_page *page;
927 fz_try (ctx) {
928 page = pdf_load_page (ctx, pdf, pageno);
929 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
930 trim = state.trimanew || !obj;
931 if (trim) {
932 fz_rect rect;
933 fz_device *dev;
934 fz_matrix ctm, page_ctm;
936 dev = fz_new_bbox_device (ctx, &rect);
937 dev->hints |= FZ_IGNORE_SHADE;
938 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
939 fz_invert_matrix (&ctm, &page_ctm);
940 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
941 fz_close_device (ctx, dev);
942 fz_drop_device (ctx, dev);
944 rect.x0 += state.trimfuzz.x0;
945 rect.x1 += state.trimfuzz.x1;
946 rect.y0 += state.trimfuzz.y0;
947 rect.y1 += state.trimfuzz.y1;
948 fz_transform_rect (&rect, &ctm);
949 fz_intersect_rect (&rect, &mediabox);
951 if (!fz_is_empty_rect (&rect)) {
952 mediabox = rect;
955 obj = pdf_new_array (ctx, pdf, 4);
956 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
957 mediabox.x0));
958 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
959 mediabox.y0));
960 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
961 mediabox.x1));
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.y1));
964 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
966 else {
967 mediabox.x0 = pdf_to_real (ctx,
968 pdf_array_get (ctx, obj, 0));
969 mediabox.y0 = pdf_to_real (ctx,
970 pdf_array_get (ctx, obj, 1));
971 mediabox.x1 = pdf_to_real (ctx,
972 pdf_array_get (ctx, obj, 2));
973 mediabox.y1 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 3));
977 fz_drop_page (ctx, &page->super);
978 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
979 if (show) {
980 printd ("progress %f Trimming %d",
981 (double) (pageno + 1) / state.pagecount,
982 pageno + 1);
985 fz_catch (ctx) {
986 fprintf (stderr, "failed to load page %d\n", pageno+1);
989 else {
990 int empty = 0;
991 fz_rect cropbox;
993 pdf_to_rect (ctx,
994 pdf_dict_gets (ctx, pageobj, "MediaBox"),
995 &mediabox);
996 if (fz_is_empty_rect (&mediabox)) {
997 mediabox.x0 = 0;
998 mediabox.y0 = 0;
999 mediabox.x1 = 612;
1000 mediabox.y1 = 792;
1001 empty = 1;
1004 pdf_to_rect (ctx,
1005 pdf_dict_gets (ctx, pageobj, "CropBox"),
1006 &cropbox);
1007 if (!fz_is_empty_rect (&cropbox)) {
1008 if (empty) {
1009 mediabox = cropbox;
1011 else {
1012 fz_intersect_rect (&mediabox, &cropbox);
1015 else {
1016 if (empty) {
1017 if (fz_is_empty_rect (&rootmediabox)) {
1018 fprintf (stderr,
1019 "cannot find page size for page %d\n",
1020 pageno+1);
1022 else {
1023 mediabox = rootmediabox;
1029 else {
1030 if (state.trimmargins && trimw) {
1031 fz_page *page;
1033 fz_try (ctx) {
1034 page = fz_load_page (ctx, state.doc, pageno);
1035 fz_bound_page (ctx, page, &mediabox);
1036 if (state.trimmargins) {
1037 fz_rect rect;
1038 fz_device *dev;
1040 dev = fz_new_bbox_device (ctx, &rect);
1041 dev->hints |= FZ_IGNORE_SHADE;
1042 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1043 fz_close_device (ctx, dev);
1044 fz_drop_device (ctx, dev);
1046 rect.x0 += state.trimfuzz.x0;
1047 rect.x1 += state.trimfuzz.x1;
1048 rect.y0 += state.trimfuzz.y0;
1049 rect.y1 += state.trimfuzz.y1;
1050 fz_intersect_rect (&rect, &mediabox);
1052 if (!fz_is_empty_rect (&rect)) {
1053 mediabox = rect;
1056 fz_drop_page (ctx, page);
1057 if (!state.cxack) {
1058 printd ("progress %f loading %d",
1059 (double) (pageno + 1) / state.pagecount,
1060 pageno + 1);
1063 fz_catch (ctx) {
1065 if (trimf) {
1066 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1067 if (n - 1) {
1068 err (1, "fwrite trim mediabox");
1072 else {
1073 if (trimf) {
1074 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1075 if (n - 1) {
1076 err (1, "fread trim mediabox %d", pageno);
1079 else {
1080 fz_page *page;
1081 fz_try (ctx) {
1082 page = fz_load_page (ctx, state.doc, pageno);
1083 fz_bound_page (ctx, page, &mediabox);
1084 fz_drop_page (ctx, page);
1086 show = !state.trimmargins && pageno % 20 == 0;
1087 if (show) {
1088 printd ("progress %f Gathering dimensions %d",
1089 (double) (pageno) / state.pagecount,
1090 pageno);
1093 fz_catch (ctx) {
1094 fprintf (stderr, "failed to load page %d\n", pageno);
1100 if (state.pagedimcount == 0
1101 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1102 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1103 size_t size;
1105 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1106 state.pagedims = realloc (state.pagedims, size);
1107 if (!state.pagedims) {
1108 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1109 size, state.pagedimcount + 1);
1112 p = &state.pagedims[state.pagedimcount++];
1113 p->rotate = rotate;
1114 p->mediabox = mediabox;
1115 p->pageno = pageno;
1118 end = now ();
1119 if (!wthack) {
1120 printd ("progress 1 %s %d pages in %f seconds",
1121 state.trimmargins ? "Trimmed" : "Processed",
1122 state.pagecount, end - start);
1124 state.trimanew = 0;
1125 if (trimf) {
1126 if (fclose (trimf)) {
1127 err (1, "fclose");
1132 static void layout (void)
1134 int pindex;
1135 fz_rect box;
1136 fz_matrix ctm, rm;
1137 struct pagedim *p = p;
1138 double zw, w, maxw = 0.0, zoom = zoom;
1140 if (state.pagedimcount == 0) return;
1142 switch (state.fitmodel) {
1143 case FitProportional:
1144 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1145 double x0, x1;
1147 p = &state.pagedims[pindex];
1148 fz_rotate (&rm, p->rotate + state.rotate);
1149 box = p->mediabox;
1150 fz_transform_rect (&box, &rm);
1152 x0 = fz_min (box.x0, box.x1);
1153 x1 = fz_max (box.x0, box.x1);
1155 w = x1 - x0;
1156 maxw = fz_max (w, maxw);
1157 zoom = state.w / maxw;
1159 break;
1161 case FitPage:
1162 maxw = state.w;
1163 break;
1165 case FitWidth:
1166 break;
1168 default:
1169 ARSERT (0 && state.fitmodel);
1172 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1173 fz_rect rect;
1174 fz_matrix tm, sm;
1176 p = &state.pagedims[pindex];
1177 fz_rotate (&ctm, state.rotate);
1178 fz_rotate (&rm, p->rotate + state.rotate);
1179 box = p->mediabox;
1180 fz_transform_rect (&box, &rm);
1181 w = box.x1 - box.x0;
1182 switch (state.fitmodel) {
1183 case FitProportional:
1184 p->left = ((maxw - w) * zoom) / 2.0;
1185 break;
1186 case FitPage:
1188 double zh, h;
1189 zw = maxw / w;
1190 h = box.y1 - box.y0;
1191 zh = state.h / h;
1192 zoom = fz_min (zw, zh);
1193 p->left = (maxw - (w * zoom)) / 2.0;
1195 break;
1196 case FitWidth:
1197 p->left = 0;
1198 zoom = state.w / w;
1199 break;
1202 fz_scale (&p->zoomctm, zoom, zoom);
1203 fz_concat (&ctm, &p->zoomctm, &ctm);
1205 fz_rotate (&rm, p->rotate);
1206 p->pagebox = p->mediabox;
1207 fz_transform_rect (&p->pagebox, &rm);
1208 p->pagebox.x1 -= p->pagebox.x0;
1209 p->pagebox.y1 -= p->pagebox.y0;
1210 p->pagebox.x0 = 0;
1211 p->pagebox.y0 = 0;
1212 rect = p->pagebox;
1213 fz_transform_rect (&rect, &ctm);
1214 fz_round_rect (&p->bounds, &rect);
1215 p->ctm = ctm;
1217 fz_translate (&tm, 0, -p->mediabox.y1);
1218 fz_scale (&sm, zoom, -zoom);
1219 fz_concat (&ctm, &tm, &sm);
1220 fz_concat (&p->lctm, &ctm, &rm);
1222 p->tctmready = 0;
1225 do {
1226 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1227 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1228 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1229 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1230 int boundw = x1 - x0;
1231 int boundh = y1 - y0;
1233 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1234 } while (p-- != state.pagedims);
1237 static
1238 struct anchor { int n; int x; int y; int w; int h; }
1239 desttoanchor (fz_link_dest *dest)
1241 int i;
1242 struct anchor a;
1243 struct pagedim *pdim = state.pagedims;
1245 a.n = -1;
1246 a.x = 0;
1247 a.y = 0;
1248 for (i = 0; i < state.pagedimcount; ++i) {
1249 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1250 break;
1251 pdim = &state.pagedims[i];
1253 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1254 fz_point p;
1255 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1256 p.x = dest->ld.gotor.lt.x;
1257 else
1258 p.x = 0.0;
1259 p.y = dest->ld.gotor.lt.y;
1260 fz_transform_point (&p, &pdim->lctm);
1261 a.x = p.x;
1262 a.y = p.y;
1264 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1265 double x0, x1, y0, y1;
1267 x0 = fz_min (pdim->bounds.x0, pdim->bounds.x1);
1268 x1 = fz_max (pdim->bounds.x0, pdim->bounds.x1);
1269 a.w = x1 - x0;
1270 y0 = fz_min (pdim->bounds.y0, pdim->bounds.y1);
1271 y1 = fz_max (pdim->bounds.y0, pdim->bounds.y1);
1272 a.h = y1 - y0;
1273 a.n = dest->ld.gotor.page;
1275 return a;
1278 static void recurse_outline (fz_outline *outline, int level)
1280 while (outline) {
1281 switch (outline->dest.kind) {
1282 case FZ_LINK_GOTO:
1284 struct anchor a = desttoanchor (&outline->dest);
1286 if (a.n >= 0) {
1287 printd ("o %d %d %d %d %s",
1288 level, a.n, a.y, a.h, outline->title);
1291 break;
1293 case FZ_LINK_URI:
1294 printd ("ou %d %" FMT_s " %s %s", level,
1295 strlen (outline->title), outline->title,
1296 outline->dest.ld.uri.uri);
1297 break;
1299 case FZ_LINK_NONE:
1300 printd ("on %d %s", level, outline->title);
1301 break;
1303 default:
1304 printd ("emsg Unhandled outline kind %d for %s\n",
1305 outline->dest.kind, outline->title);
1306 break;
1308 if (outline->down) {
1309 recurse_outline (outline->down, level + 1);
1311 outline = outline->next;
1315 static void process_outline (void)
1317 fz_outline *outline;
1319 if (!state.needoutline || !state.pagedimcount) return;
1321 state.needoutline = 0;
1322 outline = fz_load_outline (state.ctx, state.doc);
1323 if (outline) {
1324 recurse_outline (outline, 0);
1325 fz_drop_outline (state.ctx, outline);
1329 static char *strofspan (fz_stext_span *span)
1331 char *p;
1332 char utf8[10];
1333 fz_stext_char *ch;
1334 size_t size = 0, cap = 80;
1336 p = malloc (cap + 1);
1337 if (!p) return NULL;
1339 for (ch = span->text; ch < span->text + span->len; ++ch) {
1340 int n = fz_runetochar (utf8, ch->c);
1341 if (size + n > cap) {
1342 cap *= 2;
1343 p = realloc (p, cap + 1);
1344 if (!p) return NULL;
1347 memcpy (p + size, utf8, n);
1348 size += n;
1350 p[size] = 0;
1351 return p;
1354 static int matchspan (regex_t *re, fz_stext_span *span,
1355 int stop, int pageno, double start)
1357 int ret;
1358 char *p;
1359 regmatch_t rm;
1360 int a, b, c;
1361 fz_rect sb, eb;
1362 fz_point p1, p2, p3, p4;
1364 p = strofspan (span);
1365 if (!p) return -1;
1367 ret = regexec (re, p, 1, &rm, 0);
1368 if (ret) {
1369 free (p);
1370 if (ret != REG_NOMATCH) {
1371 size_t size;
1372 char errbuf[80];
1373 size = regerror (ret, re, errbuf, sizeof (errbuf));
1374 printd ("msg regexec error `%.*s'",
1375 (int) size, errbuf);
1376 return -1;
1378 return 0;
1380 else {
1381 int l = span->len;
1383 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1384 c += fz_runelen (span->text[a].c);
1386 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1387 c += fz_runelen (span->text[b].c);
1390 if (fz_runelen (span->text[b].c) > 1) {
1391 b = fz_maxi (0, b-1);
1394 fz_stext_char_bbox (state.ctx, &sb, span, a);
1395 fz_stext_char_bbox (state.ctx, &eb, span, b);
1397 p1.x = sb.x0;
1398 p1.y = sb.y0;
1399 p2.x = eb.x1;
1400 p2.y = sb.y0;
1401 p3.x = eb.x1;
1402 p3.y = eb.y1;
1403 p4.x = sb.x0;
1404 p4.y = eb.y1;
1406 if (!stop) {
1407 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1408 pageno, 1,
1409 p1.x, p1.y,
1410 p2.x, p2.y,
1411 p3.x, p3.y,
1412 p4.x, p4.y);
1414 printd ("progress 1 found at %d `%.*s' in %f sec",
1415 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1416 now () - start);
1418 else {
1419 printd ("match %d %d %f %f %f %f %f %f %f %f",
1420 pageno, 2,
1421 p1.x, p1.y,
1422 p2.x, p2.y,
1423 p3.x, p3.y,
1424 p4.x, p4.y);
1426 free (p);
1427 return 1;
1431 static int compareblocks (const void *l, const void *r)
1433 fz_stext_block const *ls = l;
1434 fz_stext_block const *rs = r;
1435 return ls->bbox.y0 - rs->bbox.y0;
1438 /* wishful thinking function */
1439 static void search (regex_t *re, int pageno, int y, int forward)
1441 int i, j;
1442 fz_device *tdev;
1443 fz_stext_page *text;
1444 fz_stext_sheet *sheet;
1445 struct pagedim *pdim, *pdimprev;
1446 int stop = 0, niters = 0;
1447 double start, end;
1448 fz_page *page;
1450 start = now ();
1451 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1452 if (niters++ == 5) {
1453 niters = 0;
1454 if (hasdata ()) {
1455 printd ("progress 1 attention requested aborting search at %d",
1456 pageno);
1457 stop = 1;
1459 else {
1460 printd ("progress %f searching in page %d",
1461 (double) (pageno + 1) / state.pagecount,
1462 pageno);
1465 pdimprev = NULL;
1466 for (i = 0; i < state.pagedimcount; ++i) {
1467 pdim = &state.pagedims[i];
1468 if (pdim->pageno == pageno) {
1469 goto found;
1471 if (pdim->pageno > pageno) {
1472 pdim = pdimprev;
1473 goto found;
1475 pdimprev = pdim;
1477 pdim = pdimprev;
1478 found:
1480 sheet = fz_new_stext_sheet (state.ctx);
1481 text = fz_new_stext_page (state.ctx);
1482 tdev = fz_new_stext_device (state.ctx, sheet, text);
1484 page = fz_load_page (state.ctx, state.doc, pageno);
1486 fz_matrix ctm = pagectm1 (page, pdim);
1487 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1490 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1491 fz_close_device (state.ctx, tdev);
1492 fz_drop_device (state.ctx, tdev);
1494 for (j = 0; j < text->len; ++j) {
1495 int k;
1496 fz_page_block *pb;
1497 fz_stext_block *block;
1499 pb = &text->blocks[forward ? j : text->len - 1 - j];
1500 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1501 block = pb->u.text;
1503 for (k = 0; k < block->len; ++k) {
1504 fz_stext_line *line;
1505 fz_stext_span *span;
1507 if (forward) {
1508 line = &block->lines[k];
1509 if (line->bbox.y0 < y + 1) continue;
1511 else {
1512 line = &block->lines[block->len - 1 - k];
1513 if (line->bbox.y0 > y - 1) continue;
1516 for (span = line->first_span; span; span = span->next) {
1517 switch (matchspan (re, span, stop, pageno, start)) {
1518 case 0: break;
1519 case 1: stop = 1; break;
1520 case -1: stop = 1; goto endloop;
1525 if (forward) {
1526 pageno += 1;
1527 y = 0;
1529 else {
1530 pageno -= 1;
1531 y = INT_MAX;
1533 endloop:
1534 fz_drop_stext_page (state.ctx, text);
1535 fz_drop_stext_sheet (state.ctx, sheet);
1536 fz_drop_page (state.ctx, page);
1538 end = now ();
1539 if (!stop) {
1540 printd ("progress 1 no matches %f sec", end - start);
1542 printd ("clearrects");
1545 static void set_tex_params (int colorspace)
1547 union {
1548 unsigned char b;
1549 unsigned int s;
1550 } endianness = {1};
1552 switch (colorspace) {
1553 case 0:
1554 state.texiform = GL_RGBA8;
1555 state.texform = GL_RGBA;
1556 state.texty = GL_UNSIGNED_BYTE;
1557 state.colorspace = fz_device_rgb (state.ctx);
1558 break;
1559 case 1:
1560 state.texiform = GL_RGBA8;
1561 state.texform = GL_BGRA;
1562 state.texty = endianness.s > 1
1563 ? GL_UNSIGNED_INT_8_8_8_8
1564 : GL_UNSIGNED_INT_8_8_8_8_REV;
1565 state.colorspace = fz_device_bgr (state.ctx);
1566 break;
1567 case 2:
1568 state.texiform = GL_LUMINANCE_ALPHA;
1569 state.texform = GL_LUMINANCE_ALPHA;
1570 state.texty = GL_UNSIGNED_BYTE;
1571 state.colorspace = fz_device_gray (state.ctx);
1572 break;
1573 default:
1574 errx (1, "invalid colorspce %d", colorspace);
1578 static void realloctexts (int texcount)
1580 size_t size;
1582 if (texcount == state.texcount) return;
1584 if (texcount < state.texcount) {
1585 glDeleteTextures (state.texcount - texcount,
1586 state.texids + texcount);
1589 size = texcount * sizeof (*state.texids);
1590 state.texids = realloc (state.texids, size);
1591 if (!state.texids) {
1592 err (1, "realloc texids %" FMT_s, size);
1595 size = texcount * sizeof (*state.texowners);
1596 state.texowners = realloc (state.texowners, size);
1597 if (!state.texowners) {
1598 err (1, "realloc texowners %" FMT_s, size);
1600 if (texcount > state.texcount) {
1601 int i;
1603 glGenTextures (texcount - state.texcount,
1604 state.texids + state.texcount);
1605 for (i = state.texcount; i < texcount; ++i) {
1606 state.texowners[i].w = -1;
1607 state.texowners[i].slice = NULL;
1610 state.texcount = texcount;
1611 state.texindex = 0;
1614 static char *mbtoutf8 (char *s)
1616 char *p, *r;
1617 wchar_t *tmp;
1618 size_t i, ret, len;
1620 len = mbstowcs (NULL, s, strlen (s));
1621 if (len == 0) {
1622 return s;
1624 else {
1625 if (len == (size_t) -1) {
1626 return s;
1630 tmp = malloc (len * sizeof (wchar_t));
1631 if (!tmp) {
1632 return s;
1635 ret = mbstowcs (tmp, s, len);
1636 if (ret == (size_t) -1) {
1637 free (tmp);
1638 return s;
1641 len = 0;
1642 for (i = 0; i < ret; ++i) {
1643 len += fz_runelen (tmp[i]);
1646 p = r = malloc (len + 1);
1647 if (!r) {
1648 free (tmp);
1649 return s;
1652 for (i = 0; i < ret; ++i) {
1653 p += fz_runetochar (p, tmp[i]);
1655 *p = 0;
1656 free (tmp);
1657 return r;
1660 CAMLprim value ml_mbtoutf8 (value s_v)
1662 CAMLparam1 (s_v);
1663 CAMLlocal1 (ret_v);
1664 char *s, *r;
1666 s = String_val (s_v);
1667 r = mbtoutf8 (s);
1668 if (r == s) {
1669 ret_v = s_v;
1671 else {
1672 ret_v = caml_copy_string (r);
1673 free (r);
1675 CAMLreturn (ret_v);
1678 static void * mainloop (void UNUSED_ATTR *unused)
1680 char *p = NULL;
1681 int len, ret, oldlen = 0;
1683 fz_var (p);
1684 fz_var (oldlen);
1685 for (;;) {
1686 len = readlen (state.csock);
1687 if (len == 0) {
1688 errx (1, "readlen returned 0");
1691 if (oldlen < len + 1) {
1692 p = realloc (p, len + 1);
1693 if (!p) {
1694 err (1, "realloc %d failed", len + 1);
1696 oldlen = len + 1;
1698 readdata (state.csock, p, len);
1699 p[len] = 0;
1701 if (!strncmp ("open", p, 4)) {
1702 int wthack, off, ok = 0;
1703 char *password;
1704 char *filename;
1705 char *utf8filename;
1706 size_t filenamelen;
1708 fz_var (ok);
1709 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1710 if (ret != 2) {
1711 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1714 filename = p + 5 + off;
1715 filenamelen = strlen (filename);
1716 password = filename + filenamelen + 1;
1718 lock ("open");
1719 fz_try (state.ctx) {
1720 ok = openxref (filename, password);
1722 fz_catch (state.ctx) {
1723 utf8filename = mbtoutf8 (filename);
1724 printd ("msg Could not open %s", utf8filename);
1726 if (ok) {
1727 pdfinfo ();
1728 initpdims (wthack);
1730 unlock ("open");
1732 if (ok) {
1733 if (!wthack) {
1734 utf8filename = mbtoutf8 (filename);
1735 printd ("msg Opened %s (press h/F1 to get help)",
1736 utf8filename);
1737 if (utf8filename != filename) {
1738 free (utf8filename);
1741 state.needoutline = 1;
1744 else if (!strncmp ("cs", p, 2)) {
1745 int i, colorspace;
1747 ret = sscanf (p + 2, " %d", &colorspace);
1748 if (ret != 1) {
1749 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1751 lock ("cs");
1752 set_tex_params (colorspace);
1753 for (i = 0; i < state.texcount; ++i) {
1754 state.texowners[i].w = -1;
1755 state.texowners[i].slice = NULL;
1757 unlock ("cs");
1759 else if (!strncmp ("freepage", p, 8)) {
1760 void *ptr;
1762 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1763 if (ret != 1) {
1764 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1766 freepage (ptr);
1768 else if (!strncmp ("freetile", p, 8)) {
1769 void *ptr;
1771 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1772 if (ret != 1) {
1773 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1775 freetile (ptr);
1777 else if (!strncmp ("search", p, 6)) {
1778 int icase, pageno, y, len2, forward;
1779 char *pattern;
1780 regex_t re;
1782 ret = sscanf (p + 6, " %d %d %d %d,%n",
1783 &icase, &pageno, &y, &forward, &len2);
1784 if (ret != 4) {
1785 errx (1, "malformed search `%s' ret=%d", p, ret);
1788 pattern = p + 6 + len2;
1789 ret = regcomp (&re, pattern,
1790 REG_EXTENDED | (icase ? REG_ICASE : 0));
1791 if (ret) {
1792 char errbuf[80];
1793 size_t size;
1795 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1796 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1798 else {
1799 search (&re, pageno, y, forward);
1800 regfree (&re);
1803 else if (!strncmp ("geometry", p, 8)) {
1804 int w, h, fitmodel;
1806 printd ("clear");
1807 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1808 if (ret != 3) {
1809 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1812 lock ("geometry");
1813 state.h = h;
1814 if (w != state.w) {
1815 int i;
1816 state.w = w;
1817 for (i = 0; i < state.texcount; ++i) {
1818 state.texowners[i].slice = NULL;
1821 state.fitmodel = fitmodel;
1822 layout ();
1823 process_outline ();
1825 state.gen++;
1826 unlock ("geometry");
1827 printd ("continue %d", state.pagecount);
1829 else if (!strncmp ("reqlayout", p, 9)) {
1830 char *nameddest;
1831 int rotate, off, h;
1832 unsigned int fitmodel;
1833 pdf_document *pdf;
1835 printd ("clear");
1836 ret = sscanf (p + 9, " %d %u %d %n",
1837 &rotate, &fitmodel, &h, &off);
1838 if (ret != 3) {
1839 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1841 lock ("reqlayout");
1842 pdf = pdf_specifics (state.ctx, state.doc);
1843 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1844 state.gen += 1;
1846 state.rotate = rotate;
1847 state.fitmodel = fitmodel;
1848 state.h = h;
1849 layout ();
1850 process_outline ();
1852 nameddest = p + 9 + off;
1853 if (pdf && nameddest && *nameddest) {
1854 struct anchor a;
1855 fz_link_dest dest;
1856 pdf_obj *needle, *obj;
1858 needle = pdf_new_string (state.ctx, pdf, nameddest,
1859 strlen (nameddest));
1860 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1861 if (obj) {
1862 dest = pdf_parse_link_dest (state.ctx, pdf,
1863 FZ_LINK_GOTO, obj);
1865 a = desttoanchor (&dest);
1866 if (a.n >= 0) {
1867 printd ("a %d %d %d", a.n, a.x, a.y);
1869 else {
1870 printd ("emsg failed to parse destination `%s'\n",
1871 nameddest);
1874 else {
1875 printd ("emsg destination `%s' not found\n",
1876 nameddest);
1878 pdf_drop_obj (state.ctx, needle);
1881 state.gen++;
1882 unlock ("reqlayout");
1883 printd ("continue %d", state.pagecount);
1885 else if (!strncmp ("page", p, 4)) {
1886 double a, b;
1887 struct page *page;
1888 int pageno, pindex;
1890 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1891 if (ret != 2) {
1892 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1895 lock ("page");
1896 a = now ();
1897 page = loadpage (pageno, pindex);
1898 b = now ();
1899 unlock ("page");
1901 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1903 else if (!strncmp ("tile", p, 4)) {
1904 int x, y, w, h;
1905 struct page *page;
1906 struct tile *tile;
1907 double a, b;
1908 void *data;
1910 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1911 SCN_ptr_cast (&page), &x, &y, &w, &h,
1912 SCN_ptr_cast (&data));
1913 if (ret != 6) {
1914 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1917 lock ("tile");
1918 a = now ();
1919 tile = rendertile (page, x, y, w, h, data);
1920 b = now ();
1921 unlock ("tile");
1923 printd ("tile %d %d %" FMT_ptr " %u %f",
1924 x, y,
1925 FMT_ptr_cast (tile),
1926 tile->w * tile->h * tile->pixmap->n,
1927 b - a);
1929 else if (!strncmp ("trimset", p, 7)) {
1930 fz_irect fuzz;
1931 int trimmargins;
1933 ret = sscanf (p + 7, " %d %d %d %d %d",
1934 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1935 if (ret != 5) {
1936 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1938 lock ("trimset");
1939 state.trimmargins = trimmargins;
1940 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1941 state.trimanew = 1;
1942 state.trimfuzz = fuzz;
1944 unlock ("trimset");
1946 else if (!strncmp ("settrim", p, 7)) {
1947 fz_irect fuzz;
1948 int trimmargins;
1950 ret = sscanf (p + 7, " %d %d %d %d %d",
1951 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1952 if (ret != 5) {
1953 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1955 printd ("clear");
1956 lock ("settrim");
1957 state.trimmargins = trimmargins;
1958 state.needoutline = 1;
1959 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1960 state.trimanew = 1;
1961 state.trimfuzz = fuzz;
1963 state.pagedimcount = 0;
1964 free (state.pagedims);
1965 state.pagedims = NULL;
1966 initpdims (0);
1967 layout ();
1968 process_outline ();
1969 unlock ("settrim");
1970 printd ("continue %d", state.pagecount);
1972 else if (!strncmp ("sliceh", p, 6)) {
1973 int h;
1975 ret = sscanf (p + 6, " %d", &h);
1976 if (ret != 1) {
1977 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1979 if (h != state.sliceheight) {
1980 int i;
1982 state.sliceheight = h;
1983 for (i = 0; i < state.texcount; ++i) {
1984 state.texowners[i].w = -1;
1985 state.texowners[i].h = -1;
1986 state.texowners[i].slice = NULL;
1990 else if (!strncmp ("interrupt", p, 9)) {
1991 printd ("vmsg interrupted");
1993 else {
1994 errx (1, "unknown command %.*s", len, p);
1997 return 0;
2000 CAMLprim value ml_realloctexts (value texcount_v)
2002 CAMLparam1 (texcount_v);
2003 int ok;
2005 if (trylock (__func__)) {
2006 ok = 0;
2007 goto done;
2009 realloctexts (Int_val (texcount_v));
2010 ok = 1;
2011 unlock (__func__);
2013 done:
2014 CAMLreturn (Val_bool (ok));
2017 static void recti (int x0, int y0, int x1, int y1)
2019 GLfloat *v = state.vertices;
2021 glVertexPointer (2, GL_FLOAT, 0, v);
2022 v[0] = x0; v[1] = y0;
2023 v[2] = x1; v[3] = y0;
2024 v[4] = x0; v[5] = y1;
2025 v[6] = x1; v[7] = y1;
2026 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2029 static void showsel (struct page *page, int ox, int oy)
2031 int seen = 0;
2032 fz_irect bbox;
2033 fz_rect rect;
2034 fz_stext_line *line;
2035 fz_page_block *pageb;
2036 fz_stext_block *block;
2037 struct mark first, last;
2038 unsigned char selcolor[] = {15,15,15,140};
2040 first = page->fmark;
2041 last = page->lmark;
2043 if (!first.span || !last.span) return;
2045 glEnable (GL_BLEND);
2046 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2047 glColor4ubv (selcolor);
2049 ox += state.pagedims[page->pdimno].bounds.x0;
2050 oy += state.pagedims[page->pdimno].bounds.y0;
2051 for (pageb = page->text->blocks;
2052 pageb < page->text->blocks + page->text->len;
2053 ++pageb) {
2054 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2055 block = pageb->u.text;
2057 for (line = block->lines;
2058 line < block->lines + block->len;
2059 ++line) {
2060 fz_stext_span *span;
2061 rect = fz_empty_rect;
2063 for (span = line->first_span; span; span = span->next) {
2064 int i, j, k;
2065 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2067 j = 0;
2068 k = span->len - 1;
2070 if (span == page->fmark.span && span == page->lmark.span) {
2071 seen = 1;
2072 j = fz_mini (first.i, last.i);
2073 k = fz_maxi (first.i, last.i);
2075 else {
2076 if (span == first.span) {
2077 seen = 1;
2078 j = first.i;
2080 else if (span == last.span) {
2081 seen = 1;
2082 k = last.i;
2086 if (seen) {
2087 for (i = j; i <= k; ++i) {
2088 fz_rect bbox1;
2089 fz_union_rect (&rect,
2090 fz_stext_char_bbox (state.ctx, &bbox1,
2091 span, i));
2093 fz_round_rect (&bbox, &rect);
2094 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2095 bbox.x0,
2096 bbox.y0,
2097 bbox.x1,
2098 bbox.y1,
2099 oy, ox);
2101 recti (bbox.x0 + ox, bbox.y0 + oy,
2102 bbox.x1 + ox, bbox.y1 + oy);
2103 if (span == last.span) {
2104 goto done;
2106 rect = fz_empty_rect;
2111 done:
2112 glDisable (GL_BLEND);
2115 #include "glfont.c"
2117 static void stipplerect (fz_matrix *m,
2118 fz_point *p1,
2119 fz_point *p2,
2120 fz_point *p3,
2121 fz_point *p4,
2122 GLfloat *texcoords,
2123 GLfloat *vertices)
2125 fz_transform_point (p1, m);
2126 fz_transform_point (p2, m);
2127 fz_transform_point (p3, m);
2128 fz_transform_point (p4, m);
2130 float w, h, s, t;
2132 w = p2->x - p1->x;
2133 h = p2->y - p1->y;
2134 t = sqrtf (w*w + h*h) * .25f;
2136 w = p3->x - p2->x;
2137 h = p3->y - p2->y;
2138 s = sqrtf (w*w + h*h) * .25f;
2140 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2141 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2143 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2144 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2146 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2147 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2149 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2150 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2152 glDrawArrays (GL_LINES, 0, 8);
2155 static void solidrect (fz_matrix *m,
2156 fz_point *p1,
2157 fz_point *p2,
2158 fz_point *p3,
2159 fz_point *p4,
2160 GLfloat *vertices)
2162 fz_transform_point (p1, m);
2163 fz_transform_point (p2, m);
2164 fz_transform_point (p3, m);
2165 fz_transform_point (p4, m);
2166 vertices[0] = p1->x; vertices[1] = p1->y;
2167 vertices[2] = p2->x; vertices[3] = p2->y;
2169 vertices[4] = p3->x; vertices[5] = p3->y;
2170 vertices[6] = p4->x; vertices[7] = p4->y;
2171 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2174 static void highlightlinks (struct page *page, int xoff, int yoff)
2176 int i;
2177 fz_matrix ctm, tm, pm;
2178 fz_link *link, *links;
2179 GLfloat *texcoords = state.texcoords;
2180 GLfloat *vertices = state.vertices;
2182 links = fz_load_links (state.ctx, page->fzpage);
2184 glEnable (GL_TEXTURE_1D);
2185 glEnable (GL_BLEND);
2186 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2187 glBindTexture (GL_TEXTURE_1D, state.stid);
2189 xoff -= state.pagedims[page->pdimno].bounds.x0;
2190 yoff -= state.pagedims[page->pdimno].bounds.y0;
2191 fz_translate (&tm, xoff, yoff);
2192 pm = pagectm (page);
2193 fz_concat (&ctm, &pm, &tm);
2195 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2196 glVertexPointer (2, GL_FLOAT, 0, vertices);
2198 for (link = links; link; link = link->next) {
2199 fz_point p1, p2, p3, p4;
2201 p1.x = link->rect.x0;
2202 p1.y = link->rect.y0;
2204 p2.x = link->rect.x1;
2205 p2.y = link->rect.y0;
2207 p3.x = link->rect.x1;
2208 p3.y = link->rect.y1;
2210 p4.x = link->rect.x0;
2211 p4.y = link->rect.y1;
2213 switch (link->dest.kind) {
2214 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2215 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2216 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2217 default: glColor3ub (0, 0, 0); break;
2219 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2222 for (i = 0; i < page->annotcount; ++i) {
2223 fz_point p1, p2, p3, p4;
2224 struct annot *annot = &page->annots[i];
2226 p1.x = annot->bbox.x0;
2227 p1.y = annot->bbox.y0;
2229 p2.x = annot->bbox.x1;
2230 p2.y = annot->bbox.y0;
2232 p3.x = annot->bbox.x1;
2233 p3.y = annot->bbox.y1;
2235 p4.x = annot->bbox.x0;
2236 p4.y = annot->bbox.y1;
2238 glColor3ub (0, 0, 128);
2239 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2242 glDisable (GL_BLEND);
2243 glDisable (GL_TEXTURE_1D);
2246 static int compareslinks (const void *l, const void *r)
2248 struct slink const *ls = l;
2249 struct slink const *rs = r;
2250 if (ls->bbox.y0 == rs->bbox.y0) {
2251 return rs->bbox.x0 - rs->bbox.x0;
2253 return ls->bbox.y0 - rs->bbox.y0;
2256 static void droptext (struct page *page)
2258 if (page->text) {
2259 fz_drop_stext_page (state.ctx, page->text);
2260 page->fmark.i = -1;
2261 page->lmark.i = -1;
2262 page->fmark.span = NULL;
2263 page->lmark.span = NULL;
2264 page->text = NULL;
2266 if (page->sheet) {
2267 fz_drop_stext_sheet (state.ctx, page->sheet);
2268 page->sheet = NULL;
2272 static void dropannots (struct page *page)
2274 if (page->annots) {
2275 free (page->annots);
2276 page->annots = NULL;
2277 page->annotcount = 0;
2281 static void ensureannots (struct page *page)
2283 int i, count = 0;
2284 size_t annotsize = sizeof (*page->annots);
2285 fz_annot *annot;
2287 if (state.gen != page->agen) {
2288 dropannots (page);
2289 page->agen = state.gen;
2291 if (page->annots) return;
2293 for (annot = fz_first_annot (state.ctx, page->fzpage);
2294 annot;
2295 annot = fz_next_annot (state.ctx, annot)) {
2296 count++;
2299 if (count > 0) {
2300 page->annotcount = count;
2301 page->annots = calloc (count, annotsize);
2302 if (!page->annots) {
2303 err (1, "calloc annots %d", count);
2306 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2307 annot;
2308 annot = fz_next_annot (state.ctx, annot), i++) {
2309 fz_rect rect;
2311 fz_bound_annot (state.ctx, annot, &rect);
2312 page->annots[i].annot = annot;
2313 fz_round_rect (&page->annots[i].bbox, &rect);
2318 static void dropslinks (struct page *page)
2320 if (page->slinks) {
2321 free (page->slinks);
2322 page->slinks = NULL;
2323 page->slinkcount = 0;
2327 static void ensureslinks (struct page *page)
2329 fz_matrix ctm;
2330 int i, count;
2331 size_t slinksize = sizeof (*page->slinks);
2332 fz_link *link, *links;
2334 ensureannots (page);
2335 if (state.gen != page->sgen) {
2336 dropslinks (page);
2337 page->sgen = state.gen;
2339 if (page->slinks) return;
2341 links = fz_load_links (state.ctx, page->fzpage);
2342 ctm = pagectm (page);
2344 count = page->annotcount;
2345 for (link = links; link; link = link->next) {
2346 count++;
2348 if (count > 0) {
2349 int j;
2351 page->slinkcount = count;
2352 page->slinks = calloc (count, slinksize);
2353 if (!page->slinks) {
2354 err (1, "calloc slinks %d", count);
2357 for (i = 0, link = links; link; ++i, link = link->next) {
2358 fz_rect rect;
2360 rect = link->rect;
2361 fz_transform_rect (&rect, &ctm);
2362 page->slinks[i].tag = SLINK;
2363 page->slinks[i].u.link = link;
2364 fz_round_rect (&page->slinks[i].bbox, &rect);
2366 for (j = 0; j < page->annotcount; ++j, ++i) {
2367 fz_rect rect;
2368 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2369 fz_transform_rect (&rect, &ctm);
2370 fz_round_rect (&page->slinks[i].bbox, &rect);
2372 page->slinks[i].tag = SANNOT;
2373 page->slinks[i].u.annot = page->annots[j].annot;
2375 qsort (page->slinks, count, slinksize, compareslinks);
2379 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2380 static void fmt_linkn (char *s, unsigned int u)
2382 unsigned int len; unsigned int q;
2383 unsigned int zma = 'z' - 'a' + 1;
2384 len = 1; q = u;
2385 while (q > zma - 1) { ++len; q /= zma; }
2386 if (s) {
2387 s += len;
2388 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2389 /* handles u == 0 */
2391 s[len] = 0;
2394 static void highlightslinks (struct page *page, int xoff, int yoff,
2395 int noff, char *targ, int tlen, int hfsize)
2397 int i;
2398 char buf[40];
2399 struct slink *slink;
2400 double x0, y0, x1, y1, w;
2402 ensureslinks (page);
2403 glColor3ub (0xc3, 0xb0, 0x91);
2404 for (i = 0; i < page->slinkcount; ++i) {
2405 fmt_linkn (buf, i + noff);
2406 if (!tlen || !strncmp (targ, buf, tlen)) {
2407 slink = &page->slinks[i];
2409 x0 = slink->bbox.x0 + xoff - 5;
2410 y1 = slink->bbox.y0 + yoff - 5;
2411 y0 = y1 + 10 + hfsize;
2412 w = measure_string (state.face, hfsize, buf);
2413 x1 = x0 + w + 10;
2414 recti (x0, y0, x1, y1);
2418 glEnable (GL_BLEND);
2419 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2420 glEnable (GL_TEXTURE_2D);
2421 glColor3ub (0, 0, 0);
2422 for (i = 0; i < page->slinkcount; ++i) {
2423 fmt_linkn (buf, i + noff);
2424 if (!tlen || !strncmp (targ, buf, tlen)) {
2425 slink = &page->slinks[i];
2427 x0 = slink->bbox.x0 + xoff;
2428 y0 = slink->bbox.y0 + yoff + hfsize;
2429 draw_string (state.face, hfsize, x0, y0, buf);
2432 glDisable (GL_TEXTURE_2D);
2433 glDisable (GL_BLEND);
2436 static void uploadslice (struct tile *tile, struct slice *slice)
2438 int offset;
2439 struct slice *slice1;
2440 unsigned char *texdata;
2442 offset = 0;
2443 for (slice1 = tile->slices; slice != slice1; slice1++) {
2444 offset += slice1->h * tile->w * tile->pixmap->n;
2446 if (slice->texindex != -1 && slice->texindex < state.texcount
2447 && state.texowners[slice->texindex].slice == slice) {
2448 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2450 else {
2451 int subimage = 0;
2452 int texindex = state.texindex++ % state.texcount;
2454 if (state.texowners[texindex].w == tile->w) {
2455 if (state.texowners[texindex].h >= slice->h) {
2456 subimage = 1;
2458 else {
2459 state.texowners[texindex].h = slice->h;
2462 else {
2463 state.texowners[texindex].h = slice->h;
2466 state.texowners[texindex].w = tile->w;
2467 state.texowners[texindex].slice = slice;
2468 slice->texindex = texindex;
2470 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2471 #if TEXT_TYPE == GL_TEXTURE_2D
2472 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2473 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2474 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2475 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2476 #endif
2477 if (tile->pbo) {
2478 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2479 texdata = 0;
2481 else {
2482 texdata = tile->pixmap->samples;
2484 if (subimage) {
2485 glTexSubImage2D (TEXT_TYPE,
2489 tile->w,
2490 slice->h,
2491 state.texform,
2492 state.texty,
2493 texdata+offset
2496 else {
2497 glTexImage2D (TEXT_TYPE,
2499 state.texiform,
2500 tile->w,
2501 slice->h,
2503 state.texform,
2504 state.texty,
2505 texdata+offset
2508 if (tile->pbo) {
2509 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2514 CAMLprim value ml_begintiles (value unit_v)
2516 CAMLparam1 (unit_v);
2517 glEnable (TEXT_TYPE);
2518 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2519 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2520 CAMLreturn (unit_v);
2523 CAMLprim value ml_endtiles (value unit_v)
2525 CAMLparam1 (unit_v);
2526 glDisable (TEXT_TYPE);
2527 CAMLreturn (unit_v);
2530 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2532 CAMLparam2 (args_v, ptr_v);
2533 int dispx = Int_val (Field (args_v, 0));
2534 int dispy = Int_val (Field (args_v, 1));
2535 int dispw = Int_val (Field (args_v, 2));
2536 int disph = Int_val (Field (args_v, 3));
2537 int tilex = Int_val (Field (args_v, 4));
2538 int tiley = Int_val (Field (args_v, 5));
2539 char *s = String_val (ptr_v);
2540 struct tile *tile = parse_pointer (__func__, s);
2541 int slicey, firstslice;
2542 struct slice *slice;
2543 GLfloat *texcoords = state.texcoords;
2544 GLfloat *vertices = state.vertices;
2546 firstslice = tiley / tile->sliceheight;
2547 slice = &tile->slices[firstslice];
2548 slicey = tiley % tile->sliceheight;
2550 while (disph > 0) {
2551 int dh;
2553 dh = slice->h - slicey;
2554 dh = fz_mini (disph, dh);
2555 uploadslice (tile, slice);
2557 texcoords[0] = tilex; texcoords[1] = slicey;
2558 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2559 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2560 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2562 vertices[0] = dispx; vertices[1] = dispy;
2563 vertices[2] = dispx+dispw; vertices[3] = dispy;
2564 vertices[4] = dispx; vertices[5] = dispy+dh;
2565 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2567 #if TEXT_TYPE == GL_TEXTURE_2D
2568 for (int i = 0; i < 8; ++i) {
2569 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2571 #endif
2573 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2574 dispy += dh;
2575 disph -= dh;
2576 slice++;
2577 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2578 slicey = 0;
2580 CAMLreturn (Val_unit);
2583 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2585 fz_matrix ctm, tm, pm;
2586 fz_point p1, p2, p3, p4;
2587 GLfloat *vertices = state.vertices;
2588 double *v = (double *) rects_v;
2590 xoff -= state.pagedims[page->pdimno].bounds.x0;
2591 yoff -= state.pagedims[page->pdimno].bounds.y0;
2592 fz_translate (&tm, xoff, yoff);
2593 pm = pagectm (page);
2594 fz_concat (&ctm, &pm, &tm);
2596 glEnable (GL_BLEND);
2597 glVertexPointer (2, GL_FLOAT, 0, vertices);
2599 glColor4dv (v);
2600 p1.x = v[4];
2601 p1.y = v[5];
2603 p2.x = v[6];
2604 p2.y = v[5];
2606 p3.x = v[6];
2607 p3.y = v[7];
2609 p4.x = v[4];
2610 p4.y = v[7];
2611 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2612 glDisable (GL_BLEND);
2615 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2616 value xoff_v, value yoff_v,
2617 value li_v)
2619 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2620 int xoff = Int_val (xoff_v);
2621 int yoff = Int_val (yoff_v);
2622 int noff = Int_val (Field (li_v, 0));
2623 char *targ = String_val (Field (li_v, 1));
2624 int tlen = caml_string_length (Field (li_v, 1));
2625 int hfsize = Int_val (Field (li_v, 2));
2626 char *s = String_val (ptr_v);
2627 int hlmask = Int_val (hlinks_v);
2628 struct page *page = parse_pointer (__func__, s);
2630 if (!page->fzpage) {
2631 /* deal with loadpage failed pages */
2632 goto done;
2635 if (trylock (__func__)) {
2636 noff = 0;
2637 goto done;
2640 ensureannots (page);
2641 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2642 if (hlmask & 2) {
2643 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2644 noff = page->slinkcount;
2646 if (page->tgen == state.gen) {
2647 showsel (page, xoff, yoff);
2649 unlock (__func__);
2651 done:
2652 CAMLreturn (Val_int (noff));
2655 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2656 value rects_v)
2658 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2659 int xoff = Int_val (xoff_v);
2660 int yoff = Int_val (yoff_v);
2661 char *s = String_val (ptr_v);
2662 struct page *page = parse_pointer (__func__, s);
2664 drawprect (page, xoff, yoff, rects_v);
2665 CAMLreturn (Val_unit);
2668 static struct annot *getannot (struct page *page, int x, int y)
2670 int i;
2671 fz_point p;
2672 fz_matrix ctm;
2673 const fz_matrix *tctm;
2674 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2676 if (!page->annots) return NULL;
2678 if (pdf) {
2679 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2680 tctm = &state.pagedims[page->pdimno].tctm;
2682 else {
2683 tctm = &fz_identity;
2686 p.x = x;
2687 p.y = y;
2689 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2690 fz_invert_matrix (&ctm, &ctm);
2691 fz_transform_point (&p, &ctm);
2693 if (pdf) {
2694 for (i = 0; i < page->annotcount; ++i) {
2695 struct annot *a = &page->annots[i];
2696 fz_rect rect;
2698 fz_bound_annot (state.ctx, a->annot, &rect);
2699 if (p.x >= rect.x0 && p.x <= rect.x1) {
2700 if (p.y >= rect.y0 && p.y <= rect.y1)
2701 return a;
2705 return NULL;
2708 static fz_link *getlink (struct page *page, int x, int y)
2710 fz_point p;
2711 fz_matrix ctm;
2712 fz_link *link, *links;
2714 links = fz_load_links (state.ctx, page->fzpage);
2716 p.x = x;
2717 p.y = y;
2719 ctm = pagectm (page);
2720 fz_invert_matrix (&ctm, &ctm);
2721 fz_transform_point (&p, &ctm);
2723 for (link = links; link; link = link->next) {
2724 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2725 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2726 return link;
2730 return NULL;
2733 static void ensuretext (struct page *page)
2735 if (state.gen != page->tgen) {
2736 droptext (page);
2737 page->tgen = state.gen;
2739 if (!page->text) {
2740 fz_matrix ctm;
2741 fz_device *tdev;
2743 page->text = fz_new_stext_page (state.ctx);
2744 page->sheet = fz_new_stext_sheet (state.ctx);
2745 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2746 ctm = pagectm (page);
2747 fz_run_display_list (state.ctx, page->dlist,
2748 tdev, &ctm, &fz_infinite_rect, NULL);
2749 qsort (page->text->blocks, page->text->len,
2750 sizeof (*page->text->blocks), compareblocks);
2751 fz_close_device (state.ctx, tdev);
2752 fz_drop_device (state.ctx, tdev);
2756 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2758 CAMLparam2 (start_page_v, dir_v);
2759 CAMLlocal1 (ret_v);
2760 int i, dir = Int_val (dir_v);
2761 int start_page = Int_val (start_page_v);
2762 int end_page = dir > 0 ? state.pagecount : -1;
2763 pdf_document *pdf;
2765 fz_var (end_page);
2766 ret_v = Val_int (0);
2767 lock (__func__);
2768 pdf = pdf_specifics (state.ctx, state.doc);
2769 for (i = start_page + dir; i != end_page; i += dir) {
2770 int found;
2772 fz_var (found);
2773 if (pdf) {
2774 pdf_page *page = NULL;
2776 fz_var (page);
2777 fz_try (state.ctx) {
2778 page = pdf_load_page (state.ctx, pdf, i);
2779 found = !!page->links || !!page->annots;
2781 fz_catch (state.ctx) {
2782 found = 0;
2784 if (page) {
2785 fz_drop_page (state.ctx, &page->super);
2788 else {
2789 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2790 found = !!fz_load_links (state.ctx, page);
2791 fz_drop_page (state.ctx, page);
2794 if (found) {
2795 ret_v = caml_alloc_small (1, 1);
2796 Field (ret_v, 0) = Val_int (i);
2797 goto unlock;
2800 unlock:
2801 unlock (__func__);
2802 CAMLreturn (ret_v);
2805 enum { dir_first, dir_last };
2806 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2808 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2810 CAMLparam2 (ptr_v, dir_v);
2811 CAMLlocal2 (ret_v, pos_v);
2812 struct page *page;
2813 int dirtag, i, slinkindex;
2814 struct slink *found = NULL ,*slink;
2815 char *s = String_val (ptr_v);
2817 page = parse_pointer (__func__, s);
2818 ret_v = Val_int (0);
2819 lock (__func__);
2820 ensureslinks (page);
2822 if (Is_block (dir_v)) {
2823 dirtag = Tag_val (dir_v);
2824 switch (dirtag) {
2825 case dir_first_visible:
2827 int x0, y0, dir, first_index, last_index;
2829 pos_v = Field (dir_v, 0);
2830 x0 = Int_val (Field (pos_v, 0));
2831 y0 = Int_val (Field (pos_v, 1));
2832 dir = Int_val (Field (pos_v, 2));
2834 if (dir >= 0) {
2835 dir = 1;
2836 first_index = 0;
2837 last_index = page->slinkcount;
2839 else {
2840 first_index = page->slinkcount - 1;
2841 last_index = -1;
2844 for (i = first_index; i != last_index; i += dir) {
2845 slink = &page->slinks[i];
2846 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2847 found = slink;
2848 break;
2852 break;
2854 case dir_left:
2855 slinkindex = Int_val (Field (dir_v, 0));
2856 found = &page->slinks[slinkindex];
2857 for (i = slinkindex - 1; i >= 0; --i) {
2858 slink = &page->slinks[i];
2859 if (slink->bbox.x0 < found->bbox.x0) {
2860 found = slink;
2861 break;
2864 break;
2866 case dir_right:
2867 slinkindex = Int_val (Field (dir_v, 0));
2868 found = &page->slinks[slinkindex];
2869 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2870 slink = &page->slinks[i];
2871 if (slink->bbox.x0 > found->bbox.x0) {
2872 found = slink;
2873 break;
2876 break;
2878 case dir_down:
2879 slinkindex = Int_val (Field (dir_v, 0));
2880 found = &page->slinks[slinkindex];
2881 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2882 slink = &page->slinks[i];
2883 if (slink->bbox.y0 >= found->bbox.y0) {
2884 found = slink;
2885 break;
2888 break;
2890 case dir_up:
2891 slinkindex = Int_val (Field (dir_v, 0));
2892 found = &page->slinks[slinkindex];
2893 for (i = slinkindex - 1; i >= 0; --i) {
2894 slink = &page->slinks[i];
2895 if (slink->bbox.y0 <= found->bbox.y0) {
2896 found = slink;
2897 break;
2900 break;
2903 else {
2904 dirtag = Int_val (dir_v);
2905 switch (dirtag) {
2906 case dir_first:
2907 found = page->slinks;
2908 break;
2910 case dir_last:
2911 if (page->slinks) {
2912 found = page->slinks + (page->slinkcount - 1);
2914 break;
2917 if (found) {
2918 ret_v = caml_alloc_small (2, 1);
2919 Field (ret_v, 0) = Val_int (found - page->slinks);
2922 unlock (__func__);
2923 CAMLreturn (ret_v);
2926 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2927 unamed, uremote, uremotedest, uannot };
2929 #define LINKTOVAL \
2931 int pageno; \
2933 switch (link->dest.kind) { \
2934 case FZ_LINK_GOTO: \
2936 fz_point p; \
2938 pageno = link->dest.ld.gotor.page; \
2939 p.x = 0; \
2940 p.y = 0; \
2942 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2943 p.y = link->dest.ld.gotor.lt.y; \
2944 fz_transform_point (&p, &pdim->lctm); \
2945 if (p.y < 0) p.y = 0; \
2947 tup_v = caml_alloc_tuple (2); \
2948 ret_v = caml_alloc_small (1, ugoto); \
2949 Field (tup_v, 0) = Val_int (pageno); \
2950 Field (tup_v, 1) = Val_int (p.y); \
2951 Field (ret_v, 0) = tup_v; \
2953 break; \
2955 case FZ_LINK_URI: \
2956 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2957 ret_v = caml_alloc_small (1, uuri); \
2958 Field (ret_v, 0) = str_v; \
2959 break; \
2961 case FZ_LINK_LAUNCH: \
2962 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2963 ret_v = caml_alloc_small (1, ulaunch); \
2964 Field (ret_v, 0) = str_v; \
2965 break; \
2967 case FZ_LINK_NAMED: \
2968 str_v = caml_copy_string (link->dest.ld.named.named); \
2969 ret_v = caml_alloc_small (1, unamed); \
2970 Field (ret_v, 0) = str_v; \
2971 break; \
2973 case FZ_LINK_GOTOR: \
2975 int rty; \
2977 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2978 pageno = link->dest.ld.gotor.page; \
2979 if (pageno == -1) { \
2980 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2981 rty = uremotedest; \
2983 else { \
2984 gr_v = Val_int (pageno); \
2985 rty = uremote; \
2987 tup_v = caml_alloc_tuple (2); \
2988 ret_v = caml_alloc_small (1, rty); \
2989 Field (tup_v, 0) = str_v; \
2990 Field (tup_v, 1) = gr_v; \
2991 Field (ret_v, 0) = tup_v; \
2993 break; \
2995 default: \
2997 char buf[80]; \
2999 snprintf (buf, sizeof (buf), \
3000 "unhandled link kind %d", link->dest.kind); \
3001 str_v = caml_copy_string (buf); \
3002 ret_v = caml_alloc_small (1, uunexpected); \
3003 Field (ret_v, 0) = str_v; \
3005 break; \
3009 CAMLprim value ml_getlink (value ptr_v, value n_v)
3011 CAMLparam2 (ptr_v, n_v);
3012 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3013 fz_link *link;
3014 struct page *page;
3015 struct pagedim *pdim;
3016 char *s = String_val (ptr_v);
3017 struct slink *slink;
3019 /* See ml_findlink for caveat */
3021 ret_v = Val_int (0);
3022 page = parse_pointer (__func__, s);
3023 ensureslinks (page);
3024 pdim = &state.pagedims[page->pdimno];
3025 slink = &page->slinks[Int_val (n_v)];
3026 if (slink->tag == SLINK) {
3027 link = slink->u.link;
3028 LINKTOVAL;
3030 else {
3031 ret_v = caml_alloc_small (1, uannot);
3032 tup_v = caml_alloc_tuple (2);
3033 Field (ret_v, 0) = tup_v;
3034 Field (tup_v, 0) = ptr_v;
3035 Field (tup_v, 1) = n_v;
3038 CAMLreturn (ret_v);
3041 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3043 CAMLparam2 (ptr_v, n_v);
3044 pdf_document *pdf;
3045 const char *contents = "";
3047 lock (__func__);
3048 pdf = pdf_specifics (state.ctx, state.doc);
3049 if (pdf) {
3050 char *s = String_val (ptr_v);
3051 struct page *page;
3052 struct slink *slink;
3054 page = parse_pointer (__func__, s);
3055 slink = &page->slinks[Int_val (n_v)];
3056 contents = pdf_annot_contents (state.ctx,
3057 (pdf_annot *) slink->u.annot);
3059 unlock (__func__);
3060 CAMLreturn (caml_copy_string (contents));
3063 CAMLprim value ml_getlinkcount (value ptr_v)
3065 CAMLparam1 (ptr_v);
3066 struct page *page;
3067 char *s = String_val (ptr_v);
3069 page = parse_pointer (__func__, s);
3070 CAMLreturn (Val_int (page->slinkcount));
3073 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3075 CAMLparam2 (ptr_v, n_v);
3076 CAMLlocal1 (ret_v);
3077 struct page *page;
3078 struct slink *slink;
3079 char *s = String_val (ptr_v);
3081 page = parse_pointer (__func__, s);
3082 ret_v = caml_alloc_tuple (4);
3083 lock (__func__);
3084 ensureslinks (page);
3086 slink = &page->slinks[Int_val (n_v)];
3087 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3088 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3089 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3090 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3091 unlock (__func__);
3092 CAMLreturn (ret_v);
3095 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3097 CAMLparam3 (ptr_v, x_v, y_v);
3098 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3099 fz_link *link;
3100 struct annot *annot;
3101 struct page *page;
3102 char *ptr = String_val (ptr_v);
3103 int x = Int_val (x_v), y = Int_val (y_v);
3104 struct pagedim *pdim;
3106 ret_v = Val_int (0);
3107 if (trylock (__func__)) {
3108 goto done;
3111 page = parse_pointer (__func__, ptr);
3112 pdim = &state.pagedims[page->pdimno];
3113 x += pdim->bounds.x0;
3114 y += pdim->bounds.y0;
3117 annot = getannot (page, x, y);
3118 if (annot) {
3119 int i, n = -1;
3121 ensureslinks (page);
3122 for (i = 0; i < page->slinkcount; ++i) {
3123 if (page->slinks[i].tag == SANNOT
3124 && page->slinks[i].u.annot == annot->annot) {
3125 n = i;
3126 break;
3129 ret_v = caml_alloc_small (1, uannot);
3130 tup_v = caml_alloc_tuple (2);
3131 Field (ret_v, 0) = tup_v;
3132 Field (tup_v, 0) = ptr_v;
3133 Field (tup_v, 1) = Val_int (n);
3134 goto unlock;
3138 link = getlink (page, x, y);
3139 if (link) {
3140 LINKTOVAL;
3142 else {
3143 fz_rect *b;
3144 fz_page_block *pageb;
3145 fz_stext_block *block;
3147 ensuretext (page);
3148 for (pageb = page->text->blocks;
3149 pageb < page->text->blocks + page->text->len;
3150 ++pageb) {
3151 fz_stext_line *line;
3152 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3153 block = pageb->u.text;
3155 b = &block->bbox;
3156 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3157 continue;
3159 for (line = block->lines;
3160 line < block->lines + block->len;
3161 ++line) {
3162 fz_stext_span *span;
3164 b = &line->bbox;
3165 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3166 continue;
3168 for (span = line->first_span; span; span = span->next) {
3169 int charnum;
3171 b = &span->bbox;
3172 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3173 continue;
3175 for (charnum = 0; charnum < span->len; ++charnum) {
3176 fz_rect bbox;
3177 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3178 b = &bbox;
3180 if (x >= b->x0 && x <= b->x1
3181 && y >= b->y0 && y <= b->y1) {
3182 fz_stext_style *style = span->text->style;
3183 const char *n2 =
3184 style->font
3185 ? style->font->name
3186 : "Span has no font name"
3188 FT_FaceRec *face = style->font->ft_face;
3189 if (face && face->family_name) {
3190 char *s;
3191 char *n1 = face->family_name;
3192 size_t l1 = strlen (n1);
3193 size_t l2 = strlen (n2);
3195 if (l1 != l2 || memcmp (n1, n2, l1)) {
3196 s = malloc (l1 + l2 + 2);
3197 if (s) {
3198 memcpy (s, n2, l2);
3199 s[l2] = '=';
3200 memcpy (s + l2 + 1, n1, l1 + 1);
3201 str_v = caml_copy_string (s);
3202 free (s);
3206 if (str_v == Val_unit) {
3207 str_v = caml_copy_string (n2);
3209 ret_v = caml_alloc_small (1, utext);
3210 Field (ret_v, 0) = str_v;
3211 goto unlock;
3218 unlock:
3219 unlock (__func__);
3221 done:
3222 CAMLreturn (ret_v);
3225 enum { mark_page, mark_block, mark_line, mark_word };
3227 static int uninteresting (int c)
3229 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3230 || ispunct (c);
3233 CAMLprim value ml_clearmark (value ptr_v)
3235 CAMLparam1 (ptr_v);
3236 char *s = String_val (ptr_v);
3237 struct page *page;
3239 if (trylock (__func__)) {
3240 goto done;
3243 page = parse_pointer (__func__, s);
3244 page->fmark.span = NULL;
3245 page->lmark.span = NULL;
3246 page->fmark.i = 0;
3247 page->lmark.i = 0;
3249 unlock (__func__);
3250 done:
3251 CAMLreturn (Val_unit);
3254 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3256 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3257 CAMLlocal1 (ret_v);
3258 fz_rect *b;
3259 struct page *page;
3260 fz_stext_line *line;
3261 fz_page_block *pageb;
3262 fz_stext_block *block;
3263 struct pagedim *pdim;
3264 int mark = Int_val (mark_v);
3265 char *s = String_val (ptr_v);
3266 int x = Int_val (x_v), y = Int_val (y_v);
3268 ret_v = Val_bool (0);
3269 if (trylock (__func__)) {
3270 goto done;
3273 page = parse_pointer (__func__, s);
3274 pdim = &state.pagedims[page->pdimno];
3276 ensuretext (page);
3278 if (mark == mark_page) {
3279 int i;
3280 fz_page_block *pb1 = NULL, *pb2 = NULL;
3282 for (i = 0; i < page->text->len; ++i) {
3283 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3284 pb1 = &page->text->blocks[i];
3285 break;
3288 if (!pb1) goto unlock;
3290 for (i = page->text->len - 1; i >= 0; --i) {
3291 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3292 pb2 = &page->text->blocks[i];
3293 break;
3296 if (!pb2) goto unlock;
3298 block = pb1->u.text;
3300 page->fmark.i = 0;
3301 page->fmark.span = block->lines->first_span;
3303 block = pb2->u.text;
3304 line = &block->lines[block->len - 1];
3305 page->lmark.i = line->last_span->len - 1;
3306 page->lmark.span = line->last_span;
3307 ret_v = Val_bool (1);
3308 goto unlock;
3311 x += pdim->bounds.x0;
3312 y += pdim->bounds.y0;
3314 for (pageb = page->text->blocks;
3315 pageb < page->text->blocks + page->text->len;
3316 ++pageb) {
3317 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3318 block = pageb->u.text;
3320 b = &block->bbox;
3321 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3322 continue;
3324 if (mark == mark_block) {
3325 page->fmark.i = 0;
3326 page->fmark.span = block->lines->first_span;
3328 line = &block->lines[block->len - 1];
3329 page->lmark.i = line->last_span->len - 1;
3330 page->lmark.span = line->last_span;
3331 ret_v = Val_bool (1);
3332 goto unlock;
3335 for (line = block->lines;
3336 line < block->lines + block->len;
3337 ++line) {
3338 fz_stext_span *span;
3340 b = &line->bbox;
3341 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3342 continue;
3344 if (mark == mark_line) {
3345 page->fmark.i = 0;
3346 page->fmark.span = line->first_span;
3348 page->lmark.i = line->last_span->len - 1;
3349 page->lmark.span = line->last_span;
3350 ret_v = Val_bool (1);
3351 goto unlock;
3354 for (span = line->first_span; span; span = span->next) {
3355 int charnum;
3357 b = &span->bbox;
3358 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3359 continue;
3361 for (charnum = 0; charnum < span->len; ++charnum) {
3362 fz_rect bbox;
3363 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3364 b = &bbox;
3366 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3367 /* unicode ftw */
3368 int charnum2, charnum3 = -1, charnum4 = -1;
3370 if (uninteresting (span->text[charnum].c)) goto unlock;
3372 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3373 if (uninteresting (span->text[charnum2].c)) {
3374 charnum3 = charnum2 + 1;
3375 break;
3378 if (charnum3 == -1) charnum3 = 0;
3380 charnum4 = charnum;
3381 for (charnum2 = charnum + 1;
3382 charnum2 < span->len;
3383 ++charnum2) {
3384 if (uninteresting (span->text[charnum2].c)) break;
3385 charnum4 = charnum2;
3388 page->fmark.i = charnum3;
3389 page->fmark.span = span;
3391 page->lmark.i = charnum4;
3392 page->lmark.span = span;
3393 ret_v = Val_bool (1);
3394 goto unlock;
3400 unlock:
3401 if (!Bool_val (ret_v)) {
3402 page->fmark.span = NULL;
3403 page->lmark.span = NULL;
3404 page->fmark.i = 0;
3405 page->lmark.i = 0;
3407 unlock (__func__);
3409 done:
3410 CAMLreturn (ret_v);
3413 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3415 CAMLparam3 (ptr_v, x_v, y_v);
3416 CAMLlocal2 (ret_v, res_v);
3417 fz_rect *b = NULL;
3418 struct page *page;
3419 fz_page_block *pageb;
3420 struct pagedim *pdim;
3421 char *s = String_val (ptr_v);
3422 int x = Int_val (x_v), y = Int_val (y_v);
3424 ret_v = Val_int (0);
3425 if (trylock (__func__)) {
3426 goto done;
3429 page = parse_pointer (__func__, s);
3430 pdim = &state.pagedims[page->pdimno];
3431 x += pdim->bounds.x0;
3432 y += pdim->bounds.y0;
3434 ensuretext (page);
3436 for (pageb = page->text->blocks;
3437 pageb < page->text->blocks + page->text->len;
3438 ++pageb) {
3439 switch (pageb->type) {
3440 case FZ_PAGE_BLOCK_TEXT:
3441 b = &pageb->u.text->bbox;
3442 break;
3444 case FZ_PAGE_BLOCK_IMAGE:
3445 b = &pageb->u.image->bbox;
3446 break;
3448 default:
3449 continue;
3452 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3453 break;
3454 b = NULL;
3456 if (b) {
3457 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3458 ret_v = caml_alloc_small (1, 1);
3459 Store_double_field (res_v, 0, b->x0);
3460 Store_double_field (res_v, 1, b->x1);
3461 Store_double_field (res_v, 2, b->y0);
3462 Store_double_field (res_v, 3, b->y1);
3463 Field (ret_v, 0) = res_v;
3465 unlock (__func__);
3467 done:
3468 CAMLreturn (ret_v);
3471 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3473 CAMLparam2 (ptr_v, rect_v);
3474 fz_rect b;
3475 struct page *page;
3476 struct pagedim *pdim;
3477 char *s = String_val (ptr_v);
3478 int i, x0, x1, y0, y1, fi, li;
3479 fz_stext_line *line;
3480 fz_page_block *pageb;
3481 fz_stext_block *block;
3482 fz_stext_span *span, *fspan, *lspan;
3484 if (trylock (__func__)) {
3485 goto done;
3488 page = parse_pointer (__func__, s);
3489 ensuretext (page);
3491 pdim = &state.pagedims[page->pdimno];
3492 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3493 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3494 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3495 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3497 if (y0 > y1) {
3498 int t = y0;
3499 y0 = y1;
3500 y1 = t;
3501 x0 = x1;
3502 x1 = t;
3505 fi = page->fmark.i;
3506 fspan = page->fmark.span;
3508 li = page->lmark.i;
3509 lspan = page->lmark.span;
3511 for (pageb = page->text->blocks;
3512 pageb < page->text->blocks + page->text->len;
3513 ++pageb) {
3514 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3515 block = pageb->u.text;
3516 for (line = block->lines;
3517 line < block->lines + block->len;
3518 ++line) {
3520 for (span = line->first_span; span; span = span->next) {
3521 for (i = 0; i < span->len; ++i) {
3522 fz_stext_char_bbox (state.ctx, &b, span, i);
3524 if (x0 >= b.x0 && x0 <= b.x1
3525 && y0 >= b.y0 && y0 <= b.y1) {
3526 fspan = span;
3527 fi = i;
3529 if (x1 >= b.x0 && x1 <= b.x1
3530 && y1 >= b.y0 && y1 <= b.y1) {
3531 lspan = span;
3532 li = i;
3538 if (x1 < x0 && fspan == lspan) {
3539 i = fi;
3540 span = fspan;
3542 fi = li;
3543 fspan = lspan;
3545 li = i;
3546 lspan = span;
3549 page->fmark.i = fi;
3550 page->fmark.span = fspan;
3552 page->lmark.i = li;
3553 page->lmark.span = lspan;
3555 unlock (__func__);
3557 done:
3558 CAMLreturn (Val_unit);
3561 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3563 char buf[4];
3564 int i, len, ret;
3566 for (i = a; i <= b; ++i) {
3567 len = fz_runetochar (buf, span->text[i].c);
3568 ret = fwrite (buf, len, 1, f);
3570 if (ret != 1) {
3571 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3572 len, ret, strerror (errno));
3573 return -1;
3576 return 0;
3579 #ifdef __CYGWIN__
3580 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3582 caml_failwith ("ml_popen not implemented under Cygwin");
3584 #else
3585 CAMLprim value ml_spawn (value command_v, value fds_v)
3587 CAMLparam2 (command_v, fds_v);
3588 CAMLlocal2 (l_v, tup_v);
3589 int ret, ret1;
3590 pid_t pid;
3591 char *msg = NULL;
3592 value earg_v = Nothing;
3593 posix_spawnattr_t attr;
3594 posix_spawn_file_actions_t fa;
3595 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3597 argv[2] = String_val (command_v);
3599 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3600 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3603 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3604 msg = "posix_spawnattr_init";
3605 goto fail1;
3608 #ifdef POSIX_SPAWN_USEVFORK
3609 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3610 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3611 goto fail;
3613 #endif
3615 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3616 int fd1, fd2;
3618 tup_v = Field (l_v, 0);
3619 fd1 = Int_val (Field (tup_v, 0));
3620 fd2 = Int_val (Field (tup_v, 1));
3621 if (fd2 < 0) {
3622 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3623 msg = "posix_spawn_file_actions_addclose";
3624 earg_v = tup_v;
3625 goto fail;
3628 else {
3629 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3630 msg = "posix_spawn_file_actions_adddup2";
3631 earg_v = tup_v;
3632 goto fail;
3637 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3638 msg = "posix_spawn";
3639 goto fail;
3642 fail:
3643 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3644 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3647 fail1:
3648 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3649 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3650 strerror (ret1));
3653 if (msg)
3654 unix_error (ret, msg, earg_v);
3656 CAMLreturn (Val_int (pid));
3658 #endif
3660 CAMLprim value ml_hassel (value ptr_v)
3662 CAMLparam1 (ptr_v);
3663 CAMLlocal1 (ret_v);
3664 struct page *page;
3665 char *s = String_val (ptr_v);
3667 ret_v = Val_bool (0);
3668 if (trylock (__func__)) {
3669 goto done;
3672 page = parse_pointer (__func__, s);
3673 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3674 unlock (__func__);
3675 done:
3676 CAMLreturn (ret_v);
3679 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3681 CAMLparam2 (fd_v, ptr_v);
3682 FILE *f;
3683 int seen = 0;
3684 struct page *page;
3685 fz_stext_line *line;
3686 fz_page_block *pageb;
3687 fz_stext_block *block;
3688 int fd = Int_val (fd_v);
3689 char *s = String_val (ptr_v);
3691 if (trylock (__func__)) {
3692 goto done;
3695 page = parse_pointer (__func__, s);
3697 if (!page->fmark.span || !page->lmark.span) {
3698 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3699 goto unlock;
3702 f = fdopen (fd, "w");
3703 if (!f) {
3704 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3705 fd, strerror (errno));
3706 f = stdout;
3709 for (pageb = page->text->blocks;
3710 pageb < page->text->blocks + page->text->len;
3711 ++pageb) {
3712 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3713 block = pageb->u.text;
3714 for (line = block->lines;
3715 line < block->lines + block->len;
3716 ++line) {
3717 fz_stext_span *span;
3719 for (span = line->first_span; span; span = span->next) {
3720 int a, b;
3722 seen |= span == page->fmark.span || span == page->lmark.span;
3723 a = span == page->fmark.span ? page->fmark.i : 0;
3724 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3726 if (seen) {
3727 if (pipespan (f, span, a, b)) {
3728 goto close;
3730 if (span == page->lmark.span) {
3731 goto close;
3733 if (span == line->last_span) {
3734 if (putc ('\n', f) == EOF) {
3735 fprintf (stderr,
3736 "failed break line on sel pipe: %s\n",
3737 strerror (errno));
3738 goto close;
3745 close:
3746 if (f != stdout) {
3747 int ret = fclose (f);
3748 fd = -1;
3749 if (ret == -1) {
3750 if (errno != ECHILD) {
3751 fprintf (stderr, "failed to close sel pipe: %s\n",
3752 strerror (errno));
3756 unlock:
3757 unlock (__func__);
3759 done:
3760 if (fd >= 0) {
3761 if (close (fd)) {
3762 fprintf (stderr, "failed to close sel pipe: %s\n",
3763 strerror (errno));
3766 CAMLreturn (Val_unit);
3769 CAMLprim value ml_getpdimrect (value pagedimno_v)
3771 CAMLparam1 (pagedimno_v);
3772 CAMLlocal1 (ret_v);
3773 int pagedimno = Int_val (pagedimno_v);
3774 fz_rect box;
3776 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3777 if (trylock (__func__)) {
3778 box = fz_empty_rect;
3780 else {
3781 box = state.pagedims[pagedimno].mediabox;
3782 unlock (__func__);
3785 Store_double_field (ret_v, 0, box.x0);
3786 Store_double_field (ret_v, 1, box.x1);
3787 Store_double_field (ret_v, 2, box.y0);
3788 Store_double_field (ret_v, 3, box.y1);
3790 CAMLreturn (ret_v);
3793 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3794 value dw_v, value cols_v)
3796 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3797 CAMLlocal1 (ret_v);
3798 int i;
3799 double zoom = -1.;
3800 double maxh = 0.0;
3801 struct pagedim *p;
3802 double winw = Int_val (winw_v);
3803 double winh = Int_val (winh_v);
3804 double dw = Int_val (dw_v);
3805 double cols = Int_val (cols_v);
3806 double pw = 1.0, ph = 1.0;
3808 if (trylock (__func__)) {
3809 goto done;
3812 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3813 double w = p->pagebox.x1 / cols;
3814 double h = p->pagebox.y1;
3815 if (h > maxh) {
3816 maxh = h;
3817 ph = h;
3818 if (state.fitmodel != FitProportional) pw = w;
3820 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3823 zoom = (((winh / ph) * pw) + dw) / winw;
3824 unlock (__func__);
3825 done:
3826 ret_v = caml_copy_double (zoom);
3827 CAMLreturn (ret_v);
3830 CAMLprim value ml_getmaxw (value unit_v)
3832 CAMLparam1 (unit_v);
3833 CAMLlocal1 (ret_v);
3834 int i;
3835 double maxw = -1.;
3836 struct pagedim *p;
3838 if (trylock (__func__)) {
3839 goto done;
3842 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3843 double w = p->pagebox.x1;
3844 maxw = fz_max (maxw, w);
3847 unlock (__func__);
3848 done:
3849 ret_v = caml_copy_double (maxw);
3850 CAMLreturn (ret_v);
3853 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3855 CAMLparam4 (pt_v, x_v, y_v, string_v);
3856 CAMLlocal1 (ret_v);
3857 int pt = Int_val(pt_v);
3858 int x = Int_val (x_v);
3859 int y = Int_val (y_v);
3860 double w;
3862 w = draw_string (state.face, pt, x, y, String_val (string_v));
3863 ret_v = caml_copy_double (w);
3864 CAMLreturn (ret_v);
3867 CAMLprim value ml_measure_string (value pt_v, value string_v)
3869 CAMLparam2 (pt_v, string_v);
3870 CAMLlocal1 (ret_v);
3871 int pt = Int_val (pt_v);
3872 double w;
3874 w = measure_string (state.face, pt, String_val (string_v));
3875 ret_v = caml_copy_double (w);
3876 CAMLreturn (ret_v);
3879 CAMLprim value ml_getpagebox (value opaque_v)
3881 CAMLparam1 (opaque_v);
3882 CAMLlocal1 (ret_v);
3883 fz_rect rect;
3884 fz_irect bbox;
3885 fz_matrix ctm;
3886 fz_device *dev;
3887 char *s = String_val (opaque_v);
3888 struct page *page = parse_pointer (__func__, s);
3890 ret_v = caml_alloc_tuple (4);
3891 dev = fz_new_bbox_device (state.ctx, &rect);
3892 dev->hints |= FZ_IGNORE_SHADE;
3894 ctm = pagectm (page);
3895 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3897 fz_close_device (state.ctx, dev);
3898 fz_drop_device (state.ctx, dev);
3899 fz_round_rect (&bbox, &rect);
3900 Field (ret_v, 0) = Val_int (bbox.x0);
3901 Field (ret_v, 1) = Val_int (bbox.y0);
3902 Field (ret_v, 2) = Val_int (bbox.x1);
3903 Field (ret_v, 3) = Val_int (bbox.y1);
3905 CAMLreturn (ret_v);
3908 CAMLprim value ml_setaalevel (value level_v)
3910 CAMLparam1 (level_v);
3912 state.aalevel = Int_val (level_v);
3913 CAMLreturn (Val_unit);
3916 #pragma GCC diagnostic push
3917 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3918 #include <X11/Xlib.h>
3919 #include <X11/cursorfont.h>
3920 #pragma GCC diagnostic pop
3922 #ifdef USE_EGL
3923 #include <EGL/egl.h>
3924 #else
3925 #include <GL/glx.h>
3926 #endif
3928 static const int shapes[] = {
3929 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3932 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3934 static struct {
3935 Window wid;
3936 Display *dpy;
3937 #ifdef USE_EGL
3938 EGLContext ctx;
3939 EGLConfig conf;
3940 EGLSurface win;
3941 EGLDisplay *edpy;
3942 #else
3943 GLXContext ctx;
3944 #endif
3945 XVisualInfo *visual;
3946 Cursor curs[CURS_COUNT];
3947 } glx;
3949 #ifdef VISAVIS
3950 static VisualID initvisual (void)
3952 /* On this system with: `Haswell-ULT Integrated Graphics
3953 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3954 using glX chosen visual and auto scrolling some document in
3955 fullscreen the power/energy-gpu is more than 1 joule bigger
3956 than when using hand picked visual that stands alone in glxinfo
3957 output: it's dead last in the list and it's the only one with
3958 `visual dep' (sic) of 32
3960 No clue what's going on here...
3962 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3964 XVisualInfo info;
3965 int ret = 1;
3967 info.depth = 32;
3968 info.class = TrueColor;
3969 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3970 &info, &ret);
3971 if (!ret || !glx.visual) {
3972 XCloseDisplay (glx.dpy);
3973 caml_failwith ("XGetVisualInfo");
3975 return glx.visual->visualid;
3977 #endif
3979 static void initcurs (void)
3981 for (size_t n = 0; n < CURS_COUNT; ++n) {
3982 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3986 CAMLprim void ml_setbgcol (value color_v)
3988 CAMLparam1 (color_v);
3989 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3990 CAMLreturn0;
3993 #ifdef USE_EGL
3994 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3996 CAMLparam3 (display_v, wid_v, screen_v);
3997 int major, minor;
3998 int num_conf;
3999 EGLint visid;
4000 EGLint attribs[] = {
4001 #ifdef VISAVIS
4002 EGL_NATIVE_VISUAL_ID, 0,
4003 #else
4004 EGL_DEPTH_SIZE, 24,
4005 #endif
4006 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
4007 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
4008 EGL_NONE
4010 EGLConfig conf;
4012 glx.dpy = XOpenDisplay (String_val (display_v));
4013 if (!glx.dpy) {
4014 caml_failwith ("XOpenDisplay");
4017 eglBindAPI (EGL_OPENGL_API);
4019 glx.edpy = eglGetDisplay (glx.dpy);
4020 if (glx.edpy == EGL_NO_DISPLAY) {
4021 caml_failwith ("eglGetDisplay");
4024 if (!eglInitialize (glx.edpy, &major, &minor)) {
4025 caml_failwith ("eglInitialize");
4028 #ifdef VISAVIS
4029 attribs[1] = visid = initvisual ();
4030 #endif
4032 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4033 !num_conf) {
4034 caml_failwith ("eglChooseConfig");
4037 glx.conf = conf;
4038 #ifndef VISAVIS
4039 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4040 EGL_NATIVE_VISUAL_ID, &visid)) {
4041 caml_failwith ("eglGetConfigAttrib");
4043 #endif
4044 initcurs ();
4046 glx.wid = Int_val (wid_v);
4047 CAMLreturn (Val_int (visid));
4050 CAMLprim value ml_glxcompleteinit (value unit_v)
4052 CAMLparam1 (unit_v);
4054 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4055 if (!glx.ctx) {
4056 caml_failwith ("eglCreateContext");
4059 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4060 glx.wid, NULL);
4061 if (glx.win == EGL_NO_SURFACE) {
4062 caml_failwith ("eglCreateWindowSurface");
4065 XFree (glx.visual);
4066 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4067 glx.ctx = NULL;
4068 caml_failwith ("eglMakeCurrent");
4070 CAMLreturn (Val_unit);
4072 #else
4073 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4075 CAMLparam3 (display_v, wid_v, screen_v);
4077 glx.dpy = XOpenDisplay (String_val (display_v));
4078 if (!glx.dpy) {
4079 caml_failwith ("XOpenDisplay");
4082 #ifdef VISAVIS
4083 initvisual ();
4084 #else
4085 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4086 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4087 if (!glx.visual) {
4088 XCloseDisplay (glx.dpy);
4089 caml_failwith ("glXChooseVisual");
4091 #endif
4092 initcurs ();
4094 glx.wid = Int_val (wid_v);
4095 CAMLreturn (Val_int (glx.visual->visualid));
4098 CAMLprim value ml_glxcompleteinit (value unit_v)
4100 CAMLparam1 (unit_v);
4102 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4103 if (!glx.ctx) {
4104 caml_failwith ("glXCreateContext");
4107 XFree (glx.visual);
4108 glx.visual = NULL;
4110 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4111 glXDestroyContext (glx.dpy, glx.ctx);
4112 glx.ctx = NULL;
4113 caml_failwith ("glXMakeCurrent");
4115 CAMLreturn (Val_unit);
4117 #endif
4119 CAMLprim value ml_setcursor (value cursor_v)
4121 CAMLparam1 (cursor_v);
4122 size_t cursn = Int_val (cursor_v);
4124 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4125 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4126 XFlush (glx.dpy);
4127 CAMLreturn (Val_unit);
4130 CAMLprim value ml_swapb (value unit_v)
4132 CAMLparam1 (unit_v);
4133 #ifdef USE_EGL
4134 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4135 caml_failwith ("eglSwapBuffers");
4137 #else
4138 glXSwapBuffers (glx.dpy, glx.wid);
4139 #endif
4140 CAMLreturn (Val_unit);
4143 #include "keysym2ucs.c"
4145 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4147 CAMLparam1 (keysym_v);
4148 CAMLlocal1 (str_v);
4149 KeySym keysym = Int_val (keysym_v);
4150 Rune rune;
4151 int len;
4152 char buf[5];
4154 rune = keysym2ucs (keysym);
4155 len = fz_runetochar (buf, rune);
4156 buf[len] = 0;
4157 str_v = caml_copy_string (buf);
4158 CAMLreturn (str_v);
4161 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4163 CAMLprim value ml_platform (value unit_v)
4165 CAMLparam1 (unit_v);
4166 CAMLlocal2 (tup_v, arr_v);
4167 int platid = piunknown;
4168 struct utsname buf;
4170 #if defined __linux__
4171 platid = pilinux;
4172 #elif defined __CYGWIN__
4173 platid = picygwin;
4174 #elif defined __DragonFly__ || defined __FreeBSD__
4175 || defined __OpenBSD__ || defined __NetBSD__
4176 platid = pibsd;
4177 #elif defined __sun__
4178 platid = pisun;
4179 #elif defined __APPLE__
4180 platid = piosx;
4181 #endif
4182 if (uname (&buf)) err (1, "uname");
4184 tup_v = caml_alloc_tuple (2);
4186 char const *sar[] = {
4187 buf.sysname,
4188 buf.release,
4189 buf.version,
4190 buf.machine,
4191 NULL
4193 arr_v = caml_copy_string_array (sar);
4195 Field (tup_v, 0) = Val_int (platid);
4196 Field (tup_v, 1) = arr_v;
4197 CAMLreturn (tup_v);
4200 CAMLprim value ml_cloexec (value fd_v)
4202 CAMLparam1 (fd_v);
4203 int fd = Int_val (fd_v);
4205 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4206 uerror ("fcntl", Nothing);
4208 CAMLreturn (Val_unit);
4211 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4213 CAMLparam2 (w_v, h_v);
4214 CAMLlocal1 (ret_v);
4215 struct bo *pbo;
4216 int w = Int_val (w_v);
4217 int h = Int_val (h_v);
4218 int cs = Int_val (cs_v);
4220 if (state.bo_usable) {
4221 pbo = calloc (sizeof (*pbo), 1);
4222 if (!pbo) {
4223 err (1, "calloc pbo");
4226 switch (cs) {
4227 case 0:
4228 case 1:
4229 pbo->size = w*h*4;
4230 break;
4231 case 2:
4232 pbo->size = w*h*2;
4233 break;
4234 default:
4235 errx (1, "%s: invalid colorspace %d", __func__, cs);
4238 state.glGenBuffersARB (1, &pbo->id);
4239 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4240 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4241 NULL, GL_STREAM_DRAW);
4242 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4243 GL_READ_WRITE);
4244 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4245 if (!pbo->ptr) {
4246 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4247 state.glDeleteBuffersARB (1, &pbo->id);
4248 free (pbo);
4249 ret_v = caml_copy_string ("0");
4251 else {
4252 int res;
4253 char *s;
4255 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4256 if (res < 0) {
4257 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4259 s = malloc (res+1);
4260 if (!s) {
4261 err (1, "malloc %d bytes failed", res+1);
4263 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4264 if (res < 0) {
4265 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4267 ret_v = caml_copy_string (s);
4268 free (s);
4271 else {
4272 ret_v = caml_copy_string ("0");
4274 CAMLreturn (ret_v);
4277 CAMLprim value ml_freepbo (value s_v)
4279 CAMLparam1 (s_v);
4280 char *s = String_val (s_v);
4281 struct tile *tile = parse_pointer (__func__, s);
4283 if (tile->pbo) {
4284 state.glDeleteBuffersARB (1, &tile->pbo->id);
4285 tile->pbo->id = -1;
4286 tile->pbo->ptr = NULL;
4287 tile->pbo->size = -1;
4289 CAMLreturn (Val_unit);
4292 CAMLprim value ml_unmappbo (value s_v)
4294 CAMLparam1 (s_v);
4295 char *s = String_val (s_v);
4296 struct tile *tile = parse_pointer (__func__, s);
4298 if (tile->pbo) {
4299 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4300 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4301 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4303 tile->pbo->ptr = NULL;
4304 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4306 CAMLreturn (Val_unit);
4309 static void setuppbo (void)
4311 #ifdef USE_EGL
4312 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4313 #else
4314 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4315 #endif
4316 state.bo_usable = GGPA (glBindBufferARB)
4317 && GGPA (glUnmapBufferARB)
4318 && GGPA (glMapBufferARB)
4319 && GGPA (glBufferDataARB)
4320 && GGPA (glGenBuffersARB)
4321 && GGPA (glDeleteBuffersARB);
4322 #undef GGPA
4325 CAMLprim value ml_bo_usable (value unit_v)
4327 CAMLparam1 (unit_v);
4328 CAMLreturn (Val_bool (state.bo_usable));
4331 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4333 CAMLparam3 (ptr_v, x_v, y_v);
4334 CAMLlocal2 (ret_v, tup_v);
4335 struct page *page;
4336 char *s = String_val (ptr_v);
4337 int x = Int_val (x_v), y = Int_val (y_v);
4338 struct pagedim *pdim;
4339 fz_point p;
4340 fz_matrix ctm;
4342 page = parse_pointer (__func__, s);
4343 pdim = &state.pagedims[page->pdimno];
4345 ret_v = Val_int (0);
4346 if (trylock (__func__)) {
4347 goto done;
4350 if (pdf_specifics (state.ctx, state.doc)) {
4351 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4352 ctm = state.pagedims[page->pdimno].tctm;
4354 else {
4355 ctm = fz_identity;
4357 p.x = x + pdim->bounds.x0;
4358 p.y = y + pdim->bounds.y0;
4360 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4361 fz_invert_matrix (&ctm, &ctm);
4362 fz_transform_point (&p, &ctm);
4364 tup_v = caml_alloc_tuple (2);
4365 ret_v = caml_alloc_small (1, 1);
4366 Field (tup_v, 0) = Val_int (p.x);
4367 Field (tup_v, 1) = Val_int (p.y);
4368 Field (ret_v, 0) = tup_v;
4370 unlock (__func__);
4371 done:
4372 CAMLreturn (ret_v);
4375 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4376 value x_v, value y_v)
4378 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4379 CAMLlocal1 (ret_v);
4380 struct page *page;
4381 char *s = String_val (ptr_v);
4382 int pageno = Int_val (pageno_v);
4383 int pdimno = Int_val (pdimno_v);
4384 double x = Double_val (x_v), y = Double_val (y_v);
4385 struct pagedim *pdim;
4386 fz_point p;
4387 fz_matrix ctm;
4389 ret_v = Val_int (0);
4390 lock (__func__);
4392 if (!*s) {
4393 page = loadpage (pageno, pdimno);
4395 else {
4396 page = parse_pointer (__func__, s);
4398 pdim = &state.pagedims[pdimno];
4400 if (pdf_specifics (state.ctx, state.doc)) {
4401 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4402 ctm = state.pagedims[page->pdimno].tctm;
4404 else {
4405 ctm = fz_identity;
4407 p.x = x + pdim->bounds.x0;
4408 p.y = y + pdim->bounds.y0;
4410 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4411 fz_transform_point (&p, &ctm);
4413 ret_v = caml_alloc_tuple (2);
4414 Field (ret_v, 0) = caml_copy_double (p.x);
4415 Field (ret_v, 1) = caml_copy_double (p.y);
4417 if (!*s) {
4418 freepage (page);
4420 unlock (__func__);
4421 CAMLreturn (ret_v);
4424 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4425 value contents_v)
4427 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4428 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4430 if (pdf) {
4431 pdf_annot *annot;
4432 struct page *page;
4433 fz_point p;
4434 char *s = String_val (ptr_v);
4436 page = parse_pointer (__func__, s);
4437 annot = pdf_create_annot (state.ctx, pdf,
4438 pdf_page_from_fz_page (state.ctx,
4439 page->fzpage),
4440 FZ_ANNOT_TEXT);
4441 p.x = Int_val (x_v);
4442 p.y = Int_val (y_v);
4443 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4444 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4445 state.dirty = 1;
4447 CAMLreturn (Val_unit);
4450 CAMLprim value ml_delannot (value ptr_v, value n_v)
4452 CAMLparam2 (ptr_v, n_v);
4453 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4455 if (pdf) {
4456 struct page *page;
4457 char *s = String_val (ptr_v);
4458 struct slink *slink;
4460 page = parse_pointer (__func__, s);
4461 slink = &page->slinks[Int_val (n_v)];
4462 pdf_delete_annot (state.ctx, pdf,
4463 pdf_page_from_fz_page (state.ctx, page->fzpage),
4464 (pdf_annot *) slink->u.annot);
4465 state.dirty = 1;
4467 CAMLreturn (Val_unit);
4470 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4472 CAMLparam3 (ptr_v, n_v, str_v);
4473 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4475 if (pdf) {
4476 struct page *page;
4477 char *s = String_val (ptr_v);
4478 struct slink *slink;
4480 page = parse_pointer (__func__, s);
4481 slink = &page->slinks[Int_val (n_v)];
4482 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4483 String_val (str_v));
4484 state.dirty = 1;
4486 CAMLreturn (Val_unit);
4489 CAMLprim value ml_hasunsavedchanges (value unit_v)
4491 CAMLparam1 (unit_v);
4492 CAMLreturn (Val_bool (state.dirty));
4495 CAMLprim value ml_savedoc (value path_v)
4497 CAMLparam1 (path_v);
4498 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4500 if (pdf) {
4501 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4503 CAMLreturn (Val_unit);
4506 static void makestippletex (void)
4508 const char pixels[] = "\xff\xff\0\0";
4509 glGenTextures (1, &state.stid);
4510 glBindTexture (GL_TEXTURE_1D, state.stid);
4511 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4512 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4513 glTexImage1D (
4514 GL_TEXTURE_1D,
4516 GL_ALPHA,
4519 GL_ALPHA,
4520 GL_UNSIGNED_BYTE,
4521 pixels
4525 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4527 return caml_copy_string (FZ_VERSION);
4530 #ifdef USE_FONTCONFIG
4531 static struct {
4532 int inited;
4533 FcConfig *config;
4534 } fc;
4536 static fz_font *fc_load_system_font_func (fz_context *ctx,
4537 const char *name,
4538 int bold,
4539 int italic,
4540 int UNUSED_ATTR needs_exact_metrics)
4542 char *buf;
4543 size_t i, size;
4544 fz_font *font;
4545 FcChar8 *path;
4546 FcResult result;
4547 FcPattern *pat, *pat1;
4549 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4550 name, bold, italic, needs_exact_metrics);
4551 if (!fc.inited) {
4552 fc.inited = 1;
4553 fc.config = FcInitLoadConfigAndFonts ();
4554 if (!fc.config) {
4555 lprintf ("FcInitLoadConfigAndFonts failed\n");
4556 return NULL;
4559 if (!fc.config) return NULL;
4561 size = strlen (name);
4562 if (bold) size += sizeof (":bold") - 1;
4563 if (italic) size += sizeof (":italic") - 1;
4564 size += 1;
4566 buf = malloc (size);
4567 if (!buf) {
4568 err (1, "malloc %zu failed", size);
4571 strcpy (buf, name);
4572 if (bold && italic) {
4573 strcat (buf, ":bold:italic");
4575 else {
4576 if (bold) strcat (buf, ":bold");
4577 if (italic) strcat (buf, ":italic");
4579 for (i = 0; i < size; ++i) {
4580 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4583 lprintf ("fcbuf=%s\n", buf);
4584 pat = FcNameParse ((FcChar8 *) buf);
4585 if (!pat) {
4586 printd ("emsg FcNameParse failed\n");
4587 free (buf);
4588 return NULL;
4591 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4592 printd ("emsg FcConfigSubstitute failed\n");
4593 free (buf);
4594 return NULL;
4596 FcDefaultSubstitute (pat);
4598 pat1 = FcFontMatch (fc.config, pat, &result);
4599 if (!pat1) {
4600 printd ("emsg FcFontMatch failed\n");
4601 FcPatternDestroy (pat);
4602 free (buf);
4603 return NULL;
4606 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4607 printd ("emsg FcPatternGetString failed\n");
4608 FcPatternDestroy (pat);
4609 FcPatternDestroy (pat1);
4610 free (buf);
4611 return NULL;
4614 #if 0
4615 printd ("emsg name=%s path=%s\n", name, path);
4616 #endif
4617 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4618 FcPatternDestroy (pat);
4619 FcPatternDestroy (pat1);
4620 free (buf);
4621 return font;
4623 #endif
4625 CAMLprim value ml_init (value csock_v, value params_v)
4627 CAMLparam2 (csock_v, params_v);
4628 CAMLlocal2 (trim_v, fuzz_v);
4629 int ret;
4630 int texcount;
4631 char *fontpath;
4632 int colorspace;
4633 int mustoresize;
4634 int haspboext;
4636 state.csock = Int_val (csock_v);
4637 state.rotate = Int_val (Field (params_v, 0));
4638 state.fitmodel = Int_val (Field (params_v, 1));
4639 trim_v = Field (params_v, 2);
4640 texcount = Int_val (Field (params_v, 3));
4641 state.sliceheight = Int_val (Field (params_v, 4));
4642 mustoresize = Int_val (Field (params_v, 5));
4643 colorspace = Int_val (Field (params_v, 6));
4644 fontpath = String_val (Field (params_v, 7));
4646 if (caml_string_length (Field (params_v, 8)) > 0) {
4647 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4649 if (!state.trimcachepath) {
4650 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4651 strerror (errno));
4654 haspboext = Bool_val (Field (params_v, 9));
4656 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4657 fz_register_document_handlers (state.ctx);
4659 #ifdef USE_FONTCONFIG
4660 if (Bool_val (Field (params_v, 10))) {
4661 fz_install_load_system_font_funcs (
4662 state.ctx, fc_load_system_font_func, NULL
4665 #endif
4667 state.trimmargins = Bool_val (Field (trim_v, 0));
4668 fuzz_v = Field (trim_v, 1);
4669 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4670 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4671 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4672 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4674 set_tex_params (colorspace);
4676 if (*fontpath) {
4677 #ifndef USE_FONTCONFIG
4678 state.face = load_font (fontpath);
4679 #else
4680 FcChar8 *path;
4681 FcResult result;
4682 char *buf = fontpath;
4683 FcPattern *pat, *pat1;
4685 fc.inited = 1;
4686 fc.config = FcInitLoadConfigAndFonts ();
4687 if (!fc.config) {
4688 errx (1, "FcInitLoadConfigAndFonts failed");
4691 pat = FcNameParse ((FcChar8 *) buf);
4692 if (!pat) {
4693 errx (1, "FcNameParse failed");
4696 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4697 errx (1, "FcConfigSubstitute failed");
4699 FcDefaultSubstitute (pat);
4701 pat1 = FcFontMatch (fc.config, pat, &result);
4702 if (!pat1) {
4703 errx (1, "FcFontMatch failed");
4706 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4707 errx (1, "FcPatternGetString failed");
4710 state.face = load_font ((char *) path);
4711 FcPatternDestroy (pat);
4712 FcPatternDestroy (pat1);
4713 #endif
4715 else {
4716 int len;
4717 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4718 0, 0, &len);
4719 state.face = load_builtin_font (data, len);
4721 if (!state.face) _exit (1);
4723 realloctexts (texcount);
4725 if (haspboext) {
4726 setuppbo ();
4729 makestippletex ();
4731 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4732 if (ret) {
4733 errx (1, "pthread_create: %s", strerror (ret));
4736 CAMLreturn (Val_unit);