Guard -Wreserved-id-macro
[llpp.git] / link.c
blob105defcea0e35f1785db95a82b68f075b6a3ad3b
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 static struct {
233 int sliceheight;
234 struct pagedim *pagedims;
235 int pagecount;
236 int pagedimcount;
237 fz_document *doc;
238 fz_context *ctx;
239 int w, h;
241 int texindex;
242 int texcount;
243 GLuint *texids;
245 GLenum texiform;
246 GLenum texform;
247 GLenum texty;
249 fz_colorspace *colorspace;
251 struct {
252 int w, h;
253 struct slice *slice;
254 } *texowners;
256 int rotate;
257 enum { FitWidth, FitProportional, FitPage };
258 int fitmodel;
259 int trimmargins;
260 int needoutline;
261 int gen;
262 int aalevel;
264 int trimanew;
265 fz_irect trimfuzz;
266 fz_pixmap *pig;
268 pthread_t thread;
269 int csock;
270 FT_Face face;
272 char *trimcachepath;
273 int cxack;
274 int dirty;
276 GLuint stid;
278 int bo_usable;
279 GLuint boid;
281 void (*glBindBufferARB) (GLenum, GLuint);
282 GLboolean (*glUnmapBufferARB) (GLenum);
283 void *(*glMapBufferARB) (GLenum, GLenum);
284 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
285 void (*glGenBuffersARB) (GLsizei, GLuint *);
286 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
288 GLfloat texcoords[8];
289 GLfloat vertices[16];
291 #ifdef CACHE_PAGEREFS
292 struct {
293 int idx;
294 int count;
295 pdf_obj **objs;
296 pdf_document *pdf;
297 } pdflut;
298 #endif
299 int utf8cs;
300 } state;
302 struct bo {
303 GLuint id;
304 void *ptr;
305 size_t size;
308 #pragma GCC diagnostic ignored "-Wdouble-promotion"
309 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
311 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
314 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
316 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
319 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
321 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
322 m.a, m.b, m.c, m.d, m.e, m.f);
324 #pragma GCC diagnostic error "-Wdouble-promotion"
326 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
328 static void lock (const char *cap)
330 int ret = pthread_mutex_lock (&mutex);
331 if (ret) {
332 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
336 static void unlock (const char *cap)
338 int ret = pthread_mutex_unlock (&mutex);
339 if (ret) {
340 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
344 static int trylock (const char *cap)
346 int ret = pthread_mutex_trylock (&mutex);
347 if (ret && ret != EBUSY) {
348 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
350 return ret == EBUSY;
353 static void *parse_pointer (const char *cap, const char *s)
355 int ret;
356 void *ptr;
358 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
359 if (ret != 1) {
360 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
362 return ptr;
365 static double now (void)
367 struct timeval tv;
369 if (gettimeofday (&tv, NULL)) {
370 err (1, "gettimeofday");
372 return tv.tv_sec + tv.tv_usec*1e-6;
375 static int hasdata (void)
377 int ret, avail;
378 ret = ioctl (state.csock, FIONREAD, &avail);
379 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
380 return avail > 0;
383 CAMLprim value ml_hasdata (value fd_v)
385 CAMLparam1 (fd_v);
386 int ret, avail;
388 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
389 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
390 CAMLreturn (Val_bool (avail > 0));
393 static void readdata (int fd, void *p, int size)
395 ssize_t n;
397 again:
398 n = read (fd, p, size);
399 if (n - size) {
400 if (n < 0 && errno == EINTR) goto again;
401 if (!n) errx (1, "EOF while reading");
402 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
406 static void writedata (int fd, char *p, int size)
408 ssize_t n;
409 uint32_t size4 = size;
410 struct iovec iov[2] = {
411 { .iov_base = &size4, .iov_len = 4 },
412 { .iov_base = p, .iov_len = size }
415 again:
416 n = writev (fd, iov, 2);
417 if (n < 0 && errno == EINTR) goto again;
418 if (n - size - 4) {
419 if (!n) errx (1, "EOF while writing data");
420 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
424 static int readlen (int fd)
426 uint32_t u;
427 readdata (fd, &u, 4);
428 return u;
431 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
433 CAMLparam3 (fd_v, bytes_v, len_v);
434 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
435 CAMLreturn0;
438 CAMLprim value ml_rcmd (value fd_v)
440 CAMLparam1 (fd_v);
441 CAMLlocal1 (strdata_v);
442 int fd = Int_val (fd_v);
443 int len = readlen (fd);
444 strdata_v = caml_alloc_string (len);
445 readdata (fd, String_val (strdata_v), len);
446 CAMLreturn (strdata_v);
449 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
451 char fbuf[64];
452 int size = sizeof (fbuf), len;
453 va_list ap;
454 char *buf = fbuf;
456 for (;;) {
457 va_start (ap, fmt);
458 len = vsnprintf (buf, size, fmt, ap);
459 va_end (ap);
461 if (len > -1) {
462 if (len < size - 4) {
463 writedata (state.csock, buf, len);
464 break;
466 else size = len + 5;
468 else {
469 err (1, "vsnprintf for `%s' failed", fmt);
471 buf = realloc (buf == fbuf ? NULL : buf, size);
472 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
474 if (buf != fbuf) free (buf);
477 static void closedoc (void)
479 #ifdef CACHE_PAGEREFS
480 if (state.pdflut.objs) {
481 for (int i = 0; i < state.pdflut.count; ++i) {
482 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
484 free (state.pdflut.objs);
485 state.pdflut.objs = NULL;
486 state.pdflut.idx = 0;
488 #endif
489 if (state.doc) {
490 fz_drop_document (state.ctx, state.doc);
491 state.doc = NULL;
495 static int openxref (char *filename, char *password)
497 for (int i = 0; i < state.texcount; ++i) {
498 state.texowners[i].w = -1;
499 state.texowners[i].slice = NULL;
502 closedoc ();
504 state.dirty = 0;
505 if (state.pagedims) {
506 free (state.pagedims);
507 state.pagedims = NULL;
509 state.pagedimcount = 0;
511 fz_set_aa_level (state.ctx, state.aalevel);
512 state.doc = fz_open_document (state.ctx, filename);
513 if (fz_needs_password (state.ctx, state.doc)) {
514 if (password && !*password) {
515 printd ("pass");
516 return 0;
518 else {
519 int ok = fz_authenticate_password (state.ctx, state.doc, password);
520 if (!ok) {
521 printd ("pass fail");
522 return 0;
526 state.pagecount = fz_count_pages (state.ctx, state.doc);
527 return 1;
530 static void pdfinfo (void)
532 struct { char *tag; char *name; } metatbl[] = {
533 { FZ_META_INFO_TITLE, "Title" },
534 { FZ_META_INFO_AUTHOR, "Author" },
535 { FZ_META_FORMAT, "Format" },
536 { FZ_META_ENCRYPTION, "Encryption" },
537 { "info:Creator", "Creator" },
538 { "info:Producer", "Producer" },
539 { "info:CreationDate", "Creation date" },
541 int len = 0;
542 char *buf = NULL;
544 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
545 int need;
546 again:
547 need = fz_lookup_metadata (state.ctx, state.doc,
548 metatbl[i].tag, buf, len);
549 if (need > 0) {
550 if (need <= len) {
551 printd ("info %s\t%s", metatbl[i].name, buf);
553 else {
554 buf = realloc (buf, need + 1);
555 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
556 len = need + 1;
557 goto again;
561 free (buf);
563 printd ("infoend");
566 static void unlinktile (struct tile *tile)
568 for (int i = 0; i < tile->slicecount; ++i) {
569 struct slice *s = &tile->slices[i];
571 if (s->texindex != -1) {
572 if (state.texowners[s->texindex].slice == s) {
573 state.texowners[s->texindex].slice = NULL;
579 static void freepage (struct page *page)
581 if (!page) return;
582 if (page->text) {
583 fz_drop_stext_page (state.ctx, page->text);
585 if (page->slinks) {
586 free (page->slinks);
588 fz_drop_display_list (state.ctx, page->dlist);
589 fz_drop_page (state.ctx, page->fzpage);
590 free (page);
593 static void freetile (struct tile *tile)
595 unlinktile (tile);
596 if (!tile->pbo) {
597 #ifndef PIGGYBACK
598 fz_drop_pixmap (state.ctx, tile->pixmap);
599 #else
600 if (state.pig) {
601 fz_drop_pixmap (state.ctx, state.pig);
603 state.pig = tile->pixmap;
604 #endif
606 else {
607 free (tile->pbo);
608 fz_drop_pixmap (state.ctx, tile->pixmap);
610 free (tile);
613 #ifdef __ALTIVEC__
614 #include <stdint.h>
615 #include <altivec.h>
617 static int cacheline32bytes;
619 static void __attribute__ ((constructor)) clcheck (void)
621 char **envp = environ;
622 unsigned long *auxv;
624 while (*envp++);
626 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
627 if (*auxv == 19) {
628 cacheline32bytes = auxv[1] == 32;
629 return;
634 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
636 size_t size = pixmap->w * pixmap->h * pixmap->n;
637 if (cacheline32bytes && size > 32) {
638 intptr_t a1, a2, diff;
639 size_t sizea, i;
640 vector unsigned char v = vec_splat_u8 (-1);
641 vector unsigned char *p;
643 a1 = a2 = (intptr_t) pixmap->samples;
644 a2 = (a1 + 31) & ~31;
645 diff = a2 - a1;
646 sizea = size - diff;
647 p = (void *) a2;
649 while (a1 != a2) *(char *) a1++ = 0xff;
650 for (i = 0; i < (sizea & ~31); i += 32) {
651 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
652 vec_st (v, i, p);
653 vec_st (v, i + 16, p);
655 while (i < sizea) *((char *) a1 + i++) = 0xff;
657 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
659 #else
660 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
661 #endif
663 static void trimctm (pdf_page *page, int pindex)
665 fz_matrix ctm;
666 struct pagedim *pdim = &state.pagedims[pindex];
668 if (!page) return;
669 if (!pdim->tctmready) {
670 fz_rect realbox, mediabox;
671 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
673 fz_rotate (&rm, -pdim->rotate);
674 fz_scale (&sm, 1, -1);
675 fz_concat (&ctm, &rm, &sm);
676 realbox = pdim->mediabox;
677 fz_transform_rect (&realbox, &ctm);
678 fz_translate (&tm, -realbox.x0, -realbox.y0);
679 fz_concat (&ctm1, &ctm, &tm);
680 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
681 fz_invert_matrix (&im, &page_ctm);
682 fz_concat (&ctm, &im, &ctm1);
683 pdim->tctm = ctm;
684 pdim->tctmready = 1;
688 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
690 fz_matrix ctm, tm;
691 ptrdiff_t pdimno = pdim - state.pagedims;
693 ARSERT (pdim - state.pagedims < INT_MAX);
694 if (pdf_specifics (state.ctx, state.doc)) {
695 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
696 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
698 else {
699 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
700 fz_concat (&ctm, &tm, &pdim->ctm);
702 return ctm;
705 static fz_matrix pagectm (struct page *page)
707 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
710 static void *loadpage (int pageno, int pindex)
712 fz_device *dev;
713 struct page *page;
715 page = calloc (sizeof (struct page), 1);
716 if (!page) {
717 err (1, "calloc page %d", pageno);
720 page->dlist = fz_new_display_list (state.ctx, NULL);
721 dev = fz_new_list_device (state.ctx, page->dlist);
722 fz_try (state.ctx) {
723 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
724 fz_run_page (state.ctx, page->fzpage, dev,
725 &fz_identity, NULL);
727 fz_catch (state.ctx) {
728 page->fzpage = NULL;
730 fz_close_device (state.ctx, dev);
731 fz_drop_device (state.ctx, dev);
733 page->pdimno = pindex;
734 page->pageno = pageno;
735 page->sgen = state.gen;
736 page->agen = state.gen;
737 page->tgen = state.gen;
738 return page;
741 static struct tile *alloctile (int h)
743 int slicecount;
744 size_t tilesize;
745 struct tile *tile;
747 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
748 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
749 tile = calloc (tilesize, 1);
750 if (!tile) {
751 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
753 for (int i = 0; i < slicecount; ++i) {
754 int sh = fz_mini (h, state.sliceheight);
755 tile->slices[i].h = sh;
756 tile->slices[i].texindex = -1;
757 h -= sh;
759 tile->slicecount = slicecount;
760 tile->sliceheight = state.sliceheight;
761 return tile;
764 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
765 struct bo *pbo)
767 fz_rect rect;
768 fz_irect bbox;
769 fz_matrix ctm;
770 fz_device *dev;
771 struct tile *tile;
772 struct pagedim *pdim;
774 tile = alloctile (h);
775 pdim = &state.pagedims[page->pdimno];
777 bbox = pdim->bounds;
778 bbox.x0 += x;
779 bbox.y0 += y;
780 bbox.x1 = bbox.x0 + w;
781 bbox.y1 = bbox.y0 + h;
783 if (state.pig) {
784 if (state.pig->w == w
785 && state.pig->h == h
786 && state.pig->colorspace == state.colorspace) {
787 tile->pixmap = state.pig;
788 tile->pixmap->x = bbox.x0;
789 tile->pixmap->y = bbox.y0;
791 else {
792 fz_drop_pixmap (state.ctx, state.pig);
794 state.pig = NULL;
796 if (!tile->pixmap) {
797 if (pbo) {
798 tile->pixmap =
799 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
800 &bbox, NULL, 1, pbo->ptr);
801 tile->pbo = pbo;
803 else {
804 tile->pixmap =
805 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
806 NULL, 1);
810 tile->w = w;
811 tile->h = h;
812 clearpixmap (tile->pixmap);
814 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
815 ctm = pagectm (page);
816 fz_rect_from_irect (&rect, &bbox);
817 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
818 fz_close_device (state.ctx, dev);
819 fz_drop_device (state.ctx, dev);
821 return tile;
824 #ifdef CACHE_PAGEREFS
825 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
826 thanks to Robin Watts */
827 static void
828 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
830 fz_context *ctx = state.ctx; /* doc->ctx; */
831 pdf_obj *kids;
832 int len;
834 if (state.pdflut.idx == state.pagecount) return;
836 kids = pdf_dict_gets (ctx, node, "Kids");
837 len = pdf_array_len (ctx, kids);
839 if (len == 0)
840 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
842 if (pdf_mark_obj (ctx, node))
843 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
844 for (int i = 0; i < len; i++) {
845 pdf_obj *kid = pdf_array_get (ctx, kids, i);
846 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
847 if (*type
848 ? !strcmp (type, "Pages")
849 : pdf_dict_gets (ctx, kid, "Kids")
850 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
851 pdf_collect_pages (doc, kid);
853 else {
854 if (*type
855 ? strcmp (type, "Page") != 0
856 : !pdf_dict_gets (ctx, kid, "MediaBox"))
857 fz_warn (ctx, "non-page object in page tree (%s)", type);
858 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
861 pdf_unmark_obj (ctx, node);
864 static void
865 pdf_load_page_objs (pdf_document *doc)
867 pdf_obj *root = pdf_dict_gets (state.ctx,
868 pdf_trailer (state.ctx, doc), "Root");
869 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
871 if (!node)
872 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
874 state.pdflut.idx = 0;
875 pdf_collect_pages (doc, node);
877 #endif
879 static void initpdims (int wthack)
881 double start, end;
882 FILE *trimf = NULL;
883 fz_rect rootmediabox = fz_empty_rect;
884 int pageno, trim, show;
885 int trimw = 0, cxcount;
886 fz_context *ctx = state.ctx;
887 pdf_document *pdf = pdf_specifics (ctx, state.doc);
889 fz_var (trimw);
890 fz_var (trimf);
891 fz_var (cxcount);
892 start = now ();
894 if (state.trimmargins && state.trimcachepath) {
895 trimf = fopen (state.trimcachepath, "rb");
896 if (!trimf) {
897 trimf = fopen (state.trimcachepath, "wb");
898 trimw = 1;
902 if (state.trimmargins || pdf || !state.cxack)
903 cxcount = state.pagecount;
904 else
905 cxcount = fz_mini (state.pagecount, 1);
907 if (pdf) {
908 pdf_obj *obj;
909 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
910 "Root/Pages/MediaBox");
911 pdf_to_rect (ctx, obj, &rootmediabox);
914 #ifdef CACHE_PAGEREFS
915 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
916 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
917 if (!state.pdflut.objs) {
918 err (1, "malloc pageobjs %zu %d %zu failed",
919 sizeof (*state.pdflut.objs), cxcount,
920 sizeof (*state.pdflut.objs) * cxcount);
922 state.pdflut.count = cxcount;
923 pdf_load_page_objs (pdf);
924 state.pdflut.pdf = pdf;
926 #endif
928 for (pageno = 0; pageno < cxcount; ++pageno) {
929 int rotate = 0;
930 struct pagedim *p;
931 fz_rect mediabox = fz_empty_rect;
933 fz_var (rotate);
934 if (pdf) {
935 pdf_obj *pageref, *pageobj;
937 #ifdef CACHE_PAGEREFS
938 pageref = state.pdflut.objs[pageno];
939 #else
940 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
941 #endif
942 pageobj = pdf_resolve_indirect (ctx, pageref);
943 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
945 if (state.trimmargins) {
946 pdf_obj *obj;
947 pdf_page *page;
949 fz_try (ctx) {
950 page = pdf_load_page (ctx, pdf, pageno);
951 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
952 trim = state.trimanew || !obj;
953 if (trim) {
954 fz_rect rect;
955 fz_device *dev;
956 fz_matrix ctm, page_ctm;
958 dev = fz_new_bbox_device (ctx, &rect);
959 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
960 fz_invert_matrix (&ctm, &page_ctm);
961 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
962 fz_close_device (ctx, dev);
963 fz_drop_device (ctx, dev);
965 rect.x0 += state.trimfuzz.x0;
966 rect.x1 += state.trimfuzz.x1;
967 rect.y0 += state.trimfuzz.y0;
968 rect.y1 += state.trimfuzz.y1;
969 fz_transform_rect (&rect, &ctm);
970 fz_intersect_rect (&rect, &mediabox);
972 if (!fz_is_empty_rect (&rect)) {
973 mediabox = rect;
976 obj = pdf_new_array (ctx, pdf, 4);
977 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
978 mediabox.x0));
979 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
980 mediabox.y0));
981 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
982 mediabox.x1));
983 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
984 mediabox.y1));
985 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
987 else {
988 mediabox.x0 = pdf_to_real (ctx,
989 pdf_array_get (ctx, obj, 0));
990 mediabox.y0 = pdf_to_real (ctx,
991 pdf_array_get (ctx, obj, 1));
992 mediabox.x1 = pdf_to_real (ctx,
993 pdf_array_get (ctx, obj, 2));
994 mediabox.y1 = pdf_to_real (ctx,
995 pdf_array_get (ctx, obj, 3));
998 fz_drop_page (ctx, &page->super);
999 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
1000 if (show) {
1001 printd ("progress %f Trimming %d",
1002 (double) (pageno + 1) / state.pagecount,
1003 pageno + 1);
1006 fz_catch (ctx) {
1007 fprintf (stderr, "failed to load page %d\n", pageno+1);
1010 else {
1011 int empty = 0;
1012 fz_rect cropbox;
1014 pdf_to_rect (ctx,
1015 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1016 &mediabox);
1017 if (fz_is_empty_rect (&mediabox)) {
1018 mediabox.x0 = 0;
1019 mediabox.y0 = 0;
1020 mediabox.x1 = 612;
1021 mediabox.y1 = 792;
1022 empty = 1;
1025 pdf_to_rect (ctx,
1026 pdf_dict_gets (ctx, pageobj, "CropBox"),
1027 &cropbox);
1028 if (!fz_is_empty_rect (&cropbox)) {
1029 if (empty) {
1030 mediabox = cropbox;
1032 else {
1033 fz_intersect_rect (&mediabox, &cropbox);
1036 else {
1037 if (empty) {
1038 if (fz_is_empty_rect (&rootmediabox)) {
1039 fprintf (stderr,
1040 "cannot find page size for page %d\n",
1041 pageno+1);
1043 else {
1044 mediabox = rootmediabox;
1050 else {
1051 if (state.trimmargins && trimw) {
1052 fz_page *page;
1054 fz_try (ctx) {
1055 page = fz_load_page (ctx, state.doc, pageno);
1056 fz_bound_page (ctx, page, &mediabox);
1057 if (state.trimmargins) {
1058 fz_rect rect;
1059 fz_device *dev;
1061 dev = fz_new_bbox_device (ctx, &rect);
1062 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1063 fz_close_device (ctx, dev);
1064 fz_drop_device (ctx, dev);
1066 rect.x0 += state.trimfuzz.x0;
1067 rect.x1 += state.trimfuzz.x1;
1068 rect.y0 += state.trimfuzz.y0;
1069 rect.y1 += state.trimfuzz.y1;
1070 fz_intersect_rect (&rect, &mediabox);
1072 if (!fz_is_empty_rect (&rect)) {
1073 mediabox = rect;
1076 fz_drop_page (ctx, page);
1077 if (!state.cxack) {
1078 printd ("progress %f loading %d",
1079 (double) (pageno + 1) / state.pagecount,
1080 pageno + 1);
1083 fz_catch (ctx) {
1085 if (trimf) {
1086 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1087 if (n - 1) {
1088 err (1, "fwrite trim mediabox");
1092 else {
1093 if (trimf) {
1094 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1095 if (n - 1) {
1096 err (1, "fread trim mediabox %d", pageno);
1099 else {
1100 fz_page *page;
1101 fz_try (ctx) {
1102 page = fz_load_page (ctx, state.doc, pageno);
1103 fz_bound_page (ctx, page, &mediabox);
1104 fz_drop_page (ctx, page);
1106 show = !state.trimmargins && pageno % 20 == 0;
1107 if (show) {
1108 printd ("progress %f Gathering dimensions %d",
1109 (double) (pageno) / state.pagecount,
1110 pageno);
1113 fz_catch (ctx) {
1114 fprintf (stderr, "failed to load page %d\n", pageno);
1120 if (state.pagedimcount == 0
1121 || ((void) (p = &state.pagedims[state.pagedimcount-1])
1122 , p->rotate != rotate)
1123 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1124 size_t size;
1126 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1127 state.pagedims = realloc (state.pagedims, size);
1128 if (!state.pagedims) {
1129 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1130 size, state.pagedimcount + 1);
1133 p = &state.pagedims[state.pagedimcount++];
1134 p->rotate = rotate;
1135 p->mediabox = mediabox;
1136 p->pageno = pageno;
1139 end = now ();
1140 if (!wthack) {
1141 printd ("progress 1 %s %d pages in %f seconds",
1142 state.trimmargins ? "Trimmed" : "Processed",
1143 state.pagecount, end - start);
1145 state.trimanew = 0;
1146 if (trimf) {
1147 if (fclose (trimf)) {
1148 err (1, "fclose");
1153 static void layout (void)
1155 int pindex;
1156 fz_rect box;
1157 fz_matrix ctm, rm;
1158 struct pagedim *p = NULL;
1159 float zw, w, maxw = 0.0, zoom = 1.0;
1161 if (state.pagedimcount == 0) return;
1163 switch (state.fitmodel) {
1164 case FitProportional:
1165 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1166 float x0, x1;
1168 p = &state.pagedims[pindex];
1169 fz_rotate (&rm, p->rotate + state.rotate);
1170 box = p->mediabox;
1171 fz_transform_rect (&box, &rm);
1173 x0 = fz_min (box.x0, box.x1);
1174 x1 = fz_max (box.x0, box.x1);
1176 w = x1 - x0;
1177 maxw = fz_max (w, maxw);
1178 zoom = state.w / maxw;
1180 break;
1182 case FitPage:
1183 maxw = state.w;
1184 break;
1186 case FitWidth:
1187 break;
1189 default:
1190 ARSERT (0 && state.fitmodel);
1193 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1194 fz_rect rect;
1195 fz_matrix tm, sm;
1197 p = &state.pagedims[pindex];
1198 fz_rotate (&ctm, state.rotate);
1199 fz_rotate (&rm, p->rotate + state.rotate);
1200 box = p->mediabox;
1201 fz_transform_rect (&box, &rm);
1202 w = box.x1 - box.x0;
1203 switch (state.fitmodel) {
1204 case FitProportional:
1205 p->left = (int) (((maxw - w) * zoom) / 2.f);
1206 break;
1207 case FitPage:
1209 float zh, h;
1210 zw = maxw / w;
1211 h = box.y1 - box.y0;
1212 zh = state.h / h;
1213 zoom = fz_min (zw, zh);
1214 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1216 break;
1217 case FitWidth:
1218 p->left = 0;
1219 zoom = state.w / w;
1220 break;
1223 fz_scale (&p->zoomctm, zoom, zoom);
1224 fz_concat (&ctm, &p->zoomctm, &ctm);
1226 fz_rotate (&rm, p->rotate);
1227 p->pagebox = p->mediabox;
1228 fz_transform_rect (&p->pagebox, &rm);
1229 p->pagebox.x1 -= p->pagebox.x0;
1230 p->pagebox.y1 -= p->pagebox.y0;
1231 p->pagebox.x0 = 0;
1232 p->pagebox.y0 = 0;
1233 rect = p->pagebox;
1234 fz_transform_rect (&rect, &ctm);
1235 fz_round_rect (&p->bounds, &rect);
1236 p->ctm = ctm;
1238 fz_translate (&tm, 0, -p->mediabox.y1);
1239 fz_scale (&sm, zoom, -zoom);
1240 fz_concat (&ctm, &tm, &sm);
1242 p->tctmready = 0;
1245 do {
1246 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1247 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1248 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1249 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1250 int boundw = x1 - x0;
1251 int boundh = y1 - y0;
1253 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1254 } while (p-- != state.pagedims);
1257 struct pagedim *pdimofpageno (int pageno)
1259 struct pagedim *pdim = state.pagedims;
1261 for (int i = 0; i < state.pagedimcount; ++i) {
1262 if (state.pagedims[i].pageno > pageno)
1263 break;
1264 pdim = &state.pagedims[i];
1266 return pdim;
1269 static void recurse_outline (fz_outline *outline, int level)
1271 while (outline) {
1272 if (outline->page >= 0) {
1273 fz_point p = {.x = outline->x, .y = outline->y};
1274 struct pagedim *pdim = pdimofpageno (outline->page);
1275 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1276 fz_transform_point (&p, &pdim->ctm);
1277 printd ("o %d %d %d %d %s",
1278 level, outline->page, (int) p.y, h, outline->title);
1280 else {
1281 printd ("on %d %s", level, outline->title);
1283 if (outline->down) {
1284 recurse_outline (outline->down, level + 1);
1286 outline = outline->next;
1290 static void process_outline (void)
1292 fz_outline *outline;
1294 if (!state.needoutline || !state.pagedimcount) return;
1296 state.needoutline = 0;
1297 outline = fz_load_outline (state.ctx, state.doc);
1298 if (outline) {
1299 recurse_outline (outline, 0);
1300 fz_drop_outline (state.ctx, outline);
1304 static char *strofline (fz_stext_line *line)
1306 char *p;
1307 char utf8[10];
1308 fz_stext_char *ch;
1309 size_t size = 0, cap = 80;
1311 p = malloc (cap + 1);
1312 if (!p) return NULL;
1314 for (ch = line->first_char; ch; ch = ch->next) {
1315 int n = fz_runetochar (utf8, ch->c);
1316 if (size + n > cap) {
1317 cap *= 2;
1318 p = realloc (p, cap + 1);
1319 if (!p) return NULL;
1322 memcpy (p + size, utf8, n);
1323 size += n;
1325 p[size] = 0;
1326 return p;
1329 static int matchline (regex_t *re, fz_stext_line *line,
1330 int stop, int pageno, double start)
1332 int ret;
1333 char *p;
1334 regmatch_t rm;
1336 p = strofline (line);
1337 if (!p) return -1;
1339 ret = regexec (re, p, 1, &rm, 0);
1340 if (ret) {
1341 free (p);
1342 if (ret != REG_NOMATCH) {
1343 size_t size;
1344 char errbuf[80];
1345 size = regerror (ret, re, errbuf, sizeof (errbuf));
1346 printd ("msg regexec error `%.*s'",
1347 (int) size, errbuf);
1348 return -1;
1350 return 0;
1352 else {
1353 fz_point p1, p2, p3, p4;
1354 fz_rect s = {0,0,0,0}, e;
1355 fz_stext_char *ch;
1356 int o = 0;
1358 for (ch = line->first_char; ch; ch = ch->next) {
1359 o += fz_runelen (ch->c);
1360 if (o > rm.rm_so) {
1361 s = ch->bbox;
1362 break;
1365 for (;ch; ch = ch->next) {
1366 o += fz_runelen (ch->c);
1367 if (o > rm.rm_eo) break;
1369 e = ch->bbox;
1371 p1.x = s.x0;
1372 p1.y = s.y0;
1373 p2.x = e.x1;
1374 p2.y = s.y0;
1375 p3.x = e.x1;
1376 p3.y = e.y1;
1377 p4.x = s.x0;
1378 p4.y = e.y1;
1380 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1381 if (!stop) {
1382 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1383 pageno, 1,
1384 p1.x, p1.y,
1385 p2.x, p2.y,
1386 p3.x, p3.y,
1387 p4.x, p4.y);
1389 printd ("progress 1 found at %d `%.*s' in %f sec",
1390 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1391 now () - start);
1393 else {
1394 printd ("match %d %d %f %f %f %f %f %f %f %f",
1395 pageno, 2,
1396 p1.x, p1.y,
1397 p2.x, p2.y,
1398 p3.x, p3.y,
1399 p4.x, p4.y);
1401 #pragma GCC diagnostic error "-Wdouble-promotion"
1402 free (p);
1403 return 1;
1407 /* wishful thinking function */
1408 static void search (regex_t *re, int pageno, int y, int forward)
1410 fz_device *tdev;
1411 fz_stext_page *text;
1412 struct pagedim *pdim;
1413 int stop = 0, niters = 0;
1414 double start, end;
1415 fz_page *page;
1416 fz_stext_block *block;
1418 start = now ();
1419 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1420 if (niters++ == 5) {
1421 niters = 0;
1422 if (hasdata ()) {
1423 printd ("progress 1 attention requested aborting search at %d",
1424 pageno);
1425 stop = 1;
1427 else {
1428 printd ("progress %f searching in page %d",
1429 (double) (pageno + 1) / state.pagecount,
1430 pageno);
1433 pdim = pdimofpageno (pageno);
1434 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1435 tdev = fz_new_stext_device (state.ctx, text, 0);
1437 page = fz_load_page (state.ctx, state.doc, pageno);
1439 fz_matrix ctm = pagectm1 (page, pdim);
1440 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1443 fz_close_device (state.ctx, tdev);
1444 fz_drop_device (state.ctx, tdev);
1446 if (forward) {
1447 for (block = text->first_block; block; block = block->next) {
1448 fz_stext_line *line;
1450 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1451 for (line = block->u.t.first_line; line; line = line->next) {
1452 if (line->bbox.y0 < y + 1) continue;
1454 switch (matchline (re, line, stop, pageno, start)) {
1455 case 0: break;
1456 case 1: stop = 1; break;
1457 case -1: stop = 1; goto endloop;
1462 else {
1463 for (block = text->last_block; block; block = block->prev) {
1464 fz_stext_line *line;
1466 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1467 for (line = block->u.t.last_line; line; line = line->prev) {
1468 if (line->bbox.y0 < y + 1) continue;
1470 switch (matchline (re, line, stop, pageno, start)) {
1471 case 0: break;
1472 case 1: stop = 1; break;
1473 case -1: stop = 1; goto endloop;
1479 if (forward) {
1480 pageno += 1;
1481 y = 0;
1483 else {
1484 pageno -= 1;
1485 y = INT_MAX;
1487 endloop:
1488 fz_drop_stext_page (state.ctx, text);
1489 fz_drop_page (state.ctx, page);
1491 end = now ();
1492 if (!stop) {
1493 printd ("progress 1 no matches %f sec", end - start);
1495 printd ("clearrects");
1498 static void set_tex_params (int colorspace)
1500 switch (colorspace) {
1501 case 0:
1502 state.texiform = GL_RGBA8;
1503 state.texform = GL_RGBA;
1504 state.texty = GL_UNSIGNED_BYTE;
1505 state.colorspace = fz_device_rgb (state.ctx);
1506 break;
1507 case 1:
1508 state.texiform = GL_RGBA8;
1509 state.texform = GL_BGRA;
1510 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1511 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1512 #else
1513 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1514 #endif
1515 state.colorspace = fz_device_bgr (state.ctx);
1516 break;
1517 case 2:
1518 state.texiform = GL_LUMINANCE_ALPHA;
1519 state.texform = GL_LUMINANCE_ALPHA;
1520 state.texty = GL_UNSIGNED_BYTE;
1521 state.colorspace = fz_device_gray (state.ctx);
1522 break;
1523 default:
1524 errx (1, "invalid colorspce %d", colorspace);
1528 static void realloctexts (int texcount)
1530 size_t size;
1532 if (texcount == state.texcount) return;
1534 if (texcount < state.texcount) {
1535 glDeleteTextures (state.texcount - texcount,
1536 state.texids + texcount);
1539 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1540 state.texids = realloc (state.texids, size);
1541 if (!state.texids) {
1542 err (1, "realloc texs %" FMT_s, size);
1545 state.texowners = (void *) (state.texids + texcount);
1546 if (texcount > state.texcount) {
1547 glGenTextures (texcount - state.texcount,
1548 state.texids + state.texcount);
1549 for (int i = state.texcount; i < texcount; ++i) {
1550 state.texowners[i].w = -1;
1551 state.texowners[i].slice = NULL;
1554 state.texcount = texcount;
1555 state.texindex = 0;
1558 static char *mbtoutf8 (char *s)
1560 char *p, *r;
1561 wchar_t *tmp;
1562 size_t i, ret, len;
1564 if (state.utf8cs) {
1565 return s;
1568 len = mbstowcs (NULL, s, strlen (s));
1569 if (len == 0) {
1570 return s;
1572 else {
1573 if (len == (size_t) -1) {
1574 printd ("emsg mbtoutf8: mbstowcs %d:%s\n", errno, strerror (errno));
1575 return s;
1579 tmp = calloc (len, sizeof (wchar_t));
1580 if (!tmp) {
1581 printd ("emsg mbtoutf8: calloc(%zu, %zu) %d:%s",
1582 len, sizeof (wchar_t), errno, strerror (errno));
1583 return s;
1586 ret = mbstowcs (tmp, s, len);
1587 if (ret == (size_t) -1) {
1588 printd ("emsg mbtoutf8: mbswcs %zu characters failed %d:%s\n",
1589 len, errno, strerror (errno));
1590 free (tmp);
1591 return s;
1594 len = 0;
1595 for (i = 0; i < ret; ++i) {
1596 len += fz_runelen (tmp[i]);
1599 p = r = malloc (len + 1);
1600 if (!r) {
1601 printd ("emsg mbtoutf8: malloc(%zu)", len);
1602 free (tmp);
1603 return s;
1606 for (i = 0; i < ret; ++i) {
1607 p += fz_runetochar (p, tmp[i]);
1609 *p = 0;
1610 free (tmp);
1611 return r;
1614 CAMLprim value ml_mbtoutf8 (value s_v)
1616 CAMLparam1 (s_v);
1617 CAMLlocal1 (ret_v);
1618 char *s, *r;
1620 s = String_val (s_v);
1621 r = mbtoutf8 (s);
1622 if (r == s) {
1623 ret_v = s_v;
1625 else {
1626 ret_v = caml_copy_string (r);
1627 free (r);
1629 CAMLreturn (ret_v);
1632 static void * mainloop (void UNUSED_ATTR *unused)
1634 char *p = NULL;
1635 int len, ret, oldlen = 0;
1637 fz_var (p);
1638 fz_var (oldlen);
1639 for (;;) {
1640 len = readlen (state.csock);
1641 if (len == 0) {
1642 errx (1, "readlen returned 0");
1645 if (oldlen < len + 1) {
1646 p = realloc (p, len + 1);
1647 if (!p) {
1648 err (1, "realloc %d failed", len + 1);
1650 oldlen = len + 1;
1652 readdata (state.csock, p, len);
1653 p[len] = 0;
1655 if (!strncmp ("open", p, 4)) {
1656 int wthack, off, usedoccss, ok = 0;
1657 char *password;
1658 char *filename;
1659 char *utf8filename;
1660 size_t filenamelen;
1662 fz_var (ok);
1663 ret = sscanf (p + 5, " %d %d %d %n",
1664 &wthack, &state.cxack, &usedoccss, &off);
1665 if (ret != 3) {
1666 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1669 filename = p + 5 + off;
1670 filenamelen = strlen (filename);
1671 password = filename + filenamelen + 1;
1673 if (password[strlen (password) + 1]) {
1674 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1677 lock ("open");
1678 fz_set_use_document_css (state.ctx, usedoccss);
1679 fz_try (state.ctx) {
1680 ok = openxref (filename, password);
1682 fz_catch (state.ctx) {
1683 utf8filename = mbtoutf8 (filename);
1684 printd ("msg Could not open %s", utf8filename);
1685 if (utf8filename != filename) {
1686 free (utf8filename);
1689 if (ok) {
1690 pdfinfo ();
1691 initpdims (wthack);
1693 unlock ("open");
1695 if (ok) {
1696 if (!wthack) {
1697 utf8filename = mbtoutf8 (filename);
1698 printd ("msg Opened %s (press h/F1 to get help)",
1699 utf8filename);
1700 if (utf8filename != filename) {
1701 free (utf8filename);
1704 state.needoutline = 1;
1707 else if (!strncmp ("cs", p, 2)) {
1708 int i, colorspace;
1710 ret = sscanf (p + 2, " %d", &colorspace);
1711 if (ret != 1) {
1712 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1714 lock ("cs");
1715 set_tex_params (colorspace);
1716 for (i = 0; i < state.texcount; ++i) {
1717 state.texowners[i].w = -1;
1718 state.texowners[i].slice = NULL;
1720 unlock ("cs");
1722 else if (!strncmp ("freepage", p, 8)) {
1723 void *ptr;
1725 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1726 if (ret != 1) {
1727 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1729 lock ("freepage");
1730 freepage (ptr);
1731 unlock ("freepage");
1733 else if (!strncmp ("freetile", p, 8)) {
1734 void *ptr;
1736 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1737 if (ret != 1) {
1738 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1740 lock ("freetile");
1741 freetile (ptr);
1742 unlock ("freetile");
1744 else if (!strncmp ("search", p, 6)) {
1745 int icase, pageno, y, len2, forward;
1746 char *pattern;
1747 regex_t re;
1749 ret = sscanf (p + 6, " %d %d %d %d,%n",
1750 &icase, &pageno, &y, &forward, &len2);
1751 if (ret != 4) {
1752 errx (1, "malformed search `%s' ret=%d", p, ret);
1755 pattern = p + 6 + len2;
1756 ret = regcomp (&re, pattern,
1757 REG_EXTENDED | (icase ? REG_ICASE : 0));
1758 if (ret) {
1759 char errbuf[80];
1760 size_t size;
1762 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1763 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1765 else {
1766 search (&re, pageno, y, forward);
1767 regfree (&re);
1770 else if (!strncmp ("geometry", p, 8)) {
1771 int w, h, fitmodel;
1773 printd ("clear");
1774 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1775 if (ret != 3) {
1776 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1779 lock ("geometry");
1780 state.h = h;
1781 if (w != state.w) {
1782 state.w = w;
1783 for (int i = 0; i < state.texcount; ++i) {
1784 state.texowners[i].slice = NULL;
1787 state.fitmodel = fitmodel;
1788 layout ();
1789 process_outline ();
1791 state.gen++;
1792 unlock ("geometry");
1793 printd ("continue %d", state.pagecount);
1795 else if (!strncmp ("reqlayout", p, 9)) {
1796 char *nameddest;
1797 int rotate, off, h;
1798 int fitmodel;
1799 pdf_document *pdf;
1801 printd ("clear");
1802 ret = sscanf (p + 9, " %d %d %d %n",
1803 &rotate, &fitmodel, &h, &off);
1804 if (ret != 3) {
1805 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1807 lock ("reqlayout");
1808 pdf = pdf_specifics (state.ctx, state.doc);
1809 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1810 state.gen += 1;
1812 state.rotate = rotate;
1813 state.fitmodel = fitmodel;
1814 state.h = h;
1815 layout ();
1816 process_outline ();
1818 nameddest = p + 9 + off;
1819 if (pdf && nameddest && *nameddest) {
1820 fz_point xy;
1821 struct pagedim *pdim;
1822 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1823 &xy.x, &xy.y);
1824 pdim = pdimofpageno (pageno);
1825 fz_transform_point (&xy, &pdim->ctm);
1826 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1829 state.gen++;
1830 unlock ("reqlayout");
1831 printd ("continue %d", state.pagecount);
1833 else if (!strncmp ("page", p, 4)) {
1834 double a, b;
1835 struct page *page;
1836 int pageno, pindex;
1838 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1839 if (ret != 2) {
1840 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1843 lock ("page");
1844 a = now ();
1845 page = loadpage (pageno, pindex);
1846 b = now ();
1847 unlock ("page");
1849 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1851 else if (!strncmp ("tile", p, 4)) {
1852 int x, y, w, h;
1853 struct page *page;
1854 struct tile *tile;
1855 double a, b;
1856 void *data;
1858 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1859 SCN_ptr_cast (&page), &x, &y, &w, &h,
1860 SCN_ptr_cast (&data));
1861 if (ret != 6) {
1862 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1865 lock ("tile");
1866 a = now ();
1867 tile = rendertile (page, x, y, w, h, data);
1868 b = now ();
1869 unlock ("tile");
1871 printd ("tile %d %d %" FMT_ptr " %u %f",
1872 x, y,
1873 FMT_ptr_cast (tile),
1874 tile->w * tile->h * tile->pixmap->n,
1875 b - a);
1877 else if (!strncmp ("trimset", p, 7)) {
1878 fz_irect fuzz;
1879 int trimmargins;
1881 ret = sscanf (p + 7, " %d %d %d %d %d",
1882 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1883 if (ret != 5) {
1884 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1886 lock ("trimset");
1887 state.trimmargins = trimmargins;
1888 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1889 state.trimanew = 1;
1890 state.trimfuzz = fuzz;
1892 unlock ("trimset");
1894 else if (!strncmp ("settrim", p, 7)) {
1895 fz_irect fuzz;
1896 int trimmargins;
1898 ret = sscanf (p + 7, " %d %d %d %d %d",
1899 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1900 if (ret != 5) {
1901 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1903 printd ("clear");
1904 lock ("settrim");
1905 state.trimmargins = trimmargins;
1906 state.needoutline = 1;
1907 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1908 state.trimanew = 1;
1909 state.trimfuzz = fuzz;
1911 state.pagedimcount = 0;
1912 free (state.pagedims);
1913 state.pagedims = NULL;
1914 initpdims (0);
1915 layout ();
1916 process_outline ();
1917 unlock ("settrim");
1918 printd ("continue %d", state.pagecount);
1920 else if (!strncmp ("sliceh", p, 6)) {
1921 int h;
1923 ret = sscanf (p + 6, " %d", &h);
1924 if (ret != 1) {
1925 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1927 if (h != state.sliceheight) {
1928 state.sliceheight = h;
1929 for (int i = 0; i < state.texcount; ++i) {
1930 state.texowners[i].w = -1;
1931 state.texowners[i].h = -1;
1932 state.texowners[i].slice = NULL;
1936 else if (!strncmp ("interrupt", p, 9)) {
1937 printd ("vmsg interrupted");
1939 else {
1940 errx (1, "unknown command %.*s", len, p);
1943 return 0;
1946 CAMLprim value ml_isexternallink (value uri_v)
1948 CAMLparam1 (uri_v);
1949 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1950 CAMLreturn (Val_bool (ext));
1953 CAMLprim value ml_uritolocation (value uri_v)
1955 CAMLparam1 (uri_v);
1956 CAMLlocal1 (ret_v);
1957 int pageno;
1958 fz_point xy;
1959 struct pagedim *pdim;
1961 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1962 &xy.x, &xy.y);
1963 pdim = pdimofpageno (pageno);
1964 fz_transform_point (&xy, &pdim->ctm);
1965 ret_v = caml_alloc_tuple (3);
1966 Field (ret_v, 0) = Val_int (pageno);
1967 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1968 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1969 CAMLreturn (ret_v);
1972 CAMLprim value ml_realloctexts (value texcount_v)
1974 CAMLparam1 (texcount_v);
1975 int ok;
1977 if (trylock (__func__)) {
1978 ok = 0;
1979 goto done;
1981 realloctexts (Int_val (texcount_v));
1982 ok = 1;
1983 unlock (__func__);
1985 done:
1986 CAMLreturn (Val_bool (ok));
1989 static void recti (int x0, int y0, int x1, int y1)
1991 GLfloat *v = state.vertices;
1993 glVertexPointer (2, GL_FLOAT, 0, v);
1994 v[0] = x0; v[1] = y0;
1995 v[2] = x1; v[3] = y0;
1996 v[4] = x0; v[5] = y1;
1997 v[6] = x1; v[7] = y1;
1998 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2001 static void showsel (struct page *page, int ox, int oy)
2003 fz_irect bbox;
2004 fz_rect rect;
2005 fz_stext_block *block;
2006 int seen = 0;
2007 unsigned char selcolor[] = {15,15,15,140};
2009 if (!page->fmark.ch || !page->lmark.ch) return;
2011 glEnable (GL_BLEND);
2012 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2013 glColor4ubv (selcolor);
2015 ox += state.pagedims[page->pdimno].bounds.x0;
2016 oy += state.pagedims[page->pdimno].bounds.y0;
2018 for (block = page->text->first_block; block; block = block->next) {
2019 fz_stext_line *line;
2021 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2022 for (line = block->u.t.first_line; line; line = line->next) {
2023 fz_stext_char *ch;
2025 rect = fz_empty_rect;
2026 for (ch = line->first_char; ch; ch = ch->next) {
2027 if (ch == page->fmark.ch) seen = 1;
2028 if (seen) fz_union_rect (&rect, &ch->bbox);
2029 if (ch == page->lmark.ch) {
2030 fz_round_rect (&bbox, &rect);
2031 recti (bbox.x0 + ox, bbox.y0 + oy,
2032 bbox.x1 + ox, bbox.y1 + oy);
2033 goto done;
2036 fz_round_rect (&bbox, &rect);
2037 recti (bbox.x0 + ox, bbox.y0 + oy,
2038 bbox.x1 + ox, bbox.y1 + oy);
2041 done:
2042 glDisable (GL_BLEND);
2045 #pragma GCC diagnostic push
2046 #pragma GCC diagnostic ignored "-Weverything"
2047 #include "glfont.c"
2048 #pragma GCC diagnostic pop
2050 static void stipplerect (fz_matrix *m,
2051 fz_point *p1,
2052 fz_point *p2,
2053 fz_point *p3,
2054 fz_point *p4,
2055 GLfloat *texcoords,
2056 GLfloat *vertices)
2058 fz_transform_point (p1, m);
2059 fz_transform_point (p2, m);
2060 fz_transform_point (p3, m);
2061 fz_transform_point (p4, m);
2063 float w, h, s, t;
2065 w = p2->x - p1->x;
2066 h = p2->y - p1->y;
2067 t = hypotf (w, h) * .25f;
2069 w = p3->x - p2->x;
2070 h = p3->y - p2->y;
2071 s = hypotf (w, h) * .25f;
2073 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2074 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2076 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2077 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2079 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2080 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2082 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2083 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2085 glDrawArrays (GL_LINES, 0, 8);
2088 static void solidrect (fz_matrix *m,
2089 fz_point *p1,
2090 fz_point *p2,
2091 fz_point *p3,
2092 fz_point *p4,
2093 GLfloat *vertices)
2095 fz_transform_point (p1, m);
2096 fz_transform_point (p2, m);
2097 fz_transform_point (p3, m);
2098 fz_transform_point (p4, m);
2099 vertices[0] = p1->x; vertices[1] = p1->y;
2100 vertices[2] = p2->x; vertices[3] = p2->y;
2102 vertices[4] = p3->x; vertices[5] = p3->y;
2103 vertices[6] = p4->x; vertices[7] = p4->y;
2104 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2107 static void ensurelinks (struct page *page)
2109 if (!page->links)
2110 page->links = fz_load_links (state.ctx, page->fzpage);
2113 static void highlightlinks (struct page *page, int xoff, int yoff)
2115 fz_matrix ctm, tm, pm;
2116 fz_link *link;
2117 GLfloat *texcoords = state.texcoords;
2118 GLfloat *vertices = state.vertices;
2120 ensurelinks (page);
2122 glEnable (GL_TEXTURE_1D);
2123 glEnable (GL_BLEND);
2124 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2125 glBindTexture (GL_TEXTURE_1D, state.stid);
2127 xoff -= state.pagedims[page->pdimno].bounds.x0;
2128 yoff -= state.pagedims[page->pdimno].bounds.y0;
2129 fz_translate (&tm, xoff, yoff);
2130 pm = pagectm (page);
2131 fz_concat (&ctm, &pm, &tm);
2133 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2134 glVertexPointer (2, GL_FLOAT, 0, vertices);
2136 for (link = page->links; link; link = link->next) {
2137 fz_point p1, p2, p3, p4;
2139 p1.x = link->rect.x0;
2140 p1.y = link->rect.y0;
2142 p2.x = link->rect.x1;
2143 p2.y = link->rect.y0;
2145 p3.x = link->rect.x1;
2146 p3.y = link->rect.y1;
2148 p4.x = link->rect.x0;
2149 p4.y = link->rect.y1;
2151 /* TODO: different colours for different schemes */
2152 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2153 else glColor3ub (255, 0, 0);
2155 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2158 for (int i = 0; i < page->annotcount; ++i) {
2159 fz_point p1, p2, p3, p4;
2160 struct annot *annot = &page->annots[i];
2162 p1.x = annot->bbox.x0;
2163 p1.y = annot->bbox.y0;
2165 p2.x = annot->bbox.x1;
2166 p2.y = annot->bbox.y0;
2168 p3.x = annot->bbox.x1;
2169 p3.y = annot->bbox.y1;
2171 p4.x = annot->bbox.x0;
2172 p4.y = annot->bbox.y1;
2174 glColor3ub (0, 0, 128);
2175 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2178 glDisable (GL_BLEND);
2179 glDisable (GL_TEXTURE_1D);
2182 static int compareslinks (const void *l, const void *r)
2184 struct slink const *ls = l;
2185 struct slink const *rs = r;
2186 if (ls->bbox.y0 == rs->bbox.y0) {
2187 return rs->bbox.x0 - rs->bbox.x0;
2189 return ls->bbox.y0 - rs->bbox.y0;
2192 static void droptext (struct page *page)
2194 if (page->text) {
2195 fz_drop_stext_page (state.ctx, page->text);
2196 page->fmark.ch = NULL;
2197 page->lmark.ch = NULL;
2198 page->text = NULL;
2202 static void dropannots (struct page *page)
2204 if (page->annots) {
2205 free (page->annots);
2206 page->annots = NULL;
2207 page->annotcount = 0;
2211 static void ensureannots (struct page *page)
2213 int i, count = 0;
2214 size_t annotsize = sizeof (*page->annots);
2215 fz_annot *annot;
2217 if (state.gen != page->agen) {
2218 dropannots (page);
2219 page->agen = state.gen;
2221 if (page->annots) return;
2223 for (annot = fz_first_annot (state.ctx, page->fzpage);
2224 annot;
2225 annot = fz_next_annot (state.ctx, annot)) {
2226 count++;
2229 if (count > 0) {
2230 page->annotcount = count;
2231 page->annots = calloc (count, annotsize);
2232 if (!page->annots) {
2233 err (1, "calloc annots %d", count);
2236 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2237 annot;
2238 annot = fz_next_annot (state.ctx, annot), i++) {
2239 fz_rect rect;
2241 fz_bound_annot (state.ctx, annot, &rect);
2242 page->annots[i].annot = annot;
2243 fz_round_rect (&page->annots[i].bbox, &rect);
2248 static void dropslinks (struct page *page)
2250 if (page->slinks) {
2251 free (page->slinks);
2252 page->slinks = NULL;
2253 page->slinkcount = 0;
2255 if (page->links) {
2256 fz_drop_link (state.ctx, page->links);
2257 page->links = NULL;
2261 static void ensureslinks (struct page *page)
2263 fz_matrix ctm;
2264 int i, count;
2265 size_t slinksize = sizeof (*page->slinks);
2266 fz_link *link;
2268 ensureannots (page);
2269 if (state.gen != page->sgen) {
2270 dropslinks (page);
2271 page->sgen = state.gen;
2273 if (page->slinks) return;
2275 ensurelinks (page);
2276 ctm = pagectm (page);
2278 count = page->annotcount;
2279 for (link = page->links; link; link = link->next) {
2280 count++;
2282 if (count > 0) {
2283 int j;
2285 page->slinkcount = count;
2286 page->slinks = calloc (count, slinksize);
2287 if (!page->slinks) {
2288 err (1, "calloc slinks %d", count);
2291 for (i = 0, link = page->links; link; ++i, link = link->next) {
2292 fz_rect rect;
2294 rect = link->rect;
2295 fz_transform_rect (&rect, &ctm);
2296 page->slinks[i].tag = SLINK;
2297 page->slinks[i].u.link = link;
2298 fz_round_rect (&page->slinks[i].bbox, &rect);
2300 for (j = 0; j < page->annotcount; ++j, ++i) {
2301 fz_rect rect;
2302 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2303 fz_transform_rect (&rect, &ctm);
2304 fz_round_rect (&page->slinks[i].bbox, &rect);
2306 page->slinks[i].tag = SANNOT;
2307 page->slinks[i].u.annot = page->annots[j].annot;
2309 qsort (page->slinks, count, slinksize, compareslinks);
2313 #pragma GCC diagnostic push
2314 #pragma GCC diagnostic ignored "-Wconversion"
2315 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2316 static void fmt_linkn (char *s, unsigned int u)
2318 unsigned int len; unsigned int q;
2319 unsigned int zma = 'z' - 'a' + 1;
2320 len = 1; q = u;
2321 while (q > zma - 1) { ++len; q /= zma; }
2322 if (s) {
2323 s += len;
2324 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2325 /* handles u == 0 */
2327 s[len] = 0;
2329 #pragma GCC diagnostic pop
2331 static void highlightslinks (struct page *page, int xoff, int yoff,
2332 int noff, char *targ, mlsize_t tlen, int hfsize)
2334 char buf[40];
2335 struct slink *slink;
2336 float x0, y0, x1, y1, w;
2338 ensureslinks (page);
2339 glColor3ub (0xc3, 0xb0, 0x91);
2340 for (int i = 0; i < page->slinkcount; ++i) {
2341 fmt_linkn (buf, i + noff);
2342 if (!tlen || !strncmp (targ, buf, tlen)) {
2343 slink = &page->slinks[i];
2345 x0 = slink->bbox.x0 + xoff - 5;
2346 y1 = slink->bbox.y0 + yoff - 5;
2347 y0 = y1 + 10 + hfsize;
2348 w = measure_string (state.face, hfsize, buf);
2349 x1 = x0 + w + 10;
2350 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2354 glEnable (GL_BLEND);
2355 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2356 glEnable (GL_TEXTURE_2D);
2357 glColor3ub (0, 0, 0);
2358 for (int i = 0; i < page->slinkcount; ++i) {
2359 fmt_linkn (buf, i + noff);
2360 if (!tlen || !strncmp (targ, buf, tlen)) {
2361 slink = &page->slinks[i];
2363 x0 = slink->bbox.x0 + xoff;
2364 y0 = slink->bbox.y0 + yoff + hfsize;
2365 draw_string (state.face, hfsize, x0, y0, buf);
2368 glDisable (GL_TEXTURE_2D);
2369 glDisable (GL_BLEND);
2372 static void uploadslice (struct tile *tile, struct slice *slice)
2374 int offset;
2375 struct slice *slice1;
2376 unsigned char *texdata;
2378 offset = 0;
2379 for (slice1 = tile->slices; slice != slice1; slice1++) {
2380 offset += slice1->h * tile->w * tile->pixmap->n;
2382 if (slice->texindex != -1 && slice->texindex < state.texcount
2383 && state.texowners[slice->texindex].slice == slice) {
2384 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2386 else {
2387 int subimage = 0;
2388 int texindex = state.texindex++ % state.texcount;
2390 if (state.texowners[texindex].w == tile->w) {
2391 if (state.texowners[texindex].h >= slice->h) {
2392 subimage = 1;
2394 else {
2395 state.texowners[texindex].h = slice->h;
2398 else {
2399 state.texowners[texindex].h = slice->h;
2402 state.texowners[texindex].w = tile->w;
2403 state.texowners[texindex].slice = slice;
2404 slice->texindex = texindex;
2406 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2407 #if TEXT_TYPE == GL_TEXTURE_2D
2408 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2409 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2410 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2411 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2412 #endif
2413 if (tile->pbo) {
2414 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2415 texdata = 0;
2417 else {
2418 texdata = tile->pixmap->samples;
2420 if (subimage) {
2421 glTexSubImage2D (TEXT_TYPE,
2425 tile->w,
2426 slice->h,
2427 state.texform,
2428 state.texty,
2429 texdata+offset
2432 else {
2433 glTexImage2D (TEXT_TYPE,
2435 state.texiform,
2436 tile->w,
2437 slice->h,
2439 state.texform,
2440 state.texty,
2441 texdata+offset
2444 if (tile->pbo) {
2445 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2450 CAMLprim void ml_begintiles (value unit_v)
2452 CAMLparam1 (unit_v);
2453 glEnable (TEXT_TYPE);
2454 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2455 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2456 CAMLreturn0;
2459 CAMLprim void ml_endtiles (value unit_v)
2461 CAMLparam1 (unit_v);
2462 glDisable (TEXT_TYPE);
2463 CAMLreturn0;
2466 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2468 CAMLparam2 (args_v, ptr_v);
2469 int dispx = Int_val (Field (args_v, 0));
2470 int dispy = Int_val (Field (args_v, 1));
2471 int dispw = Int_val (Field (args_v, 2));
2472 int disph = Int_val (Field (args_v, 3));
2473 int tilex = Int_val (Field (args_v, 4));
2474 int tiley = Int_val (Field (args_v, 5));
2475 char *s = String_val (ptr_v);
2476 struct tile *tile = parse_pointer (__func__, s);
2477 int slicey, firstslice;
2478 struct slice *slice;
2479 GLfloat *texcoords = state.texcoords;
2480 GLfloat *vertices = state.vertices;
2482 firstslice = tiley / tile->sliceheight;
2483 slice = &tile->slices[firstslice];
2484 slicey = tiley % tile->sliceheight;
2486 while (disph > 0) {
2487 int dh;
2489 dh = slice->h - slicey;
2490 dh = fz_mini (disph, dh);
2491 uploadslice (tile, slice);
2493 texcoords[0] = tilex; texcoords[1] = slicey;
2494 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2495 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2496 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2498 vertices[0] = dispx; vertices[1] = dispy;
2499 vertices[2] = dispx+dispw; vertices[3] = dispy;
2500 vertices[4] = dispx; vertices[5] = dispy+dh;
2501 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2503 #if TEXT_TYPE == GL_TEXTURE_2D
2504 for (int i = 0; i < 8; ++i) {
2505 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2507 #endif
2509 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2510 dispy += dh;
2511 disph -= dh;
2512 slice++;
2513 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2514 slicey = 0;
2516 CAMLreturn0;
2519 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2521 fz_matrix ctm, tm, pm;
2522 fz_point p1, p2, p3, p4;
2523 GLfloat *vertices = state.vertices;
2524 double *v = (double *) rects_v;
2526 xoff -= state.pagedims[page->pdimno].bounds.x0;
2527 yoff -= state.pagedims[page->pdimno].bounds.y0;
2528 fz_translate (&tm, xoff, yoff);
2529 pm = pagectm (page);
2530 fz_concat (&ctm, &pm, &tm);
2532 glEnable (GL_BLEND);
2533 glVertexPointer (2, GL_FLOAT, 0, vertices);
2535 glColor4dv (v);
2536 p1.x = (float) v[4];
2537 p1.y = (float) v[5];
2539 p2.x = (float) v[6];
2540 p2.y = (float) v[5];
2542 p3.x = (float) v[6];
2543 p3.y = (float) v[7];
2545 p4.x = (float) v[4];
2546 p4.y = (float) v[7];
2547 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2548 glDisable (GL_BLEND);
2551 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2552 value xoff_v, value yoff_v,
2553 value li_v)
2555 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2556 int xoff = Int_val (xoff_v);
2557 int yoff = Int_val (yoff_v);
2558 int noff = Int_val (Field (li_v, 0));
2559 char *targ = String_val (Field (li_v, 1));
2560 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2561 int hfsize = Int_val (Field (li_v, 2));
2562 char *s = String_val (ptr_v);
2563 int hlmask = Int_val (hlinks_v);
2564 struct page *page = parse_pointer (__func__, s);
2566 if (!page->fzpage) {
2567 /* deal with loadpage failed pages */
2568 goto done;
2571 if (trylock (__func__)) {
2572 noff = -1;
2573 goto done;
2576 ensureannots (page);
2577 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2578 if (hlmask & 2) {
2579 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2580 noff = page->slinkcount;
2582 if (page->tgen == state.gen) {
2583 showsel (page, xoff, yoff);
2585 unlock (__func__);
2587 done:
2588 CAMLreturn (Val_int (noff));
2591 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2592 value rects_v)
2594 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2595 int xoff = Int_val (xoff_v);
2596 int yoff = Int_val (yoff_v);
2597 char *s = String_val (ptr_v);
2598 struct page *page = parse_pointer (__func__, s);
2600 drawprect (page, xoff, yoff, rects_v);
2601 CAMLreturn0;
2604 static struct annot *getannot (struct page *page, int x, int y)
2606 fz_point p;
2607 fz_matrix ctm;
2608 const fz_matrix *tctm;
2609 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2611 if (!page->annots) return NULL;
2613 if (pdf) {
2614 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2615 tctm = &state.pagedims[page->pdimno].tctm;
2617 else {
2618 tctm = &fz_identity;
2621 p.x = x;
2622 p.y = y;
2624 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2625 fz_invert_matrix (&ctm, &ctm);
2626 fz_transform_point (&p, &ctm);
2628 if (pdf) {
2629 for (int i = 0; i < page->annotcount; ++i) {
2630 struct annot *a = &page->annots[i];
2631 fz_rect rect;
2633 fz_bound_annot (state.ctx, a->annot, &rect);
2634 if (p.x >= rect.x0 && p.x <= rect.x1) {
2635 if (p.y >= rect.y0 && p.y <= rect.y1)
2636 return a;
2640 return NULL;
2643 static fz_link *getlink (struct page *page, int x, int y)
2645 fz_point p;
2646 fz_matrix ctm;
2647 fz_link *link;
2649 ensureslinks (page);
2651 p.x = x;
2652 p.y = y;
2654 ctm = pagectm (page);
2655 fz_invert_matrix (&ctm, &ctm);
2656 fz_transform_point (&p, &ctm);
2658 for (link = page->links; link; link = link->next) {
2659 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2660 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2661 return link;
2665 return NULL;
2668 static void ensuretext (struct page *page)
2670 if (state.gen != page->tgen) {
2671 droptext (page);
2672 page->tgen = state.gen;
2674 if (!page->text) {
2675 fz_matrix ctm;
2676 fz_device *tdev;
2678 page->text = fz_new_stext_page (state.ctx,
2679 &state.pagedims[page->pdimno].mediabox);
2680 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2681 ctm = pagectm (page);
2682 fz_run_display_list (state.ctx, page->dlist,
2683 tdev, &ctm, &fz_infinite_rect, NULL);
2684 fz_close_device (state.ctx, tdev);
2685 fz_drop_device (state.ctx, tdev);
2689 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2691 CAMLparam2 (start_page_v, dir_v);
2692 CAMLlocal1 (ret_v);
2693 int i, dir = Int_val (dir_v);
2694 int start_page = Int_val (start_page_v);
2695 int end_page = dir > 0 ? state.pagecount : -1;
2696 pdf_document *pdf;
2698 fz_var (end_page);
2699 ret_v = Val_int (0);
2700 lock (__func__);
2701 pdf = pdf_specifics (state.ctx, state.doc);
2702 for (i = start_page + dir; i != end_page; i += dir) {
2703 int found;
2705 fz_var (found);
2706 if (pdf) {
2707 pdf_page *page = NULL;
2709 fz_var (page);
2710 fz_try (state.ctx) {
2711 page = pdf_load_page (state.ctx, pdf, i);
2712 found = !!page->links || !!page->annots;
2714 fz_catch (state.ctx) {
2715 found = 0;
2717 if (page) {
2718 fz_drop_page (state.ctx, &page->super);
2721 else {
2722 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2723 fz_link *link = fz_load_links (state.ctx, page);
2724 found = !!link;
2725 fz_drop_link (state.ctx, link);
2726 fz_drop_page (state.ctx, page);
2729 if (found) {
2730 ret_v = caml_alloc_small (1, 1);
2731 Field (ret_v, 0) = Val_int (i);
2732 goto unlock;
2735 unlock:
2736 unlock (__func__);
2737 CAMLreturn (ret_v);
2740 enum { dir_first, dir_last };
2741 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2743 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2745 CAMLparam2 (ptr_v, dir_v);
2746 CAMLlocal2 (ret_v, pos_v);
2747 struct page *page;
2748 int dirtag, i, slinkindex;
2749 struct slink *found = NULL ,*slink;
2750 char *s = String_val (ptr_v);
2752 page = parse_pointer (__func__, s);
2753 ret_v = Val_int (0);
2754 lock (__func__);
2755 ensureslinks (page);
2757 if (Is_block (dir_v)) {
2758 dirtag = Tag_val (dir_v);
2759 switch (dirtag) {
2760 case dir_first_visible:
2762 int x0, y0, dir, first_index, last_index;
2764 pos_v = Field (dir_v, 0);
2765 x0 = Int_val (Field (pos_v, 0));
2766 y0 = Int_val (Field (pos_v, 1));
2767 dir = Int_val (Field (pos_v, 2));
2769 if (dir >= 0) {
2770 dir = 1;
2771 first_index = 0;
2772 last_index = page->slinkcount;
2774 else {
2775 first_index = page->slinkcount - 1;
2776 last_index = -1;
2779 for (i = first_index; i != last_index; i += dir) {
2780 slink = &page->slinks[i];
2781 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2782 found = slink;
2783 break;
2787 break;
2789 case dir_left:
2790 slinkindex = Int_val (Field (dir_v, 0));
2791 found = &page->slinks[slinkindex];
2792 for (i = slinkindex - 1; i >= 0; --i) {
2793 slink = &page->slinks[i];
2794 if (slink->bbox.x0 < found->bbox.x0) {
2795 found = slink;
2796 break;
2799 break;
2801 case dir_right:
2802 slinkindex = Int_val (Field (dir_v, 0));
2803 found = &page->slinks[slinkindex];
2804 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2805 slink = &page->slinks[i];
2806 if (slink->bbox.x0 > found->bbox.x0) {
2807 found = slink;
2808 break;
2811 break;
2813 case dir_down:
2814 slinkindex = Int_val (Field (dir_v, 0));
2815 found = &page->slinks[slinkindex];
2816 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2817 slink = &page->slinks[i];
2818 if (slink->bbox.y0 >= found->bbox.y0) {
2819 found = slink;
2820 break;
2823 break;
2825 case dir_up:
2826 slinkindex = Int_val (Field (dir_v, 0));
2827 found = &page->slinks[slinkindex];
2828 for (i = slinkindex - 1; i >= 0; --i) {
2829 slink = &page->slinks[i];
2830 if (slink->bbox.y0 <= found->bbox.y0) {
2831 found = slink;
2832 break;
2835 break;
2838 else {
2839 dirtag = Int_val (dir_v);
2840 switch (dirtag) {
2841 case dir_first:
2842 found = page->slinks;
2843 break;
2845 case dir_last:
2846 if (page->slinks) {
2847 found = page->slinks + (page->slinkcount - 1);
2849 break;
2852 if (found) {
2853 ret_v = caml_alloc_small (2, 1);
2854 Field (ret_v, 0) = Val_int (found - page->slinks);
2857 unlock (__func__);
2858 CAMLreturn (ret_v);
2861 enum { uuri, utext, uannot };
2863 CAMLprim value ml_getlink (value ptr_v, value n_v)
2865 CAMLparam2 (ptr_v, n_v);
2866 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2867 fz_link *link;
2868 struct page *page;
2869 char *s = String_val (ptr_v);
2870 struct slink *slink;
2872 ret_v = Val_int (0);
2873 page = parse_pointer (__func__, s);
2875 lock (__func__);
2876 ensureslinks (page);
2877 slink = &page->slinks[Int_val (n_v)];
2878 if (slink->tag == SLINK) {
2879 link = slink->u.link;
2880 str_v = caml_copy_string (link->uri);
2881 ret_v = caml_alloc_small (1, uuri);
2882 Field (ret_v, 0) = str_v;
2884 else {
2885 ret_v = caml_alloc_small (1, uannot);
2886 tup_v = caml_alloc_tuple (2);
2887 Field (ret_v, 0) = tup_v;
2888 Field (tup_v, 0) = ptr_v;
2889 Field (tup_v, 1) = n_v;
2891 unlock (__func__);
2893 CAMLreturn (ret_v);
2896 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2898 CAMLparam2 (ptr_v, n_v);
2899 CAMLlocal1 (ret_v);
2900 pdf_document *pdf;
2901 char *contents = NULL;
2903 lock (__func__);
2904 pdf = pdf_specifics (state.ctx, state.doc);
2905 if (pdf) {
2906 char *s = String_val (ptr_v);
2907 struct page *page;
2908 struct slink *slink;
2910 page = parse_pointer (__func__, s);
2911 slink = &page->slinks[Int_val (n_v)];
2912 contents = pdf_copy_annot_contents (state.ctx,
2913 (pdf_annot *) slink->u.annot);
2915 unlock (__func__);
2916 if (contents) {
2917 ret_v = caml_copy_string (contents);
2918 fz_free (state.ctx, contents);
2920 else {
2921 ret_v = caml_copy_string ("");
2923 CAMLreturn (ret_v);
2926 CAMLprim value ml_getlinkcount (value ptr_v)
2928 CAMLparam1 (ptr_v);
2929 struct page *page;
2930 char *s = String_val (ptr_v);
2932 page = parse_pointer (__func__, s);
2933 CAMLreturn (Val_int (page->slinkcount));
2936 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2938 CAMLparam2 (ptr_v, n_v);
2939 CAMLlocal1 (ret_v);
2940 struct page *page;
2941 struct slink *slink;
2942 char *s = String_val (ptr_v);
2944 page = parse_pointer (__func__, s);
2945 ret_v = caml_alloc_tuple (4);
2946 lock (__func__);
2947 ensureslinks (page);
2949 slink = &page->slinks[Int_val (n_v)];
2950 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2951 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2952 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2953 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2954 unlock (__func__);
2955 CAMLreturn (ret_v);
2958 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2960 CAMLparam3 (ptr_v, x_v, y_v);
2961 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2962 fz_link *link;
2963 struct annot *annot;
2964 struct page *page;
2965 char *ptr = String_val (ptr_v);
2966 int x = Int_val (x_v), y = Int_val (y_v);
2967 struct pagedim *pdim;
2969 ret_v = Val_int (0);
2970 if (trylock (__func__)) {
2971 goto done;
2974 page = parse_pointer (__func__, ptr);
2975 pdim = &state.pagedims[page->pdimno];
2976 x += pdim->bounds.x0;
2977 y += pdim->bounds.y0;
2980 annot = getannot (page, x, y);
2981 if (annot) {
2982 int i, n = -1;
2984 ensureslinks (page);
2985 for (i = 0; i < page->slinkcount; ++i) {
2986 if (page->slinks[i].tag == SANNOT
2987 && page->slinks[i].u.annot == annot->annot) {
2988 n = i;
2989 break;
2992 ret_v = caml_alloc_small (1, uannot);
2993 tup_v = caml_alloc_tuple (2);
2994 Field (ret_v, 0) = tup_v;
2995 Field (tup_v, 0) = ptr_v;
2996 Field (tup_v, 1) = Val_int (n);
2997 goto unlock;
3001 link = getlink (page, x, y);
3002 if (link) {
3003 str_v = caml_copy_string (link->uri);
3004 ret_v = caml_alloc_small (1, uuri);
3005 Field (ret_v, 0) = str_v;
3007 else {
3008 fz_rect *b;
3009 fz_stext_block *block;
3011 ensuretext (page);
3013 for (block = page->text->first_block; block; block = block->next) {
3014 fz_stext_line *line;
3016 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3017 b = &block->bbox;
3018 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3019 continue;
3021 for (line = block->u.t.first_line; line; line = line->next) {
3022 fz_stext_char *ch;
3024 b = &line->bbox;
3025 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3026 continue;
3028 for (ch = line->first_char; ch; ch = ch->next) {
3029 b = &ch->bbox;
3031 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3032 const char *n2 = fz_font_name (state.ctx, ch->font);
3033 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3034 ch->font);
3036 if (!n2) n2 = "<unknown font>";
3038 if (face && face->family_name) {
3039 char *s;
3040 char *n1 = face->family_name;
3041 size_t l1 = strlen (n1);
3042 size_t l2 = strlen (n2);
3044 if (l1 != l2 || memcmp (n1, n2, l1)) {
3045 s = malloc (l1 + l2 + 2);
3046 if (s) {
3047 memcpy (s, n2, l2);
3048 s[l2] = '=';
3049 memcpy (s + l2 + 1, n1, l1 + 1);
3050 str_v = caml_copy_string (s);
3051 free (s);
3055 if (str_v == Val_unit) {
3056 str_v = caml_copy_string (n2);
3058 ret_v = caml_alloc_small (1, utext);
3059 Field (ret_v, 0) = str_v;
3060 goto unlock;
3066 unlock:
3067 unlock (__func__);
3069 done:
3070 CAMLreturn (ret_v);
3073 enum { mark_page, mark_block, mark_line, mark_word };
3075 static int uninteresting (int c)
3077 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3078 || ispunct (c);
3081 CAMLprim void ml_clearmark (value ptr_v)
3083 CAMLparam1 (ptr_v);
3084 char *s = String_val (ptr_v);
3085 struct page *page;
3087 if (trylock (__func__)) {
3088 goto done;
3091 page = parse_pointer (__func__, s);
3092 page->fmark.ch = NULL;
3093 page->lmark.ch = NULL;
3095 unlock (__func__);
3096 done:
3097 CAMLreturn0;
3100 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3102 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3103 CAMLlocal1 (ret_v);
3104 fz_rect *b;
3105 struct page *page;
3106 fz_stext_line *line;
3107 fz_stext_block *block;
3108 struct pagedim *pdim;
3109 int mark = Int_val (mark_v);
3110 char *s = String_val (ptr_v);
3111 int x = Int_val (x_v), y = Int_val (y_v);
3113 ret_v = Val_bool (0);
3114 if (trylock (__func__)) {
3115 goto done;
3118 page = parse_pointer (__func__, s);
3119 pdim = &state.pagedims[page->pdimno];
3121 ensuretext (page);
3123 if (mark == mark_page) {
3124 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3125 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3126 ret_v = Val_bool (1);
3127 goto unlock;
3130 x += pdim->bounds.x0;
3131 y += pdim->bounds.y0;
3133 for (block = page->text->first_block; block; block = block->next) {
3134 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3135 b = &block->bbox;
3136 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3137 continue;
3139 if (mark == mark_block) {
3140 page->fmark.ch = block->u.t.first_line->first_char;
3141 page->lmark.ch = block->u.t.last_line->last_char;
3142 ret_v = Val_bool (1);
3143 goto unlock;
3146 for (line = block->u.t.first_line; line; line = line->next) {
3147 fz_stext_char *ch;
3149 b = &line->bbox;
3150 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3151 continue;
3153 if (mark == mark_line) {
3154 page->fmark.ch = line->first_char;
3155 page->lmark.ch = line->last_char;
3156 ret_v = Val_bool (1);
3157 goto unlock;
3160 for (ch = line->first_char; ch; ch = ch->next) {
3161 fz_stext_char *ch2, *first = NULL, *last = NULL;
3162 b = &ch->bbox;
3163 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3164 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3165 if (uninteresting (ch2->c)) first = NULL;
3166 else if (!first) first = ch2;
3168 for (ch2 = ch; ch2; ch2 = ch2->next) {
3169 if (uninteresting (ch2->c)) break;
3170 last = ch2;
3173 page->fmark.ch = first;
3174 page->lmark.ch = last;
3175 ret_v = Val_bool (1);
3176 goto unlock;
3181 unlock:
3182 if (!Bool_val (ret_v)) {
3183 page->fmark.ch = NULL;
3184 page->lmark.ch = NULL;
3186 unlock (__func__);
3188 done:
3189 CAMLreturn (ret_v);
3192 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3194 CAMLparam3 (ptr_v, x_v, y_v);
3195 CAMLlocal2 (ret_v, res_v);
3196 fz_rect *b = NULL;
3197 struct page *page;
3198 struct pagedim *pdim;
3199 fz_stext_block *block;
3200 char *s = String_val (ptr_v);
3201 int x = Int_val (x_v), y = Int_val (y_v);
3203 ret_v = Val_int (0);
3204 if (trylock (__func__)) {
3205 goto done;
3208 page = parse_pointer (__func__, s);
3209 pdim = &state.pagedims[page->pdimno];
3210 x += pdim->bounds.x0;
3211 y += pdim->bounds.y0;
3213 ensuretext (page);
3215 for (block = page->text->first_block; block; block = block->next) {
3216 switch (block->type) {
3217 case FZ_STEXT_BLOCK_TEXT:
3218 b = &block->bbox;
3219 break;
3221 case FZ_STEXT_BLOCK_IMAGE:
3222 b = &block->bbox;
3223 break;
3225 default:
3226 continue;
3229 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3230 break;
3231 b = NULL;
3233 if (b) {
3234 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3235 ret_v = caml_alloc_small (1, 1);
3236 Store_double_field (res_v, 0, (double) b->x0);
3237 Store_double_field (res_v, 1, (double) b->x1);
3238 Store_double_field (res_v, 2, (double) b->y0);
3239 Store_double_field (res_v, 3, (double) b->y1);
3240 Field (ret_v, 0) = res_v;
3242 unlock (__func__);
3244 done:
3245 CAMLreturn (ret_v);
3248 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3250 CAMLparam2 (ptr_v, rect_v);
3251 fz_rect b;
3252 struct page *page;
3253 struct pagedim *pdim;
3254 char *s = String_val (ptr_v);
3255 int x0, x1, y0, y1;
3256 fz_stext_char *ch;
3257 fz_stext_line *line;
3258 fz_stext_block *block;
3259 fz_stext_char *fc, *lc;
3261 if (trylock (__func__)) {
3262 goto done;
3265 page = parse_pointer (__func__, s);
3266 ensuretext (page);
3268 pdim = &state.pagedims[page->pdimno];
3269 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3270 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3271 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3272 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3274 if (y0 > y1) {
3275 int t = y0;
3276 y0 = y1;
3277 y1 = t;
3278 x0 = x1;
3279 x1 = t;
3282 fc = page->fmark.ch;
3283 lc = page->lmark.ch;
3285 for (block = page->text->first_block; block; block = block->next) {
3286 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3287 for (line = block->u.t.first_line; line; line = line->next) {
3288 for (ch = line->first_char; ch; ch = ch->next) {
3289 b = ch->bbox;
3290 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3291 fc = ch;
3293 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3294 lc = ch;
3299 if (x1 < x0 && fc == lc) {
3300 fz_stext_char *t;
3302 t = fc;
3303 fc = lc;
3304 lc = t;
3307 page->fmark.ch = fc;
3308 page->lmark.ch = lc;
3310 unlock (__func__);
3312 done:
3313 CAMLreturn0;
3316 static int pipechar (FILE *f, fz_stext_char *ch)
3318 char buf[4];
3319 int len;
3320 size_t ret;
3322 len = fz_runetochar (buf, ch->c);
3323 ret = fwrite (buf, len, 1, f);
3324 if (ret != 1) {
3325 fprintf (stderr, "failed to write %d bytes ret=%zu: %s\n",
3326 len, ret, strerror (errno));
3327 return -1;
3329 return 0;
3332 #ifdef __CYGWIN__
3333 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3335 caml_failwith ("ml_popen not implemented under Cygwin");
3337 #else
3338 CAMLprim value ml_spawn (value command_v, value fds_v)
3340 CAMLparam2 (command_v, fds_v);
3341 CAMLlocal2 (l_v, tup_v);
3342 int ret, ret1;
3343 pid_t pid = (pid_t) -1;
3344 char *msg = NULL;
3345 value earg_v = Nothing;
3346 posix_spawnattr_t attr;
3347 posix_spawn_file_actions_t fa;
3348 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3350 argv[2] = String_val (command_v);
3352 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3353 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3356 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3357 msg = "posix_spawnattr_init";
3358 goto fail1;
3361 #ifdef POSIX_SPAWN_USEVFORK
3362 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3363 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3364 goto fail;
3366 #endif
3368 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3369 int fd1, fd2;
3371 tup_v = Field (l_v, 0);
3372 fd1 = Int_val (Field (tup_v, 0));
3373 fd2 = Int_val (Field (tup_v, 1));
3374 if (fd2 < 0) {
3375 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3376 msg = "posix_spawn_file_actions_addclose";
3377 earg_v = tup_v;
3378 goto fail;
3381 else {
3382 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3383 msg = "posix_spawn_file_actions_adddup2";
3384 earg_v = tup_v;
3385 goto fail;
3390 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3391 msg = "posix_spawn";
3392 goto fail;
3395 fail:
3396 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3397 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3400 fail1:
3401 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3402 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3403 strerror (ret1));
3406 if (msg)
3407 unix_error (ret, msg, earg_v);
3409 CAMLreturn (Val_int (pid));
3411 #endif
3413 CAMLprim value ml_hassel (value ptr_v)
3415 CAMLparam1 (ptr_v);
3416 CAMLlocal1 (ret_v);
3417 struct page *page;
3418 char *s = String_val (ptr_v);
3420 ret_v = Val_bool (0);
3421 if (trylock (__func__)) {
3422 goto done;
3425 page = parse_pointer (__func__, s);
3426 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3427 unlock (__func__);
3428 done:
3429 CAMLreturn (ret_v);
3432 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3434 CAMLparam2 (fd_v, ptr_v);
3435 FILE *f;
3436 int seen = 0;
3437 struct page *page;
3438 fz_stext_line *line;
3439 fz_stext_block *block;
3440 int fd = Int_val (fd_v);
3441 char *s = String_val (ptr_v);
3443 if (trylock (__func__)) {
3444 goto done;
3447 page = parse_pointer (__func__, s);
3449 if (!page->fmark.ch || !page->lmark.ch) {
3450 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3451 goto unlock;
3454 f = fdopen (fd, "w");
3455 if (!f) {
3456 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3457 fd, strerror (errno));
3458 f = stdout;
3461 for (block = page->text->first_block; block; block = block->next) {
3462 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3463 for (line = block->u.t.first_line; line; line = line->next) {
3464 fz_stext_char *ch;
3465 for (ch = line->first_char; ch; ch = ch->next) {
3466 if (seen || ch == page->fmark.ch) {
3467 do {
3468 pipechar (f, ch);
3469 if (ch == page->lmark.ch) goto close;
3470 } while ((ch = ch->next));
3471 seen = 1;
3472 break;
3475 if (seen) fputc ('\n', f);
3478 close:
3479 if (f != stdout) {
3480 int ret = fclose (f);
3481 fd = -1;
3482 if (ret == -1) {
3483 if (errno != ECHILD) {
3484 fprintf (stderr, "failed to close sel pipe: %s\n",
3485 strerror (errno));
3489 unlock:
3490 unlock (__func__);
3492 done:
3493 if (fd >= 0) {
3494 if (close (fd)) {
3495 fprintf (stderr, "failed to close sel pipe: %s\n",
3496 strerror (errno));
3499 CAMLreturn0;
3502 CAMLprim value ml_getpdimrect (value pagedimno_v)
3504 CAMLparam1 (pagedimno_v);
3505 CAMLlocal1 (ret_v);
3506 int pagedimno = Int_val (pagedimno_v);
3507 fz_rect box;
3509 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3510 if (trylock (__func__)) {
3511 box = fz_empty_rect;
3513 else {
3514 box = state.pagedims[pagedimno].mediabox;
3515 unlock (__func__);
3518 Store_double_field (ret_v, 0, (double) box.x0);
3519 Store_double_field (ret_v, 1, (double) box.x1);
3520 Store_double_field (ret_v, 2, (double) box.y0);
3521 Store_double_field (ret_v, 3, (double) box.y1);
3523 CAMLreturn (ret_v);
3526 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3527 value dw_v, value cols_v)
3529 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3530 CAMLlocal1 (ret_v);
3531 int i;
3532 float zoom = -1.;
3533 float maxh = 0.0;
3534 struct pagedim *p;
3535 float winw = Int_val (winw_v);
3536 float winh = Int_val (winh_v);
3537 float dw = Int_val (dw_v);
3538 float cols = Int_val (cols_v);
3539 float pw = 1.0, ph = 1.0;
3541 if (trylock (__func__)) {
3542 goto done;
3545 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3546 float w = p->pagebox.x1 / cols;
3547 float h = p->pagebox.y1;
3548 if (h > maxh) {
3549 maxh = h;
3550 ph = h;
3551 if (state.fitmodel != FitProportional) pw = w;
3553 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3556 zoom = (((winh / ph) * pw) + dw) / winw;
3557 unlock (__func__);
3558 done:
3559 ret_v = caml_copy_double ((double) zoom);
3560 CAMLreturn (ret_v);
3563 CAMLprim value ml_getmaxw (value unit_v)
3565 CAMLparam1 (unit_v);
3566 CAMLlocal1 (ret_v);
3567 int i;
3568 float maxw = -1.;
3569 struct pagedim *p;
3571 if (trylock (__func__)) {
3572 goto done;
3575 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3576 float w = p->pagebox.x1;
3577 maxw = fz_max (maxw, w);
3580 unlock (__func__);
3581 done:
3582 ret_v = caml_copy_double ((double) maxw);
3583 CAMLreturn (ret_v);
3586 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3588 CAMLparam4 (pt_v, x_v, y_v, string_v);
3589 CAMLlocal1 (ret_v);
3590 int pt = Int_val(pt_v);
3591 int x = Int_val (x_v);
3592 int y = Int_val (y_v);
3593 double w;
3595 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3596 ret_v = caml_copy_double (w);
3597 CAMLreturn (ret_v);
3600 CAMLprim value ml_measure_string (value pt_v, value string_v)
3602 CAMLparam2 (pt_v, string_v);
3603 CAMLlocal1 (ret_v);
3604 int pt = Int_val (pt_v);
3605 double w;
3607 w = (double) measure_string (state.face, pt, String_val (string_v));
3608 ret_v = caml_copy_double (w);
3609 CAMLreturn (ret_v);
3612 CAMLprim value ml_getpagebox (value opaque_v)
3614 CAMLparam1 (opaque_v);
3615 CAMLlocal1 (ret_v);
3616 fz_rect rect;
3617 fz_irect bbox;
3618 fz_matrix ctm;
3619 fz_device *dev;
3620 char *s = String_val (opaque_v);
3621 struct page *page = parse_pointer (__func__, s);
3623 ret_v = caml_alloc_tuple (4);
3624 dev = fz_new_bbox_device (state.ctx, &rect);
3626 ctm = pagectm (page);
3627 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3629 fz_close_device (state.ctx, dev);
3630 fz_drop_device (state.ctx, dev);
3631 fz_round_rect (&bbox, &rect);
3632 Field (ret_v, 0) = Val_int (bbox.x0);
3633 Field (ret_v, 1) = Val_int (bbox.y0);
3634 Field (ret_v, 2) = Val_int (bbox.x1);
3635 Field (ret_v, 3) = Val_int (bbox.y1);
3637 CAMLreturn (ret_v);
3640 CAMLprim void ml_setaalevel (value level_v)
3642 CAMLparam1 (level_v);
3644 state.aalevel = Int_val (level_v);
3645 CAMLreturn0;
3648 #ifndef __COCOA__
3649 #pragma GCC diagnostic push
3650 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3651 #include <X11/Xlib.h>
3652 #include <X11/cursorfont.h>
3653 #pragma GCC diagnostic pop
3655 #ifdef USE_EGL
3656 #include <EGL/egl.h>
3657 #else
3658 #include <GL/glx.h>
3659 #endif
3661 static const int shapes[] = {
3662 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3665 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3667 static struct {
3668 Window wid;
3669 Display *dpy;
3670 #ifdef USE_EGL
3671 EGLContext ctx;
3672 EGLConfig conf;
3673 EGLSurface win;
3674 EGLDisplay *edpy;
3675 #else
3676 GLXContext ctx;
3677 #endif
3678 XVisualInfo *visual;
3679 Cursor curs[CURS_COUNT];
3680 } glx;
3683 static void initcurs (void)
3685 for (size_t n = 0; n < CURS_COUNT; ++n) {
3686 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3690 CAMLprim void ml_setbgcol (value color_v)
3692 CAMLparam1 (color_v);
3693 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3694 CAMLreturn0;
3697 #ifdef USE_EGL
3698 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3700 CAMLparam3 (display_v, wid_v, screen_v);
3701 int major, minor;
3702 int num_conf;
3703 EGLint visid;
3704 EGLint attribs[] = {
3705 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3706 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3707 EGL_NONE
3709 EGLConfig conf;
3711 glx.dpy = XOpenDisplay (String_val (display_v));
3712 if (!glx.dpy) {
3713 caml_failwith ("XOpenDisplay");
3716 eglBindAPI (EGL_OPENGL_API);
3718 glx.edpy = eglGetDisplay (glx.dpy);
3719 if (glx.edpy == EGL_NO_DISPLAY) {
3720 caml_failwith ("eglGetDisplay");
3723 if (!eglInitialize (glx.edpy, &major, &minor)) {
3724 caml_failwith ("eglInitialize");
3727 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3728 !num_conf) {
3729 caml_failwith ("eglChooseConfig");
3732 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3733 caml_failwith ("eglGetConfigAttrib");
3736 glx.conf = conf;
3737 initcurs ();
3739 glx.wid = Int_val (wid_v);
3740 CAMLreturn (Val_int (visid));
3743 CAMLprim void ml_glxcompleteinit (value unit_v)
3745 CAMLparam1 (unit_v);
3747 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3748 if (!glx.ctx) {
3749 caml_failwith ("eglCreateContext");
3752 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3753 glx.wid, NULL);
3754 if (glx.win == EGL_NO_SURFACE) {
3755 caml_failwith ("eglCreateWindowSurface");
3758 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3759 glx.ctx = NULL;
3760 caml_failwith ("eglMakeCurrent");
3762 CAMLreturn0;
3764 #else
3765 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3767 CAMLparam3 (display_v, wid_v, screen_v);
3769 glx.dpy = XOpenDisplay (String_val (display_v));
3770 if (!glx.dpy) {
3771 caml_failwith ("XOpenDisplay");
3774 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3775 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3776 if (!glx.visual) {
3777 XCloseDisplay (glx.dpy);
3778 caml_failwith ("glXChooseVisual");
3781 initcurs ();
3783 glx.wid = Int_val (wid_v);
3784 CAMLreturn (Val_int (glx.visual->visualid));
3787 CAMLprim void ml_glxcompleteinit (value unit_v)
3789 CAMLparam1 (unit_v);
3791 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3792 if (!glx.ctx) {
3793 caml_failwith ("glXCreateContext");
3796 XFree (glx.visual);
3797 glx.visual = NULL;
3799 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3800 glXDestroyContext (glx.dpy, glx.ctx);
3801 glx.ctx = NULL;
3802 caml_failwith ("glXMakeCurrent");
3804 CAMLreturn0;
3806 #endif
3808 CAMLprim void ml_setcursor (value cursor_v)
3810 CAMLparam1 (cursor_v);
3811 size_t cursn = Int_val (cursor_v);
3813 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3814 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3815 XFlush (glx.dpy);
3816 CAMLreturn0;
3819 CAMLprim void ml_swapb (value unit_v)
3821 CAMLparam1 (unit_v);
3822 #ifdef USE_EGL
3823 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3824 caml_failwith ("eglSwapBuffers");
3826 #else
3827 glXSwapBuffers (glx.dpy, glx.wid);
3828 #endif
3829 CAMLreturn0;
3832 #pragma GCC diagnostic push
3833 #pragma GCC diagnostic ignored "-Wmissing-variable-declarations"
3834 #include "keysym2ucs.c"
3835 #pragma GCC diagnostic pop
3837 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3839 CAMLparam1 (keysym_v);
3840 CAMLlocal1 (str_v);
3841 KeySym keysym = Int_val (keysym_v);
3842 Rune rune;
3843 int len;
3844 char buf[5];
3846 rune = (Rune) keysym2ucs (keysym);
3847 len = fz_runetochar (buf, rune);
3848 buf[len] = 0;
3849 str_v = caml_copy_string (buf);
3850 CAMLreturn (str_v);
3852 #else
3853 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3855 CAMLparam1 (keysym_v);
3856 CAMLlocal1 (str_v);
3857 long ucs_v = Long_val (keysym_v);
3858 int len;
3859 char buf[5];
3861 len = fz_runetochar (buf, ucs_v);
3862 buf[len] = 0;
3863 str_v = caml_copy_string (buf);
3864 CAMLreturn (str_v);
3866 #endif
3868 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3870 CAMLprim value ml_platform (value unit_v)
3872 CAMLparam1 (unit_v);
3873 CAMLlocal2 (tup_v, arr_v);
3874 int platid = piunknown;
3875 struct utsname buf;
3877 #if defined __linux__
3878 platid = pilinux;
3879 #elif defined __CYGWIN__
3880 platid = picygwin;
3881 #elif defined __DragonFly__ || defined __FreeBSD__
3882 || defined __OpenBSD__ || defined __NetBSD__
3883 platid = pibsd;
3884 #elif defined __sun__
3885 platid = pisun;
3886 #elif defined __APPLE__
3887 platid = piosx;
3888 #endif
3889 if (uname (&buf)) err (1, "uname");
3891 tup_v = caml_alloc_tuple (2);
3893 char const *sar[] = {
3894 buf.sysname,
3895 buf.release,
3896 buf.version,
3897 buf.machine,
3898 NULL
3900 arr_v = caml_copy_string_array (sar);
3902 Field (tup_v, 0) = Val_int (platid);
3903 Field (tup_v, 1) = arr_v;
3904 CAMLreturn (tup_v);
3907 CAMLprim void ml_cloexec (value fd_v)
3909 CAMLparam1 (fd_v);
3910 int fd = Int_val (fd_v);
3912 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3913 uerror ("fcntl", Nothing);
3915 CAMLreturn0;
3918 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3920 CAMLparam2 (w_v, h_v);
3921 CAMLlocal1 (ret_v);
3922 struct bo *pbo;
3923 int w = Int_val (w_v);
3924 int h = Int_val (h_v);
3925 int cs = Int_val (cs_v);
3927 if (state.bo_usable) {
3928 pbo = calloc (sizeof (*pbo), 1);
3929 if (!pbo) {
3930 err (1, "calloc pbo");
3933 switch (cs) {
3934 case 0:
3935 case 1:
3936 pbo->size = w*h*4;
3937 break;
3938 case 2:
3939 pbo->size = w*h*2;
3940 break;
3941 default:
3942 errx (1, "%s: invalid colorspace %d", __func__, cs);
3945 state.glGenBuffersARB (1, &pbo->id);
3946 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3947 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3948 NULL, GL_STREAM_DRAW);
3949 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3950 GL_READ_WRITE);
3951 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3952 if (!pbo->ptr) {
3953 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3954 state.glDeleteBuffersARB (1, &pbo->id);
3955 free (pbo);
3956 ret_v = caml_copy_string ("0");
3958 else {
3959 int res;
3960 char *s;
3962 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3963 if (res < 0) {
3964 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3966 s = malloc (res+1);
3967 if (!s) {
3968 err (1, "malloc %d bytes failed", res+1);
3970 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3971 if (res < 0) {
3972 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3974 ret_v = caml_copy_string (s);
3975 free (s);
3978 else {
3979 ret_v = caml_copy_string ("0");
3981 CAMLreturn (ret_v);
3984 CAMLprim void ml_freepbo (value s_v)
3986 CAMLparam1 (s_v);
3987 char *s = String_val (s_v);
3988 struct tile *tile = parse_pointer (__func__, s);
3990 if (tile->pbo) {
3991 state.glDeleteBuffersARB (1, &tile->pbo->id);
3992 tile->pbo->id = -1;
3993 tile->pbo->ptr = NULL;
3994 tile->pbo->size = -1;
3996 CAMLreturn0;
3999 CAMLprim void ml_unmappbo (value s_v)
4001 CAMLparam1 (s_v);
4002 char *s = String_val (s_v);
4003 struct tile *tile = parse_pointer (__func__, s);
4005 if (tile->pbo) {
4006 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4007 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4008 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4010 tile->pbo->ptr = NULL;
4011 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4013 CAMLreturn0;
4016 static void setuppbo (void)
4018 #ifdef __COCOA__
4019 static CFBundleRef framework = NULL;
4020 if (framework == NULL)
4021 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
4022 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
4023 #else
4024 #ifdef USE_EGL
4025 #define GGPA(n) (*(void (**) (void)) &state.n = eglGetProcAddress (#n))
4026 #else
4027 #define GGPA(n) (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
4028 #endif
4029 state.bo_usable = GGPA (glBindBufferARB)
4030 && GGPA (glUnmapBufferARB)
4031 && GGPA (glMapBufferARB)
4032 && GGPA (glBufferDataARB)
4033 && GGPA (glGenBuffersARB)
4034 && GGPA (glDeleteBuffersARB);
4035 #endif
4036 #undef GGPA
4039 CAMLprim value ml_bo_usable (value unit_v)
4041 CAMLparam1 (unit_v);
4042 CAMLreturn (Val_bool (state.bo_usable));
4045 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4047 CAMLparam3 (ptr_v, x_v, y_v);
4048 CAMLlocal2 (ret_v, tup_v);
4049 struct page *page;
4050 char *s = String_val (ptr_v);
4051 int x = Int_val (x_v), y = Int_val (y_v);
4052 struct pagedim *pdim;
4053 fz_point p;
4054 fz_matrix ctm;
4056 page = parse_pointer (__func__, s);
4057 pdim = &state.pagedims[page->pdimno];
4059 ret_v = Val_int (0);
4060 if (trylock (__func__)) {
4061 goto done;
4064 if (pdf_specifics (state.ctx, state.doc)) {
4065 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4066 ctm = state.pagedims[page->pdimno].tctm;
4068 else {
4069 ctm = fz_identity;
4071 p.x = x + pdim->bounds.x0;
4072 p.y = y + pdim->bounds.y0;
4074 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4075 fz_invert_matrix (&ctm, &ctm);
4076 fz_transform_point (&p, &ctm);
4078 tup_v = caml_alloc_tuple (2);
4079 ret_v = caml_alloc_small (1, 1);
4080 Field (tup_v, 0) = Val_int (p.x);
4081 Field (tup_v, 1) = Val_int (p.y);
4082 Field (ret_v, 0) = tup_v;
4084 unlock (__func__);
4085 done:
4086 CAMLreturn (ret_v);
4089 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4090 value x_v, value y_v)
4092 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4093 CAMLlocal1 (ret_v);
4094 struct page *page;
4095 char *s = String_val (ptr_v);
4096 int pageno = Int_val (pageno_v);
4097 int pdimno = Int_val (pdimno_v);
4098 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
4099 struct pagedim *pdim;
4100 fz_point p;
4101 fz_matrix ctm;
4103 ret_v = Val_int (0);
4104 lock (__func__);
4106 if (!*s) {
4107 page = loadpage (pageno, pdimno);
4109 else {
4110 page = parse_pointer (__func__, s);
4112 pdim = &state.pagedims[pdimno];
4114 if (pdf_specifics (state.ctx, state.doc)) {
4115 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4116 ctm = state.pagedims[page->pdimno].tctm;
4118 else {
4119 ctm = fz_identity;
4121 p.x = x + pdim->bounds.x0;
4122 p.y = y + pdim->bounds.y0;
4124 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4125 fz_transform_point (&p, &ctm);
4127 ret_v = caml_alloc_tuple (2);
4128 Field (ret_v, 0) = caml_copy_double ((double) p.x);
4129 Field (ret_v, 1) = caml_copy_double ((double) p.y);
4131 if (!*s) {
4132 freepage (page);
4134 unlock (__func__);
4135 CAMLreturn (ret_v);
4138 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4139 value contents_v)
4141 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4142 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4144 if (pdf) {
4145 pdf_annot *annot;
4146 struct page *page;
4147 fz_point p;
4148 char *s = String_val (ptr_v);
4150 page = parse_pointer (__func__, s);
4151 annot = pdf_create_annot (state.ctx,
4152 pdf_page_from_fz_page (state.ctx,
4153 page->fzpage),
4154 PDF_ANNOT_TEXT);
4155 p.x = Int_val (x_v);
4156 p.y = Int_val (y_v);
4157 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4158 pdf_set_text_annot_position (state.ctx, annot, p);
4159 state.dirty = 1;
4161 CAMLreturn0;
4164 CAMLprim void ml_delannot (value ptr_v, value n_v)
4166 CAMLparam2 (ptr_v, n_v);
4167 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4169 if (pdf) {
4170 struct page *page;
4171 char *s = String_val (ptr_v);
4172 struct slink *slink;
4174 page = parse_pointer (__func__, s);
4175 slink = &page->slinks[Int_val (n_v)];
4176 pdf_delete_annot (state.ctx,
4177 pdf_page_from_fz_page (state.ctx, page->fzpage),
4178 (pdf_annot *) slink->u.annot);
4179 state.dirty = 1;
4181 CAMLreturn0;
4184 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4186 CAMLparam3 (ptr_v, n_v, str_v);
4187 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4189 if (pdf) {
4190 struct page *page;
4191 char *s = String_val (ptr_v);
4192 struct slink *slink;
4194 page = parse_pointer (__func__, s);
4195 slink = &page->slinks[Int_val (n_v)];
4196 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4197 String_val (str_v));
4198 state.dirty = 1;
4200 CAMLreturn0;
4203 CAMLprim value ml_hasunsavedchanges (value unit_v)
4205 CAMLparam1 (unit_v);
4206 CAMLreturn (Val_bool (state.dirty));
4209 CAMLprim void ml_savedoc (value path_v)
4211 CAMLparam1 (path_v);
4212 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4214 if (pdf) {
4215 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4217 CAMLreturn0;
4220 static void makestippletex (void)
4222 const char pixels[] = "\xff\xff\0\0";
4223 glGenTextures (1, &state.stid);
4224 glBindTexture (GL_TEXTURE_1D, state.stid);
4225 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4226 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4227 glTexImage1D (
4228 GL_TEXTURE_1D,
4230 GL_ALPHA,
4233 GL_ALPHA,
4234 GL_UNSIGNED_BYTE,
4235 pixels
4239 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4241 return caml_copy_string (FZ_VERSION);
4244 CAMLprim void ml_init (value csock_v, value params_v)
4246 CAMLparam2 (csock_v, params_v);
4247 CAMLlocal2 (trim_v, fuzz_v);
4248 int ret;
4249 int texcount;
4250 char *fontpath;
4251 int colorspace;
4252 int mustoresize;
4253 int haspboext;
4255 /* Without following call to setlocale mbstowcs fails for, at
4256 least, strings containing chinese symbols (δΈ­ for instance)
4257 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4258 wide character" as the reason of failure and with macOS
4259 producing bogus output) */
4260 if (setlocale (LC_CTYPE, "")) {
4261 /* Following two lines were taken from dvtm/vt.c */
4262 const char *cset = nl_langinfo (CODESET);
4263 state.utf8cs = !strcmp (cset, "UTF-8");
4265 else {
4266 fprintf (stderr, "setlocale failed\n");
4269 state.csock = Int_val (csock_v);
4270 state.rotate = Int_val (Field (params_v, 0));
4271 state.fitmodel = Int_val (Field (params_v, 1));
4272 trim_v = Field (params_v, 2);
4273 texcount = Int_val (Field (params_v, 3));
4274 state.sliceheight = Int_val (Field (params_v, 4));
4275 mustoresize = Int_val (Field (params_v, 5));
4276 colorspace = Int_val (Field (params_v, 6));
4277 fontpath = String_val (Field (params_v, 7));
4279 if (caml_string_length (Field (params_v, 8)) > 0) {
4280 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4282 if (!state.trimcachepath) {
4283 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4284 strerror (errno));
4288 haspboext = Bool_val (Field (params_v, 9));
4290 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4291 fz_register_document_handlers (state.ctx);
4293 state.trimmargins = Bool_val (Field (trim_v, 0));
4294 fuzz_v = Field (trim_v, 1);
4295 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4296 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4297 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4298 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4300 set_tex_params (colorspace);
4302 if (*fontpath) {
4303 state.face = load_font (fontpath);
4305 else {
4306 int len;
4307 const unsigned char *data;
4309 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4310 state.face = load_builtin_font (data, len);
4312 if (!state.face) _exit (1);
4314 realloctexts (texcount);
4316 if (haspboext) {
4317 setuppbo ();
4320 makestippletex ();
4322 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4323 if (ret) {
4324 errx (1, "pthread_create: %s", strerror (ret));
4327 CAMLreturn0;
4330 #if FIXME || !FIXME
4331 static void UNUSED_ATTR refmacs OPTIMIZE_ATTR (0) (void) {}
4332 #endif