Remove pointless code
[llpp.git] / link.c
bloba35cfcd4018c62ad6dd7c9a7fa270c4bf29b0d64
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
4 #include <errno.h>
5 #include <stdio.h>
6 #include <ctype.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <signal.h>
10 #include <wchar.h>
12 #include <unistd.h>
13 #include <pthread.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/utsname.h>
19 #ifdef __CYGWIN__
20 #include <cygwin/socket.h> /* FIONREAD */
21 #else
22 #include <spawn.h>
23 #endif
25 #include <regex.h>
26 #include <stdarg.h>
27 #include <limits.h>
28 #include <inttypes.h>
30 #include <GL/gl.h>
32 #include <caml/fail.h>
33 #include <caml/alloc.h>
34 #include <caml/memory.h>
35 #include <caml/unixsupport.h>
37 #if __GNUC__ < 5
38 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
39 clobbered diagnostics */
40 #pragma GCC diagnostic ignored "-Wclobbered"
41 #endif
43 #pragma GCC diagnostic push
44 #pragma GCC diagnostic ignored "-Wunused-parameter"
45 #pragma GCC diagnostic ignored "-Wshadow"
46 #include <mupdf/fitz.h>
47 #pragma GCC diagnostic pop
48 #include <mupdf/pdf.h>
50 #include <ft2build.h>
51 #include FT_FREETYPE_H
53 #ifdef USE_FONTCONFIG
54 #include <fontconfig/fontconfig.h>
55 #endif
57 #define PIGGYBACK
58 #define CACHE_PAGEREFS
60 #ifndef __USE_GNU
61 extern char **environ;
62 #endif
64 #define MIN(a,b) ((a) < (b) ? (a) : (b))
65 #define MAX(a,b) ((a) > (b) ? (a) : (b))
67 #if defined __GNUC__
68 #define NORETURN_ATTR __attribute__ ((noreturn))
69 #define UNUSED_ATTR __attribute__ ((unused))
70 #if !defined __clang__
71 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
72 #else
73 #define OPTIMIZE_ATTR(n)
74 #endif
75 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
76 #else
77 #define NORETURN_ATTR
78 #define UNUSED_ATTR
79 #define OPTIMIZE_ATTR(n)
80 #define GCC_FMT_ATTR(a, b)
81 #endif
83 #define FMT_s "zu"
85 #define FMT_ptr PRIxPTR
86 #define SCN_ptr SCNxPTR
87 #define FMT_ptr_cast(p) ((uintptr_t) (p))
88 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
90 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
91 err (int exitcode, const char *fmt, ...)
93 va_list ap;
94 int savederrno;
96 savederrno = errno;
97 va_start (ap, fmt);
98 vfprintf (stderr, fmt, ap);
99 va_end (ap);
100 fprintf (stderr, ": %s\n", strerror (savederrno));
101 fflush (stderr);
102 _exit (exitcode);
105 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
106 errx (int exitcode, const char *fmt, ...)
108 va_list ap;
110 va_start (ap, fmt);
111 vfprintf (stderr, fmt, ap);
112 va_end (ap);
113 fputc ('\n', stderr);
114 fflush (stderr);
115 _exit (exitcode);
118 #ifndef GL_TEXTURE_RECTANGLE_ARB
119 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
120 #endif
122 #ifdef USE_NPOT
123 #define TEXT_TYPE GL_TEXTURE_2D
124 #else
125 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
126 #endif
128 #ifndef GL_BGRA
129 #define GL_BGRA 0x80E1
130 #endif
132 #ifndef GL_UNSIGNED_INT_8_8_8_8
133 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
134 #endif
136 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
137 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
138 #endif
140 #if 0
141 #define lprintf printf
142 #else
143 #define lprintf(...)
144 #endif
146 #define ARSERT(cond) for (;;) { \
147 if (!(cond)) { \
148 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
150 break; \
153 struct slice {
154 int h;
155 int texindex;
158 struct tile {
159 int w, h;
160 int slicecount;
161 int sliceheight;
162 struct bo *pbo;
163 fz_pixmap *pixmap;
164 struct slice slices[1];
167 struct pagedim {
168 int pageno;
169 int rotate;
170 int left;
171 int tctmready;
172 fz_irect bounds;
173 fz_rect pagebox;
174 fz_rect mediabox;
175 fz_matrix ctm, zoomctm, lctm, tctm;
178 struct slink {
179 enum { SLINK, SANNOT } tag;
180 fz_irect bbox;
181 union {
182 fz_link *link;
183 fz_annot *annot;
184 } u;
187 struct annot {
188 fz_irect bbox;
189 fz_annot *annot;
192 struct page {
193 int tgen;
194 int sgen;
195 int agen;
196 int pageno;
197 int pdimno;
198 fz_stext_page *text;
199 fz_stext_sheet *sheet;
200 fz_page *fzpage;
201 fz_display_list *dlist;
202 int slinkcount;
203 struct slink *slinks;
204 int annotcount;
205 struct annot *annots;
206 struct mark {
207 int i;
208 fz_stext_span *span;
209 } fmark, lmark;
212 struct {
213 int sliceheight;
214 struct pagedim *pagedims;
215 int pagecount;
216 int pagedimcount;
217 fz_document *doc;
218 fz_context *ctx;
219 int w, h;
221 int texindex;
222 int texcount;
223 GLuint *texids;
225 GLenum texiform;
226 GLenum texform;
227 GLenum texty;
229 fz_colorspace *colorspace;
231 struct {
232 int w, h;
233 struct slice *slice;
234 } *texowners;
236 int rotate;
237 enum { FitWidth, FitProportional, FitPage } fitmodel;
238 int trimmargins;
239 int needoutline;
240 int gen;
241 int aalevel;
243 int trimanew;
244 fz_irect trimfuzz;
245 fz_pixmap *pig;
247 pthread_t thread;
248 int csock;
249 FT_Face face;
251 char *trimcachepath;
252 int cxack;
253 int dirty;
255 GLuint stid;
257 int bo_usable;
258 GLuint boid;
260 void (*glBindBufferARB) (GLenum, GLuint);
261 GLboolean (*glUnmapBufferARB) (GLenum);
262 void *(*glMapBufferARB) (GLenum, GLenum);
263 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
264 void (*glGenBuffersARB) (GLsizei, GLuint *);
265 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
267 GLfloat texcoords[8];
268 GLfloat vertices[16];
270 #ifdef CACHE_PAGEREFS
271 struct {
272 int idx;
273 int count;
274 pdf_obj **objs;
275 pdf_document *pdf;
276 } pdflut;
277 #endif
278 } state;
280 struct bo {
281 GLuint id;
282 void *ptr;
283 size_t size;
286 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
288 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
291 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
293 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
296 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
298 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
299 m.a, m.b, m.c, m.d, m.e, m.f);
302 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
304 static void lock (const char *cap)
306 int ret = pthread_mutex_lock (&mutex);
307 if (ret) {
308 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
312 static void unlock (const char *cap)
314 int ret = pthread_mutex_unlock (&mutex);
315 if (ret) {
316 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
320 static int trylock (const char *cap)
322 int ret = pthread_mutex_trylock (&mutex);
323 if (ret && ret != EBUSY) {
324 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
326 return ret == EBUSY;
329 static void *parse_pointer (const char *cap, const char *s)
331 int ret;
332 void *ptr;
334 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
335 if (ret != 1) {
336 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
338 return ptr;
341 static double now (void)
343 struct timeval tv;
345 if (gettimeofday (&tv, NULL)) {
346 err (1, "gettimeofday");
348 return tv.tv_sec + tv.tv_usec*1e-6;
351 static int hasdata (void)
353 int ret, avail;
354 ret = ioctl (state.csock, FIONREAD, &avail);
355 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
356 return avail > 0;
359 CAMLprim value ml_hasdata (value fd_v)
361 CAMLparam1 (fd_v);
362 int ret, avail;
364 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
365 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
366 CAMLreturn (Val_bool (avail > 0));
369 static void readdata (int fd, void *p, int size)
371 ssize_t n;
373 again:
374 n = read (fd, p, size);
375 if (n < 0) {
376 if (errno == EINTR) goto again;
377 err (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
379 if (n - size) {
380 if (!n) errx (1, "EOF while reading");
381 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
385 static void writedata (int fd, char *p, int size)
387 ssize_t n;
389 /* One should lookup type punning/strict aliasing etc in standard,DRs,Web to
390 convince herself that this is:
391 a. safe
392 b. practically the only way to achieve the result
393 (union puns notwithstanding) */
394 memcpy (p, &size, 4);
395 n = write (fd, p, size + 4);
396 if (n - size - 4) {
397 if (!n) errx (1, "EOF while writing data");
398 err (1, "write (fd %d, req %d, ret %zd)", fd, size + 4, n);
402 static int readlen (int fd)
404 /* Type punned unions here. Why? Less code (Adjusted by more comments).
405 https://en.wikipedia.org/wiki/Type_punning */
406 union { int len; char raw[4]; } buf;
407 readdata (fd, buf.raw, 4);
408 return buf.len;
411 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
413 CAMLparam3 (fd_v, bytes_v, len_v);
414 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
415 CAMLreturn0;
418 CAMLprim value ml_rcmd (value fd_v)
420 CAMLparam1 (fd_v);
421 CAMLlocal1 (strdata_v);
422 int fd = Int_val (fd_v);
423 int len = readlen (fd);
424 strdata_v = caml_alloc_string (len);
425 readdata (fd, String_val (strdata_v), len);
426 CAMLreturn (strdata_v);
429 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
431 int size = 200, len;
432 va_list ap;
433 char *buf;
435 buf = malloc (size);
436 for (;;) {
437 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
439 va_start (ap, fmt);
440 len = vsnprintf (buf + 4, size - 4, fmt, ap);
441 va_end (ap);
443 if (len > -1) {
444 if (len < size - 4) {
445 writedata (state.csock, buf, len);
446 break;
448 else size = len + 5;
450 else {
451 err (1, "vsnprintf for `%s' failed", fmt);
453 buf = realloc (buf, size);
455 free (buf);
458 static void closedoc (void)
460 #ifdef CACHE_PAGEREFS
461 if (state.pdflut.objs) {
462 int i;
464 for (i = 0; i < state.pdflut.count; ++i) {
465 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
467 free (state.pdflut.objs);
468 state.pdflut.objs = NULL;
469 state.pdflut.idx = 0;
471 #endif
472 if (state.doc) {
473 fz_drop_document (state.ctx, state.doc);
474 state.doc = NULL;
478 static int openxref (char *filename, char *password)
480 int i;
482 for (i = 0; i < state.texcount; ++i) {
483 state.texowners[i].w = -1;
484 state.texowners[i].slice = NULL;
487 closedoc ();
489 state.dirty = 0;
490 if (state.pagedims) {
491 free (state.pagedims);
492 state.pagedims = NULL;
494 state.pagedimcount = 0;
496 fz_set_aa_level (state.ctx, state.aalevel);
497 #ifdef CSS_HACK_TO_READ_EPUBS_COMFORTABLY
498 fz_set_user_css (state.ctx,
499 "body { margin-left: 20%; margin-right: 20%; }");
500 #endif
501 state.doc = fz_open_document (state.ctx, filename);
502 if (fz_needs_password (state.ctx, state.doc)) {
503 if (password && !*password) {
504 printd ("pass");
505 return 0;
507 else {
508 int ok = fz_authenticate_password (state.ctx, state.doc, password);
509 if (!ok) {
510 printd ("pass fail");
511 return 0;
515 state.pagecount = fz_count_pages (state.ctx, state.doc);
516 return 1;
519 static void pdfinfo (void)
521 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
522 if (pdf) {
523 pdf_obj *infoobj;
525 printd ("info PDF version\t%d.%d",
526 pdf->version / 10, pdf->version % 10);
528 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
529 pdf), "Info");
530 if (infoobj) {
531 unsigned int i;
532 char *s;
533 char *items[] = { "Title", "Author", "Creator",
534 "Producer", "CreationDate" };
536 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
537 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
538 s = pdf_to_utf8 (state.ctx, pdf, obj);
539 if (*s) printd ("info %s\t%s", items[i], s);
540 fz_free (state.ctx, s);
543 printd ("infoend");
547 static void unlinktile (struct tile *tile)
549 int i;
551 for (i = 0; i < tile->slicecount; ++i) {
552 struct slice *s = &tile->slices[i];
554 if (s->texindex != -1) {
555 if (state.texowners[s->texindex].slice == s) {
556 state.texowners[s->texindex].slice = NULL;
562 static void freepage (struct page *page)
564 if (!page) return;
565 if (page->text) {
566 fz_drop_stext_page (state.ctx, page->text);
568 if (page->sheet) {
569 fz_drop_stext_sheet (state.ctx, page->sheet);
571 if (page->slinks) {
572 free (page->slinks);
574 fz_drop_display_list (state.ctx, page->dlist);
575 fz_drop_page (state.ctx, page->fzpage);
576 free (page);
579 static void freetile (struct tile *tile)
581 unlinktile (tile);
582 if (!tile->pbo) {
583 #ifndef PIGGYBACK
584 fz_drop_pixmap (state.ctx, tile->pixmap);
585 #else
586 if (state.pig) {
587 fz_drop_pixmap (state.ctx, state.pig);
589 state.pig = tile->pixmap;
590 #endif
592 else {
593 free (tile->pbo);
594 fz_drop_pixmap (state.ctx, tile->pixmap);
596 free (tile);
599 #ifdef __ALTIVEC__
600 #include <stdint.h>
601 #include <altivec.h>
603 static int cacheline32bytes;
605 static void __attribute__ ((constructor)) clcheck (void)
607 char **envp = environ;
608 unsigned long *auxv;
610 while (*envp++);
612 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
613 if (*auxv == 19) {
614 cacheline32bytes = auxv[1] == 32;
615 return;
620 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
622 size_t size = pixmap->w * pixmap->h * pixmap->n;
623 if (cacheline32bytes && size > 32) {
624 intptr_t a1, a2, diff;
625 size_t sizea, i;
626 vector unsigned char v = vec_splat_u8 (-1);
627 vector unsigned char *p;
629 a1 = a2 = (intptr_t) pixmap->samples;
630 a2 = (a1 + 31) & ~31;
631 diff = a2 - a1;
632 sizea = size - diff;
633 p = (void *) a2;
635 while (a1 != a2) *(char *) a1++ = 0xff;
636 for (i = 0; i < (sizea & ~31); i += 32) {
637 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
638 vec_st (v, i, p);
639 vec_st (v, i + 16, p);
641 while (i < sizea) *((char *) a1 + i++) = 0xff;
643 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
645 #else
646 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
647 #endif
649 static void trimctm (pdf_page *page, int pindex)
651 fz_matrix ctm;
652 struct pagedim *pdim = &state.pagedims[pindex];
654 if (!pdim->tctmready) {
655 if (state.trimmargins) {
656 fz_rect realbox;
657 fz_matrix rm, sm, tm, im, ctm1;
659 fz_rotate (&rm, -pdim->rotate);
660 fz_scale (&sm, 1, -1);
661 fz_concat (&ctm, &rm, &sm);
662 realbox = pdim->mediabox;
663 fz_transform_rect (&realbox, &ctm);
664 fz_translate (&tm, -realbox.x0, -realbox.y0);
665 fz_concat (&ctm1, &ctm, &tm);
666 fz_invert_matrix (&im, &page->ctm);
667 fz_concat (&ctm, &im, &ctm1);
669 else {
670 ctm = fz_identity;
672 pdim->tctm = ctm;
673 pdim->tctmready = 1;
677 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
679 fz_matrix ctm, tm;
680 int pdimno = pdim - state.pagedims;
682 if (pdf_specifics (state.ctx, state.doc)) {
683 trimctm ((pdf_page *) fzpage, pdimno);
684 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
686 else {
687 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
688 fz_concat (&ctm, &tm, &pdim->ctm);
690 return ctm;
693 static fz_matrix pagectm (struct page *page)
695 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
698 static void *loadpage (int pageno, int pindex)
700 fz_device *dev;
701 struct page *page;
703 page = calloc (sizeof (struct page), 1);
704 if (!page) {
705 err (1, "calloc page %d", pageno);
708 page->dlist = fz_new_display_list (state.ctx);
709 dev = fz_new_list_device (state.ctx, page->dlist);
710 fz_try (state.ctx) {
711 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
712 fz_run_page (state.ctx, page->fzpage, dev,
713 &fz_identity, NULL);
715 fz_catch (state.ctx) {
716 page->fzpage = NULL;
718 fz_drop_device (state.ctx, dev);
720 page->pdimno = pindex;
721 page->pageno = pageno;
722 page->sgen = state.gen;
723 page->agen = state.gen;
724 page->tgen = state.gen;
725 return page;
728 static struct tile *alloctile (int h)
730 int i;
731 int slicecount;
732 size_t tilesize;
733 struct tile *tile;
735 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
736 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
737 tile = calloc (tilesize, 1);
738 if (!tile) {
739 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
741 for (i = 0; i < slicecount; ++i) {
742 int sh = MIN (h, state.sliceheight);
743 tile->slices[i].h = sh;
744 tile->slices[i].texindex = -1;
745 h -= sh;
747 tile->slicecount = slicecount;
748 tile->sliceheight = state.sliceheight;
749 return tile;
752 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
753 struct bo *pbo)
755 fz_rect rect;
756 fz_irect bbox;
757 fz_matrix ctm;
758 fz_device *dev;
759 struct tile *tile;
760 struct pagedim *pdim;
762 tile = alloctile (h);
763 pdim = &state.pagedims[page->pdimno];
765 bbox = pdim->bounds;
766 bbox.x0 += x;
767 bbox.y0 += y;
768 bbox.x1 = bbox.x0 + w;
769 bbox.y1 = bbox.y0 + h;
771 if (state.pig) {
772 if (state.pig->w == w
773 && state.pig->h == h
774 && state.pig->colorspace == state.colorspace) {
775 tile->pixmap = state.pig;
776 tile->pixmap->x = bbox.x0;
777 tile->pixmap->y = bbox.y0;
779 else {
780 fz_drop_pixmap (state.ctx, state.pig);
782 state.pig = NULL;
784 if (!tile->pixmap) {
785 if (pbo) {
786 tile->pixmap =
787 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
788 &bbox, pbo->ptr);
789 tile->pbo = pbo;
791 else {
792 tile->pixmap =
793 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
797 tile->w = w;
798 tile->h = h;
799 clearpixmap (tile->pixmap);
801 dev = fz_new_draw_device (state.ctx, tile->pixmap);
802 ctm = pagectm (page);
803 fz_rect_from_irect (&rect, &bbox);
804 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
805 fz_drop_device (state.ctx, dev);
807 return tile;
810 #ifdef CACHE_PAGEREFS
811 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
812 thanks to Robin Watts */
813 static void
814 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
816 fz_context *ctx = state.ctx; /* doc->ctx; */
817 pdf_obj *kids;
818 int i, len;
820 if (state.pdflut.idx == state.pagecount) return;
822 kids = pdf_dict_gets (ctx, node, "Kids");
823 len = pdf_array_len (ctx, kids);
825 if (len == 0)
826 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
828 if (pdf_mark_obj (ctx, node))
829 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
830 for (i = 0; i < len; i++) {
831 pdf_obj *kid = pdf_array_get (ctx, kids, i);
832 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
833 if (*type
834 ? !strcmp (type, "Pages")
835 : pdf_dict_gets (ctx, kid, "Kids")
836 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
837 pdf_collect_pages (doc, kid);
839 else {
840 if (*type
841 ? strcmp (type, "Page") != 0
842 : !pdf_dict_gets (ctx, kid, "MediaBox"))
843 fz_warn (ctx, "non-page object in page tree (%s)", type);
844 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
847 pdf_unmark_obj (ctx, node);
850 static void
851 pdf_load_page_objs (pdf_document *doc)
853 pdf_obj *root = pdf_dict_gets (state.ctx,
854 pdf_trailer (state.ctx, doc), "Root");
855 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
857 if (!node)
858 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
860 state.pdflut.idx = 0;
861 pdf_collect_pages (doc, node);
863 #endif
865 static void initpdims (int wthack)
867 double start, end;
868 FILE *trimf = NULL;
869 fz_rect rootmediabox;
870 int pageno, trim, show;
871 int trimw = 0, cxcount;
872 fz_context *ctx = state.ctx;
873 pdf_document *pdf = pdf_specifics (ctx, state.doc);
875 fz_var (trimw);
876 fz_var (cxcount);
877 start = now ();
879 if (state.trimmargins && state.trimcachepath) {
880 trimf = fopen (state.trimcachepath, "rb");
881 if (!trimf) {
882 trimf = fopen (state.trimcachepath, "wb");
883 trimw = 1;
887 if (state.trimmargins || pdf || !state.cxack)
888 cxcount = state.pagecount;
889 else
890 cxcount = MIN (state.pagecount, 1);
892 if (pdf) {
893 pdf_obj *obj;
894 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
895 "Root/Pages/MediaBox");
896 pdf_to_rect (ctx, obj, &rootmediabox);
899 #ifdef CACHE_PAGEREFS
900 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
901 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
902 if (!state.pdflut.objs) {
903 err (1, "malloc pageobjs %zu %d %zu failed",
904 sizeof (*state.pdflut.objs), cxcount,
905 sizeof (*state.pdflut.objs) * cxcount);
907 state.pdflut.count = cxcount;
908 pdf_load_page_objs (pdf);
909 state.pdflut.pdf = pdf;
911 #endif
913 for (pageno = 0; pageno < cxcount; ++pageno) {
914 int rotate = 0;
915 struct pagedim *p;
916 fz_rect mediabox;
918 if (pdf) {
919 pdf_obj *pageref, *pageobj;
921 #ifdef CACHE_PAGEREFS
922 pageref = state.pdflut.objs[pageno];
923 #else
924 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
925 #endif
926 pageobj = pdf_resolve_indirect (ctx, pageref);
928 if (state.trimmargins) {
929 pdf_obj *obj;
930 pdf_page *page;
932 fz_try (ctx) {
933 page = pdf_load_page (ctx, pdf, pageno);
934 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
935 trim = state.trimanew || !obj;
936 if (trim) {
937 fz_rect rect;
938 fz_matrix ctm;
939 fz_device *dev;
941 dev = fz_new_bbox_device (ctx, &rect);
942 dev->hints |= FZ_IGNORE_SHADE;
943 fz_invert_matrix (&ctm, &page->ctm);
944 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
945 fz_drop_device (ctx, dev);
947 rect.x0 += state.trimfuzz.x0;
948 rect.x1 += state.trimfuzz.x1;
949 rect.y0 += state.trimfuzz.y0;
950 rect.y1 += state.trimfuzz.y1;
951 fz_transform_rect (&rect, &ctm);
952 fz_intersect_rect (&rect, &page->mediabox);
954 if (fz_is_empty_rect (&rect)) {
955 mediabox = page->mediabox;
957 else {
958 mediabox = rect;
961 obj = pdf_new_array (ctx, pdf, 4);
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.x0));
964 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
965 mediabox.y0));
966 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
967 mediabox.x1));
968 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
969 mediabox.y1));
970 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
972 else {
973 mediabox.x0 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 0));
975 mediabox.y0 = pdf_to_real (ctx,
976 pdf_array_get (ctx, obj, 1));
977 mediabox.x1 = pdf_to_real (ctx,
978 pdf_array_get (ctx, obj, 2));
979 mediabox.y1 = pdf_to_real (ctx,
980 pdf_array_get (ctx, obj, 3));
983 rotate = page->rotate;
984 fz_drop_page (ctx, &page->super);
986 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
987 if (show) {
988 printd ("progress %f Trimming %d",
989 (double) (pageno + 1) / state.pagecount,
990 pageno + 1);
993 fz_catch (ctx) {
994 fprintf (stderr, "failed to load page %d\n", pageno+1);
997 else {
998 int empty = 0;
999 fz_rect cropbox;
1001 pdf_to_rect (ctx,
1002 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1003 &mediabox);
1004 if (fz_is_empty_rect (&mediabox)) {
1005 mediabox.x0 = 0;
1006 mediabox.y0 = 0;
1007 mediabox.x1 = 612;
1008 mediabox.y1 = 792;
1009 empty = 1;
1012 pdf_to_rect (ctx,
1013 pdf_dict_gets (ctx, pageobj, "CropBox"),
1014 &cropbox);
1015 if (!fz_is_empty_rect (&cropbox)) {
1016 if (empty) {
1017 mediabox = cropbox;
1019 else {
1020 fz_intersect_rect (&mediabox, &cropbox);
1023 else {
1024 if (empty) {
1025 if (fz_is_empty_rect (&rootmediabox)) {
1026 fprintf (stderr,
1027 "cannot find page size for page %d\n",
1028 pageno+1);
1030 else {
1031 mediabox = rootmediabox;
1035 rotate = pdf_to_int (ctx,
1036 pdf_dict_gets (ctx, pageobj, "Rotate"));
1039 else {
1040 if (state.trimmargins && trimw) {
1041 fz_page *page;
1043 fz_try (ctx) {
1044 page = fz_load_page (ctx, state.doc, pageno);
1045 fz_bound_page (ctx, page, &mediabox);
1046 rotate = 0;
1047 if (state.trimmargins) {
1048 fz_rect rect;
1049 fz_device *dev;
1051 dev = fz_new_bbox_device (ctx, &rect);
1052 dev->hints |= FZ_IGNORE_SHADE;
1053 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1054 fz_drop_device (ctx, dev);
1056 rect.x0 += state.trimfuzz.x0;
1057 rect.x1 += state.trimfuzz.x1;
1058 rect.y0 += state.trimfuzz.y0;
1059 rect.y1 += state.trimfuzz.y1;
1060 fz_intersect_rect (&rect, &mediabox);
1062 if (!fz_is_empty_rect (&rect)) {
1063 mediabox = rect;
1066 fz_drop_page (ctx, page);
1067 if (!state.cxack) {
1068 printd ("progress %f loading %d",
1069 (double) (pageno + 1) / state.pagecount,
1070 pageno + 1);
1073 fz_catch (ctx) {
1075 if (trimf) {
1076 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1077 if (n - 1) {
1078 err (1, "fwrite trim mediabox");
1082 else {
1083 if (trimf) {
1084 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1085 if (n - 1) {
1086 err (1, "fread trim mediabox %d", pageno);
1089 else {
1090 fz_page *page;
1091 fz_try (ctx) {
1092 page = fz_load_page (ctx, state.doc, pageno);
1093 fz_bound_page (ctx, page, &mediabox);
1094 fz_drop_page (ctx, page);
1096 show = !state.trimmargins && pageno % 20 == 0;
1097 if (show) {
1098 printd ("progress %f Gathering dimensions %d",
1099 (double) (pageno) / state.pagecount,
1100 pageno);
1103 fz_catch (ctx) {
1104 fprintf (stderr, "failed to load page %d\n", pageno);
1110 if (state.pagedimcount == 0
1111 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1112 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1113 size_t size;
1115 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1116 state.pagedims = realloc (state.pagedims, size);
1117 if (!state.pagedims) {
1118 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1119 size, state.pagedimcount + 1);
1122 p = &state.pagedims[state.pagedimcount++];
1123 p->rotate = rotate;
1124 p->mediabox = mediabox;
1125 p->pageno = pageno;
1128 end = now ();
1129 if (!wthack) {
1130 printd ("progress 1 %s %d pages in %f seconds",
1131 state.trimmargins ? "Trimmed" : "Processed",
1132 state.pagecount, end - start);
1134 state.trimanew = 0;
1135 if (trimf) {
1136 if (fclose (trimf)) {
1137 err (1, "fclose");
1142 static void layout (void)
1144 int pindex;
1145 fz_rect box;
1146 fz_matrix ctm, rm;
1147 struct pagedim *p = p;
1148 double zw, w, maxw = 0.0, zoom = zoom;
1150 if (state.pagedimcount == 0) return;
1152 switch (state.fitmodel) {
1153 case FitProportional:
1154 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1155 double x0, x1;
1157 p = &state.pagedims[pindex];
1158 fz_rotate (&rm, p->rotate + state.rotate);
1159 box = p->mediabox;
1160 fz_transform_rect (&box, &rm);
1162 x0 = MIN (box.x0, box.x1);
1163 x1 = MAX (box.x0, box.x1);
1165 w = x1 - x0;
1166 maxw = MAX (w, maxw);
1167 zoom = state.w / maxw;
1169 break;
1171 case FitPage:
1172 maxw = state.w;
1173 break;
1175 case FitWidth:
1176 break;
1178 default:
1179 ARSERT (0 && state.fitmodel);
1182 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1183 fz_rect rect;
1184 fz_matrix tm, sm;
1186 p = &state.pagedims[pindex];
1187 fz_rotate (&ctm, state.rotate);
1188 fz_rotate (&rm, p->rotate + state.rotate);
1189 box = p->mediabox;
1190 fz_transform_rect (&box, &rm);
1191 w = box.x1 - box.x0;
1192 switch (state.fitmodel) {
1193 case FitProportional:
1194 p->left = ((maxw - w) * zoom) / 2.0;
1195 break;
1196 case FitPage:
1198 double zh, h;
1199 zw = maxw / w;
1200 h = box.y1 - box.y0;
1201 zh = state.h / h;
1202 zoom = MIN (zw, zh);
1203 p->left = (maxw - (w * zoom)) / 2.0;
1205 break;
1206 case FitWidth:
1207 p->left = 0;
1208 zoom = state.w / w;
1209 break;
1212 fz_scale (&p->zoomctm, zoom, zoom);
1213 fz_concat (&ctm, &p->zoomctm, &ctm);
1215 fz_rotate (&rm, p->rotate);
1216 p->pagebox = p->mediabox;
1217 fz_transform_rect (&p->pagebox, &rm);
1218 p->pagebox.x1 -= p->pagebox.x0;
1219 p->pagebox.y1 -= p->pagebox.y0;
1220 p->pagebox.x0 = 0;
1221 p->pagebox.y0 = 0;
1222 rect = p->pagebox;
1223 fz_transform_rect (&rect, &ctm);
1224 fz_round_rect (&p->bounds, &rect);
1225 p->ctm = ctm;
1227 fz_translate (&tm, 0, -p->mediabox.y1);
1228 fz_scale (&sm, zoom, -zoom);
1229 fz_concat (&ctm, &tm, &sm);
1230 fz_concat (&p->lctm, &ctm, &rm);
1232 p->tctmready = 0;
1235 do {
1236 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1237 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1238 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1239 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1240 int boundw = x1 - x0;
1241 int boundh = y1 - y0;
1243 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1244 } while (p-- != state.pagedims);
1247 static
1248 struct anchor { int n; int x; int y; int w; int h; }
1249 desttoanchor (fz_link_dest *dest)
1251 int i;
1252 struct anchor a;
1253 struct pagedim *pdim = state.pagedims;
1255 a.n = -1;
1256 a.x = 0;
1257 a.y = 0;
1258 for (i = 0; i < state.pagedimcount; ++i) {
1259 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1260 break;
1261 pdim = &state.pagedims[i];
1263 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1264 fz_point p;
1265 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1266 p.x = dest->ld.gotor.lt.x;
1267 else
1268 p.x = 0.0;
1269 p.y = dest->ld.gotor.lt.y;
1270 fz_transform_point (&p, &pdim->lctm);
1271 a.x = p.x;
1272 a.y = p.y;
1274 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1275 double x0, x1, y0, y1;
1277 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1278 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1279 a.w = x1 - x0;
1280 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1281 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1282 a.h = y1 - y0;
1283 a.n = dest->ld.gotor.page;
1285 return a;
1288 static void recurse_outline (fz_outline *outline, int level)
1290 while (outline) {
1291 switch (outline->dest.kind) {
1292 case FZ_LINK_GOTO:
1294 struct anchor a = desttoanchor (&outline->dest);
1296 if (a.n >= 0) {
1297 printd ("o %d %d %d %d %s",
1298 level, a.n, a.y, a.h, outline->title);
1301 break;
1303 case FZ_LINK_URI:
1304 printd ("ou %d %" FMT_s " %s %s", level,
1305 strlen (outline->title), outline->title,
1306 outline->dest.ld.uri.uri);
1307 break;
1309 case FZ_LINK_NONE:
1310 printd ("on %d %s", level, outline->title);
1311 break;
1313 default:
1314 printd ("emsg Unhandled outline kind %d for %s\n",
1315 outline->dest.kind, outline->title);
1316 break;
1318 if (outline->down) {
1319 recurse_outline (outline->down, level + 1);
1321 outline = outline->next;
1325 static void process_outline (void)
1327 fz_outline *outline;
1329 if (!state.needoutline || !state.pagedimcount) return;
1331 state.needoutline = 0;
1332 outline = fz_load_outline (state.ctx, state.doc);
1333 if (outline) {
1334 recurse_outline (outline, 0);
1335 fz_drop_outline (state.ctx, outline);
1339 static char *strofspan (fz_stext_span *span)
1341 char *p;
1342 char utf8[10];
1343 fz_stext_char *ch;
1344 size_t size = 0, cap = 80;
1346 p = malloc (cap + 1);
1347 if (!p) return NULL;
1349 for (ch = span->text; ch < span->text + span->len; ++ch) {
1350 int n = fz_runetochar (utf8, ch->c);
1351 if (size + n > cap) {
1352 cap *= 2;
1353 p = realloc (p, cap + 1);
1354 if (!p) return NULL;
1357 memcpy (p + size, utf8, n);
1358 size += n;
1360 p[size] = 0;
1361 return p;
1364 static int matchspan (regex_t *re, fz_stext_span *span,
1365 int stop, int pageno, double start)
1367 int ret;
1368 char *p;
1369 regmatch_t rm;
1370 int a, b, c;
1371 fz_rect sb, eb;
1372 fz_point p1, p2, p3, p4;
1374 p = strofspan (span);
1375 if (!p) return -1;
1377 ret = regexec (re, p, 1, &rm, 0);
1378 if (ret) {
1379 free (p);
1380 if (ret != REG_NOMATCH) {
1381 size_t size;
1382 char errbuf[80];
1383 size = regerror (ret, re, errbuf, sizeof (errbuf));
1384 printd ("msg regexec error `%.*s'",
1385 (int) size, errbuf);
1386 return -1;
1388 return 0;
1390 else {
1391 int l = span->len;
1393 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1394 c += fz_runelen (span->text[a].c);
1396 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1397 c += fz_runelen (span->text[b].c);
1400 if (fz_runelen (span->text[b].c) > 1) {
1401 b = MAX (0, b-1);
1404 fz_stext_char_bbox (state.ctx, &sb, span, a);
1405 fz_stext_char_bbox (state.ctx, &eb, span, b);
1407 p1.x = sb.x0;
1408 p1.y = sb.y0;
1409 p2.x = eb.x1;
1410 p2.y = sb.y0;
1411 p3.x = eb.x1;
1412 p3.y = eb.y1;
1413 p4.x = sb.x0;
1414 p4.y = eb.y1;
1416 if (!stop) {
1417 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1418 pageno, 1,
1419 p1.x, p1.y,
1420 p2.x, p2.y,
1421 p3.x, p3.y,
1422 p4.x, p4.y);
1424 printd ("progress 1 found at %d `%.*s' in %f sec",
1425 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1426 now () - start);
1428 else {
1429 printd ("match %d %d %f %f %f %f %f %f %f %f",
1430 pageno, 2,
1431 p1.x, p1.y,
1432 p2.x, p2.y,
1433 p3.x, p3.y,
1434 p4.x, p4.y);
1436 free (p);
1437 return 1;
1441 static int compareblocks (const void *l, const void *r)
1443 fz_stext_block const *ls = l;
1444 fz_stext_block const *rs = r;
1445 return ls->bbox.y0 - rs->bbox.y0;
1448 /* wishful thinking function */
1449 static void search (regex_t *re, int pageno, int y, int forward)
1451 int i, j;
1452 fz_device *tdev;
1453 fz_stext_page *text;
1454 fz_stext_sheet *sheet;
1455 struct pagedim *pdim, *pdimprev;
1456 int stop = 0, niters = 0;
1457 double start, end;
1458 fz_page *page;
1460 start = now ();
1461 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1462 if (niters++ == 5) {
1463 niters = 0;
1464 if (hasdata ()) {
1465 printd ("progress 1 attention requested aborting search at %d",
1466 pageno);
1467 stop = 1;
1469 else {
1470 printd ("progress %f searching in page %d",
1471 (double) (pageno + 1) / state.pagecount,
1472 pageno);
1475 pdimprev = NULL;
1476 for (i = 0; i < state.pagedimcount; ++i) {
1477 pdim = &state.pagedims[i];
1478 if (pdim->pageno == pageno) {
1479 goto found;
1481 if (pdim->pageno > pageno) {
1482 pdim = pdimprev;
1483 goto found;
1485 pdimprev = pdim;
1487 pdim = pdimprev;
1488 found:
1490 sheet = fz_new_stext_sheet (state.ctx);
1491 text = fz_new_stext_page (state.ctx);
1492 tdev = fz_new_stext_device (state.ctx, sheet, text);
1494 page = fz_load_page (state.ctx, state.doc, pageno);
1496 fz_matrix ctm = pagectm1 (page, pdim);
1497 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1500 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1501 fz_drop_device (state.ctx, tdev);
1503 for (j = 0; j < text->len; ++j) {
1504 int k;
1505 fz_page_block *pb;
1506 fz_stext_block *block;
1508 pb = &text->blocks[forward ? j : text->len - 1 - j];
1509 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1510 block = pb->u.text;
1512 for (k = 0; k < block->len; ++k) {
1513 fz_stext_line *line;
1514 fz_stext_span *span;
1516 if (forward) {
1517 line = &block->lines[k];
1518 if (line->bbox.y0 < y + 1) continue;
1520 else {
1521 line = &block->lines[block->len - 1 - k];
1522 if (line->bbox.y0 > y - 1) continue;
1525 for (span = line->first_span; span; span = span->next) {
1526 switch (matchspan (re, span, stop, pageno, start)) {
1527 case 0: break;
1528 case 1: stop = 1; break;
1529 case -1: stop = 1; goto endloop;
1534 if (forward) {
1535 pageno += 1;
1536 y = 0;
1538 else {
1539 pageno -= 1;
1540 y = INT_MAX;
1542 endloop:
1543 fz_drop_stext_page (state.ctx, text);
1544 fz_drop_stext_sheet (state.ctx, sheet);
1545 fz_drop_page (state.ctx, page);
1547 end = now ();
1548 if (!stop) {
1549 printd ("progress 1 no matches %f sec", end - start);
1551 printd ("clearrects");
1554 static void set_tex_params (int colorspace)
1556 union {
1557 unsigned char b;
1558 unsigned int s;
1559 } endianness = {1};
1561 switch (colorspace) {
1562 case 0:
1563 state.texiform = GL_RGBA8;
1564 state.texform = GL_RGBA;
1565 state.texty = GL_UNSIGNED_BYTE;
1566 state.colorspace = fz_device_rgb (state.ctx);
1567 break;
1568 case 1:
1569 state.texiform = GL_RGBA8;
1570 state.texform = GL_BGRA;
1571 state.texty = endianness.s > 1
1572 ? GL_UNSIGNED_INT_8_8_8_8
1573 : GL_UNSIGNED_INT_8_8_8_8_REV;
1574 state.colorspace = fz_device_bgr (state.ctx);
1575 break;
1576 case 2:
1577 state.texiform = GL_LUMINANCE_ALPHA;
1578 state.texform = GL_LUMINANCE_ALPHA;
1579 state.texty = GL_UNSIGNED_BYTE;
1580 state.colorspace = fz_device_gray (state.ctx);
1581 break;
1582 default:
1583 errx (1, "invalid colorspce %d", colorspace);
1587 static void realloctexts (int texcount)
1589 size_t size;
1591 if (texcount == state.texcount) return;
1593 if (texcount < state.texcount) {
1594 glDeleteTextures (state.texcount - texcount,
1595 state.texids + texcount);
1598 size = texcount * sizeof (*state.texids);
1599 state.texids = realloc (state.texids, size);
1600 if (!state.texids) {
1601 err (1, "realloc texids %" FMT_s, size);
1604 size = texcount * sizeof (*state.texowners);
1605 state.texowners = realloc (state.texowners, size);
1606 if (!state.texowners) {
1607 err (1, "realloc texowners %" FMT_s, size);
1609 if (texcount > state.texcount) {
1610 int i;
1612 glGenTextures (texcount - state.texcount,
1613 state.texids + state.texcount);
1614 for (i = state.texcount; i < texcount; ++i) {
1615 state.texowners[i].w = -1;
1616 state.texowners[i].slice = NULL;
1619 state.texcount = texcount;
1620 state.texindex = 0;
1623 static char *mbtoutf8 (char *s)
1625 char *p, *r;
1626 wchar_t *tmp;
1627 size_t i, ret, len;
1629 len = mbstowcs (NULL, s, strlen (s));
1630 if (len == 0) {
1631 return s;
1633 else {
1634 if (len == (size_t) -1) {
1635 return s;
1639 tmp = malloc (len * sizeof (wchar_t));
1640 if (!tmp) {
1641 return s;
1644 ret = mbstowcs (tmp, s, len);
1645 if (ret == (size_t) -1) {
1646 free (tmp);
1647 return s;
1650 len = 0;
1651 for (i = 0; i < ret; ++i) {
1652 len += fz_runelen (tmp[i]);
1655 p = r = malloc (len + 1);
1656 if (!r) {
1657 free (tmp);
1658 return s;
1661 for (i = 0; i < ret; ++i) {
1662 p += fz_runetochar (p, tmp[i]);
1664 *p = 0;
1665 free (tmp);
1666 return r;
1669 CAMLprim value ml_mbtoutf8 (value s_v)
1671 CAMLparam1 (s_v);
1672 CAMLlocal1 (ret_v);
1673 char *s, *r;
1675 s = String_val (s_v);
1676 r = mbtoutf8 (s);
1677 if (r == s) {
1678 ret_v = s_v;
1680 else {
1681 ret_v = caml_copy_string (r);
1682 free (r);
1684 CAMLreturn (ret_v);
1687 static void * mainloop (void UNUSED_ATTR *unused)
1689 char *p = NULL;
1690 int len, ret, oldlen = 0;
1692 fz_var (p);
1693 fz_var (oldlen);
1694 for (;;) {
1695 len = readlen (state.csock);
1696 if (len == 0) {
1697 errx (1, "readlen returned 0");
1700 if (oldlen < len + 1) {
1701 p = realloc (p, len + 1);
1702 if (!p) {
1703 err (1, "realloc %d failed", len + 1);
1705 oldlen = len + 1;
1707 readdata (state.csock, p, len);
1708 p[len] = 0;
1710 if (!strncmp ("open", p, 4)) {
1711 int wthack, off, ok = 0;
1712 char *password;
1713 char *filename;
1714 char *utf8filename;
1715 size_t filenamelen;
1717 fz_var (ok);
1718 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1719 if (ret != 2) {
1720 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1723 filename = p + 5 + off;
1724 filenamelen = strlen (filename);
1725 password = filename + filenamelen + 1;
1727 lock ("open");
1728 fz_try (state.ctx) {
1729 ok = openxref (filename, password);
1731 fz_catch (state.ctx) {
1732 utf8filename = mbtoutf8 (filename);
1733 printd ("msg Could not open %s", utf8filename);
1735 if (ok) {
1736 pdfinfo ();
1737 initpdims (wthack);
1739 unlock ("open");
1741 if (ok) {
1742 if (!wthack) {
1743 utf8filename = mbtoutf8 (filename);
1744 printd ("msg Opened %s (press h/F1 to get help)",
1745 utf8filename);
1746 if (utf8filename != filename) {
1747 free (utf8filename);
1750 state.needoutline = 1;
1753 else if (!strncmp ("cs", p, 2)) {
1754 int i, colorspace;
1756 ret = sscanf (p + 2, " %d", &colorspace);
1757 if (ret != 1) {
1758 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1760 lock ("cs");
1761 set_tex_params (colorspace);
1762 for (i = 0; i < state.texcount; ++i) {
1763 state.texowners[i].w = -1;
1764 state.texowners[i].slice = NULL;
1766 unlock ("cs");
1768 else if (!strncmp ("freepage", p, 8)) {
1769 void *ptr;
1771 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1772 if (ret != 1) {
1773 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1775 freepage (ptr);
1777 else if (!strncmp ("freetile", p, 8)) {
1778 void *ptr;
1780 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1781 if (ret != 1) {
1782 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1784 freetile (ptr);
1786 else if (!strncmp ("search", p, 6)) {
1787 int icase, pageno, y, len2, forward;
1788 char *pattern;
1789 regex_t re;
1791 ret = sscanf (p + 6, " %d %d %d %d,%n",
1792 &icase, &pageno, &y, &forward, &len2);
1793 if (ret != 4) {
1794 errx (1, "malformed search `%s' ret=%d", p, ret);
1797 pattern = p + 6 + len2;
1798 ret = regcomp (&re, pattern,
1799 REG_EXTENDED | (icase ? REG_ICASE : 0));
1800 if (ret) {
1801 char errbuf[80];
1802 size_t size;
1804 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1805 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1807 else {
1808 search (&re, pageno, y, forward);
1809 regfree (&re);
1812 else if (!strncmp ("geometry", p, 8)) {
1813 int w, h, fitmodel;
1815 printd ("clear");
1816 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1817 if (ret != 3) {
1818 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1821 lock ("geometry");
1822 state.h = h;
1823 if (w != state.w) {
1824 int i;
1825 state.w = w;
1826 for (i = 0; i < state.texcount; ++i) {
1827 state.texowners[i].slice = NULL;
1830 state.fitmodel = fitmodel;
1831 layout ();
1832 process_outline ();
1834 state.gen++;
1835 unlock ("geometry");
1836 printd ("continue %d", state.pagecount);
1838 else if (!strncmp ("reqlayout", p, 9)) {
1839 char *nameddest;
1840 int rotate, off, h;
1841 unsigned int fitmodel;
1842 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1844 printd ("clear");
1845 ret = sscanf (p + 9, " %d %u %d %n",
1846 &rotate, &fitmodel, &h, &off);
1847 if (ret != 3) {
1848 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1850 lock ("reqlayout");
1851 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1852 state.gen += 1;
1854 state.rotate = rotate;
1855 state.fitmodel = fitmodel;
1856 state.h = h;
1857 layout ();
1858 process_outline ();
1860 nameddest = p + 9 + off;
1861 if (pdf && nameddest && *nameddest) {
1862 struct anchor a;
1863 fz_link_dest dest;
1864 pdf_obj *needle, *obj;
1866 needle = pdf_new_string (state.ctx, pdf, nameddest,
1867 strlen (nameddest));
1868 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1869 if (obj) {
1870 dest = pdf_parse_link_dest (state.ctx, pdf,
1871 FZ_LINK_GOTO, obj);
1873 a = desttoanchor (&dest);
1874 if (a.n >= 0) {
1875 printd ("a %d %d %d", a.n, a.x, a.y);
1877 else {
1878 printd ("emsg failed to parse destination `%s'\n",
1879 nameddest);
1882 else {
1883 printd ("emsg destination `%s' not found\n",
1884 nameddest);
1886 pdf_drop_obj (state.ctx, needle);
1889 state.gen++;
1890 unlock ("reqlayout");
1891 printd ("continue %d", state.pagecount);
1893 else if (!strncmp ("page", p, 4)) {
1894 double a, b;
1895 struct page *page;
1896 int pageno, pindex;
1898 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1899 if (ret != 2) {
1900 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1903 lock ("page");
1904 a = now ();
1905 page = loadpage (pageno, pindex);
1906 b = now ();
1907 unlock ("page");
1909 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1911 else if (!strncmp ("tile", p, 4)) {
1912 int x, y, w, h;
1913 struct page *page;
1914 struct tile *tile;
1915 double a, b;
1916 void *data;
1918 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1919 SCN_ptr_cast (&page), &x, &y, &w, &h,
1920 SCN_ptr_cast (&data));
1921 if (ret != 6) {
1922 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1925 lock ("tile");
1926 a = now ();
1927 tile = rendertile (page, x, y, w, h, data);
1928 b = now ();
1929 unlock ("tile");
1931 printd ("tile %d %d %" FMT_ptr " %u %f",
1932 x, y,
1933 FMT_ptr_cast (tile),
1934 tile->w * tile->h * tile->pixmap->n,
1935 b - a);
1937 else if (!strncmp ("trimset", p, 7)) {
1938 fz_irect fuzz;
1939 int trimmargins;
1941 ret = sscanf (p + 7, " %d %d %d %d %d",
1942 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1943 if (ret != 5) {
1944 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1946 lock ("trimset");
1947 state.trimmargins = trimmargins;
1948 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1949 state.trimanew = 1;
1950 state.trimfuzz = fuzz;
1952 unlock ("trimset");
1954 else if (!strncmp ("settrim", p, 7)) {
1955 fz_irect fuzz;
1956 int trimmargins;
1958 ret = sscanf (p + 7, " %d %d %d %d %d",
1959 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1960 if (ret != 5) {
1961 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1963 printd ("clear");
1964 lock ("settrim");
1965 state.trimmargins = trimmargins;
1966 state.needoutline = 1;
1967 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1968 state.trimanew = 1;
1969 state.trimfuzz = fuzz;
1971 state.pagedimcount = 0;
1972 free (state.pagedims);
1973 state.pagedims = NULL;
1974 initpdims (0);
1975 layout ();
1976 process_outline ();
1977 unlock ("settrim");
1978 printd ("continue %d", state.pagecount);
1980 else if (!strncmp ("sliceh", p, 6)) {
1981 int h;
1983 ret = sscanf (p + 6, " %d", &h);
1984 if (ret != 1) {
1985 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1987 if (h != state.sliceheight) {
1988 int i;
1990 state.sliceheight = h;
1991 for (i = 0; i < state.texcount; ++i) {
1992 state.texowners[i].w = -1;
1993 state.texowners[i].h = -1;
1994 state.texowners[i].slice = NULL;
1998 else if (!strncmp ("interrupt", p, 9)) {
1999 printd ("vmsg interrupted");
2001 else {
2002 errx (1, "unknown command %.*s", len, p);
2005 return 0;
2008 CAMLprim value ml_realloctexts (value texcount_v)
2010 CAMLparam1 (texcount_v);
2011 int ok;
2013 if (trylock (__func__)) {
2014 ok = 0;
2015 goto done;
2017 realloctexts (Int_val (texcount_v));
2018 ok = 1;
2019 unlock (__func__);
2021 done:
2022 CAMLreturn (Val_bool (ok));
2025 static void recti (int x0, int y0, int x1, int y1)
2027 GLfloat *v = state.vertices;
2029 glVertexPointer (2, GL_FLOAT, 0, v);
2030 v[0] = x0; v[1] = y0;
2031 v[2] = x1; v[3] = y0;
2032 v[4] = x0; v[5] = y1;
2033 v[6] = x1; v[7] = y1;
2034 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2037 static void showsel (struct page *page, int ox, int oy)
2039 int seen = 0;
2040 fz_irect bbox;
2041 fz_rect rect;
2042 fz_stext_line *line;
2043 fz_page_block *pageb;
2044 fz_stext_block *block;
2045 struct mark first, last;
2046 unsigned char selcolor[] = {15,15,15,140};
2048 first = page->fmark;
2049 last = page->lmark;
2051 if (!first.span || !last.span) return;
2053 glEnable (GL_BLEND);
2054 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2055 glColor4ubv (selcolor);
2057 ox += state.pagedims[page->pdimno].bounds.x0;
2058 oy += state.pagedims[page->pdimno].bounds.y0;
2059 for (pageb = page->text->blocks;
2060 pageb < page->text->blocks + page->text->len;
2061 ++pageb) {
2062 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2063 block = pageb->u.text;
2065 for (line = block->lines;
2066 line < block->lines + block->len;
2067 ++line) {
2068 fz_stext_span *span;
2069 rect = fz_empty_rect;
2071 for (span = line->first_span; span; span = span->next) {
2072 int i, j, k;
2073 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2075 j = 0;
2076 k = span->len - 1;
2078 if (span == page->fmark.span && span == page->lmark.span) {
2079 seen = 1;
2080 j = MIN (first.i, last.i);
2081 k = MAX (first.i, last.i);
2083 else {
2084 if (span == first.span) {
2085 seen = 1;
2086 j = first.i;
2088 else if (span == last.span) {
2089 seen = 1;
2090 k = last.i;
2094 if (seen) {
2095 for (i = j; i <= k; ++i) {
2096 fz_rect bbox1;
2097 fz_union_rect (&rect,
2098 fz_stext_char_bbox (state.ctx, &bbox1,
2099 span, i));
2101 fz_round_rect (&bbox, &rect);
2102 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2103 bbox.x0,
2104 bbox.y0,
2105 bbox.x1,
2106 bbox.y1,
2107 oy, ox);
2109 recti (bbox.x0 + ox, bbox.y0 + oy,
2110 bbox.x1 + ox, bbox.y1 + oy);
2111 if (span == last.span) {
2112 goto done;
2114 rect = fz_empty_rect;
2119 done:
2120 glDisable (GL_BLEND);
2123 #include "glfont.c"
2125 static void stipplerect (fz_matrix *m,
2126 fz_point *p1,
2127 fz_point *p2,
2128 fz_point *p3,
2129 fz_point *p4,
2130 GLfloat *texcoords,
2131 GLfloat *vertices)
2133 fz_transform_point (p1, m);
2134 fz_transform_point (p2, m);
2135 fz_transform_point (p3, m);
2136 fz_transform_point (p4, m);
2138 float w, h, s, t;
2140 w = p2->x - p1->x;
2141 h = p2->y - p1->y;
2142 t = sqrtf (w*w + h*h) * .25f;
2144 w = p3->x - p2->x;
2145 h = p3->y - p2->y;
2146 s = sqrtf (w*w + h*h) * .25f;
2148 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2149 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2151 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2152 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2154 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2155 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2157 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2158 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2160 glDrawArrays (GL_LINES, 0, 8);
2163 static void solidrect (fz_matrix *m,
2164 fz_point *p1,
2165 fz_point *p2,
2166 fz_point *p3,
2167 fz_point *p4,
2168 GLfloat *vertices)
2170 fz_transform_point (p1, m);
2171 fz_transform_point (p2, m);
2172 fz_transform_point (p3, m);
2173 fz_transform_point (p4, m);
2174 vertices[0] = p1->x; vertices[1] = p1->y;
2175 vertices[2] = p2->x; vertices[3] = p2->y;
2177 vertices[4] = p3->x; vertices[5] = p3->y;
2178 vertices[6] = p4->x; vertices[7] = p4->y;
2179 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2182 static void highlightlinks (struct page *page, int xoff, int yoff)
2184 int i;
2185 fz_matrix ctm, tm, pm;
2186 fz_link *link, *links;
2187 GLfloat *texcoords = state.texcoords;
2188 GLfloat *vertices = state.vertices;
2190 links = fz_load_links (state.ctx, page->fzpage);
2192 glEnable (GL_TEXTURE_1D);
2193 glEnable (GL_BLEND);
2194 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2195 glBindTexture (GL_TEXTURE_1D, state.stid);
2197 xoff -= state.pagedims[page->pdimno].bounds.x0;
2198 yoff -= state.pagedims[page->pdimno].bounds.y0;
2199 fz_translate (&tm, xoff, yoff);
2200 pm = pagectm (page);
2201 fz_concat (&ctm, &pm, &tm);
2203 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2204 glVertexPointer (2, GL_FLOAT, 0, vertices);
2206 for (link = links; link; link = link->next) {
2207 fz_point p1, p2, p3, p4;
2209 p1.x = link->rect.x0;
2210 p1.y = link->rect.y0;
2212 p2.x = link->rect.x1;
2213 p2.y = link->rect.y0;
2215 p3.x = link->rect.x1;
2216 p3.y = link->rect.y1;
2218 p4.x = link->rect.x0;
2219 p4.y = link->rect.y1;
2221 switch (link->dest.kind) {
2222 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2223 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2224 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2225 default: glColor3ub (0, 0, 0); break;
2227 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2230 for (i = 0; i < page->annotcount; ++i) {
2231 fz_point p1, p2, p3, p4;
2232 struct annot *annot = &page->annots[i];
2234 p1.x = annot->bbox.x0;
2235 p1.y = annot->bbox.y0;
2237 p2.x = annot->bbox.x1;
2238 p2.y = annot->bbox.y0;
2240 p3.x = annot->bbox.x1;
2241 p3.y = annot->bbox.y1;
2243 p4.x = annot->bbox.x0;
2244 p4.y = annot->bbox.y1;
2246 glColor3ub (0, 0, 128);
2247 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2250 glDisable (GL_BLEND);
2251 glDisable (GL_TEXTURE_1D);
2254 static int compareslinks (const void *l, const void *r)
2256 struct slink const *ls = l;
2257 struct slink const *rs = r;
2258 if (ls->bbox.y0 == rs->bbox.y0) {
2259 return rs->bbox.x0 - rs->bbox.x0;
2261 return ls->bbox.y0 - rs->bbox.y0;
2264 static void droptext (struct page *page)
2266 if (page->text) {
2267 fz_drop_stext_page (state.ctx, page->text);
2268 page->fmark.i = -1;
2269 page->lmark.i = -1;
2270 page->fmark.span = NULL;
2271 page->lmark.span = NULL;
2272 page->text = NULL;
2274 if (page->sheet) {
2275 fz_drop_stext_sheet (state.ctx, page->sheet);
2276 page->sheet = NULL;
2280 static void dropannots (struct page *page)
2282 if (page->annots) {
2283 free (page->annots);
2284 page->annots = NULL;
2285 page->annotcount = 0;
2289 static void ensureannots (struct page *page)
2291 int i, count = 0;
2292 size_t annotsize = sizeof (*page->annots);
2293 fz_annot *annot;
2295 if (state.gen != page->agen) {
2296 dropannots (page);
2297 page->agen = state.gen;
2299 if (page->annots) return;
2301 for (annot = fz_first_annot (state.ctx, page->fzpage);
2302 annot;
2303 annot = fz_next_annot (state.ctx, annot)) {
2304 count++;
2307 if (count > 0) {
2308 page->annotcount = count;
2309 page->annots = calloc (count, annotsize);
2310 if (!page->annots) {
2311 err (1, "calloc annots %d", count);
2314 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2315 annot;
2316 annot = fz_next_annot (state.ctx, annot), i++) {
2317 fz_rect rect;
2319 fz_bound_annot (state.ctx, annot, &rect);
2320 page->annots[i].annot = annot;
2321 fz_round_rect (&page->annots[i].bbox, &rect);
2326 static void dropslinks (struct page *page)
2328 if (page->slinks) {
2329 free (page->slinks);
2330 page->slinks = NULL;
2331 page->slinkcount = 0;
2335 static void ensureslinks (struct page *page)
2337 fz_matrix ctm;
2338 int i, count;
2339 size_t slinksize = sizeof (*page->slinks);
2340 fz_link *link, *links;
2342 ensureannots (page);
2343 if (state.gen != page->sgen) {
2344 dropslinks (page);
2345 page->sgen = state.gen;
2347 if (page->slinks) return;
2349 links = fz_load_links (state.ctx, page->fzpage);
2350 ctm = pagectm (page);
2352 count = page->annotcount;
2353 for (link = links; link; link = link->next) {
2354 count++;
2356 if (count > 0) {
2357 int j;
2359 page->slinkcount = count;
2360 page->slinks = calloc (count, slinksize);
2361 if (!page->slinks) {
2362 err (1, "calloc slinks %d", count);
2365 for (i = 0, link = links; link; ++i, link = link->next) {
2366 fz_rect rect;
2368 rect = link->rect;
2369 fz_transform_rect (&rect, &ctm);
2370 page->slinks[i].tag = SLINK;
2371 page->slinks[i].u.link = link;
2372 fz_round_rect (&page->slinks[i].bbox, &rect);
2374 for (j = 0; j < page->annotcount; ++j, ++i) {
2375 fz_rect rect;
2376 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2377 fz_transform_rect (&rect, &ctm);
2378 fz_round_rect (&page->slinks[i].bbox, &rect);
2380 page->slinks[i].tag = SANNOT;
2381 page->slinks[i].u.annot = page->annots[j].annot;
2383 qsort (page->slinks, count, slinksize, compareslinks);
2387 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2388 static void fmt_linkn (char *s, unsigned int u)
2390 unsigned int len; unsigned int q;
2391 unsigned int zma = 'z' - 'a' + 1;
2392 len = 1; q = u;
2393 while (q > zma - 1) { ++len; q /= zma; }
2394 if (s) {
2395 s += len;
2396 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2397 /* handles u == 0 */
2399 s[len] = 0;
2402 static void highlightslinks (struct page *page, int xoff, int yoff,
2403 int noff, char *targ, int tlen, int hfsize)
2405 int i;
2406 char buf[40];
2407 struct slink *slink;
2408 double x0, y0, x1, y1, w;
2410 ensureslinks (page);
2411 glColor3ub (0xc3, 0xb0, 0x91);
2412 for (i = 0; i < page->slinkcount; ++i) {
2413 fmt_linkn (buf, i + noff);
2414 if (!tlen || !strncmp (targ, buf, tlen)) {
2415 slink = &page->slinks[i];
2417 x0 = slink->bbox.x0 + xoff - 5;
2418 y1 = slink->bbox.y0 + yoff - 5;
2419 y0 = y1 + 10 + hfsize;
2420 w = measure_string (state.face, hfsize, buf);
2421 x1 = x0 + w + 10;
2422 recti (x0, y0, x1, y1);
2426 glEnable (GL_BLEND);
2427 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2428 glEnable (GL_TEXTURE_2D);
2429 glColor3ub (0, 0, 0);
2430 for (i = 0; i < page->slinkcount; ++i) {
2431 fmt_linkn (buf, i + noff);
2432 if (!tlen || !strncmp (targ, buf, tlen)) {
2433 slink = &page->slinks[i];
2435 x0 = slink->bbox.x0 + xoff;
2436 y0 = slink->bbox.y0 + yoff + hfsize;
2437 draw_string (state.face, hfsize, x0, y0, buf);
2440 glDisable (GL_TEXTURE_2D);
2441 glDisable (GL_BLEND);
2444 static void uploadslice (struct tile *tile, struct slice *slice)
2446 int offset;
2447 struct slice *slice1;
2448 unsigned char *texdata;
2450 offset = 0;
2451 for (slice1 = tile->slices; slice != slice1; slice1++) {
2452 offset += slice1->h * tile->w * tile->pixmap->n;
2454 if (slice->texindex != -1 && slice->texindex < state.texcount
2455 && state.texowners[slice->texindex].slice == slice) {
2456 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2458 else {
2459 int subimage = 0;
2460 int texindex = state.texindex++ % state.texcount;
2462 if (state.texowners[texindex].w == tile->w) {
2463 if (state.texowners[texindex].h >= slice->h) {
2464 subimage = 1;
2466 else {
2467 state.texowners[texindex].h = slice->h;
2470 else {
2471 state.texowners[texindex].h = slice->h;
2474 state.texowners[texindex].w = tile->w;
2475 state.texowners[texindex].slice = slice;
2476 slice->texindex = texindex;
2478 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2479 #if TEXT_TYPE == GL_TEXTURE_2D
2480 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2481 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2482 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2483 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2484 #endif
2485 if (tile->pbo) {
2486 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2487 texdata = 0;
2489 else {
2490 texdata = tile->pixmap->samples;
2492 if (subimage) {
2493 glTexSubImage2D (TEXT_TYPE,
2497 tile->w,
2498 slice->h,
2499 state.texform,
2500 state.texty,
2501 texdata+offset
2504 else {
2505 glTexImage2D (TEXT_TYPE,
2507 state.texiform,
2508 tile->w,
2509 slice->h,
2511 state.texform,
2512 state.texty,
2513 texdata+offset
2516 if (tile->pbo) {
2517 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2522 CAMLprim value ml_begintiles (value unit_v)
2524 CAMLparam1 (unit_v);
2525 glEnable (TEXT_TYPE);
2526 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2527 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2528 CAMLreturn (unit_v);
2531 CAMLprim value ml_endtiles (value unit_v)
2533 CAMLparam1 (unit_v);
2534 glDisable (TEXT_TYPE);
2535 CAMLreturn (unit_v);
2538 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2540 CAMLparam2 (args_v, ptr_v);
2541 int dispx = Int_val (Field (args_v, 0));
2542 int dispy = Int_val (Field (args_v, 1));
2543 int dispw = Int_val (Field (args_v, 2));
2544 int disph = Int_val (Field (args_v, 3));
2545 int tilex = Int_val (Field (args_v, 4));
2546 int tiley = Int_val (Field (args_v, 5));
2547 char *s = String_val (ptr_v);
2548 struct tile *tile = parse_pointer (__func__, s);
2549 int slicey, firstslice;
2550 struct slice *slice;
2551 GLfloat *texcoords = state.texcoords;
2552 GLfloat *vertices = state.vertices;
2554 firstslice = tiley / tile->sliceheight;
2555 slice = &tile->slices[firstslice];
2556 slicey = tiley % tile->sliceheight;
2558 while (disph > 0) {
2559 int dh;
2561 dh = slice->h - slicey;
2562 dh = MIN (disph, dh);
2563 uploadslice (tile, slice);
2565 texcoords[0] = tilex; texcoords[1] = slicey;
2566 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2567 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2568 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2570 vertices[0] = dispx; vertices[1] = dispy;
2571 vertices[2] = dispx+dispw; vertices[3] = dispy;
2572 vertices[4] = dispx; vertices[5] = dispy+dh;
2573 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2575 #if TEXT_TYPE == GL_TEXTURE_2D
2576 for (int i = 0; i < 8; ++i) {
2577 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2579 #endif
2581 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2582 dispy += dh;
2583 disph -= dh;
2584 slice++;
2585 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2586 slicey = 0;
2588 CAMLreturn (Val_unit);
2591 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2593 fz_matrix ctm, tm, pm;
2594 fz_point p1, p2, p3, p4;
2595 GLfloat *vertices = state.vertices;
2596 double *v = (double *) rects_v;
2598 xoff -= state.pagedims[page->pdimno].bounds.x0;
2599 yoff -= state.pagedims[page->pdimno].bounds.y0;
2600 fz_translate (&tm, xoff, yoff);
2601 pm = pagectm (page);
2602 fz_concat (&ctm, &pm, &tm);
2604 glEnable (GL_BLEND);
2605 glVertexPointer (2, GL_FLOAT, 0, vertices);
2607 glColor4dv (v);
2608 p1.x = v[4];
2609 p1.y = v[5];
2611 p2.x = v[6];
2612 p2.y = v[5];
2614 p3.x = v[6];
2615 p3.y = v[7];
2617 p4.x = v[4];
2618 p4.y = v[7];
2619 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2620 glDisable (GL_BLEND);
2623 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2624 value xoff_v, value yoff_v,
2625 value li_v)
2627 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2628 int xoff = Int_val (xoff_v);
2629 int yoff = Int_val (yoff_v);
2630 int noff = Int_val (Field (li_v, 0));
2631 char *targ = String_val (Field (li_v, 1));
2632 int tlen = caml_string_length (Field (li_v, 1));
2633 int hfsize = Int_val (Field (li_v, 2));
2634 char *s = String_val (ptr_v);
2635 int hlmask = Int_val (hlinks_v);
2636 struct page *page = parse_pointer (__func__, s);
2638 if (!page->fzpage) {
2639 /* deal with loadpage failed pages */
2640 goto done;
2643 ensureannots (page);
2645 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2646 if (trylock (__func__)) {
2647 noff = 0;
2648 goto done;
2650 if (hlmask & 2) {
2651 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2652 noff = page->slinkcount;
2654 if (page->tgen == state.gen) {
2655 showsel (page, xoff, yoff);
2657 unlock (__func__);
2659 done:
2660 CAMLreturn (Val_int (noff));
2663 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2664 value rects_v)
2666 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2667 int xoff = Int_val (xoff_v);
2668 int yoff = Int_val (yoff_v);
2669 char *s = String_val (ptr_v);
2670 struct page *page = parse_pointer (__func__, s);
2672 drawprect (page, xoff, yoff, rects_v);
2673 CAMLreturn (Val_unit);
2676 static struct annot *getannot (struct page *page, int x, int y)
2678 int i;
2679 fz_point p;
2680 fz_matrix ctm;
2681 const fz_matrix *tctm;
2682 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2684 if (!page->annots) return NULL;
2686 if (pdf) {
2687 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2688 tctm = &state.pagedims[page->pdimno].tctm;
2690 else {
2691 tctm = &fz_identity;
2694 p.x = x;
2695 p.y = y;
2697 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2698 fz_invert_matrix (&ctm, &ctm);
2699 fz_transform_point (&p, &ctm);
2701 if (pdf) {
2702 for (i = 0; i < page->annotcount; ++i) {
2703 struct annot *a = &page->annots[i];
2704 pdf_annot *annot = (pdf_annot *) a->annot;
2705 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2706 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2707 return a;
2712 return NULL;
2715 static fz_link *getlink (struct page *page, int x, int y)
2717 fz_point p;
2718 fz_matrix ctm;
2719 fz_link *link, *links;
2721 links = fz_load_links (state.ctx, page->fzpage);
2723 p.x = x;
2724 p.y = y;
2726 fz_invert_matrix (&ctm, &state.pagedims[page->pdimno].ctm);
2727 fz_transform_point (&p, &ctm);
2729 for (link = links; link; link = link->next) {
2730 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2731 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2732 return link;
2736 return NULL;
2739 static void ensuretext (struct page *page)
2741 if (state.gen != page->tgen) {
2742 droptext (page);
2743 page->tgen = state.gen;
2745 if (!page->text) {
2746 fz_matrix ctm;
2747 fz_device *tdev;
2749 page->text = fz_new_stext_page (state.ctx);
2750 page->sheet = fz_new_stext_sheet (state.ctx);
2751 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2752 ctm = pagectm (page);
2753 fz_run_display_list (state.ctx, page->dlist,
2754 tdev, &ctm, &fz_infinite_rect, NULL);
2755 qsort (page->text->blocks, page->text->len,
2756 sizeof (*page->text->blocks), compareblocks);
2757 fz_drop_device (state.ctx, tdev);
2761 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2763 CAMLparam2 (start_page_v, dir_v);
2764 CAMLlocal1 (ret_v);
2765 int i, dir = Int_val (dir_v);
2766 int start_page = Int_val (start_page_v);
2767 int end_page = dir > 0 ? state.pagecount : -1;
2768 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2770 fz_var (end_page);
2771 ret_v = Val_int (0);
2772 lock (__func__);
2773 for (i = start_page + dir; i != end_page; i += dir) {
2774 int found;
2776 fz_var (found);
2777 if (pdf) {
2778 pdf_page *page = NULL;
2780 fz_try (state.ctx) {
2781 page = pdf_load_page (state.ctx, pdf, i);
2782 found = !!page->links || !!page->annots;
2784 fz_catch (state.ctx) {
2785 found = 0;
2787 if (page) {
2788 fz_drop_page (state.ctx, &page->super);
2791 else {
2792 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2793 found = !!fz_load_links (state.ctx, page);
2794 fz_drop_page (state.ctx, page);
2797 if (found) {
2798 ret_v = caml_alloc_small (1, 1);
2799 Field (ret_v, 0) = Val_int (i);
2800 goto unlock;
2803 unlock:
2804 unlock (__func__);
2805 CAMLreturn (ret_v);
2808 enum { dir_first, dir_last };
2809 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2811 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2813 CAMLparam2 (ptr_v, dir_v);
2814 CAMLlocal2 (ret_v, pos_v);
2815 struct page *page;
2816 int dirtag, i, slinkindex;
2817 struct slink *found = NULL ,*slink;
2818 char *s = String_val (ptr_v);
2820 page = parse_pointer (__func__, s);
2821 ret_v = Val_int (0);
2822 /* This is scary we are not taking locks here ensureslinks does
2823 not modify state and given that we obtained the page it can not
2824 disappear under us either */
2825 lock (__func__);
2826 ensureslinks (page);
2828 if (Is_block (dir_v)) {
2829 dirtag = Tag_val (dir_v);
2830 switch (dirtag) {
2831 case dir_first_visible:
2833 int x0, y0, dir, first_index, last_index;
2835 pos_v = Field (dir_v, 0);
2836 x0 = Int_val (Field (pos_v, 0));
2837 y0 = Int_val (Field (pos_v, 1));
2838 dir = Int_val (Field (pos_v, 2));
2840 if (dir >= 0) {
2841 dir = 1;
2842 first_index = 0;
2843 last_index = page->slinkcount;
2845 else {
2846 first_index = page->slinkcount - 1;
2847 last_index = -1;
2850 for (i = first_index; i != last_index; i += dir) {
2851 slink = &page->slinks[i];
2852 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2853 found = slink;
2854 break;
2858 break;
2860 case dir_left:
2861 slinkindex = Int_val (Field (dir_v, 0));
2862 found = &page->slinks[slinkindex];
2863 for (i = slinkindex - 1; i >= 0; --i) {
2864 slink = &page->slinks[i];
2865 if (slink->bbox.x0 < found->bbox.x0) {
2866 found = slink;
2867 break;
2870 break;
2872 case dir_right:
2873 slinkindex = Int_val (Field (dir_v, 0));
2874 found = &page->slinks[slinkindex];
2875 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2876 slink = &page->slinks[i];
2877 if (slink->bbox.x0 > found->bbox.x0) {
2878 found = slink;
2879 break;
2882 break;
2884 case dir_down:
2885 slinkindex = Int_val (Field (dir_v, 0));
2886 found = &page->slinks[slinkindex];
2887 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2888 slink = &page->slinks[i];
2889 if (slink->bbox.y0 >= found->bbox.y0) {
2890 found = slink;
2891 break;
2894 break;
2896 case dir_up:
2897 slinkindex = Int_val (Field (dir_v, 0));
2898 found = &page->slinks[slinkindex];
2899 for (i = slinkindex - 1; i >= 0; --i) {
2900 slink = &page->slinks[i];
2901 if (slink->bbox.y0 <= found->bbox.y0) {
2902 found = slink;
2903 break;
2906 break;
2909 else {
2910 dirtag = Int_val (dir_v);
2911 switch (dirtag) {
2912 case dir_first:
2913 found = page->slinks;
2914 break;
2916 case dir_last:
2917 if (page->slinks) {
2918 found = page->slinks + (page->slinkcount - 1);
2920 break;
2923 if (found) {
2924 ret_v = caml_alloc_small (2, 1);
2925 Field (ret_v, 0) = Val_int (found - page->slinks);
2928 unlock (__func__);
2929 CAMLreturn (ret_v);
2932 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2933 unamed, uremote, uremotedest, uannot };
2935 #define LINKTOVAL \
2937 int pageno; \
2939 switch (link->dest.kind) { \
2940 case FZ_LINK_GOTO: \
2942 fz_point p; \
2944 pageno = link->dest.ld.gotor.page; \
2945 p.x = 0; \
2946 p.y = 0; \
2948 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2949 p.y = link->dest.ld.gotor.lt.y; \
2950 fz_transform_point (&p, &pdim->lctm); \
2951 if (p.y < 0) p.y = 0; \
2953 tup_v = caml_alloc_tuple (2); \
2954 ret_v = caml_alloc_small (1, ugoto); \
2955 Field (tup_v, 0) = Val_int (pageno); \
2956 Field (tup_v, 1) = Val_int (p.y); \
2957 Field (ret_v, 0) = tup_v; \
2959 break; \
2961 case FZ_LINK_URI: \
2962 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2963 ret_v = caml_alloc_small (1, uuri); \
2964 Field (ret_v, 0) = str_v; \
2965 break; \
2967 case FZ_LINK_LAUNCH: \
2968 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2969 ret_v = caml_alloc_small (1, ulaunch); \
2970 Field (ret_v, 0) = str_v; \
2971 break; \
2973 case FZ_LINK_NAMED: \
2974 str_v = caml_copy_string (link->dest.ld.named.named); \
2975 ret_v = caml_alloc_small (1, unamed); \
2976 Field (ret_v, 0) = str_v; \
2977 break; \
2979 case FZ_LINK_GOTOR: \
2981 int rty; \
2983 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2984 pageno = link->dest.ld.gotor.page; \
2985 if (pageno == -1) { \
2986 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2987 rty = uremotedest; \
2989 else { \
2990 gr_v = Val_int (pageno); \
2991 rty = uremote; \
2993 tup_v = caml_alloc_tuple (2); \
2994 ret_v = caml_alloc_small (1, rty); \
2995 Field (tup_v, 0) = str_v; \
2996 Field (tup_v, 1) = gr_v; \
2997 Field (ret_v, 0) = tup_v; \
2999 break; \
3001 default: \
3003 char buf[80]; \
3005 snprintf (buf, sizeof (buf), \
3006 "unhandled link kind %d", link->dest.kind); \
3007 str_v = caml_copy_string (buf); \
3008 ret_v = caml_alloc_small (1, uunexpected); \
3009 Field (ret_v, 0) = str_v; \
3011 break; \
3015 CAMLprim value ml_getlink (value ptr_v, value n_v)
3017 CAMLparam2 (ptr_v, n_v);
3018 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3019 fz_link *link;
3020 struct page *page;
3021 struct pagedim *pdim;
3022 char *s = String_val (ptr_v);
3023 struct slink *slink;
3025 /* See ml_findlink for caveat */
3027 ret_v = Val_int (0);
3028 page = parse_pointer (__func__, s);
3029 ensureslinks (page);
3030 pdim = &state.pagedims[page->pdimno];
3031 slink = &page->slinks[Int_val (n_v)];
3032 if (slink->tag == SLINK) {
3033 link = slink->u.link;
3034 LINKTOVAL;
3036 else {
3037 ret_v = caml_alloc_small (1, uannot);
3038 tup_v = caml_alloc_tuple (2);
3039 Field (ret_v, 0) = tup_v;
3040 Field (tup_v, 0) = ptr_v;
3041 Field (tup_v, 1) = n_v;
3044 CAMLreturn (ret_v);
3047 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3049 CAMLparam2 (ptr_v, n_v);
3050 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3051 if (pdf) {
3052 char *s = String_val (ptr_v);
3053 struct page *page;
3054 struct slink *slink;
3056 page = parse_pointer (__func__, s);
3057 slink = &page->slinks[Int_val (n_v)];
3058 CAMLreturn (caml_copy_string (
3059 pdf_annot_contents (state.ctx, pdf,
3060 (pdf_annot *) slink->u.annot)));
3062 else {
3063 CAMLreturn (caml_copy_string (""));
3067 CAMLprim value ml_getlinkcount (value ptr_v)
3069 CAMLparam1 (ptr_v);
3070 struct page *page;
3071 char *s = String_val (ptr_v);
3073 page = parse_pointer (__func__, s);
3074 CAMLreturn (Val_int (page->slinkcount));
3077 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3079 CAMLparam2 (ptr_v, n_v);
3080 CAMLlocal1 (ret_v);
3081 struct page *page;
3082 struct slink *slink;
3083 char *s = String_val (ptr_v);
3084 /* See ml_findlink for caveat */
3086 page = parse_pointer (__func__, s);
3087 ret_v = caml_alloc_tuple (4);
3088 ensureslinks (page);
3090 slink = &page->slinks[Int_val (n_v)];
3091 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3092 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3093 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3094 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3095 unlock (__func__);
3096 CAMLreturn (ret_v);
3099 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3101 CAMLparam3 (ptr_v, x_v, y_v);
3102 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3103 fz_link *link;
3104 struct annot *annot;
3105 struct page *page;
3106 char *ptr = String_val (ptr_v);
3107 int x = Int_val (x_v), y = Int_val (y_v);
3108 struct pagedim *pdim;
3110 ret_v = Val_int (0);
3111 if (trylock (__func__)) {
3112 goto done;
3115 page = parse_pointer (__func__, ptr);
3116 pdim = &state.pagedims[page->pdimno];
3117 x += pdim->bounds.x0;
3118 y += pdim->bounds.y0;
3121 annot = getannot (page, x, y);
3122 if (annot) {
3123 int i, n = -1;
3125 ensureslinks (page);
3126 for (i = 0; i < page->slinkcount; ++i) {
3127 if (page->slinks[i].tag == SANNOT
3128 && page->slinks[i].u.annot == annot->annot) {
3129 n = i;
3130 break;
3133 ret_v = caml_alloc_small (1, uannot);
3134 tup_v = caml_alloc_tuple (2);
3135 Field (ret_v, 0) = tup_v;
3136 Field (tup_v, 0) = ptr_v;
3137 Field (tup_v, 1) = Val_int (n);
3138 goto unlock;
3142 link = getlink (page, x, y);
3143 if (link) {
3144 LINKTOVAL;
3146 else {
3147 fz_rect *b;
3148 fz_page_block *pageb;
3149 fz_stext_block *block;
3151 ensuretext (page);
3152 for (pageb = page->text->blocks;
3153 pageb < page->text->blocks + page->text->len;
3154 ++pageb) {
3155 fz_stext_line *line;
3156 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3157 block = pageb->u.text;
3159 b = &block->bbox;
3160 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3161 continue;
3163 for (line = block->lines;
3164 line < block->lines + block->len;
3165 ++line) {
3166 fz_stext_span *span;
3168 b = &line->bbox;
3169 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3170 continue;
3172 for (span = line->first_span; span; span = span->next) {
3173 int charnum;
3175 b = &span->bbox;
3176 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3177 continue;
3179 for (charnum = 0; charnum < span->len; ++charnum) {
3180 fz_rect bbox;
3181 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3182 b = &bbox;
3184 if (x >= b->x0 && x <= b->x1
3185 && y >= b->y0 && y <= b->y1) {
3186 fz_stext_style *style = span->text->style;
3187 const char *n2 =
3188 style->font
3189 ? style->font->name
3190 : "Span has no font name"
3192 FT_FaceRec *face = style->font->ft_face;
3193 if (face && face->family_name) {
3194 char *s;
3195 char *n1 = face->family_name;
3196 size_t l1 = strlen (n1);
3197 size_t l2 = strlen (n2);
3199 if (l1 != l2 || memcmp (n1, n2, l1)) {
3200 s = malloc (l1 + l2 + 2);
3201 if (s) {
3202 memcpy (s, n2, l2);
3203 s[l2] = '=';
3204 memcpy (s + l2 + 1, n1, l1 + 1);
3205 str_v = caml_copy_string (s);
3206 free (s);
3210 if (str_v == Val_unit) {
3211 str_v = caml_copy_string (n2);
3213 ret_v = caml_alloc_small (1, utext);
3214 Field (ret_v, 0) = str_v;
3215 goto unlock;
3222 unlock:
3223 unlock (__func__);
3225 done:
3226 CAMLreturn (ret_v);
3229 enum { mark_page, mark_block, mark_line, mark_word };
3231 static int uninteresting (int c)
3233 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3234 || ispunct (c);
3237 CAMLprim value ml_clearmark (value ptr_v)
3239 CAMLparam1 (ptr_v);
3240 char *s = String_val (ptr_v);
3241 struct page *page;
3243 if (trylock (__func__)) {
3244 goto done;
3247 page = parse_pointer (__func__, s);
3248 page->fmark.span = NULL;
3249 page->lmark.span = NULL;
3250 page->fmark.i = 0;
3251 page->lmark.i = 0;
3253 unlock (__func__);
3254 done:
3255 CAMLreturn (Val_unit);
3258 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3260 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3261 CAMLlocal1 (ret_v);
3262 fz_rect *b;
3263 struct page *page;
3264 fz_stext_line *line;
3265 fz_page_block *pageb;
3266 fz_stext_block *block;
3267 struct pagedim *pdim;
3268 int mark = Int_val (mark_v);
3269 char *s = String_val (ptr_v);
3270 int x = Int_val (x_v), y = Int_val (y_v);
3272 ret_v = Val_bool (0);
3273 if (trylock (__func__)) {
3274 goto done;
3277 page = parse_pointer (__func__, s);
3278 pdim = &state.pagedims[page->pdimno];
3280 ensuretext (page);
3282 if (mark == mark_page) {
3283 int i;
3284 fz_page_block *pb1 = NULL, *pb2 = NULL;
3286 for (i = 0; i < page->text->len; ++i) {
3287 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3288 pb1 = &page->text->blocks[i];
3289 break;
3292 if (!pb1) goto unlock;
3294 for (i = page->text->len - 1; i >= 0; --i) {
3295 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3296 pb2 = &page->text->blocks[i];
3297 break;
3300 if (!pb2) goto unlock;
3302 block = pb1->u.text;
3304 page->fmark.i = 0;
3305 page->fmark.span = block->lines->first_span;
3307 block = pb2->u.text;
3308 line = &block->lines[block->len - 1];
3309 page->lmark.i = line->last_span->len - 1;
3310 page->lmark.span = line->last_span;
3311 ret_v = Val_bool (1);
3312 goto unlock;
3315 x += pdim->bounds.x0;
3316 y += pdim->bounds.y0;
3318 for (pageb = page->text->blocks;
3319 pageb < page->text->blocks + page->text->len;
3320 ++pageb) {
3321 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3322 block = pageb->u.text;
3324 b = &block->bbox;
3325 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3326 continue;
3328 if (mark == mark_block) {
3329 page->fmark.i = 0;
3330 page->fmark.span = block->lines->first_span;
3332 line = &block->lines[block->len - 1];
3333 page->lmark.i = line->last_span->len - 1;
3334 page->lmark.span = line->last_span;
3335 ret_v = Val_bool (1);
3336 goto unlock;
3339 for (line = block->lines;
3340 line < block->lines + block->len;
3341 ++line) {
3342 fz_stext_span *span;
3344 b = &line->bbox;
3345 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3346 continue;
3348 if (mark == mark_line) {
3349 page->fmark.i = 0;
3350 page->fmark.span = line->first_span;
3352 page->lmark.i = line->last_span->len - 1;
3353 page->lmark.span = line->last_span;
3354 ret_v = Val_bool (1);
3355 goto unlock;
3358 for (span = line->first_span; span; span = span->next) {
3359 int charnum;
3361 b = &span->bbox;
3362 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3363 continue;
3365 for (charnum = 0; charnum < span->len; ++charnum) {
3366 fz_rect bbox;
3367 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3368 b = &bbox;
3370 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3371 /* unicode ftw */
3372 int charnum2, charnum3 = -1, charnum4 = -1;
3374 if (uninteresting (span->text[charnum].c)) goto unlock;
3376 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3377 if (uninteresting (span->text[charnum2].c)) {
3378 charnum3 = charnum2 + 1;
3379 break;
3382 if (charnum3 == -1) charnum3 = 0;
3384 charnum4 = charnum;
3385 for (charnum2 = charnum + 1;
3386 charnum2 < span->len;
3387 ++charnum2) {
3388 if (uninteresting (span->text[charnum2].c)) break;
3389 charnum4 = charnum2;
3392 page->fmark.i = charnum3;
3393 page->fmark.span = span;
3395 page->lmark.i = charnum4;
3396 page->lmark.span = span;
3397 ret_v = Val_bool (1);
3398 goto unlock;
3404 unlock:
3405 if (!Bool_val (ret_v)) {
3406 page->fmark.span = NULL;
3407 page->lmark.span = NULL;
3408 page->fmark.i = 0;
3409 page->lmark.i = 0;
3411 unlock (__func__);
3413 done:
3414 CAMLreturn (ret_v);
3417 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3419 CAMLparam3 (ptr_v, x_v, y_v);
3420 CAMLlocal2 (ret_v, res_v);
3421 fz_rect *b = NULL;
3422 struct page *page;
3423 fz_page_block *pageb;
3424 struct pagedim *pdim;
3425 char *s = String_val (ptr_v);
3426 int x = Int_val (x_v), y = Int_val (y_v);
3428 ret_v = Val_int (0);
3429 if (trylock (__func__)) {
3430 goto done;
3433 page = parse_pointer (__func__, s);
3434 pdim = &state.pagedims[page->pdimno];
3435 x += pdim->bounds.x0;
3436 y += pdim->bounds.y0;
3438 ensuretext (page);
3440 for (pageb = page->text->blocks;
3441 pageb < page->text->blocks + page->text->len;
3442 ++pageb) {
3443 switch (pageb->type) {
3444 case FZ_PAGE_BLOCK_TEXT:
3445 b = &pageb->u.text->bbox;
3446 break;
3448 case FZ_PAGE_BLOCK_IMAGE:
3449 b = &pageb->u.image->bbox;
3450 break;
3452 default:
3453 continue;
3456 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3457 break;
3458 b = NULL;
3460 if (b) {
3461 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3462 ret_v = caml_alloc_small (1, 1);
3463 Store_double_field (res_v, 0, b->x0);
3464 Store_double_field (res_v, 1, b->x1);
3465 Store_double_field (res_v, 2, b->y0);
3466 Store_double_field (res_v, 3, b->y1);
3467 Field (ret_v, 0) = res_v;
3469 unlock (__func__);
3471 done:
3472 CAMLreturn (ret_v);
3475 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3477 CAMLparam2 (ptr_v, rect_v);
3478 fz_rect b;
3479 struct page *page;
3480 struct pagedim *pdim;
3481 char *s = String_val (ptr_v);
3482 int i, x0, x1, y0, y1, fi, li;
3483 fz_stext_line *line;
3484 fz_page_block *pageb;
3485 fz_stext_block *block;
3486 fz_stext_span *span, *fspan, *lspan;
3488 if (trylock (__func__)) {
3489 goto done;
3492 page = parse_pointer (__func__, s);
3493 ensuretext (page);
3495 pdim = &state.pagedims[page->pdimno];
3496 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3497 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3498 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3499 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3501 if (y0 > y1) {
3502 int t = y0;
3503 y0 = y1;
3504 y1 = t;
3505 x0 = x1;
3506 x1 = t;
3509 fi = page->fmark.i;
3510 fspan = page->fmark.span;
3512 li = page->lmark.i;
3513 lspan = page->lmark.span;
3515 for (pageb = page->text->blocks;
3516 pageb < page->text->blocks + page->text->len;
3517 ++pageb) {
3518 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3519 block = pageb->u.text;
3520 for (line = block->lines;
3521 line < block->lines + block->len;
3522 ++line) {
3524 for (span = line->first_span; span; span = span->next) {
3525 for (i = 0; i < span->len; ++i) {
3526 fz_stext_char_bbox (state.ctx, &b, span, i);
3528 if (x0 >= b.x0 && x0 <= b.x1
3529 && y0 >= b.y0 && y0 <= b.y1) {
3530 fspan = span;
3531 fi = i;
3533 if (x1 >= b.x0 && x1 <= b.x1
3534 && y1 >= b.y0 && y1 <= b.y1) {
3535 lspan = span;
3536 li = i;
3542 if (x1 < x0 && fspan == lspan) {
3543 i = fi;
3544 span = fspan;
3546 fi = li;
3547 fspan = lspan;
3549 li = i;
3550 lspan = span;
3553 page->fmark.i = fi;
3554 page->fmark.span = fspan;
3556 page->lmark.i = li;
3557 page->lmark.span = lspan;
3559 unlock (__func__);
3561 done:
3562 CAMLreturn (Val_unit);
3565 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3567 char buf[4];
3568 int i, len, ret;
3570 for (i = a; i <= b; ++i) {
3571 len = fz_runetochar (buf, span->text[i].c);
3572 ret = fwrite (buf, len, 1, f);
3574 if (ret != 1) {
3575 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3576 len, ret, strerror (errno));
3577 return -1;
3580 return 0;
3583 #ifdef __CYGWIN__
3584 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3586 caml_failwith ("ml_popen not implemented under Cygwin");
3588 #else
3589 CAMLprim value ml_spawn (value command_v, value fds_v)
3591 CAMLparam2 (command_v, fds_v);
3592 CAMLlocal2 (l_v, tup_v);
3593 int ret, ret1;
3594 pid_t pid;
3595 char *msg = NULL;
3596 value earg_v = Nothing;
3597 posix_spawnattr_t attr;
3598 posix_spawn_file_actions_t fa;
3599 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3601 argv[2] = String_val (command_v);
3603 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3604 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3607 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3608 msg = "posix_spawnattr_init";
3609 goto fail1;
3612 #ifdef POSIX_SPAWN_USEVFORK
3613 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3614 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3615 goto fail;
3617 #endif
3619 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3620 int fd1, fd2;
3622 tup_v = Field (l_v, 0);
3623 fd1 = Int_val (Field (tup_v, 0));
3624 fd2 = Int_val (Field (tup_v, 1));
3625 if (fd2 < 0) {
3626 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3627 msg = "posix_spawn_file_actions_addclose";
3628 earg_v = tup_v;
3629 goto fail;
3632 else {
3633 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3634 msg = "posix_spawn_file_actions_adddup2";
3635 earg_v = tup_v;
3636 goto fail;
3641 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3642 msg = "posix_spawn";
3643 goto fail;
3646 fail:
3647 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3648 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3651 fail1:
3652 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3653 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3654 strerror (ret1));
3657 if (msg)
3658 unix_error (ret, msg, earg_v);
3660 CAMLreturn (Val_int (pid));
3662 #endif
3664 CAMLprim value ml_hassel (value ptr_v)
3666 CAMLparam1 (ptr_v);
3667 CAMLlocal1 (ret_v);
3668 struct page *page;
3669 char *s = String_val (ptr_v);
3671 ret_v = Val_bool (0);
3672 if (trylock (__func__)) {
3673 goto done;
3676 page = parse_pointer (__func__, s);
3677 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3678 unlock (__func__);
3679 done:
3680 CAMLreturn (ret_v);
3683 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3685 CAMLparam2 (fd_v, ptr_v);
3686 FILE *f;
3687 int seen = 0;
3688 struct page *page;
3689 fz_stext_line *line;
3690 fz_page_block *pageb;
3691 fz_stext_block *block;
3692 int fd = Int_val (fd_v);
3693 char *s = String_val (ptr_v);
3695 if (trylock (__func__)) {
3696 goto done;
3699 page = parse_pointer (__func__, s);
3701 if (!page->fmark.span || !page->lmark.span) {
3702 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3703 goto unlock;
3706 f = fdopen (fd, "w");
3707 if (!f) {
3708 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3709 fd, strerror (errno));
3710 f = stdout;
3713 for (pageb = page->text->blocks;
3714 pageb < page->text->blocks + page->text->len;
3715 ++pageb) {
3716 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3717 block = pageb->u.text;
3718 for (line = block->lines;
3719 line < block->lines + block->len;
3720 ++line) {
3721 fz_stext_span *span;
3723 for (span = line->first_span; span; span = span->next) {
3724 int a, b;
3726 seen |= span == page->fmark.span || span == page->lmark.span;
3727 a = span == page->fmark.span ? page->fmark.i : 0;
3728 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3730 if (seen) {
3731 if (pipespan (f, span, a, b)) {
3732 goto close;
3734 if (span == page->lmark.span) {
3735 goto close;
3737 if (span == line->last_span) {
3738 if (putc ('\n', f) == EOF) {
3739 fprintf (stderr,
3740 "failed break line on sel pipe: %s\n",
3741 strerror (errno));
3742 goto close;
3749 close:
3750 if (f != stdout) {
3751 int ret = fclose (f);
3752 fd = -1;
3753 if (ret == -1) {
3754 if (errno != ECHILD) {
3755 fprintf (stderr, "failed to close sel pipe: %s\n",
3756 strerror (errno));
3760 unlock:
3761 unlock (__func__);
3763 done:
3764 if (fd >= 0) {
3765 if (close (fd)) {
3766 fprintf (stderr, "failed to close sel pipe: %s\n",
3767 strerror (errno));
3770 CAMLreturn (Val_unit);
3773 CAMLprim value ml_getpdimrect (value pagedimno_v)
3775 CAMLparam1 (pagedimno_v);
3776 CAMLlocal1 (ret_v);
3777 int pagedimno = Int_val (pagedimno_v);
3778 fz_rect box;
3780 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3781 if (trylock (__func__)) {
3782 box = fz_empty_rect;
3784 else {
3785 box = state.pagedims[pagedimno].mediabox;
3786 unlock (__func__);
3789 Store_double_field (ret_v, 0, box.x0);
3790 Store_double_field (ret_v, 1, box.x1);
3791 Store_double_field (ret_v, 2, box.y0);
3792 Store_double_field (ret_v, 3, box.y1);
3794 CAMLreturn (ret_v);
3797 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3798 value dw_v, value cols_v)
3800 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3801 CAMLlocal1 (ret_v);
3802 int i;
3803 double zoom = -1.;
3804 double maxh = 0.0;
3805 struct pagedim *p;
3806 double winw = Int_val (winw_v);
3807 double winh = Int_val (winh_v);
3808 double dw = Int_val (dw_v);
3809 double cols = Int_val (cols_v);
3810 double pw = 1.0, ph = 1.0;
3812 if (trylock (__func__)) {
3813 goto done;
3816 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3817 double w = p->pagebox.x1 / cols;
3818 double h = p->pagebox.y1;
3819 if (h > maxh) {
3820 maxh = h;
3821 ph = h;
3822 if (state.fitmodel != FitProportional) pw = w;
3824 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3827 zoom = (((winh / ph) * pw) + dw) / winw;
3828 unlock (__func__);
3829 done:
3830 ret_v = caml_copy_double (zoom);
3831 CAMLreturn (ret_v);
3834 CAMLprim value ml_getmaxw (value unit_v)
3836 CAMLparam1 (unit_v);
3837 CAMLlocal1 (ret_v);
3838 int i;
3839 double maxw = -1.;
3840 struct pagedim *p;
3842 if (trylock (__func__)) {
3843 goto done;
3846 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3847 double w = p->pagebox.x1;
3848 maxw = MAX (maxw, w);
3851 unlock (__func__);
3852 done:
3853 ret_v = caml_copy_double (maxw);
3854 CAMLreturn (ret_v);
3857 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3859 CAMLparam4 (pt_v, x_v, y_v, string_v);
3860 CAMLlocal1 (ret_v);
3861 int pt = Int_val(pt_v);
3862 int x = Int_val (x_v);
3863 int y = Int_val (y_v);
3864 double w;
3866 w = draw_string (state.face, pt, x, y, String_val (string_v));
3867 ret_v = caml_copy_double (w);
3868 CAMLreturn (ret_v);
3871 CAMLprim value ml_measure_string (value pt_v, value string_v)
3873 CAMLparam2 (pt_v, string_v);
3874 CAMLlocal1 (ret_v);
3875 int pt = Int_val (pt_v);
3876 double w;
3878 w = measure_string (state.face, pt, String_val (string_v));
3879 ret_v = caml_copy_double (w);
3880 CAMLreturn (ret_v);
3883 CAMLprim value ml_getpagebox (value opaque_v)
3885 CAMLparam1 (opaque_v);
3886 CAMLlocal1 (ret_v);
3887 fz_rect rect;
3888 fz_irect bbox;
3889 fz_matrix ctm;
3890 fz_device *dev;
3891 char *s = String_val (opaque_v);
3892 struct page *page = parse_pointer (__func__, s);
3894 ret_v = caml_alloc_tuple (4);
3895 dev = fz_new_bbox_device (state.ctx, &rect);
3896 dev->hints |= FZ_IGNORE_SHADE;
3898 ctm = pagectm (page);
3899 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3901 fz_drop_device (state.ctx, dev);
3902 fz_round_rect (&bbox, &rect);
3903 Field (ret_v, 0) = Val_int (bbox.x0);
3904 Field (ret_v, 1) = Val_int (bbox.y0);
3905 Field (ret_v, 2) = Val_int (bbox.x1);
3906 Field (ret_v, 3) = Val_int (bbox.y1);
3908 CAMLreturn (ret_v);
3911 CAMLprim value ml_setaalevel (value level_v)
3913 CAMLparam1 (level_v);
3915 state.aalevel = Int_val (level_v);
3916 CAMLreturn (Val_unit);
3919 #pragma GCC diagnostic push
3920 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3921 #include <X11/Xlib.h>
3922 #include <X11/cursorfont.h>
3923 #pragma GCC diagnostic pop
3925 #ifdef USE_EGL
3926 #include <EGL/egl.h>
3927 #else
3928 #include <GL/glx.h>
3929 #endif
3931 static const int shapes[] = {
3932 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3935 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3937 static struct {
3938 Window wid;
3939 Display *dpy;
3940 #ifdef USE_EGL
3941 EGLContext ctx;
3942 EGLConfig conf;
3943 EGLSurface win;
3944 EGLDisplay *edpy;
3945 #else
3946 GLXContext ctx;
3947 #endif
3948 XVisualInfo *visual;
3949 Cursor curs[CURS_COUNT];
3950 } glx;
3952 #ifdef VISAVIS
3953 static VisualID initvisual (void)
3955 /* On this system with: `Haswell-ULT Integrated Graphics
3956 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3957 using glX chosen visual and auto scrolling some document in
3958 fullscreen the power/energy-gpu is more than 1 joule bigger
3959 than when using hand picked visual that stands alone in glxinfo
3960 output: it's dead last in the list and it's the only one with
3961 `visual dep' (sic) of 32
3963 No clue what's going on here...
3965 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3967 XVisualInfo info;
3968 int ret = 1;
3970 info.depth = 32;
3971 info.class = TrueColor;
3972 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3973 &info, &ret);
3974 if (!ret || !glx.visual) {
3975 XCloseDisplay (glx.dpy);
3976 caml_failwith ("XGetVisualInfo");
3978 return glx.visual->visualid;
3980 #endif
3982 static void initcurs (void)
3984 for (size_t n = 0; n < CURS_COUNT; ++n) {
3985 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3989 CAMLprim void ml_setbgcol (value color_v)
3991 CAMLparam1 (color_v);
3992 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3993 CAMLreturn0;
3996 #ifdef USE_EGL
3997 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3999 CAMLparam3 (display_v, wid_v, screen_v);
4000 int major, minor;
4001 int num_conf;
4002 EGLint visid;
4003 EGLint attribs[] = {
4004 #ifdef VISAVIS
4005 EGL_NATIVE_VISUAL_ID, 0,
4006 #else
4007 EGL_DEPTH_SIZE, 24,
4008 #endif
4009 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
4010 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
4011 EGL_NONE
4013 EGLConfig conf;
4015 glx.dpy = XOpenDisplay (String_val (display_v));
4016 if (!glx.dpy) {
4017 caml_failwith ("XOpenDisplay");
4020 eglBindAPI (EGL_OPENGL_API);
4022 glx.edpy = eglGetDisplay (glx.dpy);
4023 if (glx.dpy == EGL_NO_DISPLAY) {
4024 caml_failwith ("eglGetDisplay");
4027 if (!eglInitialize (glx.edpy, &major, &minor)) {
4028 caml_failwith ("eglInitialize");
4031 #ifdef VISAVIS
4032 attribs[1] = visid = initvisual ();
4033 #endif
4035 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4036 !num_conf) {
4037 caml_failwith ("eglChooseConfig");
4040 glx.conf = conf;
4041 #ifndef VISAVIS
4042 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4043 EGL_NATIVE_VISUAL_ID, &visid)) {
4044 caml_failwith ("eglGetConfigAttrib");
4046 #endif
4047 initcurs ();
4049 glx.wid = Int_val (wid_v);
4050 CAMLreturn (Val_int (visid));
4053 CAMLprim value ml_glxcompleteinit (value unit_v)
4055 CAMLparam1 (unit_v);
4057 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4058 if (!glx.ctx) {
4059 caml_failwith ("eglCreateContext");
4062 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4063 glx.wid, NULL);
4064 if (glx.win == EGL_NO_SURFACE) {
4065 caml_failwith ("eglCreateWindowSurface");
4068 XFree (glx.visual);
4069 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4070 glx.ctx = NULL;
4071 caml_failwith ("eglMakeCurrent");
4073 CAMLreturn (Val_unit);
4075 #else
4076 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4078 CAMLparam3 (display_v, wid_v, screen_v);
4080 glx.dpy = XOpenDisplay (String_val (display_v));
4081 if (!glx.dpy) {
4082 caml_failwith ("XOpenDisplay");
4085 #ifdef VISAVIS
4086 initvisual ();
4087 #else
4088 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4089 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4090 if (!glx.visual) {
4091 XCloseDisplay (glx.dpy);
4092 caml_failwith ("glXChooseVisual");
4094 #endif
4095 initcurs ();
4097 glx.wid = Int_val (wid_v);
4098 CAMLreturn (Val_int (glx.visual->visualid));
4101 CAMLprim value ml_glxcompleteinit (value unit_v)
4103 CAMLparam1 (unit_v);
4105 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4106 if (!glx.ctx) {
4107 caml_failwith ("glXCreateContext");
4110 XFree (glx.visual);
4111 glx.visual = NULL;
4113 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4114 glXDestroyContext (glx.dpy, glx.ctx);
4115 glx.ctx = NULL;
4116 caml_failwith ("glXMakeCurrent");
4118 CAMLreturn (Val_unit);
4120 #endif
4122 CAMLprim value ml_setcursor (value cursor_v)
4124 CAMLparam1 (cursor_v);
4125 size_t cursn = Int_val (cursor_v);
4127 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4128 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4129 XFlush (glx.dpy);
4130 CAMLreturn (Val_unit);
4133 CAMLprim value ml_swapb (value unit_v)
4135 CAMLparam1 (unit_v);
4136 #ifdef USE_EGL
4137 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4138 caml_failwith ("eglSwapBuffers");
4140 #else
4141 glXSwapBuffers (glx.dpy, glx.wid);
4142 #endif
4143 CAMLreturn (Val_unit);
4146 #include "keysym2ucs.c"
4148 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4150 CAMLparam1 (keysym_v);
4151 CAMLlocal1 (str_v);
4152 KeySym keysym = Int_val (keysym_v);
4153 Rune rune;
4154 int len;
4155 char buf[5];
4157 rune = keysym2ucs (keysym);
4158 len = fz_runetochar (buf, rune);
4159 buf[len] = 0;
4160 str_v = caml_copy_string (buf);
4161 CAMLreturn (str_v);
4164 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4166 CAMLprim value ml_platform (value unit_v)
4168 CAMLparam1 (unit_v);
4169 CAMLlocal2 (tup_v, arr_v);
4170 int platid = piunknown;
4171 struct utsname buf;
4173 #if defined __linux__
4174 platid = pilinux;
4175 #elif defined __CYGWIN__
4176 platid = picygwin;
4177 #elif defined __DragonFly__ || defined __FreeBSD__
4178 || defined __OpenBSD__ || defined __NetBSD__
4179 platid = pibsd;
4180 #elif defined __sun__
4181 platid = pisun;
4182 #elif defined __APPLE__
4183 platid = piosx;
4184 #endif
4185 if (uname (&buf)) err (1, "uname");
4187 tup_v = caml_alloc_tuple (2);
4189 char const *sar[] = {
4190 buf.sysname,
4191 buf.release,
4192 buf.version,
4193 buf.machine,
4194 NULL
4196 arr_v = caml_copy_string_array (sar);
4198 Field (tup_v, 0) = Val_int (platid);
4199 Field (tup_v, 1) = arr_v;
4200 CAMLreturn (tup_v);
4203 CAMLprim value ml_cloexec (value fd_v)
4205 CAMLparam1 (fd_v);
4206 int fd = Int_val (fd_v);
4208 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4209 uerror ("fcntl", Nothing);
4211 CAMLreturn (Val_unit);
4214 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4216 CAMLparam2 (w_v, h_v);
4217 CAMLlocal1 (ret_v);
4218 struct bo *pbo;
4219 int w = Int_val (w_v);
4220 int h = Int_val (h_v);
4221 int cs = Int_val (cs_v);
4223 if (state.bo_usable) {
4224 pbo = calloc (sizeof (*pbo), 1);
4225 if (!pbo) {
4226 err (1, "calloc pbo");
4229 switch (cs) {
4230 case 0:
4231 case 1:
4232 pbo->size = w*h*4;
4233 break;
4234 case 2:
4235 pbo->size = w*h*2;
4236 break;
4237 default:
4238 errx (1, "%s: invalid colorspace %d", __func__, cs);
4241 state.glGenBuffersARB (1, &pbo->id);
4242 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4243 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4244 NULL, GL_STREAM_DRAW);
4245 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4246 GL_READ_WRITE);
4247 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4248 if (!pbo->ptr) {
4249 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4250 state.glDeleteBuffersARB (1, &pbo->id);
4251 free (pbo);
4252 ret_v = caml_copy_string ("0");
4254 else {
4255 int res;
4256 char *s;
4258 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4259 if (res < 0) {
4260 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4262 s = malloc (res+1);
4263 if (!s) {
4264 err (1, "malloc %d bytes failed", res+1);
4266 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4267 if (res < 0) {
4268 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4270 ret_v = caml_copy_string (s);
4271 free (s);
4274 else {
4275 ret_v = caml_copy_string ("0");
4277 CAMLreturn (ret_v);
4280 CAMLprim value ml_freepbo (value s_v)
4282 CAMLparam1 (s_v);
4283 char *s = String_val (s_v);
4284 struct tile *tile = parse_pointer (__func__, s);
4286 if (tile->pbo) {
4287 state.glDeleteBuffersARB (1, &tile->pbo->id);
4288 tile->pbo->id = -1;
4289 tile->pbo->ptr = NULL;
4290 tile->pbo->size = -1;
4292 CAMLreturn (Val_unit);
4295 CAMLprim value ml_unmappbo (value s_v)
4297 CAMLparam1 (s_v);
4298 char *s = String_val (s_v);
4299 struct tile *tile = parse_pointer (__func__, s);
4301 if (tile->pbo) {
4302 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4303 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4304 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4306 tile->pbo->ptr = NULL;
4307 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4309 CAMLreturn (Val_unit);
4312 static void setuppbo (void)
4314 #ifdef USE_EGL
4315 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4316 #else
4317 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4318 #endif
4319 state.bo_usable = GGPA (glBindBufferARB)
4320 && GGPA (glUnmapBufferARB)
4321 && GGPA (glMapBufferARB)
4322 && GGPA (glBufferDataARB)
4323 && GGPA (glGenBuffersARB)
4324 && GGPA (glDeleteBuffersARB);
4325 #undef GGPA
4328 CAMLprim value ml_bo_usable (value unit_v)
4330 CAMLparam1 (unit_v);
4331 CAMLreturn (Val_bool (state.bo_usable));
4334 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4336 CAMLparam3 (ptr_v, x_v, y_v);
4337 CAMLlocal2 (ret_v, tup_v);
4338 struct page *page;
4339 char *s = String_val (ptr_v);
4340 int x = Int_val (x_v), y = Int_val (y_v);
4341 struct pagedim *pdim;
4342 fz_point p;
4343 fz_matrix ctm;
4345 page = parse_pointer (__func__, s);
4346 pdim = &state.pagedims[page->pdimno];
4348 ret_v = Val_int (0);
4349 if (trylock (__func__)) {
4350 goto done;
4353 if (pdf_specifics (state.ctx, state.doc)) {
4354 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4355 ctm = state.pagedims[page->pdimno].tctm;
4357 else {
4358 ctm = fz_identity;
4360 p.x = x + pdim->bounds.x0;
4361 p.y = y + pdim->bounds.y0;
4363 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4364 fz_invert_matrix (&ctm, &ctm);
4365 fz_transform_point (&p, &ctm);
4367 tup_v = caml_alloc_tuple (2);
4368 ret_v = caml_alloc_small (1, 1);
4369 Field (tup_v, 0) = Val_int (p.x);
4370 Field (tup_v, 1) = Val_int (p.y);
4371 Field (ret_v, 0) = tup_v;
4373 unlock (__func__);
4374 done:
4375 CAMLreturn (ret_v);
4378 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4379 value x_v, value y_v)
4381 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4382 CAMLlocal1 (ret_v);
4383 struct page *page;
4384 char *s = String_val (ptr_v);
4385 int pageno = Int_val (pageno_v);
4386 int pdimno = Int_val (pdimno_v);
4387 double x = Double_val (x_v), y = Double_val (y_v);
4388 struct pagedim *pdim;
4389 fz_point p;
4390 fz_matrix ctm;
4392 ret_v = Val_int (0);
4393 lock (__func__);
4395 if (!*s) {
4396 page = loadpage (pageno, pdimno);
4398 else {
4399 page = parse_pointer (__func__, s);
4401 pdim = &state.pagedims[pdimno];
4403 if (pdf_specifics (state.ctx, state.doc)) {
4404 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4405 ctm = state.pagedims[page->pdimno].tctm;
4407 else {
4408 ctm = fz_identity;
4410 p.x = x + pdim->bounds.x0;
4411 p.y = y + pdim->bounds.y0;
4413 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4414 fz_transform_point (&p, &ctm);
4416 ret_v = caml_alloc_tuple (2);
4417 Field (ret_v, 0) = caml_copy_double (p.x);
4418 Field (ret_v, 1) = caml_copy_double (p.y);
4420 if (!*s) {
4421 freepage (page);
4423 unlock (__func__);
4424 CAMLreturn (ret_v);
4427 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4428 value contents_v)
4430 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4431 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4433 if (pdf) {
4434 pdf_annot *annot;
4435 struct page *page;
4436 fz_point p;
4437 char *s = String_val (ptr_v);
4439 page = parse_pointer (__func__, s);
4440 annot = pdf_create_annot (state.ctx, pdf,
4441 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4442 p.x = Int_val (x_v);
4443 p.y = Int_val (y_v);
4444 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4445 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4446 state.dirty = 1;
4448 CAMLreturn (Val_unit);
4451 CAMLprim value ml_delannot (value ptr_v, value n_v)
4453 CAMLparam2 (ptr_v, n_v);
4454 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4456 if (pdf) {
4457 struct page *page;
4458 char *s = String_val (ptr_v);
4459 struct slink *slink;
4461 page = parse_pointer (__func__, s);
4462 slink = &page->slinks[Int_val (n_v)];
4463 pdf_delete_annot (state.ctx, pdf,
4464 (pdf_page *) page->fzpage,
4465 (pdf_annot *) slink->u.annot);
4466 state.dirty = 1;
4468 CAMLreturn (Val_unit);
4471 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4473 CAMLparam3 (ptr_v, n_v, str_v);
4474 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4476 if (pdf) {
4477 struct page *page;
4478 char *s = String_val (ptr_v);
4479 struct slink *slink;
4481 page = parse_pointer (__func__, s);
4482 slink = &page->slinks[Int_val (n_v)];
4483 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4484 String_val (str_v));
4485 state.dirty = 1;
4487 CAMLreturn (Val_unit);
4490 CAMLprim value ml_hasunsavedchanges (value unit_v)
4492 CAMLparam1 (unit_v);
4493 CAMLreturn (Val_bool (state.dirty));
4496 CAMLprim value ml_savedoc (value path_v)
4498 CAMLparam1 (path_v);
4499 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4501 if (pdf) {
4502 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4504 CAMLreturn (Val_unit);
4507 static void makestippletex (void)
4509 const char pixels[] = "\xff\xff\0\0";
4510 glGenTextures (1, &state.stid);
4511 glBindTexture (GL_TEXTURE_1D, state.stid);
4512 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4513 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4514 glTexImage1D (
4515 GL_TEXTURE_1D,
4517 GL_ALPHA,
4520 GL_ALPHA,
4521 GL_UNSIGNED_BYTE,
4522 pixels
4526 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4528 return caml_copy_string (FZ_VERSION);
4531 #ifdef USE_FONTCONFIG
4532 static struct {
4533 int inited;
4534 FcConfig *config;
4535 } fc;
4537 static fz_font *fc_load_system_font_func (fz_context *ctx,
4538 const char *name,
4539 int bold,
4540 int italic,
4541 int UNUSED_ATTR needs_exact_metrics)
4543 char *buf;
4544 size_t i, size;
4545 fz_font *font;
4546 FcChar8 *path;
4547 FcResult result;
4548 FcPattern *pat, *pat1;
4550 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4551 name, bold, italic, needs_exact_metrics);
4552 if (!fc.inited) {
4553 fc.inited = 1;
4554 fc.config = FcInitLoadConfigAndFonts ();
4555 if (!fc.config) {
4556 lprintf ("FcInitLoadConfigAndFonts failed\n");
4557 return NULL;
4560 if (!fc.config) return NULL;
4562 size = strlen (name);
4563 if (bold) size += sizeof (":bold") - 1;
4564 if (italic) size += sizeof (":italic") - 1;
4565 size += 1;
4567 buf = malloc (size);
4568 if (!buf) {
4569 err (1, "malloc %zu failed", size);
4572 strcpy (buf, name);
4573 if (bold && italic) {
4574 strcat (buf, ":bold:italic");
4576 else {
4577 if (bold) strcat (buf, ":bold");
4578 if (italic) strcat (buf, ":italic");
4580 for (i = 0; i < size; ++i) {
4581 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4584 lprintf ("fcbuf=%s\n", buf);
4585 pat = FcNameParse ((FcChar8 *) buf);
4586 if (!pat) {
4587 printd ("emsg FcNameParse failed\n");
4588 free (buf);
4589 return NULL;
4592 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4593 printd ("emsg FcConfigSubstitute failed\n");
4594 free (buf);
4595 return NULL;
4597 FcDefaultSubstitute (pat);
4599 pat1 = FcFontMatch (fc.config, pat, &result);
4600 if (!pat1) {
4601 printd ("emsg FcFontMatch failed\n");
4602 FcPatternDestroy (pat);
4603 free (buf);
4604 return NULL;
4607 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4608 printd ("emsg FcPatternGetString failed\n");
4609 FcPatternDestroy (pat);
4610 FcPatternDestroy (pat1);
4611 free (buf);
4612 return NULL;
4615 #if 0
4616 printd ("emsg name=%s path=%s\n", name, path);
4617 #endif
4618 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4619 FcPatternDestroy (pat);
4620 FcPatternDestroy (pat1);
4621 free (buf);
4622 return font;
4624 #endif
4626 CAMLprim value ml_init (value csock_v, value params_v)
4628 CAMLparam2 (csock_v, params_v);
4629 CAMLlocal2 (trim_v, fuzz_v);
4630 int ret;
4631 int texcount;
4632 char *fontpath;
4633 int colorspace;
4634 int mustoresize;
4635 int haspboext;
4637 state.csock = Int_val (csock_v);
4638 state.rotate = Int_val (Field (params_v, 0));
4639 state.fitmodel = Int_val (Field (params_v, 1));
4640 trim_v = Field (params_v, 2);
4641 texcount = Int_val (Field (params_v, 3));
4642 state.sliceheight = Int_val (Field (params_v, 4));
4643 mustoresize = Int_val (Field (params_v, 5));
4644 colorspace = Int_val (Field (params_v, 6));
4645 fontpath = String_val (Field (params_v, 7));
4647 if (caml_string_length (Field (params_v, 8)) > 0) {
4648 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4650 if (!state.trimcachepath) {
4651 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4652 strerror (errno));
4655 haspboext = Bool_val (Field (params_v, 9));
4657 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4658 fz_register_document_handlers (state.ctx);
4660 #ifdef USE_FONTCONFIG
4661 if (Bool_val (Field (params_v, 10))) {
4662 fz_install_load_system_font_funcs (
4663 state.ctx, fc_load_system_font_func, NULL
4666 #endif
4668 state.trimmargins = Bool_val (Field (trim_v, 0));
4669 fuzz_v = Field (trim_v, 1);
4670 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4671 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4672 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4673 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4675 set_tex_params (colorspace);
4677 if (*fontpath) {
4678 #ifndef USE_FONTCONFIG
4679 state.face = load_font (fontpath);
4680 #else
4681 FcChar8 *path;
4682 FcResult result;
4683 char *buf = fontpath;
4684 FcPattern *pat, *pat1;
4686 fc.inited = 1;
4687 fc.config = FcInitLoadConfigAndFonts ();
4688 if (!fc.config) {
4689 errx (1, "FcInitLoadConfigAndFonts failed");
4692 pat = FcNameParse ((FcChar8 *) buf);
4693 if (!pat) {
4694 errx (1, "FcNameParse failed");
4697 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4698 errx (1, "FcConfigSubstitute failed");
4700 FcDefaultSubstitute (pat);
4702 pat1 = FcFontMatch (fc.config, pat, &result);
4703 if (!pat1) {
4704 errx (1, "FcFontMatch failed");
4707 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4708 errx (1, "FcPatternGetString failed");
4711 state.face = load_font ((char *) path);
4712 FcPatternDestroy (pat);
4713 FcPatternDestroy (pat1);
4714 #endif
4716 else {
4717 int len;
4718 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4719 0, 0, &len);
4720 state.face = load_builtin_font (data, len);
4722 if (!state.face) _exit (1);
4724 realloctexts (texcount);
4726 if (haspboext) {
4727 setuppbo ();
4730 makestippletex ();
4732 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4733 if (ret) {
4734 errx (1, "pthread_create: %s", strerror (ret));
4737 CAMLreturn (Val_unit);