Greek
[llpp.git] / link.c
blob4eb80f36f838e1fe8586d4b8afeb7d3f7cda46c9
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 cxack;
258 int dirty;
260 GLuint stid;
262 int bo_usable;
263 GLuint boid;
265 void (*glBindBufferARB) (GLenum, GLuint);
266 GLboolean (*glUnmapBufferARB) (GLenum);
267 void *(*glMapBufferARB) (GLenum, GLenum);
268 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
269 void (*glGenBuffersARB) (GLsizei, GLuint *);
270 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
272 GLfloat texcoords[8];
273 GLfloat vertices[16];
275 #ifdef CACHE_PAGEREFS
276 struct {
277 int idx;
278 int count;
279 pdf_obj **objs;
280 pdf_document *pdf;
281 } pdflut;
282 #endif
283 int utf8cs;
284 } state;
286 struct bo {
287 GLuint id;
288 void *ptr;
289 size_t size;
292 #pragma GCC diagnostic ignored "-Wdouble-promotion"
293 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
295 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
298 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
300 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
303 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
305 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
306 m.a, m.b, m.c, m.d, m.e, m.f);
308 #pragma GCC diagnostic error "-Wdouble-promotion"
310 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
312 static void lock (const char *cap)
314 int ret = pthread_mutex_lock (&mutex);
315 if (ret) {
316 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
320 static void unlock (const char *cap)
322 int ret = pthread_mutex_unlock (&mutex);
323 if (ret) {
324 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
328 static int trylock (const char *cap)
330 int ret = pthread_mutex_trylock (&mutex);
331 if (ret && ret != EBUSY) {
332 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
334 return ret == EBUSY;
337 static void *parse_pointer (const char *cap, const char *s)
339 int ret;
340 void *ptr;
342 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
343 if (ret != 1) {
344 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
346 return ptr;
349 static double now (void)
351 struct timeval tv;
353 if (gettimeofday (&tv, NULL)) {
354 err (1, "gettimeofday");
356 return tv.tv_sec + tv.tv_usec*1e-6;
359 static int hasdata (void)
361 int ret, avail;
362 ret = ioctl (state.csock, FIONREAD, &avail);
363 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
364 return avail > 0;
367 CAMLprim value ml_hasdata (value fd_v)
369 CAMLparam1 (fd_v);
370 int ret, avail;
372 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
373 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
374 CAMLreturn (Val_bool (avail > 0));
377 static void readdata (int fd, void *p, int size)
379 ssize_t n;
381 again:
382 n = read (fd, p, size);
383 if (n - size) {
384 if (n < 0 && errno == EINTR) goto again;
385 if (!n) errx (1, "EOF while reading");
386 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
390 static void writedata (int fd, char *p, int size)
392 ssize_t n;
393 uint32_t size4 = size;
394 struct iovec iov[2] = {
395 { .iov_base = &size4, .iov_len = 4 },
396 { .iov_base = p, .iov_len = size }
399 again:
400 n = writev (fd, iov, 2);
401 if (n < 0 && errno == EINTR) goto again;
402 if (n - size - 4) {
403 if (!n) errx (1, "EOF while writing data");
404 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
408 static int readlen (int fd)
410 uint32_t u;
411 readdata (fd, &u, 4);
412 return u;
415 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
417 CAMLparam3 (fd_v, bytes_v, len_v);
418 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
419 CAMLreturn0;
422 CAMLprim value ml_rcmd (value fd_v)
424 CAMLparam1 (fd_v);
425 CAMLlocal1 (strdata_v);
426 int fd = Int_val (fd_v);
427 int len = readlen (fd);
428 strdata_v = caml_alloc_string (len);
429 readdata (fd, String_val (strdata_v), len);
430 CAMLreturn (strdata_v);
433 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
435 char fbuf[64];
436 int size = sizeof (fbuf), len;
437 va_list ap;
438 char *buf = fbuf;
440 for (;;) {
441 va_start (ap, fmt);
442 len = vsnprintf (buf, size, fmt, ap);
443 va_end (ap);
445 if (len > -1) {
446 if (len < size - 4) {
447 writedata (state.csock, buf, len);
448 break;
450 else size = len + 5;
452 else {
453 err (1, "vsnprintf for `%s' failed", fmt);
455 buf = realloc (buf == fbuf ? NULL : buf, size);
456 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
458 if (buf != fbuf) free (buf);
461 static void closedoc (void)
463 #ifdef CACHE_PAGEREFS
464 if (state.pdflut.objs) {
465 for (int i = 0; i < state.pdflut.count; ++i) {
466 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
468 free (state.pdflut.objs);
469 state.pdflut.objs = NULL;
470 state.pdflut.idx = 0;
472 #endif
473 if (state.doc) {
474 fz_drop_document (state.ctx, state.doc);
475 state.doc = NULL;
479 static int openxref (char *filename, char *password)
481 for (int i = 0; i < state.texcount; ++i) {
482 state.texowners[i].w = -1;
483 state.texowners[i].slice = NULL;
486 closedoc ();
488 state.dirty = 0;
489 if (state.pagedims) {
490 free (state.pagedims);
491 state.pagedims = NULL;
493 state.pagedimcount = 0;
495 fz_set_aa_level (state.ctx, state.aalevel);
496 state.doc = fz_open_document (state.ctx, filename);
497 if (fz_needs_password (state.ctx, state.doc)) {
498 if (password && !*password) {
499 printd ("pass");
500 return 0;
502 else {
503 int ok = fz_authenticate_password (state.ctx, state.doc, password);
504 if (!ok) {
505 printd ("pass fail");
506 return 0;
510 fz_layout_document (state.ctx, state.doc, 460, 0, 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 (int wthack)
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 || !state.cxack)
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);
1061 if (!state.cxack) {
1062 printd ("progress %f loading %d",
1063 (double) (pageno + 1) / state.pagecount,
1064 pageno + 1);
1067 fz_catch (ctx) {
1069 if (trimf) {
1070 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1071 if (n - 1) {
1072 err (1, "fwrite trim mediabox");
1076 else {
1077 if (trimf) {
1078 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1079 if (n - 1) {
1080 err (1, "fread trim mediabox %d", pageno);
1083 else {
1084 fz_page *page;
1085 fz_try (ctx) {
1086 page = fz_load_page (ctx, state.doc, pageno);
1087 fz_bound_page (ctx, page, &mediabox);
1088 fz_drop_page (ctx, page);
1090 show = !state.trimmargins && pageno % 20 == 0;
1091 if (show) {
1092 printd ("progress %f Gathering dimensions %d",
1093 (double) (pageno) / state.pagecount,
1094 pageno);
1097 fz_catch (ctx) {
1098 printd ("emsg failed to load page %d", pageno);
1104 if (state.pagedimcount == 0
1105 || ((void) (p = &state.pagedims[state.pagedimcount-1])
1106 , p->rotate != rotate)
1107 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1108 size_t size;
1110 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1111 state.pagedims = realloc (state.pagedims, size);
1112 if (!state.pagedims) {
1113 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1114 size, state.pagedimcount + 1);
1117 p = &state.pagedims[state.pagedimcount++];
1118 p->rotate = rotate;
1119 p->mediabox = mediabox;
1120 p->pageno = pageno;
1123 end = now ();
1124 if (!wthack) {
1125 printd ("progress 1 %s %d pages in %f seconds",
1126 state.trimmargins ? "Trimmed" : "Processed",
1127 state.pagecount, end - start);
1129 state.trimanew = 0;
1130 if (trimf) {
1131 if (fclose (trimf)) {
1132 err (1, "fclose");
1137 static void layout (void)
1139 int pindex;
1140 fz_rect box;
1141 fz_matrix ctm, rm;
1142 struct pagedim *p = NULL;
1143 float zw, w, maxw = 0.0, zoom = 1.0;
1145 if (state.pagedimcount == 0) return;
1147 switch (state.fitmodel) {
1148 case FitProportional:
1149 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1150 float x0, x1;
1152 p = &state.pagedims[pindex];
1153 fz_rotate (&rm, p->rotate + state.rotate);
1154 box = p->mediabox;
1155 fz_transform_rect (&box, &rm);
1157 x0 = fz_min (box.x0, box.x1);
1158 x1 = fz_max (box.x0, box.x1);
1160 w = x1 - x0;
1161 maxw = fz_max (w, maxw);
1162 zoom = state.w / maxw;
1164 break;
1166 case FitPage:
1167 maxw = state.w;
1168 break;
1170 case FitWidth:
1171 break;
1173 default:
1174 ARSERT (0 && state.fitmodel);
1177 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1178 fz_rect rect;
1179 fz_matrix tm, sm;
1181 p = &state.pagedims[pindex];
1182 fz_rotate (&ctm, state.rotate);
1183 fz_rotate (&rm, p->rotate + state.rotate);
1184 box = p->mediabox;
1185 fz_transform_rect (&box, &rm);
1186 w = box.x1 - box.x0;
1187 switch (state.fitmodel) {
1188 case FitProportional:
1189 p->left = (int) (((maxw - w) * zoom) / 2.f);
1190 break;
1191 case FitPage:
1193 float zh, h;
1194 zw = maxw / w;
1195 h = box.y1 - box.y0;
1196 zh = state.h / h;
1197 zoom = fz_min (zw, zh);
1198 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1200 break;
1201 case FitWidth:
1202 p->left = 0;
1203 zoom = state.w / w;
1204 break;
1207 fz_scale (&p->zoomctm, zoom, zoom);
1208 fz_concat (&ctm, &p->zoomctm, &ctm);
1210 fz_rotate (&rm, p->rotate);
1211 p->pagebox = p->mediabox;
1212 fz_transform_rect (&p->pagebox, &rm);
1213 p->pagebox.x1 -= p->pagebox.x0;
1214 p->pagebox.y1 -= p->pagebox.y0;
1215 p->pagebox.x0 = 0;
1216 p->pagebox.y0 = 0;
1217 rect = p->pagebox;
1218 fz_transform_rect (&rect, &ctm);
1219 fz_round_rect (&p->bounds, &rect);
1220 p->ctm = ctm;
1222 fz_translate (&tm, 0, -p->mediabox.y1);
1223 fz_scale (&sm, zoom, -zoom);
1224 fz_concat (&ctm, &tm, &sm);
1226 p->tctmready = 0;
1229 do {
1230 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1231 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1232 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1233 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1234 int boundw = x1 - x0;
1235 int boundh = y1 - y0;
1237 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1238 } while (p-- != state.pagedims);
1241 struct pagedim *pdimofpageno (int pageno)
1243 struct pagedim *pdim = state.pagedims;
1245 for (int i = 0; i < state.pagedimcount; ++i) {
1246 if (state.pagedims[i].pageno > pageno)
1247 break;
1248 pdim = &state.pagedims[i];
1250 return pdim;
1253 static void recurse_outline (fz_outline *outline, int level)
1255 while (outline) {
1256 if (outline->page >= 0) {
1257 fz_point p = {.x = outline->x, .y = outline->y};
1258 struct pagedim *pdim = pdimofpageno (outline->page);
1259 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1260 fz_transform_point (&p, &pdim->ctm);
1261 printd ("o %d %d %d %d %s",
1262 level, outline->page, (int) p.y, h, outline->title);
1264 else {
1265 printd ("on %d %s", level, outline->title);
1267 if (outline->down) {
1268 recurse_outline (outline->down, level + 1);
1270 outline = outline->next;
1274 static void process_outline (void)
1276 fz_outline *outline;
1278 if (!state.needoutline || !state.pagedimcount) return;
1280 state.needoutline = 0;
1281 outline = fz_load_outline (state.ctx, state.doc);
1282 if (outline) {
1283 recurse_outline (outline, 0);
1284 fz_drop_outline (state.ctx, outline);
1288 static char *strofline (fz_stext_line *line)
1290 char *p;
1291 char utf8[10];
1292 fz_stext_char *ch;
1293 size_t size = 0, cap = 80;
1295 p = malloc (cap + 1);
1296 if (!p) return NULL;
1298 for (ch = line->first_char; ch; ch = ch->next) {
1299 int n = fz_runetochar (utf8, ch->c);
1300 if (size + n > cap) {
1301 cap *= 2;
1302 p = realloc (p, cap + 1);
1303 if (!p) return NULL;
1306 memcpy (p + size, utf8, n);
1307 size += n;
1309 p[size] = 0;
1310 return p;
1313 static int matchline (regex_t *re, fz_stext_line *line,
1314 int stop, int pageno, double start)
1316 int ret;
1317 char *p;
1318 regmatch_t rm;
1320 p = strofline (line);
1321 if (!p) return -1;
1323 ret = regexec (re, p, 1, &rm, 0);
1324 if (ret) {
1325 free (p);
1326 if (ret != REG_NOMATCH) {
1327 size_t size;
1328 char errbuf[80];
1329 size = regerror (ret, re, errbuf, sizeof (errbuf));
1330 printd ("msg regexec error `%.*s'",
1331 (int) size, errbuf);
1332 return -1;
1334 return 0;
1336 else {
1337 fz_point p1, p2, p3, p4;
1338 fz_rect s = {0,0,0,0}, e;
1339 fz_stext_char *ch;
1340 int o = 0;
1342 for (ch = line->first_char; ch; ch = ch->next) {
1343 o += fz_runelen (ch->c);
1344 if (o > rm.rm_so) {
1345 s = ch->bbox;
1346 break;
1349 for (;ch; ch = ch->next) {
1350 o += fz_runelen (ch->c);
1351 if (o > rm.rm_eo) break;
1353 e = ch->bbox;
1355 p1.x = s.x0;
1356 p1.y = s.y0;
1357 p2.x = e.x1;
1358 p2.y = s.y0;
1359 p3.x = e.x1;
1360 p3.y = e.y1;
1361 p4.x = s.x0;
1362 p4.y = e.y1;
1364 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1365 if (!stop) {
1366 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1367 pageno, 1,
1368 p1.x, p1.y,
1369 p2.x, p2.y,
1370 p3.x, p3.y,
1371 p4.x, p4.y);
1373 printd ("progress 1 found at %d `%.*s' in %f sec",
1374 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1375 now () - start);
1377 else {
1378 printd ("match %d %d %f %f %f %f %f %f %f %f",
1379 pageno, 2,
1380 p1.x, p1.y,
1381 p2.x, p2.y,
1382 p3.x, p3.y,
1383 p4.x, p4.y);
1385 #pragma GCC diagnostic error "-Wdouble-promotion"
1386 free (p);
1387 return 1;
1391 /* wishful thinking function */
1392 static void search (regex_t *re, int pageno, int y, int forward)
1394 fz_device *tdev;
1395 fz_stext_page *text;
1396 struct pagedim *pdim;
1397 int stop = 0, niters = 0;
1398 double start, end;
1399 fz_page *page;
1400 fz_stext_block *block;
1402 start = now ();
1403 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1404 if (niters++ == 5) {
1405 niters = 0;
1406 if (hasdata ()) {
1407 printd ("progress 1 attention requested aborting search at %d",
1408 pageno);
1409 stop = 1;
1411 else {
1412 printd ("progress %f searching in page %d",
1413 (double) (pageno + 1) / state.pagecount,
1414 pageno);
1417 pdim = pdimofpageno (pageno);
1418 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1419 tdev = fz_new_stext_device (state.ctx, text, 0);
1421 page = fz_load_page (state.ctx, state.doc, pageno);
1423 fz_matrix ctm = pagectm1 (page, pdim);
1424 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1427 fz_close_device (state.ctx, tdev);
1428 fz_drop_device (state.ctx, tdev);
1430 if (forward) {
1431 for (block = text->first_block; block; block = block->next) {
1432 fz_stext_line *line;
1434 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1435 for (line = block->u.t.first_line; line; line = line->next) {
1436 if (line->bbox.y0 < y + 1) continue;
1438 switch (matchline (re, line, stop, pageno, start)) {
1439 case 0: break;
1440 case 1: stop = 1; break;
1441 case -1: stop = 1; goto endloop;
1446 else {
1447 for (block = text->last_block; block; block = block->prev) {
1448 fz_stext_line *line;
1450 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1451 for (line = block->u.t.last_line; line; line = line->prev) {
1452 if (line->bbox.y0 < y + 1) continue;
1454 switch (matchline (re, line, stop, pageno, start)) {
1455 case 0: break;
1456 case 1: stop = 1; break;
1457 case -1: stop = 1; goto endloop;
1463 if (forward) {
1464 pageno += 1;
1465 y = 0;
1467 else {
1468 pageno -= 1;
1469 y = INT_MAX;
1471 endloop:
1472 fz_drop_stext_page (state.ctx, text);
1473 fz_drop_page (state.ctx, page);
1475 end = now ();
1476 if (!stop) {
1477 printd ("progress 1 no matches %f sec", end - start);
1479 printd ("clearrects");
1482 static void set_tex_params (int colorspace)
1484 switch (colorspace) {
1485 case 0:
1486 state.texiform = GL_RGBA8;
1487 state.texform = GL_RGBA;
1488 state.texty = GL_UNSIGNED_BYTE;
1489 state.colorspace = fz_device_rgb (state.ctx);
1490 break;
1491 case 1:
1492 state.texiform = GL_RGBA8;
1493 state.texform = GL_BGRA;
1494 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1495 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1496 #else
1497 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1498 #endif
1499 state.colorspace = fz_device_bgr (state.ctx);
1500 break;
1501 case 2:
1502 state.texiform = GL_LUMINANCE_ALPHA;
1503 state.texform = GL_LUMINANCE_ALPHA;
1504 state.texty = GL_UNSIGNED_BYTE;
1505 state.colorspace = fz_device_gray (state.ctx);
1506 break;
1507 default:
1508 errx (1, "invalid colorspce %d", colorspace);
1512 static void realloctexts (int texcount)
1514 size_t size;
1516 if (texcount == state.texcount) return;
1518 if (texcount < state.texcount) {
1519 glDeleteTextures (state.texcount - texcount,
1520 state.texids + texcount);
1523 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1524 state.texids = realloc (state.texids, size);
1525 if (!state.texids) {
1526 err (1, "realloc texs %" FMT_s, size);
1529 state.texowners = (void *) (state.texids + texcount);
1530 if (texcount > state.texcount) {
1531 glGenTextures (texcount - state.texcount,
1532 state.texids + state.texcount);
1533 for (int i = state.texcount; i < texcount; ++i) {
1534 state.texowners[i].w = -1;
1535 state.texowners[i].slice = NULL;
1538 state.texcount = texcount;
1539 state.texindex = 0;
1542 static char *mbtoutf8 (char *s)
1544 char *p, *r;
1545 wchar_t *tmp;
1546 size_t i, ret, len;
1548 if (state.utf8cs) {
1549 return s;
1552 len = mbstowcs (NULL, s, strlen (s));
1553 if (len == 0) {
1554 return s;
1556 else {
1557 if (len == (size_t) -1) {
1558 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1559 return s;
1563 tmp = calloc (len, sizeof (wchar_t));
1564 if (!tmp) {
1565 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1566 len, sizeof (wchar_t), errno, strerror (errno));
1567 return s;
1570 ret = mbstowcs (tmp, s, len);
1571 if (ret == (size_t) -1) {
1572 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1573 len, errno, strerror (errno));
1574 free (tmp);
1575 return s;
1578 len = 0;
1579 for (i = 0; i < ret; ++i) {
1580 len += fz_runelen (tmp[i]);
1583 p = r = malloc (len + 1);
1584 if (!r) {
1585 printd ("emsg mbtoutf8: malloc(%zu)", len);
1586 free (tmp);
1587 return s;
1590 for (i = 0; i < ret; ++i) {
1591 p += fz_runetochar (p, tmp[i]);
1593 *p = 0;
1594 free (tmp);
1595 return r;
1598 CAMLprim value ml_mbtoutf8 (value s_v)
1600 CAMLparam1 (s_v);
1601 CAMLlocal1 (ret_v);
1602 char *s, *r;
1604 s = String_val (s_v);
1605 r = mbtoutf8 (s);
1606 if (r == s) {
1607 ret_v = s_v;
1609 else {
1610 ret_v = caml_copy_string (r);
1611 free (r);
1613 CAMLreturn (ret_v);
1616 static void * mainloop (void UNUSED_ATTR *unused)
1618 char *p = NULL;
1619 int len, ret, oldlen = 0;
1621 fz_var (p);
1622 fz_var (oldlen);
1623 for (;;) {
1624 len = readlen (state.csock);
1625 if (len == 0) {
1626 errx (1, "readlen returned 0");
1629 if (oldlen < len + 1) {
1630 p = realloc (p, len + 1);
1631 if (!p) {
1632 err (1, "realloc %d failed", len + 1);
1634 oldlen = len + 1;
1636 readdata (state.csock, p, len);
1637 p[len] = 0;
1639 if (!strncmp ("open", p, 4)) {
1640 int wthack, off, usedoccss, ok = 0;
1641 char *password;
1642 char *filename;
1643 char *utf8filename;
1644 size_t filenamelen;
1646 fz_var (ok);
1647 ret = sscanf (p + 5, " %d %d %d %n",
1648 &wthack, &state.cxack, &usedoccss, &off);
1649 if (ret != 3) {
1650 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1653 filename = p + 5 + off;
1654 filenamelen = strlen (filename);
1655 password = filename + filenamelen + 1;
1657 if (password[strlen (password) + 1]) {
1658 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1661 lock ("open");
1662 fz_set_use_document_css (state.ctx, usedoccss);
1663 fz_try (state.ctx) {
1664 ok = openxref (filename, password);
1666 fz_catch (state.ctx) {
1667 utf8filename = mbtoutf8 (filename);
1668 printd ("msg Could not open %s", utf8filename);
1669 if (utf8filename != filename) {
1670 free (utf8filename);
1673 if (ok) {
1674 pdfinfo ();
1675 initpdims (wthack);
1677 unlock ("open");
1679 if (ok) {
1680 if (!wthack) {
1681 utf8filename = mbtoutf8 (filename);
1682 printd ("msg Opened %s (press h/F1 to get help)",
1683 utf8filename);
1684 if (utf8filename != filename) {
1685 free (utf8filename);
1688 state.needoutline = 1;
1691 else if (!strncmp ("cs", p, 2)) {
1692 int i, colorspace;
1694 ret = sscanf (p + 2, " %d", &colorspace);
1695 if (ret != 1) {
1696 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1698 lock ("cs");
1699 set_tex_params (colorspace);
1700 for (i = 0; i < state.texcount; ++i) {
1701 state.texowners[i].w = -1;
1702 state.texowners[i].slice = NULL;
1704 unlock ("cs");
1706 else if (!strncmp ("freepage", p, 8)) {
1707 void *ptr;
1709 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1710 if (ret != 1) {
1711 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1713 lock ("freepage");
1714 freepage (ptr);
1715 unlock ("freepage");
1717 else if (!strncmp ("freetile", p, 8)) {
1718 void *ptr;
1720 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1721 if (ret != 1) {
1722 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1724 lock ("freetile");
1725 freetile (ptr);
1726 unlock ("freetile");
1728 else if (!strncmp ("search", p, 6)) {
1729 int icase, pageno, y, len2, forward;
1730 char *pattern;
1731 regex_t re;
1733 ret = sscanf (p + 6, " %d %d %d %d,%n",
1734 &icase, &pageno, &y, &forward, &len2);
1735 if (ret != 4) {
1736 errx (1, "malformed search `%s' ret=%d", p, ret);
1739 pattern = p + 6 + len2;
1740 ret = regcomp (&re, pattern,
1741 REG_EXTENDED | (icase ? REG_ICASE : 0));
1742 if (ret) {
1743 char errbuf[80];
1744 size_t size;
1746 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1747 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1749 else {
1750 search (&re, pageno, y, forward);
1751 regfree (&re);
1754 else if (!strncmp ("geometry", p, 8)) {
1755 int w, h, fitmodel;
1757 printd ("clear");
1758 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1759 if (ret != 3) {
1760 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1763 lock ("geometry");
1764 state.h = h;
1765 if (w != state.w) {
1766 state.w = w;
1767 for (int i = 0; i < state.texcount; ++i) {
1768 state.texowners[i].slice = NULL;
1771 state.fitmodel = fitmodel;
1772 layout ();
1773 process_outline ();
1775 state.gen++;
1776 unlock ("geometry");
1777 printd ("continue %d", state.pagecount);
1779 else if (!strncmp ("reqlayout", p, 9)) {
1780 char *nameddest;
1781 int rotate, off, h;
1782 int fitmodel;
1783 pdf_document *pdf;
1785 printd ("clear");
1786 ret = sscanf (p + 9, " %d %d %d %n",
1787 &rotate, &fitmodel, &h, &off);
1788 if (ret != 3) {
1789 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1791 lock ("reqlayout");
1792 pdf = pdf_specifics (state.ctx, state.doc);
1793 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1794 state.gen += 1;
1796 state.rotate = rotate;
1797 state.fitmodel = fitmodel;
1798 state.h = h;
1799 layout ();
1800 process_outline ();
1802 nameddest = p + 9 + off;
1803 if (pdf && nameddest && *nameddest) {
1804 fz_point xy;
1805 struct pagedim *pdim;
1806 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1807 &xy.x, &xy.y);
1808 pdim = pdimofpageno (pageno);
1809 fz_transform_point (&xy, &pdim->ctm);
1810 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1813 state.gen++;
1814 unlock ("reqlayout");
1815 printd ("continue %d", state.pagecount);
1817 else if (!strncmp ("page", p, 4)) {
1818 double a, b;
1819 struct page *page;
1820 int pageno, pindex;
1822 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1823 if (ret != 2) {
1824 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1827 lock ("page");
1828 a = now ();
1829 page = loadpage (pageno, pindex);
1830 b = now ();
1831 unlock ("page");
1833 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1835 else if (!strncmp ("tile", p, 4)) {
1836 int x, y, w, h;
1837 struct page *page;
1838 struct tile *tile;
1839 double a, b;
1840 void *data;
1842 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1843 SCN_ptr_cast (&page), &x, &y, &w, &h,
1844 SCN_ptr_cast (&data));
1845 if (ret != 6) {
1846 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1849 lock ("tile");
1850 a = now ();
1851 tile = rendertile (page, x, y, w, h, data);
1852 b = now ();
1853 unlock ("tile");
1855 printd ("tile %d %d %" FMT_ptr " %u %f",
1856 x, y,
1857 FMT_ptr_cast (tile),
1858 tile->w * tile->h * tile->pixmap->n,
1859 b - a);
1861 else if (!strncmp ("trimset", p, 7)) {
1862 fz_irect fuzz;
1863 int trimmargins;
1865 ret = sscanf (p + 7, " %d %d %d %d %d",
1866 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1867 if (ret != 5) {
1868 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1870 lock ("trimset");
1871 state.trimmargins = trimmargins;
1872 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1873 state.trimanew = 1;
1874 state.trimfuzz = fuzz;
1876 unlock ("trimset");
1878 else if (!strncmp ("settrim", p, 7)) {
1879 fz_irect fuzz;
1880 int trimmargins;
1882 ret = sscanf (p + 7, " %d %d %d %d %d",
1883 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1884 if (ret != 5) {
1885 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1887 printd ("clear");
1888 lock ("settrim");
1889 state.trimmargins = trimmargins;
1890 state.needoutline = 1;
1891 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1892 state.trimanew = 1;
1893 state.trimfuzz = fuzz;
1895 state.pagedimcount = 0;
1896 free (state.pagedims);
1897 state.pagedims = NULL;
1898 initpdims (0);
1899 layout ();
1900 process_outline ();
1901 unlock ("settrim");
1902 printd ("continue %d", state.pagecount);
1904 else if (!strncmp ("sliceh", p, 6)) {
1905 int h;
1907 ret = sscanf (p + 6, " %d", &h);
1908 if (ret != 1) {
1909 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1911 if (h != state.sliceheight) {
1912 state.sliceheight = h;
1913 for (int i = 0; i < state.texcount; ++i) {
1914 state.texowners[i].w = -1;
1915 state.texowners[i].h = -1;
1916 state.texowners[i].slice = NULL;
1920 else if (!strncmp ("interrupt", p, 9)) {
1921 printd ("vmsg interrupted");
1923 else {
1924 errx (1, "unknown command %.*s", len, p);
1927 return 0;
1930 CAMLprim value ml_isexternallink (value uri_v)
1932 CAMLparam1 (uri_v);
1933 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1934 CAMLreturn (Val_bool (ext));
1937 CAMLprim value ml_uritolocation (value uri_v)
1939 CAMLparam1 (uri_v);
1940 CAMLlocal1 (ret_v);
1941 int pageno;
1942 fz_point xy;
1943 struct pagedim *pdim;
1945 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1946 &xy.x, &xy.y);
1947 pdim = pdimofpageno (pageno);
1948 fz_transform_point (&xy, &pdim->ctm);
1949 ret_v = caml_alloc_tuple (3);
1950 Field (ret_v, 0) = Val_int (pageno);
1951 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1952 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1953 CAMLreturn (ret_v);
1956 CAMLprim value ml_realloctexts (value texcount_v)
1958 CAMLparam1 (texcount_v);
1959 int ok;
1961 if (trylock (__func__)) {
1962 ok = 0;
1963 goto done;
1965 realloctexts (Int_val (texcount_v));
1966 ok = 1;
1967 unlock (__func__);
1969 done:
1970 CAMLreturn (Val_bool (ok));
1973 static void recti (int x0, int y0, int x1, int y1)
1975 GLfloat *v = state.vertices;
1977 glVertexPointer (2, GL_FLOAT, 0, v);
1978 v[0] = x0; v[1] = y0;
1979 v[2] = x1; v[3] = y0;
1980 v[4] = x0; v[5] = y1;
1981 v[6] = x1; v[7] = y1;
1982 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1985 static void showsel (struct page *page, int ox, int oy)
1987 fz_irect bbox;
1988 fz_rect rect;
1989 fz_stext_block *block;
1990 int seen = 0;
1991 unsigned char selcolor[] = {15,15,15,140};
1993 if (!page->fmark.ch || !page->lmark.ch) return;
1995 glEnable (GL_BLEND);
1996 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1997 glColor4ubv (selcolor);
1999 ox += state.pagedims[page->pdimno].bounds.x0;
2000 oy += state.pagedims[page->pdimno].bounds.y0;
2002 for (block = page->text->first_block; block; block = block->next) {
2003 fz_stext_line *line;
2005 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2006 for (line = block->u.t.first_line; line; line = line->next) {
2007 fz_stext_char *ch;
2009 rect = fz_empty_rect;
2010 for (ch = line->first_char; ch; ch = ch->next) {
2011 if (ch == page->fmark.ch) seen = 1;
2012 if (seen) fz_union_rect (&rect, &ch->bbox);
2013 if (ch == page->lmark.ch) {
2014 fz_round_rect (&bbox, &rect);
2015 recti (bbox.x0 + ox, bbox.y0 + oy,
2016 bbox.x1 + ox, bbox.y1 + oy);
2017 goto done;
2020 fz_round_rect (&bbox, &rect);
2021 recti (bbox.x0 + ox, bbox.y0 + oy,
2022 bbox.x1 + ox, bbox.y1 + oy);
2025 done:
2026 glDisable (GL_BLEND);
2029 #pragma GCC diagnostic push
2030 #pragma GCC diagnostic ignored "-Wdouble-promotion"
2031 #pragma GCC diagnostic ignored "-Wconversion"
2032 #include "glfont.c"
2033 #pragma GCC diagnostic pop
2035 static void stipplerect (fz_matrix *m,
2036 fz_point *p1,
2037 fz_point *p2,
2038 fz_point *p3,
2039 fz_point *p4,
2040 GLfloat *texcoords,
2041 GLfloat *vertices)
2043 fz_transform_point (p1, m);
2044 fz_transform_point (p2, m);
2045 fz_transform_point (p3, m);
2046 fz_transform_point (p4, m);
2048 float w, h, s, t;
2050 w = p2->x - p1->x;
2051 h = p2->y - p1->y;
2052 t = hypotf (w, h) * .25f;
2054 w = p3->x - p2->x;
2055 h = p3->y - p2->y;
2056 s = hypotf (w, h) * .25f;
2058 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2059 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2061 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2062 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2064 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2065 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2067 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2068 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2070 glDrawArrays (GL_LINES, 0, 8);
2073 static void solidrect (fz_matrix *m,
2074 fz_point *p1,
2075 fz_point *p2,
2076 fz_point *p3,
2077 fz_point *p4,
2078 GLfloat *vertices)
2080 fz_transform_point (p1, m);
2081 fz_transform_point (p2, m);
2082 fz_transform_point (p3, m);
2083 fz_transform_point (p4, m);
2084 vertices[0] = p1->x; vertices[1] = p1->y;
2085 vertices[2] = p2->x; vertices[3] = p2->y;
2087 vertices[4] = p3->x; vertices[5] = p3->y;
2088 vertices[6] = p4->x; vertices[7] = p4->y;
2089 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2092 static void ensurelinks (struct page *page)
2094 if (!page->links)
2095 page->links = fz_load_links (state.ctx, page->fzpage);
2098 static void highlightlinks (struct page *page, int xoff, int yoff)
2100 fz_matrix ctm, tm, pm;
2101 fz_link *link;
2102 GLfloat *texcoords = state.texcoords;
2103 GLfloat *vertices = state.vertices;
2105 ensurelinks (page);
2107 glEnable (GL_TEXTURE_1D);
2108 glEnable (GL_BLEND);
2109 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2110 glBindTexture (GL_TEXTURE_1D, state.stid);
2112 xoff -= state.pagedims[page->pdimno].bounds.x0;
2113 yoff -= state.pagedims[page->pdimno].bounds.y0;
2114 fz_translate (&tm, xoff, yoff);
2115 pm = pagectm (page);
2116 fz_concat (&ctm, &pm, &tm);
2118 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2119 glVertexPointer (2, GL_FLOAT, 0, vertices);
2121 for (link = page->links; link; link = link->next) {
2122 fz_point p1, p2, p3, p4;
2124 p1.x = link->rect.x0;
2125 p1.y = link->rect.y0;
2127 p2.x = link->rect.x1;
2128 p2.y = link->rect.y0;
2130 p3.x = link->rect.x1;
2131 p3.y = link->rect.y1;
2133 p4.x = link->rect.x0;
2134 p4.y = link->rect.y1;
2136 /* TODO: different colours for different schemes */
2137 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2138 else glColor3ub (255, 0, 0);
2140 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2143 for (int i = 0; i < page->annotcount; ++i) {
2144 fz_point p1, p2, p3, p4;
2145 struct annot *annot = &page->annots[i];
2147 p1.x = annot->bbox.x0;
2148 p1.y = annot->bbox.y0;
2150 p2.x = annot->bbox.x1;
2151 p2.y = annot->bbox.y0;
2153 p3.x = annot->bbox.x1;
2154 p3.y = annot->bbox.y1;
2156 p4.x = annot->bbox.x0;
2157 p4.y = annot->bbox.y1;
2159 glColor3ub (0, 0, 128);
2160 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2163 glDisable (GL_BLEND);
2164 glDisable (GL_TEXTURE_1D);
2167 static int compareslinks (const void *l, const void *r)
2169 struct slink const *ls = l;
2170 struct slink const *rs = r;
2171 if (ls->bbox.y0 == rs->bbox.y0) {
2172 return rs->bbox.x0 - rs->bbox.x0;
2174 return ls->bbox.y0 - rs->bbox.y0;
2177 static void droptext (struct page *page)
2179 if (page->text) {
2180 fz_drop_stext_page (state.ctx, page->text);
2181 page->fmark.ch = NULL;
2182 page->lmark.ch = NULL;
2183 page->text = NULL;
2187 static void dropannots (struct page *page)
2189 if (page->annots) {
2190 free (page->annots);
2191 page->annots = NULL;
2192 page->annotcount = 0;
2196 static void ensureannots (struct page *page)
2198 int i, count = 0;
2199 size_t annotsize = sizeof (*page->annots);
2200 fz_annot *annot;
2202 if (state.gen != page->agen) {
2203 dropannots (page);
2204 page->agen = state.gen;
2206 if (page->annots) return;
2208 for (annot = fz_first_annot (state.ctx, page->fzpage);
2209 annot;
2210 annot = fz_next_annot (state.ctx, annot)) {
2211 count++;
2214 if (count > 0) {
2215 page->annotcount = count;
2216 page->annots = calloc (count, annotsize);
2217 if (!page->annots) {
2218 err (1, "calloc annots %d", count);
2221 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2222 annot;
2223 annot = fz_next_annot (state.ctx, annot), i++) {
2224 fz_rect rect;
2226 fz_bound_annot (state.ctx, annot, &rect);
2227 page->annots[i].annot = annot;
2228 fz_round_rect (&page->annots[i].bbox, &rect);
2233 static void dropslinks (struct page *page)
2235 if (page->slinks) {
2236 free (page->slinks);
2237 page->slinks = NULL;
2238 page->slinkcount = 0;
2240 if (page->links) {
2241 fz_drop_link (state.ctx, page->links);
2242 page->links = NULL;
2246 static void ensureslinks (struct page *page)
2248 fz_matrix ctm;
2249 int i, count;
2250 size_t slinksize = sizeof (*page->slinks);
2251 fz_link *link;
2253 ensureannots (page);
2254 if (state.gen != page->sgen) {
2255 dropslinks (page);
2256 page->sgen = state.gen;
2258 if (page->slinks) return;
2260 ensurelinks (page);
2261 ctm = pagectm (page);
2263 count = page->annotcount;
2264 for (link = page->links; link; link = link->next) {
2265 count++;
2267 if (count > 0) {
2268 int j;
2270 page->slinkcount = count;
2271 page->slinks = calloc (count, slinksize);
2272 if (!page->slinks) {
2273 err (1, "calloc slinks %d", count);
2276 for (i = 0, link = page->links; link; ++i, link = link->next) {
2277 fz_rect rect;
2279 rect = link->rect;
2280 fz_transform_rect (&rect, &ctm);
2281 page->slinks[i].tag = SLINK;
2282 page->slinks[i].u.link = link;
2283 fz_round_rect (&page->slinks[i].bbox, &rect);
2285 for (j = 0; j < page->annotcount; ++j, ++i) {
2286 fz_rect rect;
2287 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2288 fz_transform_rect (&rect, &ctm);
2289 fz_round_rect (&page->slinks[i].bbox, &rect);
2291 page->slinks[i].tag = SANNOT;
2292 page->slinks[i].u.annot = page->annots[j].annot;
2294 qsort (page->slinks, count, slinksize, compareslinks);
2298 #pragma GCC diagnostic push
2299 #pragma GCC diagnostic ignored "-Wconversion"
2300 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2301 static void fmt_linkn (char *s, unsigned int u)
2303 unsigned int len; unsigned int q;
2304 unsigned int zma = 'z' - 'a' + 1;
2305 len = 1; q = u;
2306 while (q > zma - 1) { ++len; q /= zma; }
2307 if (s) {
2308 s += len;
2309 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2310 /* handles u == 0 */
2312 s[len] = 0;
2314 #pragma GCC diagnostic pop
2316 static void highlightslinks (struct page *page, int xoff, int yoff,
2317 int noff, char *targ, mlsize_t tlen, int hfsize)
2319 char buf[40];
2320 struct slink *slink;
2321 float x0, y0, x1, y1, w;
2323 ensureslinks (page);
2324 glColor3ub (0xc3, 0xb0, 0x91);
2325 for (int i = 0; i < page->slinkcount; ++i) {
2326 fmt_linkn (buf, i + noff);
2327 if (!tlen || !strncmp (targ, buf, tlen)) {
2328 slink = &page->slinks[i];
2330 x0 = slink->bbox.x0 + xoff - 5;
2331 y1 = slink->bbox.y0 + yoff - 5;
2332 y0 = y1 + 10 + hfsize;
2333 w = measure_string (state.face, hfsize, buf);
2334 x1 = x0 + w + 10;
2335 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2339 glEnable (GL_BLEND);
2340 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2341 glEnable (GL_TEXTURE_2D);
2342 glColor3ub (0, 0, 0);
2343 for (int i = 0; i < page->slinkcount; ++i) {
2344 fmt_linkn (buf, i + noff);
2345 if (!tlen || !strncmp (targ, buf, tlen)) {
2346 slink = &page->slinks[i];
2348 x0 = slink->bbox.x0 + xoff;
2349 y0 = slink->bbox.y0 + yoff + hfsize;
2350 draw_string (state.face, hfsize, x0, y0, buf);
2353 glDisable (GL_TEXTURE_2D);
2354 glDisable (GL_BLEND);
2357 static void uploadslice (struct tile *tile, struct slice *slice)
2359 int offset;
2360 struct slice *slice1;
2361 unsigned char *texdata;
2363 offset = 0;
2364 for (slice1 = tile->slices; slice != slice1; slice1++) {
2365 offset += slice1->h * tile->w * tile->pixmap->n;
2367 if (slice->texindex != -1 && slice->texindex < state.texcount
2368 && state.texowners[slice->texindex].slice == slice) {
2369 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2371 else {
2372 int subimage = 0;
2373 int texindex = state.texindex++ % state.texcount;
2375 if (state.texowners[texindex].w == tile->w) {
2376 if (state.texowners[texindex].h >= slice->h) {
2377 subimage = 1;
2379 else {
2380 state.texowners[texindex].h = slice->h;
2383 else {
2384 state.texowners[texindex].h = slice->h;
2387 state.texowners[texindex].w = tile->w;
2388 state.texowners[texindex].slice = slice;
2389 slice->texindex = texindex;
2391 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2392 #if TEXT_TYPE == GL_TEXTURE_2D
2393 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2394 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2395 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2396 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2397 #endif
2398 if (tile->pbo) {
2399 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2400 texdata = 0;
2402 else {
2403 texdata = tile->pixmap->samples;
2405 if (subimage) {
2406 glTexSubImage2D (TEXT_TYPE,
2410 tile->w,
2411 slice->h,
2412 state.texform,
2413 state.texty,
2414 texdata+offset
2417 else {
2418 glTexImage2D (TEXT_TYPE,
2420 state.texiform,
2421 tile->w,
2422 slice->h,
2424 state.texform,
2425 state.texty,
2426 texdata+offset
2429 if (tile->pbo) {
2430 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2435 CAMLprim void ml_begintiles (value unit_v)
2437 CAMLparam1 (unit_v);
2438 glEnable (TEXT_TYPE);
2439 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2440 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2441 CAMLreturn0;
2444 CAMLprim void ml_endtiles (value unit_v)
2446 CAMLparam1 (unit_v);
2447 glDisable (TEXT_TYPE);
2448 CAMLreturn0;
2451 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2453 CAMLparam2 (args_v, ptr_v);
2454 int dispx = Int_val (Field (args_v, 0));
2455 int dispy = Int_val (Field (args_v, 1));
2456 int dispw = Int_val (Field (args_v, 2));
2457 int disph = Int_val (Field (args_v, 3));
2458 int tilex = Int_val (Field (args_v, 4));
2459 int tiley = Int_val (Field (args_v, 5));
2460 char *s = String_val (ptr_v);
2461 struct tile *tile = parse_pointer (__func__, s);
2462 int slicey, firstslice;
2463 struct slice *slice;
2464 GLfloat *texcoords = state.texcoords;
2465 GLfloat *vertices = state.vertices;
2467 firstslice = tiley / tile->sliceheight;
2468 slice = &tile->slices[firstslice];
2469 slicey = tiley % tile->sliceheight;
2471 while (disph > 0) {
2472 int dh;
2474 dh = slice->h - slicey;
2475 dh = fz_mini (disph, dh);
2476 uploadslice (tile, slice);
2478 texcoords[0] = tilex; texcoords[1] = slicey;
2479 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2480 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2481 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2483 vertices[0] = dispx; vertices[1] = dispy;
2484 vertices[2] = dispx+dispw; vertices[3] = dispy;
2485 vertices[4] = dispx; vertices[5] = dispy+dh;
2486 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2488 #if TEXT_TYPE == GL_TEXTURE_2D
2489 for (int i = 0; i < 8; ++i) {
2490 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2492 #endif
2494 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2495 dispy += dh;
2496 disph -= dh;
2497 slice++;
2498 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2499 slicey = 0;
2501 CAMLreturn0;
2504 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2506 fz_matrix ctm, tm, pm;
2507 fz_point p1, p2, p3, p4;
2508 GLfloat *vertices = state.vertices;
2509 double *v = (double *) rects_v;
2511 xoff -= state.pagedims[page->pdimno].bounds.x0;
2512 yoff -= state.pagedims[page->pdimno].bounds.y0;
2513 fz_translate (&tm, xoff, yoff);
2514 pm = pagectm (page);
2515 fz_concat (&ctm, &pm, &tm);
2517 glEnable (GL_BLEND);
2518 glVertexPointer (2, GL_FLOAT, 0, vertices);
2520 glColor4dv (v);
2521 p1.x = (float) v[4];
2522 p1.y = (float) v[5];
2524 p2.x = (float) v[6];
2525 p2.y = (float) v[5];
2527 p3.x = (float) v[6];
2528 p3.y = (float) v[7];
2530 p4.x = (float) v[4];
2531 p4.y = (float) v[7];
2532 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2533 glDisable (GL_BLEND);
2536 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2537 value xoff_v, value yoff_v,
2538 value li_v)
2540 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2541 int xoff = Int_val (xoff_v);
2542 int yoff = Int_val (yoff_v);
2543 int noff = Int_val (Field (li_v, 0));
2544 char *targ = String_val (Field (li_v, 1));
2545 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2546 int hfsize = Int_val (Field (li_v, 2));
2547 char *s = String_val (ptr_v);
2548 int hlmask = Int_val (hlinks_v);
2549 struct page *page = parse_pointer (__func__, s);
2551 if (!page->fzpage) {
2552 /* deal with loadpage failed pages */
2553 goto done;
2556 if (trylock (__func__)) {
2557 noff = -1;
2558 goto done;
2561 ensureannots (page);
2562 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2563 if (hlmask & 2) {
2564 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2565 noff = page->slinkcount;
2567 if (page->tgen == state.gen) {
2568 showsel (page, xoff, yoff);
2570 unlock (__func__);
2572 done:
2573 CAMLreturn (Val_int (noff));
2576 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2577 value rects_v)
2579 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2580 int xoff = Int_val (xoff_v);
2581 int yoff = Int_val (yoff_v);
2582 char *s = String_val (ptr_v);
2583 struct page *page = parse_pointer (__func__, s);
2585 drawprect (page, xoff, yoff, rects_v);
2586 CAMLreturn0;
2589 static struct annot *getannot (struct page *page, int x, int y)
2591 fz_point p;
2592 fz_matrix ctm;
2593 const fz_matrix *tctm;
2594 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2596 if (!page->annots) return NULL;
2598 if (pdf) {
2599 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2600 tctm = &state.pagedims[page->pdimno].tctm;
2602 else {
2603 tctm = &fz_identity;
2606 p.x = x;
2607 p.y = y;
2609 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2610 fz_invert_matrix (&ctm, &ctm);
2611 fz_transform_point (&p, &ctm);
2613 if (pdf) {
2614 for (int i = 0; i < page->annotcount; ++i) {
2615 struct annot *a = &page->annots[i];
2616 fz_rect rect;
2618 fz_bound_annot (state.ctx, a->annot, &rect);
2619 if (p.x >= rect.x0 && p.x <= rect.x1) {
2620 if (p.y >= rect.y0 && p.y <= rect.y1)
2621 return a;
2625 return NULL;
2628 static fz_link *getlink (struct page *page, int x, int y)
2630 fz_point p;
2631 fz_matrix ctm;
2632 fz_link *link;
2634 ensureslinks (page);
2636 p.x = x;
2637 p.y = y;
2639 ctm = pagectm (page);
2640 fz_invert_matrix (&ctm, &ctm);
2641 fz_transform_point (&p, &ctm);
2643 for (link = page->links; link; link = link->next) {
2644 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2645 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2646 return link;
2650 return NULL;
2653 static void ensuretext (struct page *page)
2655 if (state.gen != page->tgen) {
2656 droptext (page);
2657 page->tgen = state.gen;
2659 if (!page->text) {
2660 fz_matrix ctm;
2661 fz_device *tdev;
2663 page->text = fz_new_stext_page (state.ctx,
2664 &state.pagedims[page->pdimno].mediabox);
2665 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2666 ctm = pagectm (page);
2667 fz_run_display_list (state.ctx, page->dlist,
2668 tdev, &ctm, &fz_infinite_rect, NULL);
2669 fz_close_device (state.ctx, tdev);
2670 fz_drop_device (state.ctx, tdev);
2674 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2676 CAMLparam2 (start_page_v, dir_v);
2677 CAMLlocal1 (ret_v);
2678 int i, dir = Int_val (dir_v);
2679 int start_page = Int_val (start_page_v);
2680 int end_page = dir > 0 ? state.pagecount : -1;
2681 pdf_document *pdf;
2683 fz_var (end_page);
2684 ret_v = Val_int (0);
2685 lock (__func__);
2686 pdf = pdf_specifics (state.ctx, state.doc);
2687 for (i = start_page + dir; i != end_page; i += dir) {
2688 int found;
2690 fz_var (found);
2691 if (pdf) {
2692 pdf_page *page = NULL;
2694 fz_var (page);
2695 fz_try (state.ctx) {
2696 page = pdf_load_page (state.ctx, pdf, i);
2697 found = !!page->links || !!page->annots;
2699 fz_catch (state.ctx) {
2700 found = 0;
2702 if (page) {
2703 fz_drop_page (state.ctx, &page->super);
2706 else {
2707 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2708 fz_link *link = fz_load_links (state.ctx, page);
2709 found = !!link;
2710 fz_drop_link (state.ctx, link);
2711 fz_drop_page (state.ctx, page);
2714 if (found) {
2715 ret_v = caml_alloc_small (1, 1);
2716 Field (ret_v, 0) = Val_int (i);
2717 goto unlock;
2720 unlock:
2721 unlock (__func__);
2722 CAMLreturn (ret_v);
2725 enum { dir_first, dir_last };
2726 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2728 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2730 CAMLparam2 (ptr_v, dir_v);
2731 CAMLlocal2 (ret_v, pos_v);
2732 struct page *page;
2733 int dirtag, i, slinkindex;
2734 struct slink *found = NULL ,*slink;
2735 char *s = String_val (ptr_v);
2737 page = parse_pointer (__func__, s);
2738 ret_v = Val_int (0);
2739 lock (__func__);
2740 ensureslinks (page);
2742 if (Is_block (dir_v)) {
2743 dirtag = Tag_val (dir_v);
2744 switch (dirtag) {
2745 case dir_first_visible:
2747 int x0, y0, dir, first_index, last_index;
2749 pos_v = Field (dir_v, 0);
2750 x0 = Int_val (Field (pos_v, 0));
2751 y0 = Int_val (Field (pos_v, 1));
2752 dir = Int_val (Field (pos_v, 2));
2754 if (dir >= 0) {
2755 dir = 1;
2756 first_index = 0;
2757 last_index = page->slinkcount;
2759 else {
2760 first_index = page->slinkcount - 1;
2761 last_index = -1;
2764 for (i = first_index; i != last_index; i += dir) {
2765 slink = &page->slinks[i];
2766 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2767 found = slink;
2768 break;
2772 break;
2774 case dir_left:
2775 slinkindex = Int_val (Field (dir_v, 0));
2776 found = &page->slinks[slinkindex];
2777 for (i = slinkindex - 1; i >= 0; --i) {
2778 slink = &page->slinks[i];
2779 if (slink->bbox.x0 < found->bbox.x0) {
2780 found = slink;
2781 break;
2784 break;
2786 case dir_right:
2787 slinkindex = Int_val (Field (dir_v, 0));
2788 found = &page->slinks[slinkindex];
2789 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2790 slink = &page->slinks[i];
2791 if (slink->bbox.x0 > found->bbox.x0) {
2792 found = slink;
2793 break;
2796 break;
2798 case dir_down:
2799 slinkindex = Int_val (Field (dir_v, 0));
2800 found = &page->slinks[slinkindex];
2801 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2802 slink = &page->slinks[i];
2803 if (slink->bbox.y0 >= found->bbox.y0) {
2804 found = slink;
2805 break;
2808 break;
2810 case dir_up:
2811 slinkindex = Int_val (Field (dir_v, 0));
2812 found = &page->slinks[slinkindex];
2813 for (i = slinkindex - 1; i >= 0; --i) {
2814 slink = &page->slinks[i];
2815 if (slink->bbox.y0 <= found->bbox.y0) {
2816 found = slink;
2817 break;
2820 break;
2823 else {
2824 dirtag = Int_val (dir_v);
2825 switch (dirtag) {
2826 case dir_first:
2827 found = page->slinks;
2828 break;
2830 case dir_last:
2831 if (page->slinks) {
2832 found = page->slinks + (page->slinkcount - 1);
2834 break;
2837 if (found) {
2838 ret_v = caml_alloc_small (2, 1);
2839 Field (ret_v, 0) = Val_int (found - page->slinks);
2842 unlock (__func__);
2843 CAMLreturn (ret_v);
2846 enum { uuri, utext, uannot };
2848 CAMLprim value ml_getlink (value ptr_v, value n_v)
2850 CAMLparam2 (ptr_v, n_v);
2851 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2852 fz_link *link;
2853 struct page *page;
2854 char *s = String_val (ptr_v);
2855 struct slink *slink;
2857 ret_v = Val_int (0);
2858 page = parse_pointer (__func__, s);
2860 lock (__func__);
2861 ensureslinks (page);
2862 slink = &page->slinks[Int_val (n_v)];
2863 if (slink->tag == SLINK) {
2864 link = slink->u.link;
2865 str_v = caml_copy_string (link->uri);
2866 ret_v = caml_alloc_small (1, uuri);
2867 Field (ret_v, 0) = str_v;
2869 else {
2870 ret_v = caml_alloc_small (1, uannot);
2871 tup_v = caml_alloc_tuple (2);
2872 Field (ret_v, 0) = tup_v;
2873 Field (tup_v, 0) = ptr_v;
2874 Field (tup_v, 1) = n_v;
2876 unlock (__func__);
2878 CAMLreturn (ret_v);
2881 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2883 CAMLparam2 (ptr_v, n_v);
2884 CAMLlocal1 (ret_v);
2885 pdf_document *pdf;
2886 char *contents = NULL;
2888 lock (__func__);
2889 pdf = pdf_specifics (state.ctx, state.doc);
2890 if (pdf) {
2891 char *s = String_val (ptr_v);
2892 struct page *page;
2893 struct slink *slink;
2895 page = parse_pointer (__func__, s);
2896 slink = &page->slinks[Int_val (n_v)];
2897 contents = pdf_copy_annot_contents (state.ctx,
2898 (pdf_annot *) slink->u.annot);
2900 unlock (__func__);
2901 if (contents) {
2902 ret_v = caml_copy_string (contents);
2903 fz_free (state.ctx, contents);
2905 else {
2906 ret_v = caml_copy_string ("");
2908 CAMLreturn (ret_v);
2911 CAMLprim value ml_getlinkcount (value ptr_v)
2913 CAMLparam1 (ptr_v);
2914 struct page *page;
2915 char *s = String_val (ptr_v);
2917 page = parse_pointer (__func__, s);
2918 CAMLreturn (Val_int (page->slinkcount));
2921 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2923 CAMLparam2 (ptr_v, n_v);
2924 CAMLlocal1 (ret_v);
2925 struct page *page;
2926 struct slink *slink;
2927 char *s = String_val (ptr_v);
2929 page = parse_pointer (__func__, s);
2930 ret_v = caml_alloc_tuple (4);
2931 lock (__func__);
2932 ensureslinks (page);
2934 slink = &page->slinks[Int_val (n_v)];
2935 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2936 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2937 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2938 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2939 unlock (__func__);
2940 CAMLreturn (ret_v);
2943 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2945 CAMLparam3 (ptr_v, x_v, y_v);
2946 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2947 fz_link *link;
2948 struct annot *annot;
2949 struct page *page;
2950 char *ptr = String_val (ptr_v);
2951 int x = Int_val (x_v), y = Int_val (y_v);
2952 struct pagedim *pdim;
2954 ret_v = Val_int (0);
2955 if (trylock (__func__)) {
2956 goto done;
2959 page = parse_pointer (__func__, ptr);
2960 pdim = &state.pagedims[page->pdimno];
2961 x += pdim->bounds.x0;
2962 y += pdim->bounds.y0;
2965 annot = getannot (page, x, y);
2966 if (annot) {
2967 int i, n = -1;
2969 ensureslinks (page);
2970 for (i = 0; i < page->slinkcount; ++i) {
2971 if (page->slinks[i].tag == SANNOT
2972 && page->slinks[i].u.annot == annot->annot) {
2973 n = i;
2974 break;
2977 ret_v = caml_alloc_small (1, uannot);
2978 tup_v = caml_alloc_tuple (2);
2979 Field (ret_v, 0) = tup_v;
2980 Field (tup_v, 0) = ptr_v;
2981 Field (tup_v, 1) = Val_int (n);
2982 goto unlock;
2986 link = getlink (page, x, y);
2987 if (link) {
2988 str_v = caml_copy_string (link->uri);
2989 ret_v = caml_alloc_small (1, uuri);
2990 Field (ret_v, 0) = str_v;
2992 else {
2993 fz_rect *b;
2994 fz_stext_block *block;
2996 ensuretext (page);
2998 for (block = page->text->first_block; block; block = block->next) {
2999 fz_stext_line *line;
3001 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3002 b = &block->bbox;
3003 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3004 continue;
3006 for (line = block->u.t.first_line; line; line = line->next) {
3007 fz_stext_char *ch;
3009 b = &line->bbox;
3010 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3011 continue;
3013 for (ch = line->first_char; ch; ch = ch->next) {
3014 b = &ch->bbox;
3016 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3017 const char *n2 = fz_font_name (state.ctx, ch->font);
3018 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3019 ch->font);
3021 if (!n2) n2 = "<unknown font>";
3023 if (face && face->family_name) {
3024 char *s;
3025 char *n1 = face->family_name;
3026 size_t l1 = strlen (n1);
3027 size_t l2 = strlen (n2);
3029 if (l1 != l2 || memcmp (n1, n2, l1)) {
3030 s = malloc (l1 + l2 + 2);
3031 if (s) {
3032 memcpy (s, n2, l2);
3033 s[l2] = '=';
3034 memcpy (s + l2 + 1, n1, l1 + 1);
3035 str_v = caml_copy_string (s);
3036 free (s);
3040 if (str_v == Val_unit) {
3041 str_v = caml_copy_string (n2);
3043 ret_v = caml_alloc_small (1, utext);
3044 Field (ret_v, 0) = str_v;
3045 goto unlock;
3051 unlock:
3052 unlock (__func__);
3054 done:
3055 CAMLreturn (ret_v);
3058 enum { mark_page, mark_block, mark_line, mark_word };
3060 static int uninteresting (int c)
3062 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3063 || ispunct (c);
3066 CAMLprim void ml_clearmark (value ptr_v)
3068 CAMLparam1 (ptr_v);
3069 char *s = String_val (ptr_v);
3070 struct page *page;
3072 if (trylock (__func__)) {
3073 goto done;
3076 page = parse_pointer (__func__, s);
3077 page->fmark.ch = NULL;
3078 page->lmark.ch = NULL;
3080 unlock (__func__);
3081 done:
3082 CAMLreturn0;
3085 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3087 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3088 CAMLlocal1 (ret_v);
3089 fz_rect *b;
3090 struct page *page;
3091 fz_stext_line *line;
3092 fz_stext_block *block;
3093 struct pagedim *pdim;
3094 int mark = Int_val (mark_v);
3095 char *s = String_val (ptr_v);
3096 int x = Int_val (x_v), y = Int_val (y_v);
3098 ret_v = Val_bool (0);
3099 if (trylock (__func__)) {
3100 goto done;
3103 page = parse_pointer (__func__, s);
3104 pdim = &state.pagedims[page->pdimno];
3106 ensuretext (page);
3108 if (mark == mark_page) {
3109 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3110 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3111 ret_v = Val_bool (1);
3112 goto unlock;
3115 x += pdim->bounds.x0;
3116 y += pdim->bounds.y0;
3118 for (block = page->text->first_block; block; block = block->next) {
3119 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3120 b = &block->bbox;
3121 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3122 continue;
3124 if (mark == mark_block) {
3125 page->fmark.ch = block->u.t.first_line->first_char;
3126 page->lmark.ch = block->u.t.last_line->last_char;
3127 ret_v = Val_bool (1);
3128 goto unlock;
3131 for (line = block->u.t.first_line; line; line = line->next) {
3132 fz_stext_char *ch;
3134 b = &line->bbox;
3135 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3136 continue;
3138 if (mark == mark_line) {
3139 page->fmark.ch = line->first_char;
3140 page->lmark.ch = line->last_char;
3141 ret_v = Val_bool (1);
3142 goto unlock;
3145 for (ch = line->first_char; ch; ch = ch->next) {
3146 fz_stext_char *ch2, *first = NULL, *last = NULL;
3147 b = &ch->bbox;
3148 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3149 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3150 if (uninteresting (ch2->c)) first = NULL;
3151 else if (!first) first = ch2;
3153 for (ch2 = ch; ch2; ch2 = ch2->next) {
3154 if (uninteresting (ch2->c)) break;
3155 last = ch2;
3158 page->fmark.ch = first;
3159 page->lmark.ch = last;
3160 ret_v = Val_bool (1);
3161 goto unlock;
3166 unlock:
3167 if (!Bool_val (ret_v)) {
3168 page->fmark.ch = NULL;
3169 page->lmark.ch = NULL;
3171 unlock (__func__);
3173 done:
3174 CAMLreturn (ret_v);
3177 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3179 CAMLparam3 (ptr_v, x_v, y_v);
3180 CAMLlocal2 (ret_v, res_v);
3181 fz_rect *b = NULL;
3182 struct page *page;
3183 struct pagedim *pdim;
3184 fz_stext_block *block;
3185 char *s = String_val (ptr_v);
3186 int x = Int_val (x_v), y = Int_val (y_v);
3188 ret_v = Val_int (0);
3189 if (trylock (__func__)) {
3190 goto done;
3193 page = parse_pointer (__func__, s);
3194 pdim = &state.pagedims[page->pdimno];
3195 x += pdim->bounds.x0;
3196 y += pdim->bounds.y0;
3198 ensuretext (page);
3200 for (block = page->text->first_block; block; block = block->next) {
3201 switch (block->type) {
3202 case FZ_STEXT_BLOCK_TEXT:
3203 b = &block->bbox;
3204 break;
3206 case FZ_STEXT_BLOCK_IMAGE:
3207 b = &block->bbox;
3208 break;
3210 default:
3211 continue;
3214 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3215 break;
3216 b = NULL;
3218 if (b) {
3219 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3220 ret_v = caml_alloc_small (1, 1);
3221 Store_double_field (res_v, 0, (double) b->x0);
3222 Store_double_field (res_v, 1, (double) b->x1);
3223 Store_double_field (res_v, 2, (double) b->y0);
3224 Store_double_field (res_v, 3, (double) b->y1);
3225 Field (ret_v, 0) = res_v;
3227 unlock (__func__);
3229 done:
3230 CAMLreturn (ret_v);
3233 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3235 CAMLparam2 (ptr_v, rect_v);
3236 fz_rect b;
3237 struct page *page;
3238 struct pagedim *pdim;
3239 char *s = String_val (ptr_v);
3240 int x0, x1, y0, y1;
3241 fz_stext_char *ch;
3242 fz_stext_line *line;
3243 fz_stext_block *block;
3244 fz_stext_char *fc, *lc;
3246 if (trylock (__func__)) {
3247 goto done;
3250 page = parse_pointer (__func__, s);
3251 ensuretext (page);
3253 pdim = &state.pagedims[page->pdimno];
3254 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3255 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3256 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3257 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3259 if (y0 > y1) {
3260 int t = y0;
3261 y0 = y1;
3262 y1 = t;
3263 x0 = x1;
3264 x1 = t;
3267 fc = page->fmark.ch;
3268 lc = page->lmark.ch;
3270 for (block = page->text->first_block; block; block = block->next) {
3271 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3272 for (line = block->u.t.first_line; line; line = line->next) {
3273 for (ch = line->first_char; ch; ch = ch->next) {
3274 b = ch->bbox;
3275 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3276 fc = ch;
3278 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3279 lc = ch;
3284 if (x1 < x0 && fc == lc) {
3285 fz_stext_char *t;
3287 t = fc;
3288 fc = lc;
3289 lc = t;
3292 page->fmark.ch = fc;
3293 page->lmark.ch = lc;
3295 unlock (__func__);
3297 done:
3298 CAMLreturn0;
3301 static int pipechar (FILE *f, fz_stext_char *ch)
3303 char buf[4];
3304 int len;
3305 size_t ret;
3307 len = fz_runetochar (buf, ch->c);
3308 ret = fwrite (buf, len, 1, f);
3309 if (ret != 1) {
3310 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3311 len, ret, errno, strerror (errno));
3312 return -1;
3314 return 0;
3317 CAMLprim value ml_spawn (value command_v, value fds_v)
3319 CAMLparam2 (command_v, fds_v);
3320 CAMLlocal2 (l_v, tup_v);
3321 int ret, ret1;
3322 pid_t pid = (pid_t) -1;
3323 char *msg = NULL;
3324 value earg_v = Nothing;
3325 posix_spawnattr_t attr;
3326 posix_spawn_file_actions_t fa;
3327 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3329 argv[2] = String_val (command_v);
3331 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3332 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3335 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3336 msg = "posix_spawnattr_init";
3337 goto fail1;
3340 #ifdef POSIX_SPAWN_USEVFORK
3341 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3342 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3343 goto fail;
3345 #endif
3347 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3348 int fd1, fd2;
3350 tup_v = Field (l_v, 0);
3351 fd1 = Int_val (Field (tup_v, 0));
3352 fd2 = Int_val (Field (tup_v, 1));
3353 if (fd2 < 0) {
3354 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3355 msg = "posix_spawn_file_actions_addclose";
3356 earg_v = tup_v;
3357 goto fail;
3360 else {
3361 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3362 msg = "posix_spawn_file_actions_adddup2";
3363 earg_v = tup_v;
3364 goto fail;
3369 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3370 msg = "posix_spawn";
3371 goto fail;
3374 fail:
3375 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3376 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3379 fail1:
3380 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3381 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3382 ret1, strerror (ret1));
3385 if (msg)
3386 unix_error (ret, msg, earg_v);
3388 CAMLreturn (Val_int (pid));
3391 CAMLprim value ml_hassel (value ptr_v)
3393 CAMLparam1 (ptr_v);
3394 CAMLlocal1 (ret_v);
3395 struct page *page;
3396 char *s = String_val (ptr_v);
3398 ret_v = Val_bool (0);
3399 if (trylock (__func__)) {
3400 goto done;
3403 page = parse_pointer (__func__, s);
3404 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3405 unlock (__func__);
3406 done:
3407 CAMLreturn (ret_v);
3410 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3412 CAMLparam2 (fd_v, ptr_v);
3413 FILE *f;
3414 int seen = 0;
3415 struct page *page;
3416 fz_stext_line *line;
3417 fz_stext_block *block;
3418 int fd = Int_val (fd_v);
3419 char *s = String_val (ptr_v);
3421 if (trylock (__func__)) {
3422 goto done;
3425 page = parse_pointer (__func__, s);
3427 if (!page->fmark.ch || !page->lmark.ch) {
3428 printd ("emsg nothing to copy on page %d", page->pageno);
3429 goto unlock;
3432 f = fdopen (fd, "w");
3433 if (!f) {
3434 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3435 fd, errno, strerror (errno));
3436 f = stdout;
3439 for (block = page->text->first_block; block; block = block->next) {
3440 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3441 for (line = block->u.t.first_line; line; line = line->next) {
3442 fz_stext_char *ch;
3443 for (ch = line->first_char; ch; ch = ch->next) {
3444 if (seen || ch == page->fmark.ch) {
3445 do {
3446 pipechar (f, ch);
3447 if (ch == page->lmark.ch) goto close;
3448 } while ((ch = ch->next));
3449 seen = 1;
3450 break;
3453 if (seen) fputc ('\n', f);
3456 close:
3457 if (f != stdout) {
3458 int ret = fclose (f);
3459 fd = -1;
3460 if (ret == -1) {
3461 if (errno != ECHILD) {
3462 printd ("emsg failed to close sel pipe: %d:%s",
3463 errno, strerror (errno));
3467 unlock:
3468 unlock (__func__);
3470 done:
3471 if (fd >= 0) {
3472 if (close (fd)) {
3473 printd ("emsg failed to close sel pipe: %d:%s",
3474 errno, strerror (errno));
3477 CAMLreturn0;
3480 CAMLprim value ml_getpdimrect (value pagedimno_v)
3482 CAMLparam1 (pagedimno_v);
3483 CAMLlocal1 (ret_v);
3484 int pagedimno = Int_val (pagedimno_v);
3485 fz_rect box;
3487 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3488 if (trylock (__func__)) {
3489 box = fz_empty_rect;
3491 else {
3492 box = state.pagedims[pagedimno].mediabox;
3493 unlock (__func__);
3496 Store_double_field (ret_v, 0, (double) box.x0);
3497 Store_double_field (ret_v, 1, (double) box.x1);
3498 Store_double_field (ret_v, 2, (double) box.y0);
3499 Store_double_field (ret_v, 3, (double) box.y1);
3501 CAMLreturn (ret_v);
3504 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3505 value dw_v, value cols_v)
3507 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3508 CAMLlocal1 (ret_v);
3509 int i;
3510 float zoom = -1.;
3511 float maxh = 0.0;
3512 struct pagedim *p;
3513 float winw = Int_val (winw_v);
3514 float winh = Int_val (winh_v);
3515 float dw = Int_val (dw_v);
3516 float cols = Int_val (cols_v);
3517 float pw = 1.0, ph = 1.0;
3519 if (trylock (__func__)) {
3520 goto done;
3523 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3524 float w = p->pagebox.x1 / cols;
3525 float h = p->pagebox.y1;
3526 if (h > maxh) {
3527 maxh = h;
3528 ph = h;
3529 if (state.fitmodel != FitProportional) pw = w;
3531 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3534 zoom = (((winh / ph) * pw) + dw) / winw;
3535 unlock (__func__);
3536 done:
3537 ret_v = caml_copy_double ((double) zoom);
3538 CAMLreturn (ret_v);
3541 CAMLprim value ml_getmaxw (value unit_v)
3543 CAMLparam1 (unit_v);
3544 CAMLlocal1 (ret_v);
3545 int i;
3546 float maxw = -1.;
3547 struct pagedim *p;
3549 if (trylock (__func__)) {
3550 goto done;
3553 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3554 float w = p->pagebox.x1;
3555 maxw = fz_max (maxw, w);
3558 unlock (__func__);
3559 done:
3560 ret_v = caml_copy_double ((double) maxw);
3561 CAMLreturn (ret_v);
3564 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3566 CAMLparam4 (pt_v, x_v, y_v, string_v);
3567 CAMLlocal1 (ret_v);
3568 int pt = Int_val(pt_v);
3569 int x = Int_val (x_v);
3570 int y = Int_val (y_v);
3571 double w;
3573 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3574 ret_v = caml_copy_double (w);
3575 CAMLreturn (ret_v);
3578 CAMLprim value ml_measure_string (value pt_v, value string_v)
3580 CAMLparam2 (pt_v, string_v);
3581 CAMLlocal1 (ret_v);
3582 int pt = Int_val (pt_v);
3583 double w;
3585 w = (double) measure_string (state.face, pt, String_val (string_v));
3586 ret_v = caml_copy_double (w);
3587 CAMLreturn (ret_v);
3590 CAMLprim value ml_getpagebox (value opaque_v)
3592 CAMLparam1 (opaque_v);
3593 CAMLlocal1 (ret_v);
3594 fz_rect rect;
3595 fz_irect bbox;
3596 fz_matrix ctm;
3597 fz_device *dev;
3598 char *s = String_val (opaque_v);
3599 struct page *page = parse_pointer (__func__, s);
3601 ret_v = caml_alloc_tuple (4);
3602 dev = fz_new_bbox_device (state.ctx, &rect);
3604 ctm = pagectm (page);
3605 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3607 fz_close_device (state.ctx, dev);
3608 fz_drop_device (state.ctx, dev);
3609 fz_round_rect (&bbox, &rect);
3610 Field (ret_v, 0) = Val_int (bbox.x0);
3611 Field (ret_v, 1) = Val_int (bbox.y0);
3612 Field (ret_v, 2) = Val_int (bbox.x1);
3613 Field (ret_v, 3) = Val_int (bbox.y1);
3615 CAMLreturn (ret_v);
3618 CAMLprim void ml_setaalevel (value level_v)
3620 CAMLparam1 (level_v);
3622 state.aalevel = Int_val (level_v);
3623 CAMLreturn0;
3626 #ifndef __COCOA__
3627 #pragma GCC diagnostic push
3628 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3629 #include <X11/Xlib.h>
3630 #include <X11/cursorfont.h>
3631 #pragma GCC diagnostic pop
3633 #ifdef USE_EGL
3634 #include <EGL/egl.h>
3635 #else
3636 #include <GL/glx.h>
3637 #endif
3639 static const int shapes[] = {
3640 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3643 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3645 static struct {
3646 Window wid;
3647 Display *dpy;
3648 #ifdef USE_EGL
3649 EGLContext ctx;
3650 EGLConfig conf;
3651 EGLSurface win;
3652 EGLDisplay *edpy;
3653 #else
3654 GLXContext ctx;
3655 #endif
3656 XVisualInfo *visual;
3657 Cursor curs[CURS_COUNT];
3658 } glx;
3661 static void initcurs (void)
3663 for (size_t n = 0; n < CURS_COUNT; ++n) {
3664 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3668 #ifdef USE_EGL
3669 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3671 CAMLparam3 (display_v, wid_v, screen_v);
3672 int major, minor;
3673 int num_conf;
3674 EGLint visid;
3675 EGLint attribs[] = {
3676 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3677 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3678 EGL_NONE
3680 EGLConfig conf;
3682 glx.dpy = XOpenDisplay (String_val (display_v));
3683 if (!glx.dpy) {
3684 caml_failwith ("XOpenDisplay");
3687 eglBindAPI (EGL_OPENGL_API);
3689 glx.edpy = eglGetDisplay (glx.dpy);
3690 if (glx.edpy == EGL_NO_DISPLAY) {
3691 caml_failwith ("eglGetDisplay");
3694 if (!eglInitialize (glx.edpy, &major, &minor)) {
3695 caml_failwith ("eglInitialize");
3698 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3699 !num_conf) {
3700 caml_failwith ("eglChooseConfig");
3703 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3704 caml_failwith ("eglGetConfigAttrib");
3707 glx.conf = conf;
3708 initcurs ();
3710 glx.wid = Int_val (wid_v);
3711 CAMLreturn (Val_int (visid));
3714 CAMLprim void ml_glxcompleteinit (value unit_v)
3716 CAMLparam1 (unit_v);
3718 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3719 if (!glx.ctx) {
3720 caml_failwith ("eglCreateContext");
3723 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3724 glx.wid, NULL);
3725 if (glx.win == EGL_NO_SURFACE) {
3726 caml_failwith ("eglCreateWindowSurface");
3729 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3730 glx.ctx = NULL;
3731 caml_failwith ("eglMakeCurrent");
3733 CAMLreturn0;
3735 #else
3736 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3738 CAMLparam3 (display_v, wid_v, screen_v);
3740 glx.dpy = XOpenDisplay (String_val (display_v));
3741 if (!glx.dpy) {
3742 caml_failwith ("XOpenDisplay");
3745 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3746 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3747 if (!glx.visual) {
3748 XCloseDisplay (glx.dpy);
3749 caml_failwith ("glXChooseVisual");
3752 initcurs ();
3754 glx.wid = Int_val (wid_v);
3755 CAMLreturn (Val_int (glx.visual->visualid));
3758 CAMLprim void ml_glxcompleteinit (value unit_v)
3760 CAMLparam1 (unit_v);
3762 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3763 if (!glx.ctx) {
3764 caml_failwith ("glXCreateContext");
3767 XFree (glx.visual);
3768 glx.visual = NULL;
3770 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3771 glXDestroyContext (glx.dpy, glx.ctx);
3772 glx.ctx = NULL;
3773 caml_failwith ("glXMakeCurrent");
3775 CAMLreturn0;
3777 #endif
3779 CAMLprim void ml_setcursor (value cursor_v)
3781 CAMLparam1 (cursor_v);
3782 size_t cursn = Int_val (cursor_v);
3784 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3785 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3786 XFlush (glx.dpy);
3787 CAMLreturn0;
3790 CAMLprim void ml_swapb (value unit_v)
3792 CAMLparam1 (unit_v);
3793 #ifdef USE_EGL
3794 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3795 caml_failwith ("eglSwapBuffers");
3797 #else
3798 glXSwapBuffers (glx.dpy, glx.wid);
3799 #endif
3800 CAMLreturn0;
3803 #pragma GCC diagnostic push
3804 #ifdef __clang__
3805 #pragma GCC diagnostic ignored "-Wmissing-variable-declarations"
3806 #endif
3807 #include "keysym2ucs.c"
3808 #pragma GCC diagnostic pop
3810 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3812 CAMLparam1 (keysym_v);
3813 CAMLlocal1 (str_v);
3814 KeySym keysym = Int_val (keysym_v);
3815 Rune rune;
3816 int len;
3817 char buf[5];
3819 rune = (Rune) keysym2ucs (keysym);
3820 len = fz_runetochar (buf, rune);
3821 buf[len] = 0;
3822 str_v = caml_copy_string (buf);
3823 CAMLreturn (str_v);
3825 #else
3826 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3828 CAMLparam1 (keysym_v);
3829 CAMLlocal1 (str_v);
3830 long ucs_v = Long_val (keysym_v);
3831 int len;
3832 char buf[5];
3834 len = fz_runetochar (buf, ucs_v);
3835 buf[len] = 0;
3836 str_v = caml_copy_string (buf);
3837 CAMLreturn (str_v);
3839 #endif
3841 enum { piunknown, pilinux, piosx, pisun, pibsd };
3843 CAMLprim value ml_platform (value unit_v)
3845 CAMLparam1 (unit_v);
3846 CAMLlocal2 (tup_v, arr_v);
3847 int platid = piunknown;
3848 struct utsname buf;
3850 #if defined __linux__
3851 platid = pilinux;
3852 #elif defined __DragonFly__ || defined __FreeBSD__
3853 || defined __OpenBSD__ || defined __NetBSD__
3854 platid = pibsd;
3855 #elif defined __sun__
3856 platid = pisun;
3857 #elif defined __APPLE__
3858 platid = piosx;
3859 #endif
3860 if (uname (&buf)) err (1, "uname");
3862 tup_v = caml_alloc_tuple (2);
3864 char const *sar[] = {
3865 buf.sysname,
3866 buf.release,
3867 buf.version,
3868 buf.machine,
3869 NULL
3871 arr_v = caml_copy_string_array (sar);
3873 Field (tup_v, 0) = Val_int (platid);
3874 Field (tup_v, 1) = arr_v;
3875 CAMLreturn (tup_v);
3878 CAMLprim void ml_cloexec (value fd_v)
3880 CAMLparam1 (fd_v);
3881 int fd = Int_val (fd_v);
3883 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3884 uerror ("fcntl", Nothing);
3886 CAMLreturn0;
3889 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3891 CAMLparam2 (w_v, h_v);
3892 CAMLlocal1 (ret_v);
3893 struct bo *pbo;
3894 int w = Int_val (w_v);
3895 int h = Int_val (h_v);
3896 int cs = Int_val (cs_v);
3898 if (state.bo_usable) {
3899 pbo = calloc (sizeof (*pbo), 1);
3900 if (!pbo) {
3901 err (1, "calloc pbo");
3904 switch (cs) {
3905 case 0:
3906 case 1:
3907 pbo->size = w*h*4;
3908 break;
3909 case 2:
3910 pbo->size = w*h*2;
3911 break;
3912 default:
3913 errx (1, "%s: invalid colorspace %d", __func__, cs);
3916 state.glGenBuffersARB (1, &pbo->id);
3917 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3918 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3919 NULL, GL_STREAM_DRAW);
3920 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3921 GL_READ_WRITE);
3922 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3923 if (!pbo->ptr) {
3924 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3925 state.glDeleteBuffersARB (1, &pbo->id);
3926 free (pbo);
3927 ret_v = caml_copy_string ("0");
3929 else {
3930 int res;
3931 char *s;
3933 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3934 if (res < 0) {
3935 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3937 s = malloc (res+1);
3938 if (!s) {
3939 err (1, "malloc %d bytes failed", res+1);
3941 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3942 if (res < 0) {
3943 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3945 ret_v = caml_copy_string (s);
3946 free (s);
3949 else {
3950 ret_v = caml_copy_string ("0");
3952 CAMLreturn (ret_v);
3955 CAMLprim void ml_freepbo (value s_v)
3957 CAMLparam1 (s_v);
3958 char *s = String_val (s_v);
3959 struct tile *tile = parse_pointer (__func__, s);
3961 if (tile->pbo) {
3962 state.glDeleteBuffersARB (1, &tile->pbo->id);
3963 tile->pbo->id = -1;
3964 tile->pbo->ptr = NULL;
3965 tile->pbo->size = -1;
3967 CAMLreturn0;
3970 CAMLprim void ml_unmappbo (value s_v)
3972 CAMLparam1 (s_v);
3973 char *s = String_val (s_v);
3974 struct tile *tile = parse_pointer (__func__, s);
3976 if (tile->pbo) {
3977 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3978 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3979 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3981 tile->pbo->ptr = NULL;
3982 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3984 CAMLreturn0;
3987 static void setuppbo (void)
3989 #ifdef __COCOA__
3990 static CFBundleRef framework = NULL;
3991 if (framework == NULL)
3992 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3993 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3994 #else
3995 #ifdef USE_EGL
3996 #define GGPA(n) (*(void (**) (void)) &state.n = eglGetProcAddress (#n))
3997 #else
3998 #define GGPA(n) (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
3999 #endif
4000 state.bo_usable = GGPA (glBindBufferARB)
4001 && GGPA (glUnmapBufferARB)
4002 && GGPA (glMapBufferARB)
4003 && GGPA (glBufferDataARB)
4004 && GGPA (glGenBuffersARB)
4005 && GGPA (glDeleteBuffersARB);
4006 #endif
4007 #undef GGPA
4010 CAMLprim value ml_bo_usable (value unit_v)
4012 CAMLparam1 (unit_v);
4013 CAMLreturn (Val_bool (state.bo_usable));
4016 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4018 CAMLparam3 (ptr_v, x_v, y_v);
4019 CAMLlocal2 (ret_v, tup_v);
4020 struct page *page;
4021 char *s = String_val (ptr_v);
4022 int x = Int_val (x_v), y = Int_val (y_v);
4023 struct pagedim *pdim;
4024 fz_point p;
4025 fz_matrix ctm;
4027 page = parse_pointer (__func__, s);
4028 pdim = &state.pagedims[page->pdimno];
4030 ret_v = Val_int (0);
4031 if (trylock (__func__)) {
4032 goto done;
4035 if (pdf_specifics (state.ctx, state.doc)) {
4036 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4037 ctm = state.pagedims[page->pdimno].tctm;
4039 else {
4040 ctm = fz_identity;
4042 p.x = x + pdim->bounds.x0;
4043 p.y = y + pdim->bounds.y0;
4045 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4046 fz_invert_matrix (&ctm, &ctm);
4047 fz_transform_point (&p, &ctm);
4049 tup_v = caml_alloc_tuple (2);
4050 ret_v = caml_alloc_small (1, 1);
4051 Field (tup_v, 0) = Val_int (p.x);
4052 Field (tup_v, 1) = Val_int (p.y);
4053 Field (ret_v, 0) = tup_v;
4055 unlock (__func__);
4056 done:
4057 CAMLreturn (ret_v);
4060 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4061 value x_v, value y_v)
4063 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4064 CAMLlocal1 (ret_v);
4065 struct page *page;
4066 char *s = String_val (ptr_v);
4067 int pageno = Int_val (pageno_v);
4068 int pdimno = Int_val (pdimno_v);
4069 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
4070 struct pagedim *pdim;
4071 fz_point p;
4072 fz_matrix ctm;
4074 ret_v = Val_int (0);
4075 lock (__func__);
4077 if (!*s) {
4078 page = loadpage (pageno, pdimno);
4080 else {
4081 page = parse_pointer (__func__, s);
4083 pdim = &state.pagedims[pdimno];
4085 if (pdf_specifics (state.ctx, state.doc)) {
4086 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4087 ctm = state.pagedims[page->pdimno].tctm;
4089 else {
4090 ctm = fz_identity;
4092 p.x = x + pdim->bounds.x0;
4093 p.y = y + pdim->bounds.y0;
4095 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4096 fz_transform_point (&p, &ctm);
4098 ret_v = caml_alloc_tuple (2);
4099 Field (ret_v, 0) = caml_copy_double ((double) p.x);
4100 Field (ret_v, 1) = caml_copy_double ((double) p.y);
4102 if (!*s) {
4103 freepage (page);
4105 unlock (__func__);
4106 CAMLreturn (ret_v);
4109 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4110 value contents_v)
4112 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4113 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4115 if (pdf) {
4116 pdf_annot *annot;
4117 struct page *page;
4118 fz_point p;
4119 char *s = String_val (ptr_v);
4121 page = parse_pointer (__func__, s);
4122 annot = pdf_create_annot (state.ctx,
4123 pdf_page_from_fz_page (state.ctx,
4124 page->fzpage),
4125 PDF_ANNOT_TEXT);
4126 p.x = Int_val (x_v);
4127 p.y = Int_val (y_v);
4128 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4129 pdf_set_text_annot_position (state.ctx, annot, p);
4130 state.dirty = 1;
4132 CAMLreturn0;
4135 CAMLprim void ml_delannot (value ptr_v, value n_v)
4137 CAMLparam2 (ptr_v, n_v);
4138 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4140 if (pdf) {
4141 struct page *page;
4142 char *s = String_val (ptr_v);
4143 struct slink *slink;
4145 page = parse_pointer (__func__, s);
4146 slink = &page->slinks[Int_val (n_v)];
4147 pdf_delete_annot (state.ctx,
4148 pdf_page_from_fz_page (state.ctx, page->fzpage),
4149 (pdf_annot *) slink->u.annot);
4150 state.dirty = 1;
4152 CAMLreturn0;
4155 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4157 CAMLparam3 (ptr_v, n_v, str_v);
4158 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4160 if (pdf) {
4161 struct page *page;
4162 char *s = String_val (ptr_v);
4163 struct slink *slink;
4165 page = parse_pointer (__func__, s);
4166 slink = &page->slinks[Int_val (n_v)];
4167 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4168 String_val (str_v));
4169 state.dirty = 1;
4171 CAMLreturn0;
4174 CAMLprim value ml_hasunsavedchanges (value unit_v)
4176 CAMLparam1 (unit_v);
4177 CAMLreturn (Val_bool (state.dirty));
4180 CAMLprim void ml_savedoc (value path_v)
4182 CAMLparam1 (path_v);
4183 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4185 if (pdf) {
4186 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4188 CAMLreturn0;
4191 static void makestippletex (void)
4193 const char pixels[] = "\xff\xff\0\0";
4194 glGenTextures (1, &state.stid);
4195 glBindTexture (GL_TEXTURE_1D, state.stid);
4196 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4197 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4198 glTexImage1D (
4199 GL_TEXTURE_1D,
4201 GL_ALPHA,
4204 GL_ALPHA,
4205 GL_UNSIGNED_BYTE,
4206 pixels
4210 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4212 return caml_copy_string (FZ_VERSION);
4215 CAMLprim void ml_init (value csock_v, value params_v)
4217 CAMLparam2 (csock_v, params_v);
4218 CAMLlocal2 (trim_v, fuzz_v);
4219 int ret;
4220 int texcount;
4221 char *fontpath;
4222 int colorspace;
4223 int mustoresize;
4224 int haspboext;
4226 state.csock = Int_val (csock_v);
4227 state.rotate = Int_val (Field (params_v, 0));
4228 state.fitmodel = Int_val (Field (params_v, 1));
4229 trim_v = Field (params_v, 2);
4230 texcount = Int_val (Field (params_v, 3));
4231 state.sliceheight = Int_val (Field (params_v, 4));
4232 mustoresize = Int_val (Field (params_v, 5));
4233 colorspace = Int_val (Field (params_v, 6));
4234 fontpath = String_val (Field (params_v, 7));
4236 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
4237 if (setlocale (LC_CTYPE, "")) {
4238 const char *cset = nl_langinfo (CODESET);
4239 state.utf8cs = !strcmp (cset, "UTF-8");
4241 else {
4242 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
4245 if (caml_string_length (Field (params_v, 8)) > 0) {
4246 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4248 if (!state.trimcachepath) {
4249 printd ("emsg failed to strdup trimcachepath: %d:%s",
4250 errno, strerror (errno));
4254 haspboext = Bool_val (Field (params_v, 9));
4256 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4257 fz_register_document_handlers (state.ctx);
4259 state.trimmargins = Bool_val (Field (trim_v, 0));
4260 fuzz_v = Field (trim_v, 1);
4261 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4262 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4263 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4264 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4266 set_tex_params (colorspace);
4268 if (*fontpath) {
4269 state.face = load_font (fontpath);
4271 else {
4272 int len;
4273 const unsigned char *data;
4275 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4276 state.face = load_builtin_font (data, len);
4278 if (!state.face) _exit (1);
4280 realloctexts (texcount);
4282 if (haspboext) {
4283 setuppbo ();
4286 makestippletex ();
4288 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4289 if (ret) {
4290 errx (1, "pthread_create: %s", strerror (ret));
4293 CAMLreturn0;
4296 #if FIXME || !FIXME
4297 static void OPTIMIZE_ATTR (0) UNUSED_ATTR refmacs (void) {}
4298 #endif