Sprinkle with some diagnostics
[llpp.git] / link.c
blobcc0bc5d5bd9ccb5451e06f7d2896e84c295b1977
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 #include <mupdf/fitz.h>
57 #include <mupdf/pdf.h>
59 #include <ft2build.h>
60 #include FT_FREETYPE_H
62 #define PIGGYBACK
63 #define CACHE_PAGEREFS
65 #ifndef __USE_GNU
66 extern char **environ;
67 #endif
69 #if defined __GNUC__
70 #define NORETURN_ATTR __attribute__ ((noreturn))
71 #define UNUSED_ATTR __attribute__ ((unused))
72 #if !defined __clang__
73 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
74 #else
75 #define OPTIMIZE_ATTR(n)
76 #endif
77 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
78 #else
79 #define NORETURN_ATTR
80 #define UNUSED_ATTR
81 #define OPTIMIZE_ATTR(n)
82 #define GCC_FMT_ATTR(a, b)
83 #endif
85 #define FMT_s "zu"
87 #define FMT_ptr PRIxPTR
88 #define SCN_ptr SCNxPTR
89 #define FMT_ptr_cast(p) ((uintptr_t) (p))
90 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
92 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
93 err (int exitcode, const char *fmt, ...)
95 va_list ap;
96 int savederrno;
98 savederrno = errno;
99 va_start (ap, fmt);
100 vfprintf (stderr, fmt, ap);
101 va_end (ap);
102 fprintf (stderr, ": %s\n", strerror (savederrno));
103 fflush (stderr);
104 _exit (exitcode);
107 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
108 errx (int exitcode, const char *fmt, ...)
110 va_list ap;
112 va_start (ap, fmt);
113 vfprintf (stderr, fmt, ap);
114 va_end (ap);
115 fputc ('\n', stderr);
116 fflush (stderr);
117 _exit (exitcode);
120 #ifndef GL_TEXTURE_RECTANGLE_ARB
121 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
122 #endif
124 #ifdef USE_NPOT
125 #define TEXT_TYPE GL_TEXTURE_2D
126 #else
127 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
128 #endif
130 #ifndef GL_BGRA
131 #define GL_BGRA 0x80E1
132 #endif
134 #ifndef GL_UNSIGNED_INT_8_8_8_8
135 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
136 #endif
138 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
139 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
140 #endif
142 #if 0
143 #define lprintf printf
144 #else
145 #define lprintf(...)
146 #endif
148 #define ARSERT(cond) for (;;) { \
149 if (!(cond)) { \
150 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
152 break; \
155 struct slice {
156 int h;
157 int texindex;
160 struct tile {
161 int w, h;
162 int slicecount;
163 int sliceheight;
164 struct bo *pbo;
165 fz_pixmap *pixmap;
166 struct slice slices[1];
169 struct pagedim {
170 int pageno;
171 int rotate;
172 int left;
173 int tctmready;
174 fz_irect bounds;
175 fz_rect pagebox;
176 fz_rect mediabox;
177 fz_matrix ctm, zoomctm, tctm;
180 struct slink {
181 enum { SLINK, SANNOT } tag;
182 fz_irect bbox;
183 union {
184 fz_link *link;
185 fz_annot *annot;
186 } u;
189 struct annot {
190 fz_irect bbox;
191 fz_annot *annot;
194 struct page {
195 int tgen;
196 int sgen;
197 int agen;
198 int pageno;
199 int pdimno;
200 fz_stext_page *text;
201 fz_stext_sheet *sheet;
202 fz_page *fzpage;
203 fz_display_list *dlist;
204 int slinkcount;
205 struct slink *slinks;
206 int annotcount;
207 struct annot *annots;
208 struct mark {
209 int i;
210 fz_stext_span *span;
211 } fmark, lmark;
214 struct {
215 int sliceheight;
216 struct pagedim *pagedims;
217 int pagecount;
218 int pagedimcount;
219 fz_document *doc;
220 fz_context *ctx;
221 int w, h;
223 int texindex;
224 int texcount;
225 GLuint *texids;
227 GLenum texiform;
228 GLenum texform;
229 GLenum texty;
231 fz_colorspace *colorspace;
233 struct {
234 int w, h;
235 struct slice *slice;
236 } *texowners;
238 int rotate;
239 enum { FitWidth, FitProportional, FitPage } fitmodel;
240 int trimmargins;
241 int needoutline;
242 int gen;
243 int aalevel;
245 int trimanew;
246 fz_irect trimfuzz;
247 fz_pixmap *pig;
249 pthread_t thread;
250 int csock;
251 FT_Face face;
253 char *trimcachepath;
254 int cxack;
255 int dirty;
257 GLuint stid;
259 int bo_usable;
260 GLuint boid;
262 void (*glBindBufferARB) (GLenum, GLuint);
263 GLboolean (*glUnmapBufferARB) (GLenum);
264 void *(*glMapBufferARB) (GLenum, GLenum);
265 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
266 void (*glGenBuffersARB) (GLsizei, GLuint *);
267 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
269 GLfloat texcoords[8];
270 GLfloat vertices[16];
272 #ifdef CACHE_PAGEREFS
273 struct {
274 int idx;
275 int count;
276 pdf_obj **objs;
277 pdf_document *pdf;
278 } pdflut;
279 #endif
280 int utf8cs;
281 } state;
283 struct bo {
284 GLuint id;
285 void *ptr;
286 size_t size;
289 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
291 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
294 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
296 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
299 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
301 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
302 m.a, m.b, m.c, m.d, m.e, m.f);
305 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
307 static void lock (const char *cap)
309 int ret = pthread_mutex_lock (&mutex);
310 if (ret) {
311 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
315 static void unlock (const char *cap)
317 int ret = pthread_mutex_unlock (&mutex);
318 if (ret) {
319 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
323 static int trylock (const char *cap)
325 int ret = pthread_mutex_trylock (&mutex);
326 if (ret && ret != EBUSY) {
327 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
329 return ret == EBUSY;
332 static void *parse_pointer (const char *cap, const char *s)
334 int ret;
335 void *ptr;
337 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
338 if (ret != 1) {
339 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
341 return ptr;
344 static double now (void)
346 struct timeval tv;
348 if (gettimeofday (&tv, NULL)) {
349 err (1, "gettimeofday");
351 return tv.tv_sec + tv.tv_usec*1e-6;
354 static int hasdata (void)
356 int ret, avail;
357 ret = ioctl (state.csock, FIONREAD, &avail);
358 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
359 return avail > 0;
362 CAMLprim value ml_hasdata (value fd_v)
364 CAMLparam1 (fd_v);
365 int ret, avail;
367 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
368 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
369 CAMLreturn (Val_bool (avail > 0));
372 static void readdata (int fd, void *p, int size)
374 ssize_t n;
376 again:
377 n = read (fd, p, size);
378 if (n - size) {
379 if (n < 0 && errno == EINTR) goto again;
380 if (!n) errx (1, "EOF while reading");
381 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
385 static void writedata (int fd, char *p, int size)
387 ssize_t n;
388 uint32_t size4 = size;
389 struct iovec iov[2] = {
390 { .iov_base = &size4, .iov_len = 4 },
391 { .iov_base = p, .iov_len = size }
394 again:
395 n = writev (fd, iov, 2);
396 if (n < 0 && errno == EINTR) goto again;
397 if (n - size - 4) {
398 if (!n) errx (1, "EOF while writing data");
399 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
403 static int readlen (int fd)
405 /* Type punned unions here. Why? Less code (Adjusted by more comments).
406 https://en.wikipedia.org/wiki/Type_punning */
407 union { uint32_t len; char raw[4]; } buf;
408 readdata (fd, buf.raw, 4);
409 return buf.len;
412 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
414 CAMLparam3 (fd_v, bytes_v, len_v);
415 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
416 CAMLreturn0;
419 CAMLprim value ml_rcmd (value fd_v)
421 CAMLparam1 (fd_v);
422 CAMLlocal1 (strdata_v);
423 int fd = Int_val (fd_v);
424 int len = readlen (fd);
425 strdata_v = caml_alloc_string (len);
426 readdata (fd, String_val (strdata_v), len);
427 CAMLreturn (strdata_v);
430 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
432 int size = 64, len;
433 va_list ap;
434 char fbuf[size];
435 char *buf = fbuf;
437 for (;;) {
438 va_start (ap, fmt);
439 len = vsnprintf (buf, size, fmt, ap);
440 va_end (ap);
442 if (len > -1) {
443 if (len < size - 4) {
444 writedata (state.csock, buf, len);
445 break;
447 else size = len + 5;
449 else {
450 err (1, "vsnprintf for `%s' failed", fmt);
452 buf = realloc (buf == fbuf ? NULL : buf, size);
453 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
455 if (buf != fbuf) free (buf);
458 static void closedoc (void)
460 #ifdef CACHE_PAGEREFS
461 if (state.pdflut.objs) {
462 for (int i = 0; i < state.pdflut.count; ++i) {
463 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
465 free (state.pdflut.objs);
466 state.pdflut.objs = NULL;
467 state.pdflut.idx = 0;
469 #endif
470 if (state.doc) {
471 fz_drop_document (state.ctx, state.doc);
472 state.doc = NULL;
476 static int openxref (char *filename, char *password)
478 for (int i = 0; i < state.texcount; ++i) {
479 state.texowners[i].w = -1;
480 state.texowners[i].slice = NULL;
483 closedoc ();
485 state.dirty = 0;
486 if (state.pagedims) {
487 free (state.pagedims);
488 state.pagedims = NULL;
490 state.pagedimcount = 0;
492 fz_set_aa_level (state.ctx, state.aalevel);
493 state.doc = fz_open_document (state.ctx, filename);
494 if (fz_needs_password (state.ctx, state.doc)) {
495 if (password && !*password) {
496 printd ("pass");
497 return 0;
499 else {
500 int ok = fz_authenticate_password (state.ctx, state.doc, password);
501 if (!ok) {
502 printd ("pass fail");
503 return 0;
507 state.pagecount = fz_count_pages (state.ctx, state.doc);
508 return 1;
511 static void pdfinfo (void)
513 struct { char *tag; char *name; } metatbl[] = {
514 { FZ_META_INFO_TITLE, "Title" },
515 { FZ_META_INFO_AUTHOR, "Author" },
516 { FZ_META_FORMAT, "Format" },
517 { FZ_META_ENCRYPTION, "Encryption" },
518 { "info:Creator", "Creator" },
519 { "info:Producer", "Producer" },
520 { "info:CreationDate", "Creation date" },
522 int len = 0;
523 char *buf = NULL;
525 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
526 int need;
527 again:
528 need = fz_lookup_metadata (state.ctx, state.doc,
529 metatbl[i].tag, buf, len);
530 if (need > 0) {
531 if (need <= len) {
532 printd ("info %s\t%s", metatbl[i].name, buf);
534 else {
535 buf = realloc (buf, need + 1);
536 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
537 len = need + 1;
538 goto again;
542 free (buf);
544 printd ("infoend");
547 static void unlinktile (struct tile *tile)
549 for (int i = 0; i < tile->slicecount; ++i) {
550 struct slice *s = &tile->slices[i];
552 if (s->texindex != -1) {
553 if (state.texowners[s->texindex].slice == s) {
554 state.texowners[s->texindex].slice = NULL;
560 static void freepage (struct page *page)
562 if (!page) return;
563 if (page->text) {
564 fz_drop_stext_page (state.ctx, page->text);
566 if (page->sheet) {
567 fz_drop_stext_sheet (state.ctx, page->sheet);
569 if (page->slinks) {
570 free (page->slinks);
572 fz_drop_display_list (state.ctx, page->dlist);
573 fz_drop_page (state.ctx, page->fzpage);
574 free (page);
577 static void freetile (struct tile *tile)
579 unlinktile (tile);
580 if (!tile->pbo) {
581 #ifndef PIGGYBACK
582 fz_drop_pixmap (state.ctx, tile->pixmap);
583 #else
584 if (state.pig) {
585 fz_drop_pixmap (state.ctx, state.pig);
587 state.pig = tile->pixmap;
588 #endif
590 else {
591 free (tile->pbo);
592 fz_drop_pixmap (state.ctx, tile->pixmap);
594 free (tile);
597 #ifdef __ALTIVEC__
598 #include <stdint.h>
599 #include <altivec.h>
601 static int cacheline32bytes;
603 static void __attribute__ ((constructor)) clcheck (void)
605 char **envp = environ;
606 unsigned long *auxv;
608 while (*envp++);
610 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
611 if (*auxv == 19) {
612 cacheline32bytes = auxv[1] == 32;
613 return;
618 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
620 size_t size = pixmap->w * pixmap->h * pixmap->n;
621 if (cacheline32bytes && size > 32) {
622 intptr_t a1, a2, diff;
623 size_t sizea, i;
624 vector unsigned char v = vec_splat_u8 (-1);
625 vector unsigned char *p;
627 a1 = a2 = (intptr_t) pixmap->samples;
628 a2 = (a1 + 31) & ~31;
629 diff = a2 - a1;
630 sizea = size - diff;
631 p = (void *) a2;
633 while (a1 != a2) *(char *) a1++ = 0xff;
634 for (i = 0; i < (sizea & ~31); i += 32) {
635 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
636 vec_st (v, i, p);
637 vec_st (v, i + 16, p);
639 while (i < sizea) *((char *) a1 + i++) = 0xff;
641 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
643 #else
644 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
645 #endif
647 static void trimctm (pdf_page *page, int pindex)
649 fz_matrix ctm;
650 struct pagedim *pdim = &state.pagedims[pindex];
652 if (!page) return;
653 if (!pdim->tctmready) {
654 fz_rect realbox, mediabox;
655 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
657 fz_rotate (&rm, -pdim->rotate);
658 fz_scale (&sm, 1, -1);
659 fz_concat (&ctm, &rm, &sm);
660 realbox = pdim->mediabox;
661 fz_transform_rect (&realbox, &ctm);
662 fz_translate (&tm, -realbox.x0, -realbox.y0);
663 fz_concat (&ctm1, &ctm, &tm);
664 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
665 fz_invert_matrix (&im, &page_ctm);
666 fz_concat (&ctm, &im, &ctm1);
667 pdim->tctm = ctm;
668 pdim->tctmready = 1;
672 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
674 fz_matrix ctm, tm;
675 int pdimno = pdim - state.pagedims;
677 if (pdf_specifics (state.ctx, state.doc)) {
678 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
679 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
681 else {
682 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
683 fz_concat (&ctm, &tm, &pdim->ctm);
685 return ctm;
688 static fz_matrix pagectm (struct page *page)
690 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
693 static void *loadpage (int pageno, int pindex)
695 fz_device *dev;
696 struct page *page;
698 page = calloc (sizeof (struct page), 1);
699 if (!page) {
700 err (1, "calloc page %d", pageno);
703 page->dlist = fz_new_display_list (state.ctx, NULL);
704 dev = fz_new_list_device (state.ctx, page->dlist);
705 fz_try (state.ctx) {
706 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
707 fz_run_page (state.ctx, page->fzpage, dev,
708 &fz_identity, NULL);
710 fz_catch (state.ctx) {
711 page->fzpage = NULL;
713 fz_close_device (state.ctx, dev);
714 fz_drop_device (state.ctx, dev);
716 page->pdimno = pindex;
717 page->pageno = pageno;
718 page->sgen = state.gen;
719 page->agen = state.gen;
720 page->tgen = state.gen;
721 return page;
724 static struct tile *alloctile (int h)
726 int slicecount;
727 size_t tilesize;
728 struct tile *tile;
730 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
731 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
732 tile = calloc (tilesize, 1);
733 if (!tile) {
734 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
736 for (int i = 0; i < slicecount; ++i) {
737 int sh = fz_mini (h, state.sliceheight);
738 tile->slices[i].h = sh;
739 tile->slices[i].texindex = -1;
740 h -= sh;
742 tile->slicecount = slicecount;
743 tile->sliceheight = state.sliceheight;
744 return tile;
747 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
748 struct bo *pbo)
750 fz_rect rect;
751 fz_irect bbox;
752 fz_matrix ctm;
753 fz_device *dev;
754 struct tile *tile;
755 struct pagedim *pdim;
757 tile = alloctile (h);
758 pdim = &state.pagedims[page->pdimno];
760 bbox = pdim->bounds;
761 bbox.x0 += x;
762 bbox.y0 += y;
763 bbox.x1 = bbox.x0 + w;
764 bbox.y1 = bbox.y0 + h;
766 if (state.pig) {
767 if (state.pig->w == w
768 && state.pig->h == h
769 && state.pig->colorspace == state.colorspace) {
770 tile->pixmap = state.pig;
771 tile->pixmap->x = bbox.x0;
772 tile->pixmap->y = bbox.y0;
774 else {
775 fz_drop_pixmap (state.ctx, state.pig);
777 state.pig = NULL;
779 if (!tile->pixmap) {
780 if (pbo) {
781 tile->pixmap =
782 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
783 &bbox, 1, pbo->ptr);
784 tile->pbo = pbo;
786 else {
787 tile->pixmap =
788 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
792 tile->w = w;
793 tile->h = h;
794 clearpixmap (tile->pixmap);
796 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
797 ctm = pagectm (page);
798 fz_rect_from_irect (&rect, &bbox);
799 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
800 fz_close_device (state.ctx, dev);
801 fz_drop_device (state.ctx, dev);
803 return tile;
806 #ifdef CACHE_PAGEREFS
807 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
808 thanks to Robin Watts */
809 static void
810 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
812 fz_context *ctx = state.ctx; /* doc->ctx; */
813 pdf_obj *kids;
814 int len;
816 if (state.pdflut.idx == state.pagecount) return;
818 kids = pdf_dict_gets (ctx, node, "Kids");
819 len = pdf_array_len (ctx, kids);
821 if (len == 0)
822 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
824 if (pdf_mark_obj (ctx, node))
825 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
826 for (int i = 0; i < len; i++) {
827 pdf_obj *kid = pdf_array_get (ctx, kids, i);
828 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
829 if (*type
830 ? !strcmp (type, "Pages")
831 : pdf_dict_gets (ctx, kid, "Kids")
832 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
833 pdf_collect_pages (doc, kid);
835 else {
836 if (*type
837 ? strcmp (type, "Page") != 0
838 : !pdf_dict_gets (ctx, kid, "MediaBox"))
839 fz_warn (ctx, "non-page object in page tree (%s)", type);
840 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
843 pdf_unmark_obj (ctx, node);
846 static void
847 pdf_load_page_objs (pdf_document *doc)
849 pdf_obj *root = pdf_dict_gets (state.ctx,
850 pdf_trailer (state.ctx, doc), "Root");
851 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
853 if (!node)
854 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
856 state.pdflut.idx = 0;
857 pdf_collect_pages (doc, node);
859 #endif
861 static void initpdims (int wthack)
863 double start, end;
864 FILE *trimf = NULL;
865 fz_rect rootmediabox;
866 int pageno, trim, show;
867 int trimw = 0, cxcount;
868 fz_context *ctx = state.ctx;
869 pdf_document *pdf = pdf_specifics (ctx, state.doc);
871 fz_var (trimw);
872 fz_var (trimf);
873 fz_var (cxcount);
874 start = now ();
876 if (state.trimmargins && state.trimcachepath) {
877 trimf = fopen (state.trimcachepath, "rb");
878 if (!trimf) {
879 trimf = fopen (state.trimcachepath, "wb");
880 trimw = 1;
884 if (state.trimmargins || pdf || !state.cxack)
885 cxcount = state.pagecount;
886 else
887 cxcount = fz_mini (state.pagecount, 1);
889 if (pdf) {
890 pdf_obj *obj;
891 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
892 "Root/Pages/MediaBox");
893 pdf_to_rect (ctx, obj, &rootmediabox);
896 #ifdef CACHE_PAGEREFS
897 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
898 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
899 if (!state.pdflut.objs) {
900 err (1, "malloc pageobjs %zu %d %zu failed",
901 sizeof (*state.pdflut.objs), cxcount,
902 sizeof (*state.pdflut.objs) * cxcount);
904 state.pdflut.count = cxcount;
905 pdf_load_page_objs (pdf);
906 state.pdflut.pdf = pdf;
908 #endif
910 for (pageno = 0; pageno < cxcount; ++pageno) {
911 int rotate = 0;
912 struct pagedim *p;
913 fz_rect mediabox;
915 fz_var (rotate);
916 if (pdf) {
917 pdf_obj *pageref, *pageobj;
919 #ifdef CACHE_PAGEREFS
920 pageref = state.pdflut.objs[pageno];
921 #else
922 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
923 #endif
924 pageobj = pdf_resolve_indirect (ctx, pageref);
925 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
927 if (state.trimmargins) {
928 pdf_obj *obj;
929 pdf_page *page;
931 fz_try (ctx) {
932 page = pdf_load_page (ctx, pdf, pageno);
933 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
934 trim = state.trimanew || !obj;
935 if (trim) {
936 fz_rect rect;
937 fz_device *dev;
938 fz_matrix ctm, page_ctm;
940 dev = fz_new_bbox_device (ctx, &rect);
941 dev->hints |= FZ_IGNORE_SHADE;
942 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
943 fz_invert_matrix (&ctm, &page_ctm);
944 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
945 fz_close_device (ctx, dev);
946 fz_drop_device (ctx, dev);
948 rect.x0 += state.trimfuzz.x0;
949 rect.x1 += state.trimfuzz.x1;
950 rect.y0 += state.trimfuzz.y0;
951 rect.y1 += state.trimfuzz.y1;
952 fz_transform_rect (&rect, &ctm);
953 fz_intersect_rect (&rect, &mediabox);
955 if (!fz_is_empty_rect (&rect)) {
956 mediabox = rect;
959 obj = pdf_new_array (ctx, pdf, 4);
960 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
961 mediabox.x0));
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.y0));
964 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
965 mediabox.x1));
966 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
967 mediabox.y1));
968 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
970 else {
971 mediabox.x0 = pdf_to_real (ctx,
972 pdf_array_get (ctx, obj, 0));
973 mediabox.y0 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 1));
975 mediabox.x1 = pdf_to_real (ctx,
976 pdf_array_get (ctx, obj, 2));
977 mediabox.y1 = pdf_to_real (ctx,
978 pdf_array_get (ctx, obj, 3));
981 fz_drop_page (ctx, &page->super);
982 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
983 if (show) {
984 printd ("progress %f Trimming %d",
985 (double) (pageno + 1) / state.pagecount,
986 pageno + 1);
989 fz_catch (ctx) {
990 fprintf (stderr, "failed to load page %d\n", pageno+1);
993 else {
994 int empty = 0;
995 fz_rect cropbox;
997 pdf_to_rect (ctx,
998 pdf_dict_gets (ctx, pageobj, "MediaBox"),
999 &mediabox);
1000 if (fz_is_empty_rect (&mediabox)) {
1001 mediabox.x0 = 0;
1002 mediabox.y0 = 0;
1003 mediabox.x1 = 612;
1004 mediabox.y1 = 792;
1005 empty = 1;
1008 pdf_to_rect (ctx,
1009 pdf_dict_gets (ctx, pageobj, "CropBox"),
1010 &cropbox);
1011 if (!fz_is_empty_rect (&cropbox)) {
1012 if (empty) {
1013 mediabox = cropbox;
1015 else {
1016 fz_intersect_rect (&mediabox, &cropbox);
1019 else {
1020 if (empty) {
1021 if (fz_is_empty_rect (&rootmediabox)) {
1022 fprintf (stderr,
1023 "cannot find page size for page %d\n",
1024 pageno+1);
1026 else {
1027 mediabox = rootmediabox;
1033 else {
1034 if (state.trimmargins && trimw) {
1035 fz_page *page;
1037 fz_try (ctx) {
1038 page = fz_load_page (ctx, state.doc, pageno);
1039 fz_bound_page (ctx, page, &mediabox);
1040 if (state.trimmargins) {
1041 fz_rect rect;
1042 fz_device *dev;
1044 dev = fz_new_bbox_device (ctx, &rect);
1045 dev->hints |= FZ_IGNORE_SHADE;
1046 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1047 fz_close_device (ctx, dev);
1048 fz_drop_device (ctx, dev);
1050 rect.x0 += state.trimfuzz.x0;
1051 rect.x1 += state.trimfuzz.x1;
1052 rect.y0 += state.trimfuzz.y0;
1053 rect.y1 += state.trimfuzz.y1;
1054 fz_intersect_rect (&rect, &mediabox);
1056 if (!fz_is_empty_rect (&rect)) {
1057 mediabox = rect;
1060 fz_drop_page (ctx, page);
1061 if (!state.cxack) {
1062 printd ("progress %f loading %d",
1063 (double) (pageno + 1) / state.pagecount,
1064 pageno + 1);
1067 fz_catch (ctx) {
1069 if (trimf) {
1070 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1071 if (n - 1) {
1072 err (1, "fwrite trim mediabox");
1076 else {
1077 if (trimf) {
1078 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1079 if (n - 1) {
1080 err (1, "fread trim mediabox %d", pageno);
1083 else {
1084 fz_page *page;
1085 fz_try (ctx) {
1086 page = fz_load_page (ctx, state.doc, pageno);
1087 fz_bound_page (ctx, page, &mediabox);
1088 fz_drop_page (ctx, page);
1090 show = !state.trimmargins && pageno % 20 == 0;
1091 if (show) {
1092 printd ("progress %f Gathering dimensions %d",
1093 (double) (pageno) / state.pagecount,
1094 pageno);
1097 fz_catch (ctx) {
1098 fprintf (stderr, "failed to load page %d\n", pageno);
1104 if (state.pagedimcount == 0
1105 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1106 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1107 size_t size;
1109 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1110 state.pagedims = realloc (state.pagedims, size);
1111 if (!state.pagedims) {
1112 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1113 size, state.pagedimcount + 1);
1116 p = &state.pagedims[state.pagedimcount++];
1117 p->rotate = rotate;
1118 p->mediabox = mediabox;
1119 p->pageno = pageno;
1122 end = now ();
1123 if (!wthack) {
1124 printd ("progress 1 %s %d pages in %f seconds",
1125 state.trimmargins ? "Trimmed" : "Processed",
1126 state.pagecount, end - start);
1128 state.trimanew = 0;
1129 if (trimf) {
1130 if (fclose (trimf)) {
1131 err (1, "fclose");
1136 static void layout (void)
1138 int pindex;
1139 fz_rect box;
1140 fz_matrix ctm, rm;
1141 struct pagedim *p = p;
1142 double zw, w, maxw = 0.0, zoom = zoom;
1144 if (state.pagedimcount == 0) return;
1146 switch (state.fitmodel) {
1147 case FitProportional:
1148 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1149 double x0, x1;
1151 p = &state.pagedims[pindex];
1152 fz_rotate (&rm, p->rotate + state.rotate);
1153 box = p->mediabox;
1154 fz_transform_rect (&box, &rm);
1156 x0 = fz_min (box.x0, box.x1);
1157 x1 = fz_max (box.x0, box.x1);
1159 w = x1 - x0;
1160 maxw = fz_max (w, maxw);
1161 zoom = state.w / maxw;
1163 break;
1165 case FitPage:
1166 maxw = state.w;
1167 break;
1169 case FitWidth:
1170 break;
1172 default:
1173 ARSERT (0 && state.fitmodel);
1176 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1177 fz_rect rect;
1178 fz_matrix tm, sm;
1180 p = &state.pagedims[pindex];
1181 fz_rotate (&ctm, state.rotate);
1182 fz_rotate (&rm, p->rotate + state.rotate);
1183 box = p->mediabox;
1184 fz_transform_rect (&box, &rm);
1185 w = box.x1 - box.x0;
1186 switch (state.fitmodel) {
1187 case FitProportional:
1188 p->left = ((maxw - w) * zoom) / 2.0;
1189 break;
1190 case FitPage:
1192 double zh, h;
1193 zw = maxw / w;
1194 h = box.y1 - box.y0;
1195 zh = state.h / h;
1196 zoom = fz_min (zw, zh);
1197 p->left = (maxw - (w * zoom)) / 2.0;
1199 break;
1200 case FitWidth:
1201 p->left = 0;
1202 zoom = state.w / w;
1203 break;
1206 fz_scale (&p->zoomctm, zoom, zoom);
1207 fz_concat (&ctm, &p->zoomctm, &ctm);
1209 fz_rotate (&rm, p->rotate);
1210 p->pagebox = p->mediabox;
1211 fz_transform_rect (&p->pagebox, &rm);
1212 p->pagebox.x1 -= p->pagebox.x0;
1213 p->pagebox.y1 -= p->pagebox.y0;
1214 p->pagebox.x0 = 0;
1215 p->pagebox.y0 = 0;
1216 rect = p->pagebox;
1217 fz_transform_rect (&rect, &ctm);
1218 fz_round_rect (&p->bounds, &rect);
1219 p->ctm = ctm;
1221 fz_translate (&tm, 0, -p->mediabox.y1);
1222 fz_scale (&sm, zoom, -zoom);
1223 fz_concat (&ctm, &tm, &sm);
1225 p->tctmready = 0;
1228 do {
1229 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1230 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1231 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1232 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1233 int boundw = x1 - x0;
1234 int boundh = y1 - y0;
1236 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1237 } while (p-- != state.pagedims);
1240 struct pagedim *pdimofpageno (int pageno)
1242 struct pagedim *pdim = state.pagedims;
1244 for (int i = 0; i < state.pagedimcount; ++i) {
1245 if (state.pagedims[i].pageno > pageno)
1246 break;
1247 pdim = &state.pagedims[i];
1249 return pdim;
1252 static
1253 struct anchor { int n; int x; int y; int w; int h; }
1254 uritoanchor (const char *uri)
1256 fz_point p;
1257 struct anchor a;
1259 a.n = -1;
1260 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1261 if (a.n >= 0) {
1262 struct pagedim *pdim = pdimofpageno (a.n);
1263 fz_transform_point (&p, &pdim->ctm);
1264 a.x = p.x;
1265 a.y = p.y;
1266 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1268 return a;
1271 static void recurse_outline (fz_outline *outline, int level)
1273 while (outline) {
1274 struct anchor a = uritoanchor (outline->uri);
1275 if (a.n >= 0) {
1276 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1278 else {
1279 printd ("on %d %s", level, outline->title);
1281 if (outline->down) {
1282 recurse_outline (outline->down, level + 1);
1284 outline = outline->next;
1288 static void process_outline (void)
1290 fz_outline *outline;
1292 if (!state.needoutline || !state.pagedimcount) return;
1294 state.needoutline = 0;
1295 outline = fz_load_outline (state.ctx, state.doc);
1296 if (outline) {
1297 recurse_outline (outline, 0);
1298 fz_drop_outline (state.ctx, outline);
1302 static char *strofspan (fz_stext_span *span)
1304 char *p;
1305 char utf8[10];
1306 fz_stext_char *ch;
1307 size_t size = 0, cap = 80;
1309 p = malloc (cap + 1);
1310 if (!p) return NULL;
1312 for (ch = span->text; ch < span->text + span->len; ++ch) {
1313 int n = fz_runetochar (utf8, ch->c);
1314 if (size + n > cap) {
1315 cap *= 2;
1316 p = realloc (p, cap + 1);
1317 if (!p) return NULL;
1320 memcpy (p + size, utf8, n);
1321 size += n;
1323 p[size] = 0;
1324 return p;
1327 static int matchspan (regex_t *re, fz_stext_span *span,
1328 int stop, int pageno, double start)
1330 int ret;
1331 char *p;
1332 regmatch_t rm;
1333 int a, b, c;
1334 fz_rect sb, eb;
1335 fz_point p1, p2, p3, p4;
1337 p = strofspan (span);
1338 if (!p) return -1;
1340 ret = regexec (re, p, 1, &rm, 0);
1341 if (ret) {
1342 free (p);
1343 if (ret != REG_NOMATCH) {
1344 size_t size;
1345 char errbuf[80];
1346 size = regerror (ret, re, errbuf, sizeof (errbuf));
1347 printd ("msg regexec error `%.*s'",
1348 (int) size, errbuf);
1349 return -1;
1351 return 0;
1353 else {
1354 int l = span->len;
1356 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1357 c += fz_runelen (span->text[a].c);
1359 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1360 c += fz_runelen (span->text[b].c);
1363 if (fz_runelen (span->text[b].c) > 1) {
1364 b = fz_maxi (0, b-1);
1367 fz_stext_char_bbox (state.ctx, &sb, span, a);
1368 fz_stext_char_bbox (state.ctx, &eb, span, b);
1370 p1.x = sb.x0;
1371 p1.y = sb.y0;
1372 p2.x = eb.x1;
1373 p2.y = sb.y0;
1374 p3.x = eb.x1;
1375 p3.y = eb.y1;
1376 p4.x = sb.x0;
1377 p4.y = eb.y1;
1379 if (!stop) {
1380 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1381 pageno, 1,
1382 p1.x, p1.y,
1383 p2.x, p2.y,
1384 p3.x, p3.y,
1385 p4.x, p4.y);
1387 printd ("progress 1 found at %d `%.*s' in %f sec",
1388 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1389 now () - start);
1391 else {
1392 printd ("match %d %d %f %f %f %f %f %f %f %f",
1393 pageno, 2,
1394 p1.x, p1.y,
1395 p2.x, p2.y,
1396 p3.x, p3.y,
1397 p4.x, p4.y);
1399 free (p);
1400 return 1;
1404 static int compareblocks (const void *l, const void *r)
1406 fz_stext_block const *ls = l;
1407 fz_stext_block const *rs = r;
1408 return ls->bbox.y0 - rs->bbox.y0;
1411 /* wishful thinking function */
1412 static void search (regex_t *re, int pageno, int y, int forward)
1414 int j;
1415 fz_device *tdev;
1416 fz_stext_page *text;
1417 fz_stext_sheet *sheet;
1418 struct pagedim *pdim;
1419 int stop = 0, niters = 0;
1420 double start, end;
1421 fz_page *page;
1423 start = now ();
1424 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1425 if (niters++ == 5) {
1426 niters = 0;
1427 if (hasdata ()) {
1428 printd ("progress 1 attention requested aborting search at %d",
1429 pageno);
1430 stop = 1;
1432 else {
1433 printd ("progress %f searching in page %d",
1434 (double) (pageno + 1) / state.pagecount,
1435 pageno);
1438 pdim = pdimofpageno (pageno);
1439 sheet = fz_new_stext_sheet (state.ctx);
1440 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1441 tdev = fz_new_stext_device (state.ctx, sheet, text, 0);
1443 page = fz_load_page (state.ctx, state.doc, pageno);
1445 fz_matrix ctm = pagectm1 (page, pdim);
1446 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1449 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1450 fz_close_device (state.ctx, tdev);
1451 fz_drop_device (state.ctx, tdev);
1453 for (j = 0; j < text->len; ++j) {
1454 int k;
1455 fz_page_block *pb;
1456 fz_stext_block *block;
1458 pb = &text->blocks[forward ? j : text->len - 1 - j];
1459 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1460 block = pb->u.text;
1462 for (k = 0; k < block->len; ++k) {
1463 fz_stext_line *line;
1464 fz_stext_span *span;
1466 if (forward) {
1467 line = &block->lines[k];
1468 if (line->bbox.y0 < y + 1) continue;
1470 else {
1471 line = &block->lines[block->len - 1 - k];
1472 if (line->bbox.y0 > y - 1) continue;
1475 for (span = line->first_span; span; span = span->next) {
1476 switch (matchspan (re, span, stop, pageno, start)) {
1477 case 0: break;
1478 case 1: stop = 1; break;
1479 case -1: stop = 1; goto endloop;
1484 if (forward) {
1485 pageno += 1;
1486 y = 0;
1488 else {
1489 pageno -= 1;
1490 y = INT_MAX;
1492 endloop:
1493 fz_drop_stext_page (state.ctx, text);
1494 fz_drop_stext_sheet (state.ctx, sheet);
1495 fz_drop_page (state.ctx, page);
1497 end = now ();
1498 if (!stop) {
1499 printd ("progress 1 no matches %f sec", end - start);
1501 printd ("clearrects");
1504 static void set_tex_params (int colorspace)
1506 union {
1507 unsigned char b;
1508 unsigned int s;
1509 } endianness = {1};
1511 switch (colorspace) {
1512 case 0:
1513 state.texiform = GL_RGBA8;
1514 state.texform = GL_RGBA;
1515 state.texty = GL_UNSIGNED_BYTE;
1516 state.colorspace = fz_device_rgb (state.ctx);
1517 break;
1518 case 1:
1519 state.texiform = GL_RGBA8;
1520 state.texform = GL_BGRA;
1521 state.texty = endianness.s > 1
1522 ? GL_UNSIGNED_INT_8_8_8_8
1523 : GL_UNSIGNED_INT_8_8_8_8_REV;
1524 state.colorspace = fz_device_bgr (state.ctx);
1525 break;
1526 case 2:
1527 state.texiform = GL_LUMINANCE_ALPHA;
1528 state.texform = GL_LUMINANCE_ALPHA;
1529 state.texty = GL_UNSIGNED_BYTE;
1530 state.colorspace = fz_device_gray (state.ctx);
1531 break;
1532 default:
1533 errx (1, "invalid colorspce %d", colorspace);
1537 static void realloctexts (int texcount)
1539 size_t size;
1541 if (texcount == state.texcount) return;
1543 if (texcount < state.texcount) {
1544 glDeleteTextures (state.texcount - texcount,
1545 state.texids + texcount);
1548 size = texcount * sizeof (*state.texids);
1549 state.texids = realloc (state.texids, size);
1550 if (!state.texids) {
1551 err (1, "realloc texids %" FMT_s, size);
1554 size = texcount * sizeof (*state.texowners);
1555 state.texowners = realloc (state.texowners, size);
1556 if (!state.texowners) {
1557 err (1, "realloc texowners %" FMT_s, size);
1559 if (texcount > state.texcount) {
1560 glGenTextures (texcount - state.texcount,
1561 state.texids + state.texcount);
1562 for (int i = state.texcount; i < texcount; ++i) {
1563 state.texowners[i].w = -1;
1564 state.texowners[i].slice = NULL;
1567 state.texcount = texcount;
1568 state.texindex = 0;
1571 static char *mbtoutf8 (char *s)
1573 char *p, *r;
1574 wchar_t *tmp;
1575 size_t i, ret, len;
1577 if (state.utf8cs) {
1578 return s;
1581 len = mbstowcs (NULL, s, strlen (s));
1582 if (len == 0) {
1583 return s;
1585 else {
1586 if (len == (size_t) -1) {
1587 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1588 return s;
1592 tmp = calloc (len, sizeof (wchar_t));
1593 if (!tmp) {
1594 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1595 len, sizeof (wchar_t), errno, strerror (errno));
1596 return s;
1599 ret = mbstowcs (tmp, s, len);
1600 if (ret == (size_t) -1) {
1601 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1602 len, errno, strerror (errno));
1603 free (tmp);
1604 return s;
1607 len = 0;
1608 for (i = 0; i < ret; ++i) {
1609 len += fz_runelen (tmp[i]);
1612 p = r = malloc (len + 1);
1613 if (!r) {
1614 printd ("emsg mbtoutf8: malloc(%zu)", len);
1615 free (tmp);
1616 return s;
1619 for (i = 0; i < ret; ++i) {
1620 p += fz_runetochar (p, tmp[i]);
1622 *p = 0;
1623 free (tmp);
1624 return r;
1627 CAMLprim value ml_mbtoutf8 (value s_v)
1629 CAMLparam1 (s_v);
1630 CAMLlocal1 (ret_v);
1631 char *s, *r;
1633 s = String_val (s_v);
1634 r = mbtoutf8 (s);
1635 if (r == s) {
1636 ret_v = s_v;
1638 else {
1639 ret_v = caml_copy_string (r);
1640 free (r);
1642 CAMLreturn (ret_v);
1645 static void * mainloop (void UNUSED_ATTR *unused)
1647 char *p = NULL;
1648 int len, ret, oldlen = 0;
1650 fz_var (p);
1651 fz_var (oldlen);
1652 for (;;) {
1653 len = readlen (state.csock);
1654 if (len == 0) {
1655 errx (1, "readlen returned 0");
1658 if (oldlen < len + 1) {
1659 p = realloc (p, len + 1);
1660 if (!p) {
1661 err (1, "realloc %d failed", len + 1);
1663 oldlen = len + 1;
1665 readdata (state.csock, p, len);
1666 p[len] = 0;
1668 if (!strncmp ("open", p, 4)) {
1669 int wthack, off, usedoccss, ok = 0;
1670 char *password;
1671 char *filename;
1672 char *utf8filename;
1673 size_t filenamelen;
1675 fz_var (ok);
1676 ret = sscanf (p + 5, " %d %d %d %n",
1677 &wthack, &state.cxack, &usedoccss, &off);
1678 if (ret != 3) {
1679 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1682 filename = p + 5 + off;
1683 filenamelen = strlen (filename);
1684 password = filename + filenamelen + 1;
1686 if (password[strlen (password) + 1]) {
1687 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1690 lock ("open");
1691 fz_set_use_document_css (state.ctx, usedoccss);
1692 fz_try (state.ctx) {
1693 ok = openxref (filename, password);
1695 fz_catch (state.ctx) {
1696 utf8filename = mbtoutf8 (filename);
1697 printd ("msg Could not open %s", utf8filename);
1699 if (ok) {
1700 pdfinfo ();
1701 initpdims (wthack);
1703 unlock ("open");
1705 if (ok) {
1706 if (!wthack) {
1707 utf8filename = mbtoutf8 (filename);
1708 printd ("msg Opened %s (press h/F1 to get help)",
1709 utf8filename);
1710 if (utf8filename != filename) {
1711 free (utf8filename);
1714 state.needoutline = 1;
1717 else if (!strncmp ("cs", p, 2)) {
1718 int i, colorspace;
1720 ret = sscanf (p + 2, " %d", &colorspace);
1721 if (ret != 1) {
1722 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1724 lock ("cs");
1725 set_tex_params (colorspace);
1726 for (i = 0; i < state.texcount; ++i) {
1727 state.texowners[i].w = -1;
1728 state.texowners[i].slice = NULL;
1730 unlock ("cs");
1732 else if (!strncmp ("freepage", p, 8)) {
1733 void *ptr;
1735 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1736 if (ret != 1) {
1737 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1739 freepage (ptr);
1741 else if (!strncmp ("freetile", p, 8)) {
1742 void *ptr;
1744 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1745 if (ret != 1) {
1746 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1748 freetile (ptr);
1750 else if (!strncmp ("search", p, 6)) {
1751 int icase, pageno, y, len2, forward;
1752 char *pattern;
1753 regex_t re;
1755 ret = sscanf (p + 6, " %d %d %d %d,%n",
1756 &icase, &pageno, &y, &forward, &len2);
1757 if (ret != 4) {
1758 errx (1, "malformed search `%s' ret=%d", p, ret);
1761 pattern = p + 6 + len2;
1762 ret = regcomp (&re, pattern,
1763 REG_EXTENDED | (icase ? REG_ICASE : 0));
1764 if (ret) {
1765 char errbuf[80];
1766 size_t size;
1768 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1769 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1771 else {
1772 search (&re, pageno, y, forward);
1773 regfree (&re);
1776 else if (!strncmp ("geometry", p, 8)) {
1777 int w, h, fitmodel;
1779 printd ("clear");
1780 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1781 if (ret != 3) {
1782 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1785 lock ("geometry");
1786 state.h = h;
1787 if (w != state.w) {
1788 state.w = w;
1789 for (int i = 0; i < state.texcount; ++i) {
1790 state.texowners[i].slice = NULL;
1793 state.fitmodel = fitmodel;
1794 layout ();
1795 process_outline ();
1797 state.gen++;
1798 unlock ("geometry");
1799 printd ("continue %d", state.pagecount);
1801 else if (!strncmp ("reqlayout", p, 9)) {
1802 char *nameddest;
1803 int rotate, off, h;
1804 unsigned int fitmodel;
1805 pdf_document *pdf;
1807 printd ("clear");
1808 ret = sscanf (p + 9, " %d %u %d %n",
1809 &rotate, &fitmodel, &h, &off);
1810 if (ret != 3) {
1811 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1813 lock ("reqlayout");
1814 pdf = pdf_specifics (state.ctx, state.doc);
1815 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1816 state.gen += 1;
1818 state.rotate = rotate;
1819 state.fitmodel = fitmodel;
1820 state.h = h;
1821 layout ();
1822 process_outline ();
1824 nameddest = p + 9 + off;
1825 if (pdf && nameddest && *nameddest) {
1826 fz_point xy;
1827 struct pagedim *pdim;
1828 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1829 &xy.x, &xy.y);
1830 pdim = pdimofpageno (pageno);
1831 fz_transform_point (&xy, &pdim->ctm);
1832 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1835 state.gen++;
1836 unlock ("reqlayout");
1837 printd ("continue %d", state.pagecount);
1839 else if (!strncmp ("page", p, 4)) {
1840 double a, b;
1841 struct page *page;
1842 int pageno, pindex;
1844 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1845 if (ret != 2) {
1846 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1849 lock ("page");
1850 a = now ();
1851 page = loadpage (pageno, pindex);
1852 b = now ();
1853 unlock ("page");
1855 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1857 else if (!strncmp ("tile", p, 4)) {
1858 int x, y, w, h;
1859 struct page *page;
1860 struct tile *tile;
1861 double a, b;
1862 void *data;
1864 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1865 SCN_ptr_cast (&page), &x, &y, &w, &h,
1866 SCN_ptr_cast (&data));
1867 if (ret != 6) {
1868 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1871 lock ("tile");
1872 a = now ();
1873 tile = rendertile (page, x, y, w, h, data);
1874 b = now ();
1875 unlock ("tile");
1877 printd ("tile %d %d %" FMT_ptr " %u %f",
1878 x, y,
1879 FMT_ptr_cast (tile),
1880 tile->w * tile->h * tile->pixmap->n,
1881 b - a);
1883 else if (!strncmp ("trimset", p, 7)) {
1884 fz_irect fuzz;
1885 int trimmargins;
1887 ret = sscanf (p + 7, " %d %d %d %d %d",
1888 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1889 if (ret != 5) {
1890 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1892 lock ("trimset");
1893 state.trimmargins = trimmargins;
1894 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1895 state.trimanew = 1;
1896 state.trimfuzz = fuzz;
1898 unlock ("trimset");
1900 else if (!strncmp ("settrim", p, 7)) {
1901 fz_irect fuzz;
1902 int trimmargins;
1904 ret = sscanf (p + 7, " %d %d %d %d %d",
1905 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1906 if (ret != 5) {
1907 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1909 printd ("clear");
1910 lock ("settrim");
1911 state.trimmargins = trimmargins;
1912 state.needoutline = 1;
1913 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1914 state.trimanew = 1;
1915 state.trimfuzz = fuzz;
1917 state.pagedimcount = 0;
1918 free (state.pagedims);
1919 state.pagedims = NULL;
1920 initpdims (0);
1921 layout ();
1922 process_outline ();
1923 unlock ("settrim");
1924 printd ("continue %d", state.pagecount);
1926 else if (!strncmp ("sliceh", p, 6)) {
1927 int h;
1929 ret = sscanf (p + 6, " %d", &h);
1930 if (ret != 1) {
1931 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1933 if (h != state.sliceheight) {
1934 state.sliceheight = h;
1935 for (int i = 0; i < state.texcount; ++i) {
1936 state.texowners[i].w = -1;
1937 state.texowners[i].h = -1;
1938 state.texowners[i].slice = NULL;
1942 else if (!strncmp ("interrupt", p, 9)) {
1943 printd ("vmsg interrupted");
1945 else {
1946 errx (1, "unknown command %.*s", len, p);
1949 return 0;
1952 CAMLprim value ml_isexternallink (value uri_v)
1954 CAMLparam1 (uri_v);
1955 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1956 CAMLreturn (Val_bool (ext));
1959 CAMLprim value ml_uritolocation (value uri_v)
1961 CAMLparam1 (uri_v);
1962 CAMLlocal1 (ret_v);
1963 int pageno;
1964 fz_point xy;
1965 struct pagedim *pdim;
1967 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1968 &xy.x, &xy.y);
1969 pdim = pdimofpageno (pageno);
1970 fz_transform_point (&xy, &pdim->ctm);
1971 ret_v = caml_alloc_tuple (3);
1972 Field (ret_v, 0) = Val_int (pageno);
1973 Field (ret_v, 1) = caml_copy_double (xy.x);
1974 Field (ret_v, 2) = caml_copy_double (xy.y);
1975 CAMLreturn (ret_v);
1978 CAMLprim value ml_realloctexts (value texcount_v)
1980 CAMLparam1 (texcount_v);
1981 int ok;
1983 if (trylock (__func__)) {
1984 ok = 0;
1985 goto done;
1987 realloctexts (Int_val (texcount_v));
1988 ok = 1;
1989 unlock (__func__);
1991 done:
1992 CAMLreturn (Val_bool (ok));
1995 static void recti (int x0, int y0, int x1, int y1)
1997 GLfloat *v = state.vertices;
1999 glVertexPointer (2, GL_FLOAT, 0, v);
2000 v[0] = x0; v[1] = y0;
2001 v[2] = x1; v[3] = y0;
2002 v[4] = x0; v[5] = y1;
2003 v[6] = x1; v[7] = y1;
2004 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2007 static void showsel (struct page *page, int ox, int oy)
2009 int seen = 0;
2010 fz_irect bbox;
2011 fz_rect rect;
2012 fz_stext_line *line;
2013 fz_page_block *pageb;
2014 fz_stext_block *block;
2015 struct mark first, last;
2016 unsigned char selcolor[] = {15,15,15,140};
2018 first = page->fmark;
2019 last = page->lmark;
2021 if (!first.span || !last.span) return;
2023 glEnable (GL_BLEND);
2024 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2025 glColor4ubv (selcolor);
2027 ox += state.pagedims[page->pdimno].bounds.x0;
2028 oy += state.pagedims[page->pdimno].bounds.y0;
2029 for (pageb = page->text->blocks;
2030 pageb < page->text->blocks + page->text->len;
2031 ++pageb) {
2032 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2033 block = pageb->u.text;
2035 for (line = block->lines;
2036 line < block->lines + block->len;
2037 ++line) {
2038 fz_stext_span *span;
2039 rect = fz_empty_rect;
2041 for (span = line->first_span; span; span = span->next) {
2042 int i, j, k;
2043 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2045 j = 0;
2046 k = span->len - 1;
2048 if (span == page->fmark.span && span == page->lmark.span) {
2049 seen = 1;
2050 j = fz_mini (first.i, last.i);
2051 k = fz_maxi (first.i, last.i);
2053 else {
2054 if (span == first.span) {
2055 seen = 1;
2056 j = first.i;
2058 else if (span == last.span) {
2059 seen = 1;
2060 k = last.i;
2064 if (seen) {
2065 for (i = j; i <= k; ++i) {
2066 fz_rect bbox1;
2067 fz_union_rect (&rect,
2068 fz_stext_char_bbox (state.ctx, &bbox1,
2069 span, i));
2071 fz_round_rect (&bbox, &rect);
2072 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2073 bbox.x0,
2074 bbox.y0,
2075 bbox.x1,
2076 bbox.y1,
2077 oy, ox);
2079 recti (bbox.x0 + ox, bbox.y0 + oy,
2080 bbox.x1 + ox, bbox.y1 + oy);
2081 if (span == last.span) {
2082 goto done;
2084 rect = fz_empty_rect;
2089 done:
2090 glDisable (GL_BLEND);
2093 #include "glfont.c"
2095 static void stipplerect (fz_matrix *m,
2096 fz_point *p1,
2097 fz_point *p2,
2098 fz_point *p3,
2099 fz_point *p4,
2100 GLfloat *texcoords,
2101 GLfloat *vertices)
2103 fz_transform_point (p1, m);
2104 fz_transform_point (p2, m);
2105 fz_transform_point (p3, m);
2106 fz_transform_point (p4, m);
2108 float w, h, s, t;
2110 w = p2->x - p1->x;
2111 h = p2->y - p1->y;
2112 t = hypotf (w, h) * .25f;
2114 w = p3->x - p2->x;
2115 h = p3->y - p2->y;
2116 s = hypotf (w, h) * .25f;
2118 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2119 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2121 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2122 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2124 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2125 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2127 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2128 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2130 glDrawArrays (GL_LINES, 0, 8);
2133 static void solidrect (fz_matrix *m,
2134 fz_point *p1,
2135 fz_point *p2,
2136 fz_point *p3,
2137 fz_point *p4,
2138 GLfloat *vertices)
2140 fz_transform_point (p1, m);
2141 fz_transform_point (p2, m);
2142 fz_transform_point (p3, m);
2143 fz_transform_point (p4, m);
2144 vertices[0] = p1->x; vertices[1] = p1->y;
2145 vertices[2] = p2->x; vertices[3] = p2->y;
2147 vertices[4] = p3->x; vertices[5] = p3->y;
2148 vertices[6] = p4->x; vertices[7] = p4->y;
2149 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2152 static void highlightlinks (struct page *page, int xoff, int yoff)
2154 fz_matrix ctm, tm, pm;
2155 fz_link *link, *links;
2156 GLfloat *texcoords = state.texcoords;
2157 GLfloat *vertices = state.vertices;
2159 links = fz_load_links (state.ctx, page->fzpage);
2161 glEnable (GL_TEXTURE_1D);
2162 glEnable (GL_BLEND);
2163 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2164 glBindTexture (GL_TEXTURE_1D, state.stid);
2166 xoff -= state.pagedims[page->pdimno].bounds.x0;
2167 yoff -= state.pagedims[page->pdimno].bounds.y0;
2168 fz_translate (&tm, xoff, yoff);
2169 pm = pagectm (page);
2170 fz_concat (&ctm, &pm, &tm);
2172 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2173 glVertexPointer (2, GL_FLOAT, 0, vertices);
2175 for (link = links; link; link = link->next) {
2176 fz_point p1, p2, p3, p4;
2178 p1.x = link->rect.x0;
2179 p1.y = link->rect.y0;
2181 p2.x = link->rect.x1;
2182 p2.y = link->rect.y0;
2184 p3.x = link->rect.x1;
2185 p3.y = link->rect.y1;
2187 p4.x = link->rect.x0;
2188 p4.y = link->rect.y1;
2190 /* TODO: different colours for different schemes */
2191 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2192 else glColor3ub (255, 0, 0);
2194 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2197 for (int i = 0; i < page->annotcount; ++i) {
2198 fz_point p1, p2, p3, p4;
2199 struct annot *annot = &page->annots[i];
2201 p1.x = annot->bbox.x0;
2202 p1.y = annot->bbox.y0;
2204 p2.x = annot->bbox.x1;
2205 p2.y = annot->bbox.y0;
2207 p3.x = annot->bbox.x1;
2208 p3.y = annot->bbox.y1;
2210 p4.x = annot->bbox.x0;
2211 p4.y = annot->bbox.y1;
2213 glColor3ub (0, 0, 128);
2214 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2217 glDisable (GL_BLEND);
2218 glDisable (GL_TEXTURE_1D);
2221 static int compareslinks (const void *l, const void *r)
2223 struct slink const *ls = l;
2224 struct slink const *rs = r;
2225 if (ls->bbox.y0 == rs->bbox.y0) {
2226 return rs->bbox.x0 - rs->bbox.x0;
2228 return ls->bbox.y0 - rs->bbox.y0;
2231 static void droptext (struct page *page)
2233 if (page->text) {
2234 fz_drop_stext_page (state.ctx, page->text);
2235 page->fmark.i = -1;
2236 page->lmark.i = -1;
2237 page->fmark.span = NULL;
2238 page->lmark.span = NULL;
2239 page->text = NULL;
2241 if (page->sheet) {
2242 fz_drop_stext_sheet (state.ctx, page->sheet);
2243 page->sheet = NULL;
2247 static void dropannots (struct page *page)
2249 if (page->annots) {
2250 free (page->annots);
2251 page->annots = NULL;
2252 page->annotcount = 0;
2256 static void ensureannots (struct page *page)
2258 int i, count = 0;
2259 size_t annotsize = sizeof (*page->annots);
2260 fz_annot *annot;
2262 if (state.gen != page->agen) {
2263 dropannots (page);
2264 page->agen = state.gen;
2266 if (page->annots) return;
2268 for (annot = fz_first_annot (state.ctx, page->fzpage);
2269 annot;
2270 annot = fz_next_annot (state.ctx, annot)) {
2271 count++;
2274 if (count > 0) {
2275 page->annotcount = count;
2276 page->annots = calloc (count, annotsize);
2277 if (!page->annots) {
2278 err (1, "calloc annots %d", count);
2281 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2282 annot;
2283 annot = fz_next_annot (state.ctx, annot), i++) {
2284 fz_rect rect;
2286 fz_bound_annot (state.ctx, annot, &rect);
2287 page->annots[i].annot = annot;
2288 fz_round_rect (&page->annots[i].bbox, &rect);
2293 static void dropslinks (struct page *page)
2295 if (page->slinks) {
2296 free (page->slinks);
2297 page->slinks = NULL;
2298 page->slinkcount = 0;
2302 static void ensureslinks (struct page *page)
2304 fz_matrix ctm;
2305 int i, count;
2306 size_t slinksize = sizeof (*page->slinks);
2307 fz_link *link, *links;
2309 ensureannots (page);
2310 if (state.gen != page->sgen) {
2311 dropslinks (page);
2312 page->sgen = state.gen;
2314 if (page->slinks) return;
2316 links = fz_load_links (state.ctx, page->fzpage);
2317 ctm = pagectm (page);
2319 count = page->annotcount;
2320 for (link = links; link; link = link->next) {
2321 count++;
2323 if (count > 0) {
2324 int j;
2326 page->slinkcount = count;
2327 page->slinks = calloc (count, slinksize);
2328 if (!page->slinks) {
2329 err (1, "calloc slinks %d", count);
2332 for (i = 0, link = links; link; ++i, link = link->next) {
2333 fz_rect rect;
2335 rect = link->rect;
2336 fz_transform_rect (&rect, &ctm);
2337 page->slinks[i].tag = SLINK;
2338 page->slinks[i].u.link = link;
2339 fz_round_rect (&page->slinks[i].bbox, &rect);
2341 for (j = 0; j < page->annotcount; ++j, ++i) {
2342 fz_rect rect;
2343 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2344 fz_transform_rect (&rect, &ctm);
2345 fz_round_rect (&page->slinks[i].bbox, &rect);
2347 page->slinks[i].tag = SANNOT;
2348 page->slinks[i].u.annot = page->annots[j].annot;
2350 qsort (page->slinks, count, slinksize, compareslinks);
2354 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2355 static void fmt_linkn (char *s, unsigned int u)
2357 unsigned int len; unsigned int q;
2358 unsigned int zma = 'z' - 'a' + 1;
2359 len = 1; q = u;
2360 while (q > zma - 1) { ++len; q /= zma; }
2361 if (s) {
2362 s += len;
2363 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2364 /* handles u == 0 */
2366 s[len] = 0;
2369 static void highlightslinks (struct page *page, int xoff, int yoff,
2370 int noff, char *targ, int tlen, int hfsize)
2372 char buf[40];
2373 struct slink *slink;
2374 double x0, y0, x1, y1, w;
2376 ensureslinks (page);
2377 glColor3ub (0xc3, 0xb0, 0x91);
2378 for (int i = 0; i < page->slinkcount; ++i) {
2379 fmt_linkn (buf, i + noff);
2380 if (!tlen || !strncmp (targ, buf, tlen)) {
2381 slink = &page->slinks[i];
2383 x0 = slink->bbox.x0 + xoff - 5;
2384 y1 = slink->bbox.y0 + yoff - 5;
2385 y0 = y1 + 10 + hfsize;
2386 w = measure_string (state.face, hfsize, buf);
2387 x1 = x0 + w + 10;
2388 recti (x0, y0, x1, y1);
2392 glEnable (GL_BLEND);
2393 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2394 glEnable (GL_TEXTURE_2D);
2395 glColor3ub (0, 0, 0);
2396 for (int i = 0; i < page->slinkcount; ++i) {
2397 fmt_linkn (buf, i + noff);
2398 if (!tlen || !strncmp (targ, buf, tlen)) {
2399 slink = &page->slinks[i];
2401 x0 = slink->bbox.x0 + xoff;
2402 y0 = slink->bbox.y0 + yoff + hfsize;
2403 draw_string (state.face, hfsize, x0, y0, buf);
2406 glDisable (GL_TEXTURE_2D);
2407 glDisable (GL_BLEND);
2410 static void uploadslice (struct tile *tile, struct slice *slice)
2412 int offset;
2413 struct slice *slice1;
2414 unsigned char *texdata;
2416 offset = 0;
2417 for (slice1 = tile->slices; slice != slice1; slice1++) {
2418 offset += slice1->h * tile->w * tile->pixmap->n;
2420 if (slice->texindex != -1 && slice->texindex < state.texcount
2421 && state.texowners[slice->texindex].slice == slice) {
2422 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2424 else {
2425 int subimage = 0;
2426 int texindex = state.texindex++ % state.texcount;
2428 if (state.texowners[texindex].w == tile->w) {
2429 if (state.texowners[texindex].h >= slice->h) {
2430 subimage = 1;
2432 else {
2433 state.texowners[texindex].h = slice->h;
2436 else {
2437 state.texowners[texindex].h = slice->h;
2440 state.texowners[texindex].w = tile->w;
2441 state.texowners[texindex].slice = slice;
2442 slice->texindex = texindex;
2444 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2445 #if TEXT_TYPE == GL_TEXTURE_2D
2446 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2447 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2448 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2449 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2450 #endif
2451 if (tile->pbo) {
2452 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2453 texdata = 0;
2455 else {
2456 texdata = tile->pixmap->samples;
2458 if (subimage) {
2459 glTexSubImage2D (TEXT_TYPE,
2463 tile->w,
2464 slice->h,
2465 state.texform,
2466 state.texty,
2467 texdata+offset
2470 else {
2471 glTexImage2D (TEXT_TYPE,
2473 state.texiform,
2474 tile->w,
2475 slice->h,
2477 state.texform,
2478 state.texty,
2479 texdata+offset
2482 if (tile->pbo) {
2483 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2488 CAMLprim value ml_begintiles (value unit_v)
2490 CAMLparam1 (unit_v);
2491 glEnable (TEXT_TYPE);
2492 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2493 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2494 CAMLreturn (unit_v);
2497 CAMLprim value ml_endtiles (value unit_v)
2499 CAMLparam1 (unit_v);
2500 glDisable (TEXT_TYPE);
2501 CAMLreturn (unit_v);
2504 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2506 CAMLparam2 (args_v, ptr_v);
2507 int dispx = Int_val (Field (args_v, 0));
2508 int dispy = Int_val (Field (args_v, 1));
2509 int dispw = Int_val (Field (args_v, 2));
2510 int disph = Int_val (Field (args_v, 3));
2511 int tilex = Int_val (Field (args_v, 4));
2512 int tiley = Int_val (Field (args_v, 5));
2513 char *s = String_val (ptr_v);
2514 struct tile *tile = parse_pointer (__func__, s);
2515 int slicey, firstslice;
2516 struct slice *slice;
2517 GLfloat *texcoords = state.texcoords;
2518 GLfloat *vertices = state.vertices;
2520 firstslice = tiley / tile->sliceheight;
2521 slice = &tile->slices[firstslice];
2522 slicey = tiley % tile->sliceheight;
2524 while (disph > 0) {
2525 int dh;
2527 dh = slice->h - slicey;
2528 dh = fz_mini (disph, dh);
2529 uploadslice (tile, slice);
2531 texcoords[0] = tilex; texcoords[1] = slicey;
2532 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2533 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2534 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2536 vertices[0] = dispx; vertices[1] = dispy;
2537 vertices[2] = dispx+dispw; vertices[3] = dispy;
2538 vertices[4] = dispx; vertices[5] = dispy+dh;
2539 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2541 #if TEXT_TYPE == GL_TEXTURE_2D
2542 for (int i = 0; i < 8; ++i) {
2543 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2545 #endif
2547 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2548 dispy += dh;
2549 disph -= dh;
2550 slice++;
2551 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2552 slicey = 0;
2554 CAMLreturn0;
2557 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2559 fz_matrix ctm, tm, pm;
2560 fz_point p1, p2, p3, p4;
2561 GLfloat *vertices = state.vertices;
2562 double *v = (double *) rects_v;
2564 xoff -= state.pagedims[page->pdimno].bounds.x0;
2565 yoff -= state.pagedims[page->pdimno].bounds.y0;
2566 fz_translate (&tm, xoff, yoff);
2567 pm = pagectm (page);
2568 fz_concat (&ctm, &pm, &tm);
2570 glEnable (GL_BLEND);
2571 glVertexPointer (2, GL_FLOAT, 0, vertices);
2573 glColor4dv (v);
2574 p1.x = v[4];
2575 p1.y = v[5];
2577 p2.x = v[6];
2578 p2.y = v[5];
2580 p3.x = v[6];
2581 p3.y = v[7];
2583 p4.x = v[4];
2584 p4.y = v[7];
2585 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2586 glDisable (GL_BLEND);
2589 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2590 value xoff_v, value yoff_v,
2591 value li_v)
2593 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2594 int xoff = Int_val (xoff_v);
2595 int yoff = Int_val (yoff_v);
2596 int noff = Int_val (Field (li_v, 0));
2597 char *targ = String_val (Field (li_v, 1));
2598 int tlen = caml_string_length (Field (li_v, 1));
2599 int hfsize = Int_val (Field (li_v, 2));
2600 char *s = String_val (ptr_v);
2601 int hlmask = Int_val (hlinks_v);
2602 struct page *page = parse_pointer (__func__, s);
2604 if (!page->fzpage) {
2605 /* deal with loadpage failed pages */
2606 goto done;
2609 if (trylock (__func__)) {
2610 noff = -1;
2611 goto done;
2614 ensureannots (page);
2615 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2616 if (hlmask & 2) {
2617 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2618 noff = page->slinkcount;
2620 if (page->tgen == state.gen) {
2621 showsel (page, xoff, yoff);
2623 unlock (__func__);
2625 done:
2626 CAMLreturn (Val_int (noff));
2629 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2630 value rects_v)
2632 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2633 int xoff = Int_val (xoff_v);
2634 int yoff = Int_val (yoff_v);
2635 char *s = String_val (ptr_v);
2636 struct page *page = parse_pointer (__func__, s);
2638 drawprect (page, xoff, yoff, rects_v);
2639 CAMLreturn0;
2642 static struct annot *getannot (struct page *page, int x, int y)
2644 fz_point p;
2645 fz_matrix ctm;
2646 const fz_matrix *tctm;
2647 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2649 if (!page->annots) return NULL;
2651 if (pdf) {
2652 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2653 tctm = &state.pagedims[page->pdimno].tctm;
2655 else {
2656 tctm = &fz_identity;
2659 p.x = x;
2660 p.y = y;
2662 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2663 fz_invert_matrix (&ctm, &ctm);
2664 fz_transform_point (&p, &ctm);
2666 if (pdf) {
2667 for (int i = 0; i < page->annotcount; ++i) {
2668 struct annot *a = &page->annots[i];
2669 fz_rect rect;
2671 fz_bound_annot (state.ctx, a->annot, &rect);
2672 if (p.x >= rect.x0 && p.x <= rect.x1) {
2673 if (p.y >= rect.y0 && p.y <= rect.y1)
2674 return a;
2678 return NULL;
2681 static fz_link *getlink (struct page *page, int x, int y)
2683 fz_point p;
2684 fz_matrix ctm;
2685 fz_link *link, *links;
2687 links = fz_load_links (state.ctx, page->fzpage);
2689 p.x = x;
2690 p.y = y;
2692 ctm = pagectm (page);
2693 fz_invert_matrix (&ctm, &ctm);
2694 fz_transform_point (&p, &ctm);
2696 for (link = links; link; link = link->next) {
2697 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2698 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2699 return link;
2703 return NULL;
2706 static void ensuretext (struct page *page)
2708 if (state.gen != page->tgen) {
2709 droptext (page);
2710 page->tgen = state.gen;
2712 if (!page->text) {
2713 fz_matrix ctm;
2714 fz_device *tdev;
2716 page->text = fz_new_stext_page (state.ctx,
2717 &state.pagedims[page->pdimno].mediabox);
2718 page->sheet = fz_new_stext_sheet (state.ctx);
2719 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2720 ctm = pagectm (page);
2721 fz_run_display_list (state.ctx, page->dlist,
2722 tdev, &ctm, &fz_infinite_rect, NULL);
2723 qsort (page->text->blocks, page->text->len,
2724 sizeof (*page->text->blocks), compareblocks);
2725 fz_close_device (state.ctx, tdev);
2726 fz_drop_device (state.ctx, tdev);
2730 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2732 CAMLparam2 (start_page_v, dir_v);
2733 CAMLlocal1 (ret_v);
2734 int i, dir = Int_val (dir_v);
2735 int start_page = Int_val (start_page_v);
2736 int end_page = dir > 0 ? state.pagecount : -1;
2737 pdf_document *pdf;
2739 fz_var (end_page);
2740 ret_v = Val_int (0);
2741 lock (__func__);
2742 pdf = pdf_specifics (state.ctx, state.doc);
2743 for (i = start_page + dir; i != end_page; i += dir) {
2744 int found;
2746 fz_var (found);
2747 if (pdf) {
2748 pdf_page *page = NULL;
2750 fz_var (page);
2751 fz_try (state.ctx) {
2752 page = pdf_load_page (state.ctx, pdf, i);
2753 found = !!page->links || !!page->annots;
2755 fz_catch (state.ctx) {
2756 found = 0;
2758 if (page) {
2759 fz_drop_page (state.ctx, &page->super);
2762 else {
2763 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2764 found = !!fz_load_links (state.ctx, page);
2765 fz_drop_page (state.ctx, page);
2768 if (found) {
2769 ret_v = caml_alloc_small (1, 1);
2770 Field (ret_v, 0) = Val_int (i);
2771 goto unlock;
2774 unlock:
2775 unlock (__func__);
2776 CAMLreturn (ret_v);
2779 enum { dir_first, dir_last };
2780 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2782 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2784 CAMLparam2 (ptr_v, dir_v);
2785 CAMLlocal2 (ret_v, pos_v);
2786 struct page *page;
2787 int dirtag, i, slinkindex;
2788 struct slink *found = NULL ,*slink;
2789 char *s = String_val (ptr_v);
2791 page = parse_pointer (__func__, s);
2792 ret_v = Val_int (0);
2793 lock (__func__);
2794 ensureslinks (page);
2796 if (Is_block (dir_v)) {
2797 dirtag = Tag_val (dir_v);
2798 switch (dirtag) {
2799 case dir_first_visible:
2801 int x0, y0, dir, first_index, last_index;
2803 pos_v = Field (dir_v, 0);
2804 x0 = Int_val (Field (pos_v, 0));
2805 y0 = Int_val (Field (pos_v, 1));
2806 dir = Int_val (Field (pos_v, 2));
2808 if (dir >= 0) {
2809 dir = 1;
2810 first_index = 0;
2811 last_index = page->slinkcount;
2813 else {
2814 first_index = page->slinkcount - 1;
2815 last_index = -1;
2818 for (i = first_index; i != last_index; i += dir) {
2819 slink = &page->slinks[i];
2820 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2821 found = slink;
2822 break;
2826 break;
2828 case dir_left:
2829 slinkindex = Int_val (Field (dir_v, 0));
2830 found = &page->slinks[slinkindex];
2831 for (i = slinkindex - 1; i >= 0; --i) {
2832 slink = &page->slinks[i];
2833 if (slink->bbox.x0 < found->bbox.x0) {
2834 found = slink;
2835 break;
2838 break;
2840 case dir_right:
2841 slinkindex = Int_val (Field (dir_v, 0));
2842 found = &page->slinks[slinkindex];
2843 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2844 slink = &page->slinks[i];
2845 if (slink->bbox.x0 > found->bbox.x0) {
2846 found = slink;
2847 break;
2850 break;
2852 case dir_down:
2853 slinkindex = Int_val (Field (dir_v, 0));
2854 found = &page->slinks[slinkindex];
2855 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2856 slink = &page->slinks[i];
2857 if (slink->bbox.y0 >= found->bbox.y0) {
2858 found = slink;
2859 break;
2862 break;
2864 case dir_up:
2865 slinkindex = Int_val (Field (dir_v, 0));
2866 found = &page->slinks[slinkindex];
2867 for (i = slinkindex - 1; i >= 0; --i) {
2868 slink = &page->slinks[i];
2869 if (slink->bbox.y0 <= found->bbox.y0) {
2870 found = slink;
2871 break;
2874 break;
2877 else {
2878 dirtag = Int_val (dir_v);
2879 switch (dirtag) {
2880 case dir_first:
2881 found = page->slinks;
2882 break;
2884 case dir_last:
2885 if (page->slinks) {
2886 found = page->slinks + (page->slinkcount - 1);
2888 break;
2891 if (found) {
2892 ret_v = caml_alloc_small (2, 1);
2893 Field (ret_v, 0) = Val_int (found - page->slinks);
2896 unlock (__func__);
2897 CAMLreturn (ret_v);
2900 enum { uuri, utext, uannot };
2902 CAMLprim value ml_getlink (value ptr_v, value n_v)
2904 CAMLparam2 (ptr_v, n_v);
2905 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2906 fz_link *link;
2907 struct page *page;
2908 char *s = String_val (ptr_v);
2909 struct slink *slink;
2911 ret_v = Val_int (0);
2912 page = parse_pointer (__func__, s);
2914 lock (__func__);
2915 ensureslinks (page);
2916 slink = &page->slinks[Int_val (n_v)];
2917 if (slink->tag == SLINK) {
2918 link = slink->u.link;
2919 str_v = caml_copy_string (link->uri);
2920 ret_v = caml_alloc_small (1, uuri);
2921 Field (ret_v, 0) = str_v;
2923 else {
2924 ret_v = caml_alloc_small (1, uannot);
2925 tup_v = caml_alloc_tuple (2);
2926 Field (ret_v, 0) = tup_v;
2927 Field (tup_v, 0) = ptr_v;
2928 Field (tup_v, 1) = n_v;
2930 unlock (__func__);
2932 CAMLreturn (ret_v);
2935 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2937 CAMLparam2 (ptr_v, n_v);
2938 pdf_document *pdf;
2939 const char *contents = "";
2941 lock (__func__);
2942 pdf = pdf_specifics (state.ctx, state.doc);
2943 if (pdf) {
2944 char *s = String_val (ptr_v);
2945 struct page *page;
2946 struct slink *slink;
2948 page = parse_pointer (__func__, s);
2949 slink = &page->slinks[Int_val (n_v)];
2950 contents = pdf_annot_contents (state.ctx,
2951 (pdf_annot *) slink->u.annot);
2953 unlock (__func__);
2954 CAMLreturn (caml_copy_string (contents));
2957 CAMLprim value ml_getlinkcount (value ptr_v)
2959 CAMLparam1 (ptr_v);
2960 struct page *page;
2961 char *s = String_val (ptr_v);
2963 page = parse_pointer (__func__, s);
2964 CAMLreturn (Val_int (page->slinkcount));
2967 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2969 CAMLparam2 (ptr_v, n_v);
2970 CAMLlocal1 (ret_v);
2971 struct page *page;
2972 struct slink *slink;
2973 char *s = String_val (ptr_v);
2975 page = parse_pointer (__func__, s);
2976 ret_v = caml_alloc_tuple (4);
2977 lock (__func__);
2978 ensureslinks (page);
2980 slink = &page->slinks[Int_val (n_v)];
2981 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2982 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2983 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2984 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2985 unlock (__func__);
2986 CAMLreturn (ret_v);
2989 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2991 CAMLparam3 (ptr_v, x_v, y_v);
2992 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2993 fz_link *link;
2994 struct annot *annot;
2995 struct page *page;
2996 char *ptr = String_val (ptr_v);
2997 int x = Int_val (x_v), y = Int_val (y_v);
2998 struct pagedim *pdim;
3000 ret_v = Val_int (0);
3001 if (trylock (__func__)) {
3002 goto done;
3005 page = parse_pointer (__func__, ptr);
3006 pdim = &state.pagedims[page->pdimno];
3007 x += pdim->bounds.x0;
3008 y += pdim->bounds.y0;
3011 annot = getannot (page, x, y);
3012 if (annot) {
3013 int i, n = -1;
3015 ensureslinks (page);
3016 for (i = 0; i < page->slinkcount; ++i) {
3017 if (page->slinks[i].tag == SANNOT
3018 && page->slinks[i].u.annot == annot->annot) {
3019 n = i;
3020 break;
3023 ret_v = caml_alloc_small (1, uannot);
3024 tup_v = caml_alloc_tuple (2);
3025 Field (ret_v, 0) = tup_v;
3026 Field (tup_v, 0) = ptr_v;
3027 Field (tup_v, 1) = Val_int (n);
3028 goto unlock;
3032 link = getlink (page, x, y);
3033 if (link) {
3034 str_v = caml_copy_string (link->uri);
3035 ret_v = caml_alloc_small (1, uuri);
3036 Field (ret_v, 0) = str_v;
3038 else {
3039 fz_rect *b;
3040 fz_page_block *pageb;
3041 fz_stext_block *block;
3043 ensuretext (page);
3044 for (pageb = page->text->blocks;
3045 pageb < page->text->blocks + page->text->len;
3046 ++pageb) {
3047 fz_stext_line *line;
3048 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3049 block = pageb->u.text;
3051 b = &block->bbox;
3052 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3053 continue;
3055 for (line = block->lines;
3056 line < block->lines + block->len;
3057 ++line) {
3058 fz_stext_span *span;
3060 b = &line->bbox;
3061 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3062 continue;
3064 for (span = line->first_span; span; span = span->next) {
3065 int charnum;
3067 b = &span->bbox;
3068 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3069 continue;
3071 for (charnum = 0; charnum < span->len; ++charnum) {
3072 fz_rect bbox;
3073 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3074 b = &bbox;
3076 if (x >= b->x0 && x <= b->x1
3077 && y >= b->y0 && y <= b->y1) {
3078 fz_stext_style *style = span->text->style;
3079 const char *n2 =
3080 style->font
3081 ? fz_font_name (state.ctx, style->font)
3082 : "Span has no font name"
3084 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3085 style->font);
3086 if (face && face->family_name) {
3087 char *s;
3088 char *n1 = face->family_name;
3089 size_t l1 = strlen (n1);
3090 size_t l2 = strlen (n2);
3092 if (l1 != l2 || memcmp (n1, n2, l1)) {
3093 s = malloc (l1 + l2 + 2);
3094 if (s) {
3095 memcpy (s, n2, l2);
3096 s[l2] = '=';
3097 memcpy (s + l2 + 1, n1, l1 + 1);
3098 str_v = caml_copy_string (s);
3099 free (s);
3103 if (str_v == Val_unit) {
3104 str_v = caml_copy_string (n2);
3106 ret_v = caml_alloc_small (1, utext);
3107 Field (ret_v, 0) = str_v;
3108 goto unlock;
3115 unlock:
3116 unlock (__func__);
3118 done:
3119 CAMLreturn (ret_v);
3122 enum { mark_page, mark_block, mark_line, mark_word };
3124 static int uninteresting (int c)
3126 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3127 || ispunct (c);
3130 CAMLprim void ml_clearmark (value ptr_v)
3132 CAMLparam1 (ptr_v);
3133 char *s = String_val (ptr_v);
3134 struct page *page;
3136 if (trylock (__func__)) {
3137 goto done;
3140 page = parse_pointer (__func__, s);
3141 page->fmark.span = NULL;
3142 page->lmark.span = NULL;
3143 page->fmark.i = 0;
3144 page->lmark.i = 0;
3146 unlock (__func__);
3147 done:
3148 CAMLreturn0;
3151 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3153 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3154 CAMLlocal1 (ret_v);
3155 fz_rect *b;
3156 struct page *page;
3157 fz_stext_line *line;
3158 fz_page_block *pageb;
3159 fz_stext_block *block;
3160 struct pagedim *pdim;
3161 int mark = Int_val (mark_v);
3162 char *s = String_val (ptr_v);
3163 int x = Int_val (x_v), y = Int_val (y_v);
3165 ret_v = Val_bool (0);
3166 if (trylock (__func__)) {
3167 goto done;
3170 page = parse_pointer (__func__, s);
3171 pdim = &state.pagedims[page->pdimno];
3173 ensuretext (page);
3175 if (mark == mark_page) {
3176 int i;
3177 fz_page_block *pb1 = NULL, *pb2 = NULL;
3179 for (i = 0; i < page->text->len; ++i) {
3180 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3181 pb1 = &page->text->blocks[i];
3182 break;
3185 if (!pb1) goto unlock;
3187 for (i = page->text->len - 1; i >= 0; --i) {
3188 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3189 pb2 = &page->text->blocks[i];
3190 break;
3193 if (!pb2) goto unlock;
3195 block = pb1->u.text;
3197 page->fmark.i = 0;
3198 page->fmark.span = block->lines->first_span;
3200 block = pb2->u.text;
3201 line = &block->lines[block->len - 1];
3202 page->lmark.i = line->last_span->len - 1;
3203 page->lmark.span = line->last_span;
3204 ret_v = Val_bool (1);
3205 goto unlock;
3208 x += pdim->bounds.x0;
3209 y += pdim->bounds.y0;
3211 for (pageb = page->text->blocks;
3212 pageb < page->text->blocks + page->text->len;
3213 ++pageb) {
3214 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3215 block = pageb->u.text;
3217 b = &block->bbox;
3218 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3219 continue;
3221 if (mark == mark_block) {
3222 page->fmark.i = 0;
3223 page->fmark.span = block->lines->first_span;
3225 line = &block->lines[block->len - 1];
3226 page->lmark.i = line->last_span->len - 1;
3227 page->lmark.span = line->last_span;
3228 ret_v = Val_bool (1);
3229 goto unlock;
3232 for (line = block->lines;
3233 line < block->lines + block->len;
3234 ++line) {
3235 fz_stext_span *span;
3237 b = &line->bbox;
3238 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3239 continue;
3241 if (mark == mark_line) {
3242 page->fmark.i = 0;
3243 page->fmark.span = line->first_span;
3245 page->lmark.i = line->last_span->len - 1;
3246 page->lmark.span = line->last_span;
3247 ret_v = Val_bool (1);
3248 goto unlock;
3251 for (span = line->first_span; span; span = span->next) {
3252 int charnum;
3254 b = &span->bbox;
3255 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3256 continue;
3258 for (charnum = 0; charnum < span->len; ++charnum) {
3259 fz_rect bbox;
3260 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3261 b = &bbox;
3263 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3264 /* unicode ftw */
3265 int charnum2, charnum3 = -1, charnum4 = -1;
3267 if (uninteresting (span->text[charnum].c)) goto unlock;
3269 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3270 if (uninteresting (span->text[charnum2].c)) {
3271 charnum3 = charnum2 + 1;
3272 break;
3275 if (charnum3 == -1) charnum3 = 0;
3277 charnum4 = charnum;
3278 for (charnum2 = charnum + 1;
3279 charnum2 < span->len;
3280 ++charnum2) {
3281 if (uninteresting (span->text[charnum2].c)) break;
3282 charnum4 = charnum2;
3285 page->fmark.i = charnum3;
3286 page->fmark.span = span;
3288 page->lmark.i = charnum4;
3289 page->lmark.span = span;
3290 ret_v = Val_bool (1);
3291 goto unlock;
3297 unlock:
3298 if (!Bool_val (ret_v)) {
3299 page->fmark.span = NULL;
3300 page->lmark.span = NULL;
3301 page->fmark.i = 0;
3302 page->lmark.i = 0;
3304 unlock (__func__);
3306 done:
3307 CAMLreturn (ret_v);
3310 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3312 CAMLparam3 (ptr_v, x_v, y_v);
3313 CAMLlocal2 (ret_v, res_v);
3314 fz_rect *b = NULL;
3315 struct page *page;
3316 fz_page_block *pageb;
3317 struct pagedim *pdim;
3318 char *s = String_val (ptr_v);
3319 int x = Int_val (x_v), y = Int_val (y_v);
3321 ret_v = Val_int (0);
3322 if (trylock (__func__)) {
3323 goto done;
3326 page = parse_pointer (__func__, s);
3327 pdim = &state.pagedims[page->pdimno];
3328 x += pdim->bounds.x0;
3329 y += pdim->bounds.y0;
3331 ensuretext (page);
3333 for (pageb = page->text->blocks;
3334 pageb < page->text->blocks + page->text->len;
3335 ++pageb) {
3336 switch (pageb->type) {
3337 case FZ_PAGE_BLOCK_TEXT:
3338 b = &pageb->u.text->bbox;
3339 break;
3341 case FZ_PAGE_BLOCK_IMAGE:
3342 b = &pageb->u.image->bbox;
3343 break;
3345 default:
3346 continue;
3349 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3350 break;
3351 b = NULL;
3353 if (b) {
3354 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3355 ret_v = caml_alloc_small (1, 1);
3356 Store_double_field (res_v, 0, b->x0);
3357 Store_double_field (res_v, 1, b->x1);
3358 Store_double_field (res_v, 2, b->y0);
3359 Store_double_field (res_v, 3, b->y1);
3360 Field (ret_v, 0) = res_v;
3362 unlock (__func__);
3364 done:
3365 CAMLreturn (ret_v);
3368 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3370 CAMLparam2 (ptr_v, rect_v);
3371 fz_rect b;
3372 struct page *page;
3373 struct pagedim *pdim;
3374 char *s = String_val (ptr_v);
3375 int i, x0, x1, y0, y1, fi, li;
3376 fz_stext_line *line;
3377 fz_page_block *pageb;
3378 fz_stext_block *block;
3379 fz_stext_span *span, *fspan, *lspan;
3381 if (trylock (__func__)) {
3382 goto done;
3385 page = parse_pointer (__func__, s);
3386 ensuretext (page);
3388 pdim = &state.pagedims[page->pdimno];
3389 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3390 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3391 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3392 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3394 if (y0 > y1) {
3395 int t = y0;
3396 y0 = y1;
3397 y1 = t;
3398 x0 = x1;
3399 x1 = t;
3402 fi = page->fmark.i;
3403 fspan = page->fmark.span;
3405 li = page->lmark.i;
3406 lspan = page->lmark.span;
3408 for (pageb = page->text->blocks;
3409 pageb < page->text->blocks + page->text->len;
3410 ++pageb) {
3411 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3412 block = pageb->u.text;
3413 for (line = block->lines;
3414 line < block->lines + block->len;
3415 ++line) {
3417 for (span = line->first_span; span; span = span->next) {
3418 for (i = 0; i < span->len; ++i) {
3419 fz_stext_char_bbox (state.ctx, &b, span, i);
3421 if (x0 >= b.x0 && x0 <= b.x1
3422 && y0 >= b.y0 && y0 <= b.y1) {
3423 fspan = span;
3424 fi = i;
3426 if (x1 >= b.x0 && x1 <= b.x1
3427 && y1 >= b.y0 && y1 <= b.y1) {
3428 lspan = span;
3429 li = i;
3435 if (x1 < x0 && fspan == lspan) {
3436 i = fi;
3437 span = fspan;
3439 fi = li;
3440 fspan = lspan;
3442 li = i;
3443 lspan = span;
3446 page->fmark.i = fi;
3447 page->fmark.span = fspan;
3449 page->lmark.i = li;
3450 page->lmark.span = lspan;
3452 unlock (__func__);
3454 done:
3455 CAMLreturn0;
3458 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3460 char buf[4];
3461 int i, len, ret;
3463 for (i = a; i <= b; ++i) {
3464 len = fz_runetochar (buf, span->text[i].c);
3465 ret = fwrite (buf, len, 1, f);
3467 if (ret != 1) {
3468 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3469 len, ret, strerror (errno));
3470 return -1;
3473 return 0;
3476 #ifdef __CYGWIN__
3477 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3479 caml_failwith ("ml_popen not implemented under Cygwin");
3481 #else
3482 CAMLprim value ml_spawn (value command_v, value fds_v)
3484 CAMLparam2 (command_v, fds_v);
3485 CAMLlocal2 (l_v, tup_v);
3486 int ret, ret1;
3487 pid_t pid;
3488 char *msg = NULL;
3489 value earg_v = Nothing;
3490 posix_spawnattr_t attr;
3491 posix_spawn_file_actions_t fa;
3492 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3494 argv[2] = String_val (command_v);
3496 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3497 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3500 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3501 msg = "posix_spawnattr_init";
3502 goto fail1;
3505 #ifdef POSIX_SPAWN_USEVFORK
3506 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3507 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3508 goto fail;
3510 #endif
3512 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3513 int fd1, fd2;
3515 tup_v = Field (l_v, 0);
3516 fd1 = Int_val (Field (tup_v, 0));
3517 fd2 = Int_val (Field (tup_v, 1));
3518 if (fd2 < 0) {
3519 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3520 msg = "posix_spawn_file_actions_addclose";
3521 earg_v = tup_v;
3522 goto fail;
3525 else {
3526 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3527 msg = "posix_spawn_file_actions_adddup2";
3528 earg_v = tup_v;
3529 goto fail;
3534 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3535 msg = "posix_spawn";
3536 goto fail;
3539 fail:
3540 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3541 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3544 fail1:
3545 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3546 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3547 strerror (ret1));
3550 if (msg)
3551 unix_error (ret, msg, earg_v);
3553 CAMLreturn (Val_int (pid));
3555 #endif
3557 CAMLprim value ml_hassel (value ptr_v)
3559 CAMLparam1 (ptr_v);
3560 CAMLlocal1 (ret_v);
3561 struct page *page;
3562 char *s = String_val (ptr_v);
3564 ret_v = Val_bool (0);
3565 if (trylock (__func__)) {
3566 goto done;
3569 page = parse_pointer (__func__, s);
3570 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3571 unlock (__func__);
3572 done:
3573 CAMLreturn (ret_v);
3576 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3578 CAMLparam2 (fd_v, ptr_v);
3579 FILE *f;
3580 int seen = 0;
3581 struct page *page;
3582 fz_stext_line *line;
3583 fz_page_block *pageb;
3584 fz_stext_block *block;
3585 int fd = Int_val (fd_v);
3586 char *s = String_val (ptr_v);
3588 if (trylock (__func__)) {
3589 goto done;
3592 page = parse_pointer (__func__, s);
3594 if (!page->fmark.span || !page->lmark.span) {
3595 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3596 goto unlock;
3599 f = fdopen (fd, "w");
3600 if (!f) {
3601 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3602 fd, strerror (errno));
3603 f = stdout;
3606 for (pageb = page->text->blocks;
3607 pageb < page->text->blocks + page->text->len;
3608 ++pageb) {
3609 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3610 block = pageb->u.text;
3611 for (line = block->lines;
3612 line < block->lines + block->len;
3613 ++line) {
3614 fz_stext_span *span;
3616 for (span = line->first_span; span; span = span->next) {
3617 int a, b;
3619 seen |= span == page->fmark.span || span == page->lmark.span;
3620 a = span == page->fmark.span ? page->fmark.i : 0;
3621 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3623 if (seen) {
3624 if (pipespan (f, span, a, b)) {
3625 goto close;
3627 if (span == page->lmark.span) {
3628 goto close;
3630 if (span == line->last_span) {
3631 if (putc ('\n', f) == EOF) {
3632 fprintf (stderr,
3633 "failed break line on sel pipe: %s\n",
3634 strerror (errno));
3635 goto close;
3642 close:
3643 if (f != stdout) {
3644 int ret = fclose (f);
3645 fd = -1;
3646 if (ret == -1) {
3647 if (errno != ECHILD) {
3648 fprintf (stderr, "failed to close sel pipe: %s\n",
3649 strerror (errno));
3653 unlock:
3654 unlock (__func__);
3656 done:
3657 if (fd >= 0) {
3658 if (close (fd)) {
3659 fprintf (stderr, "failed to close sel pipe: %s\n",
3660 strerror (errno));
3663 CAMLreturn0;
3666 CAMLprim value ml_getpdimrect (value pagedimno_v)
3668 CAMLparam1 (pagedimno_v);
3669 CAMLlocal1 (ret_v);
3670 int pagedimno = Int_val (pagedimno_v);
3671 fz_rect box;
3673 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3674 if (trylock (__func__)) {
3675 box = fz_empty_rect;
3677 else {
3678 box = state.pagedims[pagedimno].mediabox;
3679 unlock (__func__);
3682 Store_double_field (ret_v, 0, box.x0);
3683 Store_double_field (ret_v, 1, box.x1);
3684 Store_double_field (ret_v, 2, box.y0);
3685 Store_double_field (ret_v, 3, box.y1);
3687 CAMLreturn (ret_v);
3690 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3691 value dw_v, value cols_v)
3693 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3694 CAMLlocal1 (ret_v);
3695 int i;
3696 double zoom = -1.;
3697 double maxh = 0.0;
3698 struct pagedim *p;
3699 double winw = Int_val (winw_v);
3700 double winh = Int_val (winh_v);
3701 double dw = Int_val (dw_v);
3702 double cols = Int_val (cols_v);
3703 double pw = 1.0, ph = 1.0;
3705 if (trylock (__func__)) {
3706 goto done;
3709 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3710 double w = p->pagebox.x1 / cols;
3711 double h = p->pagebox.y1;
3712 if (h > maxh) {
3713 maxh = h;
3714 ph = h;
3715 if (state.fitmodel != FitProportional) pw = w;
3717 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3720 zoom = (((winh / ph) * pw) + dw) / winw;
3721 unlock (__func__);
3722 done:
3723 ret_v = caml_copy_double (zoom);
3724 CAMLreturn (ret_v);
3727 CAMLprim value ml_getmaxw (value unit_v)
3729 CAMLparam1 (unit_v);
3730 CAMLlocal1 (ret_v);
3731 int i;
3732 double maxw = -1.;
3733 struct pagedim *p;
3735 if (trylock (__func__)) {
3736 goto done;
3739 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3740 double w = p->pagebox.x1;
3741 maxw = fz_max (maxw, w);
3744 unlock (__func__);
3745 done:
3746 ret_v = caml_copy_double (maxw);
3747 CAMLreturn (ret_v);
3750 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3752 CAMLparam4 (pt_v, x_v, y_v, string_v);
3753 CAMLlocal1 (ret_v);
3754 int pt = Int_val(pt_v);
3755 int x = Int_val (x_v);
3756 int y = Int_val (y_v);
3757 double w;
3759 w = draw_string (state.face, pt, x, y, String_val (string_v));
3760 ret_v = caml_copy_double (w);
3761 CAMLreturn (ret_v);
3764 CAMLprim value ml_measure_string (value pt_v, value string_v)
3766 CAMLparam2 (pt_v, string_v);
3767 CAMLlocal1 (ret_v);
3768 int pt = Int_val (pt_v);
3769 double w;
3771 w = measure_string (state.face, pt, String_val (string_v));
3772 ret_v = caml_copy_double (w);
3773 CAMLreturn (ret_v);
3776 CAMLprim value ml_getpagebox (value opaque_v)
3778 CAMLparam1 (opaque_v);
3779 CAMLlocal1 (ret_v);
3780 fz_rect rect;
3781 fz_irect bbox;
3782 fz_matrix ctm;
3783 fz_device *dev;
3784 char *s = String_val (opaque_v);
3785 struct page *page = parse_pointer (__func__, s);
3787 ret_v = caml_alloc_tuple (4);
3788 dev = fz_new_bbox_device (state.ctx, &rect);
3789 dev->hints |= FZ_IGNORE_SHADE;
3791 ctm = pagectm (page);
3792 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3794 fz_close_device (state.ctx, dev);
3795 fz_drop_device (state.ctx, dev);
3796 fz_round_rect (&bbox, &rect);
3797 Field (ret_v, 0) = Val_int (bbox.x0);
3798 Field (ret_v, 1) = Val_int (bbox.y0);
3799 Field (ret_v, 2) = Val_int (bbox.x1);
3800 Field (ret_v, 3) = Val_int (bbox.y1);
3802 CAMLreturn (ret_v);
3805 CAMLprim void ml_setaalevel (value level_v)
3807 CAMLparam1 (level_v);
3809 state.aalevel = Int_val (level_v);
3810 CAMLreturn0;
3813 #pragma GCC diagnostic push
3814 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3816 #ifndef __COCOA__
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_DEPTH_SIZE, 24,
3872 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3873 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3874 EGL_NONE
3876 EGLConfig conf;
3878 glx.dpy = XOpenDisplay (String_val (display_v));
3879 if (!glx.dpy) {
3880 caml_failwith ("XOpenDisplay");
3883 eglBindAPI (EGL_OPENGL_API);
3885 glx.edpy = eglGetDisplay (glx.dpy);
3886 if (glx.edpy == EGL_NO_DISPLAY) {
3887 caml_failwith ("eglGetDisplay");
3890 if (!eglInitialize (glx.edpy, &major, &minor)) {
3891 caml_failwith ("eglInitialize");
3894 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3895 !num_conf) {
3896 caml_failwith ("eglChooseConfig");
3899 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3900 caml_failwith ("eglGetConfigAttrib");
3903 glx.conf = conf;
3904 initcurs ();
3906 glx.wid = Int_val (wid_v);
3907 CAMLreturn (Val_int (visid));
3910 CAMLprim value ml_glxcompleteinit (value unit_v)
3912 CAMLparam1 (unit_v);
3914 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3915 if (!glx.ctx) {
3916 caml_failwith ("eglCreateContext");
3919 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3920 glx.wid, NULL);
3921 if (glx.win == EGL_NO_SURFACE) {
3922 caml_failwith ("eglCreateWindowSurface");
3925 XFree (glx.visual);
3926 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3927 glx.ctx = NULL;
3928 caml_failwith ("eglMakeCurrent");
3930 CAMLreturn (unit_v);
3932 #else
3933 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3935 CAMLparam3 (display_v, wid_v, screen_v);
3937 glx.dpy = XOpenDisplay (String_val (display_v));
3938 if (!glx.dpy) {
3939 caml_failwith ("XOpenDisplay");
3942 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3943 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3944 if (!glx.visual) {
3945 XCloseDisplay (glx.dpy);
3946 caml_failwith ("glXChooseVisual");
3949 initcurs ();
3951 glx.wid = Int_val (wid_v);
3952 CAMLreturn (Val_int (glx.visual->visualid));
3955 CAMLprim value ml_glxcompleteinit (value unit_v)
3957 CAMLparam1 (unit_v);
3959 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3960 if (!glx.ctx) {
3961 caml_failwith ("glXCreateContext");
3964 XFree (glx.visual);
3965 glx.visual = NULL;
3967 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3968 glXDestroyContext (glx.dpy, glx.ctx);
3969 glx.ctx = NULL;
3970 caml_failwith ("glXMakeCurrent");
3972 CAMLreturn (unit_v);
3974 #endif
3976 CAMLprim void ml_setcursor (value cursor_v)
3978 CAMLparam1 (cursor_v);
3979 size_t cursn = Int_val (cursor_v);
3981 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3982 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3983 XFlush (glx.dpy);
3984 CAMLreturn0;
3987 CAMLprim value ml_swapb (value unit_v)
3989 CAMLparam1 (unit_v);
3990 #ifdef USE_EGL
3991 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3992 caml_failwith ("eglSwapBuffers");
3994 #else
3995 glXSwapBuffers (glx.dpy, glx.wid);
3996 #endif
3997 CAMLreturn (unit_v);
4000 #include "keysym2ucs.c"
4002 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4004 CAMLparam1 (keysym_v);
4005 CAMLlocal1 (str_v);
4006 KeySym keysym = Int_val (keysym_v);
4007 Rune rune;
4008 int len;
4009 char buf[5];
4011 rune = keysym2ucs (keysym);
4012 len = fz_runetochar (buf, rune);
4013 buf[len] = 0;
4014 str_v = caml_copy_string (buf);
4015 CAMLreturn (str_v);
4017 #else
4018 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4020 CAMLparam1 (keysym_v);
4021 CAMLlocal1 (str_v);
4022 long ucs_v = Long_val (keysym_v);
4023 int len;
4024 char buf[5];
4026 len = fz_runetochar (buf, ucs_v);
4027 buf[len] = 0;
4028 str_v = caml_copy_string (buf);
4029 CAMLreturn (str_v);
4031 #endif
4033 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4035 CAMLprim value ml_platform (value unit_v)
4037 CAMLparam1 (unit_v);
4038 CAMLlocal2 (tup_v, arr_v);
4039 int platid = piunknown;
4040 struct utsname buf;
4042 #if defined __linux__
4043 platid = pilinux;
4044 #elif defined __CYGWIN__
4045 platid = picygwin;
4046 #elif defined __DragonFly__ || defined __FreeBSD__
4047 || defined __OpenBSD__ || defined __NetBSD__
4048 platid = pibsd;
4049 #elif defined __sun__
4050 platid = pisun;
4051 #elif defined __APPLE__
4052 platid = piosx;
4053 #endif
4054 if (uname (&buf)) err (1, "uname");
4056 tup_v = caml_alloc_tuple (2);
4058 char const *sar[] = {
4059 buf.sysname,
4060 buf.release,
4061 buf.version,
4062 buf.machine,
4063 NULL
4065 arr_v = caml_copy_string_array (sar);
4067 Field (tup_v, 0) = Val_int (platid);
4068 Field (tup_v, 1) = arr_v;
4069 CAMLreturn (tup_v);
4072 CAMLprim void ml_cloexec (value fd_v)
4074 CAMLparam1 (fd_v);
4075 int fd = Int_val (fd_v);
4077 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4078 uerror ("fcntl", Nothing);
4080 CAMLreturn0;
4083 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4085 CAMLparam2 (w_v, h_v);
4086 CAMLlocal1 (ret_v);
4087 struct bo *pbo;
4088 int w = Int_val (w_v);
4089 int h = Int_val (h_v);
4090 int cs = Int_val (cs_v);
4092 if (state.bo_usable) {
4093 pbo = calloc (sizeof (*pbo), 1);
4094 if (!pbo) {
4095 err (1, "calloc pbo");
4098 switch (cs) {
4099 case 0:
4100 case 1:
4101 pbo->size = w*h*4;
4102 break;
4103 case 2:
4104 pbo->size = w*h*2;
4105 break;
4106 default:
4107 errx (1, "%s: invalid colorspace %d", __func__, cs);
4110 state.glGenBuffersARB (1, &pbo->id);
4111 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4112 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4113 NULL, GL_STREAM_DRAW);
4114 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4115 GL_READ_WRITE);
4116 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4117 if (!pbo->ptr) {
4118 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4119 state.glDeleteBuffersARB (1, &pbo->id);
4120 free (pbo);
4121 ret_v = caml_copy_string ("0");
4123 else {
4124 int res;
4125 char *s;
4127 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4128 if (res < 0) {
4129 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4131 s = malloc (res+1);
4132 if (!s) {
4133 err (1, "malloc %d bytes failed", res+1);
4135 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4136 if (res < 0) {
4137 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4139 ret_v = caml_copy_string (s);
4140 free (s);
4143 else {
4144 ret_v = caml_copy_string ("0");
4146 CAMLreturn (ret_v);
4149 CAMLprim void ml_freepbo (value s_v)
4151 CAMLparam1 (s_v);
4152 char *s = String_val (s_v);
4153 struct tile *tile = parse_pointer (__func__, s);
4155 if (tile->pbo) {
4156 state.glDeleteBuffersARB (1, &tile->pbo->id);
4157 tile->pbo->id = -1;
4158 tile->pbo->ptr = NULL;
4159 tile->pbo->size = -1;
4161 CAMLreturn0;
4164 CAMLprim void ml_unmappbo (value s_v)
4166 CAMLparam1 (s_v);
4167 char *s = String_val (s_v);
4168 struct tile *tile = parse_pointer (__func__, s);
4170 if (tile->pbo) {
4171 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4172 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4173 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4175 tile->pbo->ptr = NULL;
4176 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4178 CAMLreturn0;
4181 static void setuppbo (void)
4183 #ifdef __COCOA__
4184 static CFBundleRef framework = NULL;
4185 if (framework == NULL)
4186 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
4187 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
4188 #else
4189 #ifdef USE_EGL
4190 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4191 #else
4192 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4193 #endif
4194 state.bo_usable = GGPA (glBindBufferARB)
4195 && GGPA (glUnmapBufferARB)
4196 && GGPA (glMapBufferARB)
4197 && GGPA (glBufferDataARB)
4198 && GGPA (glGenBuffersARB)
4199 && GGPA (glDeleteBuffersARB);
4200 #endif
4201 #undef GGPA
4204 CAMLprim value ml_bo_usable (value unit_v)
4206 CAMLparam1 (unit_v);
4207 CAMLreturn (Val_bool (state.bo_usable));
4210 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4212 CAMLparam3 (ptr_v, x_v, y_v);
4213 CAMLlocal2 (ret_v, tup_v);
4214 struct page *page;
4215 char *s = String_val (ptr_v);
4216 int x = Int_val (x_v), y = Int_val (y_v);
4217 struct pagedim *pdim;
4218 fz_point p;
4219 fz_matrix ctm;
4221 page = parse_pointer (__func__, s);
4222 pdim = &state.pagedims[page->pdimno];
4224 ret_v = Val_int (0);
4225 if (trylock (__func__)) {
4226 goto done;
4229 if (pdf_specifics (state.ctx, state.doc)) {
4230 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4231 ctm = state.pagedims[page->pdimno].tctm;
4233 else {
4234 ctm = fz_identity;
4236 p.x = x + pdim->bounds.x0;
4237 p.y = y + pdim->bounds.y0;
4239 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4240 fz_invert_matrix (&ctm, &ctm);
4241 fz_transform_point (&p, &ctm);
4243 tup_v = caml_alloc_tuple (2);
4244 ret_v = caml_alloc_small (1, 1);
4245 Field (tup_v, 0) = Val_int (p.x);
4246 Field (tup_v, 1) = Val_int (p.y);
4247 Field (ret_v, 0) = tup_v;
4249 unlock (__func__);
4250 done:
4251 CAMLreturn (ret_v);
4254 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4255 value x_v, value y_v)
4257 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4258 CAMLlocal1 (ret_v);
4259 struct page *page;
4260 char *s = String_val (ptr_v);
4261 int pageno = Int_val (pageno_v);
4262 int pdimno = Int_val (pdimno_v);
4263 double x = Double_val (x_v), y = Double_val (y_v);
4264 struct pagedim *pdim;
4265 fz_point p;
4266 fz_matrix ctm;
4268 ret_v = Val_int (0);
4269 lock (__func__);
4271 if (!*s) {
4272 page = loadpage (pageno, pdimno);
4274 else {
4275 page = parse_pointer (__func__, s);
4277 pdim = &state.pagedims[pdimno];
4279 if (pdf_specifics (state.ctx, state.doc)) {
4280 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4281 ctm = state.pagedims[page->pdimno].tctm;
4283 else {
4284 ctm = fz_identity;
4286 p.x = x + pdim->bounds.x0;
4287 p.y = y + pdim->bounds.y0;
4289 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4290 fz_transform_point (&p, &ctm);
4292 ret_v = caml_alloc_tuple (2);
4293 Field (ret_v, 0) = caml_copy_double (p.x);
4294 Field (ret_v, 1) = caml_copy_double (p.y);
4296 if (!*s) {
4297 freepage (page);
4299 unlock (__func__);
4300 CAMLreturn (ret_v);
4303 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4304 value contents_v)
4306 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4307 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4309 if (pdf) {
4310 pdf_annot *annot;
4311 struct page *page;
4312 fz_point p;
4313 char *s = String_val (ptr_v);
4315 page = parse_pointer (__func__, s);
4316 annot = pdf_create_annot (state.ctx,
4317 pdf_page_from_fz_page (state.ctx,
4318 page->fzpage),
4319 PDF_ANNOT_TEXT);
4320 p.x = Int_val (x_v);
4321 p.y = Int_val (y_v);
4322 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4323 pdf_set_text_annot_position (state.ctx, annot, p);
4324 state.dirty = 1;
4326 CAMLreturn0;
4329 CAMLprim void ml_delannot (value ptr_v, value n_v)
4331 CAMLparam2 (ptr_v, n_v);
4332 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4334 if (pdf) {
4335 struct page *page;
4336 char *s = String_val (ptr_v);
4337 struct slink *slink;
4339 page = parse_pointer (__func__, s);
4340 slink = &page->slinks[Int_val (n_v)];
4341 pdf_delete_annot (state.ctx,
4342 pdf_page_from_fz_page (state.ctx, page->fzpage),
4343 (pdf_annot *) slink->u.annot);
4344 state.dirty = 1;
4346 CAMLreturn0;
4349 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4351 CAMLparam3 (ptr_v, n_v, str_v);
4352 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4354 if (pdf) {
4355 struct page *page;
4356 char *s = String_val (ptr_v);
4357 struct slink *slink;
4359 page = parse_pointer (__func__, s);
4360 slink = &page->slinks[Int_val (n_v)];
4361 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4362 String_val (str_v));
4363 state.dirty = 1;
4365 CAMLreturn0;
4368 CAMLprim value ml_hasunsavedchanges (value unit_v)
4370 CAMLparam1 (unit_v);
4371 CAMLreturn (Val_bool (state.dirty));
4374 CAMLprim void ml_savedoc (value path_v)
4376 CAMLparam1 (path_v);
4377 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4379 if (pdf) {
4380 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4382 CAMLreturn0;
4385 static void makestippletex (void)
4387 const char pixels[] = "\xff\xff\0\0";
4388 glGenTextures (1, &state.stid);
4389 glBindTexture (GL_TEXTURE_1D, state.stid);
4390 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4391 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4392 glTexImage1D (
4393 GL_TEXTURE_1D,
4395 GL_ALPHA,
4398 GL_ALPHA,
4399 GL_UNSIGNED_BYTE,
4400 pixels
4404 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4406 return caml_copy_string (FZ_VERSION);
4409 CAMLprim void ml_init (value csock_v, value params_v)
4411 CAMLparam2 (csock_v, params_v);
4412 CAMLlocal2 (trim_v, fuzz_v);
4413 int ret;
4414 int texcount;
4415 char *fontpath;
4416 int colorspace;
4417 int mustoresize;
4418 int haspboext;
4420 /* Without following call to setlocale mbstowcs fails for, at
4421 least, strings containing chinese symbols (δΈ­ for instance)
4422 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4423 wide character" as the reason of failure and with macOS
4424 producing bogus output) */
4425 if (setlocale (LC_CTYPE, "")) {
4426 /* Following two lines were taken from dvtm/vt.c */
4427 const char *cset = nl_langinfo (CODESET);
4428 state.utf8cs = !strcmp (cset, "UTF-8");
4430 else {
4431 fprintf (stderr, "setlocale failed\n");
4434 state.csock = Int_val (csock_v);
4435 state.rotate = Int_val (Field (params_v, 0));
4436 state.fitmodel = Int_val (Field (params_v, 1));
4437 trim_v = Field (params_v, 2);
4438 texcount = Int_val (Field (params_v, 3));
4439 state.sliceheight = Int_val (Field (params_v, 4));
4440 mustoresize = Int_val (Field (params_v, 5));
4441 colorspace = Int_val (Field (params_v, 6));
4442 fontpath = String_val (Field (params_v, 7));
4444 if (caml_string_length (Field (params_v, 8)) > 0) {
4445 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4447 if (!state.trimcachepath) {
4448 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4449 strerror (errno));
4453 haspboext = Bool_val (Field (params_v, 9));
4455 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4456 fz_register_document_handlers (state.ctx);
4458 state.trimmargins = Bool_val (Field (trim_v, 0));
4459 fuzz_v = Field (trim_v, 1);
4460 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4461 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4462 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4463 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4465 set_tex_params (colorspace);
4467 if (*fontpath) {
4468 state.face = load_font (fontpath);
4470 else {
4471 int len;
4472 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4473 0, 0, &len);
4474 state.face = load_builtin_font (data, len);
4476 if (!state.face) _exit (1);
4478 realloctexts (texcount);
4480 if (haspboext) {
4481 setuppbo ();
4484 makestippletex ();
4486 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4487 if (ret) {
4488 errx (1, "pthread_create: %s", strerror (ret));
4491 CAMLreturn0;