Use proper reporting functions
[llpp.git] / link.c
blobccc34e0c0c8fbd701b7d1f895a9c93f9a5468ff6
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 <wchar.h>
13 #include <locale.h>
14 #include <langinfo.h>
16 #include <unistd.h>
17 #include <pthread.h>
18 #include <sys/uio.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/ioctl.h>
22 #include <sys/utsname.h>
24 #ifdef __CYGWIN__
25 #include <cygwin/socket.h> /* FIONREAD */
26 #else
27 #include <spawn.h>
28 #endif
30 #include <regex.h>
31 #include <stdarg.h>
32 #include <limits.h>
33 #include <inttypes.h>
35 #ifdef __COCOA__
36 #include <CoreFoundation/CoreFoundation.h>
37 #endif
39 #ifdef __APPLE__
40 #include <OpenGL/gl.h>
41 #else
42 #include <GL/gl.h>
43 #endif
45 #include <caml/fail.h>
46 #include <caml/alloc.h>
47 #include <caml/memory.h>
48 #include <caml/unixsupport.h>
50 #if __GNUC__ < 5 && !defined __clang__
51 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
52 clobbered diagnostics */
53 #pragma GCC diagnostic ignored "-Wclobbered"
54 #endif
56 #pragma GCC diagnostic push
57 #pragma GCC diagnostic ignored "-Wunused-parameter"
58 #include <mupdf/fitz.h>
59 #include <mupdf/pdf.h>
60 #pragma GCC diagnostic pop
62 #include <ft2build.h>
63 #include FT_FREETYPE_H
65 #define PIGGYBACK
66 #define CACHE_PAGEREFS
68 #ifndef __USE_GNU
69 extern char **environ;
70 #endif
72 #if defined __GNUC__
73 #define NORETURN_ATTR __attribute__ ((noreturn))
74 #define UNUSED_ATTR __attribute__ ((unused))
75 #if !defined __clang__
76 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
77 #else
78 #define OPTIMIZE_ATTR(n)
79 #endif
80 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
81 #else
82 #define NORETURN_ATTR
83 #define UNUSED_ATTR
84 #define OPTIMIZE_ATTR(n)
85 #define GCC_FMT_ATTR(a, b)
86 #endif
88 #define FMT_s "zu"
90 #define FMT_ptr PRIxPTR
91 #define SCN_ptr SCNxPTR
92 #define FMT_ptr_cast(p) ((uintptr_t) (p))
93 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
95 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
96 err (int exitcode, const char *fmt, ...)
98 va_list ap;
99 int savederrno;
101 savederrno = errno;
102 va_start (ap, fmt);
103 vfprintf (stderr, fmt, ap);
104 va_end (ap);
105 fprintf (stderr, ": %s\n", strerror (savederrno));
106 fflush (stderr);
107 _exit (exitcode);
110 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
111 errx (int exitcode, const char *fmt, ...)
113 va_list ap;
115 va_start (ap, fmt);
116 vfprintf (stderr, fmt, ap);
117 va_end (ap);
118 fputc ('\n', stderr);
119 fflush (stderr);
120 _exit (exitcode);
123 #ifndef GL_TEXTURE_RECTANGLE_ARB
124 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
125 #endif
127 #ifdef USE_NPOT
128 #define TEXT_TYPE GL_TEXTURE_2D
129 #else
130 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
131 #endif
133 #ifndef GL_BGRA
134 #define GL_BGRA 0x80E1
135 #endif
137 #ifndef GL_UNSIGNED_INT_8_8_8_8
138 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
139 #endif
141 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
142 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
143 #endif
145 #if 0
146 #define lprintf printf
147 #else
148 #define lprintf(...)
149 #endif
151 #define ARSERT(cond) for (;;) { \
152 if (!(cond)) { \
153 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
155 break; \
158 struct slice {
159 int h;
160 int texindex;
163 struct tile {
164 int w, h;
165 int slicecount;
166 int sliceheight;
167 struct bo *pbo;
168 fz_pixmap *pixmap;
169 struct slice slices[1];
172 struct pagedim {
173 int pageno;
174 int rotate;
175 int left;
176 int tctmready;
177 fz_irect bounds;
178 fz_rect pagebox;
179 fz_rect mediabox;
180 fz_matrix ctm, zoomctm, tctm;
183 struct slink {
184 enum { SLINK, SANNOT } tag;
185 fz_irect bbox;
186 union {
187 fz_link *link;
188 fz_annot *annot;
189 } u;
192 struct annot {
193 fz_irect bbox;
194 fz_annot *annot;
197 struct page {
198 int tgen;
199 int sgen;
200 int agen;
201 int pageno;
202 int pdimno;
203 fz_stext_page *text;
204 fz_stext_sheet *sheet;
205 fz_page *fzpage;
206 fz_display_list *dlist;
207 int slinkcount;
208 struct slink *slinks;
209 int annotcount;
210 struct annot *annots;
211 struct mark {
212 int i;
213 fz_stext_span *span;
214 } fmark, lmark;
217 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 enum { FitWidth, FitProportional, FitPage } 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 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
294 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
297 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
299 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
302 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
304 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
305 m.a, m.b, m.c, m.d, m.e, m.f);
308 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
310 static void lock (const char *cap)
312 int ret = pthread_mutex_lock (&mutex);
313 if (ret) {
314 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
318 static void unlock (const char *cap)
320 int ret = pthread_mutex_unlock (&mutex);
321 if (ret) {
322 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
326 static int trylock (const char *cap)
328 int ret = pthread_mutex_trylock (&mutex);
329 if (ret && ret != EBUSY) {
330 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
332 return ret == EBUSY;
335 static void *parse_pointer (const char *cap, const char *s)
337 int ret;
338 void *ptr;
340 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
341 if (ret != 1) {
342 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
344 return ptr;
347 static double now (void)
349 struct timeval tv;
351 if (gettimeofday (&tv, NULL)) {
352 err (1, "gettimeofday");
354 return tv.tv_sec + tv.tv_usec*1e-6;
357 static int hasdata (void)
359 int ret, avail;
360 ret = ioctl (state.csock, FIONREAD, &avail);
361 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
362 return avail > 0;
365 CAMLprim value ml_hasdata (value fd_v)
367 CAMLparam1 (fd_v);
368 int ret, avail;
370 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
371 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
372 CAMLreturn (Val_bool (avail > 0));
375 static void readdata (int fd, void *p, int size)
377 ssize_t n;
379 again:
380 n = read (fd, p, size);
381 if (n - size) {
382 if (n < 0 && errno == EINTR) goto again;
383 if (!n) errx (1, "EOF while reading");
384 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
388 static void writedata (int fd, char *p, int size)
390 ssize_t n;
391 uint32_t size4 = size;
392 struct iovec iov[2] = {
393 { .iov_base = &size4, .iov_len = 4 },
394 { .iov_base = p, .iov_len = size }
397 again:
398 n = writev (fd, iov, 2);
399 if (n < 0 && errno == EINTR) goto again;
400 if (n - size - 4) {
401 if (!n) errx (1, "EOF while writing data");
402 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
406 static int readlen (int fd)
408 /* Type punned unions here. Why? Less code (Adjusted by more comments).
409 https://en.wikipedia.org/wiki/Type_punning */
410 /* Then again https://bugs.llvm.org/show_bug.cgi?id=31928 - hmm */
411 union { uint32_t len; char raw[4]; } buf;
412 readdata (fd, buf.raw, 4);
413 return buf.len;
416 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
418 CAMLparam3 (fd_v, bytes_v, len_v);
419 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
420 CAMLreturn0;
423 CAMLprim value ml_rcmd (value fd_v)
425 CAMLparam1 (fd_v);
426 CAMLlocal1 (strdata_v);
427 int fd = Int_val (fd_v);
428 int len = readlen (fd);
429 strdata_v = caml_alloc_string (len);
430 readdata (fd, String_val (strdata_v), len);
431 CAMLreturn (strdata_v);
434 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
436 int size = 64, len;
437 va_list ap;
438 char fbuf[size];
439 char *buf = fbuf;
441 for (;;) {
442 va_start (ap, fmt);
443 len = vsnprintf (buf, size, fmt, ap);
444 va_end (ap);
446 if (len > -1) {
447 if (len < size - 4) {
448 writedata (state.csock, buf, len);
449 break;
451 else size = len + 5;
453 else {
454 err (1, "vsnprintf for `%s' failed", fmt);
456 buf = realloc (buf == fbuf ? NULL : buf, size);
457 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
459 if (buf != fbuf) free (buf);
462 static void closedoc (void)
464 #ifdef CACHE_PAGEREFS
465 if (state.pdflut.objs) {
466 for (int i = 0; i < state.pdflut.count; ++i) {
467 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
469 free (state.pdflut.objs);
470 state.pdflut.objs = NULL;
471 state.pdflut.idx = 0;
473 #endif
474 if (state.doc) {
475 fz_drop_document (state.ctx, state.doc);
476 state.doc = NULL;
480 static int openxref (char *filename, char *password)
482 for (int i = 0; i < state.texcount; ++i) {
483 state.texowners[i].w = -1;
484 state.texowners[i].slice = NULL;
487 closedoc ();
489 state.dirty = 0;
490 if (state.pagedims) {
491 free (state.pagedims);
492 state.pagedims = NULL;
494 state.pagedimcount = 0;
496 fz_set_aa_level (state.ctx, state.aalevel);
497 state.doc = fz_open_document (state.ctx, filename);
498 if (fz_needs_password (state.ctx, state.doc)) {
499 if (password && !*password) {
500 printd ("pass");
501 return 0;
503 else {
504 int ok = fz_authenticate_password (state.ctx, state.doc, password);
505 if (!ok) {
506 printd ("pass fail");
507 return 0;
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->sheet) {
571 fz_drop_stext_sheet (state.ctx, page->sheet);
573 if (page->slinks) {
574 free (page->slinks);
576 fz_drop_display_list (state.ctx, page->dlist);
577 fz_drop_page (state.ctx, page->fzpage);
578 free (page);
581 static void freetile (struct tile *tile)
583 unlinktile (tile);
584 if (!tile->pbo) {
585 #ifndef PIGGYBACK
586 fz_drop_pixmap (state.ctx, tile->pixmap);
587 #else
588 if (state.pig) {
589 fz_drop_pixmap (state.ctx, state.pig);
591 state.pig = tile->pixmap;
592 #endif
594 else {
595 free (tile->pbo);
596 fz_drop_pixmap (state.ctx, tile->pixmap);
598 free (tile);
601 #ifdef __ALTIVEC__
602 #include <stdint.h>
603 #include <altivec.h>
605 static int cacheline32bytes;
607 static void __attribute__ ((constructor)) clcheck (void)
609 char **envp = environ;
610 unsigned long *auxv;
612 while (*envp++);
614 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
615 if (*auxv == 19) {
616 cacheline32bytes = auxv[1] == 32;
617 return;
622 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
624 size_t size = pixmap->w * pixmap->h * pixmap->n;
625 if (cacheline32bytes && size > 32) {
626 intptr_t a1, a2, diff;
627 size_t sizea, i;
628 vector unsigned char v = vec_splat_u8 (-1);
629 vector unsigned char *p;
631 a1 = a2 = (intptr_t) pixmap->samples;
632 a2 = (a1 + 31) & ~31;
633 diff = a2 - a1;
634 sizea = size - diff;
635 p = (void *) a2;
637 while (a1 != a2) *(char *) a1++ = 0xff;
638 for (i = 0; i < (sizea & ~31); i += 32) {
639 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
640 vec_st (v, i, p);
641 vec_st (v, i + 16, p);
643 while (i < sizea) *((char *) a1 + i++) = 0xff;
645 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
647 #else
648 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
649 #endif
651 static void trimctm (pdf_page *page, int pindex)
653 fz_matrix ctm;
654 struct pagedim *pdim = &state.pagedims[pindex];
656 if (!page) return;
657 if (!pdim->tctmready) {
658 fz_rect realbox, mediabox;
659 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
661 fz_rotate (&rm, -pdim->rotate);
662 fz_scale (&sm, 1, -1);
663 fz_concat (&ctm, &rm, &sm);
664 realbox = pdim->mediabox;
665 fz_transform_rect (&realbox, &ctm);
666 fz_translate (&tm, -realbox.x0, -realbox.y0);
667 fz_concat (&ctm1, &ctm, &tm);
668 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
669 fz_invert_matrix (&im, &page_ctm);
670 fz_concat (&ctm, &im, &ctm1);
671 pdim->tctm = ctm;
672 pdim->tctmready = 1;
676 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
678 fz_matrix ctm, tm;
679 int pdimno = pdim - state.pagedims;
681 if (pdf_specifics (state.ctx, state.doc)) {
682 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
683 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
685 else {
686 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
687 fz_concat (&ctm, &tm, &pdim->ctm);
689 return ctm;
692 static fz_matrix pagectm (struct page *page)
694 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
697 static void *loadpage (int pageno, int pindex)
699 fz_device *dev;
700 struct page *page;
702 page = calloc (sizeof (struct page), 1);
703 if (!page) {
704 err (1, "calloc page %d", pageno);
707 page->dlist = fz_new_display_list (state.ctx, NULL);
708 dev = fz_new_list_device (state.ctx, page->dlist);
709 fz_try (state.ctx) {
710 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
711 fz_run_page (state.ctx, page->fzpage, dev,
712 &fz_identity, NULL);
714 fz_catch (state.ctx) {
715 page->fzpage = NULL;
717 fz_close_device (state.ctx, dev);
718 fz_drop_device (state.ctx, dev);
720 page->pdimno = pindex;
721 page->pageno = pageno;
722 page->sgen = state.gen;
723 page->agen = state.gen;
724 page->tgen = state.gen;
725 return page;
728 static struct tile *alloctile (int h)
730 int slicecount;
731 size_t tilesize;
732 struct tile *tile;
734 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
735 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
736 tile = calloc (tilesize, 1);
737 if (!tile) {
738 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
740 for (int i = 0; i < slicecount; ++i) {
741 int sh = fz_mini (h, state.sliceheight);
742 tile->slices[i].h = sh;
743 tile->slices[i].texindex = -1;
744 h -= sh;
746 tile->slicecount = slicecount;
747 tile->sliceheight = state.sliceheight;
748 return tile;
751 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
752 struct bo *pbo)
754 fz_rect rect;
755 fz_irect bbox;
756 fz_matrix ctm;
757 fz_device *dev;
758 struct tile *tile;
759 struct pagedim *pdim;
761 tile = alloctile (h);
762 pdim = &state.pagedims[page->pdimno];
764 bbox = pdim->bounds;
765 bbox.x0 += x;
766 bbox.y0 += y;
767 bbox.x1 = bbox.x0 + w;
768 bbox.y1 = bbox.y0 + h;
770 if (state.pig) {
771 if (state.pig->w == w
772 && state.pig->h == h
773 && state.pig->colorspace == state.colorspace) {
774 tile->pixmap = state.pig;
775 tile->pixmap->x = bbox.x0;
776 tile->pixmap->y = bbox.y0;
778 else {
779 fz_drop_pixmap (state.ctx, state.pig);
781 state.pig = NULL;
783 if (!tile->pixmap) {
784 if (pbo) {
785 tile->pixmap =
786 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
787 &bbox, NULL, 1, pbo->ptr);
788 tile->pbo = pbo;
790 else {
791 tile->pixmap =
792 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
793 NULL, 1);
797 tile->w = w;
798 tile->h = h;
799 clearpixmap (tile->pixmap);
801 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
802 ctm = pagectm (page);
803 fz_rect_from_irect (&rect, &bbox);
804 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
805 fz_close_device (state.ctx, dev);
806 fz_drop_device (state.ctx, dev);
808 return tile;
811 #ifdef CACHE_PAGEREFS
812 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
813 thanks to Robin Watts */
814 static void
815 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
817 fz_context *ctx = state.ctx; /* doc->ctx; */
818 pdf_obj *kids;
819 int len;
821 if (state.pdflut.idx == state.pagecount) return;
823 kids = pdf_dict_gets (ctx, node, "Kids");
824 len = pdf_array_len (ctx, kids);
826 if (len == 0)
827 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
829 if (pdf_mark_obj (ctx, node))
830 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
831 for (int i = 0; i < len; i++) {
832 pdf_obj *kid = pdf_array_get (ctx, kids, i);
833 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
834 if (*type
835 ? !strcmp (type, "Pages")
836 : pdf_dict_gets (ctx, kid, "Kids")
837 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
838 pdf_collect_pages (doc, kid);
840 else {
841 if (*type
842 ? strcmp (type, "Page") != 0
843 : !pdf_dict_gets (ctx, kid, "MediaBox"))
844 fz_warn (ctx, "non-page object in page tree (%s)", type);
845 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
848 pdf_unmark_obj (ctx, node);
851 static void
852 pdf_load_page_objs (pdf_document *doc)
854 pdf_obj *root = pdf_dict_gets (state.ctx,
855 pdf_trailer (state.ctx, doc), "Root");
856 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
858 if (!node)
859 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
861 state.pdflut.idx = 0;
862 pdf_collect_pages (doc, node);
864 #endif
866 static void initpdims (int wthack)
868 double start, end;
869 FILE *trimf = NULL;
870 fz_rect rootmediabox;
871 int pageno, trim, show;
872 int trimw = 0, cxcount;
873 fz_context *ctx = state.ctx;
874 pdf_document *pdf = pdf_specifics (ctx, state.doc);
876 fz_var (trimw);
877 fz_var (trimf);
878 fz_var (cxcount);
879 start = now ();
881 if (state.trimmargins && state.trimcachepath) {
882 trimf = fopen (state.trimcachepath, "rb");
883 if (!trimf) {
884 trimf = fopen (state.trimcachepath, "wb");
885 trimw = 1;
889 if (state.trimmargins || pdf || !state.cxack)
890 cxcount = state.pagecount;
891 else
892 cxcount = fz_mini (state.pagecount, 1);
894 if (pdf) {
895 pdf_obj *obj;
896 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
897 "Root/Pages/MediaBox");
898 pdf_to_rect (ctx, obj, &rootmediabox);
901 #ifdef CACHE_PAGEREFS
902 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
903 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
904 if (!state.pdflut.objs) {
905 err (1, "malloc pageobjs %zu %d %zu failed",
906 sizeof (*state.pdflut.objs), cxcount,
907 sizeof (*state.pdflut.objs) * cxcount);
909 state.pdflut.count = cxcount;
910 pdf_load_page_objs (pdf);
911 state.pdflut.pdf = pdf;
913 #endif
915 for (pageno = 0; pageno < cxcount; ++pageno) {
916 int rotate = 0;
917 struct pagedim *p;
918 fz_rect mediabox;
920 fz_var (rotate);
921 if (pdf) {
922 pdf_obj *pageref, *pageobj;
924 #ifdef CACHE_PAGEREFS
925 pageref = state.pdflut.objs[pageno];
926 #else
927 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
928 #endif
929 pageobj = pdf_resolve_indirect (ctx, pageref);
930 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
932 if (state.trimmargins) {
933 pdf_obj *obj;
934 pdf_page *page;
936 fz_try (ctx) {
937 page = pdf_load_page (ctx, pdf, pageno);
938 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
939 trim = state.trimanew || !obj;
940 if (trim) {
941 fz_rect rect;
942 fz_device *dev;
943 fz_matrix ctm, page_ctm;
945 dev = fz_new_bbox_device (ctx, &rect);
946 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
947 fz_invert_matrix (&ctm, &page_ctm);
948 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
949 fz_close_device (ctx, dev);
950 fz_drop_device (ctx, dev);
952 rect.x0 += state.trimfuzz.x0;
953 rect.x1 += state.trimfuzz.x1;
954 rect.y0 += state.trimfuzz.y0;
955 rect.y1 += state.trimfuzz.y1;
956 fz_transform_rect (&rect, &ctm);
957 fz_intersect_rect (&rect, &mediabox);
959 if (!fz_is_empty_rect (&rect)) {
960 mediabox = rect;
963 obj = pdf_new_array (ctx, pdf, 4);
964 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
965 mediabox.x0));
966 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
967 mediabox.y0));
968 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
969 mediabox.x1));
970 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
971 mediabox.y1));
972 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
974 else {
975 mediabox.x0 = pdf_to_real (ctx,
976 pdf_array_get (ctx, obj, 0));
977 mediabox.y0 = pdf_to_real (ctx,
978 pdf_array_get (ctx, obj, 1));
979 mediabox.x1 = pdf_to_real (ctx,
980 pdf_array_get (ctx, obj, 2));
981 mediabox.y1 = pdf_to_real (ctx,
982 pdf_array_get (ctx, obj, 3));
985 fz_drop_page (ctx, &page->super);
986 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
987 if (show) {
988 printd ("progress %f Trimming %d",
989 (double) (pageno + 1) / state.pagecount,
990 pageno + 1);
993 fz_catch (ctx) {
994 fprintf (stderr, "failed to load page %d\n", pageno+1);
997 else {
998 int empty = 0;
999 fz_rect cropbox;
1001 pdf_to_rect (ctx,
1002 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1003 &mediabox);
1004 if (fz_is_empty_rect (&mediabox)) {
1005 mediabox.x0 = 0;
1006 mediabox.y0 = 0;
1007 mediabox.x1 = 612;
1008 mediabox.y1 = 792;
1009 empty = 1;
1012 pdf_to_rect (ctx,
1013 pdf_dict_gets (ctx, pageobj, "CropBox"),
1014 &cropbox);
1015 if (!fz_is_empty_rect (&cropbox)) {
1016 if (empty) {
1017 mediabox = cropbox;
1019 else {
1020 fz_intersect_rect (&mediabox, &cropbox);
1023 else {
1024 if (empty) {
1025 if (fz_is_empty_rect (&rootmediabox)) {
1026 fprintf (stderr,
1027 "cannot find page size for page %d\n",
1028 pageno+1);
1030 else {
1031 mediabox = rootmediabox;
1037 else {
1038 if (state.trimmargins && trimw) {
1039 fz_page *page;
1041 fz_try (ctx) {
1042 page = fz_load_page (ctx, state.doc, pageno);
1043 fz_bound_page (ctx, page, &mediabox);
1044 if (state.trimmargins) {
1045 fz_rect rect;
1046 fz_device *dev;
1048 dev = fz_new_bbox_device (ctx, &rect);
1049 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1050 fz_close_device (ctx, dev);
1051 fz_drop_device (ctx, dev);
1053 rect.x0 += state.trimfuzz.x0;
1054 rect.x1 += state.trimfuzz.x1;
1055 rect.y0 += state.trimfuzz.y0;
1056 rect.y1 += state.trimfuzz.y1;
1057 fz_intersect_rect (&rect, &mediabox);
1059 if (!fz_is_empty_rect (&rect)) {
1060 mediabox = rect;
1063 fz_drop_page (ctx, page);
1064 if (!state.cxack) {
1065 printd ("progress %f loading %d",
1066 (double) (pageno + 1) / state.pagecount,
1067 pageno + 1);
1070 fz_catch (ctx) {
1072 if (trimf) {
1073 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1074 if (n - 1) {
1075 err (1, "fwrite trim mediabox");
1079 else {
1080 if (trimf) {
1081 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1082 if (n - 1) {
1083 err (1, "fread trim mediabox %d", pageno);
1086 else {
1087 fz_page *page;
1088 fz_try (ctx) {
1089 page = fz_load_page (ctx, state.doc, pageno);
1090 fz_bound_page (ctx, page, &mediabox);
1091 fz_drop_page (ctx, page);
1093 show = !state.trimmargins && pageno % 20 == 0;
1094 if (show) {
1095 printd ("progress %f Gathering dimensions %d",
1096 (double) (pageno) / state.pagecount,
1097 pageno);
1100 fz_catch (ctx) {
1101 fprintf (stderr, "failed to load page %d\n", pageno);
1107 if (state.pagedimcount == 0
1108 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1109 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1110 size_t size;
1112 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1113 state.pagedims = realloc (state.pagedims, size);
1114 if (!state.pagedims) {
1115 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1116 size, state.pagedimcount + 1);
1119 p = &state.pagedims[state.pagedimcount++];
1120 p->rotate = rotate;
1121 p->mediabox = mediabox;
1122 p->pageno = pageno;
1125 end = now ();
1126 if (!wthack) {
1127 printd ("progress 1 %s %d pages in %f seconds",
1128 state.trimmargins ? "Trimmed" : "Processed",
1129 state.pagecount, end - start);
1131 state.trimanew = 0;
1132 if (trimf) {
1133 if (fclose (trimf)) {
1134 err (1, "fclose");
1139 static void layout (void)
1141 int pindex;
1142 fz_rect box;
1143 fz_matrix ctm, rm;
1144 struct pagedim *p = p;
1145 double zw, w, maxw = 0.0, zoom = zoom;
1147 if (state.pagedimcount == 0) return;
1149 switch (state.fitmodel) {
1150 case FitProportional:
1151 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1152 double x0, x1;
1154 p = &state.pagedims[pindex];
1155 fz_rotate (&rm, p->rotate + state.rotate);
1156 box = p->mediabox;
1157 fz_transform_rect (&box, &rm);
1159 x0 = fz_min (box.x0, box.x1);
1160 x1 = fz_max (box.x0, box.x1);
1162 w = x1 - x0;
1163 maxw = fz_max (w, maxw);
1164 zoom = state.w / maxw;
1166 break;
1168 case FitPage:
1169 maxw = state.w;
1170 break;
1172 case FitWidth:
1173 break;
1175 default:
1176 ARSERT (0 && state.fitmodel);
1179 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1180 fz_rect rect;
1181 fz_matrix tm, sm;
1183 p = &state.pagedims[pindex];
1184 fz_rotate (&ctm, state.rotate);
1185 fz_rotate (&rm, p->rotate + state.rotate);
1186 box = p->mediabox;
1187 fz_transform_rect (&box, &rm);
1188 w = box.x1 - box.x0;
1189 switch (state.fitmodel) {
1190 case FitProportional:
1191 p->left = ((maxw - w) * zoom) / 2.0;
1192 break;
1193 case FitPage:
1195 double zh, h;
1196 zw = maxw / w;
1197 h = box.y1 - box.y0;
1198 zh = state.h / h;
1199 zoom = fz_min (zw, zh);
1200 p->left = (maxw - (w * zoom)) / 2.0;
1202 break;
1203 case FitWidth:
1204 p->left = 0;
1205 zoom = state.w / w;
1206 break;
1209 fz_scale (&p->zoomctm, zoom, zoom);
1210 fz_concat (&ctm, &p->zoomctm, &ctm);
1212 fz_rotate (&rm, p->rotate);
1213 p->pagebox = p->mediabox;
1214 fz_transform_rect (&p->pagebox, &rm);
1215 p->pagebox.x1 -= p->pagebox.x0;
1216 p->pagebox.y1 -= p->pagebox.y0;
1217 p->pagebox.x0 = 0;
1218 p->pagebox.y0 = 0;
1219 rect = p->pagebox;
1220 fz_transform_rect (&rect, &ctm);
1221 fz_round_rect (&p->bounds, &rect);
1222 p->ctm = ctm;
1224 fz_translate (&tm, 0, -p->mediabox.y1);
1225 fz_scale (&sm, zoom, -zoom);
1226 fz_concat (&ctm, &tm, &sm);
1228 p->tctmready = 0;
1231 do {
1232 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1233 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1234 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1235 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1236 int boundw = x1 - x0;
1237 int boundh = y1 - y0;
1239 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1240 } while (p-- != state.pagedims);
1243 struct pagedim *pdimofpageno (int pageno)
1245 struct pagedim *pdim = state.pagedims;
1247 for (int i = 0; i < state.pagedimcount; ++i) {
1248 if (state.pagedims[i].pageno > pageno)
1249 break;
1250 pdim = &state.pagedims[i];
1252 return pdim;
1255 static
1256 struct anchor { int n; int x; int y; int w; int h; }
1257 uritoanchor (const char *uri)
1259 fz_point p;
1260 struct anchor a;
1262 a.n = -1;
1263 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1264 if (a.n >= 0) {
1265 struct pagedim *pdim = pdimofpageno (a.n);
1266 fz_transform_point (&p, &pdim->ctm);
1267 a.x = p.x;
1268 a.y = p.y;
1269 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1271 return a;
1274 static void recurse_outline (fz_outline *outline, int level)
1276 while (outline) {
1277 struct anchor a = uritoanchor (outline->uri);
1278 if (a.n >= 0) {
1279 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1281 else {
1282 printd ("on %d %s", level, outline->title);
1284 if (outline->down) {
1285 recurse_outline (outline->down, level + 1);
1287 outline = outline->next;
1291 static void process_outline (void)
1293 fz_outline *outline;
1295 if (!state.needoutline || !state.pagedimcount) return;
1297 state.needoutline = 0;
1298 outline = fz_load_outline (state.ctx, state.doc);
1299 if (outline) {
1300 recurse_outline (outline, 0);
1301 fz_drop_outline (state.ctx, outline);
1305 static char *strofspan (fz_stext_span *span)
1307 char *p;
1308 char utf8[10];
1309 fz_stext_char *ch;
1310 size_t size = 0, cap = 80;
1312 p = malloc (cap + 1);
1313 if (!p) return NULL;
1315 for (ch = span->text; ch < span->text + span->len; ++ch) {
1316 int n = fz_runetochar (utf8, ch->c);
1317 if (size + n > cap) {
1318 cap *= 2;
1319 p = realloc (p, cap + 1);
1320 if (!p) return NULL;
1323 memcpy (p + size, utf8, n);
1324 size += n;
1326 p[size] = 0;
1327 return p;
1330 static int matchspan (regex_t *re, fz_stext_span *span,
1331 int stop, int pageno, double start)
1333 int ret;
1334 char *p;
1335 regmatch_t rm;
1336 int a, b, c;
1337 fz_rect sb, eb;
1338 fz_point p1, p2, p3, p4;
1340 p = strofspan (span);
1341 if (!p) return -1;
1343 ret = regexec (re, p, 1, &rm, 0);
1344 if (ret) {
1345 free (p);
1346 if (ret != REG_NOMATCH) {
1347 size_t size;
1348 char errbuf[80];
1349 size = regerror (ret, re, errbuf, sizeof (errbuf));
1350 printd ("msg regexec error `%.*s'",
1351 (int) size, errbuf);
1352 return -1;
1354 return 0;
1356 else {
1357 int l = span->len;
1359 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1360 c += fz_runelen (span->text[a].c);
1362 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1363 c += fz_runelen (span->text[b].c);
1366 if (fz_runelen (span->text[b].c) > 1) {
1367 b = fz_maxi (0, b-1);
1370 fz_stext_char_bbox (state.ctx, &sb, span, a);
1371 fz_stext_char_bbox (state.ctx, &eb, span, b);
1373 p1.x = sb.x0;
1374 p1.y = sb.y0;
1375 p2.x = eb.x1;
1376 p2.y = sb.y0;
1377 p3.x = eb.x1;
1378 p3.y = eb.y1;
1379 p4.x = sb.x0;
1380 p4.y = eb.y1;
1382 if (!stop) {
1383 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1384 pageno, 1,
1385 p1.x, p1.y,
1386 p2.x, p2.y,
1387 p3.x, p3.y,
1388 p4.x, p4.y);
1390 printd ("progress 1 found at %d `%.*s' in %f sec",
1391 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1392 now () - start);
1394 else {
1395 printd ("match %d %d %f %f %f %f %f %f %f %f",
1396 pageno, 2,
1397 p1.x, p1.y,
1398 p2.x, p2.y,
1399 p3.x, p3.y,
1400 p4.x, p4.y);
1402 free (p);
1403 return 1;
1407 static int compareblocks (const void *l, const void *r)
1409 fz_stext_block const *ls = l;
1410 fz_stext_block const *rs = r;
1411 return ls->bbox.y0 - rs->bbox.y0;
1414 /* wishful thinking function */
1415 static void search (regex_t *re, int pageno, int y, int forward)
1417 int j;
1418 fz_device *tdev;
1419 fz_stext_page *text;
1420 fz_stext_sheet *sheet;
1421 struct pagedim *pdim;
1422 int stop = 0, niters = 0;
1423 double start, end;
1424 fz_page *page;
1426 start = now ();
1427 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1428 if (niters++ == 5) {
1429 niters = 0;
1430 if (hasdata ()) {
1431 printd ("progress 1 attention requested aborting search at %d",
1432 pageno);
1433 stop = 1;
1435 else {
1436 printd ("progress %f searching in page %d",
1437 (double) (pageno + 1) / state.pagecount,
1438 pageno);
1441 pdim = pdimofpageno (pageno);
1442 sheet = fz_new_stext_sheet (state.ctx);
1443 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1444 tdev = fz_new_stext_device (state.ctx, sheet, text, 0);
1446 page = fz_load_page (state.ctx, state.doc, pageno);
1448 fz_matrix ctm = pagectm1 (page, pdim);
1449 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1452 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1453 fz_close_device (state.ctx, tdev);
1454 fz_drop_device (state.ctx, tdev);
1456 for (j = 0; j < text->len; ++j) {
1457 int k;
1458 fz_page_block *pb;
1459 fz_stext_block *block;
1461 pb = &text->blocks[forward ? j : text->len - 1 - j];
1462 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1463 block = pb->u.text;
1465 for (k = 0; k < block->len; ++k) {
1466 fz_stext_line *line;
1467 fz_stext_span *span;
1469 if (forward) {
1470 line = &block->lines[k];
1471 if (line->bbox.y0 < y + 1) continue;
1473 else {
1474 line = &block->lines[block->len - 1 - k];
1475 if (line->bbox.y0 > y - 1) continue;
1478 for (span = line->first_span; span; span = span->next) {
1479 switch (matchspan (re, span, stop, pageno, start)) {
1480 case 0: break;
1481 case 1: stop = 1; break;
1482 case -1: stop = 1; goto endloop;
1487 if (forward) {
1488 pageno += 1;
1489 y = 0;
1491 else {
1492 pageno -= 1;
1493 y = INT_MAX;
1495 endloop:
1496 fz_drop_stext_page (state.ctx, text);
1497 fz_drop_stext_sheet (state.ctx, sheet);
1498 fz_drop_page (state.ctx, page);
1500 end = now ();
1501 if (!stop) {
1502 printd ("progress 1 no matches %f sec", end - start);
1504 printd ("clearrects");
1507 static void set_tex_params (int colorspace)
1509 union {
1510 unsigned char b;
1511 unsigned int s;
1512 } endianness = {1};
1514 switch (colorspace) {
1515 case 0:
1516 state.texiform = GL_RGBA8;
1517 state.texform = GL_RGBA;
1518 state.texty = GL_UNSIGNED_BYTE;
1519 state.colorspace = fz_device_rgb (state.ctx);
1520 break;
1521 case 1:
1522 state.texiform = GL_RGBA8;
1523 state.texform = GL_BGRA;
1524 state.texty = endianness.s > 1
1525 ? GL_UNSIGNED_INT_8_8_8_8
1526 : GL_UNSIGNED_INT_8_8_8_8_REV;
1527 state.colorspace = fz_device_bgr (state.ctx);
1528 break;
1529 case 2:
1530 state.texiform = GL_LUMINANCE_ALPHA;
1531 state.texform = GL_LUMINANCE_ALPHA;
1532 state.texty = GL_UNSIGNED_BYTE;
1533 state.colorspace = fz_device_gray (state.ctx);
1534 break;
1535 default:
1536 errx (1, "invalid colorspce %d", colorspace);
1540 static void realloctexts (int texcount)
1542 size_t size;
1544 if (texcount == state.texcount) return;
1546 if (texcount < state.texcount) {
1547 glDeleteTextures (state.texcount - texcount,
1548 state.texids + texcount);
1551 size = texcount * sizeof (*state.texids);
1552 state.texids = realloc (state.texids, size);
1553 if (!state.texids) {
1554 err (1, "realloc texids %" FMT_s, size);
1557 size = texcount * sizeof (*state.texowners);
1558 state.texowners = realloc (state.texowners, size);
1559 if (!state.texowners) {
1560 err (1, "realloc texowners %" FMT_s, size);
1562 if (texcount > state.texcount) {
1563 glGenTextures (texcount - state.texcount,
1564 state.texids + state.texcount);
1565 for (int i = state.texcount; i < texcount; ++i) {
1566 state.texowners[i].w = -1;
1567 state.texowners[i].slice = NULL;
1570 state.texcount = texcount;
1571 state.texindex = 0;
1574 static char *mbtoutf8 (char *s)
1576 char *p, *r;
1577 wchar_t *tmp;
1578 size_t i, ret, len;
1580 if (state.utf8cs) {
1581 return s;
1584 len = mbstowcs (NULL, s, strlen (s));
1585 if (len == 0) {
1586 return s;
1588 else {
1589 if (len == (size_t) -1) {
1590 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1591 return s;
1595 tmp = calloc (len, sizeof (wchar_t));
1596 if (!tmp) {
1597 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1598 len, sizeof (wchar_t), errno, strerror (errno));
1599 return s;
1602 ret = mbstowcs (tmp, s, len);
1603 if (ret == (size_t) -1) {
1604 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1605 len, errno, strerror (errno));
1606 free (tmp);
1607 return s;
1610 len = 0;
1611 for (i = 0; i < ret; ++i) {
1612 len += fz_runelen (tmp[i]);
1615 p = r = malloc (len + 1);
1616 if (!r) {
1617 printd ("emsg mbtoutf8: malloc(%zu)", len);
1618 free (tmp);
1619 return s;
1622 for (i = 0; i < ret; ++i) {
1623 p += fz_runetochar (p, tmp[i]);
1625 *p = 0;
1626 free (tmp);
1627 return r;
1630 CAMLprim value ml_mbtoutf8 (value s_v)
1632 CAMLparam1 (s_v);
1633 CAMLlocal1 (ret_v);
1634 char *s, *r;
1636 s = String_val (s_v);
1637 r = mbtoutf8 (s);
1638 if (r == s) {
1639 ret_v = s_v;
1641 else {
1642 ret_v = caml_copy_string (r);
1643 free (r);
1645 CAMLreturn (ret_v);
1648 static void * mainloop (void UNUSED_ATTR *unused)
1650 char *p = NULL;
1651 int len, ret, oldlen = 0;
1653 fz_var (p);
1654 fz_var (oldlen);
1655 for (;;) {
1656 len = readlen (state.csock);
1657 if (len == 0) {
1658 errx (1, "readlen returned 0");
1661 if (oldlen < len + 1) {
1662 p = realloc (p, len + 1);
1663 if (!p) {
1664 err (1, "realloc %d failed", len + 1);
1666 oldlen = len + 1;
1668 readdata (state.csock, p, len);
1669 p[len] = 0;
1671 if (!strncmp ("open", p, 4)) {
1672 int wthack, off, usedoccss, ok = 0;
1673 char *password;
1674 char *filename;
1675 char *utf8filename;
1676 size_t filenamelen;
1678 fz_var (ok);
1679 ret = sscanf (p + 5, " %d %d %d %n",
1680 &wthack, &state.cxack, &usedoccss, &off);
1681 if (ret != 3) {
1682 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1685 filename = p + 5 + off;
1686 filenamelen = strlen (filename);
1687 password = filename + filenamelen + 1;
1689 if (password[strlen (password) + 1]) {
1690 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1693 lock ("open");
1694 fz_set_use_document_css (state.ctx, usedoccss);
1695 fz_try (state.ctx) {
1696 ok = openxref (filename, password);
1698 fz_catch (state.ctx) {
1699 utf8filename = mbtoutf8 (filename);
1700 printd ("msg Could not open %s", utf8filename);
1702 if (ok) {
1703 pdfinfo ();
1704 initpdims (wthack);
1706 unlock ("open");
1708 if (ok) {
1709 if (!wthack) {
1710 utf8filename = mbtoutf8 (filename);
1711 printd ("msg Opened %s (press h/F1 to get help)",
1712 utf8filename);
1713 if (utf8filename != filename) {
1714 free (utf8filename);
1717 state.needoutline = 1;
1720 else if (!strncmp ("cs", p, 2)) {
1721 int i, colorspace;
1723 ret = sscanf (p + 2, " %d", &colorspace);
1724 if (ret != 1) {
1725 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1727 lock ("cs");
1728 set_tex_params (colorspace);
1729 for (i = 0; i < state.texcount; ++i) {
1730 state.texowners[i].w = -1;
1731 state.texowners[i].slice = NULL;
1733 unlock ("cs");
1735 else if (!strncmp ("freepage", p, 8)) {
1736 void *ptr;
1738 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1739 if (ret != 1) {
1740 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1742 freepage (ptr);
1744 else if (!strncmp ("freetile", p, 8)) {
1745 void *ptr;
1747 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1748 if (ret != 1) {
1749 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1751 freetile (ptr);
1753 else if (!strncmp ("search", p, 6)) {
1754 int icase, pageno, y, len2, forward;
1755 char *pattern;
1756 regex_t re;
1758 ret = sscanf (p + 6, " %d %d %d %d,%n",
1759 &icase, &pageno, &y, &forward, &len2);
1760 if (ret != 4) {
1761 errx (1, "malformed search `%s' ret=%d", p, ret);
1764 pattern = p + 6 + len2;
1765 ret = regcomp (&re, pattern,
1766 REG_EXTENDED | (icase ? REG_ICASE : 0));
1767 if (ret) {
1768 char errbuf[80];
1769 size_t size;
1771 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1772 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1774 else {
1775 search (&re, pageno, y, forward);
1776 regfree (&re);
1779 else if (!strncmp ("geometry", p, 8)) {
1780 int w, h, fitmodel;
1782 printd ("clear");
1783 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1784 if (ret != 3) {
1785 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1788 lock ("geometry");
1789 state.h = h;
1790 if (w != state.w) {
1791 state.w = w;
1792 for (int i = 0; i < state.texcount; ++i) {
1793 state.texowners[i].slice = NULL;
1796 state.fitmodel = fitmodel;
1797 layout ();
1798 process_outline ();
1800 state.gen++;
1801 unlock ("geometry");
1802 printd ("continue %d", state.pagecount);
1804 else if (!strncmp ("reqlayout", p, 9)) {
1805 char *nameddest;
1806 int rotate, off, h;
1807 unsigned int fitmodel;
1808 pdf_document *pdf;
1810 printd ("clear");
1811 ret = sscanf (p + 9, " %d %u %d %n",
1812 &rotate, &fitmodel, &h, &off);
1813 if (ret != 3) {
1814 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1816 lock ("reqlayout");
1817 pdf = pdf_specifics (state.ctx, state.doc);
1818 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1819 state.gen += 1;
1821 state.rotate = rotate;
1822 state.fitmodel = fitmodel;
1823 state.h = h;
1824 layout ();
1825 process_outline ();
1827 nameddest = p + 9 + off;
1828 if (pdf && nameddest && *nameddest) {
1829 fz_point xy;
1830 struct pagedim *pdim;
1831 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1832 &xy.x, &xy.y);
1833 pdim = pdimofpageno (pageno);
1834 fz_transform_point (&xy, &pdim->ctm);
1835 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1838 state.gen++;
1839 unlock ("reqlayout");
1840 printd ("continue %d", state.pagecount);
1842 else if (!strncmp ("page", p, 4)) {
1843 double a, b;
1844 struct page *page;
1845 int pageno, pindex;
1847 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1848 if (ret != 2) {
1849 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1852 lock ("page");
1853 a = now ();
1854 page = loadpage (pageno, pindex);
1855 b = now ();
1856 unlock ("page");
1858 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1860 else if (!strncmp ("tile", p, 4)) {
1861 int x, y, w, h;
1862 struct page *page;
1863 struct tile *tile;
1864 double a, b;
1865 void *data;
1867 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1868 SCN_ptr_cast (&page), &x, &y, &w, &h,
1869 SCN_ptr_cast (&data));
1870 if (ret != 6) {
1871 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1874 lock ("tile");
1875 a = now ();
1876 tile = rendertile (page, x, y, w, h, data);
1877 b = now ();
1878 unlock ("tile");
1880 printd ("tile %d %d %" FMT_ptr " %u %f",
1881 x, y,
1882 FMT_ptr_cast (tile),
1883 tile->w * tile->h * tile->pixmap->n,
1884 b - a);
1886 else if (!strncmp ("trimset", p, 7)) {
1887 fz_irect fuzz;
1888 int trimmargins;
1890 ret = sscanf (p + 7, " %d %d %d %d %d",
1891 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1892 if (ret != 5) {
1893 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1895 lock ("trimset");
1896 state.trimmargins = trimmargins;
1897 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1898 state.trimanew = 1;
1899 state.trimfuzz = fuzz;
1901 unlock ("trimset");
1903 else if (!strncmp ("settrim", p, 7)) {
1904 fz_irect fuzz;
1905 int trimmargins;
1907 ret = sscanf (p + 7, " %d %d %d %d %d",
1908 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1909 if (ret != 5) {
1910 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1912 printd ("clear");
1913 lock ("settrim");
1914 state.trimmargins = trimmargins;
1915 state.needoutline = 1;
1916 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1917 state.trimanew = 1;
1918 state.trimfuzz = fuzz;
1920 state.pagedimcount = 0;
1921 free (state.pagedims);
1922 state.pagedims = NULL;
1923 initpdims (0);
1924 layout ();
1925 process_outline ();
1926 unlock ("settrim");
1927 printd ("continue %d", state.pagecount);
1929 else if (!strncmp ("sliceh", p, 6)) {
1930 int h;
1932 ret = sscanf (p + 6, " %d", &h);
1933 if (ret != 1) {
1934 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1936 if (h != state.sliceheight) {
1937 state.sliceheight = h;
1938 for (int i = 0; i < state.texcount; ++i) {
1939 state.texowners[i].w = -1;
1940 state.texowners[i].h = -1;
1941 state.texowners[i].slice = NULL;
1945 else if (!strncmp ("interrupt", p, 9)) {
1946 printd ("vmsg interrupted");
1948 else {
1949 errx (1, "unknown command %.*s", len, p);
1952 return 0;
1955 CAMLprim value ml_isexternallink (value uri_v)
1957 CAMLparam1 (uri_v);
1958 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1959 CAMLreturn (Val_bool (ext));
1962 CAMLprim value ml_uritolocation (value uri_v)
1964 CAMLparam1 (uri_v);
1965 CAMLlocal1 (ret_v);
1966 int pageno;
1967 fz_point xy;
1968 struct pagedim *pdim;
1970 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1971 &xy.x, &xy.y);
1972 pdim = pdimofpageno (pageno);
1973 fz_transform_point (&xy, &pdim->ctm);
1974 ret_v = caml_alloc_tuple (3);
1975 Field (ret_v, 0) = Val_int (pageno);
1976 Field (ret_v, 1) = caml_copy_double (xy.x);
1977 Field (ret_v, 2) = caml_copy_double (xy.y);
1978 CAMLreturn (ret_v);
1981 CAMLprim value ml_realloctexts (value texcount_v)
1983 CAMLparam1 (texcount_v);
1984 int ok;
1986 if (trylock (__func__)) {
1987 ok = 0;
1988 goto done;
1990 realloctexts (Int_val (texcount_v));
1991 ok = 1;
1992 unlock (__func__);
1994 done:
1995 CAMLreturn (Val_bool (ok));
1998 static void recti (int x0, int y0, int x1, int y1)
2000 GLfloat *v = state.vertices;
2002 glVertexPointer (2, GL_FLOAT, 0, v);
2003 v[0] = x0; v[1] = y0;
2004 v[2] = x1; v[3] = y0;
2005 v[4] = x0; v[5] = y1;
2006 v[6] = x1; v[7] = y1;
2007 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2010 static void showsel (struct page *page, int ox, int oy)
2012 int seen = 0;
2013 fz_irect bbox;
2014 fz_rect rect;
2015 fz_stext_line *line;
2016 fz_page_block *pageb;
2017 fz_stext_block *block;
2018 struct mark first, last;
2019 unsigned char selcolor[] = {15,15,15,140};
2021 first = page->fmark;
2022 last = page->lmark;
2024 if (!first.span || !last.span) return;
2026 glEnable (GL_BLEND);
2027 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2028 glColor4ubv (selcolor);
2030 ox += state.pagedims[page->pdimno].bounds.x0;
2031 oy += state.pagedims[page->pdimno].bounds.y0;
2032 for (pageb = page->text->blocks;
2033 pageb < page->text->blocks + page->text->len;
2034 ++pageb) {
2035 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2036 block = pageb->u.text;
2038 for (line = block->lines;
2039 line < block->lines + block->len;
2040 ++line) {
2041 fz_stext_span *span;
2042 rect = fz_empty_rect;
2044 for (span = line->first_span; span; span = span->next) {
2045 int i, j, k;
2046 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2048 j = 0;
2049 k = span->len - 1;
2051 if (span == page->fmark.span && span == page->lmark.span) {
2052 seen = 1;
2053 j = fz_mini (first.i, last.i);
2054 k = fz_maxi (first.i, last.i);
2056 else {
2057 if (span == first.span) {
2058 seen = 1;
2059 j = first.i;
2061 else if (span == last.span) {
2062 seen = 1;
2063 k = last.i;
2067 if (seen) {
2068 for (i = j; i <= k; ++i) {
2069 fz_rect bbox1;
2070 fz_union_rect (&rect,
2071 fz_stext_char_bbox (state.ctx, &bbox1,
2072 span, i));
2074 fz_round_rect (&bbox, &rect);
2075 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2076 bbox.x0,
2077 bbox.y0,
2078 bbox.x1,
2079 bbox.y1,
2080 oy, ox);
2082 recti (bbox.x0 + ox, bbox.y0 + oy,
2083 bbox.x1 + ox, bbox.y1 + oy);
2084 if (span == last.span) {
2085 goto done;
2087 rect = fz_empty_rect;
2092 done:
2093 glDisable (GL_BLEND);
2096 #include "glfont.c"
2098 static void stipplerect (fz_matrix *m,
2099 fz_point *p1,
2100 fz_point *p2,
2101 fz_point *p3,
2102 fz_point *p4,
2103 GLfloat *texcoords,
2104 GLfloat *vertices)
2106 fz_transform_point (p1, m);
2107 fz_transform_point (p2, m);
2108 fz_transform_point (p3, m);
2109 fz_transform_point (p4, m);
2111 float w, h, s, t;
2113 w = p2->x - p1->x;
2114 h = p2->y - p1->y;
2115 t = hypotf (w, h) * .25f;
2117 w = p3->x - p2->x;
2118 h = p3->y - p2->y;
2119 s = hypotf (w, h) * .25f;
2121 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2122 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2124 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2125 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2127 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2128 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2130 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2131 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2133 glDrawArrays (GL_LINES, 0, 8);
2136 static void solidrect (fz_matrix *m,
2137 fz_point *p1,
2138 fz_point *p2,
2139 fz_point *p3,
2140 fz_point *p4,
2141 GLfloat *vertices)
2143 fz_transform_point (p1, m);
2144 fz_transform_point (p2, m);
2145 fz_transform_point (p3, m);
2146 fz_transform_point (p4, m);
2147 vertices[0] = p1->x; vertices[1] = p1->y;
2148 vertices[2] = p2->x; vertices[3] = p2->y;
2150 vertices[4] = p3->x; vertices[5] = p3->y;
2151 vertices[6] = p4->x; vertices[7] = p4->y;
2152 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2155 static void highlightlinks (struct page *page, int xoff, int yoff)
2157 fz_matrix ctm, tm, pm;
2158 fz_link *link, *links;
2159 GLfloat *texcoords = state.texcoords;
2160 GLfloat *vertices = state.vertices;
2162 links = fz_load_links (state.ctx, page->fzpage);
2164 glEnable (GL_TEXTURE_1D);
2165 glEnable (GL_BLEND);
2166 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2167 glBindTexture (GL_TEXTURE_1D, state.stid);
2169 xoff -= state.pagedims[page->pdimno].bounds.x0;
2170 yoff -= state.pagedims[page->pdimno].bounds.y0;
2171 fz_translate (&tm, xoff, yoff);
2172 pm = pagectm (page);
2173 fz_concat (&ctm, &pm, &tm);
2175 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2176 glVertexPointer (2, GL_FLOAT, 0, vertices);
2178 for (link = links; link; link = link->next) {
2179 fz_point p1, p2, p3, p4;
2181 p1.x = link->rect.x0;
2182 p1.y = link->rect.y0;
2184 p2.x = link->rect.x1;
2185 p2.y = link->rect.y0;
2187 p3.x = link->rect.x1;
2188 p3.y = link->rect.y1;
2190 p4.x = link->rect.x0;
2191 p4.y = link->rect.y1;
2193 /* TODO: different colours for different schemes */
2194 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2195 else glColor3ub (255, 0, 0);
2197 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2200 for (int i = 0; i < page->annotcount; ++i) {
2201 fz_point p1, p2, p3, p4;
2202 struct annot *annot = &page->annots[i];
2204 p1.x = annot->bbox.x0;
2205 p1.y = annot->bbox.y0;
2207 p2.x = annot->bbox.x1;
2208 p2.y = annot->bbox.y0;
2210 p3.x = annot->bbox.x1;
2211 p3.y = annot->bbox.y1;
2213 p4.x = annot->bbox.x0;
2214 p4.y = annot->bbox.y1;
2216 glColor3ub (0, 0, 128);
2217 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2220 glDisable (GL_BLEND);
2221 glDisable (GL_TEXTURE_1D);
2224 static int compareslinks (const void *l, const void *r)
2226 struct slink const *ls = l;
2227 struct slink const *rs = r;
2228 if (ls->bbox.y0 == rs->bbox.y0) {
2229 return rs->bbox.x0 - rs->bbox.x0;
2231 return ls->bbox.y0 - rs->bbox.y0;
2234 static void droptext (struct page *page)
2236 if (page->text) {
2237 fz_drop_stext_page (state.ctx, page->text);
2238 page->fmark.i = -1;
2239 page->lmark.i = -1;
2240 page->fmark.span = NULL;
2241 page->lmark.span = NULL;
2242 page->text = NULL;
2244 if (page->sheet) {
2245 fz_drop_stext_sheet (state.ctx, page->sheet);
2246 page->sheet = NULL;
2250 static void dropannots (struct page *page)
2252 if (page->annots) {
2253 free (page->annots);
2254 page->annots = NULL;
2255 page->annotcount = 0;
2259 static void ensureannots (struct page *page)
2261 int i, count = 0;
2262 size_t annotsize = sizeof (*page->annots);
2263 fz_annot *annot;
2265 if (state.gen != page->agen) {
2266 dropannots (page);
2267 page->agen = state.gen;
2269 if (page->annots) return;
2271 for (annot = fz_first_annot (state.ctx, page->fzpage);
2272 annot;
2273 annot = fz_next_annot (state.ctx, annot)) {
2274 count++;
2277 if (count > 0) {
2278 page->annotcount = count;
2279 page->annots = calloc (count, annotsize);
2280 if (!page->annots) {
2281 err (1, "calloc annots %d", count);
2284 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2285 annot;
2286 annot = fz_next_annot (state.ctx, annot), i++) {
2287 fz_rect rect;
2289 fz_bound_annot (state.ctx, annot, &rect);
2290 page->annots[i].annot = annot;
2291 fz_round_rect (&page->annots[i].bbox, &rect);
2296 static void dropslinks (struct page *page)
2298 if (page->slinks) {
2299 free (page->slinks);
2300 page->slinks = NULL;
2301 page->slinkcount = 0;
2305 static void ensureslinks (struct page *page)
2307 fz_matrix ctm;
2308 int i, count;
2309 size_t slinksize = sizeof (*page->slinks);
2310 fz_link *link, *links;
2312 ensureannots (page);
2313 if (state.gen != page->sgen) {
2314 dropslinks (page);
2315 page->sgen = state.gen;
2317 if (page->slinks) return;
2319 links = fz_load_links (state.ctx, page->fzpage);
2320 ctm = pagectm (page);
2322 count = page->annotcount;
2323 for (link = links; link; link = link->next) {
2324 count++;
2326 if (count > 0) {
2327 int j;
2329 page->slinkcount = count;
2330 page->slinks = calloc (count, slinksize);
2331 if (!page->slinks) {
2332 err (1, "calloc slinks %d", count);
2335 for (i = 0, link = links; link; ++i, link = link->next) {
2336 fz_rect rect;
2338 rect = link->rect;
2339 fz_transform_rect (&rect, &ctm);
2340 page->slinks[i].tag = SLINK;
2341 page->slinks[i].u.link = link;
2342 fz_round_rect (&page->slinks[i].bbox, &rect);
2344 for (j = 0; j < page->annotcount; ++j, ++i) {
2345 fz_rect rect;
2346 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2347 fz_transform_rect (&rect, &ctm);
2348 fz_round_rect (&page->slinks[i].bbox, &rect);
2350 page->slinks[i].tag = SANNOT;
2351 page->slinks[i].u.annot = page->annots[j].annot;
2353 qsort (page->slinks, count, slinksize, compareslinks);
2357 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2358 static void fmt_linkn (char *s, unsigned int u)
2360 unsigned int len; unsigned int q;
2361 unsigned int zma = 'z' - 'a' + 1;
2362 len = 1; q = u;
2363 while (q > zma - 1) { ++len; q /= zma; }
2364 if (s) {
2365 s += len;
2366 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2367 /* handles u == 0 */
2369 s[len] = 0;
2372 static void highlightslinks (struct page *page, int xoff, int yoff,
2373 int noff, char *targ, int tlen, int hfsize)
2375 char buf[40];
2376 struct slink *slink;
2377 double x0, y0, x1, y1, w;
2379 ensureslinks (page);
2380 glColor3ub (0xc3, 0xb0, 0x91);
2381 for (int i = 0; i < page->slinkcount; ++i) {
2382 fmt_linkn (buf, i + noff);
2383 if (!tlen || !strncmp (targ, buf, tlen)) {
2384 slink = &page->slinks[i];
2386 x0 = slink->bbox.x0 + xoff - 5;
2387 y1 = slink->bbox.y0 + yoff - 5;
2388 y0 = y1 + 10 + hfsize;
2389 w = measure_string (state.face, hfsize, buf);
2390 x1 = x0 + w + 10;
2391 recti (x0, y0, x1, y1);
2395 glEnable (GL_BLEND);
2396 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2397 glEnable (GL_TEXTURE_2D);
2398 glColor3ub (0, 0, 0);
2399 for (int i = 0; i < page->slinkcount; ++i) {
2400 fmt_linkn (buf, i + noff);
2401 if (!tlen || !strncmp (targ, buf, tlen)) {
2402 slink = &page->slinks[i];
2404 x0 = slink->bbox.x0 + xoff;
2405 y0 = slink->bbox.y0 + yoff + hfsize;
2406 draw_string (state.face, hfsize, x0, y0, buf);
2409 glDisable (GL_TEXTURE_2D);
2410 glDisable (GL_BLEND);
2413 static void uploadslice (struct tile *tile, struct slice *slice)
2415 int offset;
2416 struct slice *slice1;
2417 unsigned char *texdata;
2419 offset = 0;
2420 for (slice1 = tile->slices; slice != slice1; slice1++) {
2421 offset += slice1->h * tile->w * tile->pixmap->n;
2423 if (slice->texindex != -1 && slice->texindex < state.texcount
2424 && state.texowners[slice->texindex].slice == slice) {
2425 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2427 else {
2428 int subimage = 0;
2429 int texindex = state.texindex++ % state.texcount;
2431 if (state.texowners[texindex].w == tile->w) {
2432 if (state.texowners[texindex].h >= slice->h) {
2433 subimage = 1;
2435 else {
2436 state.texowners[texindex].h = slice->h;
2439 else {
2440 state.texowners[texindex].h = slice->h;
2443 state.texowners[texindex].w = tile->w;
2444 state.texowners[texindex].slice = slice;
2445 slice->texindex = texindex;
2447 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2448 #if TEXT_TYPE == GL_TEXTURE_2D
2449 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2450 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2451 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2452 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2453 #endif
2454 if (tile->pbo) {
2455 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2456 texdata = 0;
2458 else {
2459 texdata = tile->pixmap->samples;
2461 if (subimage) {
2462 glTexSubImage2D (TEXT_TYPE,
2466 tile->w,
2467 slice->h,
2468 state.texform,
2469 state.texty,
2470 texdata+offset
2473 else {
2474 glTexImage2D (TEXT_TYPE,
2476 state.texiform,
2477 tile->w,
2478 slice->h,
2480 state.texform,
2481 state.texty,
2482 texdata+offset
2485 if (tile->pbo) {
2486 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2491 CAMLprim void ml_begintiles (value unit_v)
2493 CAMLparam1 (unit_v);
2494 glEnable (TEXT_TYPE);
2495 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2496 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2497 CAMLreturn0;
2500 CAMLprim void ml_endtiles (value unit_v)
2502 CAMLparam1 (unit_v);
2503 glDisable (TEXT_TYPE);
2504 CAMLreturn0;
2507 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2509 CAMLparam2 (args_v, ptr_v);
2510 int dispx = Int_val (Field (args_v, 0));
2511 int dispy = Int_val (Field (args_v, 1));
2512 int dispw = Int_val (Field (args_v, 2));
2513 int disph = Int_val (Field (args_v, 3));
2514 int tilex = Int_val (Field (args_v, 4));
2515 int tiley = Int_val (Field (args_v, 5));
2516 char *s = String_val (ptr_v);
2517 struct tile *tile = parse_pointer (__func__, s);
2518 int slicey, firstslice;
2519 struct slice *slice;
2520 GLfloat *texcoords = state.texcoords;
2521 GLfloat *vertices = state.vertices;
2523 firstslice = tiley / tile->sliceheight;
2524 slice = &tile->slices[firstslice];
2525 slicey = tiley % tile->sliceheight;
2527 while (disph > 0) {
2528 int dh;
2530 dh = slice->h - slicey;
2531 dh = fz_mini (disph, dh);
2532 uploadslice (tile, slice);
2534 texcoords[0] = tilex; texcoords[1] = slicey;
2535 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2536 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2537 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2539 vertices[0] = dispx; vertices[1] = dispy;
2540 vertices[2] = dispx+dispw; vertices[3] = dispy;
2541 vertices[4] = dispx; vertices[5] = dispy+dh;
2542 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2544 #if TEXT_TYPE == GL_TEXTURE_2D
2545 for (int i = 0; i < 8; ++i) {
2546 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2548 #endif
2550 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2551 dispy += dh;
2552 disph -= dh;
2553 slice++;
2554 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2555 slicey = 0;
2557 CAMLreturn0;
2560 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2562 fz_matrix ctm, tm, pm;
2563 fz_point p1, p2, p3, p4;
2564 GLfloat *vertices = state.vertices;
2565 double *v = (double *) rects_v;
2567 xoff -= state.pagedims[page->pdimno].bounds.x0;
2568 yoff -= state.pagedims[page->pdimno].bounds.y0;
2569 fz_translate (&tm, xoff, yoff);
2570 pm = pagectm (page);
2571 fz_concat (&ctm, &pm, &tm);
2573 glEnable (GL_BLEND);
2574 glVertexPointer (2, GL_FLOAT, 0, vertices);
2576 glColor4dv (v);
2577 p1.x = v[4];
2578 p1.y = v[5];
2580 p2.x = v[6];
2581 p2.y = v[5];
2583 p3.x = v[6];
2584 p3.y = v[7];
2586 p4.x = v[4];
2587 p4.y = v[7];
2588 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2589 glDisable (GL_BLEND);
2592 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2593 value xoff_v, value yoff_v,
2594 value li_v)
2596 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2597 int xoff = Int_val (xoff_v);
2598 int yoff = Int_val (yoff_v);
2599 int noff = Int_val (Field (li_v, 0));
2600 char *targ = String_val (Field (li_v, 1));
2601 int tlen = caml_string_length (Field (li_v, 1));
2602 int hfsize = Int_val (Field (li_v, 2));
2603 char *s = String_val (ptr_v);
2604 int hlmask = Int_val (hlinks_v);
2605 struct page *page = parse_pointer (__func__, s);
2607 if (!page->fzpage) {
2608 /* deal with loadpage failed pages */
2609 goto done;
2612 if (trylock (__func__)) {
2613 noff = -1;
2614 goto done;
2617 ensureannots (page);
2618 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2619 if (hlmask & 2) {
2620 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2621 noff = page->slinkcount;
2623 if (page->tgen == state.gen) {
2624 showsel (page, xoff, yoff);
2626 unlock (__func__);
2628 done:
2629 CAMLreturn (Val_int (noff));
2632 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2633 value rects_v)
2635 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2636 int xoff = Int_val (xoff_v);
2637 int yoff = Int_val (yoff_v);
2638 char *s = String_val (ptr_v);
2639 struct page *page = parse_pointer (__func__, s);
2641 drawprect (page, xoff, yoff, rects_v);
2642 CAMLreturn0;
2645 static struct annot *getannot (struct page *page, int x, int y)
2647 fz_point p;
2648 fz_matrix ctm;
2649 const fz_matrix *tctm;
2650 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2652 if (!page->annots) return NULL;
2654 if (pdf) {
2655 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2656 tctm = &state.pagedims[page->pdimno].tctm;
2658 else {
2659 tctm = &fz_identity;
2662 p.x = x;
2663 p.y = y;
2665 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2666 fz_invert_matrix (&ctm, &ctm);
2667 fz_transform_point (&p, &ctm);
2669 if (pdf) {
2670 for (int i = 0; i < page->annotcount; ++i) {
2671 struct annot *a = &page->annots[i];
2672 fz_rect rect;
2674 fz_bound_annot (state.ctx, a->annot, &rect);
2675 if (p.x >= rect.x0 && p.x <= rect.x1) {
2676 if (p.y >= rect.y0 && p.y <= rect.y1)
2677 return a;
2681 return NULL;
2684 static fz_link *getlink (struct page *page, int x, int y)
2686 fz_point p;
2687 fz_matrix ctm;
2688 fz_link *link, *links;
2690 links = fz_load_links (state.ctx, page->fzpage);
2692 p.x = x;
2693 p.y = y;
2695 ctm = pagectm (page);
2696 fz_invert_matrix (&ctm, &ctm);
2697 fz_transform_point (&p, &ctm);
2699 for (link = links; link; link = link->next) {
2700 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2701 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2702 return link;
2706 return NULL;
2709 static void ensuretext (struct page *page)
2711 if (state.gen != page->tgen) {
2712 droptext (page);
2713 page->tgen = state.gen;
2715 if (!page->text) {
2716 fz_matrix ctm;
2717 fz_device *tdev;
2719 page->text = fz_new_stext_page (state.ctx,
2720 &state.pagedims[page->pdimno].mediabox);
2721 page->sheet = fz_new_stext_sheet (state.ctx);
2722 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2723 ctm = pagectm (page);
2724 fz_run_display_list (state.ctx, page->dlist,
2725 tdev, &ctm, &fz_infinite_rect, NULL);
2726 qsort (page->text->blocks, page->text->len,
2727 sizeof (*page->text->blocks), compareblocks);
2728 fz_close_device (state.ctx, tdev);
2729 fz_drop_device (state.ctx, tdev);
2733 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2735 CAMLparam2 (start_page_v, dir_v);
2736 CAMLlocal1 (ret_v);
2737 int i, dir = Int_val (dir_v);
2738 int start_page = Int_val (start_page_v);
2739 int end_page = dir > 0 ? state.pagecount : -1;
2740 pdf_document *pdf;
2742 fz_var (end_page);
2743 ret_v = Val_int (0);
2744 lock (__func__);
2745 pdf = pdf_specifics (state.ctx, state.doc);
2746 for (i = start_page + dir; i != end_page; i += dir) {
2747 int found;
2749 fz_var (found);
2750 if (pdf) {
2751 pdf_page *page = NULL;
2753 fz_var (page);
2754 fz_try (state.ctx) {
2755 page = pdf_load_page (state.ctx, pdf, i);
2756 found = !!page->links || !!page->annots;
2758 fz_catch (state.ctx) {
2759 found = 0;
2761 if (page) {
2762 fz_drop_page (state.ctx, &page->super);
2765 else {
2766 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2767 found = !!fz_load_links (state.ctx, page);
2768 fz_drop_page (state.ctx, page);
2771 if (found) {
2772 ret_v = caml_alloc_small (1, 1);
2773 Field (ret_v, 0) = Val_int (i);
2774 goto unlock;
2777 unlock:
2778 unlock (__func__);
2779 CAMLreturn (ret_v);
2782 enum { dir_first, dir_last };
2783 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2785 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2787 CAMLparam2 (ptr_v, dir_v);
2788 CAMLlocal2 (ret_v, pos_v);
2789 struct page *page;
2790 int dirtag, i, slinkindex;
2791 struct slink *found = NULL ,*slink;
2792 char *s = String_val (ptr_v);
2794 page = parse_pointer (__func__, s);
2795 ret_v = Val_int (0);
2796 lock (__func__);
2797 ensureslinks (page);
2799 if (Is_block (dir_v)) {
2800 dirtag = Tag_val (dir_v);
2801 switch (dirtag) {
2802 case dir_first_visible:
2804 int x0, y0, dir, first_index, last_index;
2806 pos_v = Field (dir_v, 0);
2807 x0 = Int_val (Field (pos_v, 0));
2808 y0 = Int_val (Field (pos_v, 1));
2809 dir = Int_val (Field (pos_v, 2));
2811 if (dir >= 0) {
2812 dir = 1;
2813 first_index = 0;
2814 last_index = page->slinkcount;
2816 else {
2817 first_index = page->slinkcount - 1;
2818 last_index = -1;
2821 for (i = first_index; i != last_index; i += dir) {
2822 slink = &page->slinks[i];
2823 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2824 found = slink;
2825 break;
2829 break;
2831 case dir_left:
2832 slinkindex = Int_val (Field (dir_v, 0));
2833 found = &page->slinks[slinkindex];
2834 for (i = slinkindex - 1; i >= 0; --i) {
2835 slink = &page->slinks[i];
2836 if (slink->bbox.x0 < found->bbox.x0) {
2837 found = slink;
2838 break;
2841 break;
2843 case dir_right:
2844 slinkindex = Int_val (Field (dir_v, 0));
2845 found = &page->slinks[slinkindex];
2846 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2847 slink = &page->slinks[i];
2848 if (slink->bbox.x0 > found->bbox.x0) {
2849 found = slink;
2850 break;
2853 break;
2855 case dir_down:
2856 slinkindex = Int_val (Field (dir_v, 0));
2857 found = &page->slinks[slinkindex];
2858 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2859 slink = &page->slinks[i];
2860 if (slink->bbox.y0 >= found->bbox.y0) {
2861 found = slink;
2862 break;
2865 break;
2867 case dir_up:
2868 slinkindex = Int_val (Field (dir_v, 0));
2869 found = &page->slinks[slinkindex];
2870 for (i = slinkindex - 1; i >= 0; --i) {
2871 slink = &page->slinks[i];
2872 if (slink->bbox.y0 <= found->bbox.y0) {
2873 found = slink;
2874 break;
2877 break;
2880 else {
2881 dirtag = Int_val (dir_v);
2882 switch (dirtag) {
2883 case dir_first:
2884 found = page->slinks;
2885 break;
2887 case dir_last:
2888 if (page->slinks) {
2889 found = page->slinks + (page->slinkcount - 1);
2891 break;
2894 if (found) {
2895 ret_v = caml_alloc_small (2, 1);
2896 Field (ret_v, 0) = Val_int (found - page->slinks);
2899 unlock (__func__);
2900 CAMLreturn (ret_v);
2903 enum { uuri, utext, uannot };
2905 CAMLprim value ml_getlink (value ptr_v, value n_v)
2907 CAMLparam2 (ptr_v, n_v);
2908 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2909 fz_link *link;
2910 struct page *page;
2911 char *s = String_val (ptr_v);
2912 struct slink *slink;
2914 ret_v = Val_int (0);
2915 page = parse_pointer (__func__, s);
2917 lock (__func__);
2918 ensureslinks (page);
2919 slink = &page->slinks[Int_val (n_v)];
2920 if (slink->tag == SLINK) {
2921 link = slink->u.link;
2922 str_v = caml_copy_string (link->uri);
2923 ret_v = caml_alloc_small (1, uuri);
2924 Field (ret_v, 0) = str_v;
2926 else {
2927 ret_v = caml_alloc_small (1, uannot);
2928 tup_v = caml_alloc_tuple (2);
2929 Field (ret_v, 0) = tup_v;
2930 Field (tup_v, 0) = ptr_v;
2931 Field (tup_v, 1) = n_v;
2933 unlock (__func__);
2935 CAMLreturn (ret_v);
2938 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2940 CAMLparam2 (ptr_v, n_v);
2941 pdf_document *pdf;
2942 const char *contents = "";
2944 lock (__func__);
2945 pdf = pdf_specifics (state.ctx, state.doc);
2946 if (pdf) {
2947 char *s = String_val (ptr_v);
2948 struct page *page;
2949 struct slink *slink;
2951 page = parse_pointer (__func__, s);
2952 slink = &page->slinks[Int_val (n_v)];
2953 contents = pdf_annot_contents (state.ctx,
2954 (pdf_annot *) slink->u.annot);
2956 unlock (__func__);
2957 CAMLreturn (caml_copy_string (contents));
2960 CAMLprim value ml_getlinkcount (value ptr_v)
2962 CAMLparam1 (ptr_v);
2963 struct page *page;
2964 char *s = String_val (ptr_v);
2966 page = parse_pointer (__func__, s);
2967 CAMLreturn (Val_int (page->slinkcount));
2970 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2972 CAMLparam2 (ptr_v, n_v);
2973 CAMLlocal1 (ret_v);
2974 struct page *page;
2975 struct slink *slink;
2976 char *s = String_val (ptr_v);
2978 page = parse_pointer (__func__, s);
2979 ret_v = caml_alloc_tuple (4);
2980 lock (__func__);
2981 ensureslinks (page);
2983 slink = &page->slinks[Int_val (n_v)];
2984 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2985 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2986 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2987 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2988 unlock (__func__);
2989 CAMLreturn (ret_v);
2992 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2994 CAMLparam3 (ptr_v, x_v, y_v);
2995 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2996 fz_link *link;
2997 struct annot *annot;
2998 struct page *page;
2999 char *ptr = String_val (ptr_v);
3000 int x = Int_val (x_v), y = Int_val (y_v);
3001 struct pagedim *pdim;
3003 ret_v = Val_int (0);
3004 if (trylock (__func__)) {
3005 goto done;
3008 page = parse_pointer (__func__, ptr);
3009 pdim = &state.pagedims[page->pdimno];
3010 x += pdim->bounds.x0;
3011 y += pdim->bounds.y0;
3014 annot = getannot (page, x, y);
3015 if (annot) {
3016 int i, n = -1;
3018 ensureslinks (page);
3019 for (i = 0; i < page->slinkcount; ++i) {
3020 if (page->slinks[i].tag == SANNOT
3021 && page->slinks[i].u.annot == annot->annot) {
3022 n = i;
3023 break;
3026 ret_v = caml_alloc_small (1, uannot);
3027 tup_v = caml_alloc_tuple (2);
3028 Field (ret_v, 0) = tup_v;
3029 Field (tup_v, 0) = ptr_v;
3030 Field (tup_v, 1) = Val_int (n);
3031 goto unlock;
3035 link = getlink (page, x, y);
3036 if (link) {
3037 str_v = caml_copy_string (link->uri);
3038 ret_v = caml_alloc_small (1, uuri);
3039 Field (ret_v, 0) = str_v;
3041 else {
3042 fz_rect *b;
3043 fz_page_block *pageb;
3044 fz_stext_block *block;
3046 ensuretext (page);
3047 for (pageb = page->text->blocks;
3048 pageb < page->text->blocks + page->text->len;
3049 ++pageb) {
3050 fz_stext_line *line;
3051 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3052 block = pageb->u.text;
3054 b = &block->bbox;
3055 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3056 continue;
3058 for (line = block->lines;
3059 line < block->lines + block->len;
3060 ++line) {
3061 fz_stext_span *span;
3063 b = &line->bbox;
3064 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3065 continue;
3067 for (span = line->first_span; span; span = span->next) {
3068 int charnum;
3070 b = &span->bbox;
3071 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3072 continue;
3074 for (charnum = 0; charnum < span->len; ++charnum) {
3075 fz_rect bbox;
3076 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3077 b = &bbox;
3079 if (x >= b->x0 && x <= b->x1
3080 && y >= b->y0 && y <= b->y1) {
3081 fz_stext_style *style = span->text->style;
3082 const char *n2 =
3083 style->font
3084 ? fz_font_name (state.ctx, style->font)
3085 : "Span has no font name"
3087 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3088 style->font);
3089 if (face && face->family_name) {
3090 char *s;
3091 char *n1 = face->family_name;
3092 size_t l1 = strlen (n1);
3093 size_t l2 = strlen (n2);
3095 if (l1 != l2 || memcmp (n1, n2, l1)) {
3096 s = malloc (l1 + l2 + 2);
3097 if (s) {
3098 memcpy (s, n2, l2);
3099 s[l2] = '=';
3100 memcpy (s + l2 + 1, n1, l1 + 1);
3101 str_v = caml_copy_string (s);
3102 free (s);
3106 if (str_v == Val_unit) {
3107 str_v = caml_copy_string (n2);
3109 ret_v = caml_alloc_small (1, utext);
3110 Field (ret_v, 0) = str_v;
3111 goto unlock;
3118 unlock:
3119 unlock (__func__);
3121 done:
3122 CAMLreturn (ret_v);
3125 enum { mark_page, mark_block, mark_line, mark_word };
3127 static int uninteresting (int c)
3129 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3130 || ispunct (c);
3133 CAMLprim void ml_clearmark (value ptr_v)
3135 CAMLparam1 (ptr_v);
3136 char *s = String_val (ptr_v);
3137 struct page *page;
3139 if (trylock (__func__)) {
3140 goto done;
3143 page = parse_pointer (__func__, s);
3144 page->fmark.span = NULL;
3145 page->lmark.span = NULL;
3146 page->fmark.i = 0;
3147 page->lmark.i = 0;
3149 unlock (__func__);
3150 done:
3151 CAMLreturn0;
3154 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3156 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3157 CAMLlocal1 (ret_v);
3158 fz_rect *b;
3159 struct page *page;
3160 fz_stext_line *line;
3161 fz_page_block *pageb;
3162 fz_stext_block *block;
3163 struct pagedim *pdim;
3164 int mark = Int_val (mark_v);
3165 char *s = String_val (ptr_v);
3166 int x = Int_val (x_v), y = Int_val (y_v);
3168 ret_v = Val_bool (0);
3169 if (trylock (__func__)) {
3170 goto done;
3173 page = parse_pointer (__func__, s);
3174 pdim = &state.pagedims[page->pdimno];
3176 ensuretext (page);
3178 if (mark == mark_page) {
3179 int i;
3180 fz_page_block *pb1 = NULL, *pb2 = NULL;
3182 for (i = 0; i < page->text->len; ++i) {
3183 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3184 pb1 = &page->text->blocks[i];
3185 break;
3188 if (!pb1) goto unlock;
3190 for (i = page->text->len - 1; i >= 0; --i) {
3191 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3192 pb2 = &page->text->blocks[i];
3193 break;
3196 if (!pb2) goto unlock;
3198 block = pb1->u.text;
3200 page->fmark.i = 0;
3201 page->fmark.span = block->lines->first_span;
3203 block = pb2->u.text;
3204 line = &block->lines[block->len - 1];
3205 page->lmark.i = line->last_span->len - 1;
3206 page->lmark.span = line->last_span;
3207 ret_v = Val_bool (1);
3208 goto unlock;
3211 x += pdim->bounds.x0;
3212 y += pdim->bounds.y0;
3214 for (pageb = page->text->blocks;
3215 pageb < page->text->blocks + page->text->len;
3216 ++pageb) {
3217 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3218 block = pageb->u.text;
3220 b = &block->bbox;
3221 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3222 continue;
3224 if (mark == mark_block) {
3225 page->fmark.i = 0;
3226 page->fmark.span = block->lines->first_span;
3228 line = &block->lines[block->len - 1];
3229 page->lmark.i = line->last_span->len - 1;
3230 page->lmark.span = line->last_span;
3231 ret_v = Val_bool (1);
3232 goto unlock;
3235 for (line = block->lines;
3236 line < block->lines + block->len;
3237 ++line) {
3238 fz_stext_span *span;
3240 b = &line->bbox;
3241 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3242 continue;
3244 if (mark == mark_line) {
3245 page->fmark.i = 0;
3246 page->fmark.span = line->first_span;
3248 page->lmark.i = line->last_span->len - 1;
3249 page->lmark.span = line->last_span;
3250 ret_v = Val_bool (1);
3251 goto unlock;
3254 for (span = line->first_span; span; span = span->next) {
3255 int charnum;
3257 b = &span->bbox;
3258 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3259 continue;
3261 for (charnum = 0; charnum < span->len; ++charnum) {
3262 fz_rect bbox;
3263 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3264 b = &bbox;
3266 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3267 /* unicode ftw */
3268 int charnum2, charnum3 = -1, charnum4 = -1;
3270 if (uninteresting (span->text[charnum].c)) goto unlock;
3272 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3273 if (uninteresting (span->text[charnum2].c)) {
3274 charnum3 = charnum2 + 1;
3275 break;
3278 if (charnum3 == -1) charnum3 = 0;
3280 charnum4 = charnum;
3281 for (charnum2 = charnum + 1;
3282 charnum2 < span->len;
3283 ++charnum2) {
3284 if (uninteresting (span->text[charnum2].c)) break;
3285 charnum4 = charnum2;
3288 page->fmark.i = charnum3;
3289 page->fmark.span = span;
3291 page->lmark.i = charnum4;
3292 page->lmark.span = span;
3293 ret_v = Val_bool (1);
3294 goto unlock;
3300 unlock:
3301 if (!Bool_val (ret_v)) {
3302 page->fmark.span = NULL;
3303 page->lmark.span = NULL;
3304 page->fmark.i = 0;
3305 page->lmark.i = 0;
3307 unlock (__func__);
3309 done:
3310 CAMLreturn (ret_v);
3313 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3315 CAMLparam3 (ptr_v, x_v, y_v);
3316 CAMLlocal2 (ret_v, res_v);
3317 fz_rect *b = NULL;
3318 struct page *page;
3319 fz_page_block *pageb;
3320 struct pagedim *pdim;
3321 char *s = String_val (ptr_v);
3322 int x = Int_val (x_v), y = Int_val (y_v);
3324 ret_v = Val_int (0);
3325 if (trylock (__func__)) {
3326 goto done;
3329 page = parse_pointer (__func__, s);
3330 pdim = &state.pagedims[page->pdimno];
3331 x += pdim->bounds.x0;
3332 y += pdim->bounds.y0;
3334 ensuretext (page);
3336 for (pageb = page->text->blocks;
3337 pageb < page->text->blocks + page->text->len;
3338 ++pageb) {
3339 switch (pageb->type) {
3340 case FZ_PAGE_BLOCK_TEXT:
3341 b = &pageb->u.text->bbox;
3342 break;
3344 case FZ_PAGE_BLOCK_IMAGE:
3345 b = &pageb->u.image->bbox;
3346 break;
3348 default:
3349 continue;
3352 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3353 break;
3354 b = NULL;
3356 if (b) {
3357 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3358 ret_v = caml_alloc_small (1, 1);
3359 Store_double_field (res_v, 0, b->x0);
3360 Store_double_field (res_v, 1, b->x1);
3361 Store_double_field (res_v, 2, b->y0);
3362 Store_double_field (res_v, 3, b->y1);
3363 Field (ret_v, 0) = res_v;
3365 unlock (__func__);
3367 done:
3368 CAMLreturn (ret_v);
3371 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3373 CAMLparam2 (ptr_v, rect_v);
3374 fz_rect b;
3375 struct page *page;
3376 struct pagedim *pdim;
3377 char *s = String_val (ptr_v);
3378 int i, x0, x1, y0, y1, fi, li;
3379 fz_stext_line *line;
3380 fz_page_block *pageb;
3381 fz_stext_block *block;
3382 fz_stext_span *span, *fspan, *lspan;
3384 if (trylock (__func__)) {
3385 goto done;
3388 page = parse_pointer (__func__, s);
3389 ensuretext (page);
3391 pdim = &state.pagedims[page->pdimno];
3392 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3393 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3394 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3395 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3397 if (y0 > y1) {
3398 int t = y0;
3399 y0 = y1;
3400 y1 = t;
3401 x0 = x1;
3402 x1 = t;
3405 fi = page->fmark.i;
3406 fspan = page->fmark.span;
3408 li = page->lmark.i;
3409 lspan = page->lmark.span;
3411 for (pageb = page->text->blocks;
3412 pageb < page->text->blocks + page->text->len;
3413 ++pageb) {
3414 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3415 block = pageb->u.text;
3416 for (line = block->lines;
3417 line < block->lines + block->len;
3418 ++line) {
3420 for (span = line->first_span; span; span = span->next) {
3421 for (i = 0; i < span->len; ++i) {
3422 fz_stext_char_bbox (state.ctx, &b, span, i);
3424 if (x0 >= b.x0 && x0 <= b.x1
3425 && y0 >= b.y0 && y0 <= b.y1) {
3426 fspan = span;
3427 fi = i;
3429 if (x1 >= b.x0 && x1 <= b.x1
3430 && y1 >= b.y0 && y1 <= b.y1) {
3431 lspan = span;
3432 li = i;
3438 if (x1 < x0 && fspan == lspan) {
3439 i = fi;
3440 span = fspan;
3442 fi = li;
3443 fspan = lspan;
3445 li = i;
3446 lspan = span;
3449 page->fmark.i = fi;
3450 page->fmark.span = fspan;
3452 page->lmark.i = li;
3453 page->lmark.span = lspan;
3455 unlock (__func__);
3457 done:
3458 CAMLreturn0;
3461 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3463 char buf[4];
3464 int i, len, ret;
3466 for (i = a; i <= b; ++i) {
3467 len = fz_runetochar (buf, span->text[i].c);
3468 ret = fwrite (buf, len, 1, f);
3470 if (ret != 1) {
3471 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3472 len, ret, strerror (errno));
3473 return -1;
3476 return 0;
3479 #ifdef __CYGWIN__
3480 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3482 caml_failwith ("ml_popen not implemented under Cygwin");
3484 #else
3485 CAMLprim value ml_spawn (value command_v, value fds_v)
3487 CAMLparam2 (command_v, fds_v);
3488 CAMLlocal2 (l_v, tup_v);
3489 int ret, ret1;
3490 pid_t pid;
3491 char *msg = NULL;
3492 value earg_v = Nothing;
3493 posix_spawnattr_t attr;
3494 posix_spawn_file_actions_t fa;
3495 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3497 argv[2] = String_val (command_v);
3499 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3500 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3503 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3504 msg = "posix_spawnattr_init";
3505 goto fail1;
3508 #ifdef POSIX_SPAWN_USEVFORK
3509 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3510 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3511 goto fail;
3513 #endif
3515 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3516 int fd1, fd2;
3518 tup_v = Field (l_v, 0);
3519 fd1 = Int_val (Field (tup_v, 0));
3520 fd2 = Int_val (Field (tup_v, 1));
3521 if (fd2 < 0) {
3522 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3523 msg = "posix_spawn_file_actions_addclose";
3524 earg_v = tup_v;
3525 goto fail;
3528 else {
3529 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3530 msg = "posix_spawn_file_actions_adddup2";
3531 earg_v = tup_v;
3532 goto fail;
3537 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3538 msg = "posix_spawn";
3539 goto fail;
3542 fail:
3543 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3544 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3547 fail1:
3548 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3549 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3550 strerror (ret1));
3553 if (msg)
3554 unix_error (ret, msg, earg_v);
3556 CAMLreturn (Val_int (pid));
3558 #endif
3560 CAMLprim value ml_hassel (value ptr_v)
3562 CAMLparam1 (ptr_v);
3563 CAMLlocal1 (ret_v);
3564 struct page *page;
3565 char *s = String_val (ptr_v);
3567 ret_v = Val_bool (0);
3568 if (trylock (__func__)) {
3569 goto done;
3572 page = parse_pointer (__func__, s);
3573 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3574 unlock (__func__);
3575 done:
3576 CAMLreturn (ret_v);
3579 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3581 CAMLparam2 (fd_v, ptr_v);
3582 FILE *f;
3583 int seen = 0;
3584 struct page *page;
3585 fz_stext_line *line;
3586 fz_page_block *pageb;
3587 fz_stext_block *block;
3588 int fd = Int_val (fd_v);
3589 char *s = String_val (ptr_v);
3591 if (trylock (__func__)) {
3592 goto done;
3595 page = parse_pointer (__func__, s);
3597 if (!page->fmark.span || !page->lmark.span) {
3598 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3599 goto unlock;
3602 f = fdopen (fd, "w");
3603 if (!f) {
3604 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3605 fd, strerror (errno));
3606 f = stdout;
3609 for (pageb = page->text->blocks;
3610 pageb < page->text->blocks + page->text->len;
3611 ++pageb) {
3612 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3613 block = pageb->u.text;
3614 for (line = block->lines;
3615 line < block->lines + block->len;
3616 ++line) {
3617 fz_stext_span *span;
3619 for (span = line->first_span; span; span = span->next) {
3620 int a, b;
3622 seen |= span == page->fmark.span || span == page->lmark.span;
3623 a = span == page->fmark.span ? page->fmark.i : 0;
3624 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3626 if (seen) {
3627 if (pipespan (f, span, a, b)) {
3628 goto close;
3630 if (span == page->lmark.span) {
3631 goto close;
3633 if (span == line->last_span) {
3634 if (putc ('\n', f) == EOF) {
3635 fprintf (stderr,
3636 "failed break line on sel pipe: %s\n",
3637 strerror (errno));
3638 goto close;
3645 close:
3646 if (f != stdout) {
3647 int ret = fclose (f);
3648 fd = -1;
3649 if (ret == -1) {
3650 if (errno != ECHILD) {
3651 fprintf (stderr, "failed to close sel pipe: %s\n",
3652 strerror (errno));
3656 unlock:
3657 unlock (__func__);
3659 done:
3660 if (fd >= 0) {
3661 if (close (fd)) {
3662 fprintf (stderr, "failed to close sel pipe: %s\n",
3663 strerror (errno));
3666 CAMLreturn0;
3669 CAMLprim value ml_getpdimrect (value pagedimno_v)
3671 CAMLparam1 (pagedimno_v);
3672 CAMLlocal1 (ret_v);
3673 int pagedimno = Int_val (pagedimno_v);
3674 fz_rect box;
3676 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3677 if (trylock (__func__)) {
3678 box = fz_empty_rect;
3680 else {
3681 box = state.pagedims[pagedimno].mediabox;
3682 unlock (__func__);
3685 Store_double_field (ret_v, 0, box.x0);
3686 Store_double_field (ret_v, 1, box.x1);
3687 Store_double_field (ret_v, 2, box.y0);
3688 Store_double_field (ret_v, 3, box.y1);
3690 CAMLreturn (ret_v);
3693 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3694 value dw_v, value cols_v)
3696 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3697 CAMLlocal1 (ret_v);
3698 int i;
3699 double zoom = -1.;
3700 double maxh = 0.0;
3701 struct pagedim *p;
3702 double winw = Int_val (winw_v);
3703 double winh = Int_val (winh_v);
3704 double dw = Int_val (dw_v);
3705 double cols = Int_val (cols_v);
3706 double pw = 1.0, ph = 1.0;
3708 if (trylock (__func__)) {
3709 goto done;
3712 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3713 double w = p->pagebox.x1 / cols;
3714 double h = p->pagebox.y1;
3715 if (h > maxh) {
3716 maxh = h;
3717 ph = h;
3718 if (state.fitmodel != FitProportional) pw = w;
3720 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3723 zoom = (((winh / ph) * pw) + dw) / winw;
3724 unlock (__func__);
3725 done:
3726 ret_v = caml_copy_double (zoom);
3727 CAMLreturn (ret_v);
3730 CAMLprim value ml_getmaxw (value unit_v)
3732 CAMLparam1 (unit_v);
3733 CAMLlocal1 (ret_v);
3734 int i;
3735 double maxw = -1.;
3736 struct pagedim *p;
3738 if (trylock (__func__)) {
3739 goto done;
3742 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3743 double w = p->pagebox.x1;
3744 maxw = fz_max (maxw, w);
3747 unlock (__func__);
3748 done:
3749 ret_v = caml_copy_double (maxw);
3750 CAMLreturn (ret_v);
3753 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3755 CAMLparam4 (pt_v, x_v, y_v, string_v);
3756 CAMLlocal1 (ret_v);
3757 int pt = Int_val(pt_v);
3758 int x = Int_val (x_v);
3759 int y = Int_val (y_v);
3760 double w;
3762 w = draw_string (state.face, pt, x, y, String_val (string_v));
3763 ret_v = caml_copy_double (w);
3764 CAMLreturn (ret_v);
3767 CAMLprim value ml_measure_string (value pt_v, value string_v)
3769 CAMLparam2 (pt_v, string_v);
3770 CAMLlocal1 (ret_v);
3771 int pt = Int_val (pt_v);
3772 double w;
3774 w = measure_string (state.face, pt, String_val (string_v));
3775 ret_v = caml_copy_double (w);
3776 CAMLreturn (ret_v);
3779 CAMLprim value ml_getpagebox (value opaque_v)
3781 CAMLparam1 (opaque_v);
3782 CAMLlocal1 (ret_v);
3783 fz_rect rect;
3784 fz_irect bbox;
3785 fz_matrix ctm;
3786 fz_device *dev;
3787 char *s = String_val (opaque_v);
3788 struct page *page = parse_pointer (__func__, s);
3790 ret_v = caml_alloc_tuple (4);
3791 dev = fz_new_bbox_device (state.ctx, &rect);
3793 ctm = pagectm (page);
3794 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3796 fz_close_device (state.ctx, dev);
3797 fz_drop_device (state.ctx, dev);
3798 fz_round_rect (&bbox, &rect);
3799 Field (ret_v, 0) = Val_int (bbox.x0);
3800 Field (ret_v, 1) = Val_int (bbox.y0);
3801 Field (ret_v, 2) = Val_int (bbox.x1);
3802 Field (ret_v, 3) = Val_int (bbox.y1);
3804 CAMLreturn (ret_v);
3807 CAMLprim void ml_setaalevel (value level_v)
3809 CAMLparam1 (level_v);
3811 state.aalevel = Int_val (level_v);
3812 CAMLreturn0;
3815 #ifndef __COCOA__
3816 #pragma GCC diagnostic push
3817 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3818 #include <X11/Xlib.h>
3819 #include <X11/cursorfont.h>
3820 #pragma GCC diagnostic pop
3822 #ifdef USE_EGL
3823 #include <EGL/egl.h>
3824 #else
3825 #include <GL/glx.h>
3826 #endif
3828 static const int shapes[] = {
3829 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3832 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3834 static struct {
3835 Window wid;
3836 Display *dpy;
3837 #ifdef USE_EGL
3838 EGLContext ctx;
3839 EGLConfig conf;
3840 EGLSurface win;
3841 EGLDisplay *edpy;
3842 #else
3843 GLXContext ctx;
3844 #endif
3845 XVisualInfo *visual;
3846 Cursor curs[CURS_COUNT];
3847 } glx;
3850 static void initcurs (void)
3852 for (size_t n = 0; n < CURS_COUNT; ++n) {
3853 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3857 CAMLprim void ml_setbgcol (value color_v)
3859 CAMLparam1 (color_v);
3860 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3861 CAMLreturn0;
3864 #ifdef USE_EGL
3865 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3867 CAMLparam3 (display_v, wid_v, screen_v);
3868 int major, minor;
3869 int num_conf;
3870 EGLint visid;
3871 EGLint attribs[] = {
3872 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3873 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3874 EGL_NONE
3876 EGLConfig conf;
3878 glx.dpy = XOpenDisplay (String_val (display_v));
3879 if (!glx.dpy) {
3880 caml_failwith ("XOpenDisplay");
3883 eglBindAPI (EGL_OPENGL_API);
3885 glx.edpy = eglGetDisplay (glx.dpy);
3886 if (glx.edpy == EGL_NO_DISPLAY) {
3887 caml_failwith ("eglGetDisplay");
3890 if (!eglInitialize (glx.edpy, &major, &minor)) {
3891 caml_failwith ("eglInitialize");
3894 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3895 !num_conf) {
3896 caml_failwith ("eglChooseConfig");
3899 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3900 caml_failwith ("eglGetConfigAttrib");
3903 glx.conf = conf;
3904 initcurs ();
3906 glx.wid = Int_val (wid_v);
3907 CAMLreturn (Val_int (visid));
3910 CAMLprim void ml_glxcompleteinit (value unit_v)
3912 CAMLparam1 (unit_v);
3914 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3915 if (!glx.ctx) {
3916 caml_failwith ("eglCreateContext");
3919 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3920 glx.wid, NULL);
3921 if (glx.win == EGL_NO_SURFACE) {
3922 caml_failwith ("eglCreateWindowSurface");
3925 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3926 glx.ctx = NULL;
3927 caml_failwith ("eglMakeCurrent");
3929 CAMLreturn0;
3931 #else
3932 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3934 CAMLparam3 (display_v, wid_v, screen_v);
3936 glx.dpy = XOpenDisplay (String_val (display_v));
3937 if (!glx.dpy) {
3938 caml_failwith ("XOpenDisplay");
3941 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3942 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3943 if (!glx.visual) {
3944 XCloseDisplay (glx.dpy);
3945 caml_failwith ("glXChooseVisual");
3948 initcurs ();
3950 glx.wid = Int_val (wid_v);
3951 CAMLreturn (Val_int (glx.visual->visualid));
3954 CAMLprim void ml_glxcompleteinit (value unit_v)
3956 CAMLparam1 (unit_v);
3958 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3959 if (!glx.ctx) {
3960 caml_failwith ("glXCreateContext");
3963 XFree (glx.visual);
3964 glx.visual = NULL;
3966 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3967 glXDestroyContext (glx.dpy, glx.ctx);
3968 glx.ctx = NULL;
3969 caml_failwith ("glXMakeCurrent");
3971 CAMLreturn0;
3973 #endif
3975 CAMLprim void ml_setcursor (value cursor_v)
3977 CAMLparam1 (cursor_v);
3978 size_t cursn = Int_val (cursor_v);
3980 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3981 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3982 XFlush (glx.dpy);
3983 CAMLreturn0;
3986 CAMLprim void ml_swapb (value unit_v)
3988 CAMLparam1 (unit_v);
3989 #ifdef USE_EGL
3990 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3991 caml_failwith ("eglSwapBuffers");
3993 #else
3994 glXSwapBuffers (glx.dpy, glx.wid);
3995 #endif
3996 CAMLreturn0;
3999 #include "keysym2ucs.c"
4001 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4003 CAMLparam1 (keysym_v);
4004 CAMLlocal1 (str_v);
4005 KeySym keysym = Int_val (keysym_v);
4006 Rune rune;
4007 int len;
4008 char buf[5];
4010 rune = keysym2ucs (keysym);
4011 len = fz_runetochar (buf, rune);
4012 buf[len] = 0;
4013 str_v = caml_copy_string (buf);
4014 CAMLreturn (str_v);
4016 #else
4017 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4019 CAMLparam1 (keysym_v);
4020 CAMLlocal1 (str_v);
4021 long ucs_v = Long_val (keysym_v);
4022 int len;
4023 char buf[5];
4025 len = fz_runetochar (buf, ucs_v);
4026 buf[len] = 0;
4027 str_v = caml_copy_string (buf);
4028 CAMLreturn (str_v);
4030 #endif
4032 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4034 CAMLprim value ml_platform (value unit_v)
4036 CAMLparam1 (unit_v);
4037 CAMLlocal2 (tup_v, arr_v);
4038 int platid = piunknown;
4039 struct utsname buf;
4041 #if defined __linux__
4042 platid = pilinux;
4043 #elif defined __CYGWIN__
4044 platid = picygwin;
4045 #elif defined __DragonFly__ || defined __FreeBSD__
4046 || defined __OpenBSD__ || defined __NetBSD__
4047 platid = pibsd;
4048 #elif defined __sun__
4049 platid = pisun;
4050 #elif defined __APPLE__
4051 platid = piosx;
4052 #endif
4053 if (uname (&buf)) err (1, "uname");
4055 tup_v = caml_alloc_tuple (2);
4057 char const *sar[] = {
4058 buf.sysname,
4059 buf.release,
4060 buf.version,
4061 buf.machine,
4062 NULL
4064 arr_v = caml_copy_string_array (sar);
4066 Field (tup_v, 0) = Val_int (platid);
4067 Field (tup_v, 1) = arr_v;
4068 CAMLreturn (tup_v);
4071 CAMLprim void ml_cloexec (value fd_v)
4073 CAMLparam1 (fd_v);
4074 int fd = Int_val (fd_v);
4076 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4077 uerror ("fcntl", Nothing);
4079 CAMLreturn0;
4082 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4084 CAMLparam2 (w_v, h_v);
4085 CAMLlocal1 (ret_v);
4086 struct bo *pbo;
4087 int w = Int_val (w_v);
4088 int h = Int_val (h_v);
4089 int cs = Int_val (cs_v);
4091 if (state.bo_usable) {
4092 pbo = calloc (sizeof (*pbo), 1);
4093 if (!pbo) {
4094 err (1, "calloc pbo");
4097 switch (cs) {
4098 case 0:
4099 case 1:
4100 pbo->size = w*h*4;
4101 break;
4102 case 2:
4103 pbo->size = w*h*2;
4104 break;
4105 default:
4106 errx (1, "%s: invalid colorspace %d", __func__, cs);
4109 state.glGenBuffersARB (1, &pbo->id);
4110 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4111 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4112 NULL, GL_STREAM_DRAW);
4113 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4114 GL_READ_WRITE);
4115 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4116 if (!pbo->ptr) {
4117 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4118 state.glDeleteBuffersARB (1, &pbo->id);
4119 free (pbo);
4120 ret_v = caml_copy_string ("0");
4122 else {
4123 int res;
4124 char *s;
4126 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4127 if (res < 0) {
4128 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4130 s = malloc (res+1);
4131 if (!s) {
4132 err (1, "malloc %d bytes failed", res+1);
4134 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4135 if (res < 0) {
4136 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4138 ret_v = caml_copy_string (s);
4139 free (s);
4142 else {
4143 ret_v = caml_copy_string ("0");
4145 CAMLreturn (ret_v);
4148 CAMLprim void ml_freepbo (value s_v)
4150 CAMLparam1 (s_v);
4151 char *s = String_val (s_v);
4152 struct tile *tile = parse_pointer (__func__, s);
4154 if (tile->pbo) {
4155 state.glDeleteBuffersARB (1, &tile->pbo->id);
4156 tile->pbo->id = -1;
4157 tile->pbo->ptr = NULL;
4158 tile->pbo->size = -1;
4160 CAMLreturn0;
4163 CAMLprim void ml_unmappbo (value s_v)
4165 CAMLparam1 (s_v);
4166 char *s = String_val (s_v);
4167 struct tile *tile = parse_pointer (__func__, s);
4169 if (tile->pbo) {
4170 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4171 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4172 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4174 tile->pbo->ptr = NULL;
4175 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4177 CAMLreturn0;
4180 static void setuppbo (void)
4182 #ifdef __COCOA__
4183 static CFBundleRef framework = NULL;
4184 if (framework == NULL)
4185 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
4186 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
4187 #else
4188 #ifdef USE_EGL
4189 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4190 #else
4191 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4192 #endif
4193 state.bo_usable = GGPA (glBindBufferARB)
4194 && GGPA (glUnmapBufferARB)
4195 && GGPA (glMapBufferARB)
4196 && GGPA (glBufferDataARB)
4197 && GGPA (glGenBuffersARB)
4198 && GGPA (glDeleteBuffersARB);
4199 #endif
4200 #undef GGPA
4203 CAMLprim value ml_bo_usable (value unit_v)
4205 CAMLparam1 (unit_v);
4206 CAMLreturn (Val_bool (state.bo_usable));
4209 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4211 CAMLparam3 (ptr_v, x_v, y_v);
4212 CAMLlocal2 (ret_v, tup_v);
4213 struct page *page;
4214 char *s = String_val (ptr_v);
4215 int x = Int_val (x_v), y = Int_val (y_v);
4216 struct pagedim *pdim;
4217 fz_point p;
4218 fz_matrix ctm;
4220 page = parse_pointer (__func__, s);
4221 pdim = &state.pagedims[page->pdimno];
4223 ret_v = Val_int (0);
4224 if (trylock (__func__)) {
4225 goto done;
4228 if (pdf_specifics (state.ctx, state.doc)) {
4229 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4230 ctm = state.pagedims[page->pdimno].tctm;
4232 else {
4233 ctm = fz_identity;
4235 p.x = x + pdim->bounds.x0;
4236 p.y = y + pdim->bounds.y0;
4238 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4239 fz_invert_matrix (&ctm, &ctm);
4240 fz_transform_point (&p, &ctm);
4242 tup_v = caml_alloc_tuple (2);
4243 ret_v = caml_alloc_small (1, 1);
4244 Field (tup_v, 0) = Val_int (p.x);
4245 Field (tup_v, 1) = Val_int (p.y);
4246 Field (ret_v, 0) = tup_v;
4248 unlock (__func__);
4249 done:
4250 CAMLreturn (ret_v);
4253 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4254 value x_v, value y_v)
4256 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4257 CAMLlocal1 (ret_v);
4258 struct page *page;
4259 char *s = String_val (ptr_v);
4260 int pageno = Int_val (pageno_v);
4261 int pdimno = Int_val (pdimno_v);
4262 double x = Double_val (x_v), y = Double_val (y_v);
4263 struct pagedim *pdim;
4264 fz_point p;
4265 fz_matrix ctm;
4267 ret_v = Val_int (0);
4268 lock (__func__);
4270 if (!*s) {
4271 page = loadpage (pageno, pdimno);
4273 else {
4274 page = parse_pointer (__func__, s);
4276 pdim = &state.pagedims[pdimno];
4278 if (pdf_specifics (state.ctx, state.doc)) {
4279 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4280 ctm = state.pagedims[page->pdimno].tctm;
4282 else {
4283 ctm = fz_identity;
4285 p.x = x + pdim->bounds.x0;
4286 p.y = y + pdim->bounds.y0;
4288 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4289 fz_transform_point (&p, &ctm);
4291 ret_v = caml_alloc_tuple (2);
4292 Field (ret_v, 0) = caml_copy_double (p.x);
4293 Field (ret_v, 1) = caml_copy_double (p.y);
4295 if (!*s) {
4296 freepage (page);
4298 unlock (__func__);
4299 CAMLreturn (ret_v);
4302 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4303 value contents_v)
4305 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4306 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4308 if (pdf) {
4309 pdf_annot *annot;
4310 struct page *page;
4311 fz_point p;
4312 char *s = String_val (ptr_v);
4314 page = parse_pointer (__func__, s);
4315 annot = pdf_create_annot (state.ctx,
4316 pdf_page_from_fz_page (state.ctx,
4317 page->fzpage),
4318 PDF_ANNOT_TEXT);
4319 p.x = Int_val (x_v);
4320 p.y = Int_val (y_v);
4321 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4322 pdf_set_text_annot_position (state.ctx, annot, p);
4323 state.dirty = 1;
4325 CAMLreturn0;
4328 CAMLprim void ml_delannot (value ptr_v, value n_v)
4330 CAMLparam2 (ptr_v, n_v);
4331 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4333 if (pdf) {
4334 struct page *page;
4335 char *s = String_val (ptr_v);
4336 struct slink *slink;
4338 page = parse_pointer (__func__, s);
4339 slink = &page->slinks[Int_val (n_v)];
4340 pdf_delete_annot (state.ctx,
4341 pdf_page_from_fz_page (state.ctx, page->fzpage),
4342 (pdf_annot *) slink->u.annot);
4343 state.dirty = 1;
4345 CAMLreturn0;
4348 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4350 CAMLparam3 (ptr_v, n_v, str_v);
4351 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4353 if (pdf) {
4354 struct page *page;
4355 char *s = String_val (ptr_v);
4356 struct slink *slink;
4358 page = parse_pointer (__func__, s);
4359 slink = &page->slinks[Int_val (n_v)];
4360 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4361 String_val (str_v));
4362 state.dirty = 1;
4364 CAMLreturn0;
4367 CAMLprim value ml_hasunsavedchanges (value unit_v)
4369 CAMLparam1 (unit_v);
4370 CAMLreturn (Val_bool (state.dirty));
4373 CAMLprim void ml_savedoc (value path_v)
4375 CAMLparam1 (path_v);
4376 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4378 if (pdf) {
4379 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4381 CAMLreturn0;
4384 static void makestippletex (void)
4386 const char pixels[] = "\xff\xff\0\0";
4387 glGenTextures (1, &state.stid);
4388 glBindTexture (GL_TEXTURE_1D, state.stid);
4389 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4390 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4391 glTexImage1D (
4392 GL_TEXTURE_1D,
4394 GL_ALPHA,
4397 GL_ALPHA,
4398 GL_UNSIGNED_BYTE,
4399 pixels
4403 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4405 return caml_copy_string (FZ_VERSION);
4408 CAMLprim void ml_init (value csock_v, value params_v)
4410 CAMLparam2 (csock_v, params_v);
4411 CAMLlocal2 (trim_v, fuzz_v);
4412 int ret;
4413 int texcount;
4414 char *fontpath;
4415 int colorspace;
4416 int mustoresize;
4417 int haspboext;
4419 /* Without following call to setlocale mbstowcs fails for, at
4420 least, strings containing chinese symbols (δΈ­ for instance)
4421 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4422 wide character" as the reason of failure and with macOS
4423 producing bogus output) */
4424 if (setlocale (LC_CTYPE, "")) {
4425 /* Following two lines were taken from dvtm/vt.c */
4426 const char *cset = nl_langinfo (CODESET);
4427 state.utf8cs = !strcmp (cset, "UTF-8");
4429 else {
4430 fprintf (stderr, "setlocale failed\n");
4433 state.csock = Int_val (csock_v);
4434 state.rotate = Int_val (Field (params_v, 0));
4435 state.fitmodel = Int_val (Field (params_v, 1));
4436 trim_v = Field (params_v, 2);
4437 texcount = Int_val (Field (params_v, 3));
4438 state.sliceheight = Int_val (Field (params_v, 4));
4439 mustoresize = Int_val (Field (params_v, 5));
4440 colorspace = Int_val (Field (params_v, 6));
4441 fontpath = String_val (Field (params_v, 7));
4443 if (caml_string_length (Field (params_v, 8)) > 0) {
4444 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4446 if (!state.trimcachepath) {
4447 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4448 strerror (errno));
4452 haspboext = Bool_val (Field (params_v, 9));
4454 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4455 fz_register_document_handlers (state.ctx);
4457 state.trimmargins = Bool_val (Field (trim_v, 0));
4458 fuzz_v = Field (trim_v, 1);
4459 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4460 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4461 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4462 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4464 set_tex_params (colorspace);
4466 if (*fontpath) {
4467 state.face = load_font (fontpath);
4469 else {
4470 int len;
4471 const unsigned char *data;
4473 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4474 state.face = load_builtin_font (data, len);
4476 if (!state.face) _exit (1);
4478 realloctexts (texcount);
4480 if (haspboext) {
4481 setuppbo ();
4484 makestippletex ();
4486 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4487 if (ret) {
4488 errx (1, "pthread_create: %s", strerror (ret));
4491 CAMLreturn0;