Plug a leak
[llpp.git] / link.c
blobfab6ece046c168fa3027410a7882cde2c0b265e8
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
3 #define FIXME 0
5 #include <errno.h>
6 #include <stdio.h>
7 #include <ctype.h>
8 #include <string.h>
9 #include <stdlib.h>
10 #include <signal.h>
12 #include <math.h>
13 #include <wchar.h>
14 #include <locale.h>
15 #include <langinfo.h>
17 #include <unistd.h>
18 #include <pthread.h>
19 #include <sys/uio.h>
20 #include <sys/time.h>
21 #include <sys/stat.h>
22 #include <fcntl.h>
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
25 #include <sys/utsname.h>
27 #ifdef __CYGWIN__
28 #include <cygwin/socket.h> /* FIONREAD */
29 #else
30 #include <spawn.h>
31 #endif
33 #include <regex.h>
34 #include <stdarg.h>
35 #include <limits.h>
36 #include <inttypes.h>
38 #ifdef __COCOA__
39 #include <CoreFoundation/CoreFoundation.h>
40 #endif
42 #ifdef __APPLE__
43 #include <OpenGL/gl.h>
44 #else
45 #include <GL/gl.h>
46 #endif
48 #include <caml/fail.h>
49 #include <caml/alloc.h>
50 #include <caml/memory.h>
51 #include <caml/unixsupport.h>
53 #if __GNUC__ < 5 && !defined __clang__
54 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
55 clobbered diagnostics */
56 #pragma GCC diagnostic ignored "-Wclobbered"
57 #endif
59 #include <mupdf/fitz.h>
60 #include <mupdf/pdf.h>
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 fz_link *links;
207 int slinkcount;
208 struct slink *slinks;
209 int annotcount;
210 struct annot *annots;
211 struct mark {
212 fz_stext_char *ch;
213 } fmark, lmark;
216 struct {
217 int sliceheight;
218 struct pagedim *pagedims;
219 int pagecount;
220 int pagedimcount;
221 fz_document *doc;
222 fz_context *ctx;
223 int w, h;
225 int texindex;
226 int texcount;
227 GLuint *texids;
229 GLenum texiform;
230 GLenum texform;
231 GLenum texty;
233 fz_colorspace *colorspace;
235 struct {
236 int w, h;
237 struct slice *slice;
238 } *texowners;
240 int rotate;
241 enum { FitWidth, FitProportional, FitPage } fitmodel;
242 int trimmargins;
243 int needoutline;
244 int gen;
245 int aalevel;
247 int trimanew;
248 fz_irect trimfuzz;
249 fz_pixmap *pig;
251 pthread_t thread;
252 int csock;
253 FT_Face face;
255 char *trimcachepath;
256 int cxack;
257 int dirty;
259 GLuint stid;
261 int bo_usable;
262 GLuint boid;
264 void (*glBindBufferARB) (GLenum, GLuint);
265 GLboolean (*glUnmapBufferARB) (GLenum);
266 void *(*glMapBufferARB) (GLenum, GLenum);
267 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
268 void (*glGenBuffersARB) (GLsizei, GLuint *);
269 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
271 GLfloat texcoords[8];
272 GLfloat vertices[16];
274 #ifdef CACHE_PAGEREFS
275 struct {
276 int idx;
277 int count;
278 pdf_obj **objs;
279 pdf_document *pdf;
280 } pdflut;
281 #endif
282 int utf8cs;
283 } state;
285 struct bo {
286 GLuint id;
287 void *ptr;
288 size_t size;
291 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
293 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
296 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
298 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
301 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
303 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
304 m.a, m.b, m.c, m.d, m.e, m.f);
307 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
309 static void lock (const char *cap)
311 int ret = pthread_mutex_lock (&mutex);
312 if (ret) {
313 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
317 static void unlock (const char *cap)
319 int ret = pthread_mutex_unlock (&mutex);
320 if (ret) {
321 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
325 static int trylock (const char *cap)
327 int ret = pthread_mutex_trylock (&mutex);
328 if (ret && ret != EBUSY) {
329 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
331 return ret == EBUSY;
334 static void *parse_pointer (const char *cap, const char *s)
336 int ret;
337 void *ptr;
339 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
340 if (ret != 1) {
341 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
343 return ptr;
346 static double now (void)
348 struct timeval tv;
350 if (gettimeofday (&tv, NULL)) {
351 err (1, "gettimeofday");
353 return tv.tv_sec + tv.tv_usec*1e-6;
356 static int hasdata (void)
358 int ret, avail;
359 ret = ioctl (state.csock, FIONREAD, &avail);
360 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
361 return avail > 0;
364 CAMLprim value ml_hasdata (value fd_v)
366 CAMLparam1 (fd_v);
367 int ret, avail;
369 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
370 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
371 CAMLreturn (Val_bool (avail > 0));
374 static void readdata (int fd, void *p, int size)
376 ssize_t n;
378 again:
379 n = read (fd, p, size);
380 if (n - size) {
381 if (n < 0 && errno == EINTR) goto again;
382 if (!n) errx (1, "EOF while reading");
383 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
387 static void writedata (int fd, char *p, int size)
389 ssize_t n;
390 uint32_t size4 = size;
391 struct iovec iov[2] = {
392 { .iov_base = &size4, .iov_len = 4 },
393 { .iov_base = p, .iov_len = size }
396 again:
397 n = writev (fd, iov, 2);
398 if (n < 0 && errno == EINTR) goto again;
399 if (n - size - 4) {
400 if (!n) errx (1, "EOF while writing data");
401 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
405 static int readlen (int fd)
407 uint32_t u;
408 readdata (fd, &u, 4);
409 return u;
412 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
414 CAMLparam3 (fd_v, bytes_v, len_v);
415 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
416 CAMLreturn0;
419 CAMLprim value ml_rcmd (value fd_v)
421 CAMLparam1 (fd_v);
422 CAMLlocal1 (strdata_v);
423 int fd = Int_val (fd_v);
424 int len = readlen (fd);
425 strdata_v = caml_alloc_string (len);
426 readdata (fd, String_val (strdata_v), len);
427 CAMLreturn (strdata_v);
430 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
432 int size = 64, len;
433 va_list ap;
434 char fbuf[size];
435 char *buf = fbuf;
437 for (;;) {
438 va_start (ap, fmt);
439 len = vsnprintf (buf, size, fmt, ap);
440 va_end (ap);
442 if (len > -1) {
443 if (len < size - 4) {
444 writedata (state.csock, buf, len);
445 break;
447 else size = len + 5;
449 else {
450 err (1, "vsnprintf for `%s' failed", fmt);
452 buf = realloc (buf == fbuf ? NULL : buf, size);
453 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
455 if (buf != fbuf) free (buf);
458 static void closedoc (void)
460 #ifdef CACHE_PAGEREFS
461 if (state.pdflut.objs) {
462 for (int i = 0; i < state.pdflut.count; ++i) {
463 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
465 free (state.pdflut.objs);
466 state.pdflut.objs = NULL;
467 state.pdflut.idx = 0;
469 #endif
470 if (state.doc) {
471 fz_drop_document (state.ctx, state.doc);
472 state.doc = NULL;
476 static int openxref (char *filename, char *password)
478 for (int i = 0; i < state.texcount; ++i) {
479 state.texowners[i].w = -1;
480 state.texowners[i].slice = NULL;
483 closedoc ();
485 state.dirty = 0;
486 if (state.pagedims) {
487 free (state.pagedims);
488 state.pagedims = NULL;
490 state.pagedimcount = 0;
492 fz_set_aa_level (state.ctx, state.aalevel);
493 state.doc = fz_open_document (state.ctx, filename);
494 if (fz_needs_password (state.ctx, state.doc)) {
495 if (password && !*password) {
496 printd ("pass");
497 return 0;
499 else {
500 int ok = fz_authenticate_password (state.ctx, state.doc, password);
501 if (!ok) {
502 printd ("pass fail");
503 return 0;
507 state.pagecount = fz_count_pages (state.ctx, state.doc);
508 return 1;
511 static void pdfinfo (void)
513 struct { char *tag; char *name; } metatbl[] = {
514 { FZ_META_INFO_TITLE, "Title" },
515 { FZ_META_INFO_AUTHOR, "Author" },
516 { FZ_META_FORMAT, "Format" },
517 { FZ_META_ENCRYPTION, "Encryption" },
518 { "info:Creator", "Creator" },
519 { "info:Producer", "Producer" },
520 { "info:CreationDate", "Creation date" },
522 int len = 0;
523 char *buf = NULL;
525 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
526 int need;
527 again:
528 need = fz_lookup_metadata (state.ctx, state.doc,
529 metatbl[i].tag, buf, len);
530 if (need > 0) {
531 if (need <= len) {
532 printd ("info %s\t%s", metatbl[i].name, buf);
534 else {
535 buf = realloc (buf, need + 1);
536 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
537 len = need + 1;
538 goto again;
542 free (buf);
544 printd ("infoend");
547 static void unlinktile (struct tile *tile)
549 for (int i = 0; i < tile->slicecount; ++i) {
550 struct slice *s = &tile->slices[i];
552 if (s->texindex != -1) {
553 if (state.texowners[s->texindex].slice == s) {
554 state.texowners[s->texindex].slice = NULL;
560 static void freepage (struct page *page)
562 if (!page) return;
563 if (page->text) {
564 fz_drop_stext_page (state.ctx, page->text);
566 if (page->slinks) {
567 free (page->slinks);
569 fz_drop_display_list (state.ctx, page->dlist);
570 fz_drop_page (state.ctx, page->fzpage);
571 free (page);
574 static void freetile (struct tile *tile)
576 unlinktile (tile);
577 if (!tile->pbo) {
578 #ifndef PIGGYBACK
579 fz_drop_pixmap (state.ctx, tile->pixmap);
580 #else
581 if (state.pig) {
582 fz_drop_pixmap (state.ctx, state.pig);
584 state.pig = tile->pixmap;
585 #endif
587 else {
588 free (tile->pbo);
589 fz_drop_pixmap (state.ctx, tile->pixmap);
591 free (tile);
594 #ifdef __ALTIVEC__
595 #include <stdint.h>
596 #include <altivec.h>
598 static int cacheline32bytes;
600 static void __attribute__ ((constructor)) clcheck (void)
602 char **envp = environ;
603 unsigned long *auxv;
605 while (*envp++);
607 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
608 if (*auxv == 19) {
609 cacheline32bytes = auxv[1] == 32;
610 return;
615 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
617 size_t size = pixmap->w * pixmap->h * pixmap->n;
618 if (cacheline32bytes && size > 32) {
619 intptr_t a1, a2, diff;
620 size_t sizea, i;
621 vector unsigned char v = vec_splat_u8 (-1);
622 vector unsigned char *p;
624 a1 = a2 = (intptr_t) pixmap->samples;
625 a2 = (a1 + 31) & ~31;
626 diff = a2 - a1;
627 sizea = size - diff;
628 p = (void *) a2;
630 while (a1 != a2) *(char *) a1++ = 0xff;
631 for (i = 0; i < (sizea & ~31); i += 32) {
632 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
633 vec_st (v, i, p);
634 vec_st (v, i + 16, p);
636 while (i < sizea) *((char *) a1 + i++) = 0xff;
638 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
640 #else
641 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
642 #endif
644 static void trimctm (pdf_page *page, int pindex)
646 fz_matrix ctm;
647 struct pagedim *pdim = &state.pagedims[pindex];
649 if (!page) return;
650 if (!pdim->tctmready) {
651 fz_rect realbox, mediabox;
652 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
654 fz_rotate (&rm, -pdim->rotate);
655 fz_scale (&sm, 1, -1);
656 fz_concat (&ctm, &rm, &sm);
657 realbox = pdim->mediabox;
658 fz_transform_rect (&realbox, &ctm);
659 fz_translate (&tm, -realbox.x0, -realbox.y0);
660 fz_concat (&ctm1, &ctm, &tm);
661 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
662 fz_invert_matrix (&im, &page_ctm);
663 fz_concat (&ctm, &im, &ctm1);
664 pdim->tctm = ctm;
665 pdim->tctmready = 1;
669 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
671 fz_matrix ctm, tm;
672 int pdimno = pdim - state.pagedims;
674 if (pdf_specifics (state.ctx, state.doc)) {
675 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
676 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
678 else {
679 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
680 fz_concat (&ctm, &tm, &pdim->ctm);
682 return ctm;
685 static fz_matrix pagectm (struct page *page)
687 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
690 static void *loadpage (int pageno, int pindex)
692 fz_device *dev;
693 struct page *page;
695 page = calloc (sizeof (struct page), 1);
696 if (!page) {
697 err (1, "calloc page %d", pageno);
700 page->dlist = fz_new_display_list (state.ctx, NULL);
701 dev = fz_new_list_device (state.ctx, page->dlist);
702 fz_try (state.ctx) {
703 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
704 fz_run_page (state.ctx, page->fzpage, dev,
705 &fz_identity, NULL);
707 fz_catch (state.ctx) {
708 page->fzpage = NULL;
710 fz_close_device (state.ctx, dev);
711 fz_drop_device (state.ctx, dev);
713 page->pdimno = pindex;
714 page->pageno = pageno;
715 page->sgen = state.gen;
716 page->agen = state.gen;
717 page->tgen = state.gen;
718 return page;
721 static struct tile *alloctile (int h)
723 int slicecount;
724 size_t tilesize;
725 struct tile *tile;
727 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
728 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
729 tile = calloc (tilesize, 1);
730 if (!tile) {
731 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
733 for (int i = 0; i < slicecount; ++i) {
734 int sh = fz_mini (h, state.sliceheight);
735 tile->slices[i].h = sh;
736 tile->slices[i].texindex = -1;
737 h -= sh;
739 tile->slicecount = slicecount;
740 tile->sliceheight = state.sliceheight;
741 return tile;
744 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
745 struct bo *pbo)
747 fz_rect rect;
748 fz_irect bbox;
749 fz_matrix ctm;
750 fz_device *dev;
751 struct tile *tile;
752 struct pagedim *pdim;
754 tile = alloctile (h);
755 pdim = &state.pagedims[page->pdimno];
757 bbox = pdim->bounds;
758 bbox.x0 += x;
759 bbox.y0 += y;
760 bbox.x1 = bbox.x0 + w;
761 bbox.y1 = bbox.y0 + h;
763 if (state.pig) {
764 if (state.pig->w == w
765 && state.pig->h == h
766 && state.pig->colorspace == state.colorspace) {
767 tile->pixmap = state.pig;
768 tile->pixmap->x = bbox.x0;
769 tile->pixmap->y = bbox.y0;
771 else {
772 fz_drop_pixmap (state.ctx, state.pig);
774 state.pig = NULL;
776 if (!tile->pixmap) {
777 if (pbo) {
778 tile->pixmap =
779 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
780 &bbox, NULL, 1, pbo->ptr);
781 tile->pbo = pbo;
783 else {
784 tile->pixmap =
785 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
786 NULL, 1);
790 tile->w = w;
791 tile->h = h;
792 clearpixmap (tile->pixmap);
794 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
795 ctm = pagectm (page);
796 fz_rect_from_irect (&rect, &bbox);
797 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
798 fz_close_device (state.ctx, dev);
799 fz_drop_device (state.ctx, dev);
801 return tile;
804 #ifdef CACHE_PAGEREFS
805 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
806 thanks to Robin Watts */
807 static void
808 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
810 fz_context *ctx = state.ctx; /* doc->ctx; */
811 pdf_obj *kids;
812 int len;
814 if (state.pdflut.idx == state.pagecount) return;
816 kids = pdf_dict_gets (ctx, node, "Kids");
817 len = pdf_array_len (ctx, kids);
819 if (len == 0)
820 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
822 if (pdf_mark_obj (ctx, node))
823 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
824 for (int i = 0; i < len; i++) {
825 pdf_obj *kid = pdf_array_get (ctx, kids, i);
826 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
827 if (*type
828 ? !strcmp (type, "Pages")
829 : pdf_dict_gets (ctx, kid, "Kids")
830 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
831 pdf_collect_pages (doc, kid);
833 else {
834 if (*type
835 ? strcmp (type, "Page") != 0
836 : !pdf_dict_gets (ctx, kid, "MediaBox"))
837 fz_warn (ctx, "non-page object in page tree (%s)", type);
838 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
841 pdf_unmark_obj (ctx, node);
844 static void
845 pdf_load_page_objs (pdf_document *doc)
847 pdf_obj *root = pdf_dict_gets (state.ctx,
848 pdf_trailer (state.ctx, doc), "Root");
849 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
851 if (!node)
852 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
854 state.pdflut.idx = 0;
855 pdf_collect_pages (doc, node);
857 #endif
859 static void initpdims (int wthack)
861 double start, end;
862 FILE *trimf = NULL;
863 fz_rect rootmediabox;
864 int pageno, trim, show;
865 int trimw = 0, cxcount;
866 fz_context *ctx = state.ctx;
867 pdf_document *pdf = pdf_specifics (ctx, state.doc);
869 fz_var (trimw);
870 fz_var (trimf);
871 fz_var (cxcount);
872 start = now ();
874 if (state.trimmargins && state.trimcachepath) {
875 trimf = fopen (state.trimcachepath, "rb");
876 if (!trimf) {
877 trimf = fopen (state.trimcachepath, "wb");
878 trimw = 1;
882 if (state.trimmargins || pdf || !state.cxack)
883 cxcount = state.pagecount;
884 else
885 cxcount = fz_mini (state.pagecount, 1);
887 if (pdf) {
888 pdf_obj *obj;
889 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
890 "Root/Pages/MediaBox");
891 pdf_to_rect (ctx, obj, &rootmediabox);
894 #ifdef CACHE_PAGEREFS
895 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
896 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
897 if (!state.pdflut.objs) {
898 err (1, "malloc pageobjs %zu %d %zu failed",
899 sizeof (*state.pdflut.objs), cxcount,
900 sizeof (*state.pdflut.objs) * cxcount);
902 state.pdflut.count = cxcount;
903 pdf_load_page_objs (pdf);
904 state.pdflut.pdf = pdf;
906 #endif
908 for (pageno = 0; pageno < cxcount; ++pageno) {
909 int rotate = 0;
910 struct pagedim *p;
911 fz_rect mediabox;
913 fz_var (rotate);
914 if (pdf) {
915 pdf_obj *pageref, *pageobj;
917 #ifdef CACHE_PAGEREFS
918 pageref = state.pdflut.objs[pageno];
919 #else
920 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
921 #endif
922 pageobj = pdf_resolve_indirect (ctx, pageref);
923 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
925 if (state.trimmargins) {
926 pdf_obj *obj;
927 pdf_page *page;
929 fz_try (ctx) {
930 page = pdf_load_page (ctx, pdf, pageno);
931 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
932 trim = state.trimanew || !obj;
933 if (trim) {
934 fz_rect rect;
935 fz_device *dev;
936 fz_matrix ctm, page_ctm;
938 dev = fz_new_bbox_device (ctx, &rect);
939 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
940 fz_invert_matrix (&ctm, &page_ctm);
941 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
942 fz_close_device (ctx, dev);
943 fz_drop_device (ctx, dev);
945 rect.x0 += state.trimfuzz.x0;
946 rect.x1 += state.trimfuzz.x1;
947 rect.y0 += state.trimfuzz.y0;
948 rect.y1 += state.trimfuzz.y1;
949 fz_transform_rect (&rect, &ctm);
950 fz_intersect_rect (&rect, &mediabox);
952 if (!fz_is_empty_rect (&rect)) {
953 mediabox = rect;
956 obj = pdf_new_array (ctx, pdf, 4);
957 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
958 mediabox.x0));
959 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
960 mediabox.y0));
961 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
962 mediabox.x1));
963 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
964 mediabox.y1));
965 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
967 else {
968 mediabox.x0 = pdf_to_real (ctx,
969 pdf_array_get (ctx, obj, 0));
970 mediabox.y0 = pdf_to_real (ctx,
971 pdf_array_get (ctx, obj, 1));
972 mediabox.x1 = pdf_to_real (ctx,
973 pdf_array_get (ctx, obj, 2));
974 mediabox.y1 = pdf_to_real (ctx,
975 pdf_array_get (ctx, obj, 3));
978 fz_drop_page (ctx, &page->super);
979 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
980 if (show) {
981 printd ("progress %f Trimming %d",
982 (double) (pageno + 1) / state.pagecount,
983 pageno + 1);
986 fz_catch (ctx) {
987 fprintf (stderr, "failed to load page %d\n", pageno+1);
990 else {
991 int empty = 0;
992 fz_rect cropbox;
994 pdf_to_rect (ctx,
995 pdf_dict_gets (ctx, pageobj, "MediaBox"),
996 &mediabox);
997 if (fz_is_empty_rect (&mediabox)) {
998 mediabox.x0 = 0;
999 mediabox.y0 = 0;
1000 mediabox.x1 = 612;
1001 mediabox.y1 = 792;
1002 empty = 1;
1005 pdf_to_rect (ctx,
1006 pdf_dict_gets (ctx, pageobj, "CropBox"),
1007 &cropbox);
1008 if (!fz_is_empty_rect (&cropbox)) {
1009 if (empty) {
1010 mediabox = cropbox;
1012 else {
1013 fz_intersect_rect (&mediabox, &cropbox);
1016 else {
1017 if (empty) {
1018 if (fz_is_empty_rect (&rootmediabox)) {
1019 fprintf (stderr,
1020 "cannot find page size for page %d\n",
1021 pageno+1);
1023 else {
1024 mediabox = rootmediabox;
1030 else {
1031 if (state.trimmargins && trimw) {
1032 fz_page *page;
1034 fz_try (ctx) {
1035 page = fz_load_page (ctx, state.doc, pageno);
1036 fz_bound_page (ctx, page, &mediabox);
1037 if (state.trimmargins) {
1038 fz_rect rect;
1039 fz_device *dev;
1041 dev = fz_new_bbox_device (ctx, &rect);
1042 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1043 fz_close_device (ctx, dev);
1044 fz_drop_device (ctx, dev);
1046 rect.x0 += state.trimfuzz.x0;
1047 rect.x1 += state.trimfuzz.x1;
1048 rect.y0 += state.trimfuzz.y0;
1049 rect.y1 += state.trimfuzz.y1;
1050 fz_intersect_rect (&rect, &mediabox);
1052 if (!fz_is_empty_rect (&rect)) {
1053 mediabox = rect;
1056 fz_drop_page (ctx, page);
1057 if (!state.cxack) {
1058 printd ("progress %f loading %d",
1059 (double) (pageno + 1) / state.pagecount,
1060 pageno + 1);
1063 fz_catch (ctx) {
1065 if (trimf) {
1066 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1067 if (n - 1) {
1068 err (1, "fwrite trim mediabox");
1072 else {
1073 if (trimf) {
1074 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1075 if (n - 1) {
1076 err (1, "fread trim mediabox %d", pageno);
1079 else {
1080 fz_page *page;
1081 fz_try (ctx) {
1082 page = fz_load_page (ctx, state.doc, pageno);
1083 fz_bound_page (ctx, page, &mediabox);
1084 fz_drop_page (ctx, page);
1086 show = !state.trimmargins && pageno % 20 == 0;
1087 if (show) {
1088 printd ("progress %f Gathering dimensions %d",
1089 (double) (pageno) / state.pagecount,
1090 pageno);
1093 fz_catch (ctx) {
1094 fprintf (stderr, "failed to load page %d\n", pageno);
1100 if (state.pagedimcount == 0
1101 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1102 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1103 size_t size;
1105 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1106 state.pagedims = realloc (state.pagedims, size);
1107 if (!state.pagedims) {
1108 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1109 size, state.pagedimcount + 1);
1112 p = &state.pagedims[state.pagedimcount++];
1113 p->rotate = rotate;
1114 p->mediabox = mediabox;
1115 p->pageno = pageno;
1118 end = now ();
1119 if (!wthack) {
1120 printd ("progress 1 %s %d pages in %f seconds",
1121 state.trimmargins ? "Trimmed" : "Processed",
1122 state.pagecount, end - start);
1124 state.trimanew = 0;
1125 if (trimf) {
1126 if (fclose (trimf)) {
1127 err (1, "fclose");
1132 static void layout (void)
1134 int pindex;
1135 fz_rect box;
1136 fz_matrix ctm, rm;
1137 struct pagedim *p = p;
1138 double zw, w, maxw = 0.0, zoom = zoom;
1140 if (state.pagedimcount == 0) return;
1142 switch (state.fitmodel) {
1143 case FitProportional:
1144 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1145 double x0, x1;
1147 p = &state.pagedims[pindex];
1148 fz_rotate (&rm, p->rotate + state.rotate);
1149 box = p->mediabox;
1150 fz_transform_rect (&box, &rm);
1152 x0 = fz_min (box.x0, box.x1);
1153 x1 = fz_max (box.x0, box.x1);
1155 w = x1 - x0;
1156 maxw = fz_max (w, maxw);
1157 zoom = state.w / maxw;
1159 break;
1161 case FitPage:
1162 maxw = state.w;
1163 break;
1165 case FitWidth:
1166 break;
1168 default:
1169 ARSERT (0 && state.fitmodel);
1172 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1173 fz_rect rect;
1174 fz_matrix tm, sm;
1176 p = &state.pagedims[pindex];
1177 fz_rotate (&ctm, state.rotate);
1178 fz_rotate (&rm, p->rotate + state.rotate);
1179 box = p->mediabox;
1180 fz_transform_rect (&box, &rm);
1181 w = box.x1 - box.x0;
1182 switch (state.fitmodel) {
1183 case FitProportional:
1184 p->left = ((maxw - w) * zoom) / 2.0;
1185 break;
1186 case FitPage:
1188 double zh, h;
1189 zw = maxw / w;
1190 h = box.y1 - box.y0;
1191 zh = state.h / h;
1192 zoom = fz_min (zw, zh);
1193 p->left = (maxw - (w * zoom)) / 2.0;
1195 break;
1196 case FitWidth:
1197 p->left = 0;
1198 zoom = state.w / w;
1199 break;
1202 fz_scale (&p->zoomctm, zoom, zoom);
1203 fz_concat (&ctm, &p->zoomctm, &ctm);
1205 fz_rotate (&rm, p->rotate);
1206 p->pagebox = p->mediabox;
1207 fz_transform_rect (&p->pagebox, &rm);
1208 p->pagebox.x1 -= p->pagebox.x0;
1209 p->pagebox.y1 -= p->pagebox.y0;
1210 p->pagebox.x0 = 0;
1211 p->pagebox.y0 = 0;
1212 rect = p->pagebox;
1213 fz_transform_rect (&rect, &ctm);
1214 fz_round_rect (&p->bounds, &rect);
1215 p->ctm = ctm;
1217 fz_translate (&tm, 0, -p->mediabox.y1);
1218 fz_scale (&sm, zoom, -zoom);
1219 fz_concat (&ctm, &tm, &sm);
1221 p->tctmready = 0;
1224 do {
1225 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1226 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1227 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1228 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1229 int boundw = x1 - x0;
1230 int boundh = y1 - y0;
1232 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1233 } while (p-- != state.pagedims);
1236 struct pagedim *pdimofpageno (int pageno)
1238 struct pagedim *pdim = state.pagedims;
1240 for (int i = 0; i < state.pagedimcount; ++i) {
1241 if (state.pagedims[i].pageno > pageno)
1242 break;
1243 pdim = &state.pagedims[i];
1245 return pdim;
1248 static void recurse_outline (fz_outline *outline, int level)
1250 while (outline) {
1251 if (outline->page >= 0) {
1252 fz_point p = {.x = outline->x, .y = outline->y};
1253 struct pagedim *pdim = pdimofpageno (outline->page);
1254 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1255 fz_transform_point (&p, &pdim->ctm);
1256 printd ("o %d %d %d %d %s",
1257 level, outline->page, (int) p.y, h, outline->title);
1259 else {
1260 printd ("on %d %s", level, outline->title);
1262 if (outline->down) {
1263 recurse_outline (outline->down, level + 1);
1265 outline = outline->next;
1269 static void process_outline (void)
1271 fz_outline *outline;
1273 if (!state.needoutline || !state.pagedimcount) return;
1275 state.needoutline = 0;
1276 outline = fz_load_outline (state.ctx, state.doc);
1277 if (outline) {
1278 recurse_outline (outline, 0);
1279 fz_drop_outline (state.ctx, outline);
1283 static char *strofline (fz_stext_line *line)
1285 char *p;
1286 char utf8[10];
1287 fz_stext_char *ch;
1288 size_t size = 0, cap = 80;
1290 p = malloc (cap + 1);
1291 if (!p) return NULL;
1293 for (ch = line->first_char; ch; ch = ch->next) {
1294 int n = fz_runetochar (utf8, ch->c);
1295 if (size + n > cap) {
1296 cap *= 2;
1297 p = realloc (p, cap + 1);
1298 if (!p) return NULL;
1301 memcpy (p + size, utf8, n);
1302 size += n;
1304 p[size] = 0;
1305 return p;
1308 static int matchline (regex_t *re, fz_stext_line *line,
1309 int stop, int pageno, double start)
1311 int ret;
1312 char *p;
1313 regmatch_t rm;
1315 p = strofline (line);
1316 if (!p) return -1;
1318 ret = regexec (re, p, 1, &rm, 0);
1319 if (ret) {
1320 free (p);
1321 if (ret != REG_NOMATCH) {
1322 size_t size;
1323 char errbuf[80];
1324 size = regerror (ret, re, errbuf, sizeof (errbuf));
1325 printd ("msg regexec error `%.*s'",
1326 (int) size, errbuf);
1327 return -1;
1329 return 0;
1331 else {
1332 fz_point p1, p2, p3, p4;
1333 fz_rect s = {0,0,0,0}, e;
1334 fz_stext_char *ch;
1335 int o = 0;
1337 for (ch = line->first_char; ch; ch = ch->next) {
1338 o += fz_runelen (ch->c);
1339 if (o > rm.rm_so) {
1340 s = ch->bbox;
1341 break;
1344 for (;ch; ch = ch->next) {
1345 o += fz_runelen (ch->c);
1346 if (o > rm.rm_eo) break;
1348 e = ch->bbox;
1350 p1.x = s.x0;
1351 p1.y = s.y0;
1352 p2.x = e.x1;
1353 p2.y = s.y0;
1354 p3.x = e.x1;
1355 p3.y = e.y1;
1356 p4.x = s.x0;
1357 p4.y = e.y1;
1359 if (!stop) {
1360 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1361 pageno, 1,
1362 p1.x, p1.y,
1363 p2.x, p2.y,
1364 p3.x, p3.y,
1365 p4.x, p4.y);
1367 printd ("progress 1 found at %d `%.*s' in %f sec",
1368 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1369 now () - start);
1371 else {
1372 printd ("match %d %d %f %f %f %f %f %f %f %f",
1373 pageno, 2,
1374 p1.x, p1.y,
1375 p2.x, p2.y,
1376 p3.x, p3.y,
1377 p4.x, p4.y);
1379 free (p);
1380 return 1;
1384 /* wishful thinking function */
1385 static void search (regex_t *re, int pageno, int y, int forward)
1387 fz_device *tdev;
1388 fz_stext_page *text;
1389 struct pagedim *pdim;
1390 int stop = 0, niters = 0;
1391 double start, end;
1392 fz_page *page;
1393 fz_stext_block *block;
1395 start = now ();
1396 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1397 if (niters++ == 5) {
1398 niters = 0;
1399 if (hasdata ()) {
1400 printd ("progress 1 attention requested aborting search at %d",
1401 pageno);
1402 stop = 1;
1404 else {
1405 printd ("progress %f searching in page %d",
1406 (double) (pageno + 1) / state.pagecount,
1407 pageno);
1410 pdim = pdimofpageno (pageno);
1411 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1412 tdev = fz_new_stext_device (state.ctx, text, 0);
1414 page = fz_load_page (state.ctx, state.doc, pageno);
1416 fz_matrix ctm = pagectm1 (page, pdim);
1417 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1420 fz_close_device (state.ctx, tdev);
1421 fz_drop_device (state.ctx, tdev);
1423 if (forward) {
1424 for (block = text->first_block; block; block = block->next) {
1425 fz_stext_line *line;
1427 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1428 for (line = block->u.t.first_line; line; line = line->next) {
1429 if (line->bbox.y0 < y + 1) continue;
1431 switch (matchline (re, line, stop, pageno, start)) {
1432 case 0: break;
1433 case 1: stop = 1; break;
1434 case -1: stop = 1; goto endloop;
1439 else {
1440 for (block = text->last_block; block; block = block->prev) {
1441 fz_stext_line *line;
1443 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1444 for (line = block->u.t.last_line; line; line = line->prev) {
1445 if (line->bbox.y0 < y + 1) continue;
1447 switch (matchline (re, line, stop, pageno, start)) {
1448 case 0: break;
1449 case 1: stop = 1; break;
1450 case -1: stop = 1; goto endloop;
1456 if (forward) {
1457 pageno += 1;
1458 y = 0;
1460 else {
1461 pageno -= 1;
1462 y = INT_MAX;
1464 endloop:
1465 fz_drop_stext_page (state.ctx, text);
1466 fz_drop_page (state.ctx, page);
1468 end = now ();
1469 if (!stop) {
1470 printd ("progress 1 no matches %f sec", end - start);
1472 printd ("clearrects");
1475 static void set_tex_params (int colorspace)
1477 switch (colorspace) {
1478 case 0:
1479 state.texiform = GL_RGBA8;
1480 state.texform = GL_RGBA;
1481 state.texty = GL_UNSIGNED_BYTE;
1482 state.colorspace = fz_device_rgb (state.ctx);
1483 break;
1484 case 1:
1485 state.texiform = GL_RGBA8;
1486 state.texform = GL_BGRA;
1487 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1488 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1489 #else
1490 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1491 #endif
1492 state.colorspace = fz_device_bgr (state.ctx);
1493 break;
1494 case 2:
1495 state.texiform = GL_LUMINANCE_ALPHA;
1496 state.texform = GL_LUMINANCE_ALPHA;
1497 state.texty = GL_UNSIGNED_BYTE;
1498 state.colorspace = fz_device_gray (state.ctx);
1499 break;
1500 default:
1501 errx (1, "invalid colorspce %d", colorspace);
1505 static void realloctexts (int texcount)
1507 size_t size;
1509 if (texcount == state.texcount) return;
1511 if (texcount < state.texcount) {
1512 glDeleteTextures (state.texcount - texcount,
1513 state.texids + texcount);
1516 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1517 state.texids = realloc (state.texids, size);
1518 if (!state.texids) {
1519 err (1, "realloc texs %" FMT_s, size);
1522 state.texowners = (void *) (state.texids + texcount);
1523 if (texcount > state.texcount) {
1524 glGenTextures (texcount - state.texcount,
1525 state.texids + state.texcount);
1526 for (int i = state.texcount; i < texcount; ++i) {
1527 state.texowners[i].w = -1;
1528 state.texowners[i].slice = NULL;
1531 state.texcount = texcount;
1532 state.texindex = 0;
1535 static char *mbtoutf8 (char *s)
1537 char *p, *r;
1538 wchar_t *tmp;
1539 size_t i, ret, len;
1541 if (state.utf8cs) {
1542 return s;
1545 len = mbstowcs (NULL, s, strlen (s));
1546 if (len == 0) {
1547 return s;
1549 else {
1550 if (len == (size_t) -1) {
1551 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1552 return s;
1556 tmp = calloc (len, sizeof (wchar_t));
1557 if (!tmp) {
1558 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1559 len, sizeof (wchar_t), errno, strerror (errno));
1560 return s;
1563 ret = mbstowcs (tmp, s, len);
1564 if (ret == (size_t) -1) {
1565 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1566 len, errno, strerror (errno));
1567 free (tmp);
1568 return s;
1571 len = 0;
1572 for (i = 0; i < ret; ++i) {
1573 len += fz_runelen (tmp[i]);
1576 p = r = malloc (len + 1);
1577 if (!r) {
1578 printd ("emsg mbtoutf8: malloc(%zu)", len);
1579 free (tmp);
1580 return s;
1583 for (i = 0; i < ret; ++i) {
1584 p += fz_runetochar (p, tmp[i]);
1586 *p = 0;
1587 free (tmp);
1588 return r;
1591 CAMLprim value ml_mbtoutf8 (value s_v)
1593 CAMLparam1 (s_v);
1594 CAMLlocal1 (ret_v);
1595 char *s, *r;
1597 s = String_val (s_v);
1598 r = mbtoutf8 (s);
1599 if (r == s) {
1600 ret_v = s_v;
1602 else {
1603 ret_v = caml_copy_string (r);
1604 free (r);
1606 CAMLreturn (ret_v);
1609 static void * mainloop (void UNUSED_ATTR *unused)
1611 char *p = NULL;
1612 int len, ret, oldlen = 0;
1614 fz_var (p);
1615 fz_var (oldlen);
1616 for (;;) {
1617 len = readlen (state.csock);
1618 if (len == 0) {
1619 errx (1, "readlen returned 0");
1622 if (oldlen < len + 1) {
1623 p = realloc (p, len + 1);
1624 if (!p) {
1625 err (1, "realloc %d failed", len + 1);
1627 oldlen = len + 1;
1629 readdata (state.csock, p, len);
1630 p[len] = 0;
1632 if (!strncmp ("open", p, 4)) {
1633 int wthack, off, usedoccss, ok = 0;
1634 char *password;
1635 char *filename;
1636 char *utf8filename;
1637 size_t filenamelen;
1639 fz_var (ok);
1640 ret = sscanf (p + 5, " %d %d %d %n",
1641 &wthack, &state.cxack, &usedoccss, &off);
1642 if (ret != 3) {
1643 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1646 filename = p + 5 + off;
1647 filenamelen = strlen (filename);
1648 password = filename + filenamelen + 1;
1650 if (password[strlen (password) + 1]) {
1651 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1654 lock ("open");
1655 fz_set_use_document_css (state.ctx, usedoccss);
1656 fz_try (state.ctx) {
1657 ok = openxref (filename, password);
1659 fz_catch (state.ctx) {
1660 utf8filename = mbtoutf8 (filename);
1661 printd ("msg Could not open %s", utf8filename);
1662 if (utf8filename != filename) {
1663 free (utf8filename);
1666 if (ok) {
1667 pdfinfo ();
1668 initpdims (wthack);
1670 unlock ("open");
1672 if (ok) {
1673 if (!wthack) {
1674 utf8filename = mbtoutf8 (filename);
1675 printd ("msg Opened %s (press h/F1 to get help)",
1676 utf8filename);
1677 if (utf8filename != filename) {
1678 free (utf8filename);
1681 state.needoutline = 1;
1684 else if (!strncmp ("cs", p, 2)) {
1685 int i, colorspace;
1687 ret = sscanf (p + 2, " %d", &colorspace);
1688 if (ret != 1) {
1689 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1691 lock ("cs");
1692 set_tex_params (colorspace);
1693 for (i = 0; i < state.texcount; ++i) {
1694 state.texowners[i].w = -1;
1695 state.texowners[i].slice = NULL;
1697 unlock ("cs");
1699 else if (!strncmp ("freepage", p, 8)) {
1700 void *ptr;
1702 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1703 if (ret != 1) {
1704 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1706 lock ("freepage");
1707 freepage (ptr);
1708 unlock ("freepage");
1710 else if (!strncmp ("freetile", p, 8)) {
1711 void *ptr;
1713 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1714 if (ret != 1) {
1715 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1717 lock ("freetile");
1718 freetile (ptr);
1719 unlock ("freetile");
1721 else if (!strncmp ("search", p, 6)) {
1722 int icase, pageno, y, len2, forward;
1723 char *pattern;
1724 regex_t re;
1726 ret = sscanf (p + 6, " %d %d %d %d,%n",
1727 &icase, &pageno, &y, &forward, &len2);
1728 if (ret != 4) {
1729 errx (1, "malformed search `%s' ret=%d", p, ret);
1732 pattern = p + 6 + len2;
1733 ret = regcomp (&re, pattern,
1734 REG_EXTENDED | (icase ? REG_ICASE : 0));
1735 if (ret) {
1736 char errbuf[80];
1737 size_t size;
1739 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1740 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1742 else {
1743 search (&re, pageno, y, forward);
1744 regfree (&re);
1747 else if (!strncmp ("geometry", p, 8)) {
1748 int w, h, fitmodel;
1750 printd ("clear");
1751 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1752 if (ret != 3) {
1753 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1756 lock ("geometry");
1757 state.h = h;
1758 if (w != state.w) {
1759 state.w = w;
1760 for (int i = 0; i < state.texcount; ++i) {
1761 state.texowners[i].slice = NULL;
1764 state.fitmodel = fitmodel;
1765 layout ();
1766 process_outline ();
1768 state.gen++;
1769 unlock ("geometry");
1770 printd ("continue %d", state.pagecount);
1772 else if (!strncmp ("reqlayout", p, 9)) {
1773 char *nameddest;
1774 int rotate, off, h;
1775 unsigned int fitmodel;
1776 pdf_document *pdf;
1778 printd ("clear");
1779 ret = sscanf (p + 9, " %d %u %d %n",
1780 &rotate, &fitmodel, &h, &off);
1781 if (ret != 3) {
1782 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1784 lock ("reqlayout");
1785 pdf = pdf_specifics (state.ctx, state.doc);
1786 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1787 state.gen += 1;
1789 state.rotate = rotate;
1790 state.fitmodel = fitmodel;
1791 state.h = h;
1792 layout ();
1793 process_outline ();
1795 nameddest = p + 9 + off;
1796 if (pdf && nameddest && *nameddest) {
1797 fz_point xy;
1798 struct pagedim *pdim;
1799 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1800 &xy.x, &xy.y);
1801 pdim = pdimofpageno (pageno);
1802 fz_transform_point (&xy, &pdim->ctm);
1803 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1806 state.gen++;
1807 unlock ("reqlayout");
1808 printd ("continue %d", state.pagecount);
1810 else if (!strncmp ("page", p, 4)) {
1811 double a, b;
1812 struct page *page;
1813 int pageno, pindex;
1815 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1816 if (ret != 2) {
1817 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1820 lock ("page");
1821 a = now ();
1822 page = loadpage (pageno, pindex);
1823 b = now ();
1824 unlock ("page");
1826 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1828 else if (!strncmp ("tile", p, 4)) {
1829 int x, y, w, h;
1830 struct page *page;
1831 struct tile *tile;
1832 double a, b;
1833 void *data;
1835 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1836 SCN_ptr_cast (&page), &x, &y, &w, &h,
1837 SCN_ptr_cast (&data));
1838 if (ret != 6) {
1839 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1842 lock ("tile");
1843 a = now ();
1844 tile = rendertile (page, x, y, w, h, data);
1845 b = now ();
1846 unlock ("tile");
1848 printd ("tile %d %d %" FMT_ptr " %u %f",
1849 x, y,
1850 FMT_ptr_cast (tile),
1851 tile->w * tile->h * tile->pixmap->n,
1852 b - a);
1854 else if (!strncmp ("trimset", p, 7)) {
1855 fz_irect fuzz;
1856 int trimmargins;
1858 ret = sscanf (p + 7, " %d %d %d %d %d",
1859 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1860 if (ret != 5) {
1861 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1863 lock ("trimset");
1864 state.trimmargins = trimmargins;
1865 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1866 state.trimanew = 1;
1867 state.trimfuzz = fuzz;
1869 unlock ("trimset");
1871 else if (!strncmp ("settrim", 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 settrim `%.*s' ret=%d", len, p, ret);
1880 printd ("clear");
1881 lock ("settrim");
1882 state.trimmargins = trimmargins;
1883 state.needoutline = 1;
1884 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1885 state.trimanew = 1;
1886 state.trimfuzz = fuzz;
1888 state.pagedimcount = 0;
1889 free (state.pagedims);
1890 state.pagedims = NULL;
1891 initpdims (0);
1892 layout ();
1893 process_outline ();
1894 unlock ("settrim");
1895 printd ("continue %d", state.pagecount);
1897 else if (!strncmp ("sliceh", p, 6)) {
1898 int h;
1900 ret = sscanf (p + 6, " %d", &h);
1901 if (ret != 1) {
1902 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1904 if (h != state.sliceheight) {
1905 state.sliceheight = h;
1906 for (int i = 0; i < state.texcount; ++i) {
1907 state.texowners[i].w = -1;
1908 state.texowners[i].h = -1;
1909 state.texowners[i].slice = NULL;
1913 else if (!strncmp ("interrupt", p, 9)) {
1914 printd ("vmsg interrupted");
1916 else {
1917 errx (1, "unknown command %.*s", len, p);
1920 return 0;
1923 CAMLprim value ml_isexternallink (value uri_v)
1925 CAMLparam1 (uri_v);
1926 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1927 CAMLreturn (Val_bool (ext));
1930 CAMLprim value ml_uritolocation (value uri_v)
1932 CAMLparam1 (uri_v);
1933 CAMLlocal1 (ret_v);
1934 int pageno;
1935 fz_point xy;
1936 struct pagedim *pdim;
1938 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1939 &xy.x, &xy.y);
1940 pdim = pdimofpageno (pageno);
1941 fz_transform_point (&xy, &pdim->ctm);
1942 ret_v = caml_alloc_tuple (3);
1943 Field (ret_v, 0) = Val_int (pageno);
1944 Field (ret_v, 1) = caml_copy_double (xy.x);
1945 Field (ret_v, 2) = caml_copy_double (xy.y);
1946 CAMLreturn (ret_v);
1949 CAMLprim value ml_realloctexts (value texcount_v)
1951 CAMLparam1 (texcount_v);
1952 int ok;
1954 if (trylock (__func__)) {
1955 ok = 0;
1956 goto done;
1958 realloctexts (Int_val (texcount_v));
1959 ok = 1;
1960 unlock (__func__);
1962 done:
1963 CAMLreturn (Val_bool (ok));
1966 static void recti (int x0, int y0, int x1, int y1)
1968 GLfloat *v = state.vertices;
1970 glVertexPointer (2, GL_FLOAT, 0, v);
1971 v[0] = x0; v[1] = y0;
1972 v[2] = x1; v[3] = y0;
1973 v[4] = x0; v[5] = y1;
1974 v[6] = x1; v[7] = y1;
1975 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1978 static void showsel (struct page *page, int ox, int oy)
1980 fz_irect bbox;
1981 fz_rect rect;
1982 fz_stext_block *block;
1983 int seen = 0;
1984 unsigned char selcolor[] = {15,15,15,140};
1986 if (!page->fmark.ch || !page->lmark.ch) return;
1988 glEnable (GL_BLEND);
1989 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1990 glColor4ubv (selcolor);
1992 ox += state.pagedims[page->pdimno].bounds.x0;
1993 oy += state.pagedims[page->pdimno].bounds.y0;
1995 for (block = page->text->first_block; block; block = block->next) {
1996 fz_stext_line *line;
1998 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1999 for (line = block->u.t.first_line; line; line = line->next) {
2000 fz_stext_char *ch;
2002 rect = fz_empty_rect;
2003 for (ch = line->first_char; ch; ch = ch->next) {
2004 if (ch == page->fmark.ch) seen = 1;
2005 if (seen) fz_union_rect (&rect, &ch->bbox);
2006 if (ch == page->lmark.ch) {
2007 fz_round_rect (&bbox, &rect);
2008 recti (bbox.x0 + ox, bbox.y0 + oy,
2009 bbox.x1 + ox, bbox.y1 + oy);
2010 goto done;
2013 fz_round_rect (&bbox, &rect);
2014 recti (bbox.x0 + ox, bbox.y0 + oy,
2015 bbox.x1 + ox, bbox.y1 + oy);
2018 done:
2019 glDisable (GL_BLEND);
2022 #include "glfont.c"
2024 static void stipplerect (fz_matrix *m,
2025 fz_point *p1,
2026 fz_point *p2,
2027 fz_point *p3,
2028 fz_point *p4,
2029 GLfloat *texcoords,
2030 GLfloat *vertices)
2032 fz_transform_point (p1, m);
2033 fz_transform_point (p2, m);
2034 fz_transform_point (p3, m);
2035 fz_transform_point (p4, m);
2037 float w, h, s, t;
2039 w = p2->x - p1->x;
2040 h = p2->y - p1->y;
2041 t = hypotf (w, h) * .25f;
2043 w = p3->x - p2->x;
2044 h = p3->y - p2->y;
2045 s = hypotf (w, h) * .25f;
2047 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2048 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2050 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2051 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2053 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2054 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2056 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2057 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2059 glDrawArrays (GL_LINES, 0, 8);
2062 static void solidrect (fz_matrix *m,
2063 fz_point *p1,
2064 fz_point *p2,
2065 fz_point *p3,
2066 fz_point *p4,
2067 GLfloat *vertices)
2069 fz_transform_point (p1, m);
2070 fz_transform_point (p2, m);
2071 fz_transform_point (p3, m);
2072 fz_transform_point (p4, m);
2073 vertices[0] = p1->x; vertices[1] = p1->y;
2074 vertices[2] = p2->x; vertices[3] = p2->y;
2076 vertices[4] = p3->x; vertices[5] = p3->y;
2077 vertices[6] = p4->x; vertices[7] = p4->y;
2078 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2081 static void ensurelinks (struct page *page)
2083 if (!page->links)
2084 page->links = fz_load_links (state.ctx, page->fzpage);
2087 static void highlightlinks (struct page *page, int xoff, int yoff)
2089 fz_matrix ctm, tm, pm;
2090 fz_link *link;
2091 GLfloat *texcoords = state.texcoords;
2092 GLfloat *vertices = state.vertices;
2094 ensurelinks (page);
2096 glEnable (GL_TEXTURE_1D);
2097 glEnable (GL_BLEND);
2098 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2099 glBindTexture (GL_TEXTURE_1D, state.stid);
2101 xoff -= state.pagedims[page->pdimno].bounds.x0;
2102 yoff -= state.pagedims[page->pdimno].bounds.y0;
2103 fz_translate (&tm, xoff, yoff);
2104 pm = pagectm (page);
2105 fz_concat (&ctm, &pm, &tm);
2107 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2108 glVertexPointer (2, GL_FLOAT, 0, vertices);
2110 for (link = page->links; link; link = link->next) {
2111 fz_point p1, p2, p3, p4;
2113 p1.x = link->rect.x0;
2114 p1.y = link->rect.y0;
2116 p2.x = link->rect.x1;
2117 p2.y = link->rect.y0;
2119 p3.x = link->rect.x1;
2120 p3.y = link->rect.y1;
2122 p4.x = link->rect.x0;
2123 p4.y = link->rect.y1;
2125 /* TODO: different colours for different schemes */
2126 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2127 else glColor3ub (255, 0, 0);
2129 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2132 for (int i = 0; i < page->annotcount; ++i) {
2133 fz_point p1, p2, p3, p4;
2134 struct annot *annot = &page->annots[i];
2136 p1.x = annot->bbox.x0;
2137 p1.y = annot->bbox.y0;
2139 p2.x = annot->bbox.x1;
2140 p2.y = annot->bbox.y0;
2142 p3.x = annot->bbox.x1;
2143 p3.y = annot->bbox.y1;
2145 p4.x = annot->bbox.x0;
2146 p4.y = annot->bbox.y1;
2148 glColor3ub (0, 0, 128);
2149 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2152 glDisable (GL_BLEND);
2153 glDisable (GL_TEXTURE_1D);
2156 static int compareslinks (const void *l, const void *r)
2158 struct slink const *ls = l;
2159 struct slink const *rs = r;
2160 if (ls->bbox.y0 == rs->bbox.y0) {
2161 return rs->bbox.x0 - rs->bbox.x0;
2163 return ls->bbox.y0 - rs->bbox.y0;
2166 static void droptext (struct page *page)
2168 if (page->text) {
2169 fz_drop_stext_page (state.ctx, page->text);
2170 page->fmark.ch = NULL;
2171 page->lmark.ch = NULL;
2172 page->text = NULL;
2176 static void dropannots (struct page *page)
2178 if (page->annots) {
2179 free (page->annots);
2180 page->annots = NULL;
2181 page->annotcount = 0;
2185 static void ensureannots (struct page *page)
2187 int i, count = 0;
2188 size_t annotsize = sizeof (*page->annots);
2189 fz_annot *annot;
2191 if (state.gen != page->agen) {
2192 dropannots (page);
2193 page->agen = state.gen;
2195 if (page->annots) return;
2197 for (annot = fz_first_annot (state.ctx, page->fzpage);
2198 annot;
2199 annot = fz_next_annot (state.ctx, annot)) {
2200 count++;
2203 if (count > 0) {
2204 page->annotcount = count;
2205 page->annots = calloc (count, annotsize);
2206 if (!page->annots) {
2207 err (1, "calloc annots %d", count);
2210 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2211 annot;
2212 annot = fz_next_annot (state.ctx, annot), i++) {
2213 fz_rect rect;
2215 fz_bound_annot (state.ctx, annot, &rect);
2216 page->annots[i].annot = annot;
2217 fz_round_rect (&page->annots[i].bbox, &rect);
2222 static void dropslinks (struct page *page)
2224 if (page->slinks) {
2225 free (page->slinks);
2226 page->slinks = NULL;
2227 page->slinkcount = 0;
2229 if (page->links) {
2230 fz_drop_link (state.ctx, page->links);
2231 page->links = NULL;
2235 static void ensureslinks (struct page *page)
2237 fz_matrix ctm;
2238 int i, count;
2239 size_t slinksize = sizeof (*page->slinks);
2240 fz_link *link;
2242 ensureannots (page);
2243 if (state.gen != page->sgen) {
2244 dropslinks (page);
2245 page->sgen = state.gen;
2247 if (page->slinks) return;
2249 ensurelinks (page);
2250 ctm = pagectm (page);
2252 count = page->annotcount;
2253 for (link = page->links; link; link = link->next) {
2254 count++;
2256 if (count > 0) {
2257 int j;
2259 page->slinkcount = count;
2260 page->slinks = calloc (count, slinksize);
2261 if (!page->slinks) {
2262 err (1, "calloc slinks %d", count);
2265 for (i = 0, link = page->links; link; ++i, link = link->next) {
2266 fz_rect rect;
2268 rect = link->rect;
2269 fz_transform_rect (&rect, &ctm);
2270 page->slinks[i].tag = SLINK;
2271 page->slinks[i].u.link = link;
2272 fz_round_rect (&page->slinks[i].bbox, &rect);
2274 for (j = 0; j < page->annotcount; ++j, ++i) {
2275 fz_rect rect;
2276 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2277 fz_transform_rect (&rect, &ctm);
2278 fz_round_rect (&page->slinks[i].bbox, &rect);
2280 page->slinks[i].tag = SANNOT;
2281 page->slinks[i].u.annot = page->annots[j].annot;
2283 qsort (page->slinks, count, slinksize, compareslinks);
2287 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2288 static void fmt_linkn (char *s, unsigned int u)
2290 unsigned int len; unsigned int q;
2291 unsigned int zma = 'z' - 'a' + 1;
2292 len = 1; q = u;
2293 while (q > zma - 1) { ++len; q /= zma; }
2294 if (s) {
2295 s += len;
2296 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2297 /* handles u == 0 */
2299 s[len] = 0;
2302 static void highlightslinks (struct page *page, int xoff, int yoff,
2303 int noff, char *targ, int tlen, int hfsize)
2305 char buf[40];
2306 struct slink *slink;
2307 double x0, y0, x1, y1, w;
2309 ensureslinks (page);
2310 glColor3ub (0xc3, 0xb0, 0x91);
2311 for (int i = 0; i < page->slinkcount; ++i) {
2312 fmt_linkn (buf, i + noff);
2313 if (!tlen || !strncmp (targ, buf, tlen)) {
2314 slink = &page->slinks[i];
2316 x0 = slink->bbox.x0 + xoff - 5;
2317 y1 = slink->bbox.y0 + yoff - 5;
2318 y0 = y1 + 10 + hfsize;
2319 w = measure_string (state.face, hfsize, buf);
2320 x1 = x0 + w + 10;
2321 recti (x0, y0, x1, y1);
2325 glEnable (GL_BLEND);
2326 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2327 glEnable (GL_TEXTURE_2D);
2328 glColor3ub (0, 0, 0);
2329 for (int i = 0; i < page->slinkcount; ++i) {
2330 fmt_linkn (buf, i + noff);
2331 if (!tlen || !strncmp (targ, buf, tlen)) {
2332 slink = &page->slinks[i];
2334 x0 = slink->bbox.x0 + xoff;
2335 y0 = slink->bbox.y0 + yoff + hfsize;
2336 draw_string (state.face, hfsize, x0, y0, buf);
2339 glDisable (GL_TEXTURE_2D);
2340 glDisable (GL_BLEND);
2343 static void uploadslice (struct tile *tile, struct slice *slice)
2345 int offset;
2346 struct slice *slice1;
2347 unsigned char *texdata;
2349 offset = 0;
2350 for (slice1 = tile->slices; slice != slice1; slice1++) {
2351 offset += slice1->h * tile->w * tile->pixmap->n;
2353 if (slice->texindex != -1 && slice->texindex < state.texcount
2354 && state.texowners[slice->texindex].slice == slice) {
2355 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2357 else {
2358 int subimage = 0;
2359 int texindex = state.texindex++ % state.texcount;
2361 if (state.texowners[texindex].w == tile->w) {
2362 if (state.texowners[texindex].h >= slice->h) {
2363 subimage = 1;
2365 else {
2366 state.texowners[texindex].h = slice->h;
2369 else {
2370 state.texowners[texindex].h = slice->h;
2373 state.texowners[texindex].w = tile->w;
2374 state.texowners[texindex].slice = slice;
2375 slice->texindex = texindex;
2377 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2378 #if TEXT_TYPE == GL_TEXTURE_2D
2379 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2380 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2381 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2382 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2383 #endif
2384 if (tile->pbo) {
2385 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2386 texdata = 0;
2388 else {
2389 texdata = tile->pixmap->samples;
2391 if (subimage) {
2392 glTexSubImage2D (TEXT_TYPE,
2396 tile->w,
2397 slice->h,
2398 state.texform,
2399 state.texty,
2400 texdata+offset
2403 else {
2404 glTexImage2D (TEXT_TYPE,
2406 state.texiform,
2407 tile->w,
2408 slice->h,
2410 state.texform,
2411 state.texty,
2412 texdata+offset
2415 if (tile->pbo) {
2416 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2421 CAMLprim void ml_begintiles (value unit_v)
2423 CAMLparam1 (unit_v);
2424 glEnable (TEXT_TYPE);
2425 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2426 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2427 CAMLreturn0;
2430 CAMLprim void ml_endtiles (value unit_v)
2432 CAMLparam1 (unit_v);
2433 glDisable (TEXT_TYPE);
2434 CAMLreturn0;
2437 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2439 CAMLparam2 (args_v, ptr_v);
2440 int dispx = Int_val (Field (args_v, 0));
2441 int dispy = Int_val (Field (args_v, 1));
2442 int dispw = Int_val (Field (args_v, 2));
2443 int disph = Int_val (Field (args_v, 3));
2444 int tilex = Int_val (Field (args_v, 4));
2445 int tiley = Int_val (Field (args_v, 5));
2446 char *s = String_val (ptr_v);
2447 struct tile *tile = parse_pointer (__func__, s);
2448 int slicey, firstslice;
2449 struct slice *slice;
2450 GLfloat *texcoords = state.texcoords;
2451 GLfloat *vertices = state.vertices;
2453 firstslice = tiley / tile->sliceheight;
2454 slice = &tile->slices[firstslice];
2455 slicey = tiley % tile->sliceheight;
2457 while (disph > 0) {
2458 int dh;
2460 dh = slice->h - slicey;
2461 dh = fz_mini (disph, dh);
2462 uploadslice (tile, slice);
2464 texcoords[0] = tilex; texcoords[1] = slicey;
2465 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2466 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2467 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2469 vertices[0] = dispx; vertices[1] = dispy;
2470 vertices[2] = dispx+dispw; vertices[3] = dispy;
2471 vertices[4] = dispx; vertices[5] = dispy+dh;
2472 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2474 #if TEXT_TYPE == GL_TEXTURE_2D
2475 for (int i = 0; i < 8; ++i) {
2476 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2478 #endif
2480 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2481 dispy += dh;
2482 disph -= dh;
2483 slice++;
2484 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2485 slicey = 0;
2487 CAMLreturn0;
2490 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2492 fz_matrix ctm, tm, pm;
2493 fz_point p1, p2, p3, p4;
2494 GLfloat *vertices = state.vertices;
2495 double *v = (double *) rects_v;
2497 xoff -= state.pagedims[page->pdimno].bounds.x0;
2498 yoff -= state.pagedims[page->pdimno].bounds.y0;
2499 fz_translate (&tm, xoff, yoff);
2500 pm = pagectm (page);
2501 fz_concat (&ctm, &pm, &tm);
2503 glEnable (GL_BLEND);
2504 glVertexPointer (2, GL_FLOAT, 0, vertices);
2506 glColor4dv (v);
2507 p1.x = v[4];
2508 p1.y = v[5];
2510 p2.x = v[6];
2511 p2.y = v[5];
2513 p3.x = v[6];
2514 p3.y = v[7];
2516 p4.x = v[4];
2517 p4.y = v[7];
2518 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2519 glDisable (GL_BLEND);
2522 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2523 value xoff_v, value yoff_v,
2524 value li_v)
2526 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2527 int xoff = Int_val (xoff_v);
2528 int yoff = Int_val (yoff_v);
2529 int noff = Int_val (Field (li_v, 0));
2530 char *targ = String_val (Field (li_v, 1));
2531 int tlen = caml_string_length (Field (li_v, 1));
2532 int hfsize = Int_val (Field (li_v, 2));
2533 char *s = String_val (ptr_v);
2534 int hlmask = Int_val (hlinks_v);
2535 struct page *page = parse_pointer (__func__, s);
2537 if (!page->fzpage) {
2538 /* deal with loadpage failed pages */
2539 goto done;
2542 if (trylock (__func__)) {
2543 noff = -1;
2544 goto done;
2547 ensureannots (page);
2548 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2549 if (hlmask & 2) {
2550 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2551 noff = page->slinkcount;
2553 if (page->tgen == state.gen) {
2554 showsel (page, xoff, yoff);
2556 unlock (__func__);
2558 done:
2559 CAMLreturn (Val_int (noff));
2562 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2563 value rects_v)
2565 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2566 int xoff = Int_val (xoff_v);
2567 int yoff = Int_val (yoff_v);
2568 char *s = String_val (ptr_v);
2569 struct page *page = parse_pointer (__func__, s);
2571 drawprect (page, xoff, yoff, rects_v);
2572 CAMLreturn0;
2575 static struct annot *getannot (struct page *page, int x, int y)
2577 fz_point p;
2578 fz_matrix ctm;
2579 const fz_matrix *tctm;
2580 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2582 if (!page->annots) return NULL;
2584 if (pdf) {
2585 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2586 tctm = &state.pagedims[page->pdimno].tctm;
2588 else {
2589 tctm = &fz_identity;
2592 p.x = x;
2593 p.y = y;
2595 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2596 fz_invert_matrix (&ctm, &ctm);
2597 fz_transform_point (&p, &ctm);
2599 if (pdf) {
2600 for (int i = 0; i < page->annotcount; ++i) {
2601 struct annot *a = &page->annots[i];
2602 fz_rect rect;
2604 fz_bound_annot (state.ctx, a->annot, &rect);
2605 if (p.x >= rect.x0 && p.x <= rect.x1) {
2606 if (p.y >= rect.y0 && p.y <= rect.y1)
2607 return a;
2611 return NULL;
2614 static fz_link *getlink (struct page *page, int x, int y)
2616 fz_point p;
2617 fz_matrix ctm;
2618 fz_link *link;
2620 ensureslinks (page);
2622 p.x = x;
2623 p.y = y;
2625 ctm = pagectm (page);
2626 fz_invert_matrix (&ctm, &ctm);
2627 fz_transform_point (&p, &ctm);
2629 for (link = page->links; link; link = link->next) {
2630 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2631 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2632 return link;
2636 return NULL;
2639 static void ensuretext (struct page *page)
2641 if (state.gen != page->tgen) {
2642 droptext (page);
2643 page->tgen = state.gen;
2645 if (!page->text) {
2646 fz_matrix ctm;
2647 fz_device *tdev;
2649 page->text = fz_new_stext_page (state.ctx,
2650 &state.pagedims[page->pdimno].mediabox);
2651 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2652 ctm = pagectm (page);
2653 fz_run_display_list (state.ctx, page->dlist,
2654 tdev, &ctm, &fz_infinite_rect, NULL);
2655 fz_close_device (state.ctx, tdev);
2656 fz_drop_device (state.ctx, tdev);
2660 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2662 CAMLparam2 (start_page_v, dir_v);
2663 CAMLlocal1 (ret_v);
2664 int i, dir = Int_val (dir_v);
2665 int start_page = Int_val (start_page_v);
2666 int end_page = dir > 0 ? state.pagecount : -1;
2667 pdf_document *pdf;
2669 fz_var (end_page);
2670 ret_v = Val_int (0);
2671 lock (__func__);
2672 pdf = pdf_specifics (state.ctx, state.doc);
2673 for (i = start_page + dir; i != end_page; i += dir) {
2674 int found;
2676 fz_var (found);
2677 if (pdf) {
2678 pdf_page *page = NULL;
2680 fz_var (page);
2681 fz_try (state.ctx) {
2682 page = pdf_load_page (state.ctx, pdf, i);
2683 found = !!page->links || !!page->annots;
2685 fz_catch (state.ctx) {
2686 found = 0;
2688 if (page) {
2689 fz_drop_page (state.ctx, &page->super);
2692 else {
2693 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2694 fz_link *link = fz_load_links (state.ctx, page);
2695 found = !!link;
2696 fz_drop_link (state.ctx, link);
2697 fz_drop_page (state.ctx, page);
2700 if (found) {
2701 ret_v = caml_alloc_small (1, 1);
2702 Field (ret_v, 0) = Val_int (i);
2703 goto unlock;
2706 unlock:
2707 unlock (__func__);
2708 CAMLreturn (ret_v);
2711 enum { dir_first, dir_last };
2712 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2714 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2716 CAMLparam2 (ptr_v, dir_v);
2717 CAMLlocal2 (ret_v, pos_v);
2718 struct page *page;
2719 int dirtag, i, slinkindex;
2720 struct slink *found = NULL ,*slink;
2721 char *s = String_val (ptr_v);
2723 page = parse_pointer (__func__, s);
2724 ret_v = Val_int (0);
2725 lock (__func__);
2726 ensureslinks (page);
2728 if (Is_block (dir_v)) {
2729 dirtag = Tag_val (dir_v);
2730 switch (dirtag) {
2731 case dir_first_visible:
2733 int x0, y0, dir, first_index, last_index;
2735 pos_v = Field (dir_v, 0);
2736 x0 = Int_val (Field (pos_v, 0));
2737 y0 = Int_val (Field (pos_v, 1));
2738 dir = Int_val (Field (pos_v, 2));
2740 if (dir >= 0) {
2741 dir = 1;
2742 first_index = 0;
2743 last_index = page->slinkcount;
2745 else {
2746 first_index = page->slinkcount - 1;
2747 last_index = -1;
2750 for (i = first_index; i != last_index; i += dir) {
2751 slink = &page->slinks[i];
2752 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2753 found = slink;
2754 break;
2758 break;
2760 case dir_left:
2761 slinkindex = Int_val (Field (dir_v, 0));
2762 found = &page->slinks[slinkindex];
2763 for (i = slinkindex - 1; i >= 0; --i) {
2764 slink = &page->slinks[i];
2765 if (slink->bbox.x0 < found->bbox.x0) {
2766 found = slink;
2767 break;
2770 break;
2772 case dir_right:
2773 slinkindex = Int_val (Field (dir_v, 0));
2774 found = &page->slinks[slinkindex];
2775 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2776 slink = &page->slinks[i];
2777 if (slink->bbox.x0 > found->bbox.x0) {
2778 found = slink;
2779 break;
2782 break;
2784 case dir_down:
2785 slinkindex = Int_val (Field (dir_v, 0));
2786 found = &page->slinks[slinkindex];
2787 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2788 slink = &page->slinks[i];
2789 if (slink->bbox.y0 >= found->bbox.y0) {
2790 found = slink;
2791 break;
2794 break;
2796 case dir_up:
2797 slinkindex = Int_val (Field (dir_v, 0));
2798 found = &page->slinks[slinkindex];
2799 for (i = slinkindex - 1; i >= 0; --i) {
2800 slink = &page->slinks[i];
2801 if (slink->bbox.y0 <= found->bbox.y0) {
2802 found = slink;
2803 break;
2806 break;
2809 else {
2810 dirtag = Int_val (dir_v);
2811 switch (dirtag) {
2812 case dir_first:
2813 found = page->slinks;
2814 break;
2816 case dir_last:
2817 if (page->slinks) {
2818 found = page->slinks + (page->slinkcount - 1);
2820 break;
2823 if (found) {
2824 ret_v = caml_alloc_small (2, 1);
2825 Field (ret_v, 0) = Val_int (found - page->slinks);
2828 unlock (__func__);
2829 CAMLreturn (ret_v);
2832 enum { uuri, utext, uannot };
2834 CAMLprim value ml_getlink (value ptr_v, value n_v)
2836 CAMLparam2 (ptr_v, n_v);
2837 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2838 fz_link *link;
2839 struct page *page;
2840 char *s = String_val (ptr_v);
2841 struct slink *slink;
2843 ret_v = Val_int (0);
2844 page = parse_pointer (__func__, s);
2846 lock (__func__);
2847 ensureslinks (page);
2848 slink = &page->slinks[Int_val (n_v)];
2849 if (slink->tag == SLINK) {
2850 link = slink->u.link;
2851 str_v = caml_copy_string (link->uri);
2852 ret_v = caml_alloc_small (1, uuri);
2853 Field (ret_v, 0) = str_v;
2855 else {
2856 ret_v = caml_alloc_small (1, uannot);
2857 tup_v = caml_alloc_tuple (2);
2858 Field (ret_v, 0) = tup_v;
2859 Field (tup_v, 0) = ptr_v;
2860 Field (tup_v, 1) = n_v;
2862 unlock (__func__);
2864 CAMLreturn (ret_v);
2867 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2869 CAMLparam2 (ptr_v, n_v);
2870 CAMLlocal1 (ret_v);
2871 pdf_document *pdf;
2872 char *contents = NULL;
2874 lock (__func__);
2875 pdf = pdf_specifics (state.ctx, state.doc);
2876 if (pdf) {
2877 char *s = String_val (ptr_v);
2878 struct page *page;
2879 struct slink *slink;
2881 page = parse_pointer (__func__, s);
2882 slink = &page->slinks[Int_val (n_v)];
2883 contents = pdf_copy_annot_contents (state.ctx,
2884 (pdf_annot *) slink->u.annot);
2886 unlock (__func__);
2887 if (contents) {
2888 ret_v = caml_copy_string (contents);
2889 fz_free (state.ctx, contents);
2891 else {
2892 ret_v = caml_copy_string ("");
2894 CAMLreturn (ret_v);
2897 CAMLprim value ml_getlinkcount (value ptr_v)
2899 CAMLparam1 (ptr_v);
2900 struct page *page;
2901 char *s = String_val (ptr_v);
2903 page = parse_pointer (__func__, s);
2904 CAMLreturn (Val_int (page->slinkcount));
2907 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2909 CAMLparam2 (ptr_v, n_v);
2910 CAMLlocal1 (ret_v);
2911 struct page *page;
2912 struct slink *slink;
2913 char *s = String_val (ptr_v);
2915 page = parse_pointer (__func__, s);
2916 ret_v = caml_alloc_tuple (4);
2917 lock (__func__);
2918 ensureslinks (page);
2920 slink = &page->slinks[Int_val (n_v)];
2921 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2922 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2923 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2924 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2925 unlock (__func__);
2926 CAMLreturn (ret_v);
2929 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2931 CAMLparam3 (ptr_v, x_v, y_v);
2932 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2933 fz_link *link;
2934 struct annot *annot;
2935 struct page *page;
2936 char *ptr = String_val (ptr_v);
2937 int x = Int_val (x_v), y = Int_val (y_v);
2938 struct pagedim *pdim;
2940 ret_v = Val_int (0);
2941 if (trylock (__func__)) {
2942 goto done;
2945 page = parse_pointer (__func__, ptr);
2946 pdim = &state.pagedims[page->pdimno];
2947 x += pdim->bounds.x0;
2948 y += pdim->bounds.y0;
2951 annot = getannot (page, x, y);
2952 if (annot) {
2953 int i, n = -1;
2955 ensureslinks (page);
2956 for (i = 0; i < page->slinkcount; ++i) {
2957 if (page->slinks[i].tag == SANNOT
2958 && page->slinks[i].u.annot == annot->annot) {
2959 n = i;
2960 break;
2963 ret_v = caml_alloc_small (1, uannot);
2964 tup_v = caml_alloc_tuple (2);
2965 Field (ret_v, 0) = tup_v;
2966 Field (tup_v, 0) = ptr_v;
2967 Field (tup_v, 1) = Val_int (n);
2968 goto unlock;
2972 link = getlink (page, x, y);
2973 if (link) {
2974 str_v = caml_copy_string (link->uri);
2975 ret_v = caml_alloc_small (1, uuri);
2976 Field (ret_v, 0) = str_v;
2978 else {
2979 fz_rect *b;
2980 fz_stext_block *block;
2982 ensuretext (page);
2984 for (block = page->text->first_block; block; block = block->next) {
2985 fz_stext_line *line;
2987 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2988 b = &block->bbox;
2989 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2990 continue;
2992 for (line = block->u.t.first_line; line; line = line->next) {
2993 fz_stext_char *ch;
2995 b = &line->bbox;
2996 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2997 continue;
2999 for (ch = line->first_char; ch; ch = ch->next) {
3000 b = &ch->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;