Silence the compiler
[llpp.git] / link.c
blob02d69534488d5989073ed209d89f602c4a00758f
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 const fz_matrix *tctm;
2720 fz_link *link, *links;
2722 tctm = &fz_identity;
2723 links = fz_load_links (state.ctx, page->fzpage);
2725 p.x = x;
2726 p.y = y;
2728 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2729 fz_invert_matrix (&ctm, &ctm);
2730 fz_transform_point (&p, &ctm);
2732 for (link = links; link; link = link->next) {
2733 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2734 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2735 return link;
2739 return NULL;
2742 static void ensuretext (struct page *page)
2744 if (state.gen != page->tgen) {
2745 droptext (page);
2746 page->tgen = state.gen;
2748 if (!page->text) {
2749 fz_matrix ctm;
2750 fz_device *tdev;
2752 page->text = fz_new_stext_page (state.ctx);
2753 page->sheet = fz_new_stext_sheet (state.ctx);
2754 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2755 ctm = pagectm (page);
2756 fz_run_display_list (state.ctx, page->dlist,
2757 tdev, &ctm, &fz_infinite_rect, NULL);
2758 qsort (page->text->blocks, page->text->len,
2759 sizeof (*page->text->blocks), compareblocks);
2760 fz_drop_device (state.ctx, tdev);
2764 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2766 CAMLparam2 (start_page_v, dir_v);
2767 CAMLlocal1 (ret_v);
2768 int i, dir = Int_val (dir_v);
2769 int start_page = Int_val (start_page_v);
2770 int end_page = dir > 0 ? state.pagecount : -1;
2771 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2773 fz_var (end_page);
2774 ret_v = Val_int (0);
2775 lock (__func__);
2776 for (i = start_page + dir; i != end_page; i += dir) {
2777 int found;
2779 fz_var (found);
2780 if (pdf) {
2781 pdf_page *page = NULL;
2783 fz_try (state.ctx) {
2784 page = pdf_load_page (state.ctx, pdf, i);
2785 found = !!page->links || !!page->annots;
2787 fz_catch (state.ctx) {
2788 found = 0;
2790 if (page) {
2791 fz_drop_page (state.ctx, &page->super);
2794 else {
2795 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2796 found = !!fz_load_links (state.ctx, page);
2797 fz_drop_page (state.ctx, page);
2800 if (found) {
2801 ret_v = caml_alloc_small (1, 1);
2802 Field (ret_v, 0) = Val_int (i);
2803 goto unlock;
2806 unlock:
2807 unlock (__func__);
2808 CAMLreturn (ret_v);
2811 enum { dir_first, dir_last };
2812 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2814 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2816 CAMLparam2 (ptr_v, dir_v);
2817 CAMLlocal2 (ret_v, pos_v);
2818 struct page *page;
2819 int dirtag, i, slinkindex;
2820 struct slink *found = NULL ,*slink;
2821 char *s = String_val (ptr_v);
2823 page = parse_pointer (__func__, s);
2824 ret_v = Val_int (0);
2825 /* This is scary we are not taking locks here ensureslinks does
2826 not modify state and given that we obtained the page it can not
2827 disappear under us either */
2828 lock (__func__);
2829 ensureslinks (page);
2831 if (Is_block (dir_v)) {
2832 dirtag = Tag_val (dir_v);
2833 switch (dirtag) {
2834 case dir_first_visible:
2836 int x0, y0, dir, first_index, last_index;
2838 pos_v = Field (dir_v, 0);
2839 x0 = Int_val (Field (pos_v, 0));
2840 y0 = Int_val (Field (pos_v, 1));
2841 dir = Int_val (Field (pos_v, 2));
2843 if (dir >= 0) {
2844 dir = 1;
2845 first_index = 0;
2846 last_index = page->slinkcount;
2848 else {
2849 first_index = page->slinkcount - 1;
2850 last_index = -1;
2853 for (i = first_index; i != last_index; i += dir) {
2854 slink = &page->slinks[i];
2855 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2856 found = slink;
2857 break;
2861 break;
2863 case dir_left:
2864 slinkindex = Int_val (Field (dir_v, 0));
2865 found = &page->slinks[slinkindex];
2866 for (i = slinkindex - 1; i >= 0; --i) {
2867 slink = &page->slinks[i];
2868 if (slink->bbox.x0 < found->bbox.x0) {
2869 found = slink;
2870 break;
2873 break;
2875 case dir_right:
2876 slinkindex = Int_val (Field (dir_v, 0));
2877 found = &page->slinks[slinkindex];
2878 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2879 slink = &page->slinks[i];
2880 if (slink->bbox.x0 > found->bbox.x0) {
2881 found = slink;
2882 break;
2885 break;
2887 case dir_down:
2888 slinkindex = Int_val (Field (dir_v, 0));
2889 found = &page->slinks[slinkindex];
2890 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2891 slink = &page->slinks[i];
2892 if (slink->bbox.y0 >= found->bbox.y0) {
2893 found = slink;
2894 break;
2897 break;
2899 case dir_up:
2900 slinkindex = Int_val (Field (dir_v, 0));
2901 found = &page->slinks[slinkindex];
2902 for (i = slinkindex - 1; i >= 0; --i) {
2903 slink = &page->slinks[i];
2904 if (slink->bbox.y0 <= found->bbox.y0) {
2905 found = slink;
2906 break;
2909 break;
2912 else {
2913 dirtag = Int_val (dir_v);
2914 switch (dirtag) {
2915 case dir_first:
2916 found = page->slinks;
2917 break;
2919 case dir_last:
2920 if (page->slinks) {
2921 found = page->slinks + (page->slinkcount - 1);
2923 break;
2926 if (found) {
2927 ret_v = caml_alloc_small (2, 1);
2928 Field (ret_v, 0) = Val_int (found - page->slinks);
2931 unlock (__func__);
2932 CAMLreturn (ret_v);
2935 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2936 unamed, uremote, uremotedest, uannot };
2938 #define LINKTOVAL \
2940 int pageno; \
2942 switch (link->dest.kind) { \
2943 case FZ_LINK_GOTO: \
2945 fz_point p; \
2947 pageno = link->dest.ld.gotor.page; \
2948 p.x = 0; \
2949 p.y = 0; \
2951 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2952 p.y = link->dest.ld.gotor.lt.y; \
2953 fz_transform_point (&p, &pdim->lctm); \
2954 if (p.y < 0) p.y = 0; \
2956 tup_v = caml_alloc_tuple (2); \
2957 ret_v = caml_alloc_small (1, ugoto); \
2958 Field (tup_v, 0) = Val_int (pageno); \
2959 Field (tup_v, 1) = Val_int (p.y); \
2960 Field (ret_v, 0) = tup_v; \
2962 break; \
2964 case FZ_LINK_URI: \
2965 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2966 ret_v = caml_alloc_small (1, uuri); \
2967 Field (ret_v, 0) = str_v; \
2968 break; \
2970 case FZ_LINK_LAUNCH: \
2971 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2972 ret_v = caml_alloc_small (1, ulaunch); \
2973 Field (ret_v, 0) = str_v; \
2974 break; \
2976 case FZ_LINK_NAMED: \
2977 str_v = caml_copy_string (link->dest.ld.named.named); \
2978 ret_v = caml_alloc_small (1, unamed); \
2979 Field (ret_v, 0) = str_v; \
2980 break; \
2982 case FZ_LINK_GOTOR: \
2984 int rty; \
2986 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2987 pageno = link->dest.ld.gotor.page; \
2988 if (pageno == -1) { \
2989 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2990 rty = uremotedest; \
2992 else { \
2993 gr_v = Val_int (pageno); \
2994 rty = uremote; \
2996 tup_v = caml_alloc_tuple (2); \
2997 ret_v = caml_alloc_small (1, rty); \
2998 Field (tup_v, 0) = str_v; \
2999 Field (tup_v, 1) = gr_v; \
3000 Field (ret_v, 0) = tup_v; \
3002 break; \
3004 default: \
3006 char buf[80]; \
3008 snprintf (buf, sizeof (buf), \
3009 "unhandled link kind %d", link->dest.kind); \
3010 str_v = caml_copy_string (buf); \
3011 ret_v = caml_alloc_small (1, uunexpected); \
3012 Field (ret_v, 0) = str_v; \
3014 break; \
3018 CAMLprim value ml_getlink (value ptr_v, value n_v)
3020 CAMLparam2 (ptr_v, n_v);
3021 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3022 fz_link *link;
3023 struct page *page;
3024 struct pagedim *pdim;
3025 char *s = String_val (ptr_v);
3026 struct slink *slink;
3028 /* See ml_findlink for caveat */
3030 ret_v = Val_int (0);
3031 page = parse_pointer (__func__, s);
3032 ensureslinks (page);
3033 pdim = &state.pagedims[page->pdimno];
3034 slink = &page->slinks[Int_val (n_v)];
3035 if (slink->tag == SLINK) {
3036 link = slink->u.link;
3037 LINKTOVAL;
3039 else {
3040 ret_v = caml_alloc_small (1, uannot);
3041 tup_v = caml_alloc_tuple (2);
3042 Field (ret_v, 0) = tup_v;
3043 Field (tup_v, 0) = ptr_v;
3044 Field (tup_v, 1) = n_v;
3047 CAMLreturn (ret_v);
3050 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3052 CAMLparam2 (ptr_v, n_v);
3053 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3054 if (pdf) {
3055 char *s = String_val (ptr_v);
3056 struct page *page;
3057 struct slink *slink;
3059 page = parse_pointer (__func__, s);
3060 slink = &page->slinks[Int_val (n_v)];
3061 CAMLreturn (caml_copy_string (
3062 pdf_annot_contents (state.ctx, pdf,
3063 (pdf_annot *) slink->u.annot)));
3065 else {
3066 CAMLreturn (caml_copy_string (""));
3070 CAMLprim value ml_getlinkcount (value ptr_v)
3072 CAMLparam1 (ptr_v);
3073 struct page *page;
3074 char *s = String_val (ptr_v);
3076 page = parse_pointer (__func__, s);
3077 CAMLreturn (Val_int (page->slinkcount));
3080 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3082 CAMLparam2 (ptr_v, n_v);
3083 CAMLlocal1 (ret_v);
3084 struct page *page;
3085 struct slink *slink;
3086 char *s = String_val (ptr_v);
3087 /* See ml_findlink for caveat */
3089 page = parse_pointer (__func__, s);
3090 ret_v = caml_alloc_tuple (4);
3091 ensureslinks (page);
3093 slink = &page->slinks[Int_val (n_v)];
3094 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3095 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3096 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3097 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3098 unlock (__func__);
3099 CAMLreturn (ret_v);
3102 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3104 CAMLparam3 (ptr_v, x_v, y_v);
3105 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3106 fz_link *link;
3107 struct annot *annot;
3108 struct page *page;
3109 char *ptr = String_val (ptr_v);
3110 int x = Int_val (x_v), y = Int_val (y_v);
3111 struct pagedim *pdim;
3113 ret_v = Val_int (0);
3114 if (trylock (__func__)) {
3115 goto done;
3118 page = parse_pointer (__func__, ptr);
3119 pdim = &state.pagedims[page->pdimno];
3120 x += pdim->bounds.x0;
3121 y += pdim->bounds.y0;
3124 annot = getannot (page, x, y);
3125 if (annot) {
3126 int i, n = -1;
3128 ensureslinks (page);
3129 for (i = 0; i < page->slinkcount; ++i) {
3130 if (page->slinks[i].tag == SANNOT
3131 && page->slinks[i].u.annot == annot->annot) {
3132 n = i;
3133 break;
3136 ret_v = caml_alloc_small (1, uannot);
3137 tup_v = caml_alloc_tuple (2);
3138 Field (ret_v, 0) = tup_v;
3139 Field (tup_v, 0) = ptr_v;
3140 Field (tup_v, 1) = Val_int (n);
3141 goto unlock;
3145 link = getlink (page, x, y);
3146 if (link) {
3147 LINKTOVAL;
3149 else {
3150 fz_rect *b;
3151 fz_page_block *pageb;
3152 fz_stext_block *block;
3154 ensuretext (page);
3155 for (pageb = page->text->blocks;
3156 pageb < page->text->blocks + page->text->len;
3157 ++pageb) {
3158 fz_stext_line *line;
3159 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3160 block = pageb->u.text;
3162 b = &block->bbox;
3163 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3164 continue;
3166 for (line = block->lines;
3167 line < block->lines + block->len;
3168 ++line) {
3169 fz_stext_span *span;
3171 b = &line->bbox;
3172 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3173 continue;
3175 for (span = line->first_span; span; span = span->next) {
3176 int charnum;
3178 b = &span->bbox;
3179 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3180 continue;
3182 for (charnum = 0; charnum < span->len; ++charnum) {
3183 fz_rect bbox;
3184 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3185 b = &bbox;
3187 if (x >= b->x0 && x <= b->x1
3188 && y >= b->y0 && y <= b->y1) {
3189 fz_stext_style *style = span->text->style;
3190 const char *n2 =
3191 style->font
3192 ? style->font->name
3193 : "Span has no font name"
3195 FT_FaceRec *face = style->font->ft_face;
3196 if (face && face->family_name) {
3197 char *s;
3198 char *n1 = face->family_name;
3199 size_t l1 = strlen (n1);
3200 size_t l2 = strlen (n2);
3202 if (l1 != l2 || memcmp (n1, n2, l1)) {
3203 s = malloc (l1 + l2 + 2);
3204 if (s) {
3205 memcpy (s, n2, l2);
3206 s[l2] = '=';
3207 memcpy (s + l2 + 1, n1, l1 + 1);
3208 str_v = caml_copy_string (s);
3209 free (s);
3213 if (str_v == Val_unit) {
3214 str_v = caml_copy_string (n2);
3216 ret_v = caml_alloc_small (1, utext);
3217 Field (ret_v, 0) = str_v;
3218 goto unlock;
3225 unlock:
3226 unlock (__func__);
3228 done:
3229 CAMLreturn (ret_v);
3232 enum { mark_page, mark_block, mark_line, mark_word };
3234 static int uninteresting (int c)
3236 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3237 || ispunct (c);
3240 CAMLprim value ml_clearmark (value ptr_v)
3242 CAMLparam1 (ptr_v);
3243 char *s = String_val (ptr_v);
3244 struct page *page;
3246 if (trylock (__func__)) {
3247 goto done;
3250 page = parse_pointer (__func__, s);
3251 page->fmark.span = NULL;
3252 page->lmark.span = NULL;
3253 page->fmark.i = 0;
3254 page->lmark.i = 0;
3256 unlock (__func__);
3257 done:
3258 CAMLreturn (Val_unit);
3261 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3263 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3264 CAMLlocal1 (ret_v);
3265 fz_rect *b;
3266 struct page *page;
3267 fz_stext_line *line;
3268 fz_page_block *pageb;
3269 fz_stext_block *block;
3270 struct pagedim *pdim;
3271 int mark = Int_val (mark_v);
3272 char *s = String_val (ptr_v);
3273 int x = Int_val (x_v), y = Int_val (y_v);
3275 ret_v = Val_bool (0);
3276 if (trylock (__func__)) {
3277 goto done;
3280 page = parse_pointer (__func__, s);
3281 pdim = &state.pagedims[page->pdimno];
3283 ensuretext (page);
3285 if (mark == mark_page) {
3286 int i;
3287 fz_page_block *pb1 = NULL, *pb2 = NULL;
3289 for (i = 0; i < page->text->len; ++i) {
3290 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3291 pb1 = &page->text->blocks[i];
3292 break;
3295 if (!pb1) goto unlock;
3297 for (i = page->text->len - 1; i >= 0; --i) {
3298 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3299 pb2 = &page->text->blocks[i];
3300 break;
3303 if (!pb2) goto unlock;
3305 block = pb1->u.text;
3307 page->fmark.i = 0;
3308 page->fmark.span = block->lines->first_span;
3310 block = pb2->u.text;
3311 line = &block->lines[block->len - 1];
3312 page->lmark.i = line->last_span->len - 1;
3313 page->lmark.span = line->last_span;
3314 ret_v = Val_bool (1);
3315 goto unlock;
3318 x += pdim->bounds.x0;
3319 y += pdim->bounds.y0;
3321 for (pageb = page->text->blocks;
3322 pageb < page->text->blocks + page->text->len;
3323 ++pageb) {
3324 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3325 block = pageb->u.text;
3327 b = &block->bbox;
3328 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3329 continue;
3331 if (mark == mark_block) {
3332 page->fmark.i = 0;
3333 page->fmark.span = block->lines->first_span;
3335 line = &block->lines[block->len - 1];
3336 page->lmark.i = line->last_span->len - 1;
3337 page->lmark.span = line->last_span;
3338 ret_v = Val_bool (1);
3339 goto unlock;
3342 for (line = block->lines;
3343 line < block->lines + block->len;
3344 ++line) {
3345 fz_stext_span *span;
3347 b = &line->bbox;
3348 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3349 continue;
3351 if (mark == mark_line) {
3352 page->fmark.i = 0;
3353 page->fmark.span = line->first_span;
3355 page->lmark.i = line->last_span->len - 1;
3356 page->lmark.span = line->last_span;
3357 ret_v = Val_bool (1);
3358 goto unlock;
3361 for (span = line->first_span; span; span = span->next) {
3362 int charnum;
3364 b = &span->bbox;
3365 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3366 continue;
3368 for (charnum = 0; charnum < span->len; ++charnum) {
3369 fz_rect bbox;
3370 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3371 b = &bbox;
3373 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3374 /* unicode ftw */
3375 int charnum2, charnum3 = -1, charnum4 = -1;
3377 if (uninteresting (span->text[charnum].c)) goto unlock;
3379 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3380 if (uninteresting (span->text[charnum2].c)) {
3381 charnum3 = charnum2 + 1;
3382 break;
3385 if (charnum3 == -1) charnum3 = 0;
3387 for (charnum2 = charnum + 1;
3388 charnum2 < span->len;
3389 ++charnum2) {
3390 if (uninteresting (span->text[charnum2].c)) break;
3391 charnum4 = charnum2;
3393 if (charnum4 == -1) goto unlock;
3395 page->fmark.i = charnum3;
3396 page->fmark.span = span;
3398 page->lmark.i = charnum4;
3399 page->lmark.span = span;
3400 ret_v = Val_bool (1);
3401 goto unlock;
3407 unlock:
3408 if (!Bool_val (ret_v)) {
3409 page->fmark.span = NULL;
3410 page->lmark.span = NULL;
3411 page->fmark.i = 0;
3412 page->lmark.i = 0;
3414 unlock (__func__);
3416 done:
3417 CAMLreturn (ret_v);
3420 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3422 CAMLparam3 (ptr_v, x_v, y_v);
3423 CAMLlocal2 (ret_v, res_v);
3424 fz_rect *b = NULL;
3425 struct page *page;
3426 fz_page_block *pageb;
3427 struct pagedim *pdim;
3428 char *s = String_val (ptr_v);
3429 int x = Int_val (x_v), y = Int_val (y_v);
3431 ret_v = Val_int (0);
3432 if (trylock (__func__)) {
3433 goto done;
3436 page = parse_pointer (__func__, s);
3437 pdim = &state.pagedims[page->pdimno];
3438 x += pdim->bounds.x0;
3439 y += pdim->bounds.y0;
3441 ensuretext (page);
3443 for (pageb = page->text->blocks;
3444 pageb < page->text->blocks + page->text->len;
3445 ++pageb) {
3446 switch (pageb->type) {
3447 case FZ_PAGE_BLOCK_TEXT:
3448 b = &pageb->u.text->bbox;
3449 break;
3451 case FZ_PAGE_BLOCK_IMAGE:
3452 b = &pageb->u.image->bbox;
3453 break;
3455 default:
3456 continue;
3459 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3460 break;
3461 b = NULL;
3463 if (b) {
3464 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3465 ret_v = caml_alloc_small (1, 1);
3466 Store_double_field (res_v, 0, b->x0);
3467 Store_double_field (res_v, 1, b->x1);
3468 Store_double_field (res_v, 2, b->y0);
3469 Store_double_field (res_v, 3, b->y1);
3470 Field (ret_v, 0) = res_v;
3472 unlock (__func__);
3474 done:
3475 CAMLreturn (ret_v);
3478 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3480 CAMLparam2 (ptr_v, rect_v);
3481 fz_rect b;
3482 struct page *page;
3483 struct pagedim *pdim;
3484 char *s = String_val (ptr_v);
3485 int i, x0, x1, y0, y1, fi, li;
3486 fz_stext_line *line;
3487 fz_page_block *pageb;
3488 fz_stext_block *block;
3489 fz_stext_span *span, *fspan, *lspan;
3491 if (trylock (__func__)) {
3492 goto done;
3495 page = parse_pointer (__func__, s);
3496 ensuretext (page);
3498 pdim = &state.pagedims[page->pdimno];
3499 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3500 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3501 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3502 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3504 if (y0 > y1) {
3505 int t = y0;
3506 y0 = y1;
3507 y1 = t;
3508 x0 = x1;
3509 x1 = t;
3512 fi = page->fmark.i;
3513 fspan = page->fmark.span;
3515 li = page->lmark.i;
3516 lspan = page->lmark.span;
3518 for (pageb = page->text->blocks;
3519 pageb < page->text->blocks + page->text->len;
3520 ++pageb) {
3521 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3522 block = pageb->u.text;
3523 for (line = block->lines;
3524 line < block->lines + block->len;
3525 ++line) {
3527 for (span = line->first_span; span; span = span->next) {
3528 for (i = 0; i < span->len; ++i) {
3529 fz_stext_char_bbox (state.ctx, &b, span, i);
3531 if (x0 >= b.x0 && x0 <= b.x1
3532 && y0 >= b.y0 && y0 <= b.y1) {
3533 fspan = span;
3534 fi = i;
3536 if (x1 >= b.x0 && x1 <= b.x1
3537 && y1 >= b.y0 && y1 <= b.y1) {
3538 lspan = span;
3539 li = i;
3545 if (x1 < x0 && fspan == lspan) {
3546 i = fi;
3547 span = fspan;
3549 fi = li;
3550 fspan = lspan;
3552 li = i;
3553 lspan = span;
3556 page->fmark.i = fi;
3557 page->fmark.span = fspan;
3559 page->lmark.i = li;
3560 page->lmark.span = lspan;
3562 unlock (__func__);
3564 done:
3565 CAMLreturn (Val_unit);
3568 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3570 char buf[4];
3571 int i, len, ret;
3573 for (i = a; i <= b; ++i) {
3574 len = fz_runetochar (buf, span->text[i].c);
3575 ret = fwrite (buf, len, 1, f);
3577 if (ret != 1) {
3578 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3579 len, ret, strerror (errno));
3580 return -1;
3583 return 0;
3586 #ifdef __CYGWIN__
3587 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3589 caml_failwith ("ml_popen not implemented under Cygwin");
3591 #else
3592 CAMLprim value ml_spawn (value command_v, value fds_v)
3594 CAMLparam2 (command_v, fds_v);
3595 CAMLlocal2 (l_v, tup_v);
3596 int ret, ret1;
3597 pid_t pid;
3598 char *msg = NULL;
3599 value earg_v = Nothing;
3600 posix_spawnattr_t attr;
3601 posix_spawn_file_actions_t fa;
3602 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3604 argv[2] = String_val (command_v);
3606 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3607 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3610 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3611 msg = "posix_spawnattr_init";
3612 goto fail1;
3615 #ifdef POSIX_SPAWN_USEVFORK
3616 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3617 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3618 goto fail;
3620 #endif
3622 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3623 int fd1, fd2;
3625 tup_v = Field (l_v, 0);
3626 fd1 = Int_val (Field (tup_v, 0));
3627 fd2 = Int_val (Field (tup_v, 1));
3628 if (fd2 < 0) {
3629 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3630 msg = "posix_spawn_file_actions_addclose";
3631 earg_v = tup_v;
3632 goto fail;
3635 else {
3636 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3637 msg = "posix_spawn_file_actions_adddup2";
3638 earg_v = tup_v;
3639 goto fail;
3644 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3645 msg = "posix_spawn";
3646 goto fail;
3649 fail:
3650 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3651 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3654 fail1:
3655 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3656 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3657 strerror (ret1));
3660 if (msg)
3661 unix_error (ret, msg, earg_v);
3663 CAMLreturn (Val_int (pid));
3665 #endif
3667 CAMLprim value ml_hassel (value ptr_v)
3669 CAMLparam1 (ptr_v);
3670 CAMLlocal1 (ret_v);
3671 struct page *page;
3672 char *s = String_val (ptr_v);
3674 ret_v = Val_bool (0);
3675 if (trylock (__func__)) {
3676 goto done;
3679 page = parse_pointer (__func__, s);
3680 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3681 unlock (__func__);
3682 done:
3683 CAMLreturn (ret_v);
3686 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3688 CAMLparam2 (fd_v, ptr_v);
3689 FILE *f;
3690 int seen = 0;
3691 struct page *page;
3692 fz_stext_line *line;
3693 fz_page_block *pageb;
3694 fz_stext_block *block;
3695 int fd = Int_val (fd_v);
3696 char *s = String_val (ptr_v);
3698 if (trylock (__func__)) {
3699 goto done;
3702 page = parse_pointer (__func__, s);
3704 if (!page->fmark.span || !page->lmark.span) {
3705 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3706 goto unlock;
3709 f = fdopen (fd, "w");
3710 if (!f) {
3711 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3712 fd, strerror (errno));
3713 f = stdout;
3716 for (pageb = page->text->blocks;
3717 pageb < page->text->blocks + page->text->len;
3718 ++pageb) {
3719 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3720 block = pageb->u.text;
3721 for (line = block->lines;
3722 line < block->lines + block->len;
3723 ++line) {
3724 fz_stext_span *span;
3726 for (span = line->first_span; span; span = span->next) {
3727 int a, b;
3729 seen |= span == page->fmark.span || span == page->lmark.span;
3730 a = span == page->fmark.span ? page->fmark.i : 0;
3731 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3733 if (seen) {
3734 if (pipespan (f, span, a, b)) {
3735 goto close;
3737 if (span == page->lmark.span) {
3738 goto close;
3740 if (span == line->last_span) {
3741 if (putc ('\n', f) == EOF) {
3742 fprintf (stderr,
3743 "failed break line on sel pipe: %s\n",
3744 strerror (errno));
3745 goto close;
3752 close:
3753 if (f != stdout) {
3754 int ret = fclose (f);
3755 fd = -1;
3756 if (ret == -1) {
3757 if (errno != ECHILD) {
3758 fprintf (stderr, "failed to close sel pipe: %s\n",
3759 strerror (errno));
3763 unlock:
3764 unlock (__func__);
3766 done:
3767 if (fd >= 0) {
3768 if (close (fd)) {
3769 fprintf (stderr, "failed to close sel pipe: %s\n",
3770 strerror (errno));
3773 CAMLreturn (Val_unit);
3776 CAMLprim value ml_getpdimrect (value pagedimno_v)
3778 CAMLparam1 (pagedimno_v);
3779 CAMLlocal1 (ret_v);
3780 int pagedimno = Int_val (pagedimno_v);
3781 fz_rect box;
3783 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3784 if (trylock (__func__)) {
3785 box = fz_empty_rect;
3787 else {
3788 box = state.pagedims[pagedimno].mediabox;
3789 unlock (__func__);
3792 Store_double_field (ret_v, 0, box.x0);
3793 Store_double_field (ret_v, 1, box.x1);
3794 Store_double_field (ret_v, 2, box.y0);
3795 Store_double_field (ret_v, 3, box.y1);
3797 CAMLreturn (ret_v);
3800 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3801 value dw_v, value cols_v)
3803 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3804 CAMLlocal1 (ret_v);
3805 int i;
3806 double zoom = -1.;
3807 double maxh = 0.0;
3808 struct pagedim *p;
3809 double winw = Int_val (winw_v);
3810 double winh = Int_val (winh_v);
3811 double dw = Int_val (dw_v);
3812 double cols = Int_val (cols_v);
3813 double pw = 1.0, ph = 1.0;
3815 if (trylock (__func__)) {
3816 goto done;
3819 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3820 double w = p->pagebox.x1 / cols;
3821 double h = p->pagebox.y1;
3822 if (h > maxh) {
3823 maxh = h;
3824 ph = h;
3825 if (state.fitmodel != FitProportional) pw = w;
3827 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3830 zoom = (((winh / ph) * pw) + dw) / winw;
3831 unlock (__func__);
3832 done:
3833 ret_v = caml_copy_double (zoom);
3834 CAMLreturn (ret_v);
3837 CAMLprim value ml_getmaxw (value unit_v)
3839 CAMLparam1 (unit_v);
3840 CAMLlocal1 (ret_v);
3841 int i;
3842 double maxw = -1.;
3843 struct pagedim *p;
3845 if (trylock (__func__)) {
3846 goto done;
3849 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3850 double w = p->pagebox.x1;
3851 maxw = MAX (maxw, w);
3854 unlock (__func__);
3855 done:
3856 ret_v = caml_copy_double (maxw);
3857 CAMLreturn (ret_v);
3860 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3862 CAMLparam4 (pt_v, x_v, y_v, string_v);
3863 CAMLlocal1 (ret_v);
3864 int pt = Int_val(pt_v);
3865 int x = Int_val (x_v);
3866 int y = Int_val (y_v);
3867 double w;
3869 w = draw_string (state.face, pt, x, y, String_val (string_v));
3870 ret_v = caml_copy_double (w);
3871 CAMLreturn (ret_v);
3874 CAMLprim value ml_measure_string (value pt_v, value string_v)
3876 CAMLparam2 (pt_v, string_v);
3877 CAMLlocal1 (ret_v);
3878 int pt = Int_val (pt_v);
3879 double w;
3881 w = measure_string (state.face, pt, String_val (string_v));
3882 ret_v = caml_copy_double (w);
3883 CAMLreturn (ret_v);
3886 CAMLprim value ml_getpagebox (value opaque_v)
3888 CAMLparam1 (opaque_v);
3889 CAMLlocal1 (ret_v);
3890 fz_rect rect;
3891 fz_irect bbox;
3892 fz_matrix ctm;
3893 fz_device *dev;
3894 char *s = String_val (opaque_v);
3895 struct page *page = parse_pointer (__func__, s);
3897 ret_v = caml_alloc_tuple (4);
3898 dev = fz_new_bbox_device (state.ctx, &rect);
3899 dev->hints |= FZ_IGNORE_SHADE;
3901 ctm = pagectm (page);
3902 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3904 fz_drop_device (state.ctx, dev);
3905 fz_round_rect (&bbox, &rect);
3906 Field (ret_v, 0) = Val_int (bbox.x0);
3907 Field (ret_v, 1) = Val_int (bbox.y0);
3908 Field (ret_v, 2) = Val_int (bbox.x1);
3909 Field (ret_v, 3) = Val_int (bbox.y1);
3911 CAMLreturn (ret_v);
3914 CAMLprim value ml_setaalevel (value level_v)
3916 CAMLparam1 (level_v);
3918 state.aalevel = Int_val (level_v);
3919 CAMLreturn (Val_unit);
3922 #pragma GCC diagnostic push
3923 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3924 #include <X11/Xlib.h>
3925 #include <X11/cursorfont.h>
3926 #pragma GCC diagnostic pop
3928 #ifdef USE_EGL
3929 #include <EGL/egl.h>
3930 #else
3931 #include <GL/glx.h>
3932 #endif
3934 static const int shapes[] = {
3935 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3938 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3940 static struct {
3941 Window wid;
3942 Display *dpy;
3943 #ifdef USE_EGL
3944 EGLContext ctx;
3945 EGLConfig conf;
3946 EGLSurface win;
3947 EGLDisplay *edpy;
3948 #else
3949 GLXContext ctx;
3950 #endif
3951 XVisualInfo *visual;
3952 Cursor curs[CURS_COUNT];
3953 } glx;
3955 #ifdef VISAVIS
3956 static VisualID initvisual (void)
3958 /* On this system with: `Haswell-ULT Integrated Graphics
3959 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3960 using glX chosen visual and auto scrolling some document in
3961 fullscreen the power/energy-gpu is more than 1 joule bigger
3962 than when using hand picked visual that stands alone in glxinfo
3963 output: it's dead last in the list and it's the only one with
3964 `visual dep' (sic) of 32
3966 No clue what's going on here...
3968 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3970 XVisualInfo info;
3971 int ret = 1;
3973 info.depth = 32;
3974 info.class = TrueColor;
3975 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3976 &info, &ret);
3977 if (!ret || !glx.visual) {
3978 XCloseDisplay (glx.dpy);
3979 caml_failwith ("XGetVisualInfo");
3981 return glx.visual->visualid;
3983 #endif
3985 static void initcurs (void)
3987 for (size_t n = 0; n < CURS_COUNT; ++n) {
3988 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3992 CAMLprim void ml_setbgcol (value color_v)
3994 CAMLparam1 (color_v);
3995 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3996 CAMLreturn0;
3999 #ifdef USE_EGL
4000 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4002 CAMLparam3 (display_v, wid_v, screen_v);
4003 int major, minor;
4004 int num_conf;
4005 EGLint visid;
4006 EGLint attribs[] = {
4007 #ifdef VISAVIS
4008 EGL_NATIVE_VISUAL_ID, 0,
4009 #else
4010 EGL_DEPTH_SIZE, 24,
4011 #endif
4012 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
4013 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
4014 EGL_NONE
4016 EGLConfig conf;
4018 glx.dpy = XOpenDisplay (String_val (display_v));
4019 if (!glx.dpy) {
4020 caml_failwith ("XOpenDisplay");
4023 eglBindAPI (EGL_OPENGL_API);
4025 glx.edpy = eglGetDisplay (glx.dpy);
4026 if (glx.dpy == EGL_NO_DISPLAY) {
4027 caml_failwith ("eglGetDisplay");
4030 if (!eglInitialize (glx.edpy, &major, &minor)) {
4031 caml_failwith ("eglInitialize");
4034 #ifdef VISAVIS
4035 attribs[1] = visid = initvisual ();
4036 #endif
4038 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4039 !num_conf) {
4040 caml_failwith ("eglChooseConfig");
4043 glx.conf = conf;
4044 #ifndef VISAVIS
4045 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4046 EGL_NATIVE_VISUAL_ID, &visid)) {
4047 caml_failwith ("eglGetConfigAttrib");
4049 #endif
4050 initcurs ();
4052 glx.wid = Int_val (wid_v);
4053 CAMLreturn (Val_int (visid));
4056 CAMLprim value ml_glxcompleteinit (value unit_v)
4058 CAMLparam1 (unit_v);
4060 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4061 if (!glx.ctx) {
4062 caml_failwith ("eglCreateContext");
4065 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4066 glx.wid, NULL);
4067 if (glx.win == EGL_NO_SURFACE) {
4068 caml_failwith ("eglCreateWindowSurface");
4071 XFree (glx.visual);
4072 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4073 glx.ctx = NULL;
4074 caml_failwith ("eglMakeCurrent");
4076 CAMLreturn (Val_unit);
4078 #else
4079 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4081 CAMLparam3 (display_v, wid_v, screen_v);
4083 glx.dpy = XOpenDisplay (String_val (display_v));
4084 if (!glx.dpy) {
4085 caml_failwith ("XOpenDisplay");
4088 #ifdef VISAVIS
4089 initvisual ();
4090 #else
4091 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4092 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4093 if (!glx.visual) {
4094 XCloseDisplay (glx.dpy);
4095 caml_failwith ("glXChooseVisual");
4097 #endif
4098 initcurs ();
4100 glx.wid = Int_val (wid_v);
4101 CAMLreturn (Val_int (glx.visual->visualid));
4104 CAMLprim value ml_glxcompleteinit (value unit_v)
4106 CAMLparam1 (unit_v);
4108 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4109 if (!glx.ctx) {
4110 caml_failwith ("glXCreateContext");
4113 XFree (glx.visual);
4114 glx.visual = NULL;
4116 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4117 glXDestroyContext (glx.dpy, glx.ctx);
4118 glx.ctx = NULL;
4119 caml_failwith ("glXMakeCurrent");
4121 CAMLreturn (Val_unit);
4123 #endif
4125 CAMLprim value ml_setcursor (value cursor_v)
4127 CAMLparam1 (cursor_v);
4128 size_t cursn = Int_val (cursor_v);
4130 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4131 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4132 XFlush (glx.dpy);
4133 CAMLreturn (Val_unit);
4136 CAMLprim value ml_swapb (value unit_v)
4138 CAMLparam1 (unit_v);
4139 #ifdef USE_EGL
4140 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4141 caml_failwith ("eglSwapBuffers");
4143 #else
4144 glXSwapBuffers (glx.dpy, glx.wid);
4145 #endif
4146 CAMLreturn (Val_unit);
4149 #include "keysym2ucs.c"
4151 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4153 CAMLparam1 (keysym_v);
4154 CAMLlocal1 (str_v);
4155 KeySym keysym = Int_val (keysym_v);
4156 Rune rune;
4157 int len;
4158 char buf[5];
4160 rune = keysym2ucs (keysym);
4161 len = fz_runetochar (buf, rune);
4162 buf[len] = 0;
4163 str_v = caml_copy_string (buf);
4164 CAMLreturn (str_v);
4167 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4169 CAMLprim value ml_platform (value unit_v)
4171 CAMLparam1 (unit_v);
4172 CAMLlocal2 (tup_v, arr_v);
4173 int platid = piunknown;
4174 struct utsname buf;
4176 #if defined __linux__
4177 platid = pilinux;
4178 #elif defined __CYGWIN__
4179 platid = picygwin;
4180 #elif defined __DragonFly__ || defined __FreeBSD__
4181 || defined __OpenBSD__ || defined __NetBSD__
4182 platid = pibsd;
4183 #elif defined __sun__
4184 platid = pisun;
4185 #elif defined __APPLE__
4186 platid = piosx;
4187 #endif
4188 if (uname (&buf)) err (1, "uname");
4190 tup_v = caml_alloc_tuple (2);
4192 char const *sar[] = {
4193 buf.sysname,
4194 buf.release,
4195 buf.version,
4196 buf.machine,
4197 NULL
4199 arr_v = caml_copy_string_array (sar);
4201 Field (tup_v, 0) = Val_int (platid);
4202 Field (tup_v, 1) = arr_v;
4203 CAMLreturn (tup_v);
4206 CAMLprim value ml_cloexec (value fd_v)
4208 CAMLparam1 (fd_v);
4209 int fd = Int_val (fd_v);
4211 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4212 uerror ("fcntl", Nothing);
4214 CAMLreturn (Val_unit);
4217 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4219 CAMLparam2 (w_v, h_v);
4220 CAMLlocal1 (ret_v);
4221 struct bo *pbo;
4222 int w = Int_val (w_v);
4223 int h = Int_val (h_v);
4224 int cs = Int_val (cs_v);
4226 if (state.bo_usable) {
4227 pbo = calloc (sizeof (*pbo), 1);
4228 if (!pbo) {
4229 err (1, "calloc pbo");
4232 switch (cs) {
4233 case 0:
4234 case 1:
4235 pbo->size = w*h*4;
4236 break;
4237 case 2:
4238 pbo->size = w*h*2;
4239 break;
4240 default:
4241 errx (1, "%s: invalid colorspace %d", __func__, cs);
4244 state.glGenBuffersARB (1, &pbo->id);
4245 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4246 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4247 NULL, GL_STREAM_DRAW);
4248 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4249 GL_READ_WRITE);
4250 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4251 if (!pbo->ptr) {
4252 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4253 state.glDeleteBuffersARB (1, &pbo->id);
4254 free (pbo);
4255 ret_v = caml_copy_string ("0");
4257 else {
4258 int res;
4259 char *s;
4261 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4262 if (res < 0) {
4263 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4265 s = malloc (res+1);
4266 if (!s) {
4267 err (1, "malloc %d bytes failed", res+1);
4269 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4270 if (res < 0) {
4271 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4273 ret_v = caml_copy_string (s);
4274 free (s);
4277 else {
4278 ret_v = caml_copy_string ("0");
4280 CAMLreturn (ret_v);
4283 CAMLprim value ml_freepbo (value s_v)
4285 CAMLparam1 (s_v);
4286 char *s = String_val (s_v);
4287 struct tile *tile = parse_pointer (__func__, s);
4289 if (tile->pbo) {
4290 state.glDeleteBuffersARB (1, &tile->pbo->id);
4291 tile->pbo->id = -1;
4292 tile->pbo->ptr = NULL;
4293 tile->pbo->size = -1;
4295 CAMLreturn (Val_unit);
4298 CAMLprim value ml_unmappbo (value s_v)
4300 CAMLparam1 (s_v);
4301 char *s = String_val (s_v);
4302 struct tile *tile = parse_pointer (__func__, s);
4304 if (tile->pbo) {
4305 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4306 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4307 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4309 tile->pbo->ptr = NULL;
4310 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4312 CAMLreturn (Val_unit);
4315 static void setuppbo (void)
4317 #ifdef USE_EGL
4318 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4319 #else
4320 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4321 #endif
4322 state.bo_usable = GGPA (glBindBufferARB)
4323 && GGPA (glUnmapBufferARB)
4324 && GGPA (glMapBufferARB)
4325 && GGPA (glBufferDataARB)
4326 && GGPA (glGenBuffersARB)
4327 && GGPA (glDeleteBuffersARB);
4328 #undef GGPA
4331 CAMLprim value ml_bo_usable (value unit_v)
4333 CAMLparam1 (unit_v);
4334 CAMLreturn (Val_bool (state.bo_usable));
4337 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4339 CAMLparam3 (ptr_v, x_v, y_v);
4340 CAMLlocal2 (ret_v, tup_v);
4341 struct page *page;
4342 char *s = String_val (ptr_v);
4343 int x = Int_val (x_v), y = Int_val (y_v);
4344 struct pagedim *pdim;
4345 fz_point p;
4346 fz_matrix ctm;
4348 page = parse_pointer (__func__, s);
4349 pdim = &state.pagedims[page->pdimno];
4351 ret_v = Val_int (0);
4352 if (trylock (__func__)) {
4353 goto done;
4356 if (pdf_specifics (state.ctx, state.doc)) {
4357 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4358 ctm = state.pagedims[page->pdimno].tctm;
4360 else {
4361 ctm = fz_identity;
4363 p.x = x + pdim->bounds.x0;
4364 p.y = y + pdim->bounds.y0;
4366 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4367 fz_invert_matrix (&ctm, &ctm);
4368 fz_transform_point (&p, &ctm);
4370 tup_v = caml_alloc_tuple (2);
4371 ret_v = caml_alloc_small (1, 1);
4372 Field (tup_v, 0) = Val_int (p.x);
4373 Field (tup_v, 1) = Val_int (p.y);
4374 Field (ret_v, 0) = tup_v;
4376 unlock (__func__);
4377 done:
4378 CAMLreturn (ret_v);
4381 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4382 value x_v, value y_v)
4384 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4385 CAMLlocal1 (ret_v);
4386 struct page *page;
4387 char *s = String_val (ptr_v);
4388 int pageno = Int_val (pageno_v);
4389 int pdimno = Int_val (pdimno_v);
4390 double x = Double_val (x_v), y = Double_val (y_v);
4391 struct pagedim *pdim;
4392 fz_point p;
4393 fz_matrix ctm;
4395 ret_v = Val_int (0);
4396 lock (__func__);
4398 if (!*s) {
4399 page = loadpage (pageno, pdimno);
4401 else {
4402 page = parse_pointer (__func__, s);
4404 pdim = &state.pagedims[pdimno];
4406 if (pdf_specifics (state.ctx, state.doc)) {
4407 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4408 ctm = state.pagedims[page->pdimno].tctm;
4410 else {
4411 ctm = fz_identity;
4413 p.x = x + pdim->bounds.x0;
4414 p.y = y + pdim->bounds.y0;
4416 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4417 fz_transform_point (&p, &ctm);
4419 ret_v = caml_alloc_tuple (2);
4420 Field (ret_v, 0) = caml_copy_double (p.x);
4421 Field (ret_v, 1) = caml_copy_double (p.y);
4423 if (!*s) {
4424 freepage (page);
4426 unlock (__func__);
4427 CAMLreturn (ret_v);
4430 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4431 value contents_v)
4433 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4434 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4436 if (pdf) {
4437 pdf_annot *annot;
4438 struct page *page;
4439 fz_point p;
4440 char *s = String_val (ptr_v);
4442 page = parse_pointer (__func__, s);
4443 annot = pdf_create_annot (state.ctx, pdf,
4444 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4445 p.x = Int_val (x_v);
4446 p.y = Int_val (y_v);
4447 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4448 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4449 state.dirty = 1;
4451 CAMLreturn (Val_unit);
4454 CAMLprim value ml_delannot (value ptr_v, value n_v)
4456 CAMLparam2 (ptr_v, n_v);
4457 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4459 if (pdf) {
4460 struct page *page;
4461 char *s = String_val (ptr_v);
4462 struct slink *slink;
4464 page = parse_pointer (__func__, s);
4465 slink = &page->slinks[Int_val (n_v)];
4466 pdf_delete_annot (state.ctx, pdf,
4467 (pdf_page *) page->fzpage,
4468 (pdf_annot *) slink->u.annot);
4469 state.dirty = 1;
4471 CAMLreturn (Val_unit);
4474 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4476 CAMLparam3 (ptr_v, n_v, str_v);
4477 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4479 if (pdf) {
4480 struct page *page;
4481 char *s = String_val (ptr_v);
4482 struct slink *slink;
4484 page = parse_pointer (__func__, s);
4485 slink = &page->slinks[Int_val (n_v)];
4486 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4487 String_val (str_v));
4488 state.dirty = 1;
4490 CAMLreturn (Val_unit);
4493 CAMLprim value ml_hasunsavedchanges (value unit_v)
4495 CAMLparam1 (unit_v);
4496 CAMLreturn (Val_bool (state.dirty));
4499 CAMLprim value ml_savedoc (value path_v)
4501 CAMLparam1 (path_v);
4502 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4504 if (pdf) {
4505 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4507 CAMLreturn (Val_unit);
4510 static void makestippletex (void)
4512 const char pixels[] = "\xff\xff\0\0";
4513 glGenTextures (1, &state.stid);
4514 glBindTexture (GL_TEXTURE_1D, state.stid);
4515 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4516 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4517 glTexImage1D (
4518 GL_TEXTURE_1D,
4520 GL_ALPHA,
4523 GL_ALPHA,
4524 GL_UNSIGNED_BYTE,
4525 pixels
4529 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4531 return caml_copy_string (FZ_VERSION);
4534 #ifdef USE_FONTCONFIG
4535 static struct {
4536 int inited;
4537 FcConfig *config;
4538 } fc;
4540 static fz_font *fc_load_system_font_func (fz_context *ctx,
4541 const char *name,
4542 int bold,
4543 int italic,
4544 int UNUSED_ATTR needs_exact_metrics)
4546 char *buf;
4547 size_t i, size;
4548 fz_font *font;
4549 FcChar8 *path;
4550 FcResult result;
4551 FcPattern *pat, *pat1;
4553 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4554 name, bold, italic, needs_exact_metrics);
4555 if (!fc.inited) {
4556 fc.inited = 1;
4557 fc.config = FcInitLoadConfigAndFonts ();
4558 if (!fc.config) {
4559 lprintf ("FcInitLoadConfigAndFonts failed\n");
4560 return NULL;
4563 if (!fc.config) return NULL;
4565 size = strlen (name);
4566 if (bold) size += sizeof (":bold") - 1;
4567 if (italic) size += sizeof (":italic") - 1;
4568 size += 1;
4570 buf = malloc (size);
4571 if (!buf) {
4572 err (1, "malloc %zu failed", size);
4575 strcpy (buf, name);
4576 if (bold && italic) {
4577 strcat (buf, ":bold:italic");
4579 else {
4580 if (bold) strcat (buf, ":bold");
4581 if (italic) strcat (buf, ":italic");
4583 for (i = 0; i < size; ++i) {
4584 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4587 lprintf ("fcbuf=%s\n", buf);
4588 pat = FcNameParse ((FcChar8 *) buf);
4589 if (!pat) {
4590 printd ("emsg FcNameParse failed\n");
4591 free (buf);
4592 return NULL;
4595 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4596 printd ("emsg FcConfigSubstitute failed\n");
4597 free (buf);
4598 return NULL;
4600 FcDefaultSubstitute (pat);
4602 pat1 = FcFontMatch (fc.config, pat, &result);
4603 if (!pat1) {
4604 printd ("emsg FcFontMatch failed\n");
4605 FcPatternDestroy (pat);
4606 free (buf);
4607 return NULL;
4610 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4611 printd ("emsg FcPatternGetString failed\n");
4612 FcPatternDestroy (pat);
4613 FcPatternDestroy (pat1);
4614 free (buf);
4615 return NULL;
4618 #if 0
4619 printd ("emsg name=%s path=%s\n", name, path);
4620 #endif
4621 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4622 FcPatternDestroy (pat);
4623 FcPatternDestroy (pat1);
4624 free (buf);
4625 return font;
4627 #endif
4629 CAMLprim value ml_init (value csock_v, value params_v)
4631 CAMLparam2 (csock_v, params_v);
4632 CAMLlocal2 (trim_v, fuzz_v);
4633 int ret;
4634 int texcount;
4635 char *fontpath;
4636 int colorspace;
4637 int mustoresize;
4638 int haspboext;
4640 state.csock = Int_val (csock_v);
4641 state.rotate = Int_val (Field (params_v, 0));
4642 state.fitmodel = Int_val (Field (params_v, 1));
4643 trim_v = Field (params_v, 2);
4644 texcount = Int_val (Field (params_v, 3));
4645 state.sliceheight = Int_val (Field (params_v, 4));
4646 mustoresize = Int_val (Field (params_v, 5));
4647 colorspace = Int_val (Field (params_v, 6));
4648 fontpath = String_val (Field (params_v, 7));
4650 if (caml_string_length (Field (params_v, 8)) > 0) {
4651 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4653 if (!state.trimcachepath) {
4654 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4655 strerror (errno));
4658 haspboext = Bool_val (Field (params_v, 9));
4660 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4661 fz_register_document_handlers (state.ctx);
4663 #ifdef USE_FONTCONFIG
4664 if (Bool_val (Field (params_v, 10))) {
4665 fz_install_load_system_font_funcs (
4666 state.ctx, fc_load_system_font_func, NULL
4669 #endif
4671 state.trimmargins = Bool_val (Field (trim_v, 0));
4672 fuzz_v = Field (trim_v, 1);
4673 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4674 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4675 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4676 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4678 set_tex_params (colorspace);
4680 if (*fontpath) {
4681 #ifndef USE_FONTCONFIG
4682 state.face = load_font (fontpath);
4683 #else
4684 FcChar8 *path;
4685 FcResult result;
4686 char *buf = fontpath;
4687 FcPattern *pat, *pat1;
4689 fc.inited = 1;
4690 fc.config = FcInitLoadConfigAndFonts ();
4691 if (!fc.config) {
4692 errx (1, "FcInitLoadConfigAndFonts failed");
4695 pat = FcNameParse ((FcChar8 *) buf);
4696 if (!pat) {
4697 errx (1, "FcNameParse failed");
4700 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4701 errx (1, "FcConfigSubstitute failed");
4703 FcDefaultSubstitute (pat);
4705 pat1 = FcFontMatch (fc.config, pat, &result);
4706 if (!pat1) {
4707 errx (1, "FcFontMatch failed");
4710 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4711 errx (1, "FcPatternGetString failed");
4714 state.face = load_font ((char *) path);
4715 FcPatternDestroy (pat);
4716 FcPatternDestroy (pat1);
4717 #endif
4719 else {
4720 int len;
4721 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4722 0, 0, &len);
4723 state.face = load_builtin_font (data, len);
4725 if (!state.face) _exit (1);
4727 realloctexts (texcount);
4729 if (haspboext) {
4730 setuppbo ();
4733 makestippletex ();
4735 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4736 if (ret) {
4737 errx (1, "pthread_create: %s", strerror (ret));
4740 CAMLreturn (Val_unit);