Misc
[llpp.git] / link.c
blob808687d044bf09faaf70e3097ad9e527e4b4a541
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
3 #define FIXME 0
5 #include <errno.h>
6 #include <stdio.h>
7 #include <ctype.h>
8 #include <string.h>
9 #include <stdlib.h>
10 #include <signal.h>
12 #include <math.h>
13 #include <wchar.h>
14 #include <locale.h>
15 #include <langinfo.h>
17 #include <unistd.h>
18 #include <pthread.h>
19 #include <sys/uio.h>
20 #include <sys/time.h>
21 #include <sys/stat.h>
22 #include <fcntl.h>
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
25 #include <sys/utsname.h>
27 #include <spawn.h>
29 #include <regex.h>
30 #include <stdarg.h>
31 #include <limits.h>
32 #include <inttypes.h>
34 #ifdef __COCOA__
35 #include <CoreFoundation/CoreFoundation.h>
36 #endif
38 #ifdef __APPLE__
39 #include <OpenGL/gl.h>
40 #else
41 #include <GL/gl.h>
42 #endif
44 #pragma GCC diagnostic push
45 #ifdef __clang__
46 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
47 #endif
48 #pragma GCC diagnostic ignored "-Wpedantic"
49 #include <caml/fail.h>
50 #include <caml/alloc.h>
51 #include <caml/memory.h>
52 #include <caml/unixsupport.h>
54 #if __GNUC__ < 5 && !defined __clang__
55 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
56 clobbered diagnostics */
57 #pragma GCC diagnostic ignored "-Wclobbered"
58 #endif
60 #include <mupdf/fitz.h>
61 #include <mupdf/pdf.h>
63 #include <ft2build.h>
64 #include FT_FREETYPE_H
65 #pragma GCC diagnostic pop
67 #define PIGGYBACK
68 #define CACHE_PAGEREFS
70 #if defined __GNUC__
71 #define NORETURN_ATTR __attribute__ ((noreturn))
72 #define UNUSED_ATTR __attribute__ ((unused))
73 #if !defined __clang__
74 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
75 #else
76 #define OPTIMIZE_ATTR(n)
77 #endif
78 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
79 #else
80 #define NORETURN_ATTR
81 #define UNUSED_ATTR
82 #define OPTIMIZE_ATTR(n)
83 #define GCC_FMT_ATTR(a, b)
84 #endif
86 #define FMT_s "zu"
88 #define FMT_ptr PRIxPTR
89 #define SCN_ptr SCNxPTR
90 #define FMT_ptr_cast(p) ((uintptr_t) (p))
91 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
93 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
94 err (int exitcode, const char *fmt, ...)
96 va_list ap;
97 int savederrno;
99 savederrno = errno;
100 va_start (ap, fmt);
101 vfprintf (stderr, fmt, ap);
102 va_end (ap);
103 fprintf (stderr, ": %s\n", strerror (savederrno));
104 fflush (stderr);
105 _exit (exitcode);
108 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
109 errx (int exitcode, const char *fmt, ...)
111 va_list ap;
113 va_start (ap, fmt);
114 vfprintf (stderr, fmt, ap);
115 va_end (ap);
116 fputc ('\n', stderr);
117 fflush (stderr);
118 _exit (exitcode);
121 #ifndef GL_TEXTURE_RECTANGLE_ARB
122 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
123 #endif
125 #ifdef USE_NPOT
126 #define TEXT_TYPE GL_TEXTURE_2D
127 #else
128 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
129 #endif
131 #ifndef GL_BGRA
132 #define GL_BGRA 0x80E1
133 #endif
135 #ifndef GL_UNSIGNED_INT_8_8_8_8
136 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
137 #endif
139 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
140 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
141 #endif
143 #if 0
144 #define lprintf printf
145 #else
146 #define lprintf(...)
147 #endif
149 #define ARSERT(cond) for (;;) { \
150 if (!(cond)) { \
151 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
153 break; \
156 struct slice {
157 int h;
158 int texindex;
161 struct tile {
162 int w, h;
163 int slicecount;
164 int sliceheight;
165 struct bo *pbo;
166 fz_pixmap *pixmap;
167 struct slice slices[1];
170 struct pagedim {
171 int pageno;
172 int rotate;
173 int left;
174 int tctmready;
175 fz_irect bounds;
176 fz_rect pagebox;
177 fz_rect mediabox;
178 fz_matrix ctm, zoomctm, tctm;
181 struct slink {
182 enum { SLINK, SANNOT } tag;
183 fz_irect bbox;
184 union {
185 fz_link *link;
186 fz_annot *annot;
187 } u;
190 struct annot {
191 fz_irect bbox;
192 fz_annot *annot;
195 struct page {
196 int tgen;
197 int sgen;
198 int agen;
199 int pageno;
200 int pdimno;
201 fz_stext_page *text;
202 fz_page *fzpage;
203 fz_display_list *dlist;
204 fz_link *links;
205 int slinkcount;
206 struct slink *slinks;
207 int annotcount;
208 struct annot *annots;
209 struct mark {
210 fz_stext_char *ch;
211 } fmark, lmark;
214 enum { FitWidth, FitProportional, FitPage };
216 static struct {
217 int sliceheight;
218 struct pagedim *pagedims;
219 int pagecount;
220 int pagedimcount;
221 fz_document *doc;
222 fz_context *ctx;
223 int w, h;
225 int texindex;
226 int texcount;
227 GLuint *texids;
229 GLenum texiform;
230 GLenum texform;
231 GLenum texty;
233 fz_colorspace *colorspace;
235 struct {
236 int w, h;
237 struct slice *slice;
238 } *texowners;
240 int rotate;
241 int fitmodel;
242 int trimmargins;
243 int needoutline;
244 int gen;
245 int aalevel;
247 int trimanew;
248 fz_irect trimfuzz;
249 fz_pixmap *pig;
251 pthread_t thread;
252 int csock;
253 FT_Face face;
255 char *trimcachepath;
256 int cxack;
257 int dirty;
259 GLuint stid;
261 int bo_usable;
262 GLuint boid;
264 void (*glBindBufferARB) (GLenum, GLuint);
265 GLboolean (*glUnmapBufferARB) (GLenum);
266 void *(*glMapBufferARB) (GLenum, GLenum);
267 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
268 void (*glGenBuffersARB) (GLsizei, GLuint *);
269 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
271 GLfloat texcoords[8];
272 GLfloat vertices[16];
274 #ifdef CACHE_PAGEREFS
275 struct {
276 int idx;
277 int count;
278 pdf_obj **objs;
279 pdf_document *pdf;
280 } pdflut;
281 #endif
282 int utf8cs;
283 } state;
285 struct bo {
286 GLuint id;
287 void *ptr;
288 size_t size;
291 #pragma GCC diagnostic ignored "-Wdouble-promotion"
292 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
294 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
297 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
299 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
302 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
304 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
305 m.a, m.b, m.c, m.d, m.e, m.f);
307 #pragma GCC diagnostic error "-Wdouble-promotion"
309 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
311 static void lock (const char *cap)
313 int ret = pthread_mutex_lock (&mutex);
314 if (ret) {
315 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
319 static void unlock (const char *cap)
321 int ret = pthread_mutex_unlock (&mutex);
322 if (ret) {
323 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
327 static int trylock (const char *cap)
329 int ret = pthread_mutex_trylock (&mutex);
330 if (ret && ret != EBUSY) {
331 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
333 return ret == EBUSY;
336 static void *parse_pointer (const char *cap, const char *s)
338 int ret;
339 void *ptr;
341 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
342 if (ret != 1) {
343 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
345 return ptr;
348 static double now (void)
350 struct timeval tv;
352 if (gettimeofday (&tv, NULL)) {
353 err (1, "gettimeofday");
355 return tv.tv_sec + tv.tv_usec*1e-6;
358 static int hasdata (void)
360 int ret, avail;
361 ret = ioctl (state.csock, FIONREAD, &avail);
362 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
363 return avail > 0;
366 CAMLprim value ml_hasdata (value fd_v)
368 CAMLparam1 (fd_v);
369 int ret, avail;
371 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
372 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
373 CAMLreturn (Val_bool (avail > 0));
376 static void readdata (int fd, void *p, int size)
378 ssize_t n;
380 again:
381 n = read (fd, p, size);
382 if (n - size) {
383 if (n < 0 && errno == EINTR) goto again;
384 if (!n) errx (1, "EOF while reading");
385 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
389 static void writedata (int fd, char *p, int size)
391 ssize_t n;
392 uint32_t size4 = size;
393 struct iovec iov[2] = {
394 { .iov_base = &size4, .iov_len = 4 },
395 { .iov_base = p, .iov_len = size }
398 again:
399 n = writev (fd, iov, 2);
400 if (n < 0 && errno == EINTR) goto again;
401 if (n - size - 4) {
402 if (!n) errx (1, "EOF while writing data");
403 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
407 static int readlen (int fd)
409 uint32_t u;
410 readdata (fd, &u, 4);
411 return u;
414 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
416 CAMLparam3 (fd_v, bytes_v, len_v);
417 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
418 CAMLreturn0;
421 CAMLprim value ml_rcmd (value fd_v)
423 CAMLparam1 (fd_v);
424 CAMLlocal1 (strdata_v);
425 int fd = Int_val (fd_v);
426 int len = readlen (fd);
427 strdata_v = caml_alloc_string (len);
428 readdata (fd, String_val (strdata_v), len);
429 CAMLreturn (strdata_v);
432 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
434 char fbuf[64];
435 int size = sizeof (fbuf), len;
436 va_list ap;
437 char *buf = fbuf;
439 for (;;) {
440 va_start (ap, fmt);
441 len = vsnprintf (buf, size, fmt, ap);
442 va_end (ap);
444 if (len > -1) {
445 if (len < size - 4) {
446 writedata (state.csock, buf, len);
447 break;
449 else size = len + 5;
451 else {
452 err (1, "vsnprintf for `%s' failed", fmt);
454 buf = realloc (buf == fbuf ? NULL : buf, size);
455 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
457 if (buf != fbuf) free (buf);
460 static void closedoc (void)
462 #ifdef CACHE_PAGEREFS
463 if (state.pdflut.objs) {
464 for (int i = 0; i < state.pdflut.count; ++i) {
465 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
467 free (state.pdflut.objs);
468 state.pdflut.objs = NULL;
469 state.pdflut.idx = 0;
471 #endif
472 if (state.doc) {
473 fz_drop_document (state.ctx, state.doc);
474 state.doc = NULL;
478 static int openxref (char *filename, char *password)
480 for (int i = 0; i < state.texcount; ++i) {
481 state.texowners[i].w = -1;
482 state.texowners[i].slice = NULL;
485 closedoc ();
487 state.dirty = 0;
488 if (state.pagedims) {
489 free (state.pagedims);
490 state.pagedims = NULL;
492 state.pagedimcount = 0;
494 fz_set_aa_level (state.ctx, state.aalevel);
495 state.doc = fz_open_document (state.ctx, filename);
496 if (fz_needs_password (state.ctx, state.doc)) {
497 if (password && !*password) {
498 printd ("pass");
499 return 0;
501 else {
502 int ok = fz_authenticate_password (state.ctx, state.doc, password);
503 if (!ok) {
504 printd ("pass fail");
505 return 0;
509 state.pagecount = fz_count_pages (state.ctx, state.doc);
510 return 1;
513 static void pdfinfo (void)
515 struct { char *tag; char *name; } metatbl[] = {
516 { FZ_META_INFO_TITLE, "Title" },
517 { FZ_META_INFO_AUTHOR, "Author" },
518 { FZ_META_FORMAT, "Format" },
519 { FZ_META_ENCRYPTION, "Encryption" },
520 { "info:Creator", "Creator" },
521 { "info:Producer", "Producer" },
522 { "info:CreationDate", "Creation date" },
524 int len = 0;
525 char *buf = NULL;
527 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
528 int need;
529 again:
530 need = fz_lookup_metadata (state.ctx, state.doc,
531 metatbl[i].tag, buf, len);
532 if (need > 0) {
533 if (need <= len) {
534 printd ("info %s\t%s", metatbl[i].name, buf);
536 else {
537 buf = realloc (buf, need + 1);
538 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
539 len = need + 1;
540 goto again;
544 free (buf);
546 printd ("infoend");
549 static void unlinktile (struct tile *tile)
551 for (int i = 0; i < tile->slicecount; ++i) {
552 struct slice *s = &tile->slices[i];
554 if (s->texindex != -1) {
555 if (state.texowners[s->texindex].slice == s) {
556 state.texowners[s->texindex].slice = NULL;
562 static void freepage (struct page *page)
564 if (!page) return;
565 if (page->text) {
566 fz_drop_stext_page (state.ctx, page->text);
568 if (page->slinks) {
569 free (page->slinks);
571 fz_drop_display_list (state.ctx, page->dlist);
572 fz_drop_page (state.ctx, page->fzpage);
573 free (page);
576 static void freetile (struct tile *tile)
578 unlinktile (tile);
579 if (!tile->pbo) {
580 #ifndef PIGGYBACK
581 fz_drop_pixmap (state.ctx, tile->pixmap);
582 #else
583 if (state.pig) {
584 fz_drop_pixmap (state.ctx, state.pig);
586 state.pig = tile->pixmap;
587 #endif
589 else {
590 free (tile->pbo);
591 fz_drop_pixmap (state.ctx, tile->pixmap);
593 free (tile);
596 #ifdef __ALTIVEC__
597 #include <stdint.h>
598 #include <altivec.h>
600 static int cacheline32bytes;
602 static void __attribute__ ((constructor)) clcheck (void)
604 char **envp = environ;
605 unsigned long *auxv;
607 while (*envp++);
609 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
610 if (*auxv == 19) {
611 cacheline32bytes = auxv[1] == 32;
612 return;
617 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
619 size_t size = pixmap->w * pixmap->h * pixmap->n;
620 if (cacheline32bytes && size > 32) {
621 intptr_t a1, a2, diff;
622 size_t sizea, i;
623 vector unsigned char v = vec_splat_u8 (-1);
624 vector unsigned char *p;
626 a1 = a2 = (intptr_t) pixmap->samples;
627 a2 = (a1 + 31) & ~31;
628 diff = a2 - a1;
629 sizea = size - diff;
630 p = (void *) a2;
632 while (a1 != a2) *(char *) a1++ = 0xff;
633 for (i = 0; i < (sizea & ~31); i += 32) {
634 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
635 vec_st (v, i, p);
636 vec_st (v, i + 16, p);
638 while (i < sizea) *((char *) a1 + i++) = 0xff;
640 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
642 #else
643 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
644 #endif
646 static void trimctm (pdf_page *page, int pindex)
648 fz_matrix ctm;
649 struct pagedim *pdim = &state.pagedims[pindex];
651 if (!page) return;
652 if (!pdim->tctmready) {
653 fz_rect realbox, mediabox;
654 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
656 fz_rotate (&rm, -pdim->rotate);
657 fz_scale (&sm, 1, -1);
658 fz_concat (&ctm, &rm, &sm);
659 realbox = pdim->mediabox;
660 fz_transform_rect (&realbox, &ctm);
661 fz_translate (&tm, -realbox.x0, -realbox.y0);
662 fz_concat (&ctm1, &ctm, &tm);
663 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
664 fz_invert_matrix (&im, &page_ctm);
665 fz_concat (&ctm, &im, &ctm1);
666 pdim->tctm = ctm;
667 pdim->tctmready = 1;
671 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
673 fz_matrix ctm, tm;
674 ptrdiff_t pdimno = pdim - state.pagedims;
676 ARSERT (pdim - state.pagedims < INT_MAX);
677 if (pdf_specifics (state.ctx, state.doc)) {
678 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
679 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
681 else {
682 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
683 fz_concat (&ctm, &tm, &pdim->ctm);
685 return ctm;
688 static fz_matrix pagectm (struct page *page)
690 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
693 static void *loadpage (int pageno, int pindex)
695 fz_device *dev;
696 struct page *page;
698 page = calloc (sizeof (struct page), 1);
699 if (!page) {
700 err (1, "calloc page %d", pageno);
703 page->dlist = fz_new_display_list (state.ctx, NULL);
704 dev = fz_new_list_device (state.ctx, page->dlist);
705 fz_try (state.ctx) {
706 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
707 fz_run_page (state.ctx, page->fzpage, dev,
708 &fz_identity, NULL);
710 fz_catch (state.ctx) {
711 page->fzpage = NULL;
713 fz_close_device (state.ctx, dev);
714 fz_drop_device (state.ctx, dev);
716 page->pdimno = pindex;
717 page->pageno = pageno;
718 page->sgen = state.gen;
719 page->agen = state.gen;
720 page->tgen = state.gen;
721 return page;
724 static struct tile *alloctile (int h)
726 int slicecount;
727 size_t tilesize;
728 struct tile *tile;
730 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
731 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
732 tile = calloc (tilesize, 1);
733 if (!tile) {
734 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
736 for (int i = 0; i < slicecount; ++i) {
737 int sh = fz_mini (h, state.sliceheight);
738 tile->slices[i].h = sh;
739 tile->slices[i].texindex = -1;
740 h -= sh;
742 tile->slicecount = slicecount;
743 tile->sliceheight = state.sliceheight;
744 return tile;
747 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
748 struct bo *pbo)
750 fz_rect rect;
751 fz_irect bbox;
752 fz_matrix ctm;
753 fz_device *dev;
754 struct tile *tile;
755 struct pagedim *pdim;
757 tile = alloctile (h);
758 pdim = &state.pagedims[page->pdimno];
760 bbox = pdim->bounds;
761 bbox.x0 += x;
762 bbox.y0 += y;
763 bbox.x1 = bbox.x0 + w;
764 bbox.y1 = bbox.y0 + h;
766 if (state.pig) {
767 if (state.pig->w == w
768 && state.pig->h == h
769 && state.pig->colorspace == state.colorspace) {
770 tile->pixmap = state.pig;
771 tile->pixmap->x = bbox.x0;
772 tile->pixmap->y = bbox.y0;
774 else {
775 fz_drop_pixmap (state.ctx, state.pig);
777 state.pig = NULL;
779 if (!tile->pixmap) {
780 if (pbo) {
781 tile->pixmap =
782 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
783 &bbox, NULL, 1, pbo->ptr);
784 tile->pbo = pbo;
786 else {
787 tile->pixmap =
788 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
789 NULL, 1);
793 tile->w = w;
794 tile->h = h;
795 clearpixmap (tile->pixmap);
797 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
798 ctm = pagectm (page);
799 fz_rect_from_irect (&rect, &bbox);
800 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
801 fz_close_device (state.ctx, dev);
802 fz_drop_device (state.ctx, dev);
804 return tile;
807 #ifdef CACHE_PAGEREFS
808 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
809 thanks to Robin Watts */
810 static void
811 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
813 fz_context *ctx = state.ctx; /* doc->ctx; */
814 pdf_obj *kids;
815 int len;
817 if (state.pdflut.idx == state.pagecount) return;
819 kids = pdf_dict_gets (ctx, node, "Kids");
820 len = pdf_array_len (ctx, kids);
822 if (len == 0)
823 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
825 if (pdf_mark_obj (ctx, node))
826 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
827 for (int i = 0; i < len; i++) {
828 pdf_obj *kid = pdf_array_get (ctx, kids, i);
829 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
830 if (*type
831 ? !strcmp (type, "Pages")
832 : pdf_dict_gets (ctx, kid, "Kids")
833 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
834 pdf_collect_pages (doc, kid);
836 else {
837 if (*type
838 ? strcmp (type, "Page") != 0
839 : !pdf_dict_gets (ctx, kid, "MediaBox"))
840 fz_warn (ctx, "non-page object in page tree (%s)", type);
841 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
844 pdf_unmark_obj (ctx, node);
847 static void
848 pdf_load_page_objs (pdf_document *doc)
850 pdf_obj *root = pdf_dict_gets (state.ctx,
851 pdf_trailer (state.ctx, doc), "Root");
852 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
854 if (!node)
855 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
857 state.pdflut.idx = 0;
858 pdf_collect_pages (doc, node);
860 #endif
862 static void initpdims (int wthack)
864 double start, end;
865 FILE *trimf = NULL;
866 fz_rect rootmediabox = fz_empty_rect;
867 int pageno, trim, show;
868 int trimw = 0, cxcount;
869 fz_context *ctx = state.ctx;
870 pdf_document *pdf = pdf_specifics (ctx, state.doc);
872 fz_var (trimw);
873 fz_var (trimf);
874 fz_var (cxcount);
875 start = now ();
877 if (state.trimmargins && state.trimcachepath) {
878 trimf = fopen (state.trimcachepath, "rb");
879 if (!trimf) {
880 trimf = fopen (state.trimcachepath, "wb");
881 trimw = 1;
885 if (state.trimmargins || pdf || !state.cxack)
886 cxcount = state.pagecount;
887 else
888 cxcount = fz_mini (state.pagecount, 1);
890 if (pdf) {
891 pdf_obj *obj;
892 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
893 "Root/Pages/MediaBox");
894 pdf_to_rect (ctx, obj, &rootmediabox);
897 #ifdef CACHE_PAGEREFS
898 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
899 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
900 if (!state.pdflut.objs) {
901 err (1, "malloc pageobjs %zu %d %zu failed",
902 sizeof (*state.pdflut.objs), cxcount,
903 sizeof (*state.pdflut.objs) * cxcount);
905 state.pdflut.count = cxcount;
906 pdf_load_page_objs (pdf);
907 state.pdflut.pdf = pdf;
909 #endif
911 for (pageno = 0; pageno < cxcount; ++pageno) {
912 int rotate = 0;
913 struct pagedim *p;
914 fz_rect mediabox = fz_empty_rect;
916 fz_var (rotate);
917 if (pdf) {
918 pdf_obj *pageref, *pageobj;
920 #ifdef CACHE_PAGEREFS
921 pageref = state.pdflut.objs[pageno];
922 #else
923 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
924 #endif
925 pageobj = pdf_resolve_indirect (ctx, pageref);
926 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
928 if (state.trimmargins) {
929 pdf_obj *obj;
930 pdf_page *page;
932 fz_try (ctx) {
933 page = pdf_load_page (ctx, pdf, pageno);
934 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
935 trim = state.trimanew || !obj;
936 if (trim) {
937 fz_rect rect;
938 fz_device *dev;
939 fz_matrix ctm, page_ctm;
941 dev = fz_new_bbox_device (ctx, &rect);
942 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
943 fz_invert_matrix (&ctm, &page_ctm);
944 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
945 fz_close_device (ctx, dev);
946 fz_drop_device (ctx, dev);
948 rect.x0 += state.trimfuzz.x0;
949 rect.x1 += state.trimfuzz.x1;
950 rect.y0 += state.trimfuzz.y0;
951 rect.y1 += state.trimfuzz.y1;
952 fz_transform_rect (&rect, &ctm);
953 fz_intersect_rect (&rect, &mediabox);
955 if (!fz_is_empty_rect (&rect)) {
956 mediabox = rect;
959 obj = pdf_new_array (ctx, pdf, 4);
960 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
961 mediabox.x0));
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.y0));
964 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
965 mediabox.x1));
966 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
967 mediabox.y1));
968 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
970 else {
971 mediabox.x0 = pdf_to_real (ctx,
972 pdf_array_get (ctx, obj, 0));
973 mediabox.y0 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 1));
975 mediabox.x1 = pdf_to_real (ctx,
976 pdf_array_get (ctx, obj, 2));
977 mediabox.y1 = pdf_to_real (ctx,
978 pdf_array_get (ctx, obj, 3));
981 fz_drop_page (ctx, &page->super);
982 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
983 if (show) {
984 printd ("progress %f Trimming %d",
985 (double) (pageno + 1) / state.pagecount,
986 pageno + 1);
989 fz_catch (ctx) {
990 fprintf (stderr, "failed to load page %d\n", pageno+1);
993 else {
994 int empty = 0;
995 fz_rect cropbox;
997 pdf_to_rect (ctx,
998 pdf_dict_gets (ctx, pageobj, "MediaBox"),
999 &mediabox);
1000 if (fz_is_empty_rect (&mediabox)) {
1001 mediabox.x0 = 0;
1002 mediabox.y0 = 0;
1003 mediabox.x1 = 612;
1004 mediabox.y1 = 792;
1005 empty = 1;
1008 pdf_to_rect (ctx,
1009 pdf_dict_gets (ctx, pageobj, "CropBox"),
1010 &cropbox);
1011 if (!fz_is_empty_rect (&cropbox)) {
1012 if (empty) {
1013 mediabox = cropbox;
1015 else {
1016 fz_intersect_rect (&mediabox, &cropbox);
1019 else {
1020 if (empty) {
1021 if (fz_is_empty_rect (&rootmediabox)) {
1022 fprintf (stderr,
1023 "cannot find page size for page %d\n",
1024 pageno+1);
1026 else {
1027 mediabox = rootmediabox;
1033 else {
1034 if (state.trimmargins && trimw) {
1035 fz_page *page;
1037 fz_try (ctx) {
1038 page = fz_load_page (ctx, state.doc, pageno);
1039 fz_bound_page (ctx, page, &mediabox);
1040 if (state.trimmargins) {
1041 fz_rect rect;
1042 fz_device *dev;
1044 dev = fz_new_bbox_device (ctx, &rect);
1045 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1046 fz_close_device (ctx, dev);
1047 fz_drop_device (ctx, dev);
1049 rect.x0 += state.trimfuzz.x0;
1050 rect.x1 += state.trimfuzz.x1;
1051 rect.y0 += state.trimfuzz.y0;
1052 rect.y1 += state.trimfuzz.y1;
1053 fz_intersect_rect (&rect, &mediabox);
1055 if (!fz_is_empty_rect (&rect)) {
1056 mediabox = rect;
1059 fz_drop_page (ctx, page);
1060 if (!state.cxack) {
1061 printd ("progress %f loading %d",
1062 (double) (pageno + 1) / state.pagecount,
1063 pageno + 1);
1066 fz_catch (ctx) {
1068 if (trimf) {
1069 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1070 if (n - 1) {
1071 err (1, "fwrite trim mediabox");
1075 else {
1076 if (trimf) {
1077 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1078 if (n - 1) {
1079 err (1, "fread trim mediabox %d", pageno);
1082 else {
1083 fz_page *page;
1084 fz_try (ctx) {
1085 page = fz_load_page (ctx, state.doc, pageno);
1086 fz_bound_page (ctx, page, &mediabox);
1087 fz_drop_page (ctx, page);
1089 show = !state.trimmargins && pageno % 20 == 0;
1090 if (show) {
1091 printd ("progress %f Gathering dimensions %d",
1092 (double) (pageno) / state.pagecount,
1093 pageno);
1096 fz_catch (ctx) {
1097 fprintf (stderr, "failed to load page %d\n", pageno);
1103 if (state.pagedimcount == 0
1104 || ((void) (p = &state.pagedims[state.pagedimcount-1])
1105 , p->rotate != rotate)
1106 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1107 size_t size;
1109 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1110 state.pagedims = realloc (state.pagedims, size);
1111 if (!state.pagedims) {
1112 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1113 size, state.pagedimcount + 1);
1116 p = &state.pagedims[state.pagedimcount++];
1117 p->rotate = rotate;
1118 p->mediabox = mediabox;
1119 p->pageno = pageno;
1122 end = now ();
1123 if (!wthack) {
1124 printd ("progress 1 %s %d pages in %f seconds",
1125 state.trimmargins ? "Trimmed" : "Processed",
1126 state.pagecount, end - start);
1128 state.trimanew = 0;
1129 if (trimf) {
1130 if (fclose (trimf)) {
1131 err (1, "fclose");
1136 static void layout (void)
1138 int pindex;
1139 fz_rect box;
1140 fz_matrix ctm, rm;
1141 struct pagedim *p = NULL;
1142 float zw, w, maxw = 0.0, zoom = 1.0;
1144 if (state.pagedimcount == 0) return;
1146 switch (state.fitmodel) {
1147 case FitProportional:
1148 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1149 float x0, x1;
1151 p = &state.pagedims[pindex];
1152 fz_rotate (&rm, p->rotate + state.rotate);
1153 box = p->mediabox;
1154 fz_transform_rect (&box, &rm);
1156 x0 = fz_min (box.x0, box.x1);
1157 x1 = fz_max (box.x0, box.x1);
1159 w = x1 - x0;
1160 maxw = fz_max (w, maxw);
1161 zoom = state.w / maxw;
1163 break;
1165 case FitPage:
1166 maxw = state.w;
1167 break;
1169 case FitWidth:
1170 break;
1172 default:
1173 ARSERT (0 && state.fitmodel);
1176 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1177 fz_rect rect;
1178 fz_matrix tm, sm;
1180 p = &state.pagedims[pindex];
1181 fz_rotate (&ctm, state.rotate);
1182 fz_rotate (&rm, p->rotate + state.rotate);
1183 box = p->mediabox;
1184 fz_transform_rect (&box, &rm);
1185 w = box.x1 - box.x0;
1186 switch (state.fitmodel) {
1187 case FitProportional:
1188 p->left = (int) (((maxw - w) * zoom) / 2.f);
1189 break;
1190 case FitPage:
1192 float zh, h;
1193 zw = maxw / w;
1194 h = box.y1 - box.y0;
1195 zh = state.h / h;
1196 zoom = fz_min (zw, zh);
1197 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1199 break;
1200 case FitWidth:
1201 p->left = 0;
1202 zoom = state.w / w;
1203 break;
1206 fz_scale (&p->zoomctm, zoom, zoom);
1207 fz_concat (&ctm, &p->zoomctm, &ctm);
1209 fz_rotate (&rm, p->rotate);
1210 p->pagebox = p->mediabox;
1211 fz_transform_rect (&p->pagebox, &rm);
1212 p->pagebox.x1 -= p->pagebox.x0;
1213 p->pagebox.y1 -= p->pagebox.y0;
1214 p->pagebox.x0 = 0;
1215 p->pagebox.y0 = 0;
1216 rect = p->pagebox;
1217 fz_transform_rect (&rect, &ctm);
1218 fz_round_rect (&p->bounds, &rect);
1219 p->ctm = ctm;
1221 fz_translate (&tm, 0, -p->mediabox.y1);
1222 fz_scale (&sm, zoom, -zoom);
1223 fz_concat (&ctm, &tm, &sm);
1225 p->tctmready = 0;
1228 do {
1229 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1230 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1231 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1232 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1233 int boundw = x1 - x0;
1234 int boundh = y1 - y0;
1236 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1237 } while (p-- != state.pagedims);
1240 struct pagedim *pdimofpageno (int pageno)
1242 struct pagedim *pdim = state.pagedims;
1244 for (int i = 0; i < state.pagedimcount; ++i) {
1245 if (state.pagedims[i].pageno > pageno)
1246 break;
1247 pdim = &state.pagedims[i];
1249 return pdim;
1252 static void recurse_outline (fz_outline *outline, int level)
1254 while (outline) {
1255 if (outline->page >= 0) {
1256 fz_point p = {.x = outline->x, .y = outline->y};
1257 struct pagedim *pdim = pdimofpageno (outline->page);
1258 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1259 fz_transform_point (&p, &pdim->ctm);
1260 printd ("o %d %d %d %d %s",
1261 level, outline->page, (int) p.y, h, outline->title);
1263 else {
1264 printd ("on %d %s", level, outline->title);
1266 if (outline->down) {
1267 recurse_outline (outline->down, level + 1);
1269 outline = outline->next;
1273 static void process_outline (void)
1275 fz_outline *outline;
1277 if (!state.needoutline || !state.pagedimcount) return;
1279 state.needoutline = 0;
1280 outline = fz_load_outline (state.ctx, state.doc);
1281 if (outline) {
1282 recurse_outline (outline, 0);
1283 fz_drop_outline (state.ctx, outline);
1287 static char *strofline (fz_stext_line *line)
1289 char *p;
1290 char utf8[10];
1291 fz_stext_char *ch;
1292 size_t size = 0, cap = 80;
1294 p = malloc (cap + 1);
1295 if (!p) return NULL;
1297 for (ch = line->first_char; ch; ch = ch->next) {
1298 int n = fz_runetochar (utf8, ch->c);
1299 if (size + n > cap) {
1300 cap *= 2;
1301 p = realloc (p, cap + 1);
1302 if (!p) return NULL;
1305 memcpy (p + size, utf8, n);
1306 size += n;
1308 p[size] = 0;
1309 return p;
1312 static int matchline (regex_t *re, fz_stext_line *line,
1313 int stop, int pageno, double start)
1315 int ret;
1316 char *p;
1317 regmatch_t rm;
1319 p = strofline (line);
1320 if (!p) return -1;
1322 ret = regexec (re, p, 1, &rm, 0);
1323 if (ret) {
1324 free (p);
1325 if (ret != REG_NOMATCH) {
1326 size_t size;
1327 char errbuf[80];
1328 size = regerror (ret, re, errbuf, sizeof (errbuf));
1329 printd ("msg regexec error `%.*s'",
1330 (int) size, errbuf);
1331 return -1;
1333 return 0;
1335 else {
1336 fz_point p1, p2, p3, p4;
1337 fz_rect s = {0,0,0,0}, e;
1338 fz_stext_char *ch;
1339 int o = 0;
1341 for (ch = line->first_char; ch; ch = ch->next) {
1342 o += fz_runelen (ch->c);
1343 if (o > rm.rm_so) {
1344 s = ch->bbox;
1345 break;
1348 for (;ch; ch = ch->next) {
1349 o += fz_runelen (ch->c);
1350 if (o > rm.rm_eo) break;
1352 e = ch->bbox;
1354 p1.x = s.x0;
1355 p1.y = s.y0;
1356 p2.x = e.x1;
1357 p2.y = s.y0;
1358 p3.x = e.x1;
1359 p3.y = e.y1;
1360 p4.x = s.x0;
1361 p4.y = e.y1;
1363 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1364 if (!stop) {
1365 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1366 pageno, 1,
1367 p1.x, p1.y,
1368 p2.x, p2.y,
1369 p3.x, p3.y,
1370 p4.x, p4.y);
1372 printd ("progress 1 found at %d `%.*s' in %f sec",
1373 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1374 now () - start);
1376 else {
1377 printd ("match %d %d %f %f %f %f %f %f %f %f",
1378 pageno, 2,
1379 p1.x, p1.y,
1380 p2.x, p2.y,
1381 p3.x, p3.y,
1382 p4.x, p4.y);
1384 #pragma GCC diagnostic error "-Wdouble-promotion"
1385 free (p);
1386 return 1;
1390 /* wishful thinking function */
1391 static void search (regex_t *re, int pageno, int y, int forward)
1393 fz_device *tdev;
1394 fz_stext_page *text;
1395 struct pagedim *pdim;
1396 int stop = 0, niters = 0;
1397 double start, end;
1398 fz_page *page;
1399 fz_stext_block *block;
1401 start = now ();
1402 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1403 if (niters++ == 5) {
1404 niters = 0;
1405 if (hasdata ()) {
1406 printd ("progress 1 attention requested aborting search at %d",
1407 pageno);
1408 stop = 1;
1410 else {
1411 printd ("progress %f searching in page %d",
1412 (double) (pageno + 1) / state.pagecount,
1413 pageno);
1416 pdim = pdimofpageno (pageno);
1417 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1418 tdev = fz_new_stext_device (state.ctx, text, 0);
1420 page = fz_load_page (state.ctx, state.doc, pageno);
1422 fz_matrix ctm = pagectm1 (page, pdim);
1423 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1426 fz_close_device (state.ctx, tdev);
1427 fz_drop_device (state.ctx, tdev);
1429 if (forward) {
1430 for (block = text->first_block; block; block = block->next) {
1431 fz_stext_line *line;
1433 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1434 for (line = block->u.t.first_line; line; line = line->next) {
1435 if (line->bbox.y0 < y + 1) continue;
1437 switch (matchline (re, line, stop, pageno, start)) {
1438 case 0: break;
1439 case 1: stop = 1; break;
1440 case -1: stop = 1; goto endloop;
1445 else {
1446 for (block = text->last_block; block; block = block->prev) {
1447 fz_stext_line *line;
1449 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1450 for (line = block->u.t.last_line; line; line = line->prev) {
1451 if (line->bbox.y0 < y + 1) continue;
1453 switch (matchline (re, line, stop, pageno, start)) {
1454 case 0: break;
1455 case 1: stop = 1; break;
1456 case -1: stop = 1; goto endloop;
1462 if (forward) {
1463 pageno += 1;
1464 y = 0;
1466 else {
1467 pageno -= 1;
1468 y = INT_MAX;
1470 endloop:
1471 fz_drop_stext_page (state.ctx, text);
1472 fz_drop_page (state.ctx, page);
1474 end = now ();
1475 if (!stop) {
1476 printd ("progress 1 no matches %f sec", end - start);
1478 printd ("clearrects");
1481 static void set_tex_params (int colorspace)
1483 switch (colorspace) {
1484 case 0:
1485 state.texiform = GL_RGBA8;
1486 state.texform = GL_RGBA;
1487 state.texty = GL_UNSIGNED_BYTE;
1488 state.colorspace = fz_device_rgb (state.ctx);
1489 break;
1490 case 1:
1491 state.texiform = GL_RGBA8;
1492 state.texform = GL_BGRA;
1493 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1494 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1495 #else
1496 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1497 #endif
1498 state.colorspace = fz_device_bgr (state.ctx);
1499 break;
1500 case 2:
1501 state.texiform = GL_LUMINANCE_ALPHA;
1502 state.texform = GL_LUMINANCE_ALPHA;
1503 state.texty = GL_UNSIGNED_BYTE;
1504 state.colorspace = fz_device_gray (state.ctx);
1505 break;
1506 default:
1507 errx (1, "invalid colorspce %d", colorspace);
1511 static void realloctexts (int texcount)
1513 size_t size;
1515 if (texcount == state.texcount) return;
1517 if (texcount < state.texcount) {
1518 glDeleteTextures (state.texcount - texcount,
1519 state.texids + texcount);
1522 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1523 state.texids = realloc (state.texids, size);
1524 if (!state.texids) {
1525 err (1, "realloc texs %" FMT_s, size);
1528 state.texowners = (void *) (state.texids + texcount);
1529 if (texcount > state.texcount) {
1530 glGenTextures (texcount - state.texcount,
1531 state.texids + state.texcount);
1532 for (int i = state.texcount; i < texcount; ++i) {
1533 state.texowners[i].w = -1;
1534 state.texowners[i].slice = NULL;
1537 state.texcount = texcount;
1538 state.texindex = 0;
1541 static char *mbtoutf8 (char *s)
1543 char *p, *r;
1544 wchar_t *tmp;
1545 size_t i, ret, len;
1547 if (state.utf8cs) {
1548 return s;
1551 len = mbstowcs (NULL, s, strlen (s));
1552 if (len == 0) {
1553 return s;
1555 else {
1556 if (len == (size_t) -1) {
1557 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1558 return s;
1562 tmp = calloc (len, sizeof (wchar_t));
1563 if (!tmp) {
1564 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1565 len, sizeof (wchar_t), errno, strerror (errno));
1566 return s;
1569 ret = mbstowcs (tmp, s, len);
1570 if (ret == (size_t) -1) {
1571 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1572 len, errno, strerror (errno));
1573 free (tmp);
1574 return s;
1577 len = 0;
1578 for (i = 0; i < ret; ++i) {
1579 len += fz_runelen (tmp[i]);
1582 p = r = malloc (len + 1);
1583 if (!r) {
1584 printd ("emsg mbtoutf8: malloc(%zu)", len);
1585 free (tmp);
1586 return s;
1589 for (i = 0; i < ret; ++i) {
1590 p += fz_runetochar (p, tmp[i]);
1592 *p = 0;
1593 free (tmp);
1594 return r;
1597 CAMLprim value ml_mbtoutf8 (value s_v)
1599 CAMLparam1 (s_v);
1600 CAMLlocal1 (ret_v);
1601 char *s, *r;
1603 s = String_val (s_v);
1604 r = mbtoutf8 (s);
1605 if (r == s) {
1606 ret_v = s_v;
1608 else {
1609 ret_v = caml_copy_string (r);
1610 free (r);
1612 CAMLreturn (ret_v);
1615 static void * mainloop (void UNUSED_ATTR *unused)
1617 char *p = NULL;
1618 int len, ret, oldlen = 0;
1620 fz_var (p);
1621 fz_var (oldlen);
1622 for (;;) {
1623 len = readlen (state.csock);
1624 if (len == 0) {
1625 errx (1, "readlen returned 0");
1628 if (oldlen < len + 1) {
1629 p = realloc (p, len + 1);
1630 if (!p) {
1631 err (1, "realloc %d failed", len + 1);
1633 oldlen = len + 1;
1635 readdata (state.csock, p, len);
1636 p[len] = 0;
1638 if (!strncmp ("open", p, 4)) {
1639 int wthack, off, usedoccss, ok = 0;
1640 char *password;
1641 char *filename;
1642 char *utf8filename;
1643 size_t filenamelen;
1645 fz_var (ok);
1646 ret = sscanf (p + 5, " %d %d %d %n",
1647 &wthack, &state.cxack, &usedoccss, &off);
1648 if (ret != 3) {
1649 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1652 filename = p + 5 + off;
1653 filenamelen = strlen (filename);
1654 password = filename + filenamelen + 1;
1656 if (password[strlen (password) + 1]) {
1657 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1660 lock ("open");
1661 fz_set_use_document_css (state.ctx, usedoccss);
1662 fz_try (state.ctx) {
1663 ok = openxref (filename, password);
1665 fz_catch (state.ctx) {
1666 utf8filename = mbtoutf8 (filename);
1667 printd ("msg Could not open %s", utf8filename);
1668 if (utf8filename != filename) {
1669 free (utf8filename);
1672 if (ok) {
1673 pdfinfo ();
1674 initpdims (wthack);
1676 unlock ("open");
1678 if (ok) {
1679 if (!wthack) {
1680 utf8filename = mbtoutf8 (filename);
1681 printd ("msg Opened %s (press h/F1 to get help)",
1682 utf8filename);
1683 if (utf8filename != filename) {
1684 free (utf8filename);
1687 state.needoutline = 1;
1690 else if (!strncmp ("cs", p, 2)) {
1691 int i, colorspace;
1693 ret = sscanf (p + 2, " %d", &colorspace);
1694 if (ret != 1) {
1695 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1697 lock ("cs");
1698 set_tex_params (colorspace);
1699 for (i = 0; i < state.texcount; ++i) {
1700 state.texowners[i].w = -1;
1701 state.texowners[i].slice = NULL;
1703 unlock ("cs");
1705 else if (!strncmp ("freepage", p, 8)) {
1706 void *ptr;
1708 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1709 if (ret != 1) {
1710 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1712 lock ("freepage");
1713 freepage (ptr);
1714 unlock ("freepage");
1716 else if (!strncmp ("freetile", p, 8)) {
1717 void *ptr;
1719 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1720 if (ret != 1) {
1721 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1723 lock ("freetile");
1724 freetile (ptr);
1725 unlock ("freetile");
1727 else if (!strncmp ("search", p, 6)) {
1728 int icase, pageno, y, len2, forward;
1729 char *pattern;
1730 regex_t re;
1732 ret = sscanf (p + 6, " %d %d %d %d,%n",
1733 &icase, &pageno, &y, &forward, &len2);
1734 if (ret != 4) {
1735 errx (1, "malformed search `%s' ret=%d", p, ret);
1738 pattern = p + 6 + len2;
1739 ret = regcomp (&re, pattern,
1740 REG_EXTENDED | (icase ? REG_ICASE : 0));
1741 if (ret) {
1742 char errbuf[80];
1743 size_t size;
1745 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1746 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1748 else {
1749 search (&re, pageno, y, forward);
1750 regfree (&re);
1753 else if (!strncmp ("geometry", p, 8)) {
1754 int w, h, fitmodel;
1756 printd ("clear");
1757 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1758 if (ret != 3) {
1759 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1762 lock ("geometry");
1763 state.h = h;
1764 if (w != state.w) {
1765 state.w = w;
1766 for (int i = 0; i < state.texcount; ++i) {
1767 state.texowners[i].slice = NULL;
1770 state.fitmodel = fitmodel;
1771 layout ();
1772 process_outline ();
1774 state.gen++;
1775 unlock ("geometry");
1776 printd ("continue %d", state.pagecount);
1778 else if (!strncmp ("reqlayout", p, 9)) {
1779 char *nameddest;
1780 int rotate, off, h;
1781 int fitmodel;
1782 pdf_document *pdf;
1784 printd ("clear");
1785 ret = sscanf (p + 9, " %d %d %d %n",
1786 &rotate, &fitmodel, &h, &off);
1787 if (ret != 3) {
1788 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1790 lock ("reqlayout");
1791 pdf = pdf_specifics (state.ctx, state.doc);
1792 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1793 state.gen += 1;
1795 state.rotate = rotate;
1796 state.fitmodel = fitmodel;
1797 state.h = h;
1798 layout ();
1799 process_outline ();
1801 nameddest = p + 9 + off;
1802 if (pdf && nameddest && *nameddest) {
1803 fz_point xy;
1804 struct pagedim *pdim;
1805 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1806 &xy.x, &xy.y);
1807 pdim = pdimofpageno (pageno);
1808 fz_transform_point (&xy, &pdim->ctm);
1809 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1812 state.gen++;
1813 unlock ("reqlayout");
1814 printd ("continue %d", state.pagecount);
1816 else if (!strncmp ("page", p, 4)) {
1817 double a, b;
1818 struct page *page;
1819 int pageno, pindex;
1821 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1822 if (ret != 2) {
1823 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1826 lock ("page");
1827 a = now ();
1828 page = loadpage (pageno, pindex);
1829 b = now ();
1830 unlock ("page");
1832 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1834 else if (!strncmp ("tile", p, 4)) {
1835 int x, y, w, h;
1836 struct page *page;
1837 struct tile *tile;
1838 double a, b;
1839 void *data;
1841 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1842 SCN_ptr_cast (&page), &x, &y, &w, &h,
1843 SCN_ptr_cast (&data));
1844 if (ret != 6) {
1845 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1848 lock ("tile");
1849 a = now ();
1850 tile = rendertile (page, x, y, w, h, data);
1851 b = now ();
1852 unlock ("tile");
1854 printd ("tile %d %d %" FMT_ptr " %u %f",
1855 x, y,
1856 FMT_ptr_cast (tile),
1857 tile->w * tile->h * tile->pixmap->n,
1858 b - a);
1860 else if (!strncmp ("trimset", p, 7)) {
1861 fz_irect fuzz;
1862 int trimmargins;
1864 ret = sscanf (p + 7, " %d %d %d %d %d",
1865 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1866 if (ret != 5) {
1867 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1869 lock ("trimset");
1870 state.trimmargins = trimmargins;
1871 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1872 state.trimanew = 1;
1873 state.trimfuzz = fuzz;
1875 unlock ("trimset");
1877 else if (!strncmp ("settrim", p, 7)) {
1878 fz_irect fuzz;
1879 int trimmargins;
1881 ret = sscanf (p + 7, " %d %d %d %d %d",
1882 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1883 if (ret != 5) {
1884 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1886 printd ("clear");
1887 lock ("settrim");
1888 state.trimmargins = trimmargins;
1889 state.needoutline = 1;
1890 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1891 state.trimanew = 1;
1892 state.trimfuzz = fuzz;
1894 state.pagedimcount = 0;
1895 free (state.pagedims);
1896 state.pagedims = NULL;
1897 initpdims (0);
1898 layout ();
1899 process_outline ();
1900 unlock ("settrim");
1901 printd ("continue %d", state.pagecount);
1903 else if (!strncmp ("sliceh", p, 6)) {
1904 int h;
1906 ret = sscanf (p + 6, " %d", &h);
1907 if (ret != 1) {
1908 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1910 if (h != state.sliceheight) {
1911 state.sliceheight = h;
1912 for (int i = 0; i < state.texcount; ++i) {
1913 state.texowners[i].w = -1;
1914 state.texowners[i].h = -1;
1915 state.texowners[i].slice = NULL;
1919 else if (!strncmp ("interrupt", p, 9)) {
1920 printd ("vmsg interrupted");
1922 else {
1923 errx (1, "unknown command %.*s", len, p);
1926 return 0;
1929 CAMLprim value ml_isexternallink (value uri_v)
1931 CAMLparam1 (uri_v);
1932 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1933 CAMLreturn (Val_bool (ext));
1936 CAMLprim value ml_uritolocation (value uri_v)
1938 CAMLparam1 (uri_v);
1939 CAMLlocal1 (ret_v);
1940 int pageno;
1941 fz_point xy;
1942 struct pagedim *pdim;
1944 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1945 &xy.x, &xy.y);
1946 pdim = pdimofpageno (pageno);
1947 fz_transform_point (&xy, &pdim->ctm);
1948 ret_v = caml_alloc_tuple (3);
1949 Field (ret_v, 0) = Val_int (pageno);
1950 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1951 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1952 CAMLreturn (ret_v);
1955 CAMLprim value ml_realloctexts (value texcount_v)
1957 CAMLparam1 (texcount_v);
1958 int ok;
1960 if (trylock (__func__)) {
1961 ok = 0;
1962 goto done;
1964 realloctexts (Int_val (texcount_v));
1965 ok = 1;
1966 unlock (__func__);
1968 done:
1969 CAMLreturn (Val_bool (ok));
1972 static void recti (int x0, int y0, int x1, int y1)
1974 GLfloat *v = state.vertices;
1976 glVertexPointer (2, GL_FLOAT, 0, v);
1977 v[0] = x0; v[1] = y0;
1978 v[2] = x1; v[3] = y0;
1979 v[4] = x0; v[5] = y1;
1980 v[6] = x1; v[7] = y1;
1981 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1984 static void showsel (struct page *page, int ox, int oy)
1986 fz_irect bbox;
1987 fz_rect rect;
1988 fz_stext_block *block;
1989 int seen = 0;
1990 unsigned char selcolor[] = {15,15,15,140};
1992 if (!page->fmark.ch || !page->lmark.ch) return;
1994 glEnable (GL_BLEND);
1995 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1996 glColor4ubv (selcolor);
1998 ox += state.pagedims[page->pdimno].bounds.x0;
1999 oy += state.pagedims[page->pdimno].bounds.y0;
2001 for (block = page->text->first_block; block; block = block->next) {
2002 fz_stext_line *line;
2004 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2005 for (line = block->u.t.first_line; line; line = line->next) {
2006 fz_stext_char *ch;
2008 rect = fz_empty_rect;
2009 for (ch = line->first_char; ch; ch = ch->next) {
2010 if (ch == page->fmark.ch) seen = 1;
2011 if (seen) fz_union_rect (&rect, &ch->bbox);
2012 if (ch == page->lmark.ch) {
2013 fz_round_rect (&bbox, &rect);
2014 recti (bbox.x0 + ox, bbox.y0 + oy,
2015 bbox.x1 + ox, bbox.y1 + oy);
2016 goto done;
2019 fz_round_rect (&bbox, &rect);
2020 recti (bbox.x0 + ox, bbox.y0 + oy,
2021 bbox.x1 + ox, bbox.y1 + oy);
2024 done:
2025 glDisable (GL_BLEND);
2028 #pragma GCC diagnostic push
2029 #pragma GCC diagnostic ignored "-Wdouble-promotion"
2030 #pragma GCC diagnostic ignored "-Wconversion"
2031 #include "glfont.c"
2032 #pragma GCC diagnostic pop
2034 static void stipplerect (fz_matrix *m,
2035 fz_point *p1,
2036 fz_point *p2,
2037 fz_point *p3,
2038 fz_point *p4,
2039 GLfloat *texcoords,
2040 GLfloat *vertices)
2042 fz_transform_point (p1, m);
2043 fz_transform_point (p2, m);
2044 fz_transform_point (p3, m);
2045 fz_transform_point (p4, m);
2047 float w, h, s, t;
2049 w = p2->x - p1->x;
2050 h = p2->y - p1->y;
2051 t = hypotf (w, h) * .25f;
2053 w = p3->x - p2->x;
2054 h = p3->y - p2->y;
2055 s = hypotf (w, h) * .25f;
2057 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2058 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2060 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2061 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2063 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2064 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2066 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2067 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2069 glDrawArrays (GL_LINES, 0, 8);
2072 static void solidrect (fz_matrix *m,
2073 fz_point *p1,
2074 fz_point *p2,
2075 fz_point *p3,
2076 fz_point *p4,
2077 GLfloat *vertices)
2079 fz_transform_point (p1, m);
2080 fz_transform_point (p2, m);
2081 fz_transform_point (p3, m);
2082 fz_transform_point (p4, m);
2083 vertices[0] = p1->x; vertices[1] = p1->y;
2084 vertices[2] = p2->x; vertices[3] = p2->y;
2086 vertices[4] = p3->x; vertices[5] = p3->y;
2087 vertices[6] = p4->x; vertices[7] = p4->y;
2088 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2091 static void ensurelinks (struct page *page)
2093 if (!page->links)
2094 page->links = fz_load_links (state.ctx, page->fzpage);
2097 static void highlightlinks (struct page *page, int xoff, int yoff)
2099 fz_matrix ctm, tm, pm;
2100 fz_link *link;
2101 GLfloat *texcoords = state.texcoords;
2102 GLfloat *vertices = state.vertices;
2104 ensurelinks (page);
2106 glEnable (GL_TEXTURE_1D);
2107 glEnable (GL_BLEND);
2108 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2109 glBindTexture (GL_TEXTURE_1D, state.stid);
2111 xoff -= state.pagedims[page->pdimno].bounds.x0;
2112 yoff -= state.pagedims[page->pdimno].bounds.y0;
2113 fz_translate (&tm, xoff, yoff);
2114 pm = pagectm (page);
2115 fz_concat (&ctm, &pm, &tm);
2117 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2118 glVertexPointer (2, GL_FLOAT, 0, vertices);
2120 for (link = page->links; link; link = link->next) {
2121 fz_point p1, p2, p3, p4;
2123 p1.x = link->rect.x0;
2124 p1.y = link->rect.y0;
2126 p2.x = link->rect.x1;
2127 p2.y = link->rect.y0;
2129 p3.x = link->rect.x1;
2130 p3.y = link->rect.y1;
2132 p4.x = link->rect.x0;
2133 p4.y = link->rect.y1;
2135 /* TODO: different colours for different schemes */
2136 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2137 else glColor3ub (255, 0, 0);
2139 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2142 for (int i = 0; i < page->annotcount; ++i) {
2143 fz_point p1, p2, p3, p4;
2144 struct annot *annot = &page->annots[i];
2146 p1.x = annot->bbox.x0;
2147 p1.y = annot->bbox.y0;
2149 p2.x = annot->bbox.x1;
2150 p2.y = annot->bbox.y0;
2152 p3.x = annot->bbox.x1;
2153 p3.y = annot->bbox.y1;
2155 p4.x = annot->bbox.x0;
2156 p4.y = annot->bbox.y1;
2158 glColor3ub (0, 0, 128);
2159 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2162 glDisable (GL_BLEND);
2163 glDisable (GL_TEXTURE_1D);
2166 static int compareslinks (const void *l, const void *r)
2168 struct slink const *ls = l;
2169 struct slink const *rs = r;
2170 if (ls->bbox.y0 == rs->bbox.y0) {
2171 return rs->bbox.x0 - rs->bbox.x0;
2173 return ls->bbox.y0 - rs->bbox.y0;
2176 static void droptext (struct page *page)
2178 if (page->text) {
2179 fz_drop_stext_page (state.ctx, page->text);
2180 page->fmark.ch = NULL;
2181 page->lmark.ch = NULL;
2182 page->text = NULL;
2186 static void dropannots (struct page *page)
2188 if (page->annots) {
2189 free (page->annots);
2190 page->annots = NULL;
2191 page->annotcount = 0;
2195 static void ensureannots (struct page *page)
2197 int i, count = 0;
2198 size_t annotsize = sizeof (*page->annots);
2199 fz_annot *annot;
2201 if (state.gen != page->agen) {
2202 dropannots (page);
2203 page->agen = state.gen;
2205 if (page->annots) return;
2207 for (annot = fz_first_annot (state.ctx, page->fzpage);
2208 annot;
2209 annot = fz_next_annot (state.ctx, annot)) {
2210 count++;
2213 if (count > 0) {
2214 page->annotcount = count;
2215 page->annots = calloc (count, annotsize);
2216 if (!page->annots) {
2217 err (1, "calloc annots %d", count);
2220 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2221 annot;
2222 annot = fz_next_annot (state.ctx, annot), i++) {
2223 fz_rect rect;
2225 fz_bound_annot (state.ctx, annot, &rect);
2226 page->annots[i].annot = annot;
2227 fz_round_rect (&page->annots[i].bbox, &rect);
2232 static void dropslinks (struct page *page)
2234 if (page->slinks) {
2235 free (page->slinks);
2236 page->slinks = NULL;
2237 page->slinkcount = 0;
2239 if (page->links) {
2240 fz_drop_link (state.ctx, page->links);
2241 page->links = NULL;
2245 static void ensureslinks (struct page *page)
2247 fz_matrix ctm;
2248 int i, count;
2249 size_t slinksize = sizeof (*page->slinks);
2250 fz_link *link;
2252 ensureannots (page);
2253 if (state.gen != page->sgen) {
2254 dropslinks (page);
2255 page->sgen = state.gen;
2257 if (page->slinks) return;
2259 ensurelinks (page);
2260 ctm = pagectm (page);
2262 count = page->annotcount;
2263 for (link = page->links; link; link = link->next) {
2264 count++;
2266 if (count > 0) {
2267 int j;
2269 page->slinkcount = count;
2270 page->slinks = calloc (count, slinksize);
2271 if (!page->slinks) {
2272 err (1, "calloc slinks %d", count);
2275 for (i = 0, link = page->links; link; ++i, link = link->next) {
2276 fz_rect rect;
2278 rect = link->rect;
2279 fz_transform_rect (&rect, &ctm);
2280 page->slinks[i].tag = SLINK;
2281 page->slinks[i].u.link = link;
2282 fz_round_rect (&page->slinks[i].bbox, &rect);
2284 for (j = 0; j < page->annotcount; ++j, ++i) {
2285 fz_rect rect;
2286 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2287 fz_transform_rect (&rect, &ctm);
2288 fz_round_rect (&page->slinks[i].bbox, &rect);
2290 page->slinks[i].tag = SANNOT;
2291 page->slinks[i].u.annot = page->annots[j].annot;
2293 qsort (page->slinks, count, slinksize, compareslinks);
2297 #pragma GCC diagnostic push
2298 #pragma GCC diagnostic ignored "-Wconversion"
2299 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2300 static void fmt_linkn (char *s, unsigned int u)
2302 unsigned int len; unsigned int q;
2303 unsigned int zma = 'z' - 'a' + 1;
2304 len = 1; q = u;
2305 while (q > zma - 1) { ++len; q /= zma; }
2306 if (s) {
2307 s += len;
2308 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2309 /* handles u == 0 */
2311 s[len] = 0;
2313 #pragma GCC diagnostic pop
2315 static void highlightslinks (struct page *page, int xoff, int yoff,
2316 int noff, char *targ, mlsize_t tlen, int hfsize)
2318 char buf[40];
2319 struct slink *slink;
2320 float x0, y0, x1, y1, w;
2322 ensureslinks (page);
2323 glColor3ub (0xc3, 0xb0, 0x91);
2324 for (int i = 0; i < page->slinkcount; ++i) {
2325 fmt_linkn (buf, i + noff);
2326 if (!tlen || !strncmp (targ, buf, tlen)) {
2327 slink = &page->slinks[i];
2329 x0 = slink->bbox.x0 + xoff - 5;
2330 y1 = slink->bbox.y0 + yoff - 5;
2331 y0 = y1 + 10 + hfsize;
2332 w = measure_string (state.face, hfsize, buf);
2333 x1 = x0 + w + 10;
2334 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2338 glEnable (GL_BLEND);
2339 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2340 glEnable (GL_TEXTURE_2D);
2341 glColor3ub (0, 0, 0);
2342 for (int i = 0; i < page->slinkcount; ++i) {
2343 fmt_linkn (buf, i + noff);
2344 if (!tlen || !strncmp (targ, buf, tlen)) {
2345 slink = &page->slinks[i];
2347 x0 = slink->bbox.x0 + xoff;
2348 y0 = slink->bbox.y0 + yoff + hfsize;
2349 draw_string (state.face, hfsize, x0, y0, buf);
2352 glDisable (GL_TEXTURE_2D);
2353 glDisable (GL_BLEND);
2356 static void uploadslice (struct tile *tile, struct slice *slice)
2358 int offset;
2359 struct slice *slice1;
2360 unsigned char *texdata;
2362 offset = 0;
2363 for (slice1 = tile->slices; slice != slice1; slice1++) {
2364 offset += slice1->h * tile->w * tile->pixmap->n;
2366 if (slice->texindex != -1 && slice->texindex < state.texcount
2367 && state.texowners[slice->texindex].slice == slice) {
2368 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2370 else {
2371 int subimage = 0;
2372 int texindex = state.texindex++ % state.texcount;
2374 if (state.texowners[texindex].w == tile->w) {
2375 if (state.texowners[texindex].h >= slice->h) {
2376 subimage = 1;
2378 else {
2379 state.texowners[texindex].h = slice->h;
2382 else {
2383 state.texowners[texindex].h = slice->h;
2386 state.texowners[texindex].w = tile->w;
2387 state.texowners[texindex].slice = slice;
2388 slice->texindex = texindex;
2390 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2391 #if TEXT_TYPE == GL_TEXTURE_2D
2392 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2393 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2394 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2395 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2396 #endif
2397 if (tile->pbo) {
2398 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2399 texdata = 0;
2401 else {
2402 texdata = tile->pixmap->samples;
2404 if (subimage) {
2405 glTexSubImage2D (TEXT_TYPE,
2409 tile->w,
2410 slice->h,
2411 state.texform,
2412 state.texty,
2413 texdata+offset
2416 else {
2417 glTexImage2D (TEXT_TYPE,
2419 state.texiform,
2420 tile->w,
2421 slice->h,
2423 state.texform,
2424 state.texty,
2425 texdata+offset
2428 if (tile->pbo) {
2429 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2434 CAMLprim void ml_begintiles (value unit_v)
2436 CAMLparam1 (unit_v);
2437 glEnable (TEXT_TYPE);
2438 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2439 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2440 CAMLreturn0;
2443 CAMLprim void ml_endtiles (value unit_v)
2445 CAMLparam1 (unit_v);
2446 glDisable (TEXT_TYPE);
2447 CAMLreturn0;
2450 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2452 CAMLparam2 (args_v, ptr_v);
2453 int dispx = Int_val (Field (args_v, 0));
2454 int dispy = Int_val (Field (args_v, 1));
2455 int dispw = Int_val (Field (args_v, 2));
2456 int disph = Int_val (Field (args_v, 3));
2457 int tilex = Int_val (Field (args_v, 4));
2458 int tiley = Int_val (Field (args_v, 5));
2459 char *s = String_val (ptr_v);
2460 struct tile *tile = parse_pointer (__func__, s);
2461 int slicey, firstslice;
2462 struct slice *slice;
2463 GLfloat *texcoords = state.texcoords;
2464 GLfloat *vertices = state.vertices;
2466 firstslice = tiley / tile->sliceheight;
2467 slice = &tile->slices[firstslice];
2468 slicey = tiley % tile->sliceheight;
2470 while (disph > 0) {
2471 int dh;
2473 dh = slice->h - slicey;
2474 dh = fz_mini (disph, dh);
2475 uploadslice (tile, slice);
2477 texcoords[0] = tilex; texcoords[1] = slicey;
2478 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2479 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2480 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2482 vertices[0] = dispx; vertices[1] = dispy;
2483 vertices[2] = dispx+dispw; vertices[3] = dispy;
2484 vertices[4] = dispx; vertices[5] = dispy+dh;
2485 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2487 #if TEXT_TYPE == GL_TEXTURE_2D
2488 for (int i = 0; i < 8; ++i) {
2489 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2491 #endif
2493 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2494 dispy += dh;
2495 disph -= dh;
2496 slice++;
2497 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2498 slicey = 0;
2500 CAMLreturn0;
2503 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2505 fz_matrix ctm, tm, pm;
2506 fz_point p1, p2, p3, p4;
2507 GLfloat *vertices = state.vertices;
2508 double *v = (double *) rects_v;
2510 xoff -= state.pagedims[page->pdimno].bounds.x0;
2511 yoff -= state.pagedims[page->pdimno].bounds.y0;
2512 fz_translate (&tm, xoff, yoff);
2513 pm = pagectm (page);
2514 fz_concat (&ctm, &pm, &tm);
2516 glEnable (GL_BLEND);
2517 glVertexPointer (2, GL_FLOAT, 0, vertices);
2519 glColor4dv (v);
2520 p1.x = (float) v[4];
2521 p1.y = (float) v[5];
2523 p2.x = (float) v[6];
2524 p2.y = (float) v[5];
2526 p3.x = (float) v[6];
2527 p3.y = (float) v[7];
2529 p4.x = (float) v[4];
2530 p4.y = (float) v[7];
2531 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2532 glDisable (GL_BLEND);
2535 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2536 value xoff_v, value yoff_v,
2537 value li_v)
2539 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2540 int xoff = Int_val (xoff_v);
2541 int yoff = Int_val (yoff_v);
2542 int noff = Int_val (Field (li_v, 0));
2543 char *targ = String_val (Field (li_v, 1));
2544 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2545 int hfsize = Int_val (Field (li_v, 2));
2546 char *s = String_val (ptr_v);
2547 int hlmask = Int_val (hlinks_v);
2548 struct page *page = parse_pointer (__func__, s);
2550 if (!page->fzpage) {
2551 /* deal with loadpage failed pages */
2552 goto done;
2555 if (trylock (__func__)) {
2556 noff = -1;
2557 goto done;
2560 ensureannots (page);
2561 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2562 if (hlmask & 2) {
2563 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2564 noff = page->slinkcount;
2566 if (page->tgen == state.gen) {
2567 showsel (page, xoff, yoff);
2569 unlock (__func__);
2571 done:
2572 CAMLreturn (Val_int (noff));
2575 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2576 value rects_v)
2578 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2579 int xoff = Int_val (xoff_v);
2580 int yoff = Int_val (yoff_v);
2581 char *s = String_val (ptr_v);
2582 struct page *page = parse_pointer (__func__, s);
2584 drawprect (page, xoff, yoff, rects_v);
2585 CAMLreturn0;
2588 static struct annot *getannot (struct page *page, int x, int y)
2590 fz_point p;
2591 fz_matrix ctm;
2592 const fz_matrix *tctm;
2593 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2595 if (!page->annots) return NULL;
2597 if (pdf) {
2598 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2599 tctm = &state.pagedims[page->pdimno].tctm;
2601 else {
2602 tctm = &fz_identity;
2605 p.x = x;
2606 p.y = y;
2608 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2609 fz_invert_matrix (&ctm, &ctm);
2610 fz_transform_point (&p, &ctm);
2612 if (pdf) {
2613 for (int i = 0; i < page->annotcount; ++i) {
2614 struct annot *a = &page->annots[i];
2615 fz_rect rect;
2617 fz_bound_annot (state.ctx, a->annot, &rect);
2618 if (p.x >= rect.x0 && p.x <= rect.x1) {
2619 if (p.y >= rect.y0 && p.y <= rect.y1)
2620 return a;
2624 return NULL;
2627 static fz_link *getlink (struct page *page, int x, int y)
2629 fz_point p;
2630 fz_matrix ctm;
2631 fz_link *link;
2633 ensureslinks (page);
2635 p.x = x;
2636 p.y = y;
2638 ctm = pagectm (page);
2639 fz_invert_matrix (&ctm, &ctm);
2640 fz_transform_point (&p, &ctm);
2642 for (link = page->links; link; link = link->next) {
2643 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2644 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2645 return link;
2649 return NULL;
2652 static void ensuretext (struct page *page)
2654 if (state.gen != page->tgen) {
2655 droptext (page);
2656 page->tgen = state.gen;
2658 if (!page->text) {
2659 fz_matrix ctm;
2660 fz_device *tdev;
2662 page->text = fz_new_stext_page (state.ctx,
2663 &state.pagedims[page->pdimno].mediabox);
2664 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2665 ctm = pagectm (page);
2666 fz_run_display_list (state.ctx, page->dlist,
2667 tdev, &ctm, &fz_infinite_rect, NULL);
2668 fz_close_device (state.ctx, tdev);
2669 fz_drop_device (state.ctx, tdev);
2673 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2675 CAMLparam2 (start_page_v, dir_v);
2676 CAMLlocal1 (ret_v);
2677 int i, dir = Int_val (dir_v);
2678 int start_page = Int_val (start_page_v);
2679 int end_page = dir > 0 ? state.pagecount : -1;
2680 pdf_document *pdf;
2682 fz_var (end_page);
2683 ret_v = Val_int (0);
2684 lock (__func__);
2685 pdf = pdf_specifics (state.ctx, state.doc);
2686 for (i = start_page + dir; i != end_page; i += dir) {
2687 int found;
2689 fz_var (found);
2690 if (pdf) {
2691 pdf_page *page = NULL;
2693 fz_var (page);
2694 fz_try (state.ctx) {
2695 page = pdf_load_page (state.ctx, pdf, i);
2696 found = !!page->links || !!page->annots;
2698 fz_catch (state.ctx) {
2699 found = 0;
2701 if (page) {
2702 fz_drop_page (state.ctx, &page->super);
2705 else {
2706 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2707 fz_link *link = fz_load_links (state.ctx, page);
2708 found = !!link;
2709 fz_drop_link (state.ctx, link);
2710 fz_drop_page (state.ctx, page);
2713 if (found) {
2714 ret_v = caml_alloc_small (1, 1);
2715 Field (ret_v, 0) = Val_int (i);
2716 goto unlock;
2719 unlock:
2720 unlock (__func__);
2721 CAMLreturn (ret_v);
2724 enum { dir_first, dir_last };
2725 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2727 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2729 CAMLparam2 (ptr_v, dir_v);
2730 CAMLlocal2 (ret_v, pos_v);
2731 struct page *page;
2732 int dirtag, i, slinkindex;
2733 struct slink *found = NULL ,*slink;
2734 char *s = String_val (ptr_v);
2736 page = parse_pointer (__func__, s);
2737 ret_v = Val_int (0);
2738 lock (__func__);
2739 ensureslinks (page);
2741 if (Is_block (dir_v)) {
2742 dirtag = Tag_val (dir_v);
2743 switch (dirtag) {
2744 case dir_first_visible:
2746 int x0, y0, dir, first_index, last_index;
2748 pos_v = Field (dir_v, 0);
2749 x0 = Int_val (Field (pos_v, 0));
2750 y0 = Int_val (Field (pos_v, 1));
2751 dir = Int_val (Field (pos_v, 2));
2753 if (dir >= 0) {
2754 dir = 1;
2755 first_index = 0;
2756 last_index = page->slinkcount;
2758 else {
2759 first_index = page->slinkcount - 1;
2760 last_index = -1;
2763 for (i = first_index; i != last_index; i += dir) {
2764 slink = &page->slinks[i];
2765 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2766 found = slink;
2767 break;
2771 break;
2773 case dir_left:
2774 slinkindex = Int_val (Field (dir_v, 0));
2775 found = &page->slinks[slinkindex];
2776 for (i = slinkindex - 1; i >= 0; --i) {
2777 slink = &page->slinks[i];
2778 if (slink->bbox.x0 < found->bbox.x0) {
2779 found = slink;
2780 break;
2783 break;
2785 case dir_right:
2786 slinkindex = Int_val (Field (dir_v, 0));
2787 found = &page->slinks[slinkindex];
2788 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2789 slink = &page->slinks[i];
2790 if (slink->bbox.x0 > found->bbox.x0) {
2791 found = slink;
2792 break;
2795 break;
2797 case dir_down:
2798 slinkindex = Int_val (Field (dir_v, 0));
2799 found = &page->slinks[slinkindex];
2800 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2801 slink = &page->slinks[i];
2802 if (slink->bbox.y0 >= found->bbox.y0) {
2803 found = slink;
2804 break;
2807 break;
2809 case dir_up:
2810 slinkindex = Int_val (Field (dir_v, 0));
2811 found = &page->slinks[slinkindex];
2812 for (i = slinkindex - 1; i >= 0; --i) {
2813 slink = &page->slinks[i];
2814 if (slink->bbox.y0 <= found->bbox.y0) {
2815 found = slink;
2816 break;
2819 break;
2822 else {
2823 dirtag = Int_val (dir_v);
2824 switch (dirtag) {
2825 case dir_first:
2826 found = page->slinks;
2827 break;
2829 case dir_last:
2830 if (page->slinks) {
2831 found = page->slinks + (page->slinkcount - 1);
2833 break;
2836 if (found) {
2837 ret_v = caml_alloc_small (2, 1);
2838 Field (ret_v, 0) = Val_int (found - page->slinks);
2841 unlock (__func__);
2842 CAMLreturn (ret_v);
2845 enum { uuri, utext, uannot };
2847 CAMLprim value ml_getlink (value ptr_v, value n_v)
2849 CAMLparam2 (ptr_v, n_v);
2850 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2851 fz_link *link;
2852 struct page *page;
2853 char *s = String_val (ptr_v);
2854 struct slink *slink;
2856 ret_v = Val_int (0);
2857 page = parse_pointer (__func__, s);
2859 lock (__func__);
2860 ensureslinks (page);
2861 slink = &page->slinks[Int_val (n_v)];
2862 if (slink->tag == SLINK) {
2863 link = slink->u.link;
2864 str_v = caml_copy_string (link->uri);
2865 ret_v = caml_alloc_small (1, uuri);
2866 Field (ret_v, 0) = str_v;
2868 else {
2869 ret_v = caml_alloc_small (1, uannot);
2870 tup_v = caml_alloc_tuple (2);
2871 Field (ret_v, 0) = tup_v;
2872 Field (tup_v, 0) = ptr_v;
2873 Field (tup_v, 1) = n_v;
2875 unlock (__func__);
2877 CAMLreturn (ret_v);
2880 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2882 CAMLparam2 (ptr_v, n_v);
2883 CAMLlocal1 (ret_v);
2884 pdf_document *pdf;
2885 char *contents = NULL;
2887 lock (__func__);
2888 pdf = pdf_specifics (state.ctx, state.doc);
2889 if (pdf) {
2890 char *s = String_val (ptr_v);
2891 struct page *page;
2892 struct slink *slink;
2894 page = parse_pointer (__func__, s);
2895 slink = &page->slinks[Int_val (n_v)];
2896 contents = pdf_copy_annot_contents (state.ctx,
2897 (pdf_annot *) slink->u.annot);
2899 unlock (__func__);
2900 if (contents) {
2901 ret_v = caml_copy_string (contents);
2902 fz_free (state.ctx, contents);
2904 else {
2905 ret_v = caml_copy_string ("");
2907 CAMLreturn (ret_v);
2910 CAMLprim value ml_getlinkcount (value ptr_v)
2912 CAMLparam1 (ptr_v);
2913 struct page *page;
2914 char *s = String_val (ptr_v);
2916 page = parse_pointer (__func__, s);
2917 CAMLreturn (Val_int (page->slinkcount));
2920 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2922 CAMLparam2 (ptr_v, n_v);
2923 CAMLlocal1 (ret_v);
2924 struct page *page;
2925 struct slink *slink;
2926 char *s = String_val (ptr_v);
2928 page = parse_pointer (__func__, s);
2929 ret_v = caml_alloc_tuple (4);
2930 lock (__func__);
2931 ensureslinks (page);
2933 slink = &page->slinks[Int_val (n_v)];
2934 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2935 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2936 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2937 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2938 unlock (__func__);
2939 CAMLreturn (ret_v);
2942 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2944 CAMLparam3 (ptr_v, x_v, y_v);
2945 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2946 fz_link *link;
2947 struct annot *annot;
2948 struct page *page;
2949 char *ptr = String_val (ptr_v);
2950 int x = Int_val (x_v), y = Int_val (y_v);
2951 struct pagedim *pdim;
2953 ret_v = Val_int (0);
2954 if (trylock (__func__)) {
2955 goto done;
2958 page = parse_pointer (__func__, ptr);
2959 pdim = &state.pagedims[page->pdimno];
2960 x += pdim->bounds.x0;
2961 y += pdim->bounds.y0;
2964 annot = getannot (page, x, y);
2965 if (annot) {
2966 int i, n = -1;
2968 ensureslinks (page);
2969 for (i = 0; i < page->slinkcount; ++i) {
2970 if (page->slinks[i].tag == SANNOT
2971 && page->slinks[i].u.annot == annot->annot) {
2972 n = i;
2973 break;
2976 ret_v = caml_alloc_small (1, uannot);
2977 tup_v = caml_alloc_tuple (2);
2978 Field (ret_v, 0) = tup_v;
2979 Field (tup_v, 0) = ptr_v;
2980 Field (tup_v, 1) = Val_int (n);
2981 goto unlock;
2985 link = getlink (page, x, y);
2986 if (link) {
2987 str_v = caml_copy_string (link->uri);
2988 ret_v = caml_alloc_small (1, uuri);
2989 Field (ret_v, 0) = str_v;
2991 else {
2992 fz_rect *b;
2993 fz_stext_block *block;
2995 ensuretext (page);
2997 for (block = page->text->first_block; block; block = block->next) {
2998 fz_stext_line *line;
3000 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3001 b = &block->bbox;
3002 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3003 continue;
3005 for (line = block->u.t.first_line; line; line = line->next) {
3006 fz_stext_char *ch;
3008 b = &line->bbox;
3009 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3010 continue;
3012 for (ch = line->first_char; ch; ch = ch->next) {
3013 b = &ch->bbox;
3015 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3016 const char *n2 = fz_font_name (state.ctx, ch->font);
3017 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3018 ch->font);
3020 if (!n2) n2 = "<unknown font>";
3022 if (face && face->family_name) {
3023 char *s;
3024 char *n1 = face->family_name;
3025 size_t l1 = strlen (n1);
3026 size_t l2 = strlen (n2);
3028 if (l1 != l2 || memcmp (n1, n2, l1)) {
3029 s = malloc (l1 + l2 + 2);
3030 if (s) {
3031 memcpy (s, n2, l2);
3032 s[l2] = '=';
3033 memcpy (s + l2 + 1, n1, l1 + 1);
3034 str_v = caml_copy_string (s);
3035 free (s);
3039 if (str_v == Val_unit) {
3040 str_v = caml_copy_string (n2);
3042 ret_v = caml_alloc_small (1, utext);
3043 Field (ret_v, 0) = str_v;
3044 goto unlock;
3050 unlock:
3051 unlock (__func__);
3053 done:
3054 CAMLreturn (ret_v);
3057 enum { mark_page, mark_block, mark_line, mark_word };
3059 static int uninteresting (int c)
3061 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3062 || ispunct (c);
3065 CAMLprim void ml_clearmark (value ptr_v)
3067 CAMLparam1 (ptr_v);
3068 char *s = String_val (ptr_v);
3069 struct page *page;
3071 if (trylock (__func__)) {
3072 goto done;
3075 page = parse_pointer (__func__, s);
3076 page->fmark.ch = NULL;
3077 page->lmark.ch = NULL;
3079 unlock (__func__);
3080 done:
3081 CAMLreturn0;
3084 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3086 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3087 CAMLlocal1 (ret_v);
3088 fz_rect *b;
3089 struct page *page;
3090 fz_stext_line *line;
3091 fz_stext_block *block;
3092 struct pagedim *pdim;
3093 int mark = Int_val (mark_v);
3094 char *s = String_val (ptr_v);
3095 int x = Int_val (x_v), y = Int_val (y_v);
3097 ret_v = Val_bool (0);
3098 if (trylock (__func__)) {
3099 goto done;
3102 page = parse_pointer (__func__, s);
3103 pdim = &state.pagedims[page->pdimno];
3105 ensuretext (page);
3107 if (mark == mark_page) {
3108 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3109 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3110 ret_v = Val_bool (1);
3111 goto unlock;
3114 x += pdim->bounds.x0;
3115 y += pdim->bounds.y0;
3117 for (block = page->text->first_block; block; block = block->next) {
3118 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3119 b = &block->bbox;
3120 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3121 continue;
3123 if (mark == mark_block) {
3124 page->fmark.ch = block->u.t.first_line->first_char;
3125 page->lmark.ch = block->u.t.last_line->last_char;
3126 ret_v = Val_bool (1);
3127 goto unlock;
3130 for (line = block->u.t.first_line; line; line = line->next) {
3131 fz_stext_char *ch;
3133 b = &line->bbox;
3134 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3135 continue;
3137 if (mark == mark_line) {
3138 page->fmark.ch = line->first_char;
3139 page->lmark.ch = line->last_char;
3140 ret_v = Val_bool (1);
3141 goto unlock;
3144 for (ch = line->first_char; ch; ch = ch->next) {
3145 fz_stext_char *ch2, *first = NULL, *last = NULL;
3146 b = &ch->bbox;
3147 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3148 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3149 if (uninteresting (ch2->c)) first = NULL;
3150 else if (!first) first = ch2;
3152 for (ch2 = ch; ch2; ch2 = ch2->next) {
3153 if (uninteresting (ch2->c)) break;
3154 last = ch2;
3157 page->fmark.ch = first;
3158 page->lmark.ch = last;
3159 ret_v = Val_bool (1);
3160 goto unlock;
3165 unlock:
3166 if (!Bool_val (ret_v)) {
3167 page->fmark.ch = NULL;
3168 page->lmark.ch = NULL;
3170 unlock (__func__);
3172 done:
3173 CAMLreturn (ret_v);
3176 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3178 CAMLparam3 (ptr_v, x_v, y_v);
3179 CAMLlocal2 (ret_v, res_v);
3180 fz_rect *b = NULL;
3181 struct page *page;
3182 struct pagedim *pdim;
3183 fz_stext_block *block;
3184 char *s = String_val (ptr_v);
3185 int x = Int_val (x_v), y = Int_val (y_v);
3187 ret_v = Val_int (0);
3188 if (trylock (__func__)) {
3189 goto done;
3192 page = parse_pointer (__func__, s);
3193 pdim = &state.pagedims[page->pdimno];
3194 x += pdim->bounds.x0;
3195 y += pdim->bounds.y0;
3197 ensuretext (page);
3199 for (block = page->text->first_block; block; block = block->next) {
3200 switch (block->type) {
3201 case FZ_STEXT_BLOCK_TEXT:
3202 b = &block->bbox;
3203 break;
3205 case FZ_STEXT_BLOCK_IMAGE:
3206 b = &block->bbox;
3207 break;
3209 default:
3210 continue;
3213 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3214 break;
3215 b = NULL;
3217 if (b) {
3218 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3219 ret_v = caml_alloc_small (1, 1);
3220 Store_double_field (res_v, 0, (double) b->x0);
3221 Store_double_field (res_v, 1, (double) b->x1);
3222 Store_double_field (res_v, 2, (double) b->y0);
3223 Store_double_field (res_v, 3, (double) b->y1);
3224 Field (ret_v, 0) = res_v;
3226 unlock (__func__);
3228 done:
3229 CAMLreturn (ret_v);
3232 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3234 CAMLparam2 (ptr_v, rect_v);
3235 fz_rect b;
3236 struct page *page;
3237 struct pagedim *pdim;
3238 char *s = String_val (ptr_v);
3239 int x0, x1, y0, y1;
3240 fz_stext_char *ch;
3241 fz_stext_line *line;
3242 fz_stext_block *block;
3243 fz_stext_char *fc, *lc;
3245 if (trylock (__func__)) {
3246 goto done;
3249 page = parse_pointer (__func__, s);
3250 ensuretext (page);
3252 pdim = &state.pagedims[page->pdimno];
3253 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3254 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3255 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3256 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3258 if (y0 > y1) {
3259 int t = y0;
3260 y0 = y1;
3261 y1 = t;
3262 x0 = x1;
3263 x1 = t;
3266 fc = page->fmark.ch;
3267 lc = page->lmark.ch;
3269 for (block = page->text->first_block; block; block = block->next) {
3270 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3271 for (line = block->u.t.first_line; line; line = line->next) {
3272 for (ch = line->first_char; ch; ch = ch->next) {
3273 b = ch->bbox;
3274 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3275 fc = ch;
3277 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3278 lc = ch;
3283 if (x1 < x0 && fc == lc) {
3284 fz_stext_char *t;
3286 t = fc;
3287 fc = lc;
3288 lc = t;
3291 page->fmark.ch = fc;
3292 page->lmark.ch = lc;
3294 unlock (__func__);
3296 done:
3297 CAMLreturn0;
3300 static int pipechar (FILE *f, fz_stext_char *ch)
3302 char buf[4];
3303 int len;
3304 size_t ret;
3306 len = fz_runetochar (buf, ch->c);
3307 ret = fwrite (buf, len, 1, f);
3308 if (ret != 1) {
3309 fprintf (stderr, "failed to write %d bytes ret=%zu: %s\n",
3310 len, ret, strerror (errno));
3311 return -1;
3313 return 0;
3316 CAMLprim value ml_spawn (value command_v, value fds_v)
3318 CAMLparam2 (command_v, fds_v);
3319 CAMLlocal2 (l_v, tup_v);
3320 int ret, ret1;
3321 pid_t pid = (pid_t) -1;
3322 char *msg = NULL;
3323 value earg_v = Nothing;
3324 posix_spawnattr_t attr;
3325 posix_spawn_file_actions_t fa;
3326 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3328 argv[2] = String_val (command_v);
3330 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3331 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3334 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3335 msg = "posix_spawnattr_init";
3336 goto fail1;
3339 #ifdef POSIX_SPAWN_USEVFORK
3340 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3341 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3342 goto fail;
3344 #endif
3346 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3347 int fd1, fd2;
3349 tup_v = Field (l_v, 0);
3350 fd1 = Int_val (Field (tup_v, 0));
3351 fd2 = Int_val (Field (tup_v, 1));
3352 if (fd2 < 0) {
3353 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3354 msg = "posix_spawn_file_actions_addclose";
3355 earg_v = tup_v;
3356 goto fail;
3359 else {
3360 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3361 msg = "posix_spawn_file_actions_adddup2";
3362 earg_v = tup_v;
3363 goto fail;
3368 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3369 msg = "posix_spawn";
3370 goto fail;
3373 fail:
3374 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3375 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3378 fail1:
3379 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3380 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3381 strerror (ret1));
3384 if (msg)
3385 unix_error (ret, msg, earg_v);
3387 CAMLreturn (Val_int (pid));
3390 CAMLprim value ml_hassel (value ptr_v)
3392 CAMLparam1 (ptr_v);
3393 CAMLlocal1 (ret_v);
3394 struct page *page;
3395 char *s = String_val (ptr_v);
3397 ret_v = Val_bool (0);
3398 if (trylock (__func__)) {
3399 goto done;
3402 page = parse_pointer (__func__, s);
3403 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3404 unlock (__func__);
3405 done:
3406 CAMLreturn (ret_v);
3409 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3411 CAMLparam2 (fd_v, ptr_v);
3412 FILE *f;
3413 int seen = 0;
3414 struct page *page;
3415 fz_stext_line *line;
3416 fz_stext_block *block;
3417 int fd = Int_val (fd_v);
3418 char *s = String_val (ptr_v);
3420 if (trylock (__func__)) {
3421 goto done;
3424 page = parse_pointer (__func__, s);
3426 if (!page->fmark.ch || !page->lmark.ch) {
3427 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3428 goto unlock;
3431 f = fdopen (fd, "w");
3432 if (!f) {
3433 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3434 fd, strerror (errno));
3435 f = stdout;
3438 for (block = page->text->first_block; block; block = block->next) {
3439 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3440 for (line = block->u.t.first_line; line; line = line->next) {
3441 fz_stext_char *ch;
3442 for (ch = line->first_char; ch; ch = ch->next) {
3443 if (seen || ch == page->fmark.ch) {
3444 do {
3445 pipechar (f, ch);
3446 if (ch == page->lmark.ch) goto close;
3447 } while ((ch = ch->next));
3448 seen = 1;
3449 break;
3452 if (seen) fputc ('\n', f);
3455 close:
3456 if (f != stdout) {
3457 int ret = fclose (f);
3458 fd = -1;
3459 if (ret == -1) {
3460 if (errno != ECHILD) {
3461 fprintf (stderr, "failed to close sel pipe: %s\n",
3462 strerror (errno));
3466 unlock:
3467 unlock (__func__);
3469 done:
3470 if (fd >= 0) {
3471 if (close (fd)) {
3472 fprintf (stderr, "failed to close sel pipe: %s\n",
3473 strerror (errno));
3476 CAMLreturn0;
3479 CAMLprim value ml_getpdimrect (value pagedimno_v)
3481 CAMLparam1 (pagedimno_v);
3482 CAMLlocal1 (ret_v);
3483 int pagedimno = Int_val (pagedimno_v);
3484 fz_rect box;
3486 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3487 if (trylock (__func__)) {
3488 box = fz_empty_rect;
3490 else {
3491 box = state.pagedims[pagedimno].mediabox;
3492 unlock (__func__);
3495 Store_double_field (ret_v, 0, (double) box.x0);
3496 Store_double_field (ret_v, 1, (double) box.x1);
3497 Store_double_field (ret_v, 2, (double) box.y0);
3498 Store_double_field (ret_v, 3, (double) box.y1);
3500 CAMLreturn (ret_v);
3503 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3504 value dw_v, value cols_v)
3506 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3507 CAMLlocal1 (ret_v);
3508 int i;
3509 float zoom = -1.;
3510 float maxh = 0.0;
3511 struct pagedim *p;
3512 float winw = Int_val (winw_v);
3513 float winh = Int_val (winh_v);
3514 float dw = Int_val (dw_v);
3515 float cols = Int_val (cols_v);
3516 float pw = 1.0, ph = 1.0;
3518 if (trylock (__func__)) {
3519 goto done;
3522 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3523 float w = p->pagebox.x1 / cols;
3524 float h = p->pagebox.y1;
3525 if (h > maxh) {
3526 maxh = h;
3527 ph = h;
3528 if (state.fitmodel != FitProportional) pw = w;
3530 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3533 zoom = (((winh / ph) * pw) + dw) / winw;
3534 unlock (__func__);
3535 done:
3536 ret_v = caml_copy_double ((double) zoom);
3537 CAMLreturn (ret_v);
3540 CAMLprim value ml_getmaxw (value unit_v)
3542 CAMLparam1 (unit_v);
3543 CAMLlocal1 (ret_v);
3544 int i;
3545 float maxw = -1.;
3546 struct pagedim *p;
3548 if (trylock (__func__)) {
3549 goto done;
3552 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3553 float w = p->pagebox.x1;
3554 maxw = fz_max (maxw, w);
3557 unlock (__func__);
3558 done:
3559 ret_v = caml_copy_double ((double) maxw);
3560 CAMLreturn (ret_v);
3563 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3565 CAMLparam4 (pt_v, x_v, y_v, string_v);
3566 CAMLlocal1 (ret_v);
3567 int pt = Int_val(pt_v);
3568 int x = Int_val (x_v);
3569 int y = Int_val (y_v);
3570 double w;
3572 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3573 ret_v = caml_copy_double (w);
3574 CAMLreturn (ret_v);
3577 CAMLprim value ml_measure_string (value pt_v, value string_v)
3579 CAMLparam2 (pt_v, string_v);
3580 CAMLlocal1 (ret_v);
3581 int pt = Int_val (pt_v);
3582 double w;
3584 w = (double) measure_string (state.face, pt, String_val (string_v));
3585 ret_v = caml_copy_double (w);
3586 CAMLreturn (ret_v);
3589 CAMLprim value ml_getpagebox (value opaque_v)
3591 CAMLparam1 (opaque_v);
3592 CAMLlocal1 (ret_v);
3593 fz_rect rect;
3594 fz_irect bbox;
3595 fz_matrix ctm;
3596 fz_device *dev;
3597 char *s = String_val (opaque_v);
3598 struct page *page = parse_pointer (__func__, s);
3600 ret_v = caml_alloc_tuple (4);
3601 dev = fz_new_bbox_device (state.ctx, &rect);
3603 ctm = pagectm (page);
3604 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3606 fz_close_device (state.ctx, dev);
3607 fz_drop_device (state.ctx, dev);
3608 fz_round_rect (&bbox, &rect);
3609 Field (ret_v, 0) = Val_int (bbox.x0);
3610 Field (ret_v, 1) = Val_int (bbox.y0);
3611 Field (ret_v, 2) = Val_int (bbox.x1);
3612 Field (ret_v, 3) = Val_int (bbox.y1);
3614 CAMLreturn (ret_v);
3617 CAMLprim void ml_setaalevel (value level_v)
3619 CAMLparam1 (level_v);
3621 state.aalevel = Int_val (level_v);
3622 CAMLreturn0;
3625 #ifndef __COCOA__
3626 #pragma GCC diagnostic push
3627 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3628 #include <X11/Xlib.h>
3629 #include <X11/cursorfont.h>
3630 #pragma GCC diagnostic pop
3632 #ifdef USE_EGL
3633 #include <EGL/egl.h>
3634 #else
3635 #include <GL/glx.h>
3636 #endif
3638 static const int shapes[] = {
3639 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3642 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3644 static struct {
3645 Window wid;
3646 Display *dpy;
3647 #ifdef USE_EGL
3648 EGLContext ctx;
3649 EGLConfig conf;
3650 EGLSurface win;
3651 EGLDisplay *edpy;
3652 #else
3653 GLXContext ctx;
3654 #endif
3655 XVisualInfo *visual;
3656 Cursor curs[CURS_COUNT];
3657 } glx;
3660 static void initcurs (void)
3662 for (size_t n = 0; n < CURS_COUNT; ++n) {
3663 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3667 #ifdef USE_EGL
3668 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3670 CAMLparam3 (display_v, wid_v, screen_v);
3671 int major, minor;
3672 int num_conf;
3673 EGLint visid;
3674 EGLint attribs[] = {
3675 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3676 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3677 EGL_NONE
3679 EGLConfig conf;
3681 glx.dpy = XOpenDisplay (String_val (display_v));
3682 if (!glx.dpy) {
3683 caml_failwith ("XOpenDisplay");
3686 eglBindAPI (EGL_OPENGL_API);
3688 glx.edpy = eglGetDisplay (glx.dpy);
3689 if (glx.edpy == EGL_NO_DISPLAY) {
3690 caml_failwith ("eglGetDisplay");
3693 if (!eglInitialize (glx.edpy, &major, &minor)) {
3694 caml_failwith ("eglInitialize");
3697 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3698 !num_conf) {
3699 caml_failwith ("eglChooseConfig");
3702 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3703 caml_failwith ("eglGetConfigAttrib");
3706 glx.conf = conf;
3707 initcurs ();
3709 glx.wid = Int_val (wid_v);
3710 CAMLreturn (Val_int (visid));
3713 CAMLprim void ml_glxcompleteinit (value unit_v)
3715 CAMLparam1 (unit_v);
3717 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3718 if (!glx.ctx) {
3719 caml_failwith ("eglCreateContext");
3722 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3723 glx.wid, NULL);
3724 if (glx.win == EGL_NO_SURFACE) {
3725 caml_failwith ("eglCreateWindowSurface");
3728 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3729 glx.ctx = NULL;
3730 caml_failwith ("eglMakeCurrent");
3732 CAMLreturn0;
3734 #else
3735 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3737 CAMLparam3 (display_v, wid_v, screen_v);
3739 glx.dpy = XOpenDisplay (String_val (display_v));
3740 if (!glx.dpy) {
3741 caml_failwith ("XOpenDisplay");
3744 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3745 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3746 if (!glx.visual) {
3747 XCloseDisplay (glx.dpy);
3748 caml_failwith ("glXChooseVisual");
3751 initcurs ();
3753 glx.wid = Int_val (wid_v);
3754 CAMLreturn (Val_int (glx.visual->visualid));
3757 CAMLprim void ml_glxcompleteinit (value unit_v)
3759 CAMLparam1 (unit_v);
3761 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3762 if (!glx.ctx) {
3763 caml_failwith ("glXCreateContext");
3766 XFree (glx.visual);
3767 glx.visual = NULL;
3769 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3770 glXDestroyContext (glx.dpy, glx.ctx);
3771 glx.ctx = NULL;
3772 caml_failwith ("glXMakeCurrent");
3774 CAMLreturn0;
3776 #endif
3778 CAMLprim void ml_setcursor (value cursor_v)
3780 CAMLparam1 (cursor_v);
3781 size_t cursn = Int_val (cursor_v);
3783 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3784 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3785 XFlush (glx.dpy);
3786 CAMLreturn0;
3789 CAMLprim void ml_swapb (value unit_v)
3791 CAMLparam1 (unit_v);
3792 #ifdef USE_EGL
3793 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3794 caml_failwith ("eglSwapBuffers");
3796 #else
3797 glXSwapBuffers (glx.dpy, glx.wid);
3798 #endif
3799 CAMLreturn0;
3802 #pragma GCC diagnostic push
3803 #ifdef __clang__
3804 #pragma GCC diagnostic ignored "-Wmissing-variable-declarations"
3805 #endif
3806 #include "keysym2ucs.c"
3807 #pragma GCC diagnostic pop
3809 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3811 CAMLparam1 (keysym_v);
3812 CAMLlocal1 (str_v);
3813 KeySym keysym = Int_val (keysym_v);
3814 Rune rune;
3815 int len;
3816 char buf[5];
3818 rune = (Rune) keysym2ucs (keysym);
3819 len = fz_runetochar (buf, rune);
3820 buf[len] = 0;
3821 str_v = caml_copy_string (buf);
3822 CAMLreturn (str_v);
3824 #else
3825 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3827 CAMLparam1 (keysym_v);
3828 CAMLlocal1 (str_v);
3829 long ucs_v = Long_val (keysym_v);
3830 int len;
3831 char buf[5];
3833 len = fz_runetochar (buf, ucs_v);
3834 buf[len] = 0;
3835 str_v = caml_copy_string (buf);
3836 CAMLreturn (str_v);
3838 #endif
3840 enum { piunknown, pilinux, piosx, pisun, pibsd };
3842 CAMLprim value ml_platform (value unit_v)
3844 CAMLparam1 (unit_v);
3845 CAMLlocal2 (tup_v, arr_v);
3846 int platid = piunknown;
3847 struct utsname buf;
3849 #if defined __linux__
3850 platid = pilinux;
3851 #elif defined __DragonFly__ || defined __FreeBSD__
3852 || defined __OpenBSD__ || defined __NetBSD__
3853 platid = pibsd;
3854 #elif defined __sun__
3855 platid = pisun;
3856 #elif defined __APPLE__
3857 platid = piosx;
3858 #endif
3859 if (uname (&buf)) err (1, "uname");
3861 tup_v = caml_alloc_tuple (2);
3863 char const *sar[] = {
3864 buf.sysname,
3865 buf.release,
3866 buf.version,
3867 buf.machine,
3868 NULL
3870 arr_v = caml_copy_string_array (sar);
3872 Field (tup_v, 0) = Val_int (platid);
3873 Field (tup_v, 1) = arr_v;
3874 CAMLreturn (tup_v);
3877 CAMLprim void ml_cloexec (value fd_v)
3879 CAMLparam1 (fd_v);
3880 int fd = Int_val (fd_v);
3882 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3883 uerror ("fcntl", Nothing);
3885 CAMLreturn0;
3888 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3890 CAMLparam2 (w_v, h_v);
3891 CAMLlocal1 (ret_v);
3892 struct bo *pbo;
3893 int w = Int_val (w_v);
3894 int h = Int_val (h_v);
3895 int cs = Int_val (cs_v);
3897 if (state.bo_usable) {
3898 pbo = calloc (sizeof (*pbo), 1);
3899 if (!pbo) {
3900 err (1, "calloc pbo");
3903 switch (cs) {
3904 case 0:
3905 case 1:
3906 pbo->size = w*h*4;
3907 break;
3908 case 2:
3909 pbo->size = w*h*2;
3910 break;
3911 default:
3912 errx (1, "%s: invalid colorspace %d", __func__, cs);
3915 state.glGenBuffersARB (1, &pbo->id);
3916 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3917 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3918 NULL, GL_STREAM_DRAW);
3919 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3920 GL_READ_WRITE);
3921 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3922 if (!pbo->ptr) {
3923 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3924 state.glDeleteBuffersARB (1, &pbo->id);
3925 free (pbo);
3926 ret_v = caml_copy_string ("0");
3928 else {
3929 int res;
3930 char *s;
3932 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3933 if (res < 0) {
3934 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3936 s = malloc (res+1);
3937 if (!s) {
3938 err (1, "malloc %d bytes failed", res+1);
3940 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3941 if (res < 0) {
3942 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3944 ret_v = caml_copy_string (s);
3945 free (s);
3948 else {
3949 ret_v = caml_copy_string ("0");
3951 CAMLreturn (ret_v);
3954 CAMLprim void ml_freepbo (value s_v)
3956 CAMLparam1 (s_v);
3957 char *s = String_val (s_v);
3958 struct tile *tile = parse_pointer (__func__, s);
3960 if (tile->pbo) {
3961 state.glDeleteBuffersARB (1, &tile->pbo->id);
3962 tile->pbo->id = -1;
3963 tile->pbo->ptr = NULL;
3964 tile->pbo->size = -1;
3966 CAMLreturn0;
3969 CAMLprim void ml_unmappbo (value s_v)
3971 CAMLparam1 (s_v);
3972 char *s = String_val (s_v);
3973 struct tile *tile = parse_pointer (__func__, s);
3975 if (tile->pbo) {
3976 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3977 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3978 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3980 tile->pbo->ptr = NULL;
3981 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3983 CAMLreturn0;
3986 static void setuppbo (void)
3988 #ifdef __COCOA__
3989 static CFBundleRef framework = NULL;
3990 if (framework == NULL)
3991 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3992 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3993 #else
3994 #ifdef USE_EGL
3995 #define GGPA(n) (*(void (**) (void)) &state.n = eglGetProcAddress (#n))
3996 #else
3997 #define GGPA(n) (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
3998 #endif
3999 state.bo_usable = GGPA (glBindBufferARB)
4000 && GGPA (glUnmapBufferARB)
4001 && GGPA (glMapBufferARB)
4002 && GGPA (glBufferDataARB)
4003 && GGPA (glGenBuffersARB)
4004 && GGPA (glDeleteBuffersARB);
4005 #endif
4006 #undef GGPA
4009 CAMLprim value ml_bo_usable (value unit_v)
4011 CAMLparam1 (unit_v);
4012 CAMLreturn (Val_bool (state.bo_usable));
4015 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4017 CAMLparam3 (ptr_v, x_v, y_v);
4018 CAMLlocal2 (ret_v, tup_v);
4019 struct page *page;
4020 char *s = String_val (ptr_v);
4021 int x = Int_val (x_v), y = Int_val (y_v);
4022 struct pagedim *pdim;
4023 fz_point p;
4024 fz_matrix ctm;
4026 page = parse_pointer (__func__, s);
4027 pdim = &state.pagedims[page->pdimno];
4029 ret_v = Val_int (0);
4030 if (trylock (__func__)) {
4031 goto done;
4034 if (pdf_specifics (state.ctx, state.doc)) {
4035 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4036 ctm = state.pagedims[page->pdimno].tctm;
4038 else {
4039 ctm = fz_identity;
4041 p.x = x + pdim->bounds.x0;
4042 p.y = y + pdim->bounds.y0;
4044 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4045 fz_invert_matrix (&ctm, &ctm);
4046 fz_transform_point (&p, &ctm);
4048 tup_v = caml_alloc_tuple (2);
4049 ret_v = caml_alloc_small (1, 1);
4050 Field (tup_v, 0) = Val_int (p.x);
4051 Field (tup_v, 1) = Val_int (p.y);
4052 Field (ret_v, 0) = tup_v;
4054 unlock (__func__);
4055 done:
4056 CAMLreturn (ret_v);
4059 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4060 value x_v, value y_v)
4062 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4063 CAMLlocal1 (ret_v);
4064 struct page *page;
4065 char *s = String_val (ptr_v);
4066 int pageno = Int_val (pageno_v);
4067 int pdimno = Int_val (pdimno_v);
4068 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
4069 struct pagedim *pdim;
4070 fz_point p;
4071 fz_matrix ctm;
4073 ret_v = Val_int (0);
4074 lock (__func__);
4076 if (!*s) {
4077 page = loadpage (pageno, pdimno);
4079 else {
4080 page = parse_pointer (__func__, s);
4082 pdim = &state.pagedims[pdimno];
4084 if (pdf_specifics (state.ctx, state.doc)) {
4085 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4086 ctm = state.pagedims[page->pdimno].tctm;
4088 else {
4089 ctm = fz_identity;
4091 p.x = x + pdim->bounds.x0;
4092 p.y = y + pdim->bounds.y0;
4094 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4095 fz_transform_point (&p, &ctm);
4097 ret_v = caml_alloc_tuple (2);
4098 Field (ret_v, 0) = caml_copy_double ((double) p.x);
4099 Field (ret_v, 1) = caml_copy_double ((double) p.y);
4101 if (!*s) {
4102 freepage (page);
4104 unlock (__func__);
4105 CAMLreturn (ret_v);
4108 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4109 value contents_v)
4111 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4112 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4114 if (pdf) {
4115 pdf_annot *annot;
4116 struct page *page;
4117 fz_point p;
4118 char *s = String_val (ptr_v);
4120 page = parse_pointer (__func__, s);
4121 annot = pdf_create_annot (state.ctx,
4122 pdf_page_from_fz_page (state.ctx,
4123 page->fzpage),
4124 PDF_ANNOT_TEXT);
4125 p.x = Int_val (x_v);
4126 p.y = Int_val (y_v);
4127 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4128 pdf_set_text_annot_position (state.ctx, annot, p);
4129 state.dirty = 1;
4131 CAMLreturn0;
4134 CAMLprim void ml_delannot (value ptr_v, value n_v)
4136 CAMLparam2 (ptr_v, n_v);
4137 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4139 if (pdf) {
4140 struct page *page;
4141 char *s = String_val (ptr_v);
4142 struct slink *slink;
4144 page = parse_pointer (__func__, s);
4145 slink = &page->slinks[Int_val (n_v)];
4146 pdf_delete_annot (state.ctx,
4147 pdf_page_from_fz_page (state.ctx, page->fzpage),
4148 (pdf_annot *) slink->u.annot);
4149 state.dirty = 1;
4151 CAMLreturn0;
4154 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4156 CAMLparam3 (ptr_v, n_v, str_v);
4157 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4159 if (pdf) {
4160 struct page *page;
4161 char *s = String_val (ptr_v);
4162 struct slink *slink;
4164 page = parse_pointer (__func__, s);
4165 slink = &page->slinks[Int_val (n_v)];
4166 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4167 String_val (str_v));
4168 state.dirty = 1;
4170 CAMLreturn0;
4173 CAMLprim value ml_hasunsavedchanges (value unit_v)
4175 CAMLparam1 (unit_v);
4176 CAMLreturn (Val_bool (state.dirty));
4179 CAMLprim void ml_savedoc (value path_v)
4181 CAMLparam1 (path_v);
4182 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4184 if (pdf) {
4185 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4187 CAMLreturn0;
4190 static void makestippletex (void)
4192 const char pixels[] = "\xff\xff\0\0";
4193 glGenTextures (1, &state.stid);
4194 glBindTexture (GL_TEXTURE_1D, state.stid);
4195 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4196 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4197 glTexImage1D (
4198 GL_TEXTURE_1D,
4200 GL_ALPHA,
4203 GL_ALPHA,
4204 GL_UNSIGNED_BYTE,
4205 pixels
4209 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4211 return caml_copy_string (FZ_VERSION);
4214 CAMLprim void ml_init (value csock_v, value params_v)
4216 CAMLparam2 (csock_v, params_v);
4217 CAMLlocal2 (trim_v, fuzz_v);
4218 int ret;
4219 int texcount;
4220 char *fontpath;
4221 int colorspace;
4222 int mustoresize;
4223 int haspboext;
4225 /* Without following call to setlocale mbstowcs fails for, at
4226 least, strings containing chinese symbols (δΈ­ for instance)
4227 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4228 wide character" as the reason of failure and with macOS
4229 producing bogus output) */
4230 if (setlocale (LC_CTYPE, "")) {
4231 /* Following two lines were taken from dvtm/vt.c */
4232 const char *cset = nl_langinfo (CODESET);
4233 state.utf8cs = !strcmp (cset, "UTF-8");
4235 else {
4236 fprintf (stderr, "setlocale failed\n");
4239 state.csock = Int_val (csock_v);
4240 state.rotate = Int_val (Field (params_v, 0));
4241 state.fitmodel = Int_val (Field (params_v, 1));
4242 trim_v = Field (params_v, 2);
4243 texcount = Int_val (Field (params_v, 3));
4244 state.sliceheight = Int_val (Field (params_v, 4));
4245 mustoresize = Int_val (Field (params_v, 5));
4246 colorspace = Int_val (Field (params_v, 6));
4247 fontpath = String_val (Field (params_v, 7));
4249 if (caml_string_length (Field (params_v, 8)) > 0) {
4250 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4252 if (!state.trimcachepath) {
4253 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4254 strerror (errno));
4258 haspboext = Bool_val (Field (params_v, 9));
4260 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4261 fz_register_document_handlers (state.ctx);
4263 state.trimmargins = Bool_val (Field (trim_v, 0));
4264 fuzz_v = Field (trim_v, 1);
4265 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4266 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4267 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4268 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4270 set_tex_params (colorspace);
4272 if (*fontpath) {
4273 state.face = load_font (fontpath);
4275 else {
4276 int len;
4277 const unsigned char *data;
4279 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4280 state.face = load_builtin_font (data, len);
4282 if (!state.face) _exit (1);
4284 realloctexts (texcount);
4286 if (haspboext) {
4287 setuppbo ();
4290 makestippletex ();
4292 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4293 if (ret) {
4294 errx (1, "pthread_create: %s", strerror (ret));
4297 CAMLreturn0;
4300 #if FIXME || !FIXME
4301 static void OPTIMIZE_ATTR (0) UNUSED_ATTR refmacs (void) {}
4302 #endif