More robust covered-switch-default workaround
[llpp.git] / link.c
bloba523a34291c1d10f600914c95609b5b376e82851
1 #ifdef __clang__
2 #pragma GCC diagnostic error "-Weverything"
3 #pragma GCC diagnostic ignored "-Wfloat-equal"
4 #pragma GCC diagnostic ignored "-Wpadded"
5 #pragma GCC diagnostic ignored "-Wsign-conversion"
6 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
7 #pragma GCC diagnostic ignored "-Wdocumentation"
8 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
9 #endif
11 /* lots of code c&p-ed directly from mupdf */
12 #define CAML_NAME_SPACE
13 #define FIXME 0
15 #include <errno.h>
16 #include <stdio.h>
17 #include <ctype.h>
18 #include <string.h>
19 #include <stdlib.h>
20 #include <signal.h>
22 #include <math.h>
23 #include <wchar.h>
24 #include <locale.h>
25 #include <langinfo.h>
27 #include <unistd.h>
28 #include <pthread.h>
29 #include <sys/uio.h>
30 #include <sys/time.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/utsname.h>
37 #ifdef __CYGWIN__
38 #include <cygwin/socket.h> /* FIONREAD */
39 #else
40 #include <spawn.h>
41 #endif
43 #include <regex.h>
44 #include <stdarg.h>
45 #include <limits.h>
46 #include <inttypes.h>
48 #ifdef __COCOA__
49 #include <CoreFoundation/CoreFoundation.h>
50 #endif
52 #ifdef __APPLE__
53 #include <OpenGL/gl.h>
54 #else
55 #include <GL/gl.h>
56 #endif
58 #pragma GCC diagnostic push
59 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
60 #pragma GCC diagnostic ignored "-Wpedantic"
61 #include <caml/fail.h>
62 #include <caml/alloc.h>
63 #include <caml/memory.h>
64 #include <caml/unixsupport.h>
66 #if __GNUC__ < 5 && !defined __clang__
67 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
68 clobbered diagnostics */
69 #pragma GCC diagnostic ignored "-Wclobbered"
70 #endif
72 #include <mupdf/fitz.h>
73 #include <mupdf/pdf.h>
75 #include <ft2build.h>
76 #include FT_FREETYPE_H
77 #pragma GCC diagnostic pop
79 #define PIGGYBACK
80 #define CACHE_PAGEREFS
82 #ifndef __USE_GNU
83 extern char **environ;
84 #endif
86 #if defined __GNUC__
87 #define NORETURN_ATTR __attribute__ ((noreturn))
88 #define UNUSED_ATTR __attribute__ ((unused))
89 #if !defined __clang__
90 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
91 #else
92 #define OPTIMIZE_ATTR(n)
93 #endif
94 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
95 #else
96 #define NORETURN_ATTR
97 #define UNUSED_ATTR
98 #define OPTIMIZE_ATTR(n)
99 #define GCC_FMT_ATTR(a, b)
100 #endif
102 #define FMT_s "zu"
104 #define FMT_ptr PRIxPTR
105 #define SCN_ptr SCNxPTR
106 #define FMT_ptr_cast(p) ((uintptr_t) (p))
107 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
109 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
110 err (int exitcode, const char *fmt, ...)
112 va_list ap;
113 int savederrno;
115 savederrno = errno;
116 va_start (ap, fmt);
117 vfprintf (stderr, fmt, ap);
118 va_end (ap);
119 fprintf (stderr, ": %s\n", strerror (savederrno));
120 fflush (stderr);
121 _exit (exitcode);
124 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
125 errx (int exitcode, const char *fmt, ...)
127 va_list ap;
129 va_start (ap, fmt);
130 vfprintf (stderr, fmt, ap);
131 va_end (ap);
132 fputc ('\n', stderr);
133 fflush (stderr);
134 _exit (exitcode);
137 #ifndef GL_TEXTURE_RECTANGLE_ARB
138 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
139 #endif
141 #ifdef USE_NPOT
142 #define TEXT_TYPE GL_TEXTURE_2D
143 #else
144 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
145 #endif
147 #ifndef GL_BGRA
148 #define GL_BGRA 0x80E1
149 #endif
151 #ifndef GL_UNSIGNED_INT_8_8_8_8
152 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
153 #endif
155 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
156 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
157 #endif
159 #if 0
160 #define lprintf printf
161 #else
162 #define lprintf(...)
163 #endif
165 #define ARSERT(cond) for (;;) { \
166 if (!(cond)) { \
167 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
169 break; \
172 struct slice {
173 int h;
174 int texindex;
177 struct tile {
178 int w, h;
179 int slicecount;
180 int sliceheight;
181 struct bo *pbo;
182 fz_pixmap *pixmap;
183 struct slice slices[1];
186 struct pagedim {
187 int pageno;
188 int rotate;
189 int left;
190 int tctmready;
191 fz_irect bounds;
192 fz_rect pagebox;
193 fz_rect mediabox;
194 fz_matrix ctm, zoomctm, tctm;
197 struct slink {
198 enum { SLINK, SANNOT } tag;
199 fz_irect bbox;
200 union {
201 fz_link *link;
202 fz_annot *annot;
203 } u;
206 struct annot {
207 fz_irect bbox;
208 fz_annot *annot;
211 struct page {
212 int tgen;
213 int sgen;
214 int agen;
215 int pageno;
216 int pdimno;
217 fz_stext_page *text;
218 fz_page *fzpage;
219 fz_display_list *dlist;
220 fz_link *links;
221 int slinkcount;
222 struct slink *slinks;
223 int annotcount;
224 struct annot *annots;
225 struct mark {
226 fz_stext_char *ch;
227 } fmark, lmark;
230 static struct {
231 int sliceheight;
232 struct pagedim *pagedims;
233 int pagecount;
234 int pagedimcount;
235 fz_document *doc;
236 fz_context *ctx;
237 int w, h;
239 int texindex;
240 int texcount;
241 GLuint *texids;
243 GLenum texiform;
244 GLenum texform;
245 GLenum texty;
247 fz_colorspace *colorspace;
249 struct {
250 int w, h;
251 struct slice *slice;
252 } *texowners;
254 int rotate;
255 enum { FitWidth, FitProportional, FitPage };
256 int fitmodel;
257 int trimmargins;
258 int needoutline;
259 int gen;
260 int aalevel;
262 int trimanew;
263 fz_irect trimfuzz;
264 fz_pixmap *pig;
266 pthread_t thread;
267 int csock;
268 FT_Face face;
270 char *trimcachepath;
271 int cxack;
272 int dirty;
274 GLuint stid;
276 int bo_usable;
277 GLuint boid;
279 void (*glBindBufferARB) (GLenum, GLuint);
280 GLboolean (*glUnmapBufferARB) (GLenum);
281 void *(*glMapBufferARB) (GLenum, GLenum);
282 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
283 void (*glGenBuffersARB) (GLsizei, GLuint *);
284 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
286 GLfloat texcoords[8];
287 GLfloat vertices[16];
289 #ifdef CACHE_PAGEREFS
290 struct {
291 int idx;
292 int count;
293 pdf_obj **objs;
294 pdf_document *pdf;
295 } pdflut;
296 #endif
297 int utf8cs;
298 } state;
300 struct bo {
301 GLuint id;
302 void *ptr;
303 size_t size;
306 #pragma GCC diagnostic ignored "-Wdouble-promotion"
307 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
309 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
312 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
314 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
317 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
319 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
320 m.a, m.b, m.c, m.d, m.e, m.f);
322 #pragma GCC diagnostic error "-Wdouble-promotion"
324 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
326 static void lock (const char *cap)
328 int ret = pthread_mutex_lock (&mutex);
329 if (ret) {
330 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
334 static void unlock (const char *cap)
336 int ret = pthread_mutex_unlock (&mutex);
337 if (ret) {
338 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
342 static int trylock (const char *cap)
344 int ret = pthread_mutex_trylock (&mutex);
345 if (ret && ret != EBUSY) {
346 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
348 return ret == EBUSY;
351 static void *parse_pointer (const char *cap, const char *s)
353 int ret;
354 void *ptr;
356 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
357 if (ret != 1) {
358 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
360 return ptr;
363 static double now (void)
365 struct timeval tv;
367 if (gettimeofday (&tv, NULL)) {
368 err (1, "gettimeofday");
370 return tv.tv_sec + tv.tv_usec*1e-6;
373 static int hasdata (void)
375 int ret, avail;
376 ret = ioctl (state.csock, FIONREAD, &avail);
377 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
378 return avail > 0;
381 CAMLprim value ml_hasdata (value fd_v)
383 CAMLparam1 (fd_v);
384 int ret, avail;
386 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
387 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
388 CAMLreturn (Val_bool (avail > 0));
391 static void readdata (int fd, void *p, int size)
393 ssize_t n;
395 again:
396 n = read (fd, p, size);
397 if (n - size) {
398 if (n < 0 && errno == EINTR) goto again;
399 if (!n) errx (1, "EOF while reading");
400 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
404 static void writedata (int fd, char *p, int size)
406 ssize_t n;
407 uint32_t size4 = size;
408 struct iovec iov[2] = {
409 { .iov_base = &size4, .iov_len = 4 },
410 { .iov_base = p, .iov_len = size }
413 again:
414 n = writev (fd, iov, 2);
415 if (n < 0 && errno == EINTR) goto again;
416 if (n - size - 4) {
417 if (!n) errx (1, "EOF while writing data");
418 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
422 static int readlen (int fd)
424 uint32_t u;
425 readdata (fd, &u, 4);
426 return u;
429 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
431 CAMLparam3 (fd_v, bytes_v, len_v);
432 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
433 CAMLreturn0;
436 CAMLprim value ml_rcmd (value fd_v)
438 CAMLparam1 (fd_v);
439 CAMLlocal1 (strdata_v);
440 int fd = Int_val (fd_v);
441 int len = readlen (fd);
442 strdata_v = caml_alloc_string (len);
443 readdata (fd, String_val (strdata_v), len);
444 CAMLreturn (strdata_v);
447 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
449 char fbuf[64];
450 int size = sizeof (fbuf), len;
451 va_list ap;
452 char *buf = fbuf;
454 for (;;) {
455 va_start (ap, fmt);
456 len = vsnprintf (buf, size, fmt, ap);
457 va_end (ap);
459 if (len > -1) {
460 if (len < size - 4) {
461 writedata (state.csock, buf, len);
462 break;
464 else size = len + 5;
466 else {
467 err (1, "vsnprintf for `%s' failed", fmt);
469 buf = realloc (buf == fbuf ? NULL : buf, size);
470 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
472 if (buf != fbuf) free (buf);
475 static void closedoc (void)
477 #ifdef CACHE_PAGEREFS
478 if (state.pdflut.objs) {
479 for (int i = 0; i < state.pdflut.count; ++i) {
480 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
482 free (state.pdflut.objs);
483 state.pdflut.objs = NULL;
484 state.pdflut.idx = 0;
486 #endif
487 if (state.doc) {
488 fz_drop_document (state.ctx, state.doc);
489 state.doc = NULL;
493 static int openxref (char *filename, char *password)
495 for (int i = 0; i < state.texcount; ++i) {
496 state.texowners[i].w = -1;
497 state.texowners[i].slice = NULL;
500 closedoc ();
502 state.dirty = 0;
503 if (state.pagedims) {
504 free (state.pagedims);
505 state.pagedims = NULL;
507 state.pagedimcount = 0;
509 fz_set_aa_level (state.ctx, state.aalevel);
510 state.doc = fz_open_document (state.ctx, filename);
511 if (fz_needs_password (state.ctx, state.doc)) {
512 if (password && !*password) {
513 printd ("pass");
514 return 0;
516 else {
517 int ok = fz_authenticate_password (state.ctx, state.doc, password);
518 if (!ok) {
519 printd ("pass fail");
520 return 0;
524 state.pagecount = fz_count_pages (state.ctx, state.doc);
525 return 1;
528 static void pdfinfo (void)
530 struct { char *tag; char *name; } metatbl[] = {
531 { FZ_META_INFO_TITLE, "Title" },
532 { FZ_META_INFO_AUTHOR, "Author" },
533 { FZ_META_FORMAT, "Format" },
534 { FZ_META_ENCRYPTION, "Encryption" },
535 { "info:Creator", "Creator" },
536 { "info:Producer", "Producer" },
537 { "info:CreationDate", "Creation date" },
539 int len = 0;
540 char *buf = NULL;
542 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
543 int need;
544 again:
545 need = fz_lookup_metadata (state.ctx, state.doc,
546 metatbl[i].tag, buf, len);
547 if (need > 0) {
548 if (need <= len) {
549 printd ("info %s\t%s", metatbl[i].name, buf);
551 else {
552 buf = realloc (buf, need + 1);
553 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
554 len = need + 1;
555 goto again;
559 free (buf);
561 printd ("infoend");
564 static void unlinktile (struct tile *tile)
566 for (int i = 0; i < tile->slicecount; ++i) {
567 struct slice *s = &tile->slices[i];
569 if (s->texindex != -1) {
570 if (state.texowners[s->texindex].slice == s) {
571 state.texowners[s->texindex].slice = NULL;
577 static void freepage (struct page *page)
579 if (!page) return;
580 if (page->text) {
581 fz_drop_stext_page (state.ctx, page->text);
583 if (page->slinks) {
584 free (page->slinks);
586 fz_drop_display_list (state.ctx, page->dlist);
587 fz_drop_page (state.ctx, page->fzpage);
588 free (page);
591 static void freetile (struct tile *tile)
593 unlinktile (tile);
594 if (!tile->pbo) {
595 #ifndef PIGGYBACK
596 fz_drop_pixmap (state.ctx, tile->pixmap);
597 #else
598 if (state.pig) {
599 fz_drop_pixmap (state.ctx, state.pig);
601 state.pig = tile->pixmap;
602 #endif
604 else {
605 free (tile->pbo);
606 fz_drop_pixmap (state.ctx, tile->pixmap);
608 free (tile);
611 #ifdef __ALTIVEC__
612 #include <stdint.h>
613 #include <altivec.h>
615 static int cacheline32bytes;
617 static void __attribute__ ((constructor)) clcheck (void)
619 char **envp = environ;
620 unsigned long *auxv;
622 while (*envp++);
624 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
625 if (*auxv == 19) {
626 cacheline32bytes = auxv[1] == 32;
627 return;
632 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
634 size_t size = pixmap->w * pixmap->h * pixmap->n;
635 if (cacheline32bytes && size > 32) {
636 intptr_t a1, a2, diff;
637 size_t sizea, i;
638 vector unsigned char v = vec_splat_u8 (-1);
639 vector unsigned char *p;
641 a1 = a2 = (intptr_t) pixmap->samples;
642 a2 = (a1 + 31) & ~31;
643 diff = a2 - a1;
644 sizea = size - diff;
645 p = (void *) a2;
647 while (a1 != a2) *(char *) a1++ = 0xff;
648 for (i = 0; i < (sizea & ~31); i += 32) {
649 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
650 vec_st (v, i, p);
651 vec_st (v, i + 16, p);
653 while (i < sizea) *((char *) a1 + i++) = 0xff;
655 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
657 #else
658 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
659 #endif
661 static void trimctm (pdf_page *page, int pindex)
663 fz_matrix ctm;
664 struct pagedim *pdim = &state.pagedims[pindex];
666 if (!page) return;
667 if (!pdim->tctmready) {
668 fz_rect realbox, mediabox;
669 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
671 fz_rotate (&rm, -pdim->rotate);
672 fz_scale (&sm, 1, -1);
673 fz_concat (&ctm, &rm, &sm);
674 realbox = pdim->mediabox;
675 fz_transform_rect (&realbox, &ctm);
676 fz_translate (&tm, -realbox.x0, -realbox.y0);
677 fz_concat (&ctm1, &ctm, &tm);
678 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
679 fz_invert_matrix (&im, &page_ctm);
680 fz_concat (&ctm, &im, &ctm1);
681 pdim->tctm = ctm;
682 pdim->tctmready = 1;
686 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
688 fz_matrix ctm, tm;
689 ptrdiff_t pdimno = pdim - state.pagedims;
691 ARSERT (pdim - state.pagedims < INT_MAX);
692 if (pdf_specifics (state.ctx, state.doc)) {
693 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
694 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
696 else {
697 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
698 fz_concat (&ctm, &tm, &pdim->ctm);
700 return ctm;
703 static fz_matrix pagectm (struct page *page)
705 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
708 static void *loadpage (int pageno, int pindex)
710 fz_device *dev;
711 struct page *page;
713 page = calloc (sizeof (struct page), 1);
714 if (!page) {
715 err (1, "calloc page %d", pageno);
718 page->dlist = fz_new_display_list (state.ctx, NULL);
719 dev = fz_new_list_device (state.ctx, page->dlist);
720 fz_try (state.ctx) {
721 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
722 fz_run_page (state.ctx, page->fzpage, dev,
723 &fz_identity, NULL);
725 fz_catch (state.ctx) {
726 page->fzpage = NULL;
728 fz_close_device (state.ctx, dev);
729 fz_drop_device (state.ctx, dev);
731 page->pdimno = pindex;
732 page->pageno = pageno;
733 page->sgen = state.gen;
734 page->agen = state.gen;
735 page->tgen = state.gen;
736 return page;
739 static struct tile *alloctile (int h)
741 int slicecount;
742 size_t tilesize;
743 struct tile *tile;
745 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
746 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
747 tile = calloc (tilesize, 1);
748 if (!tile) {
749 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
751 for (int i = 0; i < slicecount; ++i) {
752 int sh = fz_mini (h, state.sliceheight);
753 tile->slices[i].h = sh;
754 tile->slices[i].texindex = -1;
755 h -= sh;
757 tile->slicecount = slicecount;
758 tile->sliceheight = state.sliceheight;
759 return tile;
762 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
763 struct bo *pbo)
765 fz_rect rect;
766 fz_irect bbox;
767 fz_matrix ctm;
768 fz_device *dev;
769 struct tile *tile;
770 struct pagedim *pdim;
772 tile = alloctile (h);
773 pdim = &state.pagedims[page->pdimno];
775 bbox = pdim->bounds;
776 bbox.x0 += x;
777 bbox.y0 += y;
778 bbox.x1 = bbox.x0 + w;
779 bbox.y1 = bbox.y0 + h;
781 if (state.pig) {
782 if (state.pig->w == w
783 && state.pig->h == h
784 && state.pig->colorspace == state.colorspace) {
785 tile->pixmap = state.pig;
786 tile->pixmap->x = bbox.x0;
787 tile->pixmap->y = bbox.y0;
789 else {
790 fz_drop_pixmap (state.ctx, state.pig);
792 state.pig = NULL;
794 if (!tile->pixmap) {
795 if (pbo) {
796 tile->pixmap =
797 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
798 &bbox, NULL, 1, pbo->ptr);
799 tile->pbo = pbo;
801 else {
802 tile->pixmap =
803 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
804 NULL, 1);
808 tile->w = w;
809 tile->h = h;
810 clearpixmap (tile->pixmap);
812 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
813 ctm = pagectm (page);
814 fz_rect_from_irect (&rect, &bbox);
815 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
816 fz_close_device (state.ctx, dev);
817 fz_drop_device (state.ctx, dev);
819 return tile;
822 #ifdef CACHE_PAGEREFS
823 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
824 thanks to Robin Watts */
825 static void
826 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
828 fz_context *ctx = state.ctx; /* doc->ctx; */
829 pdf_obj *kids;
830 int len;
832 if (state.pdflut.idx == state.pagecount) return;
834 kids = pdf_dict_gets (ctx, node, "Kids");
835 len = pdf_array_len (ctx, kids);
837 if (len == 0)
838 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
840 if (pdf_mark_obj (ctx, node))
841 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
842 for (int i = 0; i < len; i++) {
843 pdf_obj *kid = pdf_array_get (ctx, kids, i);
844 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
845 if (*type
846 ? !strcmp (type, "Pages")
847 : pdf_dict_gets (ctx, kid, "Kids")
848 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
849 pdf_collect_pages (doc, kid);
851 else {
852 if (*type
853 ? strcmp (type, "Page") != 0
854 : !pdf_dict_gets (ctx, kid, "MediaBox"))
855 fz_warn (ctx, "non-page object in page tree (%s)", type);
856 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
859 pdf_unmark_obj (ctx, node);
862 static void
863 pdf_load_page_objs (pdf_document *doc)
865 pdf_obj *root = pdf_dict_gets (state.ctx,
866 pdf_trailer (state.ctx, doc), "Root");
867 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
869 if (!node)
870 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
872 state.pdflut.idx = 0;
873 pdf_collect_pages (doc, node);
875 #endif
877 static void initpdims (int wthack)
879 double start, end;
880 FILE *trimf = NULL;
881 fz_rect rootmediabox = fz_empty_rect;
882 int pageno, trim, show;
883 int trimw = 0, cxcount;
884 fz_context *ctx = state.ctx;
885 pdf_document *pdf = pdf_specifics (ctx, state.doc);
887 fz_var (trimw);
888 fz_var (trimf);
889 fz_var (cxcount);
890 start = now ();
892 if (state.trimmargins && state.trimcachepath) {
893 trimf = fopen (state.trimcachepath, "rb");
894 if (!trimf) {
895 trimf = fopen (state.trimcachepath, "wb");
896 trimw = 1;
900 if (state.trimmargins || pdf || !state.cxack)
901 cxcount = state.pagecount;
902 else
903 cxcount = fz_mini (state.pagecount, 1);
905 if (pdf) {
906 pdf_obj *obj;
907 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
908 "Root/Pages/MediaBox");
909 pdf_to_rect (ctx, obj, &rootmediabox);
912 #ifdef CACHE_PAGEREFS
913 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
914 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
915 if (!state.pdflut.objs) {
916 err (1, "malloc pageobjs %zu %d %zu failed",
917 sizeof (*state.pdflut.objs), cxcount,
918 sizeof (*state.pdflut.objs) * cxcount);
920 state.pdflut.count = cxcount;
921 pdf_load_page_objs (pdf);
922 state.pdflut.pdf = pdf;
924 #endif
926 for (pageno = 0; pageno < cxcount; ++pageno) {
927 int rotate = 0;
928 struct pagedim *p;
929 fz_rect mediabox = fz_empty_rect;
931 fz_var (rotate);
932 if (pdf) {
933 pdf_obj *pageref, *pageobj;
935 #ifdef CACHE_PAGEREFS
936 pageref = state.pdflut.objs[pageno];
937 #else
938 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
939 #endif
940 pageobj = pdf_resolve_indirect (ctx, pageref);
941 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
943 if (state.trimmargins) {
944 pdf_obj *obj;
945 pdf_page *page;
947 fz_try (ctx) {
948 page = pdf_load_page (ctx, pdf, pageno);
949 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
950 trim = state.trimanew || !obj;
951 if (trim) {
952 fz_rect rect;
953 fz_device *dev;
954 fz_matrix ctm, page_ctm;
956 dev = fz_new_bbox_device (ctx, &rect);
957 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
958 fz_invert_matrix (&ctm, &page_ctm);
959 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
960 fz_close_device (ctx, dev);
961 fz_drop_device (ctx, dev);
963 rect.x0 += state.trimfuzz.x0;
964 rect.x1 += state.trimfuzz.x1;
965 rect.y0 += state.trimfuzz.y0;
966 rect.y1 += state.trimfuzz.y1;
967 fz_transform_rect (&rect, &ctm);
968 fz_intersect_rect (&rect, &mediabox);
970 if (!fz_is_empty_rect (&rect)) {
971 mediabox = rect;
974 obj = pdf_new_array (ctx, pdf, 4);
975 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
976 mediabox.x0));
977 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
978 mediabox.y0));
979 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
980 mediabox.x1));
981 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
982 mediabox.y1));
983 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
985 else {
986 mediabox.x0 = pdf_to_real (ctx,
987 pdf_array_get (ctx, obj, 0));
988 mediabox.y0 = pdf_to_real (ctx,
989 pdf_array_get (ctx, obj, 1));
990 mediabox.x1 = pdf_to_real (ctx,
991 pdf_array_get (ctx, obj, 2));
992 mediabox.y1 = pdf_to_real (ctx,
993 pdf_array_get (ctx, obj, 3));
996 fz_drop_page (ctx, &page->super);
997 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
998 if (show) {
999 printd ("progress %f Trimming %d",
1000 (double) (pageno + 1) / state.pagecount,
1001 pageno + 1);
1004 fz_catch (ctx) {
1005 fprintf (stderr, "failed to load page %d\n", pageno+1);
1008 else {
1009 int empty = 0;
1010 fz_rect cropbox;
1012 pdf_to_rect (ctx,
1013 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1014 &mediabox);
1015 if (fz_is_empty_rect (&mediabox)) {
1016 mediabox.x0 = 0;
1017 mediabox.y0 = 0;
1018 mediabox.x1 = 612;
1019 mediabox.y1 = 792;
1020 empty = 1;
1023 pdf_to_rect (ctx,
1024 pdf_dict_gets (ctx, pageobj, "CropBox"),
1025 &cropbox);
1026 if (!fz_is_empty_rect (&cropbox)) {
1027 if (empty) {
1028 mediabox = cropbox;
1030 else {
1031 fz_intersect_rect (&mediabox, &cropbox);
1034 else {
1035 if (empty) {
1036 if (fz_is_empty_rect (&rootmediabox)) {
1037 fprintf (stderr,
1038 "cannot find page size for page %d\n",
1039 pageno+1);
1041 else {
1042 mediabox = rootmediabox;
1048 else {
1049 if (state.trimmargins && trimw) {
1050 fz_page *page;
1052 fz_try (ctx) {
1053 page = fz_load_page (ctx, state.doc, pageno);
1054 fz_bound_page (ctx, page, &mediabox);
1055 if (state.trimmargins) {
1056 fz_rect rect;
1057 fz_device *dev;
1059 dev = fz_new_bbox_device (ctx, &rect);
1060 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1061 fz_close_device (ctx, dev);
1062 fz_drop_device (ctx, dev);
1064 rect.x0 += state.trimfuzz.x0;
1065 rect.x1 += state.trimfuzz.x1;
1066 rect.y0 += state.trimfuzz.y0;
1067 rect.y1 += state.trimfuzz.y1;
1068 fz_intersect_rect (&rect, &mediabox);
1070 if (!fz_is_empty_rect (&rect)) {
1071 mediabox = rect;
1074 fz_drop_page (ctx, page);
1075 if (!state.cxack) {
1076 printd ("progress %f loading %d",
1077 (double) (pageno + 1) / state.pagecount,
1078 pageno + 1);
1081 fz_catch (ctx) {
1083 if (trimf) {
1084 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1085 if (n - 1) {
1086 err (1, "fwrite trim mediabox");
1090 else {
1091 if (trimf) {
1092 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1093 if (n - 1) {
1094 err (1, "fread trim mediabox %d", pageno);
1097 else {
1098 fz_page *page;
1099 fz_try (ctx) {
1100 page = fz_load_page (ctx, state.doc, pageno);
1101 fz_bound_page (ctx, page, &mediabox);
1102 fz_drop_page (ctx, page);
1104 show = !state.trimmargins && pageno % 20 == 0;
1105 if (show) {
1106 printd ("progress %f Gathering dimensions %d",
1107 (double) (pageno) / state.pagecount,
1108 pageno);
1111 fz_catch (ctx) {
1112 fprintf (stderr, "failed to load page %d\n", pageno);
1118 if (state.pagedimcount == 0
1119 || ((void) (p = &state.pagedims[state.pagedimcount-1])
1120 , p->rotate != rotate)
1121 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1122 size_t size;
1124 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1125 state.pagedims = realloc (state.pagedims, size);
1126 if (!state.pagedims) {
1127 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1128 size, state.pagedimcount + 1);
1131 p = &state.pagedims[state.pagedimcount++];
1132 p->rotate = rotate;
1133 p->mediabox = mediabox;
1134 p->pageno = pageno;
1137 end = now ();
1138 if (!wthack) {
1139 printd ("progress 1 %s %d pages in %f seconds",
1140 state.trimmargins ? "Trimmed" : "Processed",
1141 state.pagecount, end - start);
1143 state.trimanew = 0;
1144 if (trimf) {
1145 if (fclose (trimf)) {
1146 err (1, "fclose");
1151 static void layout (void)
1153 int pindex;
1154 fz_rect box;
1155 fz_matrix ctm, rm;
1156 struct pagedim *p = NULL;
1157 float zw, w, maxw = 0.0, zoom = 1.0;
1159 if (state.pagedimcount == 0) return;
1161 switch (state.fitmodel) {
1162 case FitProportional:
1163 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1164 float x0, x1;
1166 p = &state.pagedims[pindex];
1167 fz_rotate (&rm, p->rotate + state.rotate);
1168 box = p->mediabox;
1169 fz_transform_rect (&box, &rm);
1171 x0 = fz_min (box.x0, box.x1);
1172 x1 = fz_max (box.x0, box.x1);
1174 w = x1 - x0;
1175 maxw = fz_max (w, maxw);
1176 zoom = state.w / maxw;
1178 break;
1180 case FitPage:
1181 maxw = state.w;
1182 break;
1184 case FitWidth:
1185 break;
1187 default:
1188 ARSERT (0 && state.fitmodel);
1191 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1192 fz_rect rect;
1193 fz_matrix tm, sm;
1195 p = &state.pagedims[pindex];
1196 fz_rotate (&ctm, state.rotate);
1197 fz_rotate (&rm, p->rotate + state.rotate);
1198 box = p->mediabox;
1199 fz_transform_rect (&box, &rm);
1200 w = box.x1 - box.x0;
1201 switch (state.fitmodel) {
1202 case FitProportional:
1203 p->left = (int) (((maxw - w) * zoom) / 2.f);
1204 break;
1205 case FitPage:
1207 float zh, h;
1208 zw = maxw / w;
1209 h = box.y1 - box.y0;
1210 zh = state.h / h;
1211 zoom = fz_min (zw, zh);
1212 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1214 break;
1215 case FitWidth:
1216 p->left = 0;
1217 zoom = state.w / w;
1218 break;
1221 fz_scale (&p->zoomctm, zoom, zoom);
1222 fz_concat (&ctm, &p->zoomctm, &ctm);
1224 fz_rotate (&rm, p->rotate);
1225 p->pagebox = p->mediabox;
1226 fz_transform_rect (&p->pagebox, &rm);
1227 p->pagebox.x1 -= p->pagebox.x0;
1228 p->pagebox.y1 -= p->pagebox.y0;
1229 p->pagebox.x0 = 0;
1230 p->pagebox.y0 = 0;
1231 rect = p->pagebox;
1232 fz_transform_rect (&rect, &ctm);
1233 fz_round_rect (&p->bounds, &rect);
1234 p->ctm = ctm;
1236 fz_translate (&tm, 0, -p->mediabox.y1);
1237 fz_scale (&sm, zoom, -zoom);
1238 fz_concat (&ctm, &tm, &sm);
1240 p->tctmready = 0;
1243 do {
1244 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1245 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1246 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1247 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1248 int boundw = x1 - x0;
1249 int boundh = y1 - y0;
1251 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1252 } while (p-- != state.pagedims);
1255 struct pagedim *pdimofpageno (int pageno)
1257 struct pagedim *pdim = state.pagedims;
1259 for (int i = 0; i < state.pagedimcount; ++i) {
1260 if (state.pagedims[i].pageno > pageno)
1261 break;
1262 pdim = &state.pagedims[i];
1264 return pdim;
1267 static void recurse_outline (fz_outline *outline, int level)
1269 while (outline) {
1270 if (outline->page >= 0) {
1271 fz_point p = {.x = outline->x, .y = outline->y};
1272 struct pagedim *pdim = pdimofpageno (outline->page);
1273 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1274 fz_transform_point (&p, &pdim->ctm);
1275 printd ("o %d %d %d %d %s",
1276 level, outline->page, (int) p.y, h, outline->title);
1278 else {
1279 printd ("on %d %s", level, outline->title);
1281 if (outline->down) {
1282 recurse_outline (outline->down, level + 1);
1284 outline = outline->next;
1288 static void process_outline (void)
1290 fz_outline *outline;
1292 if (!state.needoutline || !state.pagedimcount) return;
1294 state.needoutline = 0;
1295 outline = fz_load_outline (state.ctx, state.doc);
1296 if (outline) {
1297 recurse_outline (outline, 0);
1298 fz_drop_outline (state.ctx, outline);
1302 static char *strofline (fz_stext_line *line)
1304 char *p;
1305 char utf8[10];
1306 fz_stext_char *ch;
1307 size_t size = 0, cap = 80;
1309 p = malloc (cap + 1);
1310 if (!p) return NULL;
1312 for (ch = line->first_char; ch; ch = ch->next) {
1313 int n = fz_runetochar (utf8, ch->c);
1314 if (size + n > cap) {
1315 cap *= 2;
1316 p = realloc (p, cap + 1);
1317 if (!p) return NULL;
1320 memcpy (p + size, utf8, n);
1321 size += n;
1323 p[size] = 0;
1324 return p;
1327 static int matchline (regex_t *re, fz_stext_line *line,
1328 int stop, int pageno, double start)
1330 int ret;
1331 char *p;
1332 regmatch_t rm;
1334 p = strofline (line);
1335 if (!p) return -1;
1337 ret = regexec (re, p, 1, &rm, 0);
1338 if (ret) {
1339 free (p);
1340 if (ret != REG_NOMATCH) {
1341 size_t size;
1342 char errbuf[80];
1343 size = regerror (ret, re, errbuf, sizeof (errbuf));
1344 printd ("msg regexec error `%.*s'",
1345 (int) size, errbuf);
1346 return -1;
1348 return 0;
1350 else {
1351 fz_point p1, p2, p3, p4;
1352 fz_rect s = {0,0,0,0}, e;
1353 fz_stext_char *ch;
1354 int o = 0;
1356 for (ch = line->first_char; ch; ch = ch->next) {
1357 o += fz_runelen (ch->c);
1358 if (o > rm.rm_so) {
1359 s = ch->bbox;
1360 break;
1363 for (;ch; ch = ch->next) {
1364 o += fz_runelen (ch->c);
1365 if (o > rm.rm_eo) break;
1367 e = ch->bbox;
1369 p1.x = s.x0;
1370 p1.y = s.y0;
1371 p2.x = e.x1;
1372 p2.y = s.y0;
1373 p3.x = e.x1;
1374 p3.y = e.y1;
1375 p4.x = s.x0;
1376 p4.y = e.y1;
1378 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1379 if (!stop) {
1380 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1381 pageno, 1,
1382 p1.x, p1.y,
1383 p2.x, p2.y,
1384 p3.x, p3.y,
1385 p4.x, p4.y);
1387 printd ("progress 1 found at %d `%.*s' in %f sec",
1388 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1389 now () - start);
1391 else {
1392 printd ("match %d %d %f %f %f %f %f %f %f %f",
1393 pageno, 2,
1394 p1.x, p1.y,
1395 p2.x, p2.y,
1396 p3.x, p3.y,
1397 p4.x, p4.y);
1399 #pragma GCC diagnostic error "-Wdouble-promotion"
1400 free (p);
1401 return 1;
1405 /* wishful thinking function */
1406 static void search (regex_t *re, int pageno, int y, int forward)
1408 fz_device *tdev;
1409 fz_stext_page *text;
1410 struct pagedim *pdim;
1411 int stop = 0, niters = 0;
1412 double start, end;
1413 fz_page *page;
1414 fz_stext_block *block;
1416 start = now ();
1417 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1418 if (niters++ == 5) {
1419 niters = 0;
1420 if (hasdata ()) {
1421 printd ("progress 1 attention requested aborting search at %d",
1422 pageno);
1423 stop = 1;
1425 else {
1426 printd ("progress %f searching in page %d",
1427 (double) (pageno + 1) / state.pagecount,
1428 pageno);
1431 pdim = pdimofpageno (pageno);
1432 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1433 tdev = fz_new_stext_device (state.ctx, text, 0);
1435 page = fz_load_page (state.ctx, state.doc, pageno);
1437 fz_matrix ctm = pagectm1 (page, pdim);
1438 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1441 fz_close_device (state.ctx, tdev);
1442 fz_drop_device (state.ctx, tdev);
1444 if (forward) {
1445 for (block = text->first_block; block; block = block->next) {
1446 fz_stext_line *line;
1448 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1449 for (line = block->u.t.first_line; line; line = line->next) {
1450 if (line->bbox.y0 < y + 1) continue;
1452 switch (matchline (re, line, stop, pageno, start)) {
1453 case 0: break;
1454 case 1: stop = 1; break;
1455 case -1: stop = 1; goto endloop;
1460 else {
1461 for (block = text->last_block; block; block = block->prev) {
1462 fz_stext_line *line;
1464 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1465 for (line = block->u.t.last_line; line; line = line->prev) {
1466 if (line->bbox.y0 < y + 1) continue;
1468 switch (matchline (re, line, stop, pageno, start)) {
1469 case 0: break;
1470 case 1: stop = 1; break;
1471 case -1: stop = 1; goto endloop;
1477 if (forward) {
1478 pageno += 1;
1479 y = 0;
1481 else {
1482 pageno -= 1;
1483 y = INT_MAX;
1485 endloop:
1486 fz_drop_stext_page (state.ctx, text);
1487 fz_drop_page (state.ctx, page);
1489 end = now ();
1490 if (!stop) {
1491 printd ("progress 1 no matches %f sec", end - start);
1493 printd ("clearrects");
1496 static void set_tex_params (int colorspace)
1498 switch (colorspace) {
1499 case 0:
1500 state.texiform = GL_RGBA8;
1501 state.texform = GL_RGBA;
1502 state.texty = GL_UNSIGNED_BYTE;
1503 state.colorspace = fz_device_rgb (state.ctx);
1504 break;
1505 case 1:
1506 state.texiform = GL_RGBA8;
1507 state.texform = GL_BGRA;
1508 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1509 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1510 #else
1511 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1512 #endif
1513 state.colorspace = fz_device_bgr (state.ctx);
1514 break;
1515 case 2:
1516 state.texiform = GL_LUMINANCE_ALPHA;
1517 state.texform = GL_LUMINANCE_ALPHA;
1518 state.texty = GL_UNSIGNED_BYTE;
1519 state.colorspace = fz_device_gray (state.ctx);
1520 break;
1521 default:
1522 errx (1, "invalid colorspce %d", colorspace);
1526 static void realloctexts (int texcount)
1528 size_t size;
1530 if (texcount == state.texcount) return;
1532 if (texcount < state.texcount) {
1533 glDeleteTextures (state.texcount - texcount,
1534 state.texids + texcount);
1537 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1538 state.texids = realloc (state.texids, size);
1539 if (!state.texids) {
1540 err (1, "realloc texs %" FMT_s, size);
1543 state.texowners = (void *) (state.texids + texcount);
1544 if (texcount > state.texcount) {
1545 glGenTextures (texcount - state.texcount,
1546 state.texids + state.texcount);
1547 for (int i = state.texcount; i < texcount; ++i) {
1548 state.texowners[i].w = -1;
1549 state.texowners[i].slice = NULL;
1552 state.texcount = texcount;
1553 state.texindex = 0;
1556 static char *mbtoutf8 (char *s)
1558 char *p, *r;
1559 wchar_t *tmp;
1560 size_t i, ret, len;
1562 if (state.utf8cs) {
1563 return s;
1566 len = mbstowcs (NULL, s, strlen (s));
1567 if (len == 0) {
1568 return s;
1570 else {
1571 if (len == (size_t) -1) {
1572 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1573 return s;
1577 tmp = calloc (len, sizeof (wchar_t));
1578 if (!tmp) {
1579 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1580 len, sizeof (wchar_t), errno, strerror (errno));
1581 return s;
1584 ret = mbstowcs (tmp, s, len);
1585 if (ret == (size_t) -1) {
1586 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1587 len, errno, strerror (errno));
1588 free (tmp);
1589 return s;
1592 len = 0;
1593 for (i = 0; i < ret; ++i) {
1594 len += fz_runelen (tmp[i]);
1597 p = r = malloc (len + 1);
1598 if (!r) {
1599 printd ("emsg mbtoutf8: malloc(%zu)", len);
1600 free (tmp);
1601 return s;
1604 for (i = 0; i < ret; ++i) {
1605 p += fz_runetochar (p, tmp[i]);
1607 *p = 0;
1608 free (tmp);
1609 return r;
1612 CAMLprim value ml_mbtoutf8 (value s_v)
1614 CAMLparam1 (s_v);
1615 CAMLlocal1 (ret_v);
1616 char *s, *r;
1618 s = String_val (s_v);
1619 r = mbtoutf8 (s);
1620 if (r == s) {
1621 ret_v = s_v;
1623 else {
1624 ret_v = caml_copy_string (r);
1625 free (r);
1627 CAMLreturn (ret_v);
1630 static void * mainloop (void UNUSED_ATTR *unused)
1632 char *p = NULL;
1633 int len, ret, oldlen = 0;
1635 fz_var (p);
1636 fz_var (oldlen);
1637 for (;;) {
1638 len = readlen (state.csock);
1639 if (len == 0) {
1640 errx (1, "readlen returned 0");
1643 if (oldlen < len + 1) {
1644 p = realloc (p, len + 1);
1645 if (!p) {
1646 err (1, "realloc %d failed", len + 1);
1648 oldlen = len + 1;
1650 readdata (state.csock, p, len);
1651 p[len] = 0;
1653 if (!strncmp ("open", p, 4)) {
1654 int wthack, off, usedoccss, ok = 0;
1655 char *password;
1656 char *filename;
1657 char *utf8filename;
1658 size_t filenamelen;
1660 fz_var (ok);
1661 ret = sscanf (p + 5, " %d %d %d %n",
1662 &wthack, &state.cxack, &usedoccss, &off);
1663 if (ret != 3) {
1664 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1667 filename = p + 5 + off;
1668 filenamelen = strlen (filename);
1669 password = filename + filenamelen + 1;
1671 if (password[strlen (password) + 1]) {
1672 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1675 lock ("open");
1676 fz_set_use_document_css (state.ctx, usedoccss);
1677 fz_try (state.ctx) {
1678 ok = openxref (filename, password);
1680 fz_catch (state.ctx) {
1681 utf8filename = mbtoutf8 (filename);
1682 printd ("msg Could not open %s", utf8filename);
1683 if (utf8filename != filename) {
1684 free (utf8filename);
1687 if (ok) {
1688 pdfinfo ();
1689 initpdims (wthack);
1691 unlock ("open");
1693 if (ok) {
1694 if (!wthack) {
1695 utf8filename = mbtoutf8 (filename);
1696 printd ("msg Opened %s (press h/F1 to get help)",
1697 utf8filename);
1698 if (utf8filename != filename) {
1699 free (utf8filename);
1702 state.needoutline = 1;
1705 else if (!strncmp ("cs", p, 2)) {
1706 int i, colorspace;
1708 ret = sscanf (p + 2, " %d", &colorspace);
1709 if (ret != 1) {
1710 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1712 lock ("cs");
1713 set_tex_params (colorspace);
1714 for (i = 0; i < state.texcount; ++i) {
1715 state.texowners[i].w = -1;
1716 state.texowners[i].slice = NULL;
1718 unlock ("cs");
1720 else if (!strncmp ("freepage", p, 8)) {
1721 void *ptr;
1723 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1724 if (ret != 1) {
1725 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1727 lock ("freepage");
1728 freepage (ptr);
1729 unlock ("freepage");
1731 else if (!strncmp ("freetile", p, 8)) {
1732 void *ptr;
1734 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1735 if (ret != 1) {
1736 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1738 lock ("freetile");
1739 freetile (ptr);
1740 unlock ("freetile");
1742 else if (!strncmp ("search", p, 6)) {
1743 int icase, pageno, y, len2, forward;
1744 char *pattern;
1745 regex_t re;
1747 ret = sscanf (p + 6, " %d %d %d %d,%n",
1748 &icase, &pageno, &y, &forward, &len2);
1749 if (ret != 4) {
1750 errx (1, "malformed search `%s' ret=%d", p, ret);
1753 pattern = p + 6 + len2;
1754 ret = regcomp (&re, pattern,
1755 REG_EXTENDED | (icase ? REG_ICASE : 0));
1756 if (ret) {
1757 char errbuf[80];
1758 size_t size;
1760 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1761 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1763 else {
1764 search (&re, pageno, y, forward);
1765 regfree (&re);
1768 else if (!strncmp ("geometry", p, 8)) {
1769 int w, h, fitmodel;
1771 printd ("clear");
1772 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1773 if (ret != 3) {
1774 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1777 lock ("geometry");
1778 state.h = h;
1779 if (w != state.w) {
1780 state.w = w;
1781 for (int i = 0; i < state.texcount; ++i) {
1782 state.texowners[i].slice = NULL;
1785 state.fitmodel = fitmodel;
1786 layout ();
1787 process_outline ();
1789 state.gen++;
1790 unlock ("geometry");
1791 printd ("continue %d", state.pagecount);
1793 else if (!strncmp ("reqlayout", p, 9)) {
1794 char *nameddest;
1795 int rotate, off, h;
1796 int fitmodel;
1797 pdf_document *pdf;
1799 printd ("clear");
1800 ret = sscanf (p + 9, " %d %d %d %n",
1801 &rotate, &fitmodel, &h, &off);
1802 if (ret != 3) {
1803 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1805 lock ("reqlayout");
1806 pdf = pdf_specifics (state.ctx, state.doc);
1807 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1808 state.gen += 1;
1810 state.rotate = rotate;
1811 state.fitmodel = fitmodel;
1812 state.h = h;
1813 layout ();
1814 process_outline ();
1816 nameddest = p + 9 + off;
1817 if (pdf && nameddest && *nameddest) {
1818 fz_point xy;
1819 struct pagedim *pdim;
1820 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1821 &xy.x, &xy.y);
1822 pdim = pdimofpageno (pageno);
1823 fz_transform_point (&xy, &pdim->ctm);
1824 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1827 state.gen++;
1828 unlock ("reqlayout");
1829 printd ("continue %d", state.pagecount);
1831 else if (!strncmp ("page", p, 4)) {
1832 double a, b;
1833 struct page *page;
1834 int pageno, pindex;
1836 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1837 if (ret != 2) {
1838 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1841 lock ("page");
1842 a = now ();
1843 page = loadpage (pageno, pindex);
1844 b = now ();
1845 unlock ("page");
1847 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1849 else if (!strncmp ("tile", p, 4)) {
1850 int x, y, w, h;
1851 struct page *page;
1852 struct tile *tile;
1853 double a, b;
1854 void *data;
1856 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1857 SCN_ptr_cast (&page), &x, &y, &w, &h,
1858 SCN_ptr_cast (&data));
1859 if (ret != 6) {
1860 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1863 lock ("tile");
1864 a = now ();
1865 tile = rendertile (page, x, y, w, h, data);
1866 b = now ();
1867 unlock ("tile");
1869 printd ("tile %d %d %" FMT_ptr " %u %f",
1870 x, y,
1871 FMT_ptr_cast (tile),
1872 tile->w * tile->h * tile->pixmap->n,
1873 b - a);
1875 else if (!strncmp ("trimset", p, 7)) {
1876 fz_irect fuzz;
1877 int trimmargins;
1879 ret = sscanf (p + 7, " %d %d %d %d %d",
1880 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1881 if (ret != 5) {
1882 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1884 lock ("trimset");
1885 state.trimmargins = trimmargins;
1886 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1887 state.trimanew = 1;
1888 state.trimfuzz = fuzz;
1890 unlock ("trimset");
1892 else if (!strncmp ("settrim", p, 7)) {
1893 fz_irect fuzz;
1894 int trimmargins;
1896 ret = sscanf (p + 7, " %d %d %d %d %d",
1897 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1898 if (ret != 5) {
1899 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1901 printd ("clear");
1902 lock ("settrim");
1903 state.trimmargins = trimmargins;
1904 state.needoutline = 1;
1905 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1906 state.trimanew = 1;
1907 state.trimfuzz = fuzz;
1909 state.pagedimcount = 0;
1910 free (state.pagedims);
1911 state.pagedims = NULL;
1912 initpdims (0);
1913 layout ();
1914 process_outline ();
1915 unlock ("settrim");
1916 printd ("continue %d", state.pagecount);
1918 else if (!strncmp ("sliceh", p, 6)) {
1919 int h;
1921 ret = sscanf (p + 6, " %d", &h);
1922 if (ret != 1) {
1923 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1925 if (h != state.sliceheight) {
1926 state.sliceheight = h;
1927 for (int i = 0; i < state.texcount; ++i) {
1928 state.texowners[i].w = -1;
1929 state.texowners[i].h = -1;
1930 state.texowners[i].slice = NULL;
1934 else if (!strncmp ("interrupt", p, 9)) {
1935 printd ("vmsg interrupted");
1937 else {
1938 errx (1, "unknown command %.*s", len, p);
1941 return 0;
1944 CAMLprim value ml_isexternallink (value uri_v)
1946 CAMLparam1 (uri_v);
1947 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1948 CAMLreturn (Val_bool (ext));
1951 CAMLprim value ml_uritolocation (value uri_v)
1953 CAMLparam1 (uri_v);
1954 CAMLlocal1 (ret_v);
1955 int pageno;
1956 fz_point xy;
1957 struct pagedim *pdim;
1959 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1960 &xy.x, &xy.y);
1961 pdim = pdimofpageno (pageno);
1962 fz_transform_point (&xy, &pdim->ctm);
1963 ret_v = caml_alloc_tuple (3);
1964 Field (ret_v, 0) = Val_int (pageno);
1965 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1966 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1967 CAMLreturn (ret_v);
1970 CAMLprim value ml_realloctexts (value texcount_v)
1972 CAMLparam1 (texcount_v);
1973 int ok;
1975 if (trylock (__func__)) {
1976 ok = 0;
1977 goto done;
1979 realloctexts (Int_val (texcount_v));
1980 ok = 1;
1981 unlock (__func__);
1983 done:
1984 CAMLreturn (Val_bool (ok));
1987 static void recti (int x0, int y0, int x1, int y1)
1989 GLfloat *v = state.vertices;
1991 glVertexPointer (2, GL_FLOAT, 0, v);
1992 v[0] = x0; v[1] = y0;
1993 v[2] = x1; v[3] = y0;
1994 v[4] = x0; v[5] = y1;
1995 v[6] = x1; v[7] = y1;
1996 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1999 static void showsel (struct page *page, int ox, int oy)
2001 fz_irect bbox;
2002 fz_rect rect;
2003 fz_stext_block *block;
2004 int seen = 0;
2005 unsigned char selcolor[] = {15,15,15,140};
2007 if (!page->fmark.ch || !page->lmark.ch) return;
2009 glEnable (GL_BLEND);
2010 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2011 glColor4ubv (selcolor);
2013 ox += state.pagedims[page->pdimno].bounds.x0;
2014 oy += state.pagedims[page->pdimno].bounds.y0;
2016 for (block = page->text->first_block; block; block = block->next) {
2017 fz_stext_line *line;
2019 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2020 for (line = block->u.t.first_line; line; line = line->next) {
2021 fz_stext_char *ch;
2023 rect = fz_empty_rect;
2024 for (ch = line->first_char; ch; ch = ch->next) {
2025 if (ch == page->fmark.ch) seen = 1;
2026 if (seen) fz_union_rect (&rect, &ch->bbox);
2027 if (ch == page->lmark.ch) {
2028 fz_round_rect (&bbox, &rect);
2029 recti (bbox.x0 + ox, bbox.y0 + oy,
2030 bbox.x1 + ox, bbox.y1 + oy);
2031 goto done;
2034 fz_round_rect (&bbox, &rect);
2035 recti (bbox.x0 + ox, bbox.y0 + oy,
2036 bbox.x1 + ox, bbox.y1 + oy);
2039 done:
2040 glDisable (GL_BLEND);
2043 #pragma GCC diagnostic push
2044 #pragma GCC diagnostic ignored "-Weverything"
2045 #include "glfont.c"
2046 #pragma GCC diagnostic pop
2048 static void stipplerect (fz_matrix *m,
2049 fz_point *p1,
2050 fz_point *p2,
2051 fz_point *p3,
2052 fz_point *p4,
2053 GLfloat *texcoords,
2054 GLfloat *vertices)
2056 fz_transform_point (p1, m);
2057 fz_transform_point (p2, m);
2058 fz_transform_point (p3, m);
2059 fz_transform_point (p4, m);
2061 float w, h, s, t;
2063 w = p2->x - p1->x;
2064 h = p2->y - p1->y;
2065 t = hypotf (w, h) * .25f;
2067 w = p3->x - p2->x;
2068 h = p3->y - p2->y;
2069 s = hypotf (w, h) * .25f;
2071 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2072 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2074 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2075 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2077 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2078 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2080 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2081 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2083 glDrawArrays (GL_LINES, 0, 8);
2086 static void solidrect (fz_matrix *m,
2087 fz_point *p1,
2088 fz_point *p2,
2089 fz_point *p3,
2090 fz_point *p4,
2091 GLfloat *vertices)
2093 fz_transform_point (p1, m);
2094 fz_transform_point (p2, m);
2095 fz_transform_point (p3, m);
2096 fz_transform_point (p4, m);
2097 vertices[0] = p1->x; vertices[1] = p1->y;
2098 vertices[2] = p2->x; vertices[3] = p2->y;
2100 vertices[4] = p3->x; vertices[5] = p3->y;
2101 vertices[6] = p4->x; vertices[7] = p4->y;
2102 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2105 static void ensurelinks (struct page *page)
2107 if (!page->links)
2108 page->links = fz_load_links (state.ctx, page->fzpage);
2111 static void highlightlinks (struct page *page, int xoff, int yoff)
2113 fz_matrix ctm, tm, pm;
2114 fz_link *link;
2115 GLfloat *texcoords = state.texcoords;
2116 GLfloat *vertices = state.vertices;
2118 ensurelinks (page);
2120 glEnable (GL_TEXTURE_1D);
2121 glEnable (GL_BLEND);
2122 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2123 glBindTexture (GL_TEXTURE_1D, state.stid);
2125 xoff -= state.pagedims[page->pdimno].bounds.x0;
2126 yoff -= state.pagedims[page->pdimno].bounds.y0;
2127 fz_translate (&tm, xoff, yoff);
2128 pm = pagectm (page);
2129 fz_concat (&ctm, &pm, &tm);
2131 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2132 glVertexPointer (2, GL_FLOAT, 0, vertices);
2134 for (link = page->links; link; link = link->next) {
2135 fz_point p1, p2, p3, p4;
2137 p1.x = link->rect.x0;
2138 p1.y = link->rect.y0;
2140 p2.x = link->rect.x1;
2141 p2.y = link->rect.y0;
2143 p3.x = link->rect.x1;
2144 p3.y = link->rect.y1;
2146 p4.x = link->rect.x0;
2147 p4.y = link->rect.y1;
2149 /* TODO: different colours for different schemes */
2150 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2151 else glColor3ub (255, 0, 0);
2153 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2156 for (int i = 0; i < page->annotcount; ++i) {
2157 fz_point p1, p2, p3, p4;
2158 struct annot *annot = &page->annots[i];
2160 p1.x = annot->bbox.x0;
2161 p1.y = annot->bbox.y0;
2163 p2.x = annot->bbox.x1;
2164 p2.y = annot->bbox.y0;
2166 p3.x = annot->bbox.x1;
2167 p3.y = annot->bbox.y1;
2169 p4.x = annot->bbox.x0;
2170 p4.y = annot->bbox.y1;
2172 glColor3ub (0, 0, 128);
2173 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2176 glDisable (GL_BLEND);
2177 glDisable (GL_TEXTURE_1D);
2180 static int compareslinks (const void *l, const void *r)
2182 struct slink const *ls = l;
2183 struct slink const *rs = r;
2184 if (ls->bbox.y0 == rs->bbox.y0) {
2185 return rs->bbox.x0 - rs->bbox.x0;
2187 return ls->bbox.y0 - rs->bbox.y0;
2190 static void droptext (struct page *page)
2192 if (page->text) {
2193 fz_drop_stext_page (state.ctx, page->text);
2194 page->fmark.ch = NULL;
2195 page->lmark.ch = NULL;
2196 page->text = NULL;
2200 static void dropannots (struct page *page)
2202 if (page->annots) {
2203 free (page->annots);
2204 page->annots = NULL;
2205 page->annotcount = 0;
2209 static void ensureannots (struct page *page)
2211 int i, count = 0;
2212 size_t annotsize = sizeof (*page->annots);
2213 fz_annot *annot;
2215 if (state.gen != page->agen) {
2216 dropannots (page);
2217 page->agen = state.gen;
2219 if (page->annots) return;
2221 for (annot = fz_first_annot (state.ctx, page->fzpage);
2222 annot;
2223 annot = fz_next_annot (state.ctx, annot)) {
2224 count++;
2227 if (count > 0) {
2228 page->annotcount = count;
2229 page->annots = calloc (count, annotsize);
2230 if (!page->annots) {
2231 err (1, "calloc annots %d", count);
2234 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2235 annot;
2236 annot = fz_next_annot (state.ctx, annot), i++) {
2237 fz_rect rect;
2239 fz_bound_annot (state.ctx, annot, &rect);
2240 page->annots[i].annot = annot;
2241 fz_round_rect (&page->annots[i].bbox, &rect);
2246 static void dropslinks (struct page *page)
2248 if (page->slinks) {
2249 free (page->slinks);
2250 page->slinks = NULL;
2251 page->slinkcount = 0;
2253 if (page->links) {
2254 fz_drop_link (state.ctx, page->links);
2255 page->links = NULL;
2259 static void ensureslinks (struct page *page)
2261 fz_matrix ctm;
2262 int i, count;
2263 size_t slinksize = sizeof (*page->slinks);
2264 fz_link *link;
2266 ensureannots (page);
2267 if (state.gen != page->sgen) {
2268 dropslinks (page);
2269 page->sgen = state.gen;
2271 if (page->slinks) return;
2273 ensurelinks (page);
2274 ctm = pagectm (page);
2276 count = page->annotcount;
2277 for (link = page->links; link; link = link->next) {
2278 count++;
2280 if (count > 0) {
2281 int j;
2283 page->slinkcount = count;
2284 page->slinks = calloc (count, slinksize);
2285 if (!page->slinks) {
2286 err (1, "calloc slinks %d", count);
2289 for (i = 0, link = page->links; link; ++i, link = link->next) {
2290 fz_rect rect;
2292 rect = link->rect;
2293 fz_transform_rect (&rect, &ctm);
2294 page->slinks[i].tag = SLINK;
2295 page->slinks[i].u.link = link;
2296 fz_round_rect (&page->slinks[i].bbox, &rect);
2298 for (j = 0; j < page->annotcount; ++j, ++i) {
2299 fz_rect rect;
2300 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2301 fz_transform_rect (&rect, &ctm);
2302 fz_round_rect (&page->slinks[i].bbox, &rect);
2304 page->slinks[i].tag = SANNOT;
2305 page->slinks[i].u.annot = page->annots[j].annot;
2307 qsort (page->slinks, count, slinksize, compareslinks);
2311 #pragma GCC diagnostic push
2312 #pragma GCC diagnostic ignored "-Wconversion"
2313 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2314 static void fmt_linkn (char *s, unsigned int u)
2316 unsigned int len; unsigned int q;
2317 unsigned int zma = 'z' - 'a' + 1;
2318 len = 1; q = u;
2319 while (q > zma - 1) { ++len; q /= zma; }
2320 if (s) {
2321 s += len;
2322 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2323 /* handles u == 0 */
2325 s[len] = 0;
2327 #pragma GCC diagnostic pop
2329 static void highlightslinks (struct page *page, int xoff, int yoff,
2330 int noff, char *targ, mlsize_t tlen, int hfsize)
2332 char buf[40];
2333 struct slink *slink;
2334 float x0, y0, x1, y1, w;
2336 ensureslinks (page);
2337 glColor3ub (0xc3, 0xb0, 0x91);
2338 for (int i = 0; i < page->slinkcount; ++i) {
2339 fmt_linkn (buf, i + noff);
2340 if (!tlen || !strncmp (targ, buf, tlen)) {
2341 slink = &page->slinks[i];
2343 x0 = slink->bbox.x0 + xoff - 5;
2344 y1 = slink->bbox.y0 + yoff - 5;
2345 y0 = y1 + 10 + hfsize;
2346 w = measure_string (state.face, hfsize, buf);
2347 x1 = x0 + w + 10;
2348 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2352 glEnable (GL_BLEND);
2353 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2354 glEnable (GL_TEXTURE_2D);
2355 glColor3ub (0, 0, 0);
2356 for (int i = 0; i < page->slinkcount; ++i) {
2357 fmt_linkn (buf, i + noff);
2358 if (!tlen || !strncmp (targ, buf, tlen)) {
2359 slink = &page->slinks[i];
2361 x0 = slink->bbox.x0 + xoff;
2362 y0 = slink->bbox.y0 + yoff + hfsize;
2363 draw_string (state.face, hfsize, x0, y0, buf);
2366 glDisable (GL_TEXTURE_2D);
2367 glDisable (GL_BLEND);
2370 static void uploadslice (struct tile *tile, struct slice *slice)
2372 int offset;
2373 struct slice *slice1;
2374 unsigned char *texdata;
2376 offset = 0;
2377 for (slice1 = tile->slices; slice != slice1; slice1++) {
2378 offset += slice1->h * tile->w * tile->pixmap->n;
2380 if (slice->texindex != -1 && slice->texindex < state.texcount
2381 && state.texowners[slice->texindex].slice == slice) {
2382 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2384 else {
2385 int subimage = 0;
2386 int texindex = state.texindex++ % state.texcount;
2388 if (state.texowners[texindex].w == tile->w) {
2389 if (state.texowners[texindex].h >= slice->h) {
2390 subimage = 1;
2392 else {
2393 state.texowners[texindex].h = slice->h;
2396 else {
2397 state.texowners[texindex].h = slice->h;
2400 state.texowners[texindex].w = tile->w;
2401 state.texowners[texindex].slice = slice;
2402 slice->texindex = texindex;
2404 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2405 #if TEXT_TYPE == GL_TEXTURE_2D
2406 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2407 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2408 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2409 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2410 #endif
2411 if (tile->pbo) {
2412 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2413 texdata = 0;
2415 else {
2416 texdata = tile->pixmap->samples;
2418 if (subimage) {
2419 glTexSubImage2D (TEXT_TYPE,
2423 tile->w,
2424 slice->h,
2425 state.texform,
2426 state.texty,
2427 texdata+offset
2430 else {
2431 glTexImage2D (TEXT_TYPE,
2433 state.texiform,
2434 tile->w,
2435 slice->h,
2437 state.texform,
2438 state.texty,
2439 texdata+offset
2442 if (tile->pbo) {
2443 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2448 CAMLprim void ml_begintiles (value unit_v)
2450 CAMLparam1 (unit_v);
2451 glEnable (TEXT_TYPE);
2452 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2453 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2454 CAMLreturn0;
2457 CAMLprim void ml_endtiles (value unit_v)
2459 CAMLparam1 (unit_v);
2460 glDisable (TEXT_TYPE);
2461 CAMLreturn0;
2464 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2466 CAMLparam2 (args_v, ptr_v);
2467 int dispx = Int_val (Field (args_v, 0));
2468 int dispy = Int_val (Field (args_v, 1));
2469 int dispw = Int_val (Field (args_v, 2));
2470 int disph = Int_val (Field (args_v, 3));
2471 int tilex = Int_val (Field (args_v, 4));
2472 int tiley = Int_val (Field (args_v, 5));
2473 char *s = String_val (ptr_v);
2474 struct tile *tile = parse_pointer (__func__, s);
2475 int slicey, firstslice;
2476 struct slice *slice;
2477 GLfloat *texcoords = state.texcoords;
2478 GLfloat *vertices = state.vertices;
2480 firstslice = tiley / tile->sliceheight;
2481 slice = &tile->slices[firstslice];
2482 slicey = tiley % tile->sliceheight;
2484 while (disph > 0) {
2485 int dh;
2487 dh = slice->h - slicey;
2488 dh = fz_mini (disph, dh);
2489 uploadslice (tile, slice);
2491 texcoords[0] = tilex; texcoords[1] = slicey;
2492 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2493 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2494 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2496 vertices[0] = dispx; vertices[1] = dispy;
2497 vertices[2] = dispx+dispw; vertices[3] = dispy;
2498 vertices[4] = dispx; vertices[5] = dispy+dh;
2499 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2501 #if TEXT_TYPE == GL_TEXTURE_2D
2502 for (int i = 0; i < 8; ++i) {
2503 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2505 #endif
2507 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2508 dispy += dh;
2509 disph -= dh;
2510 slice++;
2511 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2512 slicey = 0;
2514 CAMLreturn0;
2517 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2519 fz_matrix ctm, tm, pm;
2520 fz_point p1, p2, p3, p4;
2521 GLfloat *vertices = state.vertices;
2522 double *v = (double *) rects_v;
2524 xoff -= state.pagedims[page->pdimno].bounds.x0;
2525 yoff -= state.pagedims[page->pdimno].bounds.y0;
2526 fz_translate (&tm, xoff, yoff);
2527 pm = pagectm (page);
2528 fz_concat (&ctm, &pm, &tm);
2530 glEnable (GL_BLEND);
2531 glVertexPointer (2, GL_FLOAT, 0, vertices);
2533 glColor4dv (v);
2534 p1.x = (float) v[4];
2535 p1.y = (float) v[5];
2537 p2.x = (float) v[6];
2538 p2.y = (float) v[5];
2540 p3.x = (float) v[6];
2541 p3.y = (float) v[7];
2543 p4.x = (float) v[4];
2544 p4.y = (float) v[7];
2545 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2546 glDisable (GL_BLEND);
2549 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2550 value xoff_v, value yoff_v,
2551 value li_v)
2553 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2554 int xoff = Int_val (xoff_v);
2555 int yoff = Int_val (yoff_v);
2556 int noff = Int_val (Field (li_v, 0));
2557 char *targ = String_val (Field (li_v, 1));
2558 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2559 int hfsize = Int_val (Field (li_v, 2));
2560 char *s = String_val (ptr_v);
2561 int hlmask = Int_val (hlinks_v);
2562 struct page *page = parse_pointer (__func__, s);
2564 if (!page->fzpage) {
2565 /* deal with loadpage failed pages */
2566 goto done;
2569 if (trylock (__func__)) {
2570 noff = -1;
2571 goto done;
2574 ensureannots (page);
2575 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2576 if (hlmask & 2) {
2577 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2578 noff = page->slinkcount;
2580 if (page->tgen == state.gen) {
2581 showsel (page, xoff, yoff);
2583 unlock (__func__);
2585 done:
2586 CAMLreturn (Val_int (noff));
2589 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2590 value rects_v)
2592 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2593 int xoff = Int_val (xoff_v);
2594 int yoff = Int_val (yoff_v);
2595 char *s = String_val (ptr_v);
2596 struct page *page = parse_pointer (__func__, s);
2598 drawprect (page, xoff, yoff, rects_v);
2599 CAMLreturn0;
2602 static struct annot *getannot (struct page *page, int x, int y)
2604 fz_point p;
2605 fz_matrix ctm;
2606 const fz_matrix *tctm;
2607 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2609 if (!page->annots) return NULL;
2611 if (pdf) {
2612 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2613 tctm = &state.pagedims[page->pdimno].tctm;
2615 else {
2616 tctm = &fz_identity;
2619 p.x = x;
2620 p.y = y;
2622 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2623 fz_invert_matrix (&ctm, &ctm);
2624 fz_transform_point (&p, &ctm);
2626 if (pdf) {
2627 for (int i = 0; i < page->annotcount; ++i) {
2628 struct annot *a = &page->annots[i];
2629 fz_rect rect;
2631 fz_bound_annot (state.ctx, a->annot, &rect);
2632 if (p.x >= rect.x0 && p.x <= rect.x1) {
2633 if (p.y >= rect.y0 && p.y <= rect.y1)
2634 return a;
2638 return NULL;
2641 static fz_link *getlink (struct page *page, int x, int y)
2643 fz_point p;
2644 fz_matrix ctm;
2645 fz_link *link;
2647 ensureslinks (page);
2649 p.x = x;
2650 p.y = y;
2652 ctm = pagectm (page);
2653 fz_invert_matrix (&ctm, &ctm);
2654 fz_transform_point (&p, &ctm);
2656 for (link = page->links; link; link = link->next) {
2657 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2658 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2659 return link;
2663 return NULL;
2666 static void ensuretext (struct page *page)
2668 if (state.gen != page->tgen) {
2669 droptext (page);
2670 page->tgen = state.gen;
2672 if (!page->text) {
2673 fz_matrix ctm;
2674 fz_device *tdev;
2676 page->text = fz_new_stext_page (state.ctx,
2677 &state.pagedims[page->pdimno].mediabox);
2678 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2679 ctm = pagectm (page);
2680 fz_run_display_list (state.ctx, page->dlist,
2681 tdev, &ctm, &fz_infinite_rect, NULL);
2682 fz_close_device (state.ctx, tdev);
2683 fz_drop_device (state.ctx, tdev);
2687 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2689 CAMLparam2 (start_page_v, dir_v);
2690 CAMLlocal1 (ret_v);
2691 int i, dir = Int_val (dir_v);
2692 int start_page = Int_val (start_page_v);
2693 int end_page = dir > 0 ? state.pagecount : -1;
2694 pdf_document *pdf;
2696 fz_var (end_page);
2697 ret_v = Val_int (0);
2698 lock (__func__);
2699 pdf = pdf_specifics (state.ctx, state.doc);
2700 for (i = start_page + dir; i != end_page; i += dir) {
2701 int found;
2703 fz_var (found);
2704 if (pdf) {
2705 pdf_page *page = NULL;
2707 fz_var (page);
2708 fz_try (state.ctx) {
2709 page = pdf_load_page (state.ctx, pdf, i);
2710 found = !!page->links || !!page->annots;
2712 fz_catch (state.ctx) {
2713 found = 0;
2715 if (page) {
2716 fz_drop_page (state.ctx, &page->super);
2719 else {
2720 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2721 fz_link *link = fz_load_links (state.ctx, page);
2722 found = !!link;
2723 fz_drop_link (state.ctx, link);
2724 fz_drop_page (state.ctx, page);
2727 if (found) {
2728 ret_v = caml_alloc_small (1, 1);
2729 Field (ret_v, 0) = Val_int (i);
2730 goto unlock;
2733 unlock:
2734 unlock (__func__);
2735 CAMLreturn (ret_v);
2738 enum { dir_first, dir_last };
2739 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2741 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2743 CAMLparam2 (ptr_v, dir_v);
2744 CAMLlocal2 (ret_v, pos_v);
2745 struct page *page;
2746 int dirtag, i, slinkindex;
2747 struct slink *found = NULL ,*slink;
2748 char *s = String_val (ptr_v);
2750 page = parse_pointer (__func__, s);
2751 ret_v = Val_int (0);
2752 lock (__func__);
2753 ensureslinks (page);
2755 if (Is_block (dir_v)) {
2756 dirtag = Tag_val (dir_v);
2757 switch (dirtag) {
2758 case dir_first_visible:
2760 int x0, y0, dir, first_index, last_index;
2762 pos_v = Field (dir_v, 0);
2763 x0 = Int_val (Field (pos_v, 0));
2764 y0 = Int_val (Field (pos_v, 1));
2765 dir = Int_val (Field (pos_v, 2));
2767 if (dir >= 0) {
2768 dir = 1;
2769 first_index = 0;
2770 last_index = page->slinkcount;
2772 else {
2773 first_index = page->slinkcount - 1;
2774 last_index = -1;
2777 for (i = first_index; i != last_index; i += dir) {
2778 slink = &page->slinks[i];
2779 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2780 found = slink;
2781 break;
2785 break;
2787 case dir_left:
2788 slinkindex = Int_val (Field (dir_v, 0));
2789 found = &page->slinks[slinkindex];
2790 for (i = slinkindex - 1; i >= 0; --i) {
2791 slink = &page->slinks[i];
2792 if (slink->bbox.x0 < found->bbox.x0) {
2793 found = slink;
2794 break;
2797 break;
2799 case dir_right:
2800 slinkindex = Int_val (Field (dir_v, 0));
2801 found = &page->slinks[slinkindex];
2802 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2803 slink = &page->slinks[i];
2804 if (slink->bbox.x0 > found->bbox.x0) {
2805 found = slink;
2806 break;
2809 break;
2811 case dir_down:
2812 slinkindex = Int_val (Field (dir_v, 0));
2813 found = &page->slinks[slinkindex];
2814 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2815 slink = &page->slinks[i];
2816 if (slink->bbox.y0 >= found->bbox.y0) {
2817 found = slink;
2818 break;
2821 break;
2823 case dir_up:
2824 slinkindex = Int_val (Field (dir_v, 0));
2825 found = &page->slinks[slinkindex];
2826 for (i = slinkindex - 1; i >= 0; --i) {
2827 slink = &page->slinks[i];
2828 if (slink->bbox.y0 <= found->bbox.y0) {
2829 found = slink;
2830 break;
2833 break;
2836 else {
2837 dirtag = Int_val (dir_v);
2838 switch (dirtag) {
2839 case dir_first:
2840 found = page->slinks;
2841 break;
2843 case dir_last:
2844 if (page->slinks) {
2845 found = page->slinks + (page->slinkcount - 1);
2847 break;
2850 if (found) {
2851 ret_v = caml_alloc_small (2, 1);
2852 Field (ret_v, 0) = Val_int (found - page->slinks);
2855 unlock (__func__);
2856 CAMLreturn (ret_v);
2859 enum { uuri, utext, uannot };
2861 CAMLprim value ml_getlink (value ptr_v, value n_v)
2863 CAMLparam2 (ptr_v, n_v);
2864 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2865 fz_link *link;
2866 struct page *page;
2867 char *s = String_val (ptr_v);
2868 struct slink *slink;
2870 ret_v = Val_int (0);
2871 page = parse_pointer (__func__, s);
2873 lock (__func__);
2874 ensureslinks (page);
2875 slink = &page->slinks[Int_val (n_v)];
2876 if (slink->tag == SLINK) {
2877 link = slink->u.link;
2878 str_v = caml_copy_string (link->uri);
2879 ret_v = caml_alloc_small (1, uuri);
2880 Field (ret_v, 0) = str_v;
2882 else {
2883 ret_v = caml_alloc_small (1, uannot);
2884 tup_v = caml_alloc_tuple (2);
2885 Field (ret_v, 0) = tup_v;
2886 Field (tup_v, 0) = ptr_v;
2887 Field (tup_v, 1) = n_v;
2889 unlock (__func__);
2891 CAMLreturn (ret_v);
2894 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2896 CAMLparam2 (ptr_v, n_v);
2897 CAMLlocal1 (ret_v);
2898 pdf_document *pdf;
2899 char *contents = NULL;
2901 lock (__func__);
2902 pdf = pdf_specifics (state.ctx, state.doc);
2903 if (pdf) {
2904 char *s = String_val (ptr_v);
2905 struct page *page;
2906 struct slink *slink;
2908 page = parse_pointer (__func__, s);
2909 slink = &page->slinks[Int_val (n_v)];
2910 contents = pdf_copy_annot_contents (state.ctx,
2911 (pdf_annot *) slink->u.annot);
2913 unlock (__func__);
2914 if (contents) {
2915 ret_v = caml_copy_string (contents);
2916 fz_free (state.ctx, contents);
2918 else {
2919 ret_v = caml_copy_string ("");
2921 CAMLreturn (ret_v);
2924 CAMLprim value ml_getlinkcount (value ptr_v)
2926 CAMLparam1 (ptr_v);
2927 struct page *page;
2928 char *s = String_val (ptr_v);
2930 page = parse_pointer (__func__, s);
2931 CAMLreturn (Val_int (page->slinkcount));
2934 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2936 CAMLparam2 (ptr_v, n_v);
2937 CAMLlocal1 (ret_v);
2938 struct page *page;
2939 struct slink *slink;
2940 char *s = String_val (ptr_v);
2942 page = parse_pointer (__func__, s);
2943 ret_v = caml_alloc_tuple (4);
2944 lock (__func__);
2945 ensureslinks (page);
2947 slink = &page->slinks[Int_val (n_v)];
2948 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2949 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2950 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2951 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2952 unlock (__func__);
2953 CAMLreturn (ret_v);
2956 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2958 CAMLparam3 (ptr_v, x_v, y_v);
2959 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2960 fz_link *link;
2961 struct annot *annot;
2962 struct page *page;
2963 char *ptr = String_val (ptr_v);
2964 int x = Int_val (x_v), y = Int_val (y_v);
2965 struct pagedim *pdim;
2967 ret_v = Val_int (0);
2968 if (trylock (__func__)) {
2969 goto done;
2972 page = parse_pointer (__func__, ptr);
2973 pdim = &state.pagedims[page->pdimno];
2974 x += pdim->bounds.x0;
2975 y += pdim->bounds.y0;
2978 annot = getannot (page, x, y);
2979 if (annot) {
2980 int i, n = -1;
2982 ensureslinks (page);
2983 for (i = 0; i < page->slinkcount; ++i) {
2984 if (page->slinks[i].tag == SANNOT
2985 && page->slinks[i].u.annot == annot->annot) {
2986 n = i;
2987 break;
2990 ret_v = caml_alloc_small (1, uannot);
2991 tup_v = caml_alloc_tuple (2);
2992 Field (ret_v, 0) = tup_v;
2993 Field (tup_v, 0) = ptr_v;
2994 Field (tup_v, 1) = Val_int (n);
2995 goto unlock;
2999 link = getlink (page, x, y);
3000 if (link) {
3001 str_v = caml_copy_string (link->uri);
3002 ret_v = caml_alloc_small (1, uuri);
3003 Field (ret_v, 0) = str_v;
3005 else {
3006 fz_rect *b;
3007 fz_stext_block *block;
3009 ensuretext (page);
3011 for (block = page->text->first_block; block; block = block->next) {
3012 fz_stext_line *line;
3014 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3015 b = &block->bbox;
3016 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3017 continue;
3019 for (line = block->u.t.first_line; line; line = line->next) {
3020 fz_stext_char *ch;
3022 b = &line->bbox;
3023 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3024 continue;
3026 for (ch = line->first_char; ch; ch = ch->next) {
3027 b = &ch->bbox;
3029 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3030 const char *n2 = fz_font_name (state.ctx, ch->font);
3031 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3032 ch->font);
3034 if (!n2) n2 = "<unknown font>";
3036 if (face && face->family_name) {
3037 char *s;
3038 char *n1 = face->family_name;
3039 size_t l1 = strlen (n1);
3040 size_t l2 = strlen (n2);
3042 if (l1 != l2 || memcmp (n1, n2, l1)) {
3043 s = malloc (l1 + l2 + 2);
3044 if (s) {
3045 memcpy (s, n2, l2);
3046 s[l2] = '=';
3047 memcpy (s + l2 + 1, n1, l1 + 1);
3048 str_v = caml_copy_string (s);
3049 free (s);
3053 if (str_v == Val_unit) {
3054 str_v = caml_copy_string (n2);
3056 ret_v = caml_alloc_small (1, utext);
3057 Field (ret_v, 0) = str_v;
3058 goto unlock;
3064 unlock:
3065 unlock (__func__);
3067 done:
3068 CAMLreturn (ret_v);
3071 enum { mark_page, mark_block, mark_line, mark_word };
3073 static int uninteresting (int c)
3075 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3076 || ispunct (c);
3079 CAMLprim void ml_clearmark (value ptr_v)
3081 CAMLparam1 (ptr_v);
3082 char *s = String_val (ptr_v);
3083 struct page *page;
3085 if (trylock (__func__)) {
3086 goto done;
3089 page = parse_pointer (__func__, s);
3090 page->fmark.ch = NULL;
3091 page->lmark.ch = NULL;
3093 unlock (__func__);
3094 done:
3095 CAMLreturn0;
3098 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3100 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3101 CAMLlocal1 (ret_v);
3102 fz_rect *b;
3103 struct page *page;
3104 fz_stext_line *line;
3105 fz_stext_block *block;
3106 struct pagedim *pdim;
3107 int mark = Int_val (mark_v);
3108 char *s = String_val (ptr_v);
3109 int x = Int_val (x_v), y = Int_val (y_v);
3111 ret_v = Val_bool (0);
3112 if (trylock (__func__)) {
3113 goto done;
3116 page = parse_pointer (__func__, s);
3117 pdim = &state.pagedims[page->pdimno];
3119 ensuretext (page);
3121 if (mark == mark_page) {
3122 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3123 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3124 ret_v = Val_bool (1);
3125 goto unlock;
3128 x += pdim->bounds.x0;
3129 y += pdim->bounds.y0;
3131 for (block = page->text->first_block; block; block = block->next) {
3132 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3133 b = &block->bbox;
3134 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3135 continue;
3137 if (mark == mark_block) {
3138 page->fmark.ch = block->u.t.first_line->first_char;
3139 page->lmark.ch = block->u.t.last_line->last_char;
3140 ret_v = Val_bool (1);
3141 goto unlock;
3144 for (line = block->u.t.first_line; line; line = line->next) {
3145 fz_stext_char *ch;
3147 b = &line->bbox;
3148 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3149 continue;
3151 if (mark == mark_line) {
3152 page->fmark.ch = line->first_char;
3153 page->lmark.ch = line->last_char;
3154 ret_v = Val_bool (1);
3155 goto unlock;
3158 for (ch = line->first_char; ch; ch = ch->next) {
3159 fz_stext_char *ch2, *first = NULL, *last = NULL;
3160 b = &ch->bbox;
3161 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3162 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3163 if (uninteresting (ch2->c)) first = NULL;
3164 else if (!first) first = ch2;
3166 for (ch2 = ch; ch2; ch2 = ch2->next) {
3167 if (uninteresting (ch2->c)) break;
3168 last = ch2;
3171 page->fmark.ch = first;
3172 page->lmark.ch = last;
3173 ret_v = Val_bool (1);
3174 goto unlock;
3179 unlock:
3180 if (!Bool_val (ret_v)) {
3181 page->fmark.ch = NULL;
3182 page->lmark.ch = NULL;
3184 unlock (__func__);
3186 done:
3187 CAMLreturn (ret_v);
3190 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3192 CAMLparam3 (ptr_v, x_v, y_v);
3193 CAMLlocal2 (ret_v, res_v);
3194 fz_rect *b = NULL;
3195 struct page *page;
3196 struct pagedim *pdim;
3197 fz_stext_block *block;
3198 char *s = String_val (ptr_v);
3199 int x = Int_val (x_v), y = Int_val (y_v);
3201 ret_v = Val_int (0);
3202 if (trylock (__func__)) {
3203 goto done;
3206 page = parse_pointer (__func__, s);
3207 pdim = &state.pagedims[page->pdimno];
3208 x += pdim->bounds.x0;
3209 y += pdim->bounds.y0;
3211 ensuretext (page);
3213 for (block = page->text->first_block; block; block = block->next) {
3214 switch (block->type) {
3215 case FZ_STEXT_BLOCK_TEXT:
3216 b = &block->bbox;
3217 break;
3219 case FZ_STEXT_BLOCK_IMAGE:
3220 b = &block->bbox;
3221 break;
3223 default:
3224 continue;
3227 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3228 break;
3229 b = NULL;
3231 if (b) {
3232 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3233 ret_v = caml_alloc_small (1, 1);
3234 Store_double_field (res_v, 0, (double) b->x0);
3235 Store_double_field (res_v, 1, (double) b->x1);
3236 Store_double_field (res_v, 2, (double) b->y0);
3237 Store_double_field (res_v, 3, (double) b->y1);
3238 Field (ret_v, 0) = res_v;
3240 unlock (__func__);
3242 done:
3243 CAMLreturn (ret_v);
3246 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3248 CAMLparam2 (ptr_v, rect_v);
3249 fz_rect b;
3250 struct page *page;
3251 struct pagedim *pdim;
3252 char *s = String_val (ptr_v);
3253 int x0, x1, y0, y1;
3254 fz_stext_char *ch;
3255 fz_stext_line *line;
3256 fz_stext_block *block;
3257 fz_stext_char *fc, *lc;
3259 if (trylock (__func__)) {
3260 goto done;
3263 page = parse_pointer (__func__, s);
3264 ensuretext (page);
3266 pdim = &state.pagedims[page->pdimno];
3267 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3268 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3269 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3270 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3272 if (y0 > y1) {
3273 int t = y0;
3274 y0 = y1;
3275 y1 = t;
3276 x0 = x1;
3277 x1 = t;
3280 fc = page->fmark.ch;
3281 lc = page->lmark.ch;
3283 for (block = page->text->first_block; block; block = block->next) {
3284 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3285 for (line = block->u.t.first_line; line; line = line->next) {
3286 for (ch = line->first_char; ch; ch = ch->next) {
3287 b = ch->bbox;
3288 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3289 fc = ch;
3291 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3292 lc = ch;
3297 if (x1 < x0 && fc == lc) {
3298 fz_stext_char *t;
3300 t = fc;
3301 fc = lc;
3302 lc = t;
3305 page->fmark.ch = fc;
3306 page->lmark.ch = lc;
3308 unlock (__func__);
3310 done:
3311 CAMLreturn0;
3314 static int pipechar (FILE *f, fz_stext_char *ch)
3316 char buf[4];
3317 int len;
3318 size_t ret;
3320 len = fz_runetochar (buf, ch->c);
3321 ret = fwrite (buf, len, 1, f);
3322 if (ret != 1) {
3323 fprintf (stderr, "failed to write %d bytes ret=%zu: %s\n",
3324 len, ret, strerror (errno));
3325 return -1;
3327 return 0;
3330 #ifdef __CYGWIN__
3331 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3333 caml_failwith ("ml_popen not implemented under Cygwin");
3335 #else
3336 CAMLprim value ml_spawn (value command_v, value fds_v)
3338 CAMLparam2 (command_v, fds_v);
3339 CAMLlocal2 (l_v, tup_v);
3340 int ret, ret1;
3341 pid_t pid = (pid_t) -1;
3342 char *msg = NULL;
3343 value earg_v = Nothing;
3344 posix_spawnattr_t attr;
3345 posix_spawn_file_actions_t fa;
3346 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3348 argv[2] = String_val (command_v);
3350 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3351 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3354 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3355 msg = "posix_spawnattr_init";
3356 goto fail1;
3359 #ifdef POSIX_SPAWN_USEVFORK
3360 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3361 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3362 goto fail;
3364 #endif
3366 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3367 int fd1, fd2;
3369 tup_v = Field (l_v, 0);
3370 fd1 = Int_val (Field (tup_v, 0));
3371 fd2 = Int_val (Field (tup_v, 1));
3372 if (fd2 < 0) {
3373 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3374 msg = "posix_spawn_file_actions_addclose";
3375 earg_v = tup_v;
3376 goto fail;
3379 else {
3380 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3381 msg = "posix_spawn_file_actions_adddup2";
3382 earg_v = tup_v;
3383 goto fail;
3388 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3389 msg = "posix_spawn";
3390 goto fail;
3393 fail:
3394 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3395 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3398 fail1:
3399 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3400 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3401 strerror (ret1));
3404 if (msg)
3405 unix_error (ret, msg, earg_v);
3407 CAMLreturn (Val_int (pid));
3409 #endif
3411 CAMLprim value ml_hassel (value ptr_v)
3413 CAMLparam1 (ptr_v);
3414 CAMLlocal1 (ret_v);
3415 struct page *page;
3416 char *s = String_val (ptr_v);
3418 ret_v = Val_bool (0);
3419 if (trylock (__func__)) {
3420 goto done;
3423 page = parse_pointer (__func__, s);
3424 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3425 unlock (__func__);
3426 done:
3427 CAMLreturn (ret_v);
3430 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3432 CAMLparam2 (fd_v, ptr_v);
3433 FILE *f;
3434 int seen = 0;
3435 struct page *page;
3436 fz_stext_line *line;
3437 fz_stext_block *block;
3438 int fd = Int_val (fd_v);
3439 char *s = String_val (ptr_v);
3441 if (trylock (__func__)) {
3442 goto done;
3445 page = parse_pointer (__func__, s);
3447 if (!page->fmark.ch || !page->lmark.ch) {
3448 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3449 goto unlock;
3452 f = fdopen (fd, "w");
3453 if (!f) {
3454 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3455 fd, strerror (errno));
3456 f = stdout;
3459 for (block = page->text->first_block; block; block = block->next) {
3460 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3461 for (line = block->u.t.first_line; line; line = line->next) {
3462 fz_stext_char *ch;
3463 for (ch = line->first_char; ch; ch = ch->next) {
3464 if (seen || ch == page->fmark.ch) {
3465 do {
3466 pipechar (f, ch);
3467 if (ch == page->lmark.ch) goto close;
3468 } while ((ch = ch->next));
3469 seen = 1;
3470 break;
3473 if (seen) fputc ('\n', f);
3476 close:
3477 if (f != stdout) {
3478 int ret = fclose (f);
3479 fd = -1;
3480 if (ret == -1) {
3481 if (errno != ECHILD) {
3482 fprintf (stderr, "failed to close sel pipe: %s\n",
3483 strerror (errno));
3487 unlock:
3488 unlock (__func__);
3490 done:
3491 if (fd >= 0) {
3492 if (close (fd)) {
3493 fprintf (stderr, "failed to close sel pipe: %s\n",
3494 strerror (errno));
3497 CAMLreturn0;
3500 CAMLprim value ml_getpdimrect (value pagedimno_v)
3502 CAMLparam1 (pagedimno_v);
3503 CAMLlocal1 (ret_v);
3504 int pagedimno = Int_val (pagedimno_v);
3505 fz_rect box;
3507 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3508 if (trylock (__func__)) {
3509 box = fz_empty_rect;
3511 else {
3512 box = state.pagedims[pagedimno].mediabox;
3513 unlock (__func__);
3516 Store_double_field (ret_v, 0, (double) box.x0);
3517 Store_double_field (ret_v, 1, (double) box.x1);
3518 Store_double_field (ret_v, 2, (double) box.y0);
3519 Store_double_field (ret_v, 3, (double) box.y1);
3521 CAMLreturn (ret_v);
3524 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3525 value dw_v, value cols_v)
3527 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3528 CAMLlocal1 (ret_v);
3529 int i;
3530 float zoom = -1.;
3531 float maxh = 0.0;
3532 struct pagedim *p;
3533 float winw = Int_val (winw_v);
3534 float winh = Int_val (winh_v);
3535 float dw = Int_val (dw_v);
3536 float cols = Int_val (cols_v);
3537 float pw = 1.0, ph = 1.0;
3539 if (trylock (__func__)) {
3540 goto done;
3543 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3544 float w = p->pagebox.x1 / cols;
3545 float h = p->pagebox.y1;
3546 if (h > maxh) {
3547 maxh = h;
3548 ph = h;
3549 if (state.fitmodel != FitProportional) pw = w;
3551 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3554 zoom = (((winh / ph) * pw) + dw) / winw;
3555 unlock (__func__);
3556 done:
3557 ret_v = caml_copy_double ((double) zoom);
3558 CAMLreturn (ret_v);
3561 CAMLprim value ml_getmaxw (value unit_v)
3563 CAMLparam1 (unit_v);
3564 CAMLlocal1 (ret_v);
3565 int i;
3566 float maxw = -1.;
3567 struct pagedim *p;
3569 if (trylock (__func__)) {
3570 goto done;
3573 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3574 float w = p->pagebox.x1;
3575 maxw = fz_max (maxw, w);
3578 unlock (__func__);
3579 done:
3580 ret_v = caml_copy_double ((double) maxw);
3581 CAMLreturn (ret_v);
3584 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3586 CAMLparam4 (pt_v, x_v, y_v, string_v);
3587 CAMLlocal1 (ret_v);
3588 int pt = Int_val(pt_v);
3589 int x = Int_val (x_v);
3590 int y = Int_val (y_v);
3591 double w;
3593 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3594 ret_v = caml_copy_double (w);
3595 CAMLreturn (ret_v);
3598 CAMLprim value ml_measure_string (value pt_v, value string_v)
3600 CAMLparam2 (pt_v, string_v);
3601 CAMLlocal1 (ret_v);
3602 int pt = Int_val (pt_v);
3603 double w;
3605 w = (double) measure_string (state.face, pt, String_val (string_v));
3606 ret_v = caml_copy_double (w);
3607 CAMLreturn (ret_v);
3610 CAMLprim value ml_getpagebox (value opaque_v)
3612 CAMLparam1 (opaque_v);
3613 CAMLlocal1 (ret_v);
3614 fz_rect rect;
3615 fz_irect bbox;
3616 fz_matrix ctm;
3617 fz_device *dev;
3618 char *s = String_val (opaque_v);
3619 struct page *page = parse_pointer (__func__, s);
3621 ret_v = caml_alloc_tuple (4);
3622 dev = fz_new_bbox_device (state.ctx, &rect);
3624 ctm = pagectm (page);
3625 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3627 fz_close_device (state.ctx, dev);
3628 fz_drop_device (state.ctx, dev);
3629 fz_round_rect (&bbox, &rect);
3630 Field (ret_v, 0) = Val_int (bbox.x0);
3631 Field (ret_v, 1) = Val_int (bbox.y0);
3632 Field (ret_v, 2) = Val_int (bbox.x1);
3633 Field (ret_v, 3) = Val_int (bbox.y1);
3635 CAMLreturn (ret_v);
3638 CAMLprim void ml_setaalevel (value level_v)
3640 CAMLparam1 (level_v);
3642 state.aalevel = Int_val (level_v);
3643 CAMLreturn0;
3646 #ifndef __COCOA__
3647 #pragma GCC diagnostic push
3648 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3649 #include <X11/Xlib.h>
3650 #include <X11/cursorfont.h>
3651 #pragma GCC diagnostic pop
3653 #ifdef USE_EGL
3654 #include <EGL/egl.h>
3655 #else
3656 #include <GL/glx.h>
3657 #endif
3659 static const int shapes[] = {
3660 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3663 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3665 static struct {
3666 Window wid;
3667 Display *dpy;
3668 #ifdef USE_EGL
3669 EGLContext ctx;
3670 EGLConfig conf;
3671 EGLSurface win;
3672 EGLDisplay *edpy;
3673 #else
3674 GLXContext ctx;
3675 #endif
3676 XVisualInfo *visual;
3677 Cursor curs[CURS_COUNT];
3678 } glx;
3681 static void initcurs (void)
3683 for (size_t n = 0; n < CURS_COUNT; ++n) {
3684 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3688 CAMLprim void ml_setbgcol (value color_v)
3690 CAMLparam1 (color_v);
3691 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3692 CAMLreturn0;
3695 #ifdef USE_EGL
3696 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3698 CAMLparam3 (display_v, wid_v, screen_v);
3699 int major, minor;
3700 int num_conf;
3701 EGLint visid;
3702 EGLint attribs[] = {
3703 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3704 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3705 EGL_NONE
3707 EGLConfig conf;
3709 glx.dpy = XOpenDisplay (String_val (display_v));
3710 if (!glx.dpy) {
3711 caml_failwith ("XOpenDisplay");
3714 eglBindAPI (EGL_OPENGL_API);
3716 glx.edpy = eglGetDisplay (glx.dpy);
3717 if (glx.edpy == EGL_NO_DISPLAY) {
3718 caml_failwith ("eglGetDisplay");
3721 if (!eglInitialize (glx.edpy, &major, &minor)) {
3722 caml_failwith ("eglInitialize");
3725 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3726 !num_conf) {
3727 caml_failwith ("eglChooseConfig");
3730 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3731 caml_failwith ("eglGetConfigAttrib");
3734 glx.conf = conf;
3735 initcurs ();
3737 glx.wid = Int_val (wid_v);
3738 CAMLreturn (Val_int (visid));
3741 CAMLprim void ml_glxcompleteinit (value unit_v)
3743 CAMLparam1 (unit_v);
3745 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3746 if (!glx.ctx) {
3747 caml_failwith ("eglCreateContext");
3750 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3751 glx.wid, NULL);
3752 if (glx.win == EGL_NO_SURFACE) {
3753 caml_failwith ("eglCreateWindowSurface");
3756 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3757 glx.ctx = NULL;
3758 caml_failwith ("eglMakeCurrent");
3760 CAMLreturn0;
3762 #else
3763 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3765 CAMLparam3 (display_v, wid_v, screen_v);
3767 glx.dpy = XOpenDisplay (String_val (display_v));
3768 if (!glx.dpy) {
3769 caml_failwith ("XOpenDisplay");
3772 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3773 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3774 if (!glx.visual) {
3775 XCloseDisplay (glx.dpy);
3776 caml_failwith ("glXChooseVisual");
3779 initcurs ();
3781 glx.wid = Int_val (wid_v);
3782 CAMLreturn (Val_int (glx.visual->visualid));
3785 CAMLprim void ml_glxcompleteinit (value unit_v)
3787 CAMLparam1 (unit_v);
3789 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3790 if (!glx.ctx) {
3791 caml_failwith ("glXCreateContext");
3794 XFree (glx.visual);
3795 glx.visual = NULL;
3797 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3798 glXDestroyContext (glx.dpy, glx.ctx);
3799 glx.ctx = NULL;
3800 caml_failwith ("glXMakeCurrent");
3802 CAMLreturn0;
3804 #endif
3806 CAMLprim void ml_setcursor (value cursor_v)
3808 CAMLparam1 (cursor_v);
3809 size_t cursn = Int_val (cursor_v);
3811 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3812 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3813 XFlush (glx.dpy);
3814 CAMLreturn0;
3817 CAMLprim void ml_swapb (value unit_v)
3819 CAMLparam1 (unit_v);
3820 #ifdef USE_EGL
3821 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3822 caml_failwith ("eglSwapBuffers");
3824 #else
3825 glXSwapBuffers (glx.dpy, glx.wid);
3826 #endif
3827 CAMLreturn0;
3830 #pragma GCC diagnostic push
3831 #pragma GCC diagnostic ignored "-Wmissing-variable-declarations"
3832 #include "keysym2ucs.c"
3833 #pragma GCC diagnostic pop
3835 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3837 CAMLparam1 (keysym_v);
3838 CAMLlocal1 (str_v);
3839 KeySym keysym = Int_val (keysym_v);
3840 Rune rune;
3841 int len;
3842 char buf[5];
3844 rune = (Rune) keysym2ucs (keysym);
3845 len = fz_runetochar (buf, rune);
3846 buf[len] = 0;
3847 str_v = caml_copy_string (buf);
3848 CAMLreturn (str_v);
3850 #else
3851 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3853 CAMLparam1 (keysym_v);
3854 CAMLlocal1 (str_v);
3855 long ucs_v = Long_val (keysym_v);
3856 int len;
3857 char buf[5];
3859 len = fz_runetochar (buf, ucs_v);
3860 buf[len] = 0;
3861 str_v = caml_copy_string (buf);
3862 CAMLreturn (str_v);
3864 #endif
3866 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3868 CAMLprim value ml_platform (value unit_v)
3870 CAMLparam1 (unit_v);
3871 CAMLlocal2 (tup_v, arr_v);
3872 int platid = piunknown;
3873 struct utsname buf;
3875 #if defined __linux__
3876 platid = pilinux;
3877 #elif defined __CYGWIN__
3878 platid = picygwin;
3879 #elif defined __DragonFly__ || defined __FreeBSD__
3880 || defined __OpenBSD__ || defined __NetBSD__
3881 platid = pibsd;
3882 #elif defined __sun__
3883 platid = pisun;
3884 #elif defined __APPLE__
3885 platid = piosx;
3886 #endif
3887 if (uname (&buf)) err (1, "uname");
3889 tup_v = caml_alloc_tuple (2);
3891 char const *sar[] = {
3892 buf.sysname,
3893 buf.release,
3894 buf.version,
3895 buf.machine,
3896 NULL
3898 arr_v = caml_copy_string_array (sar);
3900 Field (tup_v, 0) = Val_int (platid);
3901 Field (tup_v, 1) = arr_v;
3902 CAMLreturn (tup_v);
3905 CAMLprim void ml_cloexec (value fd_v)
3907 CAMLparam1 (fd_v);
3908 int fd = Int_val (fd_v);
3910 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3911 uerror ("fcntl", Nothing);
3913 CAMLreturn0;
3916 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3918 CAMLparam2 (w_v, h_v);
3919 CAMLlocal1 (ret_v);
3920 struct bo *pbo;
3921 int w = Int_val (w_v);
3922 int h = Int_val (h_v);
3923 int cs = Int_val (cs_v);
3925 if (state.bo_usable) {
3926 pbo = calloc (sizeof (*pbo), 1);
3927 if (!pbo) {
3928 err (1, "calloc pbo");
3931 switch (cs) {
3932 case 0:
3933 case 1:
3934 pbo->size = w*h*4;
3935 break;
3936 case 2:
3937 pbo->size = w*h*2;
3938 break;
3939 default:
3940 errx (1, "%s: invalid colorspace %d", __func__, cs);
3943 state.glGenBuffersARB (1, &pbo->id);
3944 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3945 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3946 NULL, GL_STREAM_DRAW);
3947 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3948 GL_READ_WRITE);
3949 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3950 if (!pbo->ptr) {
3951 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3952 state.glDeleteBuffersARB (1, &pbo->id);
3953 free (pbo);
3954 ret_v = caml_copy_string ("0");
3956 else {
3957 int res;
3958 char *s;
3960 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3961 if (res < 0) {
3962 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3964 s = malloc (res+1);
3965 if (!s) {
3966 err (1, "malloc %d bytes failed", res+1);
3968 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3969 if (res < 0) {
3970 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3972 ret_v = caml_copy_string (s);
3973 free (s);
3976 else {
3977 ret_v = caml_copy_string ("0");
3979 CAMLreturn (ret_v);
3982 CAMLprim void ml_freepbo (value s_v)
3984 CAMLparam1 (s_v);
3985 char *s = String_val (s_v);
3986 struct tile *tile = parse_pointer (__func__, s);
3988 if (tile->pbo) {
3989 state.glDeleteBuffersARB (1, &tile->pbo->id);
3990 tile->pbo->id = -1;
3991 tile->pbo->ptr = NULL;
3992 tile->pbo->size = -1;
3994 CAMLreturn0;
3997 CAMLprim void ml_unmappbo (value s_v)
3999 CAMLparam1 (s_v);
4000 char *s = String_val (s_v);
4001 struct tile *tile = parse_pointer (__func__, s);
4003 if (tile->pbo) {
4004 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4005 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4006 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4008 tile->pbo->ptr = NULL;
4009 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4011 CAMLreturn0;
4014 static void setuppbo (void)
4016 #ifdef __COCOA__
4017 static CFBundleRef framework = NULL;
4018 if (framework == NULL)
4019 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
4020 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
4021 #else
4022 #ifdef USE_EGL
4023 #define GGPA(n) (*(void (**) (void)) &state.n = eglGetProcAddress (#n))
4024 #else
4025 #define GGPA(n) (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
4026 #endif
4027 state.bo_usable = GGPA (glBindBufferARB)
4028 && GGPA (glUnmapBufferARB)
4029 && GGPA (glMapBufferARB)
4030 && GGPA (glBufferDataARB)
4031 && GGPA (glGenBuffersARB)
4032 && GGPA (glDeleteBuffersARB);
4033 #endif
4034 #undef GGPA
4037 CAMLprim value ml_bo_usable (value unit_v)
4039 CAMLparam1 (unit_v);
4040 CAMLreturn (Val_bool (state.bo_usable));
4043 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4045 CAMLparam3 (ptr_v, x_v, y_v);
4046 CAMLlocal2 (ret_v, tup_v);
4047 struct page *page;
4048 char *s = String_val (ptr_v);
4049 int x = Int_val (x_v), y = Int_val (y_v);
4050 struct pagedim *pdim;
4051 fz_point p;
4052 fz_matrix ctm;
4054 page = parse_pointer (__func__, s);
4055 pdim = &state.pagedims[page->pdimno];
4057 ret_v = Val_int (0);
4058 if (trylock (__func__)) {
4059 goto done;
4062 if (pdf_specifics (state.ctx, state.doc)) {
4063 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4064 ctm = state.pagedims[page->pdimno].tctm;
4066 else {
4067 ctm = fz_identity;
4069 p.x = x + pdim->bounds.x0;
4070 p.y = y + pdim->bounds.y0;
4072 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4073 fz_invert_matrix (&ctm, &ctm);
4074 fz_transform_point (&p, &ctm);
4076 tup_v = caml_alloc_tuple (2);
4077 ret_v = caml_alloc_small (1, 1);
4078 Field (tup_v, 0) = Val_int (p.x);
4079 Field (tup_v, 1) = Val_int (p.y);
4080 Field (ret_v, 0) = tup_v;
4082 unlock (__func__);
4083 done:
4084 CAMLreturn (ret_v);
4087 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4088 value x_v, value y_v)
4090 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4091 CAMLlocal1 (ret_v);
4092 struct page *page;
4093 char *s = String_val (ptr_v);
4094 int pageno = Int_val (pageno_v);
4095 int pdimno = Int_val (pdimno_v);
4096 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
4097 struct pagedim *pdim;
4098 fz_point p;
4099 fz_matrix ctm;
4101 ret_v = Val_int (0);
4102 lock (__func__);
4104 if (!*s) {
4105 page = loadpage (pageno, pdimno);
4107 else {
4108 page = parse_pointer (__func__, s);
4110 pdim = &state.pagedims[pdimno];
4112 if (pdf_specifics (state.ctx, state.doc)) {
4113 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4114 ctm = state.pagedims[page->pdimno].tctm;
4116 else {
4117 ctm = fz_identity;
4119 p.x = x + pdim->bounds.x0;
4120 p.y = y + pdim->bounds.y0;
4122 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4123 fz_transform_point (&p, &ctm);
4125 ret_v = caml_alloc_tuple (2);
4126 Field (ret_v, 0) = caml_copy_double ((double) p.x);
4127 Field (ret_v, 1) = caml_copy_double ((double) p.y);
4129 if (!*s) {
4130 freepage (page);
4132 unlock (__func__);
4133 CAMLreturn (ret_v);
4136 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4137 value contents_v)
4139 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4140 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4142 if (pdf) {
4143 pdf_annot *annot;
4144 struct page *page;
4145 fz_point p;
4146 char *s = String_val (ptr_v);
4148 page = parse_pointer (__func__, s);
4149 annot = pdf_create_annot (state.ctx,
4150 pdf_page_from_fz_page (state.ctx,
4151 page->fzpage),
4152 PDF_ANNOT_TEXT);
4153 p.x = Int_val (x_v);
4154 p.y = Int_val (y_v);
4155 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4156 pdf_set_text_annot_position (state.ctx, annot, p);
4157 state.dirty = 1;
4159 CAMLreturn0;
4162 CAMLprim void ml_delannot (value ptr_v, value n_v)
4164 CAMLparam2 (ptr_v, n_v);
4165 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4167 if (pdf) {
4168 struct page *page;
4169 char *s = String_val (ptr_v);
4170 struct slink *slink;
4172 page = parse_pointer (__func__, s);
4173 slink = &page->slinks[Int_val (n_v)];
4174 pdf_delete_annot (state.ctx,
4175 pdf_page_from_fz_page (state.ctx, page->fzpage),
4176 (pdf_annot *) slink->u.annot);
4177 state.dirty = 1;
4179 CAMLreturn0;
4182 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4184 CAMLparam3 (ptr_v, n_v, str_v);
4185 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4187 if (pdf) {
4188 struct page *page;
4189 char *s = String_val (ptr_v);
4190 struct slink *slink;
4192 page = parse_pointer (__func__, s);
4193 slink = &page->slinks[Int_val (n_v)];
4194 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4195 String_val (str_v));
4196 state.dirty = 1;
4198 CAMLreturn0;
4201 CAMLprim value ml_hasunsavedchanges (value unit_v)
4203 CAMLparam1 (unit_v);
4204 CAMLreturn (Val_bool (state.dirty));
4207 CAMLprim void ml_savedoc (value path_v)
4209 CAMLparam1 (path_v);
4210 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4212 if (pdf) {
4213 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4215 CAMLreturn0;
4218 static void makestippletex (void)
4220 const char pixels[] = "\xff\xff\0\0";
4221 glGenTextures (1, &state.stid);
4222 glBindTexture (GL_TEXTURE_1D, state.stid);
4223 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4224 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4225 glTexImage1D (
4226 GL_TEXTURE_1D,
4228 GL_ALPHA,
4231 GL_ALPHA,
4232 GL_UNSIGNED_BYTE,
4233 pixels
4237 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4239 return caml_copy_string (FZ_VERSION);
4242 CAMLprim void ml_init (value csock_v, value params_v)
4244 CAMLparam2 (csock_v, params_v);
4245 CAMLlocal2 (trim_v, fuzz_v);
4246 int ret;
4247 int texcount;
4248 char *fontpath;
4249 int colorspace;
4250 int mustoresize;
4251 int haspboext;
4253 /* Without following call to setlocale mbstowcs fails for, at
4254 least, strings containing chinese symbols (δΈ­ for instance)
4255 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4256 wide character" as the reason of failure and with macOS
4257 producing bogus output) */
4258 if (setlocale (LC_CTYPE, "")) {
4259 /* Following two lines were taken from dvtm/vt.c */
4260 const char *cset = nl_langinfo (CODESET);
4261 state.utf8cs = !strcmp (cset, "UTF-8");
4263 else {
4264 fprintf (stderr, "setlocale failed\n");
4267 state.csock = Int_val (csock_v);
4268 state.rotate = Int_val (Field (params_v, 0));
4269 state.fitmodel = Int_val (Field (params_v, 1));
4270 trim_v = Field (params_v, 2);
4271 texcount = Int_val (Field (params_v, 3));
4272 state.sliceheight = Int_val (Field (params_v, 4));
4273 mustoresize = Int_val (Field (params_v, 5));
4274 colorspace = Int_val (Field (params_v, 6));
4275 fontpath = String_val (Field (params_v, 7));
4277 if (caml_string_length (Field (params_v, 8)) > 0) {
4278 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4280 if (!state.trimcachepath) {
4281 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4282 strerror (errno));
4286 haspboext = Bool_val (Field (params_v, 9));
4288 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4289 fz_register_document_handlers (state.ctx);
4291 state.trimmargins = Bool_val (Field (trim_v, 0));
4292 fuzz_v = Field (trim_v, 1);
4293 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4294 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4295 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4296 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4298 set_tex_params (colorspace);
4300 if (*fontpath) {
4301 state.face = load_font (fontpath);
4303 else {
4304 int len;
4305 const unsigned char *data;
4307 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4308 state.face = load_builtin_font (data, len);
4310 if (!state.face) _exit (1);
4312 realloctexts (texcount);
4314 if (haspboext) {
4315 setuppbo ();
4318 makestippletex ();
4320 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4321 if (ret) {
4322 errx (1, "pthread_create: %s", strerror (ret));
4325 CAMLreturn0;
4328 #if FIXME || !FIXME
4329 static void UNUSED_ATTR refmacs OPTIMIZE_ATTR (0) (void) {}
4330 #endif