Track external fullscreen-ing properly
[llpp.git] / link.c
blob4d238695524ab95b0c8dd3233f52e89881b1707c
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, 1, pbo->ptr);
788 tile->pbo = pbo;
790 else {
791 tile->pixmap =
792 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
796 tile->w = w;
797 tile->h = h;
798 clearpixmap (tile->pixmap);
800 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
801 ctm = pagectm (page);
802 fz_rect_from_irect (&rect, &bbox);
803 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
804 fz_close_device (state.ctx, dev);
805 fz_drop_device (state.ctx, dev);
807 return tile;
810 #ifdef CACHE_PAGEREFS
811 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
812 thanks to Robin Watts */
813 static void
814 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
816 fz_context *ctx = state.ctx; /* doc->ctx; */
817 pdf_obj *kids;
818 int len;
820 if (state.pdflut.idx == state.pagecount) return;
822 kids = pdf_dict_gets (ctx, node, "Kids");
823 len = pdf_array_len (ctx, kids);
825 if (len == 0)
826 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
828 if (pdf_mark_obj (ctx, node))
829 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
830 for (int i = 0; i < len; i++) {
831 pdf_obj *kid = pdf_array_get (ctx, kids, i);
832 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
833 if (*type
834 ? !strcmp (type, "Pages")
835 : pdf_dict_gets (ctx, kid, "Kids")
836 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
837 pdf_collect_pages (doc, kid);
839 else {
840 if (*type
841 ? strcmp (type, "Page") != 0
842 : !pdf_dict_gets (ctx, kid, "MediaBox"))
843 fz_warn (ctx, "non-page object in page tree (%s)", type);
844 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
847 pdf_unmark_obj (ctx, node);
850 static void
851 pdf_load_page_objs (pdf_document *doc)
853 pdf_obj *root = pdf_dict_gets (state.ctx,
854 pdf_trailer (state.ctx, doc), "Root");
855 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
857 if (!node)
858 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
860 state.pdflut.idx = 0;
861 pdf_collect_pages (doc, node);
863 #endif
865 static void initpdims (int wthack)
867 double start, end;
868 FILE *trimf = NULL;
869 fz_rect rootmediabox;
870 int pageno, trim, show;
871 int trimw = 0, cxcount;
872 fz_context *ctx = state.ctx;
873 pdf_document *pdf = pdf_specifics (ctx, state.doc);
875 fz_var (trimw);
876 fz_var (trimf);
877 fz_var (cxcount);
878 start = now ();
880 if (state.trimmargins && state.trimcachepath) {
881 trimf = fopen (state.trimcachepath, "rb");
882 if (!trimf) {
883 trimf = fopen (state.trimcachepath, "wb");
884 trimw = 1;
888 if (state.trimmargins || pdf || !state.cxack)
889 cxcount = state.pagecount;
890 else
891 cxcount = fz_mini (state.pagecount, 1);
893 if (pdf) {
894 pdf_obj *obj;
895 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
896 "Root/Pages/MediaBox");
897 pdf_to_rect (ctx, obj, &rootmediabox);
900 #ifdef CACHE_PAGEREFS
901 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
902 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
903 if (!state.pdflut.objs) {
904 err (1, "malloc pageobjs %zu %d %zu failed",
905 sizeof (*state.pdflut.objs), cxcount,
906 sizeof (*state.pdflut.objs) * cxcount);
908 state.pdflut.count = cxcount;
909 pdf_load_page_objs (pdf);
910 state.pdflut.pdf = pdf;
912 #endif
914 for (pageno = 0; pageno < cxcount; ++pageno) {
915 int rotate = 0;
916 struct pagedim *p;
917 fz_rect mediabox;
919 fz_var (rotate);
920 if (pdf) {
921 pdf_obj *pageref, *pageobj;
923 #ifdef CACHE_PAGEREFS
924 pageref = state.pdflut.objs[pageno];
925 #else
926 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
927 #endif
928 pageobj = pdf_resolve_indirect (ctx, pageref);
929 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
931 if (state.trimmargins) {
932 pdf_obj *obj;
933 pdf_page *page;
935 fz_try (ctx) {
936 page = pdf_load_page (ctx, pdf, pageno);
937 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
938 trim = state.trimanew || !obj;
939 if (trim) {
940 fz_rect rect;
941 fz_device *dev;
942 fz_matrix ctm, page_ctm;
944 dev = fz_new_bbox_device (ctx, &rect);
945 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
946 fz_invert_matrix (&ctm, &page_ctm);
947 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
948 fz_close_device (ctx, dev);
949 fz_drop_device (ctx, dev);
951 rect.x0 += state.trimfuzz.x0;
952 rect.x1 += state.trimfuzz.x1;
953 rect.y0 += state.trimfuzz.y0;
954 rect.y1 += state.trimfuzz.y1;
955 fz_transform_rect (&rect, &ctm);
956 fz_intersect_rect (&rect, &mediabox);
958 if (!fz_is_empty_rect (&rect)) {
959 mediabox = rect;
962 obj = pdf_new_array (ctx, pdf, 4);
963 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
964 mediabox.x0));
965 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
966 mediabox.y0));
967 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
968 mediabox.x1));
969 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
970 mediabox.y1));
971 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
973 else {
974 mediabox.x0 = pdf_to_real (ctx,
975 pdf_array_get (ctx, obj, 0));
976 mediabox.y0 = pdf_to_real (ctx,
977 pdf_array_get (ctx, obj, 1));
978 mediabox.x1 = pdf_to_real (ctx,
979 pdf_array_get (ctx, obj, 2));
980 mediabox.y1 = pdf_to_real (ctx,
981 pdf_array_get (ctx, obj, 3));
984 fz_drop_page (ctx, &page->super);
985 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
986 if (show) {
987 printd ("progress %f Trimming %d",
988 (double) (pageno + 1) / state.pagecount,
989 pageno + 1);
992 fz_catch (ctx) {
993 fprintf (stderr, "failed to load page %d\n", pageno+1);
996 else {
997 int empty = 0;
998 fz_rect cropbox;
1000 pdf_to_rect (ctx,
1001 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1002 &mediabox);
1003 if (fz_is_empty_rect (&mediabox)) {
1004 mediabox.x0 = 0;
1005 mediabox.y0 = 0;
1006 mediabox.x1 = 612;
1007 mediabox.y1 = 792;
1008 empty = 1;
1011 pdf_to_rect (ctx,
1012 pdf_dict_gets (ctx, pageobj, "CropBox"),
1013 &cropbox);
1014 if (!fz_is_empty_rect (&cropbox)) {
1015 if (empty) {
1016 mediabox = cropbox;
1018 else {
1019 fz_intersect_rect (&mediabox, &cropbox);
1022 else {
1023 if (empty) {
1024 if (fz_is_empty_rect (&rootmediabox)) {
1025 fprintf (stderr,
1026 "cannot find page size for page %d\n",
1027 pageno+1);
1029 else {
1030 mediabox = rootmediabox;
1036 else {
1037 if (state.trimmargins && trimw) {
1038 fz_page *page;
1040 fz_try (ctx) {
1041 page = fz_load_page (ctx, state.doc, pageno);
1042 fz_bound_page (ctx, page, &mediabox);
1043 if (state.trimmargins) {
1044 fz_rect rect;
1045 fz_device *dev;
1047 dev = fz_new_bbox_device (ctx, &rect);
1048 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1049 fz_close_device (ctx, dev);
1050 fz_drop_device (ctx, dev);
1052 rect.x0 += state.trimfuzz.x0;
1053 rect.x1 += state.trimfuzz.x1;
1054 rect.y0 += state.trimfuzz.y0;
1055 rect.y1 += state.trimfuzz.y1;
1056 fz_intersect_rect (&rect, &mediabox);
1058 if (!fz_is_empty_rect (&rect)) {
1059 mediabox = rect;
1062 fz_drop_page (ctx, page);
1063 if (!state.cxack) {
1064 printd ("progress %f loading %d",
1065 (double) (pageno + 1) / state.pagecount,
1066 pageno + 1);
1069 fz_catch (ctx) {
1071 if (trimf) {
1072 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1073 if (n - 1) {
1074 err (1, "fwrite trim mediabox");
1078 else {
1079 if (trimf) {
1080 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1081 if (n - 1) {
1082 err (1, "fread trim mediabox %d", pageno);
1085 else {
1086 fz_page *page;
1087 fz_try (ctx) {
1088 page = fz_load_page (ctx, state.doc, pageno);
1089 fz_bound_page (ctx, page, &mediabox);
1090 fz_drop_page (ctx, page);
1092 show = !state.trimmargins && pageno % 20 == 0;
1093 if (show) {
1094 printd ("progress %f Gathering dimensions %d",
1095 (double) (pageno) / state.pagecount,
1096 pageno);
1099 fz_catch (ctx) {
1100 fprintf (stderr, "failed to load page %d\n", pageno);
1106 if (state.pagedimcount == 0
1107 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1108 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1109 size_t size;
1111 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1112 state.pagedims = realloc (state.pagedims, size);
1113 if (!state.pagedims) {
1114 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1115 size, state.pagedimcount + 1);
1118 p = &state.pagedims[state.pagedimcount++];
1119 p->rotate = rotate;
1120 p->mediabox = mediabox;
1121 p->pageno = pageno;
1124 end = now ();
1125 if (!wthack) {
1126 printd ("progress 1 %s %d pages in %f seconds",
1127 state.trimmargins ? "Trimmed" : "Processed",
1128 state.pagecount, end - start);
1130 state.trimanew = 0;
1131 if (trimf) {
1132 if (fclose (trimf)) {
1133 err (1, "fclose");
1138 static void layout (void)
1140 int pindex;
1141 fz_rect box;
1142 fz_matrix ctm, rm;
1143 struct pagedim *p = p;
1144 double zw, w, maxw = 0.0, zoom = zoom;
1146 if (state.pagedimcount == 0) return;
1148 switch (state.fitmodel) {
1149 case FitProportional:
1150 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1151 double x0, x1;
1153 p = &state.pagedims[pindex];
1154 fz_rotate (&rm, p->rotate + state.rotate);
1155 box = p->mediabox;
1156 fz_transform_rect (&box, &rm);
1158 x0 = fz_min (box.x0, box.x1);
1159 x1 = fz_max (box.x0, box.x1);
1161 w = x1 - x0;
1162 maxw = fz_max (w, maxw);
1163 zoom = state.w / maxw;
1165 break;
1167 case FitPage:
1168 maxw = state.w;
1169 break;
1171 case FitWidth:
1172 break;
1174 default:
1175 ARSERT (0 && state.fitmodel);
1178 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1179 fz_rect rect;
1180 fz_matrix tm, sm;
1182 p = &state.pagedims[pindex];
1183 fz_rotate (&ctm, state.rotate);
1184 fz_rotate (&rm, p->rotate + state.rotate);
1185 box = p->mediabox;
1186 fz_transform_rect (&box, &rm);
1187 w = box.x1 - box.x0;
1188 switch (state.fitmodel) {
1189 case FitProportional:
1190 p->left = ((maxw - w) * zoom) / 2.0;
1191 break;
1192 case FitPage:
1194 double zh, h;
1195 zw = maxw / w;
1196 h = box.y1 - box.y0;
1197 zh = state.h / h;
1198 zoom = fz_min (zw, zh);
1199 p->left = (maxw - (w * zoom)) / 2.0;
1201 break;
1202 case FitWidth:
1203 p->left = 0;
1204 zoom = state.w / w;
1205 break;
1208 fz_scale (&p->zoomctm, zoom, zoom);
1209 fz_concat (&ctm, &p->zoomctm, &ctm);
1211 fz_rotate (&rm, p->rotate);
1212 p->pagebox = p->mediabox;
1213 fz_transform_rect (&p->pagebox, &rm);
1214 p->pagebox.x1 -= p->pagebox.x0;
1215 p->pagebox.y1 -= p->pagebox.y0;
1216 p->pagebox.x0 = 0;
1217 p->pagebox.y0 = 0;
1218 rect = p->pagebox;
1219 fz_transform_rect (&rect, &ctm);
1220 fz_round_rect (&p->bounds, &rect);
1221 p->ctm = ctm;
1223 fz_translate (&tm, 0, -p->mediabox.y1);
1224 fz_scale (&sm, zoom, -zoom);
1225 fz_concat (&ctm, &tm, &sm);
1227 p->tctmready = 0;
1230 do {
1231 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1232 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1233 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1234 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1235 int boundw = x1 - x0;
1236 int boundh = y1 - y0;
1238 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1239 } while (p-- != state.pagedims);
1242 struct pagedim *pdimofpageno (int pageno)
1244 struct pagedim *pdim = state.pagedims;
1246 for (int i = 0; i < state.pagedimcount; ++i) {
1247 if (state.pagedims[i].pageno > pageno)
1248 break;
1249 pdim = &state.pagedims[i];
1251 return pdim;
1254 static
1255 struct anchor { int n; int x; int y; int w; int h; }
1256 uritoanchor (const char *uri)
1258 fz_point p;
1259 struct anchor a;
1261 a.n = -1;
1262 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1263 if (a.n >= 0) {
1264 struct pagedim *pdim = pdimofpageno (a.n);
1265 fz_transform_point (&p, &pdim->ctm);
1266 a.x = p.x;
1267 a.y = p.y;
1268 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1270 return a;
1273 static void recurse_outline (fz_outline *outline, int level)
1275 while (outline) {
1276 struct anchor a = uritoanchor (outline->uri);
1277 if (a.n >= 0) {
1278 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1280 else {
1281 printd ("on %d %s", level, outline->title);
1283 if (outline->down) {
1284 recurse_outline (outline->down, level + 1);
1286 outline = outline->next;
1290 static void process_outline (void)
1292 fz_outline *outline;
1294 if (!state.needoutline || !state.pagedimcount) return;
1296 state.needoutline = 0;
1297 outline = fz_load_outline (state.ctx, state.doc);
1298 if (outline) {
1299 recurse_outline (outline, 0);
1300 fz_drop_outline (state.ctx, outline);
1304 static char *strofspan (fz_stext_span *span)
1306 char *p;
1307 char utf8[10];
1308 fz_stext_char *ch;
1309 size_t size = 0, cap = 80;
1311 p = malloc (cap + 1);
1312 if (!p) return NULL;
1314 for (ch = span->text; ch < span->text + span->len; ++ch) {
1315 int n = fz_runetochar (utf8, ch->c);
1316 if (size + n > cap) {
1317 cap *= 2;
1318 p = realloc (p, cap + 1);
1319 if (!p) return NULL;
1322 memcpy (p + size, utf8, n);
1323 size += n;
1325 p[size] = 0;
1326 return p;
1329 static int matchspan (regex_t *re, fz_stext_span *span,
1330 int stop, int pageno, double start)
1332 int ret;
1333 char *p;
1334 regmatch_t rm;
1335 int a, b, c;
1336 fz_rect sb, eb;
1337 fz_point p1, p2, p3, p4;
1339 p = strofspan (span);
1340 if (!p) return -1;
1342 ret = regexec (re, p, 1, &rm, 0);
1343 if (ret) {
1344 free (p);
1345 if (ret != REG_NOMATCH) {
1346 size_t size;
1347 char errbuf[80];
1348 size = regerror (ret, re, errbuf, sizeof (errbuf));
1349 printd ("msg regexec error `%.*s'",
1350 (int) size, errbuf);
1351 return -1;
1353 return 0;
1355 else {
1356 int l = span->len;
1358 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1359 c += fz_runelen (span->text[a].c);
1361 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1362 c += fz_runelen (span->text[b].c);
1365 if (fz_runelen (span->text[b].c) > 1) {
1366 b = fz_maxi (0, b-1);
1369 fz_stext_char_bbox (state.ctx, &sb, span, a);
1370 fz_stext_char_bbox (state.ctx, &eb, span, b);
1372 p1.x = sb.x0;
1373 p1.y = sb.y0;
1374 p2.x = eb.x1;
1375 p2.y = sb.y0;
1376 p3.x = eb.x1;
1377 p3.y = eb.y1;
1378 p4.x = sb.x0;
1379 p4.y = eb.y1;
1381 if (!stop) {
1382 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1383 pageno, 1,
1384 p1.x, p1.y,
1385 p2.x, p2.y,
1386 p3.x, p3.y,
1387 p4.x, p4.y);
1389 printd ("progress 1 found at %d `%.*s' in %f sec",
1390 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1391 now () - start);
1393 else {
1394 printd ("match %d %d %f %f %f %f %f %f %f %f",
1395 pageno, 2,
1396 p1.x, p1.y,
1397 p2.x, p2.y,
1398 p3.x, p3.y,
1399 p4.x, p4.y);
1401 free (p);
1402 return 1;
1406 static int compareblocks (const void *l, const void *r)
1408 fz_stext_block const *ls = l;
1409 fz_stext_block const *rs = r;
1410 return ls->bbox.y0 - rs->bbox.y0;
1413 /* wishful thinking function */
1414 static void search (regex_t *re, int pageno, int y, int forward)
1416 int j;
1417 fz_device *tdev;
1418 fz_stext_page *text;
1419 fz_stext_sheet *sheet;
1420 struct pagedim *pdim;
1421 int stop = 0, niters = 0;
1422 double start, end;
1423 fz_page *page;
1425 start = now ();
1426 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1427 if (niters++ == 5) {
1428 niters = 0;
1429 if (hasdata ()) {
1430 printd ("progress 1 attention requested aborting search at %d",
1431 pageno);
1432 stop = 1;
1434 else {
1435 printd ("progress %f searching in page %d",
1436 (double) (pageno + 1) / state.pagecount,
1437 pageno);
1440 pdim = pdimofpageno (pageno);
1441 sheet = fz_new_stext_sheet (state.ctx);
1442 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1443 tdev = fz_new_stext_device (state.ctx, sheet, text, 0);
1445 page = fz_load_page (state.ctx, state.doc, pageno);
1447 fz_matrix ctm = pagectm1 (page, pdim);
1448 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1451 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1452 fz_close_device (state.ctx, tdev);
1453 fz_drop_device (state.ctx, tdev);
1455 for (j = 0; j < text->len; ++j) {
1456 int k;
1457 fz_page_block *pb;
1458 fz_stext_block *block;
1460 pb = &text->blocks[forward ? j : text->len - 1 - j];
1461 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1462 block = pb->u.text;
1464 for (k = 0; k < block->len; ++k) {
1465 fz_stext_line *line;
1466 fz_stext_span *span;
1468 if (forward) {
1469 line = &block->lines[k];
1470 if (line->bbox.y0 < y + 1) continue;
1472 else {
1473 line = &block->lines[block->len - 1 - k];
1474 if (line->bbox.y0 > y - 1) continue;
1477 for (span = line->first_span; span; span = span->next) {
1478 switch (matchspan (re, span, stop, pageno, start)) {
1479 case 0: break;
1480 case 1: stop = 1; break;
1481 case -1: stop = 1; goto endloop;
1486 if (forward) {
1487 pageno += 1;
1488 y = 0;
1490 else {
1491 pageno -= 1;
1492 y = INT_MAX;
1494 endloop:
1495 fz_drop_stext_page (state.ctx, text);
1496 fz_drop_stext_sheet (state.ctx, sheet);
1497 fz_drop_page (state.ctx, page);
1499 end = now ();
1500 if (!stop) {
1501 printd ("progress 1 no matches %f sec", end - start);
1503 printd ("clearrects");
1506 static void set_tex_params (int colorspace)
1508 union {
1509 unsigned char b;
1510 unsigned int s;
1511 } endianness = {1};
1513 switch (colorspace) {
1514 case 0:
1515 state.texiform = GL_RGBA8;
1516 state.texform = GL_RGBA;
1517 state.texty = GL_UNSIGNED_BYTE;
1518 state.colorspace = fz_device_rgb (state.ctx);
1519 break;
1520 case 1:
1521 state.texiform = GL_RGBA8;
1522 state.texform = GL_BGRA;
1523 state.texty = endianness.s > 1
1524 ? GL_UNSIGNED_INT_8_8_8_8
1525 : GL_UNSIGNED_INT_8_8_8_8_REV;
1526 state.colorspace = fz_device_bgr (state.ctx);
1527 break;
1528 case 2:
1529 state.texiform = GL_LUMINANCE_ALPHA;
1530 state.texform = GL_LUMINANCE_ALPHA;
1531 state.texty = GL_UNSIGNED_BYTE;
1532 state.colorspace = fz_device_gray (state.ctx);
1533 break;
1534 default:
1535 errx (1, "invalid colorspce %d", colorspace);
1539 static void realloctexts (int texcount)
1541 size_t size;
1543 if (texcount == state.texcount) return;
1545 if (texcount < state.texcount) {
1546 glDeleteTextures (state.texcount - texcount,
1547 state.texids + texcount);
1550 size = texcount * sizeof (*state.texids);
1551 state.texids = realloc (state.texids, size);
1552 if (!state.texids) {
1553 err (1, "realloc texids %" FMT_s, size);
1556 size = texcount * sizeof (*state.texowners);
1557 state.texowners = realloc (state.texowners, size);
1558 if (!state.texowners) {
1559 err (1, "realloc texowners %" FMT_s, size);
1561 if (texcount > state.texcount) {
1562 glGenTextures (texcount - state.texcount,
1563 state.texids + state.texcount);
1564 for (int i = state.texcount; i < texcount; ++i) {
1565 state.texowners[i].w = -1;
1566 state.texowners[i].slice = NULL;
1569 state.texcount = texcount;
1570 state.texindex = 0;
1573 static char *mbtoutf8 (char *s)
1575 char *p, *r;
1576 wchar_t *tmp;
1577 size_t i, ret, len;
1579 if (state.utf8cs) {
1580 return s;
1583 len = mbstowcs (NULL, s, strlen (s));
1584 if (len == 0) {
1585 return s;
1587 else {
1588 if (len == (size_t) -1) {
1589 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1590 return s;
1594 tmp = calloc (len, sizeof (wchar_t));
1595 if (!tmp) {
1596 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1597 len, sizeof (wchar_t), errno, strerror (errno));
1598 return s;
1601 ret = mbstowcs (tmp, s, len);
1602 if (ret == (size_t) -1) {
1603 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1604 len, errno, strerror (errno));
1605 free (tmp);
1606 return s;
1609 len = 0;
1610 for (i = 0; i < ret; ++i) {
1611 len += fz_runelen (tmp[i]);
1614 p = r = malloc (len + 1);
1615 if (!r) {
1616 printd ("emsg mbtoutf8: malloc(%zu)", len);
1617 free (tmp);
1618 return s;
1621 for (i = 0; i < ret; ++i) {
1622 p += fz_runetochar (p, tmp[i]);
1624 *p = 0;
1625 free (tmp);
1626 return r;
1629 CAMLprim value ml_mbtoutf8 (value s_v)
1631 CAMLparam1 (s_v);
1632 CAMLlocal1 (ret_v);
1633 char *s, *r;
1635 s = String_val (s_v);
1636 r = mbtoutf8 (s);
1637 if (r == s) {
1638 ret_v = s_v;
1640 else {
1641 ret_v = caml_copy_string (r);
1642 free (r);
1644 CAMLreturn (ret_v);
1647 static void * mainloop (void UNUSED_ATTR *unused)
1649 char *p = NULL;
1650 int len, ret, oldlen = 0;
1652 fz_var (p);
1653 fz_var (oldlen);
1654 for (;;) {
1655 len = readlen (state.csock);
1656 if (len == 0) {
1657 errx (1, "readlen returned 0");
1660 if (oldlen < len + 1) {
1661 p = realloc (p, len + 1);
1662 if (!p) {
1663 err (1, "realloc %d failed", len + 1);
1665 oldlen = len + 1;
1667 readdata (state.csock, p, len);
1668 p[len] = 0;
1670 if (!strncmp ("open", p, 4)) {
1671 int wthack, off, usedoccss, ok = 0;
1672 char *password;
1673 char *filename;
1674 char *utf8filename;
1675 size_t filenamelen;
1677 fz_var (ok);
1678 ret = sscanf (p + 5, " %d %d %d %n",
1679 &wthack, &state.cxack, &usedoccss, &off);
1680 if (ret != 3) {
1681 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1684 filename = p + 5 + off;
1685 filenamelen = strlen (filename);
1686 password = filename + filenamelen + 1;
1688 if (password[strlen (password) + 1]) {
1689 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1692 lock ("open");
1693 fz_set_use_document_css (state.ctx, usedoccss);
1694 fz_try (state.ctx) {
1695 ok = openxref (filename, password);
1697 fz_catch (state.ctx) {
1698 utf8filename = mbtoutf8 (filename);
1699 printd ("msg Could not open %s", utf8filename);
1701 if (ok) {
1702 pdfinfo ();
1703 initpdims (wthack);
1705 unlock ("open");
1707 if (ok) {
1708 if (!wthack) {
1709 utf8filename = mbtoutf8 (filename);
1710 printd ("msg Opened %s (press h/F1 to get help)",
1711 utf8filename);
1712 if (utf8filename != filename) {
1713 free (utf8filename);
1716 state.needoutline = 1;
1719 else if (!strncmp ("cs", p, 2)) {
1720 int i, colorspace;
1722 ret = sscanf (p + 2, " %d", &colorspace);
1723 if (ret != 1) {
1724 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1726 lock ("cs");
1727 set_tex_params (colorspace);
1728 for (i = 0; i < state.texcount; ++i) {
1729 state.texowners[i].w = -1;
1730 state.texowners[i].slice = NULL;
1732 unlock ("cs");
1734 else if (!strncmp ("freepage", p, 8)) {
1735 void *ptr;
1737 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1738 if (ret != 1) {
1739 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1741 freepage (ptr);
1743 else if (!strncmp ("freetile", p, 8)) {
1744 void *ptr;
1746 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1747 if (ret != 1) {
1748 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1750 freetile (ptr);
1752 else if (!strncmp ("search", p, 6)) {
1753 int icase, pageno, y, len2, forward;
1754 char *pattern;
1755 regex_t re;
1757 ret = sscanf (p + 6, " %d %d %d %d,%n",
1758 &icase, &pageno, &y, &forward, &len2);
1759 if (ret != 4) {
1760 errx (1, "malformed search `%s' ret=%d", p, ret);
1763 pattern = p + 6 + len2;
1764 ret = regcomp (&re, pattern,
1765 REG_EXTENDED | (icase ? REG_ICASE : 0));
1766 if (ret) {
1767 char errbuf[80];
1768 size_t size;
1770 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1771 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1773 else {
1774 search (&re, pageno, y, forward);
1775 regfree (&re);
1778 else if (!strncmp ("geometry", p, 8)) {
1779 int w, h, fitmodel;
1781 printd ("clear");
1782 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1783 if (ret != 3) {
1784 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1787 lock ("geometry");
1788 state.h = h;
1789 if (w != state.w) {
1790 state.w = w;
1791 for (int i = 0; i < state.texcount; ++i) {
1792 state.texowners[i].slice = NULL;
1795 state.fitmodel = fitmodel;
1796 layout ();
1797 process_outline ();
1799 state.gen++;
1800 unlock ("geometry");
1801 printd ("continue %d", state.pagecount);
1803 else if (!strncmp ("reqlayout", p, 9)) {
1804 char *nameddest;
1805 int rotate, off, h;
1806 unsigned int fitmodel;
1807 pdf_document *pdf;
1809 printd ("clear");
1810 ret = sscanf (p + 9, " %d %u %d %n",
1811 &rotate, &fitmodel, &h, &off);
1812 if (ret != 3) {
1813 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1815 lock ("reqlayout");
1816 pdf = pdf_specifics (state.ctx, state.doc);
1817 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1818 state.gen += 1;
1820 state.rotate = rotate;
1821 state.fitmodel = fitmodel;
1822 state.h = h;
1823 layout ();
1824 process_outline ();
1826 nameddest = p + 9 + off;
1827 if (pdf && nameddest && *nameddest) {
1828 fz_point xy;
1829 struct pagedim *pdim;
1830 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1831 &xy.x, &xy.y);
1832 pdim = pdimofpageno (pageno);
1833 fz_transform_point (&xy, &pdim->ctm);
1834 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1837 state.gen++;
1838 unlock ("reqlayout");
1839 printd ("continue %d", state.pagecount);
1841 else if (!strncmp ("page", p, 4)) {
1842 double a, b;
1843 struct page *page;
1844 int pageno, pindex;
1846 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1847 if (ret != 2) {
1848 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1851 lock ("page");
1852 a = now ();
1853 page = loadpage (pageno, pindex);
1854 b = now ();
1855 unlock ("page");
1857 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1859 else if (!strncmp ("tile", p, 4)) {
1860 int x, y, w, h;
1861 struct page *page;
1862 struct tile *tile;
1863 double a, b;
1864 void *data;
1866 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1867 SCN_ptr_cast (&page), &x, &y, &w, &h,
1868 SCN_ptr_cast (&data));
1869 if (ret != 6) {
1870 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1873 lock ("tile");
1874 a = now ();
1875 tile = rendertile (page, x, y, w, h, data);
1876 b = now ();
1877 unlock ("tile");
1879 printd ("tile %d %d %" FMT_ptr " %u %f",
1880 x, y,
1881 FMT_ptr_cast (tile),
1882 tile->w * tile->h * tile->pixmap->n,
1883 b - a);
1885 else if (!strncmp ("trimset", p, 7)) {
1886 fz_irect fuzz;
1887 int trimmargins;
1889 ret = sscanf (p + 7, " %d %d %d %d %d",
1890 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1891 if (ret != 5) {
1892 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1894 lock ("trimset");
1895 state.trimmargins = trimmargins;
1896 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1897 state.trimanew = 1;
1898 state.trimfuzz = fuzz;
1900 unlock ("trimset");
1902 else if (!strncmp ("settrim", p, 7)) {
1903 fz_irect fuzz;
1904 int trimmargins;
1906 ret = sscanf (p + 7, " %d %d %d %d %d",
1907 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1908 if (ret != 5) {
1909 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1911 printd ("clear");
1912 lock ("settrim");
1913 state.trimmargins = trimmargins;
1914 state.needoutline = 1;
1915 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1916 state.trimanew = 1;
1917 state.trimfuzz = fuzz;
1919 state.pagedimcount = 0;
1920 free (state.pagedims);
1921 state.pagedims = NULL;
1922 initpdims (0);
1923 layout ();
1924 process_outline ();
1925 unlock ("settrim");
1926 printd ("continue %d", state.pagecount);
1928 else if (!strncmp ("sliceh", p, 6)) {
1929 int h;
1931 ret = sscanf (p + 6, " %d", &h);
1932 if (ret != 1) {
1933 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1935 if (h != state.sliceheight) {
1936 state.sliceheight = h;
1937 for (int i = 0; i < state.texcount; ++i) {
1938 state.texowners[i].w = -1;
1939 state.texowners[i].h = -1;
1940 state.texowners[i].slice = NULL;
1944 else if (!strncmp ("interrupt", p, 9)) {
1945 printd ("vmsg interrupted");
1947 else {
1948 errx (1, "unknown command %.*s", len, p);
1951 return 0;
1954 CAMLprim value ml_isexternallink (value uri_v)
1956 CAMLparam1 (uri_v);
1957 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1958 CAMLreturn (Val_bool (ext));
1961 CAMLprim value ml_uritolocation (value uri_v)
1963 CAMLparam1 (uri_v);
1964 CAMLlocal1 (ret_v);
1965 int pageno;
1966 fz_point xy;
1967 struct pagedim *pdim;
1969 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1970 &xy.x, &xy.y);
1971 pdim = pdimofpageno (pageno);
1972 fz_transform_point (&xy, &pdim->ctm);
1973 ret_v = caml_alloc_tuple (3);
1974 Field (ret_v, 0) = Val_int (pageno);
1975 Field (ret_v, 1) = caml_copy_double (xy.x);
1976 Field (ret_v, 2) = caml_copy_double (xy.y);
1977 CAMLreturn (ret_v);
1980 CAMLprim value ml_realloctexts (value texcount_v)
1982 CAMLparam1 (texcount_v);
1983 int ok;
1985 if (trylock (__func__)) {
1986 ok = 0;
1987 goto done;
1989 realloctexts (Int_val (texcount_v));
1990 ok = 1;
1991 unlock (__func__);
1993 done:
1994 CAMLreturn (Val_bool (ok));
1997 static void recti (int x0, int y0, int x1, int y1)
1999 GLfloat *v = state.vertices;
2001 glVertexPointer (2, GL_FLOAT, 0, v);
2002 v[0] = x0; v[1] = y0;
2003 v[2] = x1; v[3] = y0;
2004 v[4] = x0; v[5] = y1;
2005 v[6] = x1; v[7] = y1;
2006 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2009 static void showsel (struct page *page, int ox, int oy)
2011 int seen = 0;
2012 fz_irect bbox;
2013 fz_rect rect;
2014 fz_stext_line *line;
2015 fz_page_block *pageb;
2016 fz_stext_block *block;
2017 struct mark first, last;
2018 unsigned char selcolor[] = {15,15,15,140};
2020 first = page->fmark;
2021 last = page->lmark;
2023 if (!first.span || !last.span) return;
2025 glEnable (GL_BLEND);
2026 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2027 glColor4ubv (selcolor);
2029 ox += state.pagedims[page->pdimno].bounds.x0;
2030 oy += state.pagedims[page->pdimno].bounds.y0;
2031 for (pageb = page->text->blocks;
2032 pageb < page->text->blocks + page->text->len;
2033 ++pageb) {
2034 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2035 block = pageb->u.text;
2037 for (line = block->lines;
2038 line < block->lines + block->len;
2039 ++line) {
2040 fz_stext_span *span;
2041 rect = fz_empty_rect;
2043 for (span = line->first_span; span; span = span->next) {
2044 int i, j, k;
2045 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2047 j = 0;
2048 k = span->len - 1;
2050 if (span == page->fmark.span && span == page->lmark.span) {
2051 seen = 1;
2052 j = fz_mini (first.i, last.i);
2053 k = fz_maxi (first.i, last.i);
2055 else {
2056 if (span == first.span) {
2057 seen = 1;
2058 j = first.i;
2060 else if (span == last.span) {
2061 seen = 1;
2062 k = last.i;
2066 if (seen) {
2067 for (i = j; i <= k; ++i) {
2068 fz_rect bbox1;
2069 fz_union_rect (&rect,
2070 fz_stext_char_bbox (state.ctx, &bbox1,
2071 span, i));
2073 fz_round_rect (&bbox, &rect);
2074 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2075 bbox.x0,
2076 bbox.y0,
2077 bbox.x1,
2078 bbox.y1,
2079 oy, ox);
2081 recti (bbox.x0 + ox, bbox.y0 + oy,
2082 bbox.x1 + ox, bbox.y1 + oy);
2083 if (span == last.span) {
2084 goto done;
2086 rect = fz_empty_rect;
2091 done:
2092 glDisable (GL_BLEND);
2095 #include "glfont.c"
2097 static void stipplerect (fz_matrix *m,
2098 fz_point *p1,
2099 fz_point *p2,
2100 fz_point *p3,
2101 fz_point *p4,
2102 GLfloat *texcoords,
2103 GLfloat *vertices)
2105 fz_transform_point (p1, m);
2106 fz_transform_point (p2, m);
2107 fz_transform_point (p3, m);
2108 fz_transform_point (p4, m);
2110 float w, h, s, t;
2112 w = p2->x - p1->x;
2113 h = p2->y - p1->y;
2114 t = hypotf (w, h) * .25f;
2116 w = p3->x - p2->x;
2117 h = p3->y - p2->y;
2118 s = hypotf (w, h) * .25f;
2120 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2121 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2123 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2124 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2126 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2127 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2129 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2130 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2132 glDrawArrays (GL_LINES, 0, 8);
2135 static void solidrect (fz_matrix *m,
2136 fz_point *p1,
2137 fz_point *p2,
2138 fz_point *p3,
2139 fz_point *p4,
2140 GLfloat *vertices)
2142 fz_transform_point (p1, m);
2143 fz_transform_point (p2, m);
2144 fz_transform_point (p3, m);
2145 fz_transform_point (p4, m);
2146 vertices[0] = p1->x; vertices[1] = p1->y;
2147 vertices[2] = p2->x; vertices[3] = p2->y;
2149 vertices[4] = p3->x; vertices[5] = p3->y;
2150 vertices[6] = p4->x; vertices[7] = p4->y;
2151 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2154 static void highlightlinks (struct page *page, int xoff, int yoff)
2156 fz_matrix ctm, tm, pm;
2157 fz_link *link, *links;
2158 GLfloat *texcoords = state.texcoords;
2159 GLfloat *vertices = state.vertices;
2161 links = fz_load_links (state.ctx, page->fzpage);
2163 glEnable (GL_TEXTURE_1D);
2164 glEnable (GL_BLEND);
2165 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2166 glBindTexture (GL_TEXTURE_1D, state.stid);
2168 xoff -= state.pagedims[page->pdimno].bounds.x0;
2169 yoff -= state.pagedims[page->pdimno].bounds.y0;
2170 fz_translate (&tm, xoff, yoff);
2171 pm = pagectm (page);
2172 fz_concat (&ctm, &pm, &tm);
2174 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2175 glVertexPointer (2, GL_FLOAT, 0, vertices);
2177 for (link = links; link; link = link->next) {
2178 fz_point p1, p2, p3, p4;
2180 p1.x = link->rect.x0;
2181 p1.y = link->rect.y0;
2183 p2.x = link->rect.x1;
2184 p2.y = link->rect.y0;
2186 p3.x = link->rect.x1;
2187 p3.y = link->rect.y1;
2189 p4.x = link->rect.x0;
2190 p4.y = link->rect.y1;
2192 /* TODO: different colours for different schemes */
2193 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2194 else glColor3ub (255, 0, 0);
2196 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2199 for (int i = 0; i < page->annotcount; ++i) {
2200 fz_point p1, p2, p3, p4;
2201 struct annot *annot = &page->annots[i];
2203 p1.x = annot->bbox.x0;
2204 p1.y = annot->bbox.y0;
2206 p2.x = annot->bbox.x1;
2207 p2.y = annot->bbox.y0;
2209 p3.x = annot->bbox.x1;
2210 p3.y = annot->bbox.y1;
2212 p4.x = annot->bbox.x0;
2213 p4.y = annot->bbox.y1;
2215 glColor3ub (0, 0, 128);
2216 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2219 glDisable (GL_BLEND);
2220 glDisable (GL_TEXTURE_1D);
2223 static int compareslinks (const void *l, const void *r)
2225 struct slink const *ls = l;
2226 struct slink const *rs = r;
2227 if (ls->bbox.y0 == rs->bbox.y0) {
2228 return rs->bbox.x0 - rs->bbox.x0;
2230 return ls->bbox.y0 - rs->bbox.y0;
2233 static void droptext (struct page *page)
2235 if (page->text) {
2236 fz_drop_stext_page (state.ctx, page->text);
2237 page->fmark.i = -1;
2238 page->lmark.i = -1;
2239 page->fmark.span = NULL;
2240 page->lmark.span = NULL;
2241 page->text = NULL;
2243 if (page->sheet) {
2244 fz_drop_stext_sheet (state.ctx, page->sheet);
2245 page->sheet = NULL;
2249 static void dropannots (struct page *page)
2251 if (page->annots) {
2252 free (page->annots);
2253 page->annots = NULL;
2254 page->annotcount = 0;
2258 static void ensureannots (struct page *page)
2260 int i, count = 0;
2261 size_t annotsize = sizeof (*page->annots);
2262 fz_annot *annot;
2264 if (state.gen != page->agen) {
2265 dropannots (page);
2266 page->agen = state.gen;
2268 if (page->annots) return;
2270 for (annot = fz_first_annot (state.ctx, page->fzpage);
2271 annot;
2272 annot = fz_next_annot (state.ctx, annot)) {
2273 count++;
2276 if (count > 0) {
2277 page->annotcount = count;
2278 page->annots = calloc (count, annotsize);
2279 if (!page->annots) {
2280 err (1, "calloc annots %d", count);
2283 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2284 annot;
2285 annot = fz_next_annot (state.ctx, annot), i++) {
2286 fz_rect rect;
2288 fz_bound_annot (state.ctx, annot, &rect);
2289 page->annots[i].annot = annot;
2290 fz_round_rect (&page->annots[i].bbox, &rect);
2295 static void dropslinks (struct page *page)
2297 if (page->slinks) {
2298 free (page->slinks);
2299 page->slinks = NULL;
2300 page->slinkcount = 0;
2304 static void ensureslinks (struct page *page)
2306 fz_matrix ctm;
2307 int i, count;
2308 size_t slinksize = sizeof (*page->slinks);
2309 fz_link *link, *links;
2311 ensureannots (page);
2312 if (state.gen != page->sgen) {
2313 dropslinks (page);
2314 page->sgen = state.gen;
2316 if (page->slinks) return;
2318 links = fz_load_links (state.ctx, page->fzpage);
2319 ctm = pagectm (page);
2321 count = page->annotcount;
2322 for (link = links; link; link = link->next) {
2323 count++;
2325 if (count > 0) {
2326 int j;
2328 page->slinkcount = count;
2329 page->slinks = calloc (count, slinksize);
2330 if (!page->slinks) {
2331 err (1, "calloc slinks %d", count);
2334 for (i = 0, link = links; link; ++i, link = link->next) {
2335 fz_rect rect;
2337 rect = link->rect;
2338 fz_transform_rect (&rect, &ctm);
2339 page->slinks[i].tag = SLINK;
2340 page->slinks[i].u.link = link;
2341 fz_round_rect (&page->slinks[i].bbox, &rect);
2343 for (j = 0; j < page->annotcount; ++j, ++i) {
2344 fz_rect rect;
2345 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2346 fz_transform_rect (&rect, &ctm);
2347 fz_round_rect (&page->slinks[i].bbox, &rect);
2349 page->slinks[i].tag = SANNOT;
2350 page->slinks[i].u.annot = page->annots[j].annot;
2352 qsort (page->slinks, count, slinksize, compareslinks);
2356 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2357 static void fmt_linkn (char *s, unsigned int u)
2359 unsigned int len; unsigned int q;
2360 unsigned int zma = 'z' - 'a' + 1;
2361 len = 1; q = u;
2362 while (q > zma - 1) { ++len; q /= zma; }
2363 if (s) {
2364 s += len;
2365 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2366 /* handles u == 0 */
2368 s[len] = 0;
2371 static void highlightslinks (struct page *page, int xoff, int yoff,
2372 int noff, char *targ, int tlen, int hfsize)
2374 char buf[40];
2375 struct slink *slink;
2376 double x0, y0, x1, y1, w;
2378 ensureslinks (page);
2379 glColor3ub (0xc3, 0xb0, 0x91);
2380 for (int i = 0; i < page->slinkcount; ++i) {
2381 fmt_linkn (buf, i + noff);
2382 if (!tlen || !strncmp (targ, buf, tlen)) {
2383 slink = &page->slinks[i];
2385 x0 = slink->bbox.x0 + xoff - 5;
2386 y1 = slink->bbox.y0 + yoff - 5;
2387 y0 = y1 + 10 + hfsize;
2388 w = measure_string (state.face, hfsize, buf);
2389 x1 = x0 + w + 10;
2390 recti (x0, y0, x1, y1);
2394 glEnable (GL_BLEND);
2395 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2396 glEnable (GL_TEXTURE_2D);
2397 glColor3ub (0, 0, 0);
2398 for (int i = 0; i < page->slinkcount; ++i) {
2399 fmt_linkn (buf, i + noff);
2400 if (!tlen || !strncmp (targ, buf, tlen)) {
2401 slink = &page->slinks[i];
2403 x0 = slink->bbox.x0 + xoff;
2404 y0 = slink->bbox.y0 + yoff + hfsize;
2405 draw_string (state.face, hfsize, x0, y0, buf);
2408 glDisable (GL_TEXTURE_2D);
2409 glDisable (GL_BLEND);
2412 static void uploadslice (struct tile *tile, struct slice *slice)
2414 int offset;
2415 struct slice *slice1;
2416 unsigned char *texdata;
2418 offset = 0;
2419 for (slice1 = tile->slices; slice != slice1; slice1++) {
2420 offset += slice1->h * tile->w * tile->pixmap->n;
2422 if (slice->texindex != -1 && slice->texindex < state.texcount
2423 && state.texowners[slice->texindex].slice == slice) {
2424 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2426 else {
2427 int subimage = 0;
2428 int texindex = state.texindex++ % state.texcount;
2430 if (state.texowners[texindex].w == tile->w) {
2431 if (state.texowners[texindex].h >= slice->h) {
2432 subimage = 1;
2434 else {
2435 state.texowners[texindex].h = slice->h;
2438 else {
2439 state.texowners[texindex].h = slice->h;
2442 state.texowners[texindex].w = tile->w;
2443 state.texowners[texindex].slice = slice;
2444 slice->texindex = texindex;
2446 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2447 #if TEXT_TYPE == GL_TEXTURE_2D
2448 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2449 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2450 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2451 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2452 #endif
2453 if (tile->pbo) {
2454 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2455 texdata = 0;
2457 else {
2458 texdata = tile->pixmap->samples;
2460 if (subimage) {
2461 glTexSubImage2D (TEXT_TYPE,
2465 tile->w,
2466 slice->h,
2467 state.texform,
2468 state.texty,
2469 texdata+offset
2472 else {
2473 glTexImage2D (TEXT_TYPE,
2475 state.texiform,
2476 tile->w,
2477 slice->h,
2479 state.texform,
2480 state.texty,
2481 texdata+offset
2484 if (tile->pbo) {
2485 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2490 CAMLprim void ml_begintiles (value unit_v)
2492 CAMLparam1 (unit_v);
2493 glEnable (TEXT_TYPE);
2494 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2495 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2496 CAMLreturn0;
2499 CAMLprim void ml_endtiles (value unit_v)
2501 CAMLparam1 (unit_v);
2502 glDisable (TEXT_TYPE);
2503 CAMLreturn0;
2506 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2508 CAMLparam2 (args_v, ptr_v);
2509 int dispx = Int_val (Field (args_v, 0));
2510 int dispy = Int_val (Field (args_v, 1));
2511 int dispw = Int_val (Field (args_v, 2));
2512 int disph = Int_val (Field (args_v, 3));
2513 int tilex = Int_val (Field (args_v, 4));
2514 int tiley = Int_val (Field (args_v, 5));
2515 char *s = String_val (ptr_v);
2516 struct tile *tile = parse_pointer (__func__, s);
2517 int slicey, firstslice;
2518 struct slice *slice;
2519 GLfloat *texcoords = state.texcoords;
2520 GLfloat *vertices = state.vertices;
2522 firstslice = tiley / tile->sliceheight;
2523 slice = &tile->slices[firstslice];
2524 slicey = tiley % tile->sliceheight;
2526 while (disph > 0) {
2527 int dh;
2529 dh = slice->h - slicey;
2530 dh = fz_mini (disph, dh);
2531 uploadslice (tile, slice);
2533 texcoords[0] = tilex; texcoords[1] = slicey;
2534 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2535 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2536 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2538 vertices[0] = dispx; vertices[1] = dispy;
2539 vertices[2] = dispx+dispw; vertices[3] = dispy;
2540 vertices[4] = dispx; vertices[5] = dispy+dh;
2541 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2543 #if TEXT_TYPE == GL_TEXTURE_2D
2544 for (int i = 0; i < 8; ++i) {
2545 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2547 #endif
2549 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2550 dispy += dh;
2551 disph -= dh;
2552 slice++;
2553 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2554 slicey = 0;
2556 CAMLreturn0;
2559 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2561 fz_matrix ctm, tm, pm;
2562 fz_point p1, p2, p3, p4;
2563 GLfloat *vertices = state.vertices;
2564 double *v = (double *) rects_v;
2566 xoff -= state.pagedims[page->pdimno].bounds.x0;
2567 yoff -= state.pagedims[page->pdimno].bounds.y0;
2568 fz_translate (&tm, xoff, yoff);
2569 pm = pagectm (page);
2570 fz_concat (&ctm, &pm, &tm);
2572 glEnable (GL_BLEND);
2573 glVertexPointer (2, GL_FLOAT, 0, vertices);
2575 glColor4dv (v);
2576 p1.x = v[4];
2577 p1.y = v[5];
2579 p2.x = v[6];
2580 p2.y = v[5];
2582 p3.x = v[6];
2583 p3.y = v[7];
2585 p4.x = v[4];
2586 p4.y = v[7];
2587 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2588 glDisable (GL_BLEND);
2591 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2592 value xoff_v, value yoff_v,
2593 value li_v)
2595 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2596 int xoff = Int_val (xoff_v);
2597 int yoff = Int_val (yoff_v);
2598 int noff = Int_val (Field (li_v, 0));
2599 char *targ = String_val (Field (li_v, 1));
2600 int tlen = caml_string_length (Field (li_v, 1));
2601 int hfsize = Int_val (Field (li_v, 2));
2602 char *s = String_val (ptr_v);
2603 int hlmask = Int_val (hlinks_v);
2604 struct page *page = parse_pointer (__func__, s);
2606 if (!page->fzpage) {
2607 /* deal with loadpage failed pages */
2608 goto done;
2611 if (trylock (__func__)) {
2612 noff = -1;
2613 goto done;
2616 ensureannots (page);
2617 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2618 if (hlmask & 2) {
2619 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2620 noff = page->slinkcount;
2622 if (page->tgen == state.gen) {
2623 showsel (page, xoff, yoff);
2625 unlock (__func__);
2627 done:
2628 CAMLreturn (Val_int (noff));
2631 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2632 value rects_v)
2634 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2635 int xoff = Int_val (xoff_v);
2636 int yoff = Int_val (yoff_v);
2637 char *s = String_val (ptr_v);
2638 struct page *page = parse_pointer (__func__, s);
2640 drawprect (page, xoff, yoff, rects_v);
2641 CAMLreturn0;
2644 static struct annot *getannot (struct page *page, int x, int y)
2646 fz_point p;
2647 fz_matrix ctm;
2648 const fz_matrix *tctm;
2649 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2651 if (!page->annots) return NULL;
2653 if (pdf) {
2654 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2655 tctm = &state.pagedims[page->pdimno].tctm;
2657 else {
2658 tctm = &fz_identity;
2661 p.x = x;
2662 p.y = y;
2664 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2665 fz_invert_matrix (&ctm, &ctm);
2666 fz_transform_point (&p, &ctm);
2668 if (pdf) {
2669 for (int i = 0; i < page->annotcount; ++i) {
2670 struct annot *a = &page->annots[i];
2671 fz_rect rect;
2673 fz_bound_annot (state.ctx, a->annot, &rect);
2674 if (p.x >= rect.x0 && p.x <= rect.x1) {
2675 if (p.y >= rect.y0 && p.y <= rect.y1)
2676 return a;
2680 return NULL;
2683 static fz_link *getlink (struct page *page, int x, int y)
2685 fz_point p;
2686 fz_matrix ctm;
2687 fz_link *link, *links;
2689 links = fz_load_links (state.ctx, page->fzpage);
2691 p.x = x;
2692 p.y = y;
2694 ctm = pagectm (page);
2695 fz_invert_matrix (&ctm, &ctm);
2696 fz_transform_point (&p, &ctm);
2698 for (link = links; link; link = link->next) {
2699 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2700 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2701 return link;
2705 return NULL;
2708 static void ensuretext (struct page *page)
2710 if (state.gen != page->tgen) {
2711 droptext (page);
2712 page->tgen = state.gen;
2714 if (!page->text) {
2715 fz_matrix ctm;
2716 fz_device *tdev;
2718 page->text = fz_new_stext_page (state.ctx,
2719 &state.pagedims[page->pdimno].mediabox);
2720 page->sheet = fz_new_stext_sheet (state.ctx);
2721 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2722 ctm = pagectm (page);
2723 fz_run_display_list (state.ctx, page->dlist,
2724 tdev, &ctm, &fz_infinite_rect, NULL);
2725 qsort (page->text->blocks, page->text->len,
2726 sizeof (*page->text->blocks), compareblocks);
2727 fz_close_device (state.ctx, tdev);
2728 fz_drop_device (state.ctx, tdev);
2732 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2734 CAMLparam2 (start_page_v, dir_v);
2735 CAMLlocal1 (ret_v);
2736 int i, dir = Int_val (dir_v);
2737 int start_page = Int_val (start_page_v);
2738 int end_page = dir > 0 ? state.pagecount : -1;
2739 pdf_document *pdf;
2741 fz_var (end_page);
2742 ret_v = Val_int (0);
2743 lock (__func__);
2744 pdf = pdf_specifics (state.ctx, state.doc);
2745 for (i = start_page + dir; i != end_page; i += dir) {
2746 int found;
2748 fz_var (found);
2749 if (pdf) {
2750 pdf_page *page = NULL;
2752 fz_var (page);
2753 fz_try (state.ctx) {
2754 page = pdf_load_page (state.ctx, pdf, i);
2755 found = !!page->links || !!page->annots;
2757 fz_catch (state.ctx) {
2758 found = 0;
2760 if (page) {
2761 fz_drop_page (state.ctx, &page->super);
2764 else {
2765 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2766 found = !!fz_load_links (state.ctx, page);
2767 fz_drop_page (state.ctx, page);
2770 if (found) {
2771 ret_v = caml_alloc_small (1, 1);
2772 Field (ret_v, 0) = Val_int (i);
2773 goto unlock;
2776 unlock:
2777 unlock (__func__);
2778 CAMLreturn (ret_v);
2781 enum { dir_first, dir_last };
2782 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2784 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2786 CAMLparam2 (ptr_v, dir_v);
2787 CAMLlocal2 (ret_v, pos_v);
2788 struct page *page;
2789 int dirtag, i, slinkindex;
2790 struct slink *found = NULL ,*slink;
2791 char *s = String_val (ptr_v);
2793 page = parse_pointer (__func__, s);
2794 ret_v = Val_int (0);
2795 lock (__func__);
2796 ensureslinks (page);
2798 if (Is_block (dir_v)) {
2799 dirtag = Tag_val (dir_v);
2800 switch (dirtag) {
2801 case dir_first_visible:
2803 int x0, y0, dir, first_index, last_index;
2805 pos_v = Field (dir_v, 0);
2806 x0 = Int_val (Field (pos_v, 0));
2807 y0 = Int_val (Field (pos_v, 1));
2808 dir = Int_val (Field (pos_v, 2));
2810 if (dir >= 0) {
2811 dir = 1;
2812 first_index = 0;
2813 last_index = page->slinkcount;
2815 else {
2816 first_index = page->slinkcount - 1;
2817 last_index = -1;
2820 for (i = first_index; i != last_index; i += dir) {
2821 slink = &page->slinks[i];
2822 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2823 found = slink;
2824 break;
2828 break;
2830 case dir_left:
2831 slinkindex = Int_val (Field (dir_v, 0));
2832 found = &page->slinks[slinkindex];
2833 for (i = slinkindex - 1; i >= 0; --i) {
2834 slink = &page->slinks[i];
2835 if (slink->bbox.x0 < found->bbox.x0) {
2836 found = slink;
2837 break;
2840 break;
2842 case dir_right:
2843 slinkindex = Int_val (Field (dir_v, 0));
2844 found = &page->slinks[slinkindex];
2845 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2846 slink = &page->slinks[i];
2847 if (slink->bbox.x0 > found->bbox.x0) {
2848 found = slink;
2849 break;
2852 break;
2854 case dir_down:
2855 slinkindex = Int_val (Field (dir_v, 0));
2856 found = &page->slinks[slinkindex];
2857 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2858 slink = &page->slinks[i];
2859 if (slink->bbox.y0 >= found->bbox.y0) {
2860 found = slink;
2861 break;
2864 break;
2866 case dir_up:
2867 slinkindex = Int_val (Field (dir_v, 0));
2868 found = &page->slinks[slinkindex];
2869 for (i = slinkindex - 1; i >= 0; --i) {
2870 slink = &page->slinks[i];
2871 if (slink->bbox.y0 <= found->bbox.y0) {
2872 found = slink;
2873 break;
2876 break;
2879 else {
2880 dirtag = Int_val (dir_v);
2881 switch (dirtag) {
2882 case dir_first:
2883 found = page->slinks;
2884 break;
2886 case dir_last:
2887 if (page->slinks) {
2888 found = page->slinks + (page->slinkcount - 1);
2890 break;
2893 if (found) {
2894 ret_v = caml_alloc_small (2, 1);
2895 Field (ret_v, 0) = Val_int (found - page->slinks);
2898 unlock (__func__);
2899 CAMLreturn (ret_v);
2902 enum { uuri, utext, uannot };
2904 CAMLprim value ml_getlink (value ptr_v, value n_v)
2906 CAMLparam2 (ptr_v, n_v);
2907 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2908 fz_link *link;
2909 struct page *page;
2910 char *s = String_val (ptr_v);
2911 struct slink *slink;
2913 ret_v = Val_int (0);
2914 page = parse_pointer (__func__, s);
2916 lock (__func__);
2917 ensureslinks (page);
2918 slink = &page->slinks[Int_val (n_v)];
2919 if (slink->tag == SLINK) {
2920 link = slink->u.link;
2921 str_v = caml_copy_string (link->uri);
2922 ret_v = caml_alloc_small (1, uuri);
2923 Field (ret_v, 0) = str_v;
2925 else {
2926 ret_v = caml_alloc_small (1, uannot);
2927 tup_v = caml_alloc_tuple (2);
2928 Field (ret_v, 0) = tup_v;
2929 Field (tup_v, 0) = ptr_v;
2930 Field (tup_v, 1) = n_v;
2932 unlock (__func__);
2934 CAMLreturn (ret_v);
2937 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2939 CAMLparam2 (ptr_v, n_v);
2940 pdf_document *pdf;
2941 const char *contents = "";
2943 lock (__func__);
2944 pdf = pdf_specifics (state.ctx, state.doc);
2945 if (pdf) {
2946 char *s = String_val (ptr_v);
2947 struct page *page;
2948 struct slink *slink;
2950 page = parse_pointer (__func__, s);
2951 slink = &page->slinks[Int_val (n_v)];
2952 contents = pdf_annot_contents (state.ctx,
2953 (pdf_annot *) slink->u.annot);
2955 unlock (__func__);
2956 CAMLreturn (caml_copy_string (contents));
2959 CAMLprim value ml_getlinkcount (value ptr_v)
2961 CAMLparam1 (ptr_v);
2962 struct page *page;
2963 char *s = String_val (ptr_v);
2965 page = parse_pointer (__func__, s);
2966 CAMLreturn (Val_int (page->slinkcount));
2969 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2971 CAMLparam2 (ptr_v, n_v);
2972 CAMLlocal1 (ret_v);
2973 struct page *page;
2974 struct slink *slink;
2975 char *s = String_val (ptr_v);
2977 page = parse_pointer (__func__, s);
2978 ret_v = caml_alloc_tuple (4);
2979 lock (__func__);
2980 ensureslinks (page);
2982 slink = &page->slinks[Int_val (n_v)];
2983 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2984 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2985 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2986 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2987 unlock (__func__);
2988 CAMLreturn (ret_v);
2991 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2993 CAMLparam3 (ptr_v, x_v, y_v);
2994 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2995 fz_link *link;
2996 struct annot *annot;
2997 struct page *page;
2998 char *ptr = String_val (ptr_v);
2999 int x = Int_val (x_v), y = Int_val (y_v);
3000 struct pagedim *pdim;
3002 ret_v = Val_int (0);
3003 if (trylock (__func__)) {
3004 goto done;
3007 page = parse_pointer (__func__, ptr);
3008 pdim = &state.pagedims[page->pdimno];
3009 x += pdim->bounds.x0;
3010 y += pdim->bounds.y0;
3013 annot = getannot (page, x, y);
3014 if (annot) {
3015 int i, n = -1;
3017 ensureslinks (page);
3018 for (i = 0; i < page->slinkcount; ++i) {
3019 if (page->slinks[i].tag == SANNOT
3020 && page->slinks[i].u.annot == annot->annot) {
3021 n = i;
3022 break;
3025 ret_v = caml_alloc_small (1, uannot);
3026 tup_v = caml_alloc_tuple (2);
3027 Field (ret_v, 0) = tup_v;
3028 Field (tup_v, 0) = ptr_v;
3029 Field (tup_v, 1) = Val_int (n);
3030 goto unlock;
3034 link = getlink (page, x, y);
3035 if (link) {
3036 str_v = caml_copy_string (link->uri);
3037 ret_v = caml_alloc_small (1, uuri);
3038 Field (ret_v, 0) = str_v;
3040 else {
3041 fz_rect *b;
3042 fz_page_block *pageb;
3043 fz_stext_block *block;
3045 ensuretext (page);
3046 for (pageb = page->text->blocks;
3047 pageb < page->text->blocks + page->text->len;
3048 ++pageb) {
3049 fz_stext_line *line;
3050 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3051 block = pageb->u.text;
3053 b = &block->bbox;
3054 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3055 continue;
3057 for (line = block->lines;
3058 line < block->lines + block->len;
3059 ++line) {
3060 fz_stext_span *span;
3062 b = &line->bbox;
3063 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3064 continue;
3066 for (span = line->first_span; span; span = span->next) {
3067 int charnum;
3069 b = &span->bbox;
3070 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3071 continue;
3073 for (charnum = 0; charnum < span->len; ++charnum) {
3074 fz_rect bbox;
3075 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3076 b = &bbox;
3078 if (x >= b->x0 && x <= b->x1
3079 && y >= b->y0 && y <= b->y1) {
3080 fz_stext_style *style = span->text->style;
3081 const char *n2 =
3082 style->font
3083 ? fz_font_name (state.ctx, style->font)
3084 : "Span has no font name"
3086 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3087 style->font);
3088 if (face && face->family_name) {
3089 char *s;
3090 char *n1 = face->family_name;
3091 size_t l1 = strlen (n1);
3092 size_t l2 = strlen (n2);
3094 if (l1 != l2 || memcmp (n1, n2, l1)) {
3095 s = malloc (l1 + l2 + 2);
3096 if (s) {
3097 memcpy (s, n2, l2);
3098 s[l2] = '=';
3099 memcpy (s + l2 + 1, n1, l1 + 1);
3100 str_v = caml_copy_string (s);
3101 free (s);
3105 if (str_v == Val_unit) {
3106 str_v = caml_copy_string (n2);
3108 ret_v = caml_alloc_small (1, utext);
3109 Field (ret_v, 0) = str_v;
3110 goto unlock;
3117 unlock:
3118 unlock (__func__);
3120 done:
3121 CAMLreturn (ret_v);
3124 enum { mark_page, mark_block, mark_line, mark_word };
3126 static int uninteresting (int c)
3128 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3129 || ispunct (c);
3132 CAMLprim void ml_clearmark (value ptr_v)
3134 CAMLparam1 (ptr_v);
3135 char *s = String_val (ptr_v);
3136 struct page *page;
3138 if (trylock (__func__)) {
3139 goto done;
3142 page = parse_pointer (__func__, s);
3143 page->fmark.span = NULL;
3144 page->lmark.span = NULL;
3145 page->fmark.i = 0;
3146 page->lmark.i = 0;
3148 unlock (__func__);
3149 done:
3150 CAMLreturn0;
3153 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3155 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3156 CAMLlocal1 (ret_v);
3157 fz_rect *b;
3158 struct page *page;
3159 fz_stext_line *line;
3160 fz_page_block *pageb;
3161 fz_stext_block *block;
3162 struct pagedim *pdim;
3163 int mark = Int_val (mark_v);
3164 char *s = String_val (ptr_v);
3165 int x = Int_val (x_v), y = Int_val (y_v);
3167 ret_v = Val_bool (0);
3168 if (trylock (__func__)) {
3169 goto done;
3172 page = parse_pointer (__func__, s);
3173 pdim = &state.pagedims[page->pdimno];
3175 ensuretext (page);
3177 if (mark == mark_page) {
3178 int i;
3179 fz_page_block *pb1 = NULL, *pb2 = NULL;
3181 for (i = 0; i < page->text->len; ++i) {
3182 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3183 pb1 = &page->text->blocks[i];
3184 break;
3187 if (!pb1) goto unlock;
3189 for (i = page->text->len - 1; i >= 0; --i) {
3190 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3191 pb2 = &page->text->blocks[i];
3192 break;
3195 if (!pb2) goto unlock;
3197 block = pb1->u.text;
3199 page->fmark.i = 0;
3200 page->fmark.span = block->lines->first_span;
3202 block = pb2->u.text;
3203 line = &block->lines[block->len - 1];
3204 page->lmark.i = line->last_span->len - 1;
3205 page->lmark.span = line->last_span;
3206 ret_v = Val_bool (1);
3207 goto unlock;
3210 x += pdim->bounds.x0;
3211 y += pdim->bounds.y0;
3213 for (pageb = page->text->blocks;
3214 pageb < page->text->blocks + page->text->len;
3215 ++pageb) {
3216 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3217 block = pageb->u.text;
3219 b = &block->bbox;
3220 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3221 continue;
3223 if (mark == mark_block) {
3224 page->fmark.i = 0;
3225 page->fmark.span = block->lines->first_span;
3227 line = &block->lines[block->len - 1];
3228 page->lmark.i = line->last_span->len - 1;
3229 page->lmark.span = line->last_span;
3230 ret_v = Val_bool (1);
3231 goto unlock;
3234 for (line = block->lines;
3235 line < block->lines + block->len;
3236 ++line) {
3237 fz_stext_span *span;
3239 b = &line->bbox;
3240 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3241 continue;
3243 if (mark == mark_line) {
3244 page->fmark.i = 0;
3245 page->fmark.span = line->first_span;
3247 page->lmark.i = line->last_span->len - 1;
3248 page->lmark.span = line->last_span;
3249 ret_v = Val_bool (1);
3250 goto unlock;
3253 for (span = line->first_span; span; span = span->next) {
3254 int charnum;
3256 b = &span->bbox;
3257 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3258 continue;
3260 for (charnum = 0; charnum < span->len; ++charnum) {
3261 fz_rect bbox;
3262 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3263 b = &bbox;
3265 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3266 /* unicode ftw */
3267 int charnum2, charnum3 = -1, charnum4 = -1;
3269 if (uninteresting (span->text[charnum].c)) goto unlock;
3271 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3272 if (uninteresting (span->text[charnum2].c)) {
3273 charnum3 = charnum2 + 1;
3274 break;
3277 if (charnum3 == -1) charnum3 = 0;
3279 charnum4 = charnum;
3280 for (charnum2 = charnum + 1;
3281 charnum2 < span->len;
3282 ++charnum2) {
3283 if (uninteresting (span->text[charnum2].c)) break;
3284 charnum4 = charnum2;
3287 page->fmark.i = charnum3;
3288 page->fmark.span = span;
3290 page->lmark.i = charnum4;
3291 page->lmark.span = span;
3292 ret_v = Val_bool (1);
3293 goto unlock;
3299 unlock:
3300 if (!Bool_val (ret_v)) {
3301 page->fmark.span = NULL;
3302 page->lmark.span = NULL;
3303 page->fmark.i = 0;
3304 page->lmark.i = 0;
3306 unlock (__func__);
3308 done:
3309 CAMLreturn (ret_v);
3312 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3314 CAMLparam3 (ptr_v, x_v, y_v);
3315 CAMLlocal2 (ret_v, res_v);
3316 fz_rect *b = NULL;
3317 struct page *page;
3318 fz_page_block *pageb;
3319 struct pagedim *pdim;
3320 char *s = String_val (ptr_v);
3321 int x = Int_val (x_v), y = Int_val (y_v);
3323 ret_v = Val_int (0);
3324 if (trylock (__func__)) {
3325 goto done;
3328 page = parse_pointer (__func__, s);
3329 pdim = &state.pagedims[page->pdimno];
3330 x += pdim->bounds.x0;
3331 y += pdim->bounds.y0;
3333 ensuretext (page);
3335 for (pageb = page->text->blocks;
3336 pageb < page->text->blocks + page->text->len;
3337 ++pageb) {
3338 switch (pageb->type) {
3339 case FZ_PAGE_BLOCK_TEXT:
3340 b = &pageb->u.text->bbox;
3341 break;
3343 case FZ_PAGE_BLOCK_IMAGE:
3344 b = &pageb->u.image->bbox;
3345 break;
3347 default:
3348 continue;
3351 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3352 break;
3353 b = NULL;
3355 if (b) {
3356 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3357 ret_v = caml_alloc_small (1, 1);
3358 Store_double_field (res_v, 0, b->x0);
3359 Store_double_field (res_v, 1, b->x1);
3360 Store_double_field (res_v, 2, b->y0);
3361 Store_double_field (res_v, 3, b->y1);
3362 Field (ret_v, 0) = res_v;
3364 unlock (__func__);
3366 done:
3367 CAMLreturn (ret_v);
3370 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3372 CAMLparam2 (ptr_v, rect_v);
3373 fz_rect b;
3374 struct page *page;
3375 struct pagedim *pdim;
3376 char *s = String_val (ptr_v);
3377 int i, x0, x1, y0, y1, fi, li;
3378 fz_stext_line *line;
3379 fz_page_block *pageb;
3380 fz_stext_block *block;
3381 fz_stext_span *span, *fspan, *lspan;
3383 if (trylock (__func__)) {
3384 goto done;
3387 page = parse_pointer (__func__, s);
3388 ensuretext (page);
3390 pdim = &state.pagedims[page->pdimno];
3391 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3392 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3393 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3394 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3396 if (y0 > y1) {
3397 int t = y0;
3398 y0 = y1;
3399 y1 = t;
3400 x0 = x1;
3401 x1 = t;
3404 fi = page->fmark.i;
3405 fspan = page->fmark.span;
3407 li = page->lmark.i;
3408 lspan = page->lmark.span;
3410 for (pageb = page->text->blocks;
3411 pageb < page->text->blocks + page->text->len;
3412 ++pageb) {
3413 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3414 block = pageb->u.text;
3415 for (line = block->lines;
3416 line < block->lines + block->len;
3417 ++line) {
3419 for (span = line->first_span; span; span = span->next) {
3420 for (i = 0; i < span->len; ++i) {
3421 fz_stext_char_bbox (state.ctx, &b, span, i);
3423 if (x0 >= b.x0 && x0 <= b.x1
3424 && y0 >= b.y0 && y0 <= b.y1) {
3425 fspan = span;
3426 fi = i;
3428 if (x1 >= b.x0 && x1 <= b.x1
3429 && y1 >= b.y0 && y1 <= b.y1) {
3430 lspan = span;
3431 li = i;
3437 if (x1 < x0 && fspan == lspan) {
3438 i = fi;
3439 span = fspan;
3441 fi = li;
3442 fspan = lspan;
3444 li = i;
3445 lspan = span;
3448 page->fmark.i = fi;
3449 page->fmark.span = fspan;
3451 page->lmark.i = li;
3452 page->lmark.span = lspan;
3454 unlock (__func__);
3456 done:
3457 CAMLreturn0;
3460 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3462 char buf[4];
3463 int i, len, ret;
3465 for (i = a; i <= b; ++i) {
3466 len = fz_runetochar (buf, span->text[i].c);
3467 ret = fwrite (buf, len, 1, f);
3469 if (ret != 1) {
3470 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3471 len, ret, strerror (errno));
3472 return -1;
3475 return 0;
3478 #ifdef __CYGWIN__
3479 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3481 caml_failwith ("ml_popen not implemented under Cygwin");
3483 #else
3484 CAMLprim value ml_spawn (value command_v, value fds_v)
3486 CAMLparam2 (command_v, fds_v);
3487 CAMLlocal2 (l_v, tup_v);
3488 int ret, ret1;
3489 pid_t pid;
3490 char *msg = NULL;
3491 value earg_v = Nothing;
3492 posix_spawnattr_t attr;
3493 posix_spawn_file_actions_t fa;
3494 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3496 argv[2] = String_val (command_v);
3498 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3499 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3502 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3503 msg = "posix_spawnattr_init";
3504 goto fail1;
3507 #ifdef POSIX_SPAWN_USEVFORK
3508 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3509 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3510 goto fail;
3512 #endif
3514 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3515 int fd1, fd2;
3517 tup_v = Field (l_v, 0);
3518 fd1 = Int_val (Field (tup_v, 0));
3519 fd2 = Int_val (Field (tup_v, 1));
3520 if (fd2 < 0) {
3521 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3522 msg = "posix_spawn_file_actions_addclose";
3523 earg_v = tup_v;
3524 goto fail;
3527 else {
3528 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3529 msg = "posix_spawn_file_actions_adddup2";
3530 earg_v = tup_v;
3531 goto fail;
3536 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3537 msg = "posix_spawn";
3538 goto fail;
3541 fail:
3542 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3543 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3546 fail1:
3547 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3548 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3549 strerror (ret1));
3552 if (msg)
3553 unix_error (ret, msg, earg_v);
3555 CAMLreturn (Val_int (pid));
3557 #endif
3559 CAMLprim value ml_hassel (value ptr_v)
3561 CAMLparam1 (ptr_v);
3562 CAMLlocal1 (ret_v);
3563 struct page *page;
3564 char *s = String_val (ptr_v);
3566 ret_v = Val_bool (0);
3567 if (trylock (__func__)) {
3568 goto done;
3571 page = parse_pointer (__func__, s);
3572 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3573 unlock (__func__);
3574 done:
3575 CAMLreturn (ret_v);
3578 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3580 CAMLparam2 (fd_v, ptr_v);
3581 FILE *f;
3582 int seen = 0;
3583 struct page *page;
3584 fz_stext_line *line;
3585 fz_page_block *pageb;
3586 fz_stext_block *block;
3587 int fd = Int_val (fd_v);
3588 char *s = String_val (ptr_v);
3590 if (trylock (__func__)) {
3591 goto done;
3594 page = parse_pointer (__func__, s);
3596 if (!page->fmark.span || !page->lmark.span) {
3597 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3598 goto unlock;
3601 f = fdopen (fd, "w");
3602 if (!f) {
3603 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3604 fd, strerror (errno));
3605 f = stdout;
3608 for (pageb = page->text->blocks;
3609 pageb < page->text->blocks + page->text->len;
3610 ++pageb) {
3611 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3612 block = pageb->u.text;
3613 for (line = block->lines;
3614 line < block->lines + block->len;
3615 ++line) {
3616 fz_stext_span *span;
3618 for (span = line->first_span; span; span = span->next) {
3619 int a, b;
3621 seen |= span == page->fmark.span || span == page->lmark.span;
3622 a = span == page->fmark.span ? page->fmark.i : 0;
3623 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3625 if (seen) {
3626 if (pipespan (f, span, a, b)) {
3627 goto close;
3629 if (span == page->lmark.span) {
3630 goto close;
3632 if (span == line->last_span) {
3633 if (putc ('\n', f) == EOF) {
3634 fprintf (stderr,
3635 "failed break line on sel pipe: %s\n",
3636 strerror (errno));
3637 goto close;
3644 close:
3645 if (f != stdout) {
3646 int ret = fclose (f);
3647 fd = -1;
3648 if (ret == -1) {
3649 if (errno != ECHILD) {
3650 fprintf (stderr, "failed to close sel pipe: %s\n",
3651 strerror (errno));
3655 unlock:
3656 unlock (__func__);
3658 done:
3659 if (fd >= 0) {
3660 if (close (fd)) {
3661 fprintf (stderr, "failed to close sel pipe: %s\n",
3662 strerror (errno));
3665 CAMLreturn0;
3668 CAMLprim value ml_getpdimrect (value pagedimno_v)
3670 CAMLparam1 (pagedimno_v);
3671 CAMLlocal1 (ret_v);
3672 int pagedimno = Int_val (pagedimno_v);
3673 fz_rect box;
3675 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3676 if (trylock (__func__)) {
3677 box = fz_empty_rect;
3679 else {
3680 box = state.pagedims[pagedimno].mediabox;
3681 unlock (__func__);
3684 Store_double_field (ret_v, 0, box.x0);
3685 Store_double_field (ret_v, 1, box.x1);
3686 Store_double_field (ret_v, 2, box.y0);
3687 Store_double_field (ret_v, 3, box.y1);
3689 CAMLreturn (ret_v);
3692 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3693 value dw_v, value cols_v)
3695 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3696 CAMLlocal1 (ret_v);
3697 int i;
3698 double zoom = -1.;
3699 double maxh = 0.0;
3700 struct pagedim *p;
3701 double winw = Int_val (winw_v);
3702 double winh = Int_val (winh_v);
3703 double dw = Int_val (dw_v);
3704 double cols = Int_val (cols_v);
3705 double pw = 1.0, ph = 1.0;
3707 if (trylock (__func__)) {
3708 goto done;
3711 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3712 double w = p->pagebox.x1 / cols;
3713 double h = p->pagebox.y1;
3714 if (h > maxh) {
3715 maxh = h;
3716 ph = h;
3717 if (state.fitmodel != FitProportional) pw = w;
3719 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3722 zoom = (((winh / ph) * pw) + dw) / winw;
3723 unlock (__func__);
3724 done:
3725 ret_v = caml_copy_double (zoom);
3726 CAMLreturn (ret_v);
3729 CAMLprim value ml_getmaxw (value unit_v)
3731 CAMLparam1 (unit_v);
3732 CAMLlocal1 (ret_v);
3733 int i;
3734 double maxw = -1.;
3735 struct pagedim *p;
3737 if (trylock (__func__)) {
3738 goto done;
3741 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3742 double w = p->pagebox.x1;
3743 maxw = fz_max (maxw, w);
3746 unlock (__func__);
3747 done:
3748 ret_v = caml_copy_double (maxw);
3749 CAMLreturn (ret_v);
3752 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3754 CAMLparam4 (pt_v, x_v, y_v, string_v);
3755 CAMLlocal1 (ret_v);
3756 int pt = Int_val(pt_v);
3757 int x = Int_val (x_v);
3758 int y = Int_val (y_v);
3759 double w;
3761 w = draw_string (state.face, pt, x, y, String_val (string_v));
3762 ret_v = caml_copy_double (w);
3763 CAMLreturn (ret_v);
3766 CAMLprim value ml_measure_string (value pt_v, value string_v)
3768 CAMLparam2 (pt_v, string_v);
3769 CAMLlocal1 (ret_v);
3770 int pt = Int_val (pt_v);
3771 double w;
3773 w = measure_string (state.face, pt, String_val (string_v));
3774 ret_v = caml_copy_double (w);
3775 CAMLreturn (ret_v);
3778 CAMLprim value ml_getpagebox (value opaque_v)
3780 CAMLparam1 (opaque_v);
3781 CAMLlocal1 (ret_v);
3782 fz_rect rect;
3783 fz_irect bbox;
3784 fz_matrix ctm;
3785 fz_device *dev;
3786 char *s = String_val (opaque_v);
3787 struct page *page = parse_pointer (__func__, s);
3789 ret_v = caml_alloc_tuple (4);
3790 dev = fz_new_bbox_device (state.ctx, &rect);
3792 ctm = pagectm (page);
3793 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3795 fz_close_device (state.ctx, dev);
3796 fz_drop_device (state.ctx, dev);
3797 fz_round_rect (&bbox, &rect);
3798 Field (ret_v, 0) = Val_int (bbox.x0);
3799 Field (ret_v, 1) = Val_int (bbox.y0);
3800 Field (ret_v, 2) = Val_int (bbox.x1);
3801 Field (ret_v, 3) = Val_int (bbox.y1);
3803 CAMLreturn (ret_v);
3806 CAMLprim void ml_setaalevel (value level_v)
3808 CAMLparam1 (level_v);
3810 state.aalevel = Int_val (level_v);
3811 CAMLreturn0;
3814 #ifndef __COCOA__
3815 #pragma GCC diagnostic push
3816 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3817 #include <X11/Xlib.h>
3818 #include <X11/cursorfont.h>
3819 #pragma GCC diagnostic pop
3821 #ifdef USE_EGL
3822 #include <EGL/egl.h>
3823 #else
3824 #include <GL/glx.h>
3825 #endif
3827 static const int shapes[] = {
3828 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3831 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3833 static struct {
3834 Window wid;
3835 Display *dpy;
3836 #ifdef USE_EGL
3837 EGLContext ctx;
3838 EGLConfig conf;
3839 EGLSurface win;
3840 EGLDisplay *edpy;
3841 #else
3842 GLXContext ctx;
3843 #endif
3844 XVisualInfo *visual;
3845 Cursor curs[CURS_COUNT];
3846 } glx;
3849 static void initcurs (void)
3851 for (size_t n = 0; n < CURS_COUNT; ++n) {
3852 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3856 CAMLprim void ml_setbgcol (value color_v)
3858 CAMLparam1 (color_v);
3859 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3860 CAMLreturn0;
3863 #ifdef USE_EGL
3864 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3866 CAMLparam3 (display_v, wid_v, screen_v);
3867 int major, minor;
3868 int num_conf;
3869 EGLint visid;
3870 EGLint attribs[] = {
3871 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3872 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3873 EGL_NONE
3875 EGLConfig conf;
3877 glx.dpy = XOpenDisplay (String_val (display_v));
3878 if (!glx.dpy) {
3879 caml_failwith ("XOpenDisplay");
3882 eglBindAPI (EGL_OPENGL_API);
3884 glx.edpy = eglGetDisplay (glx.dpy);
3885 if (glx.edpy == EGL_NO_DISPLAY) {
3886 caml_failwith ("eglGetDisplay");
3889 if (!eglInitialize (glx.edpy, &major, &minor)) {
3890 caml_failwith ("eglInitialize");
3893 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3894 !num_conf) {
3895 caml_failwith ("eglChooseConfig");
3898 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3899 caml_failwith ("eglGetConfigAttrib");
3902 glx.conf = conf;
3903 initcurs ();
3905 glx.wid = Int_val (wid_v);
3906 CAMLreturn (Val_int (visid));
3909 CAMLprim void ml_glxcompleteinit (value unit_v)
3911 CAMLparam1 (unit_v);
3913 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3914 if (!glx.ctx) {
3915 caml_failwith ("eglCreateContext");
3918 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3919 glx.wid, NULL);
3920 if (glx.win == EGL_NO_SURFACE) {
3921 caml_failwith ("eglCreateWindowSurface");
3924 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3925 glx.ctx = NULL;
3926 caml_failwith ("eglMakeCurrent");
3928 CAMLreturn0;
3930 #else
3931 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3933 CAMLparam3 (display_v, wid_v, screen_v);
3935 glx.dpy = XOpenDisplay (String_val (display_v));
3936 if (!glx.dpy) {
3937 caml_failwith ("XOpenDisplay");
3940 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3941 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3942 if (!glx.visual) {
3943 XCloseDisplay (glx.dpy);
3944 caml_failwith ("glXChooseVisual");
3947 initcurs ();
3949 glx.wid = Int_val (wid_v);
3950 CAMLreturn (Val_int (glx.visual->visualid));
3953 CAMLprim void ml_glxcompleteinit (value unit_v)
3955 CAMLparam1 (unit_v);
3957 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3958 if (!glx.ctx) {
3959 caml_failwith ("glXCreateContext");
3962 XFree (glx.visual);
3963 glx.visual = NULL;
3965 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3966 glXDestroyContext (glx.dpy, glx.ctx);
3967 glx.ctx = NULL;
3968 caml_failwith ("glXMakeCurrent");
3970 CAMLreturn0;
3972 #endif
3974 CAMLprim void ml_setcursor (value cursor_v)
3976 CAMLparam1 (cursor_v);
3977 size_t cursn = Int_val (cursor_v);
3979 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3980 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3981 XFlush (glx.dpy);
3982 CAMLreturn0;
3985 CAMLprim void ml_swapb (value unit_v)
3987 CAMLparam1 (unit_v);
3988 #ifdef USE_EGL
3989 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3990 caml_failwith ("eglSwapBuffers");
3992 #else
3993 glXSwapBuffers (glx.dpy, glx.wid);
3994 #endif
3995 CAMLreturn0;
3998 #include "keysym2ucs.c"
4000 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4002 CAMLparam1 (keysym_v);
4003 CAMLlocal1 (str_v);
4004 KeySym keysym = Int_val (keysym_v);
4005 Rune rune;
4006 int len;
4007 char buf[5];
4009 rune = keysym2ucs (keysym);
4010 len = fz_runetochar (buf, rune);
4011 buf[len] = 0;
4012 str_v = caml_copy_string (buf);
4013 CAMLreturn (str_v);
4015 #else
4016 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4018 CAMLparam1 (keysym_v);
4019 CAMLlocal1 (str_v);
4020 long ucs_v = Long_val (keysym_v);
4021 int len;
4022 char buf[5];
4024 len = fz_runetochar (buf, ucs_v);
4025 buf[len] = 0;
4026 str_v = caml_copy_string (buf);
4027 CAMLreturn (str_v);
4029 #endif
4031 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4033 CAMLprim value ml_platform (value unit_v)
4035 CAMLparam1 (unit_v);
4036 CAMLlocal2 (tup_v, arr_v);
4037 int platid = piunknown;
4038 struct utsname buf;
4040 #if defined __linux__
4041 platid = pilinux;
4042 #elif defined __CYGWIN__
4043 platid = picygwin;
4044 #elif defined __DragonFly__ || defined __FreeBSD__
4045 || defined __OpenBSD__ || defined __NetBSD__
4046 platid = pibsd;
4047 #elif defined __sun__
4048 platid = pisun;
4049 #elif defined __APPLE__
4050 platid = piosx;
4051 #endif
4052 if (uname (&buf)) err (1, "uname");
4054 tup_v = caml_alloc_tuple (2);
4056 char const *sar[] = {
4057 buf.sysname,
4058 buf.release,
4059 buf.version,
4060 buf.machine,
4061 NULL
4063 arr_v = caml_copy_string_array (sar);
4065 Field (tup_v, 0) = Val_int (platid);
4066 Field (tup_v, 1) = arr_v;
4067 CAMLreturn (tup_v);
4070 CAMLprim void ml_cloexec (value fd_v)
4072 CAMLparam1 (fd_v);
4073 int fd = Int_val (fd_v);
4075 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4076 uerror ("fcntl", Nothing);
4078 CAMLreturn0;
4081 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4083 CAMLparam2 (w_v, h_v);
4084 CAMLlocal1 (ret_v);
4085 struct bo *pbo;
4086 int w = Int_val (w_v);
4087 int h = Int_val (h_v);
4088 int cs = Int_val (cs_v);
4090 if (state.bo_usable) {
4091 pbo = calloc (sizeof (*pbo), 1);
4092 if (!pbo) {
4093 err (1, "calloc pbo");
4096 switch (cs) {
4097 case 0:
4098 case 1:
4099 pbo->size = w*h*4;
4100 break;
4101 case 2:
4102 pbo->size = w*h*2;
4103 break;
4104 default:
4105 errx (1, "%s: invalid colorspace %d", __func__, cs);
4108 state.glGenBuffersARB (1, &pbo->id);
4109 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4110 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4111 NULL, GL_STREAM_DRAW);
4112 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4113 GL_READ_WRITE);
4114 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4115 if (!pbo->ptr) {
4116 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4117 state.glDeleteBuffersARB (1, &pbo->id);
4118 free (pbo);
4119 ret_v = caml_copy_string ("0");
4121 else {
4122 int res;
4123 char *s;
4125 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4126 if (res < 0) {
4127 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4129 s = malloc (res+1);
4130 if (!s) {
4131 err (1, "malloc %d bytes failed", res+1);
4133 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4134 if (res < 0) {
4135 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4137 ret_v = caml_copy_string (s);
4138 free (s);
4141 else {
4142 ret_v = caml_copy_string ("0");
4144 CAMLreturn (ret_v);
4147 CAMLprim void ml_freepbo (value s_v)
4149 CAMLparam1 (s_v);
4150 char *s = String_val (s_v);
4151 struct tile *tile = parse_pointer (__func__, s);
4153 if (tile->pbo) {
4154 state.glDeleteBuffersARB (1, &tile->pbo->id);
4155 tile->pbo->id = -1;
4156 tile->pbo->ptr = NULL;
4157 tile->pbo->size = -1;
4159 CAMLreturn0;
4162 CAMLprim void ml_unmappbo (value s_v)
4164 CAMLparam1 (s_v);
4165 char *s = String_val (s_v);
4166 struct tile *tile = parse_pointer (__func__, s);
4168 if (tile->pbo) {
4169 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4170 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4171 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4173 tile->pbo->ptr = NULL;
4174 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4176 CAMLreturn0;
4179 static void setuppbo (void)
4181 #ifdef __COCOA__
4182 static CFBundleRef framework = NULL;
4183 if (framework == NULL)
4184 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
4185 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
4186 #else
4187 #ifdef USE_EGL
4188 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4189 #else
4190 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4191 #endif
4192 state.bo_usable = GGPA (glBindBufferARB)
4193 && GGPA (glUnmapBufferARB)
4194 && GGPA (glMapBufferARB)
4195 && GGPA (glBufferDataARB)
4196 && GGPA (glGenBuffersARB)
4197 && GGPA (glDeleteBuffersARB);
4198 #endif
4199 #undef GGPA
4202 CAMLprim value ml_bo_usable (value unit_v)
4204 CAMLparam1 (unit_v);
4205 CAMLreturn (Val_bool (state.bo_usable));
4208 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4210 CAMLparam3 (ptr_v, x_v, y_v);
4211 CAMLlocal2 (ret_v, tup_v);
4212 struct page *page;
4213 char *s = String_val (ptr_v);
4214 int x = Int_val (x_v), y = Int_val (y_v);
4215 struct pagedim *pdim;
4216 fz_point p;
4217 fz_matrix ctm;
4219 page = parse_pointer (__func__, s);
4220 pdim = &state.pagedims[page->pdimno];
4222 ret_v = Val_int (0);
4223 if (trylock (__func__)) {
4224 goto done;
4227 if (pdf_specifics (state.ctx, state.doc)) {
4228 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4229 ctm = state.pagedims[page->pdimno].tctm;
4231 else {
4232 ctm = fz_identity;
4234 p.x = x + pdim->bounds.x0;
4235 p.y = y + pdim->bounds.y0;
4237 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4238 fz_invert_matrix (&ctm, &ctm);
4239 fz_transform_point (&p, &ctm);
4241 tup_v = caml_alloc_tuple (2);
4242 ret_v = caml_alloc_small (1, 1);
4243 Field (tup_v, 0) = Val_int (p.x);
4244 Field (tup_v, 1) = Val_int (p.y);
4245 Field (ret_v, 0) = tup_v;
4247 unlock (__func__);
4248 done:
4249 CAMLreturn (ret_v);
4252 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4253 value x_v, value y_v)
4255 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4256 CAMLlocal1 (ret_v);
4257 struct page *page;
4258 char *s = String_val (ptr_v);
4259 int pageno = Int_val (pageno_v);
4260 int pdimno = Int_val (pdimno_v);
4261 double x = Double_val (x_v), y = Double_val (y_v);
4262 struct pagedim *pdim;
4263 fz_point p;
4264 fz_matrix ctm;
4266 ret_v = Val_int (0);
4267 lock (__func__);
4269 if (!*s) {
4270 page = loadpage (pageno, pdimno);
4272 else {
4273 page = parse_pointer (__func__, s);
4275 pdim = &state.pagedims[pdimno];
4277 if (pdf_specifics (state.ctx, state.doc)) {
4278 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4279 ctm = state.pagedims[page->pdimno].tctm;
4281 else {
4282 ctm = fz_identity;
4284 p.x = x + pdim->bounds.x0;
4285 p.y = y + pdim->bounds.y0;
4287 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4288 fz_transform_point (&p, &ctm);
4290 ret_v = caml_alloc_tuple (2);
4291 Field (ret_v, 0) = caml_copy_double (p.x);
4292 Field (ret_v, 1) = caml_copy_double (p.y);
4294 if (!*s) {
4295 freepage (page);
4297 unlock (__func__);
4298 CAMLreturn (ret_v);
4301 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4302 value contents_v)
4304 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4305 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4307 if (pdf) {
4308 pdf_annot *annot;
4309 struct page *page;
4310 fz_point p;
4311 char *s = String_val (ptr_v);
4313 page = parse_pointer (__func__, s);
4314 annot = pdf_create_annot (state.ctx,
4315 pdf_page_from_fz_page (state.ctx,
4316 page->fzpage),
4317 PDF_ANNOT_TEXT);
4318 p.x = Int_val (x_v);
4319 p.y = Int_val (y_v);
4320 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4321 pdf_set_text_annot_position (state.ctx, annot, p);
4322 state.dirty = 1;
4324 CAMLreturn0;
4327 CAMLprim void ml_delannot (value ptr_v, value n_v)
4329 CAMLparam2 (ptr_v, n_v);
4330 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4332 if (pdf) {
4333 struct page *page;
4334 char *s = String_val (ptr_v);
4335 struct slink *slink;
4337 page = parse_pointer (__func__, s);
4338 slink = &page->slinks[Int_val (n_v)];
4339 pdf_delete_annot (state.ctx,
4340 pdf_page_from_fz_page (state.ctx, page->fzpage),
4341 (pdf_annot *) slink->u.annot);
4342 state.dirty = 1;
4344 CAMLreturn0;
4347 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4349 CAMLparam3 (ptr_v, n_v, str_v);
4350 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4352 if (pdf) {
4353 struct page *page;
4354 char *s = String_val (ptr_v);
4355 struct slink *slink;
4357 page = parse_pointer (__func__, s);
4358 slink = &page->slinks[Int_val (n_v)];
4359 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4360 String_val (str_v));
4361 state.dirty = 1;
4363 CAMLreturn0;
4366 CAMLprim value ml_hasunsavedchanges (value unit_v)
4368 CAMLparam1 (unit_v);
4369 CAMLreturn (Val_bool (state.dirty));
4372 CAMLprim void ml_savedoc (value path_v)
4374 CAMLparam1 (path_v);
4375 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4377 if (pdf) {
4378 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4380 CAMLreturn0;
4383 static void makestippletex (void)
4385 const char pixels[] = "\xff\xff\0\0";
4386 glGenTextures (1, &state.stid);
4387 glBindTexture (GL_TEXTURE_1D, state.stid);
4388 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4389 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4390 glTexImage1D (
4391 GL_TEXTURE_1D,
4393 GL_ALPHA,
4396 GL_ALPHA,
4397 GL_UNSIGNED_BYTE,
4398 pixels
4402 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4404 return caml_copy_string (FZ_VERSION);
4407 CAMLprim void ml_init (value csock_v, value params_v)
4409 CAMLparam2 (csock_v, params_v);
4410 CAMLlocal2 (trim_v, fuzz_v);
4411 int ret;
4412 int texcount;
4413 char *fontpath;
4414 int colorspace;
4415 int mustoresize;
4416 int haspboext;
4418 /* Without following call to setlocale mbstowcs fails for, at
4419 least, strings containing chinese symbols (δΈ­ for instance)
4420 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4421 wide character" as the reason of failure and with macOS
4422 producing bogus output) */
4423 if (setlocale (LC_CTYPE, "")) {
4424 /* Following two lines were taken from dvtm/vt.c */
4425 const char *cset = nl_langinfo (CODESET);
4426 state.utf8cs = !strcmp (cset, "UTF-8");
4428 else {
4429 fprintf (stderr, "setlocale failed\n");
4432 state.csock = Int_val (csock_v);
4433 state.rotate = Int_val (Field (params_v, 0));
4434 state.fitmodel = Int_val (Field (params_v, 1));
4435 trim_v = Field (params_v, 2);
4436 texcount = Int_val (Field (params_v, 3));
4437 state.sliceheight = Int_val (Field (params_v, 4));
4438 mustoresize = Int_val (Field (params_v, 5));
4439 colorspace = Int_val (Field (params_v, 6));
4440 fontpath = String_val (Field (params_v, 7));
4442 if (caml_string_length (Field (params_v, 8)) > 0) {
4443 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4445 if (!state.trimcachepath) {
4446 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4447 strerror (errno));
4451 haspboext = Bool_val (Field (params_v, 9));
4453 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4454 fz_register_document_handlers (state.ctx);
4456 state.trimmargins = Bool_val (Field (trim_v, 0));
4457 fuzz_v = Field (trim_v, 1);
4458 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4459 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4460 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4461 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4463 set_tex_params (colorspace);
4465 if (*fontpath) {
4466 state.face = load_font (fontpath);
4468 else {
4469 int len;
4470 const unsigned char *data;
4472 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4473 state.face = load_builtin_font (data, len);
4475 if (!state.face) _exit (1);
4477 realloctexts (texcount);
4479 if (haspboext) {
4480 setuppbo ();
4483 makestippletex ();
4485 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4486 if (ret) {
4487 errx (1, "pthread_create: %s", strerror (ret));
4490 CAMLreturn0;