Proper handling of both external and internal links
[llpp.git] / link.c
blob6a89b9c4158015a2afccc0adbf8398ca32435b21
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/time.h>
16 #include <sys/types.h>
17 #include <sys/ioctl.h>
18 #include <sys/utsname.h>
20 #ifdef __CYGWIN__
21 #include <cygwin/socket.h> /* FIONREAD */
22 #else
23 #include <spawn.h>
24 #endif
26 #include <regex.h>
27 #include <stdarg.h>
28 #include <limits.h>
29 #include <inttypes.h>
31 #include <GL/gl.h>
33 #include <caml/fail.h>
34 #include <caml/alloc.h>
35 #include <caml/memory.h>
36 #include <caml/unixsupport.h>
38 #if __GNUC__ < 5 && !defined __clang__
39 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
40 clobbered diagnostics */
41 #pragma GCC diagnostic ignored "-Wclobbered"
42 #endif
44 #include <mupdf/fitz.h>
45 #include <mupdf/pdf.h>
47 #include <ft2build.h>
48 #include FT_FREETYPE_H
50 #ifdef USE_FONTCONFIG
51 #include <fontconfig/fontconfig.h>
52 #endif
54 #define PIGGYBACK
55 #define CACHE_PAGEREFS
57 #ifndef __USE_GNU
58 extern char **environ;
59 #endif
61 #if defined __GNUC__
62 #define NORETURN_ATTR __attribute__ ((noreturn))
63 #define UNUSED_ATTR __attribute__ ((unused))
64 #if !defined __clang__
65 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
66 #else
67 #define OPTIMIZE_ATTR(n)
68 #endif
69 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
70 #else
71 #define NORETURN_ATTR
72 #define UNUSED_ATTR
73 #define OPTIMIZE_ATTR(n)
74 #define GCC_FMT_ATTR(a, b)
75 #endif
77 #define FMT_s "zu"
79 #define FMT_ptr PRIxPTR
80 #define SCN_ptr SCNxPTR
81 #define FMT_ptr_cast(p) ((uintptr_t) (p))
82 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
84 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
85 err (int exitcode, const char *fmt, ...)
87 va_list ap;
88 int savederrno;
90 savederrno = errno;
91 va_start (ap, fmt);
92 vfprintf (stderr, fmt, ap);
93 va_end (ap);
94 fprintf (stderr, ": %s\n", strerror (savederrno));
95 fflush (stderr);
96 _exit (exitcode);
99 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
100 errx (int exitcode, const char *fmt, ...)
102 va_list ap;
104 va_start (ap, fmt);
105 vfprintf (stderr, fmt, ap);
106 va_end (ap);
107 fputc ('\n', stderr);
108 fflush (stderr);
109 _exit (exitcode);
112 #ifndef GL_TEXTURE_RECTANGLE_ARB
113 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
114 #endif
116 #ifdef USE_NPOT
117 #define TEXT_TYPE GL_TEXTURE_2D
118 #else
119 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
120 #endif
122 #ifndef GL_BGRA
123 #define GL_BGRA 0x80E1
124 #endif
126 #ifndef GL_UNSIGNED_INT_8_8_8_8
127 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
128 #endif
130 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
131 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
132 #endif
134 #if 0
135 #define lprintf printf
136 #else
137 #define lprintf(...)
138 #endif
140 #define ARSERT(cond) for (;;) { \
141 if (!(cond)) { \
142 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
144 break; \
147 struct slice {
148 int h;
149 int texindex;
152 struct tile {
153 int w, h;
154 int slicecount;
155 int sliceheight;
156 struct bo *pbo;
157 fz_pixmap *pixmap;
158 struct slice slices[1];
161 struct pagedim {
162 int pageno;
163 int rotate;
164 int left;
165 int tctmready;
166 fz_irect bounds;
167 fz_rect pagebox;
168 fz_rect mediabox;
169 fz_matrix ctm, zoomctm, tctm;
172 struct slink {
173 enum { SLINK, SANNOT } tag;
174 fz_irect bbox;
175 union {
176 fz_link *link;
177 fz_annot *annot;
178 } u;
181 struct annot {
182 fz_irect bbox;
183 fz_annot *annot;
186 struct page {
187 int tgen;
188 int sgen;
189 int agen;
190 int pageno;
191 int pdimno;
192 fz_stext_page *text;
193 fz_stext_sheet *sheet;
194 fz_page *fzpage;
195 fz_display_list *dlist;
196 int slinkcount;
197 struct slink *slinks;
198 int annotcount;
199 struct annot *annots;
200 struct mark {
201 int i;
202 fz_stext_span *span;
203 } fmark, lmark;
206 struct {
207 int sliceheight;
208 struct pagedim *pagedims;
209 int pagecount;
210 int pagedimcount;
211 fz_document *doc;
212 fz_context *ctx;
213 int w, h;
215 int texindex;
216 int texcount;
217 GLuint *texids;
219 GLenum texiform;
220 GLenum texform;
221 GLenum texty;
223 fz_colorspace *colorspace;
225 struct {
226 int w, h;
227 struct slice *slice;
228 } *texowners;
230 int rotate;
231 enum { FitWidth, FitProportional, FitPage } fitmodel;
232 int trimmargins;
233 int needoutline;
234 int gen;
235 int aalevel;
237 int trimanew;
238 fz_irect trimfuzz;
239 fz_pixmap *pig;
241 pthread_t thread;
242 int csock;
243 FT_Face face;
245 char *trimcachepath;
246 int cxack;
247 int dirty;
249 GLuint stid;
251 int bo_usable;
252 GLuint boid;
254 void (*glBindBufferARB) (GLenum, GLuint);
255 GLboolean (*glUnmapBufferARB) (GLenum);
256 void *(*glMapBufferARB) (GLenum, GLenum);
257 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
258 void (*glGenBuffersARB) (GLsizei, GLuint *);
259 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
261 GLfloat texcoords[8];
262 GLfloat vertices[16];
264 #ifdef CACHE_PAGEREFS
265 struct {
266 int idx;
267 int count;
268 pdf_obj **objs;
269 pdf_document *pdf;
270 } pdflut;
271 #endif
272 } state;
274 struct bo {
275 GLuint id;
276 void *ptr;
277 size_t size;
280 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
282 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
285 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
287 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
290 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
292 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
293 m.a, m.b, m.c, m.d, m.e, m.f);
296 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
298 static void lock (const char *cap)
300 int ret = pthread_mutex_lock (&mutex);
301 if (ret) {
302 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
306 static void unlock (const char *cap)
308 int ret = pthread_mutex_unlock (&mutex);
309 if (ret) {
310 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
314 static int trylock (const char *cap)
316 int ret = pthread_mutex_trylock (&mutex);
317 if (ret && ret != EBUSY) {
318 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
320 return ret == EBUSY;
323 static void *parse_pointer (const char *cap, const char *s)
325 int ret;
326 void *ptr;
328 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
329 if (ret != 1) {
330 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
332 return ptr;
335 static double now (void)
337 struct timeval tv;
339 if (gettimeofday (&tv, NULL)) {
340 err (1, "gettimeofday");
342 return tv.tv_sec + tv.tv_usec*1e-6;
345 static int hasdata (void)
347 int ret, avail;
348 ret = ioctl (state.csock, FIONREAD, &avail);
349 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
350 return avail > 0;
353 CAMLprim value ml_hasdata (value fd_v)
355 CAMLparam1 (fd_v);
356 int ret, avail;
358 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
359 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
360 CAMLreturn (Val_bool (avail > 0));
363 static void readdata (int fd, void *p, int size)
365 ssize_t n;
367 again:
368 n = read (fd, p, size);
369 if (n < 0) {
370 if (errno == EINTR) goto again;
371 err (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
373 if (n - size) {
374 if (!n) errx (1, "EOF while reading");
375 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
379 static void writedata (int fd, char *p, int size)
381 ssize_t n;
383 /* One should lookup type punning/strict aliasing etc in standard,DRs,Web to
384 convince herself that this is:
385 a. safe
386 b. practically the only way to achieve the result
387 (union puns notwithstanding) */
388 memcpy (p, &size, 4);
389 n = write (fd, p, size + 4);
390 if (n - size - 4) {
391 if (!n) errx (1, "EOF while writing data");
392 err (1, "write (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 { int 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 + 4, size - 4, fmt, ap);
435 va_end (ap);
437 if (len > -1) {
438 if (len < size - 4) {
439 writedata (state.csock, buf, len);
440 break;
442 else size = len + 5;
444 else {
445 err (1, "vsnprintf for `%s' failed", fmt);
447 buf = realloc (buf, size);
449 free (buf);
452 static void closedoc (void)
454 #ifdef CACHE_PAGEREFS
455 if (state.pdflut.objs) {
456 int i;
458 for (i = 0; i < state.pdflut.count; ++i) {
459 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
461 free (state.pdflut.objs);
462 state.pdflut.objs = NULL;
463 state.pdflut.idx = 0;
465 #endif
466 if (state.doc) {
467 fz_drop_document (state.ctx, state.doc);
468 state.doc = NULL;
472 static int openxref (char *filename, char *password)
474 int i;
476 for (i = 0; i < state.texcount; ++i) {
477 state.texowners[i].w = -1;
478 state.texowners[i].slice = NULL;
481 closedoc ();
483 state.dirty = 0;
484 if (state.pagedims) {
485 free (state.pagedims);
486 state.pagedims = NULL;
488 state.pagedimcount = 0;
490 fz_set_aa_level (state.ctx, state.aalevel);
491 #ifdef CSS_HACK_TO_READ_EPUBS_COMFORTABLY
492 fz_set_user_css (state.ctx,
493 "body { margin-left: 20%; margin-right: 20%; }");
494 #endif
495 state.doc = fz_open_document (state.ctx, filename);
496 if (fz_needs_password (state.ctx, state.doc)) {
497 if (password && !*password) {
498 printd ("pass");
499 return 0;
501 else {
502 int ok = fz_authenticate_password (state.ctx, state.doc, password);
503 if (!ok) {
504 printd ("pass fail");
505 return 0;
509 state.pagecount = fz_count_pages (state.ctx, state.doc);
510 return 1;
513 static void pdfinfo (void)
515 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
516 if (pdf) {
517 pdf_obj *infoobj;
519 printd ("info PDF version\t%d.%d",
520 pdf->version / 10, pdf->version % 10);
522 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
523 pdf), "Info");
524 if (infoobj) {
525 unsigned int i;
526 char *s;
527 char *items[] = { "Title", "Author", "Creator",
528 "Producer", "CreationDate" };
530 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
531 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
532 s = pdf_to_utf8 (state.ctx, obj);
533 if (*s) printd ("info %s\t%s", items[i], s);
534 fz_free (state.ctx, s);
537 printd ("infoend");
541 static void unlinktile (struct tile *tile)
543 int i;
545 for (i = 0; i < tile->slicecount; ++i) {
546 struct slice *s = &tile->slices[i];
548 if (s->texindex != -1) {
549 if (state.texowners[s->texindex].slice == s) {
550 state.texowners[s->texindex].slice = NULL;
556 static void freepage (struct page *page)
558 if (!page) return;
559 if (page->text) {
560 fz_drop_stext_page (state.ctx, page->text);
562 if (page->sheet) {
563 fz_drop_stext_sheet (state.ctx, page->sheet);
565 if (page->slinks) {
566 free (page->slinks);
568 fz_drop_display_list (state.ctx, page->dlist);
569 fz_drop_page (state.ctx, page->fzpage);
570 free (page);
573 static void freetile (struct tile *tile)
575 unlinktile (tile);
576 if (!tile->pbo) {
577 #ifndef PIGGYBACK
578 fz_drop_pixmap (state.ctx, tile->pixmap);
579 #else
580 if (state.pig) {
581 fz_drop_pixmap (state.ctx, state.pig);
583 state.pig = tile->pixmap;
584 #endif
586 else {
587 free (tile->pbo);
588 fz_drop_pixmap (state.ctx, tile->pixmap);
590 free (tile);
593 #ifdef __ALTIVEC__
594 #include <stdint.h>
595 #include <altivec.h>
597 static int cacheline32bytes;
599 static void __attribute__ ((constructor)) clcheck (void)
601 char **envp = environ;
602 unsigned long *auxv;
604 while (*envp++);
606 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
607 if (*auxv == 19) {
608 cacheline32bytes = auxv[1] == 32;
609 return;
614 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
616 size_t size = pixmap->w * pixmap->h * pixmap->n;
617 if (cacheline32bytes && size > 32) {
618 intptr_t a1, a2, diff;
619 size_t sizea, i;
620 vector unsigned char v = vec_splat_u8 (-1);
621 vector unsigned char *p;
623 a1 = a2 = (intptr_t) pixmap->samples;
624 a2 = (a1 + 31) & ~31;
625 diff = a2 - a1;
626 sizea = size - diff;
627 p = (void *) a2;
629 while (a1 != a2) *(char *) a1++ = 0xff;
630 for (i = 0; i < (sizea & ~31); i += 32) {
631 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
632 vec_st (v, i, p);
633 vec_st (v, i + 16, p);
635 while (i < sizea) *((char *) a1 + i++) = 0xff;
637 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
639 #else
640 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
641 #endif
643 static void trimctm (pdf_page *page, int pindex)
645 fz_matrix ctm;
646 struct pagedim *pdim = &state.pagedims[pindex];
648 if (!page) return;
649 if (!pdim->tctmready) {
650 fz_rect realbox, mediabox;
651 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
653 fz_rotate (&rm, -pdim->rotate);
654 fz_scale (&sm, 1, -1);
655 fz_concat (&ctm, &rm, &sm);
656 realbox = pdim->mediabox;
657 fz_transform_rect (&realbox, &ctm);
658 fz_translate (&tm, -realbox.x0, -realbox.y0);
659 fz_concat (&ctm1, &ctm, &tm);
660 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
661 fz_invert_matrix (&im, &page_ctm);
662 fz_concat (&ctm, &im, &ctm1);
663 pdim->tctm = ctm;
664 pdim->tctmready = 1;
668 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
670 fz_matrix ctm, tm;
671 int pdimno = pdim - state.pagedims;
673 if (pdf_specifics (state.ctx, state.doc)) {
674 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
675 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
677 else {
678 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
679 fz_concat (&ctm, &tm, &pdim->ctm);
681 return ctm;
684 static fz_matrix pagectm (struct page *page)
686 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
689 static void *loadpage (int pageno, int pindex)
691 fz_device *dev;
692 struct page *page;
694 page = calloc (sizeof (struct page), 1);
695 if (!page) {
696 err (1, "calloc page %d", pageno);
699 page->dlist = fz_new_display_list (state.ctx, NULL);
700 dev = fz_new_list_device (state.ctx, page->dlist);
701 fz_try (state.ctx) {
702 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
703 fz_run_page (state.ctx, page->fzpage, dev,
704 &fz_identity, NULL);
706 fz_catch (state.ctx) {
707 page->fzpage = NULL;
709 fz_close_device (state.ctx, dev);
710 fz_drop_device (state.ctx, dev);
712 page->pdimno = pindex;
713 page->pageno = pageno;
714 page->sgen = state.gen;
715 page->agen = state.gen;
716 page->tgen = state.gen;
717 return page;
720 static struct tile *alloctile (int h)
722 int i;
723 int slicecount;
724 size_t tilesize;
725 struct tile *tile;
727 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
728 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
729 tile = calloc (tilesize, 1);
730 if (!tile) {
731 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
733 for (i = 0; i < slicecount; ++i) {
734 int sh = fz_mini (h, state.sliceheight);
735 tile->slices[i].h = sh;
736 tile->slices[i].texindex = -1;
737 h -= sh;
739 tile->slicecount = slicecount;
740 tile->sliceheight = state.sliceheight;
741 return tile;
744 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
745 struct bo *pbo)
747 fz_rect rect;
748 fz_irect bbox;
749 fz_matrix ctm;
750 fz_device *dev;
751 struct tile *tile;
752 struct pagedim *pdim;
754 tile = alloctile (h);
755 pdim = &state.pagedims[page->pdimno];
757 bbox = pdim->bounds;
758 bbox.x0 += x;
759 bbox.y0 += y;
760 bbox.x1 = bbox.x0 + w;
761 bbox.y1 = bbox.y0 + h;
763 if (state.pig) {
764 if (state.pig->w == w
765 && state.pig->h == h
766 && state.pig->colorspace == state.colorspace) {
767 tile->pixmap = state.pig;
768 tile->pixmap->x = bbox.x0;
769 tile->pixmap->y = bbox.y0;
771 else {
772 fz_drop_pixmap (state.ctx, state.pig);
774 state.pig = NULL;
776 if (!tile->pixmap) {
777 if (pbo) {
778 tile->pixmap =
779 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
780 &bbox, 1, pbo->ptr);
781 tile->pbo = pbo;
783 else {
784 tile->pixmap =
785 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
789 tile->w = w;
790 tile->h = h;
791 clearpixmap (tile->pixmap);
793 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
794 ctm = pagectm (page);
795 fz_rect_from_irect (&rect, &bbox);
796 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
797 fz_close_device (state.ctx, dev);
798 fz_drop_device (state.ctx, dev);
800 return tile;
803 #ifdef CACHE_PAGEREFS
804 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
805 thanks to Robin Watts */
806 static void
807 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
809 fz_context *ctx = state.ctx; /* doc->ctx; */
810 pdf_obj *kids;
811 int i, len;
813 if (state.pdflut.idx == state.pagecount) return;
815 kids = pdf_dict_gets (ctx, node, "Kids");
816 len = pdf_array_len (ctx, kids);
818 if (len == 0)
819 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
821 if (pdf_mark_obj (ctx, node))
822 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
823 for (i = 0; i < len; i++) {
824 pdf_obj *kid = pdf_array_get (ctx, kids, i);
825 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
826 if (*type
827 ? !strcmp (type, "Pages")
828 : pdf_dict_gets (ctx, kid, "Kids")
829 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
830 pdf_collect_pages (doc, kid);
832 else {
833 if (*type
834 ? strcmp (type, "Page") != 0
835 : !pdf_dict_gets (ctx, kid, "MediaBox"))
836 fz_warn (ctx, "non-page object in page tree (%s)", type);
837 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
840 pdf_unmark_obj (ctx, node);
843 static void
844 pdf_load_page_objs (pdf_document *doc)
846 pdf_obj *root = pdf_dict_gets (state.ctx,
847 pdf_trailer (state.ctx, doc), "Root");
848 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
850 if (!node)
851 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
853 state.pdflut.idx = 0;
854 pdf_collect_pages (doc, node);
856 #endif
858 static void initpdims (int wthack)
860 double start, end;
861 FILE *trimf = NULL;
862 fz_rect rootmediabox;
863 int pageno, trim, show;
864 int trimw = 0, cxcount;
865 fz_context *ctx = state.ctx;
866 pdf_document *pdf = pdf_specifics (ctx, state.doc);
868 fz_var (trimw);
869 fz_var (trimf);
870 fz_var (cxcount);
871 start = now ();
873 if (state.trimmargins && state.trimcachepath) {
874 trimf = fopen (state.trimcachepath, "rb");
875 if (!trimf) {
876 trimf = fopen (state.trimcachepath, "wb");
877 trimw = 1;
881 if (state.trimmargins || pdf || !state.cxack)
882 cxcount = state.pagecount;
883 else
884 cxcount = fz_mini (state.pagecount, 1);
886 if (pdf) {
887 pdf_obj *obj;
888 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
889 "Root/Pages/MediaBox");
890 pdf_to_rect (ctx, obj, &rootmediabox);
893 #ifdef CACHE_PAGEREFS
894 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
895 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
896 if (!state.pdflut.objs) {
897 err (1, "malloc pageobjs %zu %d %zu failed",
898 sizeof (*state.pdflut.objs), cxcount,
899 sizeof (*state.pdflut.objs) * cxcount);
901 state.pdflut.count = cxcount;
902 pdf_load_page_objs (pdf);
903 state.pdflut.pdf = pdf;
905 #endif
907 for (pageno = 0; pageno < cxcount; ++pageno) {
908 int rotate = 0;
909 struct pagedim *p;
910 fz_rect mediabox;
912 fz_var (rotate);
913 if (pdf) {
914 pdf_obj *pageref, *pageobj;
916 #ifdef CACHE_PAGEREFS
917 pageref = state.pdflut.objs[pageno];
918 #else
919 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
920 #endif
921 pageobj = pdf_resolve_indirect (ctx, pageref);
922 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
924 if (state.trimmargins) {
925 pdf_obj *obj;
926 pdf_page *page;
928 fz_try (ctx) {
929 page = pdf_load_page (ctx, pdf, pageno);
930 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
931 trim = state.trimanew || !obj;
932 if (trim) {
933 fz_rect rect;
934 fz_device *dev;
935 fz_matrix ctm, page_ctm;
937 dev = fz_new_bbox_device (ctx, &rect);
938 dev->hints |= FZ_IGNORE_SHADE;
939 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
940 fz_invert_matrix (&ctm, &page_ctm);
941 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
942 fz_close_device (ctx, dev);
943 fz_drop_device (ctx, dev);
945 rect.x0 += state.trimfuzz.x0;
946 rect.x1 += state.trimfuzz.x1;
947 rect.y0 += state.trimfuzz.y0;
948 rect.y1 += state.trimfuzz.y1;
949 fz_transform_rect (&rect, &ctm);
950 fz_intersect_rect (&rect, &mediabox);
952 if (!fz_is_empty_rect (&rect)) {
953 mediabox = rect;
956 obj = pdf_new_array (ctx, pdf, 4);
957 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
958 mediabox.x0));
959 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
960 mediabox.y0));
961 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
962 mediabox.x1));
963 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
964 mediabox.y1));
965 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
967 else {
968 mediabox.x0 = pdf_to_real (ctx,
969 pdf_array_get (ctx, obj, 0));
970 mediabox.y0 = pdf_to_real (ctx,
971 pdf_array_get (ctx, obj, 1));
972 mediabox.x1 = pdf_to_real (ctx,
973 pdf_array_get (ctx, obj, 2));
974 mediabox.y1 = pdf_to_real (ctx,
975 pdf_array_get (ctx, obj, 3));
978 fz_drop_page (ctx, &page->super);
979 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
980 if (show) {
981 printd ("progress %f Trimming %d",
982 (double) (pageno + 1) / state.pagecount,
983 pageno + 1);
986 fz_catch (ctx) {
987 fprintf (stderr, "failed to load page %d\n", pageno+1);
990 else {
991 int empty = 0;
992 fz_rect cropbox;
994 pdf_to_rect (ctx,
995 pdf_dict_gets (ctx, pageobj, "MediaBox"),
996 &mediabox);
997 if (fz_is_empty_rect (&mediabox)) {
998 mediabox.x0 = 0;
999 mediabox.y0 = 0;
1000 mediabox.x1 = 612;
1001 mediabox.y1 = 792;
1002 empty = 1;
1005 pdf_to_rect (ctx,
1006 pdf_dict_gets (ctx, pageobj, "CropBox"),
1007 &cropbox);
1008 if (!fz_is_empty_rect (&cropbox)) {
1009 if (empty) {
1010 mediabox = cropbox;
1012 else {
1013 fz_intersect_rect (&mediabox, &cropbox);
1016 else {
1017 if (empty) {
1018 if (fz_is_empty_rect (&rootmediabox)) {
1019 fprintf (stderr,
1020 "cannot find page size for page %d\n",
1021 pageno+1);
1023 else {
1024 mediabox = rootmediabox;
1030 else {
1031 if (state.trimmargins && trimw) {
1032 fz_page *page;
1034 fz_try (ctx) {
1035 page = fz_load_page (ctx, state.doc, pageno);
1036 fz_bound_page (ctx, page, &mediabox);
1037 if (state.trimmargins) {
1038 fz_rect rect;
1039 fz_device *dev;
1041 dev = fz_new_bbox_device (ctx, &rect);
1042 dev->hints |= FZ_IGNORE_SHADE;
1043 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1044 fz_close_device (ctx, dev);
1045 fz_drop_device (ctx, dev);
1047 rect.x0 += state.trimfuzz.x0;
1048 rect.x1 += state.trimfuzz.x1;
1049 rect.y0 += state.trimfuzz.y0;
1050 rect.y1 += state.trimfuzz.y1;
1051 fz_intersect_rect (&rect, &mediabox);
1053 if (!fz_is_empty_rect (&rect)) {
1054 mediabox = rect;
1057 fz_drop_page (ctx, page);
1058 if (!state.cxack) {
1059 printd ("progress %f loading %d",
1060 (double) (pageno + 1) / state.pagecount,
1061 pageno + 1);
1064 fz_catch (ctx) {
1066 if (trimf) {
1067 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1068 if (n - 1) {
1069 err (1, "fwrite trim mediabox");
1073 else {
1074 if (trimf) {
1075 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1076 if (n - 1) {
1077 err (1, "fread trim mediabox %d", pageno);
1080 else {
1081 fz_page *page;
1082 fz_try (ctx) {
1083 page = fz_load_page (ctx, state.doc, pageno);
1084 fz_bound_page (ctx, page, &mediabox);
1085 fz_drop_page (ctx, page);
1087 show = !state.trimmargins && pageno % 20 == 0;
1088 if (show) {
1089 printd ("progress %f Gathering dimensions %d",
1090 (double) (pageno) / state.pagecount,
1091 pageno);
1094 fz_catch (ctx) {
1095 fprintf (stderr, "failed to load page %d\n", pageno);
1101 if (state.pagedimcount == 0
1102 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1103 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1104 size_t size;
1106 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1107 state.pagedims = realloc (state.pagedims, size);
1108 if (!state.pagedims) {
1109 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1110 size, state.pagedimcount + 1);
1113 p = &state.pagedims[state.pagedimcount++];
1114 p->rotate = rotate;
1115 p->mediabox = mediabox;
1116 p->pageno = pageno;
1119 end = now ();
1120 if (!wthack) {
1121 printd ("progress 1 %s %d pages in %f seconds",
1122 state.trimmargins ? "Trimmed" : "Processed",
1123 state.pagecount, end - start);
1125 state.trimanew = 0;
1126 if (trimf) {
1127 if (fclose (trimf)) {
1128 err (1, "fclose");
1133 static void layout (void)
1135 int pindex;
1136 fz_rect box;
1137 fz_matrix ctm, rm;
1138 struct pagedim *p = p;
1139 double zw, w, maxw = 0.0, zoom = zoom;
1141 if (state.pagedimcount == 0) return;
1143 switch (state.fitmodel) {
1144 case FitProportional:
1145 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1146 double x0, x1;
1148 p = &state.pagedims[pindex];
1149 fz_rotate (&rm, p->rotate + state.rotate);
1150 box = p->mediabox;
1151 fz_transform_rect (&box, &rm);
1153 x0 = fz_min (box.x0, box.x1);
1154 x1 = fz_max (box.x0, box.x1);
1156 w = x1 - x0;
1157 maxw = fz_max (w, maxw);
1158 zoom = state.w / maxw;
1160 break;
1162 case FitPage:
1163 maxw = state.w;
1164 break;
1166 case FitWidth:
1167 break;
1169 default:
1170 ARSERT (0 && state.fitmodel);
1173 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1174 fz_rect rect;
1175 fz_matrix tm, sm;
1177 p = &state.pagedims[pindex];
1178 fz_rotate (&ctm, state.rotate);
1179 fz_rotate (&rm, p->rotate + state.rotate);
1180 box = p->mediabox;
1181 fz_transform_rect (&box, &rm);
1182 w = box.x1 - box.x0;
1183 switch (state.fitmodel) {
1184 case FitProportional:
1185 p->left = ((maxw - w) * zoom) / 2.0;
1186 break;
1187 case FitPage:
1189 double zh, h;
1190 zw = maxw / w;
1191 h = box.y1 - box.y0;
1192 zh = state.h / h;
1193 zoom = fz_min (zw, zh);
1194 p->left = (maxw - (w * zoom)) / 2.0;
1196 break;
1197 case FitWidth:
1198 p->left = 0;
1199 zoom = state.w / w;
1200 break;
1203 fz_scale (&p->zoomctm, zoom, zoom);
1204 fz_concat (&ctm, &p->zoomctm, &ctm);
1206 fz_rotate (&rm, p->rotate);
1207 p->pagebox = p->mediabox;
1208 fz_transform_rect (&p->pagebox, &rm);
1209 p->pagebox.x1 -= p->pagebox.x0;
1210 p->pagebox.y1 -= p->pagebox.y0;
1211 p->pagebox.x0 = 0;
1212 p->pagebox.y0 = 0;
1213 rect = p->pagebox;
1214 fz_transform_rect (&rect, &ctm);
1215 fz_round_rect (&p->bounds, &rect);
1216 p->ctm = ctm;
1218 fz_translate (&tm, 0, -p->mediabox.y1);
1219 fz_scale (&sm, zoom, -zoom);
1220 fz_concat (&ctm, &tm, &sm);
1222 p->tctmready = 0;
1225 do {
1226 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1227 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1228 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1229 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1230 int boundw = x1 - x0;
1231 int boundh = y1 - y0;
1233 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1234 } while (p-- != state.pagedims);
1237 struct pagedim *pdimofpageno (int pageno)
1239 int i;
1240 struct pagedim *pdim = state.pagedims;
1242 for (i = 0; i < state.pagedimcount; ++i) {
1243 if (state.pagedims[i].pageno > pageno)
1244 break;
1245 pdim = &state.pagedims[i];
1247 return pdim;
1250 static
1251 struct anchor { int n; int x; int y; int w; int h; }
1252 uritoanchor (const char *uri)
1254 fz_point p;
1255 struct anchor a;
1257 a.n = -1;
1258 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1259 if (a.n >= 0) {
1260 struct pagedim *pdim = pdimofpageno (a.n);
1261 fz_transform_point (&p, &pdim->ctm);
1262 a.x = p.x;
1263 a.y = p.y;
1264 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1266 return a;
1269 static void recurse_outline (fz_outline *outline, int level)
1271 while (outline) {
1272 struct anchor a = uritoanchor (outline->uri);
1273 if (a.n >= 0) {
1274 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1276 else {
1277 printd ("on %d %s", level, outline->title);
1279 if (outline->down) {
1280 recurse_outline (outline->down, level + 1);
1282 outline = outline->next;
1286 static void process_outline (void)
1288 fz_outline *outline;
1290 if (!state.needoutline || !state.pagedimcount) return;
1292 state.needoutline = 0;
1293 outline = fz_load_outline (state.ctx, state.doc);
1294 if (outline) {
1295 recurse_outline (outline, 0);
1296 fz_drop_outline (state.ctx, outline);
1300 static char *strofspan (fz_stext_span *span)
1302 char *p;
1303 char utf8[10];
1304 fz_stext_char *ch;
1305 size_t size = 0, cap = 80;
1307 p = malloc (cap + 1);
1308 if (!p) return NULL;
1310 for (ch = span->text; ch < span->text + span->len; ++ch) {
1311 int n = fz_runetochar (utf8, ch->c);
1312 if (size + n > cap) {
1313 cap *= 2;
1314 p = realloc (p, cap + 1);
1315 if (!p) return NULL;
1318 memcpy (p + size, utf8, n);
1319 size += n;
1321 p[size] = 0;
1322 return p;
1325 static int matchspan (regex_t *re, fz_stext_span *span,
1326 int stop, int pageno, double start)
1328 int ret;
1329 char *p;
1330 regmatch_t rm;
1331 int a, b, c;
1332 fz_rect sb, eb;
1333 fz_point p1, p2, p3, p4;
1335 p = strofspan (span);
1336 if (!p) return -1;
1338 ret = regexec (re, p, 1, &rm, 0);
1339 if (ret) {
1340 free (p);
1341 if (ret != REG_NOMATCH) {
1342 size_t size;
1343 char errbuf[80];
1344 size = regerror (ret, re, errbuf, sizeof (errbuf));
1345 printd ("msg regexec error `%.*s'",
1346 (int) size, errbuf);
1347 return -1;
1349 return 0;
1351 else {
1352 int l = span->len;
1354 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1355 c += fz_runelen (span->text[a].c);
1357 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1358 c += fz_runelen (span->text[b].c);
1361 if (fz_runelen (span->text[b].c) > 1) {
1362 b = fz_maxi (0, b-1);
1365 fz_stext_char_bbox (state.ctx, &sb, span, a);
1366 fz_stext_char_bbox (state.ctx, &eb, span, b);
1368 p1.x = sb.x0;
1369 p1.y = sb.y0;
1370 p2.x = eb.x1;
1371 p2.y = sb.y0;
1372 p3.x = eb.x1;
1373 p3.y = eb.y1;
1374 p4.x = sb.x0;
1375 p4.y = eb.y1;
1377 if (!stop) {
1378 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1379 pageno, 1,
1380 p1.x, p1.y,
1381 p2.x, p2.y,
1382 p3.x, p3.y,
1383 p4.x, p4.y);
1385 printd ("progress 1 found at %d `%.*s' in %f sec",
1386 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1387 now () - start);
1389 else {
1390 printd ("match %d %d %f %f %f %f %f %f %f %f",
1391 pageno, 2,
1392 p1.x, p1.y,
1393 p2.x, p2.y,
1394 p3.x, p3.y,
1395 p4.x, p4.y);
1397 free (p);
1398 return 1;
1402 static int compareblocks (const void *l, const void *r)
1404 fz_stext_block const *ls = l;
1405 fz_stext_block const *rs = r;
1406 return ls->bbox.y0 - rs->bbox.y0;
1409 /* wishful thinking function */
1410 static void search (regex_t *re, int pageno, int y, int forward)
1412 int j;
1413 fz_device *tdev;
1414 fz_stext_page *text;
1415 fz_stext_sheet *sheet;
1416 struct pagedim *pdim;
1417 int stop = 0, niters = 0;
1418 double start, end;
1419 fz_page *page;
1421 start = now ();
1422 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1423 if (niters++ == 5) {
1424 niters = 0;
1425 if (hasdata ()) {
1426 printd ("progress 1 attention requested aborting search at %d",
1427 pageno);
1428 stop = 1;
1430 else {
1431 printd ("progress %f searching in page %d",
1432 (double) (pageno + 1) / state.pagecount,
1433 pageno);
1436 pdim = pdimofpageno (pageno);
1437 sheet = fz_new_stext_sheet (state.ctx);
1438 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1439 tdev = fz_new_stext_device (state.ctx, sheet, text, 0);
1441 page = fz_load_page (state.ctx, state.doc, pageno);
1443 fz_matrix ctm = pagectm1 (page, pdim);
1444 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1447 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1448 fz_close_device (state.ctx, tdev);
1449 fz_drop_device (state.ctx, tdev);
1451 for (j = 0; j < text->len; ++j) {
1452 int k;
1453 fz_page_block *pb;
1454 fz_stext_block *block;
1456 pb = &text->blocks[forward ? j : text->len - 1 - j];
1457 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1458 block = pb->u.text;
1460 for (k = 0; k < block->len; ++k) {
1461 fz_stext_line *line;
1462 fz_stext_span *span;
1464 if (forward) {
1465 line = &block->lines[k];
1466 if (line->bbox.y0 < y + 1) continue;
1468 else {
1469 line = &block->lines[block->len - 1 - k];
1470 if (line->bbox.y0 > y - 1) continue;
1473 for (span = line->first_span; span; span = span->next) {
1474 switch (matchspan (re, span, stop, pageno, start)) {
1475 case 0: break;
1476 case 1: stop = 1; break;
1477 case -1: stop = 1; goto endloop;
1482 if (forward) {
1483 pageno += 1;
1484 y = 0;
1486 else {
1487 pageno -= 1;
1488 y = INT_MAX;
1490 endloop:
1491 fz_drop_stext_page (state.ctx, text);
1492 fz_drop_stext_sheet (state.ctx, sheet);
1493 fz_drop_page (state.ctx, page);
1495 end = now ();
1496 if (!stop) {
1497 printd ("progress 1 no matches %f sec", end - start);
1499 printd ("clearrects");
1502 static void set_tex_params (int colorspace)
1504 union {
1505 unsigned char b;
1506 unsigned int s;
1507 } endianness = {1};
1509 switch (colorspace) {
1510 case 0:
1511 state.texiform = GL_RGBA8;
1512 state.texform = GL_RGBA;
1513 state.texty = GL_UNSIGNED_BYTE;
1514 state.colorspace = fz_device_rgb (state.ctx);
1515 break;
1516 case 1:
1517 state.texiform = GL_RGBA8;
1518 state.texform = GL_BGRA;
1519 state.texty = endianness.s > 1
1520 ? GL_UNSIGNED_INT_8_8_8_8
1521 : GL_UNSIGNED_INT_8_8_8_8_REV;
1522 state.colorspace = fz_device_bgr (state.ctx);
1523 break;
1524 case 2:
1525 state.texiform = GL_LUMINANCE_ALPHA;
1526 state.texform = GL_LUMINANCE_ALPHA;
1527 state.texty = GL_UNSIGNED_BYTE;
1528 state.colorspace = fz_device_gray (state.ctx);
1529 break;
1530 default:
1531 errx (1, "invalid colorspce %d", colorspace);
1535 static void realloctexts (int texcount)
1537 size_t size;
1539 if (texcount == state.texcount) return;
1541 if (texcount < state.texcount) {
1542 glDeleteTextures (state.texcount - texcount,
1543 state.texids + texcount);
1546 size = texcount * sizeof (*state.texids);
1547 state.texids = realloc (state.texids, size);
1548 if (!state.texids) {
1549 err (1, "realloc texids %" FMT_s, size);
1552 size = texcount * sizeof (*state.texowners);
1553 state.texowners = realloc (state.texowners, size);
1554 if (!state.texowners) {
1555 err (1, "realloc texowners %" FMT_s, size);
1557 if (texcount > state.texcount) {
1558 int i;
1560 glGenTextures (texcount - state.texcount,
1561 state.texids + state.texcount);
1562 for (i = state.texcount; i < texcount; ++i) {
1563 state.texowners[i].w = -1;
1564 state.texowners[i].slice = NULL;
1567 state.texcount = texcount;
1568 state.texindex = 0;
1571 static char *mbtoutf8 (char *s)
1573 char *p, *r;
1574 wchar_t *tmp;
1575 size_t i, ret, len;
1577 len = mbstowcs (NULL, s, strlen (s));
1578 if (len == 0) {
1579 return s;
1581 else {
1582 if (len == (size_t) -1) {
1583 return s;
1587 tmp = malloc (len * sizeof (wchar_t));
1588 if (!tmp) {
1589 return s;
1592 ret = mbstowcs (tmp, s, len);
1593 if (ret == (size_t) -1) {
1594 free (tmp);
1595 return s;
1598 len = 0;
1599 for (i = 0; i < ret; ++i) {
1600 len += fz_runelen (tmp[i]);
1603 p = r = malloc (len + 1);
1604 if (!r) {
1605 free (tmp);
1606 return s;
1609 for (i = 0; i < ret; ++i) {
1610 p += fz_runetochar (p, tmp[i]);
1612 *p = 0;
1613 free (tmp);
1614 return r;
1617 CAMLprim value ml_transform_page_point (value pageno_v, value x_v, value y_v)
1619 CAMLparam3 (pageno_v, x_v, y_v);
1620 CAMLlocal1 (ret_v);
1621 struct pagedim *pdim = pdimofpageno (Int_val (pageno_v));
1622 fz_point p = { .x = Int_val (x_v), .y = Int_val (y_v) };
1624 fz_transform_point (&p, &pdim->ctm);
1626 ret_v = caml_alloc_small (2 * Double_wosize, Double_array_tag);
1627 Store_double_field (ret_v, 0, p.x);
1628 Store_double_field (ret_v, 1, p.y);
1629 CAMLreturn (ret_v);
1633 CAMLprim value ml_mbtoutf8 (value s_v)
1635 CAMLparam1 (s_v);
1636 CAMLlocal1 (ret_v);
1637 char *s, *r;
1639 s = String_val (s_v);
1640 r = mbtoutf8 (s);
1641 if (r == s) {
1642 ret_v = s_v;
1644 else {
1645 ret_v = caml_copy_string (r);
1646 free (r);
1648 CAMLreturn (ret_v);
1651 static void * mainloop (void UNUSED_ATTR *unused)
1653 char *p = NULL;
1654 int len, ret, oldlen = 0;
1656 fz_var (p);
1657 fz_var (oldlen);
1658 for (;;) {
1659 len = readlen (state.csock);
1660 if (len == 0) {
1661 errx (1, "readlen returned 0");
1664 if (oldlen < len + 1) {
1665 p = realloc (p, len + 1);
1666 if (!p) {
1667 err (1, "realloc %d failed", len + 1);
1669 oldlen = len + 1;
1671 readdata (state.csock, p, len);
1672 p[len] = 0;
1674 if (!strncmp ("open", p, 4)) {
1675 int wthack, off, ok = 0;
1676 char *password;
1677 char *filename;
1678 char *utf8filename;
1679 size_t filenamelen;
1681 fz_var (ok);
1682 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1683 if (ret != 2) {
1684 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1687 filename = p + 5 + off;
1688 filenamelen = strlen (filename);
1689 password = filename + filenamelen + 1;
1691 lock ("open");
1692 fz_try (state.ctx) {
1693 ok = openxref (filename, password);
1695 fz_catch (state.ctx) {
1696 utf8filename = mbtoutf8 (filename);
1697 printd ("msg Could not open %s", utf8filename);
1699 if (ok) {
1700 pdfinfo ();
1701 initpdims (wthack);
1703 unlock ("open");
1705 if (ok) {
1706 if (!wthack) {
1707 utf8filename = mbtoutf8 (filename);
1708 printd ("msg Opened %s (press h/F1 to get help)",
1709 utf8filename);
1710 if (utf8filename != filename) {
1711 free (utf8filename);
1714 state.needoutline = 1;
1717 else if (!strncmp ("cs", p, 2)) {
1718 int i, colorspace;
1720 ret = sscanf (p + 2, " %d", &colorspace);
1721 if (ret != 1) {
1722 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1724 lock ("cs");
1725 set_tex_params (colorspace);
1726 for (i = 0; i < state.texcount; ++i) {
1727 state.texowners[i].w = -1;
1728 state.texowners[i].slice = NULL;
1730 unlock ("cs");
1732 else if (!strncmp ("freepage", p, 8)) {
1733 void *ptr;
1735 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1736 if (ret != 1) {
1737 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1739 freepage (ptr);
1741 else if (!strncmp ("freetile", p, 8)) {
1742 void *ptr;
1744 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1745 if (ret != 1) {
1746 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1748 freetile (ptr);
1750 else if (!strncmp ("search", p, 6)) {
1751 int icase, pageno, y, len2, forward;
1752 char *pattern;
1753 regex_t re;
1755 ret = sscanf (p + 6, " %d %d %d %d,%n",
1756 &icase, &pageno, &y, &forward, &len2);
1757 if (ret != 4) {
1758 errx (1, "malformed search `%s' ret=%d", p, ret);
1761 pattern = p + 6 + len2;
1762 ret = regcomp (&re, pattern,
1763 REG_EXTENDED | (icase ? REG_ICASE : 0));
1764 if (ret) {
1765 char errbuf[80];
1766 size_t size;
1768 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1769 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1771 else {
1772 search (&re, pageno, y, forward);
1773 regfree (&re);
1776 else if (!strncmp ("geometry", p, 8)) {
1777 int w, h, fitmodel;
1779 printd ("clear");
1780 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1781 if (ret != 3) {
1782 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1785 lock ("geometry");
1786 state.h = h;
1787 if (w != state.w) {
1788 int i;
1789 state.w = w;
1790 for (i = 0; i < state.texcount; ++i) {
1791 state.texowners[i].slice = NULL;
1794 state.fitmodel = fitmodel;
1795 layout ();
1796 process_outline ();
1798 state.gen++;
1799 unlock ("geometry");
1800 printd ("continue %d", state.pagecount);
1802 else if (!strncmp ("reqlayout", p, 9)) {
1803 char *nameddest;
1804 int rotate, off, h;
1805 unsigned int fitmodel;
1806 pdf_document *pdf;
1808 printd ("clear");
1809 ret = sscanf (p + 9, " %d %u %d %n",
1810 &rotate, &fitmodel, &h, &off);
1811 if (ret != 3) {
1812 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1814 lock ("reqlayout");
1815 pdf = pdf_specifics (state.ctx, state.doc);
1816 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1817 state.gen += 1;
1819 state.rotate = rotate;
1820 state.fitmodel = fitmodel;
1821 state.h = h;
1822 layout ();
1823 process_outline ();
1825 nameddest = p + 9 + off;
1826 if (pdf && nameddest && *nameddest) {
1827 fz_point xy;
1828 struct pagedim *pdim;
1829 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1830 &xy.x, &xy.y);
1831 pdim = pdimofpageno (pageno);
1832 fz_transform_point (&xy, &pdim->ctm);
1833 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1836 state.gen++;
1837 unlock ("reqlayout");
1838 printd ("continue %d", state.pagecount);
1840 else if (!strncmp ("page", p, 4)) {
1841 double a, b;
1842 struct page *page;
1843 int pageno, pindex;
1845 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1846 if (ret != 2) {
1847 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1850 lock ("page");
1851 a = now ();
1852 page = loadpage (pageno, pindex);
1853 b = now ();
1854 unlock ("page");
1856 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1858 else if (!strncmp ("tile", p, 4)) {
1859 int x, y, w, h;
1860 struct page *page;
1861 struct tile *tile;
1862 double a, b;
1863 void *data;
1865 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1866 SCN_ptr_cast (&page), &x, &y, &w, &h,
1867 SCN_ptr_cast (&data));
1868 if (ret != 6) {
1869 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1872 lock ("tile");
1873 a = now ();
1874 tile = rendertile (page, x, y, w, h, data);
1875 b = now ();
1876 unlock ("tile");
1878 printd ("tile %d %d %" FMT_ptr " %u %f",
1879 x, y,
1880 FMT_ptr_cast (tile),
1881 tile->w * tile->h * tile->pixmap->n,
1882 b - a);
1884 else if (!strncmp ("trimset", p, 7)) {
1885 fz_irect fuzz;
1886 int trimmargins;
1888 ret = sscanf (p + 7, " %d %d %d %d %d",
1889 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1890 if (ret != 5) {
1891 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1893 lock ("trimset");
1894 state.trimmargins = trimmargins;
1895 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1896 state.trimanew = 1;
1897 state.trimfuzz = fuzz;
1899 unlock ("trimset");
1901 else if (!strncmp ("settrim", p, 7)) {
1902 fz_irect fuzz;
1903 int trimmargins;
1905 ret = sscanf (p + 7, " %d %d %d %d %d",
1906 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1907 if (ret != 5) {
1908 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1910 printd ("clear");
1911 lock ("settrim");
1912 state.trimmargins = trimmargins;
1913 state.needoutline = 1;
1914 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1915 state.trimanew = 1;
1916 state.trimfuzz = fuzz;
1918 state.pagedimcount = 0;
1919 free (state.pagedims);
1920 state.pagedims = NULL;
1921 initpdims (0);
1922 layout ();
1923 process_outline ();
1924 unlock ("settrim");
1925 printd ("continue %d", state.pagecount);
1927 else if (!strncmp ("sliceh", p, 6)) {
1928 int h;
1930 ret = sscanf (p + 6, " %d", &h);
1931 if (ret != 1) {
1932 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1934 if (h != state.sliceheight) {
1935 int i;
1937 state.sliceheight = h;
1938 for (i = 0; i < state.texcount; ++i) {
1939 state.texowners[i].w = -1;
1940 state.texowners[i].h = -1;
1941 state.texowners[i].slice = NULL;
1945 else if (!strncmp ("interrupt", p, 9)) {
1946 printd ("vmsg interrupted");
1948 else {
1949 errx (1, "unknown command %.*s", len, p);
1952 return 0;
1955 CAMLprim value ml_isexternallink (value uri_v)
1957 CAMLparam1 (uri_v);
1958 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1959 CAMLreturn (Val_bool (ext));
1962 CAMLprim value ml_uritolocation (value uri_v)
1964 CAMLparam1 (uri_v);
1965 CAMLlocal1 (ret_v);
1966 int pageno;
1967 fz_point xy;
1968 struct pagedim *pdim;
1970 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1971 &xy.x, &xy.y);
1972 pdim = pdimofpageno (pageno);
1973 fz_transform_point (&xy, &pdim->ctm);
1974 ret_v = caml_alloc_tuple (3);
1975 Field (ret_v, 0) = Val_int (pageno);
1976 Field (ret_v, 1) = caml_copy_double (xy.x);
1977 Field (ret_v, 2) = caml_copy_double (xy.y);
1978 CAMLreturn (ret_v);
1981 CAMLprim value ml_realloctexts (value texcount_v)
1983 CAMLparam1 (texcount_v);
1984 int ok;
1986 if (trylock (__func__)) {
1987 ok = 0;
1988 goto done;
1990 realloctexts (Int_val (texcount_v));
1991 ok = 1;
1992 unlock (__func__);
1994 done:
1995 CAMLreturn (Val_bool (ok));
1998 static void recti (int x0, int y0, int x1, int y1)
2000 GLfloat *v = state.vertices;
2002 glVertexPointer (2, GL_FLOAT, 0, v);
2003 v[0] = x0; v[1] = y0;
2004 v[2] = x1; v[3] = y0;
2005 v[4] = x0; v[5] = y1;
2006 v[6] = x1; v[7] = y1;
2007 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2010 static void showsel (struct page *page, int ox, int oy)
2012 int seen = 0;
2013 fz_irect bbox;
2014 fz_rect rect;
2015 fz_stext_line *line;
2016 fz_page_block *pageb;
2017 fz_stext_block *block;
2018 struct mark first, last;
2019 unsigned char selcolor[] = {15,15,15,140};
2021 first = page->fmark;
2022 last = page->lmark;
2024 if (!first.span || !last.span) return;
2026 glEnable (GL_BLEND);
2027 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2028 glColor4ubv (selcolor);
2030 ox += state.pagedims[page->pdimno].bounds.x0;
2031 oy += state.pagedims[page->pdimno].bounds.y0;
2032 for (pageb = page->text->blocks;
2033 pageb < page->text->blocks + page->text->len;
2034 ++pageb) {
2035 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2036 block = pageb->u.text;
2038 for (line = block->lines;
2039 line < block->lines + block->len;
2040 ++line) {
2041 fz_stext_span *span;
2042 rect = fz_empty_rect;
2044 for (span = line->first_span; span; span = span->next) {
2045 int i, j, k;
2046 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2048 j = 0;
2049 k = span->len - 1;
2051 if (span == page->fmark.span && span == page->lmark.span) {
2052 seen = 1;
2053 j = fz_mini (first.i, last.i);
2054 k = fz_maxi (first.i, last.i);
2056 else {
2057 if (span == first.span) {
2058 seen = 1;
2059 j = first.i;
2061 else if (span == last.span) {
2062 seen = 1;
2063 k = last.i;
2067 if (seen) {
2068 for (i = j; i <= k; ++i) {
2069 fz_rect bbox1;
2070 fz_union_rect (&rect,
2071 fz_stext_char_bbox (state.ctx, &bbox1,
2072 span, i));
2074 fz_round_rect (&bbox, &rect);
2075 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2076 bbox.x0,
2077 bbox.y0,
2078 bbox.x1,
2079 bbox.y1,
2080 oy, ox);
2082 recti (bbox.x0 + ox, bbox.y0 + oy,
2083 bbox.x1 + ox, bbox.y1 + oy);
2084 if (span == last.span) {
2085 goto done;
2087 rect = fz_empty_rect;
2092 done:
2093 glDisable (GL_BLEND);
2096 #include "glfont.c"
2098 static void stipplerect (fz_matrix *m,
2099 fz_point *p1,
2100 fz_point *p2,
2101 fz_point *p3,
2102 fz_point *p4,
2103 GLfloat *texcoords,
2104 GLfloat *vertices)
2106 fz_transform_point (p1, m);
2107 fz_transform_point (p2, m);
2108 fz_transform_point (p3, m);
2109 fz_transform_point (p4, m);
2111 float w, h, s, t;
2113 w = p2->x - p1->x;
2114 h = p2->y - p1->y;
2115 t = hypotf (w, h) * .25f;
2117 w = p3->x - p2->x;
2118 h = p3->y - p2->y;
2119 s = hypotf (w, h) * .25f;
2121 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2122 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2124 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2125 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2127 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2128 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2130 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2131 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2133 glDrawArrays (GL_LINES, 0, 8);
2136 static void solidrect (fz_matrix *m,
2137 fz_point *p1,
2138 fz_point *p2,
2139 fz_point *p3,
2140 fz_point *p4,
2141 GLfloat *vertices)
2143 fz_transform_point (p1, m);
2144 fz_transform_point (p2, m);
2145 fz_transform_point (p3, m);
2146 fz_transform_point (p4, m);
2147 vertices[0] = p1->x; vertices[1] = p1->y;
2148 vertices[2] = p2->x; vertices[3] = p2->y;
2150 vertices[4] = p3->x; vertices[5] = p3->y;
2151 vertices[6] = p4->x; vertices[7] = p4->y;
2152 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2155 static void highlightlinks (struct page *page, int xoff, int yoff)
2157 int i;
2158 fz_matrix ctm, tm, pm;
2159 fz_link *link, *links;
2160 GLfloat *texcoords = state.texcoords;
2161 GLfloat *vertices = state.vertices;
2163 links = fz_load_links (state.ctx, page->fzpage);
2165 glEnable (GL_TEXTURE_1D);
2166 glEnable (GL_BLEND);
2167 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2168 glBindTexture (GL_TEXTURE_1D, state.stid);
2170 xoff -= state.pagedims[page->pdimno].bounds.x0;
2171 yoff -= state.pagedims[page->pdimno].bounds.y0;
2172 fz_translate (&tm, xoff, yoff);
2173 pm = pagectm (page);
2174 fz_concat (&ctm, &pm, &tm);
2176 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2177 glVertexPointer (2, GL_FLOAT, 0, vertices);
2179 for (link = links; link; link = link->next) {
2180 fz_point p1, p2, p3, p4;
2182 p1.x = link->rect.x0;
2183 p1.y = link->rect.y0;
2185 p2.x = link->rect.x1;
2186 p2.y = link->rect.y0;
2188 p3.x = link->rect.x1;
2189 p3.y = link->rect.y1;
2191 p4.x = link->rect.x0;
2192 p4.y = link->rect.y1;
2194 /* TODO: different colours for different schemes */
2195 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2196 else glColor3ub (255, 0, 0);
2198 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2201 for (i = 0; i < page->annotcount; ++i) {
2202 fz_point p1, p2, p3, p4;
2203 struct annot *annot = &page->annots[i];
2205 p1.x = annot->bbox.x0;
2206 p1.y = annot->bbox.y0;
2208 p2.x = annot->bbox.x1;
2209 p2.y = annot->bbox.y0;
2211 p3.x = annot->bbox.x1;
2212 p3.y = annot->bbox.y1;
2214 p4.x = annot->bbox.x0;
2215 p4.y = annot->bbox.y1;
2217 glColor3ub (0, 0, 128);
2218 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2221 glDisable (GL_BLEND);
2222 glDisable (GL_TEXTURE_1D);
2225 static int compareslinks (const void *l, const void *r)
2227 struct slink const *ls = l;
2228 struct slink const *rs = r;
2229 if (ls->bbox.y0 == rs->bbox.y0) {
2230 return rs->bbox.x0 - rs->bbox.x0;
2232 return ls->bbox.y0 - rs->bbox.y0;
2235 static void droptext (struct page *page)
2237 if (page->text) {
2238 fz_drop_stext_page (state.ctx, page->text);
2239 page->fmark.i = -1;
2240 page->lmark.i = -1;
2241 page->fmark.span = NULL;
2242 page->lmark.span = NULL;
2243 page->text = NULL;
2245 if (page->sheet) {
2246 fz_drop_stext_sheet (state.ctx, page->sheet);
2247 page->sheet = NULL;
2251 static void dropannots (struct page *page)
2253 if (page->annots) {
2254 free (page->annots);
2255 page->annots = NULL;
2256 page->annotcount = 0;
2260 static void ensureannots (struct page *page)
2262 int i, count = 0;
2263 size_t annotsize = sizeof (*page->annots);
2264 fz_annot *annot;
2266 if (state.gen != page->agen) {
2267 dropannots (page);
2268 page->agen = state.gen;
2270 if (page->annots) return;
2272 for (annot = fz_first_annot (state.ctx, page->fzpage);
2273 annot;
2274 annot = fz_next_annot (state.ctx, annot)) {
2275 count++;
2278 if (count > 0) {
2279 page->annotcount = count;
2280 page->annots = calloc (count, annotsize);
2281 if (!page->annots) {
2282 err (1, "calloc annots %d", count);
2285 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2286 annot;
2287 annot = fz_next_annot (state.ctx, annot), i++) {
2288 fz_rect rect;
2290 fz_bound_annot (state.ctx, annot, &rect);
2291 page->annots[i].annot = annot;
2292 fz_round_rect (&page->annots[i].bbox, &rect);
2297 static void dropslinks (struct page *page)
2299 if (page->slinks) {
2300 free (page->slinks);
2301 page->slinks = NULL;
2302 page->slinkcount = 0;
2306 static void ensureslinks (struct page *page)
2308 fz_matrix ctm;
2309 int i, count;
2310 size_t slinksize = sizeof (*page->slinks);
2311 fz_link *link, *links;
2313 ensureannots (page);
2314 if (state.gen != page->sgen) {
2315 dropslinks (page);
2316 page->sgen = state.gen;
2318 if (page->slinks) return;
2320 links = fz_load_links (state.ctx, page->fzpage);
2321 ctm = pagectm (page);
2323 count = page->annotcount;
2324 for (link = links; link; link = link->next) {
2325 count++;
2327 if (count > 0) {
2328 int j;
2330 page->slinkcount = count;
2331 page->slinks = calloc (count, slinksize);
2332 if (!page->slinks) {
2333 err (1, "calloc slinks %d", count);
2336 for (i = 0, link = links; link; ++i, link = link->next) {
2337 fz_rect rect;
2339 rect = link->rect;
2340 fz_transform_rect (&rect, &ctm);
2341 page->slinks[i].tag = SLINK;
2342 page->slinks[i].u.link = link;
2343 fz_round_rect (&page->slinks[i].bbox, &rect);
2345 for (j = 0; j < page->annotcount; ++j, ++i) {
2346 fz_rect rect;
2347 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2348 fz_transform_rect (&rect, &ctm);
2349 fz_round_rect (&page->slinks[i].bbox, &rect);
2351 page->slinks[i].tag = SANNOT;
2352 page->slinks[i].u.annot = page->annots[j].annot;
2354 qsort (page->slinks, count, slinksize, compareslinks);
2358 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2359 static void fmt_linkn (char *s, unsigned int u)
2361 unsigned int len; unsigned int q;
2362 unsigned int zma = 'z' - 'a' + 1;
2363 len = 1; q = u;
2364 while (q > zma - 1) { ++len; q /= zma; }
2365 if (s) {
2366 s += len;
2367 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2368 /* handles u == 0 */
2370 s[len] = 0;
2373 static void highlightslinks (struct page *page, int xoff, int yoff,
2374 int noff, char *targ, int tlen, int hfsize)
2376 int i;
2377 char buf[40];
2378 struct slink *slink;
2379 double x0, y0, x1, y1, w;
2381 ensureslinks (page);
2382 glColor3ub (0xc3, 0xb0, 0x91);
2383 for (i = 0; i < page->slinkcount; ++i) {
2384 fmt_linkn (buf, i + noff);
2385 if (!tlen || !strncmp (targ, buf, tlen)) {
2386 slink = &page->slinks[i];
2388 x0 = slink->bbox.x0 + xoff - 5;
2389 y1 = slink->bbox.y0 + yoff - 5;
2390 y0 = y1 + 10 + hfsize;
2391 w = measure_string (state.face, hfsize, buf);
2392 x1 = x0 + w + 10;
2393 recti (x0, y0, x1, y1);
2397 glEnable (GL_BLEND);
2398 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2399 glEnable (GL_TEXTURE_2D);
2400 glColor3ub (0, 0, 0);
2401 for (i = 0; i < page->slinkcount; ++i) {
2402 fmt_linkn (buf, i + noff);
2403 if (!tlen || !strncmp (targ, buf, tlen)) {
2404 slink = &page->slinks[i];
2406 x0 = slink->bbox.x0 + xoff;
2407 y0 = slink->bbox.y0 + yoff + hfsize;
2408 draw_string (state.face, hfsize, x0, y0, buf);
2411 glDisable (GL_TEXTURE_2D);
2412 glDisable (GL_BLEND);
2415 static void uploadslice (struct tile *tile, struct slice *slice)
2417 int offset;
2418 struct slice *slice1;
2419 unsigned char *texdata;
2421 offset = 0;
2422 for (slice1 = tile->slices; slice != slice1; slice1++) {
2423 offset += slice1->h * tile->w * tile->pixmap->n;
2425 if (slice->texindex != -1 && slice->texindex < state.texcount
2426 && state.texowners[slice->texindex].slice == slice) {
2427 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2429 else {
2430 int subimage = 0;
2431 int texindex = state.texindex++ % state.texcount;
2433 if (state.texowners[texindex].w == tile->w) {
2434 if (state.texowners[texindex].h >= slice->h) {
2435 subimage = 1;
2437 else {
2438 state.texowners[texindex].h = slice->h;
2441 else {
2442 state.texowners[texindex].h = slice->h;
2445 state.texowners[texindex].w = tile->w;
2446 state.texowners[texindex].slice = slice;
2447 slice->texindex = texindex;
2449 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2450 #if TEXT_TYPE == GL_TEXTURE_2D
2451 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2452 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2453 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2454 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2455 #endif
2456 if (tile->pbo) {
2457 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2458 texdata = 0;
2460 else {
2461 texdata = tile->pixmap->samples;
2463 if (subimage) {
2464 glTexSubImage2D (TEXT_TYPE,
2468 tile->w,
2469 slice->h,
2470 state.texform,
2471 state.texty,
2472 texdata+offset
2475 else {
2476 glTexImage2D (TEXT_TYPE,
2478 state.texiform,
2479 tile->w,
2480 slice->h,
2482 state.texform,
2483 state.texty,
2484 texdata+offset
2487 if (tile->pbo) {
2488 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2493 CAMLprim value ml_begintiles (value unit_v)
2495 CAMLparam1 (unit_v);
2496 glEnable (TEXT_TYPE);
2497 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2498 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2499 CAMLreturn (unit_v);
2502 CAMLprim value ml_endtiles (value unit_v)
2504 CAMLparam1 (unit_v);
2505 glDisable (TEXT_TYPE);
2506 CAMLreturn (unit_v);
2509 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2511 CAMLparam2 (args_v, ptr_v);
2512 int dispx = Int_val (Field (args_v, 0));
2513 int dispy = Int_val (Field (args_v, 1));
2514 int dispw = Int_val (Field (args_v, 2));
2515 int disph = Int_val (Field (args_v, 3));
2516 int tilex = Int_val (Field (args_v, 4));
2517 int tiley = Int_val (Field (args_v, 5));
2518 char *s = String_val (ptr_v);
2519 struct tile *tile = parse_pointer (__func__, s);
2520 int slicey, firstslice;
2521 struct slice *slice;
2522 GLfloat *texcoords = state.texcoords;
2523 GLfloat *vertices = state.vertices;
2525 firstslice = tiley / tile->sliceheight;
2526 slice = &tile->slices[firstslice];
2527 slicey = tiley % tile->sliceheight;
2529 while (disph > 0) {
2530 int dh;
2532 dh = slice->h - slicey;
2533 dh = fz_mini (disph, dh);
2534 uploadslice (tile, slice);
2536 texcoords[0] = tilex; texcoords[1] = slicey;
2537 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2538 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2539 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2541 vertices[0] = dispx; vertices[1] = dispy;
2542 vertices[2] = dispx+dispw; vertices[3] = dispy;
2543 vertices[4] = dispx; vertices[5] = dispy+dh;
2544 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2546 #if TEXT_TYPE == GL_TEXTURE_2D
2547 for (int i = 0; i < 8; ++i) {
2548 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2550 #endif
2552 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2553 dispy += dh;
2554 disph -= dh;
2555 slice++;
2556 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2557 slicey = 0;
2559 CAMLreturn (Val_unit);
2562 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2564 fz_matrix ctm, tm, pm;
2565 fz_point p1, p2, p3, p4;
2566 GLfloat *vertices = state.vertices;
2567 double *v = (double *) rects_v;
2569 xoff -= state.pagedims[page->pdimno].bounds.x0;
2570 yoff -= state.pagedims[page->pdimno].bounds.y0;
2571 fz_translate (&tm, xoff, yoff);
2572 pm = pagectm (page);
2573 fz_concat (&ctm, &pm, &tm);
2575 glEnable (GL_BLEND);
2576 glVertexPointer (2, GL_FLOAT, 0, vertices);
2578 glColor4dv (v);
2579 p1.x = v[4];
2580 p1.y = v[5];
2582 p2.x = v[6];
2583 p2.y = v[5];
2585 p3.x = v[6];
2586 p3.y = v[7];
2588 p4.x = v[4];
2589 p4.y = v[7];
2590 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2591 glDisable (GL_BLEND);
2594 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2595 value xoff_v, value yoff_v,
2596 value li_v)
2598 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2599 int xoff = Int_val (xoff_v);
2600 int yoff = Int_val (yoff_v);
2601 int noff = Int_val (Field (li_v, 0));
2602 char *targ = String_val (Field (li_v, 1));
2603 int tlen = caml_string_length (Field (li_v, 1));
2604 int hfsize = Int_val (Field (li_v, 2));
2605 char *s = String_val (ptr_v);
2606 int hlmask = Int_val (hlinks_v);
2607 struct page *page = parse_pointer (__func__, s);
2609 if (!page->fzpage) {
2610 /* deal with loadpage failed pages */
2611 goto done;
2614 if (trylock (__func__)) {
2615 noff = -1;
2616 goto done;
2619 ensureannots (page);
2620 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2621 if (hlmask & 2) {
2622 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2623 noff = page->slinkcount;
2625 if (page->tgen == state.gen) {
2626 showsel (page, xoff, yoff);
2628 unlock (__func__);
2630 done:
2631 CAMLreturn (Val_int (noff));
2634 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2635 value rects_v)
2637 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2638 int xoff = Int_val (xoff_v);
2639 int yoff = Int_val (yoff_v);
2640 char *s = String_val (ptr_v);
2641 struct page *page = parse_pointer (__func__, s);
2643 drawprect (page, xoff, yoff, rects_v);
2644 CAMLreturn (Val_unit);
2647 static struct annot *getannot (struct page *page, int x, int y)
2649 int i;
2650 fz_point p;
2651 fz_matrix ctm;
2652 const fz_matrix *tctm;
2653 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2655 if (!page->annots) return NULL;
2657 if (pdf) {
2658 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2659 tctm = &state.pagedims[page->pdimno].tctm;
2661 else {
2662 tctm = &fz_identity;
2665 p.x = x;
2666 p.y = y;
2668 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2669 fz_invert_matrix (&ctm, &ctm);
2670 fz_transform_point (&p, &ctm);
2672 if (pdf) {
2673 for (i = 0; i < page->annotcount; ++i) {
2674 struct annot *a = &page->annots[i];
2675 fz_rect rect;
2677 fz_bound_annot (state.ctx, a->annot, &rect);
2678 if (p.x >= rect.x0 && p.x <= rect.x1) {
2679 if (p.y >= rect.y0 && p.y <= rect.y1)
2680 return a;
2684 return NULL;
2687 static fz_link *getlink (struct page *page, int x, int y)
2689 fz_point p;
2690 fz_matrix ctm;
2691 fz_link *link, *links;
2693 links = fz_load_links (state.ctx, page->fzpage);
2695 p.x = x;
2696 p.y = y;
2698 ctm = pagectm (page);
2699 fz_invert_matrix (&ctm, &ctm);
2700 fz_transform_point (&p, &ctm);
2702 for (link = links; link; link = link->next) {
2703 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2704 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2705 return link;
2709 return NULL;
2712 static void ensuretext (struct page *page)
2714 if (state.gen != page->tgen) {
2715 droptext (page);
2716 page->tgen = state.gen;
2718 if (!page->text) {
2719 fz_matrix ctm;
2720 fz_device *tdev;
2722 page->text = fz_new_stext_page (state.ctx,
2723 &state.pagedims[page->pdimno].mediabox);
2724 page->sheet = fz_new_stext_sheet (state.ctx);
2725 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2726 ctm = pagectm (page);
2727 fz_run_display_list (state.ctx, page->dlist,
2728 tdev, &ctm, &fz_infinite_rect, NULL);
2729 qsort (page->text->blocks, page->text->len,
2730 sizeof (*page->text->blocks), compareblocks);
2731 fz_close_device (state.ctx, tdev);
2732 fz_drop_device (state.ctx, tdev);
2736 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2738 CAMLparam2 (start_page_v, dir_v);
2739 CAMLlocal1 (ret_v);
2740 int i, dir = Int_val (dir_v);
2741 int start_page = Int_val (start_page_v);
2742 int end_page = dir > 0 ? state.pagecount : -1;
2743 pdf_document *pdf;
2745 fz_var (end_page);
2746 ret_v = Val_int (0);
2747 lock (__func__);
2748 pdf = pdf_specifics (state.ctx, state.doc);
2749 for (i = start_page + dir; i != end_page; i += dir) {
2750 int found;
2752 fz_var (found);
2753 if (pdf) {
2754 pdf_page *page = NULL;
2756 fz_var (page);
2757 fz_try (state.ctx) {
2758 page = pdf_load_page (state.ctx, pdf, i);
2759 found = !!page->links || !!page->annots;
2761 fz_catch (state.ctx) {
2762 found = 0;
2764 if (page) {
2765 fz_drop_page (state.ctx, &page->super);
2768 else {
2769 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2770 found = !!fz_load_links (state.ctx, page);
2771 fz_drop_page (state.ctx, page);
2774 if (found) {
2775 ret_v = caml_alloc_small (1, 1);
2776 Field (ret_v, 0) = Val_int (i);
2777 goto unlock;
2780 unlock:
2781 unlock (__func__);
2782 CAMLreturn (ret_v);
2785 enum { dir_first, dir_last };
2786 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2788 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2790 CAMLparam2 (ptr_v, dir_v);
2791 CAMLlocal2 (ret_v, pos_v);
2792 struct page *page;
2793 int dirtag, i, slinkindex;
2794 struct slink *found = NULL ,*slink;
2795 char *s = String_val (ptr_v);
2797 page = parse_pointer (__func__, s);
2798 ret_v = Val_int (0);
2799 lock (__func__);
2800 ensureslinks (page);
2802 if (Is_block (dir_v)) {
2803 dirtag = Tag_val (dir_v);
2804 switch (dirtag) {
2805 case dir_first_visible:
2807 int x0, y0, dir, first_index, last_index;
2809 pos_v = Field (dir_v, 0);
2810 x0 = Int_val (Field (pos_v, 0));
2811 y0 = Int_val (Field (pos_v, 1));
2812 dir = Int_val (Field (pos_v, 2));
2814 if (dir >= 0) {
2815 dir = 1;
2816 first_index = 0;
2817 last_index = page->slinkcount;
2819 else {
2820 first_index = page->slinkcount - 1;
2821 last_index = -1;
2824 for (i = first_index; i != last_index; i += dir) {
2825 slink = &page->slinks[i];
2826 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2827 found = slink;
2828 break;
2832 break;
2834 case dir_left:
2835 slinkindex = Int_val (Field (dir_v, 0));
2836 found = &page->slinks[slinkindex];
2837 for (i = slinkindex - 1; i >= 0; --i) {
2838 slink = &page->slinks[i];
2839 if (slink->bbox.x0 < found->bbox.x0) {
2840 found = slink;
2841 break;
2844 break;
2846 case dir_right:
2847 slinkindex = Int_val (Field (dir_v, 0));
2848 found = &page->slinks[slinkindex];
2849 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2850 slink = &page->slinks[i];
2851 if (slink->bbox.x0 > found->bbox.x0) {
2852 found = slink;
2853 break;
2856 break;
2858 case dir_down:
2859 slinkindex = Int_val (Field (dir_v, 0));
2860 found = &page->slinks[slinkindex];
2861 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2862 slink = &page->slinks[i];
2863 if (slink->bbox.y0 >= found->bbox.y0) {
2864 found = slink;
2865 break;
2868 break;
2870 case dir_up:
2871 slinkindex = Int_val (Field (dir_v, 0));
2872 found = &page->slinks[slinkindex];
2873 for (i = slinkindex - 1; i >= 0; --i) {
2874 slink = &page->slinks[i];
2875 if (slink->bbox.y0 <= found->bbox.y0) {
2876 found = slink;
2877 break;
2880 break;
2883 else {
2884 dirtag = Int_val (dir_v);
2885 switch (dirtag) {
2886 case dir_first:
2887 found = page->slinks;
2888 break;
2890 case dir_last:
2891 if (page->slinks) {
2892 found = page->slinks + (page->slinkcount - 1);
2894 break;
2897 if (found) {
2898 ret_v = caml_alloc_small (2, 1);
2899 Field (ret_v, 0) = Val_int (found - page->slinks);
2902 unlock (__func__);
2903 CAMLreturn (ret_v);
2906 enum { uuri, utext, uannot };
2908 CAMLprim value ml_getlink (value ptr_v, value n_v)
2910 CAMLparam2 (ptr_v, n_v);
2911 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2912 fz_link *link;
2913 struct page *page;
2914 char *s = String_val (ptr_v);
2915 struct slink *slink;
2917 ret_v = Val_int (0);
2918 page = parse_pointer (__func__, s);
2920 lock (__func__);
2921 ensureslinks (page);
2922 slink = &page->slinks[Int_val (n_v)];
2923 if (slink->tag == SLINK) {
2924 link = slink->u.link;
2925 str_v = caml_copy_string (link->uri);
2926 ret_v = caml_alloc_small (1, uuri);
2927 Field (ret_v, 0) = str_v;
2929 else {
2930 ret_v = caml_alloc_small (1, uannot);
2931 tup_v = caml_alloc_tuple (2);
2932 Field (ret_v, 0) = tup_v;
2933 Field (tup_v, 0) = ptr_v;
2934 Field (tup_v, 1) = n_v;
2936 unlock (__func__);
2938 CAMLreturn (ret_v);
2941 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2943 CAMLparam2 (ptr_v, n_v);
2944 pdf_document *pdf;
2945 const char *contents = "";
2947 lock (__func__);
2948 pdf = pdf_specifics (state.ctx, state.doc);
2949 if (pdf) {
2950 char *s = String_val (ptr_v);
2951 struct page *page;
2952 struct slink *slink;
2954 page = parse_pointer (__func__, s);
2955 slink = &page->slinks[Int_val (n_v)];
2956 contents = pdf_annot_contents (state.ctx,
2957 (pdf_annot *) slink->u.annot);
2959 unlock (__func__);
2960 CAMLreturn (caml_copy_string (contents));
2963 CAMLprim value ml_getlinkcount (value ptr_v)
2965 CAMLparam1 (ptr_v);
2966 struct page *page;
2967 char *s = String_val (ptr_v);
2969 page = parse_pointer (__func__, s);
2970 CAMLreturn (Val_int (page->slinkcount));
2973 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2975 CAMLparam2 (ptr_v, n_v);
2976 CAMLlocal1 (ret_v);
2977 struct page *page;
2978 struct slink *slink;
2979 char *s = String_val (ptr_v);
2981 page = parse_pointer (__func__, s);
2982 ret_v = caml_alloc_tuple (4);
2983 lock (__func__);
2984 ensureslinks (page);
2986 slink = &page->slinks[Int_val (n_v)];
2987 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2988 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2989 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2990 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2991 unlock (__func__);
2992 CAMLreturn (ret_v);
2995 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2997 CAMLparam3 (ptr_v, x_v, y_v);
2998 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2999 fz_link *link;
3000 struct annot *annot;
3001 struct page *page;
3002 char *ptr = String_val (ptr_v);
3003 int x = Int_val (x_v), y = Int_val (y_v);
3004 struct pagedim *pdim;
3006 ret_v = Val_int (0);
3007 if (trylock (__func__)) {
3008 goto done;
3011 page = parse_pointer (__func__, ptr);
3012 pdim = &state.pagedims[page->pdimno];
3013 x += pdim->bounds.x0;
3014 y += pdim->bounds.y0;
3017 annot = getannot (page, x, y);
3018 if (annot) {
3019 int i, n = -1;
3021 ensureslinks (page);
3022 for (i = 0; i < page->slinkcount; ++i) {
3023 if (page->slinks[i].tag == SANNOT
3024 && page->slinks[i].u.annot == annot->annot) {
3025 n = i;
3026 break;
3029 ret_v = caml_alloc_small (1, uannot);
3030 tup_v = caml_alloc_tuple (2);
3031 Field (ret_v, 0) = tup_v;
3032 Field (tup_v, 0) = ptr_v;
3033 Field (tup_v, 1) = Val_int (n);
3034 goto unlock;
3038 link = getlink (page, x, y);
3039 if (link) {
3040 str_v = caml_copy_string (link->uri);
3041 ret_v = caml_alloc_small (1, uuri);
3042 Field (ret_v, 0) = str_v;
3044 else {
3045 fz_rect *b;
3046 fz_page_block *pageb;
3047 fz_stext_block *block;
3049 ensuretext (page);
3050 for (pageb = page->text->blocks;
3051 pageb < page->text->blocks + page->text->len;
3052 ++pageb) {
3053 fz_stext_line *line;
3054 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3055 block = pageb->u.text;
3057 b = &block->bbox;
3058 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3059 continue;
3061 for (line = block->lines;
3062 line < block->lines + block->len;
3063 ++line) {
3064 fz_stext_span *span;
3066 b = &line->bbox;
3067 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3068 continue;
3070 for (span = line->first_span; span; span = span->next) {
3071 int charnum;
3073 b = &span->bbox;
3074 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3075 continue;
3077 for (charnum = 0; charnum < span->len; ++charnum) {
3078 fz_rect bbox;
3079 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3080 b = &bbox;
3082 if (x >= b->x0 && x <= b->x1
3083 && y >= b->y0 && y <= b->y1) {
3084 fz_stext_style *style = span->text->style;
3085 const char *n2 =
3086 style->font
3087 ? fz_font_name (state.ctx, style->font)
3088 : "Span has no font name"
3090 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3091 style->font);
3092 if (face && face->family_name) {
3093 char *s;
3094 char *n1 = face->family_name;
3095 size_t l1 = strlen (n1);
3096 size_t l2 = strlen (n2);
3098 if (l1 != l2 || memcmp (n1, n2, l1)) {
3099 s = malloc (l1 + l2 + 2);
3100 if (s) {
3101 memcpy (s, n2, l2);
3102 s[l2] = '=';
3103 memcpy (s + l2 + 1, n1, l1 + 1);
3104 str_v = caml_copy_string (s);
3105 free (s);
3109 if (str_v == Val_unit) {
3110 str_v = caml_copy_string (n2);
3112 ret_v = caml_alloc_small (1, utext);
3113 Field (ret_v, 0) = str_v;
3114 goto unlock;
3121 unlock:
3122 unlock (__func__);
3124 done:
3125 CAMLreturn (ret_v);
3128 enum { mark_page, mark_block, mark_line, mark_word };
3130 static int uninteresting (int c)
3132 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3133 || ispunct (c);
3136 CAMLprim value ml_clearmark (value ptr_v)
3138 CAMLparam1 (ptr_v);
3139 char *s = String_val (ptr_v);
3140 struct page *page;
3142 if (trylock (__func__)) {
3143 goto done;
3146 page = parse_pointer (__func__, s);
3147 page->fmark.span = NULL;
3148 page->lmark.span = NULL;
3149 page->fmark.i = 0;
3150 page->lmark.i = 0;
3152 unlock (__func__);
3153 done:
3154 CAMLreturn (Val_unit);
3157 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3159 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3160 CAMLlocal1 (ret_v);
3161 fz_rect *b;
3162 struct page *page;
3163 fz_stext_line *line;
3164 fz_page_block *pageb;
3165 fz_stext_block *block;
3166 struct pagedim *pdim;
3167 int mark = Int_val (mark_v);
3168 char *s = String_val (ptr_v);
3169 int x = Int_val (x_v), y = Int_val (y_v);
3171 ret_v = Val_bool (0);
3172 if (trylock (__func__)) {
3173 goto done;
3176 page = parse_pointer (__func__, s);
3177 pdim = &state.pagedims[page->pdimno];
3179 ensuretext (page);
3181 if (mark == mark_page) {
3182 int i;
3183 fz_page_block *pb1 = NULL, *pb2 = NULL;
3185 for (i = 0; i < page->text->len; ++i) {
3186 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3187 pb1 = &page->text->blocks[i];
3188 break;
3191 if (!pb1) goto unlock;
3193 for (i = page->text->len - 1; i >= 0; --i) {
3194 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3195 pb2 = &page->text->blocks[i];
3196 break;
3199 if (!pb2) goto unlock;
3201 block = pb1->u.text;
3203 page->fmark.i = 0;
3204 page->fmark.span = block->lines->first_span;
3206 block = pb2->u.text;
3207 line = &block->lines[block->len - 1];
3208 page->lmark.i = line->last_span->len - 1;
3209 page->lmark.span = line->last_span;
3210 ret_v = Val_bool (1);
3211 goto unlock;
3214 x += pdim->bounds.x0;
3215 y += pdim->bounds.y0;
3217 for (pageb = page->text->blocks;
3218 pageb < page->text->blocks + page->text->len;
3219 ++pageb) {
3220 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3221 block = pageb->u.text;
3223 b = &block->bbox;
3224 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3225 continue;
3227 if (mark == mark_block) {
3228 page->fmark.i = 0;
3229 page->fmark.span = block->lines->first_span;
3231 line = &block->lines[block->len - 1];
3232 page->lmark.i = line->last_span->len - 1;
3233 page->lmark.span = line->last_span;
3234 ret_v = Val_bool (1);
3235 goto unlock;
3238 for (line = block->lines;
3239 line < block->lines + block->len;
3240 ++line) {
3241 fz_stext_span *span;
3243 b = &line->bbox;
3244 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3245 continue;
3247 if (mark == mark_line) {
3248 page->fmark.i = 0;
3249 page->fmark.span = line->first_span;
3251 page->lmark.i = line->last_span->len - 1;
3252 page->lmark.span = line->last_span;
3253 ret_v = Val_bool (1);
3254 goto unlock;
3257 for (span = line->first_span; span; span = span->next) {
3258 int charnum;
3260 b = &span->bbox;
3261 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3262 continue;
3264 for (charnum = 0; charnum < span->len; ++charnum) {
3265 fz_rect bbox;
3266 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3267 b = &bbox;
3269 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3270 /* unicode ftw */
3271 int charnum2, charnum3 = -1, charnum4 = -1;
3273 if (uninteresting (span->text[charnum].c)) goto unlock;
3275 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3276 if (uninteresting (span->text[charnum2].c)) {
3277 charnum3 = charnum2 + 1;
3278 break;
3281 if (charnum3 == -1) charnum3 = 0;
3283 charnum4 = charnum;
3284 for (charnum2 = charnum + 1;
3285 charnum2 < span->len;
3286 ++charnum2) {
3287 if (uninteresting (span->text[charnum2].c)) break;
3288 charnum4 = charnum2;
3291 page->fmark.i = charnum3;
3292 page->fmark.span = span;
3294 page->lmark.i = charnum4;
3295 page->lmark.span = span;
3296 ret_v = Val_bool (1);
3297 goto unlock;
3303 unlock:
3304 if (!Bool_val (ret_v)) {
3305 page->fmark.span = NULL;
3306 page->lmark.span = NULL;
3307 page->fmark.i = 0;
3308 page->lmark.i = 0;
3310 unlock (__func__);
3312 done:
3313 CAMLreturn (ret_v);
3316 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3318 CAMLparam3 (ptr_v, x_v, y_v);
3319 CAMLlocal2 (ret_v, res_v);
3320 fz_rect *b = NULL;
3321 struct page *page;
3322 fz_page_block *pageb;
3323 struct pagedim *pdim;
3324 char *s = String_val (ptr_v);
3325 int x = Int_val (x_v), y = Int_val (y_v);
3327 ret_v = Val_int (0);
3328 if (trylock (__func__)) {
3329 goto done;
3332 page = parse_pointer (__func__, s);
3333 pdim = &state.pagedims[page->pdimno];
3334 x += pdim->bounds.x0;
3335 y += pdim->bounds.y0;
3337 ensuretext (page);
3339 for (pageb = page->text->blocks;
3340 pageb < page->text->blocks + page->text->len;
3341 ++pageb) {
3342 switch (pageb->type) {
3343 case FZ_PAGE_BLOCK_TEXT:
3344 b = &pageb->u.text->bbox;
3345 break;
3347 case FZ_PAGE_BLOCK_IMAGE:
3348 b = &pageb->u.image->bbox;
3349 break;
3351 default:
3352 continue;
3355 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3356 break;
3357 b = NULL;
3359 if (b) {
3360 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3361 ret_v = caml_alloc_small (1, 1);
3362 Store_double_field (res_v, 0, b->x0);
3363 Store_double_field (res_v, 1, b->x1);
3364 Store_double_field (res_v, 2, b->y0);
3365 Store_double_field (res_v, 3, b->y1);
3366 Field (ret_v, 0) = res_v;
3368 unlock (__func__);
3370 done:
3371 CAMLreturn (ret_v);
3374 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3376 CAMLparam2 (ptr_v, rect_v);
3377 fz_rect b;
3378 struct page *page;
3379 struct pagedim *pdim;
3380 char *s = String_val (ptr_v);
3381 int i, x0, x1, y0, y1, fi, li;
3382 fz_stext_line *line;
3383 fz_page_block *pageb;
3384 fz_stext_block *block;
3385 fz_stext_span *span, *fspan, *lspan;
3387 if (trylock (__func__)) {
3388 goto done;
3391 page = parse_pointer (__func__, s);
3392 ensuretext (page);
3394 pdim = &state.pagedims[page->pdimno];
3395 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3396 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3397 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3398 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3400 if (y0 > y1) {
3401 int t = y0;
3402 y0 = y1;
3403 y1 = t;
3404 x0 = x1;
3405 x1 = t;
3408 fi = page->fmark.i;
3409 fspan = page->fmark.span;
3411 li = page->lmark.i;
3412 lspan = page->lmark.span;
3414 for (pageb = page->text->blocks;
3415 pageb < page->text->blocks + page->text->len;
3416 ++pageb) {
3417 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3418 block = pageb->u.text;
3419 for (line = block->lines;
3420 line < block->lines + block->len;
3421 ++line) {
3423 for (span = line->first_span; span; span = span->next) {
3424 for (i = 0; i < span->len; ++i) {
3425 fz_stext_char_bbox (state.ctx, &b, span, i);
3427 if (x0 >= b.x0 && x0 <= b.x1
3428 && y0 >= b.y0 && y0 <= b.y1) {
3429 fspan = span;
3430 fi = i;
3432 if (x1 >= b.x0 && x1 <= b.x1
3433 && y1 >= b.y0 && y1 <= b.y1) {
3434 lspan = span;
3435 li = i;
3441 if (x1 < x0 && fspan == lspan) {
3442 i = fi;
3443 span = fspan;
3445 fi = li;
3446 fspan = lspan;
3448 li = i;
3449 lspan = span;
3452 page->fmark.i = fi;
3453 page->fmark.span = fspan;
3455 page->lmark.i = li;
3456 page->lmark.span = lspan;
3458 unlock (__func__);
3460 done:
3461 CAMLreturn (Val_unit);
3464 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3466 char buf[4];
3467 int i, len, ret;
3469 for (i = a; i <= b; ++i) {
3470 len = fz_runetochar (buf, span->text[i].c);
3471 ret = fwrite (buf, len, 1, f);
3473 if (ret != 1) {
3474 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3475 len, ret, strerror (errno));
3476 return -1;
3479 return 0;
3482 #ifdef __CYGWIN__
3483 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3485 caml_failwith ("ml_popen not implemented under Cygwin");
3487 #else
3488 CAMLprim value ml_spawn (value command_v, value fds_v)
3490 CAMLparam2 (command_v, fds_v);
3491 CAMLlocal2 (l_v, tup_v);
3492 int ret, ret1;
3493 pid_t pid;
3494 char *msg = NULL;
3495 value earg_v = Nothing;
3496 posix_spawnattr_t attr;
3497 posix_spawn_file_actions_t fa;
3498 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3500 argv[2] = String_val (command_v);
3502 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3503 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3506 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3507 msg = "posix_spawnattr_init";
3508 goto fail1;
3511 #ifdef POSIX_SPAWN_USEVFORK
3512 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3513 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3514 goto fail;
3516 #endif
3518 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3519 int fd1, fd2;
3521 tup_v = Field (l_v, 0);
3522 fd1 = Int_val (Field (tup_v, 0));
3523 fd2 = Int_val (Field (tup_v, 1));
3524 if (fd2 < 0) {
3525 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3526 msg = "posix_spawn_file_actions_addclose";
3527 earg_v = tup_v;
3528 goto fail;
3531 else {
3532 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3533 msg = "posix_spawn_file_actions_adddup2";
3534 earg_v = tup_v;
3535 goto fail;
3540 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3541 msg = "posix_spawn";
3542 goto fail;
3545 fail:
3546 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3547 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3550 fail1:
3551 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3552 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3553 strerror (ret1));
3556 if (msg)
3557 unix_error (ret, msg, earg_v);
3559 CAMLreturn (Val_int (pid));
3561 #endif
3563 CAMLprim value ml_hassel (value ptr_v)
3565 CAMLparam1 (ptr_v);
3566 CAMLlocal1 (ret_v);
3567 struct page *page;
3568 char *s = String_val (ptr_v);
3570 ret_v = Val_bool (0);
3571 if (trylock (__func__)) {
3572 goto done;
3575 page = parse_pointer (__func__, s);
3576 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3577 unlock (__func__);
3578 done:
3579 CAMLreturn (ret_v);
3582 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3584 CAMLparam2 (fd_v, ptr_v);
3585 FILE *f;
3586 int seen = 0;
3587 struct page *page;
3588 fz_stext_line *line;
3589 fz_page_block *pageb;
3590 fz_stext_block *block;
3591 int fd = Int_val (fd_v);
3592 char *s = String_val (ptr_v);
3594 if (trylock (__func__)) {
3595 goto done;
3598 page = parse_pointer (__func__, s);
3600 if (!page->fmark.span || !page->lmark.span) {
3601 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3602 goto unlock;
3605 f = fdopen (fd, "w");
3606 if (!f) {
3607 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3608 fd, strerror (errno));
3609 f = stdout;
3612 for (pageb = page->text->blocks;
3613 pageb < page->text->blocks + page->text->len;
3614 ++pageb) {
3615 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3616 block = pageb->u.text;
3617 for (line = block->lines;
3618 line < block->lines + block->len;
3619 ++line) {
3620 fz_stext_span *span;
3622 for (span = line->first_span; span; span = span->next) {
3623 int a, b;
3625 seen |= span == page->fmark.span || span == page->lmark.span;
3626 a = span == page->fmark.span ? page->fmark.i : 0;
3627 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3629 if (seen) {
3630 if (pipespan (f, span, a, b)) {
3631 goto close;
3633 if (span == page->lmark.span) {
3634 goto close;
3636 if (span == line->last_span) {
3637 if (putc ('\n', f) == EOF) {
3638 fprintf (stderr,
3639 "failed break line on sel pipe: %s\n",
3640 strerror (errno));
3641 goto close;
3648 close:
3649 if (f != stdout) {
3650 int ret = fclose (f);
3651 fd = -1;
3652 if (ret == -1) {
3653 if (errno != ECHILD) {
3654 fprintf (stderr, "failed to close sel pipe: %s\n",
3655 strerror (errno));
3659 unlock:
3660 unlock (__func__);
3662 done:
3663 if (fd >= 0) {
3664 if (close (fd)) {
3665 fprintf (stderr, "failed to close sel pipe: %s\n",
3666 strerror (errno));
3669 CAMLreturn (Val_unit);
3672 CAMLprim value ml_getpdimrect (value pagedimno_v)
3674 CAMLparam1 (pagedimno_v);
3675 CAMLlocal1 (ret_v);
3676 int pagedimno = Int_val (pagedimno_v);
3677 fz_rect box;
3679 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3680 if (trylock (__func__)) {
3681 box = fz_empty_rect;
3683 else {
3684 box = state.pagedims[pagedimno].mediabox;
3685 unlock (__func__);
3688 Store_double_field (ret_v, 0, box.x0);
3689 Store_double_field (ret_v, 1, box.x1);
3690 Store_double_field (ret_v, 2, box.y0);
3691 Store_double_field (ret_v, 3, box.y1);
3693 CAMLreturn (ret_v);
3696 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3697 value dw_v, value cols_v)
3699 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3700 CAMLlocal1 (ret_v);
3701 int i;
3702 double zoom = -1.;
3703 double maxh = 0.0;
3704 struct pagedim *p;
3705 double winw = Int_val (winw_v);
3706 double winh = Int_val (winh_v);
3707 double dw = Int_val (dw_v);
3708 double cols = Int_val (cols_v);
3709 double pw = 1.0, ph = 1.0;
3711 if (trylock (__func__)) {
3712 goto done;
3715 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3716 double w = p->pagebox.x1 / cols;
3717 double h = p->pagebox.y1;
3718 if (h > maxh) {
3719 maxh = h;
3720 ph = h;
3721 if (state.fitmodel != FitProportional) pw = w;
3723 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3726 zoom = (((winh / ph) * pw) + dw) / winw;
3727 unlock (__func__);
3728 done:
3729 ret_v = caml_copy_double (zoom);
3730 CAMLreturn (ret_v);
3733 CAMLprim value ml_getmaxw (value unit_v)
3735 CAMLparam1 (unit_v);
3736 CAMLlocal1 (ret_v);
3737 int i;
3738 double maxw = -1.;
3739 struct pagedim *p;
3741 if (trylock (__func__)) {
3742 goto done;
3745 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3746 double w = p->pagebox.x1;
3747 maxw = fz_max (maxw, w);
3750 unlock (__func__);
3751 done:
3752 ret_v = caml_copy_double (maxw);
3753 CAMLreturn (ret_v);
3756 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3758 CAMLparam4 (pt_v, x_v, y_v, string_v);
3759 CAMLlocal1 (ret_v);
3760 int pt = Int_val(pt_v);
3761 int x = Int_val (x_v);
3762 int y = Int_val (y_v);
3763 double w;
3765 w = draw_string (state.face, pt, x, y, String_val (string_v));
3766 ret_v = caml_copy_double (w);
3767 CAMLreturn (ret_v);
3770 CAMLprim value ml_measure_string (value pt_v, value string_v)
3772 CAMLparam2 (pt_v, string_v);
3773 CAMLlocal1 (ret_v);
3774 int pt = Int_val (pt_v);
3775 double w;
3777 w = measure_string (state.face, pt, String_val (string_v));
3778 ret_v = caml_copy_double (w);
3779 CAMLreturn (ret_v);
3782 CAMLprim value ml_getpagebox (value opaque_v)
3784 CAMLparam1 (opaque_v);
3785 CAMLlocal1 (ret_v);
3786 fz_rect rect;
3787 fz_irect bbox;
3788 fz_matrix ctm;
3789 fz_device *dev;
3790 char *s = String_val (opaque_v);
3791 struct page *page = parse_pointer (__func__, s);
3793 ret_v = caml_alloc_tuple (4);
3794 dev = fz_new_bbox_device (state.ctx, &rect);
3795 dev->hints |= FZ_IGNORE_SHADE;
3797 ctm = pagectm (page);
3798 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3800 fz_close_device (state.ctx, dev);
3801 fz_drop_device (state.ctx, dev);
3802 fz_round_rect (&bbox, &rect);
3803 Field (ret_v, 0) = Val_int (bbox.x0);
3804 Field (ret_v, 1) = Val_int (bbox.y0);
3805 Field (ret_v, 2) = Val_int (bbox.x1);
3806 Field (ret_v, 3) = Val_int (bbox.y1);
3808 CAMLreturn (ret_v);
3811 CAMLprim value ml_setaalevel (value level_v)
3813 CAMLparam1 (level_v);
3815 state.aalevel = Int_val (level_v);
3816 CAMLreturn (Val_unit);
3819 #pragma GCC diagnostic push
3820 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3821 #include <X11/Xlib.h>
3822 #include <X11/cursorfont.h>
3823 #pragma GCC diagnostic pop
3825 #ifdef USE_EGL
3826 #include <EGL/egl.h>
3827 #else
3828 #include <GL/glx.h>
3829 #endif
3831 static const int shapes[] = {
3832 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3835 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3837 static struct {
3838 Window wid;
3839 Display *dpy;
3840 #ifdef USE_EGL
3841 EGLContext ctx;
3842 EGLConfig conf;
3843 EGLSurface win;
3844 EGLDisplay *edpy;
3845 #else
3846 GLXContext ctx;
3847 #endif
3848 XVisualInfo *visual;
3849 Cursor curs[CURS_COUNT];
3850 } glx;
3852 #ifdef VISAVIS
3853 static VisualID initvisual (void)
3855 /* On this system with: `Haswell-ULT Integrated Graphics
3856 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3857 using glX chosen visual and auto scrolling some document in
3858 fullscreen the power/energy-gpu is more than 1 joule bigger
3859 than when using hand picked visual that stands alone in glxinfo
3860 output: it's dead last in the list and it's the only one with
3861 `visual dep' (sic) of 32
3863 No clue what's going on here...
3865 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3867 XVisualInfo info;
3868 int ret = 1;
3870 info.depth = 32;
3871 info.class = TrueColor;
3872 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3873 &info, &ret);
3874 if (!ret || !glx.visual) {
3875 XCloseDisplay (glx.dpy);
3876 caml_failwith ("XGetVisualInfo");
3878 return glx.visual->visualid;
3880 #endif
3882 static void initcurs (void)
3884 for (size_t n = 0; n < CURS_COUNT; ++n) {
3885 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3889 CAMLprim void ml_setbgcol (value color_v)
3891 CAMLparam1 (color_v);
3892 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3893 CAMLreturn0;
3896 #ifdef USE_EGL
3897 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3899 CAMLparam3 (display_v, wid_v, screen_v);
3900 int major, minor;
3901 int num_conf;
3902 EGLint visid;
3903 EGLint attribs[] = {
3904 #ifdef VISAVIS
3905 EGL_NATIVE_VISUAL_ID, 0,
3906 #else
3907 EGL_DEPTH_SIZE, 24,
3908 #endif
3909 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3910 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3911 EGL_NONE
3913 EGLConfig conf;
3915 glx.dpy = XOpenDisplay (String_val (display_v));
3916 if (!glx.dpy) {
3917 caml_failwith ("XOpenDisplay");
3920 eglBindAPI (EGL_OPENGL_API);
3922 glx.edpy = eglGetDisplay (glx.dpy);
3923 if (glx.edpy == EGL_NO_DISPLAY) {
3924 caml_failwith ("eglGetDisplay");
3927 if (!eglInitialize (glx.edpy, &major, &minor)) {
3928 caml_failwith ("eglInitialize");
3931 #ifdef VISAVIS
3932 attribs[1] = visid = initvisual ();
3933 #endif
3935 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3936 !num_conf) {
3937 caml_failwith ("eglChooseConfig");
3940 glx.conf = conf;
3941 #ifndef VISAVIS
3942 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
3943 EGL_NATIVE_VISUAL_ID, &visid)) {
3944 caml_failwith ("eglGetConfigAttrib");
3946 #endif
3947 initcurs ();
3949 glx.wid = Int_val (wid_v);
3950 CAMLreturn (Val_int (visid));
3953 CAMLprim value ml_glxcompleteinit (value unit_v)
3955 CAMLparam1 (unit_v);
3957 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3958 if (!glx.ctx) {
3959 caml_failwith ("eglCreateContext");
3962 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3963 glx.wid, NULL);
3964 if (glx.win == EGL_NO_SURFACE) {
3965 caml_failwith ("eglCreateWindowSurface");
3968 XFree (glx.visual);
3969 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3970 glx.ctx = NULL;
3971 caml_failwith ("eglMakeCurrent");
3973 CAMLreturn (Val_unit);
3975 #else
3976 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3978 CAMLparam3 (display_v, wid_v, screen_v);
3980 glx.dpy = XOpenDisplay (String_val (display_v));
3981 if (!glx.dpy) {
3982 caml_failwith ("XOpenDisplay");
3985 #ifdef VISAVIS
3986 initvisual ();
3987 #else
3988 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3989 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3990 if (!glx.visual) {
3991 XCloseDisplay (glx.dpy);
3992 caml_failwith ("glXChooseVisual");
3994 #endif
3995 initcurs ();
3997 glx.wid = Int_val (wid_v);
3998 CAMLreturn (Val_int (glx.visual->visualid));
4001 CAMLprim value ml_glxcompleteinit (value unit_v)
4003 CAMLparam1 (unit_v);
4005 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4006 if (!glx.ctx) {
4007 caml_failwith ("glXCreateContext");
4010 XFree (glx.visual);
4011 glx.visual = NULL;
4013 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4014 glXDestroyContext (glx.dpy, glx.ctx);
4015 glx.ctx = NULL;
4016 caml_failwith ("glXMakeCurrent");
4018 CAMLreturn (Val_unit);
4020 #endif
4022 CAMLprim value ml_setcursor (value cursor_v)
4024 CAMLparam1 (cursor_v);
4025 size_t cursn = Int_val (cursor_v);
4027 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4028 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4029 XFlush (glx.dpy);
4030 CAMLreturn (Val_unit);
4033 CAMLprim value ml_swapb (value unit_v)
4035 CAMLparam1 (unit_v);
4036 #ifdef USE_EGL
4037 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4038 caml_failwith ("eglSwapBuffers");
4040 #else
4041 glXSwapBuffers (glx.dpy, glx.wid);
4042 #endif
4043 CAMLreturn (Val_unit);
4046 #include "keysym2ucs.c"
4048 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4050 CAMLparam1 (keysym_v);
4051 CAMLlocal1 (str_v);
4052 KeySym keysym = Int_val (keysym_v);
4053 Rune rune;
4054 int len;
4055 char buf[5];
4057 rune = keysym2ucs (keysym);
4058 len = fz_runetochar (buf, rune);
4059 buf[len] = 0;
4060 str_v = caml_copy_string (buf);
4061 CAMLreturn (str_v);
4064 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4066 CAMLprim value ml_platform (value unit_v)
4068 CAMLparam1 (unit_v);
4069 CAMLlocal2 (tup_v, arr_v);
4070 int platid = piunknown;
4071 struct utsname buf;
4073 #if defined __linux__
4074 platid = pilinux;
4075 #elif defined __CYGWIN__
4076 platid = picygwin;
4077 #elif defined __DragonFly__ || defined __FreeBSD__
4078 || defined __OpenBSD__ || defined __NetBSD__
4079 platid = pibsd;
4080 #elif defined __sun__
4081 platid = pisun;
4082 #elif defined __APPLE__
4083 platid = piosx;
4084 #endif
4085 if (uname (&buf)) err (1, "uname");
4087 tup_v = caml_alloc_tuple (2);
4089 char const *sar[] = {
4090 buf.sysname,
4091 buf.release,
4092 buf.version,
4093 buf.machine,
4094 NULL
4096 arr_v = caml_copy_string_array (sar);
4098 Field (tup_v, 0) = Val_int (platid);
4099 Field (tup_v, 1) = arr_v;
4100 CAMLreturn (tup_v);
4103 CAMLprim value ml_cloexec (value fd_v)
4105 CAMLparam1 (fd_v);
4106 int fd = Int_val (fd_v);
4108 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4109 uerror ("fcntl", Nothing);
4111 CAMLreturn (Val_unit);
4114 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4116 CAMLparam2 (w_v, h_v);
4117 CAMLlocal1 (ret_v);
4118 struct bo *pbo;
4119 int w = Int_val (w_v);
4120 int h = Int_val (h_v);
4121 int cs = Int_val (cs_v);
4123 if (state.bo_usable) {
4124 pbo = calloc (sizeof (*pbo), 1);
4125 if (!pbo) {
4126 err (1, "calloc pbo");
4129 switch (cs) {
4130 case 0:
4131 case 1:
4132 pbo->size = w*h*4;
4133 break;
4134 case 2:
4135 pbo->size = w*h*2;
4136 break;
4137 default:
4138 errx (1, "%s: invalid colorspace %d", __func__, cs);
4141 state.glGenBuffersARB (1, &pbo->id);
4142 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4143 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4144 NULL, GL_STREAM_DRAW);
4145 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4146 GL_READ_WRITE);
4147 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4148 if (!pbo->ptr) {
4149 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4150 state.glDeleteBuffersARB (1, &pbo->id);
4151 free (pbo);
4152 ret_v = caml_copy_string ("0");
4154 else {
4155 int res;
4156 char *s;
4158 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4159 if (res < 0) {
4160 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4162 s = malloc (res+1);
4163 if (!s) {
4164 err (1, "malloc %d bytes failed", res+1);
4166 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4167 if (res < 0) {
4168 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4170 ret_v = caml_copy_string (s);
4171 free (s);
4174 else {
4175 ret_v = caml_copy_string ("0");
4177 CAMLreturn (ret_v);
4180 CAMLprim value ml_freepbo (value s_v)
4182 CAMLparam1 (s_v);
4183 char *s = String_val (s_v);
4184 struct tile *tile = parse_pointer (__func__, s);
4186 if (tile->pbo) {
4187 state.glDeleteBuffersARB (1, &tile->pbo->id);
4188 tile->pbo->id = -1;
4189 tile->pbo->ptr = NULL;
4190 tile->pbo->size = -1;
4192 CAMLreturn (Val_unit);
4195 CAMLprim value ml_unmappbo (value s_v)
4197 CAMLparam1 (s_v);
4198 char *s = String_val (s_v);
4199 struct tile *tile = parse_pointer (__func__, s);
4201 if (tile->pbo) {
4202 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4203 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4204 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4206 tile->pbo->ptr = NULL;
4207 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4209 CAMLreturn (Val_unit);
4212 static void setuppbo (void)
4214 #ifdef USE_EGL
4215 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4216 #else
4217 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4218 #endif
4219 state.bo_usable = GGPA (glBindBufferARB)
4220 && GGPA (glUnmapBufferARB)
4221 && GGPA (glMapBufferARB)
4222 && GGPA (glBufferDataARB)
4223 && GGPA (glGenBuffersARB)
4224 && GGPA (glDeleteBuffersARB);
4225 #undef GGPA
4228 CAMLprim value ml_bo_usable (value unit_v)
4230 CAMLparam1 (unit_v);
4231 CAMLreturn (Val_bool (state.bo_usable));
4234 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4236 CAMLparam3 (ptr_v, x_v, y_v);
4237 CAMLlocal2 (ret_v, tup_v);
4238 struct page *page;
4239 char *s = String_val (ptr_v);
4240 int x = Int_val (x_v), y = Int_val (y_v);
4241 struct pagedim *pdim;
4242 fz_point p;
4243 fz_matrix ctm;
4245 page = parse_pointer (__func__, s);
4246 pdim = &state.pagedims[page->pdimno];
4248 ret_v = Val_int (0);
4249 if (trylock (__func__)) {
4250 goto done;
4253 if (pdf_specifics (state.ctx, state.doc)) {
4254 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4255 ctm = state.pagedims[page->pdimno].tctm;
4257 else {
4258 ctm = fz_identity;
4260 p.x = x + pdim->bounds.x0;
4261 p.y = y + pdim->bounds.y0;
4263 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4264 fz_invert_matrix (&ctm, &ctm);
4265 fz_transform_point (&p, &ctm);
4267 tup_v = caml_alloc_tuple (2);
4268 ret_v = caml_alloc_small (1, 1);
4269 Field (tup_v, 0) = Val_int (p.x);
4270 Field (tup_v, 1) = Val_int (p.y);
4271 Field (ret_v, 0) = tup_v;
4273 unlock (__func__);
4274 done:
4275 CAMLreturn (ret_v);
4278 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4279 value x_v, value y_v)
4281 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4282 CAMLlocal1 (ret_v);
4283 struct page *page;
4284 char *s = String_val (ptr_v);
4285 int pageno = Int_val (pageno_v);
4286 int pdimno = Int_val (pdimno_v);
4287 double x = Double_val (x_v), y = Double_val (y_v);
4288 struct pagedim *pdim;
4289 fz_point p;
4290 fz_matrix ctm;
4292 ret_v = Val_int (0);
4293 lock (__func__);
4295 if (!*s) {
4296 page = loadpage (pageno, pdimno);
4298 else {
4299 page = parse_pointer (__func__, s);
4301 pdim = &state.pagedims[pdimno];
4303 if (pdf_specifics (state.ctx, state.doc)) {
4304 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4305 ctm = state.pagedims[page->pdimno].tctm;
4307 else {
4308 ctm = fz_identity;
4310 p.x = x + pdim->bounds.x0;
4311 p.y = y + pdim->bounds.y0;
4313 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4314 fz_transform_point (&p, &ctm);
4316 ret_v = caml_alloc_tuple (2);
4317 Field (ret_v, 0) = caml_copy_double (p.x);
4318 Field (ret_v, 1) = caml_copy_double (p.y);
4320 if (!*s) {
4321 freepage (page);
4323 unlock (__func__);
4324 CAMLreturn (ret_v);
4327 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4328 value contents_v)
4330 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4331 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4333 if (pdf) {
4334 pdf_annot *annot;
4335 struct page *page;
4336 fz_point p;
4337 char *s = String_val (ptr_v);
4339 page = parse_pointer (__func__, s);
4340 annot = pdf_create_annot (state.ctx,
4341 pdf_page_from_fz_page (state.ctx,
4342 page->fzpage),
4343 PDF_ANNOT_TEXT);
4344 p.x = Int_val (x_v);
4345 p.y = Int_val (y_v);
4346 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4347 pdf_set_text_annot_position (state.ctx, annot, p);
4348 state.dirty = 1;
4350 CAMLreturn (Val_unit);
4353 CAMLprim value ml_delannot (value ptr_v, value n_v)
4355 CAMLparam2 (ptr_v, n_v);
4356 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4358 if (pdf) {
4359 struct page *page;
4360 char *s = String_val (ptr_v);
4361 struct slink *slink;
4363 page = parse_pointer (__func__, s);
4364 slink = &page->slinks[Int_val (n_v)];
4365 pdf_delete_annot (state.ctx,
4366 pdf_page_from_fz_page (state.ctx, page->fzpage),
4367 (pdf_annot *) slink->u.annot);
4368 state.dirty = 1;
4370 CAMLreturn (Val_unit);
4373 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4375 CAMLparam3 (ptr_v, n_v, str_v);
4376 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4378 if (pdf) {
4379 struct page *page;
4380 char *s = String_val (ptr_v);
4381 struct slink *slink;
4383 page = parse_pointer (__func__, s);
4384 slink = &page->slinks[Int_val (n_v)];
4385 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4386 String_val (str_v));
4387 state.dirty = 1;
4389 CAMLreturn (Val_unit);
4392 CAMLprim value ml_hasunsavedchanges (value unit_v)
4394 CAMLparam1 (unit_v);
4395 CAMLreturn (Val_bool (state.dirty));
4398 CAMLprim value ml_savedoc (value path_v)
4400 CAMLparam1 (path_v);
4401 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4403 if (pdf) {
4404 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4406 CAMLreturn (Val_unit);
4409 static void makestippletex (void)
4411 const char pixels[] = "\xff\xff\0\0";
4412 glGenTextures (1, &state.stid);
4413 glBindTexture (GL_TEXTURE_1D, state.stid);
4414 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4415 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4416 glTexImage1D (
4417 GL_TEXTURE_1D,
4419 GL_ALPHA,
4422 GL_ALPHA,
4423 GL_UNSIGNED_BYTE,
4424 pixels
4428 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4430 return caml_copy_string (FZ_VERSION);
4433 #ifdef USE_FONTCONFIG
4434 static struct {
4435 int inited;
4436 FcConfig *config;
4437 } fc;
4439 static fz_font *fc_load_system_font_func (fz_context *ctx,
4440 const char *name,
4441 int bold,
4442 int italic,
4443 int UNUSED_ATTR needs_exact_metrics)
4445 char *buf;
4446 size_t i, size;
4447 fz_font *font;
4448 FcChar8 *path;
4449 FcResult result;
4450 FcPattern *pat, *pat1;
4452 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4453 name, bold, italic, needs_exact_metrics);
4454 if (!fc.inited) {
4455 fc.inited = 1;
4456 fc.config = FcInitLoadConfigAndFonts ();
4457 if (!fc.config) {
4458 lprintf ("FcInitLoadConfigAndFonts failed\n");
4459 return NULL;
4462 if (!fc.config) return NULL;
4464 size = strlen (name);
4465 if (bold) size += sizeof (":bold") - 1;
4466 if (italic) size += sizeof (":italic") - 1;
4467 size += 1;
4469 buf = malloc (size);
4470 if (!buf) {
4471 err (1, "malloc %zu failed", size);
4474 strcpy (buf, name);
4475 if (bold && italic) {
4476 strcat (buf, ":bold:italic");
4478 else {
4479 if (bold) strcat (buf, ":bold");
4480 if (italic) strcat (buf, ":italic");
4482 for (i = 0; i < size; ++i) {
4483 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4486 lprintf ("fcbuf=%s\n", buf);
4487 pat = FcNameParse ((FcChar8 *) buf);
4488 if (!pat) {
4489 printd ("emsg FcNameParse failed\n");
4490 free (buf);
4491 return NULL;
4494 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4495 printd ("emsg FcConfigSubstitute failed\n");
4496 free (buf);
4497 return NULL;
4499 FcDefaultSubstitute (pat);
4501 pat1 = FcFontMatch (fc.config, pat, &result);
4502 if (!pat1) {
4503 printd ("emsg FcFontMatch failed\n");
4504 FcPatternDestroy (pat);
4505 free (buf);
4506 return NULL;
4509 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4510 printd ("emsg FcPatternGetString failed\n");
4511 FcPatternDestroy (pat);
4512 FcPatternDestroy (pat1);
4513 free (buf);
4514 return NULL;
4517 #if 0
4518 printd ("emsg name=%s path=%s\n", name, path);
4519 #endif
4520 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4521 FcPatternDestroy (pat);
4522 FcPatternDestroy (pat1);
4523 free (buf);
4524 return font;
4526 #endif
4528 CAMLprim value ml_init (value csock_v, value params_v)
4530 CAMLparam2 (csock_v, params_v);
4531 CAMLlocal2 (trim_v, fuzz_v);
4532 int ret;
4533 int texcount;
4534 char *fontpath;
4535 int colorspace;
4536 int mustoresize;
4537 int haspboext;
4539 state.csock = Int_val (csock_v);
4540 state.rotate = Int_val (Field (params_v, 0));
4541 state.fitmodel = Int_val (Field (params_v, 1));
4542 trim_v = Field (params_v, 2);
4543 texcount = Int_val (Field (params_v, 3));
4544 state.sliceheight = Int_val (Field (params_v, 4));
4545 mustoresize = Int_val (Field (params_v, 5));
4546 colorspace = Int_val (Field (params_v, 6));
4547 fontpath = String_val (Field (params_v, 7));
4549 if (caml_string_length (Field (params_v, 8)) > 0) {
4550 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4552 if (!state.trimcachepath) {
4553 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4554 strerror (errno));
4557 haspboext = Bool_val (Field (params_v, 9));
4559 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4560 fz_register_document_handlers (state.ctx);
4562 #ifdef USE_FONTCONFIG
4563 if (Bool_val (Field (params_v, 10))) {
4564 fz_install_load_system_font_funcs (
4565 state.ctx, fc_load_system_font_func, NULL
4568 #endif
4570 state.trimmargins = Bool_val (Field (trim_v, 0));
4571 fuzz_v = Field (trim_v, 1);
4572 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4573 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4574 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4575 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4577 set_tex_params (colorspace);
4579 if (*fontpath) {
4580 #ifndef USE_FONTCONFIG
4581 state.face = load_font (fontpath);
4582 #else
4583 FcChar8 *path;
4584 FcResult result;
4585 char *buf = fontpath;
4586 FcPattern *pat, *pat1;
4588 fc.inited = 1;
4589 fc.config = FcInitLoadConfigAndFonts ();
4590 if (!fc.config) {
4591 errx (1, "FcInitLoadConfigAndFonts failed");
4594 pat = FcNameParse ((FcChar8 *) buf);
4595 if (!pat) {
4596 errx (1, "FcNameParse failed");
4599 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4600 errx (1, "FcConfigSubstitute failed");
4602 FcDefaultSubstitute (pat);
4604 pat1 = FcFontMatch (fc.config, pat, &result);
4605 if (!pat1) {
4606 errx (1, "FcFontMatch failed");
4609 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4610 errx (1, "FcPatternGetString failed");
4613 state.face = load_font ((char *) path);
4614 FcPatternDestroy (pat);
4615 FcPatternDestroy (pat1);
4616 #endif
4618 else {
4619 int len;
4620 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4621 0, 0, &len);
4622 state.face = load_builtin_font (data, len);
4624 if (!state.face) _exit (1);
4626 realloctexts (texcount);
4628 if (haspboext) {
4629 setuppbo ();
4632 makestippletex ();
4634 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4635 if (ret) {
4636 errx (1, "pthread_create: %s", strerror (ret));
4639 CAMLreturn (Val_unit);