Use vectored writes
[llpp.git] / link.c
blob1634701b1add32fe2ecc9e44aa309bcd6578fdee
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
3 #define FIXME 0
5 #include <errno.h>
6 #include <stdio.h>
7 #include <ctype.h>
8 #include <string.h>
9 #include <stdlib.h>
10 #include <signal.h>
11 #include <wchar.h>
13 #include <unistd.h>
14 #include <pthread.h>
15 #include <sys/uio.h>
16 #include <sys/time.h>
17 #include <sys/types.h>
18 #include <sys/ioctl.h>
19 #include <sys/utsname.h>
21 #ifdef __CYGWIN__
22 #include <cygwin/socket.h> /* FIONREAD */
23 #else
24 #include <spawn.h>
25 #endif
27 #include <regex.h>
28 #include <stdarg.h>
29 #include <limits.h>
30 #include <inttypes.h>
32 #include <GL/gl.h>
34 #include <caml/fail.h>
35 #include <caml/alloc.h>
36 #include <caml/memory.h>
37 #include <caml/unixsupport.h>
39 #if __GNUC__ < 5 && !defined __clang__
40 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
41 clobbered diagnostics */
42 #pragma GCC diagnostic ignored "-Wclobbered"
43 #endif
45 #include <mupdf/fitz.h>
46 #include <mupdf/pdf.h>
48 #include <ft2build.h>
49 #include FT_FREETYPE_H
51 #ifdef USE_FONTCONFIG
52 #include <fontconfig/fontconfig.h>
53 #endif
55 #define PIGGYBACK
56 #define CACHE_PAGEREFS
58 #ifndef __USE_GNU
59 extern char **environ;
60 #endif
62 #if defined __GNUC__
63 #define NORETURN_ATTR __attribute__ ((noreturn))
64 #define UNUSED_ATTR __attribute__ ((unused))
65 #if !defined __clang__
66 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
67 #else
68 #define OPTIMIZE_ATTR(n)
69 #endif
70 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
71 #else
72 #define NORETURN_ATTR
73 #define UNUSED_ATTR
74 #define OPTIMIZE_ATTR(n)
75 #define GCC_FMT_ATTR(a, b)
76 #endif
78 #define FMT_s "zu"
80 #define FMT_ptr PRIxPTR
81 #define SCN_ptr SCNxPTR
82 #define FMT_ptr_cast(p) ((uintptr_t) (p))
83 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
85 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
86 err (int exitcode, const char *fmt, ...)
88 va_list ap;
89 int savederrno;
91 savederrno = errno;
92 va_start (ap, fmt);
93 vfprintf (stderr, fmt, ap);
94 va_end (ap);
95 fprintf (stderr, ": %s\n", strerror (savederrno));
96 fflush (stderr);
97 _exit (exitcode);
100 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
101 errx (int exitcode, const char *fmt, ...)
103 va_list ap;
105 va_start (ap, fmt);
106 vfprintf (stderr, fmt, ap);
107 va_end (ap);
108 fputc ('\n', stderr);
109 fflush (stderr);
110 _exit (exitcode);
113 #ifndef GL_TEXTURE_RECTANGLE_ARB
114 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
115 #endif
117 #ifdef USE_NPOT
118 #define TEXT_TYPE GL_TEXTURE_2D
119 #else
120 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
121 #endif
123 #ifndef GL_BGRA
124 #define GL_BGRA 0x80E1
125 #endif
127 #ifndef GL_UNSIGNED_INT_8_8_8_8
128 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
129 #endif
131 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
132 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
133 #endif
135 #if 0
136 #define lprintf printf
137 #else
138 #define lprintf(...)
139 #endif
141 #define ARSERT(cond) for (;;) { \
142 if (!(cond)) { \
143 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
145 break; \
148 struct slice {
149 int h;
150 int texindex;
153 struct tile {
154 int w, h;
155 int slicecount;
156 int sliceheight;
157 struct bo *pbo;
158 fz_pixmap *pixmap;
159 struct slice slices[1];
162 struct pagedim {
163 int pageno;
164 int rotate;
165 int left;
166 int tctmready;
167 fz_irect bounds;
168 fz_rect pagebox;
169 fz_rect mediabox;
170 fz_matrix ctm, zoomctm, tctm;
173 struct slink {
174 enum { SLINK, SANNOT } tag;
175 fz_irect bbox;
176 union {
177 fz_link *link;
178 fz_annot *annot;
179 } u;
182 struct annot {
183 fz_irect bbox;
184 fz_annot *annot;
187 struct page {
188 int tgen;
189 int sgen;
190 int agen;
191 int pageno;
192 int pdimno;
193 fz_stext_page *text;
194 fz_stext_sheet *sheet;
195 fz_page *fzpage;
196 fz_display_list *dlist;
197 int slinkcount;
198 struct slink *slinks;
199 int annotcount;
200 struct annot *annots;
201 struct mark {
202 int i;
203 fz_stext_span *span;
204 } fmark, lmark;
207 struct {
208 int sliceheight;
209 struct pagedim *pagedims;
210 int pagecount;
211 int pagedimcount;
212 fz_document *doc;
213 fz_context *ctx;
214 int w, h;
216 int texindex;
217 int texcount;
218 GLuint *texids;
220 GLenum texiform;
221 GLenum texform;
222 GLenum texty;
224 fz_colorspace *colorspace;
226 struct {
227 int w, h;
228 struct slice *slice;
229 } *texowners;
231 int rotate;
232 enum { FitWidth, FitProportional, FitPage } fitmodel;
233 int trimmargins;
234 int needoutline;
235 int gen;
236 int aalevel;
238 int trimanew;
239 fz_irect trimfuzz;
240 fz_pixmap *pig;
242 pthread_t thread;
243 int csock;
244 FT_Face face;
246 char *trimcachepath;
247 int cxack;
248 int dirty;
250 GLuint stid;
252 int bo_usable;
253 GLuint boid;
255 void (*glBindBufferARB) (GLenum, GLuint);
256 GLboolean (*glUnmapBufferARB) (GLenum);
257 void *(*glMapBufferARB) (GLenum, GLenum);
258 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
259 void (*glGenBuffersARB) (GLsizei, GLuint *);
260 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
262 GLfloat texcoords[8];
263 GLfloat vertices[16];
265 #ifdef CACHE_PAGEREFS
266 struct {
267 int idx;
268 int count;
269 pdf_obj **objs;
270 pdf_document *pdf;
271 } pdflut;
272 #endif
273 } state;
275 struct bo {
276 GLuint id;
277 void *ptr;
278 size_t size;
281 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
283 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
286 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
288 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
291 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
293 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
294 m.a, m.b, m.c, m.d, m.e, m.f);
297 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
299 static void lock (const char *cap)
301 int ret = pthread_mutex_lock (&mutex);
302 if (ret) {
303 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
307 static void unlock (const char *cap)
309 int ret = pthread_mutex_unlock (&mutex);
310 if (ret) {
311 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
315 static int trylock (const char *cap)
317 int ret = pthread_mutex_trylock (&mutex);
318 if (ret && ret != EBUSY) {
319 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
321 return ret == EBUSY;
324 static void *parse_pointer (const char *cap, const char *s)
326 int ret;
327 void *ptr;
329 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
330 if (ret != 1) {
331 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
333 return ptr;
336 static double now (void)
338 struct timeval tv;
340 if (gettimeofday (&tv, NULL)) {
341 err (1, "gettimeofday");
343 return tv.tv_sec + tv.tv_usec*1e-6;
346 static int hasdata (void)
348 int ret, avail;
349 ret = ioctl (state.csock, FIONREAD, &avail);
350 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
351 return avail > 0;
354 CAMLprim value ml_hasdata (value fd_v)
356 CAMLparam1 (fd_v);
357 int ret, avail;
359 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
360 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
361 CAMLreturn (Val_bool (avail > 0));
364 static void readdata (int fd, void *p, int size)
366 ssize_t n;
368 again:
369 n = read (fd, p, size);
370 if (n < 0) {
371 if (errno == EINTR) goto again;
372 err (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
374 if (n - size) {
375 if (!n) errx (1, "EOF while reading");
376 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
380 static void writedata (int fd, char *p, int size)
382 uint32_t size4 = size;
383 struct iovec iov[2] = {[0] = { .iov_base = &size4,
384 .iov_len = 4},
385 [1] = { .iov_base = p,
386 .iov_len = size }};
387 ssize_t n;
389 n = writev (fd, iov, 2);
390 if (n - size - 4) {
391 if (!n) errx (1, "EOF while writing data");
392 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
396 static int readlen (int fd)
398 /* Type punned unions here. Why? Less code (Adjusted by more comments).
399 https://en.wikipedia.org/wiki/Type_punning */
400 union { uint32_t len; char raw[4]; } buf;
401 readdata (fd, buf.raw, 4);
402 return buf.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, size, 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, 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 (!page) return;
645 if (!pdim->tctmready) {
646 fz_rect realbox, mediabox;
647 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
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 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
657 fz_invert_matrix (&im, &page_ctm);
658 fz_concat (&ctm, &im, &ctm1);
659 pdim->tctm = ctm;
660 pdim->tctmready = 1;
664 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
666 fz_matrix ctm, tm;
667 int pdimno = pdim - state.pagedims;
669 if (pdf_specifics (state.ctx, state.doc)) {
670 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
671 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
673 else {
674 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
675 fz_concat (&ctm, &tm, &pdim->ctm);
677 return ctm;
680 static fz_matrix pagectm (struct page *page)
682 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
685 static void *loadpage (int pageno, int pindex)
687 fz_device *dev;
688 struct page *page;
690 page = calloc (sizeof (struct page), 1);
691 if (!page) {
692 err (1, "calloc page %d", pageno);
695 page->dlist = fz_new_display_list (state.ctx, NULL);
696 dev = fz_new_list_device (state.ctx, page->dlist);
697 fz_try (state.ctx) {
698 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
699 fz_run_page (state.ctx, page->fzpage, dev,
700 &fz_identity, NULL);
702 fz_catch (state.ctx) {
703 page->fzpage = NULL;
705 fz_close_device (state.ctx, dev);
706 fz_drop_device (state.ctx, dev);
708 page->pdimno = pindex;
709 page->pageno = pageno;
710 page->sgen = state.gen;
711 page->agen = state.gen;
712 page->tgen = state.gen;
713 return page;
716 static struct tile *alloctile (int h)
718 int i;
719 int slicecount;
720 size_t tilesize;
721 struct tile *tile;
723 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
724 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
725 tile = calloc (tilesize, 1);
726 if (!tile) {
727 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
729 for (i = 0; i < slicecount; ++i) {
730 int sh = fz_mini (h, state.sliceheight);
731 tile->slices[i].h = sh;
732 tile->slices[i].texindex = -1;
733 h -= sh;
735 tile->slicecount = slicecount;
736 tile->sliceheight = state.sliceheight;
737 return tile;
740 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
741 struct bo *pbo)
743 fz_rect rect;
744 fz_irect bbox;
745 fz_matrix ctm;
746 fz_device *dev;
747 struct tile *tile;
748 struct pagedim *pdim;
750 tile = alloctile (h);
751 pdim = &state.pagedims[page->pdimno];
753 bbox = pdim->bounds;
754 bbox.x0 += x;
755 bbox.y0 += y;
756 bbox.x1 = bbox.x0 + w;
757 bbox.y1 = bbox.y0 + h;
759 if (state.pig) {
760 if (state.pig->w == w
761 && state.pig->h == h
762 && state.pig->colorspace == state.colorspace) {
763 tile->pixmap = state.pig;
764 tile->pixmap->x = bbox.x0;
765 tile->pixmap->y = bbox.y0;
767 else {
768 fz_drop_pixmap (state.ctx, state.pig);
770 state.pig = NULL;
772 if (!tile->pixmap) {
773 if (pbo) {
774 tile->pixmap =
775 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
776 &bbox, 1, pbo->ptr);
777 tile->pbo = pbo;
779 else {
780 tile->pixmap =
781 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
785 tile->w = w;
786 tile->h = h;
787 clearpixmap (tile->pixmap);
789 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
790 ctm = pagectm (page);
791 fz_rect_from_irect (&rect, &bbox);
792 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
793 fz_close_device (state.ctx, dev);
794 fz_drop_device (state.ctx, dev);
796 return tile;
799 #ifdef CACHE_PAGEREFS
800 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
801 thanks to Robin Watts */
802 static void
803 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
805 fz_context *ctx = state.ctx; /* doc->ctx; */
806 pdf_obj *kids;
807 int i, len;
809 if (state.pdflut.idx == state.pagecount) return;
811 kids = pdf_dict_gets (ctx, node, "Kids");
812 len = pdf_array_len (ctx, kids);
814 if (len == 0)
815 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
817 if (pdf_mark_obj (ctx, node))
818 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
819 for (i = 0; i < len; i++) {
820 pdf_obj *kid = pdf_array_get (ctx, kids, i);
821 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
822 if (*type
823 ? !strcmp (type, "Pages")
824 : pdf_dict_gets (ctx, kid, "Kids")
825 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
826 pdf_collect_pages (doc, kid);
828 else {
829 if (*type
830 ? strcmp (type, "Page") != 0
831 : !pdf_dict_gets (ctx, kid, "MediaBox"))
832 fz_warn (ctx, "non-page object in page tree (%s)", type);
833 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
836 pdf_unmark_obj (ctx, node);
839 static void
840 pdf_load_page_objs (pdf_document *doc)
842 pdf_obj *root = pdf_dict_gets (state.ctx,
843 pdf_trailer (state.ctx, doc), "Root");
844 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
846 if (!node)
847 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
849 state.pdflut.idx = 0;
850 pdf_collect_pages (doc, node);
852 #endif
854 static void initpdims (int wthack)
856 double start, end;
857 FILE *trimf = NULL;
858 fz_rect rootmediabox;
859 int pageno, trim, show;
860 int trimw = 0, cxcount;
861 fz_context *ctx = state.ctx;
862 pdf_document *pdf = pdf_specifics (ctx, state.doc);
864 fz_var (trimw);
865 fz_var (trimf);
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 = fz_mini (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 fz_var (rotate);
909 if (pdf) {
910 pdf_obj *pageref, *pageobj;
912 #ifdef CACHE_PAGEREFS
913 pageref = state.pdflut.objs[pageno];
914 #else
915 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
916 #endif
917 pageobj = pdf_resolve_indirect (ctx, pageref);
918 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
920 if (state.trimmargins) {
921 pdf_obj *obj;
922 pdf_page *page;
924 fz_try (ctx) {
925 page = pdf_load_page (ctx, pdf, pageno);
926 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
927 trim = state.trimanew || !obj;
928 if (trim) {
929 fz_rect rect;
930 fz_device *dev;
931 fz_matrix ctm, page_ctm;
933 dev = fz_new_bbox_device (ctx, &rect);
934 dev->hints |= FZ_IGNORE_SHADE;
935 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
936 fz_invert_matrix (&ctm, &page_ctm);
937 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
938 fz_close_device (ctx, dev);
939 fz_drop_device (ctx, dev);
941 rect.x0 += state.trimfuzz.x0;
942 rect.x1 += state.trimfuzz.x1;
943 rect.y0 += state.trimfuzz.y0;
944 rect.y1 += state.trimfuzz.y1;
945 fz_transform_rect (&rect, &ctm);
946 fz_intersect_rect (&rect, &mediabox);
948 if (!fz_is_empty_rect (&rect)) {
949 mediabox = rect;
952 obj = pdf_new_array (ctx, pdf, 4);
953 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
954 mediabox.x0));
955 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
956 mediabox.y0));
957 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
958 mediabox.x1));
959 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
960 mediabox.y1));
961 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
963 else {
964 mediabox.x0 = pdf_to_real (ctx,
965 pdf_array_get (ctx, obj, 0));
966 mediabox.y0 = pdf_to_real (ctx,
967 pdf_array_get (ctx, obj, 1));
968 mediabox.x1 = pdf_to_real (ctx,
969 pdf_array_get (ctx, obj, 2));
970 mediabox.y1 = pdf_to_real (ctx,
971 pdf_array_get (ctx, obj, 3));
974 fz_drop_page (ctx, &page->super);
975 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
976 if (show) {
977 printd ("progress %f Trimming %d",
978 (double) (pageno + 1) / state.pagecount,
979 pageno + 1);
982 fz_catch (ctx) {
983 fprintf (stderr, "failed to load page %d\n", pageno+1);
986 else {
987 int empty = 0;
988 fz_rect cropbox;
990 pdf_to_rect (ctx,
991 pdf_dict_gets (ctx, pageobj, "MediaBox"),
992 &mediabox);
993 if (fz_is_empty_rect (&mediabox)) {
994 mediabox.x0 = 0;
995 mediabox.y0 = 0;
996 mediabox.x1 = 612;
997 mediabox.y1 = 792;
998 empty = 1;
1001 pdf_to_rect (ctx,
1002 pdf_dict_gets (ctx, pageobj, "CropBox"),
1003 &cropbox);
1004 if (!fz_is_empty_rect (&cropbox)) {
1005 if (empty) {
1006 mediabox = cropbox;
1008 else {
1009 fz_intersect_rect (&mediabox, &cropbox);
1012 else {
1013 if (empty) {
1014 if (fz_is_empty_rect (&rootmediabox)) {
1015 fprintf (stderr,
1016 "cannot find page size for page %d\n",
1017 pageno+1);
1019 else {
1020 mediabox = rootmediabox;
1026 else {
1027 if (state.trimmargins && trimw) {
1028 fz_page *page;
1030 fz_try (ctx) {
1031 page = fz_load_page (ctx, state.doc, pageno);
1032 fz_bound_page (ctx, page, &mediabox);
1033 if (state.trimmargins) {
1034 fz_rect rect;
1035 fz_device *dev;
1037 dev = fz_new_bbox_device (ctx, &rect);
1038 dev->hints |= FZ_IGNORE_SHADE;
1039 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1040 fz_close_device (ctx, dev);
1041 fz_drop_device (ctx, dev);
1043 rect.x0 += state.trimfuzz.x0;
1044 rect.x1 += state.trimfuzz.x1;
1045 rect.y0 += state.trimfuzz.y0;
1046 rect.y1 += state.trimfuzz.y1;
1047 fz_intersect_rect (&rect, &mediabox);
1049 if (!fz_is_empty_rect (&rect)) {
1050 mediabox = rect;
1053 fz_drop_page (ctx, page);
1054 if (!state.cxack) {
1055 printd ("progress %f loading %d",
1056 (double) (pageno + 1) / state.pagecount,
1057 pageno + 1);
1060 fz_catch (ctx) {
1062 if (trimf) {
1063 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1064 if (n - 1) {
1065 err (1, "fwrite trim mediabox");
1069 else {
1070 if (trimf) {
1071 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1072 if (n - 1) {
1073 err (1, "fread trim mediabox %d", pageno);
1076 else {
1077 fz_page *page;
1078 fz_try (ctx) {
1079 page = fz_load_page (ctx, state.doc, pageno);
1080 fz_bound_page (ctx, page, &mediabox);
1081 fz_drop_page (ctx, page);
1083 show = !state.trimmargins && pageno % 20 == 0;
1084 if (show) {
1085 printd ("progress %f Gathering dimensions %d",
1086 (double) (pageno) / state.pagecount,
1087 pageno);
1090 fz_catch (ctx) {
1091 fprintf (stderr, "failed to load page %d\n", pageno);
1097 if (state.pagedimcount == 0
1098 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1099 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1100 size_t size;
1102 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1103 state.pagedims = realloc (state.pagedims, size);
1104 if (!state.pagedims) {
1105 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1106 size, state.pagedimcount + 1);
1109 p = &state.pagedims[state.pagedimcount++];
1110 p->rotate = rotate;
1111 p->mediabox = mediabox;
1112 p->pageno = pageno;
1115 end = now ();
1116 if (!wthack) {
1117 printd ("progress 1 %s %d pages in %f seconds",
1118 state.trimmargins ? "Trimmed" : "Processed",
1119 state.pagecount, end - start);
1121 state.trimanew = 0;
1122 if (trimf) {
1123 if (fclose (trimf)) {
1124 err (1, "fclose");
1129 static void layout (void)
1131 int pindex;
1132 fz_rect box;
1133 fz_matrix ctm, rm;
1134 struct pagedim *p = p;
1135 double zw, w, maxw = 0.0, zoom = zoom;
1137 if (state.pagedimcount == 0) return;
1139 switch (state.fitmodel) {
1140 case FitProportional:
1141 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1142 double x0, x1;
1144 p = &state.pagedims[pindex];
1145 fz_rotate (&rm, p->rotate + state.rotate);
1146 box = p->mediabox;
1147 fz_transform_rect (&box, &rm);
1149 x0 = fz_min (box.x0, box.x1);
1150 x1 = fz_max (box.x0, box.x1);
1152 w = x1 - x0;
1153 maxw = fz_max (w, maxw);
1154 zoom = state.w / maxw;
1156 break;
1158 case FitPage:
1159 maxw = state.w;
1160 break;
1162 case FitWidth:
1163 break;
1165 default:
1166 ARSERT (0 && state.fitmodel);
1169 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1170 fz_rect rect;
1171 fz_matrix tm, sm;
1173 p = &state.pagedims[pindex];
1174 fz_rotate (&ctm, state.rotate);
1175 fz_rotate (&rm, p->rotate + state.rotate);
1176 box = p->mediabox;
1177 fz_transform_rect (&box, &rm);
1178 w = box.x1 - box.x0;
1179 switch (state.fitmodel) {
1180 case FitProportional:
1181 p->left = ((maxw - w) * zoom) / 2.0;
1182 break;
1183 case FitPage:
1185 double zh, h;
1186 zw = maxw / w;
1187 h = box.y1 - box.y0;
1188 zh = state.h / h;
1189 zoom = fz_min (zw, zh);
1190 p->left = (maxw - (w * zoom)) / 2.0;
1192 break;
1193 case FitWidth:
1194 p->left = 0;
1195 zoom = state.w / w;
1196 break;
1199 fz_scale (&p->zoomctm, zoom, zoom);
1200 fz_concat (&ctm, &p->zoomctm, &ctm);
1202 fz_rotate (&rm, p->rotate);
1203 p->pagebox = p->mediabox;
1204 fz_transform_rect (&p->pagebox, &rm);
1205 p->pagebox.x1 -= p->pagebox.x0;
1206 p->pagebox.y1 -= p->pagebox.y0;
1207 p->pagebox.x0 = 0;
1208 p->pagebox.y0 = 0;
1209 rect = p->pagebox;
1210 fz_transform_rect (&rect, &ctm);
1211 fz_round_rect (&p->bounds, &rect);
1212 p->ctm = ctm;
1214 fz_translate (&tm, 0, -p->mediabox.y1);
1215 fz_scale (&sm, zoom, -zoom);
1216 fz_concat (&ctm, &tm, &sm);
1218 p->tctmready = 0;
1221 do {
1222 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1223 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1224 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1225 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1226 int boundw = x1 - x0;
1227 int boundh = y1 - y0;
1229 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1230 } while (p-- != state.pagedims);
1233 struct pagedim *pdimofpageno (int pageno)
1235 int i;
1236 struct pagedim *pdim = state.pagedims;
1238 for (i = 0; i < state.pagedimcount; ++i) {
1239 if (state.pagedims[i].pageno > pageno)
1240 break;
1241 pdim = &state.pagedims[i];
1243 return pdim;
1246 static
1247 struct anchor { int n; int x; int y; int w; int h; }
1248 uritoanchor (const char *uri)
1250 fz_point p;
1251 struct anchor a;
1253 a.n = -1;
1254 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1255 if (a.n >= 0) {
1256 struct pagedim *pdim = pdimofpageno (a.n);
1257 fz_transform_point (&p, &pdim->ctm);
1258 a.x = p.x;
1259 a.y = p.y;
1260 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1262 return a;
1265 static void recurse_outline (fz_outline *outline, int level)
1267 while (outline) {
1268 struct anchor a = uritoanchor (outline->uri);
1269 if (a.n >= 0) {
1270 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1272 else {
1273 printd ("on %d %s", level, outline->title);
1275 if (outline->down) {
1276 recurse_outline (outline->down, level + 1);
1278 outline = outline->next;
1282 static void process_outline (void)
1284 fz_outline *outline;
1286 if (!state.needoutline || !state.pagedimcount) return;
1288 state.needoutline = 0;
1289 outline = fz_load_outline (state.ctx, state.doc);
1290 if (outline) {
1291 recurse_outline (outline, 0);
1292 fz_drop_outline (state.ctx, outline);
1296 static char *strofspan (fz_stext_span *span)
1298 char *p;
1299 char utf8[10];
1300 fz_stext_char *ch;
1301 size_t size = 0, cap = 80;
1303 p = malloc (cap + 1);
1304 if (!p) return NULL;
1306 for (ch = span->text; ch < span->text + span->len; ++ch) {
1307 int n = fz_runetochar (utf8, ch->c);
1308 if (size + n > cap) {
1309 cap *= 2;
1310 p = realloc (p, cap + 1);
1311 if (!p) return NULL;
1314 memcpy (p + size, utf8, n);
1315 size += n;
1317 p[size] = 0;
1318 return p;
1321 static int matchspan (regex_t *re, fz_stext_span *span,
1322 int stop, int pageno, double start)
1324 int ret;
1325 char *p;
1326 regmatch_t rm;
1327 int a, b, c;
1328 fz_rect sb, eb;
1329 fz_point p1, p2, p3, p4;
1331 p = strofspan (span);
1332 if (!p) return -1;
1334 ret = regexec (re, p, 1, &rm, 0);
1335 if (ret) {
1336 free (p);
1337 if (ret != REG_NOMATCH) {
1338 size_t size;
1339 char errbuf[80];
1340 size = regerror (ret, re, errbuf, sizeof (errbuf));
1341 printd ("msg regexec error `%.*s'",
1342 (int) size, errbuf);
1343 return -1;
1345 return 0;
1347 else {
1348 int l = span->len;
1350 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1351 c += fz_runelen (span->text[a].c);
1353 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1354 c += fz_runelen (span->text[b].c);
1357 if (fz_runelen (span->text[b].c) > 1) {
1358 b = fz_maxi (0, b-1);
1361 fz_stext_char_bbox (state.ctx, &sb, span, a);
1362 fz_stext_char_bbox (state.ctx, &eb, span, b);
1364 p1.x = sb.x0;
1365 p1.y = sb.y0;
1366 p2.x = eb.x1;
1367 p2.y = sb.y0;
1368 p3.x = eb.x1;
1369 p3.y = eb.y1;
1370 p4.x = sb.x0;
1371 p4.y = eb.y1;
1373 if (!stop) {
1374 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1375 pageno, 1,
1376 p1.x, p1.y,
1377 p2.x, p2.y,
1378 p3.x, p3.y,
1379 p4.x, p4.y);
1381 printd ("progress 1 found at %d `%.*s' in %f sec",
1382 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1383 now () - start);
1385 else {
1386 printd ("match %d %d %f %f %f %f %f %f %f %f",
1387 pageno, 2,
1388 p1.x, p1.y,
1389 p2.x, p2.y,
1390 p3.x, p3.y,
1391 p4.x, p4.y);
1393 free (p);
1394 return 1;
1398 static int compareblocks (const void *l, const void *r)
1400 fz_stext_block const *ls = l;
1401 fz_stext_block const *rs = r;
1402 return ls->bbox.y0 - rs->bbox.y0;
1405 /* wishful thinking function */
1406 static void search (regex_t *re, int pageno, int y, int forward)
1408 int j;
1409 fz_device *tdev;
1410 fz_stext_page *text;
1411 fz_stext_sheet *sheet;
1412 struct pagedim *pdim;
1413 int stop = 0, niters = 0;
1414 double start, end;
1415 fz_page *page;
1417 start = now ();
1418 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1419 if (niters++ == 5) {
1420 niters = 0;
1421 if (hasdata ()) {
1422 printd ("progress 1 attention requested aborting search at %d",
1423 pageno);
1424 stop = 1;
1426 else {
1427 printd ("progress %f searching in page %d",
1428 (double) (pageno + 1) / state.pagecount,
1429 pageno);
1432 pdim = pdimofpageno (pageno);
1433 sheet = fz_new_stext_sheet (state.ctx);
1434 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1435 tdev = fz_new_stext_device (state.ctx, sheet, text, 0);
1437 page = fz_load_page (state.ctx, state.doc, pageno);
1439 fz_matrix ctm = pagectm1 (page, pdim);
1440 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1443 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1444 fz_close_device (state.ctx, tdev);
1445 fz_drop_device (state.ctx, tdev);
1447 for (j = 0; j < text->len; ++j) {
1448 int k;
1449 fz_page_block *pb;
1450 fz_stext_block *block;
1452 pb = &text->blocks[forward ? j : text->len - 1 - j];
1453 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1454 block = pb->u.text;
1456 for (k = 0; k < block->len; ++k) {
1457 fz_stext_line *line;
1458 fz_stext_span *span;
1460 if (forward) {
1461 line = &block->lines[k];
1462 if (line->bbox.y0 < y + 1) continue;
1464 else {
1465 line = &block->lines[block->len - 1 - k];
1466 if (line->bbox.y0 > y - 1) continue;
1469 for (span = line->first_span; span; span = span->next) {
1470 switch (matchspan (re, span, stop, pageno, start)) {
1471 case 0: break;
1472 case 1: stop = 1; break;
1473 case -1: stop = 1; goto endloop;
1478 if (forward) {
1479 pageno += 1;
1480 y = 0;
1482 else {
1483 pageno -= 1;
1484 y = INT_MAX;
1486 endloop:
1487 fz_drop_stext_page (state.ctx, text);
1488 fz_drop_stext_sheet (state.ctx, sheet);
1489 fz_drop_page (state.ctx, page);
1491 end = now ();
1492 if (!stop) {
1493 printd ("progress 1 no matches %f sec", end - start);
1495 printd ("clearrects");
1498 static void set_tex_params (int colorspace)
1500 union {
1501 unsigned char b;
1502 unsigned int s;
1503 } endianness = {1};
1505 switch (colorspace) {
1506 case 0:
1507 state.texiform = GL_RGBA8;
1508 state.texform = GL_RGBA;
1509 state.texty = GL_UNSIGNED_BYTE;
1510 state.colorspace = fz_device_rgb (state.ctx);
1511 break;
1512 case 1:
1513 state.texiform = GL_RGBA8;
1514 state.texform = GL_BGRA;
1515 state.texty = endianness.s > 1
1516 ? GL_UNSIGNED_INT_8_8_8_8
1517 : GL_UNSIGNED_INT_8_8_8_8_REV;
1518 state.colorspace = fz_device_bgr (state.ctx);
1519 break;
1520 case 2:
1521 state.texiform = GL_LUMINANCE_ALPHA;
1522 state.texform = GL_LUMINANCE_ALPHA;
1523 state.texty = GL_UNSIGNED_BYTE;
1524 state.colorspace = fz_device_gray (state.ctx);
1525 break;
1526 default:
1527 errx (1, "invalid colorspce %d", colorspace);
1531 static void realloctexts (int texcount)
1533 size_t size;
1535 if (texcount == state.texcount) return;
1537 if (texcount < state.texcount) {
1538 glDeleteTextures (state.texcount - texcount,
1539 state.texids + texcount);
1542 size = texcount * sizeof (*state.texids);
1543 state.texids = realloc (state.texids, size);
1544 if (!state.texids) {
1545 err (1, "realloc texids %" FMT_s, size);
1548 size = texcount * sizeof (*state.texowners);
1549 state.texowners = realloc (state.texowners, size);
1550 if (!state.texowners) {
1551 err (1, "realloc texowners %" FMT_s, size);
1553 if (texcount > state.texcount) {
1554 int i;
1556 glGenTextures (texcount - state.texcount,
1557 state.texids + state.texcount);
1558 for (i = state.texcount; i < texcount; ++i) {
1559 state.texowners[i].w = -1;
1560 state.texowners[i].slice = NULL;
1563 state.texcount = texcount;
1564 state.texindex = 0;
1567 static char *mbtoutf8 (char *s)
1569 char *p, *r;
1570 wchar_t *tmp;
1571 size_t i, ret, len;
1573 len = mbstowcs (NULL, s, strlen (s));
1574 if (len == 0) {
1575 return s;
1577 else {
1578 if (len == (size_t) -1) {
1579 return s;
1583 tmp = malloc (len * sizeof (wchar_t));
1584 if (!tmp) {
1585 return s;
1588 ret = mbstowcs (tmp, s, len);
1589 if (ret == (size_t) -1) {
1590 free (tmp);
1591 return s;
1594 len = 0;
1595 for (i = 0; i < ret; ++i) {
1596 len += fz_runelen (tmp[i]);
1599 p = r = malloc (len + 1);
1600 if (!r) {
1601 free (tmp);
1602 return s;
1605 for (i = 0; i < ret; ++i) {
1606 p += fz_runetochar (p, tmp[i]);
1608 *p = 0;
1609 free (tmp);
1610 return r;
1613 CAMLprim value ml_mbtoutf8 (value s_v)
1615 CAMLparam1 (s_v);
1616 CAMLlocal1 (ret_v);
1617 char *s, *r;
1619 s = String_val (s_v);
1620 r = mbtoutf8 (s);
1621 if (r == s) {
1622 ret_v = s_v;
1624 else {
1625 ret_v = caml_copy_string (r);
1626 free (r);
1628 CAMLreturn (ret_v);
1631 static void * mainloop (void UNUSED_ATTR *unused)
1633 char *p = NULL;
1634 int len, ret, oldlen = 0;
1636 fz_var (p);
1637 fz_var (oldlen);
1638 for (;;) {
1639 len = readlen (state.csock);
1640 if (len == 0) {
1641 errx (1, "readlen returned 0");
1644 if (oldlen < len + 1) {
1645 p = realloc (p, len + 1);
1646 if (!p) {
1647 err (1, "realloc %d failed", len + 1);
1649 oldlen = len + 1;
1651 readdata (state.csock, p, len);
1652 p[len] = 0;
1654 if (!strncmp ("open", p, 4)) {
1655 int wthack, off, ok = 0;
1656 char *password;
1657 char *filename;
1658 char *utf8filename;
1659 size_t filenamelen;
1661 fz_var (ok);
1662 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1663 if (ret != 2) {
1664 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1667 filename = p + 5 + off;
1668 filenamelen = strlen (filename);
1669 password = filename + filenamelen + 1;
1671 if (password[strlen (password) + 1]) {
1672 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1675 lock ("open");
1676 fz_try (state.ctx) {
1677 ok = openxref (filename, password);
1679 fz_catch (state.ctx) {
1680 utf8filename = mbtoutf8 (filename);
1681 printd ("msg Could not open %s", utf8filename);
1683 if (ok) {
1684 pdfinfo ();
1685 initpdims (wthack);
1687 unlock ("open");
1689 if (ok) {
1690 if (!wthack) {
1691 utf8filename = mbtoutf8 (filename);
1692 printd ("msg Opened %s (press h/F1 to get help)",
1693 utf8filename);
1694 if (utf8filename != filename) {
1695 free (utf8filename);
1698 state.needoutline = 1;
1701 else if (!strncmp ("cs", p, 2)) {
1702 int i, colorspace;
1704 ret = sscanf (p + 2, " %d", &colorspace);
1705 if (ret != 1) {
1706 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1708 lock ("cs");
1709 set_tex_params (colorspace);
1710 for (i = 0; i < state.texcount; ++i) {
1711 state.texowners[i].w = -1;
1712 state.texowners[i].slice = NULL;
1714 unlock ("cs");
1716 else if (!strncmp ("freepage", p, 8)) {
1717 void *ptr;
1719 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1720 if (ret != 1) {
1721 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1723 freepage (ptr);
1725 else if (!strncmp ("freetile", p, 8)) {
1726 void *ptr;
1728 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1729 if (ret != 1) {
1730 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1732 freetile (ptr);
1734 else if (!strncmp ("search", p, 6)) {
1735 int icase, pageno, y, len2, forward;
1736 char *pattern;
1737 regex_t re;
1739 ret = sscanf (p + 6, " %d %d %d %d,%n",
1740 &icase, &pageno, &y, &forward, &len2);
1741 if (ret != 4) {
1742 errx (1, "malformed search `%s' ret=%d", p, ret);
1745 pattern = p + 6 + len2;
1746 ret = regcomp (&re, pattern,
1747 REG_EXTENDED | (icase ? REG_ICASE : 0));
1748 if (ret) {
1749 char errbuf[80];
1750 size_t size;
1752 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1753 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1755 else {
1756 search (&re, pageno, y, forward);
1757 regfree (&re);
1760 else if (!strncmp ("geometry", p, 8)) {
1761 int w, h, fitmodel;
1763 printd ("clear");
1764 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1765 if (ret != 3) {
1766 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1769 lock ("geometry");
1770 state.h = h;
1771 if (w != state.w) {
1772 int i;
1773 state.w = w;
1774 for (i = 0; i < state.texcount; ++i) {
1775 state.texowners[i].slice = NULL;
1778 state.fitmodel = fitmodel;
1779 layout ();
1780 process_outline ();
1782 state.gen++;
1783 unlock ("geometry");
1784 printd ("continue %d", state.pagecount);
1786 else if (!strncmp ("reqlayout", p, 9)) {
1787 char *nameddest;
1788 int rotate, off, h;
1789 unsigned int fitmodel;
1790 pdf_document *pdf;
1792 printd ("clear");
1793 ret = sscanf (p + 9, " %d %u %d %n",
1794 &rotate, &fitmodel, &h, &off);
1795 if (ret != 3) {
1796 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1798 lock ("reqlayout");
1799 pdf = pdf_specifics (state.ctx, state.doc);
1800 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1801 state.gen += 1;
1803 state.rotate = rotate;
1804 state.fitmodel = fitmodel;
1805 state.h = h;
1806 layout ();
1807 process_outline ();
1809 nameddest = p + 9 + off;
1810 if (pdf && nameddest && *nameddest) {
1811 fz_point xy;
1812 struct pagedim *pdim;
1813 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1814 &xy.x, &xy.y);
1815 pdim = pdimofpageno (pageno);
1816 fz_transform_point (&xy, &pdim->ctm);
1817 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1820 state.gen++;
1821 unlock ("reqlayout");
1822 printd ("continue %d", state.pagecount);
1824 else if (!strncmp ("page", p, 4)) {
1825 double a, b;
1826 struct page *page;
1827 int pageno, pindex;
1829 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1830 if (ret != 2) {
1831 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1834 lock ("page");
1835 a = now ();
1836 page = loadpage (pageno, pindex);
1837 b = now ();
1838 unlock ("page");
1840 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1842 else if (!strncmp ("tile", p, 4)) {
1843 int x, y, w, h;
1844 struct page *page;
1845 struct tile *tile;
1846 double a, b;
1847 void *data;
1849 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1850 SCN_ptr_cast (&page), &x, &y, &w, &h,
1851 SCN_ptr_cast (&data));
1852 if (ret != 6) {
1853 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1856 lock ("tile");
1857 a = now ();
1858 tile = rendertile (page, x, y, w, h, data);
1859 b = now ();
1860 unlock ("tile");
1862 printd ("tile %d %d %" FMT_ptr " %u %f",
1863 x, y,
1864 FMT_ptr_cast (tile),
1865 tile->w * tile->h * tile->pixmap->n,
1866 b - a);
1868 else if (!strncmp ("trimset", p, 7)) {
1869 fz_irect fuzz;
1870 int trimmargins;
1872 ret = sscanf (p + 7, " %d %d %d %d %d",
1873 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1874 if (ret != 5) {
1875 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1877 lock ("trimset");
1878 state.trimmargins = trimmargins;
1879 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1880 state.trimanew = 1;
1881 state.trimfuzz = fuzz;
1883 unlock ("trimset");
1885 else if (!strncmp ("settrim", p, 7)) {
1886 fz_irect fuzz;
1887 int trimmargins;
1889 ret = sscanf (p + 7, " %d %d %d %d %d",
1890 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1891 if (ret != 5) {
1892 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1894 printd ("clear");
1895 lock ("settrim");
1896 state.trimmargins = trimmargins;
1897 state.needoutline = 1;
1898 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1899 state.trimanew = 1;
1900 state.trimfuzz = fuzz;
1902 state.pagedimcount = 0;
1903 free (state.pagedims);
1904 state.pagedims = NULL;
1905 initpdims (0);
1906 layout ();
1907 process_outline ();
1908 unlock ("settrim");
1909 printd ("continue %d", state.pagecount);
1911 else if (!strncmp ("sliceh", p, 6)) {
1912 int h;
1914 ret = sscanf (p + 6, " %d", &h);
1915 if (ret != 1) {
1916 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1918 if (h != state.sliceheight) {
1919 int i;
1921 state.sliceheight = h;
1922 for (i = 0; i < state.texcount; ++i) {
1923 state.texowners[i].w = -1;
1924 state.texowners[i].h = -1;
1925 state.texowners[i].slice = NULL;
1929 else if (!strncmp ("interrupt", p, 9)) {
1930 printd ("vmsg interrupted");
1932 else {
1933 errx (1, "unknown command %.*s", len, p);
1936 return 0;
1939 CAMLprim value ml_isexternallink (value uri_v)
1941 CAMLparam1 (uri_v);
1942 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1943 CAMLreturn (Val_bool (ext));
1946 CAMLprim value ml_uritolocation (value uri_v)
1948 CAMLparam1 (uri_v);
1949 CAMLlocal1 (ret_v);
1950 int pageno;
1951 fz_point xy;
1952 struct pagedim *pdim;
1954 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1955 &xy.x, &xy.y);
1956 pdim = pdimofpageno (pageno);
1957 fz_transform_point (&xy, &pdim->ctm);
1958 ret_v = caml_alloc_tuple (3);
1959 Field (ret_v, 0) = Val_int (pageno);
1960 Field (ret_v, 1) = caml_copy_double (xy.x);
1961 Field (ret_v, 2) = caml_copy_double (xy.y);
1962 CAMLreturn (ret_v);
1965 CAMLprim value ml_realloctexts (value texcount_v)
1967 CAMLparam1 (texcount_v);
1968 int ok;
1970 if (trylock (__func__)) {
1971 ok = 0;
1972 goto done;
1974 realloctexts (Int_val (texcount_v));
1975 ok = 1;
1976 unlock (__func__);
1978 done:
1979 CAMLreturn (Val_bool (ok));
1982 static void recti (int x0, int y0, int x1, int y1)
1984 GLfloat *v = state.vertices;
1986 glVertexPointer (2, GL_FLOAT, 0, v);
1987 v[0] = x0; v[1] = y0;
1988 v[2] = x1; v[3] = y0;
1989 v[4] = x0; v[5] = y1;
1990 v[6] = x1; v[7] = y1;
1991 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1994 static void showsel (struct page *page, int ox, int oy)
1996 int seen = 0;
1997 fz_irect bbox;
1998 fz_rect rect;
1999 fz_stext_line *line;
2000 fz_page_block *pageb;
2001 fz_stext_block *block;
2002 struct mark first, last;
2003 unsigned char selcolor[] = {15,15,15,140};
2005 first = page->fmark;
2006 last = page->lmark;
2008 if (!first.span || !last.span) return;
2010 glEnable (GL_BLEND);
2011 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2012 glColor4ubv (selcolor);
2014 ox += state.pagedims[page->pdimno].bounds.x0;
2015 oy += state.pagedims[page->pdimno].bounds.y0;
2016 for (pageb = page->text->blocks;
2017 pageb < page->text->blocks + page->text->len;
2018 ++pageb) {
2019 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2020 block = pageb->u.text;
2022 for (line = block->lines;
2023 line < block->lines + block->len;
2024 ++line) {
2025 fz_stext_span *span;
2026 rect = fz_empty_rect;
2028 for (span = line->first_span; span; span = span->next) {
2029 int i, j, k;
2030 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2032 j = 0;
2033 k = span->len - 1;
2035 if (span == page->fmark.span && span == page->lmark.span) {
2036 seen = 1;
2037 j = fz_mini (first.i, last.i);
2038 k = fz_maxi (first.i, last.i);
2040 else {
2041 if (span == first.span) {
2042 seen = 1;
2043 j = first.i;
2045 else if (span == last.span) {
2046 seen = 1;
2047 k = last.i;
2051 if (seen) {
2052 for (i = j; i <= k; ++i) {
2053 fz_rect bbox1;
2054 fz_union_rect (&rect,
2055 fz_stext_char_bbox (state.ctx, &bbox1,
2056 span, i));
2058 fz_round_rect (&bbox, &rect);
2059 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2060 bbox.x0,
2061 bbox.y0,
2062 bbox.x1,
2063 bbox.y1,
2064 oy, ox);
2066 recti (bbox.x0 + ox, bbox.y0 + oy,
2067 bbox.x1 + ox, bbox.y1 + oy);
2068 if (span == last.span) {
2069 goto done;
2071 rect = fz_empty_rect;
2076 done:
2077 glDisable (GL_BLEND);
2080 #include "glfont.c"
2082 static void stipplerect (fz_matrix *m,
2083 fz_point *p1,
2084 fz_point *p2,
2085 fz_point *p3,
2086 fz_point *p4,
2087 GLfloat *texcoords,
2088 GLfloat *vertices)
2090 fz_transform_point (p1, m);
2091 fz_transform_point (p2, m);
2092 fz_transform_point (p3, m);
2093 fz_transform_point (p4, m);
2095 float w, h, s, t;
2097 w = p2->x - p1->x;
2098 h = p2->y - p1->y;
2099 t = hypotf (w, h) * .25f;
2101 w = p3->x - p2->x;
2102 h = p3->y - p2->y;
2103 s = hypotf (w, h) * .25f;
2105 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2106 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2108 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2109 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2111 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2112 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2114 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2115 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2117 glDrawArrays (GL_LINES, 0, 8);
2120 static void solidrect (fz_matrix *m,
2121 fz_point *p1,
2122 fz_point *p2,
2123 fz_point *p3,
2124 fz_point *p4,
2125 GLfloat *vertices)
2127 fz_transform_point (p1, m);
2128 fz_transform_point (p2, m);
2129 fz_transform_point (p3, m);
2130 fz_transform_point (p4, m);
2131 vertices[0] = p1->x; vertices[1] = p1->y;
2132 vertices[2] = p2->x; vertices[3] = p2->y;
2134 vertices[4] = p3->x; vertices[5] = p3->y;
2135 vertices[6] = p4->x; vertices[7] = p4->y;
2136 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2139 static void highlightlinks (struct page *page, int xoff, int yoff)
2141 int i;
2142 fz_matrix ctm, tm, pm;
2143 fz_link *link, *links;
2144 GLfloat *texcoords = state.texcoords;
2145 GLfloat *vertices = state.vertices;
2147 links = fz_load_links (state.ctx, page->fzpage);
2149 glEnable (GL_TEXTURE_1D);
2150 glEnable (GL_BLEND);
2151 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2152 glBindTexture (GL_TEXTURE_1D, state.stid);
2154 xoff -= state.pagedims[page->pdimno].bounds.x0;
2155 yoff -= state.pagedims[page->pdimno].bounds.y0;
2156 fz_translate (&tm, xoff, yoff);
2157 pm = pagectm (page);
2158 fz_concat (&ctm, &pm, &tm);
2160 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2161 glVertexPointer (2, GL_FLOAT, 0, vertices);
2163 for (link = links; link; link = link->next) {
2164 fz_point p1, p2, p3, p4;
2166 p1.x = link->rect.x0;
2167 p1.y = link->rect.y0;
2169 p2.x = link->rect.x1;
2170 p2.y = link->rect.y0;
2172 p3.x = link->rect.x1;
2173 p3.y = link->rect.y1;
2175 p4.x = link->rect.x0;
2176 p4.y = link->rect.y1;
2178 /* TODO: different colours for different schemes */
2179 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2180 else glColor3ub (255, 0, 0);
2182 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2185 for (i = 0; i < page->annotcount; ++i) {
2186 fz_point p1, p2, p3, p4;
2187 struct annot *annot = &page->annots[i];
2189 p1.x = annot->bbox.x0;
2190 p1.y = annot->bbox.y0;
2192 p2.x = annot->bbox.x1;
2193 p2.y = annot->bbox.y0;
2195 p3.x = annot->bbox.x1;
2196 p3.y = annot->bbox.y1;
2198 p4.x = annot->bbox.x0;
2199 p4.y = annot->bbox.y1;
2201 glColor3ub (0, 0, 128);
2202 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2205 glDisable (GL_BLEND);
2206 glDisable (GL_TEXTURE_1D);
2209 static int compareslinks (const void *l, const void *r)
2211 struct slink const *ls = l;
2212 struct slink const *rs = r;
2213 if (ls->bbox.y0 == rs->bbox.y0) {
2214 return rs->bbox.x0 - rs->bbox.x0;
2216 return ls->bbox.y0 - rs->bbox.y0;
2219 static void droptext (struct page *page)
2221 if (page->text) {
2222 fz_drop_stext_page (state.ctx, page->text);
2223 page->fmark.i = -1;
2224 page->lmark.i = -1;
2225 page->fmark.span = NULL;
2226 page->lmark.span = NULL;
2227 page->text = NULL;
2229 if (page->sheet) {
2230 fz_drop_stext_sheet (state.ctx, page->sheet);
2231 page->sheet = NULL;
2235 static void dropannots (struct page *page)
2237 if (page->annots) {
2238 free (page->annots);
2239 page->annots = NULL;
2240 page->annotcount = 0;
2244 static void ensureannots (struct page *page)
2246 int i, count = 0;
2247 size_t annotsize = sizeof (*page->annots);
2248 fz_annot *annot;
2250 if (state.gen != page->agen) {
2251 dropannots (page);
2252 page->agen = state.gen;
2254 if (page->annots) return;
2256 for (annot = fz_first_annot (state.ctx, page->fzpage);
2257 annot;
2258 annot = fz_next_annot (state.ctx, annot)) {
2259 count++;
2262 if (count > 0) {
2263 page->annotcount = count;
2264 page->annots = calloc (count, annotsize);
2265 if (!page->annots) {
2266 err (1, "calloc annots %d", count);
2269 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2270 annot;
2271 annot = fz_next_annot (state.ctx, annot), i++) {
2272 fz_rect rect;
2274 fz_bound_annot (state.ctx, annot, &rect);
2275 page->annots[i].annot = annot;
2276 fz_round_rect (&page->annots[i].bbox, &rect);
2281 static void dropslinks (struct page *page)
2283 if (page->slinks) {
2284 free (page->slinks);
2285 page->slinks = NULL;
2286 page->slinkcount = 0;
2290 static void ensureslinks (struct page *page)
2292 fz_matrix ctm;
2293 int i, count;
2294 size_t slinksize = sizeof (*page->slinks);
2295 fz_link *link, *links;
2297 ensureannots (page);
2298 if (state.gen != page->sgen) {
2299 dropslinks (page);
2300 page->sgen = state.gen;
2302 if (page->slinks) return;
2304 links = fz_load_links (state.ctx, page->fzpage);
2305 ctm = pagectm (page);
2307 count = page->annotcount;
2308 for (link = links; link; link = link->next) {
2309 count++;
2311 if (count > 0) {
2312 int j;
2314 page->slinkcount = count;
2315 page->slinks = calloc (count, slinksize);
2316 if (!page->slinks) {
2317 err (1, "calloc slinks %d", count);
2320 for (i = 0, link = links; link; ++i, link = link->next) {
2321 fz_rect rect;
2323 rect = link->rect;
2324 fz_transform_rect (&rect, &ctm);
2325 page->slinks[i].tag = SLINK;
2326 page->slinks[i].u.link = link;
2327 fz_round_rect (&page->slinks[i].bbox, &rect);
2329 for (j = 0; j < page->annotcount; ++j, ++i) {
2330 fz_rect rect;
2331 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2332 fz_transform_rect (&rect, &ctm);
2333 fz_round_rect (&page->slinks[i].bbox, &rect);
2335 page->slinks[i].tag = SANNOT;
2336 page->slinks[i].u.annot = page->annots[j].annot;
2338 qsort (page->slinks, count, slinksize, compareslinks);
2342 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2343 static void fmt_linkn (char *s, unsigned int u)
2345 unsigned int len; unsigned int q;
2346 unsigned int zma = 'z' - 'a' + 1;
2347 len = 1; q = u;
2348 while (q > zma - 1) { ++len; q /= zma; }
2349 if (s) {
2350 s += len;
2351 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2352 /* handles u == 0 */
2354 s[len] = 0;
2357 static void highlightslinks (struct page *page, int xoff, int yoff,
2358 int noff, char *targ, int tlen, int hfsize)
2360 int i;
2361 char buf[40];
2362 struct slink *slink;
2363 double x0, y0, x1, y1, w;
2365 ensureslinks (page);
2366 glColor3ub (0xc3, 0xb0, 0x91);
2367 for (i = 0; i < page->slinkcount; ++i) {
2368 fmt_linkn (buf, i + noff);
2369 if (!tlen || !strncmp (targ, buf, tlen)) {
2370 slink = &page->slinks[i];
2372 x0 = slink->bbox.x0 + xoff - 5;
2373 y1 = slink->bbox.y0 + yoff - 5;
2374 y0 = y1 + 10 + hfsize;
2375 w = measure_string (state.face, hfsize, buf);
2376 x1 = x0 + w + 10;
2377 recti (x0, y0, x1, y1);
2381 glEnable (GL_BLEND);
2382 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2383 glEnable (GL_TEXTURE_2D);
2384 glColor3ub (0, 0, 0);
2385 for (i = 0; i < page->slinkcount; ++i) {
2386 fmt_linkn (buf, i + noff);
2387 if (!tlen || !strncmp (targ, buf, tlen)) {
2388 slink = &page->slinks[i];
2390 x0 = slink->bbox.x0 + xoff;
2391 y0 = slink->bbox.y0 + yoff + hfsize;
2392 draw_string (state.face, hfsize, x0, y0, buf);
2395 glDisable (GL_TEXTURE_2D);
2396 glDisable (GL_BLEND);
2399 static void uploadslice (struct tile *tile, struct slice *slice)
2401 int offset;
2402 struct slice *slice1;
2403 unsigned char *texdata;
2405 offset = 0;
2406 for (slice1 = tile->slices; slice != slice1; slice1++) {
2407 offset += slice1->h * tile->w * tile->pixmap->n;
2409 if (slice->texindex != -1 && slice->texindex < state.texcount
2410 && state.texowners[slice->texindex].slice == slice) {
2411 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2413 else {
2414 int subimage = 0;
2415 int texindex = state.texindex++ % state.texcount;
2417 if (state.texowners[texindex].w == tile->w) {
2418 if (state.texowners[texindex].h >= slice->h) {
2419 subimage = 1;
2421 else {
2422 state.texowners[texindex].h = slice->h;
2425 else {
2426 state.texowners[texindex].h = slice->h;
2429 state.texowners[texindex].w = tile->w;
2430 state.texowners[texindex].slice = slice;
2431 slice->texindex = texindex;
2433 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2434 #if TEXT_TYPE == GL_TEXTURE_2D
2435 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2436 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2437 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2438 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2439 #endif
2440 if (tile->pbo) {
2441 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2442 texdata = 0;
2444 else {
2445 texdata = tile->pixmap->samples;
2447 if (subimage) {
2448 glTexSubImage2D (TEXT_TYPE,
2452 tile->w,
2453 slice->h,
2454 state.texform,
2455 state.texty,
2456 texdata+offset
2459 else {
2460 glTexImage2D (TEXT_TYPE,
2462 state.texiform,
2463 tile->w,
2464 slice->h,
2466 state.texform,
2467 state.texty,
2468 texdata+offset
2471 if (tile->pbo) {
2472 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2477 CAMLprim value ml_begintiles (value unit_v)
2479 CAMLparam1 (unit_v);
2480 glEnable (TEXT_TYPE);
2481 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2482 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2483 CAMLreturn (unit_v);
2486 CAMLprim value ml_endtiles (value unit_v)
2488 CAMLparam1 (unit_v);
2489 glDisable (TEXT_TYPE);
2490 CAMLreturn (unit_v);
2493 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2495 CAMLparam2 (args_v, ptr_v);
2496 int dispx = Int_val (Field (args_v, 0));
2497 int dispy = Int_val (Field (args_v, 1));
2498 int dispw = Int_val (Field (args_v, 2));
2499 int disph = Int_val (Field (args_v, 3));
2500 int tilex = Int_val (Field (args_v, 4));
2501 int tiley = Int_val (Field (args_v, 5));
2502 char *s = String_val (ptr_v);
2503 struct tile *tile = parse_pointer (__func__, s);
2504 int slicey, firstslice;
2505 struct slice *slice;
2506 GLfloat *texcoords = state.texcoords;
2507 GLfloat *vertices = state.vertices;
2509 firstslice = tiley / tile->sliceheight;
2510 slice = &tile->slices[firstslice];
2511 slicey = tiley % tile->sliceheight;
2513 while (disph > 0) {
2514 int dh;
2516 dh = slice->h - slicey;
2517 dh = fz_mini (disph, dh);
2518 uploadslice (tile, slice);
2520 texcoords[0] = tilex; texcoords[1] = slicey;
2521 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2522 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2523 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2525 vertices[0] = dispx; vertices[1] = dispy;
2526 vertices[2] = dispx+dispw; vertices[3] = dispy;
2527 vertices[4] = dispx; vertices[5] = dispy+dh;
2528 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2530 #if TEXT_TYPE == GL_TEXTURE_2D
2531 for (int i = 0; i < 8; ++i) {
2532 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2534 #endif
2536 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2537 dispy += dh;
2538 disph -= dh;
2539 slice++;
2540 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2541 slicey = 0;
2543 CAMLreturn (Val_unit);
2546 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2548 fz_matrix ctm, tm, pm;
2549 fz_point p1, p2, p3, p4;
2550 GLfloat *vertices = state.vertices;
2551 double *v = (double *) rects_v;
2553 xoff -= state.pagedims[page->pdimno].bounds.x0;
2554 yoff -= state.pagedims[page->pdimno].bounds.y0;
2555 fz_translate (&tm, xoff, yoff);
2556 pm = pagectm (page);
2557 fz_concat (&ctm, &pm, &tm);
2559 glEnable (GL_BLEND);
2560 glVertexPointer (2, GL_FLOAT, 0, vertices);
2562 glColor4dv (v);
2563 p1.x = v[4];
2564 p1.y = v[5];
2566 p2.x = v[6];
2567 p2.y = v[5];
2569 p3.x = v[6];
2570 p3.y = v[7];
2572 p4.x = v[4];
2573 p4.y = v[7];
2574 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2575 glDisable (GL_BLEND);
2578 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2579 value xoff_v, value yoff_v,
2580 value li_v)
2582 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2583 int xoff = Int_val (xoff_v);
2584 int yoff = Int_val (yoff_v);
2585 int noff = Int_val (Field (li_v, 0));
2586 char *targ = String_val (Field (li_v, 1));
2587 int tlen = caml_string_length (Field (li_v, 1));
2588 int hfsize = Int_val (Field (li_v, 2));
2589 char *s = String_val (ptr_v);
2590 int hlmask = Int_val (hlinks_v);
2591 struct page *page = parse_pointer (__func__, s);
2593 if (!page->fzpage) {
2594 /* deal with loadpage failed pages */
2595 goto done;
2598 if (trylock (__func__)) {
2599 noff = -1;
2600 goto done;
2603 ensureannots (page);
2604 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2605 if (hlmask & 2) {
2606 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2607 noff = page->slinkcount;
2609 if (page->tgen == state.gen) {
2610 showsel (page, xoff, yoff);
2612 unlock (__func__);
2614 done:
2615 CAMLreturn (Val_int (noff));
2618 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2619 value rects_v)
2621 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2622 int xoff = Int_val (xoff_v);
2623 int yoff = Int_val (yoff_v);
2624 char *s = String_val (ptr_v);
2625 struct page *page = parse_pointer (__func__, s);
2627 drawprect (page, xoff, yoff, rects_v);
2628 CAMLreturn (Val_unit);
2631 static struct annot *getannot (struct page *page, int x, int y)
2633 int i;
2634 fz_point p;
2635 fz_matrix ctm;
2636 const fz_matrix *tctm;
2637 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2639 if (!page->annots) return NULL;
2641 if (pdf) {
2642 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2643 tctm = &state.pagedims[page->pdimno].tctm;
2645 else {
2646 tctm = &fz_identity;
2649 p.x = x;
2650 p.y = y;
2652 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2653 fz_invert_matrix (&ctm, &ctm);
2654 fz_transform_point (&p, &ctm);
2656 if (pdf) {
2657 for (i = 0; i < page->annotcount; ++i) {
2658 struct annot *a = &page->annots[i];
2659 fz_rect rect;
2661 fz_bound_annot (state.ctx, a->annot, &rect);
2662 if (p.x >= rect.x0 && p.x <= rect.x1) {
2663 if (p.y >= rect.y0 && p.y <= rect.y1)
2664 return a;
2668 return NULL;
2671 static fz_link *getlink (struct page *page, int x, int y)
2673 fz_point p;
2674 fz_matrix ctm;
2675 fz_link *link, *links;
2677 links = fz_load_links (state.ctx, page->fzpage);
2679 p.x = x;
2680 p.y = y;
2682 ctm = pagectm (page);
2683 fz_invert_matrix (&ctm, &ctm);
2684 fz_transform_point (&p, &ctm);
2686 for (link = links; link; link = link->next) {
2687 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2688 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2689 return link;
2693 return NULL;
2696 static void ensuretext (struct page *page)
2698 if (state.gen != page->tgen) {
2699 droptext (page);
2700 page->tgen = state.gen;
2702 if (!page->text) {
2703 fz_matrix ctm;
2704 fz_device *tdev;
2706 page->text = fz_new_stext_page (state.ctx,
2707 &state.pagedims[page->pdimno].mediabox);
2708 page->sheet = fz_new_stext_sheet (state.ctx);
2709 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2710 ctm = pagectm (page);
2711 fz_run_display_list (state.ctx, page->dlist,
2712 tdev, &ctm, &fz_infinite_rect, NULL);
2713 qsort (page->text->blocks, page->text->len,
2714 sizeof (*page->text->blocks), compareblocks);
2715 fz_close_device (state.ctx, tdev);
2716 fz_drop_device (state.ctx, tdev);
2720 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2722 CAMLparam2 (start_page_v, dir_v);
2723 CAMLlocal1 (ret_v);
2724 int i, dir = Int_val (dir_v);
2725 int start_page = Int_val (start_page_v);
2726 int end_page = dir > 0 ? state.pagecount : -1;
2727 pdf_document *pdf;
2729 fz_var (end_page);
2730 ret_v = Val_int (0);
2731 lock (__func__);
2732 pdf = pdf_specifics (state.ctx, state.doc);
2733 for (i = start_page + dir; i != end_page; i += dir) {
2734 int found;
2736 fz_var (found);
2737 if (pdf) {
2738 pdf_page *page = NULL;
2740 fz_var (page);
2741 fz_try (state.ctx) {
2742 page = pdf_load_page (state.ctx, pdf, i);
2743 found = !!page->links || !!page->annots;
2745 fz_catch (state.ctx) {
2746 found = 0;
2748 if (page) {
2749 fz_drop_page (state.ctx, &page->super);
2752 else {
2753 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2754 found = !!fz_load_links (state.ctx, page);
2755 fz_drop_page (state.ctx, page);
2758 if (found) {
2759 ret_v = caml_alloc_small (1, 1);
2760 Field (ret_v, 0) = Val_int (i);
2761 goto unlock;
2764 unlock:
2765 unlock (__func__);
2766 CAMLreturn (ret_v);
2769 enum { dir_first, dir_last };
2770 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2772 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2774 CAMLparam2 (ptr_v, dir_v);
2775 CAMLlocal2 (ret_v, pos_v);
2776 struct page *page;
2777 int dirtag, i, slinkindex;
2778 struct slink *found = NULL ,*slink;
2779 char *s = String_val (ptr_v);
2781 page = parse_pointer (__func__, s);
2782 ret_v = Val_int (0);
2783 lock (__func__);
2784 ensureslinks (page);
2786 if (Is_block (dir_v)) {
2787 dirtag = Tag_val (dir_v);
2788 switch (dirtag) {
2789 case dir_first_visible:
2791 int x0, y0, dir, first_index, last_index;
2793 pos_v = Field (dir_v, 0);
2794 x0 = Int_val (Field (pos_v, 0));
2795 y0 = Int_val (Field (pos_v, 1));
2796 dir = Int_val (Field (pos_v, 2));
2798 if (dir >= 0) {
2799 dir = 1;
2800 first_index = 0;
2801 last_index = page->slinkcount;
2803 else {
2804 first_index = page->slinkcount - 1;
2805 last_index = -1;
2808 for (i = first_index; i != last_index; i += dir) {
2809 slink = &page->slinks[i];
2810 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2811 found = slink;
2812 break;
2816 break;
2818 case dir_left:
2819 slinkindex = Int_val (Field (dir_v, 0));
2820 found = &page->slinks[slinkindex];
2821 for (i = slinkindex - 1; i >= 0; --i) {
2822 slink = &page->slinks[i];
2823 if (slink->bbox.x0 < found->bbox.x0) {
2824 found = slink;
2825 break;
2828 break;
2830 case dir_right:
2831 slinkindex = Int_val (Field (dir_v, 0));
2832 found = &page->slinks[slinkindex];
2833 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2834 slink = &page->slinks[i];
2835 if (slink->bbox.x0 > found->bbox.x0) {
2836 found = slink;
2837 break;
2840 break;
2842 case dir_down:
2843 slinkindex = Int_val (Field (dir_v, 0));
2844 found = &page->slinks[slinkindex];
2845 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2846 slink = &page->slinks[i];
2847 if (slink->bbox.y0 >= found->bbox.y0) {
2848 found = slink;
2849 break;
2852 break;
2854 case dir_up:
2855 slinkindex = Int_val (Field (dir_v, 0));
2856 found = &page->slinks[slinkindex];
2857 for (i = slinkindex - 1; i >= 0; --i) {
2858 slink = &page->slinks[i];
2859 if (slink->bbox.y0 <= found->bbox.y0) {
2860 found = slink;
2861 break;
2864 break;
2867 else {
2868 dirtag = Int_val (dir_v);
2869 switch (dirtag) {
2870 case dir_first:
2871 found = page->slinks;
2872 break;
2874 case dir_last:
2875 if (page->slinks) {
2876 found = page->slinks + (page->slinkcount - 1);
2878 break;
2881 if (found) {
2882 ret_v = caml_alloc_small (2, 1);
2883 Field (ret_v, 0) = Val_int (found - page->slinks);
2886 unlock (__func__);
2887 CAMLreturn (ret_v);
2890 enum { uuri, utext, uannot };
2892 CAMLprim value ml_getlink (value ptr_v, value n_v)
2894 CAMLparam2 (ptr_v, n_v);
2895 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2896 fz_link *link;
2897 struct page *page;
2898 char *s = String_val (ptr_v);
2899 struct slink *slink;
2901 ret_v = Val_int (0);
2902 page = parse_pointer (__func__, s);
2904 lock (__func__);
2905 ensureslinks (page);
2906 slink = &page->slinks[Int_val (n_v)];
2907 if (slink->tag == SLINK) {
2908 link = slink->u.link;
2909 str_v = caml_copy_string (link->uri);
2910 ret_v = caml_alloc_small (1, uuri);
2911 Field (ret_v, 0) = str_v;
2913 else {
2914 ret_v = caml_alloc_small (1, uannot);
2915 tup_v = caml_alloc_tuple (2);
2916 Field (ret_v, 0) = tup_v;
2917 Field (tup_v, 0) = ptr_v;
2918 Field (tup_v, 1) = n_v;
2920 unlock (__func__);
2922 CAMLreturn (ret_v);
2925 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2927 CAMLparam2 (ptr_v, n_v);
2928 pdf_document *pdf;
2929 const char *contents = "";
2931 lock (__func__);
2932 pdf = pdf_specifics (state.ctx, state.doc);
2933 if (pdf) {
2934 char *s = String_val (ptr_v);
2935 struct page *page;
2936 struct slink *slink;
2938 page = parse_pointer (__func__, s);
2939 slink = &page->slinks[Int_val (n_v)];
2940 contents = pdf_annot_contents (state.ctx,
2941 (pdf_annot *) slink->u.annot);
2943 unlock (__func__);
2944 CAMLreturn (caml_copy_string (contents));
2947 CAMLprim value ml_getlinkcount (value ptr_v)
2949 CAMLparam1 (ptr_v);
2950 struct page *page;
2951 char *s = String_val (ptr_v);
2953 page = parse_pointer (__func__, s);
2954 CAMLreturn (Val_int (page->slinkcount));
2957 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2959 CAMLparam2 (ptr_v, n_v);
2960 CAMLlocal1 (ret_v);
2961 struct page *page;
2962 struct slink *slink;
2963 char *s = String_val (ptr_v);
2965 page = parse_pointer (__func__, s);
2966 ret_v = caml_alloc_tuple (4);
2967 lock (__func__);
2968 ensureslinks (page);
2970 slink = &page->slinks[Int_val (n_v)];
2971 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2972 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2973 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2974 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2975 unlock (__func__);
2976 CAMLreturn (ret_v);
2979 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2981 CAMLparam3 (ptr_v, x_v, y_v);
2982 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2983 fz_link *link;
2984 struct annot *annot;
2985 struct page *page;
2986 char *ptr = String_val (ptr_v);
2987 int x = Int_val (x_v), y = Int_val (y_v);
2988 struct pagedim *pdim;
2990 ret_v = Val_int (0);
2991 if (trylock (__func__)) {
2992 goto done;
2995 page = parse_pointer (__func__, ptr);
2996 pdim = &state.pagedims[page->pdimno];
2997 x += pdim->bounds.x0;
2998 y += pdim->bounds.y0;
3001 annot = getannot (page, x, y);
3002 if (annot) {
3003 int i, n = -1;
3005 ensureslinks (page);
3006 for (i = 0; i < page->slinkcount; ++i) {
3007 if (page->slinks[i].tag == SANNOT
3008 && page->slinks[i].u.annot == annot->annot) {
3009 n = i;
3010 break;
3013 ret_v = caml_alloc_small (1, uannot);
3014 tup_v = caml_alloc_tuple (2);
3015 Field (ret_v, 0) = tup_v;
3016 Field (tup_v, 0) = ptr_v;
3017 Field (tup_v, 1) = Val_int (n);
3018 goto unlock;
3022 link = getlink (page, x, y);
3023 if (link) {
3024 str_v = caml_copy_string (link->uri);
3025 ret_v = caml_alloc_small (1, uuri);
3026 Field (ret_v, 0) = str_v;
3028 else {
3029 fz_rect *b;
3030 fz_page_block *pageb;
3031 fz_stext_block *block;
3033 ensuretext (page);
3034 for (pageb = page->text->blocks;
3035 pageb < page->text->blocks + page->text->len;
3036 ++pageb) {
3037 fz_stext_line *line;
3038 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3039 block = pageb->u.text;
3041 b = &block->bbox;
3042 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3043 continue;
3045 for (line = block->lines;
3046 line < block->lines + block->len;
3047 ++line) {
3048 fz_stext_span *span;
3050 b = &line->bbox;
3051 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3052 continue;
3054 for (span = line->first_span; span; span = span->next) {
3055 int charnum;
3057 b = &span->bbox;
3058 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3059 continue;
3061 for (charnum = 0; charnum < span->len; ++charnum) {
3062 fz_rect bbox;
3063 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3064 b = &bbox;
3066 if (x >= b->x0 && x <= b->x1
3067 && y >= b->y0 && y <= b->y1) {
3068 fz_stext_style *style = span->text->style;
3069 const char *n2 =
3070 style->font
3071 ? fz_font_name (state.ctx, style->font)
3072 : "Span has no font name"
3074 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3075 style->font);
3076 if (face && face->family_name) {
3077 char *s;
3078 char *n1 = face->family_name;
3079 size_t l1 = strlen (n1);
3080 size_t l2 = strlen (n2);
3082 if (l1 != l2 || memcmp (n1, n2, l1)) {
3083 s = malloc (l1 + l2 + 2);
3084 if (s) {
3085 memcpy (s, n2, l2);
3086 s[l2] = '=';
3087 memcpy (s + l2 + 1, n1, l1 + 1);
3088 str_v = caml_copy_string (s);
3089 free (s);
3093 if (str_v == Val_unit) {
3094 str_v = caml_copy_string (n2);
3096 ret_v = caml_alloc_small (1, utext);
3097 Field (ret_v, 0) = str_v;
3098 goto unlock;
3105 unlock:
3106 unlock (__func__);
3108 done:
3109 CAMLreturn (ret_v);
3112 enum { mark_page, mark_block, mark_line, mark_word };
3114 static int uninteresting (int c)
3116 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3117 || ispunct (c);
3120 CAMLprim value ml_clearmark (value ptr_v)
3122 CAMLparam1 (ptr_v);
3123 char *s = String_val (ptr_v);
3124 struct page *page;
3126 if (trylock (__func__)) {
3127 goto done;
3130 page = parse_pointer (__func__, s);
3131 page->fmark.span = NULL;
3132 page->lmark.span = NULL;
3133 page->fmark.i = 0;
3134 page->lmark.i = 0;
3136 unlock (__func__);
3137 done:
3138 CAMLreturn (Val_unit);
3141 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3143 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3144 CAMLlocal1 (ret_v);
3145 fz_rect *b;
3146 struct page *page;
3147 fz_stext_line *line;
3148 fz_page_block *pageb;
3149 fz_stext_block *block;
3150 struct pagedim *pdim;
3151 int mark = Int_val (mark_v);
3152 char *s = String_val (ptr_v);
3153 int x = Int_val (x_v), y = Int_val (y_v);
3155 ret_v = Val_bool (0);
3156 if (trylock (__func__)) {
3157 goto done;
3160 page = parse_pointer (__func__, s);
3161 pdim = &state.pagedims[page->pdimno];
3163 ensuretext (page);
3165 if (mark == mark_page) {
3166 int i;
3167 fz_page_block *pb1 = NULL, *pb2 = NULL;
3169 for (i = 0; i < page->text->len; ++i) {
3170 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3171 pb1 = &page->text->blocks[i];
3172 break;
3175 if (!pb1) goto unlock;
3177 for (i = page->text->len - 1; i >= 0; --i) {
3178 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3179 pb2 = &page->text->blocks[i];
3180 break;
3183 if (!pb2) goto unlock;
3185 block = pb1->u.text;
3187 page->fmark.i = 0;
3188 page->fmark.span = block->lines->first_span;
3190 block = pb2->u.text;
3191 line = &block->lines[block->len - 1];
3192 page->lmark.i = line->last_span->len - 1;
3193 page->lmark.span = line->last_span;
3194 ret_v = Val_bool (1);
3195 goto unlock;
3198 x += pdim->bounds.x0;
3199 y += pdim->bounds.y0;
3201 for (pageb = page->text->blocks;
3202 pageb < page->text->blocks + page->text->len;
3203 ++pageb) {
3204 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3205 block = pageb->u.text;
3207 b = &block->bbox;
3208 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3209 continue;
3211 if (mark == mark_block) {
3212 page->fmark.i = 0;
3213 page->fmark.span = block->lines->first_span;
3215 line = &block->lines[block->len - 1];
3216 page->lmark.i = line->last_span->len - 1;
3217 page->lmark.span = line->last_span;
3218 ret_v = Val_bool (1);
3219 goto unlock;
3222 for (line = block->lines;
3223 line < block->lines + block->len;
3224 ++line) {
3225 fz_stext_span *span;
3227 b = &line->bbox;
3228 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3229 continue;
3231 if (mark == mark_line) {
3232 page->fmark.i = 0;
3233 page->fmark.span = line->first_span;
3235 page->lmark.i = line->last_span->len - 1;
3236 page->lmark.span = line->last_span;
3237 ret_v = Val_bool (1);
3238 goto unlock;
3241 for (span = line->first_span; span; span = span->next) {
3242 int charnum;
3244 b = &span->bbox;
3245 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3246 continue;
3248 for (charnum = 0; charnum < span->len; ++charnum) {
3249 fz_rect bbox;
3250 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3251 b = &bbox;
3253 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3254 /* unicode ftw */
3255 int charnum2, charnum3 = -1, charnum4 = -1;
3257 if (uninteresting (span->text[charnum].c)) goto unlock;
3259 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3260 if (uninteresting (span->text[charnum2].c)) {
3261 charnum3 = charnum2 + 1;
3262 break;
3265 if (charnum3 == -1) charnum3 = 0;
3267 charnum4 = charnum;
3268 for (charnum2 = charnum + 1;
3269 charnum2 < span->len;
3270 ++charnum2) {
3271 if (uninteresting (span->text[charnum2].c)) break;
3272 charnum4 = charnum2;
3275 page->fmark.i = charnum3;
3276 page->fmark.span = span;
3278 page->lmark.i = charnum4;
3279 page->lmark.span = span;
3280 ret_v = Val_bool (1);
3281 goto unlock;
3287 unlock:
3288 if (!Bool_val (ret_v)) {
3289 page->fmark.span = NULL;
3290 page->lmark.span = NULL;
3291 page->fmark.i = 0;
3292 page->lmark.i = 0;
3294 unlock (__func__);
3296 done:
3297 CAMLreturn (ret_v);
3300 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3302 CAMLparam3 (ptr_v, x_v, y_v);
3303 CAMLlocal2 (ret_v, res_v);
3304 fz_rect *b = NULL;
3305 struct page *page;
3306 fz_page_block *pageb;
3307 struct pagedim *pdim;
3308 char *s = String_val (ptr_v);
3309 int x = Int_val (x_v), y = Int_val (y_v);
3311 ret_v = Val_int (0);
3312 if (trylock (__func__)) {
3313 goto done;
3316 page = parse_pointer (__func__, s);
3317 pdim = &state.pagedims[page->pdimno];
3318 x += pdim->bounds.x0;
3319 y += pdim->bounds.y0;
3321 ensuretext (page);
3323 for (pageb = page->text->blocks;
3324 pageb < page->text->blocks + page->text->len;
3325 ++pageb) {
3326 switch (pageb->type) {
3327 case FZ_PAGE_BLOCK_TEXT:
3328 b = &pageb->u.text->bbox;
3329 break;
3331 case FZ_PAGE_BLOCK_IMAGE:
3332 b = &pageb->u.image->bbox;
3333 break;
3335 default:
3336 continue;
3339 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3340 break;
3341 b = NULL;
3343 if (b) {
3344 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3345 ret_v = caml_alloc_small (1, 1);
3346 Store_double_field (res_v, 0, b->x0);
3347 Store_double_field (res_v, 1, b->x1);
3348 Store_double_field (res_v, 2, b->y0);
3349 Store_double_field (res_v, 3, b->y1);
3350 Field (ret_v, 0) = res_v;
3352 unlock (__func__);
3354 done:
3355 CAMLreturn (ret_v);
3358 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3360 CAMLparam2 (ptr_v, rect_v);
3361 fz_rect b;
3362 struct page *page;
3363 struct pagedim *pdim;
3364 char *s = String_val (ptr_v);
3365 int i, x0, x1, y0, y1, fi, li;
3366 fz_stext_line *line;
3367 fz_page_block *pageb;
3368 fz_stext_block *block;
3369 fz_stext_span *span, *fspan, *lspan;
3371 if (trylock (__func__)) {
3372 goto done;
3375 page = parse_pointer (__func__, s);
3376 ensuretext (page);
3378 pdim = &state.pagedims[page->pdimno];
3379 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3380 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3381 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3382 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3384 if (y0 > y1) {
3385 int t = y0;
3386 y0 = y1;
3387 y1 = t;
3388 x0 = x1;
3389 x1 = t;
3392 fi = page->fmark.i;
3393 fspan = page->fmark.span;
3395 li = page->lmark.i;
3396 lspan = page->lmark.span;
3398 for (pageb = page->text->blocks;
3399 pageb < page->text->blocks + page->text->len;
3400 ++pageb) {
3401 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3402 block = pageb->u.text;
3403 for (line = block->lines;
3404 line < block->lines + block->len;
3405 ++line) {
3407 for (span = line->first_span; span; span = span->next) {
3408 for (i = 0; i < span->len; ++i) {
3409 fz_stext_char_bbox (state.ctx, &b, span, i);
3411 if (x0 >= b.x0 && x0 <= b.x1
3412 && y0 >= b.y0 && y0 <= b.y1) {
3413 fspan = span;
3414 fi = i;
3416 if (x1 >= b.x0 && x1 <= b.x1
3417 && y1 >= b.y0 && y1 <= b.y1) {
3418 lspan = span;
3419 li = i;
3425 if (x1 < x0 && fspan == lspan) {
3426 i = fi;
3427 span = fspan;
3429 fi = li;
3430 fspan = lspan;
3432 li = i;
3433 lspan = span;
3436 page->fmark.i = fi;
3437 page->fmark.span = fspan;
3439 page->lmark.i = li;
3440 page->lmark.span = lspan;
3442 unlock (__func__);
3444 done:
3445 CAMLreturn (Val_unit);
3448 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3450 char buf[4];
3451 int i, len, ret;
3453 for (i = a; i <= b; ++i) {
3454 len = fz_runetochar (buf, span->text[i].c);
3455 ret = fwrite (buf, len, 1, f);
3457 if (ret != 1) {
3458 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3459 len, ret, strerror (errno));
3460 return -1;
3463 return 0;
3466 #ifdef __CYGWIN__
3467 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3469 caml_failwith ("ml_popen not implemented under Cygwin");
3471 #else
3472 CAMLprim value ml_spawn (value command_v, value fds_v)
3474 CAMLparam2 (command_v, fds_v);
3475 CAMLlocal2 (l_v, tup_v);
3476 int ret, ret1;
3477 pid_t pid;
3478 char *msg = NULL;
3479 value earg_v = Nothing;
3480 posix_spawnattr_t attr;
3481 posix_spawn_file_actions_t fa;
3482 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3484 argv[2] = String_val (command_v);
3486 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3487 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3490 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3491 msg = "posix_spawnattr_init";
3492 goto fail1;
3495 #ifdef POSIX_SPAWN_USEVFORK
3496 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3497 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3498 goto fail;
3500 #endif
3502 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3503 int fd1, fd2;
3505 tup_v = Field (l_v, 0);
3506 fd1 = Int_val (Field (tup_v, 0));
3507 fd2 = Int_val (Field (tup_v, 1));
3508 if (fd2 < 0) {
3509 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3510 msg = "posix_spawn_file_actions_addclose";
3511 earg_v = tup_v;
3512 goto fail;
3515 else {
3516 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3517 msg = "posix_spawn_file_actions_adddup2";
3518 earg_v = tup_v;
3519 goto fail;
3524 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3525 msg = "posix_spawn";
3526 goto fail;
3529 fail:
3530 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3531 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3534 fail1:
3535 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3536 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3537 strerror (ret1));
3540 if (msg)
3541 unix_error (ret, msg, earg_v);
3543 CAMLreturn (Val_int (pid));
3545 #endif
3547 CAMLprim value ml_hassel (value ptr_v)
3549 CAMLparam1 (ptr_v);
3550 CAMLlocal1 (ret_v);
3551 struct page *page;
3552 char *s = String_val (ptr_v);
3554 ret_v = Val_bool (0);
3555 if (trylock (__func__)) {
3556 goto done;
3559 page = parse_pointer (__func__, s);
3560 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3561 unlock (__func__);
3562 done:
3563 CAMLreturn (ret_v);
3566 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3568 CAMLparam2 (fd_v, ptr_v);
3569 FILE *f;
3570 int seen = 0;
3571 struct page *page;
3572 fz_stext_line *line;
3573 fz_page_block *pageb;
3574 fz_stext_block *block;
3575 int fd = Int_val (fd_v);
3576 char *s = String_val (ptr_v);
3578 if (trylock (__func__)) {
3579 goto done;
3582 page = parse_pointer (__func__, s);
3584 if (!page->fmark.span || !page->lmark.span) {
3585 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3586 goto unlock;
3589 f = fdopen (fd, "w");
3590 if (!f) {
3591 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3592 fd, strerror (errno));
3593 f = stdout;
3596 for (pageb = page->text->blocks;
3597 pageb < page->text->blocks + page->text->len;
3598 ++pageb) {
3599 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3600 block = pageb->u.text;
3601 for (line = block->lines;
3602 line < block->lines + block->len;
3603 ++line) {
3604 fz_stext_span *span;
3606 for (span = line->first_span; span; span = span->next) {
3607 int a, b;
3609 seen |= span == page->fmark.span || span == page->lmark.span;
3610 a = span == page->fmark.span ? page->fmark.i : 0;
3611 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3613 if (seen) {
3614 if (pipespan (f, span, a, b)) {
3615 goto close;
3617 if (span == page->lmark.span) {
3618 goto close;
3620 if (span == line->last_span) {
3621 if (putc ('\n', f) == EOF) {
3622 fprintf (stderr,
3623 "failed break line on sel pipe: %s\n",
3624 strerror (errno));
3625 goto close;
3632 close:
3633 if (f != stdout) {
3634 int ret = fclose (f);
3635 fd = -1;
3636 if (ret == -1) {
3637 if (errno != ECHILD) {
3638 fprintf (stderr, "failed to close sel pipe: %s\n",
3639 strerror (errno));
3643 unlock:
3644 unlock (__func__);
3646 done:
3647 if (fd >= 0) {
3648 if (close (fd)) {
3649 fprintf (stderr, "failed to close sel pipe: %s\n",
3650 strerror (errno));
3653 CAMLreturn (Val_unit);
3656 CAMLprim value ml_getpdimrect (value pagedimno_v)
3658 CAMLparam1 (pagedimno_v);
3659 CAMLlocal1 (ret_v);
3660 int pagedimno = Int_val (pagedimno_v);
3661 fz_rect box;
3663 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3664 if (trylock (__func__)) {
3665 box = fz_empty_rect;
3667 else {
3668 box = state.pagedims[pagedimno].mediabox;
3669 unlock (__func__);
3672 Store_double_field (ret_v, 0, box.x0);
3673 Store_double_field (ret_v, 1, box.x1);
3674 Store_double_field (ret_v, 2, box.y0);
3675 Store_double_field (ret_v, 3, box.y1);
3677 CAMLreturn (ret_v);
3680 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3681 value dw_v, value cols_v)
3683 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3684 CAMLlocal1 (ret_v);
3685 int i;
3686 double zoom = -1.;
3687 double maxh = 0.0;
3688 struct pagedim *p;
3689 double winw = Int_val (winw_v);
3690 double winh = Int_val (winh_v);
3691 double dw = Int_val (dw_v);
3692 double cols = Int_val (cols_v);
3693 double pw = 1.0, ph = 1.0;
3695 if (trylock (__func__)) {
3696 goto done;
3699 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3700 double w = p->pagebox.x1 / cols;
3701 double h = p->pagebox.y1;
3702 if (h > maxh) {
3703 maxh = h;
3704 ph = h;
3705 if (state.fitmodel != FitProportional) pw = w;
3707 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3710 zoom = (((winh / ph) * pw) + dw) / winw;
3711 unlock (__func__);
3712 done:
3713 ret_v = caml_copy_double (zoom);
3714 CAMLreturn (ret_v);
3717 CAMLprim value ml_getmaxw (value unit_v)
3719 CAMLparam1 (unit_v);
3720 CAMLlocal1 (ret_v);
3721 int i;
3722 double maxw = -1.;
3723 struct pagedim *p;
3725 if (trylock (__func__)) {
3726 goto done;
3729 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3730 double w = p->pagebox.x1;
3731 maxw = fz_max (maxw, w);
3734 unlock (__func__);
3735 done:
3736 ret_v = caml_copy_double (maxw);
3737 CAMLreturn (ret_v);
3740 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3742 CAMLparam4 (pt_v, x_v, y_v, string_v);
3743 CAMLlocal1 (ret_v);
3744 int pt = Int_val(pt_v);
3745 int x = Int_val (x_v);
3746 int y = Int_val (y_v);
3747 double w;
3749 w = draw_string (state.face, pt, x, y, String_val (string_v));
3750 ret_v = caml_copy_double (w);
3751 CAMLreturn (ret_v);
3754 CAMLprim value ml_measure_string (value pt_v, value string_v)
3756 CAMLparam2 (pt_v, string_v);
3757 CAMLlocal1 (ret_v);
3758 int pt = Int_val (pt_v);
3759 double w;
3761 w = measure_string (state.face, pt, String_val (string_v));
3762 ret_v = caml_copy_double (w);
3763 CAMLreturn (ret_v);
3766 CAMLprim value ml_getpagebox (value opaque_v)
3768 CAMLparam1 (opaque_v);
3769 CAMLlocal1 (ret_v);
3770 fz_rect rect;
3771 fz_irect bbox;
3772 fz_matrix ctm;
3773 fz_device *dev;
3774 char *s = String_val (opaque_v);
3775 struct page *page = parse_pointer (__func__, s);
3777 ret_v = caml_alloc_tuple (4);
3778 dev = fz_new_bbox_device (state.ctx, &rect);
3779 dev->hints |= FZ_IGNORE_SHADE;
3781 ctm = pagectm (page);
3782 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3784 fz_close_device (state.ctx, dev);
3785 fz_drop_device (state.ctx, dev);
3786 fz_round_rect (&bbox, &rect);
3787 Field (ret_v, 0) = Val_int (bbox.x0);
3788 Field (ret_v, 1) = Val_int (bbox.y0);
3789 Field (ret_v, 2) = Val_int (bbox.x1);
3790 Field (ret_v, 3) = Val_int (bbox.y1);
3792 CAMLreturn (ret_v);
3795 CAMLprim value ml_setaalevel (value level_v)
3797 CAMLparam1 (level_v);
3799 state.aalevel = Int_val (level_v);
3800 CAMLreturn (Val_unit);
3803 #pragma GCC diagnostic push
3804 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3805 #include <X11/Xlib.h>
3806 #include <X11/cursorfont.h>
3807 #pragma GCC diagnostic pop
3809 #ifdef USE_EGL
3810 #include <EGL/egl.h>
3811 #else
3812 #include <GL/glx.h>
3813 #endif
3815 static const int shapes[] = {
3816 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3819 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3821 static struct {
3822 Window wid;
3823 Display *dpy;
3824 #ifdef USE_EGL
3825 EGLContext ctx;
3826 EGLConfig conf;
3827 EGLSurface win;
3828 EGLDisplay *edpy;
3829 #else
3830 GLXContext ctx;
3831 #endif
3832 XVisualInfo *visual;
3833 Cursor curs[CURS_COUNT];
3834 } glx;
3836 #ifdef VISAVIS
3837 static VisualID initvisual (void)
3839 /* On this system with: `Haswell-ULT Integrated Graphics
3840 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3841 using glX chosen visual and auto scrolling some document in
3842 fullscreen the power/energy-gpu is more than 1 joule bigger
3843 than when using hand picked visual that stands alone in glxinfo
3844 output: it's dead last in the list and it's the only one with
3845 `visual dep' (sic) of 32
3847 No clue what's going on here...
3849 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3851 XVisualInfo info;
3852 int ret = 1;
3854 info.depth = 32;
3855 info.class = TrueColor;
3856 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3857 &info, &ret);
3858 if (!ret || !glx.visual) {
3859 XCloseDisplay (glx.dpy);
3860 caml_failwith ("XGetVisualInfo");
3862 return glx.visual->visualid;
3864 #endif
3866 static void initcurs (void)
3868 for (size_t n = 0; n < CURS_COUNT; ++n) {
3869 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3873 CAMLprim void ml_setbgcol (value color_v)
3875 CAMLparam1 (color_v);
3876 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3877 CAMLreturn0;
3880 #ifdef USE_EGL
3881 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3883 CAMLparam3 (display_v, wid_v, screen_v);
3884 int major, minor;
3885 int num_conf;
3886 EGLint visid;
3887 EGLint attribs[] = {
3888 #ifdef VISAVIS
3889 EGL_NATIVE_VISUAL_ID, 0,
3890 #else
3891 EGL_DEPTH_SIZE, 24,
3892 #endif
3893 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3894 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3895 EGL_NONE
3897 EGLConfig conf;
3899 glx.dpy = XOpenDisplay (String_val (display_v));
3900 if (!glx.dpy) {
3901 caml_failwith ("XOpenDisplay");
3904 eglBindAPI (EGL_OPENGL_API);
3906 glx.edpy = eglGetDisplay (glx.dpy);
3907 if (glx.edpy == EGL_NO_DISPLAY) {
3908 caml_failwith ("eglGetDisplay");
3911 if (!eglInitialize (glx.edpy, &major, &minor)) {
3912 caml_failwith ("eglInitialize");
3915 #ifdef VISAVIS
3916 attribs[1] = visid = initvisual ();
3917 #endif
3919 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3920 !num_conf) {
3921 caml_failwith ("eglChooseConfig");
3924 glx.conf = conf;
3925 #ifndef VISAVIS
3926 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
3927 EGL_NATIVE_VISUAL_ID, &visid)) {
3928 caml_failwith ("eglGetConfigAttrib");
3930 #endif
3931 initcurs ();
3933 glx.wid = Int_val (wid_v);
3934 CAMLreturn (Val_int (visid));
3937 CAMLprim value ml_glxcompleteinit (value unit_v)
3939 CAMLparam1 (unit_v);
3941 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3942 if (!glx.ctx) {
3943 caml_failwith ("eglCreateContext");
3946 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3947 glx.wid, NULL);
3948 if (glx.win == EGL_NO_SURFACE) {
3949 caml_failwith ("eglCreateWindowSurface");
3952 XFree (glx.visual);
3953 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3954 glx.ctx = NULL;
3955 caml_failwith ("eglMakeCurrent");
3957 CAMLreturn (Val_unit);
3959 #else
3960 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3962 CAMLparam3 (display_v, wid_v, screen_v);
3964 glx.dpy = XOpenDisplay (String_val (display_v));
3965 if (!glx.dpy) {
3966 caml_failwith ("XOpenDisplay");
3969 #ifdef VISAVIS
3970 initvisual ();
3971 #else
3972 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3973 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3974 if (!glx.visual) {
3975 XCloseDisplay (glx.dpy);
3976 caml_failwith ("glXChooseVisual");
3978 #endif
3979 initcurs ();
3981 glx.wid = Int_val (wid_v);
3982 CAMLreturn (Val_int (glx.visual->visualid));
3985 CAMLprim value ml_glxcompleteinit (value unit_v)
3987 CAMLparam1 (unit_v);
3989 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3990 if (!glx.ctx) {
3991 caml_failwith ("glXCreateContext");
3994 XFree (glx.visual);
3995 glx.visual = NULL;
3997 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3998 glXDestroyContext (glx.dpy, glx.ctx);
3999 glx.ctx = NULL;
4000 caml_failwith ("glXMakeCurrent");
4002 CAMLreturn (Val_unit);
4004 #endif
4006 CAMLprim value ml_setcursor (value cursor_v)
4008 CAMLparam1 (cursor_v);
4009 size_t cursn = Int_val (cursor_v);
4011 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4012 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4013 XFlush (glx.dpy);
4014 CAMLreturn (Val_unit);
4017 CAMLprim value ml_swapb (value unit_v)
4019 CAMLparam1 (unit_v);
4020 #ifdef USE_EGL
4021 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4022 caml_failwith ("eglSwapBuffers");
4024 #else
4025 glXSwapBuffers (glx.dpy, glx.wid);
4026 #endif
4027 CAMLreturn (Val_unit);
4030 #include "keysym2ucs.c"
4032 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4034 CAMLparam1 (keysym_v);
4035 CAMLlocal1 (str_v);
4036 KeySym keysym = Int_val (keysym_v);
4037 Rune rune;
4038 int len;
4039 char buf[5];
4041 rune = keysym2ucs (keysym);
4042 len = fz_runetochar (buf, rune);
4043 buf[len] = 0;
4044 str_v = caml_copy_string (buf);
4045 CAMLreturn (str_v);
4048 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4050 CAMLprim value ml_platform (value unit_v)
4052 CAMLparam1 (unit_v);
4053 CAMLlocal2 (tup_v, arr_v);
4054 int platid = piunknown;
4055 struct utsname buf;
4057 #if defined __linux__
4058 platid = pilinux;
4059 #elif defined __CYGWIN__
4060 platid = picygwin;
4061 #elif defined __DragonFly__ || defined __FreeBSD__
4062 || defined __OpenBSD__ || defined __NetBSD__
4063 platid = pibsd;
4064 #elif defined __sun__
4065 platid = pisun;
4066 #elif defined __APPLE__
4067 platid = piosx;
4068 #endif
4069 if (uname (&buf)) err (1, "uname");
4071 tup_v = caml_alloc_tuple (2);
4073 char const *sar[] = {
4074 buf.sysname,
4075 buf.release,
4076 buf.version,
4077 buf.machine,
4078 NULL
4080 arr_v = caml_copy_string_array (sar);
4082 Field (tup_v, 0) = Val_int (platid);
4083 Field (tup_v, 1) = arr_v;
4084 CAMLreturn (tup_v);
4087 CAMLprim value ml_cloexec (value fd_v)
4089 CAMLparam1 (fd_v);
4090 int fd = Int_val (fd_v);
4092 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4093 uerror ("fcntl", Nothing);
4095 CAMLreturn (Val_unit);
4098 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4100 CAMLparam2 (w_v, h_v);
4101 CAMLlocal1 (ret_v);
4102 struct bo *pbo;
4103 int w = Int_val (w_v);
4104 int h = Int_val (h_v);
4105 int cs = Int_val (cs_v);
4107 if (state.bo_usable) {
4108 pbo = calloc (sizeof (*pbo), 1);
4109 if (!pbo) {
4110 err (1, "calloc pbo");
4113 switch (cs) {
4114 case 0:
4115 case 1:
4116 pbo->size = w*h*4;
4117 break;
4118 case 2:
4119 pbo->size = w*h*2;
4120 break;
4121 default:
4122 errx (1, "%s: invalid colorspace %d", __func__, cs);
4125 state.glGenBuffersARB (1, &pbo->id);
4126 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4127 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4128 NULL, GL_STREAM_DRAW);
4129 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4130 GL_READ_WRITE);
4131 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4132 if (!pbo->ptr) {
4133 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4134 state.glDeleteBuffersARB (1, &pbo->id);
4135 free (pbo);
4136 ret_v = caml_copy_string ("0");
4138 else {
4139 int res;
4140 char *s;
4142 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4143 if (res < 0) {
4144 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4146 s = malloc (res+1);
4147 if (!s) {
4148 err (1, "malloc %d bytes failed", res+1);
4150 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4151 if (res < 0) {
4152 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4154 ret_v = caml_copy_string (s);
4155 free (s);
4158 else {
4159 ret_v = caml_copy_string ("0");
4161 CAMLreturn (ret_v);
4164 CAMLprim value ml_freepbo (value s_v)
4166 CAMLparam1 (s_v);
4167 char *s = String_val (s_v);
4168 struct tile *tile = parse_pointer (__func__, s);
4170 if (tile->pbo) {
4171 state.glDeleteBuffersARB (1, &tile->pbo->id);
4172 tile->pbo->id = -1;
4173 tile->pbo->ptr = NULL;
4174 tile->pbo->size = -1;
4176 CAMLreturn (Val_unit);
4179 CAMLprim value ml_unmappbo (value s_v)
4181 CAMLparam1 (s_v);
4182 char *s = String_val (s_v);
4183 struct tile *tile = parse_pointer (__func__, s);
4185 if (tile->pbo) {
4186 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4187 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4188 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4190 tile->pbo->ptr = NULL;
4191 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4193 CAMLreturn (Val_unit);
4196 static void setuppbo (void)
4198 #ifdef USE_EGL
4199 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4200 #else
4201 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4202 #endif
4203 state.bo_usable = GGPA (glBindBufferARB)
4204 && GGPA (glUnmapBufferARB)
4205 && GGPA (glMapBufferARB)
4206 && GGPA (glBufferDataARB)
4207 && GGPA (glGenBuffersARB)
4208 && GGPA (glDeleteBuffersARB);
4209 #undef GGPA
4212 CAMLprim value ml_bo_usable (value unit_v)
4214 CAMLparam1 (unit_v);
4215 CAMLreturn (Val_bool (state.bo_usable));
4218 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4220 CAMLparam3 (ptr_v, x_v, y_v);
4221 CAMLlocal2 (ret_v, tup_v);
4222 struct page *page;
4223 char *s = String_val (ptr_v);
4224 int x = Int_val (x_v), y = Int_val (y_v);
4225 struct pagedim *pdim;
4226 fz_point p;
4227 fz_matrix ctm;
4229 page = parse_pointer (__func__, s);
4230 pdim = &state.pagedims[page->pdimno];
4232 ret_v = Val_int (0);
4233 if (trylock (__func__)) {
4234 goto done;
4237 if (pdf_specifics (state.ctx, state.doc)) {
4238 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4239 ctm = state.pagedims[page->pdimno].tctm;
4241 else {
4242 ctm = fz_identity;
4244 p.x = x + pdim->bounds.x0;
4245 p.y = y + pdim->bounds.y0;
4247 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4248 fz_invert_matrix (&ctm, &ctm);
4249 fz_transform_point (&p, &ctm);
4251 tup_v = caml_alloc_tuple (2);
4252 ret_v = caml_alloc_small (1, 1);
4253 Field (tup_v, 0) = Val_int (p.x);
4254 Field (tup_v, 1) = Val_int (p.y);
4255 Field (ret_v, 0) = tup_v;
4257 unlock (__func__);
4258 done:
4259 CAMLreturn (ret_v);
4262 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4263 value x_v, value y_v)
4265 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4266 CAMLlocal1 (ret_v);
4267 struct page *page;
4268 char *s = String_val (ptr_v);
4269 int pageno = Int_val (pageno_v);
4270 int pdimno = Int_val (pdimno_v);
4271 double x = Double_val (x_v), y = Double_val (y_v);
4272 struct pagedim *pdim;
4273 fz_point p;
4274 fz_matrix ctm;
4276 ret_v = Val_int (0);
4277 lock (__func__);
4279 if (!*s) {
4280 page = loadpage (pageno, pdimno);
4282 else {
4283 page = parse_pointer (__func__, s);
4285 pdim = &state.pagedims[pdimno];
4287 if (pdf_specifics (state.ctx, state.doc)) {
4288 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4289 ctm = state.pagedims[page->pdimno].tctm;
4291 else {
4292 ctm = fz_identity;
4294 p.x = x + pdim->bounds.x0;
4295 p.y = y + pdim->bounds.y0;
4297 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4298 fz_transform_point (&p, &ctm);
4300 ret_v = caml_alloc_tuple (2);
4301 Field (ret_v, 0) = caml_copy_double (p.x);
4302 Field (ret_v, 1) = caml_copy_double (p.y);
4304 if (!*s) {
4305 freepage (page);
4307 unlock (__func__);
4308 CAMLreturn (ret_v);
4311 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4312 value contents_v)
4314 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4315 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4317 if (pdf) {
4318 pdf_annot *annot;
4319 struct page *page;
4320 fz_point p;
4321 char *s = String_val (ptr_v);
4323 page = parse_pointer (__func__, s);
4324 annot = pdf_create_annot (state.ctx,
4325 pdf_page_from_fz_page (state.ctx,
4326 page->fzpage),
4327 PDF_ANNOT_TEXT);
4328 p.x = Int_val (x_v);
4329 p.y = Int_val (y_v);
4330 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4331 pdf_set_text_annot_position (state.ctx, annot, p);
4332 state.dirty = 1;
4334 CAMLreturn (Val_unit);
4337 CAMLprim value ml_delannot (value ptr_v, value n_v)
4339 CAMLparam2 (ptr_v, n_v);
4340 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4342 if (pdf) {
4343 struct page *page;
4344 char *s = String_val (ptr_v);
4345 struct slink *slink;
4347 page = parse_pointer (__func__, s);
4348 slink = &page->slinks[Int_val (n_v)];
4349 pdf_delete_annot (state.ctx,
4350 pdf_page_from_fz_page (state.ctx, page->fzpage),
4351 (pdf_annot *) slink->u.annot);
4352 state.dirty = 1;
4354 CAMLreturn (Val_unit);
4357 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4359 CAMLparam3 (ptr_v, n_v, str_v);
4360 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4362 if (pdf) {
4363 struct page *page;
4364 char *s = String_val (ptr_v);
4365 struct slink *slink;
4367 page = parse_pointer (__func__, s);
4368 slink = &page->slinks[Int_val (n_v)];
4369 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4370 String_val (str_v));
4371 state.dirty = 1;
4373 CAMLreturn (Val_unit);
4376 CAMLprim value ml_hasunsavedchanges (value unit_v)
4378 CAMLparam1 (unit_v);
4379 CAMLreturn (Val_bool (state.dirty));
4382 CAMLprim value ml_savedoc (value path_v)
4384 CAMLparam1 (path_v);
4385 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4387 if (pdf) {
4388 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4390 CAMLreturn (Val_unit);
4393 static void makestippletex (void)
4395 const char pixels[] = "\xff\xff\0\0";
4396 glGenTextures (1, &state.stid);
4397 glBindTexture (GL_TEXTURE_1D, state.stid);
4398 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4399 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4400 glTexImage1D (
4401 GL_TEXTURE_1D,
4403 GL_ALPHA,
4406 GL_ALPHA,
4407 GL_UNSIGNED_BYTE,
4408 pixels
4412 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4414 return caml_copy_string (FZ_VERSION);
4417 #ifdef USE_FONTCONFIG
4418 static struct {
4419 int inited;
4420 FcConfig *config;
4421 } fc;
4423 static fz_font *fc_load_system_font_func (fz_context *ctx,
4424 const char *name,
4425 int bold,
4426 int italic,
4427 int UNUSED_ATTR needs_exact_metrics)
4429 char *buf;
4430 size_t i, size;
4431 fz_font *font;
4432 FcChar8 *path;
4433 FcResult result;
4434 FcPattern *pat, *pat1;
4436 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4437 name, bold, italic, needs_exact_metrics);
4438 if (!fc.inited) {
4439 fc.inited = 1;
4440 fc.config = FcInitLoadConfigAndFonts ();
4441 if (!fc.config) {
4442 lprintf ("FcInitLoadConfigAndFonts failed\n");
4443 return NULL;
4446 if (!fc.config) return NULL;
4448 size = strlen (name);
4449 if (bold) size += sizeof (":bold") - 1;
4450 if (italic) size += sizeof (":italic") - 1;
4451 size += 1;
4453 buf = malloc (size);
4454 if (!buf) {
4455 err (1, "malloc %zu failed", size);
4458 strcpy (buf, name);
4459 if (bold && italic) {
4460 strcat (buf, ":bold:italic");
4462 else {
4463 if (bold) strcat (buf, ":bold");
4464 if (italic) strcat (buf, ":italic");
4466 for (i = 0; i < size; ++i) {
4467 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4470 lprintf ("fcbuf=%s\n", buf);
4471 pat = FcNameParse ((FcChar8 *) buf);
4472 if (!pat) {
4473 printd ("emsg FcNameParse failed\n");
4474 free (buf);
4475 return NULL;
4478 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4479 printd ("emsg FcConfigSubstitute failed\n");
4480 free (buf);
4481 return NULL;
4483 FcDefaultSubstitute (pat);
4485 pat1 = FcFontMatch (fc.config, pat, &result);
4486 if (!pat1) {
4487 printd ("emsg FcFontMatch failed\n");
4488 FcPatternDestroy (pat);
4489 free (buf);
4490 return NULL;
4493 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4494 printd ("emsg FcPatternGetString failed\n");
4495 FcPatternDestroy (pat);
4496 FcPatternDestroy (pat1);
4497 free (buf);
4498 return NULL;
4501 #if 0
4502 printd ("emsg name=%s path=%s\n", name, path);
4503 #endif
4504 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4505 FcPatternDestroy (pat);
4506 FcPatternDestroy (pat1);
4507 free (buf);
4508 return font;
4510 #endif
4512 CAMLprim value ml_init (value csock_v, value params_v)
4514 CAMLparam2 (csock_v, params_v);
4515 CAMLlocal2 (trim_v, fuzz_v);
4516 int ret;
4517 int texcount;
4518 char *fontpath;
4519 int colorspace;
4520 int mustoresize;
4521 int haspboext;
4523 state.csock = Int_val (csock_v);
4524 state.rotate = Int_val (Field (params_v, 0));
4525 state.fitmodel = Int_val (Field (params_v, 1));
4526 trim_v = Field (params_v, 2);
4527 texcount = Int_val (Field (params_v, 3));
4528 state.sliceheight = Int_val (Field (params_v, 4));
4529 mustoresize = Int_val (Field (params_v, 5));
4530 colorspace = Int_val (Field (params_v, 6));
4531 fontpath = String_val (Field (params_v, 7));
4533 if (caml_string_length (Field (params_v, 8)) > 0) {
4534 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4536 if (!state.trimcachepath) {
4537 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4538 strerror (errno));
4542 haspboext = Bool_val (Field (params_v, 9));
4544 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4545 fz_register_document_handlers (state.ctx);
4547 #ifdef USE_FONTCONFIG
4548 if (Bool_val (Field (params_v, 11))) {
4549 fz_install_load_system_font_funcs (
4550 state.ctx, fc_load_system_font_func, NULL
4553 #endif
4555 state.trimmargins = Bool_val (Field (trim_v, 0));
4556 fuzz_v = Field (trim_v, 1);
4557 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4558 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4559 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4560 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4562 set_tex_params (colorspace);
4564 if (*fontpath) {
4565 #ifndef USE_FONTCONFIG
4566 state.face = load_font (fontpath);
4567 #else
4568 FcChar8 *path;
4569 FcResult result;
4570 char *buf = fontpath;
4571 FcPattern *pat, *pat1;
4573 fc.inited = 1;
4574 fc.config = FcInitLoadConfigAndFonts ();
4575 if (!fc.config) {
4576 errx (1, "FcInitLoadConfigAndFonts failed");
4579 pat = FcNameParse ((FcChar8 *) buf);
4580 if (!pat) {
4581 errx (1, "FcNameParse failed");
4584 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4585 errx (1, "FcConfigSubstitute failed");
4587 FcDefaultSubstitute (pat);
4589 pat1 = FcFontMatch (fc.config, pat, &result);
4590 if (!pat1) {
4591 errx (1, "FcFontMatch failed");
4594 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4595 errx (1, "FcPatternGetString failed");
4598 state.face = load_font ((char *) path);
4599 FcPatternDestroy (pat);
4600 FcPatternDestroy (pat1);
4601 #endif
4603 else {
4604 int len;
4605 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4606 0, 0, &len);
4607 state.face = load_builtin_font (data, len);
4609 if (!state.face) _exit (1);
4611 realloctexts (texcount);
4613 if (haspboext) {
4614 setuppbo ();
4617 makestippletex ();
4619 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4620 if (ret) {
4621 errx (1, "pthread_create: %s", strerror (ret));
4624 CAMLreturn (Val_unit);