Cosmetics
[llpp.git] / link.c
blob54cd41f8b672dd547c6d5750b8f5f86190a67deb
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
3 #define FIXME 0
5 #include <errno.h>
6 #include <stdio.h>
7 #include <ctype.h>
8 #include <string.h>
9 #include <stdlib.h>
10 #include <signal.h>
12 #include <wchar.h>
13 #include <locale.h>
14 #include <langinfo.h>
16 #include <unistd.h>
17 #include <pthread.h>
18 #include <sys/uio.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/ioctl.h>
22 #include <sys/utsname.h>
24 #ifdef __CYGWIN__
25 #include <cygwin/socket.h> /* FIONREAD */
26 #else
27 #include <spawn.h>
28 #endif
30 #include <regex.h>
31 #include <stdarg.h>
32 #include <limits.h>
33 #include <inttypes.h>
35 #ifdef __COCOA__
36 #include <CoreFoundation/CoreFoundation.h>
37 #endif
39 #ifdef __APPLE__
40 #include <OpenGL/gl.h>
41 #else
42 #include <GL/gl.h>
43 #endif
45 #include <caml/fail.h>
46 #include <caml/alloc.h>
47 #include <caml/memory.h>
48 #include <caml/unixsupport.h>
50 #if __GNUC__ < 5 && !defined __clang__
51 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
52 clobbered diagnostics */
53 #pragma GCC diagnostic ignored "-Wclobbered"
54 #endif
56 #pragma GCC diagnostic push
57 #pragma GCC diagnostic ignored "-Wunused-parameter"
58 #include <mupdf/fitz.h>
59 #include <mupdf/pdf.h>
60 #pragma GCC diagnostic pop
62 #include <ft2build.h>
63 #include FT_FREETYPE_H
65 #define PIGGYBACK
66 #define CACHE_PAGEREFS
68 #ifndef __USE_GNU
69 extern char **environ;
70 #endif
72 #if defined __GNUC__
73 #define NORETURN_ATTR __attribute__ ((noreturn))
74 #define UNUSED_ATTR __attribute__ ((unused))
75 #if !defined __clang__
76 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
77 #else
78 #define OPTIMIZE_ATTR(n)
79 #endif
80 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
81 #else
82 #define NORETURN_ATTR
83 #define UNUSED_ATTR
84 #define OPTIMIZE_ATTR(n)
85 #define GCC_FMT_ATTR(a, b)
86 #endif
88 #define FMT_s "zu"
90 #define FMT_ptr PRIxPTR
91 #define SCN_ptr SCNxPTR
92 #define FMT_ptr_cast(p) ((uintptr_t) (p))
93 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
95 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
96 err (int exitcode, const char *fmt, ...)
98 va_list ap;
99 int savederrno;
101 savederrno = errno;
102 va_start (ap, fmt);
103 vfprintf (stderr, fmt, ap);
104 va_end (ap);
105 fprintf (stderr, ": %s\n", strerror (savederrno));
106 fflush (stderr);
107 _exit (exitcode);
110 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
111 errx (int exitcode, const char *fmt, ...)
113 va_list ap;
115 va_start (ap, fmt);
116 vfprintf (stderr, fmt, ap);
117 va_end (ap);
118 fputc ('\n', stderr);
119 fflush (stderr);
120 _exit (exitcode);
123 #ifndef GL_TEXTURE_RECTANGLE_ARB
124 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
125 #endif
127 #ifdef USE_NPOT
128 #define TEXT_TYPE GL_TEXTURE_2D
129 #else
130 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
131 #endif
133 #ifndef GL_BGRA
134 #define GL_BGRA 0x80E1
135 #endif
137 #ifndef GL_UNSIGNED_INT_8_8_8_8
138 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
139 #endif
141 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
142 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
143 #endif
145 #if 0
146 #define lprintf printf
147 #else
148 #define lprintf(...)
149 #endif
151 #define ARSERT(cond) for (;;) { \
152 if (!(cond)) { \
153 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
155 break; \
158 struct slice {
159 int h;
160 int texindex;
163 struct tile {
164 int w, h;
165 int slicecount;
166 int sliceheight;
167 struct bo *pbo;
168 fz_pixmap *pixmap;
169 struct slice slices[1];
172 struct pagedim {
173 int pageno;
174 int rotate;
175 int left;
176 int tctmready;
177 fz_irect bounds;
178 fz_rect pagebox;
179 fz_rect mediabox;
180 fz_matrix ctm, zoomctm, tctm;
183 struct slink {
184 enum { SLINK, SANNOT } tag;
185 fz_irect bbox;
186 union {
187 fz_link *link;
188 fz_annot *annot;
189 } u;
192 struct annot {
193 fz_irect bbox;
194 fz_annot *annot;
197 struct page {
198 int tgen;
199 int sgen;
200 int agen;
201 int pageno;
202 int pdimno;
203 fz_stext_page *text;
204 fz_stext_sheet *sheet;
205 fz_page *fzpage;
206 fz_display_list *dlist;
207 int slinkcount;
208 struct slink *slinks;
209 int annotcount;
210 struct annot *annots;
211 struct mark {
212 int i;
213 fz_stext_span *span;
214 } fmark, lmark;
217 struct {
218 int sliceheight;
219 struct pagedim *pagedims;
220 int pagecount;
221 int pagedimcount;
222 fz_document *doc;
223 fz_context *ctx;
224 int w, h;
226 int texindex;
227 int texcount;
228 GLuint *texids;
230 GLenum texiform;
231 GLenum texform;
232 GLenum texty;
234 fz_colorspace *colorspace;
236 struct {
237 int w, h;
238 struct slice *slice;
239 } *texowners;
241 int rotate;
242 enum { FitWidth, FitProportional, FitPage } fitmodel;
243 int trimmargins;
244 int needoutline;
245 int gen;
246 int aalevel;
248 int trimanew;
249 fz_irect trimfuzz;
250 fz_pixmap *pig;
252 pthread_t thread;
253 int csock;
254 FT_Face face;
256 char *trimcachepath;
257 int cxack;
258 int dirty;
260 GLuint stid;
262 int bo_usable;
263 GLuint boid;
265 void (*glBindBufferARB) (GLenum, GLuint);
266 GLboolean (*glUnmapBufferARB) (GLenum);
267 void *(*glMapBufferARB) (GLenum, GLenum);
268 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
269 void (*glGenBuffersARB) (GLsizei, GLuint *);
270 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
272 GLfloat texcoords[8];
273 GLfloat vertices[16];
275 #ifdef CACHE_PAGEREFS
276 struct {
277 int idx;
278 int count;
279 pdf_obj **objs;
280 pdf_document *pdf;
281 } pdflut;
282 #endif
283 int utf8cs;
284 } state;
286 struct bo {
287 GLuint id;
288 void *ptr;
289 size_t size;
292 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
294 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
297 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
299 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
302 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
304 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
305 m.a, m.b, m.c, m.d, m.e, m.f);
308 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
310 static void lock (const char *cap)
312 int ret = pthread_mutex_lock (&mutex);
313 if (ret) {
314 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
318 static void unlock (const char *cap)
320 int ret = pthread_mutex_unlock (&mutex);
321 if (ret) {
322 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
326 static int trylock (const char *cap)
328 int ret = pthread_mutex_trylock (&mutex);
329 if (ret && ret != EBUSY) {
330 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
332 return ret == EBUSY;
335 static void *parse_pointer (const char *cap, const char *s)
337 int ret;
338 void *ptr;
340 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
341 if (ret != 1) {
342 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
344 return ptr;
347 static double now (void)
349 struct timeval tv;
351 if (gettimeofday (&tv, NULL)) {
352 err (1, "gettimeofday");
354 return tv.tv_sec + tv.tv_usec*1e-6;
357 static int hasdata (void)
359 int ret, avail;
360 ret = ioctl (state.csock, FIONREAD, &avail);
361 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
362 return avail > 0;
365 CAMLprim value ml_hasdata (value fd_v)
367 CAMLparam1 (fd_v);
368 int ret, avail;
370 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
371 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
372 CAMLreturn (Val_bool (avail > 0));
375 static void readdata (int fd, void *p, int size)
377 ssize_t n;
379 again:
380 n = read (fd, p, size);
381 if (n - size) {
382 if (n < 0 && errno == EINTR) goto again;
383 if (!n) errx (1, "EOF while reading");
384 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
388 static void writedata (int fd, char *p, int size)
390 ssize_t n;
391 uint32_t size4 = size;
392 struct iovec iov[2] = {
393 { .iov_base = &size4, .iov_len = 4 },
394 { .iov_base = p, .iov_len = size }
397 again:
398 n = writev (fd, iov, 2);
399 if (n < 0 && errno == EINTR) goto again;
400 if (n - size - 4) {
401 if (!n) errx (1, "EOF while writing data");
402 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
406 static int readlen (int fd)
408 /* Type punned unions here. Why? Less code (Adjusted by more comments).
409 https://en.wikipedia.org/wiki/Type_punning */
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->sheet) {
570 fz_drop_stext_sheet (state.ctx, page->sheet);
572 if (page->slinks) {
573 free (page->slinks);
575 fz_drop_display_list (state.ctx, page->dlist);
576 fz_drop_page (state.ctx, page->fzpage);
577 free (page);
580 static void freetile (struct tile *tile)
582 unlinktile (tile);
583 if (!tile->pbo) {
584 #ifndef PIGGYBACK
585 fz_drop_pixmap (state.ctx, tile->pixmap);
586 #else
587 if (state.pig) {
588 fz_drop_pixmap (state.ctx, state.pig);
590 state.pig = tile->pixmap;
591 #endif
593 else {
594 free (tile->pbo);
595 fz_drop_pixmap (state.ctx, tile->pixmap);
597 free (tile);
600 #ifdef __ALTIVEC__
601 #include <stdint.h>
602 #include <altivec.h>
604 static int cacheline32bytes;
606 static void __attribute__ ((constructor)) clcheck (void)
608 char **envp = environ;
609 unsigned long *auxv;
611 while (*envp++);
613 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
614 if (*auxv == 19) {
615 cacheline32bytes = auxv[1] == 32;
616 return;
621 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
623 size_t size = pixmap->w * pixmap->h * pixmap->n;
624 if (cacheline32bytes && size > 32) {
625 intptr_t a1, a2, diff;
626 size_t sizea, i;
627 vector unsigned char v = vec_splat_u8 (-1);
628 vector unsigned char *p;
630 a1 = a2 = (intptr_t) pixmap->samples;
631 a2 = (a1 + 31) & ~31;
632 diff = a2 - a1;
633 sizea = size - diff;
634 p = (void *) a2;
636 while (a1 != a2) *(char *) a1++ = 0xff;
637 for (i = 0; i < (sizea & ~31); i += 32) {
638 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
639 vec_st (v, i, p);
640 vec_st (v, i + 16, p);
642 while (i < sizea) *((char *) a1 + i++) = 0xff;
644 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
646 #else
647 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
648 #endif
650 static void trimctm (pdf_page *page, int pindex)
652 fz_matrix ctm;
653 struct pagedim *pdim = &state.pagedims[pindex];
655 if (!page) return;
656 if (!pdim->tctmready) {
657 fz_rect realbox, mediabox;
658 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
660 fz_rotate (&rm, -pdim->rotate);
661 fz_scale (&sm, 1, -1);
662 fz_concat (&ctm, &rm, &sm);
663 realbox = pdim->mediabox;
664 fz_transform_rect (&realbox, &ctm);
665 fz_translate (&tm, -realbox.x0, -realbox.y0);
666 fz_concat (&ctm1, &ctm, &tm);
667 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
668 fz_invert_matrix (&im, &page_ctm);
669 fz_concat (&ctm, &im, &ctm1);
670 pdim->tctm = ctm;
671 pdim->tctmready = 1;
675 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
677 fz_matrix ctm, tm;
678 int pdimno = pdim - state.pagedims;
680 if (pdf_specifics (state.ctx, state.doc)) {
681 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
682 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
684 else {
685 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
686 fz_concat (&ctm, &tm, &pdim->ctm);
688 return ctm;
691 static fz_matrix pagectm (struct page *page)
693 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
696 static void *loadpage (int pageno, int pindex)
698 fz_device *dev;
699 struct page *page;
701 page = calloc (sizeof (struct page), 1);
702 if (!page) {
703 err (1, "calloc page %d", pageno);
706 page->dlist = fz_new_display_list (state.ctx, NULL);
707 dev = fz_new_list_device (state.ctx, page->dlist);
708 fz_try (state.ctx) {
709 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
710 fz_run_page (state.ctx, page->fzpage, dev,
711 &fz_identity, NULL);
713 fz_catch (state.ctx) {
714 page->fzpage = NULL;
716 fz_close_device (state.ctx, dev);
717 fz_drop_device (state.ctx, dev);
719 page->pdimno = pindex;
720 page->pageno = pageno;
721 page->sgen = state.gen;
722 page->agen = state.gen;
723 page->tgen = state.gen;
724 return page;
727 static struct tile *alloctile (int h)
729 int slicecount;
730 size_t tilesize;
731 struct tile *tile;
733 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
734 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
735 tile = calloc (tilesize, 1);
736 if (!tile) {
737 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
739 for (int i = 0; i < slicecount; ++i) {
740 int sh = fz_mini (h, state.sliceheight);
741 tile->slices[i].h = sh;
742 tile->slices[i].texindex = -1;
743 h -= sh;
745 tile->slicecount = slicecount;
746 tile->sliceheight = state.sliceheight;
747 return tile;
750 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
751 struct bo *pbo)
753 fz_rect rect;
754 fz_irect bbox;
755 fz_matrix ctm;
756 fz_device *dev;
757 struct tile *tile;
758 struct pagedim *pdim;
760 tile = alloctile (h);
761 pdim = &state.pagedims[page->pdimno];
763 bbox = pdim->bounds;
764 bbox.x0 += x;
765 bbox.y0 += y;
766 bbox.x1 = bbox.x0 + w;
767 bbox.y1 = bbox.y0 + h;
769 if (state.pig) {
770 if (state.pig->w == w
771 && state.pig->h == h
772 && state.pig->colorspace == state.colorspace) {
773 tile->pixmap = state.pig;
774 tile->pixmap->x = bbox.x0;
775 tile->pixmap->y = bbox.y0;
777 else {
778 fz_drop_pixmap (state.ctx, state.pig);
780 state.pig = NULL;
782 if (!tile->pixmap) {
783 if (pbo) {
784 tile->pixmap =
785 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
786 &bbox, 1, pbo->ptr);
787 tile->pbo = pbo;
789 else {
790 tile->pixmap =
791 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
795 tile->w = w;
796 tile->h = h;
797 clearpixmap (tile->pixmap);
799 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
800 ctm = pagectm (page);
801 fz_rect_from_irect (&rect, &bbox);
802 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
803 fz_close_device (state.ctx, dev);
804 fz_drop_device (state.ctx, dev);
806 return tile;
809 #ifdef CACHE_PAGEREFS
810 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
811 thanks to Robin Watts */
812 static void
813 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
815 fz_context *ctx = state.ctx; /* doc->ctx; */
816 pdf_obj *kids;
817 int len;
819 if (state.pdflut.idx == state.pagecount) return;
821 kids = pdf_dict_gets (ctx, node, "Kids");
822 len = pdf_array_len (ctx, kids);
824 if (len == 0)
825 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
827 if (pdf_mark_obj (ctx, node))
828 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
829 for (int i = 0; i < len; i++) {
830 pdf_obj *kid = pdf_array_get (ctx, kids, i);
831 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
832 if (*type
833 ? !strcmp (type, "Pages")
834 : pdf_dict_gets (ctx, kid, "Kids")
835 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
836 pdf_collect_pages (doc, kid);
838 else {
839 if (*type
840 ? strcmp (type, "Page") != 0
841 : !pdf_dict_gets (ctx, kid, "MediaBox"))
842 fz_warn (ctx, "non-page object in page tree (%s)", type);
843 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
846 pdf_unmark_obj (ctx, node);
849 static void
850 pdf_load_page_objs (pdf_document *doc)
852 pdf_obj *root = pdf_dict_gets (state.ctx,
853 pdf_trailer (state.ctx, doc), "Root");
854 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
856 if (!node)
857 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
859 state.pdflut.idx = 0;
860 pdf_collect_pages (doc, node);
862 #endif
864 static void initpdims (int wthack)
866 double start, end;
867 FILE *trimf = NULL;
868 fz_rect rootmediabox;
869 int pageno, trim, show;
870 int trimw = 0, cxcount;
871 fz_context *ctx = state.ctx;
872 pdf_document *pdf = pdf_specifics (ctx, state.doc);
874 fz_var (trimw);
875 fz_var (trimf);
876 fz_var (cxcount);
877 start = now ();
879 if (state.trimmargins && state.trimcachepath) {
880 trimf = fopen (state.trimcachepath, "rb");
881 if (!trimf) {
882 trimf = fopen (state.trimcachepath, "wb");
883 trimw = 1;
887 if (state.trimmargins || pdf || !state.cxack)
888 cxcount = state.pagecount;
889 else
890 cxcount = fz_mini (state.pagecount, 1);
892 if (pdf) {
893 pdf_obj *obj;
894 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
895 "Root/Pages/MediaBox");
896 pdf_to_rect (ctx, obj, &rootmediabox);
899 #ifdef CACHE_PAGEREFS
900 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
901 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
902 if (!state.pdflut.objs) {
903 err (1, "malloc pageobjs %zu %d %zu failed",
904 sizeof (*state.pdflut.objs), cxcount,
905 sizeof (*state.pdflut.objs) * cxcount);
907 state.pdflut.count = cxcount;
908 pdf_load_page_objs (pdf);
909 state.pdflut.pdf = pdf;
911 #endif
913 for (pageno = 0; pageno < cxcount; ++pageno) {
914 int rotate = 0;
915 struct pagedim *p;
916 fz_rect mediabox;
918 fz_var (rotate);
919 if (pdf) {
920 pdf_obj *pageref, *pageobj;
922 #ifdef CACHE_PAGEREFS
923 pageref = state.pdflut.objs[pageno];
924 #else
925 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
926 #endif
927 pageobj = pdf_resolve_indirect (ctx, pageref);
928 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
930 if (state.trimmargins) {
931 pdf_obj *obj;
932 pdf_page *page;
934 fz_try (ctx) {
935 page = pdf_load_page (ctx, pdf, pageno);
936 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
937 trim = state.trimanew || !obj;
938 if (trim) {
939 fz_rect rect;
940 fz_device *dev;
941 fz_matrix ctm, page_ctm;
943 dev = fz_new_bbox_device (ctx, &rect);
944 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
945 fz_invert_matrix (&ctm, &page_ctm);
946 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
947 fz_close_device (ctx, dev);
948 fz_drop_device (ctx, dev);
950 rect.x0 += state.trimfuzz.x0;
951 rect.x1 += state.trimfuzz.x1;
952 rect.y0 += state.trimfuzz.y0;
953 rect.y1 += state.trimfuzz.y1;
954 fz_transform_rect (&rect, &ctm);
955 fz_intersect_rect (&rect, &mediabox);
957 if (!fz_is_empty_rect (&rect)) {
958 mediabox = rect;
961 obj = pdf_new_array (ctx, pdf, 4);
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.x0));
964 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
965 mediabox.y0));
966 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
967 mediabox.x1));
968 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
969 mediabox.y1));
970 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
972 else {
973 mediabox.x0 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 0));
975 mediabox.y0 = pdf_to_real (ctx,
976 pdf_array_get (ctx, obj, 1));
977 mediabox.x1 = pdf_to_real (ctx,
978 pdf_array_get (ctx, obj, 2));
979 mediabox.y1 = pdf_to_real (ctx,
980 pdf_array_get (ctx, obj, 3));
983 fz_drop_page (ctx, &page->super);
984 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
985 if (show) {
986 printd ("progress %f Trimming %d",
987 (double) (pageno + 1) / state.pagecount,
988 pageno + 1);
991 fz_catch (ctx) {
992 fprintf (stderr, "failed to load page %d\n", pageno+1);
995 else {
996 int empty = 0;
997 fz_rect cropbox;
999 pdf_to_rect (ctx,
1000 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1001 &mediabox);
1002 if (fz_is_empty_rect (&mediabox)) {
1003 mediabox.x0 = 0;
1004 mediabox.y0 = 0;
1005 mediabox.x1 = 612;
1006 mediabox.y1 = 792;
1007 empty = 1;
1010 pdf_to_rect (ctx,
1011 pdf_dict_gets (ctx, pageobj, "CropBox"),
1012 &cropbox);
1013 if (!fz_is_empty_rect (&cropbox)) {
1014 if (empty) {
1015 mediabox = cropbox;
1017 else {
1018 fz_intersect_rect (&mediabox, &cropbox);
1021 else {
1022 if (empty) {
1023 if (fz_is_empty_rect (&rootmediabox)) {
1024 fprintf (stderr,
1025 "cannot find page size for page %d\n",
1026 pageno+1);
1028 else {
1029 mediabox = rootmediabox;
1035 else {
1036 if (state.trimmargins && trimw) {
1037 fz_page *page;
1039 fz_try (ctx) {
1040 page = fz_load_page (ctx, state.doc, pageno);
1041 fz_bound_page (ctx, page, &mediabox);
1042 if (state.trimmargins) {
1043 fz_rect rect;
1044 fz_device *dev;
1046 dev = fz_new_bbox_device (ctx, &rect);
1047 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1048 fz_close_device (ctx, dev);
1049 fz_drop_device (ctx, dev);
1051 rect.x0 += state.trimfuzz.x0;
1052 rect.x1 += state.trimfuzz.x1;
1053 rect.y0 += state.trimfuzz.y0;
1054 rect.y1 += state.trimfuzz.y1;
1055 fz_intersect_rect (&rect, &mediabox);
1057 if (!fz_is_empty_rect (&rect)) {
1058 mediabox = rect;
1061 fz_drop_page (ctx, page);
1062 if (!state.cxack) {
1063 printd ("progress %f loading %d",
1064 (double) (pageno + 1) / state.pagecount,
1065 pageno + 1);
1068 fz_catch (ctx) {
1070 if (trimf) {
1071 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1072 if (n - 1) {
1073 err (1, "fwrite trim mediabox");
1077 else {
1078 if (trimf) {
1079 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1080 if (n - 1) {
1081 err (1, "fread trim mediabox %d", pageno);
1084 else {
1085 fz_page *page;
1086 fz_try (ctx) {
1087 page = fz_load_page (ctx, state.doc, pageno);
1088 fz_bound_page (ctx, page, &mediabox);
1089 fz_drop_page (ctx, page);
1091 show = !state.trimmargins && pageno % 20 == 0;
1092 if (show) {
1093 printd ("progress %f Gathering dimensions %d",
1094 (double) (pageno) / state.pagecount,
1095 pageno);
1098 fz_catch (ctx) {
1099 fprintf (stderr, "failed to load page %d\n", pageno);
1105 if (state.pagedimcount == 0
1106 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1107 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1108 size_t size;
1110 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1111 state.pagedims = realloc (state.pagedims, size);
1112 if (!state.pagedims) {
1113 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1114 size, state.pagedimcount + 1);
1117 p = &state.pagedims[state.pagedimcount++];
1118 p->rotate = rotate;
1119 p->mediabox = mediabox;
1120 p->pageno = pageno;
1123 end = now ();
1124 if (!wthack) {
1125 printd ("progress 1 %s %d pages in %f seconds",
1126 state.trimmargins ? "Trimmed" : "Processed",
1127 state.pagecount, end - start);
1129 state.trimanew = 0;
1130 if (trimf) {
1131 if (fclose (trimf)) {
1132 err (1, "fclose");
1137 static void layout (void)
1139 int pindex;
1140 fz_rect box;
1141 fz_matrix ctm, rm;
1142 struct pagedim *p = p;
1143 double zw, w, maxw = 0.0, zoom = zoom;
1145 if (state.pagedimcount == 0) return;
1147 switch (state.fitmodel) {
1148 case FitProportional:
1149 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1150 double x0, x1;
1152 p = &state.pagedims[pindex];
1153 fz_rotate (&rm, p->rotate + state.rotate);
1154 box = p->mediabox;
1155 fz_transform_rect (&box, &rm);
1157 x0 = fz_min (box.x0, box.x1);
1158 x1 = fz_max (box.x0, box.x1);
1160 w = x1 - x0;
1161 maxw = fz_max (w, maxw);
1162 zoom = state.w / maxw;
1164 break;
1166 case FitPage:
1167 maxw = state.w;
1168 break;
1170 case FitWidth:
1171 break;
1173 default:
1174 ARSERT (0 && state.fitmodel);
1177 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1178 fz_rect rect;
1179 fz_matrix tm, sm;
1181 p = &state.pagedims[pindex];
1182 fz_rotate (&ctm, state.rotate);
1183 fz_rotate (&rm, p->rotate + state.rotate);
1184 box = p->mediabox;
1185 fz_transform_rect (&box, &rm);
1186 w = box.x1 - box.x0;
1187 switch (state.fitmodel) {
1188 case FitProportional:
1189 p->left = ((maxw - w) * zoom) / 2.0;
1190 break;
1191 case FitPage:
1193 double zh, h;
1194 zw = maxw / w;
1195 h = box.y1 - box.y0;
1196 zh = state.h / h;
1197 zoom = fz_min (zw, zh);
1198 p->left = (maxw - (w * zoom)) / 2.0;
1200 break;
1201 case FitWidth:
1202 p->left = 0;
1203 zoom = state.w / w;
1204 break;
1207 fz_scale (&p->zoomctm, zoom, zoom);
1208 fz_concat (&ctm, &p->zoomctm, &ctm);
1210 fz_rotate (&rm, p->rotate);
1211 p->pagebox = p->mediabox;
1212 fz_transform_rect (&p->pagebox, &rm);
1213 p->pagebox.x1 -= p->pagebox.x0;
1214 p->pagebox.y1 -= p->pagebox.y0;
1215 p->pagebox.x0 = 0;
1216 p->pagebox.y0 = 0;
1217 rect = p->pagebox;
1218 fz_transform_rect (&rect, &ctm);
1219 fz_round_rect (&p->bounds, &rect);
1220 p->ctm = ctm;
1222 fz_translate (&tm, 0, -p->mediabox.y1);
1223 fz_scale (&sm, zoom, -zoom);
1224 fz_concat (&ctm, &tm, &sm);
1226 p->tctmready = 0;
1229 do {
1230 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1231 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1232 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1233 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1234 int boundw = x1 - x0;
1235 int boundh = y1 - y0;
1237 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1238 } while (p-- != state.pagedims);
1241 struct pagedim *pdimofpageno (int pageno)
1243 struct pagedim *pdim = state.pagedims;
1245 for (int i = 0; i < state.pagedimcount; ++i) {
1246 if (state.pagedims[i].pageno > pageno)
1247 break;
1248 pdim = &state.pagedims[i];
1250 return pdim;
1253 static
1254 struct anchor { int n; int x; int y; int w; int h; }
1255 uritoanchor (const char *uri)
1257 fz_point p;
1258 struct anchor a;
1260 a.n = -1;
1261 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1262 if (a.n >= 0) {
1263 struct pagedim *pdim = pdimofpageno (a.n);
1264 fz_transform_point (&p, &pdim->ctm);
1265 a.x = p.x;
1266 a.y = p.y;
1267 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1269 return a;
1272 static void recurse_outline (fz_outline *outline, int level)
1274 while (outline) {
1275 struct anchor a = uritoanchor (outline->uri);
1276 if (a.n >= 0) {
1277 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1279 else {
1280 printd ("on %d %s", level, outline->title);
1282 if (outline->down) {
1283 recurse_outline (outline->down, level + 1);
1285 outline = outline->next;
1289 static void process_outline (void)
1291 fz_outline *outline;
1293 if (!state.needoutline || !state.pagedimcount) return;
1295 state.needoutline = 0;
1296 outline = fz_load_outline (state.ctx, state.doc);
1297 if (outline) {
1298 recurse_outline (outline, 0);
1299 fz_drop_outline (state.ctx, outline);
1303 static char *strofspan (fz_stext_span *span)
1305 char *p;
1306 char utf8[10];
1307 fz_stext_char *ch;
1308 size_t size = 0, cap = 80;
1310 p = malloc (cap + 1);
1311 if (!p) return NULL;
1313 for (ch = span->text; ch < span->text + span->len; ++ch) {
1314 int n = fz_runetochar (utf8, ch->c);
1315 if (size + n > cap) {
1316 cap *= 2;
1317 p = realloc (p, cap + 1);
1318 if (!p) return NULL;
1321 memcpy (p + size, utf8, n);
1322 size += n;
1324 p[size] = 0;
1325 return p;
1328 static int matchspan (regex_t *re, fz_stext_span *span,
1329 int stop, int pageno, double start)
1331 int ret;
1332 char *p;
1333 regmatch_t rm;
1334 int a, b, c;
1335 fz_rect sb, eb;
1336 fz_point p1, p2, p3, p4;
1338 p = strofspan (span);
1339 if (!p) return -1;
1341 ret = regexec (re, p, 1, &rm, 0);
1342 if (ret) {
1343 free (p);
1344 if (ret != REG_NOMATCH) {
1345 size_t size;
1346 char errbuf[80];
1347 size = regerror (ret, re, errbuf, sizeof (errbuf));
1348 printd ("msg regexec error `%.*s'",
1349 (int) size, errbuf);
1350 return -1;
1352 return 0;
1354 else {
1355 int l = span->len;
1357 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1358 c += fz_runelen (span->text[a].c);
1360 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1361 c += fz_runelen (span->text[b].c);
1364 if (fz_runelen (span->text[b].c) > 1) {
1365 b = fz_maxi (0, b-1);
1368 fz_stext_char_bbox (state.ctx, &sb, span, a);
1369 fz_stext_char_bbox (state.ctx, &eb, span, b);
1371 p1.x = sb.x0;
1372 p1.y = sb.y0;
1373 p2.x = eb.x1;
1374 p2.y = sb.y0;
1375 p3.x = eb.x1;
1376 p3.y = eb.y1;
1377 p4.x = sb.x0;
1378 p4.y = eb.y1;
1380 if (!stop) {
1381 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1382 pageno, 1,
1383 p1.x, p1.y,
1384 p2.x, p2.y,
1385 p3.x, p3.y,
1386 p4.x, p4.y);
1388 printd ("progress 1 found at %d `%.*s' in %f sec",
1389 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1390 now () - start);
1392 else {
1393 printd ("match %d %d %f %f %f %f %f %f %f %f",
1394 pageno, 2,
1395 p1.x, p1.y,
1396 p2.x, p2.y,
1397 p3.x, p3.y,
1398 p4.x, p4.y);
1400 free (p);
1401 return 1;
1405 static int compareblocks (const void *l, const void *r)
1407 fz_stext_block const *ls = l;
1408 fz_stext_block const *rs = r;
1409 return ls->bbox.y0 - rs->bbox.y0;
1412 /* wishful thinking function */
1413 static void search (regex_t *re, int pageno, int y, int forward)
1415 int j;
1416 fz_device *tdev;
1417 fz_stext_page *text;
1418 fz_stext_sheet *sheet;
1419 struct pagedim *pdim;
1420 int stop = 0, niters = 0;
1421 double start, end;
1422 fz_page *page;
1424 start = now ();
1425 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1426 if (niters++ == 5) {
1427 niters = 0;
1428 if (hasdata ()) {
1429 printd ("progress 1 attention requested aborting search at %d",
1430 pageno);
1431 stop = 1;
1433 else {
1434 printd ("progress %f searching in page %d",
1435 (double) (pageno + 1) / state.pagecount,
1436 pageno);
1439 pdim = pdimofpageno (pageno);
1440 sheet = fz_new_stext_sheet (state.ctx);
1441 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1442 tdev = fz_new_stext_device (state.ctx, sheet, text, 0);
1444 page = fz_load_page (state.ctx, state.doc, pageno);
1446 fz_matrix ctm = pagectm1 (page, pdim);
1447 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1450 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1451 fz_close_device (state.ctx, tdev);
1452 fz_drop_device (state.ctx, tdev);
1454 for (j = 0; j < text->len; ++j) {
1455 int k;
1456 fz_page_block *pb;
1457 fz_stext_block *block;
1459 pb = &text->blocks[forward ? j : text->len - 1 - j];
1460 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1461 block = pb->u.text;
1463 for (k = 0; k < block->len; ++k) {
1464 fz_stext_line *line;
1465 fz_stext_span *span;
1467 if (forward) {
1468 line = &block->lines[k];
1469 if (line->bbox.y0 < y + 1) continue;
1471 else {
1472 line = &block->lines[block->len - 1 - k];
1473 if (line->bbox.y0 > y - 1) continue;
1476 for (span = line->first_span; span; span = span->next) {
1477 switch (matchspan (re, span, stop, pageno, start)) {
1478 case 0: break;
1479 case 1: stop = 1; break;
1480 case -1: stop = 1; goto endloop;
1485 if (forward) {
1486 pageno += 1;
1487 y = 0;
1489 else {
1490 pageno -= 1;
1491 y = INT_MAX;
1493 endloop:
1494 fz_drop_stext_page (state.ctx, text);
1495 fz_drop_stext_sheet (state.ctx, sheet);
1496 fz_drop_page (state.ctx, page);
1498 end = now ();
1499 if (!stop) {
1500 printd ("progress 1 no matches %f sec", end - start);
1502 printd ("clearrects");
1505 static void set_tex_params (int colorspace)
1507 union {
1508 unsigned char b;
1509 unsigned int s;
1510 } endianness = {1};
1512 switch (colorspace) {
1513 case 0:
1514 state.texiform = GL_RGBA8;
1515 state.texform = GL_RGBA;
1516 state.texty = GL_UNSIGNED_BYTE;
1517 state.colorspace = fz_device_rgb (state.ctx);
1518 break;
1519 case 1:
1520 state.texiform = GL_RGBA8;
1521 state.texform = GL_BGRA;
1522 state.texty = endianness.s > 1
1523 ? GL_UNSIGNED_INT_8_8_8_8
1524 : GL_UNSIGNED_INT_8_8_8_8_REV;
1525 state.colorspace = fz_device_bgr (state.ctx);
1526 break;
1527 case 2:
1528 state.texiform = GL_LUMINANCE_ALPHA;
1529 state.texform = GL_LUMINANCE_ALPHA;
1530 state.texty = GL_UNSIGNED_BYTE;
1531 state.colorspace = fz_device_gray (state.ctx);
1532 break;
1533 default:
1534 errx (1, "invalid colorspce %d", colorspace);
1538 static void realloctexts (int texcount)
1540 size_t size;
1542 if (texcount == state.texcount) return;
1544 if (texcount < state.texcount) {
1545 glDeleteTextures (state.texcount - texcount,
1546 state.texids + texcount);
1549 size = texcount * sizeof (*state.texids);
1550 state.texids = realloc (state.texids, size);
1551 if (!state.texids) {
1552 err (1, "realloc texids %" FMT_s, size);
1555 size = texcount * sizeof (*state.texowners);
1556 state.texowners = realloc (state.texowners, size);
1557 if (!state.texowners) {
1558 err (1, "realloc texowners %" FMT_s, size);
1560 if (texcount > state.texcount) {
1561 glGenTextures (texcount - state.texcount,
1562 state.texids + state.texcount);
1563 for (int i = state.texcount; i < texcount; ++i) {
1564 state.texowners[i].w = -1;
1565 state.texowners[i].slice = NULL;
1568 state.texcount = texcount;
1569 state.texindex = 0;
1572 static char *mbtoutf8 (char *s)
1574 char *p, *r;
1575 wchar_t *tmp;
1576 size_t i, ret, len;
1578 if (state.utf8cs) {
1579 return s;
1582 len = mbstowcs (NULL, s, strlen (s));
1583 if (len == 0) {
1584 return s;
1586 else {
1587 if (len == (size_t) -1) {
1588 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1589 return s;
1593 tmp = calloc (len, sizeof (wchar_t));
1594 if (!tmp) {
1595 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1596 len, sizeof (wchar_t), errno, strerror (errno));
1597 return s;
1600 ret = mbstowcs (tmp, s, len);
1601 if (ret == (size_t) -1) {
1602 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1603 len, errno, strerror (errno));
1604 free (tmp);
1605 return s;
1608 len = 0;
1609 for (i = 0; i < ret; ++i) {
1610 len += fz_runelen (tmp[i]);
1613 p = r = malloc (len + 1);
1614 if (!r) {
1615 printd ("emsg mbtoutf8: malloc(%zu)", len);
1616 free (tmp);
1617 return s;
1620 for (i = 0; i < ret; ++i) {
1621 p += fz_runetochar (p, tmp[i]);
1623 *p = 0;
1624 free (tmp);
1625 return r;
1628 CAMLprim value ml_mbtoutf8 (value s_v)
1630 CAMLparam1 (s_v);
1631 CAMLlocal1 (ret_v);
1632 char *s, *r;
1634 s = String_val (s_v);
1635 r = mbtoutf8 (s);
1636 if (r == s) {
1637 ret_v = s_v;
1639 else {
1640 ret_v = caml_copy_string (r);
1641 free (r);
1643 CAMLreturn (ret_v);
1646 static void * mainloop (void UNUSED_ATTR *unused)
1648 char *p = NULL;
1649 int len, ret, oldlen = 0;
1651 fz_var (p);
1652 fz_var (oldlen);
1653 for (;;) {
1654 len = readlen (state.csock);
1655 if (len == 0) {
1656 errx (1, "readlen returned 0");
1659 if (oldlen < len + 1) {
1660 p = realloc (p, len + 1);
1661 if (!p) {
1662 err (1, "realloc %d failed", len + 1);
1664 oldlen = len + 1;
1666 readdata (state.csock, p, len);
1667 p[len] = 0;
1669 if (!strncmp ("open", p, 4)) {
1670 int wthack, off, usedoccss, ok = 0;
1671 char *password;
1672 char *filename;
1673 char *utf8filename;
1674 size_t filenamelen;
1676 fz_var (ok);
1677 ret = sscanf (p + 5, " %d %d %d %n",
1678 &wthack, &state.cxack, &usedoccss, &off);
1679 if (ret != 3) {
1680 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1683 filename = p + 5 + off;
1684 filenamelen = strlen (filename);
1685 password = filename + filenamelen + 1;
1687 if (password[strlen (password) + 1]) {
1688 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1691 lock ("open");
1692 fz_set_use_document_css (state.ctx, usedoccss);
1693 fz_try (state.ctx) {
1694 ok = openxref (filename, password);
1696 fz_catch (state.ctx) {
1697 utf8filename = mbtoutf8 (filename);
1698 printd ("msg Could not open %s", utf8filename);
1700 if (ok) {
1701 pdfinfo ();
1702 initpdims (wthack);
1704 unlock ("open");
1706 if (ok) {
1707 if (!wthack) {
1708 utf8filename = mbtoutf8 (filename);
1709 printd ("msg Opened %s (press h/F1 to get help)",
1710 utf8filename);
1711 if (utf8filename != filename) {
1712 free (utf8filename);
1715 state.needoutline = 1;
1718 else if (!strncmp ("cs", p, 2)) {
1719 int i, colorspace;
1721 ret = sscanf (p + 2, " %d", &colorspace);
1722 if (ret != 1) {
1723 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1725 lock ("cs");
1726 set_tex_params (colorspace);
1727 for (i = 0; i < state.texcount; ++i) {
1728 state.texowners[i].w = -1;
1729 state.texowners[i].slice = NULL;
1731 unlock ("cs");
1733 else if (!strncmp ("freepage", p, 8)) {
1734 void *ptr;
1736 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1737 if (ret != 1) {
1738 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1740 freepage (ptr);
1742 else if (!strncmp ("freetile", p, 8)) {
1743 void *ptr;
1745 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1746 if (ret != 1) {
1747 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1749 freetile (ptr);
1751 else if (!strncmp ("search", p, 6)) {
1752 int icase, pageno, y, len2, forward;
1753 char *pattern;
1754 regex_t re;
1756 ret = sscanf (p + 6, " %d %d %d %d,%n",
1757 &icase, &pageno, &y, &forward, &len2);
1758 if (ret != 4) {
1759 errx (1, "malformed search `%s' ret=%d", p, ret);
1762 pattern = p + 6 + len2;
1763 ret = regcomp (&re, pattern,
1764 REG_EXTENDED | (icase ? REG_ICASE : 0));
1765 if (ret) {
1766 char errbuf[80];
1767 size_t size;
1769 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1770 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1772 else {
1773 search (&re, pageno, y, forward);
1774 regfree (&re);
1777 else if (!strncmp ("geometry", p, 8)) {
1778 int w, h, fitmodel;
1780 printd ("clear");
1781 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1782 if (ret != 3) {
1783 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1786 lock ("geometry");
1787 state.h = h;
1788 if (w != state.w) {
1789 state.w = w;
1790 for (int i = 0; i < state.texcount; ++i) {
1791 state.texowners[i].slice = NULL;
1794 state.fitmodel = fitmodel;
1795 layout ();
1796 process_outline ();
1798 state.gen++;
1799 unlock ("geometry");
1800 printd ("continue %d", state.pagecount);
1802 else if (!strncmp ("reqlayout", p, 9)) {
1803 char *nameddest;
1804 int rotate, off, h;
1805 unsigned int fitmodel;
1806 pdf_document *pdf;
1808 printd ("clear");
1809 ret = sscanf (p + 9, " %d %u %d %n",
1810 &rotate, &fitmodel, &h, &off);
1811 if (ret != 3) {
1812 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1814 lock ("reqlayout");
1815 pdf = pdf_specifics (state.ctx, state.doc);
1816 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1817 state.gen += 1;
1819 state.rotate = rotate;
1820 state.fitmodel = fitmodel;
1821 state.h = h;
1822 layout ();
1823 process_outline ();
1825 nameddest = p + 9 + off;
1826 if (pdf && nameddest && *nameddest) {
1827 fz_point xy;
1828 struct pagedim *pdim;
1829 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1830 &xy.x, &xy.y);
1831 pdim = pdimofpageno (pageno);
1832 fz_transform_point (&xy, &pdim->ctm);
1833 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1836 state.gen++;
1837 unlock ("reqlayout");
1838 printd ("continue %d", state.pagecount);
1840 else if (!strncmp ("page", p, 4)) {
1841 double a, b;
1842 struct page *page;
1843 int pageno, pindex;
1845 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1846 if (ret != 2) {
1847 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1850 lock ("page");
1851 a = now ();
1852 page = loadpage (pageno, pindex);
1853 b = now ();
1854 unlock ("page");
1856 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1858 else if (!strncmp ("tile", p, 4)) {
1859 int x, y, w, h;
1860 struct page *page;
1861 struct tile *tile;
1862 double a, b;
1863 void *data;
1865 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1866 SCN_ptr_cast (&page), &x, &y, &w, &h,
1867 SCN_ptr_cast (&data));
1868 if (ret != 6) {
1869 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1872 lock ("tile");
1873 a = now ();
1874 tile = rendertile (page, x, y, w, h, data);
1875 b = now ();
1876 unlock ("tile");
1878 printd ("tile %d %d %" FMT_ptr " %u %f",
1879 x, y,
1880 FMT_ptr_cast (tile),
1881 tile->w * tile->h * tile->pixmap->n,
1882 b - a);
1884 else if (!strncmp ("trimset", p, 7)) {
1885 fz_irect fuzz;
1886 int trimmargins;
1888 ret = sscanf (p + 7, " %d %d %d %d %d",
1889 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1890 if (ret != 5) {
1891 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1893 lock ("trimset");
1894 state.trimmargins = trimmargins;
1895 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1896 state.trimanew = 1;
1897 state.trimfuzz = fuzz;
1899 unlock ("trimset");
1901 else if (!strncmp ("settrim", p, 7)) {
1902 fz_irect fuzz;
1903 int trimmargins;
1905 ret = sscanf (p + 7, " %d %d %d %d %d",
1906 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1907 if (ret != 5) {
1908 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1910 printd ("clear");
1911 lock ("settrim");
1912 state.trimmargins = trimmargins;
1913 state.needoutline = 1;
1914 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1915 state.trimanew = 1;
1916 state.trimfuzz = fuzz;
1918 state.pagedimcount = 0;
1919 free (state.pagedims);
1920 state.pagedims = NULL;
1921 initpdims (0);
1922 layout ();
1923 process_outline ();
1924 unlock ("settrim");
1925 printd ("continue %d", state.pagecount);
1927 else if (!strncmp ("sliceh", p, 6)) {
1928 int h;
1930 ret = sscanf (p + 6, " %d", &h);
1931 if (ret != 1) {
1932 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1934 if (h != state.sliceheight) {
1935 state.sliceheight = h;
1936 for (int i = 0; i < state.texcount; ++i) {
1937 state.texowners[i].w = -1;
1938 state.texowners[i].h = -1;
1939 state.texowners[i].slice = NULL;
1943 else if (!strncmp ("interrupt", p, 9)) {
1944 printd ("vmsg interrupted");
1946 else {
1947 errx (1, "unknown command %.*s", len, p);
1950 return 0;
1953 CAMLprim value ml_isexternallink (value uri_v)
1955 CAMLparam1 (uri_v);
1956 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1957 CAMLreturn (Val_bool (ext));
1960 CAMLprim value ml_uritolocation (value uri_v)
1962 CAMLparam1 (uri_v);
1963 CAMLlocal1 (ret_v);
1964 int pageno;
1965 fz_point xy;
1966 struct pagedim *pdim;
1968 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1969 &xy.x, &xy.y);
1970 pdim = pdimofpageno (pageno);
1971 fz_transform_point (&xy, &pdim->ctm);
1972 ret_v = caml_alloc_tuple (3);
1973 Field (ret_v, 0) = Val_int (pageno);
1974 Field (ret_v, 1) = caml_copy_double (xy.x);
1975 Field (ret_v, 2) = caml_copy_double (xy.y);
1976 CAMLreturn (ret_v);
1979 CAMLprim value ml_realloctexts (value texcount_v)
1981 CAMLparam1 (texcount_v);
1982 int ok;
1984 if (trylock (__func__)) {
1985 ok = 0;
1986 goto done;
1988 realloctexts (Int_val (texcount_v));
1989 ok = 1;
1990 unlock (__func__);
1992 done:
1993 CAMLreturn (Val_bool (ok));
1996 static void recti (int x0, int y0, int x1, int y1)
1998 GLfloat *v = state.vertices;
2000 glVertexPointer (2, GL_FLOAT, 0, v);
2001 v[0] = x0; v[1] = y0;
2002 v[2] = x1; v[3] = y0;
2003 v[4] = x0; v[5] = y1;
2004 v[6] = x1; v[7] = y1;
2005 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2008 static void showsel (struct page *page, int ox, int oy)
2010 int seen = 0;
2011 fz_irect bbox;
2012 fz_rect rect;
2013 fz_stext_line *line;
2014 fz_page_block *pageb;
2015 fz_stext_block *block;
2016 struct mark first, last;
2017 unsigned char selcolor[] = {15,15,15,140};
2019 first = page->fmark;
2020 last = page->lmark;
2022 if (!first.span || !last.span) return;
2024 glEnable (GL_BLEND);
2025 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2026 glColor4ubv (selcolor);
2028 ox += state.pagedims[page->pdimno].bounds.x0;
2029 oy += state.pagedims[page->pdimno].bounds.y0;
2030 for (pageb = page->text->blocks;
2031 pageb < page->text->blocks + page->text->len;
2032 ++pageb) {
2033 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2034 block = pageb->u.text;
2036 for (line = block->lines;
2037 line < block->lines + block->len;
2038 ++line) {
2039 fz_stext_span *span;
2040 rect = fz_empty_rect;
2042 for (span = line->first_span; span; span = span->next) {
2043 int i, j, k;
2044 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2046 j = 0;
2047 k = span->len - 1;
2049 if (span == page->fmark.span && span == page->lmark.span) {
2050 seen = 1;
2051 j = fz_mini (first.i, last.i);
2052 k = fz_maxi (first.i, last.i);
2054 else {
2055 if (span == first.span) {
2056 seen = 1;
2057 j = first.i;
2059 else if (span == last.span) {
2060 seen = 1;
2061 k = last.i;
2065 if (seen) {
2066 for (i = j; i <= k; ++i) {
2067 fz_rect bbox1;
2068 fz_union_rect (&rect,
2069 fz_stext_char_bbox (state.ctx, &bbox1,
2070 span, i));
2072 fz_round_rect (&bbox, &rect);
2073 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2074 bbox.x0,
2075 bbox.y0,
2076 bbox.x1,
2077 bbox.y1,
2078 oy, ox);
2080 recti (bbox.x0 + ox, bbox.y0 + oy,
2081 bbox.x1 + ox, bbox.y1 + oy);
2082 if (span == last.span) {
2083 goto done;
2085 rect = fz_empty_rect;
2090 done:
2091 glDisable (GL_BLEND);
2094 #include "glfont.c"
2096 static void stipplerect (fz_matrix *m,
2097 fz_point *p1,
2098 fz_point *p2,
2099 fz_point *p3,
2100 fz_point *p4,
2101 GLfloat *texcoords,
2102 GLfloat *vertices)
2104 fz_transform_point (p1, m);
2105 fz_transform_point (p2, m);
2106 fz_transform_point (p3, m);
2107 fz_transform_point (p4, m);
2109 float w, h, s, t;
2111 w = p2->x - p1->x;
2112 h = p2->y - p1->y;
2113 t = hypotf (w, h) * .25f;
2115 w = p3->x - p2->x;
2116 h = p3->y - p2->y;
2117 s = hypotf (w, h) * .25f;
2119 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2120 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2122 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2123 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2125 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2126 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2128 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2129 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2131 glDrawArrays (GL_LINES, 0, 8);
2134 static void solidrect (fz_matrix *m,
2135 fz_point *p1,
2136 fz_point *p2,
2137 fz_point *p3,
2138 fz_point *p4,
2139 GLfloat *vertices)
2141 fz_transform_point (p1, m);
2142 fz_transform_point (p2, m);
2143 fz_transform_point (p3, m);
2144 fz_transform_point (p4, m);
2145 vertices[0] = p1->x; vertices[1] = p1->y;
2146 vertices[2] = p2->x; vertices[3] = p2->y;
2148 vertices[4] = p3->x; vertices[5] = p3->y;
2149 vertices[6] = p4->x; vertices[7] = p4->y;
2150 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2153 static void highlightlinks (struct page *page, int xoff, int yoff)
2155 fz_matrix ctm, tm, pm;
2156 fz_link *link, *links;
2157 GLfloat *texcoords = state.texcoords;
2158 GLfloat *vertices = state.vertices;
2160 links = fz_load_links (state.ctx, page->fzpage);
2162 glEnable (GL_TEXTURE_1D);
2163 glEnable (GL_BLEND);
2164 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2165 glBindTexture (GL_TEXTURE_1D, state.stid);
2167 xoff -= state.pagedims[page->pdimno].bounds.x0;
2168 yoff -= state.pagedims[page->pdimno].bounds.y0;
2169 fz_translate (&tm, xoff, yoff);
2170 pm = pagectm (page);
2171 fz_concat (&ctm, &pm, &tm);
2173 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2174 glVertexPointer (2, GL_FLOAT, 0, vertices);
2176 for (link = links; link; link = link->next) {
2177 fz_point p1, p2, p3, p4;
2179 p1.x = link->rect.x0;
2180 p1.y = link->rect.y0;
2182 p2.x = link->rect.x1;
2183 p2.y = link->rect.y0;
2185 p3.x = link->rect.x1;
2186 p3.y = link->rect.y1;
2188 p4.x = link->rect.x0;
2189 p4.y = link->rect.y1;
2191 /* TODO: different colours for different schemes */
2192 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2193 else glColor3ub (255, 0, 0);
2195 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2198 for (int i = 0; i < page->annotcount; ++i) {
2199 fz_point p1, p2, p3, p4;
2200 struct annot *annot = &page->annots[i];
2202 p1.x = annot->bbox.x0;
2203 p1.y = annot->bbox.y0;
2205 p2.x = annot->bbox.x1;
2206 p2.y = annot->bbox.y0;
2208 p3.x = annot->bbox.x1;
2209 p3.y = annot->bbox.y1;
2211 p4.x = annot->bbox.x0;
2212 p4.y = annot->bbox.y1;
2214 glColor3ub (0, 0, 128);
2215 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2218 glDisable (GL_BLEND);
2219 glDisable (GL_TEXTURE_1D);
2222 static int compareslinks (const void *l, const void *r)
2224 struct slink const *ls = l;
2225 struct slink const *rs = r;
2226 if (ls->bbox.y0 == rs->bbox.y0) {
2227 return rs->bbox.x0 - rs->bbox.x0;
2229 return ls->bbox.y0 - rs->bbox.y0;
2232 static void droptext (struct page *page)
2234 if (page->text) {
2235 fz_drop_stext_page (state.ctx, page->text);
2236 page->fmark.i = -1;
2237 page->lmark.i = -1;
2238 page->fmark.span = NULL;
2239 page->lmark.span = NULL;
2240 page->text = NULL;
2242 if (page->sheet) {
2243 fz_drop_stext_sheet (state.ctx, page->sheet);
2244 page->sheet = NULL;
2248 static void dropannots (struct page *page)
2250 if (page->annots) {
2251 free (page->annots);
2252 page->annots = NULL;
2253 page->annotcount = 0;
2257 static void ensureannots (struct page *page)
2259 int i, count = 0;
2260 size_t annotsize = sizeof (*page->annots);
2261 fz_annot *annot;
2263 if (state.gen != page->agen) {
2264 dropannots (page);
2265 page->agen = state.gen;
2267 if (page->annots) return;
2269 for (annot = fz_first_annot (state.ctx, page->fzpage);
2270 annot;
2271 annot = fz_next_annot (state.ctx, annot)) {
2272 count++;
2275 if (count > 0) {
2276 page->annotcount = count;
2277 page->annots = calloc (count, annotsize);
2278 if (!page->annots) {
2279 err (1, "calloc annots %d", count);
2282 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2283 annot;
2284 annot = fz_next_annot (state.ctx, annot), i++) {
2285 fz_rect rect;
2287 fz_bound_annot (state.ctx, annot, &rect);
2288 page->annots[i].annot = annot;
2289 fz_round_rect (&page->annots[i].bbox, &rect);
2294 static void dropslinks (struct page *page)
2296 if (page->slinks) {
2297 free (page->slinks);
2298 page->slinks = NULL;
2299 page->slinkcount = 0;
2303 static void ensureslinks (struct page *page)
2305 fz_matrix ctm;
2306 int i, count;
2307 size_t slinksize = sizeof (*page->slinks);
2308 fz_link *link, *links;
2310 ensureannots (page);
2311 if (state.gen != page->sgen) {
2312 dropslinks (page);
2313 page->sgen = state.gen;
2315 if (page->slinks) return;
2317 links = fz_load_links (state.ctx, page->fzpage);
2318 ctm = pagectm (page);
2320 count = page->annotcount;
2321 for (link = links; link; link = link->next) {
2322 count++;
2324 if (count > 0) {
2325 int j;
2327 page->slinkcount = count;
2328 page->slinks = calloc (count, slinksize);
2329 if (!page->slinks) {
2330 err (1, "calloc slinks %d", count);
2333 for (i = 0, link = links; link; ++i, link = link->next) {
2334 fz_rect rect;
2336 rect = link->rect;
2337 fz_transform_rect (&rect, &ctm);
2338 page->slinks[i].tag = SLINK;
2339 page->slinks[i].u.link = link;
2340 fz_round_rect (&page->slinks[i].bbox, &rect);
2342 for (j = 0; j < page->annotcount; ++j, ++i) {
2343 fz_rect rect;
2344 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2345 fz_transform_rect (&rect, &ctm);
2346 fz_round_rect (&page->slinks[i].bbox, &rect);
2348 page->slinks[i].tag = SANNOT;
2349 page->slinks[i].u.annot = page->annots[j].annot;
2351 qsort (page->slinks, count, slinksize, compareslinks);
2355 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2356 static void fmt_linkn (char *s, unsigned int u)
2358 unsigned int len; unsigned int q;
2359 unsigned int zma = 'z' - 'a' + 1;
2360 len = 1; q = u;
2361 while (q > zma - 1) { ++len; q /= zma; }
2362 if (s) {
2363 s += len;
2364 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2365 /* handles u == 0 */
2367 s[len] = 0;
2370 static void highlightslinks (struct page *page, int xoff, int yoff,
2371 int noff, char *targ, int tlen, int hfsize)
2373 char buf[40];
2374 struct slink *slink;
2375 double x0, y0, x1, y1, w;
2377 ensureslinks (page);
2378 glColor3ub (0xc3, 0xb0, 0x91);
2379 for (int i = 0; i < page->slinkcount; ++i) {
2380 fmt_linkn (buf, i + noff);
2381 if (!tlen || !strncmp (targ, buf, tlen)) {
2382 slink = &page->slinks[i];
2384 x0 = slink->bbox.x0 + xoff - 5;
2385 y1 = slink->bbox.y0 + yoff - 5;
2386 y0 = y1 + 10 + hfsize;
2387 w = measure_string (state.face, hfsize, buf);
2388 x1 = x0 + w + 10;
2389 recti (x0, y0, x1, y1);
2393 glEnable (GL_BLEND);
2394 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2395 glEnable (GL_TEXTURE_2D);
2396 glColor3ub (0, 0, 0);
2397 for (int i = 0; i < page->slinkcount; ++i) {
2398 fmt_linkn (buf, i + noff);
2399 if (!tlen || !strncmp (targ, buf, tlen)) {
2400 slink = &page->slinks[i];
2402 x0 = slink->bbox.x0 + xoff;
2403 y0 = slink->bbox.y0 + yoff + hfsize;
2404 draw_string (state.face, hfsize, x0, y0, buf);
2407 glDisable (GL_TEXTURE_2D);
2408 glDisable (GL_BLEND);
2411 static void uploadslice (struct tile *tile, struct slice *slice)
2413 int offset;
2414 struct slice *slice1;
2415 unsigned char *texdata;
2417 offset = 0;
2418 for (slice1 = tile->slices; slice != slice1; slice1++) {
2419 offset += slice1->h * tile->w * tile->pixmap->n;
2421 if (slice->texindex != -1 && slice->texindex < state.texcount
2422 && state.texowners[slice->texindex].slice == slice) {
2423 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2425 else {
2426 int subimage = 0;
2427 int texindex = state.texindex++ % state.texcount;
2429 if (state.texowners[texindex].w == tile->w) {
2430 if (state.texowners[texindex].h >= slice->h) {
2431 subimage = 1;
2433 else {
2434 state.texowners[texindex].h = slice->h;
2437 else {
2438 state.texowners[texindex].h = slice->h;
2441 state.texowners[texindex].w = tile->w;
2442 state.texowners[texindex].slice = slice;
2443 slice->texindex = texindex;
2445 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2446 #if TEXT_TYPE == GL_TEXTURE_2D
2447 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2448 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2449 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2450 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2451 #endif
2452 if (tile->pbo) {
2453 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2454 texdata = 0;
2456 else {
2457 texdata = tile->pixmap->samples;
2459 if (subimage) {
2460 glTexSubImage2D (TEXT_TYPE,
2464 tile->w,
2465 slice->h,
2466 state.texform,
2467 state.texty,
2468 texdata+offset
2471 else {
2472 glTexImage2D (TEXT_TYPE,
2474 state.texiform,
2475 tile->w,
2476 slice->h,
2478 state.texform,
2479 state.texty,
2480 texdata+offset
2483 if (tile->pbo) {
2484 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2489 CAMLprim void ml_begintiles (value unit_v)
2491 CAMLparam1 (unit_v);
2492 glEnable (TEXT_TYPE);
2493 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2494 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2495 CAMLreturn0;
2498 CAMLprim void ml_endtiles (value unit_v)
2500 CAMLparam1 (unit_v);
2501 glDisable (TEXT_TYPE);
2502 CAMLreturn0;
2505 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2507 CAMLparam2 (args_v, ptr_v);
2508 int dispx = Int_val (Field (args_v, 0));
2509 int dispy = Int_val (Field (args_v, 1));
2510 int dispw = Int_val (Field (args_v, 2));
2511 int disph = Int_val (Field (args_v, 3));
2512 int tilex = Int_val (Field (args_v, 4));
2513 int tiley = Int_val (Field (args_v, 5));
2514 char *s = String_val (ptr_v);
2515 struct tile *tile = parse_pointer (__func__, s);
2516 int slicey, firstslice;
2517 struct slice *slice;
2518 GLfloat *texcoords = state.texcoords;
2519 GLfloat *vertices = state.vertices;
2521 firstslice = tiley / tile->sliceheight;
2522 slice = &tile->slices[firstslice];
2523 slicey = tiley % tile->sliceheight;
2525 while (disph > 0) {
2526 int dh;
2528 dh = slice->h - slicey;
2529 dh = fz_mini (disph, dh);
2530 uploadslice (tile, slice);
2532 texcoords[0] = tilex; texcoords[1] = slicey;
2533 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2534 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2535 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2537 vertices[0] = dispx; vertices[1] = dispy;
2538 vertices[2] = dispx+dispw; vertices[3] = dispy;
2539 vertices[4] = dispx; vertices[5] = dispy+dh;
2540 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2542 #if TEXT_TYPE == GL_TEXTURE_2D
2543 for (int i = 0; i < 8; ++i) {
2544 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2546 #endif
2548 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2549 dispy += dh;
2550 disph -= dh;
2551 slice++;
2552 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2553 slicey = 0;
2555 CAMLreturn0;
2558 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2560 fz_matrix ctm, tm, pm;
2561 fz_point p1, p2, p3, p4;
2562 GLfloat *vertices = state.vertices;
2563 double *v = (double *) rects_v;
2565 xoff -= state.pagedims[page->pdimno].bounds.x0;
2566 yoff -= state.pagedims[page->pdimno].bounds.y0;
2567 fz_translate (&tm, xoff, yoff);
2568 pm = pagectm (page);
2569 fz_concat (&ctm, &pm, &tm);
2571 glEnable (GL_BLEND);
2572 glVertexPointer (2, GL_FLOAT, 0, vertices);
2574 glColor4dv (v);
2575 p1.x = v[4];
2576 p1.y = v[5];
2578 p2.x = v[6];
2579 p2.y = v[5];
2581 p3.x = v[6];
2582 p3.y = v[7];
2584 p4.x = v[4];
2585 p4.y = v[7];
2586 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2587 glDisable (GL_BLEND);
2590 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2591 value xoff_v, value yoff_v,
2592 value li_v)
2594 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2595 int xoff = Int_val (xoff_v);
2596 int yoff = Int_val (yoff_v);
2597 int noff = Int_val (Field (li_v, 0));
2598 char *targ = String_val (Field (li_v, 1));
2599 int tlen = caml_string_length (Field (li_v, 1));
2600 int hfsize = Int_val (Field (li_v, 2));
2601 char *s = String_val (ptr_v);
2602 int hlmask = Int_val (hlinks_v);
2603 struct page *page = parse_pointer (__func__, s);
2605 if (!page->fzpage) {
2606 /* deal with loadpage failed pages */
2607 goto done;
2610 if (trylock (__func__)) {
2611 noff = -1;
2612 goto done;
2615 ensureannots (page);
2616 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2617 if (hlmask & 2) {
2618 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2619 noff = page->slinkcount;
2621 if (page->tgen == state.gen) {
2622 showsel (page, xoff, yoff);
2624 unlock (__func__);
2626 done:
2627 CAMLreturn (Val_int (noff));
2630 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2631 value rects_v)
2633 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2634 int xoff = Int_val (xoff_v);
2635 int yoff = Int_val (yoff_v);
2636 char *s = String_val (ptr_v);
2637 struct page *page = parse_pointer (__func__, s);
2639 drawprect (page, xoff, yoff, rects_v);
2640 CAMLreturn0;
2643 static struct annot *getannot (struct page *page, int x, int y)
2645 fz_point p;
2646 fz_matrix ctm;
2647 const fz_matrix *tctm;
2648 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2650 if (!page->annots) return NULL;
2652 if (pdf) {
2653 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2654 tctm = &state.pagedims[page->pdimno].tctm;
2656 else {
2657 tctm = &fz_identity;
2660 p.x = x;
2661 p.y = y;
2663 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2664 fz_invert_matrix (&ctm, &ctm);
2665 fz_transform_point (&p, &ctm);
2667 if (pdf) {
2668 for (int i = 0; i < page->annotcount; ++i) {
2669 struct annot *a = &page->annots[i];
2670 fz_rect rect;
2672 fz_bound_annot (state.ctx, a->annot, &rect);
2673 if (p.x >= rect.x0 && p.x <= rect.x1) {
2674 if (p.y >= rect.y0 && p.y <= rect.y1)
2675 return a;
2679 return NULL;
2682 static fz_link *getlink (struct page *page, int x, int y)
2684 fz_point p;
2685 fz_matrix ctm;
2686 fz_link *link, *links;
2688 links = fz_load_links (state.ctx, page->fzpage);
2690 p.x = x;
2691 p.y = y;
2693 ctm = pagectm (page);
2694 fz_invert_matrix (&ctm, &ctm);
2695 fz_transform_point (&p, &ctm);
2697 for (link = links; link; link = link->next) {
2698 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2699 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2700 return link;
2704 return NULL;
2707 static void ensuretext (struct page *page)
2709 if (state.gen != page->tgen) {
2710 droptext (page);
2711 page->tgen = state.gen;
2713 if (!page->text) {
2714 fz_matrix ctm;
2715 fz_device *tdev;
2717 page->text = fz_new_stext_page (state.ctx,
2718 &state.pagedims[page->pdimno].mediabox);
2719 page->sheet = fz_new_stext_sheet (state.ctx);
2720 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2721 ctm = pagectm (page);
2722 fz_run_display_list (state.ctx, page->dlist,
2723 tdev, &ctm, &fz_infinite_rect, NULL);
2724 qsort (page->text->blocks, page->text->len,
2725 sizeof (*page->text->blocks), compareblocks);
2726 fz_close_device (state.ctx, tdev);
2727 fz_drop_device (state.ctx, tdev);
2731 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2733 CAMLparam2 (start_page_v, dir_v);
2734 CAMLlocal1 (ret_v);
2735 int i, dir = Int_val (dir_v);
2736 int start_page = Int_val (start_page_v);
2737 int end_page = dir > 0 ? state.pagecount : -1;
2738 pdf_document *pdf;
2740 fz_var (end_page);
2741 ret_v = Val_int (0);
2742 lock (__func__);
2743 pdf = pdf_specifics (state.ctx, state.doc);
2744 for (i = start_page + dir; i != end_page; i += dir) {
2745 int found;
2747 fz_var (found);
2748 if (pdf) {
2749 pdf_page *page = NULL;
2751 fz_var (page);
2752 fz_try (state.ctx) {
2753 page = pdf_load_page (state.ctx, pdf, i);
2754 found = !!page->links || !!page->annots;
2756 fz_catch (state.ctx) {
2757 found = 0;
2759 if (page) {
2760 fz_drop_page (state.ctx, &page->super);
2763 else {
2764 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2765 found = !!fz_load_links (state.ctx, page);
2766 fz_drop_page (state.ctx, page);
2769 if (found) {
2770 ret_v = caml_alloc_small (1, 1);
2771 Field (ret_v, 0) = Val_int (i);
2772 goto unlock;
2775 unlock:
2776 unlock (__func__);
2777 CAMLreturn (ret_v);
2780 enum { dir_first, dir_last };
2781 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2783 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2785 CAMLparam2 (ptr_v, dir_v);
2786 CAMLlocal2 (ret_v, pos_v);
2787 struct page *page;
2788 int dirtag, i, slinkindex;
2789 struct slink *found = NULL ,*slink;
2790 char *s = String_val (ptr_v);
2792 page = parse_pointer (__func__, s);
2793 ret_v = Val_int (0);
2794 lock (__func__);
2795 ensureslinks (page);
2797 if (Is_block (dir_v)) {
2798 dirtag = Tag_val (dir_v);
2799 switch (dirtag) {
2800 case dir_first_visible:
2802 int x0, y0, dir, first_index, last_index;
2804 pos_v = Field (dir_v, 0);
2805 x0 = Int_val (Field (pos_v, 0));
2806 y0 = Int_val (Field (pos_v, 1));
2807 dir = Int_val (Field (pos_v, 2));
2809 if (dir >= 0) {
2810 dir = 1;
2811 first_index = 0;
2812 last_index = page->slinkcount;
2814 else {
2815 first_index = page->slinkcount - 1;
2816 last_index = -1;
2819 for (i = first_index; i != last_index; i += dir) {
2820 slink = &page->slinks[i];
2821 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2822 found = slink;
2823 break;
2827 break;
2829 case dir_left:
2830 slinkindex = Int_val (Field (dir_v, 0));
2831 found = &page->slinks[slinkindex];
2832 for (i = slinkindex - 1; i >= 0; --i) {
2833 slink = &page->slinks[i];
2834 if (slink->bbox.x0 < found->bbox.x0) {
2835 found = slink;
2836 break;
2839 break;
2841 case dir_right:
2842 slinkindex = Int_val (Field (dir_v, 0));
2843 found = &page->slinks[slinkindex];
2844 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2845 slink = &page->slinks[i];
2846 if (slink->bbox.x0 > found->bbox.x0) {
2847 found = slink;
2848 break;
2851 break;
2853 case dir_down:
2854 slinkindex = Int_val (Field (dir_v, 0));
2855 found = &page->slinks[slinkindex];
2856 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2857 slink = &page->slinks[i];
2858 if (slink->bbox.y0 >= found->bbox.y0) {
2859 found = slink;
2860 break;
2863 break;
2865 case dir_up:
2866 slinkindex = Int_val (Field (dir_v, 0));
2867 found = &page->slinks[slinkindex];
2868 for (i = slinkindex - 1; i >= 0; --i) {
2869 slink = &page->slinks[i];
2870 if (slink->bbox.y0 <= found->bbox.y0) {
2871 found = slink;
2872 break;
2875 break;
2878 else {
2879 dirtag = Int_val (dir_v);
2880 switch (dirtag) {
2881 case dir_first:
2882 found = page->slinks;
2883 break;
2885 case dir_last:
2886 if (page->slinks) {
2887 found = page->slinks + (page->slinkcount - 1);
2889 break;
2892 if (found) {
2893 ret_v = caml_alloc_small (2, 1);
2894 Field (ret_v, 0) = Val_int (found - page->slinks);
2897 unlock (__func__);
2898 CAMLreturn (ret_v);
2901 enum { uuri, utext, uannot };
2903 CAMLprim value ml_getlink (value ptr_v, value n_v)
2905 CAMLparam2 (ptr_v, n_v);
2906 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2907 fz_link *link;
2908 struct page *page;
2909 char *s = String_val (ptr_v);
2910 struct slink *slink;
2912 ret_v = Val_int (0);
2913 page = parse_pointer (__func__, s);
2915 lock (__func__);
2916 ensureslinks (page);
2917 slink = &page->slinks[Int_val (n_v)];
2918 if (slink->tag == SLINK) {
2919 link = slink->u.link;
2920 str_v = caml_copy_string (link->uri);
2921 ret_v = caml_alloc_small (1, uuri);
2922 Field (ret_v, 0) = str_v;
2924 else {
2925 ret_v = caml_alloc_small (1, uannot);
2926 tup_v = caml_alloc_tuple (2);
2927 Field (ret_v, 0) = tup_v;
2928 Field (tup_v, 0) = ptr_v;
2929 Field (tup_v, 1) = n_v;
2931 unlock (__func__);
2933 CAMLreturn (ret_v);
2936 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2938 CAMLparam2 (ptr_v, n_v);
2939 pdf_document *pdf;
2940 const char *contents = "";
2942 lock (__func__);
2943 pdf = pdf_specifics (state.ctx, state.doc);
2944 if (pdf) {
2945 char *s = String_val (ptr_v);
2946 struct page *page;
2947 struct slink *slink;
2949 page = parse_pointer (__func__, s);
2950 slink = &page->slinks[Int_val (n_v)];
2951 contents = pdf_annot_contents (state.ctx,
2952 (pdf_annot *) slink->u.annot);
2954 unlock (__func__);
2955 CAMLreturn (caml_copy_string (contents));
2958 CAMLprim value ml_getlinkcount (value ptr_v)
2960 CAMLparam1 (ptr_v);
2961 struct page *page;
2962 char *s = String_val (ptr_v);
2964 page = parse_pointer (__func__, s);
2965 CAMLreturn (Val_int (page->slinkcount));
2968 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2970 CAMLparam2 (ptr_v, n_v);
2971 CAMLlocal1 (ret_v);
2972 struct page *page;
2973 struct slink *slink;
2974 char *s = String_val (ptr_v);
2976 page = parse_pointer (__func__, s);
2977 ret_v = caml_alloc_tuple (4);
2978 lock (__func__);
2979 ensureslinks (page);
2981 slink = &page->slinks[Int_val (n_v)];
2982 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2983 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2984 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2985 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2986 unlock (__func__);
2987 CAMLreturn (ret_v);
2990 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2992 CAMLparam3 (ptr_v, x_v, y_v);
2993 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2994 fz_link *link;
2995 struct annot *annot;
2996 struct page *page;
2997 char *ptr = String_val (ptr_v);
2998 int x = Int_val (x_v), y = Int_val (y_v);
2999 struct pagedim *pdim;
3001 ret_v = Val_int (0);
3002 if (trylock (__func__)) {
3003 goto done;
3006 page = parse_pointer (__func__, ptr);
3007 pdim = &state.pagedims[page->pdimno];
3008 x += pdim->bounds.x0;
3009 y += pdim->bounds.y0;
3012 annot = getannot (page, x, y);
3013 if (annot) {
3014 int i, n = -1;
3016 ensureslinks (page);
3017 for (i = 0; i < page->slinkcount; ++i) {
3018 if (page->slinks[i].tag == SANNOT
3019 && page->slinks[i].u.annot == annot->annot) {
3020 n = i;
3021 break;
3024 ret_v = caml_alloc_small (1, uannot);
3025 tup_v = caml_alloc_tuple (2);
3026 Field (ret_v, 0) = tup_v;
3027 Field (tup_v, 0) = ptr_v;
3028 Field (tup_v, 1) = Val_int (n);
3029 goto unlock;
3033 link = getlink (page, x, y);
3034 if (link) {
3035 str_v = caml_copy_string (link->uri);
3036 ret_v = caml_alloc_small (1, uuri);
3037 Field (ret_v, 0) = str_v;
3039 else {
3040 fz_rect *b;
3041 fz_page_block *pageb;
3042 fz_stext_block *block;
3044 ensuretext (page);
3045 for (pageb = page->text->blocks;
3046 pageb < page->text->blocks + page->text->len;
3047 ++pageb) {
3048 fz_stext_line *line;
3049 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3050 block = pageb->u.text;
3052 b = &block->bbox;
3053 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3054 continue;
3056 for (line = block->lines;
3057 line < block->lines + block->len;
3058 ++line) {
3059 fz_stext_span *span;
3061 b = &line->bbox;
3062 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3063 continue;
3065 for (span = line->first_span; span; span = span->next) {
3066 int charnum;
3068 b = &span->bbox;
3069 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3070 continue;
3072 for (charnum = 0; charnum < span->len; ++charnum) {
3073 fz_rect bbox;
3074 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3075 b = &bbox;
3077 if (x >= b->x0 && x <= b->x1
3078 && y >= b->y0 && y <= b->y1) {
3079 fz_stext_style *style = span->text->style;
3080 const char *n2 =
3081 style->font
3082 ? fz_font_name (state.ctx, style->font)
3083 : "Span has no font name"
3085 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3086 style->font);
3087 if (face && face->family_name) {
3088 char *s;
3089 char *n1 = face->family_name;
3090 size_t l1 = strlen (n1);
3091 size_t l2 = strlen (n2);
3093 if (l1 != l2 || memcmp (n1, n2, l1)) {
3094 s = malloc (l1 + l2 + 2);
3095 if (s) {
3096 memcpy (s, n2, l2);
3097 s[l2] = '=';
3098 memcpy (s + l2 + 1, n1, l1 + 1);
3099 str_v = caml_copy_string (s);
3100 free (s);
3104 if (str_v == Val_unit) {
3105 str_v = caml_copy_string (n2);
3107 ret_v = caml_alloc_small (1, utext);
3108 Field (ret_v, 0) = str_v;
3109 goto unlock;
3116 unlock:
3117 unlock (__func__);
3119 done:
3120 CAMLreturn (ret_v);
3123 enum { mark_page, mark_block, mark_line, mark_word };
3125 static int uninteresting (int c)
3127 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3128 || ispunct (c);
3131 CAMLprim void ml_clearmark (value ptr_v)
3133 CAMLparam1 (ptr_v);
3134 char *s = String_val (ptr_v);
3135 struct page *page;
3137 if (trylock (__func__)) {
3138 goto done;
3141 page = parse_pointer (__func__, s);
3142 page->fmark.span = NULL;
3143 page->lmark.span = NULL;
3144 page->fmark.i = 0;
3145 page->lmark.i = 0;
3147 unlock (__func__);
3148 done:
3149 CAMLreturn0;
3152 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3154 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3155 CAMLlocal1 (ret_v);
3156 fz_rect *b;
3157 struct page *page;
3158 fz_stext_line *line;
3159 fz_page_block *pageb;
3160 fz_stext_block *block;
3161 struct pagedim *pdim;
3162 int mark = Int_val (mark_v);
3163 char *s = String_val (ptr_v);
3164 int x = Int_val (x_v), y = Int_val (y_v);
3166 ret_v = Val_bool (0);
3167 if (trylock (__func__)) {
3168 goto done;
3171 page = parse_pointer (__func__, s);
3172 pdim = &state.pagedims[page->pdimno];
3174 ensuretext (page);
3176 if (mark == mark_page) {
3177 int i;
3178 fz_page_block *pb1 = NULL, *pb2 = NULL;
3180 for (i = 0; i < page->text->len; ++i) {
3181 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3182 pb1 = &page->text->blocks[i];
3183 break;
3186 if (!pb1) goto unlock;
3188 for (i = page->text->len - 1; i >= 0; --i) {
3189 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3190 pb2 = &page->text->blocks[i];
3191 break;
3194 if (!pb2) goto unlock;
3196 block = pb1->u.text;
3198 page->fmark.i = 0;
3199 page->fmark.span = block->lines->first_span;
3201 block = pb2->u.text;
3202 line = &block->lines[block->len - 1];
3203 page->lmark.i = line->last_span->len - 1;
3204 page->lmark.span = line->last_span;
3205 ret_v = Val_bool (1);
3206 goto unlock;
3209 x += pdim->bounds.x0;
3210 y += pdim->bounds.y0;
3212 for (pageb = page->text->blocks;
3213 pageb < page->text->blocks + page->text->len;
3214 ++pageb) {
3215 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3216 block = pageb->u.text;
3218 b = &block->bbox;
3219 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3220 continue;
3222 if (mark == mark_block) {
3223 page->fmark.i = 0;
3224 page->fmark.span = block->lines->first_span;
3226 line = &block->lines[block->len - 1];
3227 page->lmark.i = line->last_span->len - 1;
3228 page->lmark.span = line->last_span;
3229 ret_v = Val_bool (1);
3230 goto unlock;
3233 for (line = block->lines;
3234 line < block->lines + block->len;
3235 ++line) {
3236 fz_stext_span *span;
3238 b = &line->bbox;
3239 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3240 continue;
3242 if (mark == mark_line) {
3243 page->fmark.i = 0;
3244 page->fmark.span = line->first_span;
3246 page->lmark.i = line->last_span->len - 1;
3247 page->lmark.span = line->last_span;
3248 ret_v = Val_bool (1);
3249 goto unlock;
3252 for (span = line->first_span; span; span = span->next) {
3253 int charnum;
3255 b = &span->bbox;
3256 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3257 continue;
3259 for (charnum = 0; charnum < span->len; ++charnum) {
3260 fz_rect bbox;
3261 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3262 b = &bbox;
3264 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3265 /* unicode ftw */
3266 int charnum2, charnum3 = -1, charnum4 = -1;
3268 if (uninteresting (span->text[charnum].c)) goto unlock;
3270 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3271 if (uninteresting (span->text[charnum2].c)) {
3272 charnum3 = charnum2 + 1;
3273 break;
3276 if (charnum3 == -1) charnum3 = 0;
3278 charnum4 = charnum;
3279 for (charnum2 = charnum + 1;
3280 charnum2 < span->len;
3281 ++charnum2) {
3282 if (uninteresting (span->text[charnum2].c)) break;
3283 charnum4 = charnum2;
3286 page->fmark.i = charnum3;
3287 page->fmark.span = span;
3289 page->lmark.i = charnum4;
3290 page->lmark.span = span;
3291 ret_v = Val_bool (1);
3292 goto unlock;
3298 unlock:
3299 if (!Bool_val (ret_v)) {
3300 page->fmark.span = NULL;
3301 page->lmark.span = NULL;
3302 page->fmark.i = 0;
3303 page->lmark.i = 0;
3305 unlock (__func__);
3307 done:
3308 CAMLreturn (ret_v);
3311 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3313 CAMLparam3 (ptr_v, x_v, y_v);
3314 CAMLlocal2 (ret_v, res_v);
3315 fz_rect *b = NULL;
3316 struct page *page;
3317 fz_page_block *pageb;
3318 struct pagedim *pdim;
3319 char *s = String_val (ptr_v);
3320 int x = Int_val (x_v), y = Int_val (y_v);
3322 ret_v = Val_int (0);
3323 if (trylock (__func__)) {
3324 goto done;
3327 page = parse_pointer (__func__, s);
3328 pdim = &state.pagedims[page->pdimno];
3329 x += pdim->bounds.x0;
3330 y += pdim->bounds.y0;
3332 ensuretext (page);
3334 for (pageb = page->text->blocks;
3335 pageb < page->text->blocks + page->text->len;
3336 ++pageb) {
3337 switch (pageb->type) {
3338 case FZ_PAGE_BLOCK_TEXT:
3339 b = &pageb->u.text->bbox;
3340 break;
3342 case FZ_PAGE_BLOCK_IMAGE:
3343 b = &pageb->u.image->bbox;
3344 break;
3346 default:
3347 continue;
3350 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3351 break;
3352 b = NULL;
3354 if (b) {
3355 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3356 ret_v = caml_alloc_small (1, 1);
3357 Store_double_field (res_v, 0, b->x0);
3358 Store_double_field (res_v, 1, b->x1);
3359 Store_double_field (res_v, 2, b->y0);
3360 Store_double_field (res_v, 3, b->y1);
3361 Field (ret_v, 0) = res_v;
3363 unlock (__func__);
3365 done:
3366 CAMLreturn (ret_v);
3369 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3371 CAMLparam2 (ptr_v, rect_v);
3372 fz_rect b;
3373 struct page *page;
3374 struct pagedim *pdim;
3375 char *s = String_val (ptr_v);
3376 int i, x0, x1, y0, y1, fi, li;
3377 fz_stext_line *line;
3378 fz_page_block *pageb;
3379 fz_stext_block *block;
3380 fz_stext_span *span, *fspan, *lspan;
3382 if (trylock (__func__)) {
3383 goto done;
3386 page = parse_pointer (__func__, s);
3387 ensuretext (page);
3389 pdim = &state.pagedims[page->pdimno];
3390 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3391 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3392 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3393 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3395 if (y0 > y1) {
3396 int t = y0;
3397 y0 = y1;
3398 y1 = t;
3399 x0 = x1;
3400 x1 = t;
3403 fi = page->fmark.i;
3404 fspan = page->fmark.span;
3406 li = page->lmark.i;
3407 lspan = page->lmark.span;
3409 for (pageb = page->text->blocks;
3410 pageb < page->text->blocks + page->text->len;
3411 ++pageb) {
3412 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3413 block = pageb->u.text;
3414 for (line = block->lines;
3415 line < block->lines + block->len;
3416 ++line) {
3418 for (span = line->first_span; span; span = span->next) {
3419 for (i = 0; i < span->len; ++i) {
3420 fz_stext_char_bbox (state.ctx, &b, span, i);
3422 if (x0 >= b.x0 && x0 <= b.x1
3423 && y0 >= b.y0 && y0 <= b.y1) {
3424 fspan = span;
3425 fi = i;
3427 if (x1 >= b.x0 && x1 <= b.x1
3428 && y1 >= b.y0 && y1 <= b.y1) {
3429 lspan = span;
3430 li = i;
3436 if (x1 < x0 && fspan == lspan) {
3437 i = fi;
3438 span = fspan;
3440 fi = li;
3441 fspan = lspan;
3443 li = i;
3444 lspan = span;
3447 page->fmark.i = fi;
3448 page->fmark.span = fspan;
3450 page->lmark.i = li;
3451 page->lmark.span = lspan;
3453 unlock (__func__);
3455 done:
3456 CAMLreturn0;
3459 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3461 char buf[4];
3462 int i, len, ret;
3464 for (i = a; i <= b; ++i) {
3465 len = fz_runetochar (buf, span->text[i].c);
3466 ret = fwrite (buf, len, 1, f);
3468 if (ret != 1) {
3469 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3470 len, ret, strerror (errno));
3471 return -1;
3474 return 0;
3477 #ifdef __CYGWIN__
3478 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3480 caml_failwith ("ml_popen not implemented under Cygwin");
3482 #else
3483 CAMLprim value ml_spawn (value command_v, value fds_v)
3485 CAMLparam2 (command_v, fds_v);
3486 CAMLlocal2 (l_v, tup_v);
3487 int ret, ret1;
3488 pid_t pid;
3489 char *msg = NULL;
3490 value earg_v = Nothing;
3491 posix_spawnattr_t attr;
3492 posix_spawn_file_actions_t fa;
3493 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3495 argv[2] = String_val (command_v);
3497 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3498 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3501 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3502 msg = "posix_spawnattr_init";
3503 goto fail1;
3506 #ifdef POSIX_SPAWN_USEVFORK
3507 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3508 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3509 goto fail;
3511 #endif
3513 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3514 int fd1, fd2;
3516 tup_v = Field (l_v, 0);
3517 fd1 = Int_val (Field (tup_v, 0));
3518 fd2 = Int_val (Field (tup_v, 1));
3519 if (fd2 < 0) {
3520 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3521 msg = "posix_spawn_file_actions_addclose";
3522 earg_v = tup_v;
3523 goto fail;
3526 else {
3527 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3528 msg = "posix_spawn_file_actions_adddup2";
3529 earg_v = tup_v;
3530 goto fail;
3535 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3536 msg = "posix_spawn";
3537 goto fail;
3540 fail:
3541 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3542 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3545 fail1:
3546 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3547 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3548 strerror (ret1));
3551 if (msg)
3552 unix_error (ret, msg, earg_v);
3554 CAMLreturn (Val_int (pid));
3556 #endif
3558 CAMLprim value ml_hassel (value ptr_v)
3560 CAMLparam1 (ptr_v);
3561 CAMLlocal1 (ret_v);
3562 struct page *page;
3563 char *s = String_val (ptr_v);
3565 ret_v = Val_bool (0);
3566 if (trylock (__func__)) {
3567 goto done;
3570 page = parse_pointer (__func__, s);
3571 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3572 unlock (__func__);
3573 done:
3574 CAMLreturn (ret_v);
3577 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3579 CAMLparam2 (fd_v, ptr_v);
3580 FILE *f;
3581 int seen = 0;
3582 struct page *page;
3583 fz_stext_line *line;
3584 fz_page_block *pageb;
3585 fz_stext_block *block;
3586 int fd = Int_val (fd_v);
3587 char *s = String_val (ptr_v);
3589 if (trylock (__func__)) {
3590 goto done;
3593 page = parse_pointer (__func__, s);
3595 if (!page->fmark.span || !page->lmark.span) {
3596 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3597 goto unlock;
3600 f = fdopen (fd, "w");
3601 if (!f) {
3602 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3603 fd, strerror (errno));
3604 f = stdout;
3607 for (pageb = page->text->blocks;
3608 pageb < page->text->blocks + page->text->len;
3609 ++pageb) {
3610 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3611 block = pageb->u.text;
3612 for (line = block->lines;
3613 line < block->lines + block->len;
3614 ++line) {
3615 fz_stext_span *span;
3617 for (span = line->first_span; span; span = span->next) {
3618 int a, b;
3620 seen |= span == page->fmark.span || span == page->lmark.span;
3621 a = span == page->fmark.span ? page->fmark.i : 0;
3622 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3624 if (seen) {
3625 if (pipespan (f, span, a, b)) {
3626 goto close;
3628 if (span == page->lmark.span) {
3629 goto close;
3631 if (span == line->last_span) {
3632 if (putc ('\n', f) == EOF) {
3633 fprintf (stderr,
3634 "failed break line on sel pipe: %s\n",
3635 strerror (errno));
3636 goto close;
3643 close:
3644 if (f != stdout) {
3645 int ret = fclose (f);
3646 fd = -1;
3647 if (ret == -1) {
3648 if (errno != ECHILD) {
3649 fprintf (stderr, "failed to close sel pipe: %s\n",
3650 strerror (errno));
3654 unlock:
3655 unlock (__func__);
3657 done:
3658 if (fd >= 0) {
3659 if (close (fd)) {
3660 fprintf (stderr, "failed to close sel pipe: %s\n",
3661 strerror (errno));
3664 CAMLreturn0;
3667 CAMLprim value ml_getpdimrect (value pagedimno_v)
3669 CAMLparam1 (pagedimno_v);
3670 CAMLlocal1 (ret_v);
3671 int pagedimno = Int_val (pagedimno_v);
3672 fz_rect box;
3674 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3675 if (trylock (__func__)) {
3676 box = fz_empty_rect;
3678 else {
3679 box = state.pagedims[pagedimno].mediabox;
3680 unlock (__func__);
3683 Store_double_field (ret_v, 0, box.x0);
3684 Store_double_field (ret_v, 1, box.x1);
3685 Store_double_field (ret_v, 2, box.y0);
3686 Store_double_field (ret_v, 3, box.y1);
3688 CAMLreturn (ret_v);
3691 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3692 value dw_v, value cols_v)
3694 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3695 CAMLlocal1 (ret_v);
3696 int i;
3697 double zoom = -1.;
3698 double maxh = 0.0;
3699 struct pagedim *p;
3700 double winw = Int_val (winw_v);
3701 double winh = Int_val (winh_v);
3702 double dw = Int_val (dw_v);
3703 double cols = Int_val (cols_v);
3704 double pw = 1.0, ph = 1.0;
3706 if (trylock (__func__)) {
3707 goto done;
3710 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3711 double w = p->pagebox.x1 / cols;
3712 double h = p->pagebox.y1;
3713 if (h > maxh) {
3714 maxh = h;
3715 ph = h;
3716 if (state.fitmodel != FitProportional) pw = w;
3718 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3721 zoom = (((winh / ph) * pw) + dw) / winw;
3722 unlock (__func__);
3723 done:
3724 ret_v = caml_copy_double (zoom);
3725 CAMLreturn (ret_v);
3728 CAMLprim value ml_getmaxw (value unit_v)
3730 CAMLparam1 (unit_v);
3731 CAMLlocal1 (ret_v);
3732 int i;
3733 double maxw = -1.;
3734 struct pagedim *p;
3736 if (trylock (__func__)) {
3737 goto done;
3740 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3741 double w = p->pagebox.x1;
3742 maxw = fz_max (maxw, w);
3745 unlock (__func__);
3746 done:
3747 ret_v = caml_copy_double (maxw);
3748 CAMLreturn (ret_v);
3751 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3753 CAMLparam4 (pt_v, x_v, y_v, string_v);
3754 CAMLlocal1 (ret_v);
3755 int pt = Int_val(pt_v);
3756 int x = Int_val (x_v);
3757 int y = Int_val (y_v);
3758 double w;
3760 w = draw_string (state.face, pt, x, y, String_val (string_v));
3761 ret_v = caml_copy_double (w);
3762 CAMLreturn (ret_v);
3765 CAMLprim value ml_measure_string (value pt_v, value string_v)
3767 CAMLparam2 (pt_v, string_v);
3768 CAMLlocal1 (ret_v);
3769 int pt = Int_val (pt_v);
3770 double w;
3772 w = measure_string (state.face, pt, String_val (string_v));
3773 ret_v = caml_copy_double (w);
3774 CAMLreturn (ret_v);
3777 CAMLprim value ml_getpagebox (value opaque_v)
3779 CAMLparam1 (opaque_v);
3780 CAMLlocal1 (ret_v);
3781 fz_rect rect;
3782 fz_irect bbox;
3783 fz_matrix ctm;
3784 fz_device *dev;
3785 char *s = String_val (opaque_v);
3786 struct page *page = parse_pointer (__func__, s);
3788 ret_v = caml_alloc_tuple (4);
3789 dev = fz_new_bbox_device (state.ctx, &rect);
3791 ctm = pagectm (page);
3792 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3794 fz_close_device (state.ctx, dev);
3795 fz_drop_device (state.ctx, dev);
3796 fz_round_rect (&bbox, &rect);
3797 Field (ret_v, 0) = Val_int (bbox.x0);
3798 Field (ret_v, 1) = Val_int (bbox.y0);
3799 Field (ret_v, 2) = Val_int (bbox.x1);
3800 Field (ret_v, 3) = Val_int (bbox.y1);
3802 CAMLreturn (ret_v);
3805 CAMLprim void ml_setaalevel (value level_v)
3807 CAMLparam1 (level_v);
3809 state.aalevel = Int_val (level_v);
3810 CAMLreturn0;
3813 #ifndef __COCOA__
3814 #pragma GCC diagnostic push
3815 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3816 #include <X11/Xlib.h>
3817 #include <X11/cursorfont.h>
3818 #pragma GCC diagnostic pop
3820 #ifdef USE_EGL
3821 #include <EGL/egl.h>
3822 #else
3823 #include <GL/glx.h>
3824 #endif
3826 static const int shapes[] = {
3827 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3830 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3832 static struct {
3833 Window wid;
3834 Display *dpy;
3835 #ifdef USE_EGL
3836 EGLContext ctx;
3837 EGLConfig conf;
3838 EGLSurface win;
3839 EGLDisplay *edpy;
3840 #else
3841 GLXContext ctx;
3842 #endif
3843 XVisualInfo *visual;
3844 Cursor curs[CURS_COUNT];
3845 } glx;
3848 static void initcurs (void)
3850 for (size_t n = 0; n < CURS_COUNT; ++n) {
3851 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3855 CAMLprim void ml_setbgcol (value color_v)
3857 CAMLparam1 (color_v);
3858 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3859 CAMLreturn0;
3862 #ifdef USE_EGL
3863 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3865 CAMLparam3 (display_v, wid_v, screen_v);
3866 int major, minor;
3867 int num_conf;
3868 EGLint visid;
3869 EGLint attribs[] = {
3870 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3871 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3872 EGL_NONE
3874 EGLConfig conf;
3876 glx.dpy = XOpenDisplay (String_val (display_v));
3877 if (!glx.dpy) {
3878 caml_failwith ("XOpenDisplay");
3881 eglBindAPI (EGL_OPENGL_API);
3883 glx.edpy = eglGetDisplay (glx.dpy);
3884 if (glx.edpy == EGL_NO_DISPLAY) {
3885 caml_failwith ("eglGetDisplay");
3888 if (!eglInitialize (glx.edpy, &major, &minor)) {
3889 caml_failwith ("eglInitialize");
3892 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3893 !num_conf) {
3894 caml_failwith ("eglChooseConfig");
3897 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3898 caml_failwith ("eglGetConfigAttrib");
3901 glx.conf = conf;
3902 initcurs ();
3904 glx.wid = Int_val (wid_v);
3905 CAMLreturn (Val_int (visid));
3908 CAMLprim void ml_glxcompleteinit (value unit_v)
3910 CAMLparam1 (unit_v);
3912 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3913 if (!glx.ctx) {
3914 caml_failwith ("eglCreateContext");
3917 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3918 glx.wid, NULL);
3919 if (glx.win == EGL_NO_SURFACE) {
3920 caml_failwith ("eglCreateWindowSurface");
3923 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3924 glx.ctx = NULL;
3925 caml_failwith ("eglMakeCurrent");
3927 CAMLreturn0;
3929 #else
3930 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3932 CAMLparam3 (display_v, wid_v, screen_v);
3934 glx.dpy = XOpenDisplay (String_val (display_v));
3935 if (!glx.dpy) {
3936 caml_failwith ("XOpenDisplay");
3939 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3940 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3941 if (!glx.visual) {
3942 XCloseDisplay (glx.dpy);
3943 caml_failwith ("glXChooseVisual");
3946 initcurs ();
3948 glx.wid = Int_val (wid_v);
3949 CAMLreturn (Val_int (glx.visual->visualid));
3952 CAMLprim void ml_glxcompleteinit (value unit_v)
3954 CAMLparam1 (unit_v);
3956 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3957 if (!glx.ctx) {
3958 caml_failwith ("glXCreateContext");
3961 XFree (glx.visual);
3962 glx.visual = NULL;
3964 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3965 glXDestroyContext (glx.dpy, glx.ctx);
3966 glx.ctx = NULL;
3967 caml_failwith ("glXMakeCurrent");
3969 CAMLreturn0;
3971 #endif
3973 CAMLprim void ml_setcursor (value cursor_v)
3975 CAMLparam1 (cursor_v);
3976 size_t cursn = Int_val (cursor_v);
3978 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3979 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3980 XFlush (glx.dpy);
3981 CAMLreturn0;
3984 CAMLprim void ml_swapb (value unit_v)
3986 CAMLparam1 (unit_v);
3987 #ifdef USE_EGL
3988 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3989 caml_failwith ("eglSwapBuffers");
3991 #else
3992 glXSwapBuffers (glx.dpy, glx.wid);
3993 #endif
3994 CAMLreturn0;
3997 #include "keysym2ucs.c"
3999 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4001 CAMLparam1 (keysym_v);
4002 CAMLlocal1 (str_v);
4003 KeySym keysym = Int_val (keysym_v);
4004 Rune rune;
4005 int len;
4006 char buf[5];
4008 rune = keysym2ucs (keysym);
4009 len = fz_runetochar (buf, rune);
4010 buf[len] = 0;
4011 str_v = caml_copy_string (buf);
4012 CAMLreturn (str_v);
4014 #else
4015 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4017 CAMLparam1 (keysym_v);
4018 CAMLlocal1 (str_v);
4019 long ucs_v = Long_val (keysym_v);
4020 int len;
4021 char buf[5];
4023 len = fz_runetochar (buf, ucs_v);
4024 buf[len] = 0;
4025 str_v = caml_copy_string (buf);
4026 CAMLreturn (str_v);
4028 #endif
4030 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4032 CAMLprim value ml_platform (value unit_v)
4034 CAMLparam1 (unit_v);
4035 CAMLlocal2 (tup_v, arr_v);
4036 int platid = piunknown;
4037 struct utsname buf;
4039 #if defined __linux__
4040 platid = pilinux;
4041 #elif defined __CYGWIN__
4042 platid = picygwin;
4043 #elif defined __DragonFly__ || defined __FreeBSD__
4044 || defined __OpenBSD__ || defined __NetBSD__
4045 platid = pibsd;
4046 #elif defined __sun__
4047 platid = pisun;
4048 #elif defined __APPLE__
4049 platid = piosx;
4050 #endif
4051 if (uname (&buf)) err (1, "uname");
4053 tup_v = caml_alloc_tuple (2);
4055 char const *sar[] = {
4056 buf.sysname,
4057 buf.release,
4058 buf.version,
4059 buf.machine,
4060 NULL
4062 arr_v = caml_copy_string_array (sar);
4064 Field (tup_v, 0) = Val_int (platid);
4065 Field (tup_v, 1) = arr_v;
4066 CAMLreturn (tup_v);
4069 CAMLprim void ml_cloexec (value fd_v)
4071 CAMLparam1 (fd_v);
4072 int fd = Int_val (fd_v);
4074 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4075 uerror ("fcntl", Nothing);
4077 CAMLreturn0;
4080 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4082 CAMLparam2 (w_v, h_v);
4083 CAMLlocal1 (ret_v);
4084 struct bo *pbo;
4085 int w = Int_val (w_v);
4086 int h = Int_val (h_v);
4087 int cs = Int_val (cs_v);
4089 if (state.bo_usable) {
4090 pbo = calloc (sizeof (*pbo), 1);
4091 if (!pbo) {
4092 err (1, "calloc pbo");
4095 switch (cs) {
4096 case 0:
4097 case 1:
4098 pbo->size = w*h*4;
4099 break;
4100 case 2:
4101 pbo->size = w*h*2;
4102 break;
4103 default:
4104 errx (1, "%s: invalid colorspace %d", __func__, cs);
4107 state.glGenBuffersARB (1, &pbo->id);
4108 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4109 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4110 NULL, GL_STREAM_DRAW);
4111 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4112 GL_READ_WRITE);
4113 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4114 if (!pbo->ptr) {
4115 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4116 state.glDeleteBuffersARB (1, &pbo->id);
4117 free (pbo);
4118 ret_v = caml_copy_string ("0");
4120 else {
4121 int res;
4122 char *s;
4124 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4125 if (res < 0) {
4126 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4128 s = malloc (res+1);
4129 if (!s) {
4130 err (1, "malloc %d bytes failed", res+1);
4132 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4133 if (res < 0) {
4134 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4136 ret_v = caml_copy_string (s);
4137 free (s);
4140 else {
4141 ret_v = caml_copy_string ("0");
4143 CAMLreturn (ret_v);
4146 CAMLprim void ml_freepbo (value s_v)
4148 CAMLparam1 (s_v);
4149 char *s = String_val (s_v);
4150 struct tile *tile = parse_pointer (__func__, s);
4152 if (tile->pbo) {
4153 state.glDeleteBuffersARB (1, &tile->pbo->id);
4154 tile->pbo->id = -1;
4155 tile->pbo->ptr = NULL;
4156 tile->pbo->size = -1;
4158 CAMLreturn0;
4161 CAMLprim void ml_unmappbo (value s_v)
4163 CAMLparam1 (s_v);
4164 char *s = String_val (s_v);
4165 struct tile *tile = parse_pointer (__func__, s);
4167 if (tile->pbo) {
4168 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4169 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4170 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4172 tile->pbo->ptr = NULL;
4173 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4175 CAMLreturn0;
4178 static void setuppbo (void)
4180 #ifdef __COCOA__
4181 static CFBundleRef framework = NULL;
4182 if (framework == NULL)
4183 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
4184 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
4185 #else
4186 #ifdef USE_EGL
4187 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4188 #else
4189 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4190 #endif
4191 state.bo_usable = GGPA (glBindBufferARB)
4192 && GGPA (glUnmapBufferARB)
4193 && GGPA (glMapBufferARB)
4194 && GGPA (glBufferDataARB)
4195 && GGPA (glGenBuffersARB)
4196 && GGPA (glDeleteBuffersARB);
4197 #endif
4198 #undef GGPA
4201 CAMLprim value ml_bo_usable (value unit_v)
4203 CAMLparam1 (unit_v);
4204 CAMLreturn (Val_bool (state.bo_usable));
4207 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4209 CAMLparam3 (ptr_v, x_v, y_v);
4210 CAMLlocal2 (ret_v, tup_v);
4211 struct page *page;
4212 char *s = String_val (ptr_v);
4213 int x = Int_val (x_v), y = Int_val (y_v);
4214 struct pagedim *pdim;
4215 fz_point p;
4216 fz_matrix ctm;
4218 page = parse_pointer (__func__, s);
4219 pdim = &state.pagedims[page->pdimno];
4221 ret_v = Val_int (0);
4222 if (trylock (__func__)) {
4223 goto done;
4226 if (pdf_specifics (state.ctx, state.doc)) {
4227 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4228 ctm = state.pagedims[page->pdimno].tctm;
4230 else {
4231 ctm = fz_identity;
4233 p.x = x + pdim->bounds.x0;
4234 p.y = y + pdim->bounds.y0;
4236 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4237 fz_invert_matrix (&ctm, &ctm);
4238 fz_transform_point (&p, &ctm);
4240 tup_v = caml_alloc_tuple (2);
4241 ret_v = caml_alloc_small (1, 1);
4242 Field (tup_v, 0) = Val_int (p.x);
4243 Field (tup_v, 1) = Val_int (p.y);
4244 Field (ret_v, 0) = tup_v;
4246 unlock (__func__);
4247 done:
4248 CAMLreturn (ret_v);
4251 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4252 value x_v, value y_v)
4254 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4255 CAMLlocal1 (ret_v);
4256 struct page *page;
4257 char *s = String_val (ptr_v);
4258 int pageno = Int_val (pageno_v);
4259 int pdimno = Int_val (pdimno_v);
4260 double x = Double_val (x_v), y = Double_val (y_v);
4261 struct pagedim *pdim;
4262 fz_point p;
4263 fz_matrix ctm;
4265 ret_v = Val_int (0);
4266 lock (__func__);
4268 if (!*s) {
4269 page = loadpage (pageno, pdimno);
4271 else {
4272 page = parse_pointer (__func__, s);
4274 pdim = &state.pagedims[pdimno];
4276 if (pdf_specifics (state.ctx, state.doc)) {
4277 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4278 ctm = state.pagedims[page->pdimno].tctm;
4280 else {
4281 ctm = fz_identity;
4283 p.x = x + pdim->bounds.x0;
4284 p.y = y + pdim->bounds.y0;
4286 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4287 fz_transform_point (&p, &ctm);
4289 ret_v = caml_alloc_tuple (2);
4290 Field (ret_v, 0) = caml_copy_double (p.x);
4291 Field (ret_v, 1) = caml_copy_double (p.y);
4293 if (!*s) {
4294 freepage (page);
4296 unlock (__func__);
4297 CAMLreturn (ret_v);
4300 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4301 value contents_v)
4303 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4304 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4306 if (pdf) {
4307 pdf_annot *annot;
4308 struct page *page;
4309 fz_point p;
4310 char *s = String_val (ptr_v);
4312 page = parse_pointer (__func__, s);
4313 annot = pdf_create_annot (state.ctx,
4314 pdf_page_from_fz_page (state.ctx,
4315 page->fzpage),
4316 PDF_ANNOT_TEXT);
4317 p.x = Int_val (x_v);
4318 p.y = Int_val (y_v);
4319 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4320 pdf_set_text_annot_position (state.ctx, annot, p);
4321 state.dirty = 1;
4323 CAMLreturn0;
4326 CAMLprim void ml_delannot (value ptr_v, value n_v)
4328 CAMLparam2 (ptr_v, n_v);
4329 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4331 if (pdf) {
4332 struct page *page;
4333 char *s = String_val (ptr_v);
4334 struct slink *slink;
4336 page = parse_pointer (__func__, s);
4337 slink = &page->slinks[Int_val (n_v)];
4338 pdf_delete_annot (state.ctx,
4339 pdf_page_from_fz_page (state.ctx, page->fzpage),
4340 (pdf_annot *) slink->u.annot);
4341 state.dirty = 1;
4343 CAMLreturn0;
4346 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4348 CAMLparam3 (ptr_v, n_v, str_v);
4349 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4351 if (pdf) {
4352 struct page *page;
4353 char *s = String_val (ptr_v);
4354 struct slink *slink;
4356 page = parse_pointer (__func__, s);
4357 slink = &page->slinks[Int_val (n_v)];
4358 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4359 String_val (str_v));
4360 state.dirty = 1;
4362 CAMLreturn0;
4365 CAMLprim value ml_hasunsavedchanges (value unit_v)
4367 CAMLparam1 (unit_v);
4368 CAMLreturn (Val_bool (state.dirty));
4371 CAMLprim void ml_savedoc (value path_v)
4373 CAMLparam1 (path_v);
4374 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4376 if (pdf) {
4377 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4379 CAMLreturn0;
4382 static void makestippletex (void)
4384 const char pixels[] = "\xff\xff\0\0";
4385 glGenTextures (1, &state.stid);
4386 glBindTexture (GL_TEXTURE_1D, state.stid);
4387 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4388 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4389 glTexImage1D (
4390 GL_TEXTURE_1D,
4392 GL_ALPHA,
4395 GL_ALPHA,
4396 GL_UNSIGNED_BYTE,
4397 pixels
4401 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4403 return caml_copy_string (FZ_VERSION);
4406 CAMLprim void ml_init (value csock_v, value params_v)
4408 CAMLparam2 (csock_v, params_v);
4409 CAMLlocal2 (trim_v, fuzz_v);
4410 int ret;
4411 int texcount;
4412 char *fontpath;
4413 int colorspace;
4414 int mustoresize;
4415 int haspboext;
4417 /* Without following call to setlocale mbstowcs fails for, at
4418 least, strings containing chinese symbols (δΈ­ for instance)
4419 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4420 wide character" as the reason of failure and with macOS
4421 producing bogus output) */
4422 if (setlocale (LC_CTYPE, "")) {
4423 /* Following two lines were taken from dvtm/vt.c */
4424 const char *cset = nl_langinfo (CODESET);
4425 state.utf8cs = !strcmp (cset, "UTF-8");
4427 else {
4428 fprintf (stderr, "setlocale failed\n");
4431 state.csock = Int_val (csock_v);
4432 state.rotate = Int_val (Field (params_v, 0));
4433 state.fitmodel = Int_val (Field (params_v, 1));
4434 trim_v = Field (params_v, 2);
4435 texcount = Int_val (Field (params_v, 3));
4436 state.sliceheight = Int_val (Field (params_v, 4));
4437 mustoresize = Int_val (Field (params_v, 5));
4438 colorspace = Int_val (Field (params_v, 6));
4439 fontpath = String_val (Field (params_v, 7));
4441 if (caml_string_length (Field (params_v, 8)) > 0) {
4442 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4444 if (!state.trimcachepath) {
4445 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4446 strerror (errno));
4450 haspboext = Bool_val (Field (params_v, 9));
4452 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4453 fz_register_document_handlers (state.ctx);
4455 state.trimmargins = Bool_val (Field (trim_v, 0));
4456 fuzz_v = Field (trim_v, 1);
4457 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4458 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4459 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4460 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4462 set_tex_params (colorspace);
4464 if (*fontpath) {
4465 state.face = load_font (fontpath);
4467 else {
4468 int len;
4469 const unsigned char *data;
4471 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4472 state.face = load_builtin_font (data, len);
4474 if (!state.face) _exit (1);
4476 realloctexts (texcount);
4478 if (haspboext) {
4479 setuppbo ();
4482 makestippletex ();
4484 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4485 if (ret) {
4486 errx (1, "pthread_create: %s", strerror (ret));
4489 CAMLreturn0;