Make things buildable with gcc/build.sh
[llpp.git] / link.c
blob852ded424ed5ce170b46b7359e7dc53dea3d5b70
1 #if defined __clang__ && !defined __APPLE__
2 #pragma GCC diagnostic error "-Weverything"
3 #pragma GCC diagnostic ignored "-Wfloat-equal"
4 #pragma GCC diagnostic ignored "-Wpadded"
5 #pragma GCC diagnostic ignored "-Wsign-conversion"
6 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
7 #pragma GCC diagnostic ignored "-Wdocumentation"
8 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
9 #endif
11 /* lots of code c&p-ed directly from mupdf */
12 #define CAML_NAME_SPACE
13 #define FIXME 0
15 #include <errno.h>
16 #include <stdio.h>
17 #include <ctype.h>
18 #include <string.h>
19 #include <stdlib.h>
20 #include <signal.h>
22 #include <math.h>
23 #include <wchar.h>
24 #include <locale.h>
25 #include <langinfo.h>
27 #include <unistd.h>
28 #include <pthread.h>
29 #include <sys/uio.h>
30 #include <sys/time.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/utsname.h>
37 #ifdef __CYGWIN__
38 #include <cygwin/socket.h> /* FIONREAD */
39 #else
40 #include <spawn.h>
41 #endif
43 #include <regex.h>
44 #include <stdarg.h>
45 #include <limits.h>
46 #include <inttypes.h>
48 #ifdef __COCOA__
49 #include <CoreFoundation/CoreFoundation.h>
50 #endif
52 #ifdef __APPLE__
53 #include <OpenGL/gl.h>
54 #else
55 #include <GL/gl.h>
56 #endif
58 #pragma GCC diagnostic push
59 #ifdef __clang__
60 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
61 #endif
62 #pragma GCC diagnostic ignored "-Wpedantic"
63 #include <caml/fail.h>
64 #include <caml/alloc.h>
65 #include <caml/memory.h>
66 #include <caml/unixsupport.h>
68 #if __GNUC__ < 5 && !defined __clang__
69 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
70 clobbered diagnostics */
71 #pragma GCC diagnostic ignored "-Wclobbered"
72 #endif
74 #include <mupdf/fitz.h>
75 #include <mupdf/pdf.h>
77 #include <ft2build.h>
78 #include FT_FREETYPE_H
79 #pragma GCC diagnostic pop
81 #define PIGGYBACK
82 #define CACHE_PAGEREFS
84 #ifndef __USE_GNU
85 extern char **environ;
86 #endif
88 #if defined __GNUC__
89 #define NORETURN_ATTR __attribute__ ((noreturn))
90 #define UNUSED_ATTR __attribute__ ((unused))
91 #if !defined __clang__
92 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
93 #else
94 #define OPTIMIZE_ATTR(n)
95 #endif
96 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
97 #else
98 #define NORETURN_ATTR
99 #define UNUSED_ATTR
100 #define OPTIMIZE_ATTR(n)
101 #define GCC_FMT_ATTR(a, b)
102 #endif
104 #define FMT_s "zu"
106 #define FMT_ptr PRIxPTR
107 #define SCN_ptr SCNxPTR
108 #define FMT_ptr_cast(p) ((uintptr_t) (p))
109 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
111 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
112 err (int exitcode, const char *fmt, ...)
114 va_list ap;
115 int savederrno;
117 savederrno = errno;
118 va_start (ap, fmt);
119 vfprintf (stderr, fmt, ap);
120 va_end (ap);
121 fprintf (stderr, ": %s\n", strerror (savederrno));
122 fflush (stderr);
123 _exit (exitcode);
126 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
127 errx (int exitcode, const char *fmt, ...)
129 va_list ap;
131 va_start (ap, fmt);
132 vfprintf (stderr, fmt, ap);
133 va_end (ap);
134 fputc ('\n', stderr);
135 fflush (stderr);
136 _exit (exitcode);
139 #ifndef GL_TEXTURE_RECTANGLE_ARB
140 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
141 #endif
143 #ifdef USE_NPOT
144 #define TEXT_TYPE GL_TEXTURE_2D
145 #else
146 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
147 #endif
149 #ifndef GL_BGRA
150 #define GL_BGRA 0x80E1
151 #endif
153 #ifndef GL_UNSIGNED_INT_8_8_8_8
154 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
155 #endif
157 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
158 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
159 #endif
161 #if 0
162 #define lprintf printf
163 #else
164 #define lprintf(...)
165 #endif
167 #define ARSERT(cond) for (;;) { \
168 if (!(cond)) { \
169 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
171 break; \
174 struct slice {
175 int h;
176 int texindex;
179 struct tile {
180 int w, h;
181 int slicecount;
182 int sliceheight;
183 struct bo *pbo;
184 fz_pixmap *pixmap;
185 struct slice slices[1];
188 struct pagedim {
189 int pageno;
190 int rotate;
191 int left;
192 int tctmready;
193 fz_irect bounds;
194 fz_rect pagebox;
195 fz_rect mediabox;
196 fz_matrix ctm, zoomctm, tctm;
199 struct slink {
200 enum { SLINK, SANNOT } tag;
201 fz_irect bbox;
202 union {
203 fz_link *link;
204 fz_annot *annot;
205 } u;
208 struct annot {
209 fz_irect bbox;
210 fz_annot *annot;
213 struct page {
214 int tgen;
215 int sgen;
216 int agen;
217 int pageno;
218 int pdimno;
219 fz_stext_page *text;
220 fz_page *fzpage;
221 fz_display_list *dlist;
222 fz_link *links;
223 int slinkcount;
224 struct slink *slinks;
225 int annotcount;
226 struct annot *annots;
227 struct mark {
228 fz_stext_char *ch;
229 } fmark, lmark;
232 enum { FitWidth, FitProportional, FitPage };
234 static struct {
235 int sliceheight;
236 struct pagedim *pagedims;
237 int pagecount;
238 int pagedimcount;
239 fz_document *doc;
240 fz_context *ctx;
241 int w, h;
243 int texindex;
244 int texcount;
245 GLuint *texids;
247 GLenum texiform;
248 GLenum texform;
249 GLenum texty;
251 fz_colorspace *colorspace;
253 struct {
254 int w, h;
255 struct slice *slice;
256 } *texowners;
258 int rotate;
259 int fitmodel;
260 int trimmargins;
261 int needoutline;
262 int gen;
263 int aalevel;
265 int trimanew;
266 fz_irect trimfuzz;
267 fz_pixmap *pig;
269 pthread_t thread;
270 int csock;
271 FT_Face face;
273 char *trimcachepath;
274 int cxack;
275 int dirty;
277 GLuint stid;
279 int bo_usable;
280 GLuint boid;
282 void (*glBindBufferARB) (GLenum, GLuint);
283 GLboolean (*glUnmapBufferARB) (GLenum);
284 void *(*glMapBufferARB) (GLenum, GLenum);
285 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
286 void (*glGenBuffersARB) (GLsizei, GLuint *);
287 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
289 GLfloat texcoords[8];
290 GLfloat vertices[16];
292 #ifdef CACHE_PAGEREFS
293 struct {
294 int idx;
295 int count;
296 pdf_obj **objs;
297 pdf_document *pdf;
298 } pdflut;
299 #endif
300 int utf8cs;
301 } state;
303 struct bo {
304 GLuint id;
305 void *ptr;
306 size_t size;
309 #pragma GCC diagnostic ignored "-Wdouble-promotion"
310 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
312 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
315 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
317 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
320 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
322 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
323 m.a, m.b, m.c, m.d, m.e, m.f);
325 #pragma GCC diagnostic error "-Wdouble-promotion"
327 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
329 static void lock (const char *cap)
331 int ret = pthread_mutex_lock (&mutex);
332 if (ret) {
333 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
337 static void unlock (const char *cap)
339 int ret = pthread_mutex_unlock (&mutex);
340 if (ret) {
341 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
345 static int trylock (const char *cap)
347 int ret = pthread_mutex_trylock (&mutex);
348 if (ret && ret != EBUSY) {
349 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
351 return ret == EBUSY;
354 static void *parse_pointer (const char *cap, const char *s)
356 int ret;
357 void *ptr;
359 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
360 if (ret != 1) {
361 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
363 return ptr;
366 static double now (void)
368 struct timeval tv;
370 if (gettimeofday (&tv, NULL)) {
371 err (1, "gettimeofday");
373 return tv.tv_sec + tv.tv_usec*1e-6;
376 static int hasdata (void)
378 int ret, avail;
379 ret = ioctl (state.csock, FIONREAD, &avail);
380 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
381 return avail > 0;
384 CAMLprim value ml_hasdata (value fd_v)
386 CAMLparam1 (fd_v);
387 int ret, avail;
389 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
390 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
391 CAMLreturn (Val_bool (avail > 0));
394 static void readdata (int fd, void *p, int size)
396 ssize_t n;
398 again:
399 n = read (fd, p, size);
400 if (n - size) {
401 if (n < 0 && errno == EINTR) goto again;
402 if (!n) errx (1, "EOF while reading");
403 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
407 static void writedata (int fd, char *p, int size)
409 ssize_t n;
410 uint32_t size4 = size;
411 struct iovec iov[2] = {
412 { .iov_base = &size4, .iov_len = 4 },
413 { .iov_base = p, .iov_len = size }
416 again:
417 n = writev (fd, iov, 2);
418 if (n < 0 && errno == EINTR) goto again;
419 if (n - size - 4) {
420 if (!n) errx (1, "EOF while writing data");
421 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
425 static int readlen (int fd)
427 uint32_t u;
428 readdata (fd, &u, 4);
429 return u;
432 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
434 CAMLparam3 (fd_v, bytes_v, len_v);
435 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
436 CAMLreturn0;
439 CAMLprim value ml_rcmd (value fd_v)
441 CAMLparam1 (fd_v);
442 CAMLlocal1 (strdata_v);
443 int fd = Int_val (fd_v);
444 int len = readlen (fd);
445 strdata_v = caml_alloc_string (len);
446 readdata (fd, String_val (strdata_v), len);
447 CAMLreturn (strdata_v);
450 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
452 char fbuf[64];
453 int size = sizeof (fbuf), len;
454 va_list ap;
455 char *buf = fbuf;
457 for (;;) {
458 va_start (ap, fmt);
459 len = vsnprintf (buf, size, fmt, ap);
460 va_end (ap);
462 if (len > -1) {
463 if (len < size - 4) {
464 writedata (state.csock, buf, len);
465 break;
467 else size = len + 5;
469 else {
470 err (1, "vsnprintf for `%s' failed", fmt);
472 buf = realloc (buf == fbuf ? NULL : buf, size);
473 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
475 if (buf != fbuf) free (buf);
478 static void closedoc (void)
480 #ifdef CACHE_PAGEREFS
481 if (state.pdflut.objs) {
482 for (int i = 0; i < state.pdflut.count; ++i) {
483 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
485 free (state.pdflut.objs);
486 state.pdflut.objs = NULL;
487 state.pdflut.idx = 0;
489 #endif
490 if (state.doc) {
491 fz_drop_document (state.ctx, state.doc);
492 state.doc = NULL;
496 static int openxref (char *filename, char *password)
498 for (int i = 0; i < state.texcount; ++i) {
499 state.texowners[i].w = -1;
500 state.texowners[i].slice = NULL;
503 closedoc ();
505 state.dirty = 0;
506 if (state.pagedims) {
507 free (state.pagedims);
508 state.pagedims = NULL;
510 state.pagedimcount = 0;
512 fz_set_aa_level (state.ctx, state.aalevel);
513 state.doc = fz_open_document (state.ctx, filename);
514 if (fz_needs_password (state.ctx, state.doc)) {
515 if (password && !*password) {
516 printd ("pass");
517 return 0;
519 else {
520 int ok = fz_authenticate_password (state.ctx, state.doc, password);
521 if (!ok) {
522 printd ("pass fail");
523 return 0;
527 state.pagecount = fz_count_pages (state.ctx, state.doc);
528 return 1;
531 static void pdfinfo (void)
533 struct { char *tag; char *name; } metatbl[] = {
534 { FZ_META_INFO_TITLE, "Title" },
535 { FZ_META_INFO_AUTHOR, "Author" },
536 { FZ_META_FORMAT, "Format" },
537 { FZ_META_ENCRYPTION, "Encryption" },
538 { "info:Creator", "Creator" },
539 { "info:Producer", "Producer" },
540 { "info:CreationDate", "Creation date" },
542 int len = 0;
543 char *buf = NULL;
545 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
546 int need;
547 again:
548 need = fz_lookup_metadata (state.ctx, state.doc,
549 metatbl[i].tag, buf, len);
550 if (need > 0) {
551 if (need <= len) {
552 printd ("info %s\t%s", metatbl[i].name, buf);
554 else {
555 buf = realloc (buf, need + 1);
556 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
557 len = need + 1;
558 goto again;
562 free (buf);
564 printd ("infoend");
567 static void unlinktile (struct tile *tile)
569 for (int i = 0; i < tile->slicecount; ++i) {
570 struct slice *s = &tile->slices[i];
572 if (s->texindex != -1) {
573 if (state.texowners[s->texindex].slice == s) {
574 state.texowners[s->texindex].slice = NULL;
580 static void freepage (struct page *page)
582 if (!page) return;
583 if (page->text) {
584 fz_drop_stext_page (state.ctx, page->text);
586 if (page->slinks) {
587 free (page->slinks);
589 fz_drop_display_list (state.ctx, page->dlist);
590 fz_drop_page (state.ctx, page->fzpage);
591 free (page);
594 static void freetile (struct tile *tile)
596 unlinktile (tile);
597 if (!tile->pbo) {
598 #ifndef PIGGYBACK
599 fz_drop_pixmap (state.ctx, tile->pixmap);
600 #else
601 if (state.pig) {
602 fz_drop_pixmap (state.ctx, state.pig);
604 state.pig = tile->pixmap;
605 #endif
607 else {
608 free (tile->pbo);
609 fz_drop_pixmap (state.ctx, tile->pixmap);
611 free (tile);
614 #ifdef __ALTIVEC__
615 #include <stdint.h>
616 #include <altivec.h>
618 static int cacheline32bytes;
620 static void __attribute__ ((constructor)) clcheck (void)
622 char **envp = environ;
623 unsigned long *auxv;
625 while (*envp++);
627 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
628 if (*auxv == 19) {
629 cacheline32bytes = auxv[1] == 32;
630 return;
635 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
637 size_t size = pixmap->w * pixmap->h * pixmap->n;
638 if (cacheline32bytes && size > 32) {
639 intptr_t a1, a2, diff;
640 size_t sizea, i;
641 vector unsigned char v = vec_splat_u8 (-1);
642 vector unsigned char *p;
644 a1 = a2 = (intptr_t) pixmap->samples;
645 a2 = (a1 + 31) & ~31;
646 diff = a2 - a1;
647 sizea = size - diff;
648 p = (void *) a2;
650 while (a1 != a2) *(char *) a1++ = 0xff;
651 for (i = 0; i < (sizea & ~31); i += 32) {
652 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
653 vec_st (v, i, p);
654 vec_st (v, i + 16, p);
656 while (i < sizea) *((char *) a1 + i++) = 0xff;
658 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
660 #else
661 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
662 #endif
664 static void trimctm (pdf_page *page, int pindex)
666 fz_matrix ctm;
667 struct pagedim *pdim = &state.pagedims[pindex];
669 if (!page) return;
670 if (!pdim->tctmready) {
671 fz_rect realbox, mediabox;
672 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
674 fz_rotate (&rm, -pdim->rotate);
675 fz_scale (&sm, 1, -1);
676 fz_concat (&ctm, &rm, &sm);
677 realbox = pdim->mediabox;
678 fz_transform_rect (&realbox, &ctm);
679 fz_translate (&tm, -realbox.x0, -realbox.y0);
680 fz_concat (&ctm1, &ctm, &tm);
681 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
682 fz_invert_matrix (&im, &page_ctm);
683 fz_concat (&ctm, &im, &ctm1);
684 pdim->tctm = ctm;
685 pdim->tctmready = 1;
689 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
691 fz_matrix ctm, tm;
692 ptrdiff_t pdimno = pdim - state.pagedims;
694 ARSERT (pdim - state.pagedims < INT_MAX);
695 if (pdf_specifics (state.ctx, state.doc)) {
696 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
697 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
699 else {
700 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
701 fz_concat (&ctm, &tm, &pdim->ctm);
703 return ctm;
706 static fz_matrix pagectm (struct page *page)
708 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
711 static void *loadpage (int pageno, int pindex)
713 fz_device *dev;
714 struct page *page;
716 page = calloc (sizeof (struct page), 1);
717 if (!page) {
718 err (1, "calloc page %d", pageno);
721 page->dlist = fz_new_display_list (state.ctx, NULL);
722 dev = fz_new_list_device (state.ctx, page->dlist);
723 fz_try (state.ctx) {
724 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
725 fz_run_page (state.ctx, page->fzpage, dev,
726 &fz_identity, NULL);
728 fz_catch (state.ctx) {
729 page->fzpage = NULL;
731 fz_close_device (state.ctx, dev);
732 fz_drop_device (state.ctx, dev);
734 page->pdimno = pindex;
735 page->pageno = pageno;
736 page->sgen = state.gen;
737 page->agen = state.gen;
738 page->tgen = state.gen;
739 return page;
742 static struct tile *alloctile (int h)
744 int slicecount;
745 size_t tilesize;
746 struct tile *tile;
748 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
749 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
750 tile = calloc (tilesize, 1);
751 if (!tile) {
752 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
754 for (int i = 0; i < slicecount; ++i) {
755 int sh = fz_mini (h, state.sliceheight);
756 tile->slices[i].h = sh;
757 tile->slices[i].texindex = -1;
758 h -= sh;
760 tile->slicecount = slicecount;
761 tile->sliceheight = state.sliceheight;
762 return tile;
765 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
766 struct bo *pbo)
768 fz_rect rect;
769 fz_irect bbox;
770 fz_matrix ctm;
771 fz_device *dev;
772 struct tile *tile;
773 struct pagedim *pdim;
775 tile = alloctile (h);
776 pdim = &state.pagedims[page->pdimno];
778 bbox = pdim->bounds;
779 bbox.x0 += x;
780 bbox.y0 += y;
781 bbox.x1 = bbox.x0 + w;
782 bbox.y1 = bbox.y0 + h;
784 if (state.pig) {
785 if (state.pig->w == w
786 && state.pig->h == h
787 && state.pig->colorspace == state.colorspace) {
788 tile->pixmap = state.pig;
789 tile->pixmap->x = bbox.x0;
790 tile->pixmap->y = bbox.y0;
792 else {
793 fz_drop_pixmap (state.ctx, state.pig);
795 state.pig = NULL;
797 if (!tile->pixmap) {
798 if (pbo) {
799 tile->pixmap =
800 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
801 &bbox, NULL, 1, pbo->ptr);
802 tile->pbo = pbo;
804 else {
805 tile->pixmap =
806 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
807 NULL, 1);
811 tile->w = w;
812 tile->h = h;
813 clearpixmap (tile->pixmap);
815 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
816 ctm = pagectm (page);
817 fz_rect_from_irect (&rect, &bbox);
818 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
819 fz_close_device (state.ctx, dev);
820 fz_drop_device (state.ctx, dev);
822 return tile;
825 #ifdef CACHE_PAGEREFS
826 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
827 thanks to Robin Watts */
828 static void
829 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
831 fz_context *ctx = state.ctx; /* doc->ctx; */
832 pdf_obj *kids;
833 int len;
835 if (state.pdflut.idx == state.pagecount) return;
837 kids = pdf_dict_gets (ctx, node, "Kids");
838 len = pdf_array_len (ctx, kids);
840 if (len == 0)
841 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
843 if (pdf_mark_obj (ctx, node))
844 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
845 for (int i = 0; i < len; i++) {
846 pdf_obj *kid = pdf_array_get (ctx, kids, i);
847 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
848 if (*type
849 ? !strcmp (type, "Pages")
850 : pdf_dict_gets (ctx, kid, "Kids")
851 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
852 pdf_collect_pages (doc, kid);
854 else {
855 if (*type
856 ? strcmp (type, "Page") != 0
857 : !pdf_dict_gets (ctx, kid, "MediaBox"))
858 fz_warn (ctx, "non-page object in page tree (%s)", type);
859 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
862 pdf_unmark_obj (ctx, node);
865 static void
866 pdf_load_page_objs (pdf_document *doc)
868 pdf_obj *root = pdf_dict_gets (state.ctx,
869 pdf_trailer (state.ctx, doc), "Root");
870 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
872 if (!node)
873 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
875 state.pdflut.idx = 0;
876 pdf_collect_pages (doc, node);
878 #endif
880 static void initpdims (int wthack)
882 double start, end;
883 FILE *trimf = NULL;
884 fz_rect rootmediabox = fz_empty_rect;
885 int pageno, trim, show;
886 int trimw = 0, cxcount;
887 fz_context *ctx = state.ctx;
888 pdf_document *pdf = pdf_specifics (ctx, state.doc);
890 fz_var (trimw);
891 fz_var (trimf);
892 fz_var (cxcount);
893 start = now ();
895 if (state.trimmargins && state.trimcachepath) {
896 trimf = fopen (state.trimcachepath, "rb");
897 if (!trimf) {
898 trimf = fopen (state.trimcachepath, "wb");
899 trimw = 1;
903 if (state.trimmargins || pdf || !state.cxack)
904 cxcount = state.pagecount;
905 else
906 cxcount = fz_mini (state.pagecount, 1);
908 if (pdf) {
909 pdf_obj *obj;
910 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
911 "Root/Pages/MediaBox");
912 pdf_to_rect (ctx, obj, &rootmediabox);
915 #ifdef CACHE_PAGEREFS
916 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
917 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
918 if (!state.pdflut.objs) {
919 err (1, "malloc pageobjs %zu %d %zu failed",
920 sizeof (*state.pdflut.objs), cxcount,
921 sizeof (*state.pdflut.objs) * cxcount);
923 state.pdflut.count = cxcount;
924 pdf_load_page_objs (pdf);
925 state.pdflut.pdf = pdf;
927 #endif
929 for (pageno = 0; pageno < cxcount; ++pageno) {
930 int rotate = 0;
931 struct pagedim *p;
932 fz_rect mediabox = fz_empty_rect;
934 fz_var (rotate);
935 if (pdf) {
936 pdf_obj *pageref, *pageobj;
938 #ifdef CACHE_PAGEREFS
939 pageref = state.pdflut.objs[pageno];
940 #else
941 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
942 #endif
943 pageobj = pdf_resolve_indirect (ctx, pageref);
944 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
946 if (state.trimmargins) {
947 pdf_obj *obj;
948 pdf_page *page;
950 fz_try (ctx) {
951 page = pdf_load_page (ctx, pdf, pageno);
952 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
953 trim = state.trimanew || !obj;
954 if (trim) {
955 fz_rect rect;
956 fz_device *dev;
957 fz_matrix ctm, page_ctm;
959 dev = fz_new_bbox_device (ctx, &rect);
960 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
961 fz_invert_matrix (&ctm, &page_ctm);
962 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
963 fz_close_device (ctx, dev);
964 fz_drop_device (ctx, dev);
966 rect.x0 += state.trimfuzz.x0;
967 rect.x1 += state.trimfuzz.x1;
968 rect.y0 += state.trimfuzz.y0;
969 rect.y1 += state.trimfuzz.y1;
970 fz_transform_rect (&rect, &ctm);
971 fz_intersect_rect (&rect, &mediabox);
973 if (!fz_is_empty_rect (&rect)) {
974 mediabox = rect;
977 obj = pdf_new_array (ctx, pdf, 4);
978 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
979 mediabox.x0));
980 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
981 mediabox.y0));
982 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
983 mediabox.x1));
984 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
985 mediabox.y1));
986 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
988 else {
989 mediabox.x0 = pdf_to_real (ctx,
990 pdf_array_get (ctx, obj, 0));
991 mediabox.y0 = pdf_to_real (ctx,
992 pdf_array_get (ctx, obj, 1));
993 mediabox.x1 = pdf_to_real (ctx,
994 pdf_array_get (ctx, obj, 2));
995 mediabox.y1 = pdf_to_real (ctx,
996 pdf_array_get (ctx, obj, 3));
999 fz_drop_page (ctx, &page->super);
1000 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
1001 if (show) {
1002 printd ("progress %f Trimming %d",
1003 (double) (pageno + 1) / state.pagecount,
1004 pageno + 1);
1007 fz_catch (ctx) {
1008 fprintf (stderr, "failed to load page %d\n", pageno+1);
1011 else {
1012 int empty = 0;
1013 fz_rect cropbox;
1015 pdf_to_rect (ctx,
1016 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1017 &mediabox);
1018 if (fz_is_empty_rect (&mediabox)) {
1019 mediabox.x0 = 0;
1020 mediabox.y0 = 0;
1021 mediabox.x1 = 612;
1022 mediabox.y1 = 792;
1023 empty = 1;
1026 pdf_to_rect (ctx,
1027 pdf_dict_gets (ctx, pageobj, "CropBox"),
1028 &cropbox);
1029 if (!fz_is_empty_rect (&cropbox)) {
1030 if (empty) {
1031 mediabox = cropbox;
1033 else {
1034 fz_intersect_rect (&mediabox, &cropbox);
1037 else {
1038 if (empty) {
1039 if (fz_is_empty_rect (&rootmediabox)) {
1040 fprintf (stderr,
1041 "cannot find page size for page %d\n",
1042 pageno+1);
1044 else {
1045 mediabox = rootmediabox;
1051 else {
1052 if (state.trimmargins && trimw) {
1053 fz_page *page;
1055 fz_try (ctx) {
1056 page = fz_load_page (ctx, state.doc, pageno);
1057 fz_bound_page (ctx, page, &mediabox);
1058 if (state.trimmargins) {
1059 fz_rect rect;
1060 fz_device *dev;
1062 dev = fz_new_bbox_device (ctx, &rect);
1063 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1064 fz_close_device (ctx, dev);
1065 fz_drop_device (ctx, dev);
1067 rect.x0 += state.trimfuzz.x0;
1068 rect.x1 += state.trimfuzz.x1;
1069 rect.y0 += state.trimfuzz.y0;
1070 rect.y1 += state.trimfuzz.y1;
1071 fz_intersect_rect (&rect, &mediabox);
1073 if (!fz_is_empty_rect (&rect)) {
1074 mediabox = rect;
1077 fz_drop_page (ctx, page);
1078 if (!state.cxack) {
1079 printd ("progress %f loading %d",
1080 (double) (pageno + 1) / state.pagecount,
1081 pageno + 1);
1084 fz_catch (ctx) {
1086 if (trimf) {
1087 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1088 if (n - 1) {
1089 err (1, "fwrite trim mediabox");
1093 else {
1094 if (trimf) {
1095 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1096 if (n - 1) {
1097 err (1, "fread trim mediabox %d", pageno);
1100 else {
1101 fz_page *page;
1102 fz_try (ctx) {
1103 page = fz_load_page (ctx, state.doc, pageno);
1104 fz_bound_page (ctx, page, &mediabox);
1105 fz_drop_page (ctx, page);
1107 show = !state.trimmargins && pageno % 20 == 0;
1108 if (show) {
1109 printd ("progress %f Gathering dimensions %d",
1110 (double) (pageno) / state.pagecount,
1111 pageno);
1114 fz_catch (ctx) {
1115 fprintf (stderr, "failed to load page %d\n", pageno);
1121 if (state.pagedimcount == 0
1122 || ((void) (p = &state.pagedims[state.pagedimcount-1])
1123 , p->rotate != rotate)
1124 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1125 size_t size;
1127 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1128 state.pagedims = realloc (state.pagedims, size);
1129 if (!state.pagedims) {
1130 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1131 size, state.pagedimcount + 1);
1134 p = &state.pagedims[state.pagedimcount++];
1135 p->rotate = rotate;
1136 p->mediabox = mediabox;
1137 p->pageno = pageno;
1140 end = now ();
1141 if (!wthack) {
1142 printd ("progress 1 %s %d pages in %f seconds",
1143 state.trimmargins ? "Trimmed" : "Processed",
1144 state.pagecount, end - start);
1146 state.trimanew = 0;
1147 if (trimf) {
1148 if (fclose (trimf)) {
1149 err (1, "fclose");
1154 static void layout (void)
1156 int pindex;
1157 fz_rect box;
1158 fz_matrix ctm, rm;
1159 struct pagedim *p = NULL;
1160 float zw, w, maxw = 0.0, zoom = 1.0;
1162 if (state.pagedimcount == 0) return;
1164 switch (state.fitmodel) {
1165 case FitProportional:
1166 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1167 float x0, x1;
1169 p = &state.pagedims[pindex];
1170 fz_rotate (&rm, p->rotate + state.rotate);
1171 box = p->mediabox;
1172 fz_transform_rect (&box, &rm);
1174 x0 = fz_min (box.x0, box.x1);
1175 x1 = fz_max (box.x0, box.x1);
1177 w = x1 - x0;
1178 maxw = fz_max (w, maxw);
1179 zoom = state.w / maxw;
1181 break;
1183 case FitPage:
1184 maxw = state.w;
1185 break;
1187 case FitWidth:
1188 break;
1190 default:
1191 ARSERT (0 && state.fitmodel);
1194 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1195 fz_rect rect;
1196 fz_matrix tm, sm;
1198 p = &state.pagedims[pindex];
1199 fz_rotate (&ctm, state.rotate);
1200 fz_rotate (&rm, p->rotate + state.rotate);
1201 box = p->mediabox;
1202 fz_transform_rect (&box, &rm);
1203 w = box.x1 - box.x0;
1204 switch (state.fitmodel) {
1205 case FitProportional:
1206 p->left = (int) (((maxw - w) * zoom) / 2.f);
1207 break;
1208 case FitPage:
1210 float zh, h;
1211 zw = maxw / w;
1212 h = box.y1 - box.y0;
1213 zh = state.h / h;
1214 zoom = fz_min (zw, zh);
1215 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1217 break;
1218 case FitWidth:
1219 p->left = 0;
1220 zoom = state.w / w;
1221 break;
1224 fz_scale (&p->zoomctm, zoom, zoom);
1225 fz_concat (&ctm, &p->zoomctm, &ctm);
1227 fz_rotate (&rm, p->rotate);
1228 p->pagebox = p->mediabox;
1229 fz_transform_rect (&p->pagebox, &rm);
1230 p->pagebox.x1 -= p->pagebox.x0;
1231 p->pagebox.y1 -= p->pagebox.y0;
1232 p->pagebox.x0 = 0;
1233 p->pagebox.y0 = 0;
1234 rect = p->pagebox;
1235 fz_transform_rect (&rect, &ctm);
1236 fz_round_rect (&p->bounds, &rect);
1237 p->ctm = ctm;
1239 fz_translate (&tm, 0, -p->mediabox.y1);
1240 fz_scale (&sm, zoom, -zoom);
1241 fz_concat (&ctm, &tm, &sm);
1243 p->tctmready = 0;
1246 do {
1247 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1248 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1249 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1250 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1251 int boundw = x1 - x0;
1252 int boundh = y1 - y0;
1254 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1255 } while (p-- != state.pagedims);
1258 struct pagedim *pdimofpageno (int pageno)
1260 struct pagedim *pdim = state.pagedims;
1262 for (int i = 0; i < state.pagedimcount; ++i) {
1263 if (state.pagedims[i].pageno > pageno)
1264 break;
1265 pdim = &state.pagedims[i];
1267 return pdim;
1270 static void recurse_outline (fz_outline *outline, int level)
1272 while (outline) {
1273 if (outline->page >= 0) {
1274 fz_point p = {.x = outline->x, .y = outline->y};
1275 struct pagedim *pdim = pdimofpageno (outline->page);
1276 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1277 fz_transform_point (&p, &pdim->ctm);
1278 printd ("o %d %d %d %d %s",
1279 level, outline->page, (int) p.y, h, outline->title);
1281 else {
1282 printd ("on %d %s", level, outline->title);
1284 if (outline->down) {
1285 recurse_outline (outline->down, level + 1);
1287 outline = outline->next;
1291 static void process_outline (void)
1293 fz_outline *outline;
1295 if (!state.needoutline || !state.pagedimcount) return;
1297 state.needoutline = 0;
1298 outline = fz_load_outline (state.ctx, state.doc);
1299 if (outline) {
1300 recurse_outline (outline, 0);
1301 fz_drop_outline (state.ctx, outline);
1305 static char *strofline (fz_stext_line *line)
1307 char *p;
1308 char utf8[10];
1309 fz_stext_char *ch;
1310 size_t size = 0, cap = 80;
1312 p = malloc (cap + 1);
1313 if (!p) return NULL;
1315 for (ch = line->first_char; ch; ch = ch->next) {
1316 int n = fz_runetochar (utf8, ch->c);
1317 if (size + n > cap) {
1318 cap *= 2;
1319 p = realloc (p, cap + 1);
1320 if (!p) return NULL;
1323 memcpy (p + size, utf8, n);
1324 size += n;
1326 p[size] = 0;
1327 return p;
1330 static int matchline (regex_t *re, fz_stext_line *line,
1331 int stop, int pageno, double start)
1333 int ret;
1334 char *p;
1335 regmatch_t rm;
1337 p = strofline (line);
1338 if (!p) return -1;
1340 ret = regexec (re, p, 1, &rm, 0);
1341 if (ret) {
1342 free (p);
1343 if (ret != REG_NOMATCH) {
1344 size_t size;
1345 char errbuf[80];
1346 size = regerror (ret, re, errbuf, sizeof (errbuf));
1347 printd ("msg regexec error `%.*s'",
1348 (int) size, errbuf);
1349 return -1;
1351 return 0;
1353 else {
1354 fz_point p1, p2, p3, p4;
1355 fz_rect s = {0,0,0,0}, e;
1356 fz_stext_char *ch;
1357 int o = 0;
1359 for (ch = line->first_char; ch; ch = ch->next) {
1360 o += fz_runelen (ch->c);
1361 if (o > rm.rm_so) {
1362 s = ch->bbox;
1363 break;
1366 for (;ch; ch = ch->next) {
1367 o += fz_runelen (ch->c);
1368 if (o > rm.rm_eo) break;
1370 e = ch->bbox;
1372 p1.x = s.x0;
1373 p1.y = s.y0;
1374 p2.x = e.x1;
1375 p2.y = s.y0;
1376 p3.x = e.x1;
1377 p3.y = e.y1;
1378 p4.x = s.x0;
1379 p4.y = e.y1;
1381 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1382 if (!stop) {
1383 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1384 pageno, 1,
1385 p1.x, p1.y,
1386 p2.x, p2.y,
1387 p3.x, p3.y,
1388 p4.x, p4.y);
1390 printd ("progress 1 found at %d `%.*s' in %f sec",
1391 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1392 now () - start);
1394 else {
1395 printd ("match %d %d %f %f %f %f %f %f %f %f",
1396 pageno, 2,
1397 p1.x, p1.y,
1398 p2.x, p2.y,
1399 p3.x, p3.y,
1400 p4.x, p4.y);
1402 #pragma GCC diagnostic error "-Wdouble-promotion"
1403 free (p);
1404 return 1;
1408 /* wishful thinking function */
1409 static void search (regex_t *re, int pageno, int y, int forward)
1411 fz_device *tdev;
1412 fz_stext_page *text;
1413 struct pagedim *pdim;
1414 int stop = 0, niters = 0;
1415 double start, end;
1416 fz_page *page;
1417 fz_stext_block *block;
1419 start = now ();
1420 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1421 if (niters++ == 5) {
1422 niters = 0;
1423 if (hasdata ()) {
1424 printd ("progress 1 attention requested aborting search at %d",
1425 pageno);
1426 stop = 1;
1428 else {
1429 printd ("progress %f searching in page %d",
1430 (double) (pageno + 1) / state.pagecount,
1431 pageno);
1434 pdim = pdimofpageno (pageno);
1435 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1436 tdev = fz_new_stext_device (state.ctx, text, 0);
1438 page = fz_load_page (state.ctx, state.doc, pageno);
1440 fz_matrix ctm = pagectm1 (page, pdim);
1441 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1444 fz_close_device (state.ctx, tdev);
1445 fz_drop_device (state.ctx, tdev);
1447 if (forward) {
1448 for (block = text->first_block; block; block = block->next) {
1449 fz_stext_line *line;
1451 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1452 for (line = block->u.t.first_line; line; line = line->next) {
1453 if (line->bbox.y0 < y + 1) continue;
1455 switch (matchline (re, line, stop, pageno, start)) {
1456 case 0: break;
1457 case 1: stop = 1; break;
1458 case -1: stop = 1; goto endloop;
1463 else {
1464 for (block = text->last_block; block; block = block->prev) {
1465 fz_stext_line *line;
1467 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1468 for (line = block->u.t.last_line; line; line = line->prev) {
1469 if (line->bbox.y0 < y + 1) continue;
1471 switch (matchline (re, line, stop, pageno, start)) {
1472 case 0: break;
1473 case 1: stop = 1; break;
1474 case -1: stop = 1; goto endloop;
1480 if (forward) {
1481 pageno += 1;
1482 y = 0;
1484 else {
1485 pageno -= 1;
1486 y = INT_MAX;
1488 endloop:
1489 fz_drop_stext_page (state.ctx, text);
1490 fz_drop_page (state.ctx, page);
1492 end = now ();
1493 if (!stop) {
1494 printd ("progress 1 no matches %f sec", end - start);
1496 printd ("clearrects");
1499 static void set_tex_params (int colorspace)
1501 switch (colorspace) {
1502 case 0:
1503 state.texiform = GL_RGBA8;
1504 state.texform = GL_RGBA;
1505 state.texty = GL_UNSIGNED_BYTE;
1506 state.colorspace = fz_device_rgb (state.ctx);
1507 break;
1508 case 1:
1509 state.texiform = GL_RGBA8;
1510 state.texform = GL_BGRA;
1511 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1512 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1513 #else
1514 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1515 #endif
1516 state.colorspace = fz_device_bgr (state.ctx);
1517 break;
1518 case 2:
1519 state.texiform = GL_LUMINANCE_ALPHA;
1520 state.texform = GL_LUMINANCE_ALPHA;
1521 state.texty = GL_UNSIGNED_BYTE;
1522 state.colorspace = fz_device_gray (state.ctx);
1523 break;
1524 default:
1525 errx (1, "invalid colorspce %d", colorspace);
1529 static void realloctexts (int texcount)
1531 size_t size;
1533 if (texcount == state.texcount) return;
1535 if (texcount < state.texcount) {
1536 glDeleteTextures (state.texcount - texcount,
1537 state.texids + texcount);
1540 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1541 state.texids = realloc (state.texids, size);
1542 if (!state.texids) {
1543 err (1, "realloc texs %" FMT_s, size);
1546 state.texowners = (void *) (state.texids + texcount);
1547 if (texcount > state.texcount) {
1548 glGenTextures (texcount - state.texcount,
1549 state.texids + state.texcount);
1550 for (int i = state.texcount; i < texcount; ++i) {
1551 state.texowners[i].w = -1;
1552 state.texowners[i].slice = NULL;
1555 state.texcount = texcount;
1556 state.texindex = 0;
1559 static char *mbtoutf8 (char *s)
1561 char *p, *r;
1562 wchar_t *tmp;
1563 size_t i, ret, len;
1565 if (state.utf8cs) {
1566 return s;
1569 len = mbstowcs (NULL, s, strlen (s));
1570 if (len == 0) {
1571 return s;
1573 else {
1574 if (len == (size_t) -1) {
1575 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1576 return s;
1580 tmp = calloc (len, sizeof (wchar_t));
1581 if (!tmp) {
1582 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1583 len, sizeof (wchar_t), errno, strerror (errno));
1584 return s;
1587 ret = mbstowcs (tmp, s, len);
1588 if (ret == (size_t) -1) {
1589 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1590 len, errno, strerror (errno));
1591 free (tmp);
1592 return s;
1595 len = 0;
1596 for (i = 0; i < ret; ++i) {
1597 len += fz_runelen (tmp[i]);
1600 p = r = malloc (len + 1);
1601 if (!r) {
1602 printd ("emsg mbtoutf8: malloc(%zu)", len);
1603 free (tmp);
1604 return s;
1607 for (i = 0; i < ret; ++i) {
1608 p += fz_runetochar (p, tmp[i]);
1610 *p = 0;
1611 free (tmp);
1612 return r;
1615 CAMLprim value ml_mbtoutf8 (value s_v)
1617 CAMLparam1 (s_v);
1618 CAMLlocal1 (ret_v);
1619 char *s, *r;
1621 s = String_val (s_v);
1622 r = mbtoutf8 (s);
1623 if (r == s) {
1624 ret_v = s_v;
1626 else {
1627 ret_v = caml_copy_string (r);
1628 free (r);
1630 CAMLreturn (ret_v);
1633 static void * mainloop (void UNUSED_ATTR *unused)
1635 char *p = NULL;
1636 int len, ret, oldlen = 0;
1638 fz_var (p);
1639 fz_var (oldlen);
1640 for (;;) {
1641 len = readlen (state.csock);
1642 if (len == 0) {
1643 errx (1, "readlen returned 0");
1646 if (oldlen < len + 1) {
1647 p = realloc (p, len + 1);
1648 if (!p) {
1649 err (1, "realloc %d failed", len + 1);
1651 oldlen = len + 1;
1653 readdata (state.csock, p, len);
1654 p[len] = 0;
1656 if (!strncmp ("open", p, 4)) {
1657 int wthack, off, usedoccss, ok = 0;
1658 char *password;
1659 char *filename;
1660 char *utf8filename;
1661 size_t filenamelen;
1663 fz_var (ok);
1664 ret = sscanf (p + 5, " %d %d %d %n",
1665 &wthack, &state.cxack, &usedoccss, &off);
1666 if (ret != 3) {
1667 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1670 filename = p + 5 + off;
1671 filenamelen = strlen (filename);
1672 password = filename + filenamelen + 1;
1674 if (password[strlen (password) + 1]) {
1675 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1678 lock ("open");
1679 fz_set_use_document_css (state.ctx, usedoccss);
1680 fz_try (state.ctx) {
1681 ok = openxref (filename, password);
1683 fz_catch (state.ctx) {
1684 utf8filename = mbtoutf8 (filename);
1685 printd ("msg Could not open %s", utf8filename);
1686 if (utf8filename != filename) {
1687 free (utf8filename);
1690 if (ok) {
1691 pdfinfo ();
1692 initpdims (wthack);
1694 unlock ("open");
1696 if (ok) {
1697 if (!wthack) {
1698 utf8filename = mbtoutf8 (filename);
1699 printd ("msg Opened %s (press h/F1 to get help)",
1700 utf8filename);
1701 if (utf8filename != filename) {
1702 free (utf8filename);
1705 state.needoutline = 1;
1708 else if (!strncmp ("cs", p, 2)) {
1709 int i, colorspace;
1711 ret = sscanf (p + 2, " %d", &colorspace);
1712 if (ret != 1) {
1713 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1715 lock ("cs");
1716 set_tex_params (colorspace);
1717 for (i = 0; i < state.texcount; ++i) {
1718 state.texowners[i].w = -1;
1719 state.texowners[i].slice = NULL;
1721 unlock ("cs");
1723 else if (!strncmp ("freepage", p, 8)) {
1724 void *ptr;
1726 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1727 if (ret != 1) {
1728 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1730 lock ("freepage");
1731 freepage (ptr);
1732 unlock ("freepage");
1734 else if (!strncmp ("freetile", p, 8)) {
1735 void *ptr;
1737 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1738 if (ret != 1) {
1739 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1741 lock ("freetile");
1742 freetile (ptr);
1743 unlock ("freetile");
1745 else if (!strncmp ("search", p, 6)) {
1746 int icase, pageno, y, len2, forward;
1747 char *pattern;
1748 regex_t re;
1750 ret = sscanf (p + 6, " %d %d %d %d,%n",
1751 &icase, &pageno, &y, &forward, &len2);
1752 if (ret != 4) {
1753 errx (1, "malformed search `%s' ret=%d", p, ret);
1756 pattern = p + 6 + len2;
1757 ret = regcomp (&re, pattern,
1758 REG_EXTENDED | (icase ? REG_ICASE : 0));
1759 if (ret) {
1760 char errbuf[80];
1761 size_t size;
1763 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1764 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1766 else {
1767 search (&re, pageno, y, forward);
1768 regfree (&re);
1771 else if (!strncmp ("geometry", p, 8)) {
1772 int w, h, fitmodel;
1774 printd ("clear");
1775 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1776 if (ret != 3) {
1777 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1780 lock ("geometry");
1781 state.h = h;
1782 if (w != state.w) {
1783 state.w = w;
1784 for (int i = 0; i < state.texcount; ++i) {
1785 state.texowners[i].slice = NULL;
1788 state.fitmodel = fitmodel;
1789 layout ();
1790 process_outline ();
1792 state.gen++;
1793 unlock ("geometry");
1794 printd ("continue %d", state.pagecount);
1796 else if (!strncmp ("reqlayout", p, 9)) {
1797 char *nameddest;
1798 int rotate, off, h;
1799 int fitmodel;
1800 pdf_document *pdf;
1802 printd ("clear");
1803 ret = sscanf (p + 9, " %d %d %d %n",
1804 &rotate, &fitmodel, &h, &off);
1805 if (ret != 3) {
1806 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1808 lock ("reqlayout");
1809 pdf = pdf_specifics (state.ctx, state.doc);
1810 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1811 state.gen += 1;
1813 state.rotate = rotate;
1814 state.fitmodel = fitmodel;
1815 state.h = h;
1816 layout ();
1817 process_outline ();
1819 nameddest = p + 9 + off;
1820 if (pdf && nameddest && *nameddest) {
1821 fz_point xy;
1822 struct pagedim *pdim;
1823 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1824 &xy.x, &xy.y);
1825 pdim = pdimofpageno (pageno);
1826 fz_transform_point (&xy, &pdim->ctm);
1827 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1830 state.gen++;
1831 unlock ("reqlayout");
1832 printd ("continue %d", state.pagecount);
1834 else if (!strncmp ("page", p, 4)) {
1835 double a, b;
1836 struct page *page;
1837 int pageno, pindex;
1839 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1840 if (ret != 2) {
1841 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1844 lock ("page");
1845 a = now ();
1846 page = loadpage (pageno, pindex);
1847 b = now ();
1848 unlock ("page");
1850 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1852 else if (!strncmp ("tile", p, 4)) {
1853 int x, y, w, h;
1854 struct page *page;
1855 struct tile *tile;
1856 double a, b;
1857 void *data;
1859 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1860 SCN_ptr_cast (&page), &x, &y, &w, &h,
1861 SCN_ptr_cast (&data));
1862 if (ret != 6) {
1863 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1866 lock ("tile");
1867 a = now ();
1868 tile = rendertile (page, x, y, w, h, data);
1869 b = now ();
1870 unlock ("tile");
1872 printd ("tile %d %d %" FMT_ptr " %u %f",
1873 x, y,
1874 FMT_ptr_cast (tile),
1875 tile->w * tile->h * tile->pixmap->n,
1876 b - a);
1878 else if (!strncmp ("trimset", p, 7)) {
1879 fz_irect fuzz;
1880 int trimmargins;
1882 ret = sscanf (p + 7, " %d %d %d %d %d",
1883 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1884 if (ret != 5) {
1885 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1887 lock ("trimset");
1888 state.trimmargins = trimmargins;
1889 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1890 state.trimanew = 1;
1891 state.trimfuzz = fuzz;
1893 unlock ("trimset");
1895 else if (!strncmp ("settrim", p, 7)) {
1896 fz_irect fuzz;
1897 int trimmargins;
1899 ret = sscanf (p + 7, " %d %d %d %d %d",
1900 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1901 if (ret != 5) {
1902 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1904 printd ("clear");
1905 lock ("settrim");
1906 state.trimmargins = trimmargins;
1907 state.needoutline = 1;
1908 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1909 state.trimanew = 1;
1910 state.trimfuzz = fuzz;
1912 state.pagedimcount = 0;
1913 free (state.pagedims);
1914 state.pagedims = NULL;
1915 initpdims (0);
1916 layout ();
1917 process_outline ();
1918 unlock ("settrim");
1919 printd ("continue %d", state.pagecount);
1921 else if (!strncmp ("sliceh", p, 6)) {
1922 int h;
1924 ret = sscanf (p + 6, " %d", &h);
1925 if (ret != 1) {
1926 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1928 if (h != state.sliceheight) {
1929 state.sliceheight = h;
1930 for (int i = 0; i < state.texcount; ++i) {
1931 state.texowners[i].w = -1;
1932 state.texowners[i].h = -1;
1933 state.texowners[i].slice = NULL;
1937 else if (!strncmp ("interrupt", p, 9)) {
1938 printd ("vmsg interrupted");
1940 else {
1941 errx (1, "unknown command %.*s", len, p);
1944 return 0;
1947 CAMLprim value ml_isexternallink (value uri_v)
1949 CAMLparam1 (uri_v);
1950 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1951 CAMLreturn (Val_bool (ext));
1954 CAMLprim value ml_uritolocation (value uri_v)
1956 CAMLparam1 (uri_v);
1957 CAMLlocal1 (ret_v);
1958 int pageno;
1959 fz_point xy;
1960 struct pagedim *pdim;
1962 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1963 &xy.x, &xy.y);
1964 pdim = pdimofpageno (pageno);
1965 fz_transform_point (&xy, &pdim->ctm);
1966 ret_v = caml_alloc_tuple (3);
1967 Field (ret_v, 0) = Val_int (pageno);
1968 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1969 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1970 CAMLreturn (ret_v);
1973 CAMLprim value ml_realloctexts (value texcount_v)
1975 CAMLparam1 (texcount_v);
1976 int ok;
1978 if (trylock (__func__)) {
1979 ok = 0;
1980 goto done;
1982 realloctexts (Int_val (texcount_v));
1983 ok = 1;
1984 unlock (__func__);
1986 done:
1987 CAMLreturn (Val_bool (ok));
1990 static void recti (int x0, int y0, int x1, int y1)
1992 GLfloat *v = state.vertices;
1994 glVertexPointer (2, GL_FLOAT, 0, v);
1995 v[0] = x0; v[1] = y0;
1996 v[2] = x1; v[3] = y0;
1997 v[4] = x0; v[5] = y1;
1998 v[6] = x1; v[7] = y1;
1999 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2002 static void showsel (struct page *page, int ox, int oy)
2004 fz_irect bbox;
2005 fz_rect rect;
2006 fz_stext_block *block;
2007 int seen = 0;
2008 unsigned char selcolor[] = {15,15,15,140};
2010 if (!page->fmark.ch || !page->lmark.ch) return;
2012 glEnable (GL_BLEND);
2013 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2014 glColor4ubv (selcolor);
2016 ox += state.pagedims[page->pdimno].bounds.x0;
2017 oy += state.pagedims[page->pdimno].bounds.y0;
2019 for (block = page->text->first_block; block; block = block->next) {
2020 fz_stext_line *line;
2022 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2023 for (line = block->u.t.first_line; line; line = line->next) {
2024 fz_stext_char *ch;
2026 rect = fz_empty_rect;
2027 for (ch = line->first_char; ch; ch = ch->next) {
2028 if (ch == page->fmark.ch) seen = 1;
2029 if (seen) fz_union_rect (&rect, &ch->bbox);
2030 if (ch == page->lmark.ch) {
2031 fz_round_rect (&bbox, &rect);
2032 recti (bbox.x0 + ox, bbox.y0 + oy,
2033 bbox.x1 + ox, bbox.y1 + oy);
2034 goto done;
2037 fz_round_rect (&bbox, &rect);
2038 recti (bbox.x0 + ox, bbox.y0 + oy,
2039 bbox.x1 + ox, bbox.y1 + oy);
2042 done:
2043 glDisable (GL_BLEND);
2046 #pragma GCC diagnostic push
2047 #pragma GCC diagnostic ignored "-Wdouble-promotion"
2048 #pragma GCC diagnostic ignored "-Wconversion"
2049 #include "glfont.c"
2050 #pragma GCC diagnostic pop
2052 static void stipplerect (fz_matrix *m,
2053 fz_point *p1,
2054 fz_point *p2,
2055 fz_point *p3,
2056 fz_point *p4,
2057 GLfloat *texcoords,
2058 GLfloat *vertices)
2060 fz_transform_point (p1, m);
2061 fz_transform_point (p2, m);
2062 fz_transform_point (p3, m);
2063 fz_transform_point (p4, m);
2065 float w, h, s, t;
2067 w = p2->x - p1->x;
2068 h = p2->y - p1->y;
2069 t = hypotf (w, h) * .25f;
2071 w = p3->x - p2->x;
2072 h = p3->y - p2->y;
2073 s = hypotf (w, h) * .25f;
2075 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2076 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2078 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2079 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2081 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2082 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2084 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2085 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2087 glDrawArrays (GL_LINES, 0, 8);
2090 static void solidrect (fz_matrix *m,
2091 fz_point *p1,
2092 fz_point *p2,
2093 fz_point *p3,
2094 fz_point *p4,
2095 GLfloat *vertices)
2097 fz_transform_point (p1, m);
2098 fz_transform_point (p2, m);
2099 fz_transform_point (p3, m);
2100 fz_transform_point (p4, m);
2101 vertices[0] = p1->x; vertices[1] = p1->y;
2102 vertices[2] = p2->x; vertices[3] = p2->y;
2104 vertices[4] = p3->x; vertices[5] = p3->y;
2105 vertices[6] = p4->x; vertices[7] = p4->y;
2106 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2109 static void ensurelinks (struct page *page)
2111 if (!page->links)
2112 page->links = fz_load_links (state.ctx, page->fzpage);
2115 static void highlightlinks (struct page *page, int xoff, int yoff)
2117 fz_matrix ctm, tm, pm;
2118 fz_link *link;
2119 GLfloat *texcoords = state.texcoords;
2120 GLfloat *vertices = state.vertices;
2122 ensurelinks (page);
2124 glEnable (GL_TEXTURE_1D);
2125 glEnable (GL_BLEND);
2126 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2127 glBindTexture (GL_TEXTURE_1D, state.stid);
2129 xoff -= state.pagedims[page->pdimno].bounds.x0;
2130 yoff -= state.pagedims[page->pdimno].bounds.y0;
2131 fz_translate (&tm, xoff, yoff);
2132 pm = pagectm (page);
2133 fz_concat (&ctm, &pm, &tm);
2135 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2136 glVertexPointer (2, GL_FLOAT, 0, vertices);
2138 for (link = page->links; link; link = link->next) {
2139 fz_point p1, p2, p3, p4;
2141 p1.x = link->rect.x0;
2142 p1.y = link->rect.y0;
2144 p2.x = link->rect.x1;
2145 p2.y = link->rect.y0;
2147 p3.x = link->rect.x1;
2148 p3.y = link->rect.y1;
2150 p4.x = link->rect.x0;
2151 p4.y = link->rect.y1;
2153 /* TODO: different colours for different schemes */
2154 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2155 else glColor3ub (255, 0, 0);
2157 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2160 for (int i = 0; i < page->annotcount; ++i) {
2161 fz_point p1, p2, p3, p4;
2162 struct annot *annot = &page->annots[i];
2164 p1.x = annot->bbox.x0;
2165 p1.y = annot->bbox.y0;
2167 p2.x = annot->bbox.x1;
2168 p2.y = annot->bbox.y0;
2170 p3.x = annot->bbox.x1;
2171 p3.y = annot->bbox.y1;
2173 p4.x = annot->bbox.x0;
2174 p4.y = annot->bbox.y1;
2176 glColor3ub (0, 0, 128);
2177 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2180 glDisable (GL_BLEND);
2181 glDisable (GL_TEXTURE_1D);
2184 static int compareslinks (const void *l, const void *r)
2186 struct slink const *ls = l;
2187 struct slink const *rs = r;
2188 if (ls->bbox.y0 == rs->bbox.y0) {
2189 return rs->bbox.x0 - rs->bbox.x0;
2191 return ls->bbox.y0 - rs->bbox.y0;
2194 static void droptext (struct page *page)
2196 if (page->text) {
2197 fz_drop_stext_page (state.ctx, page->text);
2198 page->fmark.ch = NULL;
2199 page->lmark.ch = NULL;
2200 page->text = NULL;
2204 static void dropannots (struct page *page)
2206 if (page->annots) {
2207 free (page->annots);
2208 page->annots = NULL;
2209 page->annotcount = 0;
2213 static void ensureannots (struct page *page)
2215 int i, count = 0;
2216 size_t annotsize = sizeof (*page->annots);
2217 fz_annot *annot;
2219 if (state.gen != page->agen) {
2220 dropannots (page);
2221 page->agen = state.gen;
2223 if (page->annots) return;
2225 for (annot = fz_first_annot (state.ctx, page->fzpage);
2226 annot;
2227 annot = fz_next_annot (state.ctx, annot)) {
2228 count++;
2231 if (count > 0) {
2232 page->annotcount = count;
2233 page->annots = calloc (count, annotsize);
2234 if (!page->annots) {
2235 err (1, "calloc annots %d", count);
2238 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2239 annot;
2240 annot = fz_next_annot (state.ctx, annot), i++) {
2241 fz_rect rect;
2243 fz_bound_annot (state.ctx, annot, &rect);
2244 page->annots[i].annot = annot;
2245 fz_round_rect (&page->annots[i].bbox, &rect);
2250 static void dropslinks (struct page *page)
2252 if (page->slinks) {
2253 free (page->slinks);
2254 page->slinks = NULL;
2255 page->slinkcount = 0;
2257 if (page->links) {
2258 fz_drop_link (state.ctx, page->links);
2259 page->links = NULL;
2263 static void ensureslinks (struct page *page)
2265 fz_matrix ctm;
2266 int i, count;
2267 size_t slinksize = sizeof (*page->slinks);
2268 fz_link *link;
2270 ensureannots (page);
2271 if (state.gen != page->sgen) {
2272 dropslinks (page);
2273 page->sgen = state.gen;
2275 if (page->slinks) return;
2277 ensurelinks (page);
2278 ctm = pagectm (page);
2280 count = page->annotcount;
2281 for (link = page->links; link; link = link->next) {
2282 count++;
2284 if (count > 0) {
2285 int j;
2287 page->slinkcount = count;
2288 page->slinks = calloc (count, slinksize);
2289 if (!page->slinks) {
2290 err (1, "calloc slinks %d", count);
2293 for (i = 0, link = page->links; link; ++i, link = link->next) {
2294 fz_rect rect;
2296 rect = link->rect;
2297 fz_transform_rect (&rect, &ctm);
2298 page->slinks[i].tag = SLINK;
2299 page->slinks[i].u.link = link;
2300 fz_round_rect (&page->slinks[i].bbox, &rect);
2302 for (j = 0; j < page->annotcount; ++j, ++i) {
2303 fz_rect rect;
2304 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2305 fz_transform_rect (&rect, &ctm);
2306 fz_round_rect (&page->slinks[i].bbox, &rect);
2308 page->slinks[i].tag = SANNOT;
2309 page->slinks[i].u.annot = page->annots[j].annot;
2311 qsort (page->slinks, count, slinksize, compareslinks);
2315 #pragma GCC diagnostic push
2316 #pragma GCC diagnostic ignored "-Wconversion"
2317 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2318 static void fmt_linkn (char *s, unsigned int u)
2320 unsigned int len; unsigned int q;
2321 unsigned int zma = 'z' - 'a' + 1;
2322 len = 1; q = u;
2323 while (q > zma - 1) { ++len; q /= zma; }
2324 if (s) {
2325 s += len;
2326 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2327 /* handles u == 0 */
2329 s[len] = 0;
2331 #pragma GCC diagnostic pop
2333 static void highlightslinks (struct page *page, int xoff, int yoff,
2334 int noff, char *targ, mlsize_t tlen, int hfsize)
2336 char buf[40];
2337 struct slink *slink;
2338 float x0, y0, x1, y1, w;
2340 ensureslinks (page);
2341 glColor3ub (0xc3, 0xb0, 0x91);
2342 for (int i = 0; i < page->slinkcount; ++i) {
2343 fmt_linkn (buf, i + noff);
2344 if (!tlen || !strncmp (targ, buf, tlen)) {
2345 slink = &page->slinks[i];
2347 x0 = slink->bbox.x0 + xoff - 5;
2348 y1 = slink->bbox.y0 + yoff - 5;
2349 y0 = y1 + 10 + hfsize;
2350 w = measure_string (state.face, hfsize, buf);
2351 x1 = x0 + w + 10;
2352 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2356 glEnable (GL_BLEND);
2357 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2358 glEnable (GL_TEXTURE_2D);
2359 glColor3ub (0, 0, 0);
2360 for (int i = 0; i < page->slinkcount; ++i) {
2361 fmt_linkn (buf, i + noff);
2362 if (!tlen || !strncmp (targ, buf, tlen)) {
2363 slink = &page->slinks[i];
2365 x0 = slink->bbox.x0 + xoff;
2366 y0 = slink->bbox.y0 + yoff + hfsize;
2367 draw_string (state.face, hfsize, x0, y0, buf);
2370 glDisable (GL_TEXTURE_2D);
2371 glDisable (GL_BLEND);
2374 static void uploadslice (struct tile *tile, struct slice *slice)
2376 int offset;
2377 struct slice *slice1;
2378 unsigned char *texdata;
2380 offset = 0;
2381 for (slice1 = tile->slices; slice != slice1; slice1++) {
2382 offset += slice1->h * tile->w * tile->pixmap->n;
2384 if (slice->texindex != -1 && slice->texindex < state.texcount
2385 && state.texowners[slice->texindex].slice == slice) {
2386 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2388 else {
2389 int subimage = 0;
2390 int texindex = state.texindex++ % state.texcount;
2392 if (state.texowners[texindex].w == tile->w) {
2393 if (state.texowners[texindex].h >= slice->h) {
2394 subimage = 1;
2396 else {
2397 state.texowners[texindex].h = slice->h;
2400 else {
2401 state.texowners[texindex].h = slice->h;
2404 state.texowners[texindex].w = tile->w;
2405 state.texowners[texindex].slice = slice;
2406 slice->texindex = texindex;
2408 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2409 #if TEXT_TYPE == GL_TEXTURE_2D
2410 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2411 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2412 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2413 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2414 #endif
2415 if (tile->pbo) {
2416 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2417 texdata = 0;
2419 else {
2420 texdata = tile->pixmap->samples;
2422 if (subimage) {
2423 glTexSubImage2D (TEXT_TYPE,
2427 tile->w,
2428 slice->h,
2429 state.texform,
2430 state.texty,
2431 texdata+offset
2434 else {
2435 glTexImage2D (TEXT_TYPE,
2437 state.texiform,
2438 tile->w,
2439 slice->h,
2441 state.texform,
2442 state.texty,
2443 texdata+offset
2446 if (tile->pbo) {
2447 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2452 CAMLprim void ml_begintiles (value unit_v)
2454 CAMLparam1 (unit_v);
2455 glEnable (TEXT_TYPE);
2456 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2457 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2458 CAMLreturn0;
2461 CAMLprim void ml_endtiles (value unit_v)
2463 CAMLparam1 (unit_v);
2464 glDisable (TEXT_TYPE);
2465 CAMLreturn0;
2468 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2470 CAMLparam2 (args_v, ptr_v);
2471 int dispx = Int_val (Field (args_v, 0));
2472 int dispy = Int_val (Field (args_v, 1));
2473 int dispw = Int_val (Field (args_v, 2));
2474 int disph = Int_val (Field (args_v, 3));
2475 int tilex = Int_val (Field (args_v, 4));
2476 int tiley = Int_val (Field (args_v, 5));
2477 char *s = String_val (ptr_v);
2478 struct tile *tile = parse_pointer (__func__, s);
2479 int slicey, firstslice;
2480 struct slice *slice;
2481 GLfloat *texcoords = state.texcoords;
2482 GLfloat *vertices = state.vertices;
2484 firstslice = tiley / tile->sliceheight;
2485 slice = &tile->slices[firstslice];
2486 slicey = tiley % tile->sliceheight;
2488 while (disph > 0) {
2489 int dh;
2491 dh = slice->h - slicey;
2492 dh = fz_mini (disph, dh);
2493 uploadslice (tile, slice);
2495 texcoords[0] = tilex; texcoords[1] = slicey;
2496 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2497 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2498 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2500 vertices[0] = dispx; vertices[1] = dispy;
2501 vertices[2] = dispx+dispw; vertices[3] = dispy;
2502 vertices[4] = dispx; vertices[5] = dispy+dh;
2503 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2505 #if TEXT_TYPE == GL_TEXTURE_2D
2506 for (int i = 0; i < 8; ++i) {
2507 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2509 #endif
2511 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2512 dispy += dh;
2513 disph -= dh;
2514 slice++;
2515 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2516 slicey = 0;
2518 CAMLreturn0;
2521 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2523 fz_matrix ctm, tm, pm;
2524 fz_point p1, p2, p3, p4;
2525 GLfloat *vertices = state.vertices;
2526 double *v = (double *) rects_v;
2528 xoff -= state.pagedims[page->pdimno].bounds.x0;
2529 yoff -= state.pagedims[page->pdimno].bounds.y0;
2530 fz_translate (&tm, xoff, yoff);
2531 pm = pagectm (page);
2532 fz_concat (&ctm, &pm, &tm);
2534 glEnable (GL_BLEND);
2535 glVertexPointer (2, GL_FLOAT, 0, vertices);
2537 glColor4dv (v);
2538 p1.x = (float) v[4];
2539 p1.y = (float) v[5];
2541 p2.x = (float) v[6];
2542 p2.y = (float) v[5];
2544 p3.x = (float) v[6];
2545 p3.y = (float) v[7];
2547 p4.x = (float) v[4];
2548 p4.y = (float) v[7];
2549 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2550 glDisable (GL_BLEND);
2553 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2554 value xoff_v, value yoff_v,
2555 value li_v)
2557 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2558 int xoff = Int_val (xoff_v);
2559 int yoff = Int_val (yoff_v);
2560 int noff = Int_val (Field (li_v, 0));
2561 char *targ = String_val (Field (li_v, 1));
2562 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2563 int hfsize = Int_val (Field (li_v, 2));
2564 char *s = String_val (ptr_v);
2565 int hlmask = Int_val (hlinks_v);
2566 struct page *page = parse_pointer (__func__, s);
2568 if (!page->fzpage) {
2569 /* deal with loadpage failed pages */
2570 goto done;
2573 if (trylock (__func__)) {
2574 noff = -1;
2575 goto done;
2578 ensureannots (page);
2579 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2580 if (hlmask & 2) {
2581 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2582 noff = page->slinkcount;
2584 if (page->tgen == state.gen) {
2585 showsel (page, xoff, yoff);
2587 unlock (__func__);
2589 done:
2590 CAMLreturn (Val_int (noff));
2593 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2594 value rects_v)
2596 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2597 int xoff = Int_val (xoff_v);
2598 int yoff = Int_val (yoff_v);
2599 char *s = String_val (ptr_v);
2600 struct page *page = parse_pointer (__func__, s);
2602 drawprect (page, xoff, yoff, rects_v);
2603 CAMLreturn0;
2606 static struct annot *getannot (struct page *page, int x, int y)
2608 fz_point p;
2609 fz_matrix ctm;
2610 const fz_matrix *tctm;
2611 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2613 if (!page->annots) return NULL;
2615 if (pdf) {
2616 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2617 tctm = &state.pagedims[page->pdimno].tctm;
2619 else {
2620 tctm = &fz_identity;
2623 p.x = x;
2624 p.y = y;
2626 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2627 fz_invert_matrix (&ctm, &ctm);
2628 fz_transform_point (&p, &ctm);
2630 if (pdf) {
2631 for (int i = 0; i < page->annotcount; ++i) {
2632 struct annot *a = &page->annots[i];
2633 fz_rect rect;
2635 fz_bound_annot (state.ctx, a->annot, &rect);
2636 if (p.x >= rect.x0 && p.x <= rect.x1) {
2637 if (p.y >= rect.y0 && p.y <= rect.y1)
2638 return a;
2642 return NULL;
2645 static fz_link *getlink (struct page *page, int x, int y)
2647 fz_point p;
2648 fz_matrix ctm;
2649 fz_link *link;
2651 ensureslinks (page);
2653 p.x = x;
2654 p.y = y;
2656 ctm = pagectm (page);
2657 fz_invert_matrix (&ctm, &ctm);
2658 fz_transform_point (&p, &ctm);
2660 for (link = page->links; link; link = link->next) {
2661 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2662 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2663 return link;
2667 return NULL;
2670 static void ensuretext (struct page *page)
2672 if (state.gen != page->tgen) {
2673 droptext (page);
2674 page->tgen = state.gen;
2676 if (!page->text) {
2677 fz_matrix ctm;
2678 fz_device *tdev;
2680 page->text = fz_new_stext_page (state.ctx,
2681 &state.pagedims[page->pdimno].mediabox);
2682 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2683 ctm = pagectm (page);
2684 fz_run_display_list (state.ctx, page->dlist,
2685 tdev, &ctm, &fz_infinite_rect, NULL);
2686 fz_close_device (state.ctx, tdev);
2687 fz_drop_device (state.ctx, tdev);
2691 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2693 CAMLparam2 (start_page_v, dir_v);
2694 CAMLlocal1 (ret_v);
2695 int i, dir = Int_val (dir_v);
2696 int start_page = Int_val (start_page_v);
2697 int end_page = dir > 0 ? state.pagecount : -1;
2698 pdf_document *pdf;
2700 fz_var (end_page);
2701 ret_v = Val_int (0);
2702 lock (__func__);
2703 pdf = pdf_specifics (state.ctx, state.doc);
2704 for (i = start_page + dir; i != end_page; i += dir) {
2705 int found;
2707 fz_var (found);
2708 if (pdf) {
2709 pdf_page *page = NULL;
2711 fz_var (page);
2712 fz_try (state.ctx) {
2713 page = pdf_load_page (state.ctx, pdf, i);
2714 found = !!page->links || !!page->annots;
2716 fz_catch (state.ctx) {
2717 found = 0;
2719 if (page) {
2720 fz_drop_page (state.ctx, &page->super);
2723 else {
2724 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2725 fz_link *link = fz_load_links (state.ctx, page);
2726 found = !!link;
2727 fz_drop_link (state.ctx, link);
2728 fz_drop_page (state.ctx, page);
2731 if (found) {
2732 ret_v = caml_alloc_small (1, 1);
2733 Field (ret_v, 0) = Val_int (i);
2734 goto unlock;
2737 unlock:
2738 unlock (__func__);
2739 CAMLreturn (ret_v);
2742 enum { dir_first, dir_last };
2743 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2745 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2747 CAMLparam2 (ptr_v, dir_v);
2748 CAMLlocal2 (ret_v, pos_v);
2749 struct page *page;
2750 int dirtag, i, slinkindex;
2751 struct slink *found = NULL ,*slink;
2752 char *s = String_val (ptr_v);
2754 page = parse_pointer (__func__, s);
2755 ret_v = Val_int (0);
2756 lock (__func__);
2757 ensureslinks (page);
2759 if (Is_block (dir_v)) {
2760 dirtag = Tag_val (dir_v);
2761 switch (dirtag) {
2762 case dir_first_visible:
2764 int x0, y0, dir, first_index, last_index;
2766 pos_v = Field (dir_v, 0);
2767 x0 = Int_val (Field (pos_v, 0));
2768 y0 = Int_val (Field (pos_v, 1));
2769 dir = Int_val (Field (pos_v, 2));
2771 if (dir >= 0) {
2772 dir = 1;
2773 first_index = 0;
2774 last_index = page->slinkcount;
2776 else {
2777 first_index = page->slinkcount - 1;
2778 last_index = -1;
2781 for (i = first_index; i != last_index; i += dir) {
2782 slink = &page->slinks[i];
2783 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2784 found = slink;
2785 break;
2789 break;
2791 case dir_left:
2792 slinkindex = Int_val (Field (dir_v, 0));
2793 found = &page->slinks[slinkindex];
2794 for (i = slinkindex - 1; i >= 0; --i) {
2795 slink = &page->slinks[i];
2796 if (slink->bbox.x0 < found->bbox.x0) {
2797 found = slink;
2798 break;
2801 break;
2803 case dir_right:
2804 slinkindex = Int_val (Field (dir_v, 0));
2805 found = &page->slinks[slinkindex];
2806 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2807 slink = &page->slinks[i];
2808 if (slink->bbox.x0 > found->bbox.x0) {
2809 found = slink;
2810 break;
2813 break;
2815 case dir_down:
2816 slinkindex = Int_val (Field (dir_v, 0));
2817 found = &page->slinks[slinkindex];
2818 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2819 slink = &page->slinks[i];
2820 if (slink->bbox.y0 >= found->bbox.y0) {
2821 found = slink;
2822 break;
2825 break;
2827 case dir_up:
2828 slinkindex = Int_val (Field (dir_v, 0));
2829 found = &page->slinks[slinkindex];
2830 for (i = slinkindex - 1; i >= 0; --i) {
2831 slink = &page->slinks[i];
2832 if (slink->bbox.y0 <= found->bbox.y0) {
2833 found = slink;
2834 break;
2837 break;
2840 else {
2841 dirtag = Int_val (dir_v);
2842 switch (dirtag) {
2843 case dir_first:
2844 found = page->slinks;
2845 break;
2847 case dir_last:
2848 if (page->slinks) {
2849 found = page->slinks + (page->slinkcount - 1);
2851 break;
2854 if (found) {
2855 ret_v = caml_alloc_small (2, 1);
2856 Field (ret_v, 0) = Val_int (found - page->slinks);
2859 unlock (__func__);
2860 CAMLreturn (ret_v);
2863 enum { uuri, utext, uannot };
2865 CAMLprim value ml_getlink (value ptr_v, value n_v)
2867 CAMLparam2 (ptr_v, n_v);
2868 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2869 fz_link *link;
2870 struct page *page;
2871 char *s = String_val (ptr_v);
2872 struct slink *slink;
2874 ret_v = Val_int (0);
2875 page = parse_pointer (__func__, s);
2877 lock (__func__);
2878 ensureslinks (page);
2879 slink = &page->slinks[Int_val (n_v)];
2880 if (slink->tag == SLINK) {
2881 link = slink->u.link;
2882 str_v = caml_copy_string (link->uri);
2883 ret_v = caml_alloc_small (1, uuri);
2884 Field (ret_v, 0) = str_v;
2886 else {
2887 ret_v = caml_alloc_small (1, uannot);
2888 tup_v = caml_alloc_tuple (2);
2889 Field (ret_v, 0) = tup_v;
2890 Field (tup_v, 0) = ptr_v;
2891 Field (tup_v, 1) = n_v;
2893 unlock (__func__);
2895 CAMLreturn (ret_v);
2898 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2900 CAMLparam2 (ptr_v, n_v);
2901 CAMLlocal1 (ret_v);
2902 pdf_document *pdf;
2903 char *contents = NULL;
2905 lock (__func__);
2906 pdf = pdf_specifics (state.ctx, state.doc);
2907 if (pdf) {
2908 char *s = String_val (ptr_v);
2909 struct page *page;
2910 struct slink *slink;
2912 page = parse_pointer (__func__, s);
2913 slink = &page->slinks[Int_val (n_v)];
2914 contents = pdf_copy_annot_contents (state.ctx,
2915 (pdf_annot *) slink->u.annot);
2917 unlock (__func__);
2918 if (contents) {
2919 ret_v = caml_copy_string (contents);
2920 fz_free (state.ctx, contents);
2922 else {
2923 ret_v = caml_copy_string ("");
2925 CAMLreturn (ret_v);
2928 CAMLprim value ml_getlinkcount (value ptr_v)
2930 CAMLparam1 (ptr_v);
2931 struct page *page;
2932 char *s = String_val (ptr_v);
2934 page = parse_pointer (__func__, s);
2935 CAMLreturn (Val_int (page->slinkcount));
2938 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2940 CAMLparam2 (ptr_v, n_v);
2941 CAMLlocal1 (ret_v);
2942 struct page *page;
2943 struct slink *slink;
2944 char *s = String_val (ptr_v);
2946 page = parse_pointer (__func__, s);
2947 ret_v = caml_alloc_tuple (4);
2948 lock (__func__);
2949 ensureslinks (page);
2951 slink = &page->slinks[Int_val (n_v)];
2952 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2953 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2954 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2955 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2956 unlock (__func__);
2957 CAMLreturn (ret_v);
2960 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2962 CAMLparam3 (ptr_v, x_v, y_v);
2963 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2964 fz_link *link;
2965 struct annot *annot;
2966 struct page *page;
2967 char *ptr = String_val (ptr_v);
2968 int x = Int_val (x_v), y = Int_val (y_v);
2969 struct pagedim *pdim;
2971 ret_v = Val_int (0);
2972 if (trylock (__func__)) {
2973 goto done;
2976 page = parse_pointer (__func__, ptr);
2977 pdim = &state.pagedims[page->pdimno];
2978 x += pdim->bounds.x0;
2979 y += pdim->bounds.y0;
2982 annot = getannot (page, x, y);
2983 if (annot) {
2984 int i, n = -1;
2986 ensureslinks (page);
2987 for (i = 0; i < page->slinkcount; ++i) {
2988 if (page->slinks[i].tag == SANNOT
2989 && page->slinks[i].u.annot == annot->annot) {
2990 n = i;
2991 break;
2994 ret_v = caml_alloc_small (1, uannot);
2995 tup_v = caml_alloc_tuple (2);
2996 Field (ret_v, 0) = tup_v;
2997 Field (tup_v, 0) = ptr_v;
2998 Field (tup_v, 1) = Val_int (n);
2999 goto unlock;
3003 link = getlink (page, x, y);
3004 if (link) {
3005 str_v = caml_copy_string (link->uri);
3006 ret_v = caml_alloc_small (1, uuri);
3007 Field (ret_v, 0) = str_v;
3009 else {
3010 fz_rect *b;
3011 fz_stext_block *block;
3013 ensuretext (page);
3015 for (block = page->text->first_block; block; block = block->next) {
3016 fz_stext_line *line;
3018 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3019 b = &block->bbox;
3020 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3021 continue;
3023 for (line = block->u.t.first_line; line; line = line->next) {
3024 fz_stext_char *ch;
3026 b = &line->bbox;
3027 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3028 continue;
3030 for (ch = line->first_char; ch; ch = ch->next) {
3031 b = &ch->bbox;
3033 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3034 const char *n2 = fz_font_name (state.ctx, ch->font);
3035 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3036 ch->font);
3038 if (!n2) n2 = "<unknown font>";
3040 if (face && face->family_name) {
3041 char *s;
3042 char *n1 = face->family_name;
3043 size_t l1 = strlen (n1);
3044 size_t l2 = strlen (n2);
3046 if (l1 != l2 || memcmp (n1, n2, l1)) {
3047 s = malloc (l1 + l2 + 2);
3048 if (s) {
3049 memcpy (s, n2, l2);
3050 s[l2] = '=';
3051 memcpy (s + l2 + 1, n1, l1 + 1);
3052 str_v = caml_copy_string (s);
3053 free (s);
3057 if (str_v == Val_unit) {
3058 str_v = caml_copy_string (n2);
3060 ret_v = caml_alloc_small (1, utext);
3061 Field (ret_v, 0) = str_v;
3062 goto unlock;
3068 unlock:
3069 unlock (__func__);
3071 done:
3072 CAMLreturn (ret_v);
3075 enum { mark_page, mark_block, mark_line, mark_word };
3077 static int uninteresting (int c)
3079 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3080 || ispunct (c);
3083 CAMLprim void ml_clearmark (value ptr_v)
3085 CAMLparam1 (ptr_v);
3086 char *s = String_val (ptr_v);
3087 struct page *page;
3089 if (trylock (__func__)) {
3090 goto done;
3093 page = parse_pointer (__func__, s);
3094 page->fmark.ch = NULL;
3095 page->lmark.ch = NULL;
3097 unlock (__func__);
3098 done:
3099 CAMLreturn0;
3102 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3104 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3105 CAMLlocal1 (ret_v);
3106 fz_rect *b;
3107 struct page *page;
3108 fz_stext_line *line;
3109 fz_stext_block *block;
3110 struct pagedim *pdim;
3111 int mark = Int_val (mark_v);
3112 char *s = String_val (ptr_v);
3113 int x = Int_val (x_v), y = Int_val (y_v);
3115 ret_v = Val_bool (0);
3116 if (trylock (__func__)) {
3117 goto done;
3120 page = parse_pointer (__func__, s);
3121 pdim = &state.pagedims[page->pdimno];
3123 ensuretext (page);
3125 if (mark == mark_page) {
3126 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3127 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3128 ret_v = Val_bool (1);
3129 goto unlock;
3132 x += pdim->bounds.x0;
3133 y += pdim->bounds.y0;
3135 for (block = page->text->first_block; block; block = block->next) {
3136 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3137 b = &block->bbox;
3138 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3139 continue;
3141 if (mark == mark_block) {
3142 page->fmark.ch = block->u.t.first_line->first_char;
3143 page->lmark.ch = block->u.t.last_line->last_char;
3144 ret_v = Val_bool (1);
3145 goto unlock;
3148 for (line = block->u.t.first_line; line; line = line->next) {
3149 fz_stext_char *ch;
3151 b = &line->bbox;
3152 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3153 continue;
3155 if (mark == mark_line) {
3156 page->fmark.ch = line->first_char;
3157 page->lmark.ch = line->last_char;
3158 ret_v = Val_bool (1);
3159 goto unlock;
3162 for (ch = line->first_char; ch; ch = ch->next) {
3163 fz_stext_char *ch2, *first = NULL, *last = NULL;
3164 b = &ch->bbox;
3165 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3166 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3167 if (uninteresting (ch2->c)) first = NULL;
3168 else if (!first) first = ch2;
3170 for (ch2 = ch; ch2; ch2 = ch2->next) {
3171 if (uninteresting (ch2->c)) break;
3172 last = ch2;
3175 page->fmark.ch = first;
3176 page->lmark.ch = last;
3177 ret_v = Val_bool (1);
3178 goto unlock;
3183 unlock:
3184 if (!Bool_val (ret_v)) {
3185 page->fmark.ch = NULL;
3186 page->lmark.ch = NULL;
3188 unlock (__func__);
3190 done:
3191 CAMLreturn (ret_v);
3194 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3196 CAMLparam3 (ptr_v, x_v, y_v);
3197 CAMLlocal2 (ret_v, res_v);
3198 fz_rect *b = NULL;
3199 struct page *page;
3200 struct pagedim *pdim;
3201 fz_stext_block *block;
3202 char *s = String_val (ptr_v);
3203 int x = Int_val (x_v), y = Int_val (y_v);
3205 ret_v = Val_int (0);
3206 if (trylock (__func__)) {
3207 goto done;
3210 page = parse_pointer (__func__, s);
3211 pdim = &state.pagedims[page->pdimno];
3212 x += pdim->bounds.x0;
3213 y += pdim->bounds.y0;
3215 ensuretext (page);
3217 for (block = page->text->first_block; block; block = block->next) {
3218 switch (block->type) {
3219 case FZ_STEXT_BLOCK_TEXT:
3220 b = &block->bbox;
3221 break;
3223 case FZ_STEXT_BLOCK_IMAGE:
3224 b = &block->bbox;
3225 break;
3227 default:
3228 continue;
3231 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3232 break;
3233 b = NULL;
3235 if (b) {
3236 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3237 ret_v = caml_alloc_small (1, 1);
3238 Store_double_field (res_v, 0, (double) b->x0);
3239 Store_double_field (res_v, 1, (double) b->x1);
3240 Store_double_field (res_v, 2, (double) b->y0);
3241 Store_double_field (res_v, 3, (double) b->y1);
3242 Field (ret_v, 0) = res_v;
3244 unlock (__func__);
3246 done:
3247 CAMLreturn (ret_v);
3250 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3252 CAMLparam2 (ptr_v, rect_v);
3253 fz_rect b;
3254 struct page *page;
3255 struct pagedim *pdim;
3256 char *s = String_val (ptr_v);
3257 int x0, x1, y0, y1;
3258 fz_stext_char *ch;
3259 fz_stext_line *line;
3260 fz_stext_block *block;
3261 fz_stext_char *fc, *lc;
3263 if (trylock (__func__)) {
3264 goto done;
3267 page = parse_pointer (__func__, s);
3268 ensuretext (page);
3270 pdim = &state.pagedims[page->pdimno];
3271 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3272 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3273 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3274 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3276 if (y0 > y1) {
3277 int t = y0;
3278 y0 = y1;
3279 y1 = t;
3280 x0 = x1;
3281 x1 = t;
3284 fc = page->fmark.ch;
3285 lc = page->lmark.ch;
3287 for (block = page->text->first_block; block; block = block->next) {
3288 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3289 for (line = block->u.t.first_line; line; line = line->next) {
3290 for (ch = line->first_char; ch; ch = ch->next) {
3291 b = ch->bbox;
3292 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3293 fc = ch;
3295 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3296 lc = ch;
3301 if (x1 < x0 && fc == lc) {
3302 fz_stext_char *t;
3304 t = fc;
3305 fc = lc;
3306 lc = t;
3309 page->fmark.ch = fc;
3310 page->lmark.ch = lc;
3312 unlock (__func__);
3314 done:
3315 CAMLreturn0;
3318 static int pipechar (FILE *f, fz_stext_char *ch)
3320 char buf[4];
3321 int len;
3322 size_t ret;
3324 len = fz_runetochar (buf, ch->c);
3325 ret = fwrite (buf, len, 1, f);
3326 if (ret != 1) {
3327 fprintf (stderr, "failed to write %d bytes ret=%zu: %s\n",
3328 len, ret, strerror (errno));
3329 return -1;
3331 return 0;
3334 #ifdef __CYGWIN__
3335 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3337 caml_failwith ("ml_popen not implemented under Cygwin");
3339 #else
3340 CAMLprim value ml_spawn (value command_v, value fds_v)
3342 CAMLparam2 (command_v, fds_v);
3343 CAMLlocal2 (l_v, tup_v);
3344 int ret, ret1;
3345 pid_t pid = (pid_t) -1;
3346 char *msg = NULL;
3347 value earg_v = Nothing;
3348 posix_spawnattr_t attr;
3349 posix_spawn_file_actions_t fa;
3350 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3352 argv[2] = String_val (command_v);
3354 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3355 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3358 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3359 msg = "posix_spawnattr_init";
3360 goto fail1;
3363 #ifdef POSIX_SPAWN_USEVFORK
3364 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3365 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3366 goto fail;
3368 #endif
3370 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3371 int fd1, fd2;
3373 tup_v = Field (l_v, 0);
3374 fd1 = Int_val (Field (tup_v, 0));
3375 fd2 = Int_val (Field (tup_v, 1));
3376 if (fd2 < 0) {
3377 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3378 msg = "posix_spawn_file_actions_addclose";
3379 earg_v = tup_v;
3380 goto fail;
3383 else {
3384 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3385 msg = "posix_spawn_file_actions_adddup2";
3386 earg_v = tup_v;
3387 goto fail;
3392 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3393 msg = "posix_spawn";
3394 goto fail;
3397 fail:
3398 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3399 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3402 fail1:
3403 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3404 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3405 strerror (ret1));
3408 if (msg)
3409 unix_error (ret, msg, earg_v);
3411 CAMLreturn (Val_int (pid));
3413 #endif
3415 CAMLprim value ml_hassel (value ptr_v)
3417 CAMLparam1 (ptr_v);
3418 CAMLlocal1 (ret_v);
3419 struct page *page;
3420 char *s = String_val (ptr_v);
3422 ret_v = Val_bool (0);
3423 if (trylock (__func__)) {
3424 goto done;
3427 page = parse_pointer (__func__, s);
3428 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3429 unlock (__func__);
3430 done:
3431 CAMLreturn (ret_v);
3434 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3436 CAMLparam2 (fd_v, ptr_v);
3437 FILE *f;
3438 int seen = 0;
3439 struct page *page;
3440 fz_stext_line *line;
3441 fz_stext_block *block;
3442 int fd = Int_val (fd_v);
3443 char *s = String_val (ptr_v);
3445 if (trylock (__func__)) {
3446 goto done;
3449 page = parse_pointer (__func__, s);
3451 if (!page->fmark.ch || !page->lmark.ch) {
3452 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3453 goto unlock;
3456 f = fdopen (fd, "w");
3457 if (!f) {
3458 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3459 fd, strerror (errno));
3460 f = stdout;
3463 for (block = page->text->first_block; block; block = block->next) {
3464 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3465 for (line = block->u.t.first_line; line; line = line->next) {
3466 fz_stext_char *ch;
3467 for (ch = line->first_char; ch; ch = ch->next) {
3468 if (seen || ch == page->fmark.ch) {
3469 do {
3470 pipechar (f, ch);
3471 if (ch == page->lmark.ch) goto close;
3472 } while ((ch = ch->next));
3473 seen = 1;
3474 break;
3477 if (seen) fputc ('\n', f);
3480 close:
3481 if (f != stdout) {
3482 int ret = fclose (f);
3483 fd = -1;
3484 if (ret == -1) {
3485 if (errno != ECHILD) {
3486 fprintf (stderr, "failed to close sel pipe: %s\n",
3487 strerror (errno));
3491 unlock:
3492 unlock (__func__);
3494 done:
3495 if (fd >= 0) {
3496 if (close (fd)) {
3497 fprintf (stderr, "failed to close sel pipe: %s\n",
3498 strerror (errno));
3501 CAMLreturn0;
3504 CAMLprim value ml_getpdimrect (value pagedimno_v)
3506 CAMLparam1 (pagedimno_v);
3507 CAMLlocal1 (ret_v);
3508 int pagedimno = Int_val (pagedimno_v);
3509 fz_rect box;
3511 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3512 if (trylock (__func__)) {
3513 box = fz_empty_rect;
3515 else {
3516 box = state.pagedims[pagedimno].mediabox;
3517 unlock (__func__);
3520 Store_double_field (ret_v, 0, (double) box.x0);
3521 Store_double_field (ret_v, 1, (double) box.x1);
3522 Store_double_field (ret_v, 2, (double) box.y0);
3523 Store_double_field (ret_v, 3, (double) box.y1);
3525 CAMLreturn (ret_v);
3528 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3529 value dw_v, value cols_v)
3531 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3532 CAMLlocal1 (ret_v);
3533 int i;
3534 float zoom = -1.;
3535 float maxh = 0.0;
3536 struct pagedim *p;
3537 float winw = Int_val (winw_v);
3538 float winh = Int_val (winh_v);
3539 float dw = Int_val (dw_v);
3540 float cols = Int_val (cols_v);
3541 float pw = 1.0, ph = 1.0;
3543 if (trylock (__func__)) {
3544 goto done;
3547 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3548 float w = p->pagebox.x1 / cols;
3549 float h = p->pagebox.y1;
3550 if (h > maxh) {
3551 maxh = h;
3552 ph = h;
3553 if (state.fitmodel != FitProportional) pw = w;
3555 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3558 zoom = (((winh / ph) * pw) + dw) / winw;
3559 unlock (__func__);
3560 done:
3561 ret_v = caml_copy_double ((double) zoom);
3562 CAMLreturn (ret_v);
3565 CAMLprim value ml_getmaxw (value unit_v)
3567 CAMLparam1 (unit_v);
3568 CAMLlocal1 (ret_v);
3569 int i;
3570 float maxw = -1.;
3571 struct pagedim *p;
3573 if (trylock (__func__)) {
3574 goto done;
3577 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3578 float w = p->pagebox.x1;
3579 maxw = fz_max (maxw, w);
3582 unlock (__func__);
3583 done:
3584 ret_v = caml_copy_double ((double) maxw);
3585 CAMLreturn (ret_v);
3588 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3590 CAMLparam4 (pt_v, x_v, y_v, string_v);
3591 CAMLlocal1 (ret_v);
3592 int pt = Int_val(pt_v);
3593 int x = Int_val (x_v);
3594 int y = Int_val (y_v);
3595 double w;
3597 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3598 ret_v = caml_copy_double (w);
3599 CAMLreturn (ret_v);
3602 CAMLprim value ml_measure_string (value pt_v, value string_v)
3604 CAMLparam2 (pt_v, string_v);
3605 CAMLlocal1 (ret_v);
3606 int pt = Int_val (pt_v);
3607 double w;
3609 w = (double) measure_string (state.face, pt, String_val (string_v));
3610 ret_v = caml_copy_double (w);
3611 CAMLreturn (ret_v);
3614 CAMLprim value ml_getpagebox (value opaque_v)
3616 CAMLparam1 (opaque_v);
3617 CAMLlocal1 (ret_v);
3618 fz_rect rect;
3619 fz_irect bbox;
3620 fz_matrix ctm;
3621 fz_device *dev;
3622 char *s = String_val (opaque_v);
3623 struct page *page = parse_pointer (__func__, s);
3625 ret_v = caml_alloc_tuple (4);
3626 dev = fz_new_bbox_device (state.ctx, &rect);
3628 ctm = pagectm (page);
3629 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3631 fz_close_device (state.ctx, dev);
3632 fz_drop_device (state.ctx, dev);
3633 fz_round_rect (&bbox, &rect);
3634 Field (ret_v, 0) = Val_int (bbox.x0);
3635 Field (ret_v, 1) = Val_int (bbox.y0);
3636 Field (ret_v, 2) = Val_int (bbox.x1);
3637 Field (ret_v, 3) = Val_int (bbox.y1);
3639 CAMLreturn (ret_v);
3642 CAMLprim void ml_setaalevel (value level_v)
3644 CAMLparam1 (level_v);
3646 state.aalevel = Int_val (level_v);
3647 CAMLreturn0;
3650 #ifndef __COCOA__
3651 #pragma GCC diagnostic push
3652 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3653 #include <X11/Xlib.h>
3654 #include <X11/cursorfont.h>
3655 #pragma GCC diagnostic pop
3657 #ifdef USE_EGL
3658 #include <EGL/egl.h>
3659 #else
3660 #include <GL/glx.h>
3661 #endif
3663 static const int shapes[] = {
3664 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3667 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3669 static struct {
3670 Window wid;
3671 Display *dpy;
3672 #ifdef USE_EGL
3673 EGLContext ctx;
3674 EGLConfig conf;
3675 EGLSurface win;
3676 EGLDisplay *edpy;
3677 #else
3678 GLXContext ctx;
3679 #endif
3680 XVisualInfo *visual;
3681 Cursor curs[CURS_COUNT];
3682 } glx;
3685 static void initcurs (void)
3687 for (size_t n = 0; n < CURS_COUNT; ++n) {
3688 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3692 CAMLprim void ml_setbgcol (value color_v)
3694 CAMLparam1 (color_v);
3695 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3696 CAMLreturn0;
3699 #ifdef USE_EGL
3700 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3702 CAMLparam3 (display_v, wid_v, screen_v);
3703 int major, minor;
3704 int num_conf;
3705 EGLint visid;
3706 EGLint attribs[] = {
3707 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3708 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3709 EGL_NONE
3711 EGLConfig conf;
3713 glx.dpy = XOpenDisplay (String_val (display_v));
3714 if (!glx.dpy) {
3715 caml_failwith ("XOpenDisplay");
3718 eglBindAPI (EGL_OPENGL_API);
3720 glx.edpy = eglGetDisplay (glx.dpy);
3721 if (glx.edpy == EGL_NO_DISPLAY) {
3722 caml_failwith ("eglGetDisplay");
3725 if (!eglInitialize (glx.edpy, &major, &minor)) {
3726 caml_failwith ("eglInitialize");
3729 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3730 !num_conf) {
3731 caml_failwith ("eglChooseConfig");
3734 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3735 caml_failwith ("eglGetConfigAttrib");
3738 glx.conf = conf;
3739 initcurs ();
3741 glx.wid = Int_val (wid_v);
3742 CAMLreturn (Val_int (visid));
3745 CAMLprim void ml_glxcompleteinit (value unit_v)
3747 CAMLparam1 (unit_v);
3749 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3750 if (!glx.ctx) {
3751 caml_failwith ("eglCreateContext");
3754 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3755 glx.wid, NULL);
3756 if (glx.win == EGL_NO_SURFACE) {
3757 caml_failwith ("eglCreateWindowSurface");
3760 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3761 glx.ctx = NULL;
3762 caml_failwith ("eglMakeCurrent");
3764 CAMLreturn0;
3766 #else
3767 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3769 CAMLparam3 (display_v, wid_v, screen_v);
3771 glx.dpy = XOpenDisplay (String_val (display_v));
3772 if (!glx.dpy) {
3773 caml_failwith ("XOpenDisplay");
3776 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3777 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3778 if (!glx.visual) {
3779 XCloseDisplay (glx.dpy);
3780 caml_failwith ("glXChooseVisual");
3783 initcurs ();
3785 glx.wid = Int_val (wid_v);
3786 CAMLreturn (Val_int (glx.visual->visualid));
3789 CAMLprim void ml_glxcompleteinit (value unit_v)
3791 CAMLparam1 (unit_v);
3793 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3794 if (!glx.ctx) {
3795 caml_failwith ("glXCreateContext");
3798 XFree (glx.visual);
3799 glx.visual = NULL;
3801 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3802 glXDestroyContext (glx.dpy, glx.ctx);
3803 glx.ctx = NULL;
3804 caml_failwith ("glXMakeCurrent");
3806 CAMLreturn0;
3808 #endif
3810 CAMLprim void ml_setcursor (value cursor_v)
3812 CAMLparam1 (cursor_v);
3813 size_t cursn = Int_val (cursor_v);
3815 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3816 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3817 XFlush (glx.dpy);
3818 CAMLreturn0;
3821 CAMLprim void ml_swapb (value unit_v)
3823 CAMLparam1 (unit_v);
3824 #ifdef USE_EGL
3825 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3826 caml_failwith ("eglSwapBuffers");
3828 #else
3829 glXSwapBuffers (glx.dpy, glx.wid);
3830 #endif
3831 CAMLreturn0;
3834 #pragma GCC diagnostic push
3835 #ifdef __clang__
3836 #pragma GCC diagnostic ignored "-Wmissing-variable-declarations"
3837 #endif
3838 #include "keysym2ucs.c"
3839 #pragma GCC diagnostic pop
3841 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3843 CAMLparam1 (keysym_v);
3844 CAMLlocal1 (str_v);
3845 KeySym keysym = Int_val (keysym_v);
3846 Rune rune;
3847 int len;
3848 char buf[5];
3850 rune = (Rune) keysym2ucs (keysym);
3851 len = fz_runetochar (buf, rune);
3852 buf[len] = 0;
3853 str_v = caml_copy_string (buf);
3854 CAMLreturn (str_v);
3856 #else
3857 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3859 CAMLparam1 (keysym_v);
3860 CAMLlocal1 (str_v);
3861 long ucs_v = Long_val (keysym_v);
3862 int len;
3863 char buf[5];
3865 len = fz_runetochar (buf, ucs_v);
3866 buf[len] = 0;
3867 str_v = caml_copy_string (buf);
3868 CAMLreturn (str_v);
3870 #endif
3872 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3874 CAMLprim value ml_platform (value unit_v)
3876 CAMLparam1 (unit_v);
3877 CAMLlocal2 (tup_v, arr_v);
3878 int platid = piunknown;
3879 struct utsname buf;
3881 #if defined __linux__
3882 platid = pilinux;
3883 #elif defined __CYGWIN__
3884 platid = picygwin;
3885 #elif defined __DragonFly__ || defined __FreeBSD__
3886 || defined __OpenBSD__ || defined __NetBSD__
3887 platid = pibsd;
3888 #elif defined __sun__
3889 platid = pisun;
3890 #elif defined __APPLE__
3891 platid = piosx;
3892 #endif
3893 if (uname (&buf)) err (1, "uname");
3895 tup_v = caml_alloc_tuple (2);
3897 char const *sar[] = {
3898 buf.sysname,
3899 buf.release,
3900 buf.version,
3901 buf.machine,
3902 NULL
3904 arr_v = caml_copy_string_array (sar);
3906 Field (tup_v, 0) = Val_int (platid);
3907 Field (tup_v, 1) = arr_v;
3908 CAMLreturn (tup_v);
3911 CAMLprim void ml_cloexec (value fd_v)
3913 CAMLparam1 (fd_v);
3914 int fd = Int_val (fd_v);
3916 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3917 uerror ("fcntl", Nothing);
3919 CAMLreturn0;
3922 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3924 CAMLparam2 (w_v, h_v);
3925 CAMLlocal1 (ret_v);
3926 struct bo *pbo;
3927 int w = Int_val (w_v);
3928 int h = Int_val (h_v);
3929 int cs = Int_val (cs_v);
3931 if (state.bo_usable) {
3932 pbo = calloc (sizeof (*pbo), 1);
3933 if (!pbo) {
3934 err (1, "calloc pbo");
3937 switch (cs) {
3938 case 0:
3939 case 1:
3940 pbo->size = w*h*4;
3941 break;
3942 case 2:
3943 pbo->size = w*h*2;
3944 break;
3945 default:
3946 errx (1, "%s: invalid colorspace %d", __func__, cs);
3949 state.glGenBuffersARB (1, &pbo->id);
3950 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3951 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3952 NULL, GL_STREAM_DRAW);
3953 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3954 GL_READ_WRITE);
3955 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3956 if (!pbo->ptr) {
3957 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3958 state.glDeleteBuffersARB (1, &pbo->id);
3959 free (pbo);
3960 ret_v = caml_copy_string ("0");
3962 else {
3963 int res;
3964 char *s;
3966 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3967 if (res < 0) {
3968 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3970 s = malloc (res+1);
3971 if (!s) {
3972 err (1, "malloc %d bytes failed", res+1);
3974 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3975 if (res < 0) {
3976 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3978 ret_v = caml_copy_string (s);
3979 free (s);
3982 else {
3983 ret_v = caml_copy_string ("0");
3985 CAMLreturn (ret_v);
3988 CAMLprim void ml_freepbo (value s_v)
3990 CAMLparam1 (s_v);
3991 char *s = String_val (s_v);
3992 struct tile *tile = parse_pointer (__func__, s);
3994 if (tile->pbo) {
3995 state.glDeleteBuffersARB (1, &tile->pbo->id);
3996 tile->pbo->id = -1;
3997 tile->pbo->ptr = NULL;
3998 tile->pbo->size = -1;
4000 CAMLreturn0;
4003 CAMLprim void ml_unmappbo (value s_v)
4005 CAMLparam1 (s_v);
4006 char *s = String_val (s_v);
4007 struct tile *tile = parse_pointer (__func__, s);
4009 if (tile->pbo) {
4010 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4011 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4012 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4014 tile->pbo->ptr = NULL;
4015 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4017 CAMLreturn0;
4020 static void setuppbo (void)
4022 #ifdef __COCOA__
4023 static CFBundleRef framework = NULL;
4024 if (framework == NULL)
4025 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
4026 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
4027 #else
4028 #ifdef USE_EGL
4029 #define GGPA(n) (*(void (**) (void)) &state.n = eglGetProcAddress (#n))
4030 #else
4031 #define GGPA(n) (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
4032 #endif
4033 state.bo_usable = GGPA (glBindBufferARB)
4034 && GGPA (glUnmapBufferARB)
4035 && GGPA (glMapBufferARB)
4036 && GGPA (glBufferDataARB)
4037 && GGPA (glGenBuffersARB)
4038 && GGPA (glDeleteBuffersARB);
4039 #endif
4040 #undef GGPA
4043 CAMLprim value ml_bo_usable (value unit_v)
4045 CAMLparam1 (unit_v);
4046 CAMLreturn (Val_bool (state.bo_usable));
4049 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4051 CAMLparam3 (ptr_v, x_v, y_v);
4052 CAMLlocal2 (ret_v, tup_v);
4053 struct page *page;
4054 char *s = String_val (ptr_v);
4055 int x = Int_val (x_v), y = Int_val (y_v);
4056 struct pagedim *pdim;
4057 fz_point p;
4058 fz_matrix ctm;
4060 page = parse_pointer (__func__, s);
4061 pdim = &state.pagedims[page->pdimno];
4063 ret_v = Val_int (0);
4064 if (trylock (__func__)) {
4065 goto done;
4068 if (pdf_specifics (state.ctx, state.doc)) {
4069 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4070 ctm = state.pagedims[page->pdimno].tctm;
4072 else {
4073 ctm = fz_identity;
4075 p.x = x + pdim->bounds.x0;
4076 p.y = y + pdim->bounds.y0;
4078 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4079 fz_invert_matrix (&ctm, &ctm);
4080 fz_transform_point (&p, &ctm);
4082 tup_v = caml_alloc_tuple (2);
4083 ret_v = caml_alloc_small (1, 1);
4084 Field (tup_v, 0) = Val_int (p.x);
4085 Field (tup_v, 1) = Val_int (p.y);
4086 Field (ret_v, 0) = tup_v;
4088 unlock (__func__);
4089 done:
4090 CAMLreturn (ret_v);
4093 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4094 value x_v, value y_v)
4096 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4097 CAMLlocal1 (ret_v);
4098 struct page *page;
4099 char *s = String_val (ptr_v);
4100 int pageno = Int_val (pageno_v);
4101 int pdimno = Int_val (pdimno_v);
4102 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
4103 struct pagedim *pdim;
4104 fz_point p;
4105 fz_matrix ctm;
4107 ret_v = Val_int (0);
4108 lock (__func__);
4110 if (!*s) {
4111 page = loadpage (pageno, pdimno);
4113 else {
4114 page = parse_pointer (__func__, s);
4116 pdim = &state.pagedims[pdimno];
4118 if (pdf_specifics (state.ctx, state.doc)) {
4119 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4120 ctm = state.pagedims[page->pdimno].tctm;
4122 else {
4123 ctm = fz_identity;
4125 p.x = x + pdim->bounds.x0;
4126 p.y = y + pdim->bounds.y0;
4128 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4129 fz_transform_point (&p, &ctm);
4131 ret_v = caml_alloc_tuple (2);
4132 Field (ret_v, 0) = caml_copy_double ((double) p.x);
4133 Field (ret_v, 1) = caml_copy_double ((double) p.y);
4135 if (!*s) {
4136 freepage (page);
4138 unlock (__func__);
4139 CAMLreturn (ret_v);
4142 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4143 value contents_v)
4145 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4146 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4148 if (pdf) {
4149 pdf_annot *annot;
4150 struct page *page;
4151 fz_point p;
4152 char *s = String_val (ptr_v);
4154 page = parse_pointer (__func__, s);
4155 annot = pdf_create_annot (state.ctx,
4156 pdf_page_from_fz_page (state.ctx,
4157 page->fzpage),
4158 PDF_ANNOT_TEXT);
4159 p.x = Int_val (x_v);
4160 p.y = Int_val (y_v);
4161 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4162 pdf_set_text_annot_position (state.ctx, annot, p);
4163 state.dirty = 1;
4165 CAMLreturn0;
4168 CAMLprim void ml_delannot (value ptr_v, value n_v)
4170 CAMLparam2 (ptr_v, n_v);
4171 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4173 if (pdf) {
4174 struct page *page;
4175 char *s = String_val (ptr_v);
4176 struct slink *slink;
4178 page = parse_pointer (__func__, s);
4179 slink = &page->slinks[Int_val (n_v)];
4180 pdf_delete_annot (state.ctx,
4181 pdf_page_from_fz_page (state.ctx, page->fzpage),
4182 (pdf_annot *) slink->u.annot);
4183 state.dirty = 1;
4185 CAMLreturn0;
4188 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4190 CAMLparam3 (ptr_v, n_v, str_v);
4191 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4193 if (pdf) {
4194 struct page *page;
4195 char *s = String_val (ptr_v);
4196 struct slink *slink;
4198 page = parse_pointer (__func__, s);
4199 slink = &page->slinks[Int_val (n_v)];
4200 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4201 String_val (str_v));
4202 state.dirty = 1;
4204 CAMLreturn0;
4207 CAMLprim value ml_hasunsavedchanges (value unit_v)
4209 CAMLparam1 (unit_v);
4210 CAMLreturn (Val_bool (state.dirty));
4213 CAMLprim void ml_savedoc (value path_v)
4215 CAMLparam1 (path_v);
4216 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4218 if (pdf) {
4219 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4221 CAMLreturn0;
4224 static void makestippletex (void)
4226 const char pixels[] = "\xff\xff\0\0";
4227 glGenTextures (1, &state.stid);
4228 glBindTexture (GL_TEXTURE_1D, state.stid);
4229 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4230 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4231 glTexImage1D (
4232 GL_TEXTURE_1D,
4234 GL_ALPHA,
4237 GL_ALPHA,
4238 GL_UNSIGNED_BYTE,
4239 pixels
4243 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4245 return caml_copy_string (FZ_VERSION);
4248 CAMLprim void ml_init (value csock_v, value params_v)
4250 CAMLparam2 (csock_v, params_v);
4251 CAMLlocal2 (trim_v, fuzz_v);
4252 int ret;
4253 int texcount;
4254 char *fontpath;
4255 int colorspace;
4256 int mustoresize;
4257 int haspboext;
4259 /* Without following call to setlocale mbstowcs fails for, at
4260 least, strings containing chinese symbols (δΈ­ for instance)
4261 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4262 wide character" as the reason of failure and with macOS
4263 producing bogus output) */
4264 if (setlocale (LC_CTYPE, "")) {
4265 /* Following two lines were taken from dvtm/vt.c */
4266 const char *cset = nl_langinfo (CODESET);
4267 state.utf8cs = !strcmp (cset, "UTF-8");
4269 else {
4270 fprintf (stderr, "setlocale failed\n");
4273 state.csock = Int_val (csock_v);
4274 state.rotate = Int_val (Field (params_v, 0));
4275 state.fitmodel = Int_val (Field (params_v, 1));
4276 trim_v = Field (params_v, 2);
4277 texcount = Int_val (Field (params_v, 3));
4278 state.sliceheight = Int_val (Field (params_v, 4));
4279 mustoresize = Int_val (Field (params_v, 5));
4280 colorspace = Int_val (Field (params_v, 6));
4281 fontpath = String_val (Field (params_v, 7));
4283 if (caml_string_length (Field (params_v, 8)) > 0) {
4284 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4286 if (!state.trimcachepath) {
4287 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4288 strerror (errno));
4292 haspboext = Bool_val (Field (params_v, 9));
4294 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4295 fz_register_document_handlers (state.ctx);
4297 state.trimmargins = Bool_val (Field (trim_v, 0));
4298 fuzz_v = Field (trim_v, 1);
4299 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4300 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4301 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4302 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4304 set_tex_params (colorspace);
4306 if (*fontpath) {
4307 state.face = load_font (fontpath);
4309 else {
4310 int len;
4311 const unsigned char *data;
4313 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4314 state.face = load_builtin_font (data, len);
4316 if (!state.face) _exit (1);
4318 realloctexts (texcount);
4320 if (haspboext) {
4321 setuppbo ();
4324 makestippletex ();
4326 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4327 if (ret) {
4328 errx (1, "pthread_create: %s", strerror (ret));
4331 CAMLreturn0;
4334 #if FIXME || !FIXME
4335 static void OPTIMIZE_ATTR (0) UNUSED_ATTR refmacs (void) {}
4336 #endif