Consistency
[llpp.git] / link.c
blob56ebfd03d3e6322b1ce39c9d2181aa032c463a7d
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 memcpy (p, &size, 4);
390 n = write (fd, p, size + 4);
391 if (n - size - 4) {
392 if (!n) errx (1, "EOF while writing data");
393 err (1, "write (fd %d, req %d, ret %zd)", fd, size + 4, n);
397 static int readlen (int fd)
399 int len;
401 readdata (fd, (void *) &len, 4);
402 return len;
405 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
407 CAMLparam3 (fd_v, bytes_v, len_v);
408 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
409 CAMLreturn0;
412 CAMLprim value ml_rcmd (value fd_v)
414 CAMLparam1 (fd_v);
415 CAMLlocal1 (strdata_v);
416 int fd = Int_val (fd_v);
417 int len = readlen (fd);
418 strdata_v = caml_alloc_string (len);
419 readdata (fd, String_val (strdata_v), len);
420 CAMLreturn (strdata_v);
423 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
425 int size = 200, len;
426 va_list ap;
427 char *buf;
429 buf = malloc (size);
430 for (;;) {
431 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
433 va_start (ap, fmt);
434 len = vsnprintf (buf + 4, size - 4, fmt, ap);
435 va_end (ap);
437 if (len > -1) {
438 if (len < size - 4) {
439 writedata (state.csock, buf, len);
440 break;
442 else size = len + 5;
444 else {
445 err (1, "vsnprintf for `%s' failed", fmt);
447 buf = realloc (buf, size);
449 free (buf);
452 static void closedoc (void)
454 #ifdef CACHE_PAGEREFS
455 if (state.pdflut.objs) {
456 int i;
458 for (i = 0; i < state.pdflut.count; ++i) {
459 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
461 free (state.pdflut.objs);
462 state.pdflut.objs = NULL;
463 state.pdflut.idx = 0;
465 #endif
466 if (state.doc) {
467 fz_drop_document (state.ctx, state.doc);
468 state.doc = NULL;
472 static int openxref (char *filename, char *password)
474 int i;
476 for (i = 0; i < state.texcount; ++i) {
477 state.texowners[i].w = -1;
478 state.texowners[i].slice = NULL;
481 closedoc ();
483 state.dirty = 0;
484 if (state.pagedims) {
485 free (state.pagedims);
486 state.pagedims = NULL;
488 state.pagedimcount = 0;
490 fz_set_aa_level (state.ctx, state.aalevel);
491 state.doc = fz_open_document (state.ctx, filename);
492 if (fz_needs_password (state.ctx, state.doc)) {
493 if (password && !*password) {
494 printd ("pass");
495 return 0;
497 else {
498 int ok = fz_authenticate_password (state.ctx, state.doc, password);
499 if (!ok) {
500 printd ("pass fail");
501 return 0;
505 state.pagecount = fz_count_pages (state.ctx, state.doc);
506 return 1;
509 static void pdfinfo (void)
511 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
512 if (pdf) {
513 pdf_obj *infoobj;
515 printd ("info PDF version\t%d.%d",
516 pdf->version / 10, pdf->version % 10);
518 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
519 pdf), "Info");
520 if (infoobj) {
521 unsigned int i;
522 char *s;
523 char *items[] = { "Title", "Author", "Creator",
524 "Producer", "CreationDate" };
526 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
527 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
528 s = pdf_to_utf8 (state.ctx, pdf, obj);
529 if (*s) printd ("info %s\t%s", items[i], s);
530 fz_free (state.ctx, s);
533 printd ("infoend");
537 static void unlinktile (struct tile *tile)
539 int i;
541 for (i = 0; i < tile->slicecount; ++i) {
542 struct slice *s = &tile->slices[i];
544 if (s->texindex != -1) {
545 if (state.texowners[s->texindex].slice == s) {
546 state.texowners[s->texindex].slice = NULL;
552 static void freepage (struct page *page)
554 if (!page) return;
555 if (page->text) {
556 fz_drop_stext_page (state.ctx, page->text);
558 if (page->sheet) {
559 fz_drop_stext_sheet (state.ctx, page->sheet);
561 if (page->slinks) {
562 free (page->slinks);
564 fz_drop_display_list (state.ctx, page->dlist);
565 fz_drop_page (state.ctx, page->fzpage);
566 free (page);
569 static void freetile (struct tile *tile)
571 unlinktile (tile);
572 if (!tile->pbo) {
573 #ifndef PIGGYBACK
574 fz_drop_pixmap (state.ctx, tile->pixmap);
575 #else
576 if (state.pig) {
577 fz_drop_pixmap (state.ctx, state.pig);
579 state.pig = tile->pixmap;
580 #endif
582 else {
583 free (tile->pbo);
584 fz_drop_pixmap (state.ctx, tile->pixmap);
586 free (tile);
589 #ifdef __ALTIVEC__
590 #include <stdint.h>
591 #include <altivec.h>
593 static int cacheline32bytes;
595 static void __attribute__ ((constructor)) clcheck (void)
597 char **envp = environ;
598 unsigned long *auxv;
600 while (*envp++);
602 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
603 if (*auxv == 19) {
604 cacheline32bytes = auxv[1] == 32;
605 return;
610 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
612 size_t size = pixmap->w * pixmap->h * pixmap->n;
613 if (cacheline32bytes && size > 32) {
614 intptr_t a1, a2, diff;
615 size_t sizea, i;
616 vector unsigned char v = vec_splat_u8 (-1);
617 vector unsigned char *p;
619 a1 = a2 = (intptr_t) pixmap->samples;
620 a2 = (a1 + 31) & ~31;
621 diff = a2 - a1;
622 sizea = size - diff;
623 p = (void *) a2;
625 while (a1 != a2) *(char *) a1++ = 0xff;
626 for (i = 0; i < (sizea & ~31); i += 32) {
627 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
628 vec_st (v, i, p);
629 vec_st (v, i + 16, p);
631 while (i < sizea) *((char *) a1 + i++) = 0xff;
633 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
635 #else
636 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
637 #endif
639 static void trimctm (pdf_page *page, int pindex)
641 fz_matrix ctm;
642 struct pagedim *pdim = &state.pagedims[pindex];
644 if (!pdim->tctmready) {
645 if (state.trimmargins) {
646 fz_rect realbox;
647 fz_matrix rm, sm, tm, im, ctm1;
649 fz_rotate (&rm, -pdim->rotate);
650 fz_scale (&sm, 1, -1);
651 fz_concat (&ctm, &rm, &sm);
652 realbox = pdim->mediabox;
653 fz_transform_rect (&realbox, &ctm);
654 fz_translate (&tm, -realbox.x0, -realbox.y0);
655 fz_concat (&ctm1, &ctm, &tm);
656 fz_invert_matrix (&im, &page->ctm);
657 fz_concat (&ctm, &im, &ctm1);
659 else {
660 ctm = fz_identity;
662 pdim->tctm = ctm;
663 pdim->tctmready = 1;
667 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
669 fz_matrix ctm, tm;
670 int pdimno = pdim - state.pagedims;
672 if (pdf_specifics (state.ctx, state.doc)) {
673 trimctm ((pdf_page *) fzpage, pdimno);
674 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
676 else {
677 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
678 fz_concat (&ctm, &tm, &pdim->ctm);
680 return ctm;
683 static fz_matrix pagectm (struct page *page)
685 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
688 static void *loadpage (int pageno, int pindex)
690 fz_device *dev;
691 struct page *page;
693 page = calloc (sizeof (struct page), 1);
694 if (!page) {
695 err (1, "calloc page %d", pageno);
698 page->dlist = fz_new_display_list (state.ctx);
699 dev = fz_new_list_device (state.ctx, page->dlist);
700 fz_try (state.ctx) {
701 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
702 fz_run_page (state.ctx, page->fzpage, dev,
703 &fz_identity, NULL);
705 fz_catch (state.ctx) {
706 page->fzpage = NULL;
708 fz_drop_device (state.ctx, dev);
710 page->pdimno = pindex;
711 page->pageno = pageno;
712 page->sgen = state.gen;
713 page->agen = state.gen;
714 page->tgen = state.gen;
715 return page;
718 static struct tile *alloctile (int h)
720 int i;
721 int slicecount;
722 size_t tilesize;
723 struct tile *tile;
725 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
726 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
727 tile = calloc (tilesize, 1);
728 if (!tile) {
729 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
731 for (i = 0; i < slicecount; ++i) {
732 int sh = MIN (h, state.sliceheight);
733 tile->slices[i].h = sh;
734 tile->slices[i].texindex = -1;
735 h -= sh;
737 tile->slicecount = slicecount;
738 tile->sliceheight = state.sliceheight;
739 return tile;
742 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
743 struct bo *pbo)
745 fz_rect rect;
746 fz_irect bbox;
747 fz_matrix ctm;
748 fz_device *dev;
749 struct tile *tile;
750 struct pagedim *pdim;
752 tile = alloctile (h);
753 pdim = &state.pagedims[page->pdimno];
755 bbox = pdim->bounds;
756 bbox.x0 += x;
757 bbox.y0 += y;
758 bbox.x1 = bbox.x0 + w;
759 bbox.y1 = bbox.y0 + h;
761 if (state.pig) {
762 if (state.pig->w == w
763 && state.pig->h == h
764 && state.pig->colorspace == state.colorspace) {
765 tile->pixmap = state.pig;
766 tile->pixmap->x = bbox.x0;
767 tile->pixmap->y = bbox.y0;
769 else {
770 fz_drop_pixmap (state.ctx, state.pig);
772 state.pig = NULL;
774 if (!tile->pixmap) {
775 if (pbo) {
776 tile->pixmap =
777 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
778 &bbox, pbo->ptr);
779 tile->pbo = pbo;
781 else {
782 tile->pixmap =
783 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
787 tile->w = w;
788 tile->h = h;
789 clearpixmap (tile->pixmap);
791 dev = fz_new_draw_device (state.ctx, tile->pixmap);
792 ctm = pagectm (page);
793 fz_rect_from_irect (&rect, &bbox);
794 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
795 fz_drop_device (state.ctx, dev);
797 return tile;
800 #ifdef CACHE_PAGEREFS
801 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
802 thanks to Robin Watts */
803 static void
804 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
806 fz_context *ctx = state.ctx; /* doc->ctx; */
807 pdf_obj *kids;
808 int i, len;
810 if (state.pdflut.idx == state.pagecount) return;
812 kids = pdf_dict_gets (ctx, node, "Kids");
813 len = pdf_array_len (ctx, kids);
815 if (len == 0)
816 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
818 if (pdf_mark_obj (ctx, node))
819 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
820 for (i = 0; i < len; i++) {
821 pdf_obj *kid = pdf_array_get (ctx, kids, i);
822 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
823 if (*type
824 ? !strcmp (type, "Pages")
825 : pdf_dict_gets (ctx, kid, "Kids")
826 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
827 pdf_collect_pages (doc, kid);
829 else {
830 if (*type
831 ? strcmp (type, "Page") != 0
832 : !pdf_dict_gets (ctx, kid, "MediaBox"))
833 fz_warn (ctx, "non-page object in page tree (%s)", type);
834 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
837 pdf_unmark_obj (ctx, node);
840 static void
841 pdf_load_page_objs (pdf_document *doc)
843 pdf_obj *root = pdf_dict_gets (state.ctx,
844 pdf_trailer (state.ctx, doc), "Root");
845 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
847 if (!node)
848 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
850 state.pdflut.idx = 0;
851 pdf_collect_pages (doc, node);
853 #endif
855 static void initpdims (int wthack)
857 double start, end;
858 FILE *trimf = NULL;
859 fz_rect rootmediabox;
860 int pageno, trim, show;
861 int trimw = 0, cxcount;
862 fz_context *ctx = state.ctx;
863 pdf_document *pdf = pdf_specifics (ctx, state.doc);
865 fz_var (trimw);
866 fz_var (cxcount);
867 start = now ();
869 if (state.trimmargins && state.trimcachepath) {
870 trimf = fopen (state.trimcachepath, "rb");
871 if (!trimf) {
872 trimf = fopen (state.trimcachepath, "wb");
873 trimw = 1;
877 if (state.trimmargins || pdf || !state.cxack)
878 cxcount = state.pagecount;
879 else
880 cxcount = MIN (state.pagecount, 1);
882 if (pdf) {
883 pdf_obj *obj;
884 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
885 "Root/Pages/MediaBox");
886 pdf_to_rect (ctx, obj, &rootmediabox);
889 #ifdef CACHE_PAGEREFS
890 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
891 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
892 if (!state.pdflut.objs) {
893 err (1, "malloc pageobjs %zu %d %zu failed",
894 sizeof (*state.pdflut.objs), cxcount,
895 sizeof (*state.pdflut.objs) * cxcount);
897 state.pdflut.count = cxcount;
898 pdf_load_page_objs (pdf);
899 state.pdflut.pdf = pdf;
901 #endif
903 for (pageno = 0; pageno < cxcount; ++pageno) {
904 int rotate = 0;
905 struct pagedim *p;
906 fz_rect mediabox;
908 if (pdf) {
909 pdf_obj *pageref, *pageobj;
911 #ifdef CACHE_PAGEREFS
912 pageref = state.pdflut.objs[pageno];
913 #else
914 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
915 #endif
916 pageobj = pdf_resolve_indirect (ctx, pageref);
918 if (state.trimmargins) {
919 pdf_obj *obj;
920 pdf_page *page;
922 fz_try (ctx) {
923 page = pdf_load_page (ctx, pdf, pageno);
924 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
925 trim = state.trimanew || !obj;
926 if (trim) {
927 fz_rect rect;
928 fz_matrix ctm;
929 fz_device *dev;
931 dev = fz_new_bbox_device (ctx, &rect);
932 dev->hints |= FZ_IGNORE_SHADE;
933 fz_invert_matrix (&ctm, &page->ctm);
934 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
935 fz_drop_device (ctx, dev);
937 rect.x0 += state.trimfuzz.x0;
938 rect.x1 += state.trimfuzz.x1;
939 rect.y0 += state.trimfuzz.y0;
940 rect.y1 += state.trimfuzz.y1;
941 fz_transform_rect (&rect, &ctm);
942 fz_intersect_rect (&rect, &page->mediabox);
944 if (fz_is_empty_rect (&rect)) {
945 mediabox = page->mediabox;
947 else {
948 mediabox = rect;
951 obj = pdf_new_array (ctx, pdf, 4);
952 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
953 mediabox.x0));
954 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
955 mediabox.y0));
956 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
957 mediabox.x1));
958 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
959 mediabox.y1));
960 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
962 else {
963 mediabox.x0 = pdf_to_real (ctx,
964 pdf_array_get (ctx, obj, 0));
965 mediabox.y0 = pdf_to_real (ctx,
966 pdf_array_get (ctx, obj, 1));
967 mediabox.x1 = pdf_to_real (ctx,
968 pdf_array_get (ctx, obj, 2));
969 mediabox.y1 = pdf_to_real (ctx,
970 pdf_array_get (ctx, obj, 3));
973 rotate = page->rotate;
974 fz_drop_page (ctx, &page->super);
976 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
977 if (show) {
978 printd ("progress %f Trimming %d",
979 (double) (pageno + 1) / state.pagecount,
980 pageno + 1);
983 fz_catch (ctx) {
984 fprintf (stderr, "failed to load page %d\n", pageno+1);
987 else {
988 int empty = 0;
989 fz_rect cropbox;
991 pdf_to_rect (ctx,
992 pdf_dict_gets (ctx, pageobj, "MediaBox"),
993 &mediabox);
994 if (fz_is_empty_rect (&mediabox)) {
995 mediabox.x0 = 0;
996 mediabox.y0 = 0;
997 mediabox.x1 = 612;
998 mediabox.y1 = 792;
999 empty = 1;
1002 pdf_to_rect (ctx,
1003 pdf_dict_gets (ctx, pageobj, "CropBox"),
1004 &cropbox);
1005 if (!fz_is_empty_rect (&cropbox)) {
1006 if (empty) {
1007 mediabox = cropbox;
1009 else {
1010 fz_intersect_rect (&mediabox, &cropbox);
1013 else {
1014 if (empty) {
1015 if (fz_is_empty_rect (&rootmediabox)) {
1016 fprintf (stderr,
1017 "cannot find page size for page %d\n",
1018 pageno+1);
1020 else {
1021 mediabox = rootmediabox;
1025 rotate = pdf_to_int (ctx,
1026 pdf_dict_gets (ctx, pageobj, "Rotate"));
1029 else {
1030 if (state.trimmargins && trimw) {
1031 fz_page *page;
1033 fz_try (ctx) {
1034 page = fz_load_page (ctx, state.doc, pageno);
1035 fz_bound_page (ctx, page, &mediabox);
1036 rotate = 0;
1037 if (state.trimmargins) {
1038 fz_rect rect;
1039 fz_device *dev;
1041 dev = fz_new_bbox_device (ctx, &rect);
1042 dev->hints |= FZ_IGNORE_SHADE;
1043 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1044 fz_drop_device (ctx, dev);
1046 rect.x0 += state.trimfuzz.x0;
1047 rect.x1 += state.trimfuzz.x1;
1048 rect.y0 += state.trimfuzz.y0;
1049 rect.y1 += state.trimfuzz.y1;
1050 fz_intersect_rect (&rect, &mediabox);
1052 if (!fz_is_empty_rect (&rect)) {
1053 mediabox = rect;
1056 fz_drop_page (ctx, page);
1057 if (!state.cxack) {
1058 printd ("progress %f loading %d",
1059 (double) (pageno + 1) / state.pagecount,
1060 pageno + 1);
1063 fz_catch (ctx) {
1065 if (trimf) {
1066 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1067 if (n - 1) {
1068 err (1, "fwrite trim mediabox");
1072 else {
1073 if (trimf) {
1074 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1075 if (n - 1) {
1076 err (1, "fread trim mediabox %d", pageno);
1079 else {
1080 fz_page *page;
1081 fz_try (ctx) {
1082 page = fz_load_page (ctx, state.doc, pageno);
1083 fz_bound_page (ctx, page, &mediabox);
1084 fz_drop_page (ctx, page);
1086 show = !state.trimmargins && pageno % 20 == 0;
1087 if (show) {
1088 printd ("progress %f Gathering dimensions %d",
1089 (double) (pageno) / state.pagecount,
1090 pageno);
1093 fz_catch (ctx) {
1094 fprintf (stderr, "failed to load page %d\n", pageno);
1100 if (state.pagedimcount == 0
1101 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1102 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1103 size_t size;
1105 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1106 state.pagedims = realloc (state.pagedims, size);
1107 if (!state.pagedims) {
1108 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1109 size, state.pagedimcount + 1);
1112 p = &state.pagedims[state.pagedimcount++];
1113 p->rotate = rotate;
1114 p->mediabox = mediabox;
1115 p->pageno = pageno;
1118 end = now ();
1119 if (!wthack) {
1120 printd ("progress 1 %s %d pages in %f seconds",
1121 state.trimmargins ? "Trimmed" : "Processed",
1122 state.pagecount, end - start);
1124 state.trimanew = 0;
1125 if (trimf) {
1126 if (fclose (trimf)) {
1127 err (1, "fclose");
1132 static void layout (void)
1134 int pindex;
1135 fz_rect box;
1136 fz_matrix ctm, rm;
1137 struct pagedim *p = p;
1138 double zw, w, maxw = 0.0, zoom = zoom;
1140 if (state.pagedimcount == 0) return;
1142 switch (state.fitmodel) {
1143 case FitProportional:
1144 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1145 double x0, x1;
1147 p = &state.pagedims[pindex];
1148 fz_rotate (&rm, p->rotate + state.rotate);
1149 box = p->mediabox;
1150 fz_transform_rect (&box, &rm);
1152 x0 = MIN (box.x0, box.x1);
1153 x1 = MAX (box.x0, box.x1);
1155 w = x1 - x0;
1156 maxw = MAX (w, maxw);
1157 zoom = state.w / maxw;
1159 break;
1161 case FitPage:
1162 maxw = state.w;
1163 break;
1165 case FitWidth:
1166 break;
1168 default:
1169 ARSERT (0 && state.fitmodel);
1172 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1173 fz_rect rect;
1174 fz_matrix tm, sm;
1176 p = &state.pagedims[pindex];
1177 fz_rotate (&ctm, state.rotate);
1178 fz_rotate (&rm, p->rotate + state.rotate);
1179 box = p->mediabox;
1180 fz_transform_rect (&box, &rm);
1181 w = box.x1 - box.x0;
1182 switch (state.fitmodel) {
1183 case FitProportional:
1184 p->left = ((maxw - w) * zoom) / 2.0;
1185 break;
1186 case FitPage:
1188 double zh, h;
1189 zw = maxw / w;
1190 h = box.y1 - box.y0;
1191 zh = state.h / h;
1192 zoom = MIN (zw, zh);
1193 p->left = (maxw - (w * zoom)) / 2.0;
1195 break;
1196 case FitWidth:
1197 p->left = 0;
1198 zoom = state.w / w;
1199 break;
1202 fz_scale (&p->zoomctm, zoom, zoom);
1203 fz_concat (&ctm, &p->zoomctm, &ctm);
1205 fz_rotate (&rm, p->rotate);
1206 p->pagebox = p->mediabox;
1207 fz_transform_rect (&p->pagebox, &rm);
1208 p->pagebox.x1 -= p->pagebox.x0;
1209 p->pagebox.y1 -= p->pagebox.y0;
1210 p->pagebox.x0 = 0;
1211 p->pagebox.y0 = 0;
1212 rect = p->pagebox;
1213 fz_transform_rect (&rect, &ctm);
1214 fz_round_rect (&p->bounds, &rect);
1215 p->ctm = ctm;
1217 fz_translate (&tm, 0, -p->mediabox.y1);
1218 fz_scale (&sm, zoom, -zoom);
1219 fz_concat (&ctm, &tm, &sm);
1220 fz_concat (&p->lctm, &ctm, &rm);
1222 p->tctmready = 0;
1225 do {
1226 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1227 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1228 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1229 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1230 int boundw = x1 - x0;
1231 int boundh = y1 - y0;
1233 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1234 } while (p-- != state.pagedims);
1237 static
1238 struct anchor { int n; int x; int y; int w; int h; }
1239 desttoanchor (fz_link_dest *dest)
1241 int i;
1242 struct anchor a;
1243 struct pagedim *pdim = state.pagedims;
1245 a.n = -1;
1246 a.x = 0;
1247 a.y = 0;
1248 for (i = 0; i < state.pagedimcount; ++i) {
1249 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1250 break;
1251 pdim = &state.pagedims[i];
1253 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1254 fz_point p;
1255 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1256 p.x = dest->ld.gotor.lt.x;
1257 else
1258 p.x = 0.0;
1259 p.y = dest->ld.gotor.lt.y;
1260 fz_transform_point (&p, &pdim->lctm);
1261 a.x = p.x;
1262 a.y = p.y;
1264 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1265 double x0, x1, y0, y1;
1267 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1268 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1269 a.w = x1 - x0;
1270 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1271 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1272 a.h = y1 - y0;
1273 a.n = dest->ld.gotor.page;
1275 return a;
1278 static void recurse_outline (fz_outline *outline, int level)
1280 while (outline) {
1281 switch (outline->dest.kind) {
1282 case FZ_LINK_GOTO:
1284 struct anchor a = desttoanchor (&outline->dest);
1286 if (a.n >= 0) {
1287 printd ("o %d %d %d %d %s",
1288 level, a.n, a.y, a.h, outline->title);
1291 break;
1293 case FZ_LINK_URI:
1294 printd ("ou %d %" FMT_s " %s %s", level,
1295 strlen (outline->title), outline->title,
1296 outline->dest.ld.uri.uri);
1297 break;
1299 case FZ_LINK_NONE:
1300 printd ("on %d %s", level, outline->title);
1301 break;
1303 default:
1304 printd ("emsg Unhandled outline kind %d for %s\n",
1305 outline->dest.kind, outline->title);
1306 break;
1308 if (outline->down) {
1309 recurse_outline (outline->down, level + 1);
1311 outline = outline->next;
1315 static void process_outline (void)
1317 fz_outline *outline;
1319 if (!state.needoutline || !state.pagedimcount) return;
1321 state.needoutline = 0;
1322 outline = fz_load_outline (state.ctx, state.doc);
1323 if (outline) {
1324 recurse_outline (outline, 0);
1325 fz_drop_outline (state.ctx, outline);
1329 static char *strofspan (fz_stext_span *span)
1331 char *p;
1332 char utf8[10];
1333 fz_stext_char *ch;
1334 size_t size = 0, cap = 80;
1336 p = malloc (cap + 1);
1337 if (!p) return NULL;
1339 for (ch = span->text; ch < span->text + span->len; ++ch) {
1340 int n = fz_runetochar (utf8, ch->c);
1341 if (size + n > cap) {
1342 cap *= 2;
1343 p = realloc (p, cap + 1);
1344 if (!p) return NULL;
1347 memcpy (p + size, utf8, n);
1348 size += n;
1350 p[size] = 0;
1351 return p;
1354 static int matchspan (regex_t *re, fz_stext_span *span,
1355 int stop, int pageno, double start)
1357 int ret;
1358 char *p;
1359 regmatch_t rm;
1360 int a, b, c;
1361 fz_rect sb, eb;
1362 fz_point p1, p2, p3, p4;
1364 p = strofspan (span);
1365 if (!p) return -1;
1367 ret = regexec (re, p, 1, &rm, 0);
1368 if (ret) {
1369 free (p);
1370 if (ret != REG_NOMATCH) {
1371 size_t size;
1372 char errbuf[80];
1373 size = regerror (ret, re, errbuf, sizeof (errbuf));
1374 printd ("msg regexec error `%.*s'",
1375 (int) size, errbuf);
1376 return -1;
1378 return 0;
1380 else {
1381 int l = span->len;
1383 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1384 c += fz_runelen (span->text[a].c);
1386 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1387 c += fz_runelen (span->text[b].c);
1390 if (fz_runelen (span->text[b].c) > 1) {
1391 b = MAX (0, b-1);
1394 fz_stext_char_bbox (state.ctx, &sb, span, a);
1395 fz_stext_char_bbox (state.ctx, &eb, span, b);
1397 p1.x = sb.x0;
1398 p1.y = sb.y0;
1399 p2.x = eb.x1;
1400 p2.y = sb.y0;
1401 p3.x = eb.x1;
1402 p3.y = eb.y1;
1403 p4.x = sb.x0;
1404 p4.y = eb.y1;
1406 if (!stop) {
1407 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1408 pageno, 1,
1409 p1.x, p1.y,
1410 p2.x, p2.y,
1411 p3.x, p3.y,
1412 p4.x, p4.y);
1414 printd ("progress 1 found at %d `%.*s' in %f sec",
1415 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1416 now () - start);
1418 else {
1419 printd ("match %d %d %f %f %f %f %f %f %f %f",
1420 pageno, 2,
1421 p1.x, p1.y,
1422 p2.x, p2.y,
1423 p3.x, p3.y,
1424 p4.x, p4.y);
1426 free (p);
1427 return 1;
1431 static int compareblocks (const void *l, const void *r)
1433 fz_stext_block const *ls = l;
1434 fz_stext_block const *rs = r;
1435 return ls->bbox.y0 - rs->bbox.y0;
1438 /* wishful thinking function */
1439 static void search (regex_t *re, int pageno, int y, int forward)
1441 int i, j;
1442 fz_device *tdev;
1443 fz_stext_page *text;
1444 fz_stext_sheet *sheet;
1445 struct pagedim *pdim, *pdimprev;
1446 int stop = 0, niters = 0;
1447 double start, end;
1448 fz_page *page;
1450 start = now ();
1451 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1452 if (niters++ == 5) {
1453 niters = 0;
1454 if (hasdata ()) {
1455 printd ("progress 1 attention requested aborting search at %d",
1456 pageno);
1457 stop = 1;
1459 else {
1460 printd ("progress %f searching in page %d",
1461 (double) (pageno + 1) / state.pagecount,
1462 pageno);
1465 pdimprev = NULL;
1466 for (i = 0; i < state.pagedimcount; ++i) {
1467 pdim = &state.pagedims[i];
1468 if (pdim->pageno == pageno) {
1469 goto found;
1471 if (pdim->pageno > pageno) {
1472 pdim = pdimprev;
1473 goto found;
1475 pdimprev = pdim;
1477 pdim = pdimprev;
1478 found:
1480 sheet = fz_new_stext_sheet (state.ctx);
1481 text = fz_new_stext_page (state.ctx);
1482 tdev = fz_new_stext_device (state.ctx, sheet, text);
1484 page = fz_load_page (state.ctx, state.doc, pageno);
1486 fz_matrix ctm = pagectm1 (page, pdim);
1487 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1490 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1491 fz_drop_device (state.ctx, tdev);
1493 for (j = 0; j < text->len; ++j) {
1494 int k;
1495 fz_page_block *pb;
1496 fz_stext_block *block;
1498 pb = &text->blocks[forward ? j : text->len - 1 - j];
1499 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1500 block = pb->u.text;
1502 for (k = 0; k < block->len; ++k) {
1503 fz_stext_line *line;
1504 fz_stext_span *span;
1506 if (forward) {
1507 line = &block->lines[k];
1508 if (line->bbox.y0 < y + 1) continue;
1510 else {
1511 line = &block->lines[block->len - 1 - k];
1512 if (line->bbox.y0 > y - 1) continue;
1515 for (span = line->first_span; span; span = span->next) {
1516 switch (matchspan (re, span, stop, pageno, start)) {
1517 case 0: break;
1518 case 1: stop = 1; break;
1519 case -1: stop = 1; goto endloop;
1524 if (forward) {
1525 pageno += 1;
1526 y = 0;
1528 else {
1529 pageno -= 1;
1530 y = INT_MAX;
1532 endloop:
1533 fz_drop_stext_page (state.ctx, text);
1534 fz_drop_stext_sheet (state.ctx, sheet);
1535 fz_drop_page (state.ctx, page);
1537 end = now ();
1538 if (!stop) {
1539 printd ("progress 1 no matches %f sec", end - start);
1541 printd ("clearrects");
1544 static void set_tex_params (int colorspace)
1546 union {
1547 unsigned char b;
1548 unsigned int s;
1549 } endianness = {1};
1551 switch (colorspace) {
1552 case 0:
1553 state.texiform = GL_RGBA8;
1554 state.texform = GL_RGBA;
1555 state.texty = GL_UNSIGNED_BYTE;
1556 state.colorspace = fz_device_rgb (state.ctx);
1557 break;
1558 case 1:
1559 state.texiform = GL_RGBA8;
1560 state.texform = GL_BGRA;
1561 state.texty = endianness.s > 1
1562 ? GL_UNSIGNED_INT_8_8_8_8
1563 : GL_UNSIGNED_INT_8_8_8_8_REV;
1564 state.colorspace = fz_device_bgr (state.ctx);
1565 break;
1566 case 2:
1567 state.texiform = GL_LUMINANCE_ALPHA;
1568 state.texform = GL_LUMINANCE_ALPHA;
1569 state.texty = GL_UNSIGNED_BYTE;
1570 state.colorspace = fz_device_gray (state.ctx);
1571 break;
1572 default:
1573 errx (1, "invalid colorspce %d", colorspace);
1577 static void realloctexts (int texcount)
1579 size_t size;
1581 if (texcount == state.texcount) return;
1583 if (texcount < state.texcount) {
1584 glDeleteTextures (state.texcount - texcount,
1585 state.texids + texcount);
1588 size = texcount * sizeof (*state.texids);
1589 state.texids = realloc (state.texids, size);
1590 if (!state.texids) {
1591 err (1, "realloc texids %" FMT_s, size);
1594 size = texcount * sizeof (*state.texowners);
1595 state.texowners = realloc (state.texowners, size);
1596 if (!state.texowners) {
1597 err (1, "realloc texowners %" FMT_s, size);
1599 if (texcount > state.texcount) {
1600 int i;
1602 glGenTextures (texcount - state.texcount,
1603 state.texids + state.texcount);
1604 for (i = state.texcount; i < texcount; ++i) {
1605 state.texowners[i].w = -1;
1606 state.texowners[i].slice = NULL;
1609 state.texcount = texcount;
1610 state.texindex = 0;
1613 static char *mbtoutf8 (char *s)
1615 char *p, *r;
1616 wchar_t *tmp;
1617 size_t i, ret, len;
1619 len = mbstowcs (NULL, s, strlen (s));
1620 if (len == 0) {
1621 return s;
1623 else {
1624 if (len == (size_t) -1) {
1625 return s;
1629 tmp = malloc (len * sizeof (wchar_t));
1630 if (!tmp) {
1631 return s;
1634 ret = mbstowcs (tmp, s, len);
1635 if (ret == (size_t) -1) {
1636 free (tmp);
1637 return s;
1640 len = 0;
1641 for (i = 0; i < ret; ++i) {
1642 len += fz_runelen (tmp[i]);
1645 p = r = malloc (len + 1);
1646 if (!r) {
1647 free (tmp);
1648 return s;
1651 for (i = 0; i < ret; ++i) {
1652 p += fz_runetochar (p, tmp[i]);
1654 *p = 0;
1655 free (tmp);
1656 return r;
1659 CAMLprim value ml_mbtoutf8 (value s_v)
1661 CAMLparam1 (s_v);
1662 CAMLlocal1 (ret_v);
1663 char *s, *r;
1665 s = String_val (s_v);
1666 r = mbtoutf8 (s);
1667 if (r == s) {
1668 ret_v = s_v;
1670 else {
1671 ret_v = caml_copy_string (r);
1672 free (r);
1674 CAMLreturn (ret_v);
1677 static void * mainloop (void UNUSED_ATTR *unused)
1679 char *p = NULL;
1680 int len, ret, oldlen = 0;
1682 fz_var (p);
1683 fz_var (oldlen);
1684 for (;;) {
1685 len = readlen (state.csock);
1686 if (len == 0) {
1687 errx (1, "readlen returned 0");
1690 if (oldlen < len + 1) {
1691 p = realloc (p, len + 1);
1692 if (!p) {
1693 err (1, "realloc %d failed", len + 1);
1695 oldlen = len + 1;
1697 readdata (state.csock, p, len);
1698 p[len] = 0;
1700 if (!strncmp ("open", p, 4)) {
1701 int wthack, off, ok = 0;
1702 char *password;
1703 char *filename;
1704 char *utf8filename;
1705 size_t filenamelen;
1707 fz_var (ok);
1708 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1709 if (ret != 2) {
1710 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1713 filename = p + 5 + off;
1714 filenamelen = strlen (filename);
1715 password = filename + filenamelen + 1;
1717 lock ("open");
1718 fz_try (state.ctx) {
1719 ok = openxref (filename, password);
1721 fz_catch (state.ctx) {
1722 utf8filename = mbtoutf8 (filename);
1723 printd ("msg Could not open %s", utf8filename);
1725 if (ok) {
1726 pdfinfo ();
1727 initpdims (wthack);
1729 unlock ("open");
1731 if (ok) {
1732 if (!wthack) {
1733 utf8filename = mbtoutf8 (filename);
1734 printd ("msg Opened %s (press h/F1 to get help)",
1735 utf8filename);
1736 if (utf8filename != filename) {
1737 free (utf8filename);
1740 state.needoutline = 1;
1743 else if (!strncmp ("cs", p, 2)) {
1744 int i, colorspace;
1746 ret = sscanf (p + 2, " %d", &colorspace);
1747 if (ret != 1) {
1748 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1750 lock ("cs");
1751 set_tex_params (colorspace);
1752 for (i = 0; i < state.texcount; ++i) {
1753 state.texowners[i].w = -1;
1754 state.texowners[i].slice = NULL;
1756 unlock ("cs");
1758 else if (!strncmp ("freepage", p, 8)) {
1759 void *ptr;
1761 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1762 if (ret != 1) {
1763 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1765 freepage (ptr);
1767 else if (!strncmp ("freetile", p, 8)) {
1768 void *ptr;
1770 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1771 if (ret != 1) {
1772 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1774 freetile (ptr);
1776 else if (!strncmp ("search", p, 6)) {
1777 int icase, pageno, y, len2, forward;
1778 char *pattern;
1779 regex_t re;
1781 ret = sscanf (p + 6, " %d %d %d %d,%n",
1782 &icase, &pageno, &y, &forward, &len2);
1783 if (ret != 4) {
1784 errx (1, "malformed search `%s' ret=%d", p, ret);
1787 pattern = p + 6 + len2;
1788 ret = regcomp (&re, pattern,
1789 REG_EXTENDED | (icase ? REG_ICASE : 0));
1790 if (ret) {
1791 char errbuf[80];
1792 size_t size;
1794 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1795 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1797 else {
1798 search (&re, pageno, y, forward);
1799 regfree (&re);
1802 else if (!strncmp ("geometry", p, 8)) {
1803 int w, h, fitmodel;
1805 printd ("clear");
1806 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1807 if (ret != 3) {
1808 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1811 lock ("geometry");
1812 state.h = h;
1813 if (w != state.w) {
1814 int i;
1815 state.w = w;
1816 for (i = 0; i < state.texcount; ++i) {
1817 state.texowners[i].slice = NULL;
1820 state.fitmodel = fitmodel;
1821 layout ();
1822 process_outline ();
1824 state.gen++;
1825 unlock ("geometry");
1826 printd ("continue %d", state.pagecount);
1828 else if (!strncmp ("reqlayout", p, 9)) {
1829 char *nameddest;
1830 int rotate, off, h;
1831 unsigned int fitmodel;
1832 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1834 printd ("clear");
1835 ret = sscanf (p + 9, " %d %u %d %n",
1836 &rotate, &fitmodel, &h, &off);
1837 if (ret != 3) {
1838 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1840 lock ("reqlayout");
1841 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1842 state.gen += 1;
1844 state.rotate = rotate;
1845 state.fitmodel = fitmodel;
1846 state.h = h;
1847 layout ();
1848 process_outline ();
1850 nameddest = p + 9 + off;
1851 if (pdf && nameddest && *nameddest) {
1852 struct anchor a;
1853 fz_link_dest dest;
1854 pdf_obj *needle, *obj;
1856 needle = pdf_new_string (state.ctx, pdf, nameddest,
1857 strlen (nameddest));
1858 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1859 if (obj) {
1860 dest = pdf_parse_link_dest (state.ctx, pdf,
1861 FZ_LINK_GOTO, obj);
1863 a = desttoanchor (&dest);
1864 if (a.n >= 0) {
1865 printd ("a %d %d %d", a.n, a.x, a.y);
1867 else {
1868 printd ("emsg failed to parse destination `%s'\n",
1869 nameddest);
1872 else {
1873 printd ("emsg destination `%s' not found\n",
1874 nameddest);
1876 pdf_drop_obj (state.ctx, needle);
1879 state.gen++;
1880 unlock ("reqlayout");
1881 printd ("continue %d", state.pagecount);
1883 else if (!strncmp ("page", p, 4)) {
1884 double a, b;
1885 struct page *page;
1886 int pageno, pindex;
1888 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1889 if (ret != 2) {
1890 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1893 lock ("page");
1894 a = now ();
1895 page = loadpage (pageno, pindex);
1896 b = now ();
1897 unlock ("page");
1899 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1901 else if (!strncmp ("tile", p, 4)) {
1902 int x, y, w, h;
1903 struct page *page;
1904 struct tile *tile;
1905 double a, b;
1906 void *data;
1908 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1909 SCN_ptr_cast (&page), &x, &y, &w, &h,
1910 SCN_ptr_cast (&data));
1911 if (ret != 6) {
1912 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1915 lock ("tile");
1916 a = now ();
1917 tile = rendertile (page, x, y, w, h, data);
1918 b = now ();
1919 unlock ("tile");
1921 printd ("tile %d %d %" FMT_ptr " %u %f",
1922 x, y,
1923 FMT_ptr_cast (tile),
1924 tile->w * tile->h * tile->pixmap->n,
1925 b - a);
1927 else if (!strncmp ("trimset", p, 7)) {
1928 fz_irect fuzz;
1929 int trimmargins;
1931 ret = sscanf (p + 7, " %d %d %d %d %d",
1932 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1933 if (ret != 5) {
1934 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1936 lock ("trimset");
1937 state.trimmargins = trimmargins;
1938 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1939 state.trimanew = 1;
1940 state.trimfuzz = fuzz;
1942 unlock ("trimset");
1944 else if (!strncmp ("settrim", p, 7)) {
1945 fz_irect fuzz;
1946 int trimmargins;
1948 ret = sscanf (p + 7, " %d %d %d %d %d",
1949 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1950 if (ret != 5) {
1951 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1953 printd ("clear");
1954 lock ("settrim");
1955 state.trimmargins = trimmargins;
1956 state.needoutline = 1;
1957 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1958 state.trimanew = 1;
1959 state.trimfuzz = fuzz;
1961 state.pagedimcount = 0;
1962 free (state.pagedims);
1963 state.pagedims = NULL;
1964 initpdims (0);
1965 layout ();
1966 process_outline ();
1967 unlock ("settrim");
1968 printd ("continue %d", state.pagecount);
1970 else if (!strncmp ("sliceh", p, 6)) {
1971 int h;
1973 ret = sscanf (p + 6, " %d", &h);
1974 if (ret != 1) {
1975 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1977 if (h != state.sliceheight) {
1978 int i;
1980 state.sliceheight = h;
1981 for (i = 0; i < state.texcount; ++i) {
1982 state.texowners[i].w = -1;
1983 state.texowners[i].h = -1;
1984 state.texowners[i].slice = NULL;
1988 else if (!strncmp ("interrupt", p, 9)) {
1989 printd ("vmsg interrupted");
1991 else {
1992 errx (1, "unknown command %.*s", len, p);
1995 return 0;
1998 CAMLprim value ml_realloctexts (value texcount_v)
2000 CAMLparam1 (texcount_v);
2001 int ok;
2003 if (trylock (__func__)) {
2004 ok = 0;
2005 goto done;
2007 realloctexts (Int_val (texcount_v));
2008 ok = 1;
2009 unlock (__func__);
2011 done:
2012 CAMLreturn (Val_bool (ok));
2015 static void recti (int x0, int y0, int x1, int y1)
2017 GLfloat *v = state.vertices;
2019 glVertexPointer (2, GL_FLOAT, 0, v);
2020 v[0] = x0; v[1] = y0;
2021 v[2] = x1; v[3] = y0;
2022 v[4] = x0; v[5] = y1;
2023 v[6] = x1; v[7] = y1;
2024 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2027 static void showsel (struct page *page, int ox, int oy)
2029 int seen = 0;
2030 fz_irect bbox;
2031 fz_rect rect;
2032 fz_stext_line *line;
2033 fz_page_block *pageb;
2034 fz_stext_block *block;
2035 struct mark first, last;
2036 unsigned char selcolor[] = {15,15,15,140};
2038 first = page->fmark;
2039 last = page->lmark;
2041 if (!first.span || !last.span) return;
2043 glEnable (GL_BLEND);
2044 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2045 glColor4ubv (selcolor);
2047 ox += state.pagedims[page->pdimno].bounds.x0;
2048 oy += state.pagedims[page->pdimno].bounds.y0;
2049 for (pageb = page->text->blocks;
2050 pageb < page->text->blocks + page->text->len;
2051 ++pageb) {
2052 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2053 block = pageb->u.text;
2055 for (line = block->lines;
2056 line < block->lines + block->len;
2057 ++line) {
2058 fz_stext_span *span;
2059 rect = fz_empty_rect;
2061 for (span = line->first_span; span; span = span->next) {
2062 int i, j, k;
2063 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2065 j = 0;
2066 k = span->len - 1;
2068 if (span == page->fmark.span && span == page->lmark.span) {
2069 seen = 1;
2070 j = MIN (first.i, last.i);
2071 k = MAX (first.i, last.i);
2073 else {
2074 if (span == first.span) {
2075 seen = 1;
2076 j = first.i;
2078 else if (span == last.span) {
2079 seen = 1;
2080 k = last.i;
2084 if (seen) {
2085 for (i = j; i <= k; ++i) {
2086 fz_rect bbox1;
2087 fz_union_rect (&rect,
2088 fz_stext_char_bbox (state.ctx, &bbox1,
2089 span, i));
2091 fz_round_rect (&bbox, &rect);
2092 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2093 bbox.x0,
2094 bbox.y0,
2095 bbox.x1,
2096 bbox.y1,
2097 oy, ox);
2099 recti (bbox.x0 + ox, bbox.y0 + oy,
2100 bbox.x1 + ox, bbox.y1 + oy);
2101 if (span == last.span) {
2102 goto done;
2104 rect = fz_empty_rect;
2109 done:
2110 glDisable (GL_BLEND);
2113 #include "glfont.c"
2115 static void stipplerect (fz_matrix *m,
2116 fz_point *p1,
2117 fz_point *p2,
2118 fz_point *p3,
2119 fz_point *p4,
2120 GLfloat *texcoords,
2121 GLfloat *vertices)
2123 fz_transform_point (p1, m);
2124 fz_transform_point (p2, m);
2125 fz_transform_point (p3, m);
2126 fz_transform_point (p4, m);
2128 float w, h, s, t;
2130 w = p2->x - p1->x;
2131 h = p2->y - p1->y;
2132 t = sqrtf (w*w + h*h) * .25f;
2134 w = p3->x - p2->x;
2135 h = p3->y - p2->y;
2136 s = sqrtf (w*w + h*h) * .25f;
2138 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2139 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2141 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2142 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2144 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2145 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2147 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2148 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2150 glDrawArrays (GL_LINES, 0, 8);
2153 static void solidrect (fz_matrix *m,
2154 fz_point *p1,
2155 fz_point *p2,
2156 fz_point *p3,
2157 fz_point *p4,
2158 GLfloat *vertices)
2160 fz_transform_point (p1, m);
2161 fz_transform_point (p2, m);
2162 fz_transform_point (p3, m);
2163 fz_transform_point (p4, m);
2164 vertices[0] = p1->x; vertices[1] = p1->y;
2165 vertices[2] = p2->x; vertices[3] = p2->y;
2167 vertices[4] = p3->x; vertices[5] = p3->y;
2168 vertices[6] = p4->x; vertices[7] = p4->y;
2169 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2172 static void highlightlinks (struct page *page, int xoff, int yoff)
2174 int i;
2175 fz_matrix ctm, tm, pm;
2176 fz_link *link, *links;
2177 GLfloat *texcoords = state.texcoords;
2178 GLfloat *vertices = state.vertices;
2180 links = fz_load_links (state.ctx, page->fzpage);
2182 glEnable (GL_TEXTURE_1D);
2183 glEnable (GL_BLEND);
2184 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2185 glBindTexture (GL_TEXTURE_1D, state.stid);
2187 xoff -= state.pagedims[page->pdimno].bounds.x0;
2188 yoff -= state.pagedims[page->pdimno].bounds.y0;
2189 fz_translate (&tm, xoff, yoff);
2190 pm = pagectm (page);
2191 fz_concat (&ctm, &pm, &tm);
2193 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2194 glVertexPointer (2, GL_FLOAT, 0, vertices);
2196 for (link = links; link; link = link->next) {
2197 fz_point p1, p2, p3, p4;
2199 p1.x = link->rect.x0;
2200 p1.y = link->rect.y0;
2202 p2.x = link->rect.x1;
2203 p2.y = link->rect.y0;
2205 p3.x = link->rect.x1;
2206 p3.y = link->rect.y1;
2208 p4.x = link->rect.x0;
2209 p4.y = link->rect.y1;
2211 switch (link->dest.kind) {
2212 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2213 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2214 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2215 default: glColor3ub (0, 0, 0); break;
2217 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2220 for (i = 0; i < page->annotcount; ++i) {
2221 fz_point p1, p2, p3, p4;
2222 struct annot *annot = &page->annots[i];
2224 p1.x = annot->bbox.x0;
2225 p1.y = annot->bbox.y0;
2227 p2.x = annot->bbox.x1;
2228 p2.y = annot->bbox.y0;
2230 p3.x = annot->bbox.x1;
2231 p3.y = annot->bbox.y1;
2233 p4.x = annot->bbox.x0;
2234 p4.y = annot->bbox.y1;
2236 glColor3ub (0, 0, 128);
2237 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2240 glDisable (GL_BLEND);
2241 glDisable (GL_TEXTURE_1D);
2244 static int compareslinks (const void *l, const void *r)
2246 struct slink const *ls = l;
2247 struct slink const *rs = r;
2248 if (ls->bbox.y0 == rs->bbox.y0) {
2249 return rs->bbox.x0 - rs->bbox.x0;
2251 return ls->bbox.y0 - rs->bbox.y0;
2254 static void droptext (struct page *page)
2256 if (page->text) {
2257 fz_drop_stext_page (state.ctx, page->text);
2258 page->fmark.i = -1;
2259 page->lmark.i = -1;
2260 page->fmark.span = NULL;
2261 page->lmark.span = NULL;
2262 page->text = NULL;
2264 if (page->sheet) {
2265 fz_drop_stext_sheet (state.ctx, page->sheet);
2266 page->sheet = NULL;
2270 static void dropannots (struct page *page)
2272 if (page->annots) {
2273 free (page->annots);
2274 page->annots = NULL;
2275 page->annotcount = 0;
2279 static void ensureannots (struct page *page)
2281 int i, count = 0;
2282 size_t annotsize = sizeof (*page->annots);
2283 fz_annot *annot;
2285 if (state.gen != page->agen) {
2286 dropannots (page);
2287 page->agen = state.gen;
2289 if (page->annots) return;
2291 for (annot = fz_first_annot (state.ctx, page->fzpage);
2292 annot;
2293 annot = fz_next_annot (state.ctx, annot)) {
2294 count++;
2297 if (count > 0) {
2298 page->annotcount = count;
2299 page->annots = calloc (count, annotsize);
2300 if (!page->annots) {
2301 err (1, "calloc annots %d", count);
2304 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2305 annot;
2306 annot = fz_next_annot (state.ctx, annot), i++) {
2307 fz_rect rect;
2309 fz_bound_annot (state.ctx, annot, &rect);
2310 page->annots[i].annot = annot;
2311 fz_round_rect (&page->annots[i].bbox, &rect);
2316 static void dropslinks (struct page *page)
2318 if (page->slinks) {
2319 free (page->slinks);
2320 page->slinks = NULL;
2321 page->slinkcount = 0;
2325 static void ensureslinks (struct page *page)
2327 fz_matrix ctm;
2328 int i, count;
2329 size_t slinksize = sizeof (*page->slinks);
2330 fz_link *link, *links;
2332 ensureannots (page);
2333 if (state.gen != page->sgen) {
2334 dropslinks (page);
2335 page->sgen = state.gen;
2337 if (page->slinks) return;
2339 links = fz_load_links (state.ctx, page->fzpage);
2340 ctm = pagectm (page);
2342 count = page->annotcount;
2343 for (link = links; link; link = link->next) {
2344 count++;
2346 if (count > 0) {
2347 int j;
2349 page->slinkcount = count;
2350 page->slinks = calloc (count, slinksize);
2351 if (!page->slinks) {
2352 err (1, "calloc slinks %d", count);
2355 for (i = 0, link = links; link; ++i, link = link->next) {
2356 fz_rect rect;
2358 rect = link->rect;
2359 fz_transform_rect (&rect, &ctm);
2360 page->slinks[i].tag = SLINK;
2361 page->slinks[i].u.link = link;
2362 fz_round_rect (&page->slinks[i].bbox, &rect);
2364 for (j = 0; j < page->annotcount; ++j, ++i) {
2365 fz_rect rect;
2366 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2367 fz_transform_rect (&rect, &ctm);
2368 fz_round_rect (&page->slinks[i].bbox, &rect);
2370 page->slinks[i].tag = SANNOT;
2371 page->slinks[i].u.annot = page->annots[j].annot;
2373 qsort (page->slinks, count, slinksize, compareslinks);
2377 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2378 static void fmt_linkn (char *s, unsigned int u)
2380 unsigned int len; unsigned int q;
2381 unsigned int zma = 'z' - 'a' + 1;
2382 len = 1; q = u;
2383 while (q > zma - 1) { ++len; q /= zma; }
2384 if (s) {
2385 s += len;
2386 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2387 /* handles u == 0 */
2389 s[len] = 0;
2392 static void highlightslinks (struct page *page, int xoff, int yoff,
2393 int noff, char *targ, int tlen, int hfsize)
2395 int i;
2396 char buf[40];
2397 struct slink *slink;
2398 double x0, y0, x1, y1, w;
2400 ensureslinks (page);
2401 glColor3ub (0xc3, 0xb0, 0x91);
2402 for (i = 0; i < page->slinkcount; ++i) {
2403 fmt_linkn (buf, i + noff);
2404 if (!tlen || !strncmp (targ, buf, tlen)) {
2405 slink = &page->slinks[i];
2407 x0 = slink->bbox.x0 + xoff - 5;
2408 y1 = slink->bbox.y0 + yoff - 5;
2409 y0 = y1 + 10 + hfsize;
2410 w = measure_string (state.face, hfsize, buf);
2411 x1 = x0 + w + 10;
2412 recti (x0, y0, x1, y1);
2416 glEnable (GL_BLEND);
2417 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2418 glEnable (GL_TEXTURE_2D);
2419 glColor3ub (0, 0, 0);
2420 for (i = 0; i < page->slinkcount; ++i) {
2421 fmt_linkn (buf, i + noff);
2422 if (!tlen || !strncmp (targ, buf, tlen)) {
2423 slink = &page->slinks[i];
2425 x0 = slink->bbox.x0 + xoff;
2426 y0 = slink->bbox.y0 + yoff + hfsize;
2427 draw_string (state.face, hfsize, x0, y0, buf);
2430 glDisable (GL_TEXTURE_2D);
2431 glDisable (GL_BLEND);
2434 static void uploadslice (struct tile *tile, struct slice *slice)
2436 int offset;
2437 struct slice *slice1;
2438 unsigned char *texdata;
2440 offset = 0;
2441 for (slice1 = tile->slices; slice != slice1; slice1++) {
2442 offset += slice1->h * tile->w * tile->pixmap->n;
2444 if (slice->texindex != -1 && slice->texindex < state.texcount
2445 && state.texowners[slice->texindex].slice == slice) {
2446 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2448 else {
2449 int subimage = 0;
2450 int texindex = state.texindex++ % state.texcount;
2452 if (state.texowners[texindex].w == tile->w) {
2453 if (state.texowners[texindex].h >= slice->h) {
2454 subimage = 1;
2456 else {
2457 state.texowners[texindex].h = slice->h;
2460 else {
2461 state.texowners[texindex].h = slice->h;
2464 state.texowners[texindex].w = tile->w;
2465 state.texowners[texindex].slice = slice;
2466 slice->texindex = texindex;
2468 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2469 #if TEXT_TYPE == GL_TEXTURE_2D
2470 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2471 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2472 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2473 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2474 #endif
2475 if (tile->pbo) {
2476 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2477 texdata = 0;
2479 else {
2480 texdata = tile->pixmap->samples;
2482 if (subimage) {
2483 glTexSubImage2D (TEXT_TYPE,
2487 tile->w,
2488 slice->h,
2489 state.texform,
2490 state.texty,
2491 texdata+offset
2494 else {
2495 glTexImage2D (TEXT_TYPE,
2497 state.texiform,
2498 tile->w,
2499 slice->h,
2501 state.texform,
2502 state.texty,
2503 texdata+offset
2506 if (tile->pbo) {
2507 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2512 CAMLprim value ml_begintiles (value unit_v)
2514 CAMLparam1 (unit_v);
2515 glEnable (TEXT_TYPE);
2516 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2517 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2518 CAMLreturn (unit_v);
2521 CAMLprim value ml_endtiles (value unit_v)
2523 CAMLparam1 (unit_v);
2524 glDisable (TEXT_TYPE);
2525 CAMLreturn (unit_v);
2528 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2530 CAMLparam2 (args_v, ptr_v);
2531 int dispx = Int_val (Field (args_v, 0));
2532 int dispy = Int_val (Field (args_v, 1));
2533 int dispw = Int_val (Field (args_v, 2));
2534 int disph = Int_val (Field (args_v, 3));
2535 int tilex = Int_val (Field (args_v, 4));
2536 int tiley = Int_val (Field (args_v, 5));
2537 char *s = String_val (ptr_v);
2538 struct tile *tile = parse_pointer (__func__, s);
2539 int slicey, firstslice;
2540 struct slice *slice;
2541 GLfloat *texcoords = state.texcoords;
2542 GLfloat *vertices = state.vertices;
2544 firstslice = tiley / tile->sliceheight;
2545 slice = &tile->slices[firstslice];
2546 slicey = tiley % tile->sliceheight;
2548 while (disph > 0) {
2549 int dh;
2551 dh = slice->h - slicey;
2552 dh = MIN (disph, dh);
2553 uploadslice (tile, slice);
2555 texcoords[0] = tilex; texcoords[1] = slicey;
2556 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2557 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2558 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2560 vertices[0] = dispx; vertices[1] = dispy;
2561 vertices[2] = dispx+dispw; vertices[3] = dispy;
2562 vertices[4] = dispx; vertices[5] = dispy+dh;
2563 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2565 #if TEXT_TYPE == GL_TEXTURE_2D
2566 for (int i = 0; i < 8; ++i) {
2567 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2569 #endif
2571 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2572 dispy += dh;
2573 disph -= dh;
2574 slice++;
2575 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2576 slicey = 0;
2578 CAMLreturn (Val_unit);
2581 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2583 fz_matrix ctm, tm, pm;
2584 fz_point p1, p2, p3, p4;
2585 GLfloat *vertices = state.vertices;
2586 double *v = (double *) rects_v;
2588 xoff -= state.pagedims[page->pdimno].bounds.x0;
2589 yoff -= state.pagedims[page->pdimno].bounds.y0;
2590 fz_translate (&tm, xoff, yoff);
2591 pm = pagectm (page);
2592 fz_concat (&ctm, &pm, &tm);
2594 glEnable (GL_BLEND);
2595 glVertexPointer (2, GL_FLOAT, 0, vertices);
2597 glColor4dv (v);
2598 p1.x = v[4];
2599 p1.y = v[5];
2601 p2.x = v[6];
2602 p2.y = v[5];
2604 p3.x = v[6];
2605 p3.y = v[7];
2607 p4.x = v[4];
2608 p4.y = v[7];
2609 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2610 glDisable (GL_BLEND);
2613 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2614 value xoff_v, value yoff_v,
2615 value li_v)
2617 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2618 int xoff = Int_val (xoff_v);
2619 int yoff = Int_val (yoff_v);
2620 int noff = Int_val (Field (li_v, 0));
2621 char *targ = String_val (Field (li_v, 1));
2622 int tlen = caml_string_length (Field (li_v, 1));
2623 int hfsize = Int_val (Field (li_v, 2));
2624 char *s = String_val (ptr_v);
2625 int hlmask = Int_val (hlinks_v);
2626 struct page *page = parse_pointer (__func__, s);
2628 if (!page->fzpage) {
2629 /* deal with loadpage failed pages */
2630 goto done;
2633 ensureannots (page);
2635 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2636 if (trylock (__func__)) {
2637 noff = 0;
2638 goto done;
2640 if (hlmask & 2) {
2641 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2642 noff = page->slinkcount;
2644 if (page->tgen == state.gen) {
2645 showsel (page, xoff, yoff);
2647 unlock (__func__);
2649 done:
2650 CAMLreturn (Val_int (noff));
2653 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2654 value rects_v)
2656 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2657 int xoff = Int_val (xoff_v);
2658 int yoff = Int_val (yoff_v);
2659 char *s = String_val (ptr_v);
2660 struct page *page = parse_pointer (__func__, s);
2662 drawprect (page, xoff, yoff, rects_v);
2663 CAMLreturn (Val_unit);
2666 static struct annot *getannot (struct page *page, int x, int y)
2668 int i;
2669 fz_point p;
2670 fz_matrix ctm;
2671 const fz_matrix *tctm;
2672 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2674 if (!page->annots) return NULL;
2676 if (pdf) {
2677 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2678 tctm = &state.pagedims[page->pdimno].tctm;
2680 else {
2681 tctm = &fz_identity;
2684 p.x = x;
2685 p.y = y;
2687 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2688 fz_invert_matrix (&ctm, &ctm);
2689 fz_transform_point (&p, &ctm);
2691 if (pdf) {
2692 for (i = 0; i < page->annotcount; ++i) {
2693 struct annot *a = &page->annots[i];
2694 pdf_annot *annot = (pdf_annot *) a->annot;
2695 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2696 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2697 return a;
2702 return NULL;
2705 static fz_link *getlink (struct page *page, int x, int y)
2707 fz_point p;
2708 fz_matrix ctm;
2709 const fz_matrix *tctm;
2710 fz_link *link, *links;
2712 tctm = &fz_identity;
2713 links = fz_load_links (state.ctx, page->fzpage);
2715 p.x = x;
2716 p.y = y;
2718 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2719 fz_invert_matrix (&ctm, &ctm);
2720 fz_transform_point (&p, &ctm);
2722 for (link = links; link; link = link->next) {
2723 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2724 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2725 return link;
2729 return NULL;
2732 static void ensuretext (struct page *page)
2734 if (state.gen != page->tgen) {
2735 droptext (page);
2736 page->tgen = state.gen;
2738 if (!page->text) {
2739 fz_matrix ctm;
2740 fz_device *tdev;
2742 page->text = fz_new_stext_page (state.ctx);
2743 page->sheet = fz_new_stext_sheet (state.ctx);
2744 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2745 ctm = pagectm (page);
2746 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2747 fz_run_display_list (state.ctx, page->dlist,
2748 tdev, &ctm, &fz_infinite_rect, NULL);
2749 qsort (page->text->blocks, page->text->len,
2750 sizeof (*page->text->blocks), compareblocks);
2751 fz_end_page (state.ctx, tdev);
2752 fz_drop_device (state.ctx, tdev);
2756 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2758 CAMLparam2 (start_page_v, dir_v);
2759 CAMLlocal1 (ret_v);
2760 int i, dir = Int_val (dir_v);
2761 int start_page = Int_val (start_page_v);
2762 int end_page = dir > 0 ? state.pagecount : -1;
2763 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2765 fz_var (end_page);
2766 ret_v = Val_int (0);
2767 lock (__func__);
2768 for (i = start_page + dir; i != end_page; i += dir) {
2769 int found;
2771 fz_var (found);
2772 if (pdf) {
2773 pdf_page *page = NULL;
2775 fz_try (state.ctx) {
2776 page = pdf_load_page (state.ctx, pdf, i);
2777 found = !!page->links || !!page->annots;
2779 fz_catch (state.ctx) {
2780 found = 0;
2782 if (page) {
2783 fz_drop_page (state.ctx, &page->super);
2786 else {
2787 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2788 found = !!fz_load_links (state.ctx, page);
2789 fz_drop_page (state.ctx, page);
2792 if (found) {
2793 ret_v = caml_alloc_small (1, 1);
2794 Field (ret_v, 0) = Val_int (i);
2795 goto unlock;
2798 unlock:
2799 unlock (__func__);
2800 CAMLreturn (ret_v);
2803 enum { dir_first, dir_last };
2804 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2806 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2808 CAMLparam2 (ptr_v, dir_v);
2809 CAMLlocal2 (ret_v, pos_v);
2810 struct page *page;
2811 int dirtag, i, slinkindex;
2812 struct slink *found = NULL ,*slink;
2813 char *s = String_val (ptr_v);
2815 page = parse_pointer (__func__, s);
2816 ret_v = Val_int (0);
2817 /* This is scary we are not taking locks here ensureslinks does
2818 not modify state and given that we obtained the page it can not
2819 disappear under us either */
2820 lock (__func__);
2821 ensureslinks (page);
2823 if (Is_block (dir_v)) {
2824 dirtag = Tag_val (dir_v);
2825 switch (dirtag) {
2826 case dir_first_visible:
2828 int x0, y0, dir, first_index, last_index;
2830 pos_v = Field (dir_v, 0);
2831 x0 = Int_val (Field (pos_v, 0));
2832 y0 = Int_val (Field (pos_v, 1));
2833 dir = Int_val (Field (pos_v, 2));
2835 if (dir >= 0) {
2836 dir = 1;
2837 first_index = 0;
2838 last_index = page->slinkcount;
2840 else {
2841 first_index = page->slinkcount - 1;
2842 last_index = -1;
2845 for (i = first_index; i != last_index; i += dir) {
2846 slink = &page->slinks[i];
2847 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2848 found = slink;
2849 break;
2853 break;
2855 case dir_left:
2856 slinkindex = Int_val (Field (dir_v, 0));
2857 found = &page->slinks[slinkindex];
2858 for (i = slinkindex - 1; i >= 0; --i) {
2859 slink = &page->slinks[i];
2860 if (slink->bbox.x0 < found->bbox.x0) {
2861 found = slink;
2862 break;
2865 break;
2867 case dir_right:
2868 slinkindex = Int_val (Field (dir_v, 0));
2869 found = &page->slinks[slinkindex];
2870 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2871 slink = &page->slinks[i];
2872 if (slink->bbox.x0 > found->bbox.x0) {
2873 found = slink;
2874 break;
2877 break;
2879 case dir_down:
2880 slinkindex = Int_val (Field (dir_v, 0));
2881 found = &page->slinks[slinkindex];
2882 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2883 slink = &page->slinks[i];
2884 if (slink->bbox.y0 >= found->bbox.y0) {
2885 found = slink;
2886 break;
2889 break;
2891 case dir_up:
2892 slinkindex = Int_val (Field (dir_v, 0));
2893 found = &page->slinks[slinkindex];
2894 for (i = slinkindex - 1; i >= 0; --i) {
2895 slink = &page->slinks[i];
2896 if (slink->bbox.y0 <= found->bbox.y0) {
2897 found = slink;
2898 break;
2901 break;
2904 else {
2905 dirtag = Int_val (dir_v);
2906 switch (dirtag) {
2907 case dir_first:
2908 found = page->slinks;
2909 break;
2911 case dir_last:
2912 if (page->slinks) {
2913 found = page->slinks + (page->slinkcount - 1);
2915 break;
2918 if (found) {
2919 ret_v = caml_alloc_small (2, 1);
2920 Field (ret_v, 0) = Val_int (found - page->slinks);
2923 unlock (__func__);
2924 CAMLreturn (ret_v);
2927 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2928 unamed, uremote, uremotedest, uannot };
2930 #define LINKTOVAL \
2932 int pageno; \
2934 switch (link->dest.kind) { \
2935 case FZ_LINK_GOTO: \
2937 fz_point p; \
2939 pageno = link->dest.ld.gotor.page; \
2940 p.x = 0; \
2941 p.y = 0; \
2943 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2944 p.y = link->dest.ld.gotor.lt.y; \
2945 fz_transform_point (&p, &pdim->lctm); \
2946 if (p.y < 0) p.y = 0; \
2948 tup_v = caml_alloc_tuple (2); \
2949 ret_v = caml_alloc_small (1, ugoto); \
2950 Field (tup_v, 0) = Val_int (pageno); \
2951 Field (tup_v, 1) = Val_int (p.y); \
2952 Field (ret_v, 0) = tup_v; \
2954 break; \
2956 case FZ_LINK_URI: \
2957 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2958 ret_v = caml_alloc_small (1, uuri); \
2959 Field (ret_v, 0) = str_v; \
2960 break; \
2962 case FZ_LINK_LAUNCH: \
2963 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2964 ret_v = caml_alloc_small (1, ulaunch); \
2965 Field (ret_v, 0) = str_v; \
2966 break; \
2968 case FZ_LINK_NAMED: \
2969 str_v = caml_copy_string (link->dest.ld.named.named); \
2970 ret_v = caml_alloc_small (1, unamed); \
2971 Field (ret_v, 0) = str_v; \
2972 break; \
2974 case FZ_LINK_GOTOR: \
2976 int rty; \
2978 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2979 pageno = link->dest.ld.gotor.page; \
2980 if (pageno == -1) { \
2981 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2982 rty = uremotedest; \
2984 else { \
2985 gr_v = Val_int (pageno); \
2986 rty = uremote; \
2988 tup_v = caml_alloc_tuple (2); \
2989 ret_v = caml_alloc_small (1, rty); \
2990 Field (tup_v, 0) = str_v; \
2991 Field (tup_v, 1) = gr_v; \
2992 Field (ret_v, 0) = tup_v; \
2994 break; \
2996 default: \
2998 char buf[80]; \
3000 snprintf (buf, sizeof (buf), \
3001 "unhandled link kind %d", link->dest.kind); \
3002 str_v = caml_copy_string (buf); \
3003 ret_v = caml_alloc_small (1, uunexpected); \
3004 Field (ret_v, 0) = str_v; \
3006 break; \
3010 CAMLprim value ml_getlink (value ptr_v, value n_v)
3012 CAMLparam2 (ptr_v, n_v);
3013 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3014 fz_link *link;
3015 struct page *page;
3016 struct pagedim *pdim;
3017 char *s = String_val (ptr_v);
3018 struct slink *slink;
3020 /* See ml_findlink for caveat */
3022 ret_v = Val_int (0);
3023 page = parse_pointer (__func__, s);
3024 ensureslinks (page);
3025 pdim = &state.pagedims[page->pdimno];
3026 slink = &page->slinks[Int_val (n_v)];
3027 if (slink->tag == SLINK) {
3028 link = slink->u.link;
3029 LINKTOVAL;
3031 else {
3032 ret_v = caml_alloc_small (1, uannot);
3033 tup_v = caml_alloc_tuple (2);
3034 Field (ret_v, 0) = tup_v;
3035 Field (tup_v, 0) = ptr_v;
3036 Field (tup_v, 1) = n_v;
3039 CAMLreturn (ret_v);
3042 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3044 CAMLparam2 (ptr_v, n_v);
3045 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3046 if (pdf) {
3047 char *s = String_val (ptr_v);
3048 struct page *page;
3049 struct slink *slink;
3051 page = parse_pointer (__func__, s);
3052 slink = &page->slinks[Int_val (n_v)];
3053 CAMLreturn (caml_copy_string (
3054 pdf_annot_contents (state.ctx, pdf,
3055 (pdf_annot *) slink->u.annot)));
3057 else {
3058 CAMLreturn (caml_copy_string (""));
3062 CAMLprim value ml_getlinkcount (value ptr_v)
3064 CAMLparam1 (ptr_v);
3065 struct page *page;
3066 char *s = String_val (ptr_v);
3068 page = parse_pointer (__func__, s);
3069 CAMLreturn (Val_int (page->slinkcount));
3072 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3074 CAMLparam2 (ptr_v, n_v);
3075 CAMLlocal1 (ret_v);
3076 struct page *page;
3077 struct slink *slink;
3078 char *s = String_val (ptr_v);
3079 /* See ml_findlink for caveat */
3081 page = parse_pointer (__func__, s);
3082 ret_v = caml_alloc_tuple (4);
3083 ensureslinks (page);
3085 slink = &page->slinks[Int_val (n_v)];
3086 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3087 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3088 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3089 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3090 unlock (__func__);
3091 CAMLreturn (ret_v);
3094 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3096 CAMLparam3 (ptr_v, x_v, y_v);
3097 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3098 fz_link *link;
3099 struct annot *annot;
3100 struct page *page;
3101 char *ptr = String_val (ptr_v);
3102 int x = Int_val (x_v), y = Int_val (y_v);
3103 struct pagedim *pdim;
3105 ret_v = Val_int (0);
3106 if (trylock (__func__)) {
3107 goto done;
3110 page = parse_pointer (__func__, ptr);
3111 pdim = &state.pagedims[page->pdimno];
3112 x += pdim->bounds.x0;
3113 y += pdim->bounds.y0;
3116 annot = getannot (page, x, y);
3117 if (annot) {
3118 int i, n = -1;
3120 ensureslinks (page);
3121 for (i = 0; i < page->slinkcount; ++i) {
3122 if (page->slinks[i].tag == SANNOT
3123 && page->slinks[i].u.annot == annot->annot) {
3124 n = i;
3125 break;
3128 ret_v = caml_alloc_small (1, uannot);
3129 tup_v = caml_alloc_tuple (2);
3130 Field (ret_v, 0) = tup_v;
3131 Field (tup_v, 0) = ptr_v;
3132 Field (tup_v, 1) = Val_int (n);
3133 goto unlock;
3137 link = getlink (page, x, y);
3138 if (link) {
3139 LINKTOVAL;
3141 else {
3142 fz_rect *b;
3143 fz_page_block *pageb;
3144 fz_stext_block *block;
3146 ensuretext (page);
3147 for (pageb = page->text->blocks;
3148 pageb < page->text->blocks + page->text->len;
3149 ++pageb) {
3150 fz_stext_line *line;
3151 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3152 block = pageb->u.text;
3154 b = &block->bbox;
3155 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3156 continue;
3158 for (line = block->lines;
3159 line < block->lines + block->len;
3160 ++line) {
3161 fz_stext_span *span;
3163 b = &line->bbox;
3164 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3165 continue;
3167 for (span = line->first_span; span; span = span->next) {
3168 int charnum;
3170 b = &span->bbox;
3171 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3172 continue;
3174 for (charnum = 0; charnum < span->len; ++charnum) {
3175 fz_rect bbox;
3176 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3177 b = &bbox;
3179 if (x >= b->x0 && x <= b->x1
3180 && y >= b->y0 && y <= b->y1) {
3181 fz_stext_style *style = span->text->style;
3182 const char *n2 =
3183 style->font
3184 ? style->font->name
3185 : "Span has no font name"
3187 FT_FaceRec *face = style->font->ft_face;
3188 if (face && face->family_name) {
3189 char *s;
3190 char *n1 = face->family_name;
3191 size_t l1 = strlen (n1);
3192 size_t l2 = strlen (n2);
3194 if (l1 != l2 || memcmp (n1, n2, l1)) {
3195 s = malloc (l1 + l2 + 2);
3196 if (s) {
3197 memcpy (s, n2, l2);
3198 s[l2] = '=';
3199 memcpy (s + l2 + 1, n1, l1 + 1);
3200 str_v = caml_copy_string (s);
3201 free (s);
3205 if (str_v == Val_unit) {
3206 str_v = caml_copy_string (n2);
3208 ret_v = caml_alloc_small (1, utext);
3209 Field (ret_v, 0) = str_v;
3210 goto unlock;
3217 unlock:
3218 unlock (__func__);
3220 done:
3221 CAMLreturn (ret_v);
3224 enum { mark_page, mark_block, mark_line, mark_word };
3226 static int uninteresting (int c)
3228 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3229 || ispunct (c);
3232 CAMLprim value ml_clearmark (value ptr_v)
3234 CAMLparam1 (ptr_v);
3235 char *s = String_val (ptr_v);
3236 struct page *page;
3238 if (trylock (__func__)) {
3239 goto done;
3242 page = parse_pointer (__func__, s);
3243 page->fmark.span = NULL;
3244 page->lmark.span = NULL;
3245 page->fmark.i = 0;
3246 page->lmark.i = 0;
3248 unlock (__func__);
3249 done:
3250 CAMLreturn (Val_unit);
3253 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3255 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3256 CAMLlocal1 (ret_v);
3257 fz_rect *b;
3258 struct page *page;
3259 fz_stext_line *line;
3260 fz_page_block *pageb;
3261 fz_stext_block *block;
3262 struct pagedim *pdim;
3263 int mark = Int_val (mark_v);
3264 char *s = String_val (ptr_v);
3265 int x = Int_val (x_v), y = Int_val (y_v);
3267 ret_v = Val_bool (0);
3268 if (trylock (__func__)) {
3269 goto done;
3272 page = parse_pointer (__func__, s);
3273 pdim = &state.pagedims[page->pdimno];
3275 ensuretext (page);
3277 if (mark == mark_page) {
3278 int i;
3279 fz_page_block *pb1 = NULL, *pb2 = NULL;
3281 for (i = 0; i < page->text->len; ++i) {
3282 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3283 pb1 = &page->text->blocks[i];
3284 break;
3287 if (!pb1) goto unlock;
3289 for (i = page->text->len - 1; i >= 0; --i) {
3290 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3291 pb2 = &page->text->blocks[i];
3292 break;
3295 if (!pb2) goto unlock;
3297 block = pb1->u.text;
3299 page->fmark.i = 0;
3300 page->fmark.span = block->lines->first_span;
3302 block = pb2->u.text;
3303 line = &block->lines[block->len - 1];
3304 page->lmark.i = line->last_span->len - 1;
3305 page->lmark.span = line->last_span;
3306 ret_v = Val_bool (1);
3307 goto unlock;
3310 x += pdim->bounds.x0;
3311 y += pdim->bounds.y0;
3313 for (pageb = page->text->blocks;
3314 pageb < page->text->blocks + page->text->len;
3315 ++pageb) {
3316 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3317 block = pageb->u.text;
3319 b = &block->bbox;
3320 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3321 continue;
3323 if (mark == mark_block) {
3324 page->fmark.i = 0;
3325 page->fmark.span = block->lines->first_span;
3327 line = &block->lines[block->len - 1];
3328 page->lmark.i = line->last_span->len - 1;
3329 page->lmark.span = line->last_span;
3330 ret_v = Val_bool (1);
3331 goto unlock;
3334 for (line = block->lines;
3335 line < block->lines + block->len;
3336 ++line) {
3337 fz_stext_span *span;
3339 b = &line->bbox;
3340 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3341 continue;
3343 if (mark == mark_line) {
3344 page->fmark.i = 0;
3345 page->fmark.span = line->first_span;
3347 page->lmark.i = line->last_span->len - 1;
3348 page->lmark.span = line->last_span;
3349 ret_v = Val_bool (1);
3350 goto unlock;
3353 for (span = line->first_span; span; span = span->next) {
3354 int charnum;
3356 b = &span->bbox;
3357 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3358 continue;
3360 for (charnum = 0; charnum < span->len; ++charnum) {
3361 fz_rect bbox;
3362 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3363 b = &bbox;
3365 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3366 /* unicode ftw */
3367 int charnum2, charnum3 = -1, charnum4 = -1;
3369 if (uninteresting (span->text[charnum].c)) goto unlock;
3371 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3372 if (uninteresting (span->text[charnum2].c)) {
3373 charnum3 = charnum2 + 1;
3374 break;
3377 if (charnum3 == -1) charnum3 = 0;
3379 for (charnum2 = charnum + 1;
3380 charnum2 < span->len;
3381 ++charnum2) {
3382 if (uninteresting (span->text[charnum2].c)) break;
3383 charnum4 = charnum2;
3385 if (charnum4 == -1) goto unlock;
3387 page->fmark.i = charnum3;
3388 page->fmark.span = span;
3390 page->lmark.i = charnum4;
3391 page->lmark.span = span;
3392 ret_v = Val_bool (1);
3393 goto unlock;
3399 unlock:
3400 if (!Bool_val (ret_v)) {
3401 page->fmark.span = NULL;
3402 page->lmark.span = NULL;
3403 page->fmark.i = 0;
3404 page->lmark.i = 0;
3406 unlock (__func__);
3408 done:
3409 CAMLreturn (ret_v);
3412 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3414 CAMLparam3 (ptr_v, x_v, y_v);
3415 CAMLlocal2 (ret_v, res_v);
3416 fz_rect *b = NULL;
3417 struct page *page;
3418 fz_page_block *pageb;
3419 struct pagedim *pdim;
3420 char *s = String_val (ptr_v);
3421 int x = Int_val (x_v), y = Int_val (y_v);
3423 ret_v = Val_int (0);
3424 if (trylock (__func__)) {
3425 goto done;
3428 page = parse_pointer (__func__, s);
3429 pdim = &state.pagedims[page->pdimno];
3430 x += pdim->bounds.x0;
3431 y += pdim->bounds.y0;
3433 ensuretext (page);
3435 for (pageb = page->text->blocks;
3436 pageb < page->text->blocks + page->text->len;
3437 ++pageb) {
3438 switch (pageb->type) {
3439 case FZ_PAGE_BLOCK_TEXT:
3440 b = &pageb->u.text->bbox;
3441 break;
3443 case FZ_PAGE_BLOCK_IMAGE:
3444 b = &pageb->u.image->bbox;
3445 break;
3447 default:
3448 continue;
3451 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3452 break;
3453 b = NULL;
3455 if (b) {
3456 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3457 ret_v = caml_alloc_small (1, 1);
3458 Store_double_field (res_v, 0, b->x0);
3459 Store_double_field (res_v, 1, b->x1);
3460 Store_double_field (res_v, 2, b->y0);
3461 Store_double_field (res_v, 3, b->y1);
3462 Field (ret_v, 0) = res_v;
3464 unlock (__func__);
3466 done:
3467 CAMLreturn (ret_v);
3470 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3472 CAMLparam2 (ptr_v, rect_v);
3473 fz_rect b;
3474 struct page *page;
3475 struct pagedim *pdim;
3476 char *s = String_val (ptr_v);
3477 int i, x0, x1, y0, y1, fi, li;
3478 fz_stext_line *line;
3479 fz_page_block *pageb;
3480 fz_stext_block *block;
3481 fz_stext_span *span, *fspan, *lspan;
3483 if (trylock (__func__)) {
3484 goto done;
3487 page = parse_pointer (__func__, s);
3488 ensuretext (page);
3490 pdim = &state.pagedims[page->pdimno];
3491 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3492 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3493 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3494 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3496 if (y0 > y1) {
3497 int t = y0;
3498 y0 = y1;
3499 y1 = t;
3500 x0 = x1;
3501 x1 = t;
3504 fi = page->fmark.i;
3505 fspan = page->fmark.span;
3507 li = page->lmark.i;
3508 lspan = page->lmark.span;
3510 for (pageb = page->text->blocks;
3511 pageb < page->text->blocks + page->text->len;
3512 ++pageb) {
3513 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3514 block = pageb->u.text;
3515 for (line = block->lines;
3516 line < block->lines + block->len;
3517 ++line) {
3519 for (span = line->first_span; span; span = span->next) {
3520 for (i = 0; i < span->len; ++i) {
3521 fz_stext_char_bbox (state.ctx, &b, span, i);
3523 if (x0 >= b.x0 && x0 <= b.x1
3524 && y0 >= b.y0 && y0 <= b.y1) {
3525 fspan = span;
3526 fi = i;
3528 if (x1 >= b.x0 && x1 <= b.x1
3529 && y1 >= b.y0 && y1 <= b.y1) {
3530 lspan = span;
3531 li = i;
3537 if (x1 < x0 && fspan == lspan) {
3538 i = fi;
3539 span = fspan;
3541 fi = li;
3542 fspan = lspan;
3544 li = i;
3545 lspan = span;
3548 page->fmark.i = fi;
3549 page->fmark.span = fspan;
3551 page->lmark.i = li;
3552 page->lmark.span = lspan;
3554 unlock (__func__);
3556 done:
3557 CAMLreturn (Val_unit);
3560 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3562 char buf[4];
3563 int i, len, ret;
3565 for (i = a; i <= b; ++i) {
3566 len = fz_runetochar (buf, span->text[i].c);
3567 ret = fwrite (buf, len, 1, f);
3569 if (ret != 1) {
3570 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3571 len, ret, strerror (errno));
3572 return -1;
3575 return 0;
3578 #ifdef __CYGWIN__
3579 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3581 caml_failwith ("ml_popen not implemented under Cygwin");
3583 #else
3584 CAMLprim value ml_spawn (value command_v, value fds_v)
3586 CAMLparam2 (command_v, fds_v);
3587 CAMLlocal2 (l_v, tup_v);
3588 int ret, ret1;
3589 pid_t pid;
3590 char *msg = NULL;
3591 value earg_v = Nothing;
3592 posix_spawnattr_t attr;
3593 posix_spawn_file_actions_t fa;
3594 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3596 argv[2] = String_val (command_v);
3598 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3599 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3602 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3603 msg = "posix_spawnattr_init";
3604 goto fail1;
3607 #ifdef POSIX_SPAWN_USEVFORK
3608 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3609 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3610 goto fail;
3612 #endif
3614 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3615 int fd1, fd2;
3617 tup_v = Field (l_v, 0);
3618 fd1 = Int_val (Field (tup_v, 0));
3619 fd2 = Int_val (Field (tup_v, 1));
3620 if (fd2 < 0) {
3621 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3622 msg = "posix_spawn_file_actions_addclose";
3623 earg_v = tup_v;
3624 goto fail;
3627 else {
3628 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3629 msg = "posix_spawn_file_actions_adddup2";
3630 earg_v = tup_v;
3631 goto fail;
3636 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3637 msg = "posix_spawn";
3638 goto fail;
3641 fail:
3642 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3643 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3646 fail1:
3647 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3648 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3649 strerror (ret1));
3652 if (msg)
3653 unix_error (ret, msg, earg_v);
3655 CAMLreturn (Val_int (pid));
3657 #endif
3659 CAMLprim value ml_hassel (value ptr_v)
3661 CAMLparam1 (ptr_v);
3662 CAMLlocal1 (ret_v);
3663 struct page *page;
3664 char *s = String_val (ptr_v);
3666 ret_v = Val_bool (0);
3667 if (trylock (__func__)) {
3668 goto done;
3671 page = parse_pointer (__func__, s);
3672 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3673 unlock (__func__);
3674 done:
3675 CAMLreturn (ret_v);
3678 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3680 CAMLparam2 (fd_v, ptr_v);
3681 FILE *f;
3682 int seen = 0;
3683 struct page *page;
3684 fz_stext_line *line;
3685 fz_page_block *pageb;
3686 fz_stext_block *block;
3687 int fd = Int_val (fd_v);
3688 char *s = String_val (ptr_v);
3690 if (trylock (__func__)) {
3691 goto done;
3694 page = parse_pointer (__func__, s);
3696 if (!page->fmark.span || !page->lmark.span) {
3697 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3698 goto unlock;
3701 f = fdopen (fd, "w");
3702 if (!f) {
3703 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3704 fd, strerror (errno));
3705 f = stdout;
3708 for (pageb = page->text->blocks;
3709 pageb < page->text->blocks + page->text->len;
3710 ++pageb) {
3711 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3712 block = pageb->u.text;
3713 for (line = block->lines;
3714 line < block->lines + block->len;
3715 ++line) {
3716 fz_stext_span *span;
3718 for (span = line->first_span; span; span = span->next) {
3719 int a, b;
3721 seen |= span == page->fmark.span || span == page->lmark.span;
3722 a = span == page->fmark.span ? page->fmark.i : 0;
3723 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3725 if (seen) {
3726 if (pipespan (f, span, a, b)) {
3727 goto close;
3729 if (span == page->lmark.span) {
3730 goto close;
3732 if (span == line->last_span) {
3733 if (putc ('\n', f) == EOF) {
3734 fprintf (stderr,
3735 "failed break line on sel pipe: %s\n",
3736 strerror (errno));
3737 goto close;
3744 close:
3745 if (f != stdout) {
3746 int ret = fclose (f);
3747 fd = -1;
3748 if (ret == -1) {
3749 if (errno != ECHILD) {
3750 fprintf (stderr, "failed to close sel pipe: %s\n",
3751 strerror (errno));
3755 unlock:
3756 unlock (__func__);
3758 done:
3759 if (fd >= 0) {
3760 if (close (fd)) {
3761 fprintf (stderr, "failed to close sel pipe: %s\n",
3762 strerror (errno));
3765 CAMLreturn (Val_unit);
3768 CAMLprim value ml_getpdimrect (value pagedimno_v)
3770 CAMLparam1 (pagedimno_v);
3771 CAMLlocal1 (ret_v);
3772 int pagedimno = Int_val (pagedimno_v);
3773 fz_rect box;
3775 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3776 if (trylock (__func__)) {
3777 box = fz_empty_rect;
3779 else {
3780 box = state.pagedims[pagedimno].mediabox;
3781 unlock (__func__);
3784 Store_double_field (ret_v, 0, box.x0);
3785 Store_double_field (ret_v, 1, box.x1);
3786 Store_double_field (ret_v, 2, box.y0);
3787 Store_double_field (ret_v, 3, box.y1);
3789 CAMLreturn (ret_v);
3792 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3793 value dw_v, value cols_v)
3795 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3796 CAMLlocal1 (ret_v);
3797 int i;
3798 double zoom = -1.;
3799 double maxh = 0.0;
3800 struct pagedim *p;
3801 double winw = Int_val (winw_v);
3802 double winh = Int_val (winh_v);
3803 double dw = Int_val (dw_v);
3804 double cols = Int_val (cols_v);
3805 double pw = 1.0, ph = 1.0;
3807 if (trylock (__func__)) {
3808 goto done;
3811 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3812 double w = p->pagebox.x1 / cols;
3813 double h = p->pagebox.y1;
3814 if (h > maxh) {
3815 maxh = h;
3816 ph = h;
3817 if (state.fitmodel != FitProportional) pw = w;
3819 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3822 zoom = (((winh / ph) * pw) + dw) / winw;
3823 unlock (__func__);
3824 done:
3825 ret_v = caml_copy_double (zoom);
3826 CAMLreturn (ret_v);
3829 CAMLprim value ml_getmaxw (value unit_v)
3831 CAMLparam1 (unit_v);
3832 CAMLlocal1 (ret_v);
3833 int i;
3834 double maxw = -1.;
3835 struct pagedim *p;
3837 if (trylock (__func__)) {
3838 goto done;
3841 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3842 double w = p->pagebox.x1;
3843 maxw = MAX (maxw, w);
3846 unlock (__func__);
3847 done:
3848 ret_v = caml_copy_double (maxw);
3849 CAMLreturn (ret_v);
3852 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3854 CAMLparam4 (pt_v, x_v, y_v, string_v);
3855 CAMLlocal1 (ret_v);
3856 int pt = Int_val(pt_v);
3857 int x = Int_val (x_v);
3858 int y = Int_val (y_v);
3859 double w;
3861 w = draw_string (state.face, pt, x, y, String_val (string_v));
3862 ret_v = caml_copy_double (w);
3863 CAMLreturn (ret_v);
3866 CAMLprim value ml_measure_string (value pt_v, value string_v)
3868 CAMLparam2 (pt_v, string_v);
3869 CAMLlocal1 (ret_v);
3870 int pt = Int_val (pt_v);
3871 double w;
3873 w = measure_string (state.face, pt, String_val (string_v));
3874 ret_v = caml_copy_double (w);
3875 CAMLreturn (ret_v);
3878 CAMLprim value ml_getpagebox (value opaque_v)
3880 CAMLparam1 (opaque_v);
3881 CAMLlocal1 (ret_v);
3882 fz_rect rect;
3883 fz_irect bbox;
3884 fz_matrix ctm;
3885 fz_device *dev;
3886 char *s = String_val (opaque_v);
3887 struct page *page = parse_pointer (__func__, s);
3889 ret_v = caml_alloc_tuple (4);
3890 dev = fz_new_bbox_device (state.ctx, &rect);
3891 dev->hints |= FZ_IGNORE_SHADE;
3893 ctm = pagectm (page);
3894 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3896 fz_drop_device (state.ctx, dev);
3897 fz_round_rect (&bbox, &rect);
3898 Field (ret_v, 0) = Val_int (bbox.x0);
3899 Field (ret_v, 1) = Val_int (bbox.y0);
3900 Field (ret_v, 2) = Val_int (bbox.x1);
3901 Field (ret_v, 3) = Val_int (bbox.y1);
3903 CAMLreturn (ret_v);
3906 CAMLprim value ml_setaalevel (value level_v)
3908 CAMLparam1 (level_v);
3910 state.aalevel = Int_val (level_v);
3911 CAMLreturn (Val_unit);
3914 #pragma GCC diagnostic push
3915 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3916 #include <X11/Xlib.h>
3917 #include <X11/cursorfont.h>
3918 #pragma GCC diagnostic pop
3920 #ifdef USE_EGL
3921 #include <EGL/egl.h>
3922 #else
3923 #include <GL/glx.h>
3924 #endif
3926 static const int shapes[] = {
3927 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3930 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3932 static struct {
3933 Window wid;
3934 Display *dpy;
3935 #ifdef USE_EGL
3936 EGLContext ctx;
3937 EGLConfig conf;
3938 EGLSurface win;
3939 EGLDisplay *edpy;
3940 #else
3941 GLXContext ctx;
3942 #endif
3943 XVisualInfo *visual;
3944 Cursor curs[CURS_COUNT];
3945 } glx;
3947 #ifdef VISAVIS
3948 static VisualID initvisual (void)
3950 /* On this system with: `Haswell-ULT Integrated Graphics
3951 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3952 using glX chosen visual and auto scrolling some document in
3953 fullscreen the power/energy-gpu is more than 1 joule bigger
3954 than when using hand picked visual that stands alone in glxinfo
3955 output: it's dead last in the list and it's the only one with
3956 `visual dep' (sic) of 32
3958 No clue what's going on here...
3960 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3962 XVisualInfo info;
3963 int ret = 1;
3965 info.depth = 32;
3966 info.class = TrueColor;
3967 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3968 &info, &ret);
3969 if (!ret || !glx.visual) {
3970 XCloseDisplay (glx.dpy);
3971 caml_failwith ("XGetVisualInfo");
3973 return glx.visual->visualid;
3975 #endif
3977 static void initcurs (void)
3979 for (size_t n = 0; n < CURS_COUNT; ++n) {
3980 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3984 CAMLprim void ml_setbgcol (value color_v)
3986 CAMLparam1 (color_v);
3987 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3988 CAMLreturn0;
3991 #ifdef USE_EGL
3992 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3994 CAMLparam3 (display_v, wid_v, screen_v);
3995 int major, minor;
3996 int num_conf;
3997 EGLint visid;
3998 EGLint attribs[] = {
3999 #ifdef VISAVIS
4000 EGL_NATIVE_VISUAL_ID, 0,
4001 #else
4002 EGL_DEPTH_SIZE, 24,
4003 #endif
4004 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
4005 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
4006 EGL_NONE
4008 EGLConfig conf;
4010 glx.dpy = XOpenDisplay (String_val (display_v));
4011 if (!glx.dpy) {
4012 caml_failwith ("XOpenDisplay");
4015 eglBindAPI (EGL_OPENGL_API);
4017 glx.edpy = eglGetDisplay (glx.dpy);
4018 if (glx.dpy == EGL_NO_DISPLAY) {
4019 caml_failwith ("eglGetDisplay");
4022 if (!eglInitialize (glx.edpy, &major, &minor)) {
4023 caml_failwith ("eglInitialize");
4026 #ifdef VISAVIS
4027 attribs[1] = visid = initvisual ();
4028 #endif
4030 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4031 !num_conf) {
4032 caml_failwith ("eglChooseConfig");
4035 glx.conf = conf;
4036 #ifndef VISAVIS
4037 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4038 EGL_NATIVE_VISUAL_ID, &visid)) {
4039 caml_failwith ("eglGetConfigAttrib");
4041 #endif
4042 initcurs ();
4044 glx.wid = Int_val (wid_v);
4045 CAMLreturn (Val_int (visid));
4048 CAMLprim value ml_glxcompleteinit (value unit_v)
4050 CAMLparam1 (unit_v);
4052 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4053 if (!glx.ctx) {
4054 caml_failwith ("eglCreateContext");
4057 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4058 glx.wid, NULL);
4059 if (glx.win == EGL_NO_SURFACE) {
4060 caml_failwith ("eglCreateWindowSurface");
4063 XFree (glx.visual);
4064 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4065 glx.ctx = NULL;
4066 caml_failwith ("eglMakeCurrent");
4068 CAMLreturn (Val_unit);
4070 #else
4071 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4073 CAMLparam3 (display_v, wid_v, screen_v);
4075 glx.dpy = XOpenDisplay (String_val (display_v));
4076 if (!glx.dpy) {
4077 caml_failwith ("XOpenDisplay");
4080 #ifdef VISAVIS
4081 initvisual ();
4082 #else
4083 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4084 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4085 if (!glx.visual) {
4086 XCloseDisplay (glx.dpy);
4087 caml_failwith ("glXChooseVisual");
4089 #endif
4090 initcurs ();
4092 glx.wid = Int_val (wid_v);
4093 CAMLreturn (Val_int (glx.visual->visualid));
4096 CAMLprim value ml_glxcompleteinit (value unit_v)
4098 CAMLparam1 (unit_v);
4100 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4101 if (!glx.ctx) {
4102 caml_failwith ("glXCreateContext");
4105 XFree (glx.visual);
4106 glx.visual = NULL;
4108 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4109 glXDestroyContext (glx.dpy, glx.ctx);
4110 glx.ctx = NULL;
4111 caml_failwith ("glXMakeCurrent");
4113 CAMLreturn (Val_unit);
4115 #endif
4117 CAMLprim value ml_setcursor (value cursor_v)
4119 CAMLparam1 (cursor_v);
4120 size_t cursn = Int_val (cursor_v);
4122 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4123 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4124 XFlush (glx.dpy);
4125 CAMLreturn (Val_unit);
4128 CAMLprim value ml_swapb (value unit_v)
4130 CAMLparam1 (unit_v);
4131 #ifdef USE_EGL
4132 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4133 caml_failwith ("eglSwapBuffers");
4135 #else
4136 glXSwapBuffers (glx.dpy, glx.wid);
4137 #endif
4138 CAMLreturn (Val_unit);
4141 #include "keysym2ucs.c"
4143 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4145 CAMLparam1 (keysym_v);
4146 CAMLlocal1 (str_v);
4147 KeySym keysym = Int_val (keysym_v);
4148 Rune rune;
4149 int len;
4150 char buf[5];
4152 rune = keysym2ucs (keysym);
4153 len = fz_runetochar (buf, rune);
4154 buf[len] = 0;
4155 str_v = caml_copy_string (buf);
4156 CAMLreturn (str_v);
4159 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4161 CAMLprim value ml_platform (value unit_v)
4163 CAMLparam1 (unit_v);
4164 CAMLlocal2 (tup_v, arr_v);
4165 int platid = piunknown;
4166 struct utsname buf;
4168 #if defined __linux__
4169 platid = pilinux;
4170 #elif defined __CYGWIN__
4171 platid = picygwin;
4172 #elif defined __DragonFly__ || defined __FreeBSD__
4173 || defined __OpenBSD__ || defined __NetBSD__
4174 platid = pibsd;
4175 #elif defined __sun__
4176 platid = pisun;
4177 #elif defined __APPLE__
4178 platid = piosx;
4179 #endif
4180 if (uname (&buf)) err (1, "uname");
4182 tup_v = caml_alloc_tuple (2);
4184 char const *sar[] = {
4185 buf.sysname,
4186 buf.release,
4187 buf.version,
4188 buf.machine,
4189 NULL
4191 arr_v = caml_copy_string_array (sar);
4193 Field (tup_v, 0) = Val_int (platid);
4194 Field (tup_v, 1) = arr_v;
4195 CAMLreturn (tup_v);
4198 CAMLprim value ml_cloexec (value fd_v)
4200 CAMLparam1 (fd_v);
4201 int fd = Int_val (fd_v);
4203 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4204 uerror ("fcntl", Nothing);
4206 CAMLreturn (Val_unit);
4209 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4211 CAMLparam2 (w_v, h_v);
4212 CAMLlocal1 (ret_v);
4213 struct bo *pbo;
4214 int w = Int_val (w_v);
4215 int h = Int_val (h_v);
4216 int cs = Int_val (cs_v);
4218 if (state.bo_usable) {
4219 pbo = calloc (sizeof (*pbo), 1);
4220 if (!pbo) {
4221 err (1, "calloc pbo");
4224 switch (cs) {
4225 case 0:
4226 case 1:
4227 pbo->size = w*h*4;
4228 break;
4229 case 2:
4230 pbo->size = w*h*2;
4231 break;
4232 default:
4233 errx (1, "%s: invalid colorspace %d", __func__, cs);
4236 state.glGenBuffersARB (1, &pbo->id);
4237 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4238 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4239 NULL, GL_STREAM_DRAW);
4240 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4241 GL_READ_WRITE);
4242 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4243 if (!pbo->ptr) {
4244 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4245 state.glDeleteBuffersARB (1, &pbo->id);
4246 free (pbo);
4247 ret_v = caml_copy_string ("0");
4249 else {
4250 int res;
4251 char *s;
4253 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4254 if (res < 0) {
4255 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4257 s = malloc (res+1);
4258 if (!s) {
4259 err (1, "malloc %d bytes failed", res+1);
4261 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4262 if (res < 0) {
4263 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4265 ret_v = caml_copy_string (s);
4266 free (s);
4269 else {
4270 ret_v = caml_copy_string ("0");
4272 CAMLreturn (ret_v);
4275 CAMLprim value ml_freepbo (value s_v)
4277 CAMLparam1 (s_v);
4278 char *s = String_val (s_v);
4279 struct tile *tile = parse_pointer (__func__, s);
4281 if (tile->pbo) {
4282 state.glDeleteBuffersARB (1, &tile->pbo->id);
4283 tile->pbo->id = -1;
4284 tile->pbo->ptr = NULL;
4285 tile->pbo->size = -1;
4287 CAMLreturn (Val_unit);
4290 CAMLprim value ml_unmappbo (value s_v)
4292 CAMLparam1 (s_v);
4293 char *s = String_val (s_v);
4294 struct tile *tile = parse_pointer (__func__, s);
4296 if (tile->pbo) {
4297 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4298 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4299 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4301 tile->pbo->ptr = NULL;
4302 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4304 CAMLreturn (Val_unit);
4307 static void setuppbo (void)
4309 #ifdef USE_EGL
4310 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4311 #else
4312 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4313 #endif
4314 state.bo_usable = GGPA (glBindBufferARB)
4315 && GGPA (glUnmapBufferARB)
4316 && GGPA (glMapBufferARB)
4317 && GGPA (glBufferDataARB)
4318 && GGPA (glGenBuffersARB)
4319 && GGPA (glDeleteBuffersARB);
4320 #undef GGPA
4323 CAMLprim value ml_bo_usable (value unit_v)
4325 CAMLparam1 (unit_v);
4326 CAMLreturn (Val_bool (state.bo_usable));
4329 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4331 CAMLparam3 (ptr_v, x_v, y_v);
4332 CAMLlocal2 (ret_v, tup_v);
4333 struct page *page;
4334 char *s = String_val (ptr_v);
4335 int x = Int_val (x_v), y = Int_val (y_v);
4336 struct pagedim *pdim;
4337 fz_point p;
4338 fz_matrix ctm;
4340 page = parse_pointer (__func__, s);
4341 pdim = &state.pagedims[page->pdimno];
4343 ret_v = Val_int (0);
4344 if (trylock (__func__)) {
4345 goto done;
4348 if (pdf_specifics (state.ctx, state.doc)) {
4349 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4350 ctm = state.pagedims[page->pdimno].tctm;
4352 else {
4353 ctm = fz_identity;
4355 p.x = x + pdim->bounds.x0;
4356 p.y = y + pdim->bounds.y0;
4358 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4359 fz_invert_matrix (&ctm, &ctm);
4360 fz_transform_point (&p, &ctm);
4362 tup_v = caml_alloc_tuple (2);
4363 ret_v = caml_alloc_small (1, 1);
4364 Field (tup_v, 0) = Val_int (p.x);
4365 Field (tup_v, 1) = Val_int (p.y);
4366 Field (ret_v, 0) = tup_v;
4368 unlock (__func__);
4369 done:
4370 CAMLreturn (ret_v);
4373 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4374 value x_v, value y_v)
4376 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4377 CAMLlocal1 (ret_v);
4378 struct page *page;
4379 char *s = String_val (ptr_v);
4380 int pageno = Int_val (pageno_v);
4381 int pdimno = Int_val (pdimno_v);
4382 double x = Double_val (x_v), y = Double_val (y_v);
4383 struct pagedim *pdim;
4384 fz_point p;
4385 fz_matrix ctm;
4387 ret_v = Val_int (0);
4388 lock (__func__);
4390 if (!*s) {
4391 page = loadpage (pageno, pdimno);
4393 else {
4394 page = parse_pointer (__func__, s);
4396 pdim = &state.pagedims[pdimno];
4398 if (pdf_specifics (state.ctx, state.doc)) {
4399 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4400 ctm = state.pagedims[page->pdimno].tctm;
4402 else {
4403 ctm = fz_identity;
4405 p.x = x + pdim->bounds.x0;
4406 p.y = y + pdim->bounds.y0;
4408 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4409 fz_transform_point (&p, &ctm);
4411 ret_v = caml_alloc_tuple (2);
4412 Field (ret_v, 0) = caml_copy_double (p.x);
4413 Field (ret_v, 1) = caml_copy_double (p.y);
4415 if (!*s) {
4416 freepage (page);
4418 unlock (__func__);
4419 CAMLreturn (ret_v);
4422 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4423 value contents_v)
4425 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4426 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4428 if (pdf) {
4429 pdf_annot *annot;
4430 struct page *page;
4431 fz_point p;
4432 char *s = String_val (ptr_v);
4434 page = parse_pointer (__func__, s);
4435 annot = pdf_create_annot (state.ctx, pdf,
4436 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4437 p.x = Int_val (x_v);
4438 p.y = Int_val (y_v);
4439 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4440 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4441 state.dirty = 1;
4443 CAMLreturn (Val_unit);
4446 CAMLprim value ml_delannot (value ptr_v, value n_v)
4448 CAMLparam2 (ptr_v, n_v);
4449 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4451 if (pdf) {
4452 struct page *page;
4453 char *s = String_val (ptr_v);
4454 struct slink *slink;
4456 page = parse_pointer (__func__, s);
4457 slink = &page->slinks[Int_val (n_v)];
4458 pdf_delete_annot (state.ctx, pdf,
4459 (pdf_page *) page->fzpage,
4460 (pdf_annot *) slink->u.annot);
4461 state.dirty = 1;
4463 CAMLreturn (Val_unit);
4466 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4468 CAMLparam3 (ptr_v, n_v, str_v);
4469 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4471 if (pdf) {
4472 struct page *page;
4473 char *s = String_val (ptr_v);
4474 struct slink *slink;
4476 page = parse_pointer (__func__, s);
4477 slink = &page->slinks[Int_val (n_v)];
4478 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4479 String_val (str_v));
4480 state.dirty = 1;
4482 CAMLreturn (Val_unit);
4485 CAMLprim value ml_hasunsavedchanges (value unit_v)
4487 CAMLparam1 (unit_v);
4488 CAMLreturn (Val_bool (state.dirty));
4491 CAMLprim value ml_savedoc (value path_v)
4493 CAMLparam1 (path_v);
4494 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4496 if (pdf) {
4497 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4499 CAMLreturn (Val_unit);
4502 static void makestippletex (void)
4504 const char pixels[] = "\xff\xff\0\0";
4505 glGenTextures (1, &state.stid);
4506 glBindTexture (GL_TEXTURE_1D, state.stid);
4507 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4508 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4509 glTexImage1D (
4510 GL_TEXTURE_1D,
4512 GL_ALPHA,
4515 GL_ALPHA,
4516 GL_UNSIGNED_BYTE,
4517 pixels
4521 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4523 return caml_copy_string (FZ_VERSION);
4526 #ifdef USE_FONTCONFIG
4527 static struct {
4528 int inited;
4529 FcConfig *config;
4530 } fc;
4532 static fz_font *fc_load_system_font_func (fz_context *ctx,
4533 const char *name,
4534 int bold,
4535 int italic,
4536 int UNUSED_ATTR needs_exact_metrics)
4538 char *buf;
4539 size_t i, size;
4540 fz_font *font;
4541 FcChar8 *path;
4542 FcResult result;
4543 FcPattern *pat, *pat1;
4545 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4546 name, bold, italic, needs_exact_metrics);
4547 if (!fc.inited) {
4548 fc.inited = 1;
4549 fc.config = FcInitLoadConfigAndFonts ();
4550 if (!fc.config) {
4551 lprintf ("FcInitLoadConfigAndFonts failed\n");
4552 return NULL;
4555 if (!fc.config) return NULL;
4557 size = strlen (name);
4558 if (bold) size += sizeof (":bold") - 1;
4559 if (italic) size += sizeof (":italic") - 1;
4560 size += 1;
4562 buf = malloc (size);
4563 if (!buf) {
4564 err (1, "malloc %zu failed", size);
4567 strcpy (buf, name);
4568 if (bold && italic) {
4569 strcat (buf, ":bold:italic");
4571 else {
4572 if (bold) strcat (buf, ":bold");
4573 if (italic) strcat (buf, ":italic");
4575 for (i = 0; i < size; ++i) {
4576 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4579 lprintf ("fcbuf=%s\n", buf);
4580 pat = FcNameParse ((FcChar8 *) buf);
4581 if (!pat) {
4582 printd ("emsg FcNameParse failed\n");
4583 free (buf);
4584 return NULL;
4587 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4588 printd ("emsg FcConfigSubstitute failed\n");
4589 free (buf);
4590 return NULL;
4592 FcDefaultSubstitute (pat);
4594 pat1 = FcFontMatch (fc.config, pat, &result);
4595 if (!pat1) {
4596 printd ("emsg FcFontMatch failed\n");
4597 FcPatternDestroy (pat);
4598 free (buf);
4599 return NULL;
4602 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4603 printd ("emsg FcPatternGetString failed\n");
4604 FcPatternDestroy (pat);
4605 FcPatternDestroy (pat1);
4606 free (buf);
4607 return NULL;
4610 #if 0
4611 printd ("emsg name=%s path=%s\n", name, path);
4612 #endif
4613 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4614 FcPatternDestroy (pat);
4615 FcPatternDestroy (pat1);
4616 free (buf);
4617 return font;
4619 #endif
4621 CAMLprim value ml_init (value csock_v, value params_v)
4623 CAMLparam2 (csock_v, params_v);
4624 CAMLlocal2 (trim_v, fuzz_v);
4625 int ret;
4626 int texcount;
4627 char *fontpath;
4628 int colorspace;
4629 int mustoresize;
4630 int haspboext;
4632 state.csock = Int_val (csock_v);
4633 state.rotate = Int_val (Field (params_v, 0));
4634 state.fitmodel = Int_val (Field (params_v, 1));
4635 trim_v = Field (params_v, 2);
4636 texcount = Int_val (Field (params_v, 3));
4637 state.sliceheight = Int_val (Field (params_v, 4));
4638 mustoresize = Int_val (Field (params_v, 5));
4639 colorspace = Int_val (Field (params_v, 6));
4640 fontpath = String_val (Field (params_v, 7));
4642 if (caml_string_length (Field (params_v, 8)) > 0) {
4643 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4645 if (!state.trimcachepath) {
4646 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4647 strerror (errno));
4650 haspboext = Bool_val (Field (params_v, 9));
4652 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4653 fz_register_document_handlers (state.ctx);
4655 #ifdef USE_FONTCONFIG
4656 if (Bool_val (Field (params_v, 10))) {
4657 fz_install_load_system_font_funcs (
4658 state.ctx, fc_load_system_font_func, NULL
4661 #endif
4663 state.trimmargins = Bool_val (Field (trim_v, 0));
4664 fuzz_v = Field (trim_v, 1);
4665 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4666 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4667 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4668 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4670 set_tex_params (colorspace);
4672 if (*fontpath) {
4673 #ifndef USE_FONTCONFIG
4674 state.face = load_font (fontpath);
4675 #else
4676 FcChar8 *path;
4677 FcResult result;
4678 char *buf = fontpath;
4679 FcPattern *pat, *pat1;
4681 fc.inited = 1;
4682 fc.config = FcInitLoadConfigAndFonts ();
4683 if (!fc.config) {
4684 errx (1, "FcInitLoadConfigAndFonts failed");
4687 pat = FcNameParse ((FcChar8 *) buf);
4688 if (!pat) {
4689 errx (1, "FcNameParse failed");
4692 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4693 errx (1, "FcConfigSubstitute failed");
4695 FcDefaultSubstitute (pat);
4697 pat1 = FcFontMatch (fc.config, pat, &result);
4698 if (!pat1) {
4699 errx (1, "FcFontMatch failed");
4702 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4703 errx (1, "FcPatternGetString failed");
4706 state.face = load_font ((char *) path);
4707 FcPatternDestroy (pat);
4708 FcPatternDestroy (pat1);
4709 #endif
4711 else {
4712 unsigned int len;
4713 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4715 state.face = load_builtin_font (base, len);
4717 if (!state.face) _exit (1);
4719 realloctexts (texcount);
4721 if (haspboext) {
4722 setuppbo ();
4725 makestippletex ();
4727 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4728 if (ret) {
4729 errx (1, "pthread_create: %s", strerror (ret));
4732 CAMLreturn (Val_unit);