Better naming
[llpp.git] / link.c
blobede6889604f3e5b7260d123a7fbd84bcad5a13d2
1 /* lots of code c&p-ed directly from mupdf */
2 #ifdef __clang__
3 #pragma GCC diagnostic error "-Weverything"
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 #define CAML_NAME_SPACE
12 #define FIXME 0
14 extern char **environ;
16 #include <errno.h>
17 #include <stdio.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <signal.h>
23 #include <math.h>
24 #include <wchar.h>
25 #include <locale.h>
26 #include <langinfo.h>
28 #include <unistd.h>
29 #include <pthread.h>
30 #include <sys/uio.h>
31 #include <sys/time.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/utsname.h>
38 #include <spawn.h>
40 #include <regex.h>
41 #include <stdarg.h>
42 #include <limits.h>
43 #include <inttypes.h>
45 #ifdef __COCOA__
46 #include <CoreFoundation/CoreFoundation.h>
47 #endif
49 #ifdef __APPLE__
50 #include <OpenGL/gl.h>
51 #else
52 #include <GL/gl.h>
53 #endif
55 #pragma GCC diagnostic push
56 #ifdef __clang__
57 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
58 #endif
59 #pragma GCC diagnostic ignored "-Wpedantic"
60 #include <caml/fail.h>
61 #include <caml/alloc.h>
62 #include <caml/memory.h>
63 #include <caml/unixsupport.h>
65 #pragma GCC diagnostic push
66 #pragma GCC diagnostic ignored "-Wfloat-equal"
67 #include <mupdf/fitz.h>
68 #include <mupdf/pdf.h>
69 #pragma GCC diagnostic pop
71 #include <ft2build.h>
72 #include FT_FREETYPE_H
73 #pragma GCC diagnostic pop
75 #define PIGGYBACK
76 #define CACHE_PAGEREFS
78 #if defined __GNUC__
79 #define NORETURN_ATTR __attribute__ ((noreturn))
80 #define UNUSED_ATTR __attribute__ ((unused))
81 #if !defined __clang__
82 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
83 #else
84 #define OPTIMIZE_ATTR(n)
85 #endif
86 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
87 #else
88 #define NORETURN_ATTR
89 #define UNUSED_ATTR
90 #define OPTIMIZE_ATTR(n)
91 #define GCC_FMT_ATTR(a, b)
92 #endif
94 #define FMT_s "zu"
96 #define FMT_ptr PRIxPTR
97 #define SCN_ptr SCNxPTR
98 #define FMT_ptr_cast(p) ((uintptr_t) (p))
99 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
101 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
102 err (int exitcode, const char *fmt, ...)
104 va_list ap;
105 int savederrno;
107 savederrno = errno;
108 va_start (ap, fmt);
109 vfprintf (stderr, fmt, ap);
110 va_end (ap);
111 fprintf (stderr, ": %s\n", strerror (savederrno));
112 fflush (stderr);
113 _exit (exitcode);
116 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
117 errx (int exitcode, const char *fmt, ...)
119 va_list ap;
121 va_start (ap, fmt);
122 vfprintf (stderr, fmt, ap);
123 va_end (ap);
124 fputc ('\n', stderr);
125 fflush (stderr);
126 _exit (exitcode);
129 #ifndef GL_TEXTURE_RECTANGLE_ARB
130 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
131 #endif
133 #ifdef USE_NPOT
134 #define TEXT_TYPE GL_TEXTURE_2D
135 #else
136 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
137 #endif
139 #ifndef GL_BGRA
140 #define GL_BGRA 0x80E1
141 #endif
143 #ifndef GL_UNSIGNED_INT_8_8_8_8
144 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
145 #endif
147 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
148 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
149 #endif
151 #if 0
152 #define lprintf printf
153 #else
154 #define lprintf(...)
155 #endif
157 #define ARSERT(cond) for (;;) { \
158 if (!(cond)) { \
159 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
161 break; \
164 struct slice {
165 int h;
166 int texindex;
169 struct tile {
170 int w, h;
171 int slicecount;
172 int sliceheight;
173 struct bo *pbo;
174 fz_pixmap *pixmap;
175 struct slice slices[1];
178 struct pagedim {
179 int pageno;
180 int rotate;
181 int left;
182 int tctmready;
183 fz_irect bounds;
184 fz_rect pagebox;
185 fz_rect mediabox;
186 fz_matrix ctm, zoomctm, tctm;
189 struct slink {
190 enum { SLINK, SANNOT } tag;
191 fz_irect bbox;
192 union {
193 fz_link *link;
194 fz_annot *annot;
195 } u;
198 struct annot {
199 fz_irect bbox;
200 fz_annot *annot;
203 struct page {
204 int tgen;
205 int sgen;
206 int agen;
207 int pageno;
208 int pdimno;
209 fz_stext_page *text;
210 fz_page *fzpage;
211 fz_display_list *dlist;
212 fz_link *links;
213 int slinkcount;
214 struct slink *slinks;
215 int annotcount;
216 struct annot *annots;
217 struct mark {
218 fz_stext_char *ch;
219 } fmark, lmark;
222 enum { FitWidth, FitProportional, FitPage };
224 static struct {
225 int sliceheight;
226 struct pagedim *pagedims;
227 int pagecount;
228 int pagedimcount;
229 fz_document *doc;
230 fz_context *ctx;
231 int w, h;
233 int texindex;
234 int texcount;
235 GLuint *texids;
237 GLenum texiform;
238 GLenum texform;
239 GLenum texty;
241 fz_colorspace *colorspace;
243 struct {
244 int w, h;
245 struct slice *slice;
246 } *texowners;
248 int rotate;
249 int fitmodel;
250 int trimmargins;
251 int needoutline;
252 int gen;
253 int aalevel;
255 int trimanew;
256 fz_irect trimfuzz;
257 fz_pixmap *pig;
259 pthread_t thread;
260 int csock;
261 FT_Face face;
263 char *trimcachepath;
264 int dirty;
266 GLuint stid;
268 int bo_usable;
269 GLuint boid;
271 void (*glBindBufferARB) (GLenum, GLuint);
272 GLboolean (*glUnmapBufferARB) (GLenum);
273 void *(*glMapBufferARB) (GLenum, GLenum);
274 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
275 void (*glGenBuffersARB) (GLsizei, GLuint *);
276 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
278 GLfloat texcoords[8];
279 GLfloat vertices[16];
281 #ifdef CACHE_PAGEREFS
282 struct {
283 int idx;
284 int count;
285 pdf_obj **objs;
286 pdf_document *pdf;
287 } pdflut;
288 #endif
289 int utf8cs;
290 } state;
292 struct bo {
293 GLuint id;
294 void *ptr;
295 size_t size;
298 #pragma GCC diagnostic ignored "-Wdouble-promotion"
299 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
301 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
304 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
306 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
309 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
311 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
312 m.a, m.b, m.c, m.d, m.e, m.f);
314 #pragma GCC diagnostic error "-Wdouble-promotion"
316 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
318 static void lock (const char *cap)
320 int ret = pthread_mutex_lock (&mutex);
321 if (ret) {
322 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
326 static void unlock (const char *cap)
328 int ret = pthread_mutex_unlock (&mutex);
329 if (ret) {
330 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
334 static int trylock (const char *cap)
336 int ret = pthread_mutex_trylock (&mutex);
337 if (ret && ret != EBUSY) {
338 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
340 return ret == EBUSY;
343 static void *parse_pointer (const char *cap, const char *s)
345 int ret;
346 void *ptr;
348 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
349 if (ret != 1) {
350 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
352 return ptr;
355 static double now (void)
357 struct timeval tv;
359 if (gettimeofday (&tv, NULL)) {
360 err (1, "gettimeofday");
362 return tv.tv_sec + tv.tv_usec*1e-6;
365 static int hasdata (void)
367 int ret, avail;
368 ret = ioctl (state.csock, FIONREAD, &avail);
369 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
370 return avail > 0;
373 CAMLprim value ml_hasdata (value fd_v)
375 CAMLparam1 (fd_v);
376 int ret, avail;
378 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
379 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
380 CAMLreturn (Val_bool (avail > 0));
383 static void readdata (int fd, void *p, int size)
385 ssize_t n;
387 again:
388 n = read (fd, p, size);
389 if (n - size) {
390 if (n < 0 && errno == EINTR) goto again;
391 if (!n) errx (1, "EOF while reading");
392 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
396 static void writedata (int fd, char *p, int size)
398 ssize_t n;
399 uint32_t size4 = size;
400 struct iovec iov[2] = {
401 { .iov_base = &size4, .iov_len = 4 },
402 { .iov_base = p, .iov_len = size }
405 again:
406 n = writev (fd, iov, 2);
407 if (n < 0 && errno == EINTR) goto again;
408 if (n - size - 4) {
409 if (!n) errx (1, "EOF while writing data");
410 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
414 static int readlen (int fd)
416 uint32_t u;
417 readdata (fd, &u, 4);
418 return u;
421 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
423 CAMLparam3 (fd_v, bytes_v, len_v);
424 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
425 CAMLreturn0;
428 CAMLprim value ml_rcmd (value fd_v)
430 CAMLparam1 (fd_v);
431 CAMLlocal1 (strdata_v);
432 int fd = Int_val (fd_v);
433 int len = readlen (fd);
434 strdata_v = caml_alloc_string (len);
435 readdata (fd, String_val (strdata_v), len);
436 CAMLreturn (strdata_v);
439 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
441 char fbuf[64];
442 int size = sizeof (fbuf), len;
443 va_list ap;
444 char *buf = fbuf;
446 for (;;) {
447 va_start (ap, fmt);
448 len = vsnprintf (buf, size, fmt, ap);
449 va_end (ap);
451 if (len > -1) {
452 if (len < size - 4) {
453 writedata (state.csock, buf, len);
454 break;
456 else size = len + 5;
458 else {
459 err (1, "vsnprintf for `%s' failed", fmt);
461 buf = realloc (buf == fbuf ? NULL : buf, size);
462 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
464 if (buf != fbuf) free (buf);
467 static void closedoc (void)
469 #ifdef CACHE_PAGEREFS
470 if (state.pdflut.objs) {
471 for (int i = 0; i < state.pdflut.count; ++i) {
472 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
474 free (state.pdflut.objs);
475 state.pdflut.objs = NULL;
476 state.pdflut.idx = 0;
478 #endif
479 if (state.doc) {
480 fz_drop_document (state.ctx, state.doc);
481 state.doc = NULL;
485 static int openxref (char *filename, char *password, int layouth)
487 for (int i = 0; i < state.texcount; ++i) {
488 state.texowners[i].w = -1;
489 state.texowners[i].slice = NULL;
492 closedoc ();
494 state.dirty = 0;
495 if (state.pagedims) {
496 free (state.pagedims);
497 state.pagedims = NULL;
499 state.pagedimcount = 0;
501 fz_set_aa_level (state.ctx, state.aalevel);
502 state.doc = fz_open_document (state.ctx, filename);
503 if (fz_needs_password (state.ctx, state.doc)) {
504 if (password && !*password) {
505 printd ("pass");
506 return 0;
508 else {
509 int ok = fz_authenticate_password (state.ctx, state.doc, password);
510 if (!ok) {
511 printd ("pass fail");
512 return 0;
516 if (layouth >= 0)
517 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
518 state.pagecount = fz_count_pages (state.ctx, state.doc);
519 return 1;
522 static void docinfo (void)
524 struct { char *tag; char *name; } metatbl[] = {
525 { FZ_META_INFO_TITLE, "Title" },
526 { FZ_META_INFO_AUTHOR, "Author" },
527 { FZ_META_FORMAT, "Format" },
528 { FZ_META_ENCRYPTION, "Encryption" },
529 { "info:Creator", "Creator" },
530 { "info:Producer", "Producer" },
531 { "info:CreationDate", "Creation date" },
533 int len = 0;
534 char *buf = NULL;
536 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
537 int need;
538 again:
539 need = fz_lookup_metadata (state.ctx, state.doc,
540 metatbl[i].tag, buf, len);
541 if (need > 0) {
542 if (need <= len) {
543 printd ("info %s\t%s", metatbl[i].name, buf);
545 else {
546 buf = realloc (buf, need + 1);
547 if (!buf) err (1, "docinfo realloc %d", need + 1);
548 len = need + 1;
549 goto again;
553 free (buf);
555 printd ("infoend");
558 static void unlinktile (struct tile *tile)
560 for (int i = 0; i < tile->slicecount; ++i) {
561 struct slice *s = &tile->slices[i];
563 if (s->texindex != -1) {
564 if (state.texowners[s->texindex].slice == s) {
565 state.texowners[s->texindex].slice = NULL;
571 static void freepage (struct page *page)
573 if (!page) return;
574 if (page->text) {
575 fz_drop_stext_page (state.ctx, page->text);
577 if (page->slinks) {
578 free (page->slinks);
580 fz_drop_display_list (state.ctx, page->dlist);
581 fz_drop_page (state.ctx, page->fzpage);
582 free (page);
585 static void freetile (struct tile *tile)
587 unlinktile (tile);
588 if (!tile->pbo) {
589 #ifndef PIGGYBACK
590 fz_drop_pixmap (state.ctx, tile->pixmap);
591 #else
592 if (state.pig) {
593 fz_drop_pixmap (state.ctx, state.pig);
595 state.pig = tile->pixmap;
596 #endif
598 else {
599 free (tile->pbo);
600 fz_drop_pixmap (state.ctx, tile->pixmap);
602 free (tile);
605 #ifdef __ALTIVEC__
606 #include <stdint.h>
607 #include <altivec.h>
609 static int cacheline32bytes;
611 static void __attribute__ ((constructor)) clcheck (void)
613 char **envp = environ;
614 unsigned long *auxv;
616 while (*envp++);
618 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
619 if (*auxv == 19) {
620 cacheline32bytes = auxv[1] == 32;
621 return;
626 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
628 size_t size = pixmap->w * pixmap->h * pixmap->n;
629 if (cacheline32bytes && size > 32) {
630 intptr_t a1, a2, diff;
631 size_t sizea, i;
632 vector unsigned char v = vec_splat_u8 (-1);
633 vector unsigned char *p;
635 a1 = a2 = (intptr_t) pixmap->samples;
636 a2 = (a1 + 31) & ~31;
637 diff = a2 - a1;
638 sizea = size - diff;
639 p = (void *) a2;
641 while (a1 != a2) *(char *) a1++ = 0xff;
642 for (i = 0; i < (sizea & ~31); i += 32) {
643 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
644 vec_st (v, i, p);
645 vec_st (v, i + 16, p);
647 while (i < sizea) *((char *) a1 + i++) = 0xff;
649 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
651 #else
652 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
653 #endif
655 static void trimctm (pdf_page *page, int pindex)
657 fz_matrix ctm;
658 struct pagedim *pdim = &state.pagedims[pindex];
660 if (!page) return;
661 if (!pdim->tctmready) {
662 fz_rect realbox, mediabox;
663 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
665 fz_rotate (&rm, -pdim->rotate);
666 fz_scale (&sm, 1, -1);
667 fz_concat (&ctm, &rm, &sm);
668 realbox = pdim->mediabox;
669 fz_transform_rect (&realbox, &ctm);
670 fz_translate (&tm, -realbox.x0, -realbox.y0);
671 fz_concat (&ctm1, &ctm, &tm);
672 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
673 fz_invert_matrix (&im, &page_ctm);
674 fz_concat (&ctm, &im, &ctm1);
675 pdim->tctm = ctm;
676 pdim->tctmready = 1;
680 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
682 fz_matrix ctm, tm;
683 ptrdiff_t pdimno = pdim - state.pagedims;
685 ARSERT (pdim - state.pagedims < INT_MAX);
686 if (pdf_specifics (state.ctx, state.doc)) {
687 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
688 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
690 else {
691 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
692 fz_concat (&ctm, &tm, &pdim->ctm);
694 return ctm;
697 static fz_matrix pagectm (struct page *page)
699 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
702 static void *loadpage (int pageno, int pindex)
704 fz_device *dev;
705 struct page *page;
707 page = calloc (sizeof (struct page), 1);
708 if (!page) {
709 err (1, "calloc page %d", pageno);
712 page->dlist = fz_new_display_list (state.ctx, NULL);
713 dev = fz_new_list_device (state.ctx, page->dlist);
714 fz_try (state.ctx) {
715 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
716 fz_run_page (state.ctx, page->fzpage, dev,
717 &fz_identity, NULL);
719 fz_catch (state.ctx) {
720 page->fzpage = NULL;
722 fz_close_device (state.ctx, dev);
723 fz_drop_device (state.ctx, dev);
725 page->pdimno = pindex;
726 page->pageno = pageno;
727 page->sgen = state.gen;
728 page->agen = state.gen;
729 page->tgen = state.gen;
730 return page;
733 static struct tile *alloctile (int h)
735 int slicecount;
736 size_t tilesize;
737 struct tile *tile;
739 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
740 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
741 tile = calloc (tilesize, 1);
742 if (!tile) {
743 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
745 for (int i = 0; i < slicecount; ++i) {
746 int sh = fz_mini (h, state.sliceheight);
747 tile->slices[i].h = sh;
748 tile->slices[i].texindex = -1;
749 h -= sh;
751 tile->slicecount = slicecount;
752 tile->sliceheight = state.sliceheight;
753 return tile;
756 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
757 struct bo *pbo)
759 fz_rect rect;
760 fz_irect bbox;
761 fz_matrix ctm;
762 fz_device *dev;
763 struct tile *tile;
764 struct pagedim *pdim;
766 tile = alloctile (h);
767 pdim = &state.pagedims[page->pdimno];
769 bbox = pdim->bounds;
770 bbox.x0 += x;
771 bbox.y0 += y;
772 bbox.x1 = bbox.x0 + w;
773 bbox.y1 = bbox.y0 + h;
775 if (state.pig) {
776 if (state.pig->w == w
777 && state.pig->h == h
778 && state.pig->colorspace == state.colorspace) {
779 tile->pixmap = state.pig;
780 tile->pixmap->x = bbox.x0;
781 tile->pixmap->y = bbox.y0;
783 else {
784 fz_drop_pixmap (state.ctx, state.pig);
786 state.pig = NULL;
788 if (!tile->pixmap) {
789 if (pbo) {
790 tile->pixmap =
791 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
792 &bbox, NULL, 1, pbo->ptr);
793 tile->pbo = pbo;
795 else {
796 tile->pixmap =
797 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
798 NULL, 1);
802 tile->w = w;
803 tile->h = h;
804 clearpixmap (tile->pixmap);
806 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
807 ctm = pagectm (page);
808 fz_rect_from_irect (&rect, &bbox);
809 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
810 fz_close_device (state.ctx, dev);
811 fz_drop_device (state.ctx, dev);
813 return tile;
816 #ifdef CACHE_PAGEREFS
817 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
818 thanks to Robin Watts */
819 static void
820 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
822 fz_context *ctx = state.ctx; /* doc->ctx; */
823 pdf_obj *kids;
824 int len;
826 if (state.pdflut.idx == state.pagecount) return;
828 kids = pdf_dict_gets (ctx, node, "Kids");
829 len = pdf_array_len (ctx, kids);
831 if (len == 0)
832 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
834 if (pdf_mark_obj (ctx, node))
835 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
836 for (int i = 0; i < len; i++) {
837 pdf_obj *kid = pdf_array_get (ctx, kids, i);
838 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
839 if (*type
840 ? !strcmp (type, "Pages")
841 : pdf_dict_gets (ctx, kid, "Kids")
842 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
843 pdf_collect_pages (doc, kid);
845 else {
846 if (*type
847 ? strcmp (type, "Page") != 0
848 : !pdf_dict_gets (ctx, kid, "MediaBox"))
849 fz_warn (ctx, "non-page object in page tree (%s)", type);
850 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
853 pdf_unmark_obj (ctx, node);
856 static void
857 pdf_load_page_objs (pdf_document *doc)
859 pdf_obj *root = pdf_dict_gets (state.ctx,
860 pdf_trailer (state.ctx, doc), "Root");
861 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
863 if (!node)
864 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
866 state.pdflut.idx = 0;
867 pdf_collect_pages (doc, node);
869 #endif
871 static void initpdims (void)
873 double start, end;
874 FILE *trimf = NULL;
875 fz_rect rootmediabox = fz_empty_rect;
876 int pageno, trim, show;
877 int trimw = 0, cxcount;
878 fz_context *ctx = state.ctx;
879 pdf_document *pdf = pdf_specifics (ctx, state.doc);
881 fz_var (trimw);
882 fz_var (trimf);
883 fz_var (cxcount);
884 start = now ();
886 if (state.trimmargins && state.trimcachepath) {
887 trimf = fopen (state.trimcachepath, "rb");
888 if (!trimf) {
889 trimf = fopen (state.trimcachepath, "wb");
890 trimw = 1;
894 if (state.trimmargins || pdf)
895 cxcount = state.pagecount;
896 else
897 cxcount = fz_mini (state.pagecount, 1);
899 if (pdf) {
900 pdf_obj *obj;
901 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
902 "Root/Pages/MediaBox");
903 pdf_to_rect (ctx, obj, &rootmediabox);
906 #ifdef CACHE_PAGEREFS
907 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
908 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
909 if (!state.pdflut.objs) {
910 err (1, "malloc pageobjs %zu %d %zu failed",
911 sizeof (*state.pdflut.objs), cxcount,
912 sizeof (*state.pdflut.objs) * cxcount);
914 state.pdflut.count = cxcount;
915 pdf_load_page_objs (pdf);
916 state.pdflut.pdf = pdf;
918 #endif
920 for (pageno = 0; pageno < cxcount; ++pageno) {
921 int rotate = 0;
922 struct pagedim *p;
923 fz_rect mediabox = fz_empty_rect;
925 fz_var (rotate);
926 if (pdf) {
927 pdf_obj *pageref, *pageobj;
929 #ifdef CACHE_PAGEREFS
930 pageref = state.pdflut.objs[pageno];
931 #else
932 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
933 #endif
934 pageobj = pdf_resolve_indirect (ctx, pageref);
935 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
937 if (state.trimmargins) {
938 pdf_obj *obj;
939 pdf_page *page;
941 fz_try (ctx) {
942 page = pdf_load_page (ctx, pdf, pageno);
943 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
944 trim = state.trimanew || !obj;
945 if (trim) {
946 fz_rect rect;
947 fz_device *dev;
948 fz_matrix ctm, page_ctm;
950 dev = fz_new_bbox_device (ctx, &rect);
951 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
952 fz_invert_matrix (&ctm, &page_ctm);
953 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
954 fz_close_device (ctx, dev);
955 fz_drop_device (ctx, dev);
957 rect.x0 += state.trimfuzz.x0;
958 rect.x1 += state.trimfuzz.x1;
959 rect.y0 += state.trimfuzz.y0;
960 rect.y1 += state.trimfuzz.y1;
961 fz_transform_rect (&rect, &ctm);
962 fz_intersect_rect (&rect, &mediabox);
964 if (!fz_is_empty_rect (&rect)) {
965 mediabox = rect;
968 obj = pdf_new_array (ctx, pdf, 4);
969 pdf_array_push (ctx, obj,
970 pdf_new_real (ctx, mediabox.x0));
971 pdf_array_push (ctx, obj,
972 pdf_new_real (ctx, mediabox.y0));
973 pdf_array_push (ctx, obj,
974 pdf_new_real (ctx, mediabox.x1));
975 pdf_array_push (ctx, obj,
976 pdf_new_real (ctx, mediabox.y1));
977 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
979 else {
980 mediabox.x0 = pdf_to_real (ctx,
981 pdf_array_get (ctx, obj, 0));
982 mediabox.y0 = pdf_to_real (ctx,
983 pdf_array_get (ctx, obj, 1));
984 mediabox.x1 = pdf_to_real (ctx,
985 pdf_array_get (ctx, obj, 2));
986 mediabox.y1 = pdf_to_real (ctx,
987 pdf_array_get (ctx, obj, 3));
990 fz_drop_page (ctx, &page->super);
991 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
992 if (show) {
993 printd ("progress %f Trimming %d",
994 (double) (pageno + 1) / state.pagecount,
995 pageno + 1);
998 fz_catch (ctx) {
999 printd ("emsg failed to load page %d", pageno);
1002 else {
1003 int empty = 0;
1004 fz_rect cropbox;
1006 pdf_to_rect (ctx,
1007 pdf_dict_gets (ctx, pageobj, "MediaBox"),
1008 &mediabox);
1009 if (fz_is_empty_rect (&mediabox)) {
1010 mediabox.x0 = 0;
1011 mediabox.y0 = 0;
1012 mediabox.x1 = 612;
1013 mediabox.y1 = 792;
1014 empty = 1;
1017 pdf_to_rect (ctx,
1018 pdf_dict_gets (ctx, pageobj, "CropBox"),
1019 &cropbox);
1020 if (!fz_is_empty_rect (&cropbox)) {
1021 if (empty) {
1022 mediabox = cropbox;
1024 else {
1025 fz_intersect_rect (&mediabox, &cropbox);
1028 else {
1029 if (empty) {
1030 if (fz_is_empty_rect (&rootmediabox)) {
1031 printd ("emsg cannot find page size for page %d",
1032 pageno);
1034 else {
1035 mediabox = rootmediabox;
1041 else {
1042 if (state.trimmargins && trimw) {
1043 fz_page *page;
1045 fz_try (ctx) {
1046 page = fz_load_page (ctx, state.doc, pageno);
1047 fz_bound_page (ctx, page, &mediabox);
1048 if (state.trimmargins) {
1049 fz_rect rect;
1050 fz_device *dev;
1052 dev = fz_new_bbox_device (ctx, &rect);
1053 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1054 fz_close_device (ctx, dev);
1055 fz_drop_device (ctx, dev);
1057 rect.x0 += state.trimfuzz.x0;
1058 rect.x1 += state.trimfuzz.x1;
1059 rect.y0 += state.trimfuzz.y0;
1060 rect.y1 += state.trimfuzz.y1;
1061 fz_intersect_rect (&rect, &mediabox);
1063 if (!fz_is_empty_rect (&rect)) {
1064 mediabox = rect;
1067 fz_drop_page (ctx, page);
1069 fz_catch (ctx) {
1071 if (trimf) {
1072 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1073 if (n - 1) {
1074 err (1, "fwrite trim mediabox");
1078 else {
1079 if (trimf) {
1080 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1081 if (n - 1) {
1082 err (1, "fread trim mediabox %d", pageno);
1085 else {
1086 fz_page *page;
1087 fz_try (ctx) {
1088 page = fz_load_page (ctx, state.doc, pageno);
1089 fz_bound_page (ctx, page, &mediabox);
1090 fz_drop_page (ctx, page);
1092 show = !state.trimmargins && pageno % 20 == 0;
1093 if (show) {
1094 printd ("progress %f Gathering dimensions %d",
1095 (double) (pageno) / state.pagecount,
1096 pageno);
1099 fz_catch (ctx) {
1100 printd ("emsg failed to load page %d", pageno);
1106 if (state.pagedimcount == 0
1107 || ((void) (p = &state.pagedims[state.pagedimcount-1])
1108 , p->rotate != rotate)
1109 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1110 size_t size;
1112 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1113 state.pagedims = realloc (state.pagedims, size);
1114 if (!state.pagedims) {
1115 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1116 size, state.pagedimcount + 1);
1119 p = &state.pagedims[state.pagedimcount++];
1120 p->rotate = rotate;
1121 p->mediabox = mediabox;
1122 p->pageno = pageno;
1125 end = now ();
1126 printd ("progress 1 %s %d pages in %f seconds",
1127 state.trimmargins ? "Trimmed" : "Processed",
1128 state.pagecount, end - start);
1129 state.trimanew = 0;
1130 if (trimf) {
1131 if (fclose (trimf)) {
1132 err (1, "fclose");
1137 static void layout (void)
1139 int pindex;
1140 fz_rect box;
1141 fz_matrix ctm, rm;
1142 struct pagedim *p = NULL;
1143 float zw, w, maxw = 0.0, zoom = 1.0;
1145 if (state.pagedimcount == 0) return;
1147 switch (state.fitmodel) {
1148 case FitProportional:
1149 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1150 float x0, x1;
1152 p = &state.pagedims[pindex];
1153 fz_rotate (&rm, p->rotate + state.rotate);
1154 box = p->mediabox;
1155 fz_transform_rect (&box, &rm);
1157 x0 = fz_min (box.x0, box.x1);
1158 x1 = fz_max (box.x0, box.x1);
1160 w = x1 - x0;
1161 maxw = fz_max (w, maxw);
1162 zoom = state.w / maxw;
1164 break;
1166 case FitPage:
1167 maxw = state.w;
1168 break;
1170 case FitWidth:
1171 break;
1173 default:
1174 ARSERT (0 && state.fitmodel);
1177 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1178 fz_rect rect;
1179 fz_matrix tm, sm;
1181 p = &state.pagedims[pindex];
1182 fz_rotate (&ctm, state.rotate);
1183 fz_rotate (&rm, p->rotate + state.rotate);
1184 box = p->mediabox;
1185 fz_transform_rect (&box, &rm);
1186 w = box.x1 - box.x0;
1187 switch (state.fitmodel) {
1188 case FitProportional:
1189 p->left = (int) (((maxw - w) * zoom) / 2.f);
1190 break;
1191 case FitPage:
1193 float zh, h;
1194 zw = maxw / w;
1195 h = box.y1 - box.y0;
1196 zh = state.h / h;
1197 zoom = fz_min (zw, zh);
1198 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1200 break;
1201 case FitWidth:
1202 p->left = 0;
1203 zoom = state.w / w;
1204 break;
1207 fz_scale (&p->zoomctm, zoom, zoom);
1208 fz_concat (&ctm, &p->zoomctm, &ctm);
1210 fz_rotate (&rm, p->rotate);
1211 p->pagebox = p->mediabox;
1212 fz_transform_rect (&p->pagebox, &rm);
1213 p->pagebox.x1 -= p->pagebox.x0;
1214 p->pagebox.y1 -= p->pagebox.y0;
1215 p->pagebox.x0 = 0;
1216 p->pagebox.y0 = 0;
1217 rect = p->pagebox;
1218 fz_transform_rect (&rect, &ctm);
1219 fz_round_rect (&p->bounds, &rect);
1220 p->ctm = ctm;
1222 fz_translate (&tm, 0, -p->mediabox.y1);
1223 fz_scale (&sm, zoom, -zoom);
1224 fz_concat (&ctm, &tm, &sm);
1226 p->tctmready = 0;
1229 do {
1230 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1231 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1232 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1233 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1234 int boundw = x1 - x0;
1235 int boundh = y1 - y0;
1237 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1238 } while (p-- != state.pagedims);
1241 struct pagedim *pdimofpageno (int pageno)
1243 struct pagedim *pdim = state.pagedims;
1245 for (int i = 0; i < state.pagedimcount; ++i) {
1246 if (state.pagedims[i].pageno > pageno)
1247 break;
1248 pdim = &state.pagedims[i];
1250 return pdim;
1253 static void recurse_outline (fz_outline *outline, int level)
1255 while (outline) {
1256 if (outline->page >= 0) {
1257 fz_point p = {.x = outline->x, .y = outline->y};
1258 struct pagedim *pdim = pdimofpageno (outline->page);
1259 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1260 fz_transform_point (&p, &pdim->ctm);
1261 printd ("o %d %d %d %d %s",
1262 level, outline->page, (int) p.y, h, outline->title);
1264 else {
1265 printd ("on %d %s", level, outline->title);
1267 if (outline->down) {
1268 recurse_outline (outline->down, level + 1);
1270 outline = outline->next;
1274 static void process_outline (void)
1276 fz_outline *outline;
1278 if (!state.needoutline || !state.pagedimcount) return;
1280 state.needoutline = 0;
1281 outline = fz_load_outline (state.ctx, state.doc);
1282 if (outline) {
1283 recurse_outline (outline, 0);
1284 fz_drop_outline (state.ctx, outline);
1288 static char *strofline (fz_stext_line *line)
1290 char *p;
1291 char utf8[10];
1292 fz_stext_char *ch;
1293 size_t size = 0, cap = 80;
1295 p = malloc (cap + 1);
1296 if (!p) return NULL;
1298 for (ch = line->first_char; ch; ch = ch->next) {
1299 int n = fz_runetochar (utf8, ch->c);
1300 if (size + n > cap) {
1301 cap *= 2;
1302 p = realloc (p, cap + 1);
1303 if (!p) return NULL;
1306 memcpy (p + size, utf8, n);
1307 size += n;
1309 p[size] = 0;
1310 return p;
1313 static int matchline (regex_t *re, fz_stext_line *line,
1314 int stop, int pageno, double start)
1316 int ret;
1317 char *p;
1318 regmatch_t rm;
1320 p = strofline (line);
1321 if (!p) return -1;
1323 ret = regexec (re, p, 1, &rm, 0);
1324 if (ret) {
1325 free (p);
1326 if (ret != REG_NOMATCH) {
1327 size_t size;
1328 char errbuf[80];
1329 size = regerror (ret, re, errbuf, sizeof (errbuf));
1330 printd ("msg regexec error `%.*s'",
1331 (int) size, errbuf);
1332 return -1;
1334 return 0;
1336 else {
1337 fz_point p1, p2, p3, p4;
1338 fz_rect s = {0,0,0,0}, e;
1339 fz_stext_char *ch;
1340 int o = 0;
1342 for (ch = line->first_char; ch; ch = ch->next) {
1343 o += fz_runelen (ch->c);
1344 if (o > rm.rm_so) {
1345 s = ch->bbox;
1346 break;
1349 for (;ch; ch = ch->next) {
1350 o += fz_runelen (ch->c);
1351 if (o > rm.rm_eo) break;
1353 e = ch->bbox;
1355 p1.x = s.x0;
1356 p1.y = s.y0;
1357 p2.x = e.x1;
1358 p2.y = s.y0;
1359 p3.x = e.x1;
1360 p3.y = e.y1;
1361 p4.x = s.x0;
1362 p4.y = e.y1;
1364 #pragma GCC diagnostic ignored "-Wdouble-promotion"
1365 if (!stop) {
1366 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1367 pageno, 1,
1368 p1.x, p1.y,
1369 p2.x, p2.y,
1370 p3.x, p3.y,
1371 p4.x, p4.y);
1373 printd ("progress 1 found at %d `%.*s' in %f sec",
1374 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1375 now () - start);
1377 else {
1378 printd ("match %d %d %f %f %f %f %f %f %f %f",
1379 pageno, 2,
1380 p1.x, p1.y,
1381 p2.x, p2.y,
1382 p3.x, p3.y,
1383 p4.x, p4.y);
1385 #pragma GCC diagnostic error "-Wdouble-promotion"
1386 free (p);
1387 return 1;
1391 /* wishful thinking function */
1392 static void search (regex_t *re, int pageno, int y, int forward)
1394 fz_device *tdev;
1395 fz_stext_page *text;
1396 struct pagedim *pdim;
1397 int stop = 0, niters = 0;
1398 double start, end;
1399 fz_page *page;
1400 fz_stext_block *block;
1402 start = now ();
1403 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1404 if (niters++ == 5) {
1405 niters = 0;
1406 if (hasdata ()) {
1407 printd ("progress 1 attention requested aborting search at %d",
1408 pageno);
1409 stop = 1;
1411 else {
1412 printd ("progress %f searching in page %d",
1413 (double) (pageno + 1) / state.pagecount,
1414 pageno);
1417 pdim = pdimofpageno (pageno);
1418 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1419 tdev = fz_new_stext_device (state.ctx, text, 0);
1421 page = fz_load_page (state.ctx, state.doc, pageno);
1423 fz_matrix ctm = pagectm1 (page, pdim);
1424 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1427 fz_close_device (state.ctx, tdev);
1428 fz_drop_device (state.ctx, tdev);
1430 if (forward) {
1431 for (block = text->first_block; block; block = block->next) {
1432 fz_stext_line *line;
1434 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1435 for (line = block->u.t.first_line; line; line = line->next) {
1436 if (line->bbox.y0 < y + 1) continue;
1438 switch (matchline (re, line, stop, pageno, start)) {
1439 case 0: break;
1440 case 1: stop = 1; break;
1441 case -1: stop = 1; goto endloop;
1446 else {
1447 for (block = text->last_block; block; block = block->prev) {
1448 fz_stext_line *line;
1450 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1451 for (line = block->u.t.last_line; line; line = line->prev) {
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;
1463 if (forward) {
1464 pageno += 1;
1465 y = 0;
1467 else {
1468 pageno -= 1;
1469 y = INT_MAX;
1471 endloop:
1472 fz_drop_stext_page (state.ctx, text);
1473 fz_drop_page (state.ctx, page);
1475 end = now ();
1476 if (!stop) {
1477 printd ("progress 1 no matches %f sec", end - start);
1479 printd ("clearrects");
1482 static void set_tex_params (int colorspace)
1484 switch (colorspace) {
1485 case 0:
1486 state.texiform = GL_RGBA8;
1487 state.texform = GL_RGBA;
1488 state.texty = GL_UNSIGNED_BYTE;
1489 state.colorspace = fz_device_rgb (state.ctx);
1490 break;
1491 case 1:
1492 state.texiform = GL_RGBA8;
1493 state.texform = GL_BGRA;
1494 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1495 state.texty = GL_UNSIGNED_INT_8_8_8_8_REV;
1496 #else
1497 state.texty = GL_UNSIGNED_INT_8_8_8_8;
1498 #endif
1499 state.colorspace = fz_device_bgr (state.ctx);
1500 break;
1501 case 2:
1502 state.texiform = GL_LUMINANCE_ALPHA;
1503 state.texform = GL_LUMINANCE_ALPHA;
1504 state.texty = GL_UNSIGNED_BYTE;
1505 state.colorspace = fz_device_gray (state.ctx);
1506 break;
1507 default:
1508 errx (1, "invalid colorspce %d", colorspace);
1512 static void realloctexts (int texcount)
1514 size_t size;
1516 if (texcount == state.texcount) return;
1518 if (texcount < state.texcount) {
1519 glDeleteTextures (state.texcount - texcount,
1520 state.texids + texcount);
1523 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1524 state.texids = realloc (state.texids, size);
1525 if (!state.texids) {
1526 err (1, "realloc texs %" FMT_s, size);
1529 state.texowners = (void *) (state.texids + texcount);
1530 if (texcount > state.texcount) {
1531 glGenTextures (texcount - state.texcount,
1532 state.texids + state.texcount);
1533 for (int i = state.texcount; i < texcount; ++i) {
1534 state.texowners[i].w = -1;
1535 state.texowners[i].slice = NULL;
1538 state.texcount = texcount;
1539 state.texindex = 0;
1542 static char *mbtoutf8 (char *s)
1544 char *p, *r;
1545 wchar_t *tmp;
1546 size_t i, ret, len;
1548 if (state.utf8cs) {
1549 return s;
1552 len = mbstowcs (NULL, s, strlen (s));
1553 if (len == 0) {
1554 return s;
1556 else {
1557 if (len == (size_t) -1) {
1558 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1559 return s;
1563 tmp = calloc (len, sizeof (wchar_t));
1564 if (!tmp) {
1565 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1566 len, sizeof (wchar_t), errno, strerror (errno));
1567 return s;
1570 ret = mbstowcs (tmp, s, len);
1571 if (ret == (size_t) -1) {
1572 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1573 len, errno, strerror (errno));
1574 free (tmp);
1575 return s;
1578 len = 0;
1579 for (i = 0; i < ret; ++i) {
1580 len += fz_runelen (tmp[i]);
1583 p = r = malloc (len + 1);
1584 if (!r) {
1585 printd ("emsg mbtoutf8: malloc(%zu)", len);
1586 free (tmp);
1587 return s;
1590 for (i = 0; i < ret; ++i) {
1591 p += fz_runetochar (p, tmp[i]);
1593 *p = 0;
1594 free (tmp);
1595 return r;
1598 CAMLprim value ml_mbtoutf8 (value s_v)
1600 CAMLparam1 (s_v);
1601 CAMLlocal1 (ret_v);
1602 char *s, *r;
1604 s = String_val (s_v);
1605 r = mbtoutf8 (s);
1606 if (r == s) {
1607 ret_v = s_v;
1609 else {
1610 ret_v = caml_copy_string (r);
1611 free (r);
1613 CAMLreturn (ret_v);
1616 static void * mainloop (void UNUSED_ATTR *unused)
1618 char *p = NULL;
1619 int len, ret, oldlen = 0;
1621 fz_var (p);
1622 fz_var (oldlen);
1623 for (;;) {
1624 len = readlen (state.csock);
1625 if (len == 0) {
1626 errx (1, "readlen returned 0");
1629 if (oldlen < len + 1) {
1630 p = realloc (p, len + 1);
1631 if (!p) {
1632 err (1, "realloc %d failed", len + 1);
1634 oldlen = len + 1;
1636 readdata (state.csock, p, len);
1637 p[len] = 0;
1639 if (!strncmp ("open", p, 4)) {
1640 int off, usedoccss, ok = 0, layouth;
1641 char *password;
1642 char *filename;
1643 char *utf8filename;
1644 size_t filenamelen;
1646 fz_var (ok);
1647 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1648 if (ret != 2) {
1649 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1652 filename = p + 5 + off;
1653 filenamelen = strlen (filename);
1654 password = filename + filenamelen + 1;
1656 if (password[strlen (password) + 1]) {
1657 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1660 lock ("open");
1661 fz_set_use_document_css (state.ctx, usedoccss);
1662 fz_try (state.ctx) {
1663 ok = openxref (filename, password, layouth);
1665 fz_catch (state.ctx) {
1666 utf8filename = mbtoutf8 (filename);
1667 printd ("msg Could not open %s", utf8filename);
1668 if (utf8filename != filename) {
1669 free (utf8filename);
1672 if (ok) {
1673 docinfo ();
1674 initpdims ();
1676 unlock ("open");
1678 if (ok) {
1679 utf8filename = mbtoutf8 (filename);
1680 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1681 if (utf8filename != filename) {
1682 free (utf8filename);
1684 state.needoutline = 1;
1687 else if (!strncmp ("cs", p, 2)) {
1688 int i, colorspace;
1690 ret = sscanf (p + 2, " %d", &colorspace);
1691 if (ret != 1) {
1692 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1694 lock ("cs");
1695 set_tex_params (colorspace);
1696 for (i = 0; i < state.texcount; ++i) {
1697 state.texowners[i].w = -1;
1698 state.texowners[i].slice = NULL;
1700 unlock ("cs");
1702 else if (!strncmp ("freepage", p, 8)) {
1703 void *ptr;
1705 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1706 if (ret != 1) {
1707 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1709 lock ("freepage");
1710 freepage (ptr);
1711 unlock ("freepage");
1713 else if (!strncmp ("freetile", p, 8)) {
1714 void *ptr;
1716 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1717 if (ret != 1) {
1718 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1720 lock ("freetile");
1721 freetile (ptr);
1722 unlock ("freetile");
1724 else if (!strncmp ("search", p, 6)) {
1725 int icase, pageno, y, len2, forward;
1726 char *pattern;
1727 regex_t re;
1729 ret = sscanf (p + 6, " %d %d %d %d,%n",
1730 &icase, &pageno, &y, &forward, &len2);
1731 if (ret != 4) {
1732 errx (1, "malformed search `%s' ret=%d", p, ret);
1735 pattern = p + 6 + len2;
1736 ret = regcomp (&re, pattern,
1737 REG_EXTENDED | (icase ? REG_ICASE : 0));
1738 if (ret) {
1739 char errbuf[80];
1740 size_t size;
1742 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1743 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1745 else {
1746 search (&re, pageno, y, forward);
1747 regfree (&re);
1750 else if (!strncmp ("geometry", p, 8)) {
1751 int w, h, fitmodel;
1753 printd ("clear");
1754 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1755 if (ret != 3) {
1756 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1759 lock ("geometry");
1760 state.h = h;
1761 if (w != state.w) {
1762 state.w = w;
1763 for (int i = 0; i < state.texcount; ++i) {
1764 state.texowners[i].slice = NULL;
1767 state.fitmodel = fitmodel;
1768 layout ();
1769 process_outline ();
1771 state.gen++;
1772 unlock ("geometry");
1773 printd ("continue %d", state.pagecount);
1775 else if (!strncmp ("reqlayout", p, 9)) {
1776 char *nameddest;
1777 int rotate, off, h;
1778 int fitmodel;
1779 pdf_document *pdf;
1781 printd ("clear");
1782 ret = sscanf (p + 9, " %d %d %d %n",
1783 &rotate, &fitmodel, &h, &off);
1784 if (ret != 3) {
1785 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1787 lock ("reqlayout");
1788 pdf = pdf_specifics (state.ctx, state.doc);
1789 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1790 state.gen += 1;
1792 state.rotate = rotate;
1793 state.fitmodel = fitmodel;
1794 state.h = h;
1795 layout ();
1796 process_outline ();
1798 nameddest = p + 9 + off;
1799 if (pdf && nameddest && *nameddest) {
1800 fz_point xy;
1801 struct pagedim *pdim;
1802 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1803 &xy.x, &xy.y);
1804 pdim = pdimofpageno (pageno);
1805 fz_transform_point (&xy, &pdim->ctm);
1806 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1809 state.gen++;
1810 unlock ("reqlayout");
1811 printd ("continue %d", state.pagecount);
1813 else if (!strncmp ("page", p, 4)) {
1814 double a, b;
1815 struct page *page;
1816 int pageno, pindex;
1818 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1819 if (ret != 2) {
1820 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1823 lock ("page");
1824 a = now ();
1825 page = loadpage (pageno, pindex);
1826 b = now ();
1827 unlock ("page");
1829 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1831 else if (!strncmp ("tile", p, 4)) {
1832 int x, y, w, h;
1833 struct page *page;
1834 struct tile *tile;
1835 double a, b;
1836 void *data;
1838 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1839 SCN_ptr_cast (&page), &x, &y, &w, &h,
1840 SCN_ptr_cast (&data));
1841 if (ret != 6) {
1842 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1845 lock ("tile");
1846 a = now ();
1847 tile = rendertile (page, x, y, w, h, data);
1848 b = now ();
1849 unlock ("tile");
1851 printd ("tile %d %d %" FMT_ptr " %u %f",
1852 x, y,
1853 FMT_ptr_cast (tile),
1854 tile->w * tile->h * tile->pixmap->n,
1855 b - a);
1857 else if (!strncmp ("trimset", p, 7)) {
1858 fz_irect fuzz;
1859 int trimmargins;
1861 ret = sscanf (p + 7, " %d %d %d %d %d",
1862 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1863 if (ret != 5) {
1864 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1866 lock ("trimset");
1867 state.trimmargins = trimmargins;
1868 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1869 state.trimanew = 1;
1870 state.trimfuzz = fuzz;
1872 unlock ("trimset");
1874 else if (!strncmp ("settrim", p, 7)) {
1875 fz_irect fuzz;
1876 int trimmargins;
1878 ret = sscanf (p + 7, " %d %d %d %d %d",
1879 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1880 if (ret != 5) {
1881 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1883 printd ("clear");
1884 lock ("settrim");
1885 state.trimmargins = trimmargins;
1886 state.needoutline = 1;
1887 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1888 state.trimanew = 1;
1889 state.trimfuzz = fuzz;
1891 state.pagedimcount = 0;
1892 free (state.pagedims);
1893 state.pagedims = NULL;
1894 initpdims ();
1895 layout ();
1896 process_outline ();
1897 unlock ("settrim");
1898 printd ("continue %d", state.pagecount);
1900 else if (!strncmp ("sliceh", p, 6)) {
1901 int h;
1903 ret = sscanf (p + 6, " %d", &h);
1904 if (ret != 1) {
1905 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1907 if (h != state.sliceheight) {
1908 state.sliceheight = h;
1909 for (int i = 0; i < state.texcount; ++i) {
1910 state.texowners[i].w = -1;
1911 state.texowners[i].h = -1;
1912 state.texowners[i].slice = NULL;
1916 else if (!strncmp ("interrupt", p, 9)) {
1917 printd ("vmsg interrupted");
1919 else {
1920 errx (1, "unknown command %.*s", len, p);
1923 return 0;
1926 CAMLprim value ml_isexternallink (value uri_v)
1928 CAMLparam1 (uri_v);
1929 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1930 CAMLreturn (Val_bool (ext));
1933 CAMLprim value ml_uritolocation (value uri_v)
1935 CAMLparam1 (uri_v);
1936 CAMLlocal1 (ret_v);
1937 int pageno;
1938 fz_point xy;
1939 struct pagedim *pdim;
1941 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1942 &xy.x, &xy.y);
1943 pdim = pdimofpageno (pageno);
1944 fz_transform_point (&xy, &pdim->ctm);
1945 ret_v = caml_alloc_tuple (3);
1946 Field (ret_v, 0) = Val_int (pageno);
1947 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1948 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1949 CAMLreturn (ret_v);
1952 CAMLprim value ml_realloctexts (value texcount_v)
1954 CAMLparam1 (texcount_v);
1955 int ok;
1957 if (trylock (__func__)) {
1958 ok = 0;
1959 goto done;
1961 realloctexts (Int_val (texcount_v));
1962 ok = 1;
1963 unlock (__func__);
1965 done:
1966 CAMLreturn (Val_bool (ok));
1969 static void recti (int x0, int y0, int x1, int y1)
1971 GLfloat *v = state.vertices;
1973 glVertexPointer (2, GL_FLOAT, 0, v);
1974 v[0] = x0; v[1] = y0;
1975 v[2] = x1; v[3] = y0;
1976 v[4] = x0; v[5] = y1;
1977 v[6] = x1; v[7] = y1;
1978 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1981 static void showsel (struct page *page, int ox, int oy)
1983 fz_irect bbox;
1984 fz_rect rect;
1985 fz_stext_block *block;
1986 int seen = 0;
1987 unsigned char selcolor[] = {15,15,15,140};
1989 if (!page->fmark.ch || !page->lmark.ch) return;
1991 glEnable (GL_BLEND);
1992 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1993 glColor4ubv (selcolor);
1995 ox += state.pagedims[page->pdimno].bounds.x0;
1996 oy += state.pagedims[page->pdimno].bounds.y0;
1998 for (block = page->text->first_block; block; block = block->next) {
1999 fz_stext_line *line;
2001 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2002 for (line = block->u.t.first_line; line; line = line->next) {
2003 fz_stext_char *ch;
2005 rect = fz_empty_rect;
2006 for (ch = line->first_char; ch; ch = ch->next) {
2007 if (ch == page->fmark.ch) seen = 1;
2008 if (seen) fz_union_rect (&rect, &ch->bbox);
2009 if (ch == page->lmark.ch) {
2010 fz_round_rect (&bbox, &rect);
2011 recti (bbox.x0 + ox, bbox.y0 + oy,
2012 bbox.x1 + ox, bbox.y1 + oy);
2013 goto done;
2016 fz_round_rect (&bbox, &rect);
2017 recti (bbox.x0 + ox, bbox.y0 + oy,
2018 bbox.x1 + ox, bbox.y1 + oy);
2021 done:
2022 glDisable (GL_BLEND);
2025 #pragma GCC diagnostic push
2026 #pragma GCC diagnostic ignored "-Wdouble-promotion"
2027 #pragma GCC diagnostic ignored "-Wconversion"
2028 #include "glfont.c"
2029 #pragma GCC diagnostic pop
2031 static void stipplerect (fz_matrix *m,
2032 fz_point *p1,
2033 fz_point *p2,
2034 fz_point *p3,
2035 fz_point *p4,
2036 GLfloat *texcoords,
2037 GLfloat *vertices)
2039 fz_transform_point (p1, m);
2040 fz_transform_point (p2, m);
2041 fz_transform_point (p3, m);
2042 fz_transform_point (p4, m);
2044 float w, h, s, t;
2046 w = p2->x - p1->x;
2047 h = p2->y - p1->y;
2048 t = hypotf (w, h) * .25f;
2050 w = p3->x - p2->x;
2051 h = p3->y - p2->y;
2052 s = hypotf (w, h) * .25f;
2054 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2055 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2057 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2058 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2060 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2061 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2063 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2064 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2066 glDrawArrays (GL_LINES, 0, 8);
2069 static void solidrect (fz_matrix *m,
2070 fz_point *p1,
2071 fz_point *p2,
2072 fz_point *p3,
2073 fz_point *p4,
2074 GLfloat *vertices)
2076 fz_transform_point (p1, m);
2077 fz_transform_point (p2, m);
2078 fz_transform_point (p3, m);
2079 fz_transform_point (p4, m);
2080 vertices[0] = p1->x; vertices[1] = p1->y;
2081 vertices[2] = p2->x; vertices[3] = p2->y;
2083 vertices[4] = p3->x; vertices[5] = p3->y;
2084 vertices[6] = p4->x; vertices[7] = p4->y;
2085 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2088 static void ensurelinks (struct page *page)
2090 if (!page->links)
2091 page->links = fz_load_links (state.ctx, page->fzpage);
2094 static void highlightlinks (struct page *page, int xoff, int yoff)
2096 fz_matrix ctm, tm, pm;
2097 fz_link *link;
2098 GLfloat *texcoords = state.texcoords;
2099 GLfloat *vertices = state.vertices;
2101 ensurelinks (page);
2103 glEnable (GL_TEXTURE_1D);
2104 glEnable (GL_BLEND);
2105 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2106 glBindTexture (GL_TEXTURE_1D, state.stid);
2108 xoff -= state.pagedims[page->pdimno].bounds.x0;
2109 yoff -= state.pagedims[page->pdimno].bounds.y0;
2110 fz_translate (&tm, xoff, yoff);
2111 pm = pagectm (page);
2112 fz_concat (&ctm, &pm, &tm);
2114 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2115 glVertexPointer (2, GL_FLOAT, 0, vertices);
2117 for (link = page->links; link; link = link->next) {
2118 fz_point p1, p2, p3, p4;
2120 p1.x = link->rect.x0;
2121 p1.y = link->rect.y0;
2123 p2.x = link->rect.x1;
2124 p2.y = link->rect.y0;
2126 p3.x = link->rect.x1;
2127 p3.y = link->rect.y1;
2129 p4.x = link->rect.x0;
2130 p4.y = link->rect.y1;
2132 /* TODO: different colours for different schemes */
2133 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2134 else glColor3ub (255, 0, 0);
2136 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2139 for (int i = 0; i < page->annotcount; ++i) {
2140 fz_point p1, p2, p3, p4;
2141 struct annot *annot = &page->annots[i];
2143 p1.x = annot->bbox.x0;
2144 p1.y = annot->bbox.y0;
2146 p2.x = annot->bbox.x1;
2147 p2.y = annot->bbox.y0;
2149 p3.x = annot->bbox.x1;
2150 p3.y = annot->bbox.y1;
2152 p4.x = annot->bbox.x0;
2153 p4.y = annot->bbox.y1;
2155 glColor3ub (0, 0, 128);
2156 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2159 glDisable (GL_BLEND);
2160 glDisable (GL_TEXTURE_1D);
2163 static int compareslinks (const void *l, const void *r)
2165 struct slink const *ls = l;
2166 struct slink const *rs = r;
2167 if (ls->bbox.y0 == rs->bbox.y0) {
2168 return rs->bbox.x0 - rs->bbox.x0;
2170 return ls->bbox.y0 - rs->bbox.y0;
2173 static void droptext (struct page *page)
2175 if (page->text) {
2176 fz_drop_stext_page (state.ctx, page->text);
2177 page->fmark.ch = NULL;
2178 page->lmark.ch = NULL;
2179 page->text = NULL;
2183 static void dropannots (struct page *page)
2185 if (page->annots) {
2186 free (page->annots);
2187 page->annots = NULL;
2188 page->annotcount = 0;
2192 static void ensureannots (struct page *page)
2194 int i, count = 0;
2195 size_t annotsize = sizeof (*page->annots);
2196 fz_annot *annot;
2198 if (state.gen != page->agen) {
2199 dropannots (page);
2200 page->agen = state.gen;
2202 if (page->annots) return;
2204 for (annot = fz_first_annot (state.ctx, page->fzpage);
2205 annot;
2206 annot = fz_next_annot (state.ctx, annot)) {
2207 count++;
2210 if (count > 0) {
2211 page->annotcount = count;
2212 page->annots = calloc (count, annotsize);
2213 if (!page->annots) {
2214 err (1, "calloc annots %d", count);
2217 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2218 annot;
2219 annot = fz_next_annot (state.ctx, annot), i++) {
2220 fz_rect rect;
2222 fz_bound_annot (state.ctx, annot, &rect);
2223 page->annots[i].annot = annot;
2224 fz_round_rect (&page->annots[i].bbox, &rect);
2229 static void dropslinks (struct page *page)
2231 if (page->slinks) {
2232 free (page->slinks);
2233 page->slinks = NULL;
2234 page->slinkcount = 0;
2236 if (page->links) {
2237 fz_drop_link (state.ctx, page->links);
2238 page->links = NULL;
2242 static void ensureslinks (struct page *page)
2244 fz_matrix ctm;
2245 int i, count;
2246 size_t slinksize = sizeof (*page->slinks);
2247 fz_link *link;
2249 ensureannots (page);
2250 if (state.gen != page->sgen) {
2251 dropslinks (page);
2252 page->sgen = state.gen;
2254 if (page->slinks) return;
2256 ensurelinks (page);
2257 ctm = pagectm (page);
2259 count = page->annotcount;
2260 for (link = page->links; link; link = link->next) {
2261 count++;
2263 if (count > 0) {
2264 int j;
2266 page->slinkcount = count;
2267 page->slinks = calloc (count, slinksize);
2268 if (!page->slinks) {
2269 err (1, "calloc slinks %d", count);
2272 for (i = 0, link = page->links; link; ++i, link = link->next) {
2273 fz_rect rect;
2275 rect = link->rect;
2276 fz_transform_rect (&rect, &ctm);
2277 page->slinks[i].tag = SLINK;
2278 page->slinks[i].u.link = link;
2279 fz_round_rect (&page->slinks[i].bbox, &rect);
2281 for (j = 0; j < page->annotcount; ++j, ++i) {
2282 fz_rect rect;
2283 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2284 fz_transform_rect (&rect, &ctm);
2285 fz_round_rect (&page->slinks[i].bbox, &rect);
2287 page->slinks[i].tag = SANNOT;
2288 page->slinks[i].u.annot = page->annots[j].annot;
2290 qsort (page->slinks, count, slinksize, compareslinks);
2294 #pragma GCC diagnostic push
2295 #pragma GCC diagnostic ignored "-Wconversion"
2296 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2297 static void fmt_linkn (char *s, unsigned int u)
2299 unsigned int len; unsigned int q;
2300 unsigned int zma = 'z' - 'a' + 1;
2301 len = 1; q = u;
2302 while (q > zma - 1) { ++len; q /= zma; }
2303 if (s) {
2304 s += len;
2305 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2306 /* handles u == 0 */
2308 s[len] = 0;
2310 #pragma GCC diagnostic pop
2312 static void highlightslinks (struct page *page, int xoff, int yoff,
2313 int noff, char *targ, mlsize_t tlen, int hfsize)
2315 char buf[40];
2316 struct slink *slink;
2317 float x0, y0, x1, y1, w;
2319 ensureslinks (page);
2320 glColor3ub (0xc3, 0xb0, 0x91);
2321 for (int i = 0; i < page->slinkcount; ++i) {
2322 fmt_linkn (buf, i + noff);
2323 if (!tlen || !strncmp (targ, buf, tlen)) {
2324 slink = &page->slinks[i];
2326 x0 = slink->bbox.x0 + xoff - 5;
2327 y1 = slink->bbox.y0 + yoff - 5;
2328 y0 = y1 + 10 + hfsize;
2329 w = measure_string (state.face, hfsize, buf);
2330 x1 = x0 + w + 10;
2331 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2335 glEnable (GL_BLEND);
2336 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2337 glEnable (GL_TEXTURE_2D);
2338 glColor3ub (0, 0, 0);
2339 for (int i = 0; i < page->slinkcount; ++i) {
2340 fmt_linkn (buf, i + noff);
2341 if (!tlen || !strncmp (targ, buf, tlen)) {
2342 slink = &page->slinks[i];
2344 x0 = slink->bbox.x0 + xoff;
2345 y0 = slink->bbox.y0 + yoff + hfsize;
2346 draw_string (state.face, hfsize, x0, y0, buf);
2349 glDisable (GL_TEXTURE_2D);
2350 glDisable (GL_BLEND);
2353 static void uploadslice (struct tile *tile, struct slice *slice)
2355 int offset;
2356 struct slice *slice1;
2357 unsigned char *texdata;
2359 offset = 0;
2360 for (slice1 = tile->slices; slice != slice1; slice1++) {
2361 offset += slice1->h * tile->w * tile->pixmap->n;
2363 if (slice->texindex != -1 && slice->texindex < state.texcount
2364 && state.texowners[slice->texindex].slice == slice) {
2365 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2367 else {
2368 int subimage = 0;
2369 int texindex = state.texindex++ % state.texcount;
2371 if (state.texowners[texindex].w == tile->w) {
2372 if (state.texowners[texindex].h >= slice->h) {
2373 subimage = 1;
2375 else {
2376 state.texowners[texindex].h = slice->h;
2379 else {
2380 state.texowners[texindex].h = slice->h;
2383 state.texowners[texindex].w = tile->w;
2384 state.texowners[texindex].slice = slice;
2385 slice->texindex = texindex;
2387 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2388 #if TEXT_TYPE == GL_TEXTURE_2D
2389 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2390 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2391 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2392 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2393 #endif
2394 if (tile->pbo) {
2395 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2396 texdata = 0;
2398 else {
2399 texdata = tile->pixmap->samples;
2401 if (subimage) {
2402 glTexSubImage2D (TEXT_TYPE,
2406 tile->w,
2407 slice->h,
2408 state.texform,
2409 state.texty,
2410 texdata+offset
2413 else {
2414 glTexImage2D (TEXT_TYPE,
2416 state.texiform,
2417 tile->w,
2418 slice->h,
2420 state.texform,
2421 state.texty,
2422 texdata+offset
2425 if (tile->pbo) {
2426 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2431 CAMLprim void ml_begintiles (value unit_v)
2433 CAMLparam1 (unit_v);
2434 glEnable (TEXT_TYPE);
2435 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2436 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2437 CAMLreturn0;
2440 CAMLprim void ml_endtiles (value unit_v)
2442 CAMLparam1 (unit_v);
2443 glDisable (TEXT_TYPE);
2444 CAMLreturn0;
2447 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2449 CAMLparam2 (args_v, ptr_v);
2450 int dispx = Int_val (Field (args_v, 0));
2451 int dispy = Int_val (Field (args_v, 1));
2452 int dispw = Int_val (Field (args_v, 2));
2453 int disph = Int_val (Field (args_v, 3));
2454 int tilex = Int_val (Field (args_v, 4));
2455 int tiley = Int_val (Field (args_v, 5));
2456 char *s = String_val (ptr_v);
2457 struct tile *tile = parse_pointer (__func__, s);
2458 int slicey, firstslice;
2459 struct slice *slice;
2460 GLfloat *texcoords = state.texcoords;
2461 GLfloat *vertices = state.vertices;
2463 firstslice = tiley / tile->sliceheight;
2464 slice = &tile->slices[firstslice];
2465 slicey = tiley % tile->sliceheight;
2467 while (disph > 0) {
2468 int dh;
2470 dh = slice->h - slicey;
2471 dh = fz_mini (disph, dh);
2472 uploadslice (tile, slice);
2474 texcoords[0] = tilex; texcoords[1] = slicey;
2475 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2476 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2477 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2479 vertices[0] = dispx; vertices[1] = dispy;
2480 vertices[2] = dispx+dispw; vertices[3] = dispy;
2481 vertices[4] = dispx; vertices[5] = dispy+dh;
2482 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2484 #if TEXT_TYPE == GL_TEXTURE_2D
2485 for (int i = 0; i < 8; ++i) {
2486 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2488 #endif
2490 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2491 dispy += dh;
2492 disph -= dh;
2493 slice++;
2494 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2495 slicey = 0;
2497 CAMLreturn0;
2500 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2502 fz_matrix ctm, tm, pm;
2503 fz_point p1, p2, p3, p4;
2504 GLfloat *vertices = state.vertices;
2505 double *v = (double *) rects_v;
2507 xoff -= state.pagedims[page->pdimno].bounds.x0;
2508 yoff -= state.pagedims[page->pdimno].bounds.y0;
2509 fz_translate (&tm, xoff, yoff);
2510 pm = pagectm (page);
2511 fz_concat (&ctm, &pm, &tm);
2513 glEnable (GL_BLEND);
2514 glVertexPointer (2, GL_FLOAT, 0, vertices);
2516 glColor4dv (v);
2517 p1.x = (float) v[4];
2518 p1.y = (float) v[5];
2520 p2.x = (float) v[6];
2521 p2.y = (float) v[5];
2523 p3.x = (float) v[6];
2524 p3.y = (float) v[7];
2526 p4.x = (float) v[4];
2527 p4.y = (float) v[7];
2528 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2529 glDisable (GL_BLEND);
2532 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2533 value xoff_v, value yoff_v,
2534 value li_v)
2536 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2537 int xoff = Int_val (xoff_v);
2538 int yoff = Int_val (yoff_v);
2539 int noff = Int_val (Field (li_v, 0));
2540 char *targ = String_val (Field (li_v, 1));
2541 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2542 int hfsize = Int_val (Field (li_v, 2));
2543 char *s = String_val (ptr_v);
2544 int hlmask = Int_val (hlinks_v);
2545 struct page *page = parse_pointer (__func__, s);
2547 if (!page->fzpage) {
2548 /* deal with loadpage failed pages */
2549 goto done;
2552 if (trylock (__func__)) {
2553 noff = -1;
2554 goto done;
2557 ensureannots (page);
2558 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2559 if (hlmask & 2) {
2560 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2561 noff = page->slinkcount;
2563 if (page->tgen == state.gen) {
2564 showsel (page, xoff, yoff);
2566 unlock (__func__);
2568 done:
2569 CAMLreturn (Val_int (noff));
2572 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2573 value rects_v)
2575 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2576 int xoff = Int_val (xoff_v);
2577 int yoff = Int_val (yoff_v);
2578 char *s = String_val (ptr_v);
2579 struct page *page = parse_pointer (__func__, s);
2581 drawprect (page, xoff, yoff, rects_v);
2582 CAMLreturn0;
2585 static struct annot *getannot (struct page *page, int x, int y)
2587 fz_point p;
2588 fz_matrix ctm;
2589 const fz_matrix *tctm;
2590 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2592 if (!page->annots) return NULL;
2594 if (pdf) {
2595 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2596 tctm = &state.pagedims[page->pdimno].tctm;
2598 else {
2599 tctm = &fz_identity;
2602 p.x = x;
2603 p.y = y;
2605 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2606 fz_invert_matrix (&ctm, &ctm);
2607 fz_transform_point (&p, &ctm);
2609 if (pdf) {
2610 for (int i = 0; i < page->annotcount; ++i) {
2611 struct annot *a = &page->annots[i];
2612 fz_rect rect;
2614 fz_bound_annot (state.ctx, a->annot, &rect);
2615 if (p.x >= rect.x0 && p.x <= rect.x1) {
2616 if (p.y >= rect.y0 && p.y <= rect.y1)
2617 return a;
2621 return NULL;
2624 static fz_link *getlink (struct page *page, int x, int y)
2626 fz_point p;
2627 fz_matrix ctm;
2628 fz_link *link;
2630 ensureslinks (page);
2632 p.x = x;
2633 p.y = y;
2635 ctm = pagectm (page);
2636 fz_invert_matrix (&ctm, &ctm);
2637 fz_transform_point (&p, &ctm);
2639 for (link = page->links; link; link = link->next) {
2640 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2641 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2642 return link;
2646 return NULL;
2649 static void ensuretext (struct page *page)
2651 if (state.gen != page->tgen) {
2652 droptext (page);
2653 page->tgen = state.gen;
2655 if (!page->text) {
2656 fz_matrix ctm;
2657 fz_device *tdev;
2659 page->text = fz_new_stext_page (state.ctx,
2660 &state.pagedims[page->pdimno].mediabox);
2661 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2662 ctm = pagectm (page);
2663 fz_run_display_list (state.ctx, page->dlist,
2664 tdev, &ctm, &fz_infinite_rect, NULL);
2665 fz_close_device (state.ctx, tdev);
2666 fz_drop_device (state.ctx, tdev);
2670 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2672 CAMLparam2 (start_page_v, dir_v);
2673 CAMLlocal1 (ret_v);
2674 int i, dir = Int_val (dir_v);
2675 int start_page = Int_val (start_page_v);
2676 int end_page = dir > 0 ? state.pagecount : -1;
2677 pdf_document *pdf;
2679 fz_var (end_page);
2680 ret_v = Val_int (0);
2681 lock (__func__);
2682 pdf = pdf_specifics (state.ctx, state.doc);
2683 for (i = start_page + dir; i != end_page; i += dir) {
2684 int found;
2686 fz_var (found);
2687 if (pdf) {
2688 pdf_page *page = NULL;
2690 fz_var (page);
2691 fz_try (state.ctx) {
2692 page = pdf_load_page (state.ctx, pdf, i);
2693 found = !!page->links || !!page->annots;
2695 fz_catch (state.ctx) {
2696 found = 0;
2698 if (page) {
2699 fz_drop_page (state.ctx, &page->super);
2702 else {
2703 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2704 fz_link *link = fz_load_links (state.ctx, page);
2705 found = !!link;
2706 fz_drop_link (state.ctx, link);
2707 fz_drop_page (state.ctx, page);
2710 if (found) {
2711 ret_v = caml_alloc_small (1, 1);
2712 Field (ret_v, 0) = Val_int (i);
2713 goto unlock;
2716 unlock:
2717 unlock (__func__);
2718 CAMLreturn (ret_v);
2721 enum { dir_first, dir_last };
2722 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2724 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2726 CAMLparam2 (ptr_v, dir_v);
2727 CAMLlocal2 (ret_v, pos_v);
2728 struct page *page;
2729 int dirtag, i, slinkindex;
2730 struct slink *found = NULL ,*slink;
2731 char *s = String_val (ptr_v);
2733 page = parse_pointer (__func__, s);
2734 ret_v = Val_int (0);
2735 lock (__func__);
2736 ensureslinks (page);
2738 if (Is_block (dir_v)) {
2739 dirtag = Tag_val (dir_v);
2740 switch (dirtag) {
2741 case dir_first_visible:
2743 int x0, y0, dir, first_index, last_index;
2745 pos_v = Field (dir_v, 0);
2746 x0 = Int_val (Field (pos_v, 0));
2747 y0 = Int_val (Field (pos_v, 1));
2748 dir = Int_val (Field (pos_v, 2));
2750 if (dir >= 0) {
2751 dir = 1;
2752 first_index = 0;
2753 last_index = page->slinkcount;
2755 else {
2756 first_index = page->slinkcount - 1;
2757 last_index = -1;
2760 for (i = first_index; i != last_index; i += dir) {
2761 slink = &page->slinks[i];
2762 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2763 found = slink;
2764 break;
2768 break;
2770 case dir_left:
2771 slinkindex = Int_val (Field (dir_v, 0));
2772 found = &page->slinks[slinkindex];
2773 for (i = slinkindex - 1; i >= 0; --i) {
2774 slink = &page->slinks[i];
2775 if (slink->bbox.x0 < found->bbox.x0) {
2776 found = slink;
2777 break;
2780 break;
2782 case dir_right:
2783 slinkindex = Int_val (Field (dir_v, 0));
2784 found = &page->slinks[slinkindex];
2785 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2786 slink = &page->slinks[i];
2787 if (slink->bbox.x0 > found->bbox.x0) {
2788 found = slink;
2789 break;
2792 break;
2794 case dir_down:
2795 slinkindex = Int_val (Field (dir_v, 0));
2796 found = &page->slinks[slinkindex];
2797 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2798 slink = &page->slinks[i];
2799 if (slink->bbox.y0 >= found->bbox.y0) {
2800 found = slink;
2801 break;
2804 break;
2806 case dir_up:
2807 slinkindex = Int_val (Field (dir_v, 0));
2808 found = &page->slinks[slinkindex];
2809 for (i = slinkindex - 1; i >= 0; --i) {
2810 slink = &page->slinks[i];
2811 if (slink->bbox.y0 <= found->bbox.y0) {
2812 found = slink;
2813 break;
2816 break;
2819 else {
2820 dirtag = Int_val (dir_v);
2821 switch (dirtag) {
2822 case dir_first:
2823 found = page->slinks;
2824 break;
2826 case dir_last:
2827 if (page->slinks) {
2828 found = page->slinks + (page->slinkcount - 1);
2830 break;
2833 if (found) {
2834 ret_v = caml_alloc_small (2, 1);
2835 Field (ret_v, 0) = Val_int (found - page->slinks);
2838 unlock (__func__);
2839 CAMLreturn (ret_v);
2842 enum { uuri, utext, uannot };
2844 CAMLprim value ml_getlink (value ptr_v, value n_v)
2846 CAMLparam2 (ptr_v, n_v);
2847 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2848 fz_link *link;
2849 struct page *page;
2850 char *s = String_val (ptr_v);
2851 struct slink *slink;
2853 ret_v = Val_int (0);
2854 page = parse_pointer (__func__, s);
2856 lock (__func__);
2857 ensureslinks (page);
2858 slink = &page->slinks[Int_val (n_v)];
2859 if (slink->tag == SLINK) {
2860 link = slink->u.link;
2861 str_v = caml_copy_string (link->uri);
2862 ret_v = caml_alloc_small (1, uuri);
2863 Field (ret_v, 0) = str_v;
2865 else {
2866 ret_v = caml_alloc_small (1, uannot);
2867 tup_v = caml_alloc_tuple (2);
2868 Field (ret_v, 0) = tup_v;
2869 Field (tup_v, 0) = ptr_v;
2870 Field (tup_v, 1) = n_v;
2872 unlock (__func__);
2874 CAMLreturn (ret_v);
2877 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2879 CAMLparam2 (ptr_v, n_v);
2880 CAMLlocal1 (ret_v);
2881 pdf_document *pdf;
2882 char *contents = NULL;
2884 lock (__func__);
2885 pdf = pdf_specifics (state.ctx, state.doc);
2886 if (pdf) {
2887 char *s = String_val (ptr_v);
2888 struct page *page;
2889 struct slink *slink;
2891 page = parse_pointer (__func__, s);
2892 slink = &page->slinks[Int_val (n_v)];
2893 contents = pdf_copy_annot_contents (state.ctx,
2894 (pdf_annot *) slink->u.annot);
2896 unlock (__func__);
2897 if (contents) {
2898 ret_v = caml_copy_string (contents);
2899 fz_free (state.ctx, contents);
2901 else {
2902 ret_v = caml_copy_string ("");
2904 CAMLreturn (ret_v);
2907 CAMLprim value ml_getlinkcount (value ptr_v)
2909 CAMLparam1 (ptr_v);
2910 struct page *page;
2911 char *s = String_val (ptr_v);
2913 page = parse_pointer (__func__, s);
2914 CAMLreturn (Val_int (page->slinkcount));
2917 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2919 CAMLparam2 (ptr_v, n_v);
2920 CAMLlocal1 (ret_v);
2921 struct page *page;
2922 struct slink *slink;
2923 char *s = String_val (ptr_v);
2925 page = parse_pointer (__func__, s);
2926 ret_v = caml_alloc_tuple (4);
2927 lock (__func__);
2928 ensureslinks (page);
2930 slink = &page->slinks[Int_val (n_v)];
2931 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2932 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2933 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2934 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2935 unlock (__func__);
2936 CAMLreturn (ret_v);
2939 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2941 CAMLparam3 (ptr_v, x_v, y_v);
2942 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2943 fz_link *link;
2944 struct annot *annot;
2945 struct page *page;
2946 char *ptr = String_val (ptr_v);
2947 int x = Int_val (x_v), y = Int_val (y_v);
2948 struct pagedim *pdim;
2950 ret_v = Val_int (0);
2951 if (trylock (__func__)) {
2952 goto done;
2955 page = parse_pointer (__func__, ptr);
2956 pdim = &state.pagedims[page->pdimno];
2957 x += pdim->bounds.x0;
2958 y += pdim->bounds.y0;
2961 annot = getannot (page, x, y);
2962 if (annot) {
2963 int i, n = -1;
2965 ensureslinks (page);
2966 for (i = 0; i < page->slinkcount; ++i) {
2967 if (page->slinks[i].tag == SANNOT
2968 && page->slinks[i].u.annot == annot->annot) {
2969 n = i;
2970 break;
2973 ret_v = caml_alloc_small (1, uannot);
2974 tup_v = caml_alloc_tuple (2);
2975 Field (ret_v, 0) = tup_v;
2976 Field (tup_v, 0) = ptr_v;
2977 Field (tup_v, 1) = Val_int (n);
2978 goto unlock;
2982 link = getlink (page, x, y);
2983 if (link) {
2984 str_v = caml_copy_string (link->uri);
2985 ret_v = caml_alloc_small (1, uuri);
2986 Field (ret_v, 0) = str_v;
2988 else {
2989 fz_rect *b;
2990 fz_stext_block *block;
2992 ensuretext (page);
2994 for (block = page->text->first_block; block; block = block->next) {
2995 fz_stext_line *line;
2997 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2998 b = &block->bbox;
2999 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3000 continue;
3002 for (line = block->u.t.first_line; line; line = line->next) {
3003 fz_stext_char *ch;
3005 b = &line->bbox;
3006 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3007 continue;
3009 for (ch = line->first_char; ch; ch = ch->next) {
3010 b = &ch->bbox;
3012 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3013 const char *n2 = fz_font_name (state.ctx, ch->font);
3014 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3015 ch->font);
3017 if (!n2) n2 = "<unknown font>";
3019 if (face && face->family_name) {
3020 char *s;
3021 char *n1 = face->family_name;
3022 size_t l1 = strlen (n1);
3023 size_t l2 = strlen (n2);
3025 if (l1 != l2 || memcmp (n1, n2, l1)) {
3026 s = malloc (l1 + l2 + 2);
3027 if (s) {
3028 memcpy (s, n2, l2);
3029 s[l2] = '=';
3030 memcpy (s + l2 + 1, n1, l1 + 1);
3031 str_v = caml_copy_string (s);
3032 free (s);
3036 if (str_v == Val_unit) {
3037 str_v = caml_copy_string (n2);
3039 ret_v = caml_alloc_small (1, utext);
3040 Field (ret_v, 0) = str_v;
3041 goto unlock;
3047 unlock:
3048 unlock (__func__);
3050 done:
3051 CAMLreturn (ret_v);
3054 enum { mark_page, mark_block, mark_line, mark_word };
3056 static int uninteresting (int c)
3058 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3059 || ispunct (c);
3062 CAMLprim void ml_clearmark (value ptr_v)
3064 CAMLparam1 (ptr_v);
3065 char *s = String_val (ptr_v);
3066 struct page *page;
3068 if (trylock (__func__)) {
3069 goto done;
3072 page = parse_pointer (__func__, s);
3073 page->fmark.ch = NULL;
3074 page->lmark.ch = NULL;
3076 unlock (__func__);
3077 done:
3078 CAMLreturn0;
3081 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3083 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3084 CAMLlocal1 (ret_v);
3085 fz_rect *b;
3086 struct page *page;
3087 fz_stext_line *line;
3088 fz_stext_block *block;
3089 struct pagedim *pdim;
3090 int mark = Int_val (mark_v);
3091 char *s = String_val (ptr_v);
3092 int x = Int_val (x_v), y = Int_val (y_v);
3094 ret_v = Val_bool (0);
3095 if (trylock (__func__)) {
3096 goto done;
3099 page = parse_pointer (__func__, s);
3100 pdim = &state.pagedims[page->pdimno];
3102 ensuretext (page);
3104 if (mark == mark_page) {
3105 page->fmark.ch = page->text->first_block->u.t.first_line->first_char;
3106 page->lmark.ch = page->text->last_block->u.t.last_line->last_char;
3107 ret_v = Val_bool (1);
3108 goto unlock;
3111 x += pdim->bounds.x0;
3112 y += pdim->bounds.y0;
3114 for (block = page->text->first_block; block; block = block->next) {
3115 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3116 b = &block->bbox;
3117 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3118 continue;
3120 if (mark == mark_block) {
3121 page->fmark.ch = block->u.t.first_line->first_char;
3122 page->lmark.ch = block->u.t.last_line->last_char;
3123 ret_v = Val_bool (1);
3124 goto unlock;
3127 for (line = block->u.t.first_line; line; line = line->next) {
3128 fz_stext_char *ch;
3130 b = &line->bbox;
3131 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3132 continue;
3134 if (mark == mark_line) {
3135 page->fmark.ch = line->first_char;
3136 page->lmark.ch = line->last_char;
3137 ret_v = Val_bool (1);
3138 goto unlock;
3141 for (ch = line->first_char; ch; ch = ch->next) {
3142 fz_stext_char *ch2, *first = NULL, *last = NULL;
3143 b = &ch->bbox;
3144 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3145 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
3146 if (uninteresting (ch2->c)) first = NULL;
3147 else if (!first) first = ch2;
3149 for (ch2 = ch; ch2; ch2 = ch2->next) {
3150 if (uninteresting (ch2->c)) break;
3151 last = ch2;
3154 page->fmark.ch = first;
3155 page->lmark.ch = last;
3156 ret_v = Val_bool (1);
3157 goto unlock;
3162 unlock:
3163 if (!Bool_val (ret_v)) {
3164 page->fmark.ch = NULL;
3165 page->lmark.ch = NULL;
3167 unlock (__func__);
3169 done:
3170 CAMLreturn (ret_v);
3173 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3175 CAMLparam3 (ptr_v, x_v, y_v);
3176 CAMLlocal2 (ret_v, res_v);
3177 fz_rect *b = NULL;
3178 struct page *page;
3179 struct pagedim *pdim;
3180 fz_stext_block *block;
3181 char *s = String_val (ptr_v);
3182 int x = Int_val (x_v), y = Int_val (y_v);
3184 ret_v = Val_int (0);
3185 if (trylock (__func__)) {
3186 goto done;
3189 page = parse_pointer (__func__, s);
3190 pdim = &state.pagedims[page->pdimno];
3191 x += pdim->bounds.x0;
3192 y += pdim->bounds.y0;
3194 ensuretext (page);
3196 for (block = page->text->first_block; block; block = block->next) {
3197 switch (block->type) {
3198 case FZ_STEXT_BLOCK_TEXT:
3199 b = &block->bbox;
3200 break;
3202 case FZ_STEXT_BLOCK_IMAGE:
3203 b = &block->bbox;
3204 break;
3206 default:
3207 continue;
3210 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3211 break;
3212 b = NULL;
3214 if (b) {
3215 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3216 ret_v = caml_alloc_small (1, 1);
3217 Store_double_field (res_v, 0, (double) b->x0);
3218 Store_double_field (res_v, 1, (double) b->x1);
3219 Store_double_field (res_v, 2, (double) b->y0);
3220 Store_double_field (res_v, 3, (double) b->y1);
3221 Field (ret_v, 0) = res_v;
3223 unlock (__func__);
3225 done:
3226 CAMLreturn (ret_v);
3229 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3231 CAMLparam2 (ptr_v, rect_v);
3232 fz_rect b;
3233 struct page *page;
3234 struct pagedim *pdim;
3235 char *s = String_val (ptr_v);
3236 int x0, x1, y0, y1;
3237 fz_stext_char *ch;
3238 fz_stext_line *line;
3239 fz_stext_block *block;
3240 fz_stext_char *fc, *lc;
3242 if (trylock (__func__)) {
3243 goto done;
3246 page = parse_pointer (__func__, s);
3247 ensuretext (page);
3249 pdim = &state.pagedims[page->pdimno];
3250 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3251 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3252 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3253 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3255 if (y0 > y1) {
3256 int t = y0;
3257 y0 = y1;
3258 y1 = t;
3259 x0 = x1;
3260 x1 = t;
3263 fc = page->fmark.ch;
3264 lc = page->lmark.ch;
3266 for (block = page->text->first_block; block; block = block->next) {
3267 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3268 for (line = block->u.t.first_line; line; line = line->next) {
3269 for (ch = line->first_char; ch; ch = ch->next) {
3270 b = ch->bbox;
3271 if (x0 >= b.x0 && x0 <= b.x1 && y0 >= b.y0 && y0 <= b.y1) {
3272 fc = ch;
3274 if (x1 >= b.x0 && x1 <= b.x1 && y1 >= b.y0 && y1 <= b.y1) {
3275 lc = ch;
3280 if (x1 < x0 && fc == lc) {
3281 fz_stext_char *t;
3283 t = fc;
3284 fc = lc;
3285 lc = t;
3288 page->fmark.ch = fc;
3289 page->lmark.ch = lc;
3291 unlock (__func__);
3293 done:
3294 CAMLreturn0;
3297 static int pipechar (FILE *f, fz_stext_char *ch)
3299 char buf[4];
3300 int len;
3301 size_t ret;
3303 len = fz_runetochar (buf, ch->c);
3304 ret = fwrite (buf, len, 1, f);
3305 if (ret != 1) {
3306 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3307 len, ret, errno, strerror (errno));
3308 return -1;
3310 return 0;
3313 CAMLprim value ml_spawn (value command_v, value fds_v)
3315 CAMLparam2 (command_v, fds_v);
3316 CAMLlocal2 (l_v, tup_v);
3317 int ret, ret1;
3318 pid_t pid = (pid_t) -1;
3319 char *msg = NULL;
3320 value earg_v = Nothing;
3321 posix_spawnattr_t attr;
3322 posix_spawn_file_actions_t fa;
3323 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3325 argv[2] = String_val (command_v);
3327 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3328 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3331 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3332 msg = "posix_spawnattr_init";
3333 goto fail1;
3336 #ifdef POSIX_SPAWN_USEVFORK
3337 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3338 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3339 goto fail;
3341 #endif
3343 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3344 int fd1, fd2;
3346 tup_v = Field (l_v, 0);
3347 fd1 = Int_val (Field (tup_v, 0));
3348 fd2 = Int_val (Field (tup_v, 1));
3349 if (fd2 < 0) {
3350 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3351 msg = "posix_spawn_file_actions_addclose";
3352 earg_v = tup_v;
3353 goto fail;
3356 else {
3357 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3358 msg = "posix_spawn_file_actions_adddup2";
3359 earg_v = tup_v;
3360 goto fail;
3365 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3366 msg = "posix_spawn";
3367 goto fail;
3370 fail:
3371 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3372 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3375 fail1:
3376 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3377 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3378 ret1, strerror (ret1));
3381 if (msg)
3382 unix_error (ret, msg, earg_v);
3384 CAMLreturn (Val_int (pid));
3387 CAMLprim value ml_hassel (value ptr_v)
3389 CAMLparam1 (ptr_v);
3390 CAMLlocal1 (ret_v);
3391 struct page *page;
3392 char *s = String_val (ptr_v);
3394 ret_v = Val_bool (0);
3395 if (trylock (__func__)) {
3396 goto done;
3399 page = parse_pointer (__func__, s);
3400 ret_v = Val_bool (page->fmark.ch && page->lmark.ch);
3401 unlock (__func__);
3402 done:
3403 CAMLreturn (ret_v);
3406 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3408 CAMLparam2 (fd_v, ptr_v);
3409 FILE *f;
3410 int seen = 0;
3411 struct page *page;
3412 fz_stext_line *line;
3413 fz_stext_block *block;
3414 int fd = Int_val (fd_v);
3415 char *s = String_val (ptr_v);
3417 if (trylock (__func__)) {
3418 goto done;
3421 page = parse_pointer (__func__, s);
3423 if (!page->fmark.ch || !page->lmark.ch) {
3424 printd ("emsg nothing to copy on page %d", page->pageno);
3425 goto unlock;
3428 f = fdopen (fd, "w");
3429 if (!f) {
3430 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3431 fd, errno, strerror (errno));
3432 f = stdout;
3435 for (block = page->text->first_block; block; block = block->next) {
3436 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3437 for (line = block->u.t.first_line; line; line = line->next) {
3438 fz_stext_char *ch;
3439 for (ch = line->first_char; ch; ch = ch->next) {
3440 if (seen || ch == page->fmark.ch) {
3441 do {
3442 pipechar (f, ch);
3443 if (ch == page->lmark.ch) goto close;
3444 } while ((ch = ch->next));
3445 seen = 1;
3446 break;
3449 if (seen) fputc ('\n', f);
3452 close:
3453 if (f != stdout) {
3454 int ret = fclose (f);
3455 fd = -1;
3456 if (ret == -1) {
3457 if (errno != ECHILD) {
3458 printd ("emsg failed to close sel pipe: %d:%s",
3459 errno, strerror (errno));
3463 unlock:
3464 unlock (__func__);
3466 done:
3467 if (fd >= 0) {
3468 if (close (fd)) {
3469 printd ("emsg failed to close sel pipe: %d:%s",
3470 errno, strerror (errno));
3473 CAMLreturn0;
3476 CAMLprim value ml_getpdimrect (value pagedimno_v)
3478 CAMLparam1 (pagedimno_v);
3479 CAMLlocal1 (ret_v);
3480 int pagedimno = Int_val (pagedimno_v);
3481 fz_rect box;
3483 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3484 if (trylock (__func__)) {
3485 box = fz_empty_rect;
3487 else {
3488 box = state.pagedims[pagedimno].mediabox;
3489 unlock (__func__);
3492 Store_double_field (ret_v, 0, (double) box.x0);
3493 Store_double_field (ret_v, 1, (double) box.x1);
3494 Store_double_field (ret_v, 2, (double) box.y0);
3495 Store_double_field (ret_v, 3, (double) box.y1);
3497 CAMLreturn (ret_v);
3500 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3501 value dw_v, value cols_v)
3503 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3504 CAMLlocal1 (ret_v);
3505 int i;
3506 float zoom = -1.;
3507 float maxh = 0.0;
3508 struct pagedim *p;
3509 float winw = Int_val (winw_v);
3510 float winh = Int_val (winh_v);
3511 float dw = Int_val (dw_v);
3512 float cols = Int_val (cols_v);
3513 float pw = 1.0, ph = 1.0;
3515 if (trylock (__func__)) {
3516 goto done;
3519 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3520 float w = p->pagebox.x1 / cols;
3521 float h = p->pagebox.y1;
3522 if (h > maxh) {
3523 maxh = h;
3524 ph = h;
3525 if (state.fitmodel != FitProportional) pw = w;
3527 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3530 zoom = (((winh / ph) * pw) + dw) / winw;
3531 unlock (__func__);
3532 done:
3533 ret_v = caml_copy_double ((double) zoom);
3534 CAMLreturn (ret_v);
3537 CAMLprim value ml_getmaxw (value unit_v)
3539 CAMLparam1 (unit_v);
3540 CAMLlocal1 (ret_v);
3541 int i;
3542 float maxw = -1.;
3543 struct pagedim *p;
3545 if (trylock (__func__)) {
3546 goto done;
3549 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3550 float w = p->pagebox.x1;
3551 maxw = fz_max (maxw, w);
3554 unlock (__func__);
3555 done:
3556 ret_v = caml_copy_double ((double) maxw);
3557 CAMLreturn (ret_v);
3560 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3562 CAMLparam4 (pt_v, x_v, y_v, string_v);
3563 CAMLlocal1 (ret_v);
3564 int pt = Int_val(pt_v);
3565 int x = Int_val (x_v);
3566 int y = Int_val (y_v);
3567 double w;
3569 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3570 ret_v = caml_copy_double (w);
3571 CAMLreturn (ret_v);
3574 CAMLprim value ml_measure_string (value pt_v, value string_v)
3576 CAMLparam2 (pt_v, string_v);
3577 CAMLlocal1 (ret_v);
3578 int pt = Int_val (pt_v);
3579 double w;
3581 w = (double) measure_string (state.face, pt, String_val (string_v));
3582 ret_v = caml_copy_double (w);
3583 CAMLreturn (ret_v);
3586 CAMLprim value ml_getpagebox (value opaque_v)
3588 CAMLparam1 (opaque_v);
3589 CAMLlocal1 (ret_v);
3590 fz_rect rect;
3591 fz_irect bbox;
3592 fz_matrix ctm;
3593 fz_device *dev;
3594 char *s = String_val (opaque_v);
3595 struct page *page = parse_pointer (__func__, s);
3597 ret_v = caml_alloc_tuple (4);
3598 dev = fz_new_bbox_device (state.ctx, &rect);
3600 ctm = pagectm (page);
3601 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3603 fz_close_device (state.ctx, dev);
3604 fz_drop_device (state.ctx, dev);
3605 fz_round_rect (&bbox, &rect);
3606 Field (ret_v, 0) = Val_int (bbox.x0);
3607 Field (ret_v, 1) = Val_int (bbox.y0);
3608 Field (ret_v, 2) = Val_int (bbox.x1);
3609 Field (ret_v, 3) = Val_int (bbox.y1);
3611 CAMLreturn (ret_v);
3614 CAMLprim void ml_setaalevel (value level_v)
3616 CAMLparam1 (level_v);
3618 state.aalevel = Int_val (level_v);
3619 CAMLreturn0;
3622 #ifndef __COCOA__
3623 #pragma GCC diagnostic push
3624 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3625 #include <X11/Xlib.h>
3626 #include <X11/cursorfont.h>
3627 #pragma GCC diagnostic pop
3629 #ifdef USE_EGL
3630 #include <EGL/egl.h>
3631 #else
3632 #include <GL/glx.h>
3633 #endif
3635 static const int shapes[] = {
3636 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3639 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3641 static struct {
3642 Window wid;
3643 Display *dpy;
3644 #ifdef USE_EGL
3645 EGLContext ctx;
3646 EGLConfig conf;
3647 EGLSurface win;
3648 EGLDisplay *edpy;
3649 #else
3650 GLXContext ctx;
3651 #endif
3652 XVisualInfo *visual;
3653 Cursor curs[CURS_COUNT];
3654 } glx;
3657 static void initcurs (void)
3659 for (size_t n = 0; n < CURS_COUNT; ++n) {
3660 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3664 #ifdef USE_EGL
3665 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3667 CAMLparam3 (display_v, wid_v, screen_v);
3668 int major, minor;
3669 int num_conf;
3670 EGLint visid;
3671 EGLint attribs[] = {
3672 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3673 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3674 EGL_NONE
3676 EGLConfig conf;
3678 glx.dpy = XOpenDisplay (String_val (display_v));
3679 if (!glx.dpy) {
3680 caml_failwith ("XOpenDisplay");
3683 eglBindAPI (EGL_OPENGL_API);
3685 glx.edpy = eglGetDisplay (glx.dpy);
3686 if (glx.edpy == EGL_NO_DISPLAY) {
3687 caml_failwith ("eglGetDisplay");
3690 if (!eglInitialize (glx.edpy, &major, &minor)) {
3691 caml_failwith ("eglInitialize");
3694 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3695 !num_conf) {
3696 caml_failwith ("eglChooseConfig");
3699 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3700 caml_failwith ("eglGetConfigAttrib");
3703 glx.conf = conf;
3704 initcurs ();
3706 glx.wid = Int_val (wid_v);
3707 CAMLreturn (Val_int (visid));
3710 CAMLprim void ml_glxcompleteinit (value unit_v)
3712 CAMLparam1 (unit_v);
3714 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3715 if (!glx.ctx) {
3716 caml_failwith ("eglCreateContext");
3719 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3720 glx.wid, NULL);
3721 if (glx.win == EGL_NO_SURFACE) {
3722 caml_failwith ("eglCreateWindowSurface");
3725 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3726 glx.ctx = NULL;
3727 caml_failwith ("eglMakeCurrent");
3729 CAMLreturn0;
3731 #else
3732 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3734 CAMLparam3 (display_v, wid_v, screen_v);
3736 glx.dpy = XOpenDisplay (String_val (display_v));
3737 if (!glx.dpy) {
3738 caml_failwith ("XOpenDisplay");
3741 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3742 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3743 if (!glx.visual) {
3744 XCloseDisplay (glx.dpy);
3745 caml_failwith ("glXChooseVisual");
3748 initcurs ();
3750 glx.wid = Int_val (wid_v);
3751 CAMLreturn (Val_int (glx.visual->visualid));
3754 CAMLprim void ml_glxcompleteinit (value unit_v)
3756 CAMLparam1 (unit_v);
3758 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3759 if (!glx.ctx) {
3760 caml_failwith ("glXCreateContext");
3763 XFree (glx.visual);
3764 glx.visual = NULL;
3766 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3767 glXDestroyContext (glx.dpy, glx.ctx);
3768 glx.ctx = NULL;
3769 caml_failwith ("glXMakeCurrent");
3771 CAMLreturn0;
3773 #endif
3775 CAMLprim void ml_setcursor (value cursor_v)
3777 CAMLparam1 (cursor_v);
3778 size_t cursn = Int_val (cursor_v);
3780 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3781 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3782 XFlush (glx.dpy);
3783 CAMLreturn0;
3786 CAMLprim void ml_swapb (value unit_v)
3788 CAMLparam1 (unit_v);
3789 #ifdef USE_EGL
3790 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3791 caml_failwith ("eglSwapBuffers");
3793 #else
3794 glXSwapBuffers (glx.dpy, glx.wid);
3795 #endif
3796 CAMLreturn0;
3799 long keysym2ucs (KeySym);
3800 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3802 CAMLparam1 (keysym_v);
3803 CAMLlocal1 (str_v);
3804 KeySym keysym = Int_val (keysym_v);
3805 Rune rune;
3806 int len;
3807 char buf[5];
3809 rune = (Rune) keysym2ucs (keysym);
3810 len = fz_runetochar (buf, rune);
3811 buf[len] = 0;
3812 str_v = caml_copy_string (buf);
3813 CAMLreturn (str_v);
3815 #else
3816 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3818 CAMLparam1 (keysym_v);
3819 CAMLlocal1 (str_v);
3820 long ucs_v = Long_val (keysym_v);
3821 int len;
3822 char buf[5];
3824 len = fz_runetochar (buf, (int) ucs_v);
3825 buf[len] = 0;
3826 str_v = caml_copy_string (buf);
3827 CAMLreturn (str_v);
3829 #endif
3831 enum { piunknown, pilinux, piosx, pisun, pibsd };
3833 CAMLprim value ml_platform (value unit_v)
3835 CAMLparam1 (unit_v);
3836 CAMLlocal2 (tup_v, arr_v);
3837 int platid = piunknown;
3838 struct utsname buf;
3840 #if defined __linux__
3841 platid = pilinux;
3842 #elif defined __DragonFly__ || defined __FreeBSD__
3843 || defined __OpenBSD__ || defined __NetBSD__
3844 platid = pibsd;
3845 #elif defined __sun__
3846 platid = pisun;
3847 #elif defined __APPLE__
3848 platid = piosx;
3849 #endif
3850 if (uname (&buf)) err (1, "uname");
3852 tup_v = caml_alloc_tuple (2);
3854 char const *sar[] = {
3855 buf.sysname,
3856 buf.release,
3857 buf.version,
3858 buf.machine,
3859 NULL
3861 arr_v = caml_copy_string_array (sar);
3863 Field (tup_v, 0) = Val_int (platid);
3864 Field (tup_v, 1) = arr_v;
3865 CAMLreturn (tup_v);
3868 CAMLprim void ml_cloexec (value fd_v)
3870 CAMLparam1 (fd_v);
3871 int fd = Int_val (fd_v);
3873 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3874 uerror ("fcntl", Nothing);
3876 CAMLreturn0;
3879 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3881 CAMLparam2 (w_v, h_v);
3882 CAMLlocal1 (ret_v);
3883 struct bo *pbo;
3884 int w = Int_val (w_v);
3885 int h = Int_val (h_v);
3886 int cs = Int_val (cs_v);
3888 if (state.bo_usable) {
3889 pbo = calloc (sizeof (*pbo), 1);
3890 if (!pbo) {
3891 err (1, "calloc pbo");
3894 switch (cs) {
3895 case 0:
3896 case 1:
3897 pbo->size = w*h*4;
3898 break;
3899 case 2:
3900 pbo->size = w*h*2;
3901 break;
3902 default:
3903 errx (1, "%s: invalid colorspace %d", __func__, cs);
3906 state.glGenBuffersARB (1, &pbo->id);
3907 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3908 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3909 NULL, GL_STREAM_DRAW);
3910 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3911 GL_READ_WRITE);
3912 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3913 if (!pbo->ptr) {
3914 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3915 state.glDeleteBuffersARB (1, &pbo->id);
3916 free (pbo);
3917 ret_v = caml_copy_string ("0");
3919 else {
3920 int res;
3921 char *s;
3923 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
3924 if (res < 0) {
3925 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3927 s = malloc (res+1);
3928 if (!s) {
3929 err (1, "malloc %d bytes failed", res+1);
3931 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
3932 if (res < 0) {
3933 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
3935 ret_v = caml_copy_string (s);
3936 free (s);
3939 else {
3940 ret_v = caml_copy_string ("0");
3942 CAMLreturn (ret_v);
3945 CAMLprim void ml_freepbo (value s_v)
3947 CAMLparam1 (s_v);
3948 char *s = String_val (s_v);
3949 struct tile *tile = parse_pointer (__func__, s);
3951 if (tile->pbo) {
3952 state.glDeleteBuffersARB (1, &tile->pbo->id);
3953 tile->pbo->id = -1;
3954 tile->pbo->ptr = NULL;
3955 tile->pbo->size = -1;
3957 CAMLreturn0;
3960 CAMLprim void ml_unmappbo (value s_v)
3962 CAMLparam1 (s_v);
3963 char *s = String_val (s_v);
3964 struct tile *tile = parse_pointer (__func__, s);
3966 if (tile->pbo) {
3967 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3968 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3969 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3971 tile->pbo->ptr = NULL;
3972 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3974 CAMLreturn0;
3977 static void setuppbo (void)
3979 #ifdef __clang__
3980 #pragma GCC diagnostic ignored "-Wunused-macros"
3981 #endif
3982 #ifdef __COCOA__
3983 static CFBundleRef framework = NULL;
3984 if (framework == NULL)
3985 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
3986 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
3987 #else
3988 #ifdef USE_EGL
3989 #define GGPA(n) (*(void (**) (void)) &state.n = eglGetProcAddress (#n))
3990 #else
3991 #define GGPA(n) (*(void (**) (void)) &state.n = glXGetProcAddress ((GLubyte *) #n))
3992 #endif
3993 state.bo_usable = GGPA (glBindBufferARB)
3994 && GGPA (glUnmapBufferARB)
3995 && GGPA (glMapBufferARB)
3996 && GGPA (glBufferDataARB)
3997 && GGPA (glGenBuffersARB)
3998 && GGPA (glDeleteBuffersARB);
3999 #endif
4000 #undef GGPA
4003 CAMLprim value ml_bo_usable (value unit_v)
4005 CAMLparam1 (unit_v);
4006 CAMLreturn (Val_bool (state.bo_usable));
4009 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4011 CAMLparam3 (ptr_v, x_v, y_v);
4012 CAMLlocal2 (ret_v, tup_v);
4013 struct page *page;
4014 char *s = String_val (ptr_v);
4015 int x = Int_val (x_v), y = Int_val (y_v);
4016 struct pagedim *pdim;
4017 fz_point p;
4018 fz_matrix ctm;
4020 page = parse_pointer (__func__, s);
4021 pdim = &state.pagedims[page->pdimno];
4023 ret_v = Val_int (0);
4024 if (trylock (__func__)) {
4025 goto done;
4028 if (pdf_specifics (state.ctx, state.doc)) {
4029 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4030 ctm = state.pagedims[page->pdimno].tctm;
4032 else {
4033 ctm = fz_identity;
4035 p.x = x + pdim->bounds.x0;
4036 p.y = y + pdim->bounds.y0;
4038 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4039 fz_invert_matrix (&ctm, &ctm);
4040 fz_transform_point (&p, &ctm);
4042 tup_v = caml_alloc_tuple (2);
4043 ret_v = caml_alloc_small (1, 1);
4044 Field (tup_v, 0) = Val_int (p.x);
4045 Field (tup_v, 1) = Val_int (p.y);
4046 Field (ret_v, 0) = tup_v;
4048 unlock (__func__);
4049 done:
4050 CAMLreturn (ret_v);
4053 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4054 value x_v, value y_v)
4056 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4057 CAMLlocal1 (ret_v);
4058 struct page *page;
4059 char *s = String_val (ptr_v);
4060 int pageno = Int_val (pageno_v);
4061 int pdimno = Int_val (pdimno_v);
4062 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
4063 struct pagedim *pdim;
4064 fz_point p;
4065 fz_matrix ctm;
4067 ret_v = Val_int (0);
4068 lock (__func__);
4070 if (!*s) {
4071 page = loadpage (pageno, pdimno);
4073 else {
4074 page = parse_pointer (__func__, s);
4076 pdim = &state.pagedims[pdimno];
4078 if (pdf_specifics (state.ctx, state.doc)) {
4079 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4080 ctm = state.pagedims[page->pdimno].tctm;
4082 else {
4083 ctm = fz_identity;
4085 p.x = x + pdim->bounds.x0;
4086 p.y = y + pdim->bounds.y0;
4088 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4089 fz_transform_point (&p, &ctm);
4091 ret_v = caml_alloc_tuple (2);
4092 Field (ret_v, 0) = caml_copy_double ((double) p.x);
4093 Field (ret_v, 1) = caml_copy_double ((double) p.y);
4095 if (!*s) {
4096 freepage (page);
4098 unlock (__func__);
4099 CAMLreturn (ret_v);
4102 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4103 value contents_v)
4105 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4106 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4108 if (pdf) {
4109 pdf_annot *annot;
4110 struct page *page;
4111 fz_point p;
4112 char *s = String_val (ptr_v);
4114 page = parse_pointer (__func__, s);
4115 annot = pdf_create_annot (state.ctx,
4116 pdf_page_from_fz_page (state.ctx,
4117 page->fzpage),
4118 PDF_ANNOT_TEXT);
4119 p.x = Int_val (x_v);
4120 p.y = Int_val (y_v);
4121 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4122 pdf_set_text_annot_position (state.ctx, annot, p);
4123 state.dirty = 1;
4125 CAMLreturn0;
4128 CAMLprim void ml_delannot (value ptr_v, value n_v)
4130 CAMLparam2 (ptr_v, n_v);
4131 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4133 if (pdf) {
4134 struct page *page;
4135 char *s = String_val (ptr_v);
4136 struct slink *slink;
4138 page = parse_pointer (__func__, s);
4139 slink = &page->slinks[Int_val (n_v)];
4140 pdf_delete_annot (state.ctx,
4141 pdf_page_from_fz_page (state.ctx, page->fzpage),
4142 (pdf_annot *) slink->u.annot);
4143 state.dirty = 1;
4145 CAMLreturn0;
4148 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4150 CAMLparam3 (ptr_v, n_v, str_v);
4151 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4153 if (pdf) {
4154 struct page *page;
4155 char *s = String_val (ptr_v);
4156 struct slink *slink;
4158 page = parse_pointer (__func__, s);
4159 slink = &page->slinks[Int_val (n_v)];
4160 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4161 String_val (str_v));
4162 state.dirty = 1;
4164 CAMLreturn0;
4167 CAMLprim value ml_hasunsavedchanges (value unit_v)
4169 CAMLparam1 (unit_v);
4170 CAMLreturn (Val_bool (state.dirty));
4173 CAMLprim void ml_savedoc (value path_v)
4175 CAMLparam1 (path_v);
4176 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4178 if (pdf) {
4179 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4181 CAMLreturn0;
4184 static void makestippletex (void)
4186 const char pixels[] = "\xff\xff\0\0";
4187 glGenTextures (1, &state.stid);
4188 glBindTexture (GL_TEXTURE_1D, state.stid);
4189 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4190 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4191 glTexImage1D (
4192 GL_TEXTURE_1D,
4194 GL_ALPHA,
4197 GL_ALPHA,
4198 GL_UNSIGNED_BYTE,
4199 pixels
4203 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4205 return caml_copy_string (FZ_VERSION);
4208 static char *ystrdup (const char *s)
4210 size_t len = strlen (s);
4211 if (len > 0) {
4212 char *r = malloc (len+1);
4213 if (!r) errx (1, "malloc %zu", len+1);
4214 memcpy (r, s, len+1);
4215 return r;
4217 return NULL;
4220 CAMLprim void ml_init (value csock_v, value params_v)
4222 CAMLparam2 (csock_v, params_v);
4223 CAMLlocal2 (trim_v, fuzz_v);
4224 int ret;
4225 int texcount;
4226 char *fontpath;
4227 int colorspace;
4228 int mustoresize;
4229 int haspboext;
4231 state.csock = Int_val (csock_v);
4232 state.rotate = Int_val (Field (params_v, 0));
4233 state.fitmodel = Int_val (Field (params_v, 1));
4234 trim_v = Field (params_v, 2);
4235 texcount = Int_val (Field (params_v, 3));
4236 state.sliceheight = Int_val (Field (params_v, 4));
4237 mustoresize = Int_val (Field (params_v, 5));
4238 colorspace = Int_val (Field (params_v, 6));
4239 fontpath = String_val (Field (params_v, 7));
4241 #ifdef __COCOA__
4242 state.utf8cs = 1;
4243 #else
4244 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
4245 if (setlocale (LC_CTYPE, "")) {
4246 const char *cset = nl_langinfo (CODESET);
4247 state.utf8cs = !strcmp (cset, "UTF-8");
4249 else {
4250 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
4252 #endif
4254 if (caml_string_length (Field (params_v, 8)) > 0) {
4255 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
4257 if (!state.trimcachepath) {
4258 printd ("emsg failed to strdup trimcachepath: %d:%s",
4259 errno, strerror (errno));
4263 haspboext = Bool_val (Field (params_v, 9));
4265 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4266 fz_register_document_handlers (state.ctx);
4268 state.trimmargins = Bool_val (Field (trim_v, 0));
4269 fuzz_v = Field (trim_v, 1);
4270 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4271 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4272 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4273 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4275 set_tex_params (colorspace);
4277 if (*fontpath) {
4278 state.face = load_font (fontpath);
4280 else {
4281 int len;
4282 const unsigned char *data;
4284 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4285 state.face = load_builtin_font (data, len);
4287 if (!state.face) _exit (1);
4289 realloctexts (texcount);
4291 if (haspboext) {
4292 setuppbo ();
4295 makestippletex ();
4297 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4298 if (ret) {
4299 errx (1, "pthread_create: %s", strerror (ret));
4302 CAMLreturn0;
4305 #if FIXME || !FIXME
4306 static void OPTIMIZE_ATTR (0) UNUSED_ATTR refmacs (void) {}
4307 #endif