Whoops
[llpp.git] / link.c
blobe33dd3a80ca326003dd7159d773b6243ebf7ee99
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>
12 #include <math.h>
13 #include <wchar.h>
14 #include <locale.h>
15 #include <langinfo.h>
17 #include <unistd.h>
18 #include <pthread.h>
19 #include <sys/uio.h>
20 #include <sys/time.h>
21 #include <sys/stat.h>
22 #include <fcntl.h>
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
25 #include <sys/utsname.h>
27 #include <spawn.h>
29 #include <regex.h>
30 #include <stdarg.h>
31 #include <limits.h>
32 #include <inttypes.h>
34 #ifdef __COCOA__
35 #include <CoreFoundation/CoreFoundation.h>
36 #endif
38 #ifdef __APPLE__
39 extern char ** environ;
40 #include <OpenGL/gl.h>
41 #else
42 #include <GL/gl.h>
43 #endif
45 #pragma GCC diagnostic push
46 #ifdef __clang__
47 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
48 #endif
49 #pragma GCC diagnostic ignored "-Wpedantic"
50 #include <caml/fail.h>
51 #include <caml/alloc.h>
52 #include <caml/memory.h>
53 #include <caml/unixsupport.h>
55 #if __GNUC__ < 5 && !defined __clang__
56 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
57 clobbered diagnostics */
58 #pragma GCC diagnostic ignored "-Wclobbered"
59 #endif
61 #include <mupdf/fitz.h>
62 #include <mupdf/pdf.h>
64 #include <ft2build.h>
65 #include FT_FREETYPE_H
66 #pragma GCC diagnostic pop
68 #define PIGGYBACK
69 #define CACHE_PAGEREFS
71 #if defined __GNUC__
72 #define NORETURN_ATTR __attribute__ ((noreturn))
73 #define UNUSED_ATTR __attribute__ ((unused))
74 #if !defined __clang__
75 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
76 #else
77 #define OPTIMIZE_ATTR(n)
78 #endif
79 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
80 #else
81 #define NORETURN_ATTR
82 #define UNUSED_ATTR
83 #define OPTIMIZE_ATTR(n)
84 #define GCC_FMT_ATTR(a, b)
85 #endif
87 #define FMT_s "zu"
89 #define FMT_ptr PRIxPTR
90 #define SCN_ptr SCNxPTR
91 #define FMT_ptr_cast(p) ((uintptr_t) (p))
92 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
94 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
95 err (int exitcode, const char *fmt, ...)
97 va_list ap;
98 int savederrno;
100 savederrno = errno;
101 va_start (ap, fmt);
102 vfprintf (stderr, fmt, ap);
103 va_end (ap);
104 fprintf (stderr, ": %s\n", strerror (savederrno));
105 fflush (stderr);
106 _exit (exitcode);
109 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
110 errx (int exitcode, const char *fmt, ...)
112 va_list ap;
114 va_start (ap, fmt);
115 vfprintf (stderr, fmt, ap);
116 va_end (ap);
117 fputc ('\n', stderr);
118 fflush (stderr);
119 _exit (exitcode);
122 #ifndef GL_TEXTURE_RECTANGLE_ARB
123 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
124 #endif
126 #ifdef USE_NPOT
127 #define TEXT_TYPE GL_TEXTURE_2D
128 #else
129 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
130 #endif
132 #ifndef GL_BGRA
133 #define GL_BGRA 0x80E1
134 #endif
136 #ifndef GL_UNSIGNED_INT_8_8_8_8
137 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
138 #endif
140 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
141 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
142 #endif
144 #if 0
145 #define lprintf printf
146 #else
147 #define lprintf(...)
148 #endif
150 #define ARSERT(cond) for (;;) { \
151 if (!(cond)) { \
152 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
154 break; \
157 struct slice {
158 int h;
159 int texindex;
162 struct tile {
163 int w, h;
164 int slicecount;
165 int sliceheight;
166 struct bo *pbo;
167 fz_pixmap *pixmap;
168 struct slice slices[1];
171 struct pagedim {
172 int pageno;
173 int rotate;
174 int left;
175 int tctmready;
176 fz_irect bounds;
177 fz_rect pagebox;
178 fz_rect mediabox;
179 fz_matrix ctm, zoomctm, tctm;
182 struct slink {
183 enum { SLINK, SANNOT } tag;
184 fz_irect bbox;
185 union {
186 fz_link *link;
187 fz_annot *annot;
188 } u;
191 struct annot {
192 fz_irect bbox;
193 fz_annot *annot;
196 struct page {
197 int tgen;
198 int sgen;
199 int agen;
200 int pageno;
201 int pdimno;
202 fz_stext_page *text;
203 fz_page *fzpage;
204 fz_display_list *dlist;
205 fz_link *links;
206 int slinkcount;
207 struct slink *slinks;
208 int annotcount;
209 struct annot *annots;
210 struct mark {
211 fz_stext_char *ch;
212 } fmark, lmark;
215 enum { FitWidth, FitProportional, FitPage };
217 static struct {
218 int sliceheight;
219 struct pagedim *pagedims;
220 int pagecount;
221 int pagedimcount;
222 fz_document *doc;
223 fz_context *ctx;
224 int w, h;
226 int texindex;
227 int texcount;
228 GLuint *texids;
230 GLenum texiform;
231 GLenum texform;
232 GLenum texty;
234 fz_colorspace *colorspace;
236 struct {
237 int w, h;
238 struct slice *slice;
239 } *texowners;
241 int rotate;
242 int fitmodel;
243 int trimmargins;
244 int needoutline;
245 int gen;
246 int aalevel;
248 int trimanew;
249 fz_irect trimfuzz;
250 fz_pixmap *pig;
252 pthread_t thread;
253 int csock;
254 FT_Face face;
256 char *trimcachepath;
257 int dirty;
259 GLuint stid;
261 int bo_usable;
262 GLuint boid;
264 void (*glBindBufferARB) (GLenum, GLuint);
265 GLboolean (*glUnmapBufferARB) (GLenum);
266 void *(*glMapBufferARB) (GLenum, GLenum);
267 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
268 void (*glGenBuffersARB) (GLsizei, GLuint *);
269 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
271 GLfloat texcoords[8];
272 GLfloat vertices[16];
274 #ifdef CACHE_PAGEREFS
275 struct {
276 int idx;
277 int count;
278 pdf_obj **objs;
279 pdf_document *pdf;
280 } pdflut;
281 #endif
282 int utf8cs;
283 } state;
285 struct bo {
286 GLuint id;
287 void *ptr;
288 size_t size;
291 #pragma GCC diagnostic ignored "-Wdouble-promotion"
292 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
294 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
297 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
299 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
302 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
304 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
305 m.a, m.b, m.c, m.d, m.e, m.f);
307 #pragma GCC diagnostic error "-Wdouble-promotion"
309 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
311 static void lock (const char *cap)
313 int ret = pthread_mutex_lock (&mutex);
314 if (ret) {
315 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
319 static void unlock (const char *cap)
321 int ret = pthread_mutex_unlock (&mutex);
322 if (ret) {
323 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
327 static int trylock (const char *cap)
329 int ret = pthread_mutex_trylock (&mutex);
330 if (ret && ret != EBUSY) {
331 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
333 return ret == EBUSY;
336 static void *parse_pointer (const char *cap, const char *s)
338 int ret;
339 void *ptr;
341 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
342 if (ret != 1) {
343 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
345 return ptr;
348 static double now (void)
350 struct timeval tv;
352 if (gettimeofday (&tv, NULL)) {
353 err (1, "gettimeofday");
355 return tv.tv_sec + tv.tv_usec*1e-6;
358 static int hasdata (void)
360 int ret, avail;
361 ret = ioctl (state.csock, FIONREAD, &avail);
362 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
363 return avail > 0;
366 CAMLprim value ml_hasdata (value fd_v)
368 CAMLparam1 (fd_v);
369 int ret, avail;
371 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
372 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
373 CAMLreturn (Val_bool (avail > 0));
376 static void readdata (int fd, void *p, int size)
378 ssize_t n;
380 again:
381 n = read (fd, p, size);
382 if (n - size) {
383 if (n < 0 && errno == EINTR) goto again;
384 if (!n) errx (1, "EOF while reading");
385 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
389 static void writedata (int fd, char *p, int size)
391 ssize_t n;
392 uint32_t size4 = size;
393 struct iovec iov[2] = {
394 { .iov_base = &size4, .iov_len = 4 },
395 { .iov_base = p, .iov_len = size }
398 again:
399 n = writev (fd, iov, 2);
400 if (n < 0 && errno == EINTR) goto again;
401 if (n - size - 4) {
402 if (!n) errx (1, "EOF while writing data");
403 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
407 static int readlen (int fd)
409 uint32_t u;
410 readdata (fd, &u, 4);
411 return u;
414 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
416 CAMLparam3 (fd_v, bytes_v, len_v);
417 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
418 CAMLreturn0;
421 CAMLprim value ml_rcmd (value fd_v)
423 CAMLparam1 (fd_v);
424 CAMLlocal1 (strdata_v);
425 int fd = Int_val (fd_v);
426 int len = readlen (fd);
427 strdata_v = caml_alloc_string (len);
428 readdata (fd, String_val (strdata_v), len);
429 CAMLreturn (strdata_v);
432 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
434 char fbuf[64];
435 int size = sizeof (fbuf), len;
436 va_list ap;
437 char *buf = fbuf;
439 for (;;) {
440 va_start (ap, fmt);
441 len = vsnprintf (buf, size, fmt, ap);
442 va_end (ap);
444 if (len > -1) {
445 if (len < size - 4) {
446 writedata (state.csock, buf, len);
447 break;
449 else size = len + 5;
451 else {
452 err (1, "vsnprintf for `%s' failed", fmt);
454 buf = realloc (buf == fbuf ? NULL : buf, size);
455 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
457 if (buf != fbuf) free (buf);
460 static void closedoc (void)
462 #ifdef CACHE_PAGEREFS
463 if (state.pdflut.objs) {
464 for (int i = 0; i < state.pdflut.count; ++i) {
465 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
467 free (state.pdflut.objs);
468 state.pdflut.objs = NULL;
469 state.pdflut.idx = 0;
471 #endif
472 if (state.doc) {
473 fz_drop_document (state.ctx, state.doc);
474 state.doc = NULL;
478 static int openxref (char *filename, char *password, int layouth)
480 for (int i = 0; i < state.texcount; ++i) {
481 state.texowners[i].w = -1;
482 state.texowners[i].slice = NULL;
485 closedoc ();
487 state.dirty = 0;
488 if (state.pagedims) {
489 free (state.pagedims);
490 state.pagedims = NULL;
492 state.pagedimcount = 0;
494 fz_set_aa_level (state.ctx, state.aalevel);
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 if (layouth >= 0)
510 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
511 state.pagecount = fz_count_pages (state.ctx, state.doc);
512 return 1;
515 static void pdfinfo (void)
517 struct { char *tag; char *name; } metatbl[] = {
518 { FZ_META_INFO_TITLE, "Title" },
519 { FZ_META_INFO_AUTHOR, "Author" },
520 { FZ_META_FORMAT, "Format" },
521 { FZ_META_ENCRYPTION, "Encryption" },
522 { "info:Creator", "Creator" },
523 { "info:Producer", "Producer" },
524 { "info:CreationDate", "Creation date" },
526 int len = 0;
527 char *buf = NULL;
529 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
530 int need;
531 again:
532 need = fz_lookup_metadata (state.ctx, state.doc,
533 metatbl[i].tag, buf, len);
534 if (need > 0) {
535 if (need <= len) {
536 printd ("info %s\t%s", metatbl[i].name, buf);
538 else {
539 buf = realloc (buf, need + 1);
540 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
541 len = need + 1;
542 goto again;
546 free (buf);
548 printd ("infoend");
551 static void unlinktile (struct tile *tile)
553 for (int i = 0; i < tile->slicecount; ++i) {
554 struct slice *s = &tile->slices[i];
556 if (s->texindex != -1) {
557 if (state.texowners[s->texindex].slice == s) {
558 state.texowners[s->texindex].slice = NULL;
564 static void freepage (struct page *page)
566 if (!page) return;
567 if (page->text) {
568 fz_drop_stext_page (state.ctx, page->text);
570 if (page->slinks) {
571 free (page->slinks);
573 fz_drop_display_list (state.ctx, page->dlist);
574 fz_drop_page (state.ctx, page->fzpage);
575 free (page);
578 static void freetile (struct tile *tile)
580 unlinktile (tile);
581 if (!tile->pbo) {
582 #ifndef PIGGYBACK
583 fz_drop_pixmap (state.ctx, tile->pixmap);
584 #else
585 if (state.pig) {
586 fz_drop_pixmap (state.ctx, state.pig);
588 state.pig = tile->pixmap;
589 #endif
591 else {
592 free (tile->pbo);
593 fz_drop_pixmap (state.ctx, tile->pixmap);
595 free (tile);
598 #ifdef __ALTIVEC__
599 #include <stdint.h>
600 #include <altivec.h>
602 static int cacheline32bytes;
604 static void __attribute__ ((constructor)) clcheck (void)
606 char **envp = environ;
607 unsigned long *auxv;
609 while (*envp++);
611 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
612 if (*auxv == 19) {
613 cacheline32bytes = auxv[1] == 32;
614 return;
619 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
621 size_t size = pixmap->w * pixmap->h * pixmap->n;
622 if (cacheline32bytes && size > 32) {
623 intptr_t a1, a2, diff;
624 size_t sizea, i;
625 vector unsigned char v = vec_splat_u8 (-1);
626 vector unsigned char *p;
628 a1 = a2 = (intptr_t) pixmap->samples;
629 a2 = (a1 + 31) & ~31;
630 diff = a2 - a1;
631 sizea = size - diff;
632 p = (void *) a2;
634 while (a1 != a2) *(char *) a1++ = 0xff;
635 for (i = 0; i < (sizea & ~31); i += 32) {
636 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
637 vec_st (v, i, p);
638 vec_st (v, i + 16, p);
640 while (i < sizea) *((char *) a1 + i++) = 0xff;
642 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
644 #else
645 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
646 #endif
648 static void trimctm (pdf_page *page, int pindex)
650 fz_matrix ctm;
651 struct pagedim *pdim = &state.pagedims[pindex];
653 if (!page) return;
654 if (!pdim->tctmready) {
655 fz_rect realbox, mediabox;
656 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
658 fz_rotate (&rm, -pdim->rotate);
659 fz_scale (&sm, 1, -1);
660 fz_concat (&ctm, &rm, &sm);
661 realbox = pdim->mediabox;
662 fz_transform_rect (&realbox, &ctm);
663 fz_translate (&tm, -realbox.x0, -realbox.y0);
664 fz_concat (&ctm1, &ctm, &tm);
665 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
666 fz_invert_matrix (&im, &page_ctm);
667 fz_concat (&ctm, &im, &ctm1);
668 pdim->tctm = ctm;
669 pdim->tctmready = 1;
673 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
675 fz_matrix ctm, tm;
676 ptrdiff_t pdimno = pdim - state.pagedims;
678 ARSERT (pdim - state.pagedims < INT_MAX);
679 if (pdf_specifics (state.ctx, state.doc)) {
680 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
681 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
683 else {
684 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
685 fz_concat (&ctm, &tm, &pdim->ctm);
687 return ctm;
690 static fz_matrix pagectm (struct page *page)
692 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
695 static void *loadpage (int pageno, int pindex)
697 fz_device *dev;
698 struct page *page;
700 page = calloc (sizeof (struct page), 1);
701 if (!page) {
702 err (1, "calloc page %d", pageno);
705 page->dlist = fz_new_display_list (state.ctx, NULL);
706 dev = fz_new_list_device (state.ctx, page->dlist);
707 fz_try (state.ctx) {
708 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
709 fz_run_page (state.ctx, page->fzpage, dev,
710 &fz_identity, NULL);
712 fz_catch (state.ctx) {
713 page->fzpage = NULL;
715 fz_close_device (state.ctx, dev);
716 fz_drop_device (state.ctx, dev);
718 page->pdimno = pindex;
719 page->pageno = pageno;
720 page->sgen = state.gen;
721 page->agen = state.gen;
722 page->tgen = state.gen;
723 return page;
726 static struct tile *alloctile (int h)
728 int slicecount;
729 size_t tilesize;
730 struct tile *tile;
732 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
733 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
734 tile = calloc (tilesize, 1);
735 if (!tile) {
736 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
738 for (int i = 0; i < slicecount; ++i) {
739 int sh = fz_mini (h, state.sliceheight);
740 tile->slices[i].h = sh;
741 tile->slices[i].texindex = -1;
742 h -= sh;
744 tile->slicecount = slicecount;
745 tile->sliceheight = state.sliceheight;
746 return tile;
749 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
750 struct bo *pbo)
752 fz_rect rect;
753 fz_irect bbox;
754 fz_matrix ctm;
755 fz_device *dev;
756 struct tile *tile;
757 struct pagedim *pdim;
759 tile = alloctile (h);
760 pdim = &state.pagedims[page->pdimno];
762 bbox = pdim->bounds;
763 bbox.x0 += x;
764 bbox.y0 += y;
765 bbox.x1 = bbox.x0 + w;
766 bbox.y1 = bbox.y0 + h;
768 if (state.pig) {
769 if (state.pig->w == w
770 && state.pig->h == h
771 && state.pig->colorspace == state.colorspace) {
772 tile->pixmap = state.pig;
773 tile->pixmap->x = bbox.x0;
774 tile->pixmap->y = bbox.y0;
776 else {
777 fz_drop_pixmap (state.ctx, state.pig);
779 state.pig = NULL;
781 if (!tile->pixmap) {
782 if (pbo) {
783 tile->pixmap =
784 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
785 &bbox, NULL, 1, pbo->ptr);
786 tile->pbo = pbo;
788 else {
789 tile->pixmap =
790 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
791 NULL, 1);
795 tile->w = w;
796 tile->h = h;
797 clearpixmap (tile->pixmap);
799 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
800 ctm = pagectm (page);
801 fz_rect_from_irect (&rect, &bbox);
802 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
803 fz_close_device (state.ctx, dev);
804 fz_drop_device (state.ctx, dev);
806 return tile;
809 #ifdef CACHE_PAGEREFS
810 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
811 thanks to Robin Watts */
812 static void
813 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
815 fz_context *ctx = state.ctx; /* doc->ctx; */
816 pdf_obj *kids;
817 int len;
819 if (state.pdflut.idx == state.pagecount) return;
821 kids = pdf_dict_gets (ctx, node, "Kids");
822 len = pdf_array_len (ctx, kids);
824 if (len == 0)
825 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
827 if (pdf_mark_obj (ctx, node))
828 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
829 for (int i = 0; i < len; i++) {
830 pdf_obj *kid = pdf_array_get (ctx, kids, i);
831 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
832 if (*type
833 ? !strcmp (type, "Pages")
834 : pdf_dict_gets (ctx, kid, "Kids")
835 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
836 pdf_collect_pages (doc, kid);
838 else {
839 if (*type
840 ? strcmp (type, "Page") != 0
841 : !pdf_dict_gets (ctx, kid, "MediaBox"))
842 fz_warn (ctx, "non-page object in page tree (%s)", type);
843 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
846 pdf_unmark_obj (ctx, node);
849 static void
850 pdf_load_page_objs (pdf_document *doc)
852 pdf_obj *root = pdf_dict_gets (state.ctx,
853 pdf_trailer (state.ctx, doc), "Root");
854 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
856 if (!node)
857 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
859 state.pdflut.idx = 0;
860 pdf_collect_pages (doc, node);
862 #endif
864 static void initpdims (void)
866 double start, end;
867 FILE *trimf = NULL;
868 fz_rect rootmediabox = fz_empty_rect;
869 int pageno, trim, show;
870 int trimw = 0, cxcount;
871 fz_context *ctx = state.ctx;
872 pdf_document *pdf = pdf_specifics (ctx, state.doc);
874 fz_var (trimw);
875 fz_var (trimf);
876 fz_var (cxcount);
877 start = now ();
879 if (state.trimmargins && state.trimcachepath) {
880 trimf = fopen (state.trimcachepath, "rb");
881 if (!trimf) {
882 trimf = fopen (state.trimcachepath, "wb");
883 trimw = 1;
887 if (state.trimmargins || pdf)
888 cxcount = state.pagecount;
889 else
890 cxcount = fz_mini (state.pagecount, 1);
892 if (pdf) {
893 pdf_obj *obj;
894 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
895 "Root/Pages/MediaBox");
896 pdf_to_rect (ctx, obj, &rootmediabox);
899 #ifdef CACHE_PAGEREFS
900 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
901 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
902 if (!state.pdflut.objs) {
903 err (1, "malloc pageobjs %zu %d %zu failed",
904 sizeof (*state.pdflut.objs), cxcount,
905 sizeof (*state.pdflut.objs) * cxcount);
907 state.pdflut.count = cxcount;
908 pdf_load_page_objs (pdf);
909 state.pdflut.pdf = pdf;
911 #endif
913 for (pageno = 0; pageno < cxcount; ++pageno) {
914 int rotate = 0;
915 struct pagedim *p;
916 fz_rect mediabox = fz_empty_rect;
918 fz_var (rotate);
919 if (pdf) {
920 pdf_obj *pageref, *pageobj;
922 #ifdef CACHE_PAGEREFS
923 pageref = state.pdflut.objs[pageno];
924 #else
925 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
926 #endif
927 pageobj = pdf_resolve_indirect (ctx, pageref);
928 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
930 if (state.trimmargins) {
931 pdf_obj *obj;
932 pdf_page *page;
934 fz_try (ctx) {
935 page = pdf_load_page (ctx, pdf, pageno);
936 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
937 trim = state.trimanew || !obj;
938 if (trim) {
939 fz_rect rect;
940 fz_device *dev;
941 fz_matrix ctm, page_ctm;
943 dev = fz_new_bbox_device (ctx, &rect);
944 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
945 fz_invert_matrix (&ctm, &page_ctm);
946 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
947 fz_close_device (ctx, dev);
948 fz_drop_device (ctx, dev);
950 rect.x0 += state.trimfuzz.x0;
951 rect.x1 += state.trimfuzz.x1;
952 rect.y0 += state.trimfuzz.y0;
953 rect.y1 += state.trimfuzz.y1;
954 fz_transform_rect (&rect, &ctm);
955 fz_intersect_rect (&rect, &mediabox);
957 if (!fz_is_empty_rect (&rect)) {
958 mediabox = rect;
961 obj = pdf_new_array (ctx, pdf, 4);
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.x0));
964 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
965 mediabox.y0));
966 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
967 mediabox.x1));
968 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
969 mediabox.y1));
970 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
972 else {
973 mediabox.x0 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 0));
975 mediabox.y0 = pdf_to_real (ctx,
976 pdf_array_get (ctx, obj, 1));
977 mediabox.x1 = pdf_to_real (ctx,
978 pdf_array_get (ctx, obj, 2));
979 mediabox.y1 = pdf_to_real (ctx,
980 pdf_array_get (ctx, obj, 3));
983 fz_drop_page (ctx, &page->super);
984 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
985 if (show) {
986 printd ("progress %f Trimming %d",
987 (double) (pageno + 1) / state.pagecount,
988 pageno + 1);
991 fz_catch (ctx) {
992 printd ("emsg failed to load page %d", pageno);
995 else {
996 int empty = 0;
997 fz_rect cropbox;
999 pdf_to_rect (ctx,
1000 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1001 &mediabox);
1002 if (fz_is_empty_rect (&mediabox)) {
1003 mediabox.x0 = 0;
1004 mediabox.y0 = 0;
1005 mediabox.x1 = 612;
1006 mediabox.y1 = 792;
1007 empty = 1;
1010 pdf_to_rect (ctx,
1011 pdf_dict_gets (ctx, pageobj, "CropBox"),
1012 &cropbox);
1013 if (!fz_is_empty_rect (&cropbox)) {
1014 if (empty) {
1015 mediabox = cropbox;
1017 else {
1018 fz_intersect_rect (&mediabox, &cropbox);
1021 else {
1022 if (empty) {
1023 if (fz_is_empty_rect (&rootmediabox)) {
1024 printd ("emsg cannot find page size for page %d",
1025 pageno);
1027 else {
1028 mediabox = rootmediabox;
1034 else {
1035 if (state.trimmargins && trimw) {
1036 fz_page *page;
1038 fz_try (ctx) {
1039 page = fz_load_page (ctx, state.doc, pageno);
1040 fz_bound_page (ctx, page, &mediabox);
1041 if (state.trimmargins) {
1042 fz_rect rect;
1043 fz_device *dev;
1045 dev = fz_new_bbox_device (ctx, &rect);
1046 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1047 fz_close_device (ctx, dev);
1048 fz_drop_device (ctx, dev);
1050 rect.x0 += state.trimfuzz.x0;
1051 rect.x1 += state.trimfuzz.x1;
1052 rect.y0 += state.trimfuzz.y0;
1053 rect.y1 += state.trimfuzz.y1;
1054 fz_intersect_rect (&rect, &mediabox);
1056 if (!fz_is_empty_rect (&rect)) {
1057 mediabox = rect;
1060 fz_drop_page (ctx, page);
1062 fz_catch (ctx) {
1064 if (trimf) {
1065 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1066 if (n - 1) {
1067 err (1, "fwrite trim mediabox");
1071 else {
1072 if (trimf) {
1073 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1074 if (n - 1) {
1075 err (1, "fread trim mediabox %d", pageno);
1078 else {
1079 fz_page *page;
1080 fz_try (ctx) {
1081 page = fz_load_page (ctx, state.doc, pageno);
1082 fz_bound_page (ctx, page, &mediabox);
1083 fz_drop_page (ctx, page);
1085 show = !state.trimmargins && pageno % 20 == 0;
1086 if (show) {
1087 printd ("progress %f Gathering dimensions %d",
1088 (double) (pageno) / state.pagecount,
1089 pageno);
1092 fz_catch (ctx) {
1093 printd ("emsg failed to load page %d", pageno);
1099 if (state.pagedimcount == 0
1100 || ((void) (p = &state.pagedims[state.pagedimcount-1])
1101 , p->rotate != rotate)
1102 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1103 size_t size;
1105 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1106 state.pagedims = realloc (state.pagedims, size);
1107 if (!state.pagedims) {
1108 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1109 size, state.pagedimcount + 1);
1112 p = &state.pagedims[state.pagedimcount++];
1113 p->rotate = rotate;
1114 p->mediabox = mediabox;
1115 p->pageno = pageno;
1118 end = now ();
1119 printd ("progress 1 %s %d pages in %f seconds",
1120 state.trimmargins ? "Trimmed" : "Processed",
1121 state.pagecount, end - start);
1122 state.trimanew = 0;
1123 if (trimf) {
1124 if (fclose (trimf)) {
1125 err (1, "fclose");
1130 static void layout (void)
1132 int pindex;
1133 fz_rect box;
1134 fz_matrix ctm, rm;
1135 struct pagedim *p = NULL;
1136 float zw, w, maxw = 0.0, zoom = 1.0;
1138 if (state.pagedimcount == 0) return;
1140 switch (state.fitmodel) {
1141 case FitProportional:
1142 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1143 float x0, x1;
1145 p = &state.pagedims[pindex];
1146 fz_rotate (&rm, p->rotate + state.rotate);
1147 box = p->mediabox;
1148 fz_transform_rect (&box, &rm);
1150 x0 = fz_min (box.x0, box.x1);
1151 x1 = fz_max (box.x0, box.x1);
1153 w = x1 - x0;
1154 maxw = fz_max (w, maxw);
1155 zoom = state.w / maxw;
1157 break;
1159 case FitPage:
1160 maxw = state.w;
1161 break;
1163 case FitWidth:
1164 break;
1166 default:
1167 ARSERT (0 && state.fitmodel);
1170 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1171 fz_rect rect;
1172 fz_matrix tm, sm;
1174 p = &state.pagedims[pindex];
1175 fz_rotate (&ctm, state.rotate);
1176 fz_rotate (&rm, p->rotate + state.rotate);
1177 box = p->mediabox;
1178 fz_transform_rect (&box, &rm);
1179 w = box.x1 - box.x0;
1180 switch (state.fitmodel) {
1181 case FitProportional:
1182 p->left = (int) (((maxw - w) * zoom) / 2.f);
1183 break;
1184 case FitPage:
1186 float zh, h;
1187 zw = maxw / w;
1188 h = box.y1 - box.y0;
1189 zh = state.h / h;
1190 zoom = fz_min (zw, zh);
1191 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1193 break;
1194 case FitWidth:
1195 p->left = 0;
1196 zoom = state.w / w;
1197 break;
1200 fz_scale (&p->zoomctm, zoom, zoom);
1201 fz_concat (&ctm, &p->zoomctm, &ctm);
1203 fz_rotate (&rm, p->rotate);
1204 p->pagebox = p->mediabox;
1205 fz_transform_rect (&p->pagebox, &rm);
1206 p->pagebox.x1 -= p->pagebox.x0;
1207 p->pagebox.y1 -= p->pagebox.y0;
1208 p->pagebox.x0 = 0;
1209 p->pagebox.y0 = 0;
1210 rect = p->pagebox;
1211 fz_transform_rect (&rect, &ctm);
1212 fz_round_rect (&p->bounds, &rect);
1213 p->ctm = ctm;
1215 fz_translate (&tm, 0, -p->mediabox.y1);
1216 fz_scale (&sm, zoom, -zoom);
1217 fz_concat (&ctm, &tm, &sm);
1219 p->tctmready = 0;
1222 do {
1223 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1224 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1225 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1226 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1227 int boundw = x1 - x0;
1228 int boundh = y1 - y0;
1230 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1231 } while (p-- != state.pagedims);
1234 struct pagedim *pdimofpageno (int pageno)
1236 struct pagedim *pdim = state.pagedims;
1238 for (int i = 0; i < state.pagedimcount; ++i) {
1239 if (state.pagedims[i].pageno > pageno)
1240 break;
1241 pdim = &state.pagedims[i];
1243 return pdim;
1246 static void recurse_outline (fz_outline *outline, int level)
1248 while (outline) {
1249 if (outline->page >= 0) {
1250 fz_point p = {.x = outline->x, .y = outline->y};
1251 struct pagedim *pdim = pdimofpageno (outline->page);
1252 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1253 fz_transform_point (&p, &pdim->ctm);
1254 printd ("o %d %d %d %d %s",
1255 level, outline->page, (int) p.y, h, outline->title);
1257 else {
1258 printd ("on %d %s", level, outline->title);
1260 if (outline->down) {
1261 recurse_outline (outline->down, level + 1);
1263 outline = outline->next;
1267 static void process_outline (void)
1269 fz_outline *outline;
1271 if (!state.needoutline || !state.pagedimcount) return;
1273 state.needoutline = 0;
1274 outline = fz_load_outline (state.ctx, state.doc);
1275 if (outline) {
1276 recurse_outline (outline, 0);
1277 fz_drop_outline (state.ctx, outline);
1281 static char *strofline (fz_stext_line *line)
1283 char *p;
1284 char utf8[10];
1285 fz_stext_char *ch;
1286 size_t size = 0, cap = 80;
1288 p = malloc (cap + 1);
1289 if (!p) return NULL;
1291 for (ch = line->first_char; ch; ch = ch->next) {
1292 int n = fz_runetochar (utf8, ch->c);
1293 if (size + n > cap) {
1294 cap *= 2;
1295 p = realloc (p, cap + 1);
1296 if (!p) return NULL;
1299 memcpy (p + size, utf8, n);
1300 size += n;
1302 p[size] = 0;
1303 return p;
1306 static int matchline (regex_t *re, fz_stext_line *line,
1307 int stop, int pageno, double start)
1309 int ret;
1310 char *p;
1311 regmatch_t rm;
1313 p = strofline (line);
1314 if (!p) return -1;
1316 ret = regexec (re, p, 1, &rm, 0);
1317 if (ret) {
1318 free (p);
1319 if (ret != REG_NOMATCH) {
1320 size_t size;
1321 char errbuf[80];
1322 size = regerror (ret, re, errbuf, sizeof (errbuf));
1323 printd ("msg regexec error `%.*s'",
1324 (int) size, errbuf);
1325 return -1;
1327 return 0;
1329 else {
1330 fz_point p1, p2, p3, p4;
1331 fz_rect s = {0,0,0,0}, e;
1332 fz_stext_char *ch;
1333 int o = 0;
1335 for (ch = line->first_char; ch; ch = ch->next) {
1336 o += fz_runelen (ch->c);
1337 if (o > rm.rm_so) {
1338 s = ch->bbox;
1339 break;
1342 for (;ch; ch = ch->next) {
1343 o += fz_runelen (ch->c);
1344 if (o > rm.rm_eo) break;
1346 e = ch->bbox;
1348 p1.x = s.x0;
1349 p1.y = s.y0;
1350 p2.x = e.x1;
1351 p2.y = s.y0;
1352 p3.x = e.x1;
1353 p3.y = e.y1;
1354 p4.x = s.x0;
1355 p4.y = e.y1;
1357 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1358 if (!stop) {
1359 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1360 pageno, 1,
1361 p1.x, p1.y,
1362 p2.x, p2.y,
1363 p3.x, p3.y,
1364 p4.x, p4.y);
1366 printd ("progress 1 found at %d `%.*s' in %f sec",
1367 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1368 now () - start);
1370 else {
1371 printd ("match %d %d %f %f %f %f %f %f %f %f",
1372 pageno, 2,
1373 p1.x, p1.y,
1374 p2.x, p2.y,
1375 p3.x, p3.y,
1376 p4.x, p4.y);
1378 #pragma GCC diagnostic error "-Wdouble-promotion"
1379 free (p);
1380 return 1;
1384 /* wishful thinking function */
1385 static void search (regex_t *re, int pageno, int y, int forward)
1387 fz_device *tdev;
1388 fz_stext_page *text;
1389 struct pagedim *pdim;
1390 int stop = 0, niters = 0;
1391 double start, end;
1392 fz_page *page;
1393 fz_stext_block *block;
1395 start = now ();
1396 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1397 if (niters++ == 5) {
1398 niters = 0;
1399 if (hasdata ()) {
1400 printd ("progress 1 attention requested aborting search at %d",
1401 pageno);
1402 stop = 1;
1404 else {
1405 printd ("progress %f searching in page %d",
1406 (double) (pageno + 1) / state.pagecount,
1407 pageno);
1410 pdim = pdimofpageno (pageno);
1411 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1412 tdev = fz_new_stext_device (state.ctx, text, 0);
1414 page = fz_load_page (state.ctx, state.doc, pageno);
1416 fz_matrix ctm = pagectm1 (page, pdim);
1417 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1420 fz_close_device (state.ctx, tdev);
1421 fz_drop_device (state.ctx, tdev);
1423 if (forward) {
1424 for (block = text->first_block; block; block = block->next) {
1425 fz_stext_line *line;
1427 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1428 for (line = block->u.t.first_line; line; line = line->next) {
1429 if (line->bbox.y0 < y + 1) continue;
1431 switch (matchline (re, line, stop, pageno, start)) {
1432 case 0: break;
1433 case 1: stop = 1; break;
1434 case -1: stop = 1; goto endloop;
1439 else {
1440 for (block = text->last_block; block; block = block->prev) {
1441 fz_stext_line *line;
1443 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1444 for (line = block->u.t.last_line; line; line = line->prev) {
1445 if (line->bbox.y0 < y + 1) continue;
1447 switch (matchline (re, line, stop, pageno, start)) {
1448 case 0: break;
1449 case 1: stop = 1; break;
1450 case -1: stop = 1; goto endloop;
1456 if (forward) {
1457 pageno += 1;
1458 y = 0;
1460 else {
1461 pageno -= 1;
1462 y = INT_MAX;
1464 endloop:
1465 fz_drop_stext_page (state.ctx, text);
1466 fz_drop_page (state.ctx, page);
1468 end = now ();
1469 if (!stop) {
1470 printd ("progress 1 no matches %f sec", end - start);
1472 printd ("clearrects");
1475 static void set_tex_params (int colorspace)
1477 switch (colorspace) {
1478 case 0:
1479 state.texiform = GL_RGBA8;
1480 state.texform = GL_RGBA;
1481 state.texty = GL_UNSIGNED_BYTE;
1482 state.colorspace = fz_device_rgb (state.ctx);
1483 break;
1484 case 1:
1485 state.texiform = GL_RGBA8;
1486 state.texform = GL_BGRA;
1487 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1488 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1489 #else
1490 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1491 #endif
1492 state.colorspace = fz_device_bgr (state.ctx);
1493 break;
1494 case 2:
1495 state.texiform = GL_LUMINANCE_ALPHA;
1496 state.texform = GL_LUMINANCE_ALPHA;
1497 state.texty = GL_UNSIGNED_BYTE;
1498 state.colorspace = fz_device_gray (state.ctx);
1499 break;
1500 default:
1501 errx (1, "invalid colorspce %d", colorspace);
1505 static void realloctexts (int texcount)
1507 size_t size;
1509 if (texcount == state.texcount) return;
1511 if (texcount < state.texcount) {
1512 glDeleteTextures (state.texcount - texcount,
1513 state.texids + texcount);
1516 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1517 state.texids = realloc (state.texids, size);
1518 if (!state.texids) {
1519 err (1, "realloc texs %" FMT_s, size);
1522 state.texowners = (void *) (state.texids + texcount);
1523 if (texcount > state.texcount) {
1524 glGenTextures (texcount - state.texcount,
1525 state.texids + state.texcount);
1526 for (int i = state.texcount; i < texcount; ++i) {
1527 state.texowners[i].w = -1;
1528 state.texowners[i].slice = NULL;
1531 state.texcount = texcount;
1532 state.texindex = 0;
1535 static char *mbtoutf8 (char *s)
1537 char *p, *r;
1538 wchar_t *tmp;
1539 size_t i, ret, len;
1541 if (state.utf8cs) {
1542 return s;
1545 len = mbstowcs (NULL, s, strlen (s));
1546 if (len == 0) {
1547 return s;
1549 else {
1550 if (len == (size_t) -1) {
1551 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1552 return s;
1556 tmp = calloc (len, sizeof (wchar_t));
1557 if (!tmp) {
1558 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1559 len, sizeof (wchar_t), errno, strerror (errno));
1560 return s;
1563 ret = mbstowcs (tmp, s, len);
1564 if (ret == (size_t) -1) {
1565 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1566 len, errno, strerror (errno));
1567 free (tmp);
1568 return s;
1571 len = 0;
1572 for (i = 0; i < ret; ++i) {
1573 len += fz_runelen (tmp[i]);
1576 p = r = malloc (len + 1);
1577 if (!r) {
1578 printd ("emsg mbtoutf8: malloc(%zu)", len);
1579 free (tmp);
1580 return s;
1583 for (i = 0; i < ret; ++i) {
1584 p += fz_runetochar (p, tmp[i]);
1586 *p = 0;
1587 free (tmp);
1588 return r;
1591 CAMLprim value ml_mbtoutf8 (value s_v)
1593 CAMLparam1 (s_v);
1594 CAMLlocal1 (ret_v);
1595 char *s, *r;
1597 s = String_val (s_v);
1598 r = mbtoutf8 (s);
1599 if (r == s) {
1600 ret_v = s_v;
1602 else {
1603 ret_v = caml_copy_string (r);
1604 free (r);
1606 CAMLreturn (ret_v);
1609 static void * mainloop (void UNUSED_ATTR *unused)
1611 char *p = NULL;
1612 int len, ret, oldlen = 0;
1614 fz_var (p);
1615 fz_var (oldlen);
1616 for (;;) {
1617 len = readlen (state.csock);
1618 if (len == 0) {
1619 errx (1, "readlen returned 0");
1622 if (oldlen < len + 1) {
1623 p = realloc (p, len + 1);
1624 if (!p) {
1625 err (1, "realloc %d failed", len + 1);
1627 oldlen = len + 1;
1629 readdata (state.csock, p, len);
1630 p[len] = 0;
1632 if (!strncmp ("open", p, 4)) {
1633 int off, usedoccss, ok = 0, layouth;
1634 char *password;
1635 char *filename;
1636 char *utf8filename;
1637 size_t filenamelen;
1639 fz_var (ok);
1640 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1641 if (ret != 2) {
1642 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1645 filename = p + 5 + off;
1646 filenamelen = strlen (filename);
1647 password = filename + filenamelen + 1;
1649 if (password[strlen (password) + 1]) {
1650 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1653 lock ("open");
1654 fz_set_use_document_css (state.ctx, usedoccss);
1655 fz_try (state.ctx) {
1656 ok = openxref (filename, password, layouth);
1658 fz_catch (state.ctx) {
1659 utf8filename = mbtoutf8 (filename);
1660 printd ("msg Could not open %s", utf8filename);
1661 if (utf8filename != filename) {
1662 free (utf8filename);
1665 if (ok) {
1666 pdfinfo ();
1667 initpdims ();
1669 unlock ("open");
1671 if (ok) {
1672 utf8filename = mbtoutf8 (filename);
1673 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1674 if (utf8filename != filename) {
1675 free (utf8filename);
1677 state.needoutline = 1;
1680 else if (!strncmp ("cs", p, 2)) {
1681 int i, colorspace;
1683 ret = sscanf (p + 2, " %d", &colorspace);
1684 if (ret != 1) {
1685 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1687 lock ("cs");
1688 set_tex_params (colorspace);
1689 for (i = 0; i < state.texcount; ++i) {
1690 state.texowners[i].w = -1;
1691 state.texowners[i].slice = NULL;
1693 unlock ("cs");
1695 else if (!strncmp ("freepage", p, 8)) {
1696 void *ptr;
1698 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1699 if (ret != 1) {
1700 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1702 lock ("freepage");
1703 freepage (ptr);
1704 unlock ("freepage");
1706 else if (!strncmp ("freetile", p, 8)) {
1707 void *ptr;
1709 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1710 if (ret != 1) {
1711 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1713 lock ("freetile");
1714 freetile (ptr);
1715 unlock ("freetile");
1717 else if (!strncmp ("search", p, 6)) {
1718 int icase, pageno, y, len2, forward;
1719 char *pattern;
1720 regex_t re;
1722 ret = sscanf (p + 6, " %d %d %d %d,%n",
1723 &icase, &pageno, &y, &forward, &len2);
1724 if (ret != 4) {
1725 errx (1, "malformed search `%s' ret=%d", p, ret);
1728 pattern = p + 6 + len2;
1729 ret = regcomp (&re, pattern,
1730 REG_EXTENDED | (icase ? REG_ICASE : 0));
1731 if (ret) {
1732 char errbuf[80];
1733 size_t size;
1735 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1736 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1738 else {
1739 search (&re, pageno, y, forward);
1740 regfree (&re);
1743 else if (!strncmp ("geometry", p, 8)) {
1744 int w, h, fitmodel;
1746 printd ("clear");
1747 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1748 if (ret != 3) {
1749 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1752 lock ("geometry");
1753 state.h = h;
1754 if (w != state.w) {
1755 state.w = w;
1756 for (int i = 0; i < state.texcount; ++i) {
1757 state.texowners[i].slice = NULL;
1760 state.fitmodel = fitmodel;
1761 layout ();
1762 process_outline ();
1764 state.gen++;
1765 unlock ("geometry");
1766 printd ("continue %d", state.pagecount);
1768 else if (!strncmp ("reqlayout", p, 9)) {
1769 char *nameddest;
1770 int rotate, off, h;
1771 int fitmodel;
1772 pdf_document *pdf;
1774 printd ("clear");
1775 ret = sscanf (p + 9, " %d %d %d %n",
1776 &rotate, &fitmodel, &h, &off);
1777 if (ret != 3) {
1778 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1780 lock ("reqlayout");
1781 pdf = pdf_specifics (state.ctx, state.doc);
1782 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1783 state.gen += 1;
1785 state.rotate = rotate;
1786 state.fitmodel = fitmodel;
1787 state.h = h;
1788 layout ();
1789 process_outline ();
1791 nameddest = p + 9 + off;
1792 if (pdf && nameddest && *nameddest) {
1793 fz_point xy;
1794 struct pagedim *pdim;
1795 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1796 &xy.x, &xy.y);
1797 pdim = pdimofpageno (pageno);
1798 fz_transform_point (&xy, &pdim->ctm);
1799 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1802 state.gen++;
1803 unlock ("reqlayout");
1804 printd ("continue %d", state.pagecount);
1806 else if (!strncmp ("page", p, 4)) {
1807 double a, b;
1808 struct page *page;
1809 int pageno, pindex;
1811 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1812 if (ret != 2) {
1813 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1816 lock ("page");
1817 a = now ();
1818 page = loadpage (pageno, pindex);
1819 b = now ();
1820 unlock ("page");
1822 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1824 else if (!strncmp ("tile", p, 4)) {
1825 int x, y, w, h;
1826 struct page *page;
1827 struct tile *tile;
1828 double a, b;
1829 void *data;
1831 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1832 SCN_ptr_cast (&page), &x, &y, &w, &h,
1833 SCN_ptr_cast (&data));
1834 if (ret != 6) {
1835 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1838 lock ("tile");
1839 a = now ();
1840 tile = rendertile (page, x, y, w, h, data);
1841 b = now ();
1842 unlock ("tile");
1844 printd ("tile %d %d %" FMT_ptr " %u %f",
1845 x, y,
1846 FMT_ptr_cast (tile),
1847 tile->w * tile->h * tile->pixmap->n,
1848 b - a);
1850 else if (!strncmp ("trimset", p, 7)) {
1851 fz_irect fuzz;
1852 int trimmargins;
1854 ret = sscanf (p + 7, " %d %d %d %d %d",
1855 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1856 if (ret != 5) {
1857 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1859 lock ("trimset");
1860 state.trimmargins = trimmargins;
1861 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1862 state.trimanew = 1;
1863 state.trimfuzz = fuzz;
1865 unlock ("trimset");
1867 else if (!strncmp ("settrim", p, 7)) {
1868 fz_irect fuzz;
1869 int trimmargins;
1871 ret = sscanf (p + 7, " %d %d %d %d %d",
1872 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1873 if (ret != 5) {
1874 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1876 printd ("clear");
1877 lock ("settrim");
1878 state.trimmargins = trimmargins;
1879 state.needoutline = 1;
1880 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1881 state.trimanew = 1;
1882 state.trimfuzz = fuzz;
1884 state.pagedimcount = 0;
1885 free (state.pagedims);
1886 state.pagedims = NULL;
1887 initpdims ();
1888 layout ();
1889 process_outline ();
1890 unlock ("settrim");
1891 printd ("continue %d", state.pagecount);
1893 else if (!strncmp ("sliceh", p, 6)) {
1894 int h;
1896 ret = sscanf (p + 6, " %d", &h);
1897 if (ret != 1) {
1898 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1900 if (h != state.sliceheight) {
1901 state.sliceheight = h;
1902 for (int i = 0; i < state.texcount; ++i) {
1903 state.texowners[i].w = -1;
1904 state.texowners[i].h = -1;
1905 state.texowners[i].slice = NULL;
1909 else if (!strncmp ("interrupt", p, 9)) {
1910 printd ("vmsg interrupted");
1912 else {
1913 errx (1, "unknown command %.*s", len, p);
1916 return 0;
1919 CAMLprim value ml_isexternallink (value uri_v)
1921 CAMLparam1 (uri_v);
1922 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1923 CAMLreturn (Val_bool (ext));
1926 CAMLprim value ml_uritolocation (value uri_v)
1928 CAMLparam1 (uri_v);
1929 CAMLlocal1 (ret_v);
1930 int pageno;
1931 fz_point xy;
1932 struct pagedim *pdim;
1934 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1935 &xy.x, &xy.y);
1936 pdim = pdimofpageno (pageno);
1937 fz_transform_point (&xy, &pdim->ctm);
1938 ret_v = caml_alloc_tuple (3);
1939 Field (ret_v, 0) = Val_int (pageno);
1940 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1941 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1942 CAMLreturn (ret_v);
1945 CAMLprim value ml_realloctexts (value texcount_v)
1947 CAMLparam1 (texcount_v);
1948 int ok;
1950 if (trylock (__func__)) {
1951 ok = 0;
1952 goto done;
1954 realloctexts (Int_val (texcount_v));
1955 ok = 1;
1956 unlock (__func__);
1958 done:
1959 CAMLreturn (Val_bool (ok));
1962 static void recti (int x0, int y0, int x1, int y1)
1964 GLfloat *v = state.vertices;
1966 glVertexPointer (2, GL_FLOAT, 0, v);
1967 v[0] = x0; v[1] = y0;
1968 v[2] = x1; v[3] = y0;
1969 v[4] = x0; v[5] = y1;
1970 v[6] = x1; v[7] = y1;
1971 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1974 static void showsel (struct page *page, int ox, int oy)
1976 fz_irect bbox;
1977 fz_rect rect;
1978 fz_stext_block *block;
1979 int seen = 0;
1980 unsigned char selcolor[] = {15,15,15,140};
1982 if (!page->fmark.ch || !page->lmark.ch) return;
1984 glEnable (GL_BLEND);
1985 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1986 glColor4ubv (selcolor);
1988 ox += state.pagedims[page->pdimno].bounds.x0;
1989 oy += state.pagedims[page->pdimno].bounds.y0;
1991 for (block = page->text->first_block; block; block = block->next) {
1992 fz_stext_line *line;
1994 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1995 for (line = block->u.t.first_line; line; line = line->next) {
1996 fz_stext_char *ch;
1998 rect = fz_empty_rect;
1999 for (ch = line->first_char; ch; ch = ch->next) {
2000 if (ch == page->fmark.ch) seen = 1;
2001 if (seen) fz_union_rect (&rect, &ch->bbox);
2002 if (ch == page->lmark.ch) {
2003 fz_round_rect (&bbox, &rect);
2004 recti (bbox.x0 + ox, bbox.y0 + oy,
2005 bbox.x1 + ox, bbox.y1 + oy);
2006 goto done;
2009 fz_round_rect (&bbox, &rect);
2010 recti (bbox.x0 + ox, bbox.y0 + oy,
2011 bbox.x1 + ox, bbox.y1 + oy);
2014 done:
2015 glDisable (GL_BLEND);
2018 #pragma GCC diagnostic push
2019 #pragma GCC diagnostic ignored "-Wdouble-promotion"
2020 #pragma GCC diagnostic ignored "-Wconversion"
2021 #include "glfont.c"
2022 #pragma GCC diagnostic pop
2024 static void stipplerect (fz_matrix *m,
2025 fz_point *p1,
2026 fz_point *p2,
2027 fz_point *p3,
2028 fz_point *p4,
2029 GLfloat *texcoords,
2030 GLfloat *vertices)
2032 fz_transform_point (p1, m);
2033 fz_transform_point (p2, m);
2034 fz_transform_point (p3, m);
2035 fz_transform_point (p4, m);
2037 float w, h, s, t;
2039 w = p2->x - p1->x;
2040 h = p2->y - p1->y;
2041 t = hypotf (w, h) * .25f;
2043 w = p3->x - p2->x;
2044 h = p3->y - p2->y;
2045 s = hypotf (w, h) * .25f;
2047 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2048 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2050 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2051 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2053 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2054 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2056 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2057 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2059 glDrawArrays (GL_LINES, 0, 8);
2062 static void solidrect (fz_matrix *m,
2063 fz_point *p1,
2064 fz_point *p2,
2065 fz_point *p3,
2066 fz_point *p4,
2067 GLfloat *vertices)
2069 fz_transform_point (p1, m);
2070 fz_transform_point (p2, m);
2071 fz_transform_point (p3, m);
2072 fz_transform_point (p4, m);
2073 vertices[0] = p1->x; vertices[1] = p1->y;
2074 vertices[2] = p2->x; vertices[3] = p2->y;
2076 vertices[4] = p3->x; vertices[5] = p3->y;
2077 vertices[6] = p4->x; vertices[7] = p4->y;
2078 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2081 static void ensurelinks (struct page *page)
2083 if (!page->links)
2084 page->links = fz_load_links (state.ctx, page->fzpage);
2087 static void highlightlinks (struct page *page, int xoff, int yoff)
2089 fz_matrix ctm, tm, pm;
2090 fz_link *link;
2091 GLfloat *texcoords = state.texcoords;
2092 GLfloat *vertices = state.vertices;
2094 ensurelinks (page);
2096 glEnable (GL_TEXTURE_1D);
2097 glEnable (GL_BLEND);
2098 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2099 glBindTexture (GL_TEXTURE_1D, state.stid);
2101 xoff -= state.pagedims[page->pdimno].bounds.x0;
2102 yoff -= state.pagedims[page->pdimno].bounds.y0;
2103 fz_translate (&tm, xoff, yoff);
2104 pm = pagectm (page);
2105 fz_concat (&ctm, &pm, &tm);
2107 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2108 glVertexPointer (2, GL_FLOAT, 0, vertices);
2110 for (link = page->links; link; link = link->next) {
2111 fz_point p1, p2, p3, p4;
2113 p1.x = link->rect.x0;
2114 p1.y = link->rect.y0;
2116 p2.x = link->rect.x1;
2117 p2.y = link->rect.y0;
2119 p3.x = link->rect.x1;
2120 p3.y = link->rect.y1;
2122 p4.x = link->rect.x0;
2123 p4.y = link->rect.y1;
2125 /* TODO: different colours for different schemes */
2126 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2127 else glColor3ub (255, 0, 0);
2129 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2132 for (int i = 0; i < page->annotcount; ++i) {
2133 fz_point p1, p2, p3, p4;
2134 struct annot *annot = &page->annots[i];
2136 p1.x = annot->bbox.x0;
2137 p1.y = annot->bbox.y0;
2139 p2.x = annot->bbox.x1;
2140 p2.y = annot->bbox.y0;
2142 p3.x = annot->bbox.x1;
2143 p3.y = annot->bbox.y1;
2145 p4.x = annot->bbox.x0;
2146 p4.y = annot->bbox.y1;
2148 glColor3ub (0, 0, 128);
2149 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2152 glDisable (GL_BLEND);
2153 glDisable (GL_TEXTURE_1D);
2156 static int compareslinks (const void *l, const void *r)
2158 struct slink const *ls = l;
2159 struct slink const *rs = r;
2160 if (ls->bbox.y0 == rs->bbox.y0) {
2161 return rs->bbox.x0 - rs->bbox.x0;
2163 return ls->bbox.y0 - rs->bbox.y0;
2166 static void droptext (struct page *page)
2168 if (page->text) {
2169 fz_drop_stext_page (state.ctx, page->text);
2170 page->fmark.ch = NULL;
2171 page->lmark.ch = NULL;
2172 page->text = NULL;
2176 static void dropannots (struct page *page)
2178 if (page->annots) {
2179 free (page->annots);
2180 page->annots = NULL;
2181 page->annotcount = 0;
2185 static void ensureannots (struct page *page)
2187 int i, count = 0;
2188 size_t annotsize = sizeof (*page->annots);
2189 fz_annot *annot;
2191 if (state.gen != page->agen) {
2192 dropannots (page);
2193 page->agen = state.gen;
2195 if (page->annots) return;
2197 for (annot = fz_first_annot (state.ctx, page->fzpage);
2198 annot;
2199 annot = fz_next_annot (state.ctx, annot)) {
2200 count++;
2203 if (count > 0) {
2204 page->annotcount = count;
2205 page->annots = calloc (count, annotsize);
2206 if (!page->annots) {
2207 err (1, "calloc annots %d", count);
2210 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2211 annot;
2212 annot = fz_next_annot (state.ctx, annot), i++) {
2213 fz_rect rect;
2215 fz_bound_annot (state.ctx, annot, &rect);
2216 page->annots[i].annot = annot;
2217 fz_round_rect (&page->annots[i].bbox, &rect);
2222 static void dropslinks (struct page *page)
2224 if (page->slinks) {
2225 free (page->slinks);
2226 page->slinks = NULL;
2227 page->slinkcount = 0;
2229 if (page->links) {
2230 fz_drop_link (state.ctx, page->links);
2231 page->links = NULL;
2235 static void ensureslinks (struct page *page)
2237 fz_matrix ctm;
2238 int i, count;
2239 size_t slinksize = sizeof (*page->slinks);
2240 fz_link *link;
2242 ensureannots (page);
2243 if (state.gen != page->sgen) {
2244 dropslinks (page);
2245 page->sgen = state.gen;
2247 if (page->slinks) return;
2249 ensurelinks (page);
2250 ctm = pagectm (page);
2252 count = page->annotcount;
2253 for (link = page->links; link; link = link->next) {
2254 count++;
2256 if (count > 0) {
2257 int j;
2259 page->slinkcount = count;
2260 page->slinks = calloc (count, slinksize);
2261 if (!page->slinks) {
2262 err (1, "calloc slinks %d", count);
2265 for (i = 0, link = page->links; link; ++i, link = link->next) {
2266 fz_rect rect;
2268 rect = link->rect;
2269 fz_transform_rect (&rect, &ctm);
2270 page->slinks[i].tag = SLINK;
2271 page->slinks[i].u.link = link;
2272 fz_round_rect (&page->slinks[i].bbox, &rect);
2274 for (j = 0; j < page->annotcount; ++j, ++i) {
2275 fz_rect rect;
2276 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2277 fz_transform_rect (&rect, &ctm);
2278 fz_round_rect (&page->slinks[i].bbox, &rect);
2280 page->slinks[i].tag = SANNOT;
2281 page->slinks[i].u.annot = page->annots[j].annot;
2283 qsort (page->slinks, count, slinksize, compareslinks);
2287 #pragma GCC diagnostic push
2288 #pragma GCC diagnostic ignored "-Wconversion"
2289 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2290 static void fmt_linkn (char *s, unsigned int u)
2292 unsigned int len; unsigned int q;
2293 unsigned int zma = 'z' - 'a' + 1;
2294 len = 1; q = u;
2295 while (q > zma - 1) { ++len; q /= zma; }
2296 if (s) {
2297 s += len;
2298 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2299 /* handles u == 0 */
2301 s[len] = 0;
2303 #pragma GCC diagnostic pop
2305 static void highlightslinks (struct page *page, int xoff, int yoff,
2306 int noff, char *targ, mlsize_t tlen, int hfsize)
2308 char buf[40];
2309 struct slink *slink;
2310 float x0, y0, x1, y1, w;
2312 ensureslinks (page);
2313 glColor3ub (0xc3, 0xb0, 0x91);
2314 for (int i = 0; i < page->slinkcount; ++i) {
2315 fmt_linkn (buf, i + noff);
2316 if (!tlen || !strncmp (targ, buf, tlen)) {
2317 slink = &page->slinks[i];
2319 x0 = slink->bbox.x0 + xoff - 5;
2320 y1 = slink->bbox.y0 + yoff - 5;
2321 y0 = y1 + 10 + hfsize;
2322 w = measure_string (state.face, hfsize, buf);
2323 x1 = x0 + w + 10;
2324 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2328 glEnable (GL_BLEND);
2329 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2330 glEnable (GL_TEXTURE_2D);
2331 glColor3ub (0, 0, 0);
2332 for (int i = 0; i < page->slinkcount; ++i) {
2333 fmt_linkn (buf, i + noff);
2334 if (!tlen || !strncmp (targ, buf, tlen)) {
2335 slink = &page->slinks[i];
2337 x0 = slink->bbox.x0 + xoff;
2338 y0 = slink->bbox.y0 + yoff + hfsize;
2339 draw_string (state.face, hfsize, x0, y0, buf);
2342 glDisable (GL_TEXTURE_2D);
2343 glDisable (GL_BLEND);
2346 static void uploadslice (struct tile *tile, struct slice *slice)
2348 int offset;
2349 struct slice *slice1;
2350 unsigned char *texdata;
2352 offset = 0;
2353 for (slice1 = tile->slices; slice != slice1; slice1++) {
2354 offset += slice1->h * tile->w * tile->pixmap->n;
2356 if (slice->texindex != -1 && slice->texindex < state.texcount
2357 && state.texowners[slice->texindex].slice == slice) {
2358 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2360 else {
2361 int subimage = 0;
2362 int texindex = state.texindex++ % state.texcount;
2364 if (state.texowners[texindex].w == tile->w) {
2365 if (state.texowners[texindex].h >= slice->h) {
2366 subimage = 1;
2368 else {
2369 state.texowners[texindex].h = slice->h;
2372 else {
2373 state.texowners[texindex].h = slice->h;
2376 state.texowners[texindex].w = tile->w;
2377 state.texowners[texindex].slice = slice;
2378 slice->texindex = texindex;
2380 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2381 #if TEXT_TYPE == GL_TEXTURE_2D
2382 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2383 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2384 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2385 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2386 #endif
2387 if (tile->pbo) {
2388 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2389 texdata = 0;
2391 else {
2392 texdata = tile->pixmap->samples;
2394 if (subimage) {
2395 glTexSubImage2D (TEXT_TYPE,
2399 tile->w,
2400 slice->h,
2401 state.texform,
2402 state.texty,
2403 texdata+offset
2406 else {
2407 glTexImage2D (TEXT_TYPE,
2409 state.texiform,
2410 tile->w,
2411 slice->h,
2413 state.texform,
2414 state.texty,
2415 texdata+offset
2418 if (tile->pbo) {
2419 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2424 CAMLprim void ml_begintiles (value unit_v)
2426 CAMLparam1 (unit_v);
2427 glEnable (TEXT_TYPE);
2428 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2429 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2430 CAMLreturn0;
2433 CAMLprim void ml_endtiles (value unit_v)
2435 CAMLparam1 (unit_v);
2436 glDisable (TEXT_TYPE);
2437 CAMLreturn0;
2440 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2442 CAMLparam2 (args_v, ptr_v);
2443 int dispx = Int_val (Field (args_v, 0));
2444 int dispy = Int_val (Field (args_v, 1));
2445 int dispw = Int_val (Field (args_v, 2));
2446 int disph = Int_val (Field (args_v, 3));
2447 int tilex = Int_val (Field (args_v, 4));
2448 int tiley = Int_val (Field (args_v, 5));
2449 char *s = String_val (ptr_v);
2450 struct tile *tile = parse_pointer (__func__, s);
2451 int slicey, firstslice;
2452 struct slice *slice;
2453 GLfloat *texcoords = state.texcoords;
2454 GLfloat *vertices = state.vertices;
2456 firstslice = tiley / tile->sliceheight;
2457 slice = &tile->slices[firstslice];
2458 slicey = tiley % tile->sliceheight;
2460 while (disph > 0) {
2461 int dh;
2463 dh = slice->h - slicey;
2464 dh = fz_mini (disph, dh);
2465 uploadslice (tile, slice);
2467 texcoords[0] = tilex; texcoords[1] = slicey;
2468 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2469 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2470 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2472 vertices[0] = dispx; vertices[1] = dispy;
2473 vertices[2] = dispx+dispw; vertices[3] = dispy;
2474 vertices[4] = dispx; vertices[5] = dispy+dh;
2475 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2477 #if TEXT_TYPE == GL_TEXTURE_2D
2478 for (int i = 0; i < 8; ++i) {
2479 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2481 #endif
2483 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2484 dispy += dh;
2485 disph -= dh;
2486 slice++;
2487 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2488 slicey = 0;
2490 CAMLreturn0;
2493 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2495 fz_matrix ctm, tm, pm;
2496 fz_point p1, p2, p3, p4;
2497 GLfloat *vertices = state.vertices;
2498 double *v = (double *) rects_v;
2500 xoff -= state.pagedims[page->pdimno].bounds.x0;
2501 yoff -= state.pagedims[page->pdimno].bounds.y0;
2502 fz_translate (&tm, xoff, yoff);
2503 pm = pagectm (page);
2504 fz_concat (&ctm, &pm, &tm);
2506 glEnable (GL_BLEND);
2507 glVertexPointer (2, GL_FLOAT, 0, vertices);
2509 glColor4dv (v);
2510 p1.x = (float) v[4];
2511 p1.y = (float) v[5];
2513 p2.x = (float) v[6];
2514 p2.y = (float) v[5];
2516 p3.x = (float) v[6];
2517 p3.y = (float) v[7];
2519 p4.x = (float) v[4];
2520 p4.y = (float) v[7];
2521 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2522 glDisable (GL_BLEND);
2525 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2526 value xoff_v, value yoff_v,
2527 value li_v)
2529 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2530 int xoff = Int_val (xoff_v);
2531 int yoff = Int_val (yoff_v);
2532 int noff = Int_val (Field (li_v, 0));
2533 char *targ = String_val (Field (li_v, 1));
2534 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2535 int hfsize = Int_val (Field (li_v, 2));
2536 char *s = String_val (ptr_v);
2537 int hlmask = Int_val (hlinks_v);
2538 struct page *page = parse_pointer (__func__, s);
2540 if (!page->fzpage) {
2541 /* deal with loadpage failed pages */
2542 goto done;
2545 if (trylock (__func__)) {
2546 noff = -1;
2547 goto done;
2550 ensureannots (page);
2551 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2552 if (hlmask & 2) {
2553 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2554 noff = page->slinkcount;
2556 if (page->tgen == state.gen) {
2557 showsel (page, xoff, yoff);
2559 unlock (__func__);
2561 done:
2562 CAMLreturn (Val_int (noff));
2565 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2566 value rects_v)
2568 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2569 int xoff = Int_val (xoff_v);
2570 int yoff = Int_val (yoff_v);
2571 char *s = String_val (ptr_v);
2572 struct page *page = parse_pointer (__func__, s);
2574 drawprect (page, xoff, yoff, rects_v);
2575 CAMLreturn0;
2578 static struct annot *getannot (struct page *page, int x, int y)
2580 fz_point p;
2581 fz_matrix ctm;
2582 const fz_matrix *tctm;
2583 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2585 if (!page->annots) return NULL;
2587 if (pdf) {
2588 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2589 tctm = &state.pagedims[page->pdimno].tctm;
2591 else {
2592 tctm = &fz_identity;
2595 p.x = x;
2596 p.y = y;
2598 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2599 fz_invert_matrix (&ctm, &ctm);
2600 fz_transform_point (&p, &ctm);
2602 if (pdf) {
2603 for (int i = 0; i < page->annotcount; ++i) {
2604 struct annot *a = &page->annots[i];
2605 fz_rect rect;
2607 fz_bound_annot (state.ctx, a->annot, &rect);
2608 if (p.x >= rect.x0 && p.x <= rect.x1) {
2609 if (p.y >= rect.y0 && p.y <= rect.y1)
2610 return a;
2614 return NULL;
2617 static fz_link *getlink (struct page *page, int x, int y)
2619 fz_point p;
2620 fz_matrix ctm;
2621 fz_link *link;
2623 ensureslinks (page);
2625 p.x = x;
2626 p.y = y;
2628 ctm = pagectm (page);
2629 fz_invert_matrix (&ctm, &ctm);
2630 fz_transform_point (&p, &ctm);
2632 for (link = page->links; link; link = link->next) {
2633 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2634 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2635 return link;
2639 return NULL;
2642 static void ensuretext (struct page *page)
2644 if (state.gen != page->tgen) {
2645 droptext (page);
2646 page->tgen = state.gen;
2648 if (!page->text) {
2649 fz_matrix ctm;
2650 fz_device *tdev;
2652 page->text = fz_new_stext_page (state.ctx,
2653 &state.pagedims[page->pdimno].mediabox);
2654 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2655 ctm = pagectm (page);
2656 fz_run_display_list (state.ctx, page->dlist,
2657 tdev, &ctm, &fz_infinite_rect, NULL);
2658 fz_close_device (state.ctx, tdev);
2659 fz_drop_device (state.ctx, tdev);
2663 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2665 CAMLparam2 (start_page_v, dir_v);
2666 CAMLlocal1 (ret_v);
2667 int i, dir = Int_val (dir_v);
2668 int start_page = Int_val (start_page_v);
2669 int end_page = dir > 0 ? state.pagecount : -1;
2670 pdf_document *pdf;
2672 fz_var (end_page);
2673 ret_v = Val_int (0);
2674 lock (__func__);
2675 pdf = pdf_specifics (state.ctx, state.doc);
2676 for (i = start_page + dir; i != end_page; i += dir) {
2677 int found;
2679 fz_var (found);
2680 if (pdf) {
2681 pdf_page *page = NULL;
2683 fz_var (page);
2684 fz_try (state.ctx) {
2685 page = pdf_load_page (state.ctx, pdf, i);
2686 found = !!page->links || !!page->annots;
2688 fz_catch (state.ctx) {
2689 found = 0;
2691 if (page) {
2692 fz_drop_page (state.ctx, &page->super);
2695 else {
2696 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2697 fz_link *link = fz_load_links (state.ctx, page);
2698 found = !!link;
2699 fz_drop_link (state.ctx, link);
2700 fz_drop_page (state.ctx, page);
2703 if (found) {
2704 ret_v = caml_alloc_small (1, 1);
2705 Field (ret_v, 0) = Val_int (i);
2706 goto unlock;
2709 unlock:
2710 unlock (__func__);
2711 CAMLreturn (ret_v);
2714 enum { dir_first, dir_last };
2715 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2717 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2719 CAMLparam2 (ptr_v, dir_v);
2720 CAMLlocal2 (ret_v, pos_v);
2721 struct page *page;
2722 int dirtag, i, slinkindex;
2723 struct slink *found = NULL ,*slink;
2724 char *s = String_val (ptr_v);
2726 page = parse_pointer (__func__, s);
2727 ret_v = Val_int (0);
2728 lock (__func__);
2729 ensureslinks (page);
2731 if (Is_block (dir_v)) {
2732 dirtag = Tag_val (dir_v);
2733 switch (dirtag) {
2734 case dir_first_visible:
2736 int x0, y0, dir, first_index, last_index;
2738 pos_v = Field (dir_v, 0);
2739 x0 = Int_val (Field (pos_v, 0));
2740 y0 = Int_val (Field (pos_v, 1));
2741 dir = Int_val (Field (pos_v, 2));
2743 if (dir >= 0) {
2744 dir = 1;
2745 first_index = 0;
2746 last_index = page->slinkcount;
2748 else {
2749 first_index = page->slinkcount - 1;
2750 last_index = -1;
2753 for (i = first_index; i != last_index; i += dir) {
2754 slink = &page->slinks[i];
2755 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2756 found = slink;
2757 break;
2761 break;
2763 case dir_left:
2764 slinkindex = Int_val (Field (dir_v, 0));
2765 found = &page->slinks[slinkindex];
2766 for (i = slinkindex - 1; i >= 0; --i) {
2767 slink = &page->slinks[i];
2768 if (slink->bbox.x0 < found->bbox.x0) {
2769 found = slink;
2770 break;
2773 break;
2775 case dir_right:
2776 slinkindex = Int_val (Field (dir_v, 0));
2777 found = &page->slinks[slinkindex];
2778 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2779 slink = &page->slinks[i];
2780 if (slink->bbox.x0 > found->bbox.x0) {
2781 found = slink;
2782 break;
2785 break;
2787 case dir_down:
2788 slinkindex = Int_val (Field (dir_v, 0));
2789 found = &page->slinks[slinkindex];
2790 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2791 slink = &page->slinks[i];
2792 if (slink->bbox.y0 >= found->bbox.y0) {
2793 found = slink;
2794 break;
2797 break;
2799 case dir_up:
2800 slinkindex = Int_val (Field (dir_v, 0));
2801 found = &page->slinks[slinkindex];
2802 for (i = slinkindex - 1; i >= 0; --i) {
2803 slink = &page->slinks[i];
2804 if (slink->bbox.y0 <= found->bbox.y0) {
2805 found = slink;
2806 break;
2809 break;
2812 else {
2813 dirtag = Int_val (dir_v);
2814 switch (dirtag) {
2815 case dir_first:
2816 found = page->slinks;
2817 break;
2819 case dir_last:
2820 if (page->slinks) {
2821 found = page->slinks + (page->slinkcount - 1);
2823 break;
2826 if (found) {
2827 ret_v = caml_alloc_small (2, 1);
2828 Field (ret_v, 0) = Val_int (found - page->slinks);
2831 unlock (__func__);
2832 CAMLreturn (ret_v);
2835 enum { uuri, utext, uannot };
2837 CAMLprim value ml_getlink (value ptr_v, value n_v)
2839 CAMLparam2 (ptr_v, n_v);
2840 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2841 fz_link *link;
2842 struct page *page;
2843 char *s = String_val (ptr_v);
2844 struct slink *slink;
2846 ret_v = Val_int (0);
2847 page = parse_pointer (__func__, s);
2849 lock (__func__);
2850 ensureslinks (page);
2851 slink = &page->slinks[Int_val (n_v)];
2852 if (slink->tag == SLINK) {
2853 link = slink->u.link;
2854 str_v = caml_copy_string (link->uri);
2855 ret_v = caml_alloc_small (1, uuri);
2856 Field (ret_v, 0) = str_v;
2858 else {
2859 ret_v = caml_alloc_small (1, uannot);
2860 tup_v = caml_alloc_tuple (2);
2861 Field (ret_v, 0) = tup_v;
2862 Field (tup_v, 0) = ptr_v;
2863 Field (tup_v, 1) = n_v;
2865 unlock (__func__);
2867 CAMLreturn (ret_v);
2870 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2872 CAMLparam2 (ptr_v, n_v);
2873 CAMLlocal1 (ret_v);
2874 pdf_document *pdf;
2875 char *contents = NULL;
2877 lock (__func__);
2878 pdf = pdf_specifics (state.ctx, state.doc);
2879 if (pdf) {
2880 char *s = String_val (ptr_v);
2881 struct page *page;
2882 struct slink *slink;
2884 page = parse_pointer (__func__, s);
2885 slink = &page->slinks[Int_val (n_v)];
2886 contents = pdf_copy_annot_contents (state.ctx,
2887 (pdf_annot *) slink->u.annot);
2889 unlock (__func__);
2890 if (contents) {
2891 ret_v = caml_copy_string (contents);
2892 fz_free (state.ctx, contents);
2894 else {
2895 ret_v = caml_copy_string ("");
2897 CAMLreturn (ret_v);
2900 CAMLprim value ml_getlinkcount (value ptr_v)
2902 CAMLparam1 (ptr_v);
2903 struct page *page;
2904 char *s = String_val (ptr_v);
2906 page = parse_pointer (__func__, s);
2907 CAMLreturn (Val_int (page->slinkcount));
2910 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2912 CAMLparam2 (ptr_v, n_v);
2913 CAMLlocal1 (ret_v);
2914 struct page *page;
2915 struct slink *slink;
2916 char *s = String_val (ptr_v);
2918 page = parse_pointer (__func__, s);
2919 ret_v = caml_alloc_tuple (4);
2920 lock (__func__);
2921 ensureslinks (page);
2923 slink = &page->slinks[Int_val (n_v)];
2924 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2925 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2926 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2927 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2928 unlock (__func__);
2929 CAMLreturn (ret_v);
2932 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2934 CAMLparam3 (ptr_v, x_v, y_v);
2935 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2936 fz_link *link;
2937 struct annot *annot;
2938 struct page *page;
2939 char *ptr = String_val (ptr_v);
2940 int x = Int_val (x_v), y = Int_val (y_v);
2941 struct pagedim *pdim;
2943 ret_v = Val_int (0);
2944 if (trylock (__func__)) {
2945 goto done;
2948 page = parse_pointer (__func__, ptr);
2949 pdim = &state.pagedims[page->pdimno];
2950 x += pdim->bounds.x0;
2951 y += pdim->bounds.y0;
2954 annot = getannot (page, x, y);
2955 if (annot) {
2956 int i, n = -1;
2958 ensureslinks (page);
2959 for (i = 0; i < page->slinkcount; ++i) {
2960 if (page->slinks[i].tag == SANNOT
2961 && page->slinks[i].u.annot == annot->annot) {
2962 n = i;
2963 break;
2966 ret_v = caml_alloc_small (1, uannot);
2967 tup_v = caml_alloc_tuple (2);
2968 Field (ret_v, 0) = tup_v;
2969 Field (tup_v, 0) = ptr_v;
2970 Field (tup_v, 1) = Val_int (n);
2971 goto unlock;
2975 link = getlink (page, x, y);
2976 if (link) {
2977 str_v = caml_copy_string (link->uri);
2978 ret_v = caml_alloc_small (1, uuri);
2979 Field (ret_v, 0) = str_v;
2981 else {
2982 fz_rect *b;
2983 fz_stext_block *block;
2985 ensuretext (page);
2987 for (block = page->text->first_block; block; block = block->next) {
2988 fz_stext_line *line;
2990 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2991 b = &block->bbox;
2992 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2993 continue;
2995 for (line = block->u.t.first_line; line; line = line->next) {
2996 fz_stext_char *ch;
2998 b = &line->bbox;
2999 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3000 continue;
3002 for (ch = line->first_char; ch; ch = ch->next) {
3003 b = &ch->bbox;
3005 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3006 const char *n2 = fz_font_name (state.ctx, ch->font);
3007 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3008 ch->font);
3010 if (!n2) n2 = "<unknown font>";
3012 if (face && face->family_name) {
3013 char *s;
3014 char *n1 = face->family_name;
3015 size_t l1 = strlen (n1);
3016 size_t l2 = strlen (n2);
3018 if (l1 != l2 || memcmp (n1, n2, l1)) {
3019 s = malloc (l1 + l2 + 2);
3020 if (s) {
3021 memcpy (s, n2, l2);
3022 s[l2] = '=';
3023 memcpy (s + l2 + 1, n1, l1 + 1);
3024 str_v = caml_copy_string (s);
3025 free (s);
3029 if (str_v == Val_unit) {
3030 str_v = caml_copy_string (n2);
3032 ret_v = caml_alloc_small (1, utext);
3033 Field (ret_v, 0) = str_v;
3034 goto unlock;
3040 unlock:
3041 unlock (__func__);
3043 done:
3044 CAMLreturn (ret_v);
3047 enum { mark_page, mark_block, mark_line, mark_word };
3049 static int uninteresting (int c)
3051 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3052 || ispunct (c);
3055 CAMLprim void ml_clearmark (value ptr_v)
3057 CAMLparam1 (ptr_v);
3058 char *s = String_val (ptr_v);
3059 struct page *page;
3061 if (trylock (__func__)) {
3062 goto done;
3065 page = parse_pointer (__func__, s);
3066 page->fmark.ch = NULL;
3067 page->lmark.ch = NULL;
3069 unlock (__func__);
3070 done:
3071 CAMLreturn0;
3074 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3076 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3077 CAMLlocal1 (ret_v);
3078 fz_rect *b;
3079 struct page *page;
3080 fz_stext_line *line;
3081 fz_stext_block *block;
3082 struct pagedim *pdim;
3083 int mark = Int_val (mark_v);
3084 char *s = String_val (ptr_v);
3085 int x = Int_val (x_v), y = Int_val (y_v);
3087 ret_v = Val_bool (0);
3088 if (trylock (__func__)) {
3089 goto done;
3092 page = parse_pointer (__func__, s);
3093 pdim = &state.pagedims[page->pdimno];
3095 ensuretext (page);
3097 if (mark == mark_page) {
3098 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3099 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3100 ret_v = Val_bool (1);
3101 goto unlock;
3104 x += pdim->bounds.x0;
3105 y += pdim->bounds.y0;
3107 for (block = page->text->first_block; block; block = block->next) {
3108 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3109 b = &block->bbox;
3110 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3111 continue;
3113 if (mark == mark_block) {
3114 page->fmark.ch = block->u.t.first_line->first_char;
3115 page->lmark.ch = block->u.t.last_line->last_char;
3116 ret_v = Val_bool (1);
3117 goto unlock;
3120 for (line = block->u.t.first_line; line; line = line->next) {
3121 fz_stext_char *ch;
3123 b = &line->bbox;
3124 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3125 continue;
3127 if (mark == mark_line) {
3128 page->fmark.ch = line->first_char;
3129 page->lmark.ch = line->last_char;
3130 ret_v = Val_bool (1);
3131 goto unlock;
3134 for (ch = line->first_char; ch; ch = ch->next) {
3135 fz_stext_char *ch2, *first = NULL, *last = NULL;
3136 b = &ch->bbox;
3137 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3138 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3139 if (uninteresting (ch2->c)) first = NULL;
3140 else if (!first) first = ch2;
3142 for (ch2 = ch; ch2; ch2 = ch2->next) {
3143 if (uninteresting (ch2->c)) break;
3144 last = ch2;
3147 page->fmark.ch = first;
3148 page->lmark.ch = last;
3149 ret_v = Val_bool (1);
3150 goto unlock;
3155 unlock:
3156 if (!Bool_val (ret_v)) {
3157 page->fmark.ch = NULL;
3158 page->lmark.ch = NULL;
3160 unlock (__func__);
3162 done:
3163 CAMLreturn (ret_v);
3166 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3168 CAMLparam3 (ptr_v, x_v, y_v);
3169 CAMLlocal2 (ret_v, res_v);
3170 fz_rect *b = NULL;
3171 struct page *page;
3172 struct pagedim *pdim;
3173 fz_stext_block *block;
3174 char *s = String_val (ptr_v);
3175 int x = Int_val (x_v), y = Int_val (y_v);
3177 ret_v = Val_int (0);
3178 if (trylock (__func__)) {
3179 goto done;
3182 page = parse_pointer (__func__, s);
3183 pdim = &state.pagedims[page->pdimno];
3184 x += pdim->bounds.x0;
3185 y += pdim->bounds.y0;
3187 ensuretext (page);
3189 for (block = page->text->first_block; block; block = block->next) {
3190 switch (block->type) {
3191 case FZ_STEXT_BLOCK_TEXT:
3192 b = &block->bbox;
3193 break;
3195 case FZ_STEXT_BLOCK_IMAGE:
3196 b = &block->bbox;
3197 break;
3199 default:
3200 continue;
3203 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3204 break;
3205 b = NULL;
3207 if (b) {
3208 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3209 ret_v = caml_alloc_small (1, 1);
3210 Store_double_field (res_v, 0, (double) b->x0);
3211 Store_double_field (res_v, 1, (double) b->x1);
3212 Store_double_field (res_v, 2, (double) b->y0);
3213 Store_double_field (res_v, 3, (double) b->y1);
3214 Field (ret_v, 0) = res_v;
3216 unlock (__func__);
3218 done:
3219 CAMLreturn (ret_v);
3222 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3224 CAMLparam2 (ptr_v, rect_v);
3225 fz_rect b;
3226 struct page *page;
3227 struct pagedim *pdim;
3228 char *s = String_val (ptr_v);
3229 int x0, x1, y0, y1;
3230 fz_stext_char *ch;
3231 fz_stext_line *line;
3232 fz_stext_block *block;
3233 fz_stext_char *fc, *lc;
3235 if (trylock (__func__)) {
3236 goto done;
3239 page = parse_pointer (__func__, s);
3240 ensuretext (page);
3242 pdim = &state.pagedims[page->pdimno];
3243 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3244 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3245 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3246 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3248 if (y0 > y1) {
3249 int t = y0;
3250 y0 = y1;
3251 y1 = t;
3252 x0 = x1;
3253 x1 = t;
3256 fc = page->fmark.ch;
3257 lc = page->lmark.ch;
3259 for (block = page->text->first_block; block; block = block->next) {
3260 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3261 for (line = block->u.t.first_line; line; line = line->next) {
3262 for (ch = line->first_char; ch; ch = ch->next) {
3263 b = ch->bbox;
3264 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3265 fc = ch;
3267 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3268 lc = ch;
3273 if (x1 < x0 && fc == lc) {
3274 fz_stext_char *t;
3276 t = fc;
3277 fc = lc;
3278 lc = t;
3281 page->fmark.ch = fc;
3282 page->lmark.ch = lc;
3284 unlock (__func__);
3286 done:
3287 CAMLreturn0;
3290 static int pipechar (FILE *f, fz_stext_char *ch)
3292 char buf[4];
3293 int len;
3294 size_t ret;
3296 len = fz_runetochar (buf, ch->c);
3297 ret = fwrite (buf, len, 1, f);
3298 if (ret != 1) {
3299 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3300 len, ret, errno, strerror (errno));
3301 return -1;
3303 return 0;
3306 CAMLprim value ml_spawn (value command_v, value fds_v)
3308 CAMLparam2 (command_v, fds_v);
3309 CAMLlocal2 (l_v, tup_v);
3310 int ret, ret1;
3311 pid_t pid = (pid_t) -1;
3312 char *msg = NULL;
3313 value earg_v = Nothing;
3314 posix_spawnattr_t attr;
3315 posix_spawn_file_actions_t fa;
3316 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3318 argv[2] = String_val (command_v);
3320 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3321 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3324 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3325 msg = "posix_spawnattr_init";
3326 goto fail1;
3329 #ifdef POSIX_SPAWN_USEVFORK
3330 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3331 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3332 goto fail;
3334 #endif
3336 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3337 int fd1, fd2;
3339 tup_v = Field (l_v, 0);
3340 fd1 = Int_val (Field (tup_v, 0));
3341 fd2 = Int_val (Field (tup_v, 1));
3342 if (fd2 < 0) {
3343 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3344 msg = "posix_spawn_file_actions_addclose";
3345 earg_v = tup_v;
3346 goto fail;
3349 else {
3350 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3351 msg = "posix_spawn_file_actions_adddup2";
3352 earg_v = tup_v;
3353 goto fail;
3358 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3359 msg = "posix_spawn";
3360 goto fail;
3363 fail:
3364 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3365 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3368 fail1:
3369 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3370 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3371 ret1, strerror (ret1));
3374 if (msg)
3375 unix_error (ret, msg, earg_v);
3377 CAMLreturn (Val_int (pid));
3380 CAMLprim value ml_hassel (value ptr_v)
3382 CAMLparam1 (ptr_v);
3383 CAMLlocal1 (ret_v);
3384 struct page *page;
3385 char *s = String_val (ptr_v);
3387 ret_v = Val_bool (0);
3388 if (trylock (__func__)) {
3389 goto done;
3392 page = parse_pointer (__func__, s);
3393 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3394 unlock (__func__);
3395 done:
3396 CAMLreturn (ret_v);
3399 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3401 CAMLparam2 (fd_v, ptr_v);
3402 FILE *f;
3403 int seen = 0;
3404 struct page *page;
3405 fz_stext_line *line;
3406 fz_stext_block *block;
3407 int fd = Int_val (fd_v);
3408 char *s = String_val (ptr_v);
3410 if (trylock (__func__)) {
3411 goto done;
3414 page = parse_pointer (__func__, s);
3416 if (!page->fmark.ch || !page->lmark.ch) {
3417 printd ("emsg nothing to copy on page %d", page->pageno);
3418 goto unlock;
3421 f = fdopen (fd, "w");
3422 if (!f) {
3423 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3424 fd, errno, strerror (errno));
3425 f = stdout;
3428 for (block = page->text->first_block; block; block = block->next) {
3429 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3430 for (line = block->u.t.first_line; line; line = line->next) {
3431 fz_stext_char *ch;
3432 for (ch = line->first_char; ch; ch = ch->next) {
3433 if (seen || ch == page->fmark.ch) {
3434 do {
3435 pipechar (f, ch);
3436 if (ch == page->lmark.ch) goto close;
3437 } while ((ch = ch->next));
3438 seen = 1;
3439 break;
3442 if (seen) fputc ('\n', f);
3445 close:
3446 if (f != stdout) {
3447 int ret = fclose (f);
3448 fd = -1;
3449 if (ret == -1) {
3450 if (errno != ECHILD) {
3451 printd ("emsg failed to close sel pipe: %d:%s",
3452 errno, strerror (errno));
3456 unlock:
3457 unlock (__func__);
3459 done:
3460 if (fd >= 0) {
3461 if (close (fd)) {
3462 printd ("emsg failed to close sel pipe: %d:%s",
3463 errno, strerror (errno));
3466 CAMLreturn0;
3469 CAMLprim value ml_getpdimrect (value pagedimno_v)
3471 CAMLparam1 (pagedimno_v);
3472 CAMLlocal1 (ret_v);
3473 int pagedimno = Int_val (pagedimno_v);
3474 fz_rect box;
3476 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3477 if (trylock (__func__)) {
3478 box = fz_empty_rect;
3480 else {
3481 box = state.pagedims[pagedimno].mediabox;
3482 unlock (__func__);
3485 Store_double_field (ret_v, 0, (double) box.x0);
3486 Store_double_field (ret_v, 1, (double) box.x1);
3487 Store_double_field (ret_v, 2, (double) box.y0);
3488 Store_double_field (ret_v, 3, (double) box.y1);
3490 CAMLreturn (ret_v);
3493 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3494 value dw_v, value cols_v)
3496 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3497 CAMLlocal1 (ret_v);
3498 int i;
3499 float zoom = -1.;
3500 float maxh = 0.0;
3501 struct pagedim *p;
3502 float winw = Int_val (winw_v);
3503 float winh = Int_val (winh_v);
3504 float dw = Int_val (dw_v);
3505 float cols = Int_val (cols_v);
3506 float pw = 1.0, ph = 1.0;
3508 if (trylock (__func__)) {
3509 goto done;
3512 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3513 float w = p->pagebox.x1 / cols;
3514 float h = p->pagebox.y1;
3515 if (h > maxh) {
3516 maxh = h;
3517 ph = h;
3518 if (state.fitmodel != FitProportional) pw = w;
3520 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3523 zoom = (((winh / ph) * pw) + dw) / winw;
3524 unlock (__func__);
3525 done:
3526 ret_v = caml_copy_double ((double) zoom);
3527 CAMLreturn (ret_v);
3530 CAMLprim value ml_getmaxw (value unit_v)
3532 CAMLparam1 (unit_v);
3533 CAMLlocal1 (ret_v);
3534 int i;
3535 float maxw = -1.;
3536 struct pagedim *p;
3538 if (trylock (__func__)) {
3539 goto done;
3542 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3543 float w = p->pagebox.x1;
3544 maxw = fz_max (maxw, w);
3547 unlock (__func__);
3548 done:
3549 ret_v = caml_copy_double ((double) maxw);
3550 CAMLreturn (ret_v);
3553 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3555 CAMLparam4 (pt_v, x_v, y_v, string_v);
3556 CAMLlocal1 (ret_v);
3557 int pt = Int_val(pt_v);
3558 int x = Int_val (x_v);
3559 int y = Int_val (y_v);
3560 double w;
3562 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3563 ret_v = caml_copy_double (w);
3564 CAMLreturn (ret_v);
3567 CAMLprim value ml_measure_string (value pt_v, value string_v)
3569 CAMLparam2 (pt_v, string_v);
3570 CAMLlocal1 (ret_v);
3571 int pt = Int_val (pt_v);
3572 double w;
3574 w = (double) measure_string (state.face, pt, String_val (string_v));
3575 ret_v = caml_copy_double (w);
3576 CAMLreturn (ret_v);
3579 CAMLprim value ml_getpagebox (value opaque_v)
3581 CAMLparam1 (opaque_v);
3582 CAMLlocal1 (ret_v);
3583 fz_rect rect;
3584 fz_irect bbox;
3585 fz_matrix ctm;
3586 fz_device *dev;
3587 char *s = String_val (opaque_v);
3588 struct page *page = parse_pointer (__func__, s);
3590 ret_v = caml_alloc_tuple (4);
3591 dev = fz_new_bbox_device (state.ctx, &rect);
3593 ctm = pagectm (page);
3594 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3596 fz_close_device (state.ctx, dev);
3597 fz_drop_device (state.ctx, dev);
3598 fz_round_rect (&bbox, &rect);
3599 Field (ret_v, 0) = Val_int (bbox.x0);
3600 Field (ret_v, 1) = Val_int (bbox.y0);
3601 Field (ret_v, 2) = Val_int (bbox.x1);
3602 Field (ret_v, 3) = Val_int (bbox.y1);
3604 CAMLreturn (ret_v);
3607 CAMLprim void ml_setaalevel (value level_v)
3609 CAMLparam1 (level_v);
3611 state.aalevel = Int_val (level_v);
3612 CAMLreturn0;
3615 #ifndef __COCOA__
3616 #pragma GCC diagnostic push
3617 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3618 #include <X11/Xlib.h>
3619 #include <X11/cursorfont.h>
3620 #pragma GCC diagnostic pop
3622 #ifdef USE_EGL
3623 #include <EGL/egl.h>
3624 #else
3625 #include <GL/glx.h>
3626 #endif
3628 static const int shapes[] = {
3629 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3632 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3634 static struct {
3635 Window wid;
3636 Display *dpy;
3637 #ifdef USE_EGL
3638 EGLContext ctx;
3639 EGLConfig conf;
3640 EGLSurface win;
3641 EGLDisplay *edpy;
3642 #else
3643 GLXContext ctx;
3644 #endif
3645 XVisualInfo *visual;
3646 Cursor curs[CURS_COUNT];
3647 } glx;
3650 static void initcurs (void)
3652 for (size_t n = 0; n < CURS_COUNT; ++n) {
3653 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3657 #ifdef USE_EGL
3658 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3660 CAMLparam3 (display_v, wid_v, screen_v);
3661 int major, minor;
3662 int num_conf;
3663 EGLint visid;
3664 EGLint attribs[] = {
3665 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3666 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3667 EGL_NONE
3669 EGLConfig conf;
3671 glx.dpy = XOpenDisplay (String_val (display_v));
3672 if (!glx.dpy) {
3673 caml_failwith ("XOpenDisplay");
3676 eglBindAPI (EGL_OPENGL_API);
3678 glx.edpy = eglGetDisplay (glx.dpy);
3679 if (glx.edpy == EGL_NO_DISPLAY) {
3680 caml_failwith ("eglGetDisplay");
3683 if (!eglInitialize (glx.edpy, &major, &minor)) {
3684 caml_failwith ("eglInitialize");
3687 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3688 !num_conf) {
3689 caml_failwith ("eglChooseConfig");
3692 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3693 caml_failwith ("eglGetConfigAttrib");
3696 glx.conf = conf;
3697 initcurs ();
3699 glx.wid = Int_val (wid_v);
3700 CAMLreturn (Val_int (visid));
3703 CAMLprim void ml_glxcompleteinit (value unit_v)
3705 CAMLparam1 (unit_v);
3707 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3708 if (!glx.ctx) {
3709 caml_failwith ("eglCreateContext");
3712 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3713 glx.wid, NULL);
3714 if (glx.win == EGL_NO_SURFACE) {
3715 caml_failwith ("eglCreateWindowSurface");
3718 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3719 glx.ctx = NULL;
3720 caml_failwith ("eglMakeCurrent");
3722 CAMLreturn0;
3724 #else
3725 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3727 CAMLparam3 (display_v, wid_v, screen_v);
3729 glx.dpy = XOpenDisplay (String_val (display_v));
3730 if (!glx.dpy) {
3731 caml_failwith ("XOpenDisplay");
3734 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3735 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3736 if (!glx.visual) {
3737 XCloseDisplay (glx.dpy);
3738 caml_failwith ("glXChooseVisual");
3741 initcurs ();
3743 glx.wid = Int_val (wid_v);
3744 CAMLreturn (Val_int (glx.visual->visualid));
3747 CAMLprim void ml_glxcompleteinit (value unit_v)
3749 CAMLparam1 (unit_v);
3751 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3752 if (!glx.ctx) {
3753 caml_failwith ("glXCreateContext");
3756 XFree (glx.visual);
3757 glx.visual = NULL;
3759 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3760 glXDestroyContext (glx.dpy, glx.ctx);
3761 glx.ctx = NULL;
3762 caml_failwith ("glXMakeCurrent");
3764 CAMLreturn0;
3766 #endif
3768 CAMLprim void ml_setcursor (value cursor_v)
3770 CAMLparam1 (cursor_v);
3771 size_t cursn = Int_val (cursor_v);
3773 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3774 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3775 XFlush (glx.dpy);
3776 CAMLreturn0;
3779 CAMLprim void ml_swapb (value unit_v)
3781 CAMLparam1 (unit_v);
3782 #ifdef USE_EGL
3783 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3784 caml_failwith ("eglSwapBuffers");
3786 #else
3787 glXSwapBuffers (glx.dpy, glx.wid);
3788 #endif
3789 CAMLreturn0;
3792 #pragma GCC diagnostic push
3793 #ifdef __clang__
3794 #pragma GCC diagnostic ignored "-Wmissing-variable-declarations"
3795 #endif
3796 #include "keysym2ucs.c"
3797 #pragma GCC diagnostic pop
3799 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3801 CAMLparam1 (keysym_v);
3802 CAMLlocal1 (str_v);
3803 KeySym keysym = Int_val (keysym_v);
3804 Rune rune;
3805 int len;
3806 char buf[5];
3808 rune = (Rune) keysym2ucs (keysym);
3809 len = fz_runetochar (buf, rune);
3810 buf[len] = 0;
3811 str_v = caml_copy_string (buf);
3812 CAMLreturn (str_v);
3814 #else
3815 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3817 CAMLparam1 (keysym_v);
3818 CAMLlocal1 (str_v);
3819 long ucs_v = Long_val (keysym_v);
3820 int len;
3821 char buf[5];
3823 len = fz_runetochar (buf, ucs_v);
3824 buf[len] = 0;
3825 str_v = caml_copy_string (buf);
3826 CAMLreturn (str_v);
3828 #endif
3830 enum { piunknown, pilinux, piosx, pisun, pibsd };
3832 CAMLprim value ml_platform (value unit_v)
3834 CAMLparam1 (unit_v);
3835 CAMLlocal2 (tup_v, arr_v);
3836 int platid = piunknown;
3837 struct utsname buf;
3839 #if defined __linux__
3840 platid = pilinux;
3841 #elif defined __DragonFly__ || defined __FreeBSD__
3842 || defined __OpenBSD__ || defined __NetBSD__
3843 platid = pibsd;
3844 #elif defined __sun__
3845 platid = pisun;
3846 #elif defined __APPLE__
3847 platid = piosx;
3848 #endif
3849 if (uname (&buf)) err (1, "uname");
3851 tup_v = caml_alloc_tuple (2);
3853 char const *sar[] = {
3854 buf.sysname,
3855 buf.release,
3856 buf.version,
3857 buf.machine,
3858 NULL
3860 arr_v = caml_copy_string_array (sar);
3862 Field (tup_v, 0) = Val_int (platid);
3863 Field (tup_v, 1) = arr_v;
3864 CAMLreturn (tup_v);
3867 CAMLprim void ml_cloexec (value fd_v)
3869 CAMLparam1 (fd_v);
3870 int fd = Int_val (fd_v);
3872 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3873 uerror ("fcntl", Nothing);
3875 CAMLreturn0;
3878 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3880 CAMLparam2 (w_v, h_v);
3881 CAMLlocal1 (ret_v);
3882 struct bo *pbo;
3883 int w = Int_val (w_v);
3884 int h = Int_val (h_v);
3885 int cs = Int_val (cs_v);
3887 if (state.bo_usable) {
3888 pbo = calloc (sizeof (*pbo), 1);
3889 if (!pbo) {
3890 err (1, "calloc pbo");
3893 switch (cs) {
3894 case 0:
3895 case 1:
3896 pbo->size = w*h*4;
3897 break;
3898 case 2:
3899 pbo->size = w*h*2;
3900 break;
3901 default:
3902 errx (1, "%s: invalid colorspace %d", __func__, cs);
3905 state.glGenBuffersARB (1, &pbo->id);
3906 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3907 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3908 NULL, GL_STREAM_DRAW);
3909 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3910 GL_READ_WRITE);
3911 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3912 if (!pbo->ptr) {
3913 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3914 state.glDeleteBuffersARB (1, &pbo->id);
3915 free (pbo);
3916 ret_v = caml_copy_string ("0");
3918 else {
3919 int res;
3920 char *s;
3922 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3923 if (res < 0) {
3924 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3926 s = malloc (res+1);
3927 if (!s) {
3928 err (1, "malloc %d bytes failed", res+1);
3930 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3931 if (res < 0) {
3932 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3934 ret_v = caml_copy_string (s);
3935 free (s);
3938 else {
3939 ret_v = caml_copy_string ("0");
3941 CAMLreturn (ret_v);
3944 CAMLprim void ml_freepbo (value s_v)
3946 CAMLparam1 (s_v);
3947 char *s = String_val (s_v);
3948 struct tile *tile = parse_pointer (__func__, s);
3950 if (tile->pbo) {
3951 state.glDeleteBuffersARB (1, &tile->pbo->id);
3952 tile->pbo->id = -1;
3953 tile->pbo->ptr = NULL;
3954 tile->pbo->size = -1;
3956 CAMLreturn0;
3959 CAMLprim void ml_unmappbo (value s_v)
3961 CAMLparam1 (s_v);
3962 char *s = String_val (s_v);
3963 struct tile *tile = parse_pointer (__func__, s);
3965 if (tile->pbo) {
3966 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3967 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3968 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3970 tile->pbo->ptr = NULL;
3971 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3973 CAMLreturn0;
3976 static void setuppbo (void)
3978 #ifdef __COCOA__
3979 static CFBundleRef framework = NULL;
3980 if (framework == NULL)
3981 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3982 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3983 #else
3984 #ifdef USE_EGL
3985 #define GGPA(n) (*(void (**) (void)) &state.n = eglGetProcAddress (#n))
3986 #else
3987 #define GGPA(n) (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
3988 #endif
3989 state.bo_usable = GGPA (glBindBufferARB)
3990 && GGPA (glUnmapBufferARB)
3991 && GGPA (glMapBufferARB)
3992 && GGPA (glBufferDataARB)
3993 && GGPA (glGenBuffersARB)
3994 && GGPA (glDeleteBuffersARB);
3995 #endif
3996 #undef GGPA
3999 CAMLprim value ml_bo_usable (value unit_v)
4001 CAMLparam1 (unit_v);
4002 CAMLreturn (Val_bool (state.bo_usable));
4005 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4007 CAMLparam3 (ptr_v, x_v, y_v);
4008 CAMLlocal2 (ret_v, tup_v);
4009 struct page *page;
4010 char *s = String_val (ptr_v);
4011 int x = Int_val (x_v), y = Int_val (y_v);
4012 struct pagedim *pdim;
4013 fz_point p;
4014 fz_matrix ctm;
4016 page = parse_pointer (__func__, s);
4017 pdim = &state.pagedims[page->pdimno];
4019 ret_v = Val_int (0);
4020 if (trylock (__func__)) {
4021 goto done;
4024 if (pdf_specifics (state.ctx, state.doc)) {
4025 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4026 ctm = state.pagedims[page->pdimno].tctm;
4028 else {
4029 ctm = fz_identity;
4031 p.x = x + pdim->bounds.x0;
4032 p.y = y + pdim->bounds.y0;
4034 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4035 fz_invert_matrix (&ctm, &ctm);
4036 fz_transform_point (&p, &ctm);
4038 tup_v = caml_alloc_tuple (2);
4039 ret_v = caml_alloc_small (1, 1);
4040 Field (tup_v, 0) = Val_int (p.x);
4041 Field (tup_v, 1) = Val_int (p.y);
4042 Field (ret_v, 0) = tup_v;
4044 unlock (__func__);
4045 done:
4046 CAMLreturn (ret_v);
4049 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4050 value x_v, value y_v)
4052 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4053 CAMLlocal1 (ret_v);
4054 struct page *page;
4055 char *s = String_val (ptr_v);
4056 int pageno = Int_val (pageno_v);
4057 int pdimno = Int_val (pdimno_v);
4058 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
4059 struct pagedim *pdim;
4060 fz_point p;
4061 fz_matrix ctm;
4063 ret_v = Val_int (0);
4064 lock (__func__);
4066 if (!*s) {
4067 page = loadpage (pageno, pdimno);
4069 else {
4070 page = parse_pointer (__func__, s);
4072 pdim = &state.pagedims[pdimno];
4074 if (pdf_specifics (state.ctx, state.doc)) {
4075 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4076 ctm = state.pagedims[page->pdimno].tctm;
4078 else {
4079 ctm = fz_identity;
4081 p.x = x + pdim->bounds.x0;
4082 p.y = y + pdim->bounds.y0;
4084 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4085 fz_transform_point (&p, &ctm);
4087 ret_v = caml_alloc_tuple (2);
4088 Field (ret_v, 0) = caml_copy_double ((double) p.x);
4089 Field (ret_v, 1) = caml_copy_double ((double) p.y);
4091 if (!*s) {
4092 freepage (page);
4094 unlock (__func__);
4095 CAMLreturn (ret_v);
4098 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4099 value contents_v)
4101 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4102 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4104 if (pdf) {
4105 pdf_annot *annot;
4106 struct page *page;
4107 fz_point p;
4108 char *s = String_val (ptr_v);
4110 page = parse_pointer (__func__, s);
4111 annot = pdf_create_annot (state.ctx,
4112 pdf_page_from_fz_page (state.ctx,
4113 page->fzpage),
4114 PDF_ANNOT_TEXT);
4115 p.x = Int_val (x_v);
4116 p.y = Int_val (y_v);
4117 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4118 pdf_set_text_annot_position (state.ctx, annot, p);
4119 state.dirty = 1;
4121 CAMLreturn0;
4124 CAMLprim void ml_delannot (value ptr_v, value n_v)
4126 CAMLparam2 (ptr_v, n_v);
4127 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4129 if (pdf) {
4130 struct page *page;
4131 char *s = String_val (ptr_v);
4132 struct slink *slink;
4134 page = parse_pointer (__func__, s);
4135 slink = &page->slinks[Int_val (n_v)];
4136 pdf_delete_annot (state.ctx,
4137 pdf_page_from_fz_page (state.ctx, page->fzpage),
4138 (pdf_annot *) slink->u.annot);
4139 state.dirty = 1;
4141 CAMLreturn0;
4144 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4146 CAMLparam3 (ptr_v, n_v, str_v);
4147 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4149 if (pdf) {
4150 struct page *page;
4151 char *s = String_val (ptr_v);
4152 struct slink *slink;
4154 page = parse_pointer (__func__, s);
4155 slink = &page->slinks[Int_val (n_v)];
4156 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4157 String_val (str_v));
4158 state.dirty = 1;
4160 CAMLreturn0;
4163 CAMLprim value ml_hasunsavedchanges (value unit_v)
4165 CAMLparam1 (unit_v);
4166 CAMLreturn (Val_bool (state.dirty));
4169 CAMLprim void ml_savedoc (value path_v)
4171 CAMLparam1 (path_v);
4172 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4174 if (pdf) {
4175 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4177 CAMLreturn0;
4180 static void makestippletex (void)
4182 const char pixels[] = "\xff\xff\0\0";
4183 glGenTextures (1, &state.stid);
4184 glBindTexture (GL_TEXTURE_1D, state.stid);
4185 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4186 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4187 glTexImage1D (
4188 GL_TEXTURE_1D,
4190 GL_ALPHA,
4193 GL_ALPHA,
4194 GL_UNSIGNED_BYTE,
4195 pixels
4199 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4201 return caml_copy_string (FZ_VERSION);
4204 CAMLprim void ml_init (value csock_v, value params_v)
4206 CAMLparam2 (csock_v, params_v);
4207 CAMLlocal2 (trim_v, fuzz_v);
4208 int ret;
4209 int texcount;
4210 char *fontpath;
4211 int colorspace;
4212 int mustoresize;
4213 int haspboext;
4215 state.csock = Int_val (csock_v);
4216 state.rotate = Int_val (Field (params_v, 0));
4217 state.fitmodel = Int_val (Field (params_v, 1));
4218 trim_v = Field (params_v, 2);
4219 texcount = Int_val (Field (params_v, 3));
4220 state.sliceheight = Int_val (Field (params_v, 4));
4221 mustoresize = Int_val (Field (params_v, 5));
4222 colorspace = Int_val (Field (params_v, 6));
4223 fontpath = String_val (Field (params_v, 7));
4225 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
4226 if (setlocale (LC_CTYPE, "")) {
4227 const char *cset = nl_langinfo (CODESET);
4228 state.utf8cs = !strcmp (cset, "UTF-8");
4230 else {
4231 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
4234 if (caml_string_length (Field (params_v, 8)) > 0) {
4235 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4237 if (!state.trimcachepath) {
4238 printd ("emsg failed to strdup trimcachepath: %d:%s",
4239 errno, strerror (errno));
4243 haspboext = Bool_val (Field (params_v, 9));
4245 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4246 fz_register_document_handlers (state.ctx);
4248 state.trimmargins = Bool_val (Field (trim_v, 0));
4249 fuzz_v = Field (trim_v, 1);
4250 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4251 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4252 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4253 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4255 set_tex_params (colorspace);
4257 if (*fontpath) {
4258 state.face = load_font (fontpath);
4260 else {
4261 int len;
4262 const unsigned char *data;
4264 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4265 state.face = load_builtin_font (data, len);
4267 if (!state.face) _exit (1);
4269 realloctexts (texcount);
4271 if (haspboext) {
4272 setuppbo ();
4275 makestippletex ();
4277 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4278 if (ret) {
4279 errx (1, "pthread_create: %s", strerror (ret));
4282 CAMLreturn0;
4285 #if FIXME || !FIXME
4286 static void OPTIMIZE_ATTR (0) UNUSED_ATTR refmacs (void) {}
4287 #endif