Fix block/page selection
[llpp.git] / link.c
blobb973cb13cc4383686545dffa9d561c04c0323cfc
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
3 #define FIXME 0
5 #include <errno.h>
6 #include <stdio.h>
7 #include <ctype.h>
8 #include <string.h>
9 #include <stdlib.h>
10 #include <signal.h>
12 #include <wchar.h>
13 #include <locale.h>
14 #include <langinfo.h>
16 #include <unistd.h>
17 #include <pthread.h>
18 #include <sys/uio.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/ioctl.h>
22 #include <sys/utsname.h>
24 #ifdef __CYGWIN__
25 #include <cygwin/socket.h> /* FIONREAD */
26 #else
27 #include <spawn.h>
28 #endif
30 #include <regex.h>
31 #include <stdarg.h>
32 #include <limits.h>
33 #include <inttypes.h>
35 #ifdef __COCOA__
36 #include <CoreFoundation/CoreFoundation.h>
37 #endif
39 #ifdef __APPLE__
40 #include <OpenGL/gl.h>
41 #else
42 #include <GL/gl.h>
43 #endif
45 #include <caml/fail.h>
46 #include <caml/alloc.h>
47 #include <caml/memory.h>
48 #include <caml/unixsupport.h>
50 #if __GNUC__ < 5 && !defined __clang__
51 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
52 clobbered diagnostics */
53 #pragma GCC diagnostic ignored "-Wclobbered"
54 #endif
56 #pragma GCC diagnostic push
57 #pragma GCC diagnostic ignored "-Wunused-parameter"
58 #include <mupdf/fitz.h>
59 #include <mupdf/pdf.h>
60 #pragma GCC diagnostic pop
62 #include <ft2build.h>
63 #include FT_FREETYPE_H
65 #define PIGGYBACK
66 #define CACHE_PAGEREFS
68 #ifndef __USE_GNU
69 extern char **environ;
70 #endif
72 #if defined __GNUC__
73 #define NORETURN_ATTR __attribute__ ((noreturn))
74 #define UNUSED_ATTR __attribute__ ((unused))
75 #if !defined __clang__
76 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
77 #else
78 #define OPTIMIZE_ATTR(n)
79 #endif
80 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
81 #else
82 #define NORETURN_ATTR
83 #define UNUSED_ATTR
84 #define OPTIMIZE_ATTR(n)
85 #define GCC_FMT_ATTR(a, b)
86 #endif
88 #define FMT_s "zu"
90 #define FMT_ptr PRIxPTR
91 #define SCN_ptr SCNxPTR
92 #define FMT_ptr_cast(p) ((uintptr_t) (p))
93 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
95 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
96 err (int exitcode, const char *fmt, ...)
98 va_list ap;
99 int savederrno;
101 savederrno = errno;
102 va_start (ap, fmt);
103 vfprintf (stderr, fmt, ap);
104 va_end (ap);
105 fprintf (stderr, ": %s\n", strerror (savederrno));
106 fflush (stderr);
107 _exit (exitcode);
110 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
111 errx (int exitcode, const char *fmt, ...)
113 va_list ap;
115 va_start (ap, fmt);
116 vfprintf (stderr, fmt, ap);
117 va_end (ap);
118 fputc ('\n', stderr);
119 fflush (stderr);
120 _exit (exitcode);
123 #ifndef GL_TEXTURE_RECTANGLE_ARB
124 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
125 #endif
127 #ifdef USE_NPOT
128 #define TEXT_TYPE GL_TEXTURE_2D
129 #else
130 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
131 #endif
133 #ifndef GL_BGRA
134 #define GL_BGRA 0x80E1
135 #endif
137 #ifndef GL_UNSIGNED_INT_8_8_8_8
138 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
139 #endif
141 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
142 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
143 #endif
145 #if 0
146 #define lprintf printf
147 #else
148 #define lprintf(...)
149 #endif
151 #define ARSERT(cond) for (;;) { \
152 if (!(cond)) { \
153 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
155 break; \
158 struct slice {
159 int h;
160 int texindex;
163 struct tile {
164 int w, h;
165 int slicecount;
166 int sliceheight;
167 struct bo *pbo;
168 fz_pixmap *pixmap;
169 struct slice slices[1];
172 struct pagedim {
173 int pageno;
174 int rotate;
175 int left;
176 int tctmready;
177 fz_irect bounds;
178 fz_rect pagebox;
179 fz_rect mediabox;
180 fz_matrix ctm, zoomctm, tctm;
183 struct slink {
184 enum { SLINK, SANNOT } tag;
185 fz_irect bbox;
186 union {
187 fz_link *link;
188 fz_annot *annot;
189 } u;
192 struct annot {
193 fz_irect bbox;
194 fz_annot *annot;
197 struct page {
198 int tgen;
199 int sgen;
200 int agen;
201 int pageno;
202 int pdimno;
203 fz_stext_page *text;
204 fz_page *fzpage;
205 fz_display_list *dlist;
206 int slinkcount;
207 struct slink *slinks;
208 int annotcount;
209 struct annot *annots;
210 struct mark {
211 fz_stext_char *ch;
212 } fmark, lmark;
215 struct {
216 int sliceheight;
217 struct pagedim *pagedims;
218 int pagecount;
219 int pagedimcount;
220 fz_document *doc;
221 fz_context *ctx;
222 int w, h;
224 int texindex;
225 int texcount;
226 GLuint *texids;
228 GLenum texiform;
229 GLenum texform;
230 GLenum texty;
232 fz_colorspace *colorspace;
234 struct {
235 int w, h;
236 struct slice *slice;
237 } *texowners;
239 int rotate;
240 enum { FitWidth, FitProportional, FitPage } fitmodel;
241 int trimmargins;
242 int needoutline;
243 int gen;
244 int aalevel;
246 int trimanew;
247 fz_irect trimfuzz;
248 fz_pixmap *pig;
250 pthread_t thread;
251 int csock;
252 FT_Face face;
254 char *trimcachepath;
255 int cxack;
256 int dirty;
258 GLuint stid;
260 int bo_usable;
261 GLuint boid;
263 void (*glBindBufferARB) (GLenum, GLuint);
264 GLboolean (*glUnmapBufferARB) (GLenum);
265 void *(*glMapBufferARB) (GLenum, GLenum);
266 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
267 void (*glGenBuffersARB) (GLsizei, GLuint *);
268 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
270 GLfloat texcoords[8];
271 GLfloat vertices[16];
273 #ifdef CACHE_PAGEREFS
274 struct {
275 int idx;
276 int count;
277 pdf_obj **objs;
278 pdf_document *pdf;
279 } pdflut;
280 #endif
281 int utf8cs;
282 } state;
284 struct bo {
285 GLuint id;
286 void *ptr;
287 size_t size;
290 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
292 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
295 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
297 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
300 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
302 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
303 m.a, m.b, m.c, m.d, m.e, m.f);
306 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
308 static void lock (const char *cap)
310 int ret = pthread_mutex_lock (&mutex);
311 if (ret) {
312 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
316 static void unlock (const char *cap)
318 int ret = pthread_mutex_unlock (&mutex);
319 if (ret) {
320 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
324 static int trylock (const char *cap)
326 int ret = pthread_mutex_trylock (&mutex);
327 if (ret && ret != EBUSY) {
328 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
330 return ret == EBUSY;
333 static void *parse_pointer (const char *cap, const char *s)
335 int ret;
336 void *ptr;
338 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
339 if (ret != 1) {
340 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
342 return ptr;
345 static double now (void)
347 struct timeval tv;
349 if (gettimeofday (&tv, NULL)) {
350 err (1, "gettimeofday");
352 return tv.tv_sec + tv.tv_usec*1e-6;
355 static int hasdata (void)
357 int ret, avail;
358 ret = ioctl (state.csock, FIONREAD, &avail);
359 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
360 return avail > 0;
363 CAMLprim value ml_hasdata (value fd_v)
365 CAMLparam1 (fd_v);
366 int ret, avail;
368 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
369 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
370 CAMLreturn (Val_bool (avail > 0));
373 static void readdata (int fd, void *p, int size)
375 ssize_t n;
377 again:
378 n = read (fd, p, size);
379 if (n - size) {
380 if (n < 0 && errno == EINTR) goto again;
381 if (!n) errx (1, "EOF while reading");
382 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
386 static void writedata (int fd, char *p, int size)
388 ssize_t n;
389 uint32_t size4 = size;
390 struct iovec iov[2] = {
391 { .iov_base = &size4, .iov_len = 4 },
392 { .iov_base = p, .iov_len = size }
395 again:
396 n = writev (fd, iov, 2);
397 if (n < 0 && errno == EINTR) goto again;
398 if (n - size - 4) {
399 if (!n) errx (1, "EOF while writing data");
400 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
404 static int readlen (int fd)
406 /* Type punned unions here. Why? Less code (Adjusted by more comments).
407 https://en.wikipedia.org/wiki/Type_punning */
408 /* Then again https://bugs.llvm.org/show_bug.cgi?id=31928 - hmm */
409 union { uint32_t len; char raw[4]; } buf;
410 readdata (fd, buf.raw, 4);
411 return buf.len;
414 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
416 CAMLparam3 (fd_v, bytes_v, len_v);
417 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
418 CAMLreturn0;
421 CAMLprim value ml_rcmd (value fd_v)
423 CAMLparam1 (fd_v);
424 CAMLlocal1 (strdata_v);
425 int fd = Int_val (fd_v);
426 int len = readlen (fd);
427 strdata_v = caml_alloc_string (len);
428 readdata (fd, String_val (strdata_v), len);
429 CAMLreturn (strdata_v);
432 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
434 int size = 64, len;
435 va_list ap;
436 char fbuf[size];
437 char *buf = fbuf;
439 for (;;) {
440 va_start (ap, fmt);
441 len = vsnprintf (buf, size, fmt, ap);
442 va_end (ap);
444 if (len > -1) {
445 if (len < size - 4) {
446 writedata (state.csock, buf, len);
447 break;
449 else size = len + 5;
451 else {
452 err (1, "vsnprintf for `%s' failed", fmt);
454 buf = realloc (buf == fbuf ? NULL : buf, size);
455 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
457 if (buf != fbuf) free (buf);
460 static void closedoc (void)
462 #ifdef CACHE_PAGEREFS
463 if (state.pdflut.objs) {
464 for (int i = 0; i < state.pdflut.count; ++i) {
465 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
467 free (state.pdflut.objs);
468 state.pdflut.objs = NULL;
469 state.pdflut.idx = 0;
471 #endif
472 if (state.doc) {
473 fz_drop_document (state.ctx, state.doc);
474 state.doc = NULL;
478 static int openxref (char *filename, char *password)
480 for (int i = 0; i < state.texcount; ++i) {
481 state.texowners[i].w = -1;
482 state.texowners[i].slice = NULL;
485 closedoc ();
487 state.dirty = 0;
488 if (state.pagedims) {
489 free (state.pagedims);
490 state.pagedims = NULL;
492 state.pagedimcount = 0;
494 fz_set_aa_level (state.ctx, state.aalevel);
495 state.doc = fz_open_document (state.ctx, filename);
496 if (fz_needs_password (state.ctx, state.doc)) {
497 if (password && !*password) {
498 printd ("pass");
499 return 0;
501 else {
502 int ok = fz_authenticate_password (state.ctx, state.doc, password);
503 if (!ok) {
504 printd ("pass fail");
505 return 0;
509 state.pagecount = fz_count_pages (state.ctx, state.doc);
510 return 1;
513 static void pdfinfo (void)
515 struct { char *tag; char *name; } metatbl[] = {
516 { FZ_META_INFO_TITLE, "Title" },
517 { FZ_META_INFO_AUTHOR, "Author" },
518 { FZ_META_FORMAT, "Format" },
519 { FZ_META_ENCRYPTION, "Encryption" },
520 { "info:Creator", "Creator" },
521 { "info:Producer", "Producer" },
522 { "info:CreationDate", "Creation date" },
524 int len = 0;
525 char *buf = NULL;
527 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
528 int need;
529 again:
530 need = fz_lookup_metadata (state.ctx, state.doc,
531 metatbl[i].tag, buf, len);
532 if (need > 0) {
533 if (need <= len) {
534 printd ("info %s\t%s", metatbl[i].name, buf);
536 else {
537 buf = realloc (buf, need + 1);
538 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
539 len = need + 1;
540 goto again;
544 free (buf);
546 printd ("infoend");
549 static void unlinktile (struct tile *tile)
551 for (int i = 0; i < tile->slicecount; ++i) {
552 struct slice *s = &tile->slices[i];
554 if (s->texindex != -1) {
555 if (state.texowners[s->texindex].slice == s) {
556 state.texowners[s->texindex].slice = NULL;
562 static void freepage (struct page *page)
564 if (!page) return;
565 if (page->text) {
566 fz_drop_stext_page (state.ctx, page->text);
568 if (page->slinks) {
569 free (page->slinks);
571 fz_drop_display_list (state.ctx, page->dlist);
572 fz_drop_page (state.ctx, page->fzpage);
573 free (page);
576 static void freetile (struct tile *tile)
578 unlinktile (tile);
579 if (!tile->pbo) {
580 #ifndef PIGGYBACK
581 fz_drop_pixmap (state.ctx, tile->pixmap);
582 #else
583 if (state.pig) {
584 fz_drop_pixmap (state.ctx, state.pig);
586 state.pig = tile->pixmap;
587 #endif
589 else {
590 free (tile->pbo);
591 fz_drop_pixmap (state.ctx, tile->pixmap);
593 free (tile);
596 #ifdef __ALTIVEC__
597 #include <stdint.h>
598 #include <altivec.h>
600 static int cacheline32bytes;
602 static void __attribute__ ((constructor)) clcheck (void)
604 char **envp = environ;
605 unsigned long *auxv;
607 while (*envp++);
609 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
610 if (*auxv == 19) {
611 cacheline32bytes = auxv[1] == 32;
612 return;
617 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
619 size_t size = pixmap->w * pixmap->h * pixmap->n;
620 if (cacheline32bytes && size > 32) {
621 intptr_t a1, a2, diff;
622 size_t sizea, i;
623 vector unsigned char v = vec_splat_u8 (-1);
624 vector unsigned char *p;
626 a1 = a2 = (intptr_t) pixmap->samples;
627 a2 = (a1 + 31) & ~31;
628 diff = a2 - a1;
629 sizea = size - diff;
630 p = (void *) a2;
632 while (a1 != a2) *(char *) a1++ = 0xff;
633 for (i = 0; i < (sizea & ~31); i += 32) {
634 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
635 vec_st (v, i, p);
636 vec_st (v, i + 16, p);
638 while (i < sizea) *((char *) a1 + i++) = 0xff;
640 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
642 #else
643 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
644 #endif
646 static void trimctm (pdf_page *page, int pindex)
648 fz_matrix ctm;
649 struct pagedim *pdim = &state.pagedims[pindex];
651 if (!page) return;
652 if (!pdim->tctmready) {
653 fz_rect realbox, mediabox;
654 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
656 fz_rotate (&rm, -pdim->rotate);
657 fz_scale (&sm, 1, -1);
658 fz_concat (&ctm, &rm, &sm);
659 realbox = pdim->mediabox;
660 fz_transform_rect (&realbox, &ctm);
661 fz_translate (&tm, -realbox.x0, -realbox.y0);
662 fz_concat (&ctm1, &ctm, &tm);
663 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
664 fz_invert_matrix (&im, &page_ctm);
665 fz_concat (&ctm, &im, &ctm1);
666 pdim->tctm = ctm;
667 pdim->tctmready = 1;
671 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
673 fz_matrix ctm, tm;
674 int pdimno = pdim - state.pagedims;
676 if (pdf_specifics (state.ctx, state.doc)) {
677 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
678 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
680 else {
681 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
682 fz_concat (&ctm, &tm, &pdim->ctm);
684 return ctm;
687 static fz_matrix pagectm (struct page *page)
689 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
692 static void *loadpage (int pageno, int pindex)
694 fz_device *dev;
695 struct page *page;
697 page = calloc (sizeof (struct page), 1);
698 if (!page) {
699 err (1, "calloc page %d", pageno);
702 page->dlist = fz_new_display_list (state.ctx, NULL);
703 dev = fz_new_list_device (state.ctx, page->dlist);
704 fz_try (state.ctx) {
705 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
706 fz_run_page (state.ctx, page->fzpage, dev,
707 &fz_identity, NULL);
709 fz_catch (state.ctx) {
710 page->fzpage = NULL;
712 fz_close_device (state.ctx, dev);
713 fz_drop_device (state.ctx, dev);
715 page->pdimno = pindex;
716 page->pageno = pageno;
717 page->sgen = state.gen;
718 page->agen = state.gen;
719 page->tgen = state.gen;
720 return page;
723 static struct tile *alloctile (int h)
725 int slicecount;
726 size_t tilesize;
727 struct tile *tile;
729 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
730 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
731 tile = calloc (tilesize, 1);
732 if (!tile) {
733 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
735 for (int i = 0; i < slicecount; ++i) {
736 int sh = fz_mini (h, state.sliceheight);
737 tile->slices[i].h = sh;
738 tile->slices[i].texindex = -1;
739 h -= sh;
741 tile->slicecount = slicecount;
742 tile->sliceheight = state.sliceheight;
743 return tile;
746 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
747 struct bo *pbo)
749 fz_rect rect;
750 fz_irect bbox;
751 fz_matrix ctm;
752 fz_device *dev;
753 struct tile *tile;
754 struct pagedim *pdim;
756 tile = alloctile (h);
757 pdim = &state.pagedims[page->pdimno];
759 bbox = pdim->bounds;
760 bbox.x0 += x;
761 bbox.y0 += y;
762 bbox.x1 = bbox.x0 + w;
763 bbox.y1 = bbox.y0 + h;
765 if (state.pig) {
766 if (state.pig->w == w
767 && state.pig->h == h
768 && state.pig->colorspace == state.colorspace) {
769 tile->pixmap = state.pig;
770 tile->pixmap->x = bbox.x0;
771 tile->pixmap->y = bbox.y0;
773 else {
774 fz_drop_pixmap (state.ctx, state.pig);
776 state.pig = NULL;
778 if (!tile->pixmap) {
779 if (pbo) {
780 tile->pixmap =
781 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
782 &bbox, NULL, 1, pbo->ptr);
783 tile->pbo = pbo;
785 else {
786 tile->pixmap =
787 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
788 NULL, 1);
792 tile->w = w;
793 tile->h = h;
794 clearpixmap (tile->pixmap);
796 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
797 ctm = pagectm (page);
798 fz_rect_from_irect (&rect, &bbox);
799 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
800 fz_close_device (state.ctx, dev);
801 fz_drop_device (state.ctx, dev);
803 return tile;
806 #ifdef CACHE_PAGEREFS
807 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
808 thanks to Robin Watts */
809 static void
810 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
812 fz_context *ctx = state.ctx; /* doc->ctx; */
813 pdf_obj *kids;
814 int len;
816 if (state.pdflut.idx == state.pagecount) return;
818 kids = pdf_dict_gets (ctx, node, "Kids");
819 len = pdf_array_len (ctx, kids);
821 if (len == 0)
822 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
824 if (pdf_mark_obj (ctx, node))
825 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
826 for (int i = 0; i < len; i++) {
827 pdf_obj *kid = pdf_array_get (ctx, kids, i);
828 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
829 if (*type
830 ? !strcmp (type, "Pages")
831 : pdf_dict_gets (ctx, kid, "Kids")
832 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
833 pdf_collect_pages (doc, kid);
835 else {
836 if (*type
837 ? strcmp (type, "Page") != 0
838 : !pdf_dict_gets (ctx, kid, "MediaBox"))
839 fz_warn (ctx, "non-page object in page tree (%s)", type);
840 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
843 pdf_unmark_obj (ctx, node);
846 static void
847 pdf_load_page_objs (pdf_document *doc)
849 pdf_obj *root = pdf_dict_gets (state.ctx,
850 pdf_trailer (state.ctx, doc), "Root");
851 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
853 if (!node)
854 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
856 state.pdflut.idx = 0;
857 pdf_collect_pages (doc, node);
859 #endif
861 static void initpdims (int wthack)
863 double start, end;
864 FILE *trimf = NULL;
865 fz_rect rootmediabox;
866 int pageno, trim, show;
867 int trimw = 0, cxcount;
868 fz_context *ctx = state.ctx;
869 pdf_document *pdf = pdf_specifics (ctx, state.doc);
871 fz_var (trimw);
872 fz_var (trimf);
873 fz_var (cxcount);
874 start = now ();
876 if (state.trimmargins && state.trimcachepath) {
877 trimf = fopen (state.trimcachepath, "rb");
878 if (!trimf) {
879 trimf = fopen (state.trimcachepath, "wb");
880 trimw = 1;
884 if (state.trimmargins || pdf || !state.cxack)
885 cxcount = state.pagecount;
886 else
887 cxcount = fz_mini (state.pagecount, 1);
889 if (pdf) {
890 pdf_obj *obj;
891 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
892 "Root/Pages/MediaBox");
893 pdf_to_rect (ctx, obj, &rootmediabox);
896 #ifdef CACHE_PAGEREFS
897 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
898 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
899 if (!state.pdflut.objs) {
900 err (1, "malloc pageobjs %zu %d %zu failed",
901 sizeof (*state.pdflut.objs), cxcount,
902 sizeof (*state.pdflut.objs) * cxcount);
904 state.pdflut.count = cxcount;
905 pdf_load_page_objs (pdf);
906 state.pdflut.pdf = pdf;
908 #endif
910 for (pageno = 0; pageno < cxcount; ++pageno) {
911 int rotate = 0;
912 struct pagedim *p;
913 fz_rect mediabox;
915 fz_var (rotate);
916 if (pdf) {
917 pdf_obj *pageref, *pageobj;
919 #ifdef CACHE_PAGEREFS
920 pageref = state.pdflut.objs[pageno];
921 #else
922 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
923 #endif
924 pageobj = pdf_resolve_indirect (ctx, pageref);
925 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
927 if (state.trimmargins) {
928 pdf_obj *obj;
929 pdf_page *page;
931 fz_try (ctx) {
932 page = pdf_load_page (ctx, pdf, pageno);
933 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
934 trim = state.trimanew || !obj;
935 if (trim) {
936 fz_rect rect;
937 fz_device *dev;
938 fz_matrix ctm, page_ctm;
940 dev = fz_new_bbox_device (ctx, &rect);
941 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
942 fz_invert_matrix (&ctm, &page_ctm);
943 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
944 fz_close_device (ctx, dev);
945 fz_drop_device (ctx, dev);
947 rect.x0 += state.trimfuzz.x0;
948 rect.x1 += state.trimfuzz.x1;
949 rect.y0 += state.trimfuzz.y0;
950 rect.y1 += state.trimfuzz.y1;
951 fz_transform_rect (&rect, &ctm);
952 fz_intersect_rect (&rect, &mediabox);
954 if (!fz_is_empty_rect (&rect)) {
955 mediabox = rect;
958 obj = pdf_new_array (ctx, pdf, 4);
959 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
960 mediabox.x0));
961 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
962 mediabox.y0));
963 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
964 mediabox.x1));
965 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
966 mediabox.y1));
967 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
969 else {
970 mediabox.x0 = pdf_to_real (ctx,
971 pdf_array_get (ctx, obj, 0));
972 mediabox.y0 = pdf_to_real (ctx,
973 pdf_array_get (ctx, obj, 1));
974 mediabox.x1 = pdf_to_real (ctx,
975 pdf_array_get (ctx, obj, 2));
976 mediabox.y1 = pdf_to_real (ctx,
977 pdf_array_get (ctx, obj, 3));
980 fz_drop_page (ctx, &page->super);
981 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
982 if (show) {
983 printd ("progress %f Trimming %d",
984 (double) (pageno + 1) / state.pagecount,
985 pageno + 1);
988 fz_catch (ctx) {
989 fprintf (stderr, "failed to load page %d\n", pageno+1);
992 else {
993 int empty = 0;
994 fz_rect cropbox;
996 pdf_to_rect (ctx,
997 pdf_dict_gets (ctx, pageobj, "MediaBox"),
998 &mediabox);
999 if (fz_is_empty_rect (&mediabox)) {
1000 mediabox.x0 = 0;
1001 mediabox.y0 = 0;
1002 mediabox.x1 = 612;
1003 mediabox.y1 = 792;
1004 empty = 1;
1007 pdf_to_rect (ctx,
1008 pdf_dict_gets (ctx, pageobj, "CropBox"),
1009 &cropbox);
1010 if (!fz_is_empty_rect (&cropbox)) {
1011 if (empty) {
1012 mediabox = cropbox;
1014 else {
1015 fz_intersect_rect (&mediabox, &cropbox);
1018 else {
1019 if (empty) {
1020 if (fz_is_empty_rect (&rootmediabox)) {
1021 fprintf (stderr,
1022 "cannot find page size for page %d\n",
1023 pageno+1);
1025 else {
1026 mediabox = rootmediabox;
1032 else {
1033 if (state.trimmargins && trimw) {
1034 fz_page *page;
1036 fz_try (ctx) {
1037 page = fz_load_page (ctx, state.doc, pageno);
1038 fz_bound_page (ctx, page, &mediabox);
1039 if (state.trimmargins) {
1040 fz_rect rect;
1041 fz_device *dev;
1043 dev = fz_new_bbox_device (ctx, &rect);
1044 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1045 fz_close_device (ctx, dev);
1046 fz_drop_device (ctx, dev);
1048 rect.x0 += state.trimfuzz.x0;
1049 rect.x1 += state.trimfuzz.x1;
1050 rect.y0 += state.trimfuzz.y0;
1051 rect.y1 += state.trimfuzz.y1;
1052 fz_intersect_rect (&rect, &mediabox);
1054 if (!fz_is_empty_rect (&rect)) {
1055 mediabox = rect;
1058 fz_drop_page (ctx, page);
1059 if (!state.cxack) {
1060 printd ("progress %f loading %d",
1061 (double) (pageno + 1) / state.pagecount,
1062 pageno + 1);
1065 fz_catch (ctx) {
1067 if (trimf) {
1068 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1069 if (n - 1) {
1070 err (1, "fwrite trim mediabox");
1074 else {
1075 if (trimf) {
1076 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1077 if (n - 1) {
1078 err (1, "fread trim mediabox %d", pageno);
1081 else {
1082 fz_page *page;
1083 fz_try (ctx) {
1084 page = fz_load_page (ctx, state.doc, pageno);
1085 fz_bound_page (ctx, page, &mediabox);
1086 fz_drop_page (ctx, page);
1088 show = !state.trimmargins && pageno % 20 == 0;
1089 if (show) {
1090 printd ("progress %f Gathering dimensions %d",
1091 (double) (pageno) / state.pagecount,
1092 pageno);
1095 fz_catch (ctx) {
1096 fprintf (stderr, "failed to load page %d\n", pageno);
1102 if (state.pagedimcount == 0
1103 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1104 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1105 size_t size;
1107 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1108 state.pagedims = realloc (state.pagedims, size);
1109 if (!state.pagedims) {
1110 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1111 size, state.pagedimcount + 1);
1114 p = &state.pagedims[state.pagedimcount++];
1115 p->rotate = rotate;
1116 p->mediabox = mediabox;
1117 p->pageno = pageno;
1120 end = now ();
1121 if (!wthack) {
1122 printd ("progress 1 %s %d pages in %f seconds",
1123 state.trimmargins ? "Trimmed" : "Processed",
1124 state.pagecount, end - start);
1126 state.trimanew = 0;
1127 if (trimf) {
1128 if (fclose (trimf)) {
1129 err (1, "fclose");
1134 static void layout (void)
1136 int pindex;
1137 fz_rect box;
1138 fz_matrix ctm, rm;
1139 struct pagedim *p = p;
1140 double zw, w, maxw = 0.0, zoom = zoom;
1142 if (state.pagedimcount == 0) return;
1144 switch (state.fitmodel) {
1145 case FitProportional:
1146 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1147 double x0, x1;
1149 p = &state.pagedims[pindex];
1150 fz_rotate (&rm, p->rotate + state.rotate);
1151 box = p->mediabox;
1152 fz_transform_rect (&box, &rm);
1154 x0 = fz_min (box.x0, box.x1);
1155 x1 = fz_max (box.x0, box.x1);
1157 w = x1 - x0;
1158 maxw = fz_max (w, maxw);
1159 zoom = state.w / maxw;
1161 break;
1163 case FitPage:
1164 maxw = state.w;
1165 break;
1167 case FitWidth:
1168 break;
1170 default:
1171 ARSERT (0 && state.fitmodel);
1174 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1175 fz_rect rect;
1176 fz_matrix tm, sm;
1178 p = &state.pagedims[pindex];
1179 fz_rotate (&ctm, state.rotate);
1180 fz_rotate (&rm, p->rotate + state.rotate);
1181 box = p->mediabox;
1182 fz_transform_rect (&box, &rm);
1183 w = box.x1 - box.x0;
1184 switch (state.fitmodel) {
1185 case FitProportional:
1186 p->left = ((maxw - w) * zoom) / 2.0;
1187 break;
1188 case FitPage:
1190 double zh, h;
1191 zw = maxw / w;
1192 h = box.y1 - box.y0;
1193 zh = state.h / h;
1194 zoom = fz_min (zw, zh);
1195 p->left = (maxw - (w * zoom)) / 2.0;
1197 break;
1198 case FitWidth:
1199 p->left = 0;
1200 zoom = state.w / w;
1201 break;
1204 fz_scale (&p->zoomctm, zoom, zoom);
1205 fz_concat (&ctm, &p->zoomctm, &ctm);
1207 fz_rotate (&rm, p->rotate);
1208 p->pagebox = p->mediabox;
1209 fz_transform_rect (&p->pagebox, &rm);
1210 p->pagebox.x1 -= p->pagebox.x0;
1211 p->pagebox.y1 -= p->pagebox.y0;
1212 p->pagebox.x0 = 0;
1213 p->pagebox.y0 = 0;
1214 rect = p->pagebox;
1215 fz_transform_rect (&rect, &ctm);
1216 fz_round_rect (&p->bounds, &rect);
1217 p->ctm = ctm;
1219 fz_translate (&tm, 0, -p->mediabox.y1);
1220 fz_scale (&sm, zoom, -zoom);
1221 fz_concat (&ctm, &tm, &sm);
1223 p->tctmready = 0;
1226 do {
1227 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1228 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1229 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1230 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1231 int boundw = x1 - x0;
1232 int boundh = y1 - y0;
1234 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1235 } while (p-- != state.pagedims);
1238 struct pagedim *pdimofpageno (int pageno)
1240 struct pagedim *pdim = state.pagedims;
1242 for (int i = 0; i < state.pagedimcount; ++i) {
1243 if (state.pagedims[i].pageno > pageno)
1244 break;
1245 pdim = &state.pagedims[i];
1247 return pdim;
1250 static
1251 struct anchor { int n; int x; int y; int w; int h; }
1252 uritoanchor (const char *uri)
1254 fz_point p;
1255 struct anchor a;
1257 a.n = -1;
1258 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1259 if (a.n >= 0) {
1260 struct pagedim *pdim = pdimofpageno (a.n);
1261 fz_transform_point (&p, &pdim->ctm);
1262 a.x = p.x;
1263 a.y = p.y;
1264 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1266 return a;
1269 static void recurse_outline (fz_outline *outline, int level)
1271 while (outline) {
1272 struct anchor a = uritoanchor (outline->uri);
1273 if (a.n >= 0) {
1274 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1276 else {
1277 printd ("on %d %s", level, outline->title);
1279 if (outline->down) {
1280 recurse_outline (outline->down, level + 1);
1282 outline = outline->next;
1286 static void process_outline (void)
1288 fz_outline *outline;
1290 if (!state.needoutline || !state.pagedimcount) return;
1292 state.needoutline = 0;
1293 outline = fz_load_outline (state.ctx, state.doc);
1294 if (outline) {
1295 recurse_outline (outline, 0);
1296 fz_drop_outline (state.ctx, outline);
1300 static char *strofline (fz_stext_line *line)
1302 char *p;
1303 char utf8[10];
1304 fz_stext_char *ch;
1305 size_t size = 0, cap = 80;
1307 p = malloc (cap + 1);
1308 if (!p) return NULL;
1310 for (ch = line->first_char; ch; ch = ch->next) {
1311 int n = fz_runetochar (utf8, ch->c);
1312 if (size + n > cap) {
1313 cap *= 2;
1314 p = realloc (p, cap + 1);
1315 if (!p) return NULL;
1318 memcpy (p + size, utf8, n);
1319 size += n;
1321 p[size] = 0;
1322 return p;
1325 static int matchline (regex_t *re, fz_stext_line *line,
1326 int stop, int pageno, double start)
1328 int ret;
1329 char *p;
1330 regmatch_t rm;
1332 p = strofline (line);
1333 if (!p) return -1;
1335 ret = regexec (re, p, 1, &rm, 0);
1336 if (ret) {
1337 free (p);
1338 if (ret != REG_NOMATCH) {
1339 size_t size;
1340 char errbuf[80];
1341 size = regerror (ret, re, errbuf, sizeof (errbuf));
1342 printd ("msg regexec error `%.*s'",
1343 (int) size, errbuf);
1344 return -1;
1346 return 0;
1348 else {
1349 fz_point p1, p2, p3, p4;
1350 fz_rect s = {0,0,0,0}, e;
1351 fz_stext_char *ch;
1352 int o = 0;
1354 for (ch = line->first_char; ch; ch = ch->next) {
1355 o += fz_runelen (ch->c);
1356 if (o > rm.rm_so) {
1357 s = ch->bbox;
1358 break;
1361 for (;ch; ch = ch->next) {
1362 o += fz_runelen (ch->c);
1363 if (o > rm.rm_eo) break;
1365 e = ch->bbox;
1367 p1.x = s.x0;
1368 p1.y = s.y0;
1369 p2.x = e.x1;
1370 p2.y = s.y0;
1371 p3.x = e.x1;
1372 p3.y = e.y1;
1373 p4.x = s.x0;
1374 p4.y = e.y1;
1376 if (!stop) {
1377 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1378 pageno, 1,
1379 p1.x, p1.y,
1380 p2.x, p2.y,
1381 p3.x, p3.y,
1382 p4.x, p4.y);
1384 printd ("progress 1 found at %d `%.*s' in %f sec",
1385 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1386 now () - start);
1388 else {
1389 printd ("match %d %d %f %f %f %f %f %f %f %f",
1390 pageno, 2,
1391 p1.x, p1.y,
1392 p2.x, p2.y,
1393 p3.x, p3.y,
1394 p4.x, p4.y);
1396 free (p);
1397 return 1;
1401 /* wishful thinking function */
1402 static void search (regex_t *re, int pageno, int y, int forward)
1404 fz_device *tdev;
1405 fz_stext_page *text;
1406 struct pagedim *pdim;
1407 int stop = 0, niters = 0;
1408 double start, end;
1409 fz_page *page;
1410 fz_stext_block *block;
1412 start = now ();
1413 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1414 if (niters++ == 5) {
1415 niters = 0;
1416 if (hasdata ()) {
1417 printd ("progress 1 attention requested aborting search at %d",
1418 pageno);
1419 stop = 1;
1421 else {
1422 printd ("progress %f searching in page %d",
1423 (double) (pageno + 1) / state.pagecount,
1424 pageno);
1427 pdim = pdimofpageno (pageno);
1428 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1429 tdev = fz_new_stext_device (state.ctx, text, 0);
1431 page = fz_load_page (state.ctx, state.doc, pageno);
1433 fz_matrix ctm = pagectm1 (page, pdim);
1434 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1437 fz_close_device (state.ctx, tdev);
1438 fz_drop_device (state.ctx, tdev);
1440 if (forward) {
1441 for (block = text->first_block; block; block = block->next) {
1442 fz_stext_line *line;
1444 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1445 for (line = block->u.t.first_line; line; line = line->next) {
1446 if (line->bbox.y0 < y + 1) continue;
1448 switch (matchline (re, line, stop, pageno, start)) {
1449 case 0: break;
1450 case 1: stop = 1; break;
1451 case -1: stop = 1; goto endloop;
1456 else {
1457 for (block = text->last_block; block; block = block->prev) {
1458 fz_stext_line *line;
1460 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1461 for (line = block->u.t.last_line; line; line = line->prev) {
1462 if (line->bbox.y0 < y + 1) continue;
1464 switch (matchline (re, line, stop, pageno, start)) {
1465 case 0: break;
1466 case 1: stop = 1; break;
1467 case -1: stop = 1; goto endloop;
1473 if (forward) {
1474 pageno += 1;
1475 y = 0;
1477 else {
1478 pageno -= 1;
1479 y = INT_MAX;
1481 endloop:
1482 fz_drop_stext_page (state.ctx, text);
1483 fz_drop_page (state.ctx, page);
1485 end = now ();
1486 if (!stop) {
1487 printd ("progress 1 no matches %f sec", end - start);
1489 printd ("clearrects");
1492 static void set_tex_params (int colorspace)
1494 union {
1495 unsigned char b;
1496 unsigned int s;
1497 } endianness = {1};
1499 switch (colorspace) {
1500 case 0:
1501 state.texiform = GL_RGBA8;
1502 state.texform = GL_RGBA;
1503 state.texty = GL_UNSIGNED_BYTE;
1504 state.colorspace = fz_device_rgb (state.ctx);
1505 break;
1506 case 1:
1507 state.texiform = GL_RGBA8;
1508 state.texform = GL_BGRA;
1509 state.texty = endianness.s > 1
1510 ? GL_UNSIGNED_INT_8_8_8_8
1511 : GL_UNSIGNED_INT_8_8_8_8_REV;
1512 state.colorspace = fz_device_bgr (state.ctx);
1513 break;
1514 case 2:
1515 state.texiform = GL_LUMINANCE_ALPHA;
1516 state.texform = GL_LUMINANCE_ALPHA;
1517 state.texty = GL_UNSIGNED_BYTE;
1518 state.colorspace = fz_device_gray (state.ctx);
1519 break;
1520 default:
1521 errx (1, "invalid colorspce %d", colorspace);
1525 static void realloctexts (int texcount)
1527 size_t size;
1529 if (texcount == state.texcount) return;
1531 if (texcount < state.texcount) {
1532 glDeleteTextures (state.texcount - texcount,
1533 state.texids + texcount);
1536 size = texcount * sizeof (*state.texids);
1537 state.texids = realloc (state.texids, size);
1538 if (!state.texids) {
1539 err (1, "realloc texids %" FMT_s, size);
1542 size = texcount * sizeof (*state.texowners);
1543 state.texowners = realloc (state.texowners, size);
1544 if (!state.texowners) {
1545 err (1, "realloc texowners %" FMT_s, size);
1547 if (texcount > state.texcount) {
1548 glGenTextures (texcount - state.texcount,
1549 state.texids + state.texcount);
1550 for (int i = state.texcount; i < texcount; ++i) {
1551 state.texowners[i].w = -1;
1552 state.texowners[i].slice = NULL;
1555 state.texcount = texcount;
1556 state.texindex = 0;
1559 static char *mbtoutf8 (char *s)
1561 char *p, *r;
1562 wchar_t *tmp;
1563 size_t i, ret, len;
1565 if (state.utf8cs) {
1566 return s;
1569 len = mbstowcs (NULL, s, strlen (s));
1570 if (len == 0) {
1571 return s;
1573 else {
1574 if (len == (size_t) -1) {
1575 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1576 return s;
1580 tmp = calloc (len, sizeof (wchar_t));
1581 if (!tmp) {
1582 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1583 len, sizeof (wchar_t), errno, strerror (errno));
1584 return s;
1587 ret = mbstowcs (tmp, s, len);
1588 if (ret == (size_t) -1) {
1589 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1590 len, errno, strerror (errno));
1591 free (tmp);
1592 return s;
1595 len = 0;
1596 for (i = 0; i < ret; ++i) {
1597 len += fz_runelen (tmp[i]);
1600 p = r = malloc (len + 1);
1601 if (!r) {
1602 printd ("emsg mbtoutf8: malloc(%zu)", len);
1603 free (tmp);
1604 return s;
1607 for (i = 0; i < ret; ++i) {
1608 p += fz_runetochar (p, tmp[i]);
1610 *p = 0;
1611 free (tmp);
1612 return r;
1615 CAMLprim value ml_mbtoutf8 (value s_v)
1617 CAMLparam1 (s_v);
1618 CAMLlocal1 (ret_v);
1619 char *s, *r;
1621 s = String_val (s_v);
1622 r = mbtoutf8 (s);
1623 if (r == s) {
1624 ret_v = s_v;
1626 else {
1627 ret_v = caml_copy_string (r);
1628 free (r);
1630 CAMLreturn (ret_v);
1633 static void * mainloop (void UNUSED_ATTR *unused)
1635 char *p = NULL;
1636 int len, ret, oldlen = 0;
1638 fz_var (p);
1639 fz_var (oldlen);
1640 for (;;) {
1641 len = readlen (state.csock);
1642 if (len == 0) {
1643 errx (1, "readlen returned 0");
1646 if (oldlen < len + 1) {
1647 p = realloc (p, len + 1);
1648 if (!p) {
1649 err (1, "realloc %d failed", len + 1);
1651 oldlen = len + 1;
1653 readdata (state.csock, p, len);
1654 p[len] = 0;
1656 if (!strncmp ("open", p, 4)) {
1657 int wthack, off, usedoccss, ok = 0;
1658 char *password;
1659 char *filename;
1660 char *utf8filename;
1661 size_t filenamelen;
1663 fz_var (ok);
1664 ret = sscanf (p + 5, " %d %d %d %n",
1665 &wthack, &state.cxack, &usedoccss, &off);
1666 if (ret != 3) {
1667 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1670 filename = p + 5 + off;
1671 filenamelen = strlen (filename);
1672 password = filename + filenamelen + 1;
1674 if (password[strlen (password) + 1]) {
1675 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1678 lock ("open");
1679 fz_set_use_document_css (state.ctx, usedoccss);
1680 fz_try (state.ctx) {
1681 ok = openxref (filename, password);
1683 fz_catch (state.ctx) {
1684 utf8filename = mbtoutf8 (filename);
1685 printd ("msg Could not open %s", utf8filename);
1687 if (ok) {
1688 pdfinfo ();
1689 initpdims (wthack);
1691 unlock ("open");
1693 if (ok) {
1694 if (!wthack) {
1695 utf8filename = mbtoutf8 (filename);
1696 printd ("msg Opened %s (press h/F1 to get help)",
1697 utf8filename);
1698 if (utf8filename != filename) {
1699 free (utf8filename);
1702 state.needoutline = 1;
1705 else if (!strncmp ("cs", p, 2)) {
1706 int i, colorspace;
1708 ret = sscanf (p + 2, " %d", &colorspace);
1709 if (ret != 1) {
1710 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1712 lock ("cs");
1713 set_tex_params (colorspace);
1714 for (i = 0; i < state.texcount; ++i) {
1715 state.texowners[i].w = -1;
1716 state.texowners[i].slice = NULL;
1718 unlock ("cs");
1720 else if (!strncmp ("freepage", p, 8)) {
1721 void *ptr;
1723 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1724 if (ret != 1) {
1725 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1727 freepage (ptr);
1729 else if (!strncmp ("freetile", p, 8)) {
1730 void *ptr;
1732 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1733 if (ret != 1) {
1734 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1736 freetile (ptr);
1738 else if (!strncmp ("search", p, 6)) {
1739 int icase, pageno, y, len2, forward;
1740 char *pattern;
1741 regex_t re;
1743 ret = sscanf (p + 6, " %d %d %d %d,%n",
1744 &icase, &pageno, &y, &forward, &len2);
1745 if (ret != 4) {
1746 errx (1, "malformed search `%s' ret=%d", p, ret);
1749 pattern = p + 6 + len2;
1750 ret = regcomp (&re, pattern,
1751 REG_EXTENDED | (icase ? REG_ICASE : 0));
1752 if (ret) {
1753 char errbuf[80];
1754 size_t size;
1756 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1757 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1759 else {
1760 search (&re, pageno, y, forward);
1761 regfree (&re);
1764 else if (!strncmp ("geometry", p, 8)) {
1765 int w, h, fitmodel;
1767 printd ("clear");
1768 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1769 if (ret != 3) {
1770 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1773 lock ("geometry");
1774 state.h = h;
1775 if (w != state.w) {
1776 state.w = w;
1777 for (int i = 0; i < state.texcount; ++i) {
1778 state.texowners[i].slice = NULL;
1781 state.fitmodel = fitmodel;
1782 layout ();
1783 process_outline ();
1785 state.gen++;
1786 unlock ("geometry");
1787 printd ("continue %d", state.pagecount);
1789 else if (!strncmp ("reqlayout", p, 9)) {
1790 char *nameddest;
1791 int rotate, off, h;
1792 unsigned int fitmodel;
1793 pdf_document *pdf;
1795 printd ("clear");
1796 ret = sscanf (p + 9, " %d %u %d %n",
1797 &rotate, &fitmodel, &h, &off);
1798 if (ret != 3) {
1799 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1801 lock ("reqlayout");
1802 pdf = pdf_specifics (state.ctx, state.doc);
1803 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1804 state.gen += 1;
1806 state.rotate = rotate;
1807 state.fitmodel = fitmodel;
1808 state.h = h;
1809 layout ();
1810 process_outline ();
1812 nameddest = p + 9 + off;
1813 if (pdf && nameddest && *nameddest) {
1814 fz_point xy;
1815 struct pagedim *pdim;
1816 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1817 &xy.x, &xy.y);
1818 pdim = pdimofpageno (pageno);
1819 fz_transform_point (&xy, &pdim->ctm);
1820 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1823 state.gen++;
1824 unlock ("reqlayout");
1825 printd ("continue %d", state.pagecount);
1827 else if (!strncmp ("page", p, 4)) {
1828 double a, b;
1829 struct page *page;
1830 int pageno, pindex;
1832 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1833 if (ret != 2) {
1834 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1837 lock ("page");
1838 a = now ();
1839 page = loadpage (pageno, pindex);
1840 b = now ();
1841 unlock ("page");
1843 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1845 else if (!strncmp ("tile", p, 4)) {
1846 int x, y, w, h;
1847 struct page *page;
1848 struct tile *tile;
1849 double a, b;
1850 void *data;
1852 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1853 SCN_ptr_cast (&page), &x, &y, &w, &h,
1854 SCN_ptr_cast (&data));
1855 if (ret != 6) {
1856 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1859 lock ("tile");
1860 a = now ();
1861 tile = rendertile (page, x, y, w, h, data);
1862 b = now ();
1863 unlock ("tile");
1865 printd ("tile %d %d %" FMT_ptr " %u %f",
1866 x, y,
1867 FMT_ptr_cast (tile),
1868 tile->w * tile->h * tile->pixmap->n,
1869 b - a);
1871 else if (!strncmp ("trimset", p, 7)) {
1872 fz_irect fuzz;
1873 int trimmargins;
1875 ret = sscanf (p + 7, " %d %d %d %d %d",
1876 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1877 if (ret != 5) {
1878 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1880 lock ("trimset");
1881 state.trimmargins = trimmargins;
1882 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1883 state.trimanew = 1;
1884 state.trimfuzz = fuzz;
1886 unlock ("trimset");
1888 else if (!strncmp ("settrim", p, 7)) {
1889 fz_irect fuzz;
1890 int trimmargins;
1892 ret = sscanf (p + 7, " %d %d %d %d %d",
1893 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1894 if (ret != 5) {
1895 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1897 printd ("clear");
1898 lock ("settrim");
1899 state.trimmargins = trimmargins;
1900 state.needoutline = 1;
1901 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1902 state.trimanew = 1;
1903 state.trimfuzz = fuzz;
1905 state.pagedimcount = 0;
1906 free (state.pagedims);
1907 state.pagedims = NULL;
1908 initpdims (0);
1909 layout ();
1910 process_outline ();
1911 unlock ("settrim");
1912 printd ("continue %d", state.pagecount);
1914 else if (!strncmp ("sliceh", p, 6)) {
1915 int h;
1917 ret = sscanf (p + 6, " %d", &h);
1918 if (ret != 1) {
1919 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1921 if (h != state.sliceheight) {
1922 state.sliceheight = h;
1923 for (int i = 0; i < state.texcount; ++i) {
1924 state.texowners[i].w = -1;
1925 state.texowners[i].h = -1;
1926 state.texowners[i].slice = NULL;
1930 else if (!strncmp ("interrupt", p, 9)) {
1931 printd ("vmsg interrupted");
1933 else {
1934 errx (1, "unknown command %.*s", len, p);
1937 return 0;
1940 CAMLprim value ml_isexternallink (value uri_v)
1942 CAMLparam1 (uri_v);
1943 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1944 CAMLreturn (Val_bool (ext));
1947 CAMLprim value ml_uritolocation (value uri_v)
1949 CAMLparam1 (uri_v);
1950 CAMLlocal1 (ret_v);
1951 int pageno;
1952 fz_point xy;
1953 struct pagedim *pdim;
1955 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1956 &xy.x, &xy.y);
1957 pdim = pdimofpageno (pageno);
1958 fz_transform_point (&xy, &pdim->ctm);
1959 ret_v = caml_alloc_tuple (3);
1960 Field (ret_v, 0) = Val_int (pageno);
1961 Field (ret_v, 1) = caml_copy_double (xy.x);
1962 Field (ret_v, 2) = caml_copy_double (xy.y);
1963 CAMLreturn (ret_v);
1966 CAMLprim value ml_realloctexts (value texcount_v)
1968 CAMLparam1 (texcount_v);
1969 int ok;
1971 if (trylock (__func__)) {
1972 ok = 0;
1973 goto done;
1975 realloctexts (Int_val (texcount_v));
1976 ok = 1;
1977 unlock (__func__);
1979 done:
1980 CAMLreturn (Val_bool (ok));
1983 static void recti (int x0, int y0, int x1, int y1)
1985 GLfloat *v = state.vertices;
1987 glVertexPointer (2, GL_FLOAT, 0, v);
1988 v[0] = x0; v[1] = y0;
1989 v[2] = x1; v[3] = y0;
1990 v[4] = x0; v[5] = y1;
1991 v[6] = x1; v[7] = y1;
1992 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1995 static void showsel (struct page *page, int ox, int oy)
1997 fz_irect bbox;
1998 fz_rect rect;
1999 fz_stext_block *block;
2000 int seen = 0;
2001 unsigned char selcolor[] = {15,15,15,140};
2003 if (!page->fmark.ch || !page->lmark.ch) return;
2005 glEnable (GL_BLEND);
2006 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2007 glColor4ubv (selcolor);
2009 ox += state.pagedims[page->pdimno].bounds.x0;
2010 oy += state.pagedims[page->pdimno].bounds.y0;
2012 for (block = page->text->first_block; block; block = block->next) {
2013 fz_stext_line *line;
2015 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2016 for (line = block->u.t.first_line; line; line = line->next) {
2017 fz_stext_char *ch;
2019 rect = fz_empty_rect;
2020 for (ch = line->first_char; ch; ch = ch->next) {
2021 if (ch == page->fmark.ch) seen = 1;
2022 if (seen) fz_union_rect (&rect, &ch->bbox);
2023 if (ch == page->lmark.ch) {
2024 fz_round_rect (&bbox, &rect);
2025 recti (bbox.x0 + ox, bbox.y0 + oy,
2026 bbox.x1 + ox, bbox.y1 + oy);
2027 goto done;
2030 fz_round_rect (&bbox, &rect);
2031 recti (bbox.x0 + ox, bbox.y0 + oy,
2032 bbox.x1 + ox, bbox.y1 + oy);
2035 done:
2036 glDisable (GL_BLEND);
2039 #include "glfont.c"
2041 static void stipplerect (fz_matrix *m,
2042 fz_point *p1,
2043 fz_point *p2,
2044 fz_point *p3,
2045 fz_point *p4,
2046 GLfloat *texcoords,
2047 GLfloat *vertices)
2049 fz_transform_point (p1, m);
2050 fz_transform_point (p2, m);
2051 fz_transform_point (p3, m);
2052 fz_transform_point (p4, m);
2054 float w, h, s, t;
2056 w = p2->x - p1->x;
2057 h = p2->y - p1->y;
2058 t = hypotf (w, h) * .25f;
2060 w = p3->x - p2->x;
2061 h = p3->y - p2->y;
2062 s = hypotf (w, h) * .25f;
2064 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2065 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2067 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2068 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2070 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2071 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2073 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2074 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2076 glDrawArrays (GL_LINES, 0, 8);
2079 static void solidrect (fz_matrix *m,
2080 fz_point *p1,
2081 fz_point *p2,
2082 fz_point *p3,
2083 fz_point *p4,
2084 GLfloat *vertices)
2086 fz_transform_point (p1, m);
2087 fz_transform_point (p2, m);
2088 fz_transform_point (p3, m);
2089 fz_transform_point (p4, m);
2090 vertices[0] = p1->x; vertices[1] = p1->y;
2091 vertices[2] = p2->x; vertices[3] = p2->y;
2093 vertices[4] = p3->x; vertices[5] = p3->y;
2094 vertices[6] = p4->x; vertices[7] = p4->y;
2095 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2098 static void highlightlinks (struct page *page, int xoff, int yoff)
2100 fz_matrix ctm, tm, pm;
2101 fz_link *link, *links;
2102 GLfloat *texcoords = state.texcoords;
2103 GLfloat *vertices = state.vertices;
2105 links = fz_load_links (state.ctx, page->fzpage);
2107 glEnable (GL_TEXTURE_1D);
2108 glEnable (GL_BLEND);
2109 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2110 glBindTexture (GL_TEXTURE_1D, state.stid);
2112 xoff -= state.pagedims[page->pdimno].bounds.x0;
2113 yoff -= state.pagedims[page->pdimno].bounds.y0;
2114 fz_translate (&tm, xoff, yoff);
2115 pm = pagectm (page);
2116 fz_concat (&ctm, &pm, &tm);
2118 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2119 glVertexPointer (2, GL_FLOAT, 0, vertices);
2121 for (link = links; link; link = link->next) {
2122 fz_point p1, p2, p3, p4;
2124 p1.x = link->rect.x0;
2125 p1.y = link->rect.y0;
2127 p2.x = link->rect.x1;
2128 p2.y = link->rect.y0;
2130 p3.x = link->rect.x1;
2131 p3.y = link->rect.y1;
2133 p4.x = link->rect.x0;
2134 p4.y = link->rect.y1;
2136 /* TODO: different colours for different schemes */
2137 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2138 else glColor3ub (255, 0, 0);
2140 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2143 for (int i = 0; i < page->annotcount; ++i) {
2144 fz_point p1, p2, p3, p4;
2145 struct annot *annot = &page->annots[i];
2147 p1.x = annot->bbox.x0;
2148 p1.y = annot->bbox.y0;
2150 p2.x = annot->bbox.x1;
2151 p2.y = annot->bbox.y0;
2153 p3.x = annot->bbox.x1;
2154 p3.y = annot->bbox.y1;
2156 p4.x = annot->bbox.x0;
2157 p4.y = annot->bbox.y1;
2159 glColor3ub (0, 0, 128);
2160 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2163 glDisable (GL_BLEND);
2164 glDisable (GL_TEXTURE_1D);
2167 static int compareslinks (const void *l, const void *r)
2169 struct slink const *ls = l;
2170 struct slink const *rs = r;
2171 if (ls->bbox.y0 == rs->bbox.y0) {
2172 return rs->bbox.x0 - rs->bbox.x0;
2174 return ls->bbox.y0 - rs->bbox.y0;
2177 static void droptext (struct page *page)
2179 if (page->text) {
2180 fz_drop_stext_page (state.ctx, page->text);
2181 page->fmark.ch = NULL;
2182 page->lmark.ch = NULL;
2183 page->text = NULL;
2187 static void dropannots (struct page *page)
2189 if (page->annots) {
2190 free (page->annots);
2191 page->annots = NULL;
2192 page->annotcount = 0;
2196 static void ensureannots (struct page *page)
2198 int i, count = 0;
2199 size_t annotsize = sizeof (*page->annots);
2200 fz_annot *annot;
2202 if (state.gen != page->agen) {
2203 dropannots (page);
2204 page->agen = state.gen;
2206 if (page->annots) return;
2208 for (annot = fz_first_annot (state.ctx, page->fzpage);
2209 annot;
2210 annot = fz_next_annot (state.ctx, annot)) {
2211 count++;
2214 if (count > 0) {
2215 page->annotcount = count;
2216 page->annots = calloc (count, annotsize);
2217 if (!page->annots) {
2218 err (1, "calloc annots %d", count);
2221 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2222 annot;
2223 annot = fz_next_annot (state.ctx, annot), i++) {
2224 fz_rect rect;
2226 fz_bound_annot (state.ctx, annot, &rect);
2227 page->annots[i].annot = annot;
2228 fz_round_rect (&page->annots[i].bbox, &rect);
2233 static void dropslinks (struct page *page)
2235 if (page->slinks) {
2236 free (page->slinks);
2237 page->slinks = NULL;
2238 page->slinkcount = 0;
2242 static void ensureslinks (struct page *page)
2244 fz_matrix ctm;
2245 int i, count;
2246 size_t slinksize = sizeof (*page->slinks);
2247 fz_link *link, *links;
2249 ensureannots (page);
2250 if (state.gen != page->sgen) {
2251 dropslinks (page);
2252 page->sgen = state.gen;
2254 if (page->slinks) return;
2256 links = fz_load_links (state.ctx, page->fzpage);
2257 ctm = pagectm (page);
2259 count = page->annotcount;
2260 for (link = links; link; link = link->next) {
2261 count++;
2263 if (count > 0) {
2264 int j;
2266 page->slinkcount = count;
2267 page->slinks = calloc (count, slinksize);
2268 if (!page->slinks) {
2269 err (1, "calloc slinks %d", count);
2272 for (i = 0, link = links; link; ++i, link = link->next) {
2273 fz_rect rect;
2275 rect = link->rect;
2276 fz_transform_rect (&rect, &ctm);
2277 page->slinks[i].tag = SLINK;
2278 page->slinks[i].u.link = link;
2279 fz_round_rect (&page->slinks[i].bbox, &rect);
2281 for (j = 0; j < page->annotcount; ++j, ++i) {
2282 fz_rect rect;
2283 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2284 fz_transform_rect (&rect, &ctm);
2285 fz_round_rect (&page->slinks[i].bbox, &rect);
2287 page->slinks[i].tag = SANNOT;
2288 page->slinks[i].u.annot = page->annots[j].annot;
2290 qsort (page->slinks, count, slinksize, compareslinks);
2294 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2295 static void fmt_linkn (char *s, unsigned int u)
2297 unsigned int len; unsigned int q;
2298 unsigned int zma = 'z' - 'a' + 1;
2299 len = 1; q = u;
2300 while (q > zma - 1) { ++len; q /= zma; }
2301 if (s) {
2302 s += len;
2303 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2304 /* handles u == 0 */
2306 s[len] = 0;
2309 static void highlightslinks (struct page *page, int xoff, int yoff,
2310 int noff, char *targ, int tlen, int hfsize)
2312 char buf[40];
2313 struct slink *slink;
2314 double x0, y0, x1, y1, w;
2316 ensureslinks (page);
2317 glColor3ub (0xc3, 0xb0, 0x91);
2318 for (int i = 0; i < page->slinkcount; ++i) {
2319 fmt_linkn (buf, i + noff);
2320 if (!tlen || !strncmp (targ, buf, tlen)) {
2321 slink = &page->slinks[i];
2323 x0 = slink->bbox.x0 + xoff - 5;
2324 y1 = slink->bbox.y0 + yoff - 5;
2325 y0 = y1 + 10 + hfsize;
2326 w = measure_string (state.face, hfsize, buf);
2327 x1 = x0 + w + 10;
2328 recti (x0, y0, x1, y1);
2332 glEnable (GL_BLEND);
2333 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2334 glEnable (GL_TEXTURE_2D);
2335 glColor3ub (0, 0, 0);
2336 for (int i = 0; i < page->slinkcount; ++i) {
2337 fmt_linkn (buf, i + noff);
2338 if (!tlen || !strncmp (targ, buf, tlen)) {
2339 slink = &page->slinks[i];
2341 x0 = slink->bbox.x0 + xoff;
2342 y0 = slink->bbox.y0 + yoff + hfsize;
2343 draw_string (state.face, hfsize, x0, y0, buf);
2346 glDisable (GL_TEXTURE_2D);
2347 glDisable (GL_BLEND);
2350 static void uploadslice (struct tile *tile, struct slice *slice)
2352 int offset;
2353 struct slice *slice1;
2354 unsigned char *texdata;
2356 offset = 0;
2357 for (slice1 = tile->slices; slice != slice1; slice1++) {
2358 offset += slice1->h * tile->w * tile->pixmap->n;
2360 if (slice->texindex != -1 && slice->texindex < state.texcount
2361 && state.texowners[slice->texindex].slice == slice) {
2362 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2364 else {
2365 int subimage = 0;
2366 int texindex = state.texindex++ % state.texcount;
2368 if (state.texowners[texindex].w == tile->w) {
2369 if (state.texowners[texindex].h >= slice->h) {
2370 subimage = 1;
2372 else {
2373 state.texowners[texindex].h = slice->h;
2376 else {
2377 state.texowners[texindex].h = slice->h;
2380 state.texowners[texindex].w = tile->w;
2381 state.texowners[texindex].slice = slice;
2382 slice->texindex = texindex;
2384 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2385 #if TEXT_TYPE == GL_TEXTURE_2D
2386 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2387 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2388 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2389 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2390 #endif
2391 if (tile->pbo) {
2392 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2393 texdata = 0;
2395 else {
2396 texdata = tile->pixmap->samples;
2398 if (subimage) {
2399 glTexSubImage2D (TEXT_TYPE,
2403 tile->w,
2404 slice->h,
2405 state.texform,
2406 state.texty,
2407 texdata+offset
2410 else {
2411 glTexImage2D (TEXT_TYPE,
2413 state.texiform,
2414 tile->w,
2415 slice->h,
2417 state.texform,
2418 state.texty,
2419 texdata+offset
2422 if (tile->pbo) {
2423 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2428 CAMLprim void ml_begintiles (value unit_v)
2430 CAMLparam1 (unit_v);
2431 glEnable (TEXT_TYPE);
2432 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2433 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2434 CAMLreturn0;
2437 CAMLprim void ml_endtiles (value unit_v)
2439 CAMLparam1 (unit_v);
2440 glDisable (TEXT_TYPE);
2441 CAMLreturn0;
2444 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2446 CAMLparam2 (args_v, ptr_v);
2447 int dispx = Int_val (Field (args_v, 0));
2448 int dispy = Int_val (Field (args_v, 1));
2449 int dispw = Int_val (Field (args_v, 2));
2450 int disph = Int_val (Field (args_v, 3));
2451 int tilex = Int_val (Field (args_v, 4));
2452 int tiley = Int_val (Field (args_v, 5));
2453 char *s = String_val (ptr_v);
2454 struct tile *tile = parse_pointer (__func__, s);
2455 int slicey, firstslice;
2456 struct slice *slice;
2457 GLfloat *texcoords = state.texcoords;
2458 GLfloat *vertices = state.vertices;
2460 firstslice = tiley / tile->sliceheight;
2461 slice = &tile->slices[firstslice];
2462 slicey = tiley % tile->sliceheight;
2464 while (disph > 0) {
2465 int dh;
2467 dh = slice->h - slicey;
2468 dh = fz_mini (disph, dh);
2469 uploadslice (tile, slice);
2471 texcoords[0] = tilex; texcoords[1] = slicey;
2472 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2473 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2474 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2476 vertices[0] = dispx; vertices[1] = dispy;
2477 vertices[2] = dispx+dispw; vertices[3] = dispy;
2478 vertices[4] = dispx; vertices[5] = dispy+dh;
2479 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2481 #if TEXT_TYPE == GL_TEXTURE_2D
2482 for (int i = 0; i < 8; ++i) {
2483 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2485 #endif
2487 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2488 dispy += dh;
2489 disph -= dh;
2490 slice++;
2491 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2492 slicey = 0;
2494 CAMLreturn0;
2497 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2499 fz_matrix ctm, tm, pm;
2500 fz_point p1, p2, p3, p4;
2501 GLfloat *vertices = state.vertices;
2502 double *v = (double *) rects_v;
2504 xoff -= state.pagedims[page->pdimno].bounds.x0;
2505 yoff -= state.pagedims[page->pdimno].bounds.y0;
2506 fz_translate (&tm, xoff, yoff);
2507 pm = pagectm (page);
2508 fz_concat (&ctm, &pm, &tm);
2510 glEnable (GL_BLEND);
2511 glVertexPointer (2, GL_FLOAT, 0, vertices);
2513 glColor4dv (v);
2514 p1.x = v[4];
2515 p1.y = v[5];
2517 p2.x = v[6];
2518 p2.y = v[5];
2520 p3.x = v[6];
2521 p3.y = v[7];
2523 p4.x = v[4];
2524 p4.y = v[7];
2525 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2526 glDisable (GL_BLEND);
2529 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2530 value xoff_v, value yoff_v,
2531 value li_v)
2533 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2534 int xoff = Int_val (xoff_v);
2535 int yoff = Int_val (yoff_v);
2536 int noff = Int_val (Field (li_v, 0));
2537 char *targ = String_val (Field (li_v, 1));
2538 int tlen = caml_string_length (Field (li_v, 1));
2539 int hfsize = Int_val (Field (li_v, 2));
2540 char *s = String_val (ptr_v);
2541 int hlmask = Int_val (hlinks_v);
2542 struct page *page = parse_pointer (__func__, s);
2544 if (!page->fzpage) {
2545 /* deal with loadpage failed pages */
2546 goto done;
2549 if (trylock (__func__)) {
2550 noff = -1;
2551 goto done;
2554 ensureannots (page);
2555 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2556 if (hlmask & 2) {
2557 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2558 noff = page->slinkcount;
2560 if (page->tgen == state.gen) {
2561 showsel (page, xoff, yoff);
2563 unlock (__func__);
2565 done:
2566 CAMLreturn (Val_int (noff));
2569 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2570 value rects_v)
2572 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2573 int xoff = Int_val (xoff_v);
2574 int yoff = Int_val (yoff_v);
2575 char *s = String_val (ptr_v);
2576 struct page *page = parse_pointer (__func__, s);
2578 drawprect (page, xoff, yoff, rects_v);
2579 CAMLreturn0;
2582 static struct annot *getannot (struct page *page, int x, int y)
2584 fz_point p;
2585 fz_matrix ctm;
2586 const fz_matrix *tctm;
2587 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2589 if (!page->annots) return NULL;
2591 if (pdf) {
2592 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2593 tctm = &state.pagedims[page->pdimno].tctm;
2595 else {
2596 tctm = &fz_identity;
2599 p.x = x;
2600 p.y = y;
2602 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2603 fz_invert_matrix (&ctm, &ctm);
2604 fz_transform_point (&p, &ctm);
2606 if (pdf) {
2607 for (int i = 0; i < page->annotcount; ++i) {
2608 struct annot *a = &page->annots[i];
2609 fz_rect rect;
2611 fz_bound_annot (state.ctx, a->annot, &rect);
2612 if (p.x >= rect.x0 && p.x <= rect.x1) {
2613 if (p.y >= rect.y0 && p.y <= rect.y1)
2614 return a;
2618 return NULL;
2621 static fz_link *getlink (struct page *page, int x, int y)
2623 fz_point p;
2624 fz_matrix ctm;
2625 fz_link *link, *links;
2627 links = fz_load_links (state.ctx, page->fzpage);
2629 p.x = x;
2630 p.y = y;
2632 ctm = pagectm (page);
2633 fz_invert_matrix (&ctm, &ctm);
2634 fz_transform_point (&p, &ctm);
2636 for (link = links; link; link = link->next) {
2637 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2638 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2639 return link;
2643 return NULL;
2646 static void ensuretext (struct page *page)
2648 if (state.gen != page->tgen) {
2649 droptext (page);
2650 page->tgen = state.gen;
2652 if (!page->text) {
2653 fz_matrix ctm;
2654 fz_device *tdev;
2656 page->text = fz_new_stext_page (state.ctx,
2657 &state.pagedims[page->pdimno].mediabox);
2658 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2659 ctm = pagectm (page);
2660 fz_run_display_list (state.ctx, page->dlist,
2661 tdev, &ctm, &fz_infinite_rect, NULL);
2662 fz_close_device (state.ctx, tdev);
2663 fz_drop_device (state.ctx, tdev);
2667 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2669 CAMLparam2 (start_page_v, dir_v);
2670 CAMLlocal1 (ret_v);
2671 int i, dir = Int_val (dir_v);
2672 int start_page = Int_val (start_page_v);
2673 int end_page = dir > 0 ? state.pagecount : -1;
2674 pdf_document *pdf;
2676 fz_var (end_page);
2677 ret_v = Val_int (0);
2678 lock (__func__);
2679 pdf = pdf_specifics (state.ctx, state.doc);
2680 for (i = start_page + dir; i != end_page; i += dir) {
2681 int found;
2683 fz_var (found);
2684 if (pdf) {
2685 pdf_page *page = NULL;
2687 fz_var (page);
2688 fz_try (state.ctx) {
2689 page = pdf_load_page (state.ctx, pdf, i);
2690 found = !!page->links || !!page->annots;
2692 fz_catch (state.ctx) {
2693 found = 0;
2695 if (page) {
2696 fz_drop_page (state.ctx, &page->super);
2699 else {
2700 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2701 found = !!fz_load_links (state.ctx, page);
2702 fz_drop_page (state.ctx, page);
2705 if (found) {
2706 ret_v = caml_alloc_small (1, 1);
2707 Field (ret_v, 0) = Val_int (i);
2708 goto unlock;
2711 unlock:
2712 unlock (__func__);
2713 CAMLreturn (ret_v);
2716 enum { dir_first, dir_last };
2717 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2719 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2721 CAMLparam2 (ptr_v, dir_v);
2722 CAMLlocal2 (ret_v, pos_v);
2723 struct page *page;
2724 int dirtag, i, slinkindex;
2725 struct slink *found = NULL ,*slink;
2726 char *s = String_val (ptr_v);
2728 page = parse_pointer (__func__, s);
2729 ret_v = Val_int (0);
2730 lock (__func__);
2731 ensureslinks (page);
2733 if (Is_block (dir_v)) {
2734 dirtag = Tag_val (dir_v);
2735 switch (dirtag) {
2736 case dir_first_visible:
2738 int x0, y0, dir, first_index, last_index;
2740 pos_v = Field (dir_v, 0);
2741 x0 = Int_val (Field (pos_v, 0));
2742 y0 = Int_val (Field (pos_v, 1));
2743 dir = Int_val (Field (pos_v, 2));
2745 if (dir >= 0) {
2746 dir = 1;
2747 first_index = 0;
2748 last_index = page->slinkcount;
2750 else {
2751 first_index = page->slinkcount - 1;
2752 last_index = -1;
2755 for (i = first_index; i != last_index; i += dir) {
2756 slink = &page->slinks[i];
2757 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2758 found = slink;
2759 break;
2763 break;
2765 case dir_left:
2766 slinkindex = Int_val (Field (dir_v, 0));
2767 found = &page->slinks[slinkindex];
2768 for (i = slinkindex - 1; i >= 0; --i) {
2769 slink = &page->slinks[i];
2770 if (slink->bbox.x0 < found->bbox.x0) {
2771 found = slink;
2772 break;
2775 break;
2777 case dir_right:
2778 slinkindex = Int_val (Field (dir_v, 0));
2779 found = &page->slinks[slinkindex];
2780 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2781 slink = &page->slinks[i];
2782 if (slink->bbox.x0 > found->bbox.x0) {
2783 found = slink;
2784 break;
2787 break;
2789 case dir_down:
2790 slinkindex = Int_val (Field (dir_v, 0));
2791 found = &page->slinks[slinkindex];
2792 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2793 slink = &page->slinks[i];
2794 if (slink->bbox.y0 >= found->bbox.y0) {
2795 found = slink;
2796 break;
2799 break;
2801 case dir_up:
2802 slinkindex = Int_val (Field (dir_v, 0));
2803 found = &page->slinks[slinkindex];
2804 for (i = slinkindex - 1; i >= 0; --i) {
2805 slink = &page->slinks[i];
2806 if (slink->bbox.y0 <= found->bbox.y0) {
2807 found = slink;
2808 break;
2811 break;
2814 else {
2815 dirtag = Int_val (dir_v);
2816 switch (dirtag) {
2817 case dir_first:
2818 found = page->slinks;
2819 break;
2821 case dir_last:
2822 if (page->slinks) {
2823 found = page->slinks + (page->slinkcount - 1);
2825 break;
2828 if (found) {
2829 ret_v = caml_alloc_small (2, 1);
2830 Field (ret_v, 0) = Val_int (found - page->slinks);
2833 unlock (__func__);
2834 CAMLreturn (ret_v);
2837 enum { uuri, utext, uannot };
2839 CAMLprim value ml_getlink (value ptr_v, value n_v)
2841 CAMLparam2 (ptr_v, n_v);
2842 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2843 fz_link *link;
2844 struct page *page;
2845 char *s = String_val (ptr_v);
2846 struct slink *slink;
2848 ret_v = Val_int (0);
2849 page = parse_pointer (__func__, s);
2851 lock (__func__);
2852 ensureslinks (page);
2853 slink = &page->slinks[Int_val (n_v)];
2854 if (slink->tag == SLINK) {
2855 link = slink->u.link;
2856 str_v = caml_copy_string (link->uri);
2857 ret_v = caml_alloc_small (1, uuri);
2858 Field (ret_v, 0) = str_v;
2860 else {
2861 ret_v = caml_alloc_small (1, uannot);
2862 tup_v = caml_alloc_tuple (2);
2863 Field (ret_v, 0) = tup_v;
2864 Field (tup_v, 0) = ptr_v;
2865 Field (tup_v, 1) = n_v;
2867 unlock (__func__);
2869 CAMLreturn (ret_v);
2872 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2874 CAMLparam2 (ptr_v, n_v);
2875 pdf_document *pdf;
2876 const char *contents = "";
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_annot_contents (state.ctx,
2888 (pdf_annot *) slink->u.annot);
2890 unlock (__func__);
2891 CAMLreturn (caml_copy_string (contents));
2894 CAMLprim value ml_getlinkcount (value ptr_v)
2896 CAMLparam1 (ptr_v);
2897 struct page *page;
2898 char *s = String_val (ptr_v);
2900 page = parse_pointer (__func__, s);
2901 CAMLreturn (Val_int (page->slinkcount));
2904 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2906 CAMLparam2 (ptr_v, n_v);
2907 CAMLlocal1 (ret_v);
2908 struct page *page;
2909 struct slink *slink;
2910 char *s = String_val (ptr_v);
2912 page = parse_pointer (__func__, s);
2913 ret_v = caml_alloc_tuple (4);
2914 lock (__func__);
2915 ensureslinks (page);
2917 slink = &page->slinks[Int_val (n_v)];
2918 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2919 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2920 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2921 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2922 unlock (__func__);
2923 CAMLreturn (ret_v);
2926 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2928 CAMLparam3 (ptr_v, x_v, y_v);
2929 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2930 fz_link *link;
2931 struct annot *annot;
2932 struct page *page;
2933 char *ptr = String_val (ptr_v);
2934 int x = Int_val (x_v), y = Int_val (y_v);
2935 struct pagedim *pdim;
2937 ret_v = Val_int (0);
2938 if (trylock (__func__)) {
2939 goto done;
2942 page = parse_pointer (__func__, ptr);
2943 pdim = &state.pagedims[page->pdimno];
2944 x += pdim->bounds.x0;
2945 y += pdim->bounds.y0;
2948 annot = getannot (page, x, y);
2949 if (annot) {
2950 int i, n = -1;
2952 ensureslinks (page);
2953 for (i = 0; i < page->slinkcount; ++i) {
2954 if (page->slinks[i].tag == SANNOT
2955 && page->slinks[i].u.annot == annot->annot) {
2956 n = i;
2957 break;
2960 ret_v = caml_alloc_small (1, uannot);
2961 tup_v = caml_alloc_tuple (2);
2962 Field (ret_v, 0) = tup_v;
2963 Field (tup_v, 0) = ptr_v;
2964 Field (tup_v, 1) = Val_int (n);
2965 goto unlock;
2969 link = getlink (page, x, y);
2970 if (link) {
2971 str_v = caml_copy_string (link->uri);
2972 ret_v = caml_alloc_small (1, uuri);
2973 Field (ret_v, 0) = str_v;
2975 else {
2976 fz_rect *b;
2977 fz_stext_block *block;
2979 ensuretext (page);
2981 for (block = page->text->first_block; block; block = block->next) {
2982 fz_stext_line *line;
2984 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2985 b = &block->bbox;
2986 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2987 continue;
2989 for (line = block->u.t.first_line; line; line = line->next) {
2990 fz_stext_char *ch;
2992 b = &line->bbox;
2993 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2994 continue;
2996 for (ch = line->first_char; ch; ch = ch->next) {
2997 fz_rect bbox;
2998 bbox = ch->bbox;
2999 /* fz_stext_char_bbox (state.ctx, &bbox, line, ch); */
3000 b = &bbox;
3002 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3003 const char *n2 = fz_font_name (state.ctx, ch->font);
3004 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3005 ch->font);
3007 if (!n2) n2 = "<unknown font>";
3009 if (face && face->family_name) {
3010 char *s;
3011 char *n1 = face->family_name;
3012 size_t l1 = strlen (n1);
3013 size_t l2 = strlen (n2);
3015 if (l1 != l2 || memcmp (n1, n2, l1)) {
3016 s = malloc (l1 + l2 + 2);
3017 if (s) {
3018 memcpy (s, n2, l2);
3019 s[l2] = '=';
3020 memcpy (s + l2 + 1, n1, l1 + 1);
3021 str_v = caml_copy_string (s);
3022 free (s);
3026 if (str_v == Val_unit) {
3027 str_v = caml_copy_string (n2);
3029 ret_v = caml_alloc_small (1, utext);
3030 Field (ret_v, 0) = str_v;
3031 goto unlock;
3037 unlock:
3038 unlock (__func__);
3040 done:
3041 CAMLreturn (ret_v);
3044 enum { mark_page, mark_block, mark_line, mark_word };
3046 static int uninteresting (int c)
3048 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3049 || ispunct (c);
3052 CAMLprim void ml_clearmark (value ptr_v)
3054 CAMLparam1 (ptr_v);
3055 char *s = String_val (ptr_v);
3056 struct page *page;
3058 if (trylock (__func__)) {
3059 goto done;
3062 page = parse_pointer (__func__, s);
3063 page->fmark.ch = NULL;
3064 page->lmark.ch = NULL;
3066 unlock (__func__);
3067 done:
3068 CAMLreturn0;
3071 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3073 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3074 CAMLlocal1 (ret_v);
3075 fz_rect *b;
3076 struct page *page;
3077 fz_stext_line *line;
3078 fz_stext_block *block;
3079 struct pagedim *pdim;
3080 int mark = Int_val (mark_v);
3081 char *s = String_val (ptr_v);
3082 int x = Int_val (x_v), y = Int_val (y_v);
3084 ret_v = Val_bool (0);
3085 if (trylock (__func__)) {
3086 goto done;
3089 page = parse_pointer (__func__, s);
3090 pdim = &state.pagedims[page->pdimno];
3092 ensuretext (page);
3094 if (mark == mark_page) {
3095 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3096 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3097 ret_v = Val_bool (1);
3098 goto unlock;
3101 x += pdim->bounds.x0;
3102 y += pdim->bounds.y0;
3104 for (block = page->text->first_block; block; block = block->next) {
3105 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3106 b = &block->bbox;
3107 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3108 continue;
3110 if (mark == mark_block) {
3111 page->fmark.ch = block->u.t.first_line->first_char;
3112 page->lmark.ch = block->u.t.last_line->last_char;
3113 ret_v = Val_bool (1);
3114 goto unlock;
3117 for (line = block->u.t.first_line; line; line = line->next) {
3118 fz_stext_char *ch;
3120 b = &line->bbox;
3121 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3122 continue;
3124 if (mark == mark_line) {
3125 page->fmark.ch = line->first_char;
3126 page->lmark.ch = line->last_char;
3127 ret_v = Val_bool (1);
3128 goto unlock;
3131 for (ch = line->first_char; ch; ch = ch->next) {
3132 fz_stext_char *ch2, *first = NULL, *last = NULL;
3133 b = &ch->bbox;
3134 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3135 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3136 if (uninteresting (ch2->c)) first = NULL;
3137 else if (!first) first = ch2;
3139 for (ch2 = ch; ch2; ch2 = ch2->next) {
3140 if (uninteresting (ch2->c)) break;
3141 last = ch2;
3144 page->fmark.ch = first;
3145 page->lmark.ch = last;
3146 ret_v = Val_bool (1);
3147 goto unlock;
3152 unlock:
3153 if (!Bool_val (ret_v)) {
3154 page->fmark.ch = NULL;
3155 page->lmark.ch = NULL;
3157 unlock (__func__);
3159 done:
3160 CAMLreturn (ret_v);
3163 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3165 CAMLparam3 (ptr_v, x_v, y_v);
3166 CAMLlocal2 (ret_v, res_v);
3167 fz_rect *b = NULL;
3168 struct page *page;
3169 struct pagedim *pdim;
3170 fz_stext_block *block;
3171 char *s = String_val (ptr_v);
3172 int x = Int_val (x_v), y = Int_val (y_v);
3174 ret_v = Val_int (0);
3175 if (trylock (__func__)) {
3176 goto done;
3179 page = parse_pointer (__func__, s);
3180 pdim = &state.pagedims[page->pdimno];
3181 x += pdim->bounds.x0;
3182 y += pdim->bounds.y0;
3184 ensuretext (page);
3186 for (block = page->text->first_block; block; block = block->next) {
3187 switch (block->type) {
3188 case FZ_STEXT_BLOCK_TEXT:
3189 b = &block->bbox;
3190 break;
3192 case FZ_STEXT_BLOCK_IMAGE:
3193 b = &block->bbox;
3194 break;
3196 default:
3197 continue;
3200 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3201 break;
3202 b = NULL;
3204 if (b) {
3205 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3206 ret_v = caml_alloc_small (1, 1);
3207 Store_double_field (res_v, 0, b->x0);
3208 Store_double_field (res_v, 1, b->x1);
3209 Store_double_field (res_v, 2, b->y0);
3210 Store_double_field (res_v, 3, b->y1);
3211 Field (ret_v, 0) = res_v;
3213 unlock (__func__);
3215 done:
3216 CAMLreturn (ret_v);
3219 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3221 CAMLparam2 (ptr_v, rect_v);
3222 fz_rect b;
3223 struct page *page;
3224 struct pagedim *pdim;
3225 char *s = String_val (ptr_v);
3226 int x0, x1, y0, y1;
3227 fz_stext_char *ch;
3228 fz_stext_line *line;
3229 fz_stext_block *block;
3230 fz_stext_char *fc, *lc;
3232 if (trylock (__func__)) {
3233 goto done;
3236 page = parse_pointer (__func__, s);
3237 ensuretext (page);
3239 pdim = &state.pagedims[page->pdimno];
3240 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3241 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3242 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3243 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3245 if (y0 > y1) {
3246 int t = y0;
3247 y0 = y1;
3248 y1 = t;
3249 x0 = x1;
3250 x1 = t;
3253 fc = page->fmark.ch;
3254 lc = page->lmark.ch;
3256 for (block = page->text->first_block; block; block = block->next) {
3257 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3258 for (line = block->u.t.first_line; line; line = line->next) {
3259 for (ch = line->first_char; ch; ch = ch->next) {
3260 b = ch->bbox;
3261 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3262 fc = ch;
3264 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3265 lc = ch;
3270 if (x1 < x0 && fc == lc) {
3271 fz_stext_char *t;
3273 t = fc;
3274 fc = lc;
3275 lc = t;
3278 page->fmark.ch = fc;
3279 page->lmark.ch = lc;
3281 unlock (__func__);
3283 done:
3284 CAMLreturn0;
3287 static int pipechar (FILE *f, fz_stext_char *ch)
3289 char buf[4];
3290 int len, ret;
3292 len = fz_runetochar (buf, ch->c);
3293 ret = fwrite (buf, len, 1, f);
3294 if (ret != 1) {
3295 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3296 len, ret, strerror (errno));
3297 return -1;
3299 return 0;
3302 #ifdef __CYGWIN__
3303 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3305 caml_failwith ("ml_popen not implemented under Cygwin");
3307 #else
3308 CAMLprim value ml_spawn (value command_v, value fds_v)
3310 CAMLparam2 (command_v, fds_v);
3311 CAMLlocal2 (l_v, tup_v);
3312 int ret, ret1;
3313 pid_t pid;
3314 char *msg = NULL;
3315 value earg_v = Nothing;
3316 posix_spawnattr_t attr;
3317 posix_spawn_file_actions_t fa;
3318 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3320 argv[2] = String_val (command_v);
3322 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3323 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3326 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3327 msg = "posix_spawnattr_init";
3328 goto fail1;
3331 #ifdef POSIX_SPAWN_USEVFORK
3332 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3333 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3334 goto fail;
3336 #endif
3338 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3339 int fd1, fd2;
3341 tup_v = Field (l_v, 0);
3342 fd1 = Int_val (Field (tup_v, 0));
3343 fd2 = Int_val (Field (tup_v, 1));
3344 if (fd2 < 0) {
3345 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3346 msg = "posix_spawn_file_actions_addclose";
3347 earg_v = tup_v;
3348 goto fail;
3351 else {
3352 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3353 msg = "posix_spawn_file_actions_adddup2";
3354 earg_v = tup_v;
3355 goto fail;
3360 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3361 msg = "posix_spawn";
3362 goto fail;
3365 fail:
3366 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3367 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3370 fail1:
3371 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3372 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3373 strerror (ret1));
3376 if (msg)
3377 unix_error (ret, msg, earg_v);
3379 CAMLreturn (Val_int (pid));
3381 #endif
3383 CAMLprim value ml_hassel (value ptr_v)
3385 CAMLparam1 (ptr_v);
3386 CAMLlocal1 (ret_v);
3387 struct page *page;
3388 char *s = String_val (ptr_v);
3390 ret_v = Val_bool (0);
3391 if (trylock (__func__)) {
3392 goto done;
3395 page = parse_pointer (__func__, s);
3396 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3397 unlock (__func__);
3398 done:
3399 CAMLreturn (ret_v);
3402 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3404 CAMLparam2 (fd_v, ptr_v);
3405 FILE *f;
3406 int seen = 0;
3407 struct page *page;
3408 fz_stext_line *line;
3409 fz_stext_block *block;
3410 int fd = Int_val (fd_v);
3411 char *s = String_val (ptr_v);
3413 if (trylock (__func__)) {
3414 goto done;
3417 page = parse_pointer (__func__, s);
3419 if (!page->fmark.ch || !page->lmark.ch) {
3420 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3421 goto unlock;
3424 f = fdopen (fd, "w");
3425 if (!f) {
3426 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3427 fd, strerror (errno));
3428 f = stdout;
3431 for (block = page->text->first_block; block; block = block->next) {
3432 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3433 for (line = block->u.t.first_line; line; line = line->next) {
3434 fz_stext_char *ch;
3435 for (ch = line->first_char; ch; ch = ch->next) {
3436 if (seen || ch == page->fmark.ch) {
3437 do {
3438 pipechar (f, ch);
3439 if (ch == page->lmark.ch) goto close;
3440 } while ((ch = ch->next));
3441 seen = 1;
3442 break;
3445 if (seen) fputc ('\n', f);
3448 close:
3449 if (f != stdout) {
3450 int ret = fclose (f);
3451 fd = -1;
3452 if (ret == -1) {
3453 if (errno != ECHILD) {
3454 fprintf (stderr, "failed to close sel pipe: %s\n",
3455 strerror (errno));
3459 unlock:
3460 unlock (__func__);
3462 done:
3463 if (fd >= 0) {
3464 if (close (fd)) {
3465 fprintf (stderr, "failed to close sel pipe: %s\n",
3466 strerror (errno));
3469 CAMLreturn0;
3472 CAMLprim value ml_getpdimrect (value pagedimno_v)
3474 CAMLparam1 (pagedimno_v);
3475 CAMLlocal1 (ret_v);
3476 int pagedimno = Int_val (pagedimno_v);
3477 fz_rect box;
3479 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3480 if (trylock (__func__)) {
3481 box = fz_empty_rect;
3483 else {
3484 box = state.pagedims[pagedimno].mediabox;
3485 unlock (__func__);
3488 Store_double_field (ret_v, 0, box.x0);
3489 Store_double_field (ret_v, 1, box.x1);
3490 Store_double_field (ret_v, 2, box.y0);
3491 Store_double_field (ret_v, 3, box.y1);
3493 CAMLreturn (ret_v);
3496 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3497 value dw_v, value cols_v)
3499 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3500 CAMLlocal1 (ret_v);
3501 int i;
3502 double zoom = -1.;
3503 double maxh = 0.0;
3504 struct pagedim *p;
3505 double winw = Int_val (winw_v);
3506 double winh = Int_val (winh_v);
3507 double dw = Int_val (dw_v);
3508 double cols = Int_val (cols_v);
3509 double pw = 1.0, ph = 1.0;
3511 if (trylock (__func__)) {
3512 goto done;
3515 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3516 double w = p->pagebox.x1 / cols;
3517 double h = p->pagebox.y1;
3518 if (h > maxh) {
3519 maxh = h;
3520 ph = h;
3521 if (state.fitmodel != FitProportional) pw = w;
3523 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3526 zoom = (((winh / ph) * pw) + dw) / winw;
3527 unlock (__func__);
3528 done:
3529 ret_v = caml_copy_double (zoom);
3530 CAMLreturn (ret_v);
3533 CAMLprim value ml_getmaxw (value unit_v)
3535 CAMLparam1 (unit_v);
3536 CAMLlocal1 (ret_v);
3537 int i;
3538 double maxw = -1.;
3539 struct pagedim *p;
3541 if (trylock (__func__)) {
3542 goto done;
3545 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3546 double w = p->pagebox.x1;
3547 maxw = fz_max (maxw, w);
3550 unlock (__func__);
3551 done:
3552 ret_v = caml_copy_double (maxw);
3553 CAMLreturn (ret_v);
3556 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3558 CAMLparam4 (pt_v, x_v, y_v, string_v);
3559 CAMLlocal1 (ret_v);
3560 int pt = Int_val(pt_v);
3561 int x = Int_val (x_v);
3562 int y = Int_val (y_v);
3563 double w;
3565 w = draw_string (state.face, pt, x, y, String_val (string_v));
3566 ret_v = caml_copy_double (w);
3567 CAMLreturn (ret_v);
3570 CAMLprim value ml_measure_string (value pt_v, value string_v)
3572 CAMLparam2 (pt_v, string_v);
3573 CAMLlocal1 (ret_v);
3574 int pt = Int_val (pt_v);
3575 double w;
3577 w = measure_string (state.face, pt, String_val (string_v));
3578 ret_v = caml_copy_double (w);
3579 CAMLreturn (ret_v);
3582 CAMLprim value ml_getpagebox (value opaque_v)
3584 CAMLparam1 (opaque_v);
3585 CAMLlocal1 (ret_v);
3586 fz_rect rect;
3587 fz_irect bbox;
3588 fz_matrix ctm;
3589 fz_device *dev;
3590 char *s = String_val (opaque_v);
3591 struct page *page = parse_pointer (__func__, s);
3593 ret_v = caml_alloc_tuple (4);
3594 dev = fz_new_bbox_device (state.ctx, &rect);
3596 ctm = pagectm (page);
3597 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3599 fz_close_device (state.ctx, dev);
3600 fz_drop_device (state.ctx, dev);
3601 fz_round_rect (&bbox, &rect);
3602 Field (ret_v, 0) = Val_int (bbox.x0);
3603 Field (ret_v, 1) = Val_int (bbox.y0);
3604 Field (ret_v, 2) = Val_int (bbox.x1);
3605 Field (ret_v, 3) = Val_int (bbox.y1);
3607 CAMLreturn (ret_v);
3610 CAMLprim void ml_setaalevel (value level_v)
3612 CAMLparam1 (level_v);
3614 state.aalevel = Int_val (level_v);
3615 CAMLreturn0;
3618 #ifndef __COCOA__
3619 #pragma GCC diagnostic push
3620 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3621 #include <X11/Xlib.h>
3622 #include <X11/cursorfont.h>
3623 #pragma GCC diagnostic pop
3625 #ifdef USE_EGL
3626 #include <EGL/egl.h>
3627 #else
3628 #include <GL/glx.h>
3629 #endif
3631 static const int shapes[] = {
3632 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3635 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3637 static struct {
3638 Window wid;
3639 Display *dpy;
3640 #ifdef USE_EGL
3641 EGLContext ctx;
3642 EGLConfig conf;
3643 EGLSurface win;
3644 EGLDisplay *edpy;
3645 #else
3646 GLXContext ctx;
3647 #endif
3648 XVisualInfo *visual;
3649 Cursor curs[CURS_COUNT];
3650 } glx;
3653 static void initcurs (void)
3655 for (size_t n = 0; n < CURS_COUNT; ++n) {
3656 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3660 CAMLprim void ml_setbgcol (value color_v)
3662 CAMLparam1 (color_v);
3663 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3664 CAMLreturn0;
3667 #ifdef USE_EGL
3668 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3670 CAMLparam3 (display_v, wid_v, screen_v);
3671 int major, minor;
3672 int num_conf;
3673 EGLint visid;
3674 EGLint attribs[] = {
3675 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3676 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3677 EGL_NONE
3679 EGLConfig conf;
3681 glx.dpy = XOpenDisplay (String_val (display_v));
3682 if (!glx.dpy) {
3683 caml_failwith ("XOpenDisplay");
3686 eglBindAPI (EGL_OPENGL_API);
3688 glx.edpy = eglGetDisplay (glx.dpy);
3689 if (glx.edpy == EGL_NO_DISPLAY) {
3690 caml_failwith ("eglGetDisplay");
3693 if (!eglInitialize (glx.edpy, &major, &minor)) {
3694 caml_failwith ("eglInitialize");
3697 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3698 !num_conf) {
3699 caml_failwith ("eglChooseConfig");
3702 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3703 caml_failwith ("eglGetConfigAttrib");
3706 glx.conf = conf;
3707 initcurs ();
3709 glx.wid = Int_val (wid_v);
3710 CAMLreturn (Val_int (visid));
3713 CAMLprim void ml_glxcompleteinit (value unit_v)
3715 CAMLparam1 (unit_v);
3717 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3718 if (!glx.ctx) {
3719 caml_failwith ("eglCreateContext");
3722 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3723 glx.wid, NULL);
3724 if (glx.win == EGL_NO_SURFACE) {
3725 caml_failwith ("eglCreateWindowSurface");
3728 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3729 glx.ctx = NULL;
3730 caml_failwith ("eglMakeCurrent");
3732 CAMLreturn0;
3734 #else
3735 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3737 CAMLparam3 (display_v, wid_v, screen_v);
3739 glx.dpy = XOpenDisplay (String_val (display_v));
3740 if (!glx.dpy) {
3741 caml_failwith ("XOpenDisplay");
3744 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3745 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3746 if (!glx.visual) {
3747 XCloseDisplay (glx.dpy);
3748 caml_failwith ("glXChooseVisual");
3751 initcurs ();
3753 glx.wid = Int_val (wid_v);
3754 CAMLreturn (Val_int (glx.visual->visualid));
3757 CAMLprim void ml_glxcompleteinit (value unit_v)
3759 CAMLparam1 (unit_v);
3761 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3762 if (!glx.ctx) {
3763 caml_failwith ("glXCreateContext");
3766 XFree (glx.visual);
3767 glx.visual = NULL;
3769 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3770 glXDestroyContext (glx.dpy, glx.ctx);
3771 glx.ctx = NULL;
3772 caml_failwith ("glXMakeCurrent");
3774 CAMLreturn0;
3776 #endif
3778 CAMLprim void ml_setcursor (value cursor_v)
3780 CAMLparam1 (cursor_v);
3781 size_t cursn = Int_val (cursor_v);
3783 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3784 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3785 XFlush (glx.dpy);
3786 CAMLreturn0;
3789 CAMLprim void ml_swapb (value unit_v)
3791 CAMLparam1 (unit_v);
3792 #ifdef USE_EGL
3793 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3794 caml_failwith ("eglSwapBuffers");
3796 #else
3797 glXSwapBuffers (glx.dpy, glx.wid);
3798 #endif
3799 CAMLreturn0;
3802 #include "keysym2ucs.c"
3804 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3806 CAMLparam1 (keysym_v);
3807 CAMLlocal1 (str_v);
3808 KeySym keysym = Int_val (keysym_v);
3809 Rune rune;
3810 int len;
3811 char buf[5];
3813 rune = keysym2ucs (keysym);
3814 len = fz_runetochar (buf, rune);
3815 buf[len] = 0;
3816 str_v = caml_copy_string (buf);
3817 CAMLreturn (str_v);
3819 #else
3820 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3822 CAMLparam1 (keysym_v);
3823 CAMLlocal1 (str_v);
3824 long ucs_v = Long_val (keysym_v);
3825 int len;
3826 char buf[5];
3828 len = fz_runetochar (buf, ucs_v);
3829 buf[len] = 0;
3830 str_v = caml_copy_string (buf);
3831 CAMLreturn (str_v);
3833 #endif
3835 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3837 CAMLprim value ml_platform (value unit_v)
3839 CAMLparam1 (unit_v);
3840 CAMLlocal2 (tup_v, arr_v);
3841 int platid = piunknown;
3842 struct utsname buf;
3844 #if defined __linux__
3845 platid = pilinux;
3846 #elif defined __CYGWIN__
3847 platid = picygwin;
3848 #elif defined __DragonFly__ || defined __FreeBSD__
3849 || defined __OpenBSD__ || defined __NetBSD__
3850 platid = pibsd;
3851 #elif defined __sun__
3852 platid = pisun;
3853 #elif defined __APPLE__
3854 platid = piosx;
3855 #endif
3856 if (uname (&buf)) err (1, "uname");
3858 tup_v = caml_alloc_tuple (2);
3860 char const *sar[] = {
3861 buf.sysname,
3862 buf.release,
3863 buf.version,
3864 buf.machine,
3865 NULL
3867 arr_v = caml_copy_string_array (sar);
3869 Field (tup_v, 0) = Val_int (platid);
3870 Field (tup_v, 1) = arr_v;
3871 CAMLreturn (tup_v);
3874 CAMLprim void ml_cloexec (value fd_v)
3876 CAMLparam1 (fd_v);
3877 int fd = Int_val (fd_v);
3879 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3880 uerror ("fcntl", Nothing);
3882 CAMLreturn0;
3885 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3887 CAMLparam2 (w_v, h_v);
3888 CAMLlocal1 (ret_v);
3889 struct bo *pbo;
3890 int w = Int_val (w_v);
3891 int h = Int_val (h_v);
3892 int cs = Int_val (cs_v);
3894 if (state.bo_usable) {
3895 pbo = calloc (sizeof (*pbo), 1);
3896 if (!pbo) {
3897 err (1, "calloc pbo");
3900 switch (cs) {
3901 case 0:
3902 case 1:
3903 pbo->size = w*h*4;
3904 break;
3905 case 2:
3906 pbo->size = w*h*2;
3907 break;
3908 default:
3909 errx (1, "%s: invalid colorspace %d", __func__, cs);
3912 state.glGenBuffersARB (1, &pbo->id);
3913 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3914 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3915 NULL, GL_STREAM_DRAW);
3916 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3917 GL_READ_WRITE);
3918 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3919 if (!pbo->ptr) {
3920 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3921 state.glDeleteBuffersARB (1, &pbo->id);
3922 free (pbo);
3923 ret_v = caml_copy_string ("0");
3925 else {
3926 int res;
3927 char *s;
3929 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3930 if (res < 0) {
3931 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3933 s = malloc (res+1);
3934 if (!s) {
3935 err (1, "malloc %d bytes failed", res+1);
3937 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3938 if (res < 0) {
3939 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3941 ret_v = caml_copy_string (s);
3942 free (s);
3945 else {
3946 ret_v = caml_copy_string ("0");
3948 CAMLreturn (ret_v);
3951 CAMLprim void ml_freepbo (value s_v)
3953 CAMLparam1 (s_v);
3954 char *s = String_val (s_v);
3955 struct tile *tile = parse_pointer (__func__, s);
3957 if (tile->pbo) {
3958 state.glDeleteBuffersARB (1, &tile->pbo->id);
3959 tile->pbo->id = -1;
3960 tile->pbo->ptr = NULL;
3961 tile->pbo->size = -1;
3963 CAMLreturn0;
3966 CAMLprim void ml_unmappbo (value s_v)
3968 CAMLparam1 (s_v);
3969 char *s = String_val (s_v);
3970 struct tile *tile = parse_pointer (__func__, s);
3972 if (tile->pbo) {
3973 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3974 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3975 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3977 tile->pbo->ptr = NULL;
3978 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3980 CAMLreturn0;
3983 static void setuppbo (void)
3985 #ifdef __COCOA__
3986 static CFBundleRef framework = NULL;
3987 if (framework == NULL)
3988 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3989 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3990 #else
3991 #ifdef USE_EGL
3992 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
3993 #else
3994 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
3995 #endif
3996 state.bo_usable = GGPA (glBindBufferARB)
3997 && GGPA (glUnmapBufferARB)
3998 && GGPA (glMapBufferARB)
3999 && GGPA (glBufferDataARB)
4000 && GGPA (glGenBuffersARB)
4001 && GGPA (glDeleteBuffersARB);
4002 #endif
4003 #undef GGPA
4006 CAMLprim value ml_bo_usable (value unit_v)
4008 CAMLparam1 (unit_v);
4009 CAMLreturn (Val_bool (state.bo_usable));
4012 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4014 CAMLparam3 (ptr_v, x_v, y_v);
4015 CAMLlocal2 (ret_v, tup_v);
4016 struct page *page;
4017 char *s = String_val (ptr_v);
4018 int x = Int_val (x_v), y = Int_val (y_v);
4019 struct pagedim *pdim;
4020 fz_point p;
4021 fz_matrix ctm;
4023 page = parse_pointer (__func__, s);
4024 pdim = &state.pagedims[page->pdimno];
4026 ret_v = Val_int (0);
4027 if (trylock (__func__)) {
4028 goto done;
4031 if (pdf_specifics (state.ctx, state.doc)) {
4032 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4033 ctm = state.pagedims[page->pdimno].tctm;
4035 else {
4036 ctm = fz_identity;
4038 p.x = x + pdim->bounds.x0;
4039 p.y = y + pdim->bounds.y0;
4041 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4042 fz_invert_matrix (&ctm, &ctm);
4043 fz_transform_point (&p, &ctm);
4045 tup_v = caml_alloc_tuple (2);
4046 ret_v = caml_alloc_small (1, 1);
4047 Field (tup_v, 0) = Val_int (p.x);
4048 Field (tup_v, 1) = Val_int (p.y);
4049 Field (ret_v, 0) = tup_v;
4051 unlock (__func__);
4052 done:
4053 CAMLreturn (ret_v);
4056 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4057 value x_v, value y_v)
4059 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4060 CAMLlocal1 (ret_v);
4061 struct page *page;
4062 char *s = String_val (ptr_v);
4063 int pageno = Int_val (pageno_v);
4064 int pdimno = Int_val (pdimno_v);
4065 double x = Double_val (x_v), y = Double_val (y_v);
4066 struct pagedim *pdim;
4067 fz_point p;
4068 fz_matrix ctm;
4070 ret_v = Val_int (0);
4071 lock (__func__);
4073 if (!*s) {
4074 page = loadpage (pageno, pdimno);
4076 else {
4077 page = parse_pointer (__func__, s);
4079 pdim = &state.pagedims[pdimno];
4081 if (pdf_specifics (state.ctx, state.doc)) {
4082 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4083 ctm = state.pagedims[page->pdimno].tctm;
4085 else {
4086 ctm = fz_identity;
4088 p.x = x + pdim->bounds.x0;
4089 p.y = y + pdim->bounds.y0;
4091 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4092 fz_transform_point (&p, &ctm);
4094 ret_v = caml_alloc_tuple (2);
4095 Field (ret_v, 0) = caml_copy_double (p.x);
4096 Field (ret_v, 1) = caml_copy_double (p.y);
4098 if (!*s) {
4099 freepage (page);
4101 unlock (__func__);
4102 CAMLreturn (ret_v);
4105 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4106 value contents_v)
4108 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4109 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4111 if (pdf) {
4112 pdf_annot *annot;
4113 struct page *page;
4114 fz_point p;
4115 char *s = String_val (ptr_v);
4117 page = parse_pointer (__func__, s);
4118 annot = pdf_create_annot (state.ctx,
4119 pdf_page_from_fz_page (state.ctx,
4120 page->fzpage),
4121 PDF_ANNOT_TEXT);
4122 p.x = Int_val (x_v);
4123 p.y = Int_val (y_v);
4124 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4125 pdf_set_text_annot_position (state.ctx, annot, p);
4126 state.dirty = 1;
4128 CAMLreturn0;
4131 CAMLprim void ml_delannot (value ptr_v, value n_v)
4133 CAMLparam2 (ptr_v, n_v);
4134 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4136 if (pdf) {
4137 struct page *page;
4138 char *s = String_val (ptr_v);
4139 struct slink *slink;
4141 page = parse_pointer (__func__, s);
4142 slink = &page->slinks[Int_val (n_v)];
4143 pdf_delete_annot (state.ctx,
4144 pdf_page_from_fz_page (state.ctx, page->fzpage),
4145 (pdf_annot *) slink->u.annot);
4146 state.dirty = 1;
4148 CAMLreturn0;
4151 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4153 CAMLparam3 (ptr_v, n_v, str_v);
4154 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4156 if (pdf) {
4157 struct page *page;
4158 char *s = String_val (ptr_v);
4159 struct slink *slink;
4161 page = parse_pointer (__func__, s);
4162 slink = &page->slinks[Int_val (n_v)];
4163 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4164 String_val (str_v));
4165 state.dirty = 1;
4167 CAMLreturn0;
4170 CAMLprim value ml_hasunsavedchanges (value unit_v)
4172 CAMLparam1 (unit_v);
4173 CAMLreturn (Val_bool (state.dirty));
4176 CAMLprim void ml_savedoc (value path_v)
4178 CAMLparam1 (path_v);
4179 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4181 if (pdf) {
4182 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4184 CAMLreturn0;
4187 static void makestippletex (void)
4189 const char pixels[] = "\xff\xff\0\0";
4190 glGenTextures (1, &state.stid);
4191 glBindTexture (GL_TEXTURE_1D, state.stid);
4192 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4193 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4194 glTexImage1D (
4195 GL_TEXTURE_1D,
4197 GL_ALPHA,
4200 GL_ALPHA,
4201 GL_UNSIGNED_BYTE,
4202 pixels
4206 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4208 return caml_copy_string (FZ_VERSION);
4211 CAMLprim void ml_init (value csock_v, value params_v)
4213 CAMLparam2 (csock_v, params_v);
4214 CAMLlocal2 (trim_v, fuzz_v);
4215 int ret;
4216 int texcount;
4217 char *fontpath;
4218 int colorspace;
4219 int mustoresize;
4220 int haspboext;
4222 /* Without following call to setlocale mbstowcs fails for, at
4223 least, strings containing chinese symbols (δΈ­ for instance)
4224 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4225 wide character" as the reason of failure and with macOS
4226 producing bogus output) */
4227 if (setlocale (LC_CTYPE, "")) {
4228 /* Following two lines were taken from dvtm/vt.c */
4229 const char *cset = nl_langinfo (CODESET);
4230 state.utf8cs = !strcmp (cset, "UTF-8");
4232 else {
4233 fprintf (stderr, "setlocale failed\n");
4236 state.csock = Int_val (csock_v);
4237 state.rotate = Int_val (Field (params_v, 0));
4238 state.fitmodel = Int_val (Field (params_v, 1));
4239 trim_v = Field (params_v, 2);
4240 texcount = Int_val (Field (params_v, 3));
4241 state.sliceheight = Int_val (Field (params_v, 4));
4242 mustoresize = Int_val (Field (params_v, 5));
4243 colorspace = Int_val (Field (params_v, 6));
4244 fontpath = String_val (Field (params_v, 7));
4246 if (caml_string_length (Field (params_v, 8)) > 0) {
4247 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4249 if (!state.trimcachepath) {
4250 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4251 strerror (errno));
4255 haspboext = Bool_val (Field (params_v, 9));
4257 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4258 fz_register_document_handlers (state.ctx);
4260 state.trimmargins = Bool_val (Field (trim_v, 0));
4261 fuzz_v = Field (trim_v, 1);
4262 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4263 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4264 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4265 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4267 set_tex_params (colorspace);
4269 if (*fontpath) {
4270 state.face = load_font (fontpath);
4272 else {
4273 int len;
4274 const unsigned char *data;
4276 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4277 state.face = load_builtin_font (data, len);
4279 if (!state.face) _exit (1);
4281 realloctexts (texcount);
4283 if (haspboext) {
4284 setuppbo ();
4287 makestippletex ();
4289 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4290 if (ret) {
4291 errx (1, "pthread_create: %s", strerror (ret));
4294 CAMLreturn0;