Sync with upstream
[llpp.git] / link.c
blobc64b31dbfaecc7bc448e2b6eb9780726f6bee252
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 static
1238 struct anchor { int n; int x; int y; int w; int h; }
1239 uritoanchor (const char *uri)
1241 fz_point p;
1242 struct anchor a;
1244 a.n = -1;
1245 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1246 if (a.n >= 0) {
1247 int i;
1248 struct pagedim *pdim = state.pagedims;
1250 for (i = 0; i < state.pagedimcount; ++i) {
1251 if (state.pagedims[i].pageno > a.n)
1252 break;
1253 pdim = &state.pagedims[i];
1256 fz_transform_point (&p, &pdim->ctm);
1257 a.x = p.x;
1258 a.y = p.y;
1259 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1261 return a;
1264 static void recurse_outline (fz_outline *outline, int level)
1266 while (outline) {
1267 struct anchor a = uritoanchor (outline->uri);
1268 if (a.n >= 0) {
1269 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1271 else {
1272 printd ("on %d %s", level, outline->title);
1274 if (outline->down) {
1275 recurse_outline (outline->down, level + 1);
1277 outline = outline->next;
1281 static void process_outline (void)
1283 fz_outline *outline;
1285 if (!state.needoutline || !state.pagedimcount) return;
1287 state.needoutline = 0;
1288 outline = fz_load_outline (state.ctx, state.doc);
1289 if (outline) {
1290 recurse_outline (outline, 0);
1291 fz_drop_outline (state.ctx, outline);
1295 static char *strofspan (fz_stext_span *span)
1297 char *p;
1298 char utf8[10];
1299 fz_stext_char *ch;
1300 size_t size = 0, cap = 80;
1302 p = malloc (cap + 1);
1303 if (!p) return NULL;
1305 for (ch = span->text; ch < span->text + span->len; ++ch) {
1306 int n = fz_runetochar (utf8, ch->c);
1307 if (size + n > cap) {
1308 cap *= 2;
1309 p = realloc (p, cap + 1);
1310 if (!p) return NULL;
1313 memcpy (p + size, utf8, n);
1314 size += n;
1316 p[size] = 0;
1317 return p;
1320 static int matchspan (regex_t *re, fz_stext_span *span,
1321 int stop, int pageno, double start)
1323 int ret;
1324 char *p;
1325 regmatch_t rm;
1326 int a, b, c;
1327 fz_rect sb, eb;
1328 fz_point p1, p2, p3, p4;
1330 p = strofspan (span);
1331 if (!p) return -1;
1333 ret = regexec (re, p, 1, &rm, 0);
1334 if (ret) {
1335 free (p);
1336 if (ret != REG_NOMATCH) {
1337 size_t size;
1338 char errbuf[80];
1339 size = regerror (ret, re, errbuf, sizeof (errbuf));
1340 printd ("msg regexec error `%.*s'",
1341 (int) size, errbuf);
1342 return -1;
1344 return 0;
1346 else {
1347 int l = span->len;
1349 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1350 c += fz_runelen (span->text[a].c);
1352 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1353 c += fz_runelen (span->text[b].c);
1356 if (fz_runelen (span->text[b].c) > 1) {
1357 b = fz_maxi (0, b-1);
1360 fz_stext_char_bbox (state.ctx, &sb, span, a);
1361 fz_stext_char_bbox (state.ctx, &eb, span, b);
1363 p1.x = sb.x0;
1364 p1.y = sb.y0;
1365 p2.x = eb.x1;
1366 p2.y = sb.y0;
1367 p3.x = eb.x1;
1368 p3.y = eb.y1;
1369 p4.x = sb.x0;
1370 p4.y = eb.y1;
1372 if (!stop) {
1373 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1374 pageno, 1,
1375 p1.x, p1.y,
1376 p2.x, p2.y,
1377 p3.x, p3.y,
1378 p4.x, p4.y);
1380 printd ("progress 1 found at %d `%.*s' in %f sec",
1381 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1382 now () - start);
1384 else {
1385 printd ("match %d %d %f %f %f %f %f %f %f %f",
1386 pageno, 2,
1387 p1.x, p1.y,
1388 p2.x, p2.y,
1389 p3.x, p3.y,
1390 p4.x, p4.y);
1392 free (p);
1393 return 1;
1397 static int compareblocks (const void *l, const void *r)
1399 fz_stext_block const *ls = l;
1400 fz_stext_block const *rs = r;
1401 return ls->bbox.y0 - rs->bbox.y0;
1404 /* wishful thinking function */
1405 static void search (regex_t *re, int pageno, int y, int forward)
1407 int i, j;
1408 fz_device *tdev;
1409 fz_stext_page *text;
1410 fz_stext_sheet *sheet;
1411 struct pagedim *pdim, *pdimprev;
1412 int stop = 0, niters = 0;
1413 double start, end;
1414 fz_page *page;
1416 start = now ();
1417 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1418 if (niters++ == 5) {
1419 niters = 0;
1420 if (hasdata ()) {
1421 printd ("progress 1 attention requested aborting search at %d",
1422 pageno);
1423 stop = 1;
1425 else {
1426 printd ("progress %f searching in page %d",
1427 (double) (pageno + 1) / state.pagecount,
1428 pageno);
1431 pdimprev = NULL;
1432 for (i = 0; i < state.pagedimcount; ++i) {
1433 pdim = &state.pagedims[i];
1434 if (pdim->pageno == pageno) {
1435 goto found;
1437 if (pdim->pageno > pageno) {
1438 pdim = pdimprev;
1439 goto found;
1441 pdimprev = pdim;
1443 pdim = pdimprev;
1444 found:
1446 sheet = fz_new_stext_sheet (state.ctx);
1447 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1448 tdev = fz_new_stext_device (state.ctx, sheet, text, 0);
1450 page = fz_load_page (state.ctx, state.doc, pageno);
1452 fz_matrix ctm = pagectm1 (page, pdim);
1453 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1456 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1457 fz_close_device (state.ctx, tdev);
1458 fz_drop_device (state.ctx, tdev);
1460 for (j = 0; j < text->len; ++j) {
1461 int k;
1462 fz_page_block *pb;
1463 fz_stext_block *block;
1465 pb = &text->blocks[forward ? j : text->len - 1 - j];
1466 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1467 block = pb->u.text;
1469 for (k = 0; k < block->len; ++k) {
1470 fz_stext_line *line;
1471 fz_stext_span *span;
1473 if (forward) {
1474 line = &block->lines[k];
1475 if (line->bbox.y0 < y + 1) continue;
1477 else {
1478 line = &block->lines[block->len - 1 - k];
1479 if (line->bbox.y0 > y - 1) continue;
1482 for (span = line->first_span; span; span = span->next) {
1483 switch (matchspan (re, span, stop, pageno, start)) {
1484 case 0: break;
1485 case 1: stop = 1; break;
1486 case -1: stop = 1; goto endloop;
1491 if (forward) {
1492 pageno += 1;
1493 y = 0;
1495 else {
1496 pageno -= 1;
1497 y = INT_MAX;
1499 endloop:
1500 fz_drop_stext_page (state.ctx, text);
1501 fz_drop_stext_sheet (state.ctx, sheet);
1502 fz_drop_page (state.ctx, page);
1504 end = now ();
1505 if (!stop) {
1506 printd ("progress 1 no matches %f sec", end - start);
1508 printd ("clearrects");
1511 static void set_tex_params (int colorspace)
1513 union {
1514 unsigned char b;
1515 unsigned int s;
1516 } endianness = {1};
1518 switch (colorspace) {
1519 case 0:
1520 state.texiform = GL_RGBA8;
1521 state.texform = GL_RGBA;
1522 state.texty = GL_UNSIGNED_BYTE;
1523 state.colorspace = fz_device_rgb (state.ctx);
1524 break;
1525 case 1:
1526 state.texiform = GL_RGBA8;
1527 state.texform = GL_BGRA;
1528 state.texty = endianness.s > 1
1529 ? GL_UNSIGNED_INT_8_8_8_8
1530 : GL_UNSIGNED_INT_8_8_8_8_REV;
1531 state.colorspace = fz_device_bgr (state.ctx);
1532 break;
1533 case 2:
1534 state.texiform = GL_LUMINANCE_ALPHA;
1535 state.texform = GL_LUMINANCE_ALPHA;
1536 state.texty = GL_UNSIGNED_BYTE;
1537 state.colorspace = fz_device_gray (state.ctx);
1538 break;
1539 default:
1540 errx (1, "invalid colorspce %d", colorspace);
1544 static void realloctexts (int texcount)
1546 size_t size;
1548 if (texcount == state.texcount) return;
1550 if (texcount < state.texcount) {
1551 glDeleteTextures (state.texcount - texcount,
1552 state.texids + texcount);
1555 size = texcount * sizeof (*state.texids);
1556 state.texids = realloc (state.texids, size);
1557 if (!state.texids) {
1558 err (1, "realloc texids %" FMT_s, size);
1561 size = texcount * sizeof (*state.texowners);
1562 state.texowners = realloc (state.texowners, size);
1563 if (!state.texowners) {
1564 err (1, "realloc texowners %" FMT_s, size);
1566 if (texcount > state.texcount) {
1567 int i;
1569 glGenTextures (texcount - state.texcount,
1570 state.texids + state.texcount);
1571 for (i = state.texcount; i < texcount; ++i) {
1572 state.texowners[i].w = -1;
1573 state.texowners[i].slice = NULL;
1576 state.texcount = texcount;
1577 state.texindex = 0;
1580 static char *mbtoutf8 (char *s)
1582 char *p, *r;
1583 wchar_t *tmp;
1584 size_t i, ret, len;
1586 len = mbstowcs (NULL, s, strlen (s));
1587 if (len == 0) {
1588 return s;
1590 else {
1591 if (len == (size_t) -1) {
1592 return s;
1596 tmp = malloc (len * sizeof (wchar_t));
1597 if (!tmp) {
1598 return s;
1601 ret = mbstowcs (tmp, s, len);
1602 if (ret == (size_t) -1) {
1603 free (tmp);
1604 return s;
1607 len = 0;
1608 for (i = 0; i < ret; ++i) {
1609 len += fz_runelen (tmp[i]);
1612 p = r = malloc (len + 1);
1613 if (!r) {
1614 free (tmp);
1615 return s;
1618 for (i = 0; i < ret; ++i) {
1619 p += fz_runetochar (p, tmp[i]);
1621 *p = 0;
1622 free (tmp);
1623 return r;
1626 CAMLprim value ml_transform_page_point (value pageno_v, value x_v, value y_v)
1628 CAMLparam3 (pageno_v, x_v, y_v);
1629 CAMLlocal1 (ret_v);
1630 int i;
1631 struct pagedim *pdim = state.pagedims;
1632 fz_point p = { .x = Int_val (x_v), .y = Int_val (y_v) };
1634 for (i = 0; i < state.pagedimcount; ++i) {
1635 if (state.pagedims[i].pageno > Int_val (pageno_v))
1636 break;
1637 pdim = &state.pagedims[i];
1639 fz_transform_point (&p, &pdim->ctm);
1641 ret_v = caml_alloc_small (2 * Double_wosize, Double_array_tag);
1642 Store_double_field (ret_v, 0, p.x);
1643 Store_double_field (ret_v, 1, p.y);
1644 CAMLreturn (ret_v);
1648 CAMLprim value ml_mbtoutf8 (value s_v)
1650 CAMLparam1 (s_v);
1651 CAMLlocal1 (ret_v);
1652 char *s, *r;
1654 s = String_val (s_v);
1655 r = mbtoutf8 (s);
1656 if (r == s) {
1657 ret_v = s_v;
1659 else {
1660 ret_v = caml_copy_string (r);
1661 free (r);
1663 CAMLreturn (ret_v);
1666 static void * mainloop (void UNUSED_ATTR *unused)
1668 char *p = NULL;
1669 int len, ret, oldlen = 0;
1671 fz_var (p);
1672 fz_var (oldlen);
1673 for (;;) {
1674 len = readlen (state.csock);
1675 if (len == 0) {
1676 errx (1, "readlen returned 0");
1679 if (oldlen < len + 1) {
1680 p = realloc (p, len + 1);
1681 if (!p) {
1682 err (1, "realloc %d failed", len + 1);
1684 oldlen = len + 1;
1686 readdata (state.csock, p, len);
1687 p[len] = 0;
1689 if (!strncmp ("open", p, 4)) {
1690 int wthack, off, ok = 0;
1691 char *password;
1692 char *filename;
1693 char *utf8filename;
1694 size_t filenamelen;
1696 fz_var (ok);
1697 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1698 if (ret != 2) {
1699 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1702 filename = p + 5 + off;
1703 filenamelen = strlen (filename);
1704 password = filename + filenamelen + 1;
1706 lock ("open");
1707 fz_try (state.ctx) {
1708 ok = openxref (filename, password);
1710 fz_catch (state.ctx) {
1711 utf8filename = mbtoutf8 (filename);
1712 printd ("msg Could not open %s", utf8filename);
1714 if (ok) {
1715 pdfinfo ();
1716 initpdims (wthack);
1718 unlock ("open");
1720 if (ok) {
1721 if (!wthack) {
1722 utf8filename = mbtoutf8 (filename);
1723 printd ("msg Opened %s (press h/F1 to get help)",
1724 utf8filename);
1725 if (utf8filename != filename) {
1726 free (utf8filename);
1729 state.needoutline = 1;
1732 else if (!strncmp ("cs", p, 2)) {
1733 int i, colorspace;
1735 ret = sscanf (p + 2, " %d", &colorspace);
1736 if (ret != 1) {
1737 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1739 lock ("cs");
1740 set_tex_params (colorspace);
1741 for (i = 0; i < state.texcount; ++i) {
1742 state.texowners[i].w = -1;
1743 state.texowners[i].slice = NULL;
1745 unlock ("cs");
1747 else if (!strncmp ("freepage", p, 8)) {
1748 void *ptr;
1750 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1751 if (ret != 1) {
1752 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1754 freepage (ptr);
1756 else if (!strncmp ("freetile", p, 8)) {
1757 void *ptr;
1759 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1760 if (ret != 1) {
1761 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1763 freetile (ptr);
1765 else if (!strncmp ("search", p, 6)) {
1766 int icase, pageno, y, len2, forward;
1767 char *pattern;
1768 regex_t re;
1770 ret = sscanf (p + 6, " %d %d %d %d,%n",
1771 &icase, &pageno, &y, &forward, &len2);
1772 if (ret != 4) {
1773 errx (1, "malformed search `%s' ret=%d", p, ret);
1776 pattern = p + 6 + len2;
1777 ret = regcomp (&re, pattern,
1778 REG_EXTENDED | (icase ? REG_ICASE : 0));
1779 if (ret) {
1780 char errbuf[80];
1781 size_t size;
1783 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1784 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1786 else {
1787 search (&re, pageno, y, forward);
1788 regfree (&re);
1791 else if (!strncmp ("geometry", p, 8)) {
1792 int w, h, fitmodel;
1794 printd ("clear");
1795 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1796 if (ret != 3) {
1797 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1800 lock ("geometry");
1801 state.h = h;
1802 if (w != state.w) {
1803 int i;
1804 state.w = w;
1805 for (i = 0; i < state.texcount; ++i) {
1806 state.texowners[i].slice = NULL;
1809 state.fitmodel = fitmodel;
1810 layout ();
1811 process_outline ();
1813 state.gen++;
1814 unlock ("geometry");
1815 printd ("continue %d", state.pagecount);
1817 else if (!strncmp ("reqlayout", p, 9)) {
1818 char *nameddest;
1819 int rotate, off, h;
1820 unsigned int fitmodel;
1821 pdf_document *pdf;
1823 printd ("clear");
1824 ret = sscanf (p + 9, " %d %u %d %n",
1825 &rotate, &fitmodel, &h, &off);
1826 if (ret != 3) {
1827 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1829 lock ("reqlayout");
1830 pdf = pdf_specifics (state.ctx, state.doc);
1831 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1832 state.gen += 1;
1834 state.rotate = rotate;
1835 state.fitmodel = fitmodel;
1836 state.h = h;
1837 layout ();
1838 process_outline ();
1840 nameddest = p + 9 + off;
1841 if (pdf && nameddest && *nameddest) {
1842 #if FIXME
1843 struct anchor a;
1844 fz_link_dest dest;
1845 pdf_obj *needle, *obj;
1847 needle = pdf_new_string (state.ctx, pdf, nameddest,
1848 strlen (nameddest));
1849 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1850 if (obj) {
1851 dest = pdf_parse_link_dest (state.ctx, pdf,
1852 FZ_LINK_GOTO, obj);
1854 a = desttoanchor (&dest);
1855 if (a.n >= 0) {
1856 printd ("a %d %d %d", a.n, a.x, a.y);
1858 else {
1859 printd ("emsg failed to parse destination `%s'\n",
1860 nameddest);
1863 else {
1864 printd ("emsg destination `%s' not found\n",
1865 nameddest);
1867 pdf_drop_obj (state.ctx, needle);
1868 #else
1869 printd ("emsg nameddest `%s'\n", nameddest);
1870 #endif
1873 state.gen++;
1874 unlock ("reqlayout");
1875 printd ("continue %d", state.pagecount);
1877 else if (!strncmp ("page", p, 4)) {
1878 double a, b;
1879 struct page *page;
1880 int pageno, pindex;
1882 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1883 if (ret != 2) {
1884 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1887 lock ("page");
1888 a = now ();
1889 page = loadpage (pageno, pindex);
1890 b = now ();
1891 unlock ("page");
1893 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1895 else if (!strncmp ("tile", p, 4)) {
1896 int x, y, w, h;
1897 struct page *page;
1898 struct tile *tile;
1899 double a, b;
1900 void *data;
1902 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1903 SCN_ptr_cast (&page), &x, &y, &w, &h,
1904 SCN_ptr_cast (&data));
1905 if (ret != 6) {
1906 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1909 lock ("tile");
1910 a = now ();
1911 tile = rendertile (page, x, y, w, h, data);
1912 b = now ();
1913 unlock ("tile");
1915 printd ("tile %d %d %" FMT_ptr " %u %f",
1916 x, y,
1917 FMT_ptr_cast (tile),
1918 tile->w * tile->h * tile->pixmap->n,
1919 b - a);
1921 else if (!strncmp ("trimset", p, 7)) {
1922 fz_irect fuzz;
1923 int trimmargins;
1925 ret = sscanf (p + 7, " %d %d %d %d %d",
1926 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1927 if (ret != 5) {
1928 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1930 lock ("trimset");
1931 state.trimmargins = trimmargins;
1932 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1933 state.trimanew = 1;
1934 state.trimfuzz = fuzz;
1936 unlock ("trimset");
1938 else if (!strncmp ("settrim", p, 7)) {
1939 fz_irect fuzz;
1940 int trimmargins;
1942 ret = sscanf (p + 7, " %d %d %d %d %d",
1943 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1944 if (ret != 5) {
1945 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1947 printd ("clear");
1948 lock ("settrim");
1949 state.trimmargins = trimmargins;
1950 state.needoutline = 1;
1951 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1952 state.trimanew = 1;
1953 state.trimfuzz = fuzz;
1955 state.pagedimcount = 0;
1956 free (state.pagedims);
1957 state.pagedims = NULL;
1958 initpdims (0);
1959 layout ();
1960 process_outline ();
1961 unlock ("settrim");
1962 printd ("continue %d", state.pagecount);
1964 else if (!strncmp ("sliceh", p, 6)) {
1965 int h;
1967 ret = sscanf (p + 6, " %d", &h);
1968 if (ret != 1) {
1969 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1971 if (h != state.sliceheight) {
1972 int i;
1974 state.sliceheight = h;
1975 for (i = 0; i < state.texcount; ++i) {
1976 state.texowners[i].w = -1;
1977 state.texowners[i].h = -1;
1978 state.texowners[i].slice = NULL;
1982 else if (!strncmp ("interrupt", p, 9)) {
1983 printd ("vmsg interrupted");
1985 else {
1986 errx (1, "unknown command %.*s", len, p);
1989 return 0;
1992 CAMLprim value ml_realloctexts (value texcount_v)
1994 CAMLparam1 (texcount_v);
1995 int ok;
1997 if (trylock (__func__)) {
1998 ok = 0;
1999 goto done;
2001 realloctexts (Int_val (texcount_v));
2002 ok = 1;
2003 unlock (__func__);
2005 done:
2006 CAMLreturn (Val_bool (ok));
2009 static void recti (int x0, int y0, int x1, int y1)
2011 GLfloat *v = state.vertices;
2013 glVertexPointer (2, GL_FLOAT, 0, v);
2014 v[0] = x0; v[1] = y0;
2015 v[2] = x1; v[3] = y0;
2016 v[4] = x0; v[5] = y1;
2017 v[6] = x1; v[7] = y1;
2018 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2021 static void showsel (struct page *page, int ox, int oy)
2023 int seen = 0;
2024 fz_irect bbox;
2025 fz_rect rect;
2026 fz_stext_line *line;
2027 fz_page_block *pageb;
2028 fz_stext_block *block;
2029 struct mark first, last;
2030 unsigned char selcolor[] = {15,15,15,140};
2032 first = page->fmark;
2033 last = page->lmark;
2035 if (!first.span || !last.span) return;
2037 glEnable (GL_BLEND);
2038 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2039 glColor4ubv (selcolor);
2041 ox += state.pagedims[page->pdimno].bounds.x0;
2042 oy += state.pagedims[page->pdimno].bounds.y0;
2043 for (pageb = page->text->blocks;
2044 pageb < page->text->blocks + page->text->len;
2045 ++pageb) {
2046 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2047 block = pageb->u.text;
2049 for (line = block->lines;
2050 line < block->lines + block->len;
2051 ++line) {
2052 fz_stext_span *span;
2053 rect = fz_empty_rect;
2055 for (span = line->first_span; span; span = span->next) {
2056 int i, j, k;
2057 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2059 j = 0;
2060 k = span->len - 1;
2062 if (span == page->fmark.span && span == page->lmark.span) {
2063 seen = 1;
2064 j = fz_mini (first.i, last.i);
2065 k = fz_maxi (first.i, last.i);
2067 else {
2068 if (span == first.span) {
2069 seen = 1;
2070 j = first.i;
2072 else if (span == last.span) {
2073 seen = 1;
2074 k = last.i;
2078 if (seen) {
2079 for (i = j; i <= k; ++i) {
2080 fz_rect bbox1;
2081 fz_union_rect (&rect,
2082 fz_stext_char_bbox (state.ctx, &bbox1,
2083 span, i));
2085 fz_round_rect (&bbox, &rect);
2086 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2087 bbox.x0,
2088 bbox.y0,
2089 bbox.x1,
2090 bbox.y1,
2091 oy, ox);
2093 recti (bbox.x0 + ox, bbox.y0 + oy,
2094 bbox.x1 + ox, bbox.y1 + oy);
2095 if (span == last.span) {
2096 goto done;
2098 rect = fz_empty_rect;
2103 done:
2104 glDisable (GL_BLEND);
2107 #include "glfont.c"
2109 static void stipplerect (fz_matrix *m,
2110 fz_point *p1,
2111 fz_point *p2,
2112 fz_point *p3,
2113 fz_point *p4,
2114 GLfloat *texcoords,
2115 GLfloat *vertices)
2117 fz_transform_point (p1, m);
2118 fz_transform_point (p2, m);
2119 fz_transform_point (p3, m);
2120 fz_transform_point (p4, m);
2122 float w, h, s, t;
2124 w = p2->x - p1->x;
2125 h = p2->y - p1->y;
2126 t = hypotf (w, h) * .25f;
2128 w = p3->x - p2->x;
2129 h = p3->y - p2->y;
2130 s = hypotf (w, h) * .25f;
2132 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2133 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2135 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2136 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2138 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2139 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2141 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2142 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2144 glDrawArrays (GL_LINES, 0, 8);
2147 static void solidrect (fz_matrix *m,
2148 fz_point *p1,
2149 fz_point *p2,
2150 fz_point *p3,
2151 fz_point *p4,
2152 GLfloat *vertices)
2154 fz_transform_point (p1, m);
2155 fz_transform_point (p2, m);
2156 fz_transform_point (p3, m);
2157 fz_transform_point (p4, m);
2158 vertices[0] = p1->x; vertices[1] = p1->y;
2159 vertices[2] = p2->x; vertices[3] = p2->y;
2161 vertices[4] = p3->x; vertices[5] = p3->y;
2162 vertices[6] = p4->x; vertices[7] = p4->y;
2163 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2166 static void highlightlinks (struct page *page, int xoff, int yoff)
2168 int i;
2169 fz_matrix ctm, tm, pm;
2170 fz_link *link, *links;
2171 GLfloat *texcoords = state.texcoords;
2172 GLfloat *vertices = state.vertices;
2174 links = fz_load_links (state.ctx, page->fzpage);
2176 glEnable (GL_TEXTURE_1D);
2177 glEnable (GL_BLEND);
2178 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2179 glBindTexture (GL_TEXTURE_1D, state.stid);
2181 xoff -= state.pagedims[page->pdimno].bounds.x0;
2182 yoff -= state.pagedims[page->pdimno].bounds.y0;
2183 fz_translate (&tm, xoff, yoff);
2184 pm = pagectm (page);
2185 fz_concat (&ctm, &pm, &tm);
2187 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2188 glVertexPointer (2, GL_FLOAT, 0, vertices);
2190 for (link = links; link; link = link->next) {
2191 fz_point p1, p2, p3, p4;
2193 p1.x = link->rect.x0;
2194 p1.y = link->rect.y0;
2196 p2.x = link->rect.x1;
2197 p2.y = link->rect.y0;
2199 p3.x = link->rect.x1;
2200 p3.y = link->rect.y1;
2202 p4.x = link->rect.x0;
2203 p4.y = link->rect.y1;
2205 #if FIXME
2206 switch (link->dest.kind) {
2207 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2208 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2209 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2210 default: glColor3ub (0, 0, 0); break;
2212 #else
2213 glColor3ub (255, 0, 0);
2214 #endif
2215 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2218 for (i = 0; i < page->annotcount; ++i) {
2219 fz_point p1, p2, p3, p4;
2220 struct annot *annot = &page->annots[i];
2222 p1.x = annot->bbox.x0;
2223 p1.y = annot->bbox.y0;
2225 p2.x = annot->bbox.x1;
2226 p2.y = annot->bbox.y0;
2228 p3.x = annot->bbox.x1;
2229 p3.y = annot->bbox.y1;
2231 p4.x = annot->bbox.x0;
2232 p4.y = annot->bbox.y1;
2234 glColor3ub (0, 0, 128);
2235 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2238 glDisable (GL_BLEND);
2239 glDisable (GL_TEXTURE_1D);
2242 static int compareslinks (const void *l, const void *r)
2244 struct slink const *ls = l;
2245 struct slink const *rs = r;
2246 if (ls->bbox.y0 == rs->bbox.y0) {
2247 return rs->bbox.x0 - rs->bbox.x0;
2249 return ls->bbox.y0 - rs->bbox.y0;
2252 static void droptext (struct page *page)
2254 if (page->text) {
2255 fz_drop_stext_page (state.ctx, page->text);
2256 page->fmark.i = -1;
2257 page->lmark.i = -1;
2258 page->fmark.span = NULL;
2259 page->lmark.span = NULL;
2260 page->text = NULL;
2262 if (page->sheet) {
2263 fz_drop_stext_sheet (state.ctx, page->sheet);
2264 page->sheet = NULL;
2268 static void dropannots (struct page *page)
2270 if (page->annots) {
2271 free (page->annots);
2272 page->annots = NULL;
2273 page->annotcount = 0;
2277 static void ensureannots (struct page *page)
2279 int i, count = 0;
2280 size_t annotsize = sizeof (*page->annots);
2281 fz_annot *annot;
2283 if (state.gen != page->agen) {
2284 dropannots (page);
2285 page->agen = state.gen;
2287 if (page->annots) return;
2289 for (annot = fz_first_annot (state.ctx, page->fzpage);
2290 annot;
2291 annot = fz_next_annot (state.ctx, annot)) {
2292 count++;
2295 if (count > 0) {
2296 page->annotcount = count;
2297 page->annots = calloc (count, annotsize);
2298 if (!page->annots) {
2299 err (1, "calloc annots %d", count);
2302 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2303 annot;
2304 annot = fz_next_annot (state.ctx, annot), i++) {
2305 fz_rect rect;
2307 fz_bound_annot (state.ctx, annot, &rect);
2308 page->annots[i].annot = annot;
2309 fz_round_rect (&page->annots[i].bbox, &rect);
2314 static void dropslinks (struct page *page)
2316 if (page->slinks) {
2317 free (page->slinks);
2318 page->slinks = NULL;
2319 page->slinkcount = 0;
2323 static void ensureslinks (struct page *page)
2325 fz_matrix ctm;
2326 int i, count;
2327 size_t slinksize = sizeof (*page->slinks);
2328 fz_link *link, *links;
2330 ensureannots (page);
2331 if (state.gen != page->sgen) {
2332 dropslinks (page);
2333 page->sgen = state.gen;
2335 if (page->slinks) return;
2337 links = fz_load_links (state.ctx, page->fzpage);
2338 ctm = pagectm (page);
2340 count = page->annotcount;
2341 for (link = links; link; link = link->next) {
2342 count++;
2344 if (count > 0) {
2345 int j;
2347 page->slinkcount = count;
2348 page->slinks = calloc (count, slinksize);
2349 if (!page->slinks) {
2350 err (1, "calloc slinks %d", count);
2353 for (i = 0, link = links; link; ++i, link = link->next) {
2354 fz_rect rect;
2356 rect = link->rect;
2357 fz_transform_rect (&rect, &ctm);
2358 page->slinks[i].tag = SLINK;
2359 page->slinks[i].u.link = link;
2360 fz_round_rect (&page->slinks[i].bbox, &rect);
2362 for (j = 0; j < page->annotcount; ++j, ++i) {
2363 fz_rect rect;
2364 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2365 fz_transform_rect (&rect, &ctm);
2366 fz_round_rect (&page->slinks[i].bbox, &rect);
2368 page->slinks[i].tag = SANNOT;
2369 page->slinks[i].u.annot = page->annots[j].annot;
2371 qsort (page->slinks, count, slinksize, compareslinks);
2375 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2376 static void fmt_linkn (char *s, unsigned int u)
2378 unsigned int len; unsigned int q;
2379 unsigned int zma = 'z' - 'a' + 1;
2380 len = 1; q = u;
2381 while (q > zma - 1) { ++len; q /= zma; }
2382 if (s) {
2383 s += len;
2384 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2385 /* handles u == 0 */
2387 s[len] = 0;
2390 static void highlightslinks (struct page *page, int xoff, int yoff,
2391 int noff, char *targ, int tlen, int hfsize)
2393 int i;
2394 char buf[40];
2395 struct slink *slink;
2396 double x0, y0, x1, y1, w;
2398 ensureslinks (page);
2399 glColor3ub (0xc3, 0xb0, 0x91);
2400 for (i = 0; i < page->slinkcount; ++i) {
2401 fmt_linkn (buf, i + noff);
2402 if (!tlen || !strncmp (targ, buf, tlen)) {
2403 slink = &page->slinks[i];
2405 x0 = slink->bbox.x0 + xoff - 5;
2406 y1 = slink->bbox.y0 + yoff - 5;
2407 y0 = y1 + 10 + hfsize;
2408 w = measure_string (state.face, hfsize, buf);
2409 x1 = x0 + w + 10;
2410 recti (x0, y0, x1, y1);
2414 glEnable (GL_BLEND);
2415 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2416 glEnable (GL_TEXTURE_2D);
2417 glColor3ub (0, 0, 0);
2418 for (i = 0; i < page->slinkcount; ++i) {
2419 fmt_linkn (buf, i + noff);
2420 if (!tlen || !strncmp (targ, buf, tlen)) {
2421 slink = &page->slinks[i];
2423 x0 = slink->bbox.x0 + xoff;
2424 y0 = slink->bbox.y0 + yoff + hfsize;
2425 draw_string (state.face, hfsize, x0, y0, buf);
2428 glDisable (GL_TEXTURE_2D);
2429 glDisable (GL_BLEND);
2432 static void uploadslice (struct tile *tile, struct slice *slice)
2434 int offset;
2435 struct slice *slice1;
2436 unsigned char *texdata;
2438 offset = 0;
2439 for (slice1 = tile->slices; slice != slice1; slice1++) {
2440 offset += slice1->h * tile->w * tile->pixmap->n;
2442 if (slice->texindex != -1 && slice->texindex < state.texcount
2443 && state.texowners[slice->texindex].slice == slice) {
2444 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2446 else {
2447 int subimage = 0;
2448 int texindex = state.texindex++ % state.texcount;
2450 if (state.texowners[texindex].w == tile->w) {
2451 if (state.texowners[texindex].h >= slice->h) {
2452 subimage = 1;
2454 else {
2455 state.texowners[texindex].h = slice->h;
2458 else {
2459 state.texowners[texindex].h = slice->h;
2462 state.texowners[texindex].w = tile->w;
2463 state.texowners[texindex].slice = slice;
2464 slice->texindex = texindex;
2466 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2467 #if TEXT_TYPE == GL_TEXTURE_2D
2468 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2469 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2470 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2471 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2472 #endif
2473 if (tile->pbo) {
2474 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2475 texdata = 0;
2477 else {
2478 texdata = tile->pixmap->samples;
2480 if (subimage) {
2481 glTexSubImage2D (TEXT_TYPE,
2485 tile->w,
2486 slice->h,
2487 state.texform,
2488 state.texty,
2489 texdata+offset
2492 else {
2493 glTexImage2D (TEXT_TYPE,
2495 state.texiform,
2496 tile->w,
2497 slice->h,
2499 state.texform,
2500 state.texty,
2501 texdata+offset
2504 if (tile->pbo) {
2505 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2510 CAMLprim value ml_begintiles (value unit_v)
2512 CAMLparam1 (unit_v);
2513 glEnable (TEXT_TYPE);
2514 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2515 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2516 CAMLreturn (unit_v);
2519 CAMLprim value ml_endtiles (value unit_v)
2521 CAMLparam1 (unit_v);
2522 glDisable (TEXT_TYPE);
2523 CAMLreturn (unit_v);
2526 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2528 CAMLparam2 (args_v, ptr_v);
2529 int dispx = Int_val (Field (args_v, 0));
2530 int dispy = Int_val (Field (args_v, 1));
2531 int dispw = Int_val (Field (args_v, 2));
2532 int disph = Int_val (Field (args_v, 3));
2533 int tilex = Int_val (Field (args_v, 4));
2534 int tiley = Int_val (Field (args_v, 5));
2535 char *s = String_val (ptr_v);
2536 struct tile *tile = parse_pointer (__func__, s);
2537 int slicey, firstslice;
2538 struct slice *slice;
2539 GLfloat *texcoords = state.texcoords;
2540 GLfloat *vertices = state.vertices;
2542 firstslice = tiley / tile->sliceheight;
2543 slice = &tile->slices[firstslice];
2544 slicey = tiley % tile->sliceheight;
2546 while (disph > 0) {
2547 int dh;
2549 dh = slice->h - slicey;
2550 dh = fz_mini (disph, dh);
2551 uploadslice (tile, slice);
2553 texcoords[0] = tilex; texcoords[1] = slicey;
2554 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2555 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2556 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2558 vertices[0] = dispx; vertices[1] = dispy;
2559 vertices[2] = dispx+dispw; vertices[3] = dispy;
2560 vertices[4] = dispx; vertices[5] = dispy+dh;
2561 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2563 #if TEXT_TYPE == GL_TEXTURE_2D
2564 for (int i = 0; i < 8; ++i) {
2565 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2567 #endif
2569 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2570 dispy += dh;
2571 disph -= dh;
2572 slice++;
2573 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2574 slicey = 0;
2576 CAMLreturn (Val_unit);
2579 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2581 fz_matrix ctm, tm, pm;
2582 fz_point p1, p2, p3, p4;
2583 GLfloat *vertices = state.vertices;
2584 double *v = (double *) rects_v;
2586 xoff -= state.pagedims[page->pdimno].bounds.x0;
2587 yoff -= state.pagedims[page->pdimno].bounds.y0;
2588 fz_translate (&tm, xoff, yoff);
2589 pm = pagectm (page);
2590 fz_concat (&ctm, &pm, &tm);
2592 glEnable (GL_BLEND);
2593 glVertexPointer (2, GL_FLOAT, 0, vertices);
2595 glColor4dv (v);
2596 p1.x = v[4];
2597 p1.y = v[5];
2599 p2.x = v[6];
2600 p2.y = v[5];
2602 p3.x = v[6];
2603 p3.y = v[7];
2605 p4.x = v[4];
2606 p4.y = v[7];
2607 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2608 glDisable (GL_BLEND);
2611 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2612 value xoff_v, value yoff_v,
2613 value li_v)
2615 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2616 int xoff = Int_val (xoff_v);
2617 int yoff = Int_val (yoff_v);
2618 int noff = Int_val (Field (li_v, 0));
2619 char *targ = String_val (Field (li_v, 1));
2620 int tlen = caml_string_length (Field (li_v, 1));
2621 int hfsize = Int_val (Field (li_v, 2));
2622 char *s = String_val (ptr_v);
2623 int hlmask = Int_val (hlinks_v);
2624 struct page *page = parse_pointer (__func__, s);
2626 if (!page->fzpage) {
2627 /* deal with loadpage failed pages */
2628 goto done;
2631 if (trylock (__func__)) {
2632 noff = -1;
2633 goto done;
2636 ensureannots (page);
2637 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2638 if (hlmask & 2) {
2639 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2640 noff = page->slinkcount;
2642 if (page->tgen == state.gen) {
2643 showsel (page, xoff, yoff);
2645 unlock (__func__);
2647 done:
2648 CAMLreturn (Val_int (noff));
2651 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2652 value rects_v)
2654 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2655 int xoff = Int_val (xoff_v);
2656 int yoff = Int_val (yoff_v);
2657 char *s = String_val (ptr_v);
2658 struct page *page = parse_pointer (__func__, s);
2660 drawprect (page, xoff, yoff, rects_v);
2661 CAMLreturn (Val_unit);
2664 static struct annot *getannot (struct page *page, int x, int y)
2666 int i;
2667 fz_point p;
2668 fz_matrix ctm;
2669 const fz_matrix *tctm;
2670 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2672 if (!page->annots) return NULL;
2674 if (pdf) {
2675 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2676 tctm = &state.pagedims[page->pdimno].tctm;
2678 else {
2679 tctm = &fz_identity;
2682 p.x = x;
2683 p.y = y;
2685 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2686 fz_invert_matrix (&ctm, &ctm);
2687 fz_transform_point (&p, &ctm);
2689 if (pdf) {
2690 for (i = 0; i < page->annotcount; ++i) {
2691 struct annot *a = &page->annots[i];
2692 fz_rect rect;
2694 fz_bound_annot (state.ctx, a->annot, &rect);
2695 if (p.x >= rect.x0 && p.x <= rect.x1) {
2696 if (p.y >= rect.y0 && p.y <= rect.y1)
2697 return a;
2701 return NULL;
2704 static fz_link *getlink (struct page *page, int x, int y)
2706 fz_point p;
2707 fz_matrix ctm;
2708 fz_link *link, *links;
2710 links = fz_load_links (state.ctx, page->fzpage);
2712 p.x = x;
2713 p.y = y;
2715 ctm = pagectm (page);
2716 fz_invert_matrix (&ctm, &ctm);
2717 fz_transform_point (&p, &ctm);
2719 for (link = links; link; link = link->next) {
2720 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2721 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2722 return link;
2726 return NULL;
2729 static void ensuretext (struct page *page)
2731 if (state.gen != page->tgen) {
2732 droptext (page);
2733 page->tgen = state.gen;
2735 if (!page->text) {
2736 fz_matrix ctm;
2737 fz_device *tdev;
2739 page->text = fz_new_stext_page (state.ctx,
2740 &state.pagedims[page->pdimno].mediabox);
2741 page->sheet = fz_new_stext_sheet (state.ctx);
2742 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2743 ctm = pagectm (page);
2744 fz_run_display_list (state.ctx, page->dlist,
2745 tdev, &ctm, &fz_infinite_rect, NULL);
2746 qsort (page->text->blocks, page->text->len,
2747 sizeof (*page->text->blocks), compareblocks);
2748 fz_close_device (state.ctx, tdev);
2749 fz_drop_device (state.ctx, tdev);
2753 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2755 CAMLparam2 (start_page_v, dir_v);
2756 CAMLlocal1 (ret_v);
2757 int i, dir = Int_val (dir_v);
2758 int start_page = Int_val (start_page_v);
2759 int end_page = dir > 0 ? state.pagecount : -1;
2760 pdf_document *pdf;
2762 fz_var (end_page);
2763 ret_v = Val_int (0);
2764 lock (__func__);
2765 pdf = pdf_specifics (state.ctx, state.doc);
2766 for (i = start_page + dir; i != end_page; i += dir) {
2767 int found;
2769 fz_var (found);
2770 if (pdf) {
2771 pdf_page *page = NULL;
2773 fz_var (page);
2774 fz_try (state.ctx) {
2775 page = pdf_load_page (state.ctx, pdf, i);
2776 found = !!page->links || !!page->annots;
2778 fz_catch (state.ctx) {
2779 found = 0;
2781 if (page) {
2782 fz_drop_page (state.ctx, &page->super);
2785 else {
2786 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2787 found = !!fz_load_links (state.ctx, page);
2788 fz_drop_page (state.ctx, page);
2791 if (found) {
2792 ret_v = caml_alloc_small (1, 1);
2793 Field (ret_v, 0) = Val_int (i);
2794 goto unlock;
2797 unlock:
2798 unlock (__func__);
2799 CAMLreturn (ret_v);
2802 enum { dir_first, dir_last };
2803 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2805 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2807 CAMLparam2 (ptr_v, dir_v);
2808 CAMLlocal2 (ret_v, pos_v);
2809 struct page *page;
2810 int dirtag, i, slinkindex;
2811 struct slink *found = NULL ,*slink;
2812 char *s = String_val (ptr_v);
2814 page = parse_pointer (__func__, s);
2815 ret_v = Val_int (0);
2816 lock (__func__);
2817 ensureslinks (page);
2819 if (Is_block (dir_v)) {
2820 dirtag = Tag_val (dir_v);
2821 switch (dirtag) {
2822 case dir_first_visible:
2824 int x0, y0, dir, first_index, last_index;
2826 pos_v = Field (dir_v, 0);
2827 x0 = Int_val (Field (pos_v, 0));
2828 y0 = Int_val (Field (pos_v, 1));
2829 dir = Int_val (Field (pos_v, 2));
2831 if (dir >= 0) {
2832 dir = 1;
2833 first_index = 0;
2834 last_index = page->slinkcount;
2836 else {
2837 first_index = page->slinkcount - 1;
2838 last_index = -1;
2841 for (i = first_index; i != last_index; i += dir) {
2842 slink = &page->slinks[i];
2843 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2844 found = slink;
2845 break;
2849 break;
2851 case dir_left:
2852 slinkindex = Int_val (Field (dir_v, 0));
2853 found = &page->slinks[slinkindex];
2854 for (i = slinkindex - 1; i >= 0; --i) {
2855 slink = &page->slinks[i];
2856 if (slink->bbox.x0 < found->bbox.x0) {
2857 found = slink;
2858 break;
2861 break;
2863 case dir_right:
2864 slinkindex = Int_val (Field (dir_v, 0));
2865 found = &page->slinks[slinkindex];
2866 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2867 slink = &page->slinks[i];
2868 if (slink->bbox.x0 > found->bbox.x0) {
2869 found = slink;
2870 break;
2873 break;
2875 case dir_down:
2876 slinkindex = Int_val (Field (dir_v, 0));
2877 found = &page->slinks[slinkindex];
2878 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2879 slink = &page->slinks[i];
2880 if (slink->bbox.y0 >= found->bbox.y0) {
2881 found = slink;
2882 break;
2885 break;
2887 case dir_up:
2888 slinkindex = Int_val (Field (dir_v, 0));
2889 found = &page->slinks[slinkindex];
2890 for (i = slinkindex - 1; i >= 0; --i) {
2891 slink = &page->slinks[i];
2892 if (slink->bbox.y0 <= found->bbox.y0) {
2893 found = slink;
2894 break;
2897 break;
2900 else {
2901 dirtag = Int_val (dir_v);
2902 switch (dirtag) {
2903 case dir_first:
2904 found = page->slinks;
2905 break;
2907 case dir_last:
2908 if (page->slinks) {
2909 found = page->slinks + (page->slinkcount - 1);
2911 break;
2914 if (found) {
2915 ret_v = caml_alloc_small (2, 1);
2916 Field (ret_v, 0) = Val_int (found - page->slinks);
2919 unlock (__func__);
2920 CAMLreturn (ret_v);
2923 enum { uuri, utext, uannot };
2925 CAMLprim value ml_getlink (value ptr_v, value n_v)
2927 CAMLparam2 (ptr_v, n_v);
2928 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2929 fz_link *link;
2930 struct page *page;
2931 char *s = String_val (ptr_v);
2932 struct slink *slink;
2934 ret_v = Val_int (0);
2935 page = parse_pointer (__func__, s);
2937 lock (__func__);
2938 ensureslinks (page);
2939 slink = &page->slinks[Int_val (n_v)];
2940 if (slink->tag == SLINK) {
2941 link = slink->u.link;
2942 str_v = caml_copy_string (link->uri);
2943 ret_v = caml_alloc_small (1, uuri);
2944 Field (ret_v, 0) = str_v;
2946 else {
2947 ret_v = caml_alloc_small (1, uannot);
2948 tup_v = caml_alloc_tuple (2);
2949 Field (ret_v, 0) = tup_v;
2950 Field (tup_v, 0) = ptr_v;
2951 Field (tup_v, 1) = n_v;
2953 unlock (__func__);
2955 CAMLreturn (ret_v);
2958 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2960 CAMLparam2 (ptr_v, n_v);
2961 pdf_document *pdf;
2962 const char *contents = "";
2964 lock (__func__);
2965 pdf = pdf_specifics (state.ctx, state.doc);
2966 if (pdf) {
2967 char *s = String_val (ptr_v);
2968 struct page *page;
2969 struct slink *slink;
2971 page = parse_pointer (__func__, s);
2972 slink = &page->slinks[Int_val (n_v)];
2973 contents = pdf_annot_contents (state.ctx,
2974 (pdf_annot *) slink->u.annot);
2976 unlock (__func__);
2977 CAMLreturn (caml_copy_string (contents));
2980 CAMLprim value ml_getlinkcount (value ptr_v)
2982 CAMLparam1 (ptr_v);
2983 struct page *page;
2984 char *s = String_val (ptr_v);
2986 page = parse_pointer (__func__, s);
2987 CAMLreturn (Val_int (page->slinkcount));
2990 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2992 CAMLparam2 (ptr_v, n_v);
2993 CAMLlocal1 (ret_v);
2994 struct page *page;
2995 struct slink *slink;
2996 char *s = String_val (ptr_v);
2998 page = parse_pointer (__func__, s);
2999 ret_v = caml_alloc_tuple (4);
3000 lock (__func__);
3001 ensureslinks (page);
3003 slink = &page->slinks[Int_val (n_v)];
3004 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3005 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3006 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3007 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3008 unlock (__func__);
3009 CAMLreturn (ret_v);
3012 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3014 CAMLparam3 (ptr_v, x_v, y_v);
3015 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3016 fz_link *link;
3017 struct annot *annot;
3018 struct page *page;
3019 char *ptr = String_val (ptr_v);
3020 int x = Int_val (x_v), y = Int_val (y_v);
3021 struct pagedim *pdim;
3023 ret_v = Val_int (0);
3024 if (trylock (__func__)) {
3025 goto done;
3028 page = parse_pointer (__func__, ptr);
3029 pdim = &state.pagedims[page->pdimno];
3030 x += pdim->bounds.x0;
3031 y += pdim->bounds.y0;
3034 annot = getannot (page, x, y);
3035 if (annot) {
3036 int i, n = -1;
3038 ensureslinks (page);
3039 for (i = 0; i < page->slinkcount; ++i) {
3040 if (page->slinks[i].tag == SANNOT
3041 && page->slinks[i].u.annot == annot->annot) {
3042 n = i;
3043 break;
3046 ret_v = caml_alloc_small (1, uannot);
3047 tup_v = caml_alloc_tuple (2);
3048 Field (ret_v, 0) = tup_v;
3049 Field (tup_v, 0) = ptr_v;
3050 Field (tup_v, 1) = Val_int (n);
3051 goto unlock;
3055 link = getlink (page, x, y);
3056 if (link) {
3057 str_v = caml_copy_string (link->uri);
3058 ret_v = caml_alloc_small (1, uuri);
3059 Field (ret_v, 0) = str_v;
3061 else {
3062 fz_rect *b;
3063 fz_page_block *pageb;
3064 fz_stext_block *block;
3066 ensuretext (page);
3067 for (pageb = page->text->blocks;
3068 pageb < page->text->blocks + page->text->len;
3069 ++pageb) {
3070 fz_stext_line *line;
3071 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3072 block = pageb->u.text;
3074 b = &block->bbox;
3075 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3076 continue;
3078 for (line = block->lines;
3079 line < block->lines + block->len;
3080 ++line) {
3081 fz_stext_span *span;
3083 b = &line->bbox;
3084 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3085 continue;
3087 for (span = line->first_span; span; span = span->next) {
3088 int charnum;
3090 b = &span->bbox;
3091 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3092 continue;
3094 for (charnum = 0; charnum < span->len; ++charnum) {
3095 fz_rect bbox;
3096 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3097 b = &bbox;
3099 if (x >= b->x0 && x <= b->x1
3100 && y >= b->y0 && y <= b->y1) {
3101 fz_stext_style *style = span->text->style;
3102 const char *n2 =
3103 style->font
3104 ? fz_font_name (state.ctx, style->font)
3105 : "Span has no font name"
3107 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3108 style->font);
3109 if (face && face->family_name) {
3110 char *s;
3111 char *n1 = face->family_name;
3112 size_t l1 = strlen (n1);
3113 size_t l2 = strlen (n2);
3115 if (l1 != l2 || memcmp (n1, n2, l1)) {
3116 s = malloc (l1 + l2 + 2);
3117 if (s) {
3118 memcpy (s, n2, l2);
3119 s[l2] = '=';
3120 memcpy (s + l2 + 1, n1, l1 + 1);
3121 str_v = caml_copy_string (s);
3122 free (s);
3126 if (str_v == Val_unit) {
3127 str_v = caml_copy_string (n2);
3129 ret_v = caml_alloc_small (1, utext);
3130 Field (ret_v, 0) = str_v;
3131 goto unlock;
3138 unlock:
3139 unlock (__func__);
3141 done:
3142 CAMLreturn (ret_v);
3145 enum { mark_page, mark_block, mark_line, mark_word };
3147 static int uninteresting (int c)
3149 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3150 || ispunct (c);
3153 CAMLprim value ml_clearmark (value ptr_v)
3155 CAMLparam1 (ptr_v);
3156 char *s = String_val (ptr_v);
3157 struct page *page;
3159 if (trylock (__func__)) {
3160 goto done;
3163 page = parse_pointer (__func__, s);
3164 page->fmark.span = NULL;
3165 page->lmark.span = NULL;
3166 page->fmark.i = 0;
3167 page->lmark.i = 0;
3169 unlock (__func__);
3170 done:
3171 CAMLreturn (Val_unit);
3174 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3176 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3177 CAMLlocal1 (ret_v);
3178 fz_rect *b;
3179 struct page *page;
3180 fz_stext_line *line;
3181 fz_page_block *pageb;
3182 fz_stext_block *block;
3183 struct pagedim *pdim;
3184 int mark = Int_val (mark_v);
3185 char *s = String_val (ptr_v);
3186 int x = Int_val (x_v), y = Int_val (y_v);
3188 ret_v = Val_bool (0);
3189 if (trylock (__func__)) {
3190 goto done;
3193 page = parse_pointer (__func__, s);
3194 pdim = &state.pagedims[page->pdimno];
3196 ensuretext (page);
3198 if (mark == mark_page) {
3199 int i;
3200 fz_page_block *pb1 = NULL, *pb2 = NULL;
3202 for (i = 0; i < page->text->len; ++i) {
3203 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3204 pb1 = &page->text->blocks[i];
3205 break;
3208 if (!pb1) goto unlock;
3210 for (i = page->text->len - 1; i >= 0; --i) {
3211 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3212 pb2 = &page->text->blocks[i];
3213 break;
3216 if (!pb2) goto unlock;
3218 block = pb1->u.text;
3220 page->fmark.i = 0;
3221 page->fmark.span = block->lines->first_span;
3223 block = pb2->u.text;
3224 line = &block->lines[block->len - 1];
3225 page->lmark.i = line->last_span->len - 1;
3226 page->lmark.span = line->last_span;
3227 ret_v = Val_bool (1);
3228 goto unlock;
3231 x += pdim->bounds.x0;
3232 y += pdim->bounds.y0;
3234 for (pageb = page->text->blocks;
3235 pageb < page->text->blocks + page->text->len;
3236 ++pageb) {
3237 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3238 block = pageb->u.text;
3240 b = &block->bbox;
3241 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3242 continue;
3244 if (mark == mark_block) {
3245 page->fmark.i = 0;
3246 page->fmark.span = block->lines->first_span;
3248 line = &block->lines[block->len - 1];
3249 page->lmark.i = line->last_span->len - 1;
3250 page->lmark.span = line->last_span;
3251 ret_v = Val_bool (1);
3252 goto unlock;
3255 for (line = block->lines;
3256 line < block->lines + block->len;
3257 ++line) {
3258 fz_stext_span *span;
3260 b = &line->bbox;
3261 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3262 continue;
3264 if (mark == mark_line) {
3265 page->fmark.i = 0;
3266 page->fmark.span = line->first_span;
3268 page->lmark.i = line->last_span->len - 1;
3269 page->lmark.span = line->last_span;
3270 ret_v = Val_bool (1);
3271 goto unlock;
3274 for (span = line->first_span; span; span = span->next) {
3275 int charnum;
3277 b = &span->bbox;
3278 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3279 continue;
3281 for (charnum = 0; charnum < span->len; ++charnum) {
3282 fz_rect bbox;
3283 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3284 b = &bbox;
3286 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3287 /* unicode ftw */
3288 int charnum2, charnum3 = -1, charnum4 = -1;
3290 if (uninteresting (span->text[charnum].c)) goto unlock;
3292 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3293 if (uninteresting (span->text[charnum2].c)) {
3294 charnum3 = charnum2 + 1;
3295 break;
3298 if (charnum3 == -1) charnum3 = 0;
3300 charnum4 = charnum;
3301 for (charnum2 = charnum + 1;
3302 charnum2 < span->len;
3303 ++charnum2) {
3304 if (uninteresting (span->text[charnum2].c)) break;
3305 charnum4 = charnum2;
3308 page->fmark.i = charnum3;
3309 page->fmark.span = span;
3311 page->lmark.i = charnum4;
3312 page->lmark.span = span;
3313 ret_v = Val_bool (1);
3314 goto unlock;
3320 unlock:
3321 if (!Bool_val (ret_v)) {
3322 page->fmark.span = NULL;
3323 page->lmark.span = NULL;
3324 page->fmark.i = 0;
3325 page->lmark.i = 0;
3327 unlock (__func__);
3329 done:
3330 CAMLreturn (ret_v);
3333 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3335 CAMLparam3 (ptr_v, x_v, y_v);
3336 CAMLlocal2 (ret_v, res_v);
3337 fz_rect *b = NULL;
3338 struct page *page;
3339 fz_page_block *pageb;
3340 struct pagedim *pdim;
3341 char *s = String_val (ptr_v);
3342 int x = Int_val (x_v), y = Int_val (y_v);
3344 ret_v = Val_int (0);
3345 if (trylock (__func__)) {
3346 goto done;
3349 page = parse_pointer (__func__, s);
3350 pdim = &state.pagedims[page->pdimno];
3351 x += pdim->bounds.x0;
3352 y += pdim->bounds.y0;
3354 ensuretext (page);
3356 for (pageb = page->text->blocks;
3357 pageb < page->text->blocks + page->text->len;
3358 ++pageb) {
3359 switch (pageb->type) {
3360 case FZ_PAGE_BLOCK_TEXT:
3361 b = &pageb->u.text->bbox;
3362 break;
3364 case FZ_PAGE_BLOCK_IMAGE:
3365 b = &pageb->u.image->bbox;
3366 break;
3368 default:
3369 continue;
3372 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3373 break;
3374 b = NULL;
3376 if (b) {
3377 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3378 ret_v = caml_alloc_small (1, 1);
3379 Store_double_field (res_v, 0, b->x0);
3380 Store_double_field (res_v, 1, b->x1);
3381 Store_double_field (res_v, 2, b->y0);
3382 Store_double_field (res_v, 3, b->y1);
3383 Field (ret_v, 0) = res_v;
3385 unlock (__func__);
3387 done:
3388 CAMLreturn (ret_v);
3391 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3393 CAMLparam2 (ptr_v, rect_v);
3394 fz_rect b;
3395 struct page *page;
3396 struct pagedim *pdim;
3397 char *s = String_val (ptr_v);
3398 int i, x0, x1, y0, y1, fi, li;
3399 fz_stext_line *line;
3400 fz_page_block *pageb;
3401 fz_stext_block *block;
3402 fz_stext_span *span, *fspan, *lspan;
3404 if (trylock (__func__)) {
3405 goto done;
3408 page = parse_pointer (__func__, s);
3409 ensuretext (page);
3411 pdim = &state.pagedims[page->pdimno];
3412 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3413 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3414 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3415 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3417 if (y0 > y1) {
3418 int t = y0;
3419 y0 = y1;
3420 y1 = t;
3421 x0 = x1;
3422 x1 = t;
3425 fi = page->fmark.i;
3426 fspan = page->fmark.span;
3428 li = page->lmark.i;
3429 lspan = page->lmark.span;
3431 for (pageb = page->text->blocks;
3432 pageb < page->text->blocks + page->text->len;
3433 ++pageb) {
3434 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3435 block = pageb->u.text;
3436 for (line = block->lines;
3437 line < block->lines + block->len;
3438 ++line) {
3440 for (span = line->first_span; span; span = span->next) {
3441 for (i = 0; i < span->len; ++i) {
3442 fz_stext_char_bbox (state.ctx, &b, span, i);
3444 if (x0 >= b.x0 && x0 <= b.x1
3445 && y0 >= b.y0 && y0 <= b.y1) {
3446 fspan = span;
3447 fi = i;
3449 if (x1 >= b.x0 && x1 <= b.x1
3450 && y1 >= b.y0 && y1 <= b.y1) {
3451 lspan = span;
3452 li = i;
3458 if (x1 < x0 && fspan == lspan) {
3459 i = fi;
3460 span = fspan;
3462 fi = li;
3463 fspan = lspan;
3465 li = i;
3466 lspan = span;
3469 page->fmark.i = fi;
3470 page->fmark.span = fspan;
3472 page->lmark.i = li;
3473 page->lmark.span = lspan;
3475 unlock (__func__);
3477 done:
3478 CAMLreturn (Val_unit);
3481 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3483 char buf[4];
3484 int i, len, ret;
3486 for (i = a; i <= b; ++i) {
3487 len = fz_runetochar (buf, span->text[i].c);
3488 ret = fwrite (buf, len, 1, f);
3490 if (ret != 1) {
3491 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3492 len, ret, strerror (errno));
3493 return -1;
3496 return 0;
3499 #ifdef __CYGWIN__
3500 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3502 caml_failwith ("ml_popen not implemented under Cygwin");
3504 #else
3505 CAMLprim value ml_spawn (value command_v, value fds_v)
3507 CAMLparam2 (command_v, fds_v);
3508 CAMLlocal2 (l_v, tup_v);
3509 int ret, ret1;
3510 pid_t pid;
3511 char *msg = NULL;
3512 value earg_v = Nothing;
3513 posix_spawnattr_t attr;
3514 posix_spawn_file_actions_t fa;
3515 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3517 argv[2] = String_val (command_v);
3519 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3520 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3523 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3524 msg = "posix_spawnattr_init";
3525 goto fail1;
3528 #ifdef POSIX_SPAWN_USEVFORK
3529 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3530 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3531 goto fail;
3533 #endif
3535 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3536 int fd1, fd2;
3538 tup_v = Field (l_v, 0);
3539 fd1 = Int_val (Field (tup_v, 0));
3540 fd2 = Int_val (Field (tup_v, 1));
3541 if (fd2 < 0) {
3542 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3543 msg = "posix_spawn_file_actions_addclose";
3544 earg_v = tup_v;
3545 goto fail;
3548 else {
3549 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3550 msg = "posix_spawn_file_actions_adddup2";
3551 earg_v = tup_v;
3552 goto fail;
3557 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3558 msg = "posix_spawn";
3559 goto fail;
3562 fail:
3563 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3564 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3567 fail1:
3568 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3569 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3570 strerror (ret1));
3573 if (msg)
3574 unix_error (ret, msg, earg_v);
3576 CAMLreturn (Val_int (pid));
3578 #endif
3580 CAMLprim value ml_hassel (value ptr_v)
3582 CAMLparam1 (ptr_v);
3583 CAMLlocal1 (ret_v);
3584 struct page *page;
3585 char *s = String_val (ptr_v);
3587 ret_v = Val_bool (0);
3588 if (trylock (__func__)) {
3589 goto done;
3592 page = parse_pointer (__func__, s);
3593 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3594 unlock (__func__);
3595 done:
3596 CAMLreturn (ret_v);
3599 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3601 CAMLparam2 (fd_v, ptr_v);
3602 FILE *f;
3603 int seen = 0;
3604 struct page *page;
3605 fz_stext_line *line;
3606 fz_page_block *pageb;
3607 fz_stext_block *block;
3608 int fd = Int_val (fd_v);
3609 char *s = String_val (ptr_v);
3611 if (trylock (__func__)) {
3612 goto done;
3615 page = parse_pointer (__func__, s);
3617 if (!page->fmark.span || !page->lmark.span) {
3618 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3619 goto unlock;
3622 f = fdopen (fd, "w");
3623 if (!f) {
3624 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3625 fd, strerror (errno));
3626 f = stdout;
3629 for (pageb = page->text->blocks;
3630 pageb < page->text->blocks + page->text->len;
3631 ++pageb) {
3632 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3633 block = pageb->u.text;
3634 for (line = block->lines;
3635 line < block->lines + block->len;
3636 ++line) {
3637 fz_stext_span *span;
3639 for (span = line->first_span; span; span = span->next) {
3640 int a, b;
3642 seen |= span == page->fmark.span || span == page->lmark.span;
3643 a = span == page->fmark.span ? page->fmark.i : 0;
3644 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3646 if (seen) {
3647 if (pipespan (f, span, a, b)) {
3648 goto close;
3650 if (span == page->lmark.span) {
3651 goto close;
3653 if (span == line->last_span) {
3654 if (putc ('\n', f) == EOF) {
3655 fprintf (stderr,
3656 "failed break line on sel pipe: %s\n",
3657 strerror (errno));
3658 goto close;
3665 close:
3666 if (f != stdout) {
3667 int ret = fclose (f);
3668 fd = -1;
3669 if (ret == -1) {
3670 if (errno != ECHILD) {
3671 fprintf (stderr, "failed to close sel pipe: %s\n",
3672 strerror (errno));
3676 unlock:
3677 unlock (__func__);
3679 done:
3680 if (fd >= 0) {
3681 if (close (fd)) {
3682 fprintf (stderr, "failed to close sel pipe: %s\n",
3683 strerror (errno));
3686 CAMLreturn (Val_unit);
3689 CAMLprim value ml_getpdimrect (value pagedimno_v)
3691 CAMLparam1 (pagedimno_v);
3692 CAMLlocal1 (ret_v);
3693 int pagedimno = Int_val (pagedimno_v);
3694 fz_rect box;
3696 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3697 if (trylock (__func__)) {
3698 box = fz_empty_rect;
3700 else {
3701 box = state.pagedims[pagedimno].mediabox;
3702 unlock (__func__);
3705 Store_double_field (ret_v, 0, box.x0);
3706 Store_double_field (ret_v, 1, box.x1);
3707 Store_double_field (ret_v, 2, box.y0);
3708 Store_double_field (ret_v, 3, box.y1);
3710 CAMLreturn (ret_v);
3713 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3714 value dw_v, value cols_v)
3716 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3717 CAMLlocal1 (ret_v);
3718 int i;
3719 double zoom = -1.;
3720 double maxh = 0.0;
3721 struct pagedim *p;
3722 double winw = Int_val (winw_v);
3723 double winh = Int_val (winh_v);
3724 double dw = Int_val (dw_v);
3725 double cols = Int_val (cols_v);
3726 double pw = 1.0, ph = 1.0;
3728 if (trylock (__func__)) {
3729 goto done;
3732 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3733 double w = p->pagebox.x1 / cols;
3734 double h = p->pagebox.y1;
3735 if (h > maxh) {
3736 maxh = h;
3737 ph = h;
3738 if (state.fitmodel != FitProportional) pw = w;
3740 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3743 zoom = (((winh / ph) * pw) + dw) / winw;
3744 unlock (__func__);
3745 done:
3746 ret_v = caml_copy_double (zoom);
3747 CAMLreturn (ret_v);
3750 CAMLprim value ml_getmaxw (value unit_v)
3752 CAMLparam1 (unit_v);
3753 CAMLlocal1 (ret_v);
3754 int i;
3755 double maxw = -1.;
3756 struct pagedim *p;
3758 if (trylock (__func__)) {
3759 goto done;
3762 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3763 double w = p->pagebox.x1;
3764 maxw = fz_max (maxw, w);
3767 unlock (__func__);
3768 done:
3769 ret_v = caml_copy_double (maxw);
3770 CAMLreturn (ret_v);
3773 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3775 CAMLparam4 (pt_v, x_v, y_v, string_v);
3776 CAMLlocal1 (ret_v);
3777 int pt = Int_val(pt_v);
3778 int x = Int_val (x_v);
3779 int y = Int_val (y_v);
3780 double w;
3782 w = draw_string (state.face, pt, x, y, String_val (string_v));
3783 ret_v = caml_copy_double (w);
3784 CAMLreturn (ret_v);
3787 CAMLprim value ml_measure_string (value pt_v, value string_v)
3789 CAMLparam2 (pt_v, string_v);
3790 CAMLlocal1 (ret_v);
3791 int pt = Int_val (pt_v);
3792 double w;
3794 w = measure_string (state.face, pt, String_val (string_v));
3795 ret_v = caml_copy_double (w);
3796 CAMLreturn (ret_v);
3799 CAMLprim value ml_getpagebox (value opaque_v)
3801 CAMLparam1 (opaque_v);
3802 CAMLlocal1 (ret_v);
3803 fz_rect rect;
3804 fz_irect bbox;
3805 fz_matrix ctm;
3806 fz_device *dev;
3807 char *s = String_val (opaque_v);
3808 struct page *page = parse_pointer (__func__, s);
3810 ret_v = caml_alloc_tuple (4);
3811 dev = fz_new_bbox_device (state.ctx, &rect);
3812 dev->hints |= FZ_IGNORE_SHADE;
3814 ctm = pagectm (page);
3815 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3817 fz_close_device (state.ctx, dev);
3818 fz_drop_device (state.ctx, dev);
3819 fz_round_rect (&bbox, &rect);
3820 Field (ret_v, 0) = Val_int (bbox.x0);
3821 Field (ret_v, 1) = Val_int (bbox.y0);
3822 Field (ret_v, 2) = Val_int (bbox.x1);
3823 Field (ret_v, 3) = Val_int (bbox.y1);
3825 CAMLreturn (ret_v);
3828 CAMLprim value ml_setaalevel (value level_v)
3830 CAMLparam1 (level_v);
3832 state.aalevel = Int_val (level_v);
3833 CAMLreturn (Val_unit);
3836 #pragma GCC diagnostic push
3837 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3838 #include <X11/Xlib.h>
3839 #include <X11/cursorfont.h>
3840 #pragma GCC diagnostic pop
3842 #ifdef USE_EGL
3843 #include <EGL/egl.h>
3844 #else
3845 #include <GL/glx.h>
3846 #endif
3848 static const int shapes[] = {
3849 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3852 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3854 static struct {
3855 Window wid;
3856 Display *dpy;
3857 #ifdef USE_EGL
3858 EGLContext ctx;
3859 EGLConfig conf;
3860 EGLSurface win;
3861 EGLDisplay *edpy;
3862 #else
3863 GLXContext ctx;
3864 #endif
3865 XVisualInfo *visual;
3866 Cursor curs[CURS_COUNT];
3867 } glx;
3869 #ifdef VISAVIS
3870 static VisualID initvisual (void)
3872 /* On this system with: `Haswell-ULT Integrated Graphics
3873 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3874 using glX chosen visual and auto scrolling some document in
3875 fullscreen the power/energy-gpu is more than 1 joule bigger
3876 than when using hand picked visual that stands alone in glxinfo
3877 output: it's dead last in the list and it's the only one with
3878 `visual dep' (sic) of 32
3880 No clue what's going on here...
3882 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3884 XVisualInfo info;
3885 int ret = 1;
3887 info.depth = 32;
3888 info.class = TrueColor;
3889 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3890 &info, &ret);
3891 if (!ret || !glx.visual) {
3892 XCloseDisplay (glx.dpy);
3893 caml_failwith ("XGetVisualInfo");
3895 return glx.visual->visualid;
3897 #endif
3899 static void initcurs (void)
3901 for (size_t n = 0; n < CURS_COUNT; ++n) {
3902 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3906 CAMLprim void ml_setbgcol (value color_v)
3908 CAMLparam1 (color_v);
3909 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3910 CAMLreturn0;
3913 #ifdef USE_EGL
3914 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3916 CAMLparam3 (display_v, wid_v, screen_v);
3917 int major, minor;
3918 int num_conf;
3919 EGLint visid;
3920 EGLint attribs[] = {
3921 #ifdef VISAVIS
3922 EGL_NATIVE_VISUAL_ID, 0,
3923 #else
3924 EGL_DEPTH_SIZE, 24,
3925 #endif
3926 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3927 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3928 EGL_NONE
3930 EGLConfig conf;
3932 glx.dpy = XOpenDisplay (String_val (display_v));
3933 if (!glx.dpy) {
3934 caml_failwith ("XOpenDisplay");
3937 eglBindAPI (EGL_OPENGL_API);
3939 glx.edpy = eglGetDisplay (glx.dpy);
3940 if (glx.edpy == EGL_NO_DISPLAY) {
3941 caml_failwith ("eglGetDisplay");
3944 if (!eglInitialize (glx.edpy, &major, &minor)) {
3945 caml_failwith ("eglInitialize");
3948 #ifdef VISAVIS
3949 attribs[1] = visid = initvisual ();
3950 #endif
3952 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3953 !num_conf) {
3954 caml_failwith ("eglChooseConfig");
3957 glx.conf = conf;
3958 #ifndef VISAVIS
3959 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
3960 EGL_NATIVE_VISUAL_ID, &visid)) {
3961 caml_failwith ("eglGetConfigAttrib");
3963 #endif
3964 initcurs ();
3966 glx.wid = Int_val (wid_v);
3967 CAMLreturn (Val_int (visid));
3970 CAMLprim value ml_glxcompleteinit (value unit_v)
3972 CAMLparam1 (unit_v);
3974 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3975 if (!glx.ctx) {
3976 caml_failwith ("eglCreateContext");
3979 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3980 glx.wid, NULL);
3981 if (glx.win == EGL_NO_SURFACE) {
3982 caml_failwith ("eglCreateWindowSurface");
3985 XFree (glx.visual);
3986 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3987 glx.ctx = NULL;
3988 caml_failwith ("eglMakeCurrent");
3990 CAMLreturn (Val_unit);
3992 #else
3993 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3995 CAMLparam3 (display_v, wid_v, screen_v);
3997 glx.dpy = XOpenDisplay (String_val (display_v));
3998 if (!glx.dpy) {
3999 caml_failwith ("XOpenDisplay");
4002 #ifdef VISAVIS
4003 initvisual ();
4004 #else
4005 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4006 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4007 if (!glx.visual) {
4008 XCloseDisplay (glx.dpy);
4009 caml_failwith ("glXChooseVisual");
4011 #endif
4012 initcurs ();
4014 glx.wid = Int_val (wid_v);
4015 CAMLreturn (Val_int (glx.visual->visualid));
4018 CAMLprim value ml_glxcompleteinit (value unit_v)
4020 CAMLparam1 (unit_v);
4022 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4023 if (!glx.ctx) {
4024 caml_failwith ("glXCreateContext");
4027 XFree (glx.visual);
4028 glx.visual = NULL;
4030 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4031 glXDestroyContext (glx.dpy, glx.ctx);
4032 glx.ctx = NULL;
4033 caml_failwith ("glXMakeCurrent");
4035 CAMLreturn (Val_unit);
4037 #endif
4039 CAMLprim value ml_setcursor (value cursor_v)
4041 CAMLparam1 (cursor_v);
4042 size_t cursn = Int_val (cursor_v);
4044 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4045 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4046 XFlush (glx.dpy);
4047 CAMLreturn (Val_unit);
4050 CAMLprim value ml_swapb (value unit_v)
4052 CAMLparam1 (unit_v);
4053 #ifdef USE_EGL
4054 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4055 caml_failwith ("eglSwapBuffers");
4057 #else
4058 glXSwapBuffers (glx.dpy, glx.wid);
4059 #endif
4060 CAMLreturn (Val_unit);
4063 #include "keysym2ucs.c"
4065 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4067 CAMLparam1 (keysym_v);
4068 CAMLlocal1 (str_v);
4069 KeySym keysym = Int_val (keysym_v);
4070 Rune rune;
4071 int len;
4072 char buf[5];
4074 rune = keysym2ucs (keysym);
4075 len = fz_runetochar (buf, rune);
4076 buf[len] = 0;
4077 str_v = caml_copy_string (buf);
4078 CAMLreturn (str_v);
4081 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4083 CAMLprim value ml_platform (value unit_v)
4085 CAMLparam1 (unit_v);
4086 CAMLlocal2 (tup_v, arr_v);
4087 int platid = piunknown;
4088 struct utsname buf;
4090 #if defined __linux__
4091 platid = pilinux;
4092 #elif defined __CYGWIN__
4093 platid = picygwin;
4094 #elif defined __DragonFly__ || defined __FreeBSD__
4095 || defined __OpenBSD__ || defined __NetBSD__
4096 platid = pibsd;
4097 #elif defined __sun__
4098 platid = pisun;
4099 #elif defined __APPLE__
4100 platid = piosx;
4101 #endif
4102 if (uname (&buf)) err (1, "uname");
4104 tup_v = caml_alloc_tuple (2);
4106 char const *sar[] = {
4107 buf.sysname,
4108 buf.release,
4109 buf.version,
4110 buf.machine,
4111 NULL
4113 arr_v = caml_copy_string_array (sar);
4115 Field (tup_v, 0) = Val_int (platid);
4116 Field (tup_v, 1) = arr_v;
4117 CAMLreturn (tup_v);
4120 CAMLprim value ml_cloexec (value fd_v)
4122 CAMLparam1 (fd_v);
4123 int fd = Int_val (fd_v);
4125 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4126 uerror ("fcntl", Nothing);
4128 CAMLreturn (Val_unit);
4131 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4133 CAMLparam2 (w_v, h_v);
4134 CAMLlocal1 (ret_v);
4135 struct bo *pbo;
4136 int w = Int_val (w_v);
4137 int h = Int_val (h_v);
4138 int cs = Int_val (cs_v);
4140 if (state.bo_usable) {
4141 pbo = calloc (sizeof (*pbo), 1);
4142 if (!pbo) {
4143 err (1, "calloc pbo");
4146 switch (cs) {
4147 case 0:
4148 case 1:
4149 pbo->size = w*h*4;
4150 break;
4151 case 2:
4152 pbo->size = w*h*2;
4153 break;
4154 default:
4155 errx (1, "%s: invalid colorspace %d", __func__, cs);
4158 state.glGenBuffersARB (1, &pbo->id);
4159 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4160 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4161 NULL, GL_STREAM_DRAW);
4162 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4163 GL_READ_WRITE);
4164 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4165 if (!pbo->ptr) {
4166 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4167 state.glDeleteBuffersARB (1, &pbo->id);
4168 free (pbo);
4169 ret_v = caml_copy_string ("0");
4171 else {
4172 int res;
4173 char *s;
4175 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4176 if (res < 0) {
4177 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4179 s = malloc (res+1);
4180 if (!s) {
4181 err (1, "malloc %d bytes failed", res+1);
4183 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4184 if (res < 0) {
4185 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4187 ret_v = caml_copy_string (s);
4188 free (s);
4191 else {
4192 ret_v = caml_copy_string ("0");
4194 CAMLreturn (ret_v);
4197 CAMLprim value ml_freepbo (value s_v)
4199 CAMLparam1 (s_v);
4200 char *s = String_val (s_v);
4201 struct tile *tile = parse_pointer (__func__, s);
4203 if (tile->pbo) {
4204 state.glDeleteBuffersARB (1, &tile->pbo->id);
4205 tile->pbo->id = -1;
4206 tile->pbo->ptr = NULL;
4207 tile->pbo->size = -1;
4209 CAMLreturn (Val_unit);
4212 CAMLprim value ml_unmappbo (value s_v)
4214 CAMLparam1 (s_v);
4215 char *s = String_val (s_v);
4216 struct tile *tile = parse_pointer (__func__, s);
4218 if (tile->pbo) {
4219 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4220 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4221 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4223 tile->pbo->ptr = NULL;
4224 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4226 CAMLreturn (Val_unit);
4229 static void setuppbo (void)
4231 #ifdef USE_EGL
4232 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4233 #else
4234 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4235 #endif
4236 state.bo_usable = GGPA (glBindBufferARB)
4237 && GGPA (glUnmapBufferARB)
4238 && GGPA (glMapBufferARB)
4239 && GGPA (glBufferDataARB)
4240 && GGPA (glGenBuffersARB)
4241 && GGPA (glDeleteBuffersARB);
4242 #undef GGPA
4245 CAMLprim value ml_bo_usable (value unit_v)
4247 CAMLparam1 (unit_v);
4248 CAMLreturn (Val_bool (state.bo_usable));
4251 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4253 CAMLparam3 (ptr_v, x_v, y_v);
4254 CAMLlocal2 (ret_v, tup_v);
4255 struct page *page;
4256 char *s = String_val (ptr_v);
4257 int x = Int_val (x_v), y = Int_val (y_v);
4258 struct pagedim *pdim;
4259 fz_point p;
4260 fz_matrix ctm;
4262 page = parse_pointer (__func__, s);
4263 pdim = &state.pagedims[page->pdimno];
4265 ret_v = Val_int (0);
4266 if (trylock (__func__)) {
4267 goto done;
4270 if (pdf_specifics (state.ctx, state.doc)) {
4271 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4272 ctm = state.pagedims[page->pdimno].tctm;
4274 else {
4275 ctm = fz_identity;
4277 p.x = x + pdim->bounds.x0;
4278 p.y = y + pdim->bounds.y0;
4280 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4281 fz_invert_matrix (&ctm, &ctm);
4282 fz_transform_point (&p, &ctm);
4284 tup_v = caml_alloc_tuple (2);
4285 ret_v = caml_alloc_small (1, 1);
4286 Field (tup_v, 0) = Val_int (p.x);
4287 Field (tup_v, 1) = Val_int (p.y);
4288 Field (ret_v, 0) = tup_v;
4290 unlock (__func__);
4291 done:
4292 CAMLreturn (ret_v);
4295 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4296 value x_v, value y_v)
4298 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4299 CAMLlocal1 (ret_v);
4300 struct page *page;
4301 char *s = String_val (ptr_v);
4302 int pageno = Int_val (pageno_v);
4303 int pdimno = Int_val (pdimno_v);
4304 double x = Double_val (x_v), y = Double_val (y_v);
4305 struct pagedim *pdim;
4306 fz_point p;
4307 fz_matrix ctm;
4309 ret_v = Val_int (0);
4310 lock (__func__);
4312 if (!*s) {
4313 page = loadpage (pageno, pdimno);
4315 else {
4316 page = parse_pointer (__func__, s);
4318 pdim = &state.pagedims[pdimno];
4320 if (pdf_specifics (state.ctx, state.doc)) {
4321 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4322 ctm = state.pagedims[page->pdimno].tctm;
4324 else {
4325 ctm = fz_identity;
4327 p.x = x + pdim->bounds.x0;
4328 p.y = y + pdim->bounds.y0;
4330 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4331 fz_transform_point (&p, &ctm);
4333 ret_v = caml_alloc_tuple (2);
4334 Field (ret_v, 0) = caml_copy_double (p.x);
4335 Field (ret_v, 1) = caml_copy_double (p.y);
4337 if (!*s) {
4338 freepage (page);
4340 unlock (__func__);
4341 CAMLreturn (ret_v);
4344 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4345 value contents_v)
4347 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4348 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4350 if (pdf) {
4351 pdf_annot *annot;
4352 struct page *page;
4353 fz_point p;
4354 char *s = String_val (ptr_v);
4356 page = parse_pointer (__func__, s);
4357 annot = pdf_create_annot (state.ctx,
4358 pdf_page_from_fz_page (state.ctx,
4359 page->fzpage),
4360 PDF_ANNOT_TEXT);
4361 p.x = Int_val (x_v);
4362 p.y = Int_val (y_v);
4363 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4364 pdf_set_text_annot_position (state.ctx, annot, p);
4365 state.dirty = 1;
4367 CAMLreturn (Val_unit);
4370 CAMLprim value ml_delannot (value ptr_v, value n_v)
4372 CAMLparam2 (ptr_v, n_v);
4373 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4375 if (pdf) {
4376 struct page *page;
4377 char *s = String_val (ptr_v);
4378 struct slink *slink;
4380 page = parse_pointer (__func__, s);
4381 slink = &page->slinks[Int_val (n_v)];
4382 pdf_delete_annot (state.ctx,
4383 pdf_page_from_fz_page (state.ctx, page->fzpage),
4384 (pdf_annot *) slink->u.annot);
4385 state.dirty = 1;
4387 CAMLreturn (Val_unit);
4390 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4392 CAMLparam3 (ptr_v, n_v, str_v);
4393 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4395 if (pdf) {
4396 struct page *page;
4397 char *s = String_val (ptr_v);
4398 struct slink *slink;
4400 page = parse_pointer (__func__, s);
4401 slink = &page->slinks[Int_val (n_v)];
4402 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4403 String_val (str_v));
4404 state.dirty = 1;
4406 CAMLreturn (Val_unit);
4409 CAMLprim value ml_hasunsavedchanges (value unit_v)
4411 CAMLparam1 (unit_v);
4412 CAMLreturn (Val_bool (state.dirty));
4415 CAMLprim value ml_savedoc (value path_v)
4417 CAMLparam1 (path_v);
4418 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4420 if (pdf) {
4421 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4423 CAMLreturn (Val_unit);
4426 static void makestippletex (void)
4428 const char pixels[] = "\xff\xff\0\0";
4429 glGenTextures (1, &state.stid);
4430 glBindTexture (GL_TEXTURE_1D, state.stid);
4431 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4432 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4433 glTexImage1D (
4434 GL_TEXTURE_1D,
4436 GL_ALPHA,
4439 GL_ALPHA,
4440 GL_UNSIGNED_BYTE,
4441 pixels
4445 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4447 return caml_copy_string (FZ_VERSION);
4450 #ifdef USE_FONTCONFIG
4451 static struct {
4452 int inited;
4453 FcConfig *config;
4454 } fc;
4456 static fz_font *fc_load_system_font_func (fz_context *ctx,
4457 const char *name,
4458 int bold,
4459 int italic,
4460 int UNUSED_ATTR needs_exact_metrics)
4462 char *buf;
4463 size_t i, size;
4464 fz_font *font;
4465 FcChar8 *path;
4466 FcResult result;
4467 FcPattern *pat, *pat1;
4469 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4470 name, bold, italic, needs_exact_metrics);
4471 if (!fc.inited) {
4472 fc.inited = 1;
4473 fc.config = FcInitLoadConfigAndFonts ();
4474 if (!fc.config) {
4475 lprintf ("FcInitLoadConfigAndFonts failed\n");
4476 return NULL;
4479 if (!fc.config) return NULL;
4481 size = strlen (name);
4482 if (bold) size += sizeof (":bold") - 1;
4483 if (italic) size += sizeof (":italic") - 1;
4484 size += 1;
4486 buf = malloc (size);
4487 if (!buf) {
4488 err (1, "malloc %zu failed", size);
4491 strcpy (buf, name);
4492 if (bold && italic) {
4493 strcat (buf, ":bold:italic");
4495 else {
4496 if (bold) strcat (buf, ":bold");
4497 if (italic) strcat (buf, ":italic");
4499 for (i = 0; i < size; ++i) {
4500 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4503 lprintf ("fcbuf=%s\n", buf);
4504 pat = FcNameParse ((FcChar8 *) buf);
4505 if (!pat) {
4506 printd ("emsg FcNameParse failed\n");
4507 free (buf);
4508 return NULL;
4511 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4512 printd ("emsg FcConfigSubstitute failed\n");
4513 free (buf);
4514 return NULL;
4516 FcDefaultSubstitute (pat);
4518 pat1 = FcFontMatch (fc.config, pat, &result);
4519 if (!pat1) {
4520 printd ("emsg FcFontMatch failed\n");
4521 FcPatternDestroy (pat);
4522 free (buf);
4523 return NULL;
4526 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4527 printd ("emsg FcPatternGetString failed\n");
4528 FcPatternDestroy (pat);
4529 FcPatternDestroy (pat1);
4530 free (buf);
4531 return NULL;
4534 #if 0
4535 printd ("emsg name=%s path=%s\n", name, path);
4536 #endif
4537 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4538 FcPatternDestroy (pat);
4539 FcPatternDestroy (pat1);
4540 free (buf);
4541 return font;
4543 #endif
4545 CAMLprim value ml_init (value csock_v, value params_v)
4547 CAMLparam2 (csock_v, params_v);
4548 CAMLlocal2 (trim_v, fuzz_v);
4549 int ret;
4550 int texcount;
4551 char *fontpath;
4552 int colorspace;
4553 int mustoresize;
4554 int haspboext;
4556 state.csock = Int_val (csock_v);
4557 state.rotate = Int_val (Field (params_v, 0));
4558 state.fitmodel = Int_val (Field (params_v, 1));
4559 trim_v = Field (params_v, 2);
4560 texcount = Int_val (Field (params_v, 3));
4561 state.sliceheight = Int_val (Field (params_v, 4));
4562 mustoresize = Int_val (Field (params_v, 5));
4563 colorspace = Int_val (Field (params_v, 6));
4564 fontpath = String_val (Field (params_v, 7));
4566 if (caml_string_length (Field (params_v, 8)) > 0) {
4567 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4569 if (!state.trimcachepath) {
4570 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4571 strerror (errno));
4574 haspboext = Bool_val (Field (params_v, 9));
4576 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4577 fz_register_document_handlers (state.ctx);
4579 #ifdef USE_FONTCONFIG
4580 if (Bool_val (Field (params_v, 10))) {
4581 fz_install_load_system_font_funcs (
4582 state.ctx, fc_load_system_font_func, NULL
4585 #endif
4587 state.trimmargins = Bool_val (Field (trim_v, 0));
4588 fuzz_v = Field (trim_v, 1);
4589 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4590 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4591 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4592 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4594 set_tex_params (colorspace);
4596 if (*fontpath) {
4597 #ifndef USE_FONTCONFIG
4598 state.face = load_font (fontpath);
4599 #else
4600 FcChar8 *path;
4601 FcResult result;
4602 char *buf = fontpath;
4603 FcPattern *pat, *pat1;
4605 fc.inited = 1;
4606 fc.config = FcInitLoadConfigAndFonts ();
4607 if (!fc.config) {
4608 errx (1, "FcInitLoadConfigAndFonts failed");
4611 pat = FcNameParse ((FcChar8 *) buf);
4612 if (!pat) {
4613 errx (1, "FcNameParse failed");
4616 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4617 errx (1, "FcConfigSubstitute failed");
4619 FcDefaultSubstitute (pat);
4621 pat1 = FcFontMatch (fc.config, pat, &result);
4622 if (!pat1) {
4623 errx (1, "FcFontMatch failed");
4626 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4627 errx (1, "FcPatternGetString failed");
4630 state.face = load_font ((char *) path);
4631 FcPatternDestroy (pat);
4632 FcPatternDestroy (pat1);
4633 #endif
4635 else {
4636 int len;
4637 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4638 0, 0, &len);
4639 state.face = load_builtin_font (data, len);
4641 if (!state.face) _exit (1);
4643 realloctexts (texcount);
4645 if (haspboext) {
4646 setuppbo ();
4649 makestippletex ();
4651 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4652 if (ret) {
4653 errx (1, "pthread_create: %s", strerror (ret));
4656 CAMLreturn (Val_unit);