Merge branch 'master' of https://github.com/ghennequin/llpp into ghennequin-master
[llpp.git] / link.c
blob699aacb47892f2bbf24483fce2f7f122f8ecc403
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 (trimf);
877 fz_var (cxcount);
878 start = now ();
880 if (state.trimmargins && state.trimcachepath) {
881 trimf = fopen (state.trimcachepath, "rb");
882 if (!trimf) {
883 trimf = fopen (state.trimcachepath, "wb");
884 trimw = 1;
888 if (state.trimmargins || pdf || !state.cxack)
889 cxcount = state.pagecount;
890 else
891 cxcount = MIN (state.pagecount, 1);
893 if (pdf) {
894 pdf_obj *obj;
895 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
896 "Root/Pages/MediaBox");
897 pdf_to_rect (ctx, obj, &rootmediabox);
900 #ifdef CACHE_PAGEREFS
901 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
902 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
903 if (!state.pdflut.objs) {
904 err (1, "malloc pageobjs %zu %d %zu failed",
905 sizeof (*state.pdflut.objs), cxcount,
906 sizeof (*state.pdflut.objs) * cxcount);
908 state.pdflut.count = cxcount;
909 pdf_load_page_objs (pdf);
910 state.pdflut.pdf = pdf;
912 #endif
914 for (pageno = 0; pageno < cxcount; ++pageno) {
915 int rotate = 0;
916 struct pagedim *p;
917 fz_rect mediabox;
919 fz_var (rotate);
920 if (pdf) {
921 pdf_obj *pageref, *pageobj;
923 #ifdef CACHE_PAGEREFS
924 pageref = state.pdflut.objs[pageno];
925 #else
926 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
927 #endif
928 pageobj = pdf_resolve_indirect (ctx, pageref);
930 if (state.trimmargins) {
931 pdf_obj *obj;
932 pdf_page *page;
934 fz_try (ctx) {
935 page = pdf_load_page (ctx, pdf, pageno);
936 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
937 trim = state.trimanew || !obj;
938 if (trim) {
939 fz_rect rect;
940 fz_matrix ctm;
941 fz_device *dev;
943 dev = fz_new_bbox_device (ctx, &rect);
944 dev->hints |= FZ_IGNORE_SHADE;
945 fz_invert_matrix (&ctm, &page->ctm);
946 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
947 fz_drop_device (ctx, dev);
949 rect.x0 += state.trimfuzz.x0;
950 rect.x1 += state.trimfuzz.x1;
951 rect.y0 += state.trimfuzz.y0;
952 rect.y1 += state.trimfuzz.y1;
953 fz_transform_rect (&rect, &ctm);
954 fz_intersect_rect (&rect, &page->mediabox);
956 if (fz_is_empty_rect (&rect)) {
957 mediabox = page->mediabox;
959 else {
960 mediabox = rect;
963 obj = pdf_new_array (ctx, pdf, 4);
964 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
965 mediabox.x0));
966 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
967 mediabox.y0));
968 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
969 mediabox.x1));
970 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
971 mediabox.y1));
972 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
974 else {
975 mediabox.x0 = pdf_to_real (ctx,
976 pdf_array_get (ctx, obj, 0));
977 mediabox.y0 = pdf_to_real (ctx,
978 pdf_array_get (ctx, obj, 1));
979 mediabox.x1 = pdf_to_real (ctx,
980 pdf_array_get (ctx, obj, 2));
981 mediabox.y1 = pdf_to_real (ctx,
982 pdf_array_get (ctx, obj, 3));
985 rotate = page->rotate;
986 fz_drop_page (ctx, &page->super);
988 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
989 if (show) {
990 printd ("progress %f Trimming %d",
991 (double) (pageno + 1) / state.pagecount,
992 pageno + 1);
995 fz_catch (ctx) {
996 fprintf (stderr, "failed to load page %d\n", pageno+1);
999 else {
1000 int empty = 0;
1001 fz_rect cropbox;
1003 pdf_to_rect (ctx,
1004 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1005 &mediabox);
1006 if (fz_is_empty_rect (&mediabox)) {
1007 mediabox.x0 = 0;
1008 mediabox.y0 = 0;
1009 mediabox.x1 = 612;
1010 mediabox.y1 = 792;
1011 empty = 1;
1014 pdf_to_rect (ctx,
1015 pdf_dict_gets (ctx, pageobj, "CropBox"),
1016 &cropbox);
1017 if (!fz_is_empty_rect (&cropbox)) {
1018 if (empty) {
1019 mediabox = cropbox;
1021 else {
1022 fz_intersect_rect (&mediabox, &cropbox);
1025 else {
1026 if (empty) {
1027 if (fz_is_empty_rect (&rootmediabox)) {
1028 fprintf (stderr,
1029 "cannot find page size for page %d\n",
1030 pageno+1);
1032 else {
1033 mediabox = rootmediabox;
1037 rotate = pdf_to_int (ctx,
1038 pdf_dict_gets (ctx, pageobj, "Rotate"));
1041 else {
1042 if (state.trimmargins && trimw) {
1043 fz_page *page;
1045 fz_try (ctx) {
1046 page = fz_load_page (ctx, state.doc, pageno);
1047 fz_bound_page (ctx, page, &mediabox);
1048 rotate = 0;
1049 if (state.trimmargins) {
1050 fz_rect rect;
1051 fz_device *dev;
1053 dev = fz_new_bbox_device (ctx, &rect);
1054 dev->hints |= FZ_IGNORE_SHADE;
1055 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1056 fz_drop_device (ctx, dev);
1058 rect.x0 += state.trimfuzz.x0;
1059 rect.x1 += state.trimfuzz.x1;
1060 rect.y0 += state.trimfuzz.y0;
1061 rect.y1 += state.trimfuzz.y1;
1062 fz_intersect_rect (&rect, &mediabox);
1064 if (!fz_is_empty_rect (&rect)) {
1065 mediabox = rect;
1068 fz_drop_page (ctx, page);
1069 if (!state.cxack) {
1070 printd ("progress %f loading %d",
1071 (double) (pageno + 1) / state.pagecount,
1072 pageno + 1);
1075 fz_catch (ctx) {
1077 if (trimf) {
1078 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1079 if (n - 1) {
1080 err (1, "fwrite trim mediabox");
1084 else {
1085 if (trimf) {
1086 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1087 if (n - 1) {
1088 err (1, "fread trim mediabox %d", pageno);
1091 else {
1092 fz_page *page;
1093 fz_try (ctx) {
1094 page = fz_load_page (ctx, state.doc, pageno);
1095 fz_bound_page (ctx, page, &mediabox);
1096 fz_drop_page (ctx, page);
1098 show = !state.trimmargins && pageno % 20 == 0;
1099 if (show) {
1100 printd ("progress %f Gathering dimensions %d",
1101 (double) (pageno) / state.pagecount,
1102 pageno);
1105 fz_catch (ctx) {
1106 fprintf (stderr, "failed to load page %d\n", pageno);
1112 if (state.pagedimcount == 0
1113 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1114 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1115 size_t size;
1117 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1118 state.pagedims = realloc (state.pagedims, size);
1119 if (!state.pagedims) {
1120 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1121 size, state.pagedimcount + 1);
1124 p = &state.pagedims[state.pagedimcount++];
1125 p->rotate = rotate;
1126 p->mediabox = mediabox;
1127 p->pageno = pageno;
1130 end = now ();
1131 if (!wthack) {
1132 printd ("progress 1 %s %d pages in %f seconds",
1133 state.trimmargins ? "Trimmed" : "Processed",
1134 state.pagecount, end - start);
1136 state.trimanew = 0;
1137 if (trimf) {
1138 if (fclose (trimf)) {
1139 err (1, "fclose");
1144 static void layout (void)
1146 int pindex;
1147 fz_rect box;
1148 fz_matrix ctm, rm;
1149 struct pagedim *p = p;
1150 double zw, w, maxw = 0.0, zoom = zoom;
1152 if (state.pagedimcount == 0) return;
1154 switch (state.fitmodel) {
1155 case FitProportional:
1156 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1157 double x0, x1;
1159 p = &state.pagedims[pindex];
1160 fz_rotate (&rm, p->rotate + state.rotate);
1161 box = p->mediabox;
1162 fz_transform_rect (&box, &rm);
1164 x0 = MIN (box.x0, box.x1);
1165 x1 = MAX (box.x0, box.x1);
1167 w = x1 - x0;
1168 maxw = MAX (w, maxw);
1169 zoom = state.w / maxw;
1171 break;
1173 case FitPage:
1174 maxw = state.w;
1175 break;
1177 case FitWidth:
1178 break;
1180 default:
1181 ARSERT (0 && state.fitmodel);
1184 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1185 fz_rect rect;
1186 fz_matrix tm, sm;
1188 p = &state.pagedims[pindex];
1189 fz_rotate (&ctm, state.rotate);
1190 fz_rotate (&rm, p->rotate + state.rotate);
1191 box = p->mediabox;
1192 fz_transform_rect (&box, &rm);
1193 w = box.x1 - box.x0;
1194 switch (state.fitmodel) {
1195 case FitProportional:
1196 p->left = ((maxw - w) * zoom) / 2.0;
1197 break;
1198 case FitPage:
1200 double zh, h;
1201 zw = maxw / w;
1202 h = box.y1 - box.y0;
1203 zh = state.h / h;
1204 zoom = MIN (zw, zh);
1205 p->left = (maxw - (w * zoom)) / 2.0;
1207 break;
1208 case FitWidth:
1209 p->left = 0;
1210 zoom = state.w / w;
1211 break;
1214 fz_scale (&p->zoomctm, zoom, zoom);
1215 fz_concat (&ctm, &p->zoomctm, &ctm);
1217 fz_rotate (&rm, p->rotate);
1218 p->pagebox = p->mediabox;
1219 fz_transform_rect (&p->pagebox, &rm);
1220 p->pagebox.x1 -= p->pagebox.x0;
1221 p->pagebox.y1 -= p->pagebox.y0;
1222 p->pagebox.x0 = 0;
1223 p->pagebox.y0 = 0;
1224 rect = p->pagebox;
1225 fz_transform_rect (&rect, &ctm);
1226 fz_round_rect (&p->bounds, &rect);
1227 p->ctm = ctm;
1229 fz_translate (&tm, 0, -p->mediabox.y1);
1230 fz_scale (&sm, zoom, -zoom);
1231 fz_concat (&ctm, &tm, &sm);
1232 fz_concat (&p->lctm, &ctm, &rm);
1234 p->tctmready = 0;
1237 do {
1238 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1239 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1240 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1241 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1242 int boundw = x1 - x0;
1243 int boundh = y1 - y0;
1245 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1246 } while (p-- != state.pagedims);
1249 static
1250 struct anchor { int n; int x; int y; int w; int h; }
1251 desttoanchor (fz_link_dest *dest)
1253 int i;
1254 struct anchor a;
1255 struct pagedim *pdim = state.pagedims;
1257 a.n = -1;
1258 a.x = 0;
1259 a.y = 0;
1260 for (i = 0; i < state.pagedimcount; ++i) {
1261 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1262 break;
1263 pdim = &state.pagedims[i];
1265 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1266 fz_point p;
1267 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1268 p.x = dest->ld.gotor.lt.x;
1269 else
1270 p.x = 0.0;
1271 p.y = dest->ld.gotor.lt.y;
1272 fz_transform_point (&p, &pdim->lctm);
1273 a.x = p.x;
1274 a.y = p.y;
1276 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1277 double x0, x1, y0, y1;
1279 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1280 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1281 a.w = x1 - x0;
1282 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1283 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1284 a.h = y1 - y0;
1285 a.n = dest->ld.gotor.page;
1287 return a;
1290 static void recurse_outline (fz_outline *outline, int level)
1292 while (outline) {
1293 switch (outline->dest.kind) {
1294 case FZ_LINK_GOTO:
1296 struct anchor a = desttoanchor (&outline->dest);
1298 if (a.n >= 0) {
1299 printd ("o %d %d %d %d %s",
1300 level, a.n, a.y, a.h, outline->title);
1303 break;
1305 case FZ_LINK_URI:
1306 printd ("ou %d %" FMT_s " %s %s", level,
1307 strlen (outline->title), outline->title,
1308 outline->dest.ld.uri.uri);
1309 break;
1311 case FZ_LINK_NONE:
1312 printd ("on %d %s", level, outline->title);
1313 break;
1315 default:
1316 printd ("emsg Unhandled outline kind %d for %s\n",
1317 outline->dest.kind, outline->title);
1318 break;
1320 if (outline->down) {
1321 recurse_outline (outline->down, level + 1);
1323 outline = outline->next;
1327 static void process_outline (void)
1329 fz_outline *outline;
1331 if (!state.needoutline || !state.pagedimcount) return;
1333 state.needoutline = 0;
1334 outline = fz_load_outline (state.ctx, state.doc);
1335 if (outline) {
1336 recurse_outline (outline, 0);
1337 fz_drop_outline (state.ctx, outline);
1341 static char *strofspan (fz_stext_span *span)
1343 char *p;
1344 char utf8[10];
1345 fz_stext_char *ch;
1346 size_t size = 0, cap = 80;
1348 p = malloc (cap + 1);
1349 if (!p) return NULL;
1351 for (ch = span->text; ch < span->text + span->len; ++ch) {
1352 int n = fz_runetochar (utf8, ch->c);
1353 if (size + n > cap) {
1354 cap *= 2;
1355 p = realloc (p, cap + 1);
1356 if (!p) return NULL;
1359 memcpy (p + size, utf8, n);
1360 size += n;
1362 p[size] = 0;
1363 return p;
1366 static int matchspan (regex_t *re, fz_stext_span *span,
1367 int stop, int pageno, double start)
1369 int ret;
1370 char *p;
1371 regmatch_t rm;
1372 int a, b, c;
1373 fz_rect sb, eb;
1374 fz_point p1, p2, p3, p4;
1376 p = strofspan (span);
1377 if (!p) return -1;
1379 ret = regexec (re, p, 1, &rm, 0);
1380 if (ret) {
1381 free (p);
1382 if (ret != REG_NOMATCH) {
1383 size_t size;
1384 char errbuf[80];
1385 size = regerror (ret, re, errbuf, sizeof (errbuf));
1386 printd ("msg regexec error `%.*s'",
1387 (int) size, errbuf);
1388 return -1;
1390 return 0;
1392 else {
1393 int l = span->len;
1395 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1396 c += fz_runelen (span->text[a].c);
1398 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1399 c += fz_runelen (span->text[b].c);
1402 if (fz_runelen (span->text[b].c) > 1) {
1403 b = MAX (0, b-1);
1406 fz_stext_char_bbox (state.ctx, &sb, span, a);
1407 fz_stext_char_bbox (state.ctx, &eb, span, b);
1409 p1.x = sb.x0;
1410 p1.y = sb.y0;
1411 p2.x = eb.x1;
1412 p2.y = sb.y0;
1413 p3.x = eb.x1;
1414 p3.y = eb.y1;
1415 p4.x = sb.x0;
1416 p4.y = eb.y1;
1418 if (!stop) {
1419 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1420 pageno, 1,
1421 p1.x, p1.y,
1422 p2.x, p2.y,
1423 p3.x, p3.y,
1424 p4.x, p4.y);
1426 printd ("progress 1 found at %d `%.*s' in %f sec",
1427 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1428 now () - start);
1430 else {
1431 printd ("match %d %d %f %f %f %f %f %f %f %f",
1432 pageno, 2,
1433 p1.x, p1.y,
1434 p2.x, p2.y,
1435 p3.x, p3.y,
1436 p4.x, p4.y);
1438 free (p);
1439 return 1;
1443 static int compareblocks (const void *l, const void *r)
1445 fz_stext_block const *ls = l;
1446 fz_stext_block const *rs = r;
1447 return ls->bbox.y0 - rs->bbox.y0;
1450 /* wishful thinking function */
1451 static void search (regex_t *re, int pageno, int y, int forward)
1453 int i, j;
1454 fz_device *tdev;
1455 fz_stext_page *text;
1456 fz_stext_sheet *sheet;
1457 struct pagedim *pdim, *pdimprev;
1458 int stop = 0, niters = 0;
1459 double start, end;
1460 fz_page *page;
1462 start = now ();
1463 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1464 if (niters++ == 5) {
1465 niters = 0;
1466 if (hasdata ()) {
1467 printd ("progress 1 attention requested aborting search at %d",
1468 pageno);
1469 stop = 1;
1471 else {
1472 printd ("progress %f searching in page %d",
1473 (double) (pageno + 1) / state.pagecount,
1474 pageno);
1477 pdimprev = NULL;
1478 for (i = 0; i < state.pagedimcount; ++i) {
1479 pdim = &state.pagedims[i];
1480 if (pdim->pageno == pageno) {
1481 goto found;
1483 if (pdim->pageno > pageno) {
1484 pdim = pdimprev;
1485 goto found;
1487 pdimprev = pdim;
1489 pdim = pdimprev;
1490 found:
1492 sheet = fz_new_stext_sheet (state.ctx);
1493 text = fz_new_stext_page (state.ctx);
1494 tdev = fz_new_stext_device (state.ctx, sheet, text);
1496 page = fz_load_page (state.ctx, state.doc, pageno);
1498 fz_matrix ctm = pagectm1 (page, pdim);
1499 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1502 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1503 fz_drop_device (state.ctx, tdev);
1505 for (j = 0; j < text->len; ++j) {
1506 int k;
1507 fz_page_block *pb;
1508 fz_stext_block *block;
1510 pb = &text->blocks[forward ? j : text->len - 1 - j];
1511 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1512 block = pb->u.text;
1514 for (k = 0; k < block->len; ++k) {
1515 fz_stext_line *line;
1516 fz_stext_span *span;
1518 if (forward) {
1519 line = &block->lines[k];
1520 if (line->bbox.y0 < y + 1) continue;
1522 else {
1523 line = &block->lines[block->len - 1 - k];
1524 if (line->bbox.y0 > y - 1) continue;
1527 for (span = line->first_span; span; span = span->next) {
1528 switch (matchspan (re, span, stop, pageno, start)) {
1529 case 0: break;
1530 case 1: stop = 1; break;
1531 case -1: stop = 1; goto endloop;
1536 if (forward) {
1537 pageno += 1;
1538 y = 0;
1540 else {
1541 pageno -= 1;
1542 y = INT_MAX;
1544 endloop:
1545 fz_drop_stext_page (state.ctx, text);
1546 fz_drop_stext_sheet (state.ctx, sheet);
1547 fz_drop_page (state.ctx, page);
1549 end = now ();
1550 if (!stop) {
1551 printd ("progress 1 no matches %f sec", end - start);
1553 printd ("clearrects");
1556 static void set_tex_params (int colorspace)
1558 union {
1559 unsigned char b;
1560 unsigned int s;
1561 } endianness = {1};
1563 switch (colorspace) {
1564 case 0:
1565 state.texiform = GL_RGBA8;
1566 state.texform = GL_RGBA;
1567 state.texty = GL_UNSIGNED_BYTE;
1568 state.colorspace = fz_device_rgb (state.ctx);
1569 break;
1570 case 1:
1571 state.texiform = GL_RGBA8;
1572 state.texform = GL_BGRA;
1573 state.texty = endianness.s > 1
1574 ? GL_UNSIGNED_INT_8_8_8_8
1575 : GL_UNSIGNED_INT_8_8_8_8_REV;
1576 state.colorspace = fz_device_bgr (state.ctx);
1577 break;
1578 case 2:
1579 state.texiform = GL_LUMINANCE_ALPHA;
1580 state.texform = GL_LUMINANCE_ALPHA;
1581 state.texty = GL_UNSIGNED_BYTE;
1582 state.colorspace = fz_device_gray (state.ctx);
1583 break;
1584 default:
1585 errx (1, "invalid colorspce %d", colorspace);
1589 static void realloctexts (int texcount)
1591 size_t size;
1593 if (texcount == state.texcount) return;
1595 if (texcount < state.texcount) {
1596 glDeleteTextures (state.texcount - texcount,
1597 state.texids + texcount);
1600 size = texcount * sizeof (*state.texids);
1601 state.texids = realloc (state.texids, size);
1602 if (!state.texids) {
1603 err (1, "realloc texids %" FMT_s, size);
1606 size = texcount * sizeof (*state.texowners);
1607 state.texowners = realloc (state.texowners, size);
1608 if (!state.texowners) {
1609 err (1, "realloc texowners %" FMT_s, size);
1611 if (texcount > state.texcount) {
1612 int i;
1614 glGenTextures (texcount - state.texcount,
1615 state.texids + state.texcount);
1616 for (i = state.texcount; i < texcount; ++i) {
1617 state.texowners[i].w = -1;
1618 state.texowners[i].slice = NULL;
1621 state.texcount = texcount;
1622 state.texindex = 0;
1625 static char *mbtoutf8 (char *s)
1627 char *p, *r;
1628 wchar_t *tmp;
1629 size_t i, ret, len;
1631 len = mbstowcs (NULL, s, strlen (s));
1632 if (len == 0) {
1633 return s;
1635 else {
1636 if (len == (size_t) -1) {
1637 return s;
1641 tmp = malloc (len * sizeof (wchar_t));
1642 if (!tmp) {
1643 return s;
1646 ret = mbstowcs (tmp, s, len);
1647 if (ret == (size_t) -1) {
1648 free (tmp);
1649 return s;
1652 len = 0;
1653 for (i = 0; i < ret; ++i) {
1654 len += fz_runelen (tmp[i]);
1657 p = r = malloc (len + 1);
1658 if (!r) {
1659 free (tmp);
1660 return s;
1663 for (i = 0; i < ret; ++i) {
1664 p += fz_runetochar (p, tmp[i]);
1666 *p = 0;
1667 free (tmp);
1668 return r;
1671 CAMLprim value ml_mbtoutf8 (value s_v)
1673 CAMLparam1 (s_v);
1674 CAMLlocal1 (ret_v);
1675 char *s, *r;
1677 s = String_val (s_v);
1678 r = mbtoutf8 (s);
1679 if (r == s) {
1680 ret_v = s_v;
1682 else {
1683 ret_v = caml_copy_string (r);
1684 free (r);
1686 CAMLreturn (ret_v);
1689 static void * mainloop (void UNUSED_ATTR *unused)
1691 char *p = NULL;
1692 int len, ret, oldlen = 0;
1694 fz_var (p);
1695 fz_var (oldlen);
1696 for (;;) {
1697 len = readlen (state.csock);
1698 if (len == 0) {
1699 errx (1, "readlen returned 0");
1702 if (oldlen < len + 1) {
1703 p = realloc (p, len + 1);
1704 if (!p) {
1705 err (1, "realloc %d failed", len + 1);
1707 oldlen = len + 1;
1709 readdata (state.csock, p, len);
1710 p[len] = 0;
1712 if (!strncmp ("open", p, 4)) {
1713 int wthack, off, ok = 0;
1714 char *password;
1715 char *filename;
1716 char *utf8filename;
1717 size_t filenamelen;
1719 fz_var (ok);
1720 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1721 if (ret != 2) {
1722 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1725 filename = p + 5 + off;
1726 filenamelen = strlen (filename);
1727 password = filename + filenamelen + 1;
1729 lock ("open");
1730 fz_try (state.ctx) {
1731 ok = openxref (filename, password);
1733 fz_catch (state.ctx) {
1734 utf8filename = mbtoutf8 (filename);
1735 printd ("msg Could not open %s", utf8filename);
1737 if (ok) {
1738 pdfinfo ();
1739 initpdims (wthack);
1741 unlock ("open");
1743 if (ok) {
1744 if (!wthack) {
1745 utf8filename = mbtoutf8 (filename);
1746 printd ("msg Opened %s (press h/F1 to get help)",
1747 utf8filename);
1748 if (utf8filename != filename) {
1749 free (utf8filename);
1752 state.needoutline = 1;
1755 else if (!strncmp ("cs", p, 2)) {
1756 int i, colorspace;
1758 ret = sscanf (p + 2, " %d", &colorspace);
1759 if (ret != 1) {
1760 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1762 lock ("cs");
1763 set_tex_params (colorspace);
1764 for (i = 0; i < state.texcount; ++i) {
1765 state.texowners[i].w = -1;
1766 state.texowners[i].slice = NULL;
1768 unlock ("cs");
1770 else if (!strncmp ("freepage", p, 8)) {
1771 void *ptr;
1773 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1774 if (ret != 1) {
1775 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1777 freepage (ptr);
1779 else if (!strncmp ("freetile", p, 8)) {
1780 void *ptr;
1782 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1783 if (ret != 1) {
1784 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1786 freetile (ptr);
1788 else if (!strncmp ("search", p, 6)) {
1789 int icase, pageno, y, len2, forward;
1790 char *pattern;
1791 regex_t re;
1793 ret = sscanf (p + 6, " %d %d %d %d,%n",
1794 &icase, &pageno, &y, &forward, &len2);
1795 if (ret != 4) {
1796 errx (1, "malformed search `%s' ret=%d", p, ret);
1799 pattern = p + 6 + len2;
1800 ret = regcomp (&re, pattern,
1801 REG_EXTENDED | (icase ? REG_ICASE : 0));
1802 if (ret) {
1803 char errbuf[80];
1804 size_t size;
1806 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1807 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1809 else {
1810 search (&re, pageno, y, forward);
1811 regfree (&re);
1814 else if (!strncmp ("geometry", p, 8)) {
1815 int w, h, fitmodel;
1817 printd ("clear");
1818 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1819 if (ret != 3) {
1820 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1823 lock ("geometry");
1824 state.h = h;
1825 if (w != state.w) {
1826 int i;
1827 state.w = w;
1828 for (i = 0; i < state.texcount; ++i) {
1829 state.texowners[i].slice = NULL;
1832 state.fitmodel = fitmodel;
1833 layout ();
1834 process_outline ();
1836 state.gen++;
1837 unlock ("geometry");
1838 printd ("continue %d", state.pagecount);
1840 else if (!strncmp ("reqlayout", p, 9)) {
1841 char *nameddest;
1842 int rotate, off, h;
1843 unsigned int fitmodel;
1844 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1846 printd ("clear");
1847 ret = sscanf (p + 9, " %d %u %d %n",
1848 &rotate, &fitmodel, &h, &off);
1849 if (ret != 3) {
1850 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1852 lock ("reqlayout");
1853 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1854 state.gen += 1;
1856 state.rotate = rotate;
1857 state.fitmodel = fitmodel;
1858 state.h = h;
1859 layout ();
1860 process_outline ();
1862 nameddest = p + 9 + off;
1863 if (pdf && nameddest && *nameddest) {
1864 struct anchor a;
1865 fz_link_dest dest;
1866 pdf_obj *needle, *obj;
1868 needle = pdf_new_string (state.ctx, pdf, nameddest,
1869 strlen (nameddest));
1870 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1871 if (obj) {
1872 dest = pdf_parse_link_dest (state.ctx, pdf,
1873 FZ_LINK_GOTO, obj);
1875 a = desttoanchor (&dest);
1876 if (a.n >= 0) {
1877 printd ("a %d %d %d", a.n, a.x, a.y);
1879 else {
1880 printd ("emsg failed to parse destination `%s'\n",
1881 nameddest);
1884 else {
1885 printd ("emsg destination `%s' not found\n",
1886 nameddest);
1888 pdf_drop_obj (state.ctx, needle);
1891 state.gen++;
1892 unlock ("reqlayout");
1893 printd ("continue %d", state.pagecount);
1895 else if (!strncmp ("page", p, 4)) {
1896 double a, b;
1897 struct page *page;
1898 int pageno, pindex;
1900 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1901 if (ret != 2) {
1902 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1905 lock ("page");
1906 a = now ();
1907 page = loadpage (pageno, pindex);
1908 b = now ();
1909 unlock ("page");
1911 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1913 else if (!strncmp ("tile", p, 4)) {
1914 int x, y, w, h;
1915 struct page *page;
1916 struct tile *tile;
1917 double a, b;
1918 void *data;
1920 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1921 SCN_ptr_cast (&page), &x, &y, &w, &h,
1922 SCN_ptr_cast (&data));
1923 if (ret != 6) {
1924 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1927 lock ("tile");
1928 a = now ();
1929 tile = rendertile (page, x, y, w, h, data);
1930 b = now ();
1931 unlock ("tile");
1933 printd ("tile %d %d %" FMT_ptr " %u %f",
1934 x, y,
1935 FMT_ptr_cast (tile),
1936 tile->w * tile->h * tile->pixmap->n,
1937 b - a);
1939 else if (!strncmp ("trimset", p, 7)) {
1940 fz_irect fuzz;
1941 int trimmargins;
1943 ret = sscanf (p + 7, " %d %d %d %d %d",
1944 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1945 if (ret != 5) {
1946 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1948 lock ("trimset");
1949 state.trimmargins = trimmargins;
1950 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1951 state.trimanew = 1;
1952 state.trimfuzz = fuzz;
1954 unlock ("trimset");
1956 else if (!strncmp ("settrim", p, 7)) {
1957 fz_irect fuzz;
1958 int trimmargins;
1960 ret = sscanf (p + 7, " %d %d %d %d %d",
1961 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1962 if (ret != 5) {
1963 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1965 printd ("clear");
1966 lock ("settrim");
1967 state.trimmargins = trimmargins;
1968 state.needoutline = 1;
1969 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1970 state.trimanew = 1;
1971 state.trimfuzz = fuzz;
1973 state.pagedimcount = 0;
1974 free (state.pagedims);
1975 state.pagedims = NULL;
1976 initpdims (0);
1977 layout ();
1978 process_outline ();
1979 unlock ("settrim");
1980 printd ("continue %d", state.pagecount);
1982 else if (!strncmp ("sliceh", p, 6)) {
1983 int h;
1985 ret = sscanf (p + 6, " %d", &h);
1986 if (ret != 1) {
1987 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1989 if (h != state.sliceheight) {
1990 int i;
1992 state.sliceheight = h;
1993 for (i = 0; i < state.texcount; ++i) {
1994 state.texowners[i].w = -1;
1995 state.texowners[i].h = -1;
1996 state.texowners[i].slice = NULL;
2000 else if (!strncmp ("interrupt", p, 9)) {
2001 printd ("vmsg interrupted");
2003 else {
2004 errx (1, "unknown command %.*s", len, p);
2007 return 0;
2010 CAMLprim value ml_realloctexts (value texcount_v)
2012 CAMLparam1 (texcount_v);
2013 int ok;
2015 if (trylock (__func__)) {
2016 ok = 0;
2017 goto done;
2019 realloctexts (Int_val (texcount_v));
2020 ok = 1;
2021 unlock (__func__);
2023 done:
2024 CAMLreturn (Val_bool (ok));
2027 static void recti (int x0, int y0, int x1, int y1)
2029 GLfloat *v = state.vertices;
2031 glVertexPointer (2, GL_FLOAT, 0, v);
2032 v[0] = x0; v[1] = y0;
2033 v[2] = x1; v[3] = y0;
2034 v[4] = x0; v[5] = y1;
2035 v[6] = x1; v[7] = y1;
2036 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2039 static void showsel (struct page *page, int ox, int oy)
2041 int seen = 0;
2042 fz_irect bbox;
2043 fz_rect rect;
2044 fz_stext_line *line;
2045 fz_page_block *pageb;
2046 fz_stext_block *block;
2047 struct mark first, last;
2048 unsigned char selcolor[] = {15,15,15,140};
2050 first = page->fmark;
2051 last = page->lmark;
2053 if (!first.span || !last.span) return;
2055 glEnable (GL_BLEND);
2056 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2057 glColor4ubv (selcolor);
2059 ox += state.pagedims[page->pdimno].bounds.x0;
2060 oy += state.pagedims[page->pdimno].bounds.y0;
2061 for (pageb = page->text->blocks;
2062 pageb < page->text->blocks + page->text->len;
2063 ++pageb) {
2064 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2065 block = pageb->u.text;
2067 for (line = block->lines;
2068 line < block->lines + block->len;
2069 ++line) {
2070 fz_stext_span *span;
2071 rect = fz_empty_rect;
2073 for (span = line->first_span; span; span = span->next) {
2074 int i, j, k;
2075 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2077 j = 0;
2078 k = span->len - 1;
2080 if (span == page->fmark.span && span == page->lmark.span) {
2081 seen = 1;
2082 j = MIN (first.i, last.i);
2083 k = MAX (first.i, last.i);
2085 else {
2086 if (span == first.span) {
2087 seen = 1;
2088 j = first.i;
2090 else if (span == last.span) {
2091 seen = 1;
2092 k = last.i;
2096 if (seen) {
2097 for (i = j; i <= k; ++i) {
2098 fz_rect bbox1;
2099 fz_union_rect (&rect,
2100 fz_stext_char_bbox (state.ctx, &bbox1,
2101 span, i));
2103 fz_round_rect (&bbox, &rect);
2104 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2105 bbox.x0,
2106 bbox.y0,
2107 bbox.x1,
2108 bbox.y1,
2109 oy, ox);
2111 recti (bbox.x0 + ox, bbox.y0 + oy,
2112 bbox.x1 + ox, bbox.y1 + oy);
2113 if (span == last.span) {
2114 goto done;
2116 rect = fz_empty_rect;
2121 done:
2122 glDisable (GL_BLEND);
2125 #include "glfont.c"
2127 static void stipplerect (fz_matrix *m,
2128 fz_point *p1,
2129 fz_point *p2,
2130 fz_point *p3,
2131 fz_point *p4,
2132 GLfloat *texcoords,
2133 GLfloat *vertices)
2135 fz_transform_point (p1, m);
2136 fz_transform_point (p2, m);
2137 fz_transform_point (p3, m);
2138 fz_transform_point (p4, m);
2140 float w, h, s, t;
2142 w = p2->x - p1->x;
2143 h = p2->y - p1->y;
2144 t = sqrtf (w*w + h*h) * .25f;
2146 w = p3->x - p2->x;
2147 h = p3->y - p2->y;
2148 s = sqrtf (w*w + h*h) * .25f;
2150 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2151 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2153 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2154 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2156 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2157 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2159 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2160 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2162 glDrawArrays (GL_LINES, 0, 8);
2165 static void solidrect (fz_matrix *m,
2166 fz_point *p1,
2167 fz_point *p2,
2168 fz_point *p3,
2169 fz_point *p4,
2170 GLfloat *vertices)
2172 fz_transform_point (p1, m);
2173 fz_transform_point (p2, m);
2174 fz_transform_point (p3, m);
2175 fz_transform_point (p4, m);
2176 vertices[0] = p1->x; vertices[1] = p1->y;
2177 vertices[2] = p2->x; vertices[3] = p2->y;
2179 vertices[4] = p3->x; vertices[5] = p3->y;
2180 vertices[6] = p4->x; vertices[7] = p4->y;
2181 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2184 static void highlightlinks (struct page *page, int xoff, int yoff)
2186 int i;
2187 fz_matrix ctm, tm, pm;
2188 fz_link *link, *links;
2189 GLfloat *texcoords = state.texcoords;
2190 GLfloat *vertices = state.vertices;
2192 links = fz_load_links (state.ctx, page->fzpage);
2194 glEnable (GL_TEXTURE_1D);
2195 glEnable (GL_BLEND);
2196 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2197 glBindTexture (GL_TEXTURE_1D, state.stid);
2199 xoff -= state.pagedims[page->pdimno].bounds.x0;
2200 yoff -= state.pagedims[page->pdimno].bounds.y0;
2201 fz_translate (&tm, xoff, yoff);
2202 pm = pagectm (page);
2203 fz_concat (&ctm, &pm, &tm);
2205 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2206 glVertexPointer (2, GL_FLOAT, 0, vertices);
2208 for (link = links; link; link = link->next) {
2209 fz_point p1, p2, p3, p4;
2211 p1.x = link->rect.x0;
2212 p1.y = link->rect.y0;
2214 p2.x = link->rect.x1;
2215 p2.y = link->rect.y0;
2217 p3.x = link->rect.x1;
2218 p3.y = link->rect.y1;
2220 p4.x = link->rect.x0;
2221 p4.y = link->rect.y1;
2223 switch (link->dest.kind) {
2224 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2225 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2226 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2227 default: glColor3ub (0, 0, 0); break;
2229 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2232 for (i = 0; i < page->annotcount; ++i) {
2233 fz_point p1, p2, p3, p4;
2234 struct annot *annot = &page->annots[i];
2236 p1.x = annot->bbox.x0;
2237 p1.y = annot->bbox.y0;
2239 p2.x = annot->bbox.x1;
2240 p2.y = annot->bbox.y0;
2242 p3.x = annot->bbox.x1;
2243 p3.y = annot->bbox.y1;
2245 p4.x = annot->bbox.x0;
2246 p4.y = annot->bbox.y1;
2248 glColor3ub (0, 0, 128);
2249 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2252 glDisable (GL_BLEND);
2253 glDisable (GL_TEXTURE_1D);
2256 static int compareslinks (const void *l, const void *r)
2258 struct slink const *ls = l;
2259 struct slink const *rs = r;
2260 if (ls->bbox.y0 == rs->bbox.y0) {
2261 return rs->bbox.x0 - rs->bbox.x0;
2263 return ls->bbox.y0 - rs->bbox.y0;
2266 static void droptext (struct page *page)
2268 if (page->text) {
2269 fz_drop_stext_page (state.ctx, page->text);
2270 page->fmark.i = -1;
2271 page->lmark.i = -1;
2272 page->fmark.span = NULL;
2273 page->lmark.span = NULL;
2274 page->text = NULL;
2276 if (page->sheet) {
2277 fz_drop_stext_sheet (state.ctx, page->sheet);
2278 page->sheet = NULL;
2282 static void dropannots (struct page *page)
2284 if (page->annots) {
2285 free (page->annots);
2286 page->annots = NULL;
2287 page->annotcount = 0;
2291 static void ensureannots (struct page *page)
2293 int i, count = 0;
2294 size_t annotsize = sizeof (*page->annots);
2295 fz_annot *annot;
2297 if (state.gen != page->agen) {
2298 dropannots (page);
2299 page->agen = state.gen;
2301 if (page->annots) return;
2303 for (annot = fz_first_annot (state.ctx, page->fzpage);
2304 annot;
2305 annot = fz_next_annot (state.ctx, annot)) {
2306 count++;
2309 if (count > 0) {
2310 page->annotcount = count;
2311 page->annots = calloc (count, annotsize);
2312 if (!page->annots) {
2313 err (1, "calloc annots %d", count);
2316 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2317 annot;
2318 annot = fz_next_annot (state.ctx, annot), i++) {
2319 fz_rect rect;
2321 fz_bound_annot (state.ctx, annot, &rect);
2322 page->annots[i].annot = annot;
2323 fz_round_rect (&page->annots[i].bbox, &rect);
2328 static void dropslinks (struct page *page)
2330 if (page->slinks) {
2331 free (page->slinks);
2332 page->slinks = NULL;
2333 page->slinkcount = 0;
2337 static void ensureslinks (struct page *page)
2339 fz_matrix ctm;
2340 int i, count;
2341 size_t slinksize = sizeof (*page->slinks);
2342 fz_link *link, *links;
2344 ensureannots (page);
2345 if (state.gen != page->sgen) {
2346 dropslinks (page);
2347 page->sgen = state.gen;
2349 if (page->slinks) return;
2351 links = fz_load_links (state.ctx, page->fzpage);
2352 ctm = pagectm (page);
2354 count = page->annotcount;
2355 for (link = links; link; link = link->next) {
2356 count++;
2358 if (count > 0) {
2359 int j;
2361 page->slinkcount = count;
2362 page->slinks = calloc (count, slinksize);
2363 if (!page->slinks) {
2364 err (1, "calloc slinks %d", count);
2367 for (i = 0, link = links; link; ++i, link = link->next) {
2368 fz_rect rect;
2370 rect = link->rect;
2371 fz_transform_rect (&rect, &ctm);
2372 page->slinks[i].tag = SLINK;
2373 page->slinks[i].u.link = link;
2374 fz_round_rect (&page->slinks[i].bbox, &rect);
2376 for (j = 0; j < page->annotcount; ++j, ++i) {
2377 fz_rect rect;
2378 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2379 fz_transform_rect (&rect, &ctm);
2380 fz_round_rect (&page->slinks[i].bbox, &rect);
2382 page->slinks[i].tag = SANNOT;
2383 page->slinks[i].u.annot = page->annots[j].annot;
2385 qsort (page->slinks, count, slinksize, compareslinks);
2389 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2390 static void fmt_linkn (char *s, unsigned int u)
2392 unsigned int len; unsigned int q;
2393 unsigned int zma = 'z' - 'a' + 1;
2394 len = 1; q = u;
2395 while (q > zma - 1) { ++len; q /= zma; }
2396 if (s) {
2397 s += len;
2398 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2399 /* handles u == 0 */
2401 s[len] = 0;
2404 static void highlightslinks (struct page *page, int xoff, int yoff,
2405 int noff, char *targ, int tlen, int hfsize)
2407 int i;
2408 char buf[40];
2409 struct slink *slink;
2410 double x0, y0, x1, y1, w;
2412 ensureslinks (page);
2413 glColor3ub (0xc3, 0xb0, 0x91);
2414 for (i = 0; i < page->slinkcount; ++i) {
2415 fmt_linkn (buf, i + noff);
2416 if (!tlen || !strncmp (targ, buf, tlen)) {
2417 slink = &page->slinks[i];
2419 x0 = slink->bbox.x0 + xoff - 5;
2420 y1 = slink->bbox.y0 + yoff - 5;
2421 y0 = y1 + 10 + hfsize;
2422 w = measure_string (state.face, hfsize, buf);
2423 x1 = x0 + w + 10;
2424 recti (x0, y0, x1, y1);
2428 glEnable (GL_BLEND);
2429 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2430 glEnable (GL_TEXTURE_2D);
2431 glColor3ub (0, 0, 0);
2432 for (i = 0; i < page->slinkcount; ++i) {
2433 fmt_linkn (buf, i + noff);
2434 if (!tlen || !strncmp (targ, buf, tlen)) {
2435 slink = &page->slinks[i];
2437 x0 = slink->bbox.x0 + xoff;
2438 y0 = slink->bbox.y0 + yoff + hfsize;
2439 draw_string (state.face, hfsize, x0, y0, buf);
2442 glDisable (GL_TEXTURE_2D);
2443 glDisable (GL_BLEND);
2446 static void uploadslice (struct tile *tile, struct slice *slice)
2448 int offset;
2449 struct slice *slice1;
2450 unsigned char *texdata;
2452 offset = 0;
2453 for (slice1 = tile->slices; slice != slice1; slice1++) {
2454 offset += slice1->h * tile->w * tile->pixmap->n;
2456 if (slice->texindex != -1 && slice->texindex < state.texcount
2457 && state.texowners[slice->texindex].slice == slice) {
2458 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2460 else {
2461 int subimage = 0;
2462 int texindex = state.texindex++ % state.texcount;
2464 if (state.texowners[texindex].w == tile->w) {
2465 if (state.texowners[texindex].h >= slice->h) {
2466 subimage = 1;
2468 else {
2469 state.texowners[texindex].h = slice->h;
2472 else {
2473 state.texowners[texindex].h = slice->h;
2476 state.texowners[texindex].w = tile->w;
2477 state.texowners[texindex].slice = slice;
2478 slice->texindex = texindex;
2480 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2481 #if TEXT_TYPE == GL_TEXTURE_2D
2482 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2483 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2484 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2485 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2486 #endif
2487 if (tile->pbo) {
2488 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2489 texdata = 0;
2491 else {
2492 texdata = tile->pixmap->samples;
2494 if (subimage) {
2495 glTexSubImage2D (TEXT_TYPE,
2499 tile->w,
2500 slice->h,
2501 state.texform,
2502 state.texty,
2503 texdata+offset
2506 else {
2507 glTexImage2D (TEXT_TYPE,
2509 state.texiform,
2510 tile->w,
2511 slice->h,
2513 state.texform,
2514 state.texty,
2515 texdata+offset
2518 if (tile->pbo) {
2519 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2524 CAMLprim value ml_begintiles (value unit_v)
2526 CAMLparam1 (unit_v);
2527 glEnable (TEXT_TYPE);
2528 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2529 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2530 CAMLreturn (unit_v);
2533 CAMLprim value ml_endtiles (value unit_v)
2535 CAMLparam1 (unit_v);
2536 glDisable (TEXT_TYPE);
2537 CAMLreturn (unit_v);
2540 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2542 CAMLparam2 (args_v, ptr_v);
2543 int dispx = Int_val (Field (args_v, 0));
2544 int dispy = Int_val (Field (args_v, 1));
2545 int dispw = Int_val (Field (args_v, 2));
2546 int disph = Int_val (Field (args_v, 3));
2547 int tilex = Int_val (Field (args_v, 4));
2548 int tiley = Int_val (Field (args_v, 5));
2549 char *s = String_val (ptr_v);
2550 struct tile *tile = parse_pointer (__func__, s);
2551 int slicey, firstslice;
2552 struct slice *slice;
2553 GLfloat *texcoords = state.texcoords;
2554 GLfloat *vertices = state.vertices;
2556 firstslice = tiley / tile->sliceheight;
2557 slice = &tile->slices[firstslice];
2558 slicey = tiley % tile->sliceheight;
2560 while (disph > 0) {
2561 int dh;
2563 dh = slice->h - slicey;
2564 dh = MIN (disph, dh);
2565 uploadslice (tile, slice);
2567 texcoords[0] = tilex; texcoords[1] = slicey;
2568 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2569 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2570 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2572 vertices[0] = dispx; vertices[1] = dispy;
2573 vertices[2] = dispx+dispw; vertices[3] = dispy;
2574 vertices[4] = dispx; vertices[5] = dispy+dh;
2575 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2577 #if TEXT_TYPE == GL_TEXTURE_2D
2578 for (int i = 0; i < 8; ++i) {
2579 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2581 #endif
2583 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2584 dispy += dh;
2585 disph -= dh;
2586 slice++;
2587 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2588 slicey = 0;
2590 CAMLreturn (Val_unit);
2593 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2595 fz_matrix ctm, tm, pm;
2596 fz_point p1, p2, p3, p4;
2597 GLfloat *vertices = state.vertices;
2598 double *v = (double *) rects_v;
2600 xoff -= state.pagedims[page->pdimno].bounds.x0;
2601 yoff -= state.pagedims[page->pdimno].bounds.y0;
2602 fz_translate (&tm, xoff, yoff);
2603 pm = pagectm (page);
2604 fz_concat (&ctm, &pm, &tm);
2606 glEnable (GL_BLEND);
2607 glVertexPointer (2, GL_FLOAT, 0, vertices);
2609 glColor4dv (v);
2610 p1.x = v[4];
2611 p1.y = v[5];
2613 p2.x = v[6];
2614 p2.y = v[5];
2616 p3.x = v[6];
2617 p3.y = v[7];
2619 p4.x = v[4];
2620 p4.y = v[7];
2621 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2622 glDisable (GL_BLEND);
2625 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2626 value xoff_v, value yoff_v,
2627 value li_v)
2629 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2630 int xoff = Int_val (xoff_v);
2631 int yoff = Int_val (yoff_v);
2632 int noff = Int_val (Field (li_v, 0));
2633 char *targ = String_val (Field (li_v, 1));
2634 int tlen = caml_string_length (Field (li_v, 1));
2635 int hfsize = Int_val (Field (li_v, 2));
2636 char *s = String_val (ptr_v);
2637 int hlmask = Int_val (hlinks_v);
2638 struct page *page = parse_pointer (__func__, s);
2640 if (!page->fzpage) {
2641 /* deal with loadpage failed pages */
2642 goto done;
2645 ensureannots (page);
2647 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2648 if (trylock (__func__)) {
2649 noff = 0;
2650 goto done;
2652 if (hlmask & 2) {
2653 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2654 noff = page->slinkcount;
2656 if (page->tgen == state.gen) {
2657 showsel (page, xoff, yoff);
2659 unlock (__func__);
2661 done:
2662 CAMLreturn (Val_int (noff));
2665 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2666 value rects_v)
2668 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2669 int xoff = Int_val (xoff_v);
2670 int yoff = Int_val (yoff_v);
2671 char *s = String_val (ptr_v);
2672 struct page *page = parse_pointer (__func__, s);
2674 drawprect (page, xoff, yoff, rects_v);
2675 CAMLreturn (Val_unit);
2678 static struct annot *getannot (struct page *page, int x, int y)
2680 int i;
2681 fz_point p;
2682 fz_matrix ctm;
2683 const fz_matrix *tctm;
2684 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2686 if (!page->annots) return NULL;
2688 if (pdf) {
2689 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2690 tctm = &state.pagedims[page->pdimno].tctm;
2692 else {
2693 tctm = &fz_identity;
2696 p.x = x;
2697 p.y = y;
2699 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2700 fz_invert_matrix (&ctm, &ctm);
2701 fz_transform_point (&p, &ctm);
2703 if (pdf) {
2704 for (i = 0; i < page->annotcount; ++i) {
2705 struct annot *a = &page->annots[i];
2706 pdf_annot *annot = (pdf_annot *) a->annot;
2707 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2708 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2709 return a;
2714 return NULL;
2717 static fz_link *getlink (struct page *page, int x, int y)
2719 fz_point p;
2720 fz_matrix ctm;
2721 fz_link *link, *links;
2723 links = fz_load_links (state.ctx, page->fzpage);
2725 p.x = x;
2726 p.y = y;
2728 ctm = pagectm (page);
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_var (page);
2784 fz_try (state.ctx) {
2785 page = pdf_load_page (state.ctx, pdf, i);
2786 found = !!page->links || !!page->annots;
2788 fz_catch (state.ctx) {
2789 found = 0;
2791 if (page) {
2792 fz_drop_page (state.ctx, &page->super);
2795 else {
2796 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2797 found = !!fz_load_links (state.ctx, page);
2798 fz_drop_page (state.ctx, page);
2801 if (found) {
2802 ret_v = caml_alloc_small (1, 1);
2803 Field (ret_v, 0) = Val_int (i);
2804 goto unlock;
2807 unlock:
2808 unlock (__func__);
2809 CAMLreturn (ret_v);
2812 enum { dir_first, dir_last };
2813 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2815 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2817 CAMLparam2 (ptr_v, dir_v);
2818 CAMLlocal2 (ret_v, pos_v);
2819 struct page *page;
2820 int dirtag, i, slinkindex;
2821 struct slink *found = NULL ,*slink;
2822 char *s = String_val (ptr_v);
2824 page = parse_pointer (__func__, s);
2825 ret_v = Val_int (0);
2826 /* This is scary we are not taking locks here ensureslinks does
2827 not modify state and given that we obtained the page it can not
2828 disappear under us either */
2829 lock (__func__);
2830 ensureslinks (page);
2832 if (Is_block (dir_v)) {
2833 dirtag = Tag_val (dir_v);
2834 switch (dirtag) {
2835 case dir_first_visible:
2837 int x0, y0, dir, first_index, last_index;
2839 pos_v = Field (dir_v, 0);
2840 x0 = Int_val (Field (pos_v, 0));
2841 y0 = Int_val (Field (pos_v, 1));
2842 dir = Int_val (Field (pos_v, 2));
2844 if (dir >= 0) {
2845 dir = 1;
2846 first_index = 0;
2847 last_index = page->slinkcount;
2849 else {
2850 first_index = page->slinkcount - 1;
2851 last_index = -1;
2854 for (i = first_index; i != last_index; i += dir) {
2855 slink = &page->slinks[i];
2856 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2857 found = slink;
2858 break;
2862 break;
2864 case dir_left:
2865 slinkindex = Int_val (Field (dir_v, 0));
2866 found = &page->slinks[slinkindex];
2867 for (i = slinkindex - 1; i >= 0; --i) {
2868 slink = &page->slinks[i];
2869 if (slink->bbox.x0 < found->bbox.x0) {
2870 found = slink;
2871 break;
2874 break;
2876 case dir_right:
2877 slinkindex = Int_val (Field (dir_v, 0));
2878 found = &page->slinks[slinkindex];
2879 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2880 slink = &page->slinks[i];
2881 if (slink->bbox.x0 > found->bbox.x0) {
2882 found = slink;
2883 break;
2886 break;
2888 case dir_down:
2889 slinkindex = Int_val (Field (dir_v, 0));
2890 found = &page->slinks[slinkindex];
2891 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2892 slink = &page->slinks[i];
2893 if (slink->bbox.y0 >= found->bbox.y0) {
2894 found = slink;
2895 break;
2898 break;
2900 case dir_up:
2901 slinkindex = Int_val (Field (dir_v, 0));
2902 found = &page->slinks[slinkindex];
2903 for (i = slinkindex - 1; i >= 0; --i) {
2904 slink = &page->slinks[i];
2905 if (slink->bbox.y0 <= found->bbox.y0) {
2906 found = slink;
2907 break;
2910 break;
2913 else {
2914 dirtag = Int_val (dir_v);
2915 switch (dirtag) {
2916 case dir_first:
2917 found = page->slinks;
2918 break;
2920 case dir_last:
2921 if (page->slinks) {
2922 found = page->slinks + (page->slinkcount - 1);
2924 break;
2927 if (found) {
2928 ret_v = caml_alloc_small (2, 1);
2929 Field (ret_v, 0) = Val_int (found - page->slinks);
2932 unlock (__func__);
2933 CAMLreturn (ret_v);
2936 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2937 unamed, uremote, uremotedest, uannot };
2939 #define LINKTOVAL \
2941 int pageno; \
2943 switch (link->dest.kind) { \
2944 case FZ_LINK_GOTO: \
2946 fz_point p; \
2948 pageno = link->dest.ld.gotor.page; \
2949 p.x = 0; \
2950 p.y = 0; \
2952 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2953 p.y = link->dest.ld.gotor.lt.y; \
2954 fz_transform_point (&p, &pdim->lctm); \
2955 if (p.y < 0) p.y = 0; \
2957 tup_v = caml_alloc_tuple (2); \
2958 ret_v = caml_alloc_small (1, ugoto); \
2959 Field (tup_v, 0) = Val_int (pageno); \
2960 Field (tup_v, 1) = Val_int (p.y); \
2961 Field (ret_v, 0) = tup_v; \
2963 break; \
2965 case FZ_LINK_URI: \
2966 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2967 ret_v = caml_alloc_small (1, uuri); \
2968 Field (ret_v, 0) = str_v; \
2969 break; \
2971 case FZ_LINK_LAUNCH: \
2972 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2973 ret_v = caml_alloc_small (1, ulaunch); \
2974 Field (ret_v, 0) = str_v; \
2975 break; \
2977 case FZ_LINK_NAMED: \
2978 str_v = caml_copy_string (link->dest.ld.named.named); \
2979 ret_v = caml_alloc_small (1, unamed); \
2980 Field (ret_v, 0) = str_v; \
2981 break; \
2983 case FZ_LINK_GOTOR: \
2985 int rty; \
2987 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2988 pageno = link->dest.ld.gotor.page; \
2989 if (pageno == -1) { \
2990 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2991 rty = uremotedest; \
2993 else { \
2994 gr_v = Val_int (pageno); \
2995 rty = uremote; \
2997 tup_v = caml_alloc_tuple (2); \
2998 ret_v = caml_alloc_small (1, rty); \
2999 Field (tup_v, 0) = str_v; \
3000 Field (tup_v, 1) = gr_v; \
3001 Field (ret_v, 0) = tup_v; \
3003 break; \
3005 default: \
3007 char buf[80]; \
3009 snprintf (buf, sizeof (buf), \
3010 "unhandled link kind %d", link->dest.kind); \
3011 str_v = caml_copy_string (buf); \
3012 ret_v = caml_alloc_small (1, uunexpected); \
3013 Field (ret_v, 0) = str_v; \
3015 break; \
3019 CAMLprim value ml_getlink (value ptr_v, value n_v)
3021 CAMLparam2 (ptr_v, n_v);
3022 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3023 fz_link *link;
3024 struct page *page;
3025 struct pagedim *pdim;
3026 char *s = String_val (ptr_v);
3027 struct slink *slink;
3029 /* See ml_findlink for caveat */
3031 ret_v = Val_int (0);
3032 page = parse_pointer (__func__, s);
3033 ensureslinks (page);
3034 pdim = &state.pagedims[page->pdimno];
3035 slink = &page->slinks[Int_val (n_v)];
3036 if (slink->tag == SLINK) {
3037 link = slink->u.link;
3038 LINKTOVAL;
3040 else {
3041 ret_v = caml_alloc_small (1, uannot);
3042 tup_v = caml_alloc_tuple (2);
3043 Field (ret_v, 0) = tup_v;
3044 Field (tup_v, 0) = ptr_v;
3045 Field (tup_v, 1) = n_v;
3048 CAMLreturn (ret_v);
3051 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3053 CAMLparam2 (ptr_v, n_v);
3054 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3055 if (pdf) {
3056 char *s = String_val (ptr_v);
3057 struct page *page;
3058 struct slink *slink;
3060 page = parse_pointer (__func__, s);
3061 slink = &page->slinks[Int_val (n_v)];
3062 CAMLreturn (caml_copy_string (
3063 pdf_annot_contents (state.ctx, pdf,
3064 (pdf_annot *) slink->u.annot)));
3066 else {
3067 CAMLreturn (caml_copy_string (""));
3071 CAMLprim value ml_getlinkcount (value ptr_v)
3073 CAMLparam1 (ptr_v);
3074 struct page *page;
3075 char *s = String_val (ptr_v);
3077 page = parse_pointer (__func__, s);
3078 CAMLreturn (Val_int (page->slinkcount));
3081 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3083 CAMLparam2 (ptr_v, n_v);
3084 CAMLlocal1 (ret_v);
3085 struct page *page;
3086 struct slink *slink;
3087 char *s = String_val (ptr_v);
3088 /* See ml_findlink for caveat */
3090 page = parse_pointer (__func__, s);
3091 ret_v = caml_alloc_tuple (4);
3092 ensureslinks (page);
3094 slink = &page->slinks[Int_val (n_v)];
3095 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3096 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3097 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3098 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3099 unlock (__func__);
3100 CAMLreturn (ret_v);
3103 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3105 CAMLparam3 (ptr_v, x_v, y_v);
3106 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3107 fz_link *link;
3108 struct annot *annot;
3109 struct page *page;
3110 char *ptr = String_val (ptr_v);
3111 int x = Int_val (x_v), y = Int_val (y_v);
3112 struct pagedim *pdim;
3114 ret_v = Val_int (0);
3115 if (trylock (__func__)) {
3116 goto done;
3119 page = parse_pointer (__func__, ptr);
3120 pdim = &state.pagedims[page->pdimno];
3121 x += pdim->bounds.x0;
3122 y += pdim->bounds.y0;
3125 annot = getannot (page, x, y);
3126 if (annot) {
3127 int i, n = -1;
3129 ensureslinks (page);
3130 for (i = 0; i < page->slinkcount; ++i) {
3131 if (page->slinks[i].tag == SANNOT
3132 && page->slinks[i].u.annot == annot->annot) {
3133 n = i;
3134 break;
3137 ret_v = caml_alloc_small (1, uannot);
3138 tup_v = caml_alloc_tuple (2);
3139 Field (ret_v, 0) = tup_v;
3140 Field (tup_v, 0) = ptr_v;
3141 Field (tup_v, 1) = Val_int (n);
3142 goto unlock;
3146 link = getlink (page, x, y);
3147 if (link) {
3148 LINKTOVAL;
3150 else {
3151 fz_rect *b;
3152 fz_page_block *pageb;
3153 fz_stext_block *block;
3155 ensuretext (page);
3156 for (pageb = page->text->blocks;
3157 pageb < page->text->blocks + page->text->len;
3158 ++pageb) {
3159 fz_stext_line *line;
3160 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3161 block = pageb->u.text;
3163 b = &block->bbox;
3164 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3165 continue;
3167 for (line = block->lines;
3168 line < block->lines + block->len;
3169 ++line) {
3170 fz_stext_span *span;
3172 b = &line->bbox;
3173 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3174 continue;
3176 for (span = line->first_span; span; span = span->next) {
3177 int charnum;
3179 b = &span->bbox;
3180 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3181 continue;
3183 for (charnum = 0; charnum < span->len; ++charnum) {
3184 fz_rect bbox;
3185 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3186 b = &bbox;
3188 if (x >= b->x0 && x <= b->x1
3189 && y >= b->y0 && y <= b->y1) {
3190 fz_stext_style *style = span->text->style;
3191 const char *n2 =
3192 style->font
3193 ? style->font->name
3194 : "Span has no font name"
3196 FT_FaceRec *face = style->font->ft_face;
3197 if (face && face->family_name) {
3198 char *s;
3199 char *n1 = face->family_name;
3200 size_t l1 = strlen (n1);
3201 size_t l2 = strlen (n2);
3203 if (l1 != l2 || memcmp (n1, n2, l1)) {
3204 s = malloc (l1 + l2 + 2);
3205 if (s) {
3206 memcpy (s, n2, l2);
3207 s[l2] = '=';
3208 memcpy (s + l2 + 1, n1, l1 + 1);
3209 str_v = caml_copy_string (s);
3210 free (s);
3214 if (str_v == Val_unit) {
3215 str_v = caml_copy_string (n2);
3217 ret_v = caml_alloc_small (1, utext);
3218 Field (ret_v, 0) = str_v;
3219 goto unlock;
3226 unlock:
3227 unlock (__func__);
3229 done:
3230 CAMLreturn (ret_v);
3233 enum { mark_page, mark_block, mark_line, mark_word };
3235 static int uninteresting (int c)
3237 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3238 || ispunct (c);
3241 CAMLprim value ml_clearmark (value ptr_v)
3243 CAMLparam1 (ptr_v);
3244 char *s = String_val (ptr_v);
3245 struct page *page;
3247 if (trylock (__func__)) {
3248 goto done;
3251 page = parse_pointer (__func__, s);
3252 page->fmark.span = NULL;
3253 page->lmark.span = NULL;
3254 page->fmark.i = 0;
3255 page->lmark.i = 0;
3257 unlock (__func__);
3258 done:
3259 CAMLreturn (Val_unit);
3262 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3264 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3265 CAMLlocal1 (ret_v);
3266 fz_rect *b;
3267 struct page *page;
3268 fz_stext_line *line;
3269 fz_page_block *pageb;
3270 fz_stext_block *block;
3271 struct pagedim *pdim;
3272 int mark = Int_val (mark_v);
3273 char *s = String_val (ptr_v);
3274 int x = Int_val (x_v), y = Int_val (y_v);
3276 ret_v = Val_bool (0);
3277 if (trylock (__func__)) {
3278 goto done;
3281 page = parse_pointer (__func__, s);
3282 pdim = &state.pagedims[page->pdimno];
3284 ensuretext (page);
3286 if (mark == mark_page) {
3287 int i;
3288 fz_page_block *pb1 = NULL, *pb2 = NULL;
3290 for (i = 0; i < page->text->len; ++i) {
3291 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3292 pb1 = &page->text->blocks[i];
3293 break;
3296 if (!pb1) goto unlock;
3298 for (i = page->text->len - 1; i >= 0; --i) {
3299 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3300 pb2 = &page->text->blocks[i];
3301 break;
3304 if (!pb2) goto unlock;
3306 block = pb1->u.text;
3308 page->fmark.i = 0;
3309 page->fmark.span = block->lines->first_span;
3311 block = pb2->u.text;
3312 line = &block->lines[block->len - 1];
3313 page->lmark.i = line->last_span->len - 1;
3314 page->lmark.span = line->last_span;
3315 ret_v = Val_bool (1);
3316 goto unlock;
3319 x += pdim->bounds.x0;
3320 y += pdim->bounds.y0;
3322 for (pageb = page->text->blocks;
3323 pageb < page->text->blocks + page->text->len;
3324 ++pageb) {
3325 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3326 block = pageb->u.text;
3328 b = &block->bbox;
3329 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3330 continue;
3332 if (mark == mark_block) {
3333 page->fmark.i = 0;
3334 page->fmark.span = block->lines->first_span;
3336 line = &block->lines[block->len - 1];
3337 page->lmark.i = line->last_span->len - 1;
3338 page->lmark.span = line->last_span;
3339 ret_v = Val_bool (1);
3340 goto unlock;
3343 for (line = block->lines;
3344 line < block->lines + block->len;
3345 ++line) {
3346 fz_stext_span *span;
3348 b = &line->bbox;
3349 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3350 continue;
3352 if (mark == mark_line) {
3353 page->fmark.i = 0;
3354 page->fmark.span = line->first_span;
3356 page->lmark.i = line->last_span->len - 1;
3357 page->lmark.span = line->last_span;
3358 ret_v = Val_bool (1);
3359 goto unlock;
3362 for (span = line->first_span; span; span = span->next) {
3363 int charnum;
3365 b = &span->bbox;
3366 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3367 continue;
3369 for (charnum = 0; charnum < span->len; ++charnum) {
3370 fz_rect bbox;
3371 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3372 b = &bbox;
3374 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3375 /* unicode ftw */
3376 int charnum2, charnum3 = -1, charnum4 = -1;
3378 if (uninteresting (span->text[charnum].c)) goto unlock;
3380 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3381 if (uninteresting (span->text[charnum2].c)) {
3382 charnum3 = charnum2 + 1;
3383 break;
3386 if (charnum3 == -1) charnum3 = 0;
3388 charnum4 = charnum;
3389 for (charnum2 = charnum + 1;
3390 charnum2 < span->len;
3391 ++charnum2) {
3392 if (uninteresting (span->text[charnum2].c)) break;
3393 charnum4 = charnum2;
3396 page->fmark.i = charnum3;
3397 page->fmark.span = span;
3399 page->lmark.i = charnum4;
3400 page->lmark.span = span;
3401 ret_v = Val_bool (1);
3402 goto unlock;
3408 unlock:
3409 if (!Bool_val (ret_v)) {
3410 page->fmark.span = NULL;
3411 page->lmark.span = NULL;
3412 page->fmark.i = 0;
3413 page->lmark.i = 0;
3415 unlock (__func__);
3417 done:
3418 CAMLreturn (ret_v);
3421 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3423 CAMLparam3 (ptr_v, x_v, y_v);
3424 CAMLlocal2 (ret_v, res_v);
3425 fz_rect *b = NULL;
3426 struct page *page;
3427 fz_page_block *pageb;
3428 struct pagedim *pdim;
3429 char *s = String_val (ptr_v);
3430 int x = Int_val (x_v), y = Int_val (y_v);
3432 ret_v = Val_int (0);
3433 if (trylock (__func__)) {
3434 goto done;
3437 page = parse_pointer (__func__, s);
3438 pdim = &state.pagedims[page->pdimno];
3439 x += pdim->bounds.x0;
3440 y += pdim->bounds.y0;
3442 ensuretext (page);
3444 for (pageb = page->text->blocks;
3445 pageb < page->text->blocks + page->text->len;
3446 ++pageb) {
3447 switch (pageb->type) {
3448 case FZ_PAGE_BLOCK_TEXT:
3449 b = &pageb->u.text->bbox;
3450 break;
3452 case FZ_PAGE_BLOCK_IMAGE:
3453 b = &pageb->u.image->bbox;
3454 break;
3456 default:
3457 continue;
3460 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3461 break;
3462 b = NULL;
3464 if (b) {
3465 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3466 ret_v = caml_alloc_small (1, 1);
3467 Store_double_field (res_v, 0, b->x0);
3468 Store_double_field (res_v, 1, b->x1);
3469 Store_double_field (res_v, 2, b->y0);
3470 Store_double_field (res_v, 3, b->y1);
3471 Field (ret_v, 0) = res_v;
3473 unlock (__func__);
3475 done:
3476 CAMLreturn (ret_v);
3479 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3481 CAMLparam2 (ptr_v, rect_v);
3482 fz_rect b;
3483 struct page *page;
3484 struct pagedim *pdim;
3485 char *s = String_val (ptr_v);
3486 int i, x0, x1, y0, y1, fi, li;
3487 fz_stext_line *line;
3488 fz_page_block *pageb;
3489 fz_stext_block *block;
3490 fz_stext_span *span, *fspan, *lspan;
3492 if (trylock (__func__)) {
3493 goto done;
3496 page = parse_pointer (__func__, s);
3497 ensuretext (page);
3499 pdim = &state.pagedims[page->pdimno];
3500 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3501 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3502 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3503 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3505 if (y0 > y1) {
3506 int t = y0;
3507 y0 = y1;
3508 y1 = t;
3509 x0 = x1;
3510 x1 = t;
3513 fi = page->fmark.i;
3514 fspan = page->fmark.span;
3516 li = page->lmark.i;
3517 lspan = page->lmark.span;
3519 for (pageb = page->text->blocks;
3520 pageb < page->text->blocks + page->text->len;
3521 ++pageb) {
3522 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3523 block = pageb->u.text;
3524 for (line = block->lines;
3525 line < block->lines + block->len;
3526 ++line) {
3528 for (span = line->first_span; span; span = span->next) {
3529 for (i = 0; i < span->len; ++i) {
3530 fz_stext_char_bbox (state.ctx, &b, span, i);
3532 if (x0 >= b.x0 && x0 <= b.x1
3533 && y0 >= b.y0 && y0 <= b.y1) {
3534 fspan = span;
3535 fi = i;
3537 if (x1 >= b.x0 && x1 <= b.x1
3538 && y1 >= b.y0 && y1 <= b.y1) {
3539 lspan = span;
3540 li = i;
3546 if (x1 < x0 && fspan == lspan) {
3547 i = fi;
3548 span = fspan;
3550 fi = li;
3551 fspan = lspan;
3553 li = i;
3554 lspan = span;
3557 page->fmark.i = fi;
3558 page->fmark.span = fspan;
3560 page->lmark.i = li;
3561 page->lmark.span = lspan;
3563 unlock (__func__);
3565 done:
3566 CAMLreturn (Val_unit);
3569 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3571 char buf[4];
3572 int i, len, ret;
3574 for (i = a; i <= b; ++i) {
3575 len = fz_runetochar (buf, span->text[i].c);
3576 ret = fwrite (buf, len, 1, f);
3578 if (ret != 1) {
3579 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3580 len, ret, strerror (errno));
3581 return -1;
3584 return 0;
3587 #ifdef __CYGWIN__
3588 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3590 caml_failwith ("ml_popen not implemented under Cygwin");
3592 #else
3593 CAMLprim value ml_spawn (value command_v, value fds_v)
3595 CAMLparam2 (command_v, fds_v);
3596 CAMLlocal2 (l_v, tup_v);
3597 int ret, ret1;
3598 pid_t pid;
3599 char *msg = NULL;
3600 value earg_v = Nothing;
3601 posix_spawnattr_t attr;
3602 posix_spawn_file_actions_t fa;
3603 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3605 argv[2] = String_val (command_v);
3607 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3608 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3611 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3612 msg = "posix_spawnattr_init";
3613 goto fail1;
3616 #ifdef POSIX_SPAWN_USEVFORK
3617 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3618 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3619 goto fail;
3621 #endif
3623 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3624 int fd1, fd2;
3626 tup_v = Field (l_v, 0);
3627 fd1 = Int_val (Field (tup_v, 0));
3628 fd2 = Int_val (Field (tup_v, 1));
3629 if (fd2 < 0) {
3630 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3631 msg = "posix_spawn_file_actions_addclose";
3632 earg_v = tup_v;
3633 goto fail;
3636 else {
3637 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3638 msg = "posix_spawn_file_actions_adddup2";
3639 earg_v = tup_v;
3640 goto fail;
3645 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3646 msg = "posix_spawn";
3647 goto fail;
3650 fail:
3651 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3652 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3655 fail1:
3656 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3657 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3658 strerror (ret1));
3661 if (msg)
3662 unix_error (ret, msg, earg_v);
3664 CAMLreturn (Val_int (pid));
3666 #endif
3668 CAMLprim value ml_hassel (value ptr_v)
3670 CAMLparam1 (ptr_v);
3671 CAMLlocal1 (ret_v);
3672 struct page *page;
3673 char *s = String_val (ptr_v);
3675 ret_v = Val_bool (0);
3676 if (trylock (__func__)) {
3677 goto done;
3680 page = parse_pointer (__func__, s);
3681 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3682 unlock (__func__);
3683 done:
3684 CAMLreturn (ret_v);
3687 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3689 CAMLparam2 (fd_v, ptr_v);
3690 FILE *f;
3691 int seen = 0;
3692 struct page *page;
3693 fz_stext_line *line;
3694 fz_page_block *pageb;
3695 fz_stext_block *block;
3696 int fd = Int_val (fd_v);
3697 char *s = String_val (ptr_v);
3699 if (trylock (__func__)) {
3700 goto done;
3703 page = parse_pointer (__func__, s);
3705 if (!page->fmark.span || !page->lmark.span) {
3706 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3707 goto unlock;
3710 f = fdopen (fd, "w");
3711 if (!f) {
3712 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3713 fd, strerror (errno));
3714 f = stdout;
3717 for (pageb = page->text->blocks;
3718 pageb < page->text->blocks + page->text->len;
3719 ++pageb) {
3720 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3721 block = pageb->u.text;
3722 for (line = block->lines;
3723 line < block->lines + block->len;
3724 ++line) {
3725 fz_stext_span *span;
3727 for (span = line->first_span; span; span = span->next) {
3728 int a, b;
3730 seen |= span == page->fmark.span || span == page->lmark.span;
3731 a = span == page->fmark.span ? page->fmark.i : 0;
3732 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3734 if (seen) {
3735 if (pipespan (f, span, a, b)) {
3736 goto close;
3738 if (span == page->lmark.span) {
3739 goto close;
3741 if (span == line->last_span) {
3742 if (putc ('\n', f) == EOF) {
3743 fprintf (stderr,
3744 "failed break line on sel pipe: %s\n",
3745 strerror (errno));
3746 goto close;
3753 close:
3754 if (f != stdout) {
3755 int ret = fclose (f);
3756 fd = -1;
3757 if (ret == -1) {
3758 if (errno != ECHILD) {
3759 fprintf (stderr, "failed to close sel pipe: %s\n",
3760 strerror (errno));
3764 unlock:
3765 unlock (__func__);
3767 done:
3768 if (fd >= 0) {
3769 if (close (fd)) {
3770 fprintf (stderr, "failed to close sel pipe: %s\n",
3771 strerror (errno));
3774 CAMLreturn (Val_unit);
3777 CAMLprim value ml_getpdimrect (value pagedimno_v)
3779 CAMLparam1 (pagedimno_v);
3780 CAMLlocal1 (ret_v);
3781 int pagedimno = Int_val (pagedimno_v);
3782 fz_rect box;
3784 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3785 if (trylock (__func__)) {
3786 box = fz_empty_rect;
3788 else {
3789 box = state.pagedims[pagedimno].mediabox;
3790 unlock (__func__);
3793 Store_double_field (ret_v, 0, box.x0);
3794 Store_double_field (ret_v, 1, box.x1);
3795 Store_double_field (ret_v, 2, box.y0);
3796 Store_double_field (ret_v, 3, box.y1);
3798 CAMLreturn (ret_v);
3801 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3802 value dw_v, value cols_v)
3804 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3805 CAMLlocal1 (ret_v);
3806 int i;
3807 double zoom = -1.;
3808 double maxh = 0.0;
3809 struct pagedim *p;
3810 double winw = Int_val (winw_v);
3811 double winh = Int_val (winh_v);
3812 double dw = Int_val (dw_v);
3813 double cols = Int_val (cols_v);
3814 double pw = 1.0, ph = 1.0;
3816 if (trylock (__func__)) {
3817 goto done;
3820 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3821 double w = p->pagebox.x1 / cols;
3822 double h = p->pagebox.y1;
3823 if (h > maxh) {
3824 maxh = h;
3825 ph = h;
3826 if (state.fitmodel != FitProportional) pw = w;
3828 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3831 zoom = (((winh / ph) * pw) + dw) / winw;
3832 unlock (__func__);
3833 done:
3834 ret_v = caml_copy_double (zoom);
3835 CAMLreturn (ret_v);
3838 CAMLprim value ml_getmaxw (value unit_v)
3840 CAMLparam1 (unit_v);
3841 CAMLlocal1 (ret_v);
3842 int i;
3843 double maxw = -1.;
3844 struct pagedim *p;
3846 if (trylock (__func__)) {
3847 goto done;
3850 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3851 double w = p->pagebox.x1;
3852 maxw = MAX (maxw, w);
3855 unlock (__func__);
3856 done:
3857 ret_v = caml_copy_double (maxw);
3858 CAMLreturn (ret_v);
3861 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3863 CAMLparam4 (pt_v, x_v, y_v, string_v);
3864 CAMLlocal1 (ret_v);
3865 int pt = Int_val(pt_v);
3866 int x = Int_val (x_v);
3867 int y = Int_val (y_v);
3868 double w;
3870 w = draw_string (state.face, pt, x, y, String_val (string_v));
3871 ret_v = caml_copy_double (w);
3872 CAMLreturn (ret_v);
3875 CAMLprim value ml_measure_string (value pt_v, value string_v)
3877 CAMLparam2 (pt_v, string_v);
3878 CAMLlocal1 (ret_v);
3879 int pt = Int_val (pt_v);
3880 double w;
3882 w = measure_string (state.face, pt, String_val (string_v));
3883 ret_v = caml_copy_double (w);
3884 CAMLreturn (ret_v);
3887 CAMLprim value ml_getpagebox (value opaque_v)
3889 CAMLparam1 (opaque_v);
3890 CAMLlocal1 (ret_v);
3891 fz_rect rect;
3892 fz_irect bbox;
3893 fz_matrix ctm;
3894 fz_device *dev;
3895 char *s = String_val (opaque_v);
3896 struct page *page = parse_pointer (__func__, s);
3898 ret_v = caml_alloc_tuple (4);
3899 dev = fz_new_bbox_device (state.ctx, &rect);
3900 dev->hints |= FZ_IGNORE_SHADE;
3902 ctm = pagectm (page);
3903 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3905 fz_drop_device (state.ctx, dev);
3906 fz_round_rect (&bbox, &rect);
3907 Field (ret_v, 0) = Val_int (bbox.x0);
3908 Field (ret_v, 1) = Val_int (bbox.y0);
3909 Field (ret_v, 2) = Val_int (bbox.x1);
3910 Field (ret_v, 3) = Val_int (bbox.y1);
3912 CAMLreturn (ret_v);
3915 CAMLprim value ml_setaalevel (value level_v)
3917 CAMLparam1 (level_v);
3919 state.aalevel = Int_val (level_v);
3920 CAMLreturn (Val_unit);
3923 #pragma GCC diagnostic push
3924 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3925 #include <X11/Xlib.h>
3926 #include <X11/cursorfont.h>
3927 #pragma GCC diagnostic pop
3929 #ifdef USE_EGL
3930 #include <EGL/egl.h>
3931 #else
3932 #include <GL/glx.h>
3933 #endif
3935 static const int shapes[] = {
3936 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3939 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3941 static struct {
3942 Window wid;
3943 Display *dpy;
3944 #ifdef USE_EGL
3945 EGLContext ctx;
3946 EGLConfig conf;
3947 EGLSurface win;
3948 EGLDisplay *edpy;
3949 #else
3950 GLXContext ctx;
3951 #endif
3952 XVisualInfo *visual;
3953 Cursor curs[CURS_COUNT];
3954 } glx;
3956 #ifdef VISAVIS
3957 static VisualID initvisual (void)
3959 /* On this system with: `Haswell-ULT Integrated Graphics
3960 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3961 using glX chosen visual and auto scrolling some document in
3962 fullscreen the power/energy-gpu is more than 1 joule bigger
3963 than when using hand picked visual that stands alone in glxinfo
3964 output: it's dead last in the list and it's the only one with
3965 `visual dep' (sic) of 32
3967 No clue what's going on here...
3969 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3971 XVisualInfo info;
3972 int ret = 1;
3974 info.depth = 32;
3975 info.class = TrueColor;
3976 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3977 &info, &ret);
3978 if (!ret || !glx.visual) {
3979 XCloseDisplay (glx.dpy);
3980 caml_failwith ("XGetVisualInfo");
3982 return glx.visual->visualid;
3984 #endif
3986 static void initcurs (void)
3988 for (size_t n = 0; n < CURS_COUNT; ++n) {
3989 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3993 CAMLprim void ml_setbgcol (value color_v)
3995 CAMLparam1 (color_v);
3996 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3997 CAMLreturn0;
4000 #ifdef USE_EGL
4001 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4003 CAMLparam3 (display_v, wid_v, screen_v);
4004 int major, minor;
4005 int num_conf;
4006 EGLint visid;
4007 EGLint attribs[] = {
4008 #ifdef VISAVIS
4009 EGL_NATIVE_VISUAL_ID, 0,
4010 #else
4011 EGL_DEPTH_SIZE, 24,
4012 #endif
4013 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
4014 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
4015 EGL_NONE
4017 EGLConfig conf;
4019 glx.dpy = XOpenDisplay (String_val (display_v));
4020 if (!glx.dpy) {
4021 caml_failwith ("XOpenDisplay");
4024 eglBindAPI (EGL_OPENGL_API);
4026 glx.edpy = eglGetDisplay (glx.dpy);
4027 if (glx.dpy == EGL_NO_DISPLAY) {
4028 caml_failwith ("eglGetDisplay");
4031 if (!eglInitialize (glx.edpy, &major, &minor)) {
4032 caml_failwith ("eglInitialize");
4035 #ifdef VISAVIS
4036 attribs[1] = visid = initvisual ();
4037 #endif
4039 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4040 !num_conf) {
4041 caml_failwith ("eglChooseConfig");
4044 glx.conf = conf;
4045 #ifndef VISAVIS
4046 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4047 EGL_NATIVE_VISUAL_ID, &visid)) {
4048 caml_failwith ("eglGetConfigAttrib");
4050 #endif
4051 initcurs ();
4053 glx.wid = Int_val (wid_v);
4054 CAMLreturn (Val_int (visid));
4057 CAMLprim value ml_glxcompleteinit (value unit_v)
4059 CAMLparam1 (unit_v);
4061 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4062 if (!glx.ctx) {
4063 caml_failwith ("eglCreateContext");
4066 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4067 glx.wid, NULL);
4068 if (glx.win == EGL_NO_SURFACE) {
4069 caml_failwith ("eglCreateWindowSurface");
4072 XFree (glx.visual);
4073 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4074 glx.ctx = NULL;
4075 caml_failwith ("eglMakeCurrent");
4077 CAMLreturn (Val_unit);
4079 #else
4080 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4082 CAMLparam3 (display_v, wid_v, screen_v);
4084 glx.dpy = XOpenDisplay (String_val (display_v));
4085 if (!glx.dpy) {
4086 caml_failwith ("XOpenDisplay");
4089 #ifdef VISAVIS
4090 initvisual ();
4091 #else
4092 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4093 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4094 if (!glx.visual) {
4095 XCloseDisplay (glx.dpy);
4096 caml_failwith ("glXChooseVisual");
4098 #endif
4099 initcurs ();
4101 glx.wid = Int_val (wid_v);
4102 CAMLreturn (Val_int (glx.visual->visualid));
4105 CAMLprim value ml_glxcompleteinit (value unit_v)
4107 CAMLparam1 (unit_v);
4109 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4110 if (!glx.ctx) {
4111 caml_failwith ("glXCreateContext");
4114 XFree (glx.visual);
4115 glx.visual = NULL;
4117 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4118 glXDestroyContext (glx.dpy, glx.ctx);
4119 glx.ctx = NULL;
4120 caml_failwith ("glXMakeCurrent");
4122 CAMLreturn (Val_unit);
4124 #endif
4126 CAMLprim value ml_setcursor (value cursor_v)
4128 CAMLparam1 (cursor_v);
4129 size_t cursn = Int_val (cursor_v);
4131 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4132 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4133 XFlush (glx.dpy);
4134 CAMLreturn (Val_unit);
4137 CAMLprim value ml_swapb (value unit_v)
4139 CAMLparam1 (unit_v);
4140 #ifdef USE_EGL
4141 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4142 caml_failwith ("eglSwapBuffers");
4144 #else
4145 glXSwapBuffers (glx.dpy, glx.wid);
4146 #endif
4147 CAMLreturn (Val_unit);
4150 #include "keysym2ucs.c"
4152 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4154 CAMLparam1 (keysym_v);
4155 CAMLlocal1 (str_v);
4156 KeySym keysym = Int_val (keysym_v);
4157 Rune rune;
4158 int len;
4159 char buf[5];
4161 rune = keysym2ucs (keysym);
4162 len = fz_runetochar (buf, rune);
4163 buf[len] = 0;
4164 str_v = caml_copy_string (buf);
4165 CAMLreturn (str_v);
4168 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4170 CAMLprim value ml_platform (value unit_v)
4172 CAMLparam1 (unit_v);
4173 CAMLlocal2 (tup_v, arr_v);
4174 int platid = piunknown;
4175 struct utsname buf;
4177 #if defined __linux__
4178 platid = pilinux;
4179 #elif defined __CYGWIN__
4180 platid = picygwin;
4181 #elif defined __DragonFly__ || defined __FreeBSD__
4182 || defined __OpenBSD__ || defined __NetBSD__
4183 platid = pibsd;
4184 #elif defined __sun__
4185 platid = pisun;
4186 #elif defined __APPLE__
4187 platid = piosx;
4188 #endif
4189 if (uname (&buf)) err (1, "uname");
4191 tup_v = caml_alloc_tuple (2);
4193 char const *sar[] = {
4194 buf.sysname,
4195 buf.release,
4196 buf.version,
4197 buf.machine,
4198 NULL
4200 arr_v = caml_copy_string_array (sar);
4202 Field (tup_v, 0) = Val_int (platid);
4203 Field (tup_v, 1) = arr_v;
4204 CAMLreturn (tup_v);
4207 CAMLprim value ml_cloexec (value fd_v)
4209 CAMLparam1 (fd_v);
4210 int fd = Int_val (fd_v);
4212 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4213 uerror ("fcntl", Nothing);
4215 CAMLreturn (Val_unit);
4218 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4220 CAMLparam2 (w_v, h_v);
4221 CAMLlocal1 (ret_v);
4222 struct bo *pbo;
4223 int w = Int_val (w_v);
4224 int h = Int_val (h_v);
4225 int cs = Int_val (cs_v);
4227 if (state.bo_usable) {
4228 pbo = calloc (sizeof (*pbo), 1);
4229 if (!pbo) {
4230 err (1, "calloc pbo");
4233 switch (cs) {
4234 case 0:
4235 case 1:
4236 pbo->size = w*h*4;
4237 break;
4238 case 2:
4239 pbo->size = w*h*2;
4240 break;
4241 default:
4242 errx (1, "%s: invalid colorspace %d", __func__, cs);
4245 state.glGenBuffersARB (1, &pbo->id);
4246 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4247 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4248 NULL, GL_STREAM_DRAW);
4249 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4250 GL_READ_WRITE);
4251 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4252 if (!pbo->ptr) {
4253 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4254 state.glDeleteBuffersARB (1, &pbo->id);
4255 free (pbo);
4256 ret_v = caml_copy_string ("0");
4258 else {
4259 int res;
4260 char *s;
4262 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4263 if (res < 0) {
4264 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4266 s = malloc (res+1);
4267 if (!s) {
4268 err (1, "malloc %d bytes failed", res+1);
4270 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4271 if (res < 0) {
4272 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4274 ret_v = caml_copy_string (s);
4275 free (s);
4278 else {
4279 ret_v = caml_copy_string ("0");
4281 CAMLreturn (ret_v);
4284 CAMLprim value ml_freepbo (value s_v)
4286 CAMLparam1 (s_v);
4287 char *s = String_val (s_v);
4288 struct tile *tile = parse_pointer (__func__, s);
4290 if (tile->pbo) {
4291 state.glDeleteBuffersARB (1, &tile->pbo->id);
4292 tile->pbo->id = -1;
4293 tile->pbo->ptr = NULL;
4294 tile->pbo->size = -1;
4296 CAMLreturn (Val_unit);
4299 CAMLprim value ml_unmappbo (value s_v)
4301 CAMLparam1 (s_v);
4302 char *s = String_val (s_v);
4303 struct tile *tile = parse_pointer (__func__, s);
4305 if (tile->pbo) {
4306 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4307 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4308 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4310 tile->pbo->ptr = NULL;
4311 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4313 CAMLreturn (Val_unit);
4316 static void setuppbo (void)
4318 #ifdef USE_EGL
4319 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4320 #else
4321 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4322 #endif
4323 state.bo_usable = GGPA (glBindBufferARB)
4324 && GGPA (glUnmapBufferARB)
4325 && GGPA (glMapBufferARB)
4326 && GGPA (glBufferDataARB)
4327 && GGPA (glGenBuffersARB)
4328 && GGPA (glDeleteBuffersARB);
4329 #undef GGPA
4332 CAMLprim value ml_bo_usable (value unit_v)
4334 CAMLparam1 (unit_v);
4335 CAMLreturn (Val_bool (state.bo_usable));
4338 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4340 CAMLparam3 (ptr_v, x_v, y_v);
4341 CAMLlocal2 (ret_v, tup_v);
4342 struct page *page;
4343 char *s = String_val (ptr_v);
4344 int x = Int_val (x_v), y = Int_val (y_v);
4345 struct pagedim *pdim;
4346 fz_point p;
4347 fz_matrix ctm;
4349 page = parse_pointer (__func__, s);
4350 pdim = &state.pagedims[page->pdimno];
4352 ret_v = Val_int (0);
4353 if (trylock (__func__)) {
4354 goto done;
4357 if (pdf_specifics (state.ctx, state.doc)) {
4358 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4359 ctm = state.pagedims[page->pdimno].tctm;
4361 else {
4362 ctm = fz_identity;
4364 p.x = x + pdim->bounds.x0;
4365 p.y = y + pdim->bounds.y0;
4367 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4368 fz_invert_matrix (&ctm, &ctm);
4369 fz_transform_point (&p, &ctm);
4371 tup_v = caml_alloc_tuple (2);
4372 ret_v = caml_alloc_small (1, 1);
4373 Field (tup_v, 0) = Val_int (p.x);
4374 Field (tup_v, 1) = Val_int (p.y);
4375 Field (ret_v, 0) = tup_v;
4377 unlock (__func__);
4378 done:
4379 CAMLreturn (ret_v);
4382 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4383 value x_v, value y_v)
4385 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4386 CAMLlocal1 (ret_v);
4387 struct page *page;
4388 char *s = String_val (ptr_v);
4389 int pageno = Int_val (pageno_v);
4390 int pdimno = Int_val (pdimno_v);
4391 double x = Double_val (x_v), y = Double_val (y_v);
4392 struct pagedim *pdim;
4393 fz_point p;
4394 fz_matrix ctm;
4396 ret_v = Val_int (0);
4397 lock (__func__);
4399 if (!*s) {
4400 page = loadpage (pageno, pdimno);
4402 else {
4403 page = parse_pointer (__func__, s);
4405 pdim = &state.pagedims[pdimno];
4407 if (pdf_specifics (state.ctx, state.doc)) {
4408 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4409 ctm = state.pagedims[page->pdimno].tctm;
4411 else {
4412 ctm = fz_identity;
4414 p.x = x + pdim->bounds.x0;
4415 p.y = y + pdim->bounds.y0;
4417 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4418 fz_transform_point (&p, &ctm);
4420 ret_v = caml_alloc_tuple (2);
4421 Field (ret_v, 0) = caml_copy_double (p.x);
4422 Field (ret_v, 1) = caml_copy_double (p.y);
4424 if (!*s) {
4425 freepage (page);
4427 unlock (__func__);
4428 CAMLreturn (ret_v);
4431 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4432 value contents_v)
4434 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4435 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4437 if (pdf) {
4438 pdf_annot *annot;
4439 struct page *page;
4440 fz_point p;
4441 char *s = String_val (ptr_v);
4443 page = parse_pointer (__func__, s);
4444 annot = pdf_create_annot (state.ctx, pdf,
4445 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4446 p.x = Int_val (x_v);
4447 p.y = Int_val (y_v);
4448 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4449 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4450 state.dirty = 1;
4452 CAMLreturn (Val_unit);
4455 CAMLprim value ml_delannot (value ptr_v, value n_v)
4457 CAMLparam2 (ptr_v, n_v);
4458 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4460 if (pdf) {
4461 struct page *page;
4462 char *s = String_val (ptr_v);
4463 struct slink *slink;
4465 page = parse_pointer (__func__, s);
4466 slink = &page->slinks[Int_val (n_v)];
4467 pdf_delete_annot (state.ctx, pdf,
4468 (pdf_page *) page->fzpage,
4469 (pdf_annot *) slink->u.annot);
4470 state.dirty = 1;
4472 CAMLreturn (Val_unit);
4475 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4477 CAMLparam3 (ptr_v, n_v, str_v);
4478 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4480 if (pdf) {
4481 struct page *page;
4482 char *s = String_val (ptr_v);
4483 struct slink *slink;
4485 page = parse_pointer (__func__, s);
4486 slink = &page->slinks[Int_val (n_v)];
4487 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4488 String_val (str_v));
4489 state.dirty = 1;
4491 CAMLreturn (Val_unit);
4494 CAMLprim value ml_hasunsavedchanges (value unit_v)
4496 CAMLparam1 (unit_v);
4497 CAMLreturn (Val_bool (state.dirty));
4500 CAMLprim value ml_savedoc (value path_v)
4502 CAMLparam1 (path_v);
4503 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4505 if (pdf) {
4506 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4508 CAMLreturn (Val_unit);
4511 static void makestippletex (void)
4513 const char pixels[] = "\xff\xff\0\0";
4514 glGenTextures (1, &state.stid);
4515 glBindTexture (GL_TEXTURE_1D, state.stid);
4516 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4517 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4518 glTexImage1D (
4519 GL_TEXTURE_1D,
4521 GL_ALPHA,
4524 GL_ALPHA,
4525 GL_UNSIGNED_BYTE,
4526 pixels
4530 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4532 return caml_copy_string (FZ_VERSION);
4535 #ifdef USE_FONTCONFIG
4536 static struct {
4537 int inited;
4538 FcConfig *config;
4539 } fc;
4541 static fz_font *fc_load_system_font_func (fz_context *ctx,
4542 const char *name,
4543 int bold,
4544 int italic,
4545 int UNUSED_ATTR needs_exact_metrics)
4547 char *buf;
4548 size_t i, size;
4549 fz_font *font;
4550 FcChar8 *path;
4551 FcResult result;
4552 FcPattern *pat, *pat1;
4554 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4555 name, bold, italic, needs_exact_metrics);
4556 if (!fc.inited) {
4557 fc.inited = 1;
4558 fc.config = FcInitLoadConfigAndFonts ();
4559 if (!fc.config) {
4560 lprintf ("FcInitLoadConfigAndFonts failed\n");
4561 return NULL;
4564 if (!fc.config) return NULL;
4566 size = strlen (name);
4567 if (bold) size += sizeof (":bold") - 1;
4568 if (italic) size += sizeof (":italic") - 1;
4569 size += 1;
4571 buf = malloc (size);
4572 if (!buf) {
4573 err (1, "malloc %zu failed", size);
4576 strcpy (buf, name);
4577 if (bold && italic) {
4578 strcat (buf, ":bold:italic");
4580 else {
4581 if (bold) strcat (buf, ":bold");
4582 if (italic) strcat (buf, ":italic");
4584 for (i = 0; i < size; ++i) {
4585 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4588 lprintf ("fcbuf=%s\n", buf);
4589 pat = FcNameParse ((FcChar8 *) buf);
4590 if (!pat) {
4591 printd ("emsg FcNameParse failed\n");
4592 free (buf);
4593 return NULL;
4596 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4597 printd ("emsg FcConfigSubstitute failed\n");
4598 free (buf);
4599 return NULL;
4601 FcDefaultSubstitute (pat);
4603 pat1 = FcFontMatch (fc.config, pat, &result);
4604 if (!pat1) {
4605 printd ("emsg FcFontMatch failed\n");
4606 FcPatternDestroy (pat);
4607 free (buf);
4608 return NULL;
4611 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4612 printd ("emsg FcPatternGetString failed\n");
4613 FcPatternDestroy (pat);
4614 FcPatternDestroy (pat1);
4615 free (buf);
4616 return NULL;
4619 #if 0
4620 printd ("emsg name=%s path=%s\n", name, path);
4621 #endif
4622 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4623 FcPatternDestroy (pat);
4624 FcPatternDestroy (pat1);
4625 free (buf);
4626 return font;
4628 #endif
4630 CAMLprim value ml_init (value csock_v, value params_v)
4632 CAMLparam2 (csock_v, params_v);
4633 CAMLlocal2 (trim_v, fuzz_v);
4634 int ret;
4635 int texcount;
4636 char *fontpath;
4637 int colorspace;
4638 int mustoresize;
4639 int haspboext;
4641 state.csock = Int_val (csock_v);
4642 state.rotate = Int_val (Field (params_v, 0));
4643 state.fitmodel = Int_val (Field (params_v, 1));
4644 trim_v = Field (params_v, 2);
4645 texcount = Int_val (Field (params_v, 3));
4646 state.sliceheight = Int_val (Field (params_v, 4));
4647 mustoresize = Int_val (Field (params_v, 5));
4648 colorspace = Int_val (Field (params_v, 6));
4649 fontpath = String_val (Field (params_v, 7));
4651 if (caml_string_length (Field (params_v, 8)) > 0) {
4652 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4654 if (!state.trimcachepath) {
4655 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4656 strerror (errno));
4659 haspboext = Bool_val (Field (params_v, 9));
4661 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4662 fz_register_document_handlers (state.ctx);
4664 #ifdef USE_FONTCONFIG
4665 if (Bool_val (Field (params_v, 10))) {
4666 fz_install_load_system_font_funcs (
4667 state.ctx, fc_load_system_font_func, NULL
4670 #endif
4672 state.trimmargins = Bool_val (Field (trim_v, 0));
4673 fuzz_v = Field (trim_v, 1);
4674 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4675 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4676 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4677 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4679 set_tex_params (colorspace);
4681 if (*fontpath) {
4682 #ifndef USE_FONTCONFIG
4683 state.face = load_font (fontpath);
4684 #else
4685 FcChar8 *path;
4686 FcResult result;
4687 char *buf = fontpath;
4688 FcPattern *pat, *pat1;
4690 fc.inited = 1;
4691 fc.config = FcInitLoadConfigAndFonts ();
4692 if (!fc.config) {
4693 errx (1, "FcInitLoadConfigAndFonts failed");
4696 pat = FcNameParse ((FcChar8 *) buf);
4697 if (!pat) {
4698 errx (1, "FcNameParse failed");
4701 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4702 errx (1, "FcConfigSubstitute failed");
4704 FcDefaultSubstitute (pat);
4706 pat1 = FcFontMatch (fc.config, pat, &result);
4707 if (!pat1) {
4708 errx (1, "FcFontMatch failed");
4711 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4712 errx (1, "FcPatternGetString failed");
4715 state.face = load_font ((char *) path);
4716 FcPatternDestroy (pat);
4717 FcPatternDestroy (pat1);
4718 #endif
4720 else {
4721 int len;
4722 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4723 0, 0, &len);
4724 state.face = load_builtin_font (data, len);
4726 if (!state.face) _exit (1);
4728 realloctexts (texcount);
4730 if (haspboext) {
4731 setuppbo ();
4734 makestippletex ();
4736 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4737 if (ret) {
4738 errx (1, "pthread_create: %s", strerror (ret));
4741 CAMLreturn (Val_unit);