Do not leak memory
[llpp.git] / link.c
blob191e9d89f7f1295c2d923b7b061929b81623fca6
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 /* Type punned unions here. Why? Less code (Adjusted by more comments).
408 https://en.wikipedia.org/wiki/Type_punning */
409 /* Then again https://bugs.llvm.org/show_bug.cgi?id=31928 - hmm */
410 union { uint32_t len; char raw[4]; } buf;
411 readdata (fd, buf.raw, 4);
412 return buf.len;
415 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
417 CAMLparam3 (fd_v, bytes_v, len_v);
418 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
419 CAMLreturn0;
422 CAMLprim value ml_rcmd (value fd_v)
424 CAMLparam1 (fd_v);
425 CAMLlocal1 (strdata_v);
426 int fd = Int_val (fd_v);
427 int len = readlen (fd);
428 strdata_v = caml_alloc_string (len);
429 readdata (fd, String_val (strdata_v), len);
430 CAMLreturn (strdata_v);
433 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
435 int size = 64, len;
436 va_list ap;
437 char fbuf[size];
438 char *buf = fbuf;
440 for (;;) {
441 va_start (ap, fmt);
442 len = vsnprintf (buf, size, fmt, ap);
443 va_end (ap);
445 if (len > -1) {
446 if (len < size - 4) {
447 writedata (state.csock, buf, len);
448 break;
450 else size = len + 5;
452 else {
453 err (1, "vsnprintf for `%s' failed", fmt);
455 buf = realloc (buf == fbuf ? NULL : buf, size);
456 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
458 if (buf != fbuf) free (buf);
461 static void closedoc (void)
463 #ifdef CACHE_PAGEREFS
464 if (state.pdflut.objs) {
465 for (int i = 0; i < state.pdflut.count; ++i) {
466 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
468 free (state.pdflut.objs);
469 state.pdflut.objs = NULL;
470 state.pdflut.idx = 0;
472 #endif
473 if (state.doc) {
474 fz_drop_document (state.ctx, state.doc);
475 state.doc = NULL;
479 static int openxref (char *filename, char *password)
481 for (int i = 0; i < state.texcount; ++i) {
482 state.texowners[i].w = -1;
483 state.texowners[i].slice = NULL;
486 closedoc ();
488 state.dirty = 0;
489 if (state.pagedims) {
490 free (state.pagedims);
491 state.pagedims = NULL;
493 state.pagedimcount = 0;
495 fz_set_aa_level (state.ctx, state.aalevel);
496 state.doc = fz_open_document (state.ctx, filename);
497 if (fz_needs_password (state.ctx, state.doc)) {
498 if (password && !*password) {
499 printd ("pass");
500 return 0;
502 else {
503 int ok = fz_authenticate_password (state.ctx, state.doc, password);
504 if (!ok) {
505 printd ("pass fail");
506 return 0;
510 state.pagecount = fz_count_pages (state.ctx, state.doc);
511 return 1;
514 static void pdfinfo (void)
516 struct { char *tag; char *name; } metatbl[] = {
517 { FZ_META_INFO_TITLE, "Title" },
518 { FZ_META_INFO_AUTHOR, "Author" },
519 { FZ_META_FORMAT, "Format" },
520 { FZ_META_ENCRYPTION, "Encryption" },
521 { "info:Creator", "Creator" },
522 { "info:Producer", "Producer" },
523 { "info:CreationDate", "Creation date" },
525 int len = 0;
526 char *buf = NULL;
528 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
529 int need;
530 again:
531 need = fz_lookup_metadata (state.ctx, state.doc,
532 metatbl[i].tag, buf, len);
533 if (need > 0) {
534 if (need <= len) {
535 printd ("info %s\t%s", metatbl[i].name, buf);
537 else {
538 buf = realloc (buf, need + 1);
539 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
540 len = need + 1;
541 goto again;
545 free (buf);
547 printd ("infoend");
550 static void unlinktile (struct tile *tile)
552 for (int i = 0; i < tile->slicecount; ++i) {
553 struct slice *s = &tile->slices[i];
555 if (s->texindex != -1) {
556 if (state.texowners[s->texindex].slice == s) {
557 state.texowners[s->texindex].slice = NULL;
563 static void freepage (struct page *page)
565 if (!page) return;
566 if (page->text) {
567 fz_drop_stext_page (state.ctx, page->text);
569 if (page->slinks) {
570 free (page->slinks);
572 fz_drop_display_list (state.ctx, page->dlist);
573 fz_drop_page (state.ctx, page->fzpage);
574 free (page);
577 static void freetile (struct tile *tile)
579 unlinktile (tile);
580 if (!tile->pbo) {
581 #ifndef PIGGYBACK
582 fz_drop_pixmap (state.ctx, tile->pixmap);
583 #else
584 if (state.pig) {
585 fz_drop_pixmap (state.ctx, state.pig);
587 state.pig = tile->pixmap;
588 #endif
590 else {
591 free (tile->pbo);
592 fz_drop_pixmap (state.ctx, tile->pixmap);
594 free (tile);
597 #ifdef __ALTIVEC__
598 #include <stdint.h>
599 #include <altivec.h>
601 static int cacheline32bytes;
603 static void __attribute__ ((constructor)) clcheck (void)
605 char **envp = environ;
606 unsigned long *auxv;
608 while (*envp++);
610 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
611 if (*auxv == 19) {
612 cacheline32bytes = auxv[1] == 32;
613 return;
618 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
620 size_t size = pixmap->w * pixmap->h * pixmap->n;
621 if (cacheline32bytes && size > 32) {
622 intptr_t a1, a2, diff;
623 size_t sizea, i;
624 vector unsigned char v = vec_splat_u8 (-1);
625 vector unsigned char *p;
627 a1 = a2 = (intptr_t) pixmap->samples;
628 a2 = (a1 + 31) & ~31;
629 diff = a2 - a1;
630 sizea = size - diff;
631 p = (void *) a2;
633 while (a1 != a2) *(char *) a1++ = 0xff;
634 for (i = 0; i < (sizea & ~31); i += 32) {
635 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
636 vec_st (v, i, p);
637 vec_st (v, i + 16, p);
639 while (i < sizea) *((char *) a1 + i++) = 0xff;
641 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
643 #else
644 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
645 #endif
647 static void trimctm (pdf_page *page, int pindex)
649 fz_matrix ctm;
650 struct pagedim *pdim = &state.pagedims[pindex];
652 if (!page) return;
653 if (!pdim->tctmready) {
654 fz_rect realbox, mediabox;
655 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
657 fz_rotate (&rm, -pdim->rotate);
658 fz_scale (&sm, 1, -1);
659 fz_concat (&ctm, &rm, &sm);
660 realbox = pdim->mediabox;
661 fz_transform_rect (&realbox, &ctm);
662 fz_translate (&tm, -realbox.x0, -realbox.y0);
663 fz_concat (&ctm1, &ctm, &tm);
664 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
665 fz_invert_matrix (&im, &page_ctm);
666 fz_concat (&ctm, &im, &ctm1);
667 pdim->tctm = ctm;
668 pdim->tctmready = 1;
672 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
674 fz_matrix ctm, tm;
675 int pdimno = pdim - state.pagedims;
677 if (pdf_specifics (state.ctx, state.doc)) {
678 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
679 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
681 else {
682 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
683 fz_concat (&ctm, &tm, &pdim->ctm);
685 return ctm;
688 static fz_matrix pagectm (struct page *page)
690 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
693 static void *loadpage (int pageno, int pindex)
695 fz_device *dev;
696 struct page *page;
698 page = calloc (sizeof (struct page), 1);
699 if (!page) {
700 err (1, "calloc page %d", pageno);
703 page->dlist = fz_new_display_list (state.ctx, NULL);
704 dev = fz_new_list_device (state.ctx, page->dlist);
705 fz_try (state.ctx) {
706 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
707 fz_run_page (state.ctx, page->fzpage, dev,
708 &fz_identity, NULL);
710 fz_catch (state.ctx) {
711 page->fzpage = NULL;
713 fz_close_device (state.ctx, dev);
714 fz_drop_device (state.ctx, dev);
716 page->pdimno = pindex;
717 page->pageno = pageno;
718 page->sgen = state.gen;
719 page->agen = state.gen;
720 page->tgen = state.gen;
721 return page;
724 static struct tile *alloctile (int h)
726 int slicecount;
727 size_t tilesize;
728 struct tile *tile;
730 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
731 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
732 tile = calloc (tilesize, 1);
733 if (!tile) {
734 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
736 for (int i = 0; i < slicecount; ++i) {
737 int sh = fz_mini (h, state.sliceheight);
738 tile->slices[i].h = sh;
739 tile->slices[i].texindex = -1;
740 h -= sh;
742 tile->slicecount = slicecount;
743 tile->sliceheight = state.sliceheight;
744 return tile;
747 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
748 struct bo *pbo)
750 fz_rect rect;
751 fz_irect bbox;
752 fz_matrix ctm;
753 fz_device *dev;
754 struct tile *tile;
755 struct pagedim *pdim;
757 tile = alloctile (h);
758 pdim = &state.pagedims[page->pdimno];
760 bbox = pdim->bounds;
761 bbox.x0 += x;
762 bbox.y0 += y;
763 bbox.x1 = bbox.x0 + w;
764 bbox.y1 = bbox.y0 + h;
766 if (state.pig) {
767 if (state.pig->w == w
768 && state.pig->h == h
769 && state.pig->colorspace == state.colorspace) {
770 tile->pixmap = state.pig;
771 tile->pixmap->x = bbox.x0;
772 tile->pixmap->y = bbox.y0;
774 else {
775 fz_drop_pixmap (state.ctx, state.pig);
777 state.pig = NULL;
779 if (!tile->pixmap) {
780 if (pbo) {
781 tile->pixmap =
782 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
783 &bbox, NULL, 1, pbo->ptr);
784 tile->pbo = pbo;
786 else {
787 tile->pixmap =
788 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
789 NULL, 1);
793 tile->w = w;
794 tile->h = h;
795 clearpixmap (tile->pixmap);
797 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
798 ctm = pagectm (page);
799 fz_rect_from_irect (&rect, &bbox);
800 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
801 fz_close_device (state.ctx, dev);
802 fz_drop_device (state.ctx, dev);
804 return tile;
807 #ifdef CACHE_PAGEREFS
808 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
809 thanks to Robin Watts */
810 static void
811 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
813 fz_context *ctx = state.ctx; /* doc->ctx; */
814 pdf_obj *kids;
815 int len;
817 if (state.pdflut.idx == state.pagecount) return;
819 kids = pdf_dict_gets (ctx, node, "Kids");
820 len = pdf_array_len (ctx, kids);
822 if (len == 0)
823 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
825 if (pdf_mark_obj (ctx, node))
826 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
827 for (int i = 0; i < len; i++) {
828 pdf_obj *kid = pdf_array_get (ctx, kids, i);
829 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
830 if (*type
831 ? !strcmp (type, "Pages")
832 : pdf_dict_gets (ctx, kid, "Kids")
833 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
834 pdf_collect_pages (doc, kid);
836 else {
837 if (*type
838 ? strcmp (type, "Page") != 0
839 : !pdf_dict_gets (ctx, kid, "MediaBox"))
840 fz_warn (ctx, "non-page object in page tree (%s)", type);
841 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
844 pdf_unmark_obj (ctx, node);
847 static void
848 pdf_load_page_objs (pdf_document *doc)
850 pdf_obj *root = pdf_dict_gets (state.ctx,
851 pdf_trailer (state.ctx, doc), "Root");
852 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
854 if (!node)
855 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
857 state.pdflut.idx = 0;
858 pdf_collect_pages (doc, node);
860 #endif
862 static void initpdims (int wthack)
864 double start, end;
865 FILE *trimf = NULL;
866 fz_rect rootmediabox;
867 int pageno, trim, show;
868 int trimw = 0, cxcount;
869 fz_context *ctx = state.ctx;
870 pdf_document *pdf = pdf_specifics (ctx, state.doc);
872 fz_var (trimw);
873 fz_var (trimf);
874 fz_var (cxcount);
875 start = now ();
877 if (state.trimmargins && state.trimcachepath) {
878 trimf = fopen (state.trimcachepath, "rb");
879 if (!trimf) {
880 trimf = fopen (state.trimcachepath, "wb");
881 trimw = 1;
885 if (state.trimmargins || pdf || !state.cxack)
886 cxcount = state.pagecount;
887 else
888 cxcount = fz_mini (state.pagecount, 1);
890 if (pdf) {
891 pdf_obj *obj;
892 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
893 "Root/Pages/MediaBox");
894 pdf_to_rect (ctx, obj, &rootmediabox);
897 #ifdef CACHE_PAGEREFS
898 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
899 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
900 if (!state.pdflut.objs) {
901 err (1, "malloc pageobjs %zu %d %zu failed",
902 sizeof (*state.pdflut.objs), cxcount,
903 sizeof (*state.pdflut.objs) * cxcount);
905 state.pdflut.count = cxcount;
906 pdf_load_page_objs (pdf);
907 state.pdflut.pdf = pdf;
909 #endif
911 for (pageno = 0; pageno < cxcount; ++pageno) {
912 int rotate = 0;
913 struct pagedim *p;
914 fz_rect mediabox;
916 fz_var (rotate);
917 if (pdf) {
918 pdf_obj *pageref, *pageobj;
920 #ifdef CACHE_PAGEREFS
921 pageref = state.pdflut.objs[pageno];
922 #else
923 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
924 #endif
925 pageobj = pdf_resolve_indirect (ctx, pageref);
926 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
928 if (state.trimmargins) {
929 pdf_obj *obj;
930 pdf_page *page;
932 fz_try (ctx) {
933 page = pdf_load_page (ctx, pdf, pageno);
934 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
935 trim = state.trimanew || !obj;
936 if (trim) {
937 fz_rect rect;
938 fz_device *dev;
939 fz_matrix ctm, page_ctm;
941 dev = fz_new_bbox_device (ctx, &rect);
942 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
943 fz_invert_matrix (&ctm, &page_ctm);
944 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
945 fz_close_device (ctx, dev);
946 fz_drop_device (ctx, dev);
948 rect.x0 += state.trimfuzz.x0;
949 rect.x1 += state.trimfuzz.x1;
950 rect.y0 += state.trimfuzz.y0;
951 rect.y1 += state.trimfuzz.y1;
952 fz_transform_rect (&rect, &ctm);
953 fz_intersect_rect (&rect, &mediabox);
955 if (!fz_is_empty_rect (&rect)) {
956 mediabox = rect;
959 obj = pdf_new_array (ctx, pdf, 4);
960 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
961 mediabox.x0));
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.y0));
964 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
965 mediabox.x1));
966 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
967 mediabox.y1));
968 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
970 else {
971 mediabox.x0 = pdf_to_real (ctx,
972 pdf_array_get (ctx, obj, 0));
973 mediabox.y0 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 1));
975 mediabox.x1 = pdf_to_real (ctx,
976 pdf_array_get (ctx, obj, 2));
977 mediabox.y1 = pdf_to_real (ctx,
978 pdf_array_get (ctx, obj, 3));
981 fz_drop_page (ctx, &page->super);
982 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
983 if (show) {
984 printd ("progress %f Trimming %d",
985 (double) (pageno + 1) / state.pagecount,
986 pageno + 1);
989 fz_catch (ctx) {
990 fprintf (stderr, "failed to load page %d\n", pageno+1);
993 else {
994 int empty = 0;
995 fz_rect cropbox;
997 pdf_to_rect (ctx,
998 pdf_dict_gets (ctx, pageobj, "MediaBox"),
999 &mediabox);
1000 if (fz_is_empty_rect (&mediabox)) {
1001 mediabox.x0 = 0;
1002 mediabox.y0 = 0;
1003 mediabox.x1 = 612;
1004 mediabox.y1 = 792;
1005 empty = 1;
1008 pdf_to_rect (ctx,
1009 pdf_dict_gets (ctx, pageobj, "CropBox"),
1010 &cropbox);
1011 if (!fz_is_empty_rect (&cropbox)) {
1012 if (empty) {
1013 mediabox = cropbox;
1015 else {
1016 fz_intersect_rect (&mediabox, &cropbox);
1019 else {
1020 if (empty) {
1021 if (fz_is_empty_rect (&rootmediabox)) {
1022 fprintf (stderr,
1023 "cannot find page size for page %d\n",
1024 pageno+1);
1026 else {
1027 mediabox = rootmediabox;
1033 else {
1034 if (state.trimmargins && trimw) {
1035 fz_page *page;
1037 fz_try (ctx) {
1038 page = fz_load_page (ctx, state.doc, pageno);
1039 fz_bound_page (ctx, page, &mediabox);
1040 if (state.trimmargins) {
1041 fz_rect rect;
1042 fz_device *dev;
1044 dev = fz_new_bbox_device (ctx, &rect);
1045 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1046 fz_close_device (ctx, dev);
1047 fz_drop_device (ctx, dev);
1049 rect.x0 += state.trimfuzz.x0;
1050 rect.x1 += state.trimfuzz.x1;
1051 rect.y0 += state.trimfuzz.y0;
1052 rect.y1 += state.trimfuzz.y1;
1053 fz_intersect_rect (&rect, &mediabox);
1055 if (!fz_is_empty_rect (&rect)) {
1056 mediabox = rect;
1059 fz_drop_page (ctx, page);
1060 if (!state.cxack) {
1061 printd ("progress %f loading %d",
1062 (double) (pageno + 1) / state.pagecount,
1063 pageno + 1);
1066 fz_catch (ctx) {
1068 if (trimf) {
1069 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1070 if (n - 1) {
1071 err (1, "fwrite trim mediabox");
1075 else {
1076 if (trimf) {
1077 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1078 if (n - 1) {
1079 err (1, "fread trim mediabox %d", pageno);
1082 else {
1083 fz_page *page;
1084 fz_try (ctx) {
1085 page = fz_load_page (ctx, state.doc, pageno);
1086 fz_bound_page (ctx, page, &mediabox);
1087 fz_drop_page (ctx, page);
1089 show = !state.trimmargins && pageno % 20 == 0;
1090 if (show) {
1091 printd ("progress %f Gathering dimensions %d",
1092 (double) (pageno) / state.pagecount,
1093 pageno);
1096 fz_catch (ctx) {
1097 fprintf (stderr, "failed to load page %d\n", pageno);
1103 if (state.pagedimcount == 0
1104 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1105 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1106 size_t size;
1108 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1109 state.pagedims = realloc (state.pagedims, size);
1110 if (!state.pagedims) {
1111 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1112 size, state.pagedimcount + 1);
1115 p = &state.pagedims[state.pagedimcount++];
1116 p->rotate = rotate;
1117 p->mediabox = mediabox;
1118 p->pageno = pageno;
1121 end = now ();
1122 if (!wthack) {
1123 printd ("progress 1 %s %d pages in %f seconds",
1124 state.trimmargins ? "Trimmed" : "Processed",
1125 state.pagecount, end - start);
1127 state.trimanew = 0;
1128 if (trimf) {
1129 if (fclose (trimf)) {
1130 err (1, "fclose");
1135 static void layout (void)
1137 int pindex;
1138 fz_rect box;
1139 fz_matrix ctm, rm;
1140 struct pagedim *p = p;
1141 double zw, w, maxw = 0.0, zoom = zoom;
1143 if (state.pagedimcount == 0) return;
1145 switch (state.fitmodel) {
1146 case FitProportional:
1147 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1148 double x0, x1;
1150 p = &state.pagedims[pindex];
1151 fz_rotate (&rm, p->rotate + state.rotate);
1152 box = p->mediabox;
1153 fz_transform_rect (&box, &rm);
1155 x0 = fz_min (box.x0, box.x1);
1156 x1 = fz_max (box.x0, box.x1);
1158 w = x1 - x0;
1159 maxw = fz_max (w, maxw);
1160 zoom = state.w / maxw;
1162 break;
1164 case FitPage:
1165 maxw = state.w;
1166 break;
1168 case FitWidth:
1169 break;
1171 default:
1172 ARSERT (0 && state.fitmodel);
1175 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1176 fz_rect rect;
1177 fz_matrix tm, sm;
1179 p = &state.pagedims[pindex];
1180 fz_rotate (&ctm, state.rotate);
1181 fz_rotate (&rm, p->rotate + state.rotate);
1182 box = p->mediabox;
1183 fz_transform_rect (&box, &rm);
1184 w = box.x1 - box.x0;
1185 switch (state.fitmodel) {
1186 case FitProportional:
1187 p->left = ((maxw - w) * zoom) / 2.0;
1188 break;
1189 case FitPage:
1191 double zh, h;
1192 zw = maxw / w;
1193 h = box.y1 - box.y0;
1194 zh = state.h / h;
1195 zoom = fz_min (zw, zh);
1196 p->left = (maxw - (w * zoom)) / 2.0;
1198 break;
1199 case FitWidth:
1200 p->left = 0;
1201 zoom = state.w / w;
1202 break;
1205 fz_scale (&p->zoomctm, zoom, zoom);
1206 fz_concat (&ctm, &p->zoomctm, &ctm);
1208 fz_rotate (&rm, p->rotate);
1209 p->pagebox = p->mediabox;
1210 fz_transform_rect (&p->pagebox, &rm);
1211 p->pagebox.x1 -= p->pagebox.x0;
1212 p->pagebox.y1 -= p->pagebox.y0;
1213 p->pagebox.x0 = 0;
1214 p->pagebox.y0 = 0;
1215 rect = p->pagebox;
1216 fz_transform_rect (&rect, &ctm);
1217 fz_round_rect (&p->bounds, &rect);
1218 p->ctm = ctm;
1220 fz_translate (&tm, 0, -p->mediabox.y1);
1221 fz_scale (&sm, zoom, -zoom);
1222 fz_concat (&ctm, &tm, &sm);
1224 p->tctmready = 0;
1227 do {
1228 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1229 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1230 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1231 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1232 int boundw = x1 - x0;
1233 int boundh = y1 - y0;
1235 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1236 } while (p-- != state.pagedims);
1239 struct pagedim *pdimofpageno (int pageno)
1241 struct pagedim *pdim = state.pagedims;
1243 for (int i = 0; i < state.pagedimcount; ++i) {
1244 if (state.pagedims[i].pageno > pageno)
1245 break;
1246 pdim = &state.pagedims[i];
1248 return pdim;
1251 static
1252 struct anchor { int n; int x; int y; int w; int h; }
1253 uritoanchor (const char *uri)
1255 fz_point p;
1256 struct anchor a;
1258 a.n = -1;
1259 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1260 if (a.n >= 0) {
1261 struct pagedim *pdim = pdimofpageno (a.n);
1262 fz_transform_point (&p, &pdim->ctm);
1263 a.x = p.x;
1264 a.y = p.y;
1265 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1267 return a;
1270 static void recurse_outline (fz_outline *outline, int level)
1272 while (outline) {
1273 struct anchor a = uritoanchor (outline->uri);
1274 if (a.n >= 0) {
1275 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1277 else {
1278 printd ("on %d %s", level, outline->title);
1280 if (outline->down) {
1281 recurse_outline (outline->down, level + 1);
1283 outline = outline->next;
1287 static void process_outline (void)
1289 fz_outline *outline;
1291 if (!state.needoutline || !state.pagedimcount) return;
1293 state.needoutline = 0;
1294 outline = fz_load_outline (state.ctx, state.doc);
1295 if (outline) {
1296 recurse_outline (outline, 0);
1297 fz_drop_outline (state.ctx, outline);
1301 static char *strofline (fz_stext_line *line)
1303 char *p;
1304 char utf8[10];
1305 fz_stext_char *ch;
1306 size_t size = 0, cap = 80;
1308 p = malloc (cap + 1);
1309 if (!p) return NULL;
1311 for (ch = line->first_char; ch; ch = ch->next) {
1312 int n = fz_runetochar (utf8, ch->c);
1313 if (size + n > cap) {
1314 cap *= 2;
1315 p = realloc (p, cap + 1);
1316 if (!p) return NULL;
1319 memcpy (p + size, utf8, n);
1320 size += n;
1322 p[size] = 0;
1323 return p;
1326 static int matchline (regex_t *re, fz_stext_line *line,
1327 int stop, int pageno, double start)
1329 int ret;
1330 char *p;
1331 regmatch_t rm;
1333 p = strofline (line);
1334 if (!p) return -1;
1336 ret = regexec (re, p, 1, &rm, 0);
1337 if (ret) {
1338 free (p);
1339 if (ret != REG_NOMATCH) {
1340 size_t size;
1341 char errbuf[80];
1342 size = regerror (ret, re, errbuf, sizeof (errbuf));
1343 printd ("msg regexec error `%.*s'",
1344 (int) size, errbuf);
1345 return -1;
1347 return 0;
1349 else {
1350 fz_point p1, p2, p3, p4;
1351 fz_rect s = {0,0,0,0}, e;
1352 fz_stext_char *ch;
1353 int o = 0;
1355 for (ch = line->first_char; ch; ch = ch->next) {
1356 o += fz_runelen (ch->c);
1357 if (o > rm.rm_so) {
1358 s = ch->bbox;
1359 break;
1362 for (;ch; ch = ch->next) {
1363 o += fz_runelen (ch->c);
1364 if (o > rm.rm_eo) break;
1366 e = ch->bbox;
1368 p1.x = s.x0;
1369 p1.y = s.y0;
1370 p2.x = e.x1;
1371 p2.y = s.y0;
1372 p3.x = e.x1;
1373 p3.y = e.y1;
1374 p4.x = s.x0;
1375 p4.y = e.y1;
1377 if (!stop) {
1378 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1379 pageno, 1,
1380 p1.x, p1.y,
1381 p2.x, p2.y,
1382 p3.x, p3.y,
1383 p4.x, p4.y);
1385 printd ("progress 1 found at %d `%.*s' in %f sec",
1386 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1387 now () - start);
1389 else {
1390 printd ("match %d %d %f %f %f %f %f %f %f %f",
1391 pageno, 2,
1392 p1.x, p1.y,
1393 p2.x, p2.y,
1394 p3.x, p3.y,
1395 p4.x, p4.y);
1397 free (p);
1398 return 1;
1402 /* wishful thinking function */
1403 static void search (regex_t *re, int pageno, int y, int forward)
1405 fz_device *tdev;
1406 fz_stext_page *text;
1407 struct pagedim *pdim;
1408 int stop = 0, niters = 0;
1409 double start, end;
1410 fz_page *page;
1411 fz_stext_block *block;
1413 start = now ();
1414 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1415 if (niters++ == 5) {
1416 niters = 0;
1417 if (hasdata ()) {
1418 printd ("progress 1 attention requested aborting search at %d",
1419 pageno);
1420 stop = 1;
1422 else {
1423 printd ("progress %f searching in page %d",
1424 (double) (pageno + 1) / state.pagecount,
1425 pageno);
1428 pdim = pdimofpageno (pageno);
1429 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1430 tdev = fz_new_stext_device (state.ctx, text, 0);
1432 page = fz_load_page (state.ctx, state.doc, pageno);
1434 fz_matrix ctm = pagectm1 (page, pdim);
1435 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1438 fz_close_device (state.ctx, tdev);
1439 fz_drop_device (state.ctx, tdev);
1441 if (forward) {
1442 for (block = text->first_block; block; block = block->next) {
1443 fz_stext_line *line;
1445 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1446 for (line = block->u.t.first_line; line; line = line->next) {
1447 if (line->bbox.y0 < y + 1) continue;
1449 switch (matchline (re, line, stop, pageno, start)) {
1450 case 0: break;
1451 case 1: stop = 1; break;
1452 case -1: stop = 1; goto endloop;
1457 else {
1458 for (block = text->last_block; block; block = block->prev) {
1459 fz_stext_line *line;
1461 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1462 for (line = block->u.t.last_line; line; line = line->prev) {
1463 if (line->bbox.y0 < y + 1) continue;
1465 switch (matchline (re, line, stop, pageno, start)) {
1466 case 0: break;
1467 case 1: stop = 1; break;
1468 case -1: stop = 1; goto endloop;
1474 if (forward) {
1475 pageno += 1;
1476 y = 0;
1478 else {
1479 pageno -= 1;
1480 y = INT_MAX;
1482 endloop:
1483 fz_drop_stext_page (state.ctx, text);
1484 fz_drop_page (state.ctx, page);
1486 end = now ();
1487 if (!stop) {
1488 printd ("progress 1 no matches %f sec", end - start);
1490 printd ("clearrects");
1493 static void set_tex_params (int colorspace)
1495 union {
1496 unsigned char b;
1497 unsigned int s;
1498 } endianness = {1};
1500 switch (colorspace) {
1501 case 0:
1502 state.texiform = GL_RGBA8;
1503 state.texform = GL_RGBA;
1504 state.texty = GL_UNSIGNED_BYTE;
1505 state.colorspace = fz_device_rgb (state.ctx);
1506 break;
1507 case 1:
1508 state.texiform = GL_RGBA8;
1509 state.texform = GL_BGRA;
1510 state.texty = endianness.s > 1
1511 ? GL_UNSIGNED_INT_8_8_8_8
1512 : GL_UNSIGNED_INT_8_8_8_8_REV;
1513 state.colorspace = fz_device_bgr (state.ctx);
1514 break;
1515 case 2:
1516 state.texiform = GL_LUMINANCE_ALPHA;
1517 state.texform = GL_LUMINANCE_ALPHA;
1518 state.texty = GL_UNSIGNED_BYTE;
1519 state.colorspace = fz_device_gray (state.ctx);
1520 break;
1521 default:
1522 errx (1, "invalid colorspce %d", colorspace);
1526 static void realloctexts (int texcount)
1528 size_t size;
1530 if (texcount == state.texcount) return;
1532 if (texcount < state.texcount) {
1533 glDeleteTextures (state.texcount - texcount,
1534 state.texids + texcount);
1537 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1538 state.texids = realloc (state.texids, size);
1539 if (!state.texids) {
1540 err (1, "realloc texs %" FMT_s, size);
1543 state.texowners = (void *) (state.texids + texcount);
1544 if (texcount > state.texcount) {
1545 glGenTextures (texcount - state.texcount,
1546 state.texids + state.texcount);
1547 for (int i = state.texcount; i < texcount; ++i) {
1548 state.texowners[i].w = -1;
1549 state.texowners[i].slice = NULL;
1552 state.texcount = texcount;
1553 state.texindex = 0;
1556 static char *mbtoutf8 (char *s)
1558 char *p, *r;
1559 wchar_t *tmp;
1560 size_t i, ret, len;
1562 if (state.utf8cs) {
1563 return s;
1566 len = mbstowcs (NULL, s, strlen (s));
1567 if (len == 0) {
1568 return s;
1570 else {
1571 if (len == (size_t) -1) {
1572 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1573 return s;
1577 tmp = calloc (len, sizeof (wchar_t));
1578 if (!tmp) {
1579 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1580 len, sizeof (wchar_t), errno, strerror (errno));
1581 return s;
1584 ret = mbstowcs (tmp, s, len);
1585 if (ret == (size_t) -1) {
1586 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1587 len, errno, strerror (errno));
1588 free (tmp);
1589 return s;
1592 len = 0;
1593 for (i = 0; i < ret; ++i) {
1594 len += fz_runelen (tmp[i]);
1597 p = r = malloc (len + 1);
1598 if (!r) {
1599 printd ("emsg mbtoutf8: malloc(%zu)", len);
1600 free (tmp);
1601 return s;
1604 for (i = 0; i < ret; ++i) {
1605 p += fz_runetochar (p, tmp[i]);
1607 *p = 0;
1608 free (tmp);
1609 return r;
1612 CAMLprim value ml_mbtoutf8 (value s_v)
1614 CAMLparam1 (s_v);
1615 CAMLlocal1 (ret_v);
1616 char *s, *r;
1618 s = String_val (s_v);
1619 r = mbtoutf8 (s);
1620 if (r == s) {
1621 ret_v = s_v;
1623 else {
1624 ret_v = caml_copy_string (r);
1625 free (r);
1627 CAMLreturn (ret_v);
1630 static void * mainloop (void UNUSED_ATTR *unused)
1632 char *p = NULL;
1633 int len, ret, oldlen = 0;
1635 fz_var (p);
1636 fz_var (oldlen);
1637 for (;;) {
1638 len = readlen (state.csock);
1639 if (len == 0) {
1640 errx (1, "readlen returned 0");
1643 if (oldlen < len + 1) {
1644 p = realloc (p, len + 1);
1645 if (!p) {
1646 err (1, "realloc %d failed", len + 1);
1648 oldlen = len + 1;
1650 readdata (state.csock, p, len);
1651 p[len] = 0;
1653 if (!strncmp ("open", p, 4)) {
1654 int wthack, off, usedoccss, ok = 0;
1655 char *password;
1656 char *filename;
1657 char *utf8filename;
1658 size_t filenamelen;
1660 fz_var (ok);
1661 ret = sscanf (p + 5, " %d %d %d %n",
1662 &wthack, &state.cxack, &usedoccss, &off);
1663 if (ret != 3) {
1664 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1667 filename = p + 5 + off;
1668 filenamelen = strlen (filename);
1669 password = filename + filenamelen + 1;
1671 if (password[strlen (password) + 1]) {
1672 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1675 lock ("open");
1676 fz_set_use_document_css (state.ctx, usedoccss);
1677 fz_try (state.ctx) {
1678 ok = openxref (filename, password);
1680 fz_catch (state.ctx) {
1681 utf8filename = mbtoutf8 (filename);
1682 printd ("msg Could not open %s", utf8filename);
1684 if (ok) {
1685 pdfinfo ();
1686 initpdims (wthack);
1688 unlock ("open");
1690 if (ok) {
1691 if (!wthack) {
1692 utf8filename = mbtoutf8 (filename);
1693 printd ("msg Opened %s (press h/F1 to get help)",
1694 utf8filename);
1695 if (utf8filename != filename) {
1696 free (utf8filename);
1699 state.needoutline = 1;
1702 else if (!strncmp ("cs", p, 2)) {
1703 int i, colorspace;
1705 ret = sscanf (p + 2, " %d", &colorspace);
1706 if (ret != 1) {
1707 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1709 lock ("cs");
1710 set_tex_params (colorspace);
1711 for (i = 0; i < state.texcount; ++i) {
1712 state.texowners[i].w = -1;
1713 state.texowners[i].slice = NULL;
1715 unlock ("cs");
1717 else if (!strncmp ("freepage", p, 8)) {
1718 void *ptr;
1720 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1721 if (ret != 1) {
1722 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1724 freepage (ptr);
1726 else if (!strncmp ("freetile", p, 8)) {
1727 void *ptr;
1729 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1730 if (ret != 1) {
1731 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1733 freetile (ptr);
1735 else if (!strncmp ("search", p, 6)) {
1736 int icase, pageno, y, len2, forward;
1737 char *pattern;
1738 regex_t re;
1740 ret = sscanf (p + 6, " %d %d %d %d,%n",
1741 &icase, &pageno, &y, &forward, &len2);
1742 if (ret != 4) {
1743 errx (1, "malformed search `%s' ret=%d", p, ret);
1746 pattern = p + 6 + len2;
1747 ret = regcomp (&re, pattern,
1748 REG_EXTENDED | (icase ? REG_ICASE : 0));
1749 if (ret) {
1750 char errbuf[80];
1751 size_t size;
1753 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1754 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1756 else {
1757 search (&re, pageno, y, forward);
1758 regfree (&re);
1761 else if (!strncmp ("geometry", p, 8)) {
1762 int w, h, fitmodel;
1764 printd ("clear");
1765 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1766 if (ret != 3) {
1767 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1770 lock ("geometry");
1771 state.h = h;
1772 if (w != state.w) {
1773 state.w = w;
1774 for (int i = 0; i < state.texcount; ++i) {
1775 state.texowners[i].slice = NULL;
1778 state.fitmodel = fitmodel;
1779 layout ();
1780 process_outline ();
1782 state.gen++;
1783 unlock ("geometry");
1784 printd ("continue %d", state.pagecount);
1786 else if (!strncmp ("reqlayout", p, 9)) {
1787 char *nameddest;
1788 int rotate, off, h;
1789 unsigned int fitmodel;
1790 pdf_document *pdf;
1792 printd ("clear");
1793 ret = sscanf (p + 9, " %d %u %d %n",
1794 &rotate, &fitmodel, &h, &off);
1795 if (ret != 3) {
1796 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1798 lock ("reqlayout");
1799 pdf = pdf_specifics (state.ctx, state.doc);
1800 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1801 state.gen += 1;
1803 state.rotate = rotate;
1804 state.fitmodel = fitmodel;
1805 state.h = h;
1806 layout ();
1807 process_outline ();
1809 nameddest = p + 9 + off;
1810 if (pdf && nameddest && *nameddest) {
1811 fz_point xy;
1812 struct pagedim *pdim;
1813 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1814 &xy.x, &xy.y);
1815 pdim = pdimofpageno (pageno);
1816 fz_transform_point (&xy, &pdim->ctm);
1817 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1820 state.gen++;
1821 unlock ("reqlayout");
1822 printd ("continue %d", state.pagecount);
1824 else if (!strncmp ("page", p, 4)) {
1825 double a, b;
1826 struct page *page;
1827 int pageno, pindex;
1829 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1830 if (ret != 2) {
1831 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1834 lock ("page");
1835 a = now ();
1836 page = loadpage (pageno, pindex);
1837 b = now ();
1838 unlock ("page");
1840 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1842 else if (!strncmp ("tile", p, 4)) {
1843 int x, y, w, h;
1844 struct page *page;
1845 struct tile *tile;
1846 double a, b;
1847 void *data;
1849 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1850 SCN_ptr_cast (&page), &x, &y, &w, &h,
1851 SCN_ptr_cast (&data));
1852 if (ret != 6) {
1853 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1856 lock ("tile");
1857 a = now ();
1858 tile = rendertile (page, x, y, w, h, data);
1859 b = now ();
1860 unlock ("tile");
1862 printd ("tile %d %d %" FMT_ptr " %u %f",
1863 x, y,
1864 FMT_ptr_cast (tile),
1865 tile->w * tile->h * tile->pixmap->n,
1866 b - a);
1868 else if (!strncmp ("trimset", p, 7)) {
1869 fz_irect fuzz;
1870 int trimmargins;
1872 ret = sscanf (p + 7, " %d %d %d %d %d",
1873 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1874 if (ret != 5) {
1875 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1877 lock ("trimset");
1878 state.trimmargins = trimmargins;
1879 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1880 state.trimanew = 1;
1881 state.trimfuzz = fuzz;
1883 unlock ("trimset");
1885 else if (!strncmp ("settrim", p, 7)) {
1886 fz_irect fuzz;
1887 int trimmargins;
1889 ret = sscanf (p + 7, " %d %d %d %d %d",
1890 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1891 if (ret != 5) {
1892 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1894 printd ("clear");
1895 lock ("settrim");
1896 state.trimmargins = trimmargins;
1897 state.needoutline = 1;
1898 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1899 state.trimanew = 1;
1900 state.trimfuzz = fuzz;
1902 state.pagedimcount = 0;
1903 free (state.pagedims);
1904 state.pagedims = NULL;
1905 initpdims (0);
1906 layout ();
1907 process_outline ();
1908 unlock ("settrim");
1909 printd ("continue %d", state.pagecount);
1911 else if (!strncmp ("sliceh", p, 6)) {
1912 int h;
1914 ret = sscanf (p + 6, " %d", &h);
1915 if (ret != 1) {
1916 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1918 if (h != state.sliceheight) {
1919 state.sliceheight = h;
1920 for (int i = 0; i < state.texcount; ++i) {
1921 state.texowners[i].w = -1;
1922 state.texowners[i].h = -1;
1923 state.texowners[i].slice = NULL;
1927 else if (!strncmp ("interrupt", p, 9)) {
1928 printd ("vmsg interrupted");
1930 else {
1931 errx (1, "unknown command %.*s", len, p);
1934 return 0;
1937 CAMLprim value ml_isexternallink (value uri_v)
1939 CAMLparam1 (uri_v);
1940 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1941 CAMLreturn (Val_bool (ext));
1944 CAMLprim value ml_uritolocation (value uri_v)
1946 CAMLparam1 (uri_v);
1947 CAMLlocal1 (ret_v);
1948 int pageno;
1949 fz_point xy;
1950 struct pagedim *pdim;
1952 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1953 &xy.x, &xy.y);
1954 pdim = pdimofpageno (pageno);
1955 fz_transform_point (&xy, &pdim->ctm);
1956 ret_v = caml_alloc_tuple (3);
1957 Field (ret_v, 0) = Val_int (pageno);
1958 Field (ret_v, 1) = caml_copy_double (xy.x);
1959 Field (ret_v, 2) = caml_copy_double (xy.y);
1960 CAMLreturn (ret_v);
1963 CAMLprim value ml_realloctexts (value texcount_v)
1965 CAMLparam1 (texcount_v);
1966 int ok;
1968 if (trylock (__func__)) {
1969 ok = 0;
1970 goto done;
1972 realloctexts (Int_val (texcount_v));
1973 ok = 1;
1974 unlock (__func__);
1976 done:
1977 CAMLreturn (Val_bool (ok));
1980 static void recti (int x0, int y0, int x1, int y1)
1982 GLfloat *v = state.vertices;
1984 glVertexPointer (2, GL_FLOAT, 0, v);
1985 v[0] = x0; v[1] = y0;
1986 v[2] = x1; v[3] = y0;
1987 v[4] = x0; v[5] = y1;
1988 v[6] = x1; v[7] = y1;
1989 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1992 static void showsel (struct page *page, int ox, int oy)
1994 fz_irect bbox;
1995 fz_rect rect;
1996 fz_stext_block *block;
1997 int seen = 0;
1998 unsigned char selcolor[] = {15,15,15,140};
2000 if (!page->fmark.ch || !page->lmark.ch) return;
2002 glEnable (GL_BLEND);
2003 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2004 glColor4ubv (selcolor);
2006 ox += state.pagedims[page->pdimno].bounds.x0;
2007 oy += state.pagedims[page->pdimno].bounds.y0;
2009 for (block = page->text->first_block; block; block = block->next) {
2010 fz_stext_line *line;
2012 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2013 for (line = block->u.t.first_line; line; line = line->next) {
2014 fz_stext_char *ch;
2016 rect = fz_empty_rect;
2017 for (ch = line->first_char; ch; ch = ch->next) {
2018 if (ch == page->fmark.ch) seen = 1;
2019 if (seen) fz_union_rect (&rect, &ch->bbox);
2020 if (ch == page->lmark.ch) {
2021 fz_round_rect (&bbox, &rect);
2022 recti (bbox.x0 + ox, bbox.y0 + oy,
2023 bbox.x1 + ox, bbox.y1 + oy);
2024 goto done;
2027 fz_round_rect (&bbox, &rect);
2028 recti (bbox.x0 + ox, bbox.y0 + oy,
2029 bbox.x1 + ox, bbox.y1 + oy);
2032 done:
2033 glDisable (GL_BLEND);
2036 #include "glfont.c"
2038 static void stipplerect (fz_matrix *m,
2039 fz_point *p1,
2040 fz_point *p2,
2041 fz_point *p3,
2042 fz_point *p4,
2043 GLfloat *texcoords,
2044 GLfloat *vertices)
2046 fz_transform_point (p1, m);
2047 fz_transform_point (p2, m);
2048 fz_transform_point (p3, m);
2049 fz_transform_point (p4, m);
2051 float w, h, s, t;
2053 w = p2->x - p1->x;
2054 h = p2->y - p1->y;
2055 t = hypotf (w, h) * .25f;
2057 w = p3->x - p2->x;
2058 h = p3->y - p2->y;
2059 s = hypotf (w, h) * .25f;
2061 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2062 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2064 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2065 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2067 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2068 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2070 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2071 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2073 glDrawArrays (GL_LINES, 0, 8);
2076 static void solidrect (fz_matrix *m,
2077 fz_point *p1,
2078 fz_point *p2,
2079 fz_point *p3,
2080 fz_point *p4,
2081 GLfloat *vertices)
2083 fz_transform_point (p1, m);
2084 fz_transform_point (p2, m);
2085 fz_transform_point (p3, m);
2086 fz_transform_point (p4, m);
2087 vertices[0] = p1->x; vertices[1] = p1->y;
2088 vertices[2] = p2->x; vertices[3] = p2->y;
2090 vertices[4] = p3->x; vertices[5] = p3->y;
2091 vertices[6] = p4->x; vertices[7] = p4->y;
2092 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2095 static void ensurelinks (struct page *page)
2097 if (!page->links)
2098 page->links = fz_load_links (state.ctx, page->fzpage);
2101 static void highlightlinks (struct page *page, int xoff, int yoff)
2103 fz_matrix ctm, tm, pm;
2104 fz_link *link;
2105 GLfloat *texcoords = state.texcoords;
2106 GLfloat *vertices = state.vertices;
2108 ensurelinks (page);
2110 glEnable (GL_TEXTURE_1D);
2111 glEnable (GL_BLEND);
2112 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2113 glBindTexture (GL_TEXTURE_1D, state.stid);
2115 xoff -= state.pagedims[page->pdimno].bounds.x0;
2116 yoff -= state.pagedims[page->pdimno].bounds.y0;
2117 fz_translate (&tm, xoff, yoff);
2118 pm = pagectm (page);
2119 fz_concat (&ctm, &pm, &tm);
2121 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2122 glVertexPointer (2, GL_FLOAT, 0, vertices);
2124 for (link = page->links; link; link = link->next) {
2125 fz_point p1, p2, p3, p4;
2127 p1.x = link->rect.x0;
2128 p1.y = link->rect.y0;
2130 p2.x = link->rect.x1;
2131 p2.y = link->rect.y0;
2133 p3.x = link->rect.x1;
2134 p3.y = link->rect.y1;
2136 p4.x = link->rect.x0;
2137 p4.y = link->rect.y1;
2139 /* TODO: different colours for different schemes */
2140 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2141 else glColor3ub (255, 0, 0);
2143 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2146 for (int i = 0; i < page->annotcount; ++i) {
2147 fz_point p1, p2, p3, p4;
2148 struct annot *annot = &page->annots[i];
2150 p1.x = annot->bbox.x0;
2151 p1.y = annot->bbox.y0;
2153 p2.x = annot->bbox.x1;
2154 p2.y = annot->bbox.y0;
2156 p3.x = annot->bbox.x1;
2157 p3.y = annot->bbox.y1;
2159 p4.x = annot->bbox.x0;
2160 p4.y = annot->bbox.y1;
2162 glColor3ub (0, 0, 128);
2163 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2166 glDisable (GL_BLEND);
2167 glDisable (GL_TEXTURE_1D);
2170 static int compareslinks (const void *l, const void *r)
2172 struct slink const *ls = l;
2173 struct slink const *rs = r;
2174 if (ls->bbox.y0 == rs->bbox.y0) {
2175 return rs->bbox.x0 - rs->bbox.x0;
2177 return ls->bbox.y0 - rs->bbox.y0;
2180 static void droptext (struct page *page)
2182 if (page->text) {
2183 fz_drop_stext_page (state.ctx, page->text);
2184 page->fmark.ch = NULL;
2185 page->lmark.ch = NULL;
2186 page->text = NULL;
2190 static void dropannots (struct page *page)
2192 if (page->annots) {
2193 free (page->annots);
2194 page->annots = NULL;
2195 page->annotcount = 0;
2199 static void ensureannots (struct page *page)
2201 int i, count = 0;
2202 size_t annotsize = sizeof (*page->annots);
2203 fz_annot *annot;
2205 if (state.gen != page->agen) {
2206 dropannots (page);
2207 page->agen = state.gen;
2209 if (page->annots) return;
2211 for (annot = fz_first_annot (state.ctx, page->fzpage);
2212 annot;
2213 annot = fz_next_annot (state.ctx, annot)) {
2214 count++;
2217 if (count > 0) {
2218 page->annotcount = count;
2219 page->annots = calloc (count, annotsize);
2220 if (!page->annots) {
2221 err (1, "calloc annots %d", count);
2224 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2225 annot;
2226 annot = fz_next_annot (state.ctx, annot), i++) {
2227 fz_rect rect;
2229 fz_bound_annot (state.ctx, annot, &rect);
2230 page->annots[i].annot = annot;
2231 fz_round_rect (&page->annots[i].bbox, &rect);
2236 static void dropslinks (struct page *page)
2238 if (page->slinks) {
2239 free (page->slinks);
2240 page->slinks = NULL;
2241 page->slinkcount = 0;
2243 if (page->links) {
2244 fz_drop_link (state.ctx, page->links);
2245 page->links = NULL;
2249 static void ensureslinks (struct page *page)
2251 fz_matrix ctm;
2252 int i, count;
2253 size_t slinksize = sizeof (*page->slinks);
2254 fz_link *link;
2256 ensureannots (page);
2257 if (state.gen != page->sgen) {
2258 dropslinks (page);
2259 page->sgen = state.gen;
2261 if (page->slinks) return;
2263 ensurelinks (page);
2264 ctm = pagectm (page);
2266 count = page->annotcount;
2267 for (link = page->links; link; link = link->next) {
2268 count++;
2270 if (count > 0) {
2271 int j;
2273 page->slinkcount = count;
2274 page->slinks = calloc (count, slinksize);
2275 if (!page->slinks) {
2276 err (1, "calloc slinks %d", count);
2279 for (i = 0, link = page->links; link; ++i, link = link->next) {
2280 fz_rect rect;
2282 rect = link->rect;
2283 fz_transform_rect (&rect, &ctm);
2284 page->slinks[i].tag = SLINK;
2285 page->slinks[i].u.link = link;
2286 fz_round_rect (&page->slinks[i].bbox, &rect);
2288 for (j = 0; j < page->annotcount; ++j, ++i) {
2289 fz_rect rect;
2290 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2291 fz_transform_rect (&rect, &ctm);
2292 fz_round_rect (&page->slinks[i].bbox, &rect);
2294 page->slinks[i].tag = SANNOT;
2295 page->slinks[i].u.annot = page->annots[j].annot;
2297 qsort (page->slinks, count, slinksize, compareslinks);
2301 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2302 static void fmt_linkn (char *s, unsigned int u)
2304 unsigned int len; unsigned int q;
2305 unsigned int zma = 'z' - 'a' + 1;
2306 len = 1; q = u;
2307 while (q > zma - 1) { ++len; q /= zma; }
2308 if (s) {
2309 s += len;
2310 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2311 /* handles u == 0 */
2313 s[len] = 0;
2316 static void highlightslinks (struct page *page, int xoff, int yoff,
2317 int noff, char *targ, int tlen, int hfsize)
2319 char buf[40];
2320 struct slink *slink;
2321 double x0, y0, x1, y1, w;
2323 ensureslinks (page);
2324 glColor3ub (0xc3, 0xb0, 0x91);
2325 for (int i = 0; i < page->slinkcount; ++i) {
2326 fmt_linkn (buf, i + noff);
2327 if (!tlen || !strncmp (targ, buf, tlen)) {
2328 slink = &page->slinks[i];
2330 x0 = slink->bbox.x0 + xoff - 5;
2331 y1 = slink->bbox.y0 + yoff - 5;
2332 y0 = y1 + 10 + hfsize;
2333 w = measure_string (state.face, hfsize, buf);
2334 x1 = x0 + w + 10;
2335 recti (x0, y0, x1, y1);
2339 glEnable (GL_BLEND);
2340 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2341 glEnable (GL_TEXTURE_2D);
2342 glColor3ub (0, 0, 0);
2343 for (int i = 0; i < page->slinkcount; ++i) {
2344 fmt_linkn (buf, i + noff);
2345 if (!tlen || !strncmp (targ, buf, tlen)) {
2346 slink = &page->slinks[i];
2348 x0 = slink->bbox.x0 + xoff;
2349 y0 = slink->bbox.y0 + yoff + hfsize;
2350 draw_string (state.face, hfsize, x0, y0, buf);
2353 glDisable (GL_TEXTURE_2D);
2354 glDisable (GL_BLEND);
2357 static void uploadslice (struct tile *tile, struct slice *slice)
2359 int offset;
2360 struct slice *slice1;
2361 unsigned char *texdata;
2363 offset = 0;
2364 for (slice1 = tile->slices; slice != slice1; slice1++) {
2365 offset += slice1->h * tile->w * tile->pixmap->n;
2367 if (slice->texindex != -1 && slice->texindex < state.texcount
2368 && state.texowners[slice->texindex].slice == slice) {
2369 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2371 else {
2372 int subimage = 0;
2373 int texindex = state.texindex++ % state.texcount;
2375 if (state.texowners[texindex].w == tile->w) {
2376 if (state.texowners[texindex].h >= slice->h) {
2377 subimage = 1;
2379 else {
2380 state.texowners[texindex].h = slice->h;
2383 else {
2384 state.texowners[texindex].h = slice->h;
2387 state.texowners[texindex].w = tile->w;
2388 state.texowners[texindex].slice = slice;
2389 slice->texindex = texindex;
2391 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2392 #if TEXT_TYPE == GL_TEXTURE_2D
2393 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2394 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2395 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2396 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2397 #endif
2398 if (tile->pbo) {
2399 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2400 texdata = 0;
2402 else {
2403 texdata = tile->pixmap->samples;
2405 if (subimage) {
2406 glTexSubImage2D (TEXT_TYPE,
2410 tile->w,
2411 slice->h,
2412 state.texform,
2413 state.texty,
2414 texdata+offset
2417 else {
2418 glTexImage2D (TEXT_TYPE,
2420 state.texiform,
2421 tile->w,
2422 slice->h,
2424 state.texform,
2425 state.texty,
2426 texdata+offset
2429 if (tile->pbo) {
2430 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2435 CAMLprim void ml_begintiles (value unit_v)
2437 CAMLparam1 (unit_v);
2438 glEnable (TEXT_TYPE);
2439 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2440 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2441 CAMLreturn0;
2444 CAMLprim void ml_endtiles (value unit_v)
2446 CAMLparam1 (unit_v);
2447 glDisable (TEXT_TYPE);
2448 CAMLreturn0;
2451 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2453 CAMLparam2 (args_v, ptr_v);
2454 int dispx = Int_val (Field (args_v, 0));
2455 int dispy = Int_val (Field (args_v, 1));
2456 int dispw = Int_val (Field (args_v, 2));
2457 int disph = Int_val (Field (args_v, 3));
2458 int tilex = Int_val (Field (args_v, 4));
2459 int tiley = Int_val (Field (args_v, 5));
2460 char *s = String_val (ptr_v);
2461 struct tile *tile = parse_pointer (__func__, s);
2462 int slicey, firstslice;
2463 struct slice *slice;
2464 GLfloat *texcoords = state.texcoords;
2465 GLfloat *vertices = state.vertices;
2467 firstslice = tiley / tile->sliceheight;
2468 slice = &tile->slices[firstslice];
2469 slicey = tiley % tile->sliceheight;
2471 while (disph > 0) {
2472 int dh;
2474 dh = slice->h - slicey;
2475 dh = fz_mini (disph, dh);
2476 uploadslice (tile, slice);
2478 texcoords[0] = tilex; texcoords[1] = slicey;
2479 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2480 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2481 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2483 vertices[0] = dispx; vertices[1] = dispy;
2484 vertices[2] = dispx+dispw; vertices[3] = dispy;
2485 vertices[4] = dispx; vertices[5] = dispy+dh;
2486 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2488 #if TEXT_TYPE == GL_TEXTURE_2D
2489 for (int i = 0; i < 8; ++i) {
2490 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2492 #endif
2494 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2495 dispy += dh;
2496 disph -= dh;
2497 slice++;
2498 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2499 slicey = 0;
2501 CAMLreturn0;
2504 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2506 fz_matrix ctm, tm, pm;
2507 fz_point p1, p2, p3, p4;
2508 GLfloat *vertices = state.vertices;
2509 double *v = (double *) rects_v;
2511 xoff -= state.pagedims[page->pdimno].bounds.x0;
2512 yoff -= state.pagedims[page->pdimno].bounds.y0;
2513 fz_translate (&tm, xoff, yoff);
2514 pm = pagectm (page);
2515 fz_concat (&ctm, &pm, &tm);
2517 glEnable (GL_BLEND);
2518 glVertexPointer (2, GL_FLOAT, 0, vertices);
2520 glColor4dv (v);
2521 p1.x = v[4];
2522 p1.y = v[5];
2524 p2.x = v[6];
2525 p2.y = v[5];
2527 p3.x = v[6];
2528 p3.y = v[7];
2530 p4.x = v[4];
2531 p4.y = v[7];
2532 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2533 glDisable (GL_BLEND);
2536 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2537 value xoff_v, value yoff_v,
2538 value li_v)
2540 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2541 int xoff = Int_val (xoff_v);
2542 int yoff = Int_val (yoff_v);
2543 int noff = Int_val (Field (li_v, 0));
2544 char *targ = String_val (Field (li_v, 1));
2545 int tlen = caml_string_length (Field (li_v, 1));
2546 int hfsize = Int_val (Field (li_v, 2));
2547 char *s = String_val (ptr_v);
2548 int hlmask = Int_val (hlinks_v);
2549 struct page *page = parse_pointer (__func__, s);
2551 if (!page->fzpage) {
2552 /* deal with loadpage failed pages */
2553 goto done;
2556 if (trylock (__func__)) {
2557 noff = -1;
2558 goto done;
2561 ensureannots (page);
2562 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2563 if (hlmask & 2) {
2564 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2565 noff = page->slinkcount;
2567 if (page->tgen == state.gen) {
2568 showsel (page, xoff, yoff);
2570 unlock (__func__);
2572 done:
2573 CAMLreturn (Val_int (noff));
2576 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2577 value rects_v)
2579 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2580 int xoff = Int_val (xoff_v);
2581 int yoff = Int_val (yoff_v);
2582 char *s = String_val (ptr_v);
2583 struct page *page = parse_pointer (__func__, s);
2585 drawprect (page, xoff, yoff, rects_v);
2586 CAMLreturn0;
2589 static struct annot *getannot (struct page *page, int x, int y)
2591 fz_point p;
2592 fz_matrix ctm;
2593 const fz_matrix *tctm;
2594 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2596 if (!page->annots) return NULL;
2598 if (pdf) {
2599 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2600 tctm = &state.pagedims[page->pdimno].tctm;
2602 else {
2603 tctm = &fz_identity;
2606 p.x = x;
2607 p.y = y;
2609 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2610 fz_invert_matrix (&ctm, &ctm);
2611 fz_transform_point (&p, &ctm);
2613 if (pdf) {
2614 for (int i = 0; i < page->annotcount; ++i) {
2615 struct annot *a = &page->annots[i];
2616 fz_rect rect;
2618 fz_bound_annot (state.ctx, a->annot, &rect);
2619 if (p.x >= rect.x0 && p.x <= rect.x1) {
2620 if (p.y >= rect.y0 && p.y <= rect.y1)
2621 return a;
2625 return NULL;
2628 static fz_link *getlink (struct page *page, int x, int y)
2630 fz_point p;
2631 fz_matrix ctm;
2632 fz_link *link;
2634 ensureslinks (page);
2636 p.x = x;
2637 p.y = y;
2639 ctm = pagectm (page);
2640 fz_invert_matrix (&ctm, &ctm);
2641 fz_transform_point (&p, &ctm);
2643 for (link = page->links; link; link = link->next) {
2644 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2645 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2646 return link;
2650 return NULL;
2653 static void ensuretext (struct page *page)
2655 if (state.gen != page->tgen) {
2656 droptext (page);
2657 page->tgen = state.gen;
2659 if (!page->text) {
2660 fz_matrix ctm;
2661 fz_device *tdev;
2663 page->text = fz_new_stext_page (state.ctx,
2664 &state.pagedims[page->pdimno].mediabox);
2665 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2666 ctm = pagectm (page);
2667 fz_run_display_list (state.ctx, page->dlist,
2668 tdev, &ctm, &fz_infinite_rect, NULL);
2669 fz_close_device (state.ctx, tdev);
2670 fz_drop_device (state.ctx, tdev);
2674 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2676 CAMLparam2 (start_page_v, dir_v);
2677 CAMLlocal1 (ret_v);
2678 int i, dir = Int_val (dir_v);
2679 int start_page = Int_val (start_page_v);
2680 int end_page = dir > 0 ? state.pagecount : -1;
2681 pdf_document *pdf;
2683 fz_var (end_page);
2684 ret_v = Val_int (0);
2685 lock (__func__);
2686 pdf = pdf_specifics (state.ctx, state.doc);
2687 for (i = start_page + dir; i != end_page; i += dir) {
2688 int found;
2690 fz_var (found);
2691 if (pdf) {
2692 pdf_page *page = NULL;
2694 fz_var (page);
2695 fz_try (state.ctx) {
2696 page = pdf_load_page (state.ctx, pdf, i);
2697 found = !!page->links || !!page->annots;
2699 fz_catch (state.ctx) {
2700 found = 0;
2702 if (page) {
2703 fz_drop_page (state.ctx, &page->super);
2706 else {
2707 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2708 fz_link *link = fz_load_links (state.ctx, page);
2709 found = !!link;
2710 fz_drop_link (state.ctx, link);
2711 fz_drop_page (state.ctx, page);
2714 if (found) {
2715 ret_v = caml_alloc_small (1, 1);
2716 Field (ret_v, 0) = Val_int (i);
2717 goto unlock;
2720 unlock:
2721 unlock (__func__);
2722 CAMLreturn (ret_v);
2725 enum { dir_first, dir_last };
2726 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2728 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2730 CAMLparam2 (ptr_v, dir_v);
2731 CAMLlocal2 (ret_v, pos_v);
2732 struct page *page;
2733 int dirtag, i, slinkindex;
2734 struct slink *found = NULL ,*slink;
2735 char *s = String_val (ptr_v);
2737 page = parse_pointer (__func__, s);
2738 ret_v = Val_int (0);
2739 lock (__func__);
2740 ensureslinks (page);
2742 if (Is_block (dir_v)) {
2743 dirtag = Tag_val (dir_v);
2744 switch (dirtag) {
2745 case dir_first_visible:
2747 int x0, y0, dir, first_index, last_index;
2749 pos_v = Field (dir_v, 0);
2750 x0 = Int_val (Field (pos_v, 0));
2751 y0 = Int_val (Field (pos_v, 1));
2752 dir = Int_val (Field (pos_v, 2));
2754 if (dir >= 0) {
2755 dir = 1;
2756 first_index = 0;
2757 last_index = page->slinkcount;
2759 else {
2760 first_index = page->slinkcount - 1;
2761 last_index = -1;
2764 for (i = first_index; i != last_index; i += dir) {
2765 slink = &page->slinks[i];
2766 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2767 found = slink;
2768 break;
2772 break;
2774 case dir_left:
2775 slinkindex = Int_val (Field (dir_v, 0));
2776 found = &page->slinks[slinkindex];
2777 for (i = slinkindex - 1; i >= 0; --i) {
2778 slink = &page->slinks[i];
2779 if (slink->bbox.x0 < found->bbox.x0) {
2780 found = slink;
2781 break;
2784 break;
2786 case dir_right:
2787 slinkindex = Int_val (Field (dir_v, 0));
2788 found = &page->slinks[slinkindex];
2789 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2790 slink = &page->slinks[i];
2791 if (slink->bbox.x0 > found->bbox.x0) {
2792 found = slink;
2793 break;
2796 break;
2798 case dir_down:
2799 slinkindex = Int_val (Field (dir_v, 0));
2800 found = &page->slinks[slinkindex];
2801 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2802 slink = &page->slinks[i];
2803 if (slink->bbox.y0 >= found->bbox.y0) {
2804 found = slink;
2805 break;
2808 break;
2810 case dir_up:
2811 slinkindex = Int_val (Field (dir_v, 0));
2812 found = &page->slinks[slinkindex];
2813 for (i = slinkindex - 1; i >= 0; --i) {
2814 slink = &page->slinks[i];
2815 if (slink->bbox.y0 <= found->bbox.y0) {
2816 found = slink;
2817 break;
2820 break;
2823 else {
2824 dirtag = Int_val (dir_v);
2825 switch (dirtag) {
2826 case dir_first:
2827 found = page->slinks;
2828 break;
2830 case dir_last:
2831 if (page->slinks) {
2832 found = page->slinks + (page->slinkcount - 1);
2834 break;
2837 if (found) {
2838 ret_v = caml_alloc_small (2, 1);
2839 Field (ret_v, 0) = Val_int (found - page->slinks);
2842 unlock (__func__);
2843 CAMLreturn (ret_v);
2846 enum { uuri, utext, uannot };
2848 CAMLprim value ml_getlink (value ptr_v, value n_v)
2850 CAMLparam2 (ptr_v, n_v);
2851 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2852 fz_link *link;
2853 struct page *page;
2854 char *s = String_val (ptr_v);
2855 struct slink *slink;
2857 ret_v = Val_int (0);
2858 page = parse_pointer (__func__, s);
2860 lock (__func__);
2861 ensureslinks (page);
2862 slink = &page->slinks[Int_val (n_v)];
2863 if (slink->tag == SLINK) {
2864 link = slink->u.link;
2865 str_v = caml_copy_string (link->uri);
2866 ret_v = caml_alloc_small (1, uuri);
2867 Field (ret_v, 0) = str_v;
2869 else {
2870 ret_v = caml_alloc_small (1, uannot);
2871 tup_v = caml_alloc_tuple (2);
2872 Field (ret_v, 0) = tup_v;
2873 Field (tup_v, 0) = ptr_v;
2874 Field (tup_v, 1) = n_v;
2876 unlock (__func__);
2878 CAMLreturn (ret_v);
2881 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2883 CAMLparam2 (ptr_v, n_v);
2884 CAMLlocal1 (ret_v);
2885 pdf_document *pdf;
2886 char *contents = NULL;
2888 lock (__func__);
2889 pdf = pdf_specifics (state.ctx, state.doc);
2890 if (pdf) {
2891 char *s = String_val (ptr_v);
2892 struct page *page;
2893 struct slink *slink;
2895 page = parse_pointer (__func__, s);
2896 slink = &page->slinks[Int_val (n_v)];
2897 contents = pdf_copy_annot_contents (state.ctx,
2898 (pdf_annot *) slink->u.annot);
2900 unlock (__func__);
2901 if (contents) {
2902 ret_v = caml_copy_string (contents);
2903 fz_free (state.ctx, contents);
2905 else {
2906 ret_v = caml_copy_string ("");
2908 CAMLreturn (ret_v);
2911 CAMLprim value ml_getlinkcount (value ptr_v)
2913 CAMLparam1 (ptr_v);
2914 struct page *page;
2915 char *s = String_val (ptr_v);
2917 page = parse_pointer (__func__, s);
2918 CAMLreturn (Val_int (page->slinkcount));
2921 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2923 CAMLparam2 (ptr_v, n_v);
2924 CAMLlocal1 (ret_v);
2925 struct page *page;
2926 struct slink *slink;
2927 char *s = String_val (ptr_v);
2929 page = parse_pointer (__func__, s);
2930 ret_v = caml_alloc_tuple (4);
2931 lock (__func__);
2932 ensureslinks (page);
2934 slink = &page->slinks[Int_val (n_v)];
2935 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2936 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2937 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2938 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2939 unlock (__func__);
2940 CAMLreturn (ret_v);
2943 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2945 CAMLparam3 (ptr_v, x_v, y_v);
2946 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2947 fz_link *link;
2948 struct annot *annot;
2949 struct page *page;
2950 char *ptr = String_val (ptr_v);
2951 int x = Int_val (x_v), y = Int_val (y_v);
2952 struct pagedim *pdim;
2954 ret_v = Val_int (0);
2955 if (trylock (__func__)) {
2956 goto done;
2959 page = parse_pointer (__func__, ptr);
2960 pdim = &state.pagedims[page->pdimno];
2961 x += pdim->bounds.x0;
2962 y += pdim->bounds.y0;
2965 annot = getannot (page, x, y);
2966 if (annot) {
2967 int i, n = -1;
2969 ensureslinks (page);
2970 for (i = 0; i < page->slinkcount; ++i) {
2971 if (page->slinks[i].tag == SANNOT
2972 && page->slinks[i].u.annot == annot->annot) {
2973 n = i;
2974 break;
2977 ret_v = caml_alloc_small (1, uannot);
2978 tup_v = caml_alloc_tuple (2);
2979 Field (ret_v, 0) = tup_v;
2980 Field (tup_v, 0) = ptr_v;
2981 Field (tup_v, 1) = Val_int (n);
2982 goto unlock;
2986 link = getlink (page, x, y);
2987 if (link) {
2988 str_v = caml_copy_string (link->uri);
2989 ret_v = caml_alloc_small (1, uuri);
2990 Field (ret_v, 0) = str_v;
2992 else {
2993 fz_rect *b;
2994 fz_stext_block *block;
2996 ensuretext (page);
2998 for (block = page->text->first_block; block; block = block->next) {
2999 fz_stext_line *line;
3001 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3002 b = &block->bbox;
3003 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3004 continue;
3006 for (line = block->u.t.first_line; line; line = line->next) {
3007 fz_stext_char *ch;
3009 b = &line->bbox;
3010 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3011 continue;
3013 for (ch = line->first_char; ch; ch = ch->next) {
3014 b = &ch->bbox;
3016 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3017 const char *n2 = fz_font_name (state.ctx, ch->font);
3018 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3019 ch->font);
3021 if (!n2) n2 = "<unknown font>";
3023 if (face && face->family_name) {
3024 char *s;
3025 char *n1 = face->family_name;
3026 size_t l1 = strlen (n1);
3027 size_t l2 = strlen (n2);
3029 if (l1 != l2 || memcmp (n1, n2, l1)) {
3030 s = malloc (l1 + l2 + 2);
3031 if (s) {
3032 memcpy (s, n2, l2);
3033 s[l2] = '=';
3034 memcpy (s + l2 + 1, n1, l1 + 1);
3035 str_v = caml_copy_string (s);
3036 free (s);
3040 if (str_v == Val_unit) {
3041 str_v = caml_copy_string (n2);
3043 ret_v = caml_alloc_small (1, utext);
3044 Field (ret_v, 0) = str_v;
3045 goto unlock;
3051 unlock:
3052 unlock (__func__);
3054 done:
3055 CAMLreturn (ret_v);
3058 enum { mark_page, mark_block, mark_line, mark_word };
3060 static int uninteresting (int c)
3062 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3063 || ispunct (c);
3066 CAMLprim void ml_clearmark (value ptr_v)
3068 CAMLparam1 (ptr_v);
3069 char *s = String_val (ptr_v);
3070 struct page *page;
3072 if (trylock (__func__)) {
3073 goto done;
3076 page = parse_pointer (__func__, s);
3077 page->fmark.ch = NULL;
3078 page->lmark.ch = NULL;
3080 unlock (__func__);
3081 done:
3082 CAMLreturn0;
3085 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3087 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3088 CAMLlocal1 (ret_v);
3089 fz_rect *b;
3090 struct page *page;
3091 fz_stext_line *line;
3092 fz_stext_block *block;
3093 struct pagedim *pdim;
3094 int mark = Int_val (mark_v);
3095 char *s = String_val (ptr_v);
3096 int x = Int_val (x_v), y = Int_val (y_v);
3098 ret_v = Val_bool (0);
3099 if (trylock (__func__)) {
3100 goto done;
3103 page = parse_pointer (__func__, s);
3104 pdim = &state.pagedims[page->pdimno];
3106 ensuretext (page);
3108 if (mark == mark_page) {
3109 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3110 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3111 ret_v = Val_bool (1);
3112 goto unlock;
3115 x += pdim->bounds.x0;
3116 y += pdim->bounds.y0;
3118 for (block = page->text->first_block; block; block = block->next) {
3119 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3120 b = &block->bbox;
3121 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3122 continue;
3124 if (mark == mark_block) {
3125 page->fmark.ch = block->u.t.first_line->first_char;
3126 page->lmark.ch = block->u.t.last_line->last_char;
3127 ret_v = Val_bool (1);
3128 goto unlock;
3131 for (line = block->u.t.first_line; line; line = line->next) {
3132 fz_stext_char *ch;
3134 b = &line->bbox;
3135 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3136 continue;
3138 if (mark == mark_line) {
3139 page->fmark.ch = line->first_char;
3140 page->lmark.ch = line->last_char;
3141 ret_v = Val_bool (1);
3142 goto unlock;
3145 for (ch = line->first_char; ch; ch = ch->next) {
3146 fz_stext_char *ch2, *first = NULL, *last = NULL;
3147 b = &ch->bbox;
3148 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3149 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3150 if (uninteresting (ch2->c)) first = NULL;
3151 else if (!first) first = ch2;
3153 for (ch2 = ch; ch2; ch2 = ch2->next) {
3154 if (uninteresting (ch2->c)) break;
3155 last = ch2;
3158 page->fmark.ch = first;
3159 page->lmark.ch = last;
3160 ret_v = Val_bool (1);
3161 goto unlock;
3166 unlock:
3167 if (!Bool_val (ret_v)) {
3168 page->fmark.ch = NULL;
3169 page->lmark.ch = NULL;
3171 unlock (__func__);
3173 done:
3174 CAMLreturn (ret_v);
3177 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3179 CAMLparam3 (ptr_v, x_v, y_v);
3180 CAMLlocal2 (ret_v, res_v);
3181 fz_rect *b = NULL;
3182 struct page *page;
3183 struct pagedim *pdim;
3184 fz_stext_block *block;
3185 char *s = String_val (ptr_v);
3186 int x = Int_val (x_v), y = Int_val (y_v);
3188 ret_v = Val_int (0);
3189 if (trylock (__func__)) {
3190 goto done;
3193 page = parse_pointer (__func__, s);
3194 pdim = &state.pagedims[page->pdimno];
3195 x += pdim->bounds.x0;
3196 y += pdim->bounds.y0;
3198 ensuretext (page);
3200 for (block = page->text->first_block; block; block = block->next) {
3201 switch (block->type) {
3202 case FZ_STEXT_BLOCK_TEXT:
3203 b = &block->bbox;
3204 break;
3206 case FZ_STEXT_BLOCK_IMAGE:
3207 b = &block->bbox;
3208 break;
3210 default:
3211 continue;
3214 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3215 break;
3216 b = NULL;
3218 if (b) {
3219 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3220 ret_v = caml_alloc_small (1, 1);
3221 Store_double_field (res_v, 0, b->x0);
3222 Store_double_field (res_v, 1, b->x1);
3223 Store_double_field (res_v, 2, b->y0);
3224 Store_double_field (res_v, 3, b->y1);
3225 Field (ret_v, 0) = res_v;
3227 unlock (__func__);
3229 done:
3230 CAMLreturn (ret_v);
3233 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3235 CAMLparam2 (ptr_v, rect_v);
3236 fz_rect b;
3237 struct page *page;
3238 struct pagedim *pdim;
3239 char *s = String_val (ptr_v);
3240 int x0, x1, y0, y1;
3241 fz_stext_char *ch;
3242 fz_stext_line *line;
3243 fz_stext_block *block;
3244 fz_stext_char *fc, *lc;
3246 if (trylock (__func__)) {
3247 goto done;
3250 page = parse_pointer (__func__, s);
3251 ensuretext (page);
3253 pdim = &state.pagedims[page->pdimno];
3254 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3255 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3256 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3257 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3259 if (y0 > y1) {
3260 int t = y0;
3261 y0 = y1;
3262 y1 = t;
3263 x0 = x1;
3264 x1 = t;
3267 fc = page->fmark.ch;
3268 lc = page->lmark.ch;
3270 for (block = page->text->first_block; block; block = block->next) {
3271 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3272 for (line = block->u.t.first_line; line; line = line->next) {
3273 for (ch = line->first_char; ch; ch = ch->next) {
3274 b = ch->bbox;
3275 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3276 fc = ch;
3278 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3279 lc = ch;
3284 if (x1 < x0 && fc == lc) {
3285 fz_stext_char *t;
3287 t = fc;
3288 fc = lc;
3289 lc = t;
3292 page->fmark.ch = fc;
3293 page->lmark.ch = lc;
3295 unlock (__func__);
3297 done:
3298 CAMLreturn0;
3301 static int pipechar (FILE *f, fz_stext_char *ch)
3303 char buf[4];
3304 int len, ret;
3306 len = fz_runetochar (buf, ch->c);
3307 ret = fwrite (buf, len, 1, f);
3308 if (ret != 1) {
3309 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3310 len, ret, strerror (errno));
3311 return -1;
3313 return 0;
3316 #ifdef __CYGWIN__
3317 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3319 caml_failwith ("ml_popen not implemented under Cygwin");
3321 #else
3322 CAMLprim value ml_spawn (value command_v, value fds_v)
3324 CAMLparam2 (command_v, fds_v);
3325 CAMLlocal2 (l_v, tup_v);
3326 int ret, ret1;
3327 pid_t pid;
3328 char *msg = NULL;
3329 value earg_v = Nothing;
3330 posix_spawnattr_t attr;
3331 posix_spawn_file_actions_t fa;
3332 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3334 argv[2] = String_val (command_v);
3336 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3337 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3340 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3341 msg = "posix_spawnattr_init";
3342 goto fail1;
3345 #ifdef POSIX_SPAWN_USEVFORK
3346 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3347 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3348 goto fail;
3350 #endif
3352 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3353 int fd1, fd2;
3355 tup_v = Field (l_v, 0);
3356 fd1 = Int_val (Field (tup_v, 0));
3357 fd2 = Int_val (Field (tup_v, 1));
3358 if (fd2 < 0) {
3359 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3360 msg = "posix_spawn_file_actions_addclose";
3361 earg_v = tup_v;
3362 goto fail;
3365 else {
3366 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3367 msg = "posix_spawn_file_actions_adddup2";
3368 earg_v = tup_v;
3369 goto fail;
3374 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3375 msg = "posix_spawn";
3376 goto fail;
3379 fail:
3380 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3381 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3384 fail1:
3385 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3386 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3387 strerror (ret1));
3390 if (msg)
3391 unix_error (ret, msg, earg_v);
3393 CAMLreturn (Val_int (pid));
3395 #endif
3397 CAMLprim value ml_hassel (value ptr_v)
3399 CAMLparam1 (ptr_v);
3400 CAMLlocal1 (ret_v);
3401 struct page *page;
3402 char *s = String_val (ptr_v);
3404 ret_v = Val_bool (0);
3405 if (trylock (__func__)) {
3406 goto done;
3409 page = parse_pointer (__func__, s);
3410 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3411 unlock (__func__);
3412 done:
3413 CAMLreturn (ret_v);
3416 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3418 CAMLparam2 (fd_v, ptr_v);
3419 FILE *f;
3420 int seen = 0;
3421 struct page *page;
3422 fz_stext_line *line;
3423 fz_stext_block *block;
3424 int fd = Int_val (fd_v);
3425 char *s = String_val (ptr_v);
3427 if (trylock (__func__)) {
3428 goto done;
3431 page = parse_pointer (__func__, s);
3433 if (!page->fmark.ch || !page->lmark.ch) {
3434 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3435 goto unlock;
3438 f = fdopen (fd, "w");
3439 if (!f) {
3440 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3441 fd, strerror (errno));
3442 f = stdout;
3445 for (block = page->text->first_block; block; block = block->next) {
3446 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3447 for (line = block->u.t.first_line; line; line = line->next) {
3448 fz_stext_char *ch;
3449 for (ch = line->first_char; ch; ch = ch->next) {
3450 if (seen || ch == page->fmark.ch) {
3451 do {
3452 pipechar (f, ch);
3453 if (ch == page->lmark.ch) goto close;
3454 } while ((ch = ch->next));
3455 seen = 1;
3456 break;
3459 if (seen) fputc ('\n', f);
3462 close:
3463 if (f != stdout) {
3464 int ret = fclose (f);
3465 fd = -1;
3466 if (ret == -1) {
3467 if (errno != ECHILD) {
3468 fprintf (stderr, "failed to close sel pipe: %s\n",
3469 strerror (errno));
3473 unlock:
3474 unlock (__func__);
3476 done:
3477 if (fd >= 0) {
3478 if (close (fd)) {
3479 fprintf (stderr, "failed to close sel pipe: %s\n",
3480 strerror (errno));
3483 CAMLreturn0;
3486 CAMLprim value ml_getpdimrect (value pagedimno_v)
3488 CAMLparam1 (pagedimno_v);
3489 CAMLlocal1 (ret_v);
3490 int pagedimno = Int_val (pagedimno_v);
3491 fz_rect box;
3493 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3494 if (trylock (__func__)) {
3495 box = fz_empty_rect;
3497 else {
3498 box = state.pagedims[pagedimno].mediabox;
3499 unlock (__func__);
3502 Store_double_field (ret_v, 0, box.x0);
3503 Store_double_field (ret_v, 1, box.x1);
3504 Store_double_field (ret_v, 2, box.y0);
3505 Store_double_field (ret_v, 3, box.y1);
3507 CAMLreturn (ret_v);
3510 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3511 value dw_v, value cols_v)
3513 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3514 CAMLlocal1 (ret_v);
3515 int i;
3516 double zoom = -1.;
3517 double maxh = 0.0;
3518 struct pagedim *p;
3519 double winw = Int_val (winw_v);
3520 double winh = Int_val (winh_v);
3521 double dw = Int_val (dw_v);
3522 double cols = Int_val (cols_v);
3523 double pw = 1.0, ph = 1.0;
3525 if (trylock (__func__)) {
3526 goto done;
3529 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3530 double w = p->pagebox.x1 / cols;
3531 double h = p->pagebox.y1;
3532 if (h > maxh) {
3533 maxh = h;
3534 ph = h;
3535 if (state.fitmodel != FitProportional) pw = w;
3537 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3540 zoom = (((winh / ph) * pw) + dw) / winw;
3541 unlock (__func__);
3542 done:
3543 ret_v = caml_copy_double (zoom);
3544 CAMLreturn (ret_v);
3547 CAMLprim value ml_getmaxw (value unit_v)
3549 CAMLparam1 (unit_v);
3550 CAMLlocal1 (ret_v);
3551 int i;
3552 double maxw = -1.;
3553 struct pagedim *p;
3555 if (trylock (__func__)) {
3556 goto done;
3559 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3560 double w = p->pagebox.x1;
3561 maxw = fz_max (maxw, w);
3564 unlock (__func__);
3565 done:
3566 ret_v = caml_copy_double (maxw);
3567 CAMLreturn (ret_v);
3570 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3572 CAMLparam4 (pt_v, x_v, y_v, string_v);
3573 CAMLlocal1 (ret_v);
3574 int pt = Int_val(pt_v);
3575 int x = Int_val (x_v);
3576 int y = Int_val (y_v);
3577 double w;
3579 w = draw_string (state.face, pt, x, y, String_val (string_v));
3580 ret_v = caml_copy_double (w);
3581 CAMLreturn (ret_v);
3584 CAMLprim value ml_measure_string (value pt_v, value string_v)
3586 CAMLparam2 (pt_v, string_v);
3587 CAMLlocal1 (ret_v);
3588 int pt = Int_val (pt_v);
3589 double w;
3591 w = measure_string (state.face, pt, String_val (string_v));
3592 ret_v = caml_copy_double (w);
3593 CAMLreturn (ret_v);
3596 CAMLprim value ml_getpagebox (value opaque_v)
3598 CAMLparam1 (opaque_v);
3599 CAMLlocal1 (ret_v);
3600 fz_rect rect;
3601 fz_irect bbox;
3602 fz_matrix ctm;
3603 fz_device *dev;
3604 char *s = String_val (opaque_v);
3605 struct page *page = parse_pointer (__func__, s);
3607 ret_v = caml_alloc_tuple (4);
3608 dev = fz_new_bbox_device (state.ctx, &rect);
3610 ctm = pagectm (page);
3611 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3613 fz_close_device (state.ctx, dev);
3614 fz_drop_device (state.ctx, dev);
3615 fz_round_rect (&bbox, &rect);
3616 Field (ret_v, 0) = Val_int (bbox.x0);
3617 Field (ret_v, 1) = Val_int (bbox.y0);
3618 Field (ret_v, 2) = Val_int (bbox.x1);
3619 Field (ret_v, 3) = Val_int (bbox.y1);
3621 CAMLreturn (ret_v);
3624 CAMLprim void ml_setaalevel (value level_v)
3626 CAMLparam1 (level_v);
3628 state.aalevel = Int_val (level_v);
3629 CAMLreturn0;
3632 #ifndef __COCOA__
3633 #pragma GCC diagnostic push
3634 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3635 #include <X11/Xlib.h>
3636 #include <X11/cursorfont.h>
3637 #pragma GCC diagnostic pop
3639 #ifdef USE_EGL
3640 #include <EGL/egl.h>
3641 #else
3642 #include <GL/glx.h>
3643 #endif
3645 static const int shapes[] = {
3646 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3649 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3651 static struct {
3652 Window wid;
3653 Display *dpy;
3654 #ifdef USE_EGL
3655 EGLContext ctx;
3656 EGLConfig conf;
3657 EGLSurface win;
3658 EGLDisplay *edpy;
3659 #else
3660 GLXContext ctx;
3661 #endif
3662 XVisualInfo *visual;
3663 Cursor curs[CURS_COUNT];
3664 } glx;
3667 static void initcurs (void)
3669 for (size_t n = 0; n < CURS_COUNT; ++n) {
3670 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3674 CAMLprim void ml_setbgcol (value color_v)
3676 CAMLparam1 (color_v);
3677 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3678 CAMLreturn0;
3681 #ifdef USE_EGL
3682 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3684 CAMLparam3 (display_v, wid_v, screen_v);
3685 int major, minor;
3686 int num_conf;
3687 EGLint visid;
3688 EGLint attribs[] = {
3689 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3690 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3691 EGL_NONE
3693 EGLConfig conf;
3695 glx.dpy = XOpenDisplay (String_val (display_v));
3696 if (!glx.dpy) {
3697 caml_failwith ("XOpenDisplay");
3700 eglBindAPI (EGL_OPENGL_API);
3702 glx.edpy = eglGetDisplay (glx.dpy);
3703 if (glx.edpy == EGL_NO_DISPLAY) {
3704 caml_failwith ("eglGetDisplay");
3707 if (!eglInitialize (glx.edpy, &major, &minor)) {
3708 caml_failwith ("eglInitialize");
3711 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3712 !num_conf) {
3713 caml_failwith ("eglChooseConfig");
3716 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3717 caml_failwith ("eglGetConfigAttrib");
3720 glx.conf = conf;
3721 initcurs ();
3723 glx.wid = Int_val (wid_v);
3724 CAMLreturn (Val_int (visid));
3727 CAMLprim void ml_glxcompleteinit (value unit_v)
3729 CAMLparam1 (unit_v);
3731 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3732 if (!glx.ctx) {
3733 caml_failwith ("eglCreateContext");
3736 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3737 glx.wid, NULL);
3738 if (glx.win == EGL_NO_SURFACE) {
3739 caml_failwith ("eglCreateWindowSurface");
3742 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3743 glx.ctx = NULL;
3744 caml_failwith ("eglMakeCurrent");
3746 CAMLreturn0;
3748 #else
3749 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3751 CAMLparam3 (display_v, wid_v, screen_v);
3753 glx.dpy = XOpenDisplay (String_val (display_v));
3754 if (!glx.dpy) {
3755 caml_failwith ("XOpenDisplay");
3758 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3759 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3760 if (!glx.visual) {
3761 XCloseDisplay (glx.dpy);
3762 caml_failwith ("glXChooseVisual");
3765 initcurs ();
3767 glx.wid = Int_val (wid_v);
3768 CAMLreturn (Val_int (glx.visual->visualid));
3771 CAMLprim void ml_glxcompleteinit (value unit_v)
3773 CAMLparam1 (unit_v);
3775 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3776 if (!glx.ctx) {
3777 caml_failwith ("glXCreateContext");
3780 XFree (glx.visual);
3781 glx.visual = NULL;
3783 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3784 glXDestroyContext (glx.dpy, glx.ctx);
3785 glx.ctx = NULL;
3786 caml_failwith ("glXMakeCurrent");
3788 CAMLreturn0;
3790 #endif
3792 CAMLprim void ml_setcursor (value cursor_v)
3794 CAMLparam1 (cursor_v);
3795 size_t cursn = Int_val (cursor_v);
3797 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3798 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3799 XFlush (glx.dpy);
3800 CAMLreturn0;
3803 CAMLprim void ml_swapb (value unit_v)
3805 CAMLparam1 (unit_v);
3806 #ifdef USE_EGL
3807 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3808 caml_failwith ("eglSwapBuffers");
3810 #else
3811 glXSwapBuffers (glx.dpy, glx.wid);
3812 #endif
3813 CAMLreturn0;
3816 #include "keysym2ucs.c"
3818 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3820 CAMLparam1 (keysym_v);
3821 CAMLlocal1 (str_v);
3822 KeySym keysym = Int_val (keysym_v);
3823 Rune rune;
3824 int len;
3825 char buf[5];
3827 rune = keysym2ucs (keysym);
3828 len = fz_runetochar (buf, rune);
3829 buf[len] = 0;
3830 str_v = caml_copy_string (buf);
3831 CAMLreturn (str_v);
3833 #else
3834 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3836 CAMLparam1 (keysym_v);
3837 CAMLlocal1 (str_v);
3838 long ucs_v = Long_val (keysym_v);
3839 int len;
3840 char buf[5];
3842 len = fz_runetochar (buf, ucs_v);
3843 buf[len] = 0;
3844 str_v = caml_copy_string (buf);
3845 CAMLreturn (str_v);
3847 #endif
3849 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3851 CAMLprim value ml_platform (value unit_v)
3853 CAMLparam1 (unit_v);
3854 CAMLlocal2 (tup_v, arr_v);
3855 int platid = piunknown;
3856 struct utsname buf;
3858 #if defined __linux__
3859 platid = pilinux;
3860 #elif defined __CYGWIN__
3861 platid = picygwin;
3862 #elif defined __DragonFly__ || defined __FreeBSD__
3863 || defined __OpenBSD__ || defined __NetBSD__
3864 platid = pibsd;
3865 #elif defined __sun__
3866 platid = pisun;
3867 #elif defined __APPLE__
3868 platid = piosx;
3869 #endif
3870 if (uname (&buf)) err (1, "uname");
3872 tup_v = caml_alloc_tuple (2);
3874 char const *sar[] = {
3875 buf.sysname,
3876 buf.release,
3877 buf.version,
3878 buf.machine,
3879 NULL
3881 arr_v = caml_copy_string_array (sar);
3883 Field (tup_v, 0) = Val_int (platid);
3884 Field (tup_v, 1) = arr_v;
3885 CAMLreturn (tup_v);
3888 CAMLprim void ml_cloexec (value fd_v)
3890 CAMLparam1 (fd_v);
3891 int fd = Int_val (fd_v);
3893 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3894 uerror ("fcntl", Nothing);
3896 CAMLreturn0;
3899 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3901 CAMLparam2 (w_v, h_v);
3902 CAMLlocal1 (ret_v);
3903 struct bo *pbo;
3904 int w = Int_val (w_v);
3905 int h = Int_val (h_v);
3906 int cs = Int_val (cs_v);
3908 if (state.bo_usable) {
3909 pbo = calloc (sizeof (*pbo), 1);
3910 if (!pbo) {
3911 err (1, "calloc pbo");
3914 switch (cs) {
3915 case 0:
3916 case 1:
3917 pbo->size = w*h*4;
3918 break;
3919 case 2:
3920 pbo->size = w*h*2;
3921 break;
3922 default:
3923 errx (1, "%s: invalid colorspace %d", __func__, cs);
3926 state.glGenBuffersARB (1, &pbo->id);
3927 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3928 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3929 NULL, GL_STREAM_DRAW);
3930 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3931 GL_READ_WRITE);
3932 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3933 if (!pbo->ptr) {
3934 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3935 state.glDeleteBuffersARB (1, &pbo->id);
3936 free (pbo);
3937 ret_v = caml_copy_string ("0");
3939 else {
3940 int res;
3941 char *s;
3943 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3944 if (res < 0) {
3945 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3947 s = malloc (res+1);
3948 if (!s) {
3949 err (1, "malloc %d bytes failed", res+1);
3951 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3952 if (res < 0) {
3953 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3955 ret_v = caml_copy_string (s);
3956 free (s);
3959 else {
3960 ret_v = caml_copy_string ("0");
3962 CAMLreturn (ret_v);
3965 CAMLprim void ml_freepbo (value s_v)
3967 CAMLparam1 (s_v);
3968 char *s = String_val (s_v);
3969 struct tile *tile = parse_pointer (__func__, s);
3971 if (tile->pbo) {
3972 state.glDeleteBuffersARB (1, &tile->pbo->id);
3973 tile->pbo->id = -1;
3974 tile->pbo->ptr = NULL;
3975 tile->pbo->size = -1;
3977 CAMLreturn0;
3980 CAMLprim void ml_unmappbo (value s_v)
3982 CAMLparam1 (s_v);
3983 char *s = String_val (s_v);
3984 struct tile *tile = parse_pointer (__func__, s);
3986 if (tile->pbo) {
3987 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3988 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3989 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3991 tile->pbo->ptr = NULL;
3992 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3994 CAMLreturn0;
3997 static void setuppbo (void)
3999 #ifdef __COCOA__
4000 static CFBundleRef framework = NULL;
4001 if (framework == NULL)
4002 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
4003 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
4004 #else
4005 #ifdef USE_EGL
4006 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4007 #else
4008 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4009 #endif
4010 state.bo_usable = GGPA (glBindBufferARB)
4011 && GGPA (glUnmapBufferARB)
4012 && GGPA (glMapBufferARB)
4013 && GGPA (glBufferDataARB)
4014 && GGPA (glGenBuffersARB)
4015 && GGPA (glDeleteBuffersARB);
4016 #endif
4017 #undef GGPA
4020 CAMLprim value ml_bo_usable (value unit_v)
4022 CAMLparam1 (unit_v);
4023 CAMLreturn (Val_bool (state.bo_usable));
4026 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4028 CAMLparam3 (ptr_v, x_v, y_v);
4029 CAMLlocal2 (ret_v, tup_v);
4030 struct page *page;
4031 char *s = String_val (ptr_v);
4032 int x = Int_val (x_v), y = Int_val (y_v);
4033 struct pagedim *pdim;
4034 fz_point p;
4035 fz_matrix ctm;
4037 page = parse_pointer (__func__, s);
4038 pdim = &state.pagedims[page->pdimno];
4040 ret_v = Val_int (0);
4041 if (trylock (__func__)) {
4042 goto done;
4045 if (pdf_specifics (state.ctx, state.doc)) {
4046 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4047 ctm = state.pagedims[page->pdimno].tctm;
4049 else {
4050 ctm = fz_identity;
4052 p.x = x + pdim->bounds.x0;
4053 p.y = y + pdim->bounds.y0;
4055 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4056 fz_invert_matrix (&ctm, &ctm);
4057 fz_transform_point (&p, &ctm);
4059 tup_v = caml_alloc_tuple (2);
4060 ret_v = caml_alloc_small (1, 1);
4061 Field (tup_v, 0) = Val_int (p.x);
4062 Field (tup_v, 1) = Val_int (p.y);
4063 Field (ret_v, 0) = tup_v;
4065 unlock (__func__);
4066 done:
4067 CAMLreturn (ret_v);
4070 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4071 value x_v, value y_v)
4073 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4074 CAMLlocal1 (ret_v);
4075 struct page *page;
4076 char *s = String_val (ptr_v);
4077 int pageno = Int_val (pageno_v);
4078 int pdimno = Int_val (pdimno_v);
4079 double x = Double_val (x_v), y = Double_val (y_v);
4080 struct pagedim *pdim;
4081 fz_point p;
4082 fz_matrix ctm;
4084 ret_v = Val_int (0);
4085 lock (__func__);
4087 if (!*s) {
4088 page = loadpage (pageno, pdimno);
4090 else {
4091 page = parse_pointer (__func__, s);
4093 pdim = &state.pagedims[pdimno];
4095 if (pdf_specifics (state.ctx, state.doc)) {
4096 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4097 ctm = state.pagedims[page->pdimno].tctm;
4099 else {
4100 ctm = fz_identity;
4102 p.x = x + pdim->bounds.x0;
4103 p.y = y + pdim->bounds.y0;
4105 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4106 fz_transform_point (&p, &ctm);
4108 ret_v = caml_alloc_tuple (2);
4109 Field (ret_v, 0) = caml_copy_double (p.x);
4110 Field (ret_v, 1) = caml_copy_double (p.y);
4112 if (!*s) {
4113 freepage (page);
4115 unlock (__func__);
4116 CAMLreturn (ret_v);
4119 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4120 value contents_v)
4122 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4123 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4125 if (pdf) {
4126 pdf_annot *annot;
4127 struct page *page;
4128 fz_point p;
4129 char *s = String_val (ptr_v);
4131 page = parse_pointer (__func__, s);
4132 annot = pdf_create_annot (state.ctx,
4133 pdf_page_from_fz_page (state.ctx,
4134 page->fzpage),
4135 PDF_ANNOT_TEXT);
4136 p.x = Int_val (x_v);
4137 p.y = Int_val (y_v);
4138 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4139 pdf_set_text_annot_position (state.ctx, annot, p);
4140 state.dirty = 1;
4142 CAMLreturn0;
4145 CAMLprim void ml_delannot (value ptr_v, value n_v)
4147 CAMLparam2 (ptr_v, n_v);
4148 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4150 if (pdf) {
4151 struct page *page;
4152 char *s = String_val (ptr_v);
4153 struct slink *slink;
4155 page = parse_pointer (__func__, s);
4156 slink = &page->slinks[Int_val (n_v)];
4157 pdf_delete_annot (state.ctx,
4158 pdf_page_from_fz_page (state.ctx, page->fzpage),
4159 (pdf_annot *) slink->u.annot);
4160 state.dirty = 1;
4162 CAMLreturn0;
4165 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4167 CAMLparam3 (ptr_v, n_v, str_v);
4168 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4170 if (pdf) {
4171 struct page *page;
4172 char *s = String_val (ptr_v);
4173 struct slink *slink;
4175 page = parse_pointer (__func__, s);
4176 slink = &page->slinks[Int_val (n_v)];
4177 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4178 String_val (str_v));
4179 state.dirty = 1;
4181 CAMLreturn0;
4184 CAMLprim value ml_hasunsavedchanges (value unit_v)
4186 CAMLparam1 (unit_v);
4187 CAMLreturn (Val_bool (state.dirty));
4190 CAMLprim void ml_savedoc (value path_v)
4192 CAMLparam1 (path_v);
4193 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4195 if (pdf) {
4196 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4198 CAMLreturn0;
4201 static void makestippletex (void)
4203 const char pixels[] = "\xff\xff\0\0";
4204 glGenTextures (1, &state.stid);
4205 glBindTexture (GL_TEXTURE_1D, state.stid);
4206 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4207 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4208 glTexImage1D (
4209 GL_TEXTURE_1D,
4211 GL_ALPHA,
4214 GL_ALPHA,
4215 GL_UNSIGNED_BYTE,
4216 pixels
4220 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4222 return caml_copy_string (FZ_VERSION);
4225 CAMLprim void ml_init (value csock_v, value params_v)
4227 CAMLparam2 (csock_v, params_v);
4228 CAMLlocal2 (trim_v, fuzz_v);
4229 int ret;
4230 int texcount;
4231 char *fontpath;
4232 int colorspace;
4233 int mustoresize;
4234 int haspboext;
4236 /* Without following call to setlocale mbstowcs fails for, at
4237 least, strings containing chinese symbols (δΈ­ for instance)
4238 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4239 wide character" as the reason of failure and with macOS
4240 producing bogus output) */
4241 if (setlocale (LC_CTYPE, "")) {
4242 /* Following two lines were taken from dvtm/vt.c */
4243 const char *cset = nl_langinfo (CODESET);
4244 state.utf8cs = !strcmp (cset, "UTF-8");
4246 else {
4247 fprintf (stderr, "setlocale failed\n");
4250 state.csock = Int_val (csock_v);
4251 state.rotate = Int_val (Field (params_v, 0));
4252 state.fitmodel = Int_val (Field (params_v, 1));
4253 trim_v = Field (params_v, 2);
4254 texcount = Int_val (Field (params_v, 3));
4255 state.sliceheight = Int_val (Field (params_v, 4));
4256 mustoresize = Int_val (Field (params_v, 5));
4257 colorspace = Int_val (Field (params_v, 6));
4258 fontpath = String_val (Field (params_v, 7));
4260 if (caml_string_length (Field (params_v, 8)) > 0) {
4261 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4263 if (!state.trimcachepath) {
4264 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4265 strerror (errno));
4269 haspboext = Bool_val (Field (params_v, 9));
4271 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4272 fz_register_document_handlers (state.ctx);
4274 state.trimmargins = Bool_val (Field (trim_v, 0));
4275 fuzz_v = Field (trim_v, 1);
4276 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4277 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4278 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4279 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4281 set_tex_params (colorspace);
4283 if (*fontpath) {
4284 state.face = load_font (fontpath);
4286 else {
4287 int len;
4288 const unsigned char *data;
4290 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4291 state.face = load_builtin_font (data, len);
4293 if (!state.face) _exit (1);
4295 realloctexts (texcount);
4297 if (haspboext) {
4298 setuppbo ();
4301 makestippletex ();
4303 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4304 if (ret) {
4305 errx (1, "pthread_create: %s", strerror (ret));
4308 CAMLreturn0;