"Fix" describe_location
[llpp/slowscroll.git] / link.c
blobf71d63aee75313ebc4ea06c71ebb8a815f8b7f26
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
3 #define FIXME 0
5 #include <errno.h>
6 #include <stdio.h>
7 #include <ctype.h>
8 #include <string.h>
9 #include <stdlib.h>
10 #include <signal.h>
12 #include <wchar.h>
13 #include <locale.h>
14 #include <langinfo.h>
16 #include <unistd.h>
17 #include <pthread.h>
18 #include <sys/uio.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/ioctl.h>
22 #include <sys/utsname.h>
24 #ifdef __CYGWIN__
25 #include <cygwin/socket.h> /* FIONREAD */
26 #else
27 #include <spawn.h>
28 #endif
30 #include <regex.h>
31 #include <stdarg.h>
32 #include <limits.h>
33 #include <inttypes.h>
35 #ifdef __COCOA__
36 #include <CoreFoundation/CoreFoundation.h>
37 #endif
39 #ifdef __APPLE__
40 #include <OpenGL/gl.h>
41 #else
42 #include <GL/gl.h>
43 #endif
45 #include <caml/fail.h>
46 #include <caml/alloc.h>
47 #include <caml/memory.h>
48 #include <caml/unixsupport.h>
50 #if __GNUC__ < 5 && !defined __clang__
51 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
52 clobbered diagnostics */
53 #pragma GCC diagnostic ignored "-Wclobbered"
54 #endif
56 #pragma GCC diagnostic push
57 #pragma GCC diagnostic ignored "-Wunused-parameter"
58 #include <mupdf/fitz.h>
59 #include <mupdf/pdf.h>
60 #pragma GCC diagnostic pop
62 #include <ft2build.h>
63 #include FT_FREETYPE_H
65 #define PIGGYBACK
66 #define CACHE_PAGEREFS
68 #ifndef __USE_GNU
69 extern char **environ;
70 #endif
72 #if defined __GNUC__
73 #define NORETURN_ATTR __attribute__ ((noreturn))
74 #define UNUSED_ATTR __attribute__ ((unused))
75 #if !defined __clang__
76 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
77 #else
78 #define OPTIMIZE_ATTR(n)
79 #endif
80 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
81 #else
82 #define NORETURN_ATTR
83 #define UNUSED_ATTR
84 #define OPTIMIZE_ATTR(n)
85 #define GCC_FMT_ATTR(a, b)
86 #endif
88 #define FMT_s "zu"
90 #define FMT_ptr PRIxPTR
91 #define SCN_ptr SCNxPTR
92 #define FMT_ptr_cast(p) ((uintptr_t) (p))
93 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
95 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
96 err (int exitcode, const char *fmt, ...)
98 va_list ap;
99 int savederrno;
101 savederrno = errno;
102 va_start (ap, fmt);
103 vfprintf (stderr, fmt, ap);
104 va_end (ap);
105 fprintf (stderr, ": %s\n", strerror (savederrno));
106 fflush (stderr);
107 _exit (exitcode);
110 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
111 errx (int exitcode, const char *fmt, ...)
113 va_list ap;
115 va_start (ap, fmt);
116 vfprintf (stderr, fmt, ap);
117 va_end (ap);
118 fputc ('\n', stderr);
119 fflush (stderr);
120 _exit (exitcode);
123 #ifndef GL_TEXTURE_RECTANGLE_ARB
124 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
125 #endif
127 #ifdef USE_NPOT
128 #define TEXT_TYPE GL_TEXTURE_2D
129 #else
130 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
131 #endif
133 #ifndef GL_BGRA
134 #define GL_BGRA 0x80E1
135 #endif
137 #ifndef GL_UNSIGNED_INT_8_8_8_8
138 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
139 #endif
141 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
142 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
143 #endif
145 #if 0
146 #define lprintf printf
147 #else
148 #define lprintf(...)
149 #endif
151 #define ARSERT(cond) for (;;) { \
152 if (!(cond)) { \
153 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
155 break; \
158 struct slice {
159 int h;
160 int texindex;
163 struct tile {
164 int w, h;
165 int slicecount;
166 int sliceheight;
167 struct bo *pbo;
168 fz_pixmap *pixmap;
169 struct slice slices[1];
172 struct pagedim {
173 int pageno;
174 int rotate;
175 int left;
176 int tctmready;
177 fz_irect bounds;
178 fz_rect pagebox;
179 fz_rect mediabox;
180 fz_matrix ctm, zoomctm, tctm;
183 struct slink {
184 enum { SLINK, SANNOT } tag;
185 fz_irect bbox;
186 union {
187 fz_link *link;
188 fz_annot *annot;
189 } u;
192 struct annot {
193 fz_irect bbox;
194 fz_annot *annot;
197 struct page {
198 int tgen;
199 int sgen;
200 int agen;
201 int pageno;
202 int pdimno;
203 fz_stext_page *text;
204 fz_page *fzpage;
205 fz_display_list *dlist;
206 int slinkcount;
207 struct slink *slinks;
208 int annotcount;
209 struct annot *annots;
210 struct mark {
211 fz_stext_char *ch;
212 } fmark, lmark;
215 struct {
216 int sliceheight;
217 struct pagedim *pagedims;
218 int pagecount;
219 int pagedimcount;
220 fz_document *doc;
221 fz_context *ctx;
222 int w, h;
224 int texindex;
225 int texcount;
226 GLuint *texids;
228 GLenum texiform;
229 GLenum texform;
230 GLenum texty;
232 fz_colorspace *colorspace;
234 struct {
235 int w, h;
236 struct slice *slice;
237 } *texowners;
239 int rotate;
240 enum { FitWidth, FitProportional, FitPage } fitmodel;
241 int trimmargins;
242 int needoutline;
243 int gen;
244 int aalevel;
246 int trimanew;
247 fz_irect trimfuzz;
248 fz_pixmap *pig;
250 pthread_t thread;
251 int csock;
252 FT_Face face;
254 char *trimcachepath;
255 int cxack;
256 int dirty;
258 GLuint stid;
260 int bo_usable;
261 GLuint boid;
263 void (*glBindBufferARB) (GLenum, GLuint);
264 GLboolean (*glUnmapBufferARB) (GLenum);
265 void *(*glMapBufferARB) (GLenum, GLenum);
266 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
267 void (*glGenBuffersARB) (GLsizei, GLuint *);
268 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
270 GLfloat texcoords[8];
271 GLfloat vertices[16];
273 #ifdef CACHE_PAGEREFS
274 struct {
275 int idx;
276 int count;
277 pdf_obj **objs;
278 pdf_document *pdf;
279 } pdflut;
280 #endif
281 int utf8cs;
282 } state;
284 struct bo {
285 GLuint id;
286 void *ptr;
287 size_t size;
290 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
292 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
295 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
297 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
300 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
302 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
303 m.a, m.b, m.c, m.d, m.e, m.f);
306 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
308 static void lock (const char *cap)
310 int ret = pthread_mutex_lock (&mutex);
311 if (ret) {
312 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
316 static void unlock (const char *cap)
318 int ret = pthread_mutex_unlock (&mutex);
319 if (ret) {
320 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
324 static int trylock (const char *cap)
326 int ret = pthread_mutex_trylock (&mutex);
327 if (ret && ret != EBUSY) {
328 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
330 return ret == EBUSY;
333 static void *parse_pointer (const char *cap, const char *s)
335 int ret;
336 void *ptr;
338 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
339 if (ret != 1) {
340 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
342 return ptr;
345 static double now (void)
347 struct timeval tv;
349 if (gettimeofday (&tv, NULL)) {
350 err (1, "gettimeofday");
352 return tv.tv_sec + tv.tv_usec*1e-6;
355 static int hasdata (void)
357 int ret, avail;
358 ret = ioctl (state.csock, FIONREAD, &avail);
359 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
360 return avail > 0;
363 CAMLprim value ml_hasdata (value fd_v)
365 CAMLparam1 (fd_v);
366 int ret, avail;
368 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
369 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
370 CAMLreturn (Val_bool (avail > 0));
373 static void readdata (int fd, void *p, int size)
375 ssize_t n;
377 again:
378 n = read (fd, p, size);
379 if (n - size) {
380 if (n < 0 && errno == EINTR) goto again;
381 if (!n) errx (1, "EOF while reading");
382 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
386 static void writedata (int fd, char *p, int size)
388 ssize_t n;
389 uint32_t size4 = size;
390 struct iovec iov[2] = {
391 { .iov_base = &size4, .iov_len = 4 },
392 { .iov_base = p, .iov_len = size }
395 again:
396 n = writev (fd, iov, 2);
397 if (n < 0 && errno == EINTR) goto again;
398 if (n - size - 4) {
399 if (!n) errx (1, "EOF while writing data");
400 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
404 static int readlen (int fd)
406 /* Type punned unions here. Why? Less code (Adjusted by more comments).
407 https://en.wikipedia.org/wiki/Type_punning */
408 /* Then again https://bugs.llvm.org/show_bug.cgi?id=31928 - hmm */
409 union { uint32_t len; char raw[4]; } buf;
410 readdata (fd, buf.raw, 4);
411 return buf.len;
414 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
416 CAMLparam3 (fd_v, bytes_v, len_v);
417 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
418 CAMLreturn0;
421 CAMLprim value ml_rcmd (value fd_v)
423 CAMLparam1 (fd_v);
424 CAMLlocal1 (strdata_v);
425 int fd = Int_val (fd_v);
426 int len = readlen (fd);
427 strdata_v = caml_alloc_string (len);
428 readdata (fd, String_val (strdata_v), len);
429 CAMLreturn (strdata_v);
432 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
434 int size = 64, len;
435 va_list ap;
436 char fbuf[size];
437 char *buf = fbuf;
439 for (;;) {
440 va_start (ap, fmt);
441 len = vsnprintf (buf, size, fmt, ap);
442 va_end (ap);
444 if (len > -1) {
445 if (len < size - 4) {
446 writedata (state.csock, buf, len);
447 break;
449 else size = len + 5;
451 else {
452 err (1, "vsnprintf for `%s' failed", fmt);
454 buf = realloc (buf == fbuf ? NULL : buf, size);
455 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
457 if (buf != fbuf) free (buf);
460 static void closedoc (void)
462 #ifdef CACHE_PAGEREFS
463 if (state.pdflut.objs) {
464 for (int i = 0; i < state.pdflut.count; ++i) {
465 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
467 free (state.pdflut.objs);
468 state.pdflut.objs = NULL;
469 state.pdflut.idx = 0;
471 #endif
472 if (state.doc) {
473 fz_drop_document (state.ctx, state.doc);
474 state.doc = NULL;
478 static int openxref (char *filename, char *password)
480 for (int i = 0; i < state.texcount; ++i) {
481 state.texowners[i].w = -1;
482 state.texowners[i].slice = NULL;
485 closedoc ();
487 state.dirty = 0;
488 if (state.pagedims) {
489 free (state.pagedims);
490 state.pagedims = NULL;
492 state.pagedimcount = 0;
494 fz_set_aa_level (state.ctx, state.aalevel);
495 state.doc = fz_open_document (state.ctx, filename);
496 if (fz_needs_password (state.ctx, state.doc)) {
497 if (password && !*password) {
498 printd ("pass");
499 return 0;
501 else {
502 int ok = fz_authenticate_password (state.ctx, state.doc, password);
503 if (!ok) {
504 printd ("pass fail");
505 return 0;
509 state.pagecount = fz_count_pages (state.ctx, state.doc);
510 return 1;
513 static void pdfinfo (void)
515 struct { char *tag; char *name; } metatbl[] = {
516 { FZ_META_INFO_TITLE, "Title" },
517 { FZ_META_INFO_AUTHOR, "Author" },
518 { FZ_META_FORMAT, "Format" },
519 { FZ_META_ENCRYPTION, "Encryption" },
520 { "info:Creator", "Creator" },
521 { "info:Producer", "Producer" },
522 { "info:CreationDate", "Creation date" },
524 int len = 0;
525 char *buf = NULL;
527 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
528 int need;
529 again:
530 need = fz_lookup_metadata (state.ctx, state.doc,
531 metatbl[i].tag, buf, len);
532 if (need > 0) {
533 if (need <= len) {
534 printd ("info %s\t%s", metatbl[i].name, buf);
536 else {
537 buf = realloc (buf, need + 1);
538 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
539 len = need + 1;
540 goto again;
544 free (buf);
546 printd ("infoend");
549 static void unlinktile (struct tile *tile)
551 for (int i = 0; i < tile->slicecount; ++i) {
552 struct slice *s = &tile->slices[i];
554 if (s->texindex != -1) {
555 if (state.texowners[s->texindex].slice == s) {
556 state.texowners[s->texindex].slice = NULL;
562 static void freepage (struct page *page)
564 if (!page) return;
565 if (page->text) {
566 fz_drop_stext_page (state.ctx, page->text);
568 if (page->slinks) {
569 free (page->slinks);
571 fz_drop_display_list (state.ctx, page->dlist);
572 fz_drop_page (state.ctx, page->fzpage);
573 free (page);
576 static void freetile (struct tile *tile)
578 unlinktile (tile);
579 if (!tile->pbo) {
580 #ifndef PIGGYBACK
581 fz_drop_pixmap (state.ctx, tile->pixmap);
582 #else
583 if (state.pig) {
584 fz_drop_pixmap (state.ctx, state.pig);
586 state.pig = tile->pixmap;
587 #endif
589 else {
590 free (tile->pbo);
591 fz_drop_pixmap (state.ctx, tile->pixmap);
593 free (tile);
596 #ifdef __ALTIVEC__
597 #include <stdint.h>
598 #include <altivec.h>
600 static int cacheline32bytes;
602 static void __attribute__ ((constructor)) clcheck (void)
604 char **envp = environ;
605 unsigned long *auxv;
607 while (*envp++);
609 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
610 if (*auxv == 19) {
611 cacheline32bytes = auxv[1] == 32;
612 return;
617 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
619 size_t size = pixmap->w * pixmap->h * pixmap->n;
620 if (cacheline32bytes && size > 32) {
621 intptr_t a1, a2, diff;
622 size_t sizea, i;
623 vector unsigned char v = vec_splat_u8 (-1);
624 vector unsigned char *p;
626 a1 = a2 = (intptr_t) pixmap->samples;
627 a2 = (a1 + 31) & ~31;
628 diff = a2 - a1;
629 sizea = size - diff;
630 p = (void *) a2;
632 while (a1 != a2) *(char *) a1++ = 0xff;
633 for (i = 0; i < (sizea & ~31); i += 32) {
634 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
635 vec_st (v, i, p);
636 vec_st (v, i + 16, p);
638 while (i < sizea) *((char *) a1 + i++) = 0xff;
640 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
642 #else
643 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
644 #endif
646 static void trimctm (pdf_page *page, int pindex)
648 fz_matrix ctm;
649 struct pagedim *pdim = &state.pagedims[pindex];
651 if (!page) return;
652 if (!pdim->tctmready) {
653 fz_rect realbox, mediabox;
654 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
656 fz_rotate (&rm, -pdim->rotate);
657 fz_scale (&sm, 1, -1);
658 fz_concat (&ctm, &rm, &sm);
659 realbox = pdim->mediabox;
660 fz_transform_rect (&realbox, &ctm);
661 fz_translate (&tm, -realbox.x0, -realbox.y0);
662 fz_concat (&ctm1, &ctm, &tm);
663 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
664 fz_invert_matrix (&im, &page_ctm);
665 fz_concat (&ctm, &im, &ctm1);
666 pdim->tctm = ctm;
667 pdim->tctmready = 1;
671 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
673 fz_matrix ctm, tm;
674 int pdimno = pdim - state.pagedims;
676 if (pdf_specifics (state.ctx, state.doc)) {
677 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
678 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
680 else {
681 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
682 fz_concat (&ctm, &tm, &pdim->ctm);
684 return ctm;
687 static fz_matrix pagectm (struct page *page)
689 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
692 static void *loadpage (int pageno, int pindex)
694 fz_device *dev;
695 struct page *page;
697 page = calloc (sizeof (struct page), 1);
698 if (!page) {
699 err (1, "calloc page %d", pageno);
702 page->dlist = fz_new_display_list (state.ctx, NULL);
703 dev = fz_new_list_device (state.ctx, page->dlist);
704 fz_try (state.ctx) {
705 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
706 fz_run_page (state.ctx, page->fzpage, dev,
707 &fz_identity, NULL);
709 fz_catch (state.ctx) {
710 page->fzpage = NULL;
712 fz_close_device (state.ctx, dev);
713 fz_drop_device (state.ctx, dev);
715 page->pdimno = pindex;
716 page->pageno = pageno;
717 page->sgen = state.gen;
718 page->agen = state.gen;
719 page->tgen = state.gen;
720 return page;
723 static struct tile *alloctile (int h)
725 int slicecount;
726 size_t tilesize;
727 struct tile *tile;
729 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
730 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
731 tile = calloc (tilesize, 1);
732 if (!tile) {
733 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
735 for (int i = 0; i < slicecount; ++i) {
736 int sh = fz_mini (h, state.sliceheight);
737 tile->slices[i].h = sh;
738 tile->slices[i].texindex = -1;
739 h -= sh;
741 tile->slicecount = slicecount;
742 tile->sliceheight = state.sliceheight;
743 return tile;
746 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
747 struct bo *pbo)
749 fz_rect rect;
750 fz_irect bbox;
751 fz_matrix ctm;
752 fz_device *dev;
753 struct tile *tile;
754 struct pagedim *pdim;
756 tile = alloctile (h);
757 pdim = &state.pagedims[page->pdimno];
759 bbox = pdim->bounds;
760 bbox.x0 += x;
761 bbox.y0 += y;
762 bbox.x1 = bbox.x0 + w;
763 bbox.y1 = bbox.y0 + h;
765 if (state.pig) {
766 if (state.pig->w == w
767 && state.pig->h == h
768 && state.pig->colorspace == state.colorspace) {
769 tile->pixmap = state.pig;
770 tile->pixmap->x = bbox.x0;
771 tile->pixmap->y = bbox.y0;
773 else {
774 fz_drop_pixmap (state.ctx, state.pig);
776 state.pig = NULL;
778 if (!tile->pixmap) {
779 if (pbo) {
780 tile->pixmap =
781 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
782 &bbox, NULL, 1, pbo->ptr);
783 tile->pbo = pbo;
785 else {
786 tile->pixmap =
787 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
788 NULL, 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 const 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 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
942 fz_invert_matrix (&ctm, &page_ctm);
943 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
944 fz_close_device (ctx, dev);
945 fz_drop_device (ctx, dev);
947 rect.x0 += state.trimfuzz.x0;
948 rect.x1 += state.trimfuzz.x1;
949 rect.y0 += state.trimfuzz.y0;
950 rect.y1 += state.trimfuzz.y1;
951 fz_transform_rect (&rect, &ctm);
952 fz_intersect_rect (&rect, &mediabox);
954 if (!fz_is_empty_rect (&rect)) {
955 mediabox = rect;
958 obj = pdf_new_array (ctx, pdf, 4);
959 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
960 mediabox.x0));
961 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
962 mediabox.y0));
963 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
964 mediabox.x1));
965 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
966 mediabox.y1));
967 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
969 else {
970 mediabox.x0 = pdf_to_real (ctx,
971 pdf_array_get (ctx, obj, 0));
972 mediabox.y0 = pdf_to_real (ctx,
973 pdf_array_get (ctx, obj, 1));
974 mediabox.x1 = pdf_to_real (ctx,
975 pdf_array_get (ctx, obj, 2));
976 mediabox.y1 = pdf_to_real (ctx,
977 pdf_array_get (ctx, obj, 3));
980 fz_drop_page (ctx, &page->super);
981 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
982 if (show) {
983 printd ("progress %f Trimming %d",
984 (double) (pageno + 1) / state.pagecount,
985 pageno + 1);
988 fz_catch (ctx) {
989 fprintf (stderr, "failed to load page %d\n", pageno+1);
992 else {
993 int empty = 0;
994 fz_rect cropbox;
996 pdf_to_rect (ctx,
997 pdf_dict_gets (ctx, pageobj, "MediaBox"),
998 &mediabox);
999 if (fz_is_empty_rect (&mediabox)) {
1000 mediabox.x0 = 0;
1001 mediabox.y0 = 0;
1002 mediabox.x1 = 612;
1003 mediabox.y1 = 792;
1004 empty = 1;
1007 pdf_to_rect (ctx,
1008 pdf_dict_gets (ctx, pageobj, "CropBox"),
1009 &cropbox);
1010 if (!fz_is_empty_rect (&cropbox)) {
1011 if (empty) {
1012 mediabox = cropbox;
1014 else {
1015 fz_intersect_rect (&mediabox, &cropbox);
1018 else {
1019 if (empty) {
1020 if (fz_is_empty_rect (&rootmediabox)) {
1021 fprintf (stderr,
1022 "cannot find page size for page %d\n",
1023 pageno+1);
1025 else {
1026 mediabox = rootmediabox;
1032 else {
1033 if (state.trimmargins && trimw) {
1034 fz_page *page;
1036 fz_try (ctx) {
1037 page = fz_load_page (ctx, state.doc, pageno);
1038 fz_bound_page (ctx, page, &mediabox);
1039 if (state.trimmargins) {
1040 fz_rect rect;
1041 fz_device *dev;
1043 dev = fz_new_bbox_device (ctx, &rect);
1044 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1045 fz_close_device (ctx, dev);
1046 fz_drop_device (ctx, dev);
1048 rect.x0 += state.trimfuzz.x0;
1049 rect.x1 += state.trimfuzz.x1;
1050 rect.y0 += state.trimfuzz.y0;
1051 rect.y1 += state.trimfuzz.y1;
1052 fz_intersect_rect (&rect, &mediabox);
1054 if (!fz_is_empty_rect (&rect)) {
1055 mediabox = rect;
1058 fz_drop_page (ctx, page);
1059 if (!state.cxack) {
1060 printd ("progress %f loading %d",
1061 (double) (pageno + 1) / state.pagecount,
1062 pageno + 1);
1065 fz_catch (ctx) {
1067 if (trimf) {
1068 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1069 if (n - 1) {
1070 err (1, "fwrite trim mediabox");
1074 else {
1075 if (trimf) {
1076 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1077 if (n - 1) {
1078 err (1, "fread trim mediabox %d", pageno);
1081 else {
1082 fz_page *page;
1083 fz_try (ctx) {
1084 page = fz_load_page (ctx, state.doc, pageno);
1085 fz_bound_page (ctx, page, &mediabox);
1086 fz_drop_page (ctx, page);
1088 show = !state.trimmargins && pageno % 20 == 0;
1089 if (show) {
1090 printd ("progress %f Gathering dimensions %d",
1091 (double) (pageno) / state.pagecount,
1092 pageno);
1095 fz_catch (ctx) {
1096 fprintf (stderr, "failed to load page %d\n", pageno);
1102 if (state.pagedimcount == 0
1103 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1104 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1105 size_t size;
1107 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1108 state.pagedims = realloc (state.pagedims, size);
1109 if (!state.pagedims) {
1110 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1111 size, state.pagedimcount + 1);
1114 p = &state.pagedims[state.pagedimcount++];
1115 p->rotate = rotate;
1116 p->mediabox = mediabox;
1117 p->pageno = pageno;
1120 end = now ();
1121 if (!wthack) {
1122 printd ("progress 1 %s %d pages in %f seconds",
1123 state.trimmargins ? "Trimmed" : "Processed",
1124 state.pagecount, end - start);
1126 state.trimanew = 0;
1127 if (trimf) {
1128 if (fclose (trimf)) {
1129 err (1, "fclose");
1134 static void layout (void)
1136 int pindex;
1137 fz_rect box;
1138 fz_matrix ctm, rm;
1139 struct pagedim *p = p;
1140 double zw, w, maxw = 0.0, zoom = zoom;
1142 if (state.pagedimcount == 0) return;
1144 switch (state.fitmodel) {
1145 case FitProportional:
1146 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1147 double x0, x1;
1149 p = &state.pagedims[pindex];
1150 fz_rotate (&rm, p->rotate + state.rotate);
1151 box = p->mediabox;
1152 fz_transform_rect (&box, &rm);
1154 x0 = fz_min (box.x0, box.x1);
1155 x1 = fz_max (box.x0, box.x1);
1157 w = x1 - x0;
1158 maxw = fz_max (w, maxw);
1159 zoom = state.w / maxw;
1161 break;
1163 case FitPage:
1164 maxw = state.w;
1165 break;
1167 case FitWidth:
1168 break;
1170 default:
1171 ARSERT (0 && state.fitmodel);
1174 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1175 fz_rect rect;
1176 fz_matrix tm, sm;
1178 p = &state.pagedims[pindex];
1179 fz_rotate (&ctm, state.rotate);
1180 fz_rotate (&rm, p->rotate + state.rotate);
1181 box = p->mediabox;
1182 fz_transform_rect (&box, &rm);
1183 w = box.x1 - box.x0;
1184 switch (state.fitmodel) {
1185 case FitProportional:
1186 p->left = ((maxw - w) * zoom) / 2.0;
1187 break;
1188 case FitPage:
1190 double zh, h;
1191 zw = maxw / w;
1192 h = box.y1 - box.y0;
1193 zh = state.h / h;
1194 zoom = fz_min (zw, zh);
1195 p->left = (maxw - (w * zoom)) / 2.0;
1197 break;
1198 case FitWidth:
1199 p->left = 0;
1200 zoom = state.w / w;
1201 break;
1204 fz_scale (&p->zoomctm, zoom, zoom);
1205 fz_concat (&ctm, &p->zoomctm, &ctm);
1207 fz_rotate (&rm, p->rotate);
1208 p->pagebox = p->mediabox;
1209 fz_transform_rect (&p->pagebox, &rm);
1210 p->pagebox.x1 -= p->pagebox.x0;
1211 p->pagebox.y1 -= p->pagebox.y0;
1212 p->pagebox.x0 = 0;
1213 p->pagebox.y0 = 0;
1214 rect = p->pagebox;
1215 fz_transform_rect (&rect, &ctm);
1216 fz_round_rect (&p->bounds, &rect);
1217 p->ctm = ctm;
1219 fz_translate (&tm, 0, -p->mediabox.y1);
1220 fz_scale (&sm, zoom, -zoom);
1221 fz_concat (&ctm, &tm, &sm);
1223 p->tctmready = 0;
1226 do {
1227 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1228 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1229 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1230 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1231 int boundw = x1 - x0;
1232 int boundh = y1 - y0;
1234 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1235 } while (p-- != state.pagedims);
1238 struct pagedim *pdimofpageno (int pageno)
1240 struct pagedim *pdim = state.pagedims;
1242 for (int i = 0; i < state.pagedimcount; ++i) {
1243 if (state.pagedims[i].pageno > pageno)
1244 break;
1245 pdim = &state.pagedims[i];
1247 return pdim;
1250 static
1251 struct anchor { int n; int x; int y; int w; int h; }
1252 uritoanchor (const char *uri)
1254 fz_point p;
1255 struct anchor a;
1257 a.n = -1;
1258 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1259 if (a.n >= 0) {
1260 struct pagedim *pdim = pdimofpageno (a.n);
1261 fz_transform_point (&p, &pdim->ctm);
1262 a.x = p.x;
1263 a.y = p.y;
1264 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1266 return a;
1269 static void recurse_outline (fz_outline *outline, int level)
1271 while (outline) {
1272 struct anchor a = uritoanchor (outline->uri);
1273 if (a.n >= 0) {
1274 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1276 else {
1277 printd ("on %d %s", level, outline->title);
1279 if (outline->down) {
1280 recurse_outline (outline->down, level + 1);
1282 outline = outline->next;
1286 static void process_outline (void)
1288 fz_outline *outline;
1290 if (!state.needoutline || !state.pagedimcount) return;
1292 state.needoutline = 0;
1293 outline = fz_load_outline (state.ctx, state.doc);
1294 if (outline) {
1295 recurse_outline (outline, 0);
1296 fz_drop_outline (state.ctx, outline);
1300 static char *strofline (fz_stext_line *line)
1302 char *p;
1303 char utf8[10];
1304 fz_stext_char *ch;
1305 size_t size = 0, cap = 80;
1307 p = malloc (cap + 1);
1308 if (!p) return NULL;
1310 for (ch = line->first_char; ch; ch = ch->next) {
1311 int n = fz_runetochar (utf8, ch->c);
1312 if (size + n > cap) {
1313 cap *= 2;
1314 p = realloc (p, cap + 1);
1315 if (!p) return NULL;
1318 memcpy (p + size, utf8, n);
1319 size += n;
1321 p[size] = 0;
1322 return p;
1325 static int matchline (regex_t *re, fz_stext_line *line,
1326 int stop, int pageno, double start)
1328 int ret;
1329 char *p;
1330 regmatch_t rm;
1332 p = strofline (line);
1333 if (!p) return -1;
1335 ret = regexec (re, p, 1, &rm, 0);
1336 if (ret) {
1337 free (p);
1338 if (ret != REG_NOMATCH) {
1339 size_t size;
1340 char errbuf[80];
1341 size = regerror (ret, re, errbuf, sizeof (errbuf));
1342 printd ("msg regexec error `%.*s'",
1343 (int) size, errbuf);
1344 return -1;
1346 return 0;
1348 else {
1349 fz_point p1, p2, p3, p4;
1350 fz_rect s = {0,0,0,0}, e;
1351 fz_stext_char *ch;
1352 int o = 0;
1354 for (ch = line->first_char; ch; ch = ch->next) {
1355 o += fz_runelen (ch->c);
1356 if (o > rm.rm_so) {
1357 s = ch->bbox;
1358 break;
1361 for (;ch; ch = ch->next) {
1362 o += fz_runelen (ch->c);
1363 if (o > rm.rm_eo) break;
1365 e = ch->bbox;
1367 p1.x = s.x0;
1368 p1.y = s.y0;
1369 p2.x = e.x1;
1370 p2.y = s.y0;
1371 p3.x = e.x1;
1372 p3.y = e.y1;
1373 p4.x = s.x0;
1374 p4.y = e.y1;
1376 if (!stop) {
1377 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1378 pageno, 1,
1379 p1.x, p1.y,
1380 p2.x, p2.y,
1381 p3.x, p3.y,
1382 p4.x, p4.y);
1384 printd ("progress 1 found at %d `%.*s' in %f sec",
1385 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1386 now () - start);
1388 else {
1389 printd ("match %d %d %f %f %f %f %f %f %f %f",
1390 pageno, 2,
1391 p1.x, p1.y,
1392 p2.x, p2.y,
1393 p3.x, p3.y,
1394 p4.x, p4.y);
1396 free (p);
1397 return 1;
1401 /* wishful thinking function */
1402 static void search (regex_t *re, int pageno, int y, int forward)
1404 fz_device *tdev;
1405 fz_stext_page *text;
1406 struct pagedim *pdim;
1407 int stop = 0, niters = 0;
1408 double start, end;
1409 fz_page *page;
1410 fz_stext_block *block;
1412 start = now ();
1413 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1414 if (niters++ == 5) {
1415 niters = 0;
1416 if (hasdata ()) {
1417 printd ("progress 1 attention requested aborting search at %d",
1418 pageno);
1419 stop = 1;
1421 else {
1422 printd ("progress %f searching in page %d",
1423 (double) (pageno + 1) / state.pagecount,
1424 pageno);
1427 pdim = pdimofpageno (pageno);
1428 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1429 tdev = fz_new_stext_device (state.ctx, text, 0);
1431 page = fz_load_page (state.ctx, state.doc, pageno);
1433 fz_matrix ctm = pagectm1 (page, pdim);
1434 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1437 fz_close_device (state.ctx, tdev);
1438 fz_drop_device (state.ctx, tdev);
1440 if (forward) {
1441 for (block = text->first_block; block; block = block->next) {
1442 fz_stext_line *line;
1444 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1445 for (line = block->u.t.first_line; line; line = line->next) {
1446 if (line->bbox.y0 < y + 1) continue;
1448 switch (matchline (re, line, stop, pageno, start)) {
1449 case 0: break;
1450 case 1: stop = 1; break;
1451 case -1: stop = 1; goto endloop;
1456 else {
1457 for (block = text->last_block; block; block = block->prev) {
1458 fz_stext_line *line;
1460 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1461 for (line = block->u.t.last_line; line; line = line->prev) {
1462 if (line->bbox.y0 < y + 1) continue;
1464 switch (matchline (re, line, stop, pageno, start)) {
1465 case 0: break;
1466 case 1: stop = 1; break;
1467 case -1: stop = 1; goto endloop;
1473 if (forward) {
1474 pageno += 1;
1475 y = 0;
1477 else {
1478 pageno -= 1;
1479 y = INT_MAX;
1481 endloop:
1482 fz_drop_stext_page (state.ctx, text);
1483 fz_drop_page (state.ctx, page);
1485 end = now ();
1486 if (!stop) {
1487 printd ("progress 1 no matches %f sec", end - start);
1489 printd ("clearrects");
1492 static void set_tex_params (int colorspace)
1494 union {
1495 unsigned char b;
1496 unsigned int s;
1497 } endianness = {1};
1499 switch (colorspace) {
1500 case 0:
1501 state.texiform = GL_RGBA8;
1502 state.texform = GL_RGBA;
1503 state.texty = GL_UNSIGNED_BYTE;
1504 state.colorspace = fz_device_rgb (state.ctx);
1505 break;
1506 case 1:
1507 state.texiform = GL_RGBA8;
1508 state.texform = GL_BGRA;
1509 state.texty = endianness.s > 1
1510 ? GL_UNSIGNED_INT_8_8_8_8
1511 : GL_UNSIGNED_INT_8_8_8_8_REV;
1512 state.colorspace = fz_device_bgr (state.ctx);
1513 break;
1514 case 2:
1515 state.texiform = GL_LUMINANCE_ALPHA;
1516 state.texform = GL_LUMINANCE_ALPHA;
1517 state.texty = GL_UNSIGNED_BYTE;
1518 state.colorspace = fz_device_gray (state.ctx);
1519 break;
1520 default:
1521 errx (1, "invalid colorspce %d", colorspace);
1525 static void realloctexts (int texcount)
1527 size_t size;
1529 if (texcount == state.texcount) return;
1531 if (texcount < state.texcount) {
1532 glDeleteTextures (state.texcount - texcount,
1533 state.texids + texcount);
1536 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1537 state.texids = realloc (state.texids, size);
1538 if (!state.texids) {
1539 err (1, "realloc texs %" FMT_s, size);
1542 state.texowners = (void *) (state.texids + texcount);
1543 if (texcount > state.texcount) {
1544 glGenTextures (texcount - state.texcount,
1545 state.texids + state.texcount);
1546 for (int i = state.texcount; i < texcount; ++i) {
1547 state.texowners[i].w = -1;
1548 state.texowners[i].slice = NULL;
1551 state.texcount = texcount;
1552 state.texindex = 0;
1555 static char *mbtoutf8 (char *s)
1557 char *p, *r;
1558 wchar_t *tmp;
1559 size_t i, ret, len;
1561 if (state.utf8cs) {
1562 return s;
1565 len = mbstowcs (NULL, s, strlen (s));
1566 if (len == 0) {
1567 return s;
1569 else {
1570 if (len == (size_t) -1) {
1571 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1572 return s;
1576 tmp = calloc (len, sizeof (wchar_t));
1577 if (!tmp) {
1578 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1579 len, sizeof (wchar_t), errno, strerror (errno));
1580 return s;
1583 ret = mbstowcs (tmp, s, len);
1584 if (ret == (size_t) -1) {
1585 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1586 len, errno, strerror (errno));
1587 free (tmp);
1588 return s;
1591 len = 0;
1592 for (i = 0; i < ret; ++i) {
1593 len += fz_runelen (tmp[i]);
1596 p = r = malloc (len + 1);
1597 if (!r) {
1598 printd ("emsg mbtoutf8: malloc(%zu)", len);
1599 free (tmp);
1600 return s;
1603 for (i = 0; i < ret; ++i) {
1604 p += fz_runetochar (p, tmp[i]);
1606 *p = 0;
1607 free (tmp);
1608 return r;
1611 CAMLprim value ml_mbtoutf8 (value s_v)
1613 CAMLparam1 (s_v);
1614 CAMLlocal1 (ret_v);
1615 char *s, *r;
1617 s = String_val (s_v);
1618 r = mbtoutf8 (s);
1619 if (r == s) {
1620 ret_v = s_v;
1622 else {
1623 ret_v = caml_copy_string (r);
1624 free (r);
1626 CAMLreturn (ret_v);
1629 static void * mainloop (void UNUSED_ATTR *unused)
1631 char *p = NULL;
1632 int len, ret, oldlen = 0;
1634 fz_var (p);
1635 fz_var (oldlen);
1636 for (;;) {
1637 len = readlen (state.csock);
1638 if (len == 0) {
1639 errx (1, "readlen returned 0");
1642 if (oldlen < len + 1) {
1643 p = realloc (p, len + 1);
1644 if (!p) {
1645 err (1, "realloc %d failed", len + 1);
1647 oldlen = len + 1;
1649 readdata (state.csock, p, len);
1650 p[len] = 0;
1652 if (!strncmp ("open", p, 4)) {
1653 int wthack, off, usedoccss, ok = 0;
1654 char *password;
1655 char *filename;
1656 char *utf8filename;
1657 size_t filenamelen;
1659 fz_var (ok);
1660 ret = sscanf (p + 5, " %d %d %d %n",
1661 &wthack, &state.cxack, &usedoccss, &off);
1662 if (ret != 3) {
1663 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1666 filename = p + 5 + off;
1667 filenamelen = strlen (filename);
1668 password = filename + filenamelen + 1;
1670 if (password[strlen (password) + 1]) {
1671 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1674 lock ("open");
1675 fz_set_use_document_css (state.ctx, usedoccss);
1676 fz_try (state.ctx) {
1677 ok = openxref (filename, password);
1679 fz_catch (state.ctx) {
1680 utf8filename = mbtoutf8 (filename);
1681 printd ("msg Could not open %s", utf8filename);
1683 if (ok) {
1684 pdfinfo ();
1685 initpdims (wthack);
1687 unlock ("open");
1689 if (ok) {
1690 if (!wthack) {
1691 utf8filename = mbtoutf8 (filename);
1692 printd ("msg Opened %s (press h/F1 to get help)",
1693 utf8filename);
1694 if (utf8filename != filename) {
1695 free (utf8filename);
1698 state.needoutline = 1;
1701 else if (!strncmp ("cs", p, 2)) {
1702 int i, colorspace;
1704 ret = sscanf (p + 2, " %d", &colorspace);
1705 if (ret != 1) {
1706 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1708 lock ("cs");
1709 set_tex_params (colorspace);
1710 for (i = 0; i < state.texcount; ++i) {
1711 state.texowners[i].w = -1;
1712 state.texowners[i].slice = NULL;
1714 unlock ("cs");
1716 else if (!strncmp ("freepage", p, 8)) {
1717 void *ptr;
1719 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1720 if (ret != 1) {
1721 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1723 freepage (ptr);
1725 else if (!strncmp ("freetile", p, 8)) {
1726 void *ptr;
1728 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1729 if (ret != 1) {
1730 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1732 freetile (ptr);
1734 else if (!strncmp ("search", p, 6)) {
1735 int icase, pageno, y, len2, forward;
1736 char *pattern;
1737 regex_t re;
1739 ret = sscanf (p + 6, " %d %d %d %d,%n",
1740 &icase, &pageno, &y, &forward, &len2);
1741 if (ret != 4) {
1742 errx (1, "malformed search `%s' ret=%d", p, ret);
1745 pattern = p + 6 + len2;
1746 ret = regcomp (&re, pattern,
1747 REG_EXTENDED | (icase ? REG_ICASE : 0));
1748 if (ret) {
1749 char errbuf[80];
1750 size_t size;
1752 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1753 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1755 else {
1756 search (&re, pageno, y, forward);
1757 regfree (&re);
1760 else if (!strncmp ("geometry", p, 8)) {
1761 int w, h, fitmodel;
1763 printd ("clear");
1764 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1765 if (ret != 3) {
1766 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1769 lock ("geometry");
1770 state.h = h;
1771 if (w != state.w) {
1772 state.w = w;
1773 for (int i = 0; i < state.texcount; ++i) {
1774 state.texowners[i].slice = NULL;
1777 state.fitmodel = fitmodel;
1778 layout ();
1779 process_outline ();
1781 state.gen++;
1782 unlock ("geometry");
1783 printd ("continue %d", state.pagecount);
1785 else if (!strncmp ("reqlayout", p, 9)) {
1786 char *nameddest;
1787 int rotate, off, h;
1788 unsigned int fitmodel;
1789 pdf_document *pdf;
1791 printd ("clear");
1792 ret = sscanf (p + 9, " %d %u %d %n",
1793 &rotate, &fitmodel, &h, &off);
1794 if (ret != 3) {
1795 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1797 lock ("reqlayout");
1798 pdf = pdf_specifics (state.ctx, state.doc);
1799 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1800 state.gen += 1;
1802 state.rotate = rotate;
1803 state.fitmodel = fitmodel;
1804 state.h = h;
1805 layout ();
1806 process_outline ();
1808 nameddest = p + 9 + off;
1809 if (pdf && nameddest && *nameddest) {
1810 fz_point xy;
1811 struct pagedim *pdim;
1812 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1813 &xy.x, &xy.y);
1814 pdim = pdimofpageno (pageno);
1815 fz_transform_point (&xy, &pdim->ctm);
1816 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1819 state.gen++;
1820 unlock ("reqlayout");
1821 printd ("continue %d", state.pagecount);
1823 else if (!strncmp ("page", p, 4)) {
1824 double a, b;
1825 struct page *page;
1826 int pageno, pindex;
1828 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1829 if (ret != 2) {
1830 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1833 lock ("page");
1834 a = now ();
1835 page = loadpage (pageno, pindex);
1836 b = now ();
1837 unlock ("page");
1839 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1841 else if (!strncmp ("tile", p, 4)) {
1842 int x, y, w, h;
1843 struct page *page;
1844 struct tile *tile;
1845 double a, b;
1846 void *data;
1848 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1849 SCN_ptr_cast (&page), &x, &y, &w, &h,
1850 SCN_ptr_cast (&data));
1851 if (ret != 6) {
1852 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1855 lock ("tile");
1856 a = now ();
1857 tile = rendertile (page, x, y, w, h, data);
1858 b = now ();
1859 unlock ("tile");
1861 printd ("tile %d %d %" FMT_ptr " %u %f",
1862 x, y,
1863 FMT_ptr_cast (tile),
1864 tile->w * tile->h * tile->pixmap->n,
1865 b - a);
1867 else if (!strncmp ("trimset", p, 7)) {
1868 fz_irect fuzz;
1869 int trimmargins;
1871 ret = sscanf (p + 7, " %d %d %d %d %d",
1872 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1873 if (ret != 5) {
1874 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1876 lock ("trimset");
1877 state.trimmargins = trimmargins;
1878 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1879 state.trimanew = 1;
1880 state.trimfuzz = fuzz;
1882 unlock ("trimset");
1884 else if (!strncmp ("settrim", p, 7)) {
1885 fz_irect fuzz;
1886 int trimmargins;
1888 ret = sscanf (p + 7, " %d %d %d %d %d",
1889 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1890 if (ret != 5) {
1891 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1893 printd ("clear");
1894 lock ("settrim");
1895 state.trimmargins = trimmargins;
1896 state.needoutline = 1;
1897 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1898 state.trimanew = 1;
1899 state.trimfuzz = fuzz;
1901 state.pagedimcount = 0;
1902 free (state.pagedims);
1903 state.pagedims = NULL;
1904 initpdims (0);
1905 layout ();
1906 process_outline ();
1907 unlock ("settrim");
1908 printd ("continue %d", state.pagecount);
1910 else if (!strncmp ("sliceh", p, 6)) {
1911 int h;
1913 ret = sscanf (p + 6, " %d", &h);
1914 if (ret != 1) {
1915 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1917 if (h != state.sliceheight) {
1918 state.sliceheight = h;
1919 for (int i = 0; i < state.texcount; ++i) {
1920 state.texowners[i].w = -1;
1921 state.texowners[i].h = -1;
1922 state.texowners[i].slice = NULL;
1926 else if (!strncmp ("interrupt", p, 9)) {
1927 printd ("vmsg interrupted");
1929 else {
1930 errx (1, "unknown command %.*s", len, p);
1933 return 0;
1936 CAMLprim value ml_isexternallink (value uri_v)
1938 CAMLparam1 (uri_v);
1939 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1940 CAMLreturn (Val_bool (ext));
1943 CAMLprim value ml_uritolocation (value uri_v)
1945 CAMLparam1 (uri_v);
1946 CAMLlocal1 (ret_v);
1947 int pageno;
1948 fz_point xy;
1949 struct pagedim *pdim;
1951 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1952 &xy.x, &xy.y);
1953 pdim = pdimofpageno (pageno);
1954 fz_transform_point (&xy, &pdim->ctm);
1955 ret_v = caml_alloc_tuple (3);
1956 Field (ret_v, 0) = Val_int (pageno);
1957 Field (ret_v, 1) = caml_copy_double (xy.x);
1958 Field (ret_v, 2) = caml_copy_double (xy.y);
1959 CAMLreturn (ret_v);
1962 CAMLprim value ml_realloctexts (value texcount_v)
1964 CAMLparam1 (texcount_v);
1965 int ok;
1967 if (trylock (__func__)) {
1968 ok = 0;
1969 goto done;
1971 realloctexts (Int_val (texcount_v));
1972 ok = 1;
1973 unlock (__func__);
1975 done:
1976 CAMLreturn (Val_bool (ok));
1979 static void recti (int x0, int y0, int x1, int y1)
1981 GLfloat *v = state.vertices;
1983 glVertexPointer (2, GL_FLOAT, 0, v);
1984 v[0] = x0; v[1] = y0;
1985 v[2] = x1; v[3] = y0;
1986 v[4] = x0; v[5] = y1;
1987 v[6] = x1; v[7] = y1;
1988 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1991 static void showsel (struct page *page, int ox, int oy)
1993 fz_irect bbox;
1994 fz_rect rect;
1995 fz_stext_block *block;
1996 int seen = 0;
1997 unsigned char selcolor[] = {15,15,15,140};
1999 if (!page->fmark.ch || !page->lmark.ch) return;
2001 glEnable (GL_BLEND);
2002 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2003 glColor4ubv (selcolor);
2005 ox += state.pagedims[page->pdimno].bounds.x0;
2006 oy += state.pagedims[page->pdimno].bounds.y0;
2008 for (block = page->text->first_block; block; block = block->next) {
2009 fz_stext_line *line;
2011 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2012 for (line = block->u.t.first_line; line; line = line->next) {
2013 fz_stext_char *ch;
2015 rect = fz_empty_rect;
2016 for (ch = line->first_char; ch; ch = ch->next) {
2017 if (ch == page->fmark.ch) seen = 1;
2018 if (seen) fz_union_rect (&rect, &ch->bbox);
2019 if (ch == page->lmark.ch) {
2020 fz_round_rect (&bbox, &rect);
2021 recti (bbox.x0 + ox, bbox.y0 + oy,
2022 bbox.x1 + ox, bbox.y1 + oy);
2023 goto done;
2026 fz_round_rect (&bbox, &rect);
2027 recti (bbox.x0 + ox, bbox.y0 + oy,
2028 bbox.x1 + ox, bbox.y1 + oy);
2031 done:
2032 glDisable (GL_BLEND);
2035 #include "glfont.c"
2037 static void stipplerect (fz_matrix *m,
2038 fz_point *p1,
2039 fz_point *p2,
2040 fz_point *p3,
2041 fz_point *p4,
2042 GLfloat *texcoords,
2043 GLfloat *vertices)
2045 fz_transform_point (p1, m);
2046 fz_transform_point (p2, m);
2047 fz_transform_point (p3, m);
2048 fz_transform_point (p4, m);
2050 float w, h, s, t;
2052 w = p2->x - p1->x;
2053 h = p2->y - p1->y;
2054 t = hypotf (w, h) * .25f;
2056 w = p3->x - p2->x;
2057 h = p3->y - p2->y;
2058 s = hypotf (w, h) * .25f;
2060 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2061 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2063 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2064 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2066 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2067 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2069 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2070 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2072 glDrawArrays (GL_LINES, 0, 8);
2075 static void solidrect (fz_matrix *m,
2076 fz_point *p1,
2077 fz_point *p2,
2078 fz_point *p3,
2079 fz_point *p4,
2080 GLfloat *vertices)
2082 fz_transform_point (p1, m);
2083 fz_transform_point (p2, m);
2084 fz_transform_point (p3, m);
2085 fz_transform_point (p4, m);
2086 vertices[0] = p1->x; vertices[1] = p1->y;
2087 vertices[2] = p2->x; vertices[3] = p2->y;
2089 vertices[4] = p3->x; vertices[5] = p3->y;
2090 vertices[6] = p4->x; vertices[7] = p4->y;
2091 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2094 static void highlightlinks (struct page *page, int xoff, int yoff)
2096 fz_matrix ctm, tm, pm;
2097 fz_link *link, *links;
2098 GLfloat *texcoords = state.texcoords;
2099 GLfloat *vertices = state.vertices;
2101 links = fz_load_links (state.ctx, page->fzpage);
2103 glEnable (GL_TEXTURE_1D);
2104 glEnable (GL_BLEND);
2105 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2106 glBindTexture (GL_TEXTURE_1D, state.stid);
2108 xoff -= state.pagedims[page->pdimno].bounds.x0;
2109 yoff -= state.pagedims[page->pdimno].bounds.y0;
2110 fz_translate (&tm, xoff, yoff);
2111 pm = pagectm (page);
2112 fz_concat (&ctm, &pm, &tm);
2114 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2115 glVertexPointer (2, GL_FLOAT, 0, vertices);
2117 for (link = links; link; link = link->next) {
2118 fz_point p1, p2, p3, p4;
2120 p1.x = link->rect.x0;
2121 p1.y = link->rect.y0;
2123 p2.x = link->rect.x1;
2124 p2.y = link->rect.y0;
2126 p3.x = link->rect.x1;
2127 p3.y = link->rect.y1;
2129 p4.x = link->rect.x0;
2130 p4.y = link->rect.y1;
2132 /* TODO: different colours for different schemes */
2133 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2134 else glColor3ub (255, 0, 0);
2136 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2139 for (int i = 0; i < page->annotcount; ++i) {
2140 fz_point p1, p2, p3, p4;
2141 struct annot *annot = &page->annots[i];
2143 p1.x = annot->bbox.x0;
2144 p1.y = annot->bbox.y0;
2146 p2.x = annot->bbox.x1;
2147 p2.y = annot->bbox.y0;
2149 p3.x = annot->bbox.x1;
2150 p3.y = annot->bbox.y1;
2152 p4.x = annot->bbox.x0;
2153 p4.y = annot->bbox.y1;
2155 glColor3ub (0, 0, 128);
2156 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2159 glDisable (GL_BLEND);
2160 glDisable (GL_TEXTURE_1D);
2163 static int compareslinks (const void *l, const void *r)
2165 struct slink const *ls = l;
2166 struct slink const *rs = r;
2167 if (ls->bbox.y0 == rs->bbox.y0) {
2168 return rs->bbox.x0 - rs->bbox.x0;
2170 return ls->bbox.y0 - rs->bbox.y0;
2173 static void droptext (struct page *page)
2175 if (page->text) {
2176 fz_drop_stext_page (state.ctx, page->text);
2177 page->fmark.ch = NULL;
2178 page->lmark.ch = NULL;
2179 page->text = NULL;
2183 static void dropannots (struct page *page)
2185 if (page->annots) {
2186 free (page->annots);
2187 page->annots = NULL;
2188 page->annotcount = 0;
2192 static void ensureannots (struct page *page)
2194 int i, count = 0;
2195 size_t annotsize = sizeof (*page->annots);
2196 fz_annot *annot;
2198 if (state.gen != page->agen) {
2199 dropannots (page);
2200 page->agen = state.gen;
2202 if (page->annots) return;
2204 for (annot = fz_first_annot (state.ctx, page->fzpage);
2205 annot;
2206 annot = fz_next_annot (state.ctx, annot)) {
2207 count++;
2210 if (count > 0) {
2211 page->annotcount = count;
2212 page->annots = calloc (count, annotsize);
2213 if (!page->annots) {
2214 err (1, "calloc annots %d", count);
2217 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2218 annot;
2219 annot = fz_next_annot (state.ctx, annot), i++) {
2220 fz_rect rect;
2222 fz_bound_annot (state.ctx, annot, &rect);
2223 page->annots[i].annot = annot;
2224 fz_round_rect (&page->annots[i].bbox, &rect);
2229 static void dropslinks (struct page *page)
2231 if (page->slinks) {
2232 free (page->slinks);
2233 page->slinks = NULL;
2234 page->slinkcount = 0;
2238 static void ensureslinks (struct page *page)
2240 fz_matrix ctm;
2241 int i, count;
2242 size_t slinksize = sizeof (*page->slinks);
2243 fz_link *link, *links;
2245 ensureannots (page);
2246 if (state.gen != page->sgen) {
2247 dropslinks (page);
2248 page->sgen = state.gen;
2250 if (page->slinks) return;
2252 links = fz_load_links (state.ctx, page->fzpage);
2253 ctm = pagectm (page);
2255 count = page->annotcount;
2256 for (link = links; link; link = link->next) {
2257 count++;
2259 if (count > 0) {
2260 int j;
2262 page->slinkcount = count;
2263 page->slinks = calloc (count, slinksize);
2264 if (!page->slinks) {
2265 err (1, "calloc slinks %d", count);
2268 for (i = 0, link = links; link; ++i, link = link->next) {
2269 fz_rect rect;
2271 rect = link->rect;
2272 fz_transform_rect (&rect, &ctm);
2273 page->slinks[i].tag = SLINK;
2274 page->slinks[i].u.link = link;
2275 fz_round_rect (&page->slinks[i].bbox, &rect);
2277 for (j = 0; j < page->annotcount; ++j, ++i) {
2278 fz_rect rect;
2279 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2280 fz_transform_rect (&rect, &ctm);
2281 fz_round_rect (&page->slinks[i].bbox, &rect);
2283 page->slinks[i].tag = SANNOT;
2284 page->slinks[i].u.annot = page->annots[j].annot;
2286 qsort (page->slinks, count, slinksize, compareslinks);
2290 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2291 static void fmt_linkn (char *s, unsigned int u)
2293 unsigned int len; unsigned int q;
2294 unsigned int zma = 'z' - 'a' + 1;
2295 len = 1; q = u;
2296 while (q > zma - 1) { ++len; q /= zma; }
2297 if (s) {
2298 s += len;
2299 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2300 /* handles u == 0 */
2302 s[len] = 0;
2305 static void highlightslinks (struct page *page, int xoff, int yoff,
2306 int noff, char *targ, int tlen, int hfsize)
2308 char buf[40];
2309 struct slink *slink;
2310 double x0, y0, x1, y1, w;
2312 ensureslinks (page);
2313 glColor3ub (0xc3, 0xb0, 0x91);
2314 for (int i = 0; i < page->slinkcount; ++i) {
2315 fmt_linkn (buf, i + noff);
2316 if (!tlen || !strncmp (targ, buf, tlen)) {
2317 slink = &page->slinks[i];
2319 x0 = slink->bbox.x0 + xoff - 5;
2320 y1 = slink->bbox.y0 + yoff - 5;
2321 y0 = y1 + 10 + hfsize;
2322 w = measure_string (state.face, hfsize, buf);
2323 x1 = x0 + w + 10;
2324 recti (x0, y0, x1, y1);
2328 glEnable (GL_BLEND);
2329 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2330 glEnable (GL_TEXTURE_2D);
2331 glColor3ub (0, 0, 0);
2332 for (int i = 0; i < page->slinkcount; ++i) {
2333 fmt_linkn (buf, i + noff);
2334 if (!tlen || !strncmp (targ, buf, tlen)) {
2335 slink = &page->slinks[i];
2337 x0 = slink->bbox.x0 + xoff;
2338 y0 = slink->bbox.y0 + yoff + hfsize;
2339 draw_string (state.face, hfsize, x0, y0, buf);
2342 glDisable (GL_TEXTURE_2D);
2343 glDisable (GL_BLEND);
2346 static void uploadslice (struct tile *tile, struct slice *slice)
2348 int offset;
2349 struct slice *slice1;
2350 unsigned char *texdata;
2352 offset = 0;
2353 for (slice1 = tile->slices; slice != slice1; slice1++) {
2354 offset += slice1->h * tile->w * tile->pixmap->n;
2356 if (slice->texindex != -1 && slice->texindex < state.texcount
2357 && state.texowners[slice->texindex].slice == slice) {
2358 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2360 else {
2361 int subimage = 0;
2362 int texindex = state.texindex++ % state.texcount;
2364 if (state.texowners[texindex].w == tile->w) {
2365 if (state.texowners[texindex].h >= slice->h) {
2366 subimage = 1;
2368 else {
2369 state.texowners[texindex].h = slice->h;
2372 else {
2373 state.texowners[texindex].h = slice->h;
2376 state.texowners[texindex].w = tile->w;
2377 state.texowners[texindex].slice = slice;
2378 slice->texindex = texindex;
2380 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2381 #if TEXT_TYPE == GL_TEXTURE_2D
2382 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2383 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2384 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2385 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2386 #endif
2387 if (tile->pbo) {
2388 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2389 texdata = 0;
2391 else {
2392 texdata = tile->pixmap->samples;
2394 if (subimage) {
2395 glTexSubImage2D (TEXT_TYPE,
2399 tile->w,
2400 slice->h,
2401 state.texform,
2402 state.texty,
2403 texdata+offset
2406 else {
2407 glTexImage2D (TEXT_TYPE,
2409 state.texiform,
2410 tile->w,
2411 slice->h,
2413 state.texform,
2414 state.texty,
2415 texdata+offset
2418 if (tile->pbo) {
2419 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2424 CAMLprim void ml_begintiles (value unit_v)
2426 CAMLparam1 (unit_v);
2427 glEnable (TEXT_TYPE);
2428 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2429 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2430 CAMLreturn0;
2433 CAMLprim void ml_endtiles (value unit_v)
2435 CAMLparam1 (unit_v);
2436 glDisable (TEXT_TYPE);
2437 CAMLreturn0;
2440 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2442 CAMLparam2 (args_v, ptr_v);
2443 int dispx = Int_val (Field (args_v, 0));
2444 int dispy = Int_val (Field (args_v, 1));
2445 int dispw = Int_val (Field (args_v, 2));
2446 int disph = Int_val (Field (args_v, 3));
2447 int tilex = Int_val (Field (args_v, 4));
2448 int tiley = Int_val (Field (args_v, 5));
2449 char *s = String_val (ptr_v);
2450 struct tile *tile = parse_pointer (__func__, s);
2451 int slicey, firstslice;
2452 struct slice *slice;
2453 GLfloat *texcoords = state.texcoords;
2454 GLfloat *vertices = state.vertices;
2456 firstslice = tiley / tile->sliceheight;
2457 slice = &tile->slices[firstslice];
2458 slicey = tiley % tile->sliceheight;
2460 while (disph > 0) {
2461 int dh;
2463 dh = slice->h - slicey;
2464 dh = fz_mini (disph, dh);
2465 uploadslice (tile, slice);
2467 texcoords[0] = tilex; texcoords[1] = slicey;
2468 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2469 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2470 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2472 vertices[0] = dispx; vertices[1] = dispy;
2473 vertices[2] = dispx+dispw; vertices[3] = dispy;
2474 vertices[4] = dispx; vertices[5] = dispy+dh;
2475 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2477 #if TEXT_TYPE == GL_TEXTURE_2D
2478 for (int i = 0; i < 8; ++i) {
2479 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2481 #endif
2483 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2484 dispy += dh;
2485 disph -= dh;
2486 slice++;
2487 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2488 slicey = 0;
2490 CAMLreturn0;
2493 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2495 fz_matrix ctm, tm, pm;
2496 fz_point p1, p2, p3, p4;
2497 GLfloat *vertices = state.vertices;
2498 double *v = (double *) rects_v;
2500 xoff -= state.pagedims[page->pdimno].bounds.x0;
2501 yoff -= state.pagedims[page->pdimno].bounds.y0;
2502 fz_translate (&tm, xoff, yoff);
2503 pm = pagectm (page);
2504 fz_concat (&ctm, &pm, &tm);
2506 glEnable (GL_BLEND);
2507 glVertexPointer (2, GL_FLOAT, 0, vertices);
2509 glColor4dv (v);
2510 p1.x = v[4];
2511 p1.y = v[5];
2513 p2.x = v[6];
2514 p2.y = v[5];
2516 p3.x = v[6];
2517 p3.y = v[7];
2519 p4.x = v[4];
2520 p4.y = v[7];
2521 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2522 glDisable (GL_BLEND);
2525 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2526 value xoff_v, value yoff_v,
2527 value li_v)
2529 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2530 int xoff = Int_val (xoff_v);
2531 int yoff = Int_val (yoff_v);
2532 int noff = Int_val (Field (li_v, 0));
2533 char *targ = String_val (Field (li_v, 1));
2534 int tlen = caml_string_length (Field (li_v, 1));
2535 int hfsize = Int_val (Field (li_v, 2));
2536 char *s = String_val (ptr_v);
2537 int hlmask = Int_val (hlinks_v);
2538 struct page *page = parse_pointer (__func__, s);
2540 if (!page->fzpage) {
2541 /* deal with loadpage failed pages */
2542 goto done;
2545 if (trylock (__func__)) {
2546 noff = -1;
2547 goto done;
2550 ensureannots (page);
2551 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2552 if (hlmask & 2) {
2553 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2554 noff = page->slinkcount;
2556 if (page->tgen == state.gen) {
2557 showsel (page, xoff, yoff);
2559 unlock (__func__);
2561 done:
2562 CAMLreturn (Val_int (noff));
2565 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2566 value rects_v)
2568 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2569 int xoff = Int_val (xoff_v);
2570 int yoff = Int_val (yoff_v);
2571 char *s = String_val (ptr_v);
2572 struct page *page = parse_pointer (__func__, s);
2574 drawprect (page, xoff, yoff, rects_v);
2575 CAMLreturn0;
2578 static struct annot *getannot (struct page *page, int x, int y)
2580 fz_point p;
2581 fz_matrix ctm;
2582 const fz_matrix *tctm;
2583 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2585 if (!page->annots) return NULL;
2587 if (pdf) {
2588 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2589 tctm = &state.pagedims[page->pdimno].tctm;
2591 else {
2592 tctm = &fz_identity;
2595 p.x = x;
2596 p.y = y;
2598 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2599 fz_invert_matrix (&ctm, &ctm);
2600 fz_transform_point (&p, &ctm);
2602 if (pdf) {
2603 for (int i = 0; i < page->annotcount; ++i) {
2604 struct annot *a = &page->annots[i];
2605 fz_rect rect;
2607 fz_bound_annot (state.ctx, a->annot, &rect);
2608 if (p.x >= rect.x0 && p.x <= rect.x1) {
2609 if (p.y >= rect.y0 && p.y <= rect.y1)
2610 return a;
2614 return NULL;
2617 static fz_link *getlink (struct page *page, int x, int y)
2619 fz_point p;
2620 fz_matrix ctm;
2621 fz_link *link, *links;
2623 links = fz_load_links (state.ctx, page->fzpage);
2625 p.x = x;
2626 p.y = y;
2628 ctm = pagectm (page);
2629 fz_invert_matrix (&ctm, &ctm);
2630 fz_transform_point (&p, &ctm);
2632 for (link = links; link; link = link->next) {
2633 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2634 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2635 return link;
2639 return NULL;
2642 static void ensuretext (struct page *page)
2644 if (state.gen != page->tgen) {
2645 droptext (page);
2646 page->tgen = state.gen;
2648 if (!page->text) {
2649 fz_matrix ctm;
2650 fz_device *tdev;
2652 page->text = fz_new_stext_page (state.ctx,
2653 &state.pagedims[page->pdimno].mediabox);
2654 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2655 ctm = pagectm (page);
2656 fz_run_display_list (state.ctx, page->dlist,
2657 tdev, &ctm, &fz_infinite_rect, NULL);
2658 fz_close_device (state.ctx, tdev);
2659 fz_drop_device (state.ctx, tdev);
2663 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2665 CAMLparam2 (start_page_v, dir_v);
2666 CAMLlocal1 (ret_v);
2667 int i, dir = Int_val (dir_v);
2668 int start_page = Int_val (start_page_v);
2669 int end_page = dir > 0 ? state.pagecount : -1;
2670 pdf_document *pdf;
2672 fz_var (end_page);
2673 ret_v = Val_int (0);
2674 lock (__func__);
2675 pdf = pdf_specifics (state.ctx, state.doc);
2676 for (i = start_page + dir; i != end_page; i += dir) {
2677 int found;
2679 fz_var (found);
2680 if (pdf) {
2681 pdf_page *page = NULL;
2683 fz_var (page);
2684 fz_try (state.ctx) {
2685 page = pdf_load_page (state.ctx, pdf, i);
2686 found = !!page->links || !!page->annots;
2688 fz_catch (state.ctx) {
2689 found = 0;
2691 if (page) {
2692 fz_drop_page (state.ctx, &page->super);
2695 else {
2696 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2697 found = !!fz_load_links (state.ctx, page);
2698 fz_drop_page (state.ctx, page);
2701 if (found) {
2702 ret_v = caml_alloc_small (1, 1);
2703 Field (ret_v, 0) = Val_int (i);
2704 goto unlock;
2707 unlock:
2708 unlock (__func__);
2709 CAMLreturn (ret_v);
2712 enum { dir_first, dir_last };
2713 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2715 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2717 CAMLparam2 (ptr_v, dir_v);
2718 CAMLlocal2 (ret_v, pos_v);
2719 struct page *page;
2720 int dirtag, i, slinkindex;
2721 struct slink *found = NULL ,*slink;
2722 char *s = String_val (ptr_v);
2724 page = parse_pointer (__func__, s);
2725 ret_v = Val_int (0);
2726 lock (__func__);
2727 ensureslinks (page);
2729 if (Is_block (dir_v)) {
2730 dirtag = Tag_val (dir_v);
2731 switch (dirtag) {
2732 case dir_first_visible:
2734 int x0, y0, dir, first_index, last_index;
2736 pos_v = Field (dir_v, 0);
2737 x0 = Int_val (Field (pos_v, 0));
2738 y0 = Int_val (Field (pos_v, 1));
2739 dir = Int_val (Field (pos_v, 2));
2741 if (dir >= 0) {
2742 dir = 1;
2743 first_index = 0;
2744 last_index = page->slinkcount;
2746 else {
2747 first_index = page->slinkcount - 1;
2748 last_index = -1;
2751 for (i = first_index; i != last_index; i += dir) {
2752 slink = &page->slinks[i];
2753 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2754 found = slink;
2755 break;
2759 break;
2761 case dir_left:
2762 slinkindex = Int_val (Field (dir_v, 0));
2763 found = &page->slinks[slinkindex];
2764 for (i = slinkindex - 1; i >= 0; --i) {
2765 slink = &page->slinks[i];
2766 if (slink->bbox.x0 < found->bbox.x0) {
2767 found = slink;
2768 break;
2771 break;
2773 case dir_right:
2774 slinkindex = Int_val (Field (dir_v, 0));
2775 found = &page->slinks[slinkindex];
2776 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2777 slink = &page->slinks[i];
2778 if (slink->bbox.x0 > found->bbox.x0) {
2779 found = slink;
2780 break;
2783 break;
2785 case dir_down:
2786 slinkindex = Int_val (Field (dir_v, 0));
2787 found = &page->slinks[slinkindex];
2788 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2789 slink = &page->slinks[i];
2790 if (slink->bbox.y0 >= found->bbox.y0) {
2791 found = slink;
2792 break;
2795 break;
2797 case dir_up:
2798 slinkindex = Int_val (Field (dir_v, 0));
2799 found = &page->slinks[slinkindex];
2800 for (i = slinkindex - 1; i >= 0; --i) {
2801 slink = &page->slinks[i];
2802 if (slink->bbox.y0 <= found->bbox.y0) {
2803 found = slink;
2804 break;
2807 break;
2810 else {
2811 dirtag = Int_val (dir_v);
2812 switch (dirtag) {
2813 case dir_first:
2814 found = page->slinks;
2815 break;
2817 case dir_last:
2818 if (page->slinks) {
2819 found = page->slinks + (page->slinkcount - 1);
2821 break;
2824 if (found) {
2825 ret_v = caml_alloc_small (2, 1);
2826 Field (ret_v, 0) = Val_int (found - page->slinks);
2829 unlock (__func__);
2830 CAMLreturn (ret_v);
2833 enum { uuri, utext, uannot };
2835 CAMLprim value ml_getlink (value ptr_v, value n_v)
2837 CAMLparam2 (ptr_v, n_v);
2838 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2839 fz_link *link;
2840 struct page *page;
2841 char *s = String_val (ptr_v);
2842 struct slink *slink;
2844 ret_v = Val_int (0);
2845 page = parse_pointer (__func__, s);
2847 lock (__func__);
2848 ensureslinks (page);
2849 slink = &page->slinks[Int_val (n_v)];
2850 if (slink->tag == SLINK) {
2851 link = slink->u.link;
2852 str_v = caml_copy_string (link->uri);
2853 ret_v = caml_alloc_small (1, uuri);
2854 Field (ret_v, 0) = str_v;
2856 else {
2857 ret_v = caml_alloc_small (1, uannot);
2858 tup_v = caml_alloc_tuple (2);
2859 Field (ret_v, 0) = tup_v;
2860 Field (tup_v, 0) = ptr_v;
2861 Field (tup_v, 1) = n_v;
2863 unlock (__func__);
2865 CAMLreturn (ret_v);
2868 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2870 CAMLparam2 (ptr_v, n_v);
2871 pdf_document *pdf;
2872 const char *contents = "";
2874 lock (__func__);
2875 pdf = pdf_specifics (state.ctx, state.doc);
2876 if (pdf) {
2877 char *s = String_val (ptr_v);
2878 struct page *page;
2879 struct slink *slink;
2881 page = parse_pointer (__func__, s);
2882 slink = &page->slinks[Int_val (n_v)];
2883 contents = pdf_annot_contents (state.ctx,
2884 (pdf_annot *) slink->u.annot);
2886 unlock (__func__);
2887 CAMLreturn (caml_copy_string (contents));
2890 CAMLprim value ml_getlinkcount (value ptr_v)
2892 CAMLparam1 (ptr_v);
2893 struct page *page;
2894 char *s = String_val (ptr_v);
2896 page = parse_pointer (__func__, s);
2897 CAMLreturn (Val_int (page->slinkcount));
2900 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2902 CAMLparam2 (ptr_v, n_v);
2903 CAMLlocal1 (ret_v);
2904 struct page *page;
2905 struct slink *slink;
2906 char *s = String_val (ptr_v);
2908 page = parse_pointer (__func__, s);
2909 ret_v = caml_alloc_tuple (4);
2910 lock (__func__);
2911 ensureslinks (page);
2913 slink = &page->slinks[Int_val (n_v)];
2914 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2915 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2916 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2917 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2918 unlock (__func__);
2919 CAMLreturn (ret_v);
2922 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2924 CAMLparam3 (ptr_v, x_v, y_v);
2925 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2926 fz_link *link;
2927 struct annot *annot;
2928 struct page *page;
2929 char *ptr = String_val (ptr_v);
2930 int x = Int_val (x_v), y = Int_val (y_v);
2931 struct pagedim *pdim;
2933 ret_v = Val_int (0);
2934 if (trylock (__func__)) {
2935 goto done;
2938 page = parse_pointer (__func__, ptr);
2939 pdim = &state.pagedims[page->pdimno];
2940 x += pdim->bounds.x0;
2941 y += pdim->bounds.y0;
2944 annot = getannot (page, x, y);
2945 if (annot) {
2946 int i, n = -1;
2948 ensureslinks (page);
2949 for (i = 0; i < page->slinkcount; ++i) {
2950 if (page->slinks[i].tag == SANNOT
2951 && page->slinks[i].u.annot == annot->annot) {
2952 n = i;
2953 break;
2956 ret_v = caml_alloc_small (1, uannot);
2957 tup_v = caml_alloc_tuple (2);
2958 Field (ret_v, 0) = tup_v;
2959 Field (tup_v, 0) = ptr_v;
2960 Field (tup_v, 1) = Val_int (n);
2961 goto unlock;
2965 link = getlink (page, x, y);
2966 if (link) {
2967 str_v = caml_copy_string (link->uri);
2968 ret_v = caml_alloc_small (1, uuri);
2969 Field (ret_v, 0) = str_v;
2971 else {
2972 fz_rect *b;
2973 fz_stext_block *block;
2975 ensuretext (page);
2977 for (block = page->text->first_block; block; block = block->next) {
2978 fz_stext_line *line;
2980 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2981 b = &block->bbox;
2982 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2983 continue;
2985 for (line = block->u.t.first_line; line; line = line->next) {
2986 fz_stext_char *ch;
2988 b = &line->bbox;
2989 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2990 continue;
2992 for (ch = line->first_char; ch; ch = ch->next) {
2993 b = &ch->bbox;
2995 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
2996 const char *n2 = fz_font_name (state.ctx, ch->font);
2997 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2998 ch->font);
3000 if (!n2) n2 = "<unknown font>";
3002 if (face && face->family_name) {
3003 char *s;
3004 char *n1 = face->family_name;
3005 size_t l1 = strlen (n1);
3006 size_t l2 = strlen (n2);
3008 if (l1 != l2 || memcmp (n1, n2, l1)) {
3009 s = malloc (l1 + l2 + 2);
3010 if (s) {
3011 memcpy (s, n2, l2);
3012 s[l2] = '=';
3013 memcpy (s + l2 + 1, n1, l1 + 1);
3014 str_v = caml_copy_string (s);
3015 free (s);
3019 if (str_v == Val_unit) {
3020 str_v = caml_copy_string (n2);
3022 ret_v = caml_alloc_small (1, utext);
3023 Field (ret_v, 0) = str_v;
3024 goto unlock;
3030 unlock:
3031 unlock (__func__);
3033 done:
3034 CAMLreturn (ret_v);
3037 enum { mark_page, mark_block, mark_line, mark_word };
3039 static int uninteresting (int c)
3041 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3042 || ispunct (c);
3045 CAMLprim void ml_clearmark (value ptr_v)
3047 CAMLparam1 (ptr_v);
3048 char *s = String_val (ptr_v);
3049 struct page *page;
3051 if (trylock (__func__)) {
3052 goto done;
3055 page = parse_pointer (__func__, s);
3056 page->fmark.ch = NULL;
3057 page->lmark.ch = NULL;
3059 unlock (__func__);
3060 done:
3061 CAMLreturn0;
3064 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3066 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3067 CAMLlocal1 (ret_v);
3068 fz_rect *b;
3069 struct page *page;
3070 fz_stext_line *line;
3071 fz_stext_block *block;
3072 struct pagedim *pdim;
3073 int mark = Int_val (mark_v);
3074 char *s = String_val (ptr_v);
3075 int x = Int_val (x_v), y = Int_val (y_v);
3077 ret_v = Val_bool (0);
3078 if (trylock (__func__)) {
3079 goto done;
3082 page = parse_pointer (__func__, s);
3083 pdim = &state.pagedims[page->pdimno];
3085 ensuretext (page);
3087 if (mark == mark_page) {
3088 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3089 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3090 ret_v = Val_bool (1);
3091 goto unlock;
3094 x += pdim->bounds.x0;
3095 y += pdim->bounds.y0;
3097 for (block = page->text->first_block; block; block = block->next) {
3098 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3099 b = &block->bbox;
3100 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3101 continue;
3103 if (mark == mark_block) {
3104 page->fmark.ch = block->u.t.first_line->first_char;
3105 page->lmark.ch = block->u.t.last_line->last_char;
3106 ret_v = Val_bool (1);
3107 goto unlock;
3110 for (line = block->u.t.first_line; line; line = line->next) {
3111 fz_stext_char *ch;
3113 b = &line->bbox;
3114 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3115 continue;
3117 if (mark == mark_line) {
3118 page->fmark.ch = line->first_char;
3119 page->lmark.ch = line->last_char;
3120 ret_v = Val_bool (1);
3121 goto unlock;
3124 for (ch = line->first_char; ch; ch = ch->next) {
3125 fz_stext_char *ch2, *first = NULL, *last = NULL;
3126 b = &ch->bbox;
3127 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3128 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3129 if (uninteresting (ch2->c)) first = NULL;
3130 else if (!first) first = ch2;
3132 for (ch2 = ch; ch2; ch2 = ch2->next) {
3133 if (uninteresting (ch2->c)) break;
3134 last = ch2;
3137 page->fmark.ch = first;
3138 page->lmark.ch = last;
3139 ret_v = Val_bool (1);
3140 goto unlock;
3145 unlock:
3146 if (!Bool_val (ret_v)) {
3147 page->fmark.ch = NULL;
3148 page->lmark.ch = NULL;
3150 unlock (__func__);
3152 done:
3153 CAMLreturn (ret_v);
3156 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3158 CAMLparam3 (ptr_v, x_v, y_v);
3159 CAMLlocal2 (ret_v, res_v);
3160 fz_rect *b = NULL;
3161 struct page *page;
3162 struct pagedim *pdim;
3163 fz_stext_block *block;
3164 char *s = String_val (ptr_v);
3165 int x = Int_val (x_v), y = Int_val (y_v);
3167 ret_v = Val_int (0);
3168 if (trylock (__func__)) {
3169 goto done;
3172 page = parse_pointer (__func__, s);
3173 pdim = &state.pagedims[page->pdimno];
3174 x += pdim->bounds.x0;
3175 y += pdim->bounds.y0;
3177 ensuretext (page);
3179 for (block = page->text->first_block; block; block = block->next) {
3180 switch (block->type) {
3181 case FZ_STEXT_BLOCK_TEXT:
3182 b = &block->bbox;
3183 break;
3185 case FZ_STEXT_BLOCK_IMAGE:
3186 b = &block->bbox;
3187 break;
3189 default:
3190 continue;
3193 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3194 break;
3195 b = NULL;
3197 if (b) {
3198 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3199 ret_v = caml_alloc_small (1, 1);
3200 Store_double_field (res_v, 0, b->x0);
3201 Store_double_field (res_v, 1, b->x1);
3202 Store_double_field (res_v, 2, b->y0);
3203 Store_double_field (res_v, 3, b->y1);
3204 Field (ret_v, 0) = res_v;
3206 unlock (__func__);
3208 done:
3209 CAMLreturn (ret_v);
3212 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3214 CAMLparam2 (ptr_v, rect_v);
3215 fz_rect b;
3216 struct page *page;
3217 struct pagedim *pdim;
3218 char *s = String_val (ptr_v);
3219 int x0, x1, y0, y1;
3220 fz_stext_char *ch;
3221 fz_stext_line *line;
3222 fz_stext_block *block;
3223 fz_stext_char *fc, *lc;
3225 if (trylock (__func__)) {
3226 goto done;
3229 page = parse_pointer (__func__, s);
3230 ensuretext (page);
3232 pdim = &state.pagedims[page->pdimno];
3233 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3234 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3235 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3236 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3238 if (y0 > y1) {
3239 int t = y0;
3240 y0 = y1;
3241 y1 = t;
3242 x0 = x1;
3243 x1 = t;
3246 fc = page->fmark.ch;
3247 lc = page->lmark.ch;
3249 for (block = page->text->first_block; block; block = block->next) {
3250 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3251 for (line = block->u.t.first_line; line; line = line->next) {
3252 for (ch = line->first_char; ch; ch = ch->next) {
3253 b = ch->bbox;
3254 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3255 fc = ch;
3257 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3258 lc = ch;
3263 if (x1 < x0 && fc == lc) {
3264 fz_stext_char *t;
3266 t = fc;
3267 fc = lc;
3268 lc = t;
3271 page->fmark.ch = fc;
3272 page->lmark.ch = lc;
3274 unlock (__func__);
3276 done:
3277 CAMLreturn0;
3280 static int pipechar (FILE *f, fz_stext_char *ch)
3282 char buf[4];
3283 int len, ret;
3285 len = fz_runetochar (buf, ch->c);
3286 ret = fwrite (buf, len, 1, f);
3287 if (ret != 1) {
3288 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3289 len, ret, strerror (errno));
3290 return -1;
3292 return 0;
3295 #ifdef __CYGWIN__
3296 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3298 caml_failwith ("ml_popen not implemented under Cygwin");
3300 #else
3301 CAMLprim value ml_spawn (value command_v, value fds_v)
3303 CAMLparam2 (command_v, fds_v);
3304 CAMLlocal2 (l_v, tup_v);
3305 int ret, ret1;
3306 pid_t pid;
3307 char *msg = NULL;
3308 value earg_v = Nothing;
3309 posix_spawnattr_t attr;
3310 posix_spawn_file_actions_t fa;
3311 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3313 argv[2] = String_val (command_v);
3315 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3316 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3319 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3320 msg = "posix_spawnattr_init";
3321 goto fail1;
3324 #ifdef POSIX_SPAWN_USEVFORK
3325 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3326 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3327 goto fail;
3329 #endif
3331 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3332 int fd1, fd2;
3334 tup_v = Field (l_v, 0);
3335 fd1 = Int_val (Field (tup_v, 0));
3336 fd2 = Int_val (Field (tup_v, 1));
3337 if (fd2 < 0) {
3338 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3339 msg = "posix_spawn_file_actions_addclose";
3340 earg_v = tup_v;
3341 goto fail;
3344 else {
3345 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3346 msg = "posix_spawn_file_actions_adddup2";
3347 earg_v = tup_v;
3348 goto fail;
3353 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3354 msg = "posix_spawn";
3355 goto fail;
3358 fail:
3359 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3360 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3363 fail1:
3364 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3365 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3366 strerror (ret1));
3369 if (msg)
3370 unix_error (ret, msg, earg_v);
3372 CAMLreturn (Val_int (pid));
3374 #endif
3376 CAMLprim value ml_hassel (value ptr_v)
3378 CAMLparam1 (ptr_v);
3379 CAMLlocal1 (ret_v);
3380 struct page *page;
3381 char *s = String_val (ptr_v);
3383 ret_v = Val_bool (0);
3384 if (trylock (__func__)) {
3385 goto done;
3388 page = parse_pointer (__func__, s);
3389 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3390 unlock (__func__);
3391 done:
3392 CAMLreturn (ret_v);
3395 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3397 CAMLparam2 (fd_v, ptr_v);
3398 FILE *f;
3399 int seen = 0;
3400 struct page *page;
3401 fz_stext_line *line;
3402 fz_stext_block *block;
3403 int fd = Int_val (fd_v);
3404 char *s = String_val (ptr_v);
3406 if (trylock (__func__)) {
3407 goto done;
3410 page = parse_pointer (__func__, s);
3412 if (!page->fmark.ch || !page->lmark.ch) {
3413 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3414 goto unlock;
3417 f = fdopen (fd, "w");
3418 if (!f) {
3419 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3420 fd, strerror (errno));
3421 f = stdout;
3424 for (block = page->text->first_block; block; block = block->next) {
3425 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3426 for (line = block->u.t.first_line; line; line = line->next) {
3427 fz_stext_char *ch;
3428 for (ch = line->first_char; ch; ch = ch->next) {
3429 if (seen || ch == page->fmark.ch) {
3430 do {
3431 pipechar (f, ch);
3432 if (ch == page->lmark.ch) goto close;
3433 } while ((ch = ch->next));
3434 seen = 1;
3435 break;
3438 if (seen) fputc ('\n', f);
3441 close:
3442 if (f != stdout) {
3443 int ret = fclose (f);
3444 fd = -1;
3445 if (ret == -1) {
3446 if (errno != ECHILD) {
3447 fprintf (stderr, "failed to close sel pipe: %s\n",
3448 strerror (errno));
3452 unlock:
3453 unlock (__func__);
3455 done:
3456 if (fd >= 0) {
3457 if (close (fd)) {
3458 fprintf (stderr, "failed to close sel pipe: %s\n",
3459 strerror (errno));
3462 CAMLreturn0;
3465 CAMLprim value ml_getpdimrect (value pagedimno_v)
3467 CAMLparam1 (pagedimno_v);
3468 CAMLlocal1 (ret_v);
3469 int pagedimno = Int_val (pagedimno_v);
3470 fz_rect box;
3472 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3473 if (trylock (__func__)) {
3474 box = fz_empty_rect;
3476 else {
3477 box = state.pagedims[pagedimno].mediabox;
3478 unlock (__func__);
3481 Store_double_field (ret_v, 0, box.x0);
3482 Store_double_field (ret_v, 1, box.x1);
3483 Store_double_field (ret_v, 2, box.y0);
3484 Store_double_field (ret_v, 3, box.y1);
3486 CAMLreturn (ret_v);
3489 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3490 value dw_v, value cols_v)
3492 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3493 CAMLlocal1 (ret_v);
3494 int i;
3495 double zoom = -1.;
3496 double maxh = 0.0;
3497 struct pagedim *p;
3498 double winw = Int_val (winw_v);
3499 double winh = Int_val (winh_v);
3500 double dw = Int_val (dw_v);
3501 double cols = Int_val (cols_v);
3502 double pw = 1.0, ph = 1.0;
3504 if (trylock (__func__)) {
3505 goto done;
3508 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3509 double w = p->pagebox.x1 / cols;
3510 double h = p->pagebox.y1;
3511 if (h > maxh) {
3512 maxh = h;
3513 ph = h;
3514 if (state.fitmodel != FitProportional) pw = w;
3516 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3519 zoom = (((winh / ph) * pw) + dw) / winw;
3520 unlock (__func__);
3521 done:
3522 ret_v = caml_copy_double (zoom);
3523 CAMLreturn (ret_v);
3526 CAMLprim value ml_getmaxw (value unit_v)
3528 CAMLparam1 (unit_v);
3529 CAMLlocal1 (ret_v);
3530 int i;
3531 double maxw = -1.;
3532 struct pagedim *p;
3534 if (trylock (__func__)) {
3535 goto done;
3538 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3539 double w = p->pagebox.x1;
3540 maxw = fz_max (maxw, w);
3543 unlock (__func__);
3544 done:
3545 ret_v = caml_copy_double (maxw);
3546 CAMLreturn (ret_v);
3549 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3551 CAMLparam4 (pt_v, x_v, y_v, string_v);
3552 CAMLlocal1 (ret_v);
3553 int pt = Int_val(pt_v);
3554 int x = Int_val (x_v);
3555 int y = Int_val (y_v);
3556 double w;
3558 w = draw_string (state.face, pt, x, y, String_val (string_v));
3559 ret_v = caml_copy_double (w);
3560 CAMLreturn (ret_v);
3563 CAMLprim value ml_measure_string (value pt_v, value string_v)
3565 CAMLparam2 (pt_v, string_v);
3566 CAMLlocal1 (ret_v);
3567 int pt = Int_val (pt_v);
3568 double w;
3570 w = measure_string (state.face, pt, String_val (string_v));
3571 ret_v = caml_copy_double (w);
3572 CAMLreturn (ret_v);
3575 CAMLprim value ml_getpagebox (value opaque_v)
3577 CAMLparam1 (opaque_v);
3578 CAMLlocal1 (ret_v);
3579 fz_rect rect;
3580 fz_irect bbox;
3581 fz_matrix ctm;
3582 fz_device *dev;
3583 char *s = String_val (opaque_v);
3584 struct page *page = parse_pointer (__func__, s);
3586 ret_v = caml_alloc_tuple (4);
3587 dev = fz_new_bbox_device (state.ctx, &rect);
3589 ctm = pagectm (page);
3590 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3592 fz_close_device (state.ctx, dev);
3593 fz_drop_device (state.ctx, dev);
3594 fz_round_rect (&bbox, &rect);
3595 Field (ret_v, 0) = Val_int (bbox.x0);
3596 Field (ret_v, 1) = Val_int (bbox.y0);
3597 Field (ret_v, 2) = Val_int (bbox.x1);
3598 Field (ret_v, 3) = Val_int (bbox.y1);
3600 CAMLreturn (ret_v);
3603 CAMLprim void ml_setaalevel (value level_v)
3605 CAMLparam1 (level_v);
3607 state.aalevel = Int_val (level_v);
3608 CAMLreturn0;
3611 #ifndef __COCOA__
3612 #pragma GCC diagnostic push
3613 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3614 #include <X11/Xlib.h>
3615 #include <X11/cursorfont.h>
3616 #pragma GCC diagnostic pop
3618 #ifdef USE_EGL
3619 #include <EGL/egl.h>
3620 #else
3621 #include <GL/glx.h>
3622 #endif
3624 static const int shapes[] = {
3625 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3628 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3630 static struct {
3631 Window wid;
3632 Display *dpy;
3633 #ifdef USE_EGL
3634 EGLContext ctx;
3635 EGLConfig conf;
3636 EGLSurface win;
3637 EGLDisplay *edpy;
3638 #else
3639 GLXContext ctx;
3640 #endif
3641 XVisualInfo *visual;
3642 Cursor curs[CURS_COUNT];
3643 } glx;
3646 static void initcurs (void)
3648 for (size_t n = 0; n < CURS_COUNT; ++n) {
3649 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3653 CAMLprim void ml_setbgcol (value color_v)
3655 CAMLparam1 (color_v);
3656 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3657 CAMLreturn0;
3660 #ifdef USE_EGL
3661 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3663 CAMLparam3 (display_v, wid_v, screen_v);
3664 int major, minor;
3665 int num_conf;
3666 EGLint visid;
3667 EGLint attribs[] = {
3668 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3669 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3670 EGL_NONE
3672 EGLConfig conf;
3674 glx.dpy = XOpenDisplay (String_val (display_v));
3675 if (!glx.dpy) {
3676 caml_failwith ("XOpenDisplay");
3679 eglBindAPI (EGL_OPENGL_API);
3681 glx.edpy = eglGetDisplay (glx.dpy);
3682 if (glx.edpy == EGL_NO_DISPLAY) {
3683 caml_failwith ("eglGetDisplay");
3686 if (!eglInitialize (glx.edpy, &major, &minor)) {
3687 caml_failwith ("eglInitialize");
3690 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3691 !num_conf) {
3692 caml_failwith ("eglChooseConfig");
3695 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3696 caml_failwith ("eglGetConfigAttrib");
3699 glx.conf = conf;
3700 initcurs ();
3702 glx.wid = Int_val (wid_v);
3703 CAMLreturn (Val_int (visid));
3706 CAMLprim void ml_glxcompleteinit (value unit_v)
3708 CAMLparam1 (unit_v);
3710 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3711 if (!glx.ctx) {
3712 caml_failwith ("eglCreateContext");
3715 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3716 glx.wid, NULL);
3717 if (glx.win == EGL_NO_SURFACE) {
3718 caml_failwith ("eglCreateWindowSurface");
3721 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3722 glx.ctx = NULL;
3723 caml_failwith ("eglMakeCurrent");
3725 CAMLreturn0;
3727 #else
3728 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3730 CAMLparam3 (display_v, wid_v, screen_v);
3732 glx.dpy = XOpenDisplay (String_val (display_v));
3733 if (!glx.dpy) {
3734 caml_failwith ("XOpenDisplay");
3737 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3738 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3739 if (!glx.visual) {
3740 XCloseDisplay (glx.dpy);
3741 caml_failwith ("glXChooseVisual");
3744 initcurs ();
3746 glx.wid = Int_val (wid_v);
3747 CAMLreturn (Val_int (glx.visual->visualid));
3750 CAMLprim void ml_glxcompleteinit (value unit_v)
3752 CAMLparam1 (unit_v);
3754 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3755 if (!glx.ctx) {
3756 caml_failwith ("glXCreateContext");
3759 XFree (glx.visual);
3760 glx.visual = NULL;
3762 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3763 glXDestroyContext (glx.dpy, glx.ctx);
3764 glx.ctx = NULL;
3765 caml_failwith ("glXMakeCurrent");
3767 CAMLreturn0;
3769 #endif
3771 CAMLprim void ml_setcursor (value cursor_v)
3773 CAMLparam1 (cursor_v);
3774 size_t cursn = Int_val (cursor_v);
3776 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3777 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3778 XFlush (glx.dpy);
3779 CAMLreturn0;
3782 CAMLprim void ml_swapb (value unit_v)
3784 CAMLparam1 (unit_v);
3785 #ifdef USE_EGL
3786 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3787 caml_failwith ("eglSwapBuffers");
3789 #else
3790 glXSwapBuffers (glx.dpy, glx.wid);
3791 #endif
3792 CAMLreturn0;
3795 #include "keysym2ucs.c"
3797 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3799 CAMLparam1 (keysym_v);
3800 CAMLlocal1 (str_v);
3801 KeySym keysym = Int_val (keysym_v);
3802 Rune rune;
3803 int len;
3804 char buf[5];
3806 rune = keysym2ucs (keysym);
3807 len = fz_runetochar (buf, rune);
3808 buf[len] = 0;
3809 str_v = caml_copy_string (buf);
3810 CAMLreturn (str_v);
3812 #else
3813 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3815 CAMLparam1 (keysym_v);
3816 CAMLlocal1 (str_v);
3817 long ucs_v = Long_val (keysym_v);
3818 int len;
3819 char buf[5];
3821 len = fz_runetochar (buf, ucs_v);
3822 buf[len] = 0;
3823 str_v = caml_copy_string (buf);
3824 CAMLreturn (str_v);
3826 #endif
3828 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3830 CAMLprim value ml_platform (value unit_v)
3832 CAMLparam1 (unit_v);
3833 CAMLlocal2 (tup_v, arr_v);
3834 int platid = piunknown;
3835 struct utsname buf;
3837 #if defined __linux__
3838 platid = pilinux;
3839 #elif defined __CYGWIN__
3840 platid = picygwin;
3841 #elif defined __DragonFly__ || defined __FreeBSD__
3842 || defined __OpenBSD__ || defined __NetBSD__
3843 platid = pibsd;
3844 #elif defined __sun__
3845 platid = pisun;
3846 #elif defined __APPLE__
3847 platid = piosx;
3848 #endif
3849 if (uname (&buf)) err (1, "uname");
3851 tup_v = caml_alloc_tuple (2);
3853 char const *sar[] = {
3854 buf.sysname,
3855 buf.release,
3856 buf.version,
3857 buf.machine,
3858 NULL
3860 arr_v = caml_copy_string_array (sar);
3862 Field (tup_v, 0) = Val_int (platid);
3863 Field (tup_v, 1) = arr_v;
3864 CAMLreturn (tup_v);
3867 CAMLprim void ml_cloexec (value fd_v)
3869 CAMLparam1 (fd_v);
3870 int fd = Int_val (fd_v);
3872 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3873 uerror ("fcntl", Nothing);
3875 CAMLreturn0;
3878 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3880 CAMLparam2 (w_v, h_v);
3881 CAMLlocal1 (ret_v);
3882 struct bo *pbo;
3883 int w = Int_val (w_v);
3884 int h = Int_val (h_v);
3885 int cs = Int_val (cs_v);
3887 if (state.bo_usable) {
3888 pbo = calloc (sizeof (*pbo), 1);
3889 if (!pbo) {
3890 err (1, "calloc pbo");
3893 switch (cs) {
3894 case 0:
3895 case 1:
3896 pbo->size = w*h*4;
3897 break;
3898 case 2:
3899 pbo->size = w*h*2;
3900 break;
3901 default:
3902 errx (1, "%s: invalid colorspace %d", __func__, cs);
3905 state.glGenBuffersARB (1, &pbo->id);
3906 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3907 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3908 NULL, GL_STREAM_DRAW);
3909 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3910 GL_READ_WRITE);
3911 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3912 if (!pbo->ptr) {
3913 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3914 state.glDeleteBuffersARB (1, &pbo->id);
3915 free (pbo);
3916 ret_v = caml_copy_string ("0");
3918 else {
3919 int res;
3920 char *s;
3922 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3923 if (res < 0) {
3924 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3926 s = malloc (res+1);
3927 if (!s) {
3928 err (1, "malloc %d bytes failed", res+1);
3930 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3931 if (res < 0) {
3932 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3934 ret_v = caml_copy_string (s);
3935 free (s);
3938 else {
3939 ret_v = caml_copy_string ("0");
3941 CAMLreturn (ret_v);
3944 CAMLprim void ml_freepbo (value s_v)
3946 CAMLparam1 (s_v);
3947 char *s = String_val (s_v);
3948 struct tile *tile = parse_pointer (__func__, s);
3950 if (tile->pbo) {
3951 state.glDeleteBuffersARB (1, &tile->pbo->id);
3952 tile->pbo->id = -1;
3953 tile->pbo->ptr = NULL;
3954 tile->pbo->size = -1;
3956 CAMLreturn0;
3959 CAMLprim void ml_unmappbo (value s_v)
3961 CAMLparam1 (s_v);
3962 char *s = String_val (s_v);
3963 struct tile *tile = parse_pointer (__func__, s);
3965 if (tile->pbo) {
3966 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3967 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3968 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3970 tile->pbo->ptr = NULL;
3971 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3973 CAMLreturn0;
3976 static void setuppbo (void)
3978 #ifdef __COCOA__
3979 static CFBundleRef framework = NULL;
3980 if (framework == NULL)
3981 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3982 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3983 #else
3984 #ifdef USE_EGL
3985 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
3986 #else
3987 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
3988 #endif
3989 state.bo_usable = GGPA (glBindBufferARB)
3990 && GGPA (glUnmapBufferARB)
3991 && GGPA (glMapBufferARB)
3992 && GGPA (glBufferDataARB)
3993 && GGPA (glGenBuffersARB)
3994 && GGPA (glDeleteBuffersARB);
3995 #endif
3996 #undef GGPA
3999 CAMLprim value ml_bo_usable (value unit_v)
4001 CAMLparam1 (unit_v);
4002 CAMLreturn (Val_bool (state.bo_usable));
4005 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4007 CAMLparam3 (ptr_v, x_v, y_v);
4008 CAMLlocal2 (ret_v, tup_v);
4009 struct page *page;
4010 char *s = String_val (ptr_v);
4011 int x = Int_val (x_v), y = Int_val (y_v);
4012 struct pagedim *pdim;
4013 fz_point p;
4014 fz_matrix ctm;
4016 page = parse_pointer (__func__, s);
4017 pdim = &state.pagedims[page->pdimno];
4019 ret_v = Val_int (0);
4020 if (trylock (__func__)) {
4021 goto done;
4024 if (pdf_specifics (state.ctx, state.doc)) {
4025 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4026 ctm = state.pagedims[page->pdimno].tctm;
4028 else {
4029 ctm = fz_identity;
4031 p.x = x + pdim->bounds.x0;
4032 p.y = y + pdim->bounds.y0;
4034 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4035 fz_invert_matrix (&ctm, &ctm);
4036 fz_transform_point (&p, &ctm);
4038 tup_v = caml_alloc_tuple (2);
4039 ret_v = caml_alloc_small (1, 1);
4040 Field (tup_v, 0) = Val_int (p.x);
4041 Field (tup_v, 1) = Val_int (p.y);
4042 Field (ret_v, 0) = tup_v;
4044 unlock (__func__);
4045 done:
4046 CAMLreturn (ret_v);
4049 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4050 value x_v, value y_v)
4052 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4053 CAMLlocal1 (ret_v);
4054 struct page *page;
4055 char *s = String_val (ptr_v);
4056 int pageno = Int_val (pageno_v);
4057 int pdimno = Int_val (pdimno_v);
4058 double x = Double_val (x_v), y = Double_val (y_v);
4059 struct pagedim *pdim;
4060 fz_point p;
4061 fz_matrix ctm;
4063 ret_v = Val_int (0);
4064 lock (__func__);
4066 if (!*s) {
4067 page = loadpage (pageno, pdimno);
4069 else {
4070 page = parse_pointer (__func__, s);
4072 pdim = &state.pagedims[pdimno];
4074 if (pdf_specifics (state.ctx, state.doc)) {
4075 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4076 ctm = state.pagedims[page->pdimno].tctm;
4078 else {
4079 ctm = fz_identity;
4081 p.x = x + pdim->bounds.x0;
4082 p.y = y + pdim->bounds.y0;
4084 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4085 fz_transform_point (&p, &ctm);
4087 ret_v = caml_alloc_tuple (2);
4088 Field (ret_v, 0) = caml_copy_double (p.x);
4089 Field (ret_v, 1) = caml_copy_double (p.y);
4091 if (!*s) {
4092 freepage (page);
4094 unlock (__func__);
4095 CAMLreturn (ret_v);
4098 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4099 value contents_v)
4101 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4102 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4104 if (pdf) {
4105 pdf_annot *annot;
4106 struct page *page;
4107 fz_point p;
4108 char *s = String_val (ptr_v);
4110 page = parse_pointer (__func__, s);
4111 annot = pdf_create_annot (state.ctx,
4112 pdf_page_from_fz_page (state.ctx,
4113 page->fzpage),
4114 PDF_ANNOT_TEXT);
4115 p.x = Int_val (x_v);
4116 p.y = Int_val (y_v);
4117 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4118 pdf_set_text_annot_position (state.ctx, annot, p);
4119 state.dirty = 1;
4121 CAMLreturn0;
4124 CAMLprim void ml_delannot (value ptr_v, value n_v)
4126 CAMLparam2 (ptr_v, n_v);
4127 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4129 if (pdf) {
4130 struct page *page;
4131 char *s = String_val (ptr_v);
4132 struct slink *slink;
4134 page = parse_pointer (__func__, s);
4135 slink = &page->slinks[Int_val (n_v)];
4136 pdf_delete_annot (state.ctx,
4137 pdf_page_from_fz_page (state.ctx, page->fzpage),
4138 (pdf_annot *) slink->u.annot);
4139 state.dirty = 1;
4141 CAMLreturn0;
4144 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4146 CAMLparam3 (ptr_v, n_v, str_v);
4147 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4149 if (pdf) {
4150 struct page *page;
4151 char *s = String_val (ptr_v);
4152 struct slink *slink;
4154 page = parse_pointer (__func__, s);
4155 slink = &page->slinks[Int_val (n_v)];
4156 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4157 String_val (str_v));
4158 state.dirty = 1;
4160 CAMLreturn0;
4163 CAMLprim value ml_hasunsavedchanges (value unit_v)
4165 CAMLparam1 (unit_v);
4166 CAMLreturn (Val_bool (state.dirty));
4169 CAMLprim void ml_savedoc (value path_v)
4171 CAMLparam1 (path_v);
4172 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4174 if (pdf) {
4175 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4177 CAMLreturn0;
4180 static void makestippletex (void)
4182 const char pixels[] = "\xff\xff\0\0";
4183 glGenTextures (1, &state.stid);
4184 glBindTexture (GL_TEXTURE_1D, state.stid);
4185 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4186 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4187 glTexImage1D (
4188 GL_TEXTURE_1D,
4190 GL_ALPHA,
4193 GL_ALPHA,
4194 GL_UNSIGNED_BYTE,
4195 pixels
4199 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4201 return caml_copy_string (FZ_VERSION);
4204 CAMLprim void ml_init (value csock_v, value params_v)
4206 CAMLparam2 (csock_v, params_v);
4207 CAMLlocal2 (trim_v, fuzz_v);
4208 int ret;
4209 int texcount;
4210 char *fontpath;
4211 int colorspace;
4212 int mustoresize;
4213 int haspboext;
4215 /* Without following call to setlocale mbstowcs fails for, at
4216 least, strings containing chinese symbols (δΈ­ for instance)
4217 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4218 wide character" as the reason of failure and with macOS
4219 producing bogus output) */
4220 if (setlocale (LC_CTYPE, "")) {
4221 /* Following two lines were taken from dvtm/vt.c */
4222 const char *cset = nl_langinfo (CODESET);
4223 state.utf8cs = !strcmp (cset, "UTF-8");
4225 else {
4226 fprintf (stderr, "setlocale failed\n");
4229 state.csock = Int_val (csock_v);
4230 state.rotate = Int_val (Field (params_v, 0));
4231 state.fitmodel = Int_val (Field (params_v, 1));
4232 trim_v = Field (params_v, 2);
4233 texcount = Int_val (Field (params_v, 3));
4234 state.sliceheight = Int_val (Field (params_v, 4));
4235 mustoresize = Int_val (Field (params_v, 5));
4236 colorspace = Int_val (Field (params_v, 6));
4237 fontpath = String_val (Field (params_v, 7));
4239 if (caml_string_length (Field (params_v, 8)) > 0) {
4240 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4242 if (!state.trimcachepath) {
4243 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4244 strerror (errno));
4248 haspboext = Bool_val (Field (params_v, 9));
4250 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4251 fz_register_document_handlers (state.ctx);
4253 state.trimmargins = Bool_val (Field (trim_v, 0));
4254 fuzz_v = Field (trim_v, 1);
4255 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4256 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4257 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4258 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4260 set_tex_params (colorspace);
4262 if (*fontpath) {
4263 state.face = load_font (fontpath);
4265 else {
4266 int len;
4267 const unsigned char *data;
4269 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4270 state.face = load_builtin_font (data, len);
4272 if (!state.face) _exit (1);
4274 realloctexts (texcount);
4276 if (haspboext) {
4277 setuppbo ();
4280 makestippletex ();
4282 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4283 if (ret) {
4284 errx (1, "pthread_create: %s", strerror (ret));
4287 CAMLreturn0;