Shellology
[llpp.git] / link.c
blob2b62f888db7cca084bf2449518078aeb90baafa3
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
3 #define FIXME 0
5 extern char **environ;
7 #include <errno.h>
8 #include <stdio.h>
9 #include <ctype.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <signal.h>
14 #include <math.h>
15 #include <wchar.h>
16 #include <locale.h>
17 #include <langinfo.h>
19 #include <unistd.h>
20 #include <pthread.h>
21 #include <sys/uio.h>
22 #include <sys/time.h>
23 #include <sys/stat.h>
24 #include <fcntl.h>
25 #include <sys/types.h>
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
29 #include <spawn.h>
31 #include <regex.h>
32 #include <stdarg.h>
33 #include <limits.h>
34 #include <inttypes.h>
36 #ifdef __COCOA__
37 #include <CoreFoundation/CoreFoundation.h>
38 #endif
40 #ifdef __APPLE__
41 #include <OpenGL/gl.h>
42 #else
43 #include <GL/gl.h>
44 #endif
46 #pragma GCC diagnostic push
47 #ifdef __clang__
48 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
49 #endif
50 #pragma GCC diagnostic ignored "-Wpedantic"
51 #include <caml/fail.h>
52 #include <caml/alloc.h>
53 #include <caml/memory.h>
54 #include <caml/unixsupport.h>
56 #if __GNUC__ < 5 && !defined __clang__
57 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
58 clobbered diagnostics */
59 #pragma GCC diagnostic ignored "-Wclobbered"
60 #endif
62 #include <mupdf/fitz.h>
63 #include <mupdf/pdf.h>
65 #include <ft2build.h>
66 #include FT_FREETYPE_H
67 #pragma GCC diagnostic pop
69 #define PIGGYBACK
70 #define CACHE_PAGEREFS
72 #if defined __GNUC__
73 #define NORETURN_ATTR __attribute__ ((noreturn))
74 #define UNUSED_ATTR __attribute__ ((unused))
75 #if !defined __clang__
76 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
77 #else
78 #define OPTIMIZE_ATTR(n)
79 #endif
80 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
81 #else
82 #define NORETURN_ATTR
83 #define UNUSED_ATTR
84 #define OPTIMIZE_ATTR(n)
85 #define GCC_FMT_ATTR(a, b)
86 #endif
88 #define FMT_s "zu"
90 #define FMT_ptr PRIxPTR
91 #define SCN_ptr SCNxPTR
92 #define FMT_ptr_cast(p) ((uintptr_t) (p))
93 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
95 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
96 err (int exitcode, const char *fmt, ...)
98 va_list ap;
99 int savederrno;
101 savederrno = errno;
102 va_start (ap, fmt);
103 vfprintf (stderr, fmt, ap);
104 va_end (ap);
105 fprintf (stderr, ": %s\n", strerror (savederrno));
106 fflush (stderr);
107 _exit (exitcode);
110 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
111 errx (int exitcode, const char *fmt, ...)
113 va_list ap;
115 va_start (ap, fmt);
116 vfprintf (stderr, fmt, ap);
117 va_end (ap);
118 fputc ('\n', stderr);
119 fflush (stderr);
120 _exit (exitcode);
123 #ifndef GL_TEXTURE_RECTANGLE_ARB
124 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
125 #endif
127 #ifdef USE_NPOT
128 #define TEXT_TYPE GL_TEXTURE_2D
129 #else
130 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
131 #endif
133 #ifndef GL_BGRA
134 #define GL_BGRA 0x80E1
135 #endif
137 #ifndef GL_UNSIGNED_INT_8_8_8_8
138 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
139 #endif
141 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
142 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
143 #endif
145 #if 0
146 #define lprintf printf
147 #else
148 #define lprintf(...)
149 #endif
151 #define ARSERT(cond) for (;;) { \
152 if (!(cond)) { \
153 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
155 break; \
158 struct slice {
159 int h;
160 int texindex;
163 struct tile {
164 int w, h;
165 int slicecount;
166 int sliceheight;
167 struct bo *pbo;
168 fz_pixmap *pixmap;
169 struct slice slices[1];
172 struct pagedim {
173 int pageno;
174 int rotate;
175 int left;
176 int tctmready;
177 fz_irect bounds;
178 fz_rect pagebox;
179 fz_rect mediabox;
180 fz_matrix ctm, zoomctm, tctm;
183 struct slink {
184 enum { SLINK, SANNOT } tag;
185 fz_irect bbox;
186 union {
187 fz_link *link;
188 fz_annot *annot;
189 } u;
192 struct annot {
193 fz_irect bbox;
194 fz_annot *annot;
197 struct page {
198 int tgen;
199 int sgen;
200 int agen;
201 int pageno;
202 int pdimno;
203 fz_stext_page *text;
204 fz_page *fzpage;
205 fz_display_list *dlist;
206 fz_link *links;
207 int slinkcount;
208 struct slink *slinks;
209 int annotcount;
210 struct annot *annots;
211 struct mark {
212 fz_stext_char *ch;
213 } fmark, lmark;
216 enum { FitWidth, FitProportional, FitPage };
218 static struct {
219 int sliceheight;
220 struct pagedim *pagedims;
221 int pagecount;
222 int pagedimcount;
223 fz_document *doc;
224 fz_context *ctx;
225 int w, h;
227 int texindex;
228 int texcount;
229 GLuint *texids;
231 GLenum texiform;
232 GLenum texform;
233 GLenum texty;
235 fz_colorspace *colorspace;
237 struct {
238 int w, h;
239 struct slice *slice;
240 } *texowners;
242 int rotate;
243 int fitmodel;
244 int trimmargins;
245 int needoutline;
246 int gen;
247 int aalevel;
249 int trimanew;
250 fz_irect trimfuzz;
251 fz_pixmap *pig;
253 pthread_t thread;
254 int csock;
255 FT_Face face;
257 char *trimcachepath;
258 int dirty;
260 GLuint stid;
262 int bo_usable;
263 GLuint boid;
265 void (*glBindBufferARB) (GLenum, GLuint);
266 GLboolean (*glUnmapBufferARB) (GLenum);
267 void *(*glMapBufferARB) (GLenum, GLenum);
268 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
269 void (*glGenBuffersARB) (GLsizei, GLuint *);
270 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
272 GLfloat texcoords[8];
273 GLfloat vertices[16];
275 #ifdef CACHE_PAGEREFS
276 struct {
277 int idx;
278 int count;
279 pdf_obj **objs;
280 pdf_document *pdf;
281 } pdflut;
282 #endif
283 int utf8cs;
284 } state;
286 struct bo {
287 GLuint id;
288 void *ptr;
289 size_t size;
292 #pragma GCC diagnostic ignored "-Wdouble-promotion"
293 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
295 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
298 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
300 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
303 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
305 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
306 m.a, m.b, m.c, m.d, m.e, m.f);
308 #pragma GCC diagnostic error "-Wdouble-promotion"
310 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
312 static void lock (const char *cap)
314 int ret = pthread_mutex_lock (&mutex);
315 if (ret) {
316 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
320 static void unlock (const char *cap)
322 int ret = pthread_mutex_unlock (&mutex);
323 if (ret) {
324 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
328 static int trylock (const char *cap)
330 int ret = pthread_mutex_trylock (&mutex);
331 if (ret && ret != EBUSY) {
332 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
334 return ret == EBUSY;
337 static void *parse_pointer (const char *cap, const char *s)
339 int ret;
340 void *ptr;
342 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
343 if (ret != 1) {
344 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
346 return ptr;
349 static double now (void)
351 struct timeval tv;
353 if (gettimeofday (&tv, NULL)) {
354 err (1, "gettimeofday");
356 return tv.tv_sec + tv.tv_usec*1e-6;
359 static int hasdata (void)
361 int ret, avail;
362 ret = ioctl (state.csock, FIONREAD, &avail);
363 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
364 return avail > 0;
367 CAMLprim value ml_hasdata (value fd_v)
369 CAMLparam1 (fd_v);
370 int ret, avail;
372 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
373 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
374 CAMLreturn (Val_bool (avail > 0));
377 static void readdata (int fd, void *p, int size)
379 ssize_t n;
381 again:
382 n = read (fd, p, size);
383 if (n - size) {
384 if (n < 0 && errno == EINTR) goto again;
385 if (!n) errx (1, "EOF while reading");
386 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
390 static void writedata (int fd, char *p, int size)
392 ssize_t n;
393 uint32_t size4 = size;
394 struct iovec iov[2] = {
395 { .iov_base = &size4, .iov_len = 4 },
396 { .iov_base = p, .iov_len = size }
399 again:
400 n = writev (fd, iov, 2);
401 if (n < 0 && errno == EINTR) goto again;
402 if (n - size - 4) {
403 if (!n) errx (1, "EOF while writing data");
404 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
408 static int readlen (int fd)
410 uint32_t u;
411 readdata (fd, &u, 4);
412 return u;
415 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
417 CAMLparam3 (fd_v, bytes_v, len_v);
418 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
419 CAMLreturn0;
422 CAMLprim value ml_rcmd (value fd_v)
424 CAMLparam1 (fd_v);
425 CAMLlocal1 (strdata_v);
426 int fd = Int_val (fd_v);
427 int len = readlen (fd);
428 strdata_v = caml_alloc_string (len);
429 readdata (fd, String_val (strdata_v), len);
430 CAMLreturn (strdata_v);
433 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
435 char fbuf[64];
436 int size = sizeof (fbuf), len;
437 va_list ap;
438 char *buf = fbuf;
440 for (;;) {
441 va_start (ap, fmt);
442 len = vsnprintf (buf, size, fmt, ap);
443 va_end (ap);
445 if (len > -1) {
446 if (len < size - 4) {
447 writedata (state.csock, buf, len);
448 break;
450 else size = len + 5;
452 else {
453 err (1, "vsnprintf for `%s' failed", fmt);
455 buf = realloc (buf == fbuf ? NULL : buf, size);
456 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
458 if (buf != fbuf) free (buf);
461 static void closedoc (void)
463 #ifdef CACHE_PAGEREFS
464 if (state.pdflut.objs) {
465 for (int i = 0; i < state.pdflut.count; ++i) {
466 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
468 free (state.pdflut.objs);
469 state.pdflut.objs = NULL;
470 state.pdflut.idx = 0;
472 #endif
473 if (state.doc) {
474 fz_drop_document (state.ctx, state.doc);
475 state.doc = NULL;
479 static int openxref (char *filename, char *password, int layouth)
481 for (int i = 0; i < state.texcount; ++i) {
482 state.texowners[i].w = -1;
483 state.texowners[i].slice = NULL;
486 closedoc ();
488 state.dirty = 0;
489 if (state.pagedims) {
490 free (state.pagedims);
491 state.pagedims = NULL;
493 state.pagedimcount = 0;
495 fz_set_aa_level (state.ctx, state.aalevel);
496 state.doc = fz_open_document (state.ctx, filename);
497 if (fz_needs_password (state.ctx, state.doc)) {
498 if (password && !*password) {
499 printd ("pass");
500 return 0;
502 else {
503 int ok = fz_authenticate_password (state.ctx, state.doc, password);
504 if (!ok) {
505 printd ("pass fail");
506 return 0;
510 if (layouth >= 0)
511 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
512 state.pagecount = fz_count_pages (state.ctx, state.doc);
513 return 1;
516 static void pdfinfo (void)
518 struct { char *tag; char *name; } metatbl[] = {
519 { FZ_META_INFO_TITLE, "Title" },
520 { FZ_META_INFO_AUTHOR, "Author" },
521 { FZ_META_FORMAT, "Format" },
522 { FZ_META_ENCRYPTION, "Encryption" },
523 { "info:Creator", "Creator" },
524 { "info:Producer", "Producer" },
525 { "info:CreationDate", "Creation date" },
527 int len = 0;
528 char *buf = NULL;
530 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
531 int need;
532 again:
533 need = fz_lookup_metadata (state.ctx, state.doc,
534 metatbl[i].tag, buf, len);
535 if (need > 0) {
536 if (need <= len) {
537 printd ("info %s\t%s", metatbl[i].name, buf);
539 else {
540 buf = realloc (buf, need + 1);
541 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
542 len = need + 1;
543 goto again;
547 free (buf);
549 printd ("infoend");
552 static void unlinktile (struct tile *tile)
554 for (int i = 0; i < tile->slicecount; ++i) {
555 struct slice *s = &tile->slices[i];
557 if (s->texindex != -1) {
558 if (state.texowners[s->texindex].slice == s) {
559 state.texowners[s->texindex].slice = NULL;
565 static void freepage (struct page *page)
567 if (!page) return;
568 if (page->text) {
569 fz_drop_stext_page (state.ctx, page->text);
571 if (page->slinks) {
572 free (page->slinks);
574 fz_drop_display_list (state.ctx, page->dlist);
575 fz_drop_page (state.ctx, page->fzpage);
576 free (page);
579 static void freetile (struct tile *tile)
581 unlinktile (tile);
582 if (!tile->pbo) {
583 #ifndef PIGGYBACK
584 fz_drop_pixmap (state.ctx, tile->pixmap);
585 #else
586 if (state.pig) {
587 fz_drop_pixmap (state.ctx, state.pig);
589 state.pig = tile->pixmap;
590 #endif
592 else {
593 free (tile->pbo);
594 fz_drop_pixmap (state.ctx, tile->pixmap);
596 free (tile);
599 #ifdef __ALTIVEC__
600 #include <stdint.h>
601 #include <altivec.h>
603 static int cacheline32bytes;
605 static void __attribute__ ((constructor)) clcheck (void)
607 char **envp = environ;
608 unsigned long *auxv;
610 while (*envp++);
612 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
613 if (*auxv == 19) {
614 cacheline32bytes = auxv[1] == 32;
615 return;
620 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
622 size_t size = pixmap->w * pixmap->h * pixmap->n;
623 if (cacheline32bytes && size > 32) {
624 intptr_t a1, a2, diff;
625 size_t sizea, i;
626 vector unsigned char v = vec_splat_u8 (-1);
627 vector unsigned char *p;
629 a1 = a2 = (intptr_t) pixmap->samples;
630 a2 = (a1 + 31) & ~31;
631 diff = a2 - a1;
632 sizea = size - diff;
633 p = (void *) a2;
635 while (a1 != a2) *(char *) a1++ = 0xff;
636 for (i = 0; i < (sizea & ~31); i += 32) {
637 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
638 vec_st (v, i, p);
639 vec_st (v, i + 16, p);
641 while (i < sizea) *((char *) a1 + i++) = 0xff;
643 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
645 #else
646 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
647 #endif
649 static void trimctm (pdf_page *page, int pindex)
651 fz_matrix ctm;
652 struct pagedim *pdim = &state.pagedims[pindex];
654 if (!page) return;
655 if (!pdim->tctmready) {
656 fz_rect realbox, mediabox;
657 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
659 fz_rotate (&rm, -pdim->rotate);
660 fz_scale (&sm, 1, -1);
661 fz_concat (&ctm, &rm, &sm);
662 realbox = pdim->mediabox;
663 fz_transform_rect (&realbox, &ctm);
664 fz_translate (&tm, -realbox.x0, -realbox.y0);
665 fz_concat (&ctm1, &ctm, &tm);
666 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
667 fz_invert_matrix (&im, &page_ctm);
668 fz_concat (&ctm, &im, &ctm1);
669 pdim->tctm = ctm;
670 pdim->tctmready = 1;
674 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
676 fz_matrix ctm, tm;
677 ptrdiff_t pdimno = pdim - state.pagedims;
679 ARSERT (pdim - state.pagedims < INT_MAX);
680 if (pdf_specifics (state.ctx, state.doc)) {
681 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
682 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
684 else {
685 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
686 fz_concat (&ctm, &tm, &pdim->ctm);
688 return ctm;
691 static fz_matrix pagectm (struct page *page)
693 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
696 static void *loadpage (int pageno, int pindex)
698 fz_device *dev;
699 struct page *page;
701 page = calloc (sizeof (struct page), 1);
702 if (!page) {
703 err (1, "calloc page %d", pageno);
706 page->dlist = fz_new_display_list (state.ctx, NULL);
707 dev = fz_new_list_device (state.ctx, page->dlist);
708 fz_try (state.ctx) {
709 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
710 fz_run_page (state.ctx, page->fzpage, dev,
711 &fz_identity, NULL);
713 fz_catch (state.ctx) {
714 page->fzpage = NULL;
716 fz_close_device (state.ctx, dev);
717 fz_drop_device (state.ctx, dev);
719 page->pdimno = pindex;
720 page->pageno = pageno;
721 page->sgen = state.gen;
722 page->agen = state.gen;
723 page->tgen = state.gen;
724 return page;
727 static struct tile *alloctile (int h)
729 int slicecount;
730 size_t tilesize;
731 struct tile *tile;
733 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
734 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
735 tile = calloc (tilesize, 1);
736 if (!tile) {
737 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
739 for (int i = 0; i < slicecount; ++i) {
740 int sh = fz_mini (h, state.sliceheight);
741 tile->slices[i].h = sh;
742 tile->slices[i].texindex = -1;
743 h -= sh;
745 tile->slicecount = slicecount;
746 tile->sliceheight = state.sliceheight;
747 return tile;
750 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
751 struct bo *pbo)
753 fz_rect rect;
754 fz_irect bbox;
755 fz_matrix ctm;
756 fz_device *dev;
757 struct tile *tile;
758 struct pagedim *pdim;
760 tile = alloctile (h);
761 pdim = &state.pagedims[page->pdimno];
763 bbox = pdim->bounds;
764 bbox.x0 += x;
765 bbox.y0 += y;
766 bbox.x1 = bbox.x0 + w;
767 bbox.y1 = bbox.y0 + h;
769 if (state.pig) {
770 if (state.pig->w == w
771 && state.pig->h == h
772 && state.pig->colorspace == state.colorspace) {
773 tile->pixmap = state.pig;
774 tile->pixmap->x = bbox.x0;
775 tile->pixmap->y = bbox.y0;
777 else {
778 fz_drop_pixmap (state.ctx, state.pig);
780 state.pig = NULL;
782 if (!tile->pixmap) {
783 if (pbo) {
784 tile->pixmap =
785 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
786 &bbox, NULL, 1, pbo->ptr);
787 tile->pbo = pbo;
789 else {
790 tile->pixmap =
791 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
792 NULL, 1);
796 tile->w = w;
797 tile->h = h;
798 clearpixmap (tile->pixmap);
800 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
801 ctm = pagectm (page);
802 fz_rect_from_irect (&rect, &bbox);
803 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
804 fz_close_device (state.ctx, dev);
805 fz_drop_device (state.ctx, dev);
807 return tile;
810 #ifdef CACHE_PAGEREFS
811 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
812 thanks to Robin Watts */
813 static void
814 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
816 fz_context *ctx = state.ctx; /* doc->ctx; */
817 pdf_obj *kids;
818 int len;
820 if (state.pdflut.idx == state.pagecount) return;
822 kids = pdf_dict_gets (ctx, node, "Kids");
823 len = pdf_array_len (ctx, kids);
825 if (len == 0)
826 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
828 if (pdf_mark_obj (ctx, node))
829 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
830 for (int i = 0; i < len; i++) {
831 pdf_obj *kid = pdf_array_get (ctx, kids, i);
832 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
833 if (*type
834 ? !strcmp (type, "Pages")
835 : pdf_dict_gets (ctx, kid, "Kids")
836 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
837 pdf_collect_pages (doc, kid);
839 else {
840 if (*type
841 ? strcmp (type, "Page") != 0
842 : !pdf_dict_gets (ctx, kid, "MediaBox"))
843 fz_warn (ctx, "non-page object in page tree (%s)", type);
844 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
847 pdf_unmark_obj (ctx, node);
850 static void
851 pdf_load_page_objs (pdf_document *doc)
853 pdf_obj *root = pdf_dict_gets (state.ctx,
854 pdf_trailer (state.ctx, doc), "Root");
855 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
857 if (!node)
858 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
860 state.pdflut.idx = 0;
861 pdf_collect_pages (doc, node);
863 #endif
865 static void initpdims (void)
867 double start, end;
868 FILE *trimf = NULL;
869 fz_rect rootmediabox = fz_empty_rect;
870 int pageno, trim, show;
871 int trimw = 0, cxcount;
872 fz_context *ctx = state.ctx;
873 pdf_document *pdf = pdf_specifics (ctx, state.doc);
875 fz_var (trimw);
876 fz_var (trimf);
877 fz_var (cxcount);
878 start = now ();
880 if (state.trimmargins && state.trimcachepath) {
881 trimf = fopen (state.trimcachepath, "rb");
882 if (!trimf) {
883 trimf = fopen (state.trimcachepath, "wb");
884 trimw = 1;
888 if (state.trimmargins || pdf)
889 cxcount = state.pagecount;
890 else
891 cxcount = fz_mini (state.pagecount, 1);
893 if (pdf) {
894 pdf_obj *obj;
895 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
896 "Root/Pages/MediaBox");
897 pdf_to_rect (ctx, obj, &rootmediabox);
900 #ifdef CACHE_PAGEREFS
901 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
902 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
903 if (!state.pdflut.objs) {
904 err (1, "malloc pageobjs %zu %d %zu failed",
905 sizeof (*state.pdflut.objs), cxcount,
906 sizeof (*state.pdflut.objs) * cxcount);
908 state.pdflut.count = cxcount;
909 pdf_load_page_objs (pdf);
910 state.pdflut.pdf = pdf;
912 #endif
914 for (pageno = 0; pageno < cxcount; ++pageno) {
915 int rotate = 0;
916 struct pagedim *p;
917 fz_rect mediabox = fz_empty_rect;
919 fz_var (rotate);
920 if (pdf) {
921 pdf_obj *pageref, *pageobj;
923 #ifdef CACHE_PAGEREFS
924 pageref = state.pdflut.objs[pageno];
925 #else
926 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
927 #endif
928 pageobj = pdf_resolve_indirect (ctx, pageref);
929 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
931 if (state.trimmargins) {
932 pdf_obj *obj;
933 pdf_page *page;
935 fz_try (ctx) {
936 page = pdf_load_page (ctx, pdf, pageno);
937 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
938 trim = state.trimanew || !obj;
939 if (trim) {
940 fz_rect rect;
941 fz_device *dev;
942 fz_matrix ctm, page_ctm;
944 dev = fz_new_bbox_device (ctx, &rect);
945 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
946 fz_invert_matrix (&ctm, &page_ctm);
947 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
948 fz_close_device (ctx, dev);
949 fz_drop_device (ctx, dev);
951 rect.x0 += state.trimfuzz.x0;
952 rect.x1 += state.trimfuzz.x1;
953 rect.y0 += state.trimfuzz.y0;
954 rect.y1 += state.trimfuzz.y1;
955 fz_transform_rect (&rect, &ctm);
956 fz_intersect_rect (&rect, &mediabox);
958 if (!fz_is_empty_rect (&rect)) {
959 mediabox = rect;
962 obj = pdf_new_array (ctx, pdf, 4);
963 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
964 mediabox.x0));
965 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
966 mediabox.y0));
967 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
968 mediabox.x1));
969 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
970 mediabox.y1));
971 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
973 else {
974 mediabox.x0 = pdf_to_real (ctx,
975 pdf_array_get (ctx, obj, 0));
976 mediabox.y0 = pdf_to_real (ctx,
977 pdf_array_get (ctx, obj, 1));
978 mediabox.x1 = pdf_to_real (ctx,
979 pdf_array_get (ctx, obj, 2));
980 mediabox.y1 = pdf_to_real (ctx,
981 pdf_array_get (ctx, obj, 3));
984 fz_drop_page (ctx, &page->super);
985 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
986 if (show) {
987 printd ("progress %f Trimming %d",
988 (double) (pageno + 1) / state.pagecount,
989 pageno + 1);
992 fz_catch (ctx) {
993 printd ("emsg failed to load page %d", pageno);
996 else {
997 int empty = 0;
998 fz_rect cropbox;
1000 pdf_to_rect (ctx,
1001 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1002 &mediabox);
1003 if (fz_is_empty_rect (&mediabox)) {
1004 mediabox.x0 = 0;
1005 mediabox.y0 = 0;
1006 mediabox.x1 = 612;
1007 mediabox.y1 = 792;
1008 empty = 1;
1011 pdf_to_rect (ctx,
1012 pdf_dict_gets (ctx, pageobj, "CropBox"),
1013 &cropbox);
1014 if (!fz_is_empty_rect (&cropbox)) {
1015 if (empty) {
1016 mediabox = cropbox;
1018 else {
1019 fz_intersect_rect (&mediabox, &cropbox);
1022 else {
1023 if (empty) {
1024 if (fz_is_empty_rect (&rootmediabox)) {
1025 printd ("emsg cannot find page size for page %d",
1026 pageno);
1028 else {
1029 mediabox = rootmediabox;
1035 else {
1036 if (state.trimmargins && trimw) {
1037 fz_page *page;
1039 fz_try (ctx) {
1040 page = fz_load_page (ctx, state.doc, pageno);
1041 fz_bound_page (ctx, page, &mediabox);
1042 if (state.trimmargins) {
1043 fz_rect rect;
1044 fz_device *dev;
1046 dev = fz_new_bbox_device (ctx, &rect);
1047 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1048 fz_close_device (ctx, dev);
1049 fz_drop_device (ctx, dev);
1051 rect.x0 += state.trimfuzz.x0;
1052 rect.x1 += state.trimfuzz.x1;
1053 rect.y0 += state.trimfuzz.y0;
1054 rect.y1 += state.trimfuzz.y1;
1055 fz_intersect_rect (&rect, &mediabox);
1057 if (!fz_is_empty_rect (&rect)) {
1058 mediabox = rect;
1061 fz_drop_page (ctx, page);
1063 fz_catch (ctx) {
1065 if (trimf) {
1066 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1067 if (n - 1) {
1068 err (1, "fwrite trim mediabox");
1072 else {
1073 if (trimf) {
1074 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1075 if (n - 1) {
1076 err (1, "fread trim mediabox %d", pageno);
1079 else {
1080 fz_page *page;
1081 fz_try (ctx) {
1082 page = fz_load_page (ctx, state.doc, pageno);
1083 fz_bound_page (ctx, page, &mediabox);
1084 fz_drop_page (ctx, page);
1086 show = !state.trimmargins && pageno % 20 == 0;
1087 if (show) {
1088 printd ("progress %f Gathering dimensions %d",
1089 (double) (pageno) / state.pagecount,
1090 pageno);
1093 fz_catch (ctx) {
1094 printd ("emsg failed to load page %d", pageno);
1100 if (state.pagedimcount == 0
1101 || ((void) (p = &state.pagedims[state.pagedimcount-1])
1102 , p->rotate != rotate)
1103 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1104 size_t size;
1106 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1107 state.pagedims = realloc (state.pagedims, size);
1108 if (!state.pagedims) {
1109 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1110 size, state.pagedimcount + 1);
1113 p = &state.pagedims[state.pagedimcount++];
1114 p->rotate = rotate;
1115 p->mediabox = mediabox;
1116 p->pageno = pageno;
1119 end = now ();
1120 printd ("progress 1 %s %d pages in %f seconds",
1121 state.trimmargins ? "Trimmed" : "Processed",
1122 state.pagecount, end - start);
1123 state.trimanew = 0;
1124 if (trimf) {
1125 if (fclose (trimf)) {
1126 err (1, "fclose");
1131 static void layout (void)
1133 int pindex;
1134 fz_rect box;
1135 fz_matrix ctm, rm;
1136 struct pagedim *p = NULL;
1137 float zw, w, maxw = 0.0, zoom = 1.0;
1139 if (state.pagedimcount == 0) return;
1141 switch (state.fitmodel) {
1142 case FitProportional:
1143 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1144 float x0, x1;
1146 p = &state.pagedims[pindex];
1147 fz_rotate (&rm, p->rotate + state.rotate);
1148 box = p->mediabox;
1149 fz_transform_rect (&box, &rm);
1151 x0 = fz_min (box.x0, box.x1);
1152 x1 = fz_max (box.x0, box.x1);
1154 w = x1 - x0;
1155 maxw = fz_max (w, maxw);
1156 zoom = state.w / maxw;
1158 break;
1160 case FitPage:
1161 maxw = state.w;
1162 break;
1164 case FitWidth:
1165 break;
1167 default:
1168 ARSERT (0 && state.fitmodel);
1171 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1172 fz_rect rect;
1173 fz_matrix tm, sm;
1175 p = &state.pagedims[pindex];
1176 fz_rotate (&ctm, state.rotate);
1177 fz_rotate (&rm, p->rotate + state.rotate);
1178 box = p->mediabox;
1179 fz_transform_rect (&box, &rm);
1180 w = box.x1 - box.x0;
1181 switch (state.fitmodel) {
1182 case FitProportional:
1183 p->left = (int) (((maxw - w) * zoom) / 2.f);
1184 break;
1185 case FitPage:
1187 float zh, h;
1188 zw = maxw / w;
1189 h = box.y1 - box.y0;
1190 zh = state.h / h;
1191 zoom = fz_min (zw, zh);
1192 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1194 break;
1195 case FitWidth:
1196 p->left = 0;
1197 zoom = state.w / w;
1198 break;
1201 fz_scale (&p->zoomctm, zoom, zoom);
1202 fz_concat (&ctm, &p->zoomctm, &ctm);
1204 fz_rotate (&rm, p->rotate);
1205 p->pagebox = p->mediabox;
1206 fz_transform_rect (&p->pagebox, &rm);
1207 p->pagebox.x1 -= p->pagebox.x0;
1208 p->pagebox.y1 -= p->pagebox.y0;
1209 p->pagebox.x0 = 0;
1210 p->pagebox.y0 = 0;
1211 rect = p->pagebox;
1212 fz_transform_rect (&rect, &ctm);
1213 fz_round_rect (&p->bounds, &rect);
1214 p->ctm = ctm;
1216 fz_translate (&tm, 0, -p->mediabox.y1);
1217 fz_scale (&sm, zoom, -zoom);
1218 fz_concat (&ctm, &tm, &sm);
1220 p->tctmready = 0;
1223 do {
1224 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1225 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1226 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1227 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1228 int boundw = x1 - x0;
1229 int boundh = y1 - y0;
1231 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1232 } while (p-- != state.pagedims);
1235 struct pagedim *pdimofpageno (int pageno)
1237 struct pagedim *pdim = state.pagedims;
1239 for (int i = 0; i < state.pagedimcount; ++i) {
1240 if (state.pagedims[i].pageno > pageno)
1241 break;
1242 pdim = &state.pagedims[i];
1244 return pdim;
1247 static void recurse_outline (fz_outline *outline, int level)
1249 while (outline) {
1250 if (outline->page >= 0) {
1251 fz_point p = {.x = outline->x, .y = outline->y};
1252 struct pagedim *pdim = pdimofpageno (outline->page);
1253 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1254 fz_transform_point (&p, &pdim->ctm);
1255 printd ("o %d %d %d %d %s",
1256 level, outline->page, (int) p.y, h, outline->title);
1258 else {
1259 printd ("on %d %s", level, outline->title);
1261 if (outline->down) {
1262 recurse_outline (outline->down, level + 1);
1264 outline = outline->next;
1268 static void process_outline (void)
1270 fz_outline *outline;
1272 if (!state.needoutline || !state.pagedimcount) return;
1274 state.needoutline = 0;
1275 outline = fz_load_outline (state.ctx, state.doc);
1276 if (outline) {
1277 recurse_outline (outline, 0);
1278 fz_drop_outline (state.ctx, outline);
1282 static char *strofline (fz_stext_line *line)
1284 char *p;
1285 char utf8[10];
1286 fz_stext_char *ch;
1287 size_t size = 0, cap = 80;
1289 p = malloc (cap + 1);
1290 if (!p) return NULL;
1292 for (ch = line->first_char; ch; ch = ch->next) {
1293 int n = fz_runetochar (utf8, ch->c);
1294 if (size + n > cap) {
1295 cap *= 2;
1296 p = realloc (p, cap + 1);
1297 if (!p) return NULL;
1300 memcpy (p + size, utf8, n);
1301 size += n;
1303 p[size] = 0;
1304 return p;
1307 static int matchline (regex_t *re, fz_stext_line *line,
1308 int stop, int pageno, double start)
1310 int ret;
1311 char *p;
1312 regmatch_t rm;
1314 p = strofline (line);
1315 if (!p) return -1;
1317 ret = regexec (re, p, 1, &rm, 0);
1318 if (ret) {
1319 free (p);
1320 if (ret != REG_NOMATCH) {
1321 size_t size;
1322 char errbuf[80];
1323 size = regerror (ret, re, errbuf, sizeof (errbuf));
1324 printd ("msg regexec error `%.*s'",
1325 (int) size, errbuf);
1326 return -1;
1328 return 0;
1330 else {
1331 fz_point p1, p2, p3, p4;
1332 fz_rect s = {0,0,0,0}, e;
1333 fz_stext_char *ch;
1334 int o = 0;
1336 for (ch = line->first_char; ch; ch = ch->next) {
1337 o += fz_runelen (ch->c);
1338 if (o > rm.rm_so) {
1339 s = ch->bbox;
1340 break;
1343 for (;ch; ch = ch->next) {
1344 o += fz_runelen (ch->c);
1345 if (o > rm.rm_eo) break;
1347 e = ch->bbox;
1349 p1.x = s.x0;
1350 p1.y = s.y0;
1351 p2.x = e.x1;
1352 p2.y = s.y0;
1353 p3.x = e.x1;
1354 p3.y = e.y1;
1355 p4.x = s.x0;
1356 p4.y = e.y1;
1358 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1359 if (!stop) {
1360 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1361 pageno, 1,
1362 p1.x, p1.y,
1363 p2.x, p2.y,
1364 p3.x, p3.y,
1365 p4.x, p4.y);
1367 printd ("progress 1 found at %d `%.*s' in %f sec",
1368 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1369 now () - start);
1371 else {
1372 printd ("match %d %d %f %f %f %f %f %f %f %f",
1373 pageno, 2,
1374 p1.x, p1.y,
1375 p2.x, p2.y,
1376 p3.x, p3.y,
1377 p4.x, p4.y);
1379 #pragma GCC diagnostic error "-Wdouble-promotion"
1380 free (p);
1381 return 1;
1385 /* wishful thinking function */
1386 static void search (regex_t *re, int pageno, int y, int forward)
1388 fz_device *tdev;
1389 fz_stext_page *text;
1390 struct pagedim *pdim;
1391 int stop = 0, niters = 0;
1392 double start, end;
1393 fz_page *page;
1394 fz_stext_block *block;
1396 start = now ();
1397 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1398 if (niters++ == 5) {
1399 niters = 0;
1400 if (hasdata ()) {
1401 printd ("progress 1 attention requested aborting search at %d",
1402 pageno);
1403 stop = 1;
1405 else {
1406 printd ("progress %f searching in page %d",
1407 (double) (pageno + 1) / state.pagecount,
1408 pageno);
1411 pdim = pdimofpageno (pageno);
1412 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1413 tdev = fz_new_stext_device (state.ctx, text, 0);
1415 page = fz_load_page (state.ctx, state.doc, pageno);
1417 fz_matrix ctm = pagectm1 (page, pdim);
1418 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1421 fz_close_device (state.ctx, tdev);
1422 fz_drop_device (state.ctx, tdev);
1424 if (forward) {
1425 for (block = text->first_block; block; block = block->next) {
1426 fz_stext_line *line;
1428 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1429 for (line = block->u.t.first_line; line; line = line->next) {
1430 if (line->bbox.y0 < y + 1) continue;
1432 switch (matchline (re, line, stop, pageno, start)) {
1433 case 0: break;
1434 case 1: stop = 1; break;
1435 case -1: stop = 1; goto endloop;
1440 else {
1441 for (block = text->last_block; block; block = block->prev) {
1442 fz_stext_line *line;
1444 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1445 for (line = block->u.t.last_line; line; line = line->prev) {
1446 if (line->bbox.y0 < y + 1) continue;
1448 switch (matchline (re, line, stop, pageno, start)) {
1449 case 0: break;
1450 case 1: stop = 1; break;
1451 case -1: stop = 1; goto endloop;
1457 if (forward) {
1458 pageno += 1;
1459 y = 0;
1461 else {
1462 pageno -= 1;
1463 y = INT_MAX;
1465 endloop:
1466 fz_drop_stext_page (state.ctx, text);
1467 fz_drop_page (state.ctx, page);
1469 end = now ();
1470 if (!stop) {
1471 printd ("progress 1 no matches %f sec", end - start);
1473 printd ("clearrects");
1476 static void set_tex_params (int colorspace)
1478 switch (colorspace) {
1479 case 0:
1480 state.texiform = GL_RGBA8;
1481 state.texform = GL_RGBA;
1482 state.texty = GL_UNSIGNED_BYTE;
1483 state.colorspace = fz_device_rgb (state.ctx);
1484 break;
1485 case 1:
1486 state.texiform = GL_RGBA8;
1487 state.texform = GL_BGRA;
1488 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1489 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1490 #else
1491 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1492 #endif
1493 state.colorspace = fz_device_bgr (state.ctx);
1494 break;
1495 case 2:
1496 state.texiform = GL_LUMINANCE_ALPHA;
1497 state.texform = GL_LUMINANCE_ALPHA;
1498 state.texty = GL_UNSIGNED_BYTE;
1499 state.colorspace = fz_device_gray (state.ctx);
1500 break;
1501 default:
1502 errx (1, "invalid colorspce %d", colorspace);
1506 static void realloctexts (int texcount)
1508 size_t size;
1510 if (texcount == state.texcount) return;
1512 if (texcount < state.texcount) {
1513 glDeleteTextures (state.texcount - texcount,
1514 state.texids + texcount);
1517 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1518 state.texids = realloc (state.texids, size);
1519 if (!state.texids) {
1520 err (1, "realloc texs %" FMT_s, size);
1523 state.texowners = (void *) (state.texids + texcount);
1524 if (texcount > state.texcount) {
1525 glGenTextures (texcount - state.texcount,
1526 state.texids + state.texcount);
1527 for (int i = state.texcount; i < texcount; ++i) {
1528 state.texowners[i].w = -1;
1529 state.texowners[i].slice = NULL;
1532 state.texcount = texcount;
1533 state.texindex = 0;
1536 static char *mbtoutf8 (char *s)
1538 char *p, *r;
1539 wchar_t *tmp;
1540 size_t i, ret, len;
1542 if (state.utf8cs) {
1543 return s;
1546 len = mbstowcs (NULL, s, strlen (s));
1547 if (len == 0) {
1548 return s;
1550 else {
1551 if (len == (size_t) -1) {
1552 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1553 return s;
1557 tmp = calloc (len, sizeof (wchar_t));
1558 if (!tmp) {
1559 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1560 len, sizeof (wchar_t), errno, strerror (errno));
1561 return s;
1564 ret = mbstowcs (tmp, s, len);
1565 if (ret == (size_t) -1) {
1566 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1567 len, errno, strerror (errno));
1568 free (tmp);
1569 return s;
1572 len = 0;
1573 for (i = 0; i < ret; ++i) {
1574 len += fz_runelen (tmp[i]);
1577 p = r = malloc (len + 1);
1578 if (!r) {
1579 printd ("emsg mbtoutf8: malloc(%zu)", len);
1580 free (tmp);
1581 return s;
1584 for (i = 0; i < ret; ++i) {
1585 p += fz_runetochar (p, tmp[i]);
1587 *p = 0;
1588 free (tmp);
1589 return r;
1592 CAMLprim value ml_mbtoutf8 (value s_v)
1594 CAMLparam1 (s_v);
1595 CAMLlocal1 (ret_v);
1596 char *s, *r;
1598 s = String_val (s_v);
1599 r = mbtoutf8 (s);
1600 if (r == s) {
1601 ret_v = s_v;
1603 else {
1604 ret_v = caml_copy_string (r);
1605 free (r);
1607 CAMLreturn (ret_v);
1610 static void * mainloop (void UNUSED_ATTR *unused)
1612 char *p = NULL;
1613 int len, ret, oldlen = 0;
1615 fz_var (p);
1616 fz_var (oldlen);
1617 for (;;) {
1618 len = readlen (state.csock);
1619 if (len == 0) {
1620 errx (1, "readlen returned 0");
1623 if (oldlen < len + 1) {
1624 p = realloc (p, len + 1);
1625 if (!p) {
1626 err (1, "realloc %d failed", len + 1);
1628 oldlen = len + 1;
1630 readdata (state.csock, p, len);
1631 p[len] = 0;
1633 if (!strncmp ("open", p, 4)) {
1634 int off, usedoccss, ok = 0, layouth;
1635 char *password;
1636 char *filename;
1637 char *utf8filename;
1638 size_t filenamelen;
1640 fz_var (ok);
1641 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1642 if (ret != 2) {
1643 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1646 filename = p + 5 + off;
1647 filenamelen = strlen (filename);
1648 password = filename + filenamelen + 1;
1650 if (password[strlen (password) + 1]) {
1651 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1654 lock ("open");
1655 fz_set_use_document_css (state.ctx, usedoccss);
1656 fz_try (state.ctx) {
1657 ok = openxref (filename, password, layouth);
1659 fz_catch (state.ctx) {
1660 utf8filename = mbtoutf8 (filename);
1661 printd ("msg Could not open %s", utf8filename);
1662 if (utf8filename != filename) {
1663 free (utf8filename);
1666 if (ok) {
1667 pdfinfo ();
1668 initpdims ();
1670 unlock ("open");
1672 if (ok) {
1673 utf8filename = mbtoutf8 (filename);
1674 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1675 if (utf8filename != filename) {
1676 free (utf8filename);
1678 state.needoutline = 1;
1681 else if (!strncmp ("cs", p, 2)) {
1682 int i, colorspace;
1684 ret = sscanf (p + 2, " %d", &colorspace);
1685 if (ret != 1) {
1686 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1688 lock ("cs");
1689 set_tex_params (colorspace);
1690 for (i = 0; i < state.texcount; ++i) {
1691 state.texowners[i].w = -1;
1692 state.texowners[i].slice = NULL;
1694 unlock ("cs");
1696 else if (!strncmp ("freepage", p, 8)) {
1697 void *ptr;
1699 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1700 if (ret != 1) {
1701 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1703 lock ("freepage");
1704 freepage (ptr);
1705 unlock ("freepage");
1707 else if (!strncmp ("freetile", p, 8)) {
1708 void *ptr;
1710 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1711 if (ret != 1) {
1712 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1714 lock ("freetile");
1715 freetile (ptr);
1716 unlock ("freetile");
1718 else if (!strncmp ("search", p, 6)) {
1719 int icase, pageno, y, len2, forward;
1720 char *pattern;
1721 regex_t re;
1723 ret = sscanf (p + 6, " %d %d %d %d,%n",
1724 &icase, &pageno, &y, &forward, &len2);
1725 if (ret != 4) {
1726 errx (1, "malformed search `%s' ret=%d", p, ret);
1729 pattern = p + 6 + len2;
1730 ret = regcomp (&re, pattern,
1731 REG_EXTENDED | (icase ? REG_ICASE : 0));
1732 if (ret) {
1733 char errbuf[80];
1734 size_t size;
1736 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1737 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1739 else {
1740 search (&re, pageno, y, forward);
1741 regfree (&re);
1744 else if (!strncmp ("geometry", p, 8)) {
1745 int w, h, fitmodel;
1747 printd ("clear");
1748 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1749 if (ret != 3) {
1750 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1753 lock ("geometry");
1754 state.h = h;
1755 if (w != state.w) {
1756 state.w = w;
1757 for (int i = 0; i < state.texcount; ++i) {
1758 state.texowners[i].slice = NULL;
1761 state.fitmodel = fitmodel;
1762 layout ();
1763 process_outline ();
1765 state.gen++;
1766 unlock ("geometry");
1767 printd ("continue %d", state.pagecount);
1769 else if (!strncmp ("reqlayout", p, 9)) {
1770 char *nameddest;
1771 int rotate, off, h;
1772 int fitmodel;
1773 pdf_document *pdf;
1775 printd ("clear");
1776 ret = sscanf (p + 9, " %d %d %d %n",
1777 &rotate, &fitmodel, &h, &off);
1778 if (ret != 3) {
1779 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1781 lock ("reqlayout");
1782 pdf = pdf_specifics (state.ctx, state.doc);
1783 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1784 state.gen += 1;
1786 state.rotate = rotate;
1787 state.fitmodel = fitmodel;
1788 state.h = h;
1789 layout ();
1790 process_outline ();
1792 nameddest = p + 9 + off;
1793 if (pdf && nameddest && *nameddest) {
1794 fz_point xy;
1795 struct pagedim *pdim;
1796 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1797 &xy.x, &xy.y);
1798 pdim = pdimofpageno (pageno);
1799 fz_transform_point (&xy, &pdim->ctm);
1800 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1803 state.gen++;
1804 unlock ("reqlayout");
1805 printd ("continue %d", state.pagecount);
1807 else if (!strncmp ("page", p, 4)) {
1808 double a, b;
1809 struct page *page;
1810 int pageno, pindex;
1812 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1813 if (ret != 2) {
1814 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1817 lock ("page");
1818 a = now ();
1819 page = loadpage (pageno, pindex);
1820 b = now ();
1821 unlock ("page");
1823 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1825 else if (!strncmp ("tile", p, 4)) {
1826 int x, y, w, h;
1827 struct page *page;
1828 struct tile *tile;
1829 double a, b;
1830 void *data;
1832 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1833 SCN_ptr_cast (&page), &x, &y, &w, &h,
1834 SCN_ptr_cast (&data));
1835 if (ret != 6) {
1836 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1839 lock ("tile");
1840 a = now ();
1841 tile = rendertile (page, x, y, w, h, data);
1842 b = now ();
1843 unlock ("tile");
1845 printd ("tile %d %d %" FMT_ptr " %u %f",
1846 x, y,
1847 FMT_ptr_cast (tile),
1848 tile->w * tile->h * tile->pixmap->n,
1849 b - a);
1851 else if (!strncmp ("trimset", p, 7)) {
1852 fz_irect fuzz;
1853 int trimmargins;
1855 ret = sscanf (p + 7, " %d %d %d %d %d",
1856 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1857 if (ret != 5) {
1858 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1860 lock ("trimset");
1861 state.trimmargins = trimmargins;
1862 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1863 state.trimanew = 1;
1864 state.trimfuzz = fuzz;
1866 unlock ("trimset");
1868 else if (!strncmp ("settrim", p, 7)) {
1869 fz_irect fuzz;
1870 int trimmargins;
1872 ret = sscanf (p + 7, " %d %d %d %d %d",
1873 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1874 if (ret != 5) {
1875 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1877 printd ("clear");
1878 lock ("settrim");
1879 state.trimmargins = trimmargins;
1880 state.needoutline = 1;
1881 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1882 state.trimanew = 1;
1883 state.trimfuzz = fuzz;
1885 state.pagedimcount = 0;
1886 free (state.pagedims);
1887 state.pagedims = NULL;
1888 initpdims ();
1889 layout ();
1890 process_outline ();
1891 unlock ("settrim");
1892 printd ("continue %d", state.pagecount);
1894 else if (!strncmp ("sliceh", p, 6)) {
1895 int h;
1897 ret = sscanf (p + 6, " %d", &h);
1898 if (ret != 1) {
1899 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1901 if (h != state.sliceheight) {
1902 state.sliceheight = h;
1903 for (int i = 0; i < state.texcount; ++i) {
1904 state.texowners[i].w = -1;
1905 state.texowners[i].h = -1;
1906 state.texowners[i].slice = NULL;
1910 else if (!strncmp ("interrupt", p, 9)) {
1911 printd ("vmsg interrupted");
1913 else {
1914 errx (1, "unknown command %.*s", len, p);
1917 return 0;
1920 CAMLprim value ml_isexternallink (value uri_v)
1922 CAMLparam1 (uri_v);
1923 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1924 CAMLreturn (Val_bool (ext));
1927 CAMLprim value ml_uritolocation (value uri_v)
1929 CAMLparam1 (uri_v);
1930 CAMLlocal1 (ret_v);
1931 int pageno;
1932 fz_point xy;
1933 struct pagedim *pdim;
1935 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1936 &xy.x, &xy.y);
1937 pdim = pdimofpageno (pageno);
1938 fz_transform_point (&xy, &pdim->ctm);
1939 ret_v = caml_alloc_tuple (3);
1940 Field (ret_v, 0) = Val_int (pageno);
1941 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1942 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1943 CAMLreturn (ret_v);
1946 CAMLprim value ml_realloctexts (value texcount_v)
1948 CAMLparam1 (texcount_v);
1949 int ok;
1951 if (trylock (__func__)) {
1952 ok = 0;
1953 goto done;
1955 realloctexts (Int_val (texcount_v));
1956 ok = 1;
1957 unlock (__func__);
1959 done:
1960 CAMLreturn (Val_bool (ok));
1963 static void recti (int x0, int y0, int x1, int y1)
1965 GLfloat *v = state.vertices;
1967 glVertexPointer (2, GL_FLOAT, 0, v);
1968 v[0] = x0; v[1] = y0;
1969 v[2] = x1; v[3] = y0;
1970 v[4] = x0; v[5] = y1;
1971 v[6] = x1; v[7] = y1;
1972 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1975 static void showsel (struct page *page, int ox, int oy)
1977 fz_irect bbox;
1978 fz_rect rect;
1979 fz_stext_block *block;
1980 int seen = 0;
1981 unsigned char selcolor[] = {15,15,15,140};
1983 if (!page->fmark.ch || !page->lmark.ch) return;
1985 glEnable (GL_BLEND);
1986 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1987 glColor4ubv (selcolor);
1989 ox += state.pagedims[page->pdimno].bounds.x0;
1990 oy += state.pagedims[page->pdimno].bounds.y0;
1992 for (block = page->text->first_block; block; block = block->next) {
1993 fz_stext_line *line;
1995 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1996 for (line = block->u.t.first_line; line; line = line->next) {
1997 fz_stext_char *ch;
1999 rect = fz_empty_rect;
2000 for (ch = line->first_char; ch; ch = ch->next) {
2001 if (ch == page->fmark.ch) seen = 1;
2002 if (seen) fz_union_rect (&rect, &ch->bbox);
2003 if (ch == page->lmark.ch) {
2004 fz_round_rect (&bbox, &rect);
2005 recti (bbox.x0 + ox, bbox.y0 + oy,
2006 bbox.x1 + ox, bbox.y1 + oy);
2007 goto done;
2010 fz_round_rect (&bbox, &rect);
2011 recti (bbox.x0 + ox, bbox.y0 + oy,
2012 bbox.x1 + ox, bbox.y1 + oy);
2015 done:
2016 glDisable (GL_BLEND);
2019 #pragma GCC diagnostic push
2020 #pragma GCC diagnostic ignored "-Wdouble-promotion"
2021 #pragma GCC diagnostic ignored "-Wconversion"
2022 #include "glfont.c"
2023 #pragma GCC diagnostic pop
2025 static void stipplerect (fz_matrix *m,
2026 fz_point *p1,
2027 fz_point *p2,
2028 fz_point *p3,
2029 fz_point *p4,
2030 GLfloat *texcoords,
2031 GLfloat *vertices)
2033 fz_transform_point (p1, m);
2034 fz_transform_point (p2, m);
2035 fz_transform_point (p3, m);
2036 fz_transform_point (p4, m);
2038 float w, h, s, t;
2040 w = p2->x - p1->x;
2041 h = p2->y - p1->y;
2042 t = hypotf (w, h) * .25f;
2044 w = p3->x - p2->x;
2045 h = p3->y - p2->y;
2046 s = hypotf (w, h) * .25f;
2048 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2049 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2051 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2052 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2054 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2055 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2057 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2058 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2060 glDrawArrays (GL_LINES, 0, 8);
2063 static void solidrect (fz_matrix *m,
2064 fz_point *p1,
2065 fz_point *p2,
2066 fz_point *p3,
2067 fz_point *p4,
2068 GLfloat *vertices)
2070 fz_transform_point (p1, m);
2071 fz_transform_point (p2, m);
2072 fz_transform_point (p3, m);
2073 fz_transform_point (p4, m);
2074 vertices[0] = p1->x; vertices[1] = p1->y;
2075 vertices[2] = p2->x; vertices[3] = p2->y;
2077 vertices[4] = p3->x; vertices[5] = p3->y;
2078 vertices[6] = p4->x; vertices[7] = p4->y;
2079 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2082 static void ensurelinks (struct page *page)
2084 if (!page->links)
2085 page->links = fz_load_links (state.ctx, page->fzpage);
2088 static void highlightlinks (struct page *page, int xoff, int yoff)
2090 fz_matrix ctm, tm, pm;
2091 fz_link *link;
2092 GLfloat *texcoords = state.texcoords;
2093 GLfloat *vertices = state.vertices;
2095 ensurelinks (page);
2097 glEnable (GL_TEXTURE_1D);
2098 glEnable (GL_BLEND);
2099 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2100 glBindTexture (GL_TEXTURE_1D, state.stid);
2102 xoff -= state.pagedims[page->pdimno].bounds.x0;
2103 yoff -= state.pagedims[page->pdimno].bounds.y0;
2104 fz_translate (&tm, xoff, yoff);
2105 pm = pagectm (page);
2106 fz_concat (&ctm, &pm, &tm);
2108 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2109 glVertexPointer (2, GL_FLOAT, 0, vertices);
2111 for (link = page->links; link; link = link->next) {
2112 fz_point p1, p2, p3, p4;
2114 p1.x = link->rect.x0;
2115 p1.y = link->rect.y0;
2117 p2.x = link->rect.x1;
2118 p2.y = link->rect.y0;
2120 p3.x = link->rect.x1;
2121 p3.y = link->rect.y1;
2123 p4.x = link->rect.x0;
2124 p4.y = link->rect.y1;
2126 /* TODO: different colours for different schemes */
2127 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2128 else glColor3ub (255, 0, 0);
2130 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2133 for (int i = 0; i < page->annotcount; ++i) {
2134 fz_point p1, p2, p3, p4;
2135 struct annot *annot = &page->annots[i];
2137 p1.x = annot->bbox.x0;
2138 p1.y = annot->bbox.y0;
2140 p2.x = annot->bbox.x1;
2141 p2.y = annot->bbox.y0;
2143 p3.x = annot->bbox.x1;
2144 p3.y = annot->bbox.y1;
2146 p4.x = annot->bbox.x0;
2147 p4.y = annot->bbox.y1;
2149 glColor3ub (0, 0, 128);
2150 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2153 glDisable (GL_BLEND);
2154 glDisable (GL_TEXTURE_1D);
2157 static int compareslinks (const void *l, const void *r)
2159 struct slink const *ls = l;
2160 struct slink const *rs = r;
2161 if (ls->bbox.y0 == rs->bbox.y0) {
2162 return rs->bbox.x0 - rs->bbox.x0;
2164 return ls->bbox.y0 - rs->bbox.y0;
2167 static void droptext (struct page *page)
2169 if (page->text) {
2170 fz_drop_stext_page (state.ctx, page->text);
2171 page->fmark.ch = NULL;
2172 page->lmark.ch = NULL;
2173 page->text = NULL;
2177 static void dropannots (struct page *page)
2179 if (page->annots) {
2180 free (page->annots);
2181 page->annots = NULL;
2182 page->annotcount = 0;
2186 static void ensureannots (struct page *page)
2188 int i, count = 0;
2189 size_t annotsize = sizeof (*page->annots);
2190 fz_annot *annot;
2192 if (state.gen != page->agen) {
2193 dropannots (page);
2194 page->agen = state.gen;
2196 if (page->annots) return;
2198 for (annot = fz_first_annot (state.ctx, page->fzpage);
2199 annot;
2200 annot = fz_next_annot (state.ctx, annot)) {
2201 count++;
2204 if (count > 0) {
2205 page->annotcount = count;
2206 page->annots = calloc (count, annotsize);
2207 if (!page->annots) {
2208 err (1, "calloc annots %d", count);
2211 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2212 annot;
2213 annot = fz_next_annot (state.ctx, annot), i++) {
2214 fz_rect rect;
2216 fz_bound_annot (state.ctx, annot, &rect);
2217 page->annots[i].annot = annot;
2218 fz_round_rect (&page->annots[i].bbox, &rect);
2223 static void dropslinks (struct page *page)
2225 if (page->slinks) {
2226 free (page->slinks);
2227 page->slinks = NULL;
2228 page->slinkcount = 0;
2230 if (page->links) {
2231 fz_drop_link (state.ctx, page->links);
2232 page->links = NULL;
2236 static void ensureslinks (struct page *page)
2238 fz_matrix ctm;
2239 int i, count;
2240 size_t slinksize = sizeof (*page->slinks);
2241 fz_link *link;
2243 ensureannots (page);
2244 if (state.gen != page->sgen) {
2245 dropslinks (page);
2246 page->sgen = state.gen;
2248 if (page->slinks) return;
2250 ensurelinks (page);
2251 ctm = pagectm (page);
2253 count = page->annotcount;
2254 for (link = page->links; link; link = link->next) {
2255 count++;
2257 if (count > 0) {
2258 int j;
2260 page->slinkcount = count;
2261 page->slinks = calloc (count, slinksize);
2262 if (!page->slinks) {
2263 err (1, "calloc slinks %d", count);
2266 for (i = 0, link = page->links; link; ++i, link = link->next) {
2267 fz_rect rect;
2269 rect = link->rect;
2270 fz_transform_rect (&rect, &ctm);
2271 page->slinks[i].tag = SLINK;
2272 page->slinks[i].u.link = link;
2273 fz_round_rect (&page->slinks[i].bbox, &rect);
2275 for (j = 0; j < page->annotcount; ++j, ++i) {
2276 fz_rect rect;
2277 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2278 fz_transform_rect (&rect, &ctm);
2279 fz_round_rect (&page->slinks[i].bbox, &rect);
2281 page->slinks[i].tag = SANNOT;
2282 page->slinks[i].u.annot = page->annots[j].annot;
2284 qsort (page->slinks, count, slinksize, compareslinks);
2288 #pragma GCC diagnostic push
2289 #pragma GCC diagnostic ignored "-Wconversion"
2290 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2291 static void fmt_linkn (char *s, unsigned int u)
2293 unsigned int len; unsigned int q;
2294 unsigned int zma = 'z' - 'a' + 1;
2295 len = 1; q = u;
2296 while (q > zma - 1) { ++len; q /= zma; }
2297 if (s) {
2298 s += len;
2299 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2300 /* handles u == 0 */
2302 s[len] = 0;
2304 #pragma GCC diagnostic pop
2306 static void highlightslinks (struct page *page, int xoff, int yoff,
2307 int noff, char *targ, mlsize_t tlen, int hfsize)
2309 char buf[40];
2310 struct slink *slink;
2311 float x0, y0, x1, y1, w;
2313 ensureslinks (page);
2314 glColor3ub (0xc3, 0xb0, 0x91);
2315 for (int i = 0; i < page->slinkcount; ++i) {
2316 fmt_linkn (buf, i + noff);
2317 if (!tlen || !strncmp (targ, buf, tlen)) {
2318 slink = &page->slinks[i];
2320 x0 = slink->bbox.x0 + xoff - 5;
2321 y1 = slink->bbox.y0 + yoff - 5;
2322 y0 = y1 + 10 + hfsize;
2323 w = measure_string (state.face, hfsize, buf);
2324 x1 = x0 + w + 10;
2325 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2329 glEnable (GL_BLEND);
2330 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2331 glEnable (GL_TEXTURE_2D);
2332 glColor3ub (0, 0, 0);
2333 for (int i = 0; i < page->slinkcount; ++i) {
2334 fmt_linkn (buf, i + noff);
2335 if (!tlen || !strncmp (targ, buf, tlen)) {
2336 slink = &page->slinks[i];
2338 x0 = slink->bbox.x0 + xoff;
2339 y0 = slink->bbox.y0 + yoff + hfsize;
2340 draw_string (state.face, hfsize, x0, y0, buf);
2343 glDisable (GL_TEXTURE_2D);
2344 glDisable (GL_BLEND);
2347 static void uploadslice (struct tile *tile, struct slice *slice)
2349 int offset;
2350 struct slice *slice1;
2351 unsigned char *texdata;
2353 offset = 0;
2354 for (slice1 = tile->slices; slice != slice1; slice1++) {
2355 offset += slice1->h * tile->w * tile->pixmap->n;
2357 if (slice->texindex != -1 && slice->texindex < state.texcount
2358 && state.texowners[slice->texindex].slice == slice) {
2359 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2361 else {
2362 int subimage = 0;
2363 int texindex = state.texindex++ % state.texcount;
2365 if (state.texowners[texindex].w == tile->w) {
2366 if (state.texowners[texindex].h >= slice->h) {
2367 subimage = 1;
2369 else {
2370 state.texowners[texindex].h = slice->h;
2373 else {
2374 state.texowners[texindex].h = slice->h;
2377 state.texowners[texindex].w = tile->w;
2378 state.texowners[texindex].slice = slice;
2379 slice->texindex = texindex;
2381 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2382 #if TEXT_TYPE == GL_TEXTURE_2D
2383 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2384 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2385 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2386 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2387 #endif
2388 if (tile->pbo) {
2389 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2390 texdata = 0;
2392 else {
2393 texdata = tile->pixmap->samples;
2395 if (subimage) {
2396 glTexSubImage2D (TEXT_TYPE,
2400 tile->w,
2401 slice->h,
2402 state.texform,
2403 state.texty,
2404 texdata+offset
2407 else {
2408 glTexImage2D (TEXT_TYPE,
2410 state.texiform,
2411 tile->w,
2412 slice->h,
2414 state.texform,
2415 state.texty,
2416 texdata+offset
2419 if (tile->pbo) {
2420 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2425 CAMLprim void ml_begintiles (value unit_v)
2427 CAMLparam1 (unit_v);
2428 glEnable (TEXT_TYPE);
2429 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2430 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2431 CAMLreturn0;
2434 CAMLprim void ml_endtiles (value unit_v)
2436 CAMLparam1 (unit_v);
2437 glDisable (TEXT_TYPE);
2438 CAMLreturn0;
2441 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2443 CAMLparam2 (args_v, ptr_v);
2444 int dispx = Int_val (Field (args_v, 0));
2445 int dispy = Int_val (Field (args_v, 1));
2446 int dispw = Int_val (Field (args_v, 2));
2447 int disph = Int_val (Field (args_v, 3));
2448 int tilex = Int_val (Field (args_v, 4));
2449 int tiley = Int_val (Field (args_v, 5));
2450 char *s = String_val (ptr_v);
2451 struct tile *tile = parse_pointer (__func__, s);
2452 int slicey, firstslice;
2453 struct slice *slice;
2454 GLfloat *texcoords = state.texcoords;
2455 GLfloat *vertices = state.vertices;
2457 firstslice = tiley / tile->sliceheight;
2458 slice = &tile->slices[firstslice];
2459 slicey = tiley % tile->sliceheight;
2461 while (disph > 0) {
2462 int dh;
2464 dh = slice->h - slicey;
2465 dh = fz_mini (disph, dh);
2466 uploadslice (tile, slice);
2468 texcoords[0] = tilex; texcoords[1] = slicey;
2469 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2470 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2471 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2473 vertices[0] = dispx; vertices[1] = dispy;
2474 vertices[2] = dispx+dispw; vertices[3] = dispy;
2475 vertices[4] = dispx; vertices[5] = dispy+dh;
2476 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2478 #if TEXT_TYPE == GL_TEXTURE_2D
2479 for (int i = 0; i < 8; ++i) {
2480 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2482 #endif
2484 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2485 dispy += dh;
2486 disph -= dh;
2487 slice++;
2488 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2489 slicey = 0;
2491 CAMLreturn0;
2494 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2496 fz_matrix ctm, tm, pm;
2497 fz_point p1, p2, p3, p4;
2498 GLfloat *vertices = state.vertices;
2499 double *v = (double *) rects_v;
2501 xoff -= state.pagedims[page->pdimno].bounds.x0;
2502 yoff -= state.pagedims[page->pdimno].bounds.y0;
2503 fz_translate (&tm, xoff, yoff);
2504 pm = pagectm (page);
2505 fz_concat (&ctm, &pm, &tm);
2507 glEnable (GL_BLEND);
2508 glVertexPointer (2, GL_FLOAT, 0, vertices);
2510 glColor4dv (v);
2511 p1.x = (float) v[4];
2512 p1.y = (float) v[5];
2514 p2.x = (float) v[6];
2515 p2.y = (float) v[5];
2517 p3.x = (float) v[6];
2518 p3.y = (float) v[7];
2520 p4.x = (float) v[4];
2521 p4.y = (float) v[7];
2522 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2523 glDisable (GL_BLEND);
2526 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2527 value xoff_v, value yoff_v,
2528 value li_v)
2530 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2531 int xoff = Int_val (xoff_v);
2532 int yoff = Int_val (yoff_v);
2533 int noff = Int_val (Field (li_v, 0));
2534 char *targ = String_val (Field (li_v, 1));
2535 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2536 int hfsize = Int_val (Field (li_v, 2));
2537 char *s = String_val (ptr_v);
2538 int hlmask = Int_val (hlinks_v);
2539 struct page *page = parse_pointer (__func__, s);
2541 if (!page->fzpage) {
2542 /* deal with loadpage failed pages */
2543 goto done;
2546 if (trylock (__func__)) {
2547 noff = -1;
2548 goto done;
2551 ensureannots (page);
2552 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2553 if (hlmask & 2) {
2554 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2555 noff = page->slinkcount;
2557 if (page->tgen == state.gen) {
2558 showsel (page, xoff, yoff);
2560 unlock (__func__);
2562 done:
2563 CAMLreturn (Val_int (noff));
2566 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2567 value rects_v)
2569 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2570 int xoff = Int_val (xoff_v);
2571 int yoff = Int_val (yoff_v);
2572 char *s = String_val (ptr_v);
2573 struct page *page = parse_pointer (__func__, s);
2575 drawprect (page, xoff, yoff, rects_v);
2576 CAMLreturn0;
2579 static struct annot *getannot (struct page *page, int x, int y)
2581 fz_point p;
2582 fz_matrix ctm;
2583 const fz_matrix *tctm;
2584 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2586 if (!page->annots) return NULL;
2588 if (pdf) {
2589 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2590 tctm = &state.pagedims[page->pdimno].tctm;
2592 else {
2593 tctm = &fz_identity;
2596 p.x = x;
2597 p.y = y;
2599 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2600 fz_invert_matrix (&ctm, &ctm);
2601 fz_transform_point (&p, &ctm);
2603 if (pdf) {
2604 for (int i = 0; i < page->annotcount; ++i) {
2605 struct annot *a = &page->annots[i];
2606 fz_rect rect;
2608 fz_bound_annot (state.ctx, a->annot, &rect);
2609 if (p.x >= rect.x0 && p.x <= rect.x1) {
2610 if (p.y >= rect.y0 && p.y <= rect.y1)
2611 return a;
2615 return NULL;
2618 static fz_link *getlink (struct page *page, int x, int y)
2620 fz_point p;
2621 fz_matrix ctm;
2622 fz_link *link;
2624 ensureslinks (page);
2626 p.x = x;
2627 p.y = y;
2629 ctm = pagectm (page);
2630 fz_invert_matrix (&ctm, &ctm);
2631 fz_transform_point (&p, &ctm);
2633 for (link = page->links; link; link = link->next) {
2634 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2635 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2636 return link;
2640 return NULL;
2643 static void ensuretext (struct page *page)
2645 if (state.gen != page->tgen) {
2646 droptext (page);
2647 page->tgen = state.gen;
2649 if (!page->text) {
2650 fz_matrix ctm;
2651 fz_device *tdev;
2653 page->text = fz_new_stext_page (state.ctx,
2654 &state.pagedims[page->pdimno].mediabox);
2655 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2656 ctm = pagectm (page);
2657 fz_run_display_list (state.ctx, page->dlist,
2658 tdev, &ctm, &fz_infinite_rect, NULL);
2659 fz_close_device (state.ctx, tdev);
2660 fz_drop_device (state.ctx, tdev);
2664 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2666 CAMLparam2 (start_page_v, dir_v);
2667 CAMLlocal1 (ret_v);
2668 int i, dir = Int_val (dir_v);
2669 int start_page = Int_val (start_page_v);
2670 int end_page = dir > 0 ? state.pagecount : -1;
2671 pdf_document *pdf;
2673 fz_var (end_page);
2674 ret_v = Val_int (0);
2675 lock (__func__);
2676 pdf = pdf_specifics (state.ctx, state.doc);
2677 for (i = start_page + dir; i != end_page; i += dir) {
2678 int found;
2680 fz_var (found);
2681 if (pdf) {
2682 pdf_page *page = NULL;
2684 fz_var (page);
2685 fz_try (state.ctx) {
2686 page = pdf_load_page (state.ctx, pdf, i);
2687 found = !!page->links || !!page->annots;
2689 fz_catch (state.ctx) {
2690 found = 0;
2692 if (page) {
2693 fz_drop_page (state.ctx, &page->super);
2696 else {
2697 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2698 fz_link *link = fz_load_links (state.ctx, page);
2699 found = !!link;
2700 fz_drop_link (state.ctx, link);
2701 fz_drop_page (state.ctx, page);
2704 if (found) {
2705 ret_v = caml_alloc_small (1, 1);
2706 Field (ret_v, 0) = Val_int (i);
2707 goto unlock;
2710 unlock:
2711 unlock (__func__);
2712 CAMLreturn (ret_v);
2715 enum { dir_first, dir_last };
2716 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2718 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2720 CAMLparam2 (ptr_v, dir_v);
2721 CAMLlocal2 (ret_v, pos_v);
2722 struct page *page;
2723 int dirtag, i, slinkindex;
2724 struct slink *found = NULL ,*slink;
2725 char *s = String_val (ptr_v);
2727 page = parse_pointer (__func__, s);
2728 ret_v = Val_int (0);
2729 lock (__func__);
2730 ensureslinks (page);
2732 if (Is_block (dir_v)) {
2733 dirtag = Tag_val (dir_v);
2734 switch (dirtag) {
2735 case dir_first_visible:
2737 int x0, y0, dir, first_index, last_index;
2739 pos_v = Field (dir_v, 0);
2740 x0 = Int_val (Field (pos_v, 0));
2741 y0 = Int_val (Field (pos_v, 1));
2742 dir = Int_val (Field (pos_v, 2));
2744 if (dir >= 0) {
2745 dir = 1;
2746 first_index = 0;
2747 last_index = page->slinkcount;
2749 else {
2750 first_index = page->slinkcount - 1;
2751 last_index = -1;
2754 for (i = first_index; i != last_index; i += dir) {
2755 slink = &page->slinks[i];
2756 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2757 found = slink;
2758 break;
2762 break;
2764 case dir_left:
2765 slinkindex = Int_val (Field (dir_v, 0));
2766 found = &page->slinks[slinkindex];
2767 for (i = slinkindex - 1; i >= 0; --i) {
2768 slink = &page->slinks[i];
2769 if (slink->bbox.x0 < found->bbox.x0) {
2770 found = slink;
2771 break;
2774 break;
2776 case dir_right:
2777 slinkindex = Int_val (Field (dir_v, 0));
2778 found = &page->slinks[slinkindex];
2779 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2780 slink = &page->slinks[i];
2781 if (slink->bbox.x0 > found->bbox.x0) {
2782 found = slink;
2783 break;
2786 break;
2788 case dir_down:
2789 slinkindex = Int_val (Field (dir_v, 0));
2790 found = &page->slinks[slinkindex];
2791 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2792 slink = &page->slinks[i];
2793 if (slink->bbox.y0 >= found->bbox.y0) {
2794 found = slink;
2795 break;
2798 break;
2800 case dir_up:
2801 slinkindex = Int_val (Field (dir_v, 0));
2802 found = &page->slinks[slinkindex];
2803 for (i = slinkindex - 1; i >= 0; --i) {
2804 slink = &page->slinks[i];
2805 if (slink->bbox.y0 <= found->bbox.y0) {
2806 found = slink;
2807 break;
2810 break;
2813 else {
2814 dirtag = Int_val (dir_v);
2815 switch (dirtag) {
2816 case dir_first:
2817 found = page->slinks;
2818 break;
2820 case dir_last:
2821 if (page->slinks) {
2822 found = page->slinks + (page->slinkcount - 1);
2824 break;
2827 if (found) {
2828 ret_v = caml_alloc_small (2, 1);
2829 Field (ret_v, 0) = Val_int (found - page->slinks);
2832 unlock (__func__);
2833 CAMLreturn (ret_v);
2836 enum { uuri, utext, uannot };
2838 CAMLprim value ml_getlink (value ptr_v, value n_v)
2840 CAMLparam2 (ptr_v, n_v);
2841 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2842 fz_link *link;
2843 struct page *page;
2844 char *s = String_val (ptr_v);
2845 struct slink *slink;
2847 ret_v = Val_int (0);
2848 page = parse_pointer (__func__, s);
2850 lock (__func__);
2851 ensureslinks (page);
2852 slink = &page->slinks[Int_val (n_v)];
2853 if (slink->tag == SLINK) {
2854 link = slink->u.link;
2855 str_v = caml_copy_string (link->uri);
2856 ret_v = caml_alloc_small (1, uuri);
2857 Field (ret_v, 0) = str_v;
2859 else {
2860 ret_v = caml_alloc_small (1, uannot);
2861 tup_v = caml_alloc_tuple (2);
2862 Field (ret_v, 0) = tup_v;
2863 Field (tup_v, 0) = ptr_v;
2864 Field (tup_v, 1) = n_v;
2866 unlock (__func__);
2868 CAMLreturn (ret_v);
2871 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2873 CAMLparam2 (ptr_v, n_v);
2874 CAMLlocal1 (ret_v);
2875 pdf_document *pdf;
2876 char *contents = NULL;
2878 lock (__func__);
2879 pdf = pdf_specifics (state.ctx, state.doc);
2880 if (pdf) {
2881 char *s = String_val (ptr_v);
2882 struct page *page;
2883 struct slink *slink;
2885 page = parse_pointer (__func__, s);
2886 slink = &page->slinks[Int_val (n_v)];
2887 contents = pdf_copy_annot_contents (state.ctx,
2888 (pdf_annot *) slink->u.annot);
2890 unlock (__func__);
2891 if (contents) {
2892 ret_v = caml_copy_string (contents);
2893 fz_free (state.ctx, contents);
2895 else {
2896 ret_v = caml_copy_string ("");
2898 CAMLreturn (ret_v);
2901 CAMLprim value ml_getlinkcount (value ptr_v)
2903 CAMLparam1 (ptr_v);
2904 struct page *page;
2905 char *s = String_val (ptr_v);
2907 page = parse_pointer (__func__, s);
2908 CAMLreturn (Val_int (page->slinkcount));
2911 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2913 CAMLparam2 (ptr_v, n_v);
2914 CAMLlocal1 (ret_v);
2915 struct page *page;
2916 struct slink *slink;
2917 char *s = String_val (ptr_v);
2919 page = parse_pointer (__func__, s);
2920 ret_v = caml_alloc_tuple (4);
2921 lock (__func__);
2922 ensureslinks (page);
2924 slink = &page->slinks[Int_val (n_v)];
2925 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2926 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2927 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2928 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2929 unlock (__func__);
2930 CAMLreturn (ret_v);
2933 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2935 CAMLparam3 (ptr_v, x_v, y_v);
2936 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2937 fz_link *link;
2938 struct annot *annot;
2939 struct page *page;
2940 char *ptr = String_val (ptr_v);
2941 int x = Int_val (x_v), y = Int_val (y_v);
2942 struct pagedim *pdim;
2944 ret_v = Val_int (0);
2945 if (trylock (__func__)) {
2946 goto done;
2949 page = parse_pointer (__func__, ptr);
2950 pdim = &state.pagedims[page->pdimno];
2951 x += pdim->bounds.x0;
2952 y += pdim->bounds.y0;
2955 annot = getannot (page, x, y);
2956 if (annot) {
2957 int i, n = -1;
2959 ensureslinks (page);
2960 for (i = 0; i < page->slinkcount; ++i) {
2961 if (page->slinks[i].tag == SANNOT
2962 && page->slinks[i].u.annot == annot->annot) {
2963 n = i;
2964 break;
2967 ret_v = caml_alloc_small (1, uannot);
2968 tup_v = caml_alloc_tuple (2);
2969 Field (ret_v, 0) = tup_v;
2970 Field (tup_v, 0) = ptr_v;
2971 Field (tup_v, 1) = Val_int (n);
2972 goto unlock;
2976 link = getlink (page, x, y);
2977 if (link) {
2978 str_v = caml_copy_string (link->uri);
2979 ret_v = caml_alloc_small (1, uuri);
2980 Field (ret_v, 0) = str_v;
2982 else {
2983 fz_rect *b;
2984 fz_stext_block *block;
2986 ensuretext (page);
2988 for (block = page->text->first_block; block; block = block->next) {
2989 fz_stext_line *line;
2991 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2992 b = &block->bbox;
2993 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2994 continue;
2996 for (line = block->u.t.first_line; line; line = line->next) {
2997 fz_stext_char *ch;
2999 b = &line->bbox;
3000 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3001 continue;
3003 for (ch = line->first_char; ch; ch = ch->next) {
3004 b = &ch->bbox;
3006 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3007 const char *n2 = fz_font_name (state.ctx, ch->font);
3008 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3009 ch->font);
3011 if (!n2) n2 = "<unknown font>";
3013 if (face && face->family_name) {
3014 char *s;
3015 char *n1 = face->family_name;
3016 size_t l1 = strlen (n1);
3017 size_t l2 = strlen (n2);
3019 if (l1 != l2 || memcmp (n1, n2, l1)) {
3020 s = malloc (l1 + l2 + 2);
3021 if (s) {
3022 memcpy (s, n2, l2);
3023 s[l2] = '=';
3024 memcpy (s + l2 + 1, n1, l1 + 1);
3025 str_v = caml_copy_string (s);
3026 free (s);
3030 if (str_v == Val_unit) {
3031 str_v = caml_copy_string (n2);
3033 ret_v = caml_alloc_small (1, utext);
3034 Field (ret_v, 0) = str_v;
3035 goto unlock;
3041 unlock:
3042 unlock (__func__);
3044 done:
3045 CAMLreturn (ret_v);
3048 enum { mark_page, mark_block, mark_line, mark_word };
3050 static int uninteresting (int c)
3052 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3053 || ispunct (c);
3056 CAMLprim void ml_clearmark (value ptr_v)
3058 CAMLparam1 (ptr_v);
3059 char *s = String_val (ptr_v);
3060 struct page *page;
3062 if (trylock (__func__)) {
3063 goto done;
3066 page = parse_pointer (__func__, s);
3067 page->fmark.ch = NULL;
3068 page->lmark.ch = NULL;
3070 unlock (__func__);
3071 done:
3072 CAMLreturn0;
3075 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3077 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3078 CAMLlocal1 (ret_v);
3079 fz_rect *b;
3080 struct page *page;
3081 fz_stext_line *line;
3082 fz_stext_block *block;
3083 struct pagedim *pdim;
3084 int mark = Int_val (mark_v);
3085 char *s = String_val (ptr_v);
3086 int x = Int_val (x_v), y = Int_val (y_v);
3088 ret_v = Val_bool (0);
3089 if (trylock (__func__)) {
3090 goto done;
3093 page = parse_pointer (__func__, s);
3094 pdim = &state.pagedims[page->pdimno];
3096 ensuretext (page);
3098 if (mark == mark_page) {
3099 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3100 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3101 ret_v = Val_bool (1);
3102 goto unlock;
3105 x += pdim->bounds.x0;
3106 y += pdim->bounds.y0;
3108 for (block = page->text->first_block; block; block = block->next) {
3109 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3110 b = &block->bbox;
3111 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3112 continue;
3114 if (mark == mark_block) {
3115 page->fmark.ch = block->u.t.first_line->first_char;
3116 page->lmark.ch = block->u.t.last_line->last_char;
3117 ret_v = Val_bool (1);
3118 goto unlock;
3121 for (line = block->u.t.first_line; line; line = line->next) {
3122 fz_stext_char *ch;
3124 b = &line->bbox;
3125 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3126 continue;
3128 if (mark == mark_line) {
3129 page->fmark.ch = line->first_char;
3130 page->lmark.ch = line->last_char;
3131 ret_v = Val_bool (1);
3132 goto unlock;
3135 for (ch = line->first_char; ch; ch = ch->next) {
3136 fz_stext_char *ch2, *first = NULL, *last = NULL;
3137 b = &ch->bbox;
3138 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3139 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3140 if (uninteresting (ch2->c)) first = NULL;
3141 else if (!first) first = ch2;
3143 for (ch2 = ch; ch2; ch2 = ch2->next) {
3144 if (uninteresting (ch2->c)) break;
3145 last = ch2;
3148 page->fmark.ch = first;
3149 page->lmark.ch = last;
3150 ret_v = Val_bool (1);
3151 goto unlock;
3156 unlock:
3157 if (!Bool_val (ret_v)) {
3158 page->fmark.ch = NULL;
3159 page->lmark.ch = NULL;
3161 unlock (__func__);
3163 done:
3164 CAMLreturn (ret_v);
3167 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3169 CAMLparam3 (ptr_v, x_v, y_v);
3170 CAMLlocal2 (ret_v, res_v);
3171 fz_rect *b = NULL;
3172 struct page *page;
3173 struct pagedim *pdim;
3174 fz_stext_block *block;
3175 char *s = String_val (ptr_v);
3176 int x = Int_val (x_v), y = Int_val (y_v);
3178 ret_v = Val_int (0);
3179 if (trylock (__func__)) {
3180 goto done;
3183 page = parse_pointer (__func__, s);
3184 pdim = &state.pagedims[page->pdimno];
3185 x += pdim->bounds.x0;
3186 y += pdim->bounds.y0;
3188 ensuretext (page);
3190 for (block = page->text->first_block; block; block = block->next) {
3191 switch (block->type) {
3192 case FZ_STEXT_BLOCK_TEXT:
3193 b = &block->bbox;
3194 break;
3196 case FZ_STEXT_BLOCK_IMAGE:
3197 b = &block->bbox;
3198 break;
3200 default:
3201 continue;
3204 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3205 break;
3206 b = NULL;
3208 if (b) {
3209 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3210 ret_v = caml_alloc_small (1, 1);
3211 Store_double_field (res_v, 0, (double) b->x0);
3212 Store_double_field (res_v, 1, (double) b->x1);
3213 Store_double_field (res_v, 2, (double) b->y0);
3214 Store_double_field (res_v, 3, (double) b->y1);
3215 Field (ret_v, 0) = res_v;
3217 unlock (__func__);
3219 done:
3220 CAMLreturn (ret_v);
3223 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3225 CAMLparam2 (ptr_v, rect_v);
3226 fz_rect b;
3227 struct page *page;
3228 struct pagedim *pdim;
3229 char *s = String_val (ptr_v);
3230 int x0, x1, y0, y1;
3231 fz_stext_char *ch;
3232 fz_stext_line *line;
3233 fz_stext_block *block;
3234 fz_stext_char *fc, *lc;
3236 if (trylock (__func__)) {
3237 goto done;
3240 page = parse_pointer (__func__, s);
3241 ensuretext (page);
3243 pdim = &state.pagedims[page->pdimno];
3244 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3245 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3246 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3247 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3249 if (y0 > y1) {
3250 int t = y0;
3251 y0 = y1;
3252 y1 = t;
3253 x0 = x1;
3254 x1 = t;
3257 fc = page->fmark.ch;
3258 lc = page->lmark.ch;
3260 for (block = page->text->first_block; block; block = block->next) {
3261 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3262 for (line = block->u.t.first_line; line; line = line->next) {
3263 for (ch = line->first_char; ch; ch = ch->next) {
3264 b = ch->bbox;
3265 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3266 fc = ch;
3268 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3269 lc = ch;
3274 if (x1 < x0 && fc == lc) {
3275 fz_stext_char *t;
3277 t = fc;
3278 fc = lc;
3279 lc = t;
3282 page->fmark.ch = fc;
3283 page->lmark.ch = lc;
3285 unlock (__func__);
3287 done:
3288 CAMLreturn0;
3291 static int pipechar (FILE *f, fz_stext_char *ch)
3293 char buf[4];
3294 int len;
3295 size_t ret;
3297 len = fz_runetochar (buf, ch->c);
3298 ret = fwrite (buf, len, 1, f);
3299 if (ret != 1) {
3300 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3301 len, ret, errno, strerror (errno));
3302 return -1;
3304 return 0;
3307 CAMLprim value ml_spawn (value command_v, value fds_v)
3309 CAMLparam2 (command_v, fds_v);
3310 CAMLlocal2 (l_v, tup_v);
3311 int ret, ret1;
3312 pid_t pid = (pid_t) -1;
3313 char *msg = NULL;
3314 value earg_v = Nothing;
3315 posix_spawnattr_t attr;
3316 posix_spawn_file_actions_t fa;
3317 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3319 argv[2] = String_val (command_v);
3321 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3322 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3325 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3326 msg = "posix_spawnattr_init";
3327 goto fail1;
3330 #ifdef POSIX_SPAWN_USEVFORK
3331 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3332 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3333 goto fail;
3335 #endif
3337 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3338 int fd1, fd2;
3340 tup_v = Field (l_v, 0);
3341 fd1 = Int_val (Field (tup_v, 0));
3342 fd2 = Int_val (Field (tup_v, 1));
3343 if (fd2 < 0) {
3344 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3345 msg = "posix_spawn_file_actions_addclose";
3346 earg_v = tup_v;
3347 goto fail;
3350 else {
3351 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3352 msg = "posix_spawn_file_actions_adddup2";
3353 earg_v = tup_v;
3354 goto fail;
3359 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3360 msg = "posix_spawn";
3361 goto fail;
3364 fail:
3365 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3366 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3369 fail1:
3370 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3371 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3372 ret1, strerror (ret1));
3375 if (msg)
3376 unix_error (ret, msg, earg_v);
3378 CAMLreturn (Val_int (pid));
3381 CAMLprim value ml_hassel (value ptr_v)
3383 CAMLparam1 (ptr_v);
3384 CAMLlocal1 (ret_v);
3385 struct page *page;
3386 char *s = String_val (ptr_v);
3388 ret_v = Val_bool (0);
3389 if (trylock (__func__)) {
3390 goto done;
3393 page = parse_pointer (__func__, s);
3394 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3395 unlock (__func__);
3396 done:
3397 CAMLreturn (ret_v);
3400 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3402 CAMLparam2 (fd_v, ptr_v);
3403 FILE *f;
3404 int seen = 0;
3405 struct page *page;
3406 fz_stext_line *line;
3407 fz_stext_block *block;
3408 int fd = Int_val (fd_v);
3409 char *s = String_val (ptr_v);
3411 if (trylock (__func__)) {
3412 goto done;
3415 page = parse_pointer (__func__, s);
3417 if (!page->fmark.ch || !page->lmark.ch) {
3418 printd ("emsg nothing to copy on page %d", page->pageno);
3419 goto unlock;
3422 f = fdopen (fd, "w");
3423 if (!f) {
3424 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3425 fd, errno, strerror (errno));
3426 f = stdout;
3429 for (block = page->text->first_block; block; block = block->next) {
3430 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3431 for (line = block->u.t.first_line; line; line = line->next) {
3432 fz_stext_char *ch;
3433 for (ch = line->first_char; ch; ch = ch->next) {
3434 if (seen || ch == page->fmark.ch) {
3435 do {
3436 pipechar (f, ch);
3437 if (ch == page->lmark.ch) goto close;
3438 } while ((ch = ch->next));
3439 seen = 1;
3440 break;
3443 if (seen) fputc ('\n', f);
3446 close:
3447 if (f != stdout) {
3448 int ret = fclose (f);
3449 fd = -1;
3450 if (ret == -1) {
3451 if (errno != ECHILD) {
3452 printd ("emsg failed to close sel pipe: %d:%s",
3453 errno, strerror (errno));
3457 unlock:
3458 unlock (__func__);
3460 done:
3461 if (fd >= 0) {
3462 if (close (fd)) {
3463 printd ("emsg failed to close sel pipe: %d:%s",
3464 errno, strerror (errno));
3467 CAMLreturn0;
3470 CAMLprim value ml_getpdimrect (value pagedimno_v)
3472 CAMLparam1 (pagedimno_v);
3473 CAMLlocal1 (ret_v);
3474 int pagedimno = Int_val (pagedimno_v);
3475 fz_rect box;
3477 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3478 if (trylock (__func__)) {
3479 box = fz_empty_rect;
3481 else {
3482 box = state.pagedims[pagedimno].mediabox;
3483 unlock (__func__);
3486 Store_double_field (ret_v, 0, (double) box.x0);
3487 Store_double_field (ret_v, 1, (double) box.x1);
3488 Store_double_field (ret_v, 2, (double) box.y0);
3489 Store_double_field (ret_v, 3, (double) box.y1);
3491 CAMLreturn (ret_v);
3494 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3495 value dw_v, value cols_v)
3497 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3498 CAMLlocal1 (ret_v);
3499 int i;
3500 float zoom = -1.;
3501 float maxh = 0.0;
3502 struct pagedim *p;
3503 float winw = Int_val (winw_v);
3504 float winh = Int_val (winh_v);
3505 float dw = Int_val (dw_v);
3506 float cols = Int_val (cols_v);
3507 float pw = 1.0, ph = 1.0;
3509 if (trylock (__func__)) {
3510 goto done;
3513 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3514 float w = p->pagebox.x1 / cols;
3515 float h = p->pagebox.y1;
3516 if (h > maxh) {
3517 maxh = h;
3518 ph = h;
3519 if (state.fitmodel != FitProportional) pw = w;
3521 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3524 zoom = (((winh / ph) * pw) + dw) / winw;
3525 unlock (__func__);
3526 done:
3527 ret_v = caml_copy_double ((double) zoom);
3528 CAMLreturn (ret_v);
3531 CAMLprim value ml_getmaxw (value unit_v)
3533 CAMLparam1 (unit_v);
3534 CAMLlocal1 (ret_v);
3535 int i;
3536 float maxw = -1.;
3537 struct pagedim *p;
3539 if (trylock (__func__)) {
3540 goto done;
3543 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3544 float w = p->pagebox.x1;
3545 maxw = fz_max (maxw, w);
3548 unlock (__func__);
3549 done:
3550 ret_v = caml_copy_double ((double) maxw);
3551 CAMLreturn (ret_v);
3554 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3556 CAMLparam4 (pt_v, x_v, y_v, string_v);
3557 CAMLlocal1 (ret_v);
3558 int pt = Int_val(pt_v);
3559 int x = Int_val (x_v);
3560 int y = Int_val (y_v);
3561 double w;
3563 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3564 ret_v = caml_copy_double (w);
3565 CAMLreturn (ret_v);
3568 CAMLprim value ml_measure_string (value pt_v, value string_v)
3570 CAMLparam2 (pt_v, string_v);
3571 CAMLlocal1 (ret_v);
3572 int pt = Int_val (pt_v);
3573 double w;
3575 w = (double) measure_string (state.face, pt, String_val (string_v));
3576 ret_v = caml_copy_double (w);
3577 CAMLreturn (ret_v);
3580 CAMLprim value ml_getpagebox (value opaque_v)
3582 CAMLparam1 (opaque_v);
3583 CAMLlocal1 (ret_v);
3584 fz_rect rect;
3585 fz_irect bbox;
3586 fz_matrix ctm;
3587 fz_device *dev;
3588 char *s = String_val (opaque_v);
3589 struct page *page = parse_pointer (__func__, s);
3591 ret_v = caml_alloc_tuple (4);
3592 dev = fz_new_bbox_device (state.ctx, &rect);
3594 ctm = pagectm (page);
3595 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3597 fz_close_device (state.ctx, dev);
3598 fz_drop_device (state.ctx, dev);
3599 fz_round_rect (&bbox, &rect);
3600 Field (ret_v, 0) = Val_int (bbox.x0);
3601 Field (ret_v, 1) = Val_int (bbox.y0);
3602 Field (ret_v, 2) = Val_int (bbox.x1);
3603 Field (ret_v, 3) = Val_int (bbox.y1);
3605 CAMLreturn (ret_v);
3608 CAMLprim void ml_setaalevel (value level_v)
3610 CAMLparam1 (level_v);
3612 state.aalevel = Int_val (level_v);
3613 CAMLreturn0;
3616 #ifndef __COCOA__
3617 #pragma GCC diagnostic push
3618 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3619 #include <X11/Xlib.h>
3620 #include <X11/cursorfont.h>
3621 #pragma GCC diagnostic pop
3623 #ifdef USE_EGL
3624 #include <EGL/egl.h>
3625 #else
3626 #include <GL/glx.h>
3627 #endif
3629 static const int shapes[] = {
3630 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3633 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3635 static struct {
3636 Window wid;
3637 Display *dpy;
3638 #ifdef USE_EGL
3639 EGLContext ctx;
3640 EGLConfig conf;
3641 EGLSurface win;
3642 EGLDisplay *edpy;
3643 #else
3644 GLXContext ctx;
3645 #endif
3646 XVisualInfo *visual;
3647 Cursor curs[CURS_COUNT];
3648 } glx;
3651 static void initcurs (void)
3653 for (size_t n = 0; n < CURS_COUNT; ++n) {
3654 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3658 #ifdef USE_EGL
3659 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3661 CAMLparam3 (display_v, wid_v, screen_v);
3662 int major, minor;
3663 int num_conf;
3664 EGLint visid;
3665 EGLint attribs[] = {
3666 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3667 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3668 EGL_NONE
3670 EGLConfig conf;
3672 glx.dpy = XOpenDisplay (String_val (display_v));
3673 if (!glx.dpy) {
3674 caml_failwith ("XOpenDisplay");
3677 eglBindAPI (EGL_OPENGL_API);
3679 glx.edpy = eglGetDisplay (glx.dpy);
3680 if (glx.edpy == EGL_NO_DISPLAY) {
3681 caml_failwith ("eglGetDisplay");
3684 if (!eglInitialize (glx.edpy, &major, &minor)) {
3685 caml_failwith ("eglInitialize");
3688 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3689 !num_conf) {
3690 caml_failwith ("eglChooseConfig");
3693 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3694 caml_failwith ("eglGetConfigAttrib");
3697 glx.conf = conf;
3698 initcurs ();
3700 glx.wid = Int_val (wid_v);
3701 CAMLreturn (Val_int (visid));
3704 CAMLprim void ml_glxcompleteinit (value unit_v)
3706 CAMLparam1 (unit_v);
3708 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3709 if (!glx.ctx) {
3710 caml_failwith ("eglCreateContext");
3713 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3714 glx.wid, NULL);
3715 if (glx.win == EGL_NO_SURFACE) {
3716 caml_failwith ("eglCreateWindowSurface");
3719 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3720 glx.ctx = NULL;
3721 caml_failwith ("eglMakeCurrent");
3723 CAMLreturn0;
3725 #else
3726 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3728 CAMLparam3 (display_v, wid_v, screen_v);
3730 glx.dpy = XOpenDisplay (String_val (display_v));
3731 if (!glx.dpy) {
3732 caml_failwith ("XOpenDisplay");
3735 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3736 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3737 if (!glx.visual) {
3738 XCloseDisplay (glx.dpy);
3739 caml_failwith ("glXChooseVisual");
3742 initcurs ();
3744 glx.wid = Int_val (wid_v);
3745 CAMLreturn (Val_int (glx.visual->visualid));
3748 CAMLprim void ml_glxcompleteinit (value unit_v)
3750 CAMLparam1 (unit_v);
3752 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3753 if (!glx.ctx) {
3754 caml_failwith ("glXCreateContext");
3757 XFree (glx.visual);
3758 glx.visual = NULL;
3760 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3761 glXDestroyContext (glx.dpy, glx.ctx);
3762 glx.ctx = NULL;
3763 caml_failwith ("glXMakeCurrent");
3765 CAMLreturn0;
3767 #endif
3769 CAMLprim void ml_setcursor (value cursor_v)
3771 CAMLparam1 (cursor_v);
3772 size_t cursn = Int_val (cursor_v);
3774 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3775 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3776 XFlush (glx.dpy);
3777 CAMLreturn0;
3780 CAMLprim void ml_swapb (value unit_v)
3782 CAMLparam1 (unit_v);
3783 #ifdef USE_EGL
3784 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3785 caml_failwith ("eglSwapBuffers");
3787 #else
3788 glXSwapBuffers (glx.dpy, glx.wid);
3789 #endif
3790 CAMLreturn0;
3793 #pragma GCC diagnostic push
3794 #ifdef __clang__
3795 #pragma GCC diagnostic ignored "-Wmissing-variable-declarations"
3796 #endif
3797 #include "keysym2ucs.c"
3798 #pragma GCC diagnostic pop
3800 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3802 CAMLparam1 (keysym_v);
3803 CAMLlocal1 (str_v);
3804 KeySym keysym = Int_val (keysym_v);
3805 Rune rune;
3806 int len;
3807 char buf[5];
3809 rune = (Rune) keysym2ucs (keysym);
3810 len = fz_runetochar (buf, rune);
3811 buf[len] = 0;
3812 str_v = caml_copy_string (buf);
3813 CAMLreturn (str_v);
3815 #else
3816 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3818 CAMLparam1 (keysym_v);
3819 CAMLlocal1 (str_v);
3820 long ucs_v = Long_val (keysym_v);
3821 int len;
3822 char buf[5];
3824 len = fz_runetochar (buf, ucs_v);
3825 buf[len] = 0;
3826 str_v = caml_copy_string (buf);
3827 CAMLreturn (str_v);
3829 #endif
3831 enum { piunknown, pilinux, piosx, pisun, pibsd };
3833 CAMLprim value ml_platform (value unit_v)
3835 CAMLparam1 (unit_v);
3836 CAMLlocal2 (tup_v, arr_v);
3837 int platid = piunknown;
3838 struct utsname buf;
3840 #if defined __linux__
3841 platid = pilinux;
3842 #elif defined __DragonFly__ || defined __FreeBSD__
3843 || defined __OpenBSD__ || defined __NetBSD__
3844 platid = pibsd;
3845 #elif defined __sun__
3846 platid = pisun;
3847 #elif defined __APPLE__
3848 platid = piosx;
3849 #endif
3850 if (uname (&buf)) err (1, "uname");
3852 tup_v = caml_alloc_tuple (2);
3854 char const *sar[] = {
3855 buf.sysname,
3856 buf.release,
3857 buf.version,
3858 buf.machine,
3859 NULL
3861 arr_v = caml_copy_string_array (sar);
3863 Field (tup_v, 0) = Val_int (platid);
3864 Field (tup_v, 1) = arr_v;
3865 CAMLreturn (tup_v);
3868 CAMLprim void ml_cloexec (value fd_v)
3870 CAMLparam1 (fd_v);
3871 int fd = Int_val (fd_v);
3873 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3874 uerror ("fcntl", Nothing);
3876 CAMLreturn0;
3879 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3881 CAMLparam2 (w_v, h_v);
3882 CAMLlocal1 (ret_v);
3883 struct bo *pbo;
3884 int w = Int_val (w_v);
3885 int h = Int_val (h_v);
3886 int cs = Int_val (cs_v);
3888 if (state.bo_usable) {
3889 pbo = calloc (sizeof (*pbo), 1);
3890 if (!pbo) {
3891 err (1, "calloc pbo");
3894 switch (cs) {
3895 case 0:
3896 case 1:
3897 pbo->size = w*h*4;
3898 break;
3899 case 2:
3900 pbo->size = w*h*2;
3901 break;
3902 default:
3903 errx (1, "%s: invalid colorspace %d", __func__, cs);
3906 state.glGenBuffersARB (1, &pbo->id);
3907 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3908 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3909 NULL, GL_STREAM_DRAW);
3910 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3911 GL_READ_WRITE);
3912 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3913 if (!pbo->ptr) {
3914 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3915 state.glDeleteBuffersARB (1, &pbo->id);
3916 free (pbo);
3917 ret_v = caml_copy_string ("0");
3919 else {
3920 int res;
3921 char *s;
3923 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3924 if (res < 0) {
3925 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3927 s = malloc (res+1);
3928 if (!s) {
3929 err (1, "malloc %d bytes failed", res+1);
3931 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3932 if (res < 0) {
3933 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3935 ret_v = caml_copy_string (s);
3936 free (s);
3939 else {
3940 ret_v = caml_copy_string ("0");
3942 CAMLreturn (ret_v);
3945 CAMLprim void ml_freepbo (value s_v)
3947 CAMLparam1 (s_v);
3948 char *s = String_val (s_v);
3949 struct tile *tile = parse_pointer (__func__, s);
3951 if (tile->pbo) {
3952 state.glDeleteBuffersARB (1, &tile->pbo->id);
3953 tile->pbo->id = -1;
3954 tile->pbo->ptr = NULL;
3955 tile->pbo->size = -1;
3957 CAMLreturn0;
3960 CAMLprim void ml_unmappbo (value s_v)
3962 CAMLparam1 (s_v);
3963 char *s = String_val (s_v);
3964 struct tile *tile = parse_pointer (__func__, s);
3966 if (tile->pbo) {
3967 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3968 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3969 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3971 tile->pbo->ptr = NULL;
3972 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3974 CAMLreturn0;
3977 static void setuppbo (void)
3979 #ifdef __COCOA__
3980 static CFBundleRef framework = NULL;
3981 if (framework == NULL)
3982 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3983 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3984 #else
3985 #ifdef USE_EGL
3986 #define GGPA(n) (*(void (**) (void)) &state.n = eglGetProcAddress (#n))
3987 #else
3988 #define GGPA(n) (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
3989 #endif
3990 state.bo_usable = GGPA (glBindBufferARB)
3991 && GGPA (glUnmapBufferARB)
3992 && GGPA (glMapBufferARB)
3993 && GGPA (glBufferDataARB)
3994 && GGPA (glGenBuffersARB)
3995 && GGPA (glDeleteBuffersARB);
3996 #endif
3997 #undef GGPA
4000 CAMLprim value ml_bo_usable (value unit_v)
4002 CAMLparam1 (unit_v);
4003 CAMLreturn (Val_bool (state.bo_usable));
4006 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4008 CAMLparam3 (ptr_v, x_v, y_v);
4009 CAMLlocal2 (ret_v, tup_v);
4010 struct page *page;
4011 char *s = String_val (ptr_v);
4012 int x = Int_val (x_v), y = Int_val (y_v);
4013 struct pagedim *pdim;
4014 fz_point p;
4015 fz_matrix ctm;
4017 page = parse_pointer (__func__, s);
4018 pdim = &state.pagedims[page->pdimno];
4020 ret_v = Val_int (0);
4021 if (trylock (__func__)) {
4022 goto done;
4025 if (pdf_specifics (state.ctx, state.doc)) {
4026 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4027 ctm = state.pagedims[page->pdimno].tctm;
4029 else {
4030 ctm = fz_identity;
4032 p.x = x + pdim->bounds.x0;
4033 p.y = y + pdim->bounds.y0;
4035 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4036 fz_invert_matrix (&ctm, &ctm);
4037 fz_transform_point (&p, &ctm);
4039 tup_v = caml_alloc_tuple (2);
4040 ret_v = caml_alloc_small (1, 1);
4041 Field (tup_v, 0) = Val_int (p.x);
4042 Field (tup_v, 1) = Val_int (p.y);
4043 Field (ret_v, 0) = tup_v;
4045 unlock (__func__);
4046 done:
4047 CAMLreturn (ret_v);
4050 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4051 value x_v, value y_v)
4053 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4054 CAMLlocal1 (ret_v);
4055 struct page *page;
4056 char *s = String_val (ptr_v);
4057 int pageno = Int_val (pageno_v);
4058 int pdimno = Int_val (pdimno_v);
4059 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
4060 struct pagedim *pdim;
4061 fz_point p;
4062 fz_matrix ctm;
4064 ret_v = Val_int (0);
4065 lock (__func__);
4067 if (!*s) {
4068 page = loadpage (pageno, pdimno);
4070 else {
4071 page = parse_pointer (__func__, s);
4073 pdim = &state.pagedims[pdimno];
4075 if (pdf_specifics (state.ctx, state.doc)) {
4076 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4077 ctm = state.pagedims[page->pdimno].tctm;
4079 else {
4080 ctm = fz_identity;
4082 p.x = x + pdim->bounds.x0;
4083 p.y = y + pdim->bounds.y0;
4085 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4086 fz_transform_point (&p, &ctm);
4088 ret_v = caml_alloc_tuple (2);
4089 Field (ret_v, 0) = caml_copy_double ((double) p.x);
4090 Field (ret_v, 1) = caml_copy_double ((double) p.y);
4092 if (!*s) {
4093 freepage (page);
4095 unlock (__func__);
4096 CAMLreturn (ret_v);
4099 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4100 value contents_v)
4102 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4103 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4105 if (pdf) {
4106 pdf_annot *annot;
4107 struct page *page;
4108 fz_point p;
4109 char *s = String_val (ptr_v);
4111 page = parse_pointer (__func__, s);
4112 annot = pdf_create_annot (state.ctx,
4113 pdf_page_from_fz_page (state.ctx,
4114 page->fzpage),
4115 PDF_ANNOT_TEXT);
4116 p.x = Int_val (x_v);
4117 p.y = Int_val (y_v);
4118 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4119 pdf_set_text_annot_position (state.ctx, annot, p);
4120 state.dirty = 1;
4122 CAMLreturn0;
4125 CAMLprim void ml_delannot (value ptr_v, value n_v)
4127 CAMLparam2 (ptr_v, n_v);
4128 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4130 if (pdf) {
4131 struct page *page;
4132 char *s = String_val (ptr_v);
4133 struct slink *slink;
4135 page = parse_pointer (__func__, s);
4136 slink = &page->slinks[Int_val (n_v)];
4137 pdf_delete_annot (state.ctx,
4138 pdf_page_from_fz_page (state.ctx, page->fzpage),
4139 (pdf_annot *) slink->u.annot);
4140 state.dirty = 1;
4142 CAMLreturn0;
4145 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4147 CAMLparam3 (ptr_v, n_v, str_v);
4148 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4150 if (pdf) {
4151 struct page *page;
4152 char *s = String_val (ptr_v);
4153 struct slink *slink;
4155 page = parse_pointer (__func__, s);
4156 slink = &page->slinks[Int_val (n_v)];
4157 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4158 String_val (str_v));
4159 state.dirty = 1;
4161 CAMLreturn0;
4164 CAMLprim value ml_hasunsavedchanges (value unit_v)
4166 CAMLparam1 (unit_v);
4167 CAMLreturn (Val_bool (state.dirty));
4170 CAMLprim void ml_savedoc (value path_v)
4172 CAMLparam1 (path_v);
4173 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4175 if (pdf) {
4176 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4178 CAMLreturn0;
4181 static void makestippletex (void)
4183 const char pixels[] = "\xff\xff\0\0";
4184 glGenTextures (1, &state.stid);
4185 glBindTexture (GL_TEXTURE_1D, state.stid);
4186 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4187 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4188 glTexImage1D (
4189 GL_TEXTURE_1D,
4191 GL_ALPHA,
4194 GL_ALPHA,
4195 GL_UNSIGNED_BYTE,
4196 pixels
4200 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4202 return caml_copy_string (FZ_VERSION);
4205 static char *ystrdup (const char *s)
4207 size_t len = strlen (s);
4208 if (len > 0) {
4209 char *r = malloc (len+1);
4210 if (!r) errx (1, "malloc %zu", len+1);
4211 memcpy (r, s, len+1);
4212 return r;
4214 return NULL;
4217 CAMLprim void ml_init (value csock_v, value params_v)
4219 CAMLparam2 (csock_v, params_v);
4220 CAMLlocal2 (trim_v, fuzz_v);
4221 int ret;
4222 int texcount;
4223 char *fontpath;
4224 int colorspace;
4225 int mustoresize;
4226 int haspboext;
4228 state.csock = Int_val (csock_v);
4229 state.rotate = Int_val (Field (params_v, 0));
4230 state.fitmodel = Int_val (Field (params_v, 1));
4231 trim_v = Field (params_v, 2);
4232 texcount = Int_val (Field (params_v, 3));
4233 state.sliceheight = Int_val (Field (params_v, 4));
4234 mustoresize = Int_val (Field (params_v, 5));
4235 colorspace = Int_val (Field (params_v, 6));
4236 fontpath = String_val (Field (params_v, 7));
4238 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
4239 if (setlocale (LC_CTYPE, "")) {
4240 const char *cset = nl_langinfo (CODESET);
4241 state.utf8cs = !strcmp (cset, "UTF-8");
4243 else {
4244 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
4247 if (caml_string_length (Field (params_v, 8)) > 0) {
4248 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
4250 if (!state.trimcachepath) {
4251 printd ("emsg failed to strdup trimcachepath: %d:%s",
4252 errno, strerror (errno));
4256 haspboext = Bool_val (Field (params_v, 9));
4258 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4259 fz_register_document_handlers (state.ctx);
4261 state.trimmargins = Bool_val (Field (trim_v, 0));
4262 fuzz_v = Field (trim_v, 1);
4263 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4264 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4265 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4266 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4268 set_tex_params (colorspace);
4270 if (*fontpath) {
4271 state.face = load_font (fontpath);
4273 else {
4274 int len;
4275 const unsigned char *data;
4277 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4278 state.face = load_builtin_font (data, len);
4280 if (!state.face) _exit (1);
4282 realloctexts (texcount);
4284 if (haspboext) {
4285 setuppbo ();
4288 makestippletex ();
4290 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4291 if (ret) {
4292 errx (1, "pthread_create: %s", strerror (ret));
4295 CAMLreturn0;
4298 #if FIXME || !FIXME
4299 static void OPTIMIZE_ATTR (0) UNUSED_ATTR refmacs (void) {}
4300 #endif