Cosmetics
[llpp.git] / link.c
blob5d3dc3caf951b608cbbe038cf4fc9925e934bc47
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
3 #define FIXME 0
5 #include <errno.h>
6 #include <stdio.h>
7 #include <ctype.h>
8 #include <string.h>
9 #include <stdlib.h>
10 #include <signal.h>
11 #include <wchar.h>
13 #include <unistd.h>
14 #include <pthread.h>
15 #include <sys/uio.h>
16 #include <sys/time.h>
17 #include <sys/types.h>
18 #include <sys/ioctl.h>
19 #include <sys/utsname.h>
21 #ifdef __CYGWIN__
22 #include <cygwin/socket.h> /* FIONREAD */
23 #else
24 #include <spawn.h>
25 #endif
27 #include <regex.h>
28 #include <stdarg.h>
29 #include <limits.h>
30 #include <inttypes.h>
32 #include <GL/gl.h>
34 #include <caml/fail.h>
35 #include <caml/alloc.h>
36 #include <caml/memory.h>
37 #include <caml/unixsupport.h>
39 #if __GNUC__ < 5 && !defined __clang__
40 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
41 clobbered diagnostics */
42 #pragma GCC diagnostic ignored "-Wclobbered"
43 #endif
45 #include <mupdf/fitz.h>
46 #include <mupdf/pdf.h>
48 #include <ft2build.h>
49 #include FT_FREETYPE_H
51 #ifdef USE_FONTCONFIG
52 #include <fontconfig/fontconfig.h>
53 #endif
55 #define PIGGYBACK
56 #define CACHE_PAGEREFS
58 #ifndef __USE_GNU
59 extern char **environ;
60 #endif
62 #if defined __GNUC__
63 #define NORETURN_ATTR __attribute__ ((noreturn))
64 #define UNUSED_ATTR __attribute__ ((unused))
65 #if !defined __clang__
66 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
67 #else
68 #define OPTIMIZE_ATTR(n)
69 #endif
70 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
71 #else
72 #define NORETURN_ATTR
73 #define UNUSED_ATTR
74 #define OPTIMIZE_ATTR(n)
75 #define GCC_FMT_ATTR(a, b)
76 #endif
78 #define FMT_s "zu"
80 #define FMT_ptr PRIxPTR
81 #define SCN_ptr SCNxPTR
82 #define FMT_ptr_cast(p) ((uintptr_t) (p))
83 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
85 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
86 err (int exitcode, const char *fmt, ...)
88 va_list ap;
89 int savederrno;
91 savederrno = errno;
92 va_start (ap, fmt);
93 vfprintf (stderr, fmt, ap);
94 va_end (ap);
95 fprintf (stderr, ": %s\n", strerror (savederrno));
96 fflush (stderr);
97 _exit (exitcode);
100 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
101 errx (int exitcode, const char *fmt, ...)
103 va_list ap;
105 va_start (ap, fmt);
106 vfprintf (stderr, fmt, ap);
107 va_end (ap);
108 fputc ('\n', stderr);
109 fflush (stderr);
110 _exit (exitcode);
113 #ifndef GL_TEXTURE_RECTANGLE_ARB
114 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
115 #endif
117 #ifdef USE_NPOT
118 #define TEXT_TYPE GL_TEXTURE_2D
119 #else
120 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
121 #endif
123 #ifndef GL_BGRA
124 #define GL_BGRA 0x80E1
125 #endif
127 #ifndef GL_UNSIGNED_INT_8_8_8_8
128 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
129 #endif
131 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
132 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
133 #endif
135 #if 0
136 #define lprintf printf
137 #else
138 #define lprintf(...)
139 #endif
141 #define ARSERT(cond) for (;;) { \
142 if (!(cond)) { \
143 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
145 break; \
148 struct slice {
149 int h;
150 int texindex;
153 struct tile {
154 int w, h;
155 int slicecount;
156 int sliceheight;
157 struct bo *pbo;
158 fz_pixmap *pixmap;
159 struct slice slices[1];
162 struct pagedim {
163 int pageno;
164 int rotate;
165 int left;
166 int tctmready;
167 fz_irect bounds;
168 fz_rect pagebox;
169 fz_rect mediabox;
170 fz_matrix ctm, zoomctm, tctm;
173 struct slink {
174 enum { SLINK, SANNOT } tag;
175 fz_irect bbox;
176 union {
177 fz_link *link;
178 fz_annot *annot;
179 } u;
182 struct annot {
183 fz_irect bbox;
184 fz_annot *annot;
187 struct page {
188 int tgen;
189 int sgen;
190 int agen;
191 int pageno;
192 int pdimno;
193 fz_stext_page *text;
194 fz_stext_sheet *sheet;
195 fz_page *fzpage;
196 fz_display_list *dlist;
197 int slinkcount;
198 struct slink *slinks;
199 int annotcount;
200 struct annot *annots;
201 struct mark {
202 int i;
203 fz_stext_span *span;
204 } fmark, lmark;
207 struct {
208 int sliceheight;
209 struct pagedim *pagedims;
210 int pagecount;
211 int pagedimcount;
212 fz_document *doc;
213 fz_context *ctx;
214 int w, h;
216 int texindex;
217 int texcount;
218 GLuint *texids;
220 GLenum texiform;
221 GLenum texform;
222 GLenum texty;
224 fz_colorspace *colorspace;
226 struct {
227 int w, h;
228 struct slice *slice;
229 } *texowners;
231 int rotate;
232 enum { FitWidth, FitProportional, FitPage } fitmodel;
233 int trimmargins;
234 int needoutline;
235 int gen;
236 int aalevel;
238 int trimanew;
239 fz_irect trimfuzz;
240 fz_pixmap *pig;
242 pthread_t thread;
243 int csock;
244 FT_Face face;
246 char *trimcachepath;
247 int cxack;
248 int dirty;
250 GLuint stid;
252 int bo_usable;
253 GLuint boid;
255 void (*glBindBufferARB) (GLenum, GLuint);
256 GLboolean (*glUnmapBufferARB) (GLenum);
257 void *(*glMapBufferARB) (GLenum, GLenum);
258 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
259 void (*glGenBuffersARB) (GLsizei, GLuint *);
260 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
262 GLfloat texcoords[8];
263 GLfloat vertices[16];
265 #ifdef CACHE_PAGEREFS
266 struct {
267 int idx;
268 int count;
269 pdf_obj **objs;
270 pdf_document *pdf;
271 } pdflut;
272 #endif
273 } state;
275 struct bo {
276 GLuint id;
277 void *ptr;
278 size_t size;
281 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
283 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
286 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
288 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
291 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
293 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
294 m.a, m.b, m.c, m.d, m.e, m.f);
297 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
299 static void lock (const char *cap)
301 int ret = pthread_mutex_lock (&mutex);
302 if (ret) {
303 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
307 static void unlock (const char *cap)
309 int ret = pthread_mutex_unlock (&mutex);
310 if (ret) {
311 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
315 static int trylock (const char *cap)
317 int ret = pthread_mutex_trylock (&mutex);
318 if (ret && ret != EBUSY) {
319 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
321 return ret == EBUSY;
324 static void *parse_pointer (const char *cap, const char *s)
326 int ret;
327 void *ptr;
329 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
330 if (ret != 1) {
331 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
333 return ptr;
336 static double now (void)
338 struct timeval tv;
340 if (gettimeofday (&tv, NULL)) {
341 err (1, "gettimeofday");
343 return tv.tv_sec + tv.tv_usec*1e-6;
346 static int hasdata (void)
348 int ret, avail;
349 ret = ioctl (state.csock, FIONREAD, &avail);
350 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
351 return avail > 0;
354 CAMLprim value ml_hasdata (value fd_v)
356 CAMLparam1 (fd_v);
357 int ret, avail;
359 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
360 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
361 CAMLreturn (Val_bool (avail > 0));
364 static void readdata (int fd, void *p, int size)
366 ssize_t n;
368 again:
369 n = read (fd, p, size);
370 if (n - size) {
371 if (n < 0 && errno == EINTR) goto again;
372 if (!n) errx (1, "EOF while reading");
373 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
377 static void writedata (int fd, char *p, int size)
379 ssize_t n;
380 uint32_t size4 = size;
381 struct iovec iov[2] = {[0] = { .iov_base = &size4,
382 .iov_len = 4},
383 [1] = { .iov_base = p,
384 .iov_len = size }};
386 again:
387 n = writev (fd, iov, 2);
388 if (n < 0 && errno == EINTR) goto again;
389 if (n - size - 4) {
390 if (!n) errx (1, "EOF while writing data");
391 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
395 static int readlen (int fd)
397 /* Type punned unions here. Why? Less code (Adjusted by more comments).
398 https://en.wikipedia.org/wiki/Type_punning */
399 union { uint32_t len; char raw[4]; } buf;
400 readdata (fd, buf.raw, 4);
401 return buf.len;
404 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
406 CAMLparam3 (fd_v, bytes_v, len_v);
407 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
408 CAMLreturn0;
411 CAMLprim value ml_rcmd (value fd_v)
413 CAMLparam1 (fd_v);
414 CAMLlocal1 (strdata_v);
415 int fd = Int_val (fd_v);
416 int len = readlen (fd);
417 strdata_v = caml_alloc_string (len);
418 readdata (fd, String_val (strdata_v), len);
419 CAMLreturn (strdata_v);
422 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
424 int size = 64, len;
425 va_list ap;
426 char fbuf[size];
427 char *buf = fbuf;
429 for (;;) {
430 va_start (ap, fmt);
431 len = vsnprintf (buf, size, fmt, ap);
432 va_end (ap);
434 if (len > -1) {
435 if (len < size - 4) {
436 writedata (state.csock, buf, len);
437 break;
439 else size = len + 5;
441 else {
442 err (1, "vsnprintf for `%s' failed", fmt);
444 buf = realloc (buf == fbuf ? NULL : buf, size);
445 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
447 if (buf != fbuf) free (buf);
450 static void closedoc (void)
452 #ifdef CACHE_PAGEREFS
453 if (state.pdflut.objs) {
454 int i;
456 for (i = 0; i < state.pdflut.count; ++i) {
457 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
459 free (state.pdflut.objs);
460 state.pdflut.objs = NULL;
461 state.pdflut.idx = 0;
463 #endif
464 if (state.doc) {
465 fz_drop_document (state.ctx, state.doc);
466 state.doc = NULL;
470 static int openxref (char *filename, char *password)
472 int i;
474 for (i = 0; i < state.texcount; ++i) {
475 state.texowners[i].w = -1;
476 state.texowners[i].slice = NULL;
479 closedoc ();
481 state.dirty = 0;
482 if (state.pagedims) {
483 free (state.pagedims);
484 state.pagedims = NULL;
486 state.pagedimcount = 0;
488 fz_set_aa_level (state.ctx, state.aalevel);
489 state.doc = fz_open_document (state.ctx, filename);
490 if (fz_needs_password (state.ctx, state.doc)) {
491 if (password && !*password) {
492 printd ("pass");
493 return 0;
495 else {
496 int ok = fz_authenticate_password (state.ctx, state.doc, password);
497 if (!ok) {
498 printd ("pass fail");
499 return 0;
503 state.pagecount = fz_count_pages (state.ctx, state.doc);
504 return 1;
507 static void pdfinfo (void)
509 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
510 if (pdf) {
511 pdf_obj *infoobj;
513 printd ("info PDF version\t%d.%d",
514 pdf->version / 10, pdf->version % 10);
516 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
517 pdf), "Info");
518 if (infoobj) {
519 unsigned int i;
520 char *s;
521 char *items[] = { "Title", "Author", "Creator",
522 "Producer", "CreationDate" };
524 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
525 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
526 s = pdf_to_utf8 (state.ctx, obj);
527 if (*s) printd ("info %s\t%s", items[i], s);
528 fz_free (state.ctx, s);
531 printd ("infoend");
535 static void unlinktile (struct tile *tile)
537 int i;
539 for (i = 0; i < tile->slicecount; ++i) {
540 struct slice *s = &tile->slices[i];
542 if (s->texindex != -1) {
543 if (state.texowners[s->texindex].slice == s) {
544 state.texowners[s->texindex].slice = NULL;
550 static void freepage (struct page *page)
552 if (!page) return;
553 if (page->text) {
554 fz_drop_stext_page (state.ctx, page->text);
556 if (page->sheet) {
557 fz_drop_stext_sheet (state.ctx, page->sheet);
559 if (page->slinks) {
560 free (page->slinks);
562 fz_drop_display_list (state.ctx, page->dlist);
563 fz_drop_page (state.ctx, page->fzpage);
564 free (page);
567 static void freetile (struct tile *tile)
569 unlinktile (tile);
570 if (!tile->pbo) {
571 #ifndef PIGGYBACK
572 fz_drop_pixmap (state.ctx, tile->pixmap);
573 #else
574 if (state.pig) {
575 fz_drop_pixmap (state.ctx, state.pig);
577 state.pig = tile->pixmap;
578 #endif
580 else {
581 free (tile->pbo);
582 fz_drop_pixmap (state.ctx, tile->pixmap);
584 free (tile);
587 #ifdef __ALTIVEC__
588 #include <stdint.h>
589 #include <altivec.h>
591 static int cacheline32bytes;
593 static void __attribute__ ((constructor)) clcheck (void)
595 char **envp = environ;
596 unsigned long *auxv;
598 while (*envp++);
600 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
601 if (*auxv == 19) {
602 cacheline32bytes = auxv[1] == 32;
603 return;
608 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
610 size_t size = pixmap->w * pixmap->h * pixmap->n;
611 if (cacheline32bytes && size > 32) {
612 intptr_t a1, a2, diff;
613 size_t sizea, i;
614 vector unsigned char v = vec_splat_u8 (-1);
615 vector unsigned char *p;
617 a1 = a2 = (intptr_t) pixmap->samples;
618 a2 = (a1 + 31) & ~31;
619 diff = a2 - a1;
620 sizea = size - diff;
621 p = (void *) a2;
623 while (a1 != a2) *(char *) a1++ = 0xff;
624 for (i = 0; i < (sizea & ~31); i += 32) {
625 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
626 vec_st (v, i, p);
627 vec_st (v, i + 16, p);
629 while (i < sizea) *((char *) a1 + i++) = 0xff;
631 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
633 #else
634 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
635 #endif
637 static void trimctm (pdf_page *page, int pindex)
639 fz_matrix ctm;
640 struct pagedim *pdim = &state.pagedims[pindex];
642 if (!page) return;
643 if (!pdim->tctmready) {
644 fz_rect realbox, mediabox;
645 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
647 fz_rotate (&rm, -pdim->rotate);
648 fz_scale (&sm, 1, -1);
649 fz_concat (&ctm, &rm, &sm);
650 realbox = pdim->mediabox;
651 fz_transform_rect (&realbox, &ctm);
652 fz_translate (&tm, -realbox.x0, -realbox.y0);
653 fz_concat (&ctm1, &ctm, &tm);
654 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
655 fz_invert_matrix (&im, &page_ctm);
656 fz_concat (&ctm, &im, &ctm1);
657 pdim->tctm = ctm;
658 pdim->tctmready = 1;
662 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
664 fz_matrix ctm, tm;
665 int pdimno = pdim - state.pagedims;
667 if (pdf_specifics (state.ctx, state.doc)) {
668 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
669 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
671 else {
672 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
673 fz_concat (&ctm, &tm, &pdim->ctm);
675 return ctm;
678 static fz_matrix pagectm (struct page *page)
680 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
683 static void *loadpage (int pageno, int pindex)
685 fz_device *dev;
686 struct page *page;
688 page = calloc (sizeof (struct page), 1);
689 if (!page) {
690 err (1, "calloc page %d", pageno);
693 page->dlist = fz_new_display_list (state.ctx, NULL);
694 dev = fz_new_list_device (state.ctx, page->dlist);
695 fz_try (state.ctx) {
696 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
697 fz_run_page (state.ctx, page->fzpage, dev,
698 &fz_identity, NULL);
700 fz_catch (state.ctx) {
701 page->fzpage = NULL;
703 fz_close_device (state.ctx, dev);
704 fz_drop_device (state.ctx, dev);
706 page->pdimno = pindex;
707 page->pageno = pageno;
708 page->sgen = state.gen;
709 page->agen = state.gen;
710 page->tgen = state.gen;
711 return page;
714 static struct tile *alloctile (int h)
716 int i;
717 int slicecount;
718 size_t tilesize;
719 struct tile *tile;
721 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
722 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
723 tile = calloc (tilesize, 1);
724 if (!tile) {
725 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
727 for (i = 0; i < slicecount; ++i) {
728 int sh = fz_mini (h, state.sliceheight);
729 tile->slices[i].h = sh;
730 tile->slices[i].texindex = -1;
731 h -= sh;
733 tile->slicecount = slicecount;
734 tile->sliceheight = state.sliceheight;
735 return tile;
738 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
739 struct bo *pbo)
741 fz_rect rect;
742 fz_irect bbox;
743 fz_matrix ctm;
744 fz_device *dev;
745 struct tile *tile;
746 struct pagedim *pdim;
748 tile = alloctile (h);
749 pdim = &state.pagedims[page->pdimno];
751 bbox = pdim->bounds;
752 bbox.x0 += x;
753 bbox.y0 += y;
754 bbox.x1 = bbox.x0 + w;
755 bbox.y1 = bbox.y0 + h;
757 if (state.pig) {
758 if (state.pig->w == w
759 && state.pig->h == h
760 && state.pig->colorspace == state.colorspace) {
761 tile->pixmap = state.pig;
762 tile->pixmap->x = bbox.x0;
763 tile->pixmap->y = bbox.y0;
765 else {
766 fz_drop_pixmap (state.ctx, state.pig);
768 state.pig = NULL;
770 if (!tile->pixmap) {
771 if (pbo) {
772 tile->pixmap =
773 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
774 &bbox, 1, pbo->ptr);
775 tile->pbo = pbo;
777 else {
778 tile->pixmap =
779 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
783 tile->w = w;
784 tile->h = h;
785 clearpixmap (tile->pixmap);
787 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
788 ctm = pagectm (page);
789 fz_rect_from_irect (&rect, &bbox);
790 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
791 fz_close_device (state.ctx, dev);
792 fz_drop_device (state.ctx, dev);
794 return tile;
797 #ifdef CACHE_PAGEREFS
798 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
799 thanks to Robin Watts */
800 static void
801 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
803 fz_context *ctx = state.ctx; /* doc->ctx; */
804 pdf_obj *kids;
805 int i, len;
807 if (state.pdflut.idx == state.pagecount) return;
809 kids = pdf_dict_gets (ctx, node, "Kids");
810 len = pdf_array_len (ctx, kids);
812 if (len == 0)
813 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
815 if (pdf_mark_obj (ctx, node))
816 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
817 for (i = 0; i < len; i++) {
818 pdf_obj *kid = pdf_array_get (ctx, kids, i);
819 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
820 if (*type
821 ? !strcmp (type, "Pages")
822 : pdf_dict_gets (ctx, kid, "Kids")
823 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
824 pdf_collect_pages (doc, kid);
826 else {
827 if (*type
828 ? strcmp (type, "Page") != 0
829 : !pdf_dict_gets (ctx, kid, "MediaBox"))
830 fz_warn (ctx, "non-page object in page tree (%s)", type);
831 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
834 pdf_unmark_obj (ctx, node);
837 static void
838 pdf_load_page_objs (pdf_document *doc)
840 pdf_obj *root = pdf_dict_gets (state.ctx,
841 pdf_trailer (state.ctx, doc), "Root");
842 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
844 if (!node)
845 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
847 state.pdflut.idx = 0;
848 pdf_collect_pages (doc, node);
850 #endif
852 static void initpdims (int wthack)
854 double start, end;
855 FILE *trimf = NULL;
856 fz_rect rootmediabox;
857 int pageno, trim, show;
858 int trimw = 0, cxcount;
859 fz_context *ctx = state.ctx;
860 pdf_document *pdf = pdf_specifics (ctx, state.doc);
862 fz_var (trimw);
863 fz_var (trimf);
864 fz_var (cxcount);
865 start = now ();
867 if (state.trimmargins && state.trimcachepath) {
868 trimf = fopen (state.trimcachepath, "rb");
869 if (!trimf) {
870 trimf = fopen (state.trimcachepath, "wb");
871 trimw = 1;
875 if (state.trimmargins || pdf || !state.cxack)
876 cxcount = state.pagecount;
877 else
878 cxcount = fz_mini (state.pagecount, 1);
880 if (pdf) {
881 pdf_obj *obj;
882 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
883 "Root/Pages/MediaBox");
884 pdf_to_rect (ctx, obj, &rootmediabox);
887 #ifdef CACHE_PAGEREFS
888 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
889 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
890 if (!state.pdflut.objs) {
891 err (1, "malloc pageobjs %zu %d %zu failed",
892 sizeof (*state.pdflut.objs), cxcount,
893 sizeof (*state.pdflut.objs) * cxcount);
895 state.pdflut.count = cxcount;
896 pdf_load_page_objs (pdf);
897 state.pdflut.pdf = pdf;
899 #endif
901 for (pageno = 0; pageno < cxcount; ++pageno) {
902 int rotate = 0;
903 struct pagedim *p;
904 fz_rect mediabox;
906 fz_var (rotate);
907 if (pdf) {
908 pdf_obj *pageref, *pageobj;
910 #ifdef CACHE_PAGEREFS
911 pageref = state.pdflut.objs[pageno];
912 #else
913 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
914 #endif
915 pageobj = pdf_resolve_indirect (ctx, pageref);
916 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
918 if (state.trimmargins) {
919 pdf_obj *obj;
920 pdf_page *page;
922 fz_try (ctx) {
923 page = pdf_load_page (ctx, pdf, pageno);
924 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
925 trim = state.trimanew || !obj;
926 if (trim) {
927 fz_rect rect;
928 fz_device *dev;
929 fz_matrix ctm, page_ctm;
931 dev = fz_new_bbox_device (ctx, &rect);
932 dev->hints |= FZ_IGNORE_SHADE;
933 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
934 fz_invert_matrix (&ctm, &page_ctm);
935 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
936 fz_close_device (ctx, dev);
937 fz_drop_device (ctx, dev);
939 rect.x0 += state.trimfuzz.x0;
940 rect.x1 += state.trimfuzz.x1;
941 rect.y0 += state.trimfuzz.y0;
942 rect.y1 += state.trimfuzz.y1;
943 fz_transform_rect (&rect, &ctm);
944 fz_intersect_rect (&rect, &mediabox);
946 if (!fz_is_empty_rect (&rect)) {
947 mediabox = rect;
950 obj = pdf_new_array (ctx, pdf, 4);
951 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
952 mediabox.x0));
953 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
954 mediabox.y0));
955 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
956 mediabox.x1));
957 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
958 mediabox.y1));
959 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
961 else {
962 mediabox.x0 = pdf_to_real (ctx,
963 pdf_array_get (ctx, obj, 0));
964 mediabox.y0 = pdf_to_real (ctx,
965 pdf_array_get (ctx, obj, 1));
966 mediabox.x1 = pdf_to_real (ctx,
967 pdf_array_get (ctx, obj, 2));
968 mediabox.y1 = pdf_to_real (ctx,
969 pdf_array_get (ctx, obj, 3));
972 fz_drop_page (ctx, &page->super);
973 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
974 if (show) {
975 printd ("progress %f Trimming %d",
976 (double) (pageno + 1) / state.pagecount,
977 pageno + 1);
980 fz_catch (ctx) {
981 fprintf (stderr, "failed to load page %d\n", pageno+1);
984 else {
985 int empty = 0;
986 fz_rect cropbox;
988 pdf_to_rect (ctx,
989 pdf_dict_gets (ctx, pageobj, "MediaBox"),
990 &mediabox);
991 if (fz_is_empty_rect (&mediabox)) {
992 mediabox.x0 = 0;
993 mediabox.y0 = 0;
994 mediabox.x1 = 612;
995 mediabox.y1 = 792;
996 empty = 1;
999 pdf_to_rect (ctx,
1000 pdf_dict_gets (ctx, pageobj, "CropBox"),
1001 &cropbox);
1002 if (!fz_is_empty_rect (&cropbox)) {
1003 if (empty) {
1004 mediabox = cropbox;
1006 else {
1007 fz_intersect_rect (&mediabox, &cropbox);
1010 else {
1011 if (empty) {
1012 if (fz_is_empty_rect (&rootmediabox)) {
1013 fprintf (stderr,
1014 "cannot find page size for page %d\n",
1015 pageno+1);
1017 else {
1018 mediabox = rootmediabox;
1024 else {
1025 if (state.trimmargins && trimw) {
1026 fz_page *page;
1028 fz_try (ctx) {
1029 page = fz_load_page (ctx, state.doc, pageno);
1030 fz_bound_page (ctx, page, &mediabox);
1031 if (state.trimmargins) {
1032 fz_rect rect;
1033 fz_device *dev;
1035 dev = fz_new_bbox_device (ctx, &rect);
1036 dev->hints |= FZ_IGNORE_SHADE;
1037 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1038 fz_close_device (ctx, dev);
1039 fz_drop_device (ctx, dev);
1041 rect.x0 += state.trimfuzz.x0;
1042 rect.x1 += state.trimfuzz.x1;
1043 rect.y0 += state.trimfuzz.y0;
1044 rect.y1 += state.trimfuzz.y1;
1045 fz_intersect_rect (&rect, &mediabox);
1047 if (!fz_is_empty_rect (&rect)) {
1048 mediabox = rect;
1051 fz_drop_page (ctx, page);
1052 if (!state.cxack) {
1053 printd ("progress %f loading %d",
1054 (double) (pageno + 1) / state.pagecount,
1055 pageno + 1);
1058 fz_catch (ctx) {
1060 if (trimf) {
1061 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1062 if (n - 1) {
1063 err (1, "fwrite trim mediabox");
1067 else {
1068 if (trimf) {
1069 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1070 if (n - 1) {
1071 err (1, "fread trim mediabox %d", pageno);
1074 else {
1075 fz_page *page;
1076 fz_try (ctx) {
1077 page = fz_load_page (ctx, state.doc, pageno);
1078 fz_bound_page (ctx, page, &mediabox);
1079 fz_drop_page (ctx, page);
1081 show = !state.trimmargins && pageno % 20 == 0;
1082 if (show) {
1083 printd ("progress %f Gathering dimensions %d",
1084 (double) (pageno) / state.pagecount,
1085 pageno);
1088 fz_catch (ctx) {
1089 fprintf (stderr, "failed to load page %d\n", pageno);
1095 if (state.pagedimcount == 0
1096 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1097 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1098 size_t size;
1100 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1101 state.pagedims = realloc (state.pagedims, size);
1102 if (!state.pagedims) {
1103 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1104 size, state.pagedimcount + 1);
1107 p = &state.pagedims[state.pagedimcount++];
1108 p->rotate = rotate;
1109 p->mediabox = mediabox;
1110 p->pageno = pageno;
1113 end = now ();
1114 if (!wthack) {
1115 printd ("progress 1 %s %d pages in %f seconds",
1116 state.trimmargins ? "Trimmed" : "Processed",
1117 state.pagecount, end - start);
1119 state.trimanew = 0;
1120 if (trimf) {
1121 if (fclose (trimf)) {
1122 err (1, "fclose");
1127 static void layout (void)
1129 int pindex;
1130 fz_rect box;
1131 fz_matrix ctm, rm;
1132 struct pagedim *p = p;
1133 double zw, w, maxw = 0.0, zoom = zoom;
1135 if (state.pagedimcount == 0) return;
1137 switch (state.fitmodel) {
1138 case FitProportional:
1139 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1140 double x0, x1;
1142 p = &state.pagedims[pindex];
1143 fz_rotate (&rm, p->rotate + state.rotate);
1144 box = p->mediabox;
1145 fz_transform_rect (&box, &rm);
1147 x0 = fz_min (box.x0, box.x1);
1148 x1 = fz_max (box.x0, box.x1);
1150 w = x1 - x0;
1151 maxw = fz_max (w, maxw);
1152 zoom = state.w / maxw;
1154 break;
1156 case FitPage:
1157 maxw = state.w;
1158 break;
1160 case FitWidth:
1161 break;
1163 default:
1164 ARSERT (0 && state.fitmodel);
1167 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1168 fz_rect rect;
1169 fz_matrix tm, sm;
1171 p = &state.pagedims[pindex];
1172 fz_rotate (&ctm, state.rotate);
1173 fz_rotate (&rm, p->rotate + state.rotate);
1174 box = p->mediabox;
1175 fz_transform_rect (&box, &rm);
1176 w = box.x1 - box.x0;
1177 switch (state.fitmodel) {
1178 case FitProportional:
1179 p->left = ((maxw - w) * zoom) / 2.0;
1180 break;
1181 case FitPage:
1183 double zh, h;
1184 zw = maxw / w;
1185 h = box.y1 - box.y0;
1186 zh = state.h / h;
1187 zoom = fz_min (zw, zh);
1188 p->left = (maxw - (w * zoom)) / 2.0;
1190 break;
1191 case FitWidth:
1192 p->left = 0;
1193 zoom = state.w / w;
1194 break;
1197 fz_scale (&p->zoomctm, zoom, zoom);
1198 fz_concat (&ctm, &p->zoomctm, &ctm);
1200 fz_rotate (&rm, p->rotate);
1201 p->pagebox = p->mediabox;
1202 fz_transform_rect (&p->pagebox, &rm);
1203 p->pagebox.x1 -= p->pagebox.x0;
1204 p->pagebox.y1 -= p->pagebox.y0;
1205 p->pagebox.x0 = 0;
1206 p->pagebox.y0 = 0;
1207 rect = p->pagebox;
1208 fz_transform_rect (&rect, &ctm);
1209 fz_round_rect (&p->bounds, &rect);
1210 p->ctm = ctm;
1212 fz_translate (&tm, 0, -p->mediabox.y1);
1213 fz_scale (&sm, zoom, -zoom);
1214 fz_concat (&ctm, &tm, &sm);
1216 p->tctmready = 0;
1219 do {
1220 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1221 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1222 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1223 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1224 int boundw = x1 - x0;
1225 int boundh = y1 - y0;
1227 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1228 } while (p-- != state.pagedims);
1231 struct pagedim *pdimofpageno (int pageno)
1233 int i;
1234 struct pagedim *pdim = state.pagedims;
1236 for (i = 0; i < state.pagedimcount; ++i) {
1237 if (state.pagedims[i].pageno > pageno)
1238 break;
1239 pdim = &state.pagedims[i];
1241 return pdim;
1244 static
1245 struct anchor { int n; int x; int y; int w; int h; }
1246 uritoanchor (const char *uri)
1248 fz_point p;
1249 struct anchor a;
1251 a.n = -1;
1252 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1253 if (a.n >= 0) {
1254 struct pagedim *pdim = pdimofpageno (a.n);
1255 fz_transform_point (&p, &pdim->ctm);
1256 a.x = p.x;
1257 a.y = p.y;
1258 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1260 return a;
1263 static void recurse_outline (fz_outline *outline, int level)
1265 while (outline) {
1266 struct anchor a = uritoanchor (outline->uri);
1267 if (a.n >= 0) {
1268 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1270 else {
1271 printd ("on %d %s", level, outline->title);
1273 if (outline->down) {
1274 recurse_outline (outline->down, level + 1);
1276 outline = outline->next;
1280 static void process_outline (void)
1282 fz_outline *outline;
1284 if (!state.needoutline || !state.pagedimcount) return;
1286 state.needoutline = 0;
1287 outline = fz_load_outline (state.ctx, state.doc);
1288 if (outline) {
1289 recurse_outline (outline, 0);
1290 fz_drop_outline (state.ctx, outline);
1294 static char *strofspan (fz_stext_span *span)
1296 char *p;
1297 char utf8[10];
1298 fz_stext_char *ch;
1299 size_t size = 0, cap = 80;
1301 p = malloc (cap + 1);
1302 if (!p) return NULL;
1304 for (ch = span->text; ch < span->text + span->len; ++ch) {
1305 int n = fz_runetochar (utf8, ch->c);
1306 if (size + n > cap) {
1307 cap *= 2;
1308 p = realloc (p, cap + 1);
1309 if (!p) return NULL;
1312 memcpy (p + size, utf8, n);
1313 size += n;
1315 p[size] = 0;
1316 return p;
1319 static int matchspan (regex_t *re, fz_stext_span *span,
1320 int stop, int pageno, double start)
1322 int ret;
1323 char *p;
1324 regmatch_t rm;
1325 int a, b, c;
1326 fz_rect sb, eb;
1327 fz_point p1, p2, p3, p4;
1329 p = strofspan (span);
1330 if (!p) return -1;
1332 ret = regexec (re, p, 1, &rm, 0);
1333 if (ret) {
1334 free (p);
1335 if (ret != REG_NOMATCH) {
1336 size_t size;
1337 char errbuf[80];
1338 size = regerror (ret, re, errbuf, sizeof (errbuf));
1339 printd ("msg regexec error `%.*s'",
1340 (int) size, errbuf);
1341 return -1;
1343 return 0;
1345 else {
1346 int l = span->len;
1348 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1349 c += fz_runelen (span->text[a].c);
1351 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1352 c += fz_runelen (span->text[b].c);
1355 if (fz_runelen (span->text[b].c) > 1) {
1356 b = fz_maxi (0, b-1);
1359 fz_stext_char_bbox (state.ctx, &sb, span, a);
1360 fz_stext_char_bbox (state.ctx, &eb, span, b);
1362 p1.x = sb.x0;
1363 p1.y = sb.y0;
1364 p2.x = eb.x1;
1365 p2.y = sb.y0;
1366 p3.x = eb.x1;
1367 p3.y = eb.y1;
1368 p4.x = sb.x0;
1369 p4.y = eb.y1;
1371 if (!stop) {
1372 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1373 pageno, 1,
1374 p1.x, p1.y,
1375 p2.x, p2.y,
1376 p3.x, p3.y,
1377 p4.x, p4.y);
1379 printd ("progress 1 found at %d `%.*s' in %f sec",
1380 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1381 now () - start);
1383 else {
1384 printd ("match %d %d %f %f %f %f %f %f %f %f",
1385 pageno, 2,
1386 p1.x, p1.y,
1387 p2.x, p2.y,
1388 p3.x, p3.y,
1389 p4.x, p4.y);
1391 free (p);
1392 return 1;
1396 static int compareblocks (const void *l, const void *r)
1398 fz_stext_block const *ls = l;
1399 fz_stext_block const *rs = r;
1400 return ls->bbox.y0 - rs->bbox.y0;
1403 /* wishful thinking function */
1404 static void search (regex_t *re, int pageno, int y, int forward)
1406 int j;
1407 fz_device *tdev;
1408 fz_stext_page *text;
1409 fz_stext_sheet *sheet;
1410 struct pagedim *pdim;
1411 int stop = 0, niters = 0;
1412 double start, end;
1413 fz_page *page;
1415 start = now ();
1416 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1417 if (niters++ == 5) {
1418 niters = 0;
1419 if (hasdata ()) {
1420 printd ("progress 1 attention requested aborting search at %d",
1421 pageno);
1422 stop = 1;
1424 else {
1425 printd ("progress %f searching in page %d",
1426 (double) (pageno + 1) / state.pagecount,
1427 pageno);
1430 pdim = pdimofpageno (pageno);
1431 sheet = fz_new_stext_sheet (state.ctx);
1432 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1433 tdev = fz_new_stext_device (state.ctx, sheet, text, 0);
1435 page = fz_load_page (state.ctx, state.doc, pageno);
1437 fz_matrix ctm = pagectm1 (page, pdim);
1438 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1441 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1442 fz_close_device (state.ctx, tdev);
1443 fz_drop_device (state.ctx, tdev);
1445 for (j = 0; j < text->len; ++j) {
1446 int k;
1447 fz_page_block *pb;
1448 fz_stext_block *block;
1450 pb = &text->blocks[forward ? j : text->len - 1 - j];
1451 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1452 block = pb->u.text;
1454 for (k = 0; k < block->len; ++k) {
1455 fz_stext_line *line;
1456 fz_stext_span *span;
1458 if (forward) {
1459 line = &block->lines[k];
1460 if (line->bbox.y0 < y + 1) continue;
1462 else {
1463 line = &block->lines[block->len - 1 - k];
1464 if (line->bbox.y0 > y - 1) continue;
1467 for (span = line->first_span; span; span = span->next) {
1468 switch (matchspan (re, span, stop, pageno, start)) {
1469 case 0: break;
1470 case 1: stop = 1; break;
1471 case -1: stop = 1; goto endloop;
1476 if (forward) {
1477 pageno += 1;
1478 y = 0;
1480 else {
1481 pageno -= 1;
1482 y = INT_MAX;
1484 endloop:
1485 fz_drop_stext_page (state.ctx, text);
1486 fz_drop_stext_sheet (state.ctx, sheet);
1487 fz_drop_page (state.ctx, page);
1489 end = now ();
1490 if (!stop) {
1491 printd ("progress 1 no matches %f sec", end - start);
1493 printd ("clearrects");
1496 static void set_tex_params (int colorspace)
1498 union {
1499 unsigned char b;
1500 unsigned int s;
1501 } endianness = {1};
1503 switch (colorspace) {
1504 case 0:
1505 state.texiform = GL_RGBA8;
1506 state.texform = GL_RGBA;
1507 state.texty = GL_UNSIGNED_BYTE;
1508 state.colorspace = fz_device_rgb (state.ctx);
1509 break;
1510 case 1:
1511 state.texiform = GL_RGBA8;
1512 state.texform = GL_BGRA;
1513 state.texty = endianness.s > 1
1514 ? GL_UNSIGNED_INT_8_8_8_8
1515 : GL_UNSIGNED_INT_8_8_8_8_REV;
1516 state.colorspace = fz_device_bgr (state.ctx);
1517 break;
1518 case 2:
1519 state.texiform = GL_LUMINANCE_ALPHA;
1520 state.texform = GL_LUMINANCE_ALPHA;
1521 state.texty = GL_UNSIGNED_BYTE;
1522 state.colorspace = fz_device_gray (state.ctx);
1523 break;
1524 default:
1525 errx (1, "invalid colorspce %d", colorspace);
1529 static void realloctexts (int texcount)
1531 size_t size;
1533 if (texcount == state.texcount) return;
1535 if (texcount < state.texcount) {
1536 glDeleteTextures (state.texcount - texcount,
1537 state.texids + texcount);
1540 size = texcount * sizeof (*state.texids);
1541 state.texids = realloc (state.texids, size);
1542 if (!state.texids) {
1543 err (1, "realloc texids %" FMT_s, size);
1546 size = texcount * sizeof (*state.texowners);
1547 state.texowners = realloc (state.texowners, size);
1548 if (!state.texowners) {
1549 err (1, "realloc texowners %" FMT_s, size);
1551 if (texcount > state.texcount) {
1552 int i;
1554 glGenTextures (texcount - state.texcount,
1555 state.texids + state.texcount);
1556 for (i = state.texcount; i < texcount; ++i) {
1557 state.texowners[i].w = -1;
1558 state.texowners[i].slice = NULL;
1561 state.texcount = texcount;
1562 state.texindex = 0;
1565 static char *mbtoutf8 (char *s)
1567 char *p, *r;
1568 wchar_t *tmp;
1569 size_t i, ret, len;
1571 len = mbstowcs (NULL, s, strlen (s));
1572 if (len == 0) {
1573 return s;
1575 else {
1576 if (len == (size_t) -1) {
1577 return s;
1581 tmp = malloc (len * sizeof (wchar_t));
1582 if (!tmp) {
1583 return s;
1586 ret = mbstowcs (tmp, s, len);
1587 if (ret == (size_t) -1) {
1588 free (tmp);
1589 return s;
1592 len = 0;
1593 for (i = 0; i < ret; ++i) {
1594 len += fz_runelen (tmp[i]);
1597 p = r = malloc (len + 1);
1598 if (!r) {
1599 free (tmp);
1600 return s;
1603 for (i = 0; i < ret; ++i) {
1604 p += fz_runetochar (p, tmp[i]);
1606 *p = 0;
1607 free (tmp);
1608 return r;
1611 CAMLprim value ml_mbtoutf8 (value s_v)
1613 CAMLparam1 (s_v);
1614 CAMLlocal1 (ret_v);
1615 char *s, *r;
1617 s = String_val (s_v);
1618 r = mbtoutf8 (s);
1619 if (r == s) {
1620 ret_v = s_v;
1622 else {
1623 ret_v = caml_copy_string (r);
1624 free (r);
1626 CAMLreturn (ret_v);
1629 static void * mainloop (void UNUSED_ATTR *unused)
1631 char *p = NULL;
1632 int len, ret, oldlen = 0;
1634 fz_var (p);
1635 fz_var (oldlen);
1636 for (;;) {
1637 len = readlen (state.csock);
1638 if (len == 0) {
1639 errx (1, "readlen returned 0");
1642 if (oldlen < len + 1) {
1643 p = realloc (p, len + 1);
1644 if (!p) {
1645 err (1, "realloc %d failed", len + 1);
1647 oldlen = len + 1;
1649 readdata (state.csock, p, len);
1650 p[len] = 0;
1652 if (!strncmp ("open", p, 4)) {
1653 int wthack, off, ok = 0;
1654 char *password;
1655 char *filename;
1656 char *utf8filename;
1657 size_t filenamelen;
1659 fz_var (ok);
1660 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1661 if (ret != 2) {
1662 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1665 filename = p + 5 + off;
1666 filenamelen = strlen (filename);
1667 password = filename + filenamelen + 1;
1669 if (password[strlen (password) + 1]) {
1670 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1673 lock ("open");
1674 fz_try (state.ctx) {
1675 ok = openxref (filename, password);
1677 fz_catch (state.ctx) {
1678 utf8filename = mbtoutf8 (filename);
1679 printd ("msg Could not open %s", utf8filename);
1681 if (ok) {
1682 pdfinfo ();
1683 initpdims (wthack);
1685 unlock ("open");
1687 if (ok) {
1688 if (!wthack) {
1689 utf8filename = mbtoutf8 (filename);
1690 printd ("msg Opened %s (press h/F1 to get help)",
1691 utf8filename);
1692 if (utf8filename != filename) {
1693 free (utf8filename);
1696 state.needoutline = 1;
1699 else if (!strncmp ("cs", p, 2)) {
1700 int i, colorspace;
1702 ret = sscanf (p + 2, " %d", &colorspace);
1703 if (ret != 1) {
1704 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1706 lock ("cs");
1707 set_tex_params (colorspace);
1708 for (i = 0; i < state.texcount; ++i) {
1709 state.texowners[i].w = -1;
1710 state.texowners[i].slice = NULL;
1712 unlock ("cs");
1714 else if (!strncmp ("freepage", p, 8)) {
1715 void *ptr;
1717 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1718 if (ret != 1) {
1719 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1721 freepage (ptr);
1723 else if (!strncmp ("freetile", p, 8)) {
1724 void *ptr;
1726 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1727 if (ret != 1) {
1728 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1730 freetile (ptr);
1732 else if (!strncmp ("search", p, 6)) {
1733 int icase, pageno, y, len2, forward;
1734 char *pattern;
1735 regex_t re;
1737 ret = sscanf (p + 6, " %d %d %d %d,%n",
1738 &icase, &pageno, &y, &forward, &len2);
1739 if (ret != 4) {
1740 errx (1, "malformed search `%s' ret=%d", p, ret);
1743 pattern = p + 6 + len2;
1744 ret = regcomp (&re, pattern,
1745 REG_EXTENDED | (icase ? REG_ICASE : 0));
1746 if (ret) {
1747 char errbuf[80];
1748 size_t size;
1750 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1751 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1753 else {
1754 search (&re, pageno, y, forward);
1755 regfree (&re);
1758 else if (!strncmp ("geometry", p, 8)) {
1759 int w, h, fitmodel;
1761 printd ("clear");
1762 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1763 if (ret != 3) {
1764 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1767 lock ("geometry");
1768 state.h = h;
1769 if (w != state.w) {
1770 int i;
1771 state.w = w;
1772 for (i = 0; i < state.texcount; ++i) {
1773 state.texowners[i].slice = NULL;
1776 state.fitmodel = fitmodel;
1777 layout ();
1778 process_outline ();
1780 state.gen++;
1781 unlock ("geometry");
1782 printd ("continue %d", state.pagecount);
1784 else if (!strncmp ("reqlayout", p, 9)) {
1785 char *nameddest;
1786 int rotate, off, h;
1787 unsigned int fitmodel;
1788 pdf_document *pdf;
1790 printd ("clear");
1791 ret = sscanf (p + 9, " %d %u %d %n",
1792 &rotate, &fitmodel, &h, &off);
1793 if (ret != 3) {
1794 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1796 lock ("reqlayout");
1797 pdf = pdf_specifics (state.ctx, state.doc);
1798 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1799 state.gen += 1;
1801 state.rotate = rotate;
1802 state.fitmodel = fitmodel;
1803 state.h = h;
1804 layout ();
1805 process_outline ();
1807 nameddest = p + 9 + off;
1808 if (pdf && nameddest && *nameddest) {
1809 fz_point xy;
1810 struct pagedim *pdim;
1811 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1812 &xy.x, &xy.y);
1813 pdim = pdimofpageno (pageno);
1814 fz_transform_point (&xy, &pdim->ctm);
1815 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1818 state.gen++;
1819 unlock ("reqlayout");
1820 printd ("continue %d", state.pagecount);
1822 else if (!strncmp ("page", p, 4)) {
1823 double a, b;
1824 struct page *page;
1825 int pageno, pindex;
1827 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1828 if (ret != 2) {
1829 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1832 lock ("page");
1833 a = now ();
1834 page = loadpage (pageno, pindex);
1835 b = now ();
1836 unlock ("page");
1838 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1840 else if (!strncmp ("tile", p, 4)) {
1841 int x, y, w, h;
1842 struct page *page;
1843 struct tile *tile;
1844 double a, b;
1845 void *data;
1847 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1848 SCN_ptr_cast (&page), &x, &y, &w, &h,
1849 SCN_ptr_cast (&data));
1850 if (ret != 6) {
1851 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1854 lock ("tile");
1855 a = now ();
1856 tile = rendertile (page, x, y, w, h, data);
1857 b = now ();
1858 unlock ("tile");
1860 printd ("tile %d %d %" FMT_ptr " %u %f",
1861 x, y,
1862 FMT_ptr_cast (tile),
1863 tile->w * tile->h * tile->pixmap->n,
1864 b - a);
1866 else if (!strncmp ("trimset", p, 7)) {
1867 fz_irect fuzz;
1868 int trimmargins;
1870 ret = sscanf (p + 7, " %d %d %d %d %d",
1871 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1872 if (ret != 5) {
1873 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1875 lock ("trimset");
1876 state.trimmargins = trimmargins;
1877 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1878 state.trimanew = 1;
1879 state.trimfuzz = fuzz;
1881 unlock ("trimset");
1883 else if (!strncmp ("settrim", p, 7)) {
1884 fz_irect fuzz;
1885 int trimmargins;
1887 ret = sscanf (p + 7, " %d %d %d %d %d",
1888 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1889 if (ret != 5) {
1890 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1892 printd ("clear");
1893 lock ("settrim");
1894 state.trimmargins = trimmargins;
1895 state.needoutline = 1;
1896 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1897 state.trimanew = 1;
1898 state.trimfuzz = fuzz;
1900 state.pagedimcount = 0;
1901 free (state.pagedims);
1902 state.pagedims = NULL;
1903 initpdims (0);
1904 layout ();
1905 process_outline ();
1906 unlock ("settrim");
1907 printd ("continue %d", state.pagecount);
1909 else if (!strncmp ("sliceh", p, 6)) {
1910 int h;
1912 ret = sscanf (p + 6, " %d", &h);
1913 if (ret != 1) {
1914 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1916 if (h != state.sliceheight) {
1917 int i;
1919 state.sliceheight = h;
1920 for (i = 0; i < state.texcount; ++i) {
1921 state.texowners[i].w = -1;
1922 state.texowners[i].h = -1;
1923 state.texowners[i].slice = NULL;
1927 else if (!strncmp ("interrupt", p, 9)) {
1928 printd ("vmsg interrupted");
1930 else {
1931 errx (1, "unknown command %.*s", len, p);
1934 return 0;
1937 CAMLprim value ml_isexternallink (value uri_v)
1939 CAMLparam1 (uri_v);
1940 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1941 CAMLreturn (Val_bool (ext));
1944 CAMLprim value ml_uritolocation (value uri_v)
1946 CAMLparam1 (uri_v);
1947 CAMLlocal1 (ret_v);
1948 int pageno;
1949 fz_point xy;
1950 struct pagedim *pdim;
1952 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1953 &xy.x, &xy.y);
1954 pdim = pdimofpageno (pageno);
1955 fz_transform_point (&xy, &pdim->ctm);
1956 ret_v = caml_alloc_tuple (3);
1957 Field (ret_v, 0) = Val_int (pageno);
1958 Field (ret_v, 1) = caml_copy_double (xy.x);
1959 Field (ret_v, 2) = caml_copy_double (xy.y);
1960 CAMLreturn (ret_v);
1963 CAMLprim value ml_realloctexts (value texcount_v)
1965 CAMLparam1 (texcount_v);
1966 int ok;
1968 if (trylock (__func__)) {
1969 ok = 0;
1970 goto done;
1972 realloctexts (Int_val (texcount_v));
1973 ok = 1;
1974 unlock (__func__);
1976 done:
1977 CAMLreturn (Val_bool (ok));
1980 static void recti (int x0, int y0, int x1, int y1)
1982 GLfloat *v = state.vertices;
1984 glVertexPointer (2, GL_FLOAT, 0, v);
1985 v[0] = x0; v[1] = y0;
1986 v[2] = x1; v[3] = y0;
1987 v[4] = x0; v[5] = y1;
1988 v[6] = x1; v[7] = y1;
1989 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1992 static void showsel (struct page *page, int ox, int oy)
1994 int seen = 0;
1995 fz_irect bbox;
1996 fz_rect rect;
1997 fz_stext_line *line;
1998 fz_page_block *pageb;
1999 fz_stext_block *block;
2000 struct mark first, last;
2001 unsigned char selcolor[] = {15,15,15,140};
2003 first = page->fmark;
2004 last = page->lmark;
2006 if (!first.span || !last.span) return;
2008 glEnable (GL_BLEND);
2009 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2010 glColor4ubv (selcolor);
2012 ox += state.pagedims[page->pdimno].bounds.x0;
2013 oy += state.pagedims[page->pdimno].bounds.y0;
2014 for (pageb = page->text->blocks;
2015 pageb < page->text->blocks + page->text->len;
2016 ++pageb) {
2017 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2018 block = pageb->u.text;
2020 for (line = block->lines;
2021 line < block->lines + block->len;
2022 ++line) {
2023 fz_stext_span *span;
2024 rect = fz_empty_rect;
2026 for (span = line->first_span; span; span = span->next) {
2027 int i, j, k;
2028 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2030 j = 0;
2031 k = span->len - 1;
2033 if (span == page->fmark.span && span == page->lmark.span) {
2034 seen = 1;
2035 j = fz_mini (first.i, last.i);
2036 k = fz_maxi (first.i, last.i);
2038 else {
2039 if (span == first.span) {
2040 seen = 1;
2041 j = first.i;
2043 else if (span == last.span) {
2044 seen = 1;
2045 k = last.i;
2049 if (seen) {
2050 for (i = j; i <= k; ++i) {
2051 fz_rect bbox1;
2052 fz_union_rect (&rect,
2053 fz_stext_char_bbox (state.ctx, &bbox1,
2054 span, i));
2056 fz_round_rect (&bbox, &rect);
2057 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2058 bbox.x0,
2059 bbox.y0,
2060 bbox.x1,
2061 bbox.y1,
2062 oy, ox);
2064 recti (bbox.x0 + ox, bbox.y0 + oy,
2065 bbox.x1 + ox, bbox.y1 + oy);
2066 if (span == last.span) {
2067 goto done;
2069 rect = fz_empty_rect;
2074 done:
2075 glDisable (GL_BLEND);
2078 #include "glfont.c"
2080 static void stipplerect (fz_matrix *m,
2081 fz_point *p1,
2082 fz_point *p2,
2083 fz_point *p3,
2084 fz_point *p4,
2085 GLfloat *texcoords,
2086 GLfloat *vertices)
2088 fz_transform_point (p1, m);
2089 fz_transform_point (p2, m);
2090 fz_transform_point (p3, m);
2091 fz_transform_point (p4, m);
2093 float w, h, s, t;
2095 w = p2->x - p1->x;
2096 h = p2->y - p1->y;
2097 t = hypotf (w, h) * .25f;
2099 w = p3->x - p2->x;
2100 h = p3->y - p2->y;
2101 s = hypotf (w, h) * .25f;
2103 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2104 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2106 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2107 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2109 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2110 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2112 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2113 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2115 glDrawArrays (GL_LINES, 0, 8);
2118 static void solidrect (fz_matrix *m,
2119 fz_point *p1,
2120 fz_point *p2,
2121 fz_point *p3,
2122 fz_point *p4,
2123 GLfloat *vertices)
2125 fz_transform_point (p1, m);
2126 fz_transform_point (p2, m);
2127 fz_transform_point (p3, m);
2128 fz_transform_point (p4, m);
2129 vertices[0] = p1->x; vertices[1] = p1->y;
2130 vertices[2] = p2->x; vertices[3] = p2->y;
2132 vertices[4] = p3->x; vertices[5] = p3->y;
2133 vertices[6] = p4->x; vertices[7] = p4->y;
2134 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2137 static void highlightlinks (struct page *page, int xoff, int yoff)
2139 int i;
2140 fz_matrix ctm, tm, pm;
2141 fz_link *link, *links;
2142 GLfloat *texcoords = state.texcoords;
2143 GLfloat *vertices = state.vertices;
2145 links = fz_load_links (state.ctx, page->fzpage);
2147 glEnable (GL_TEXTURE_1D);
2148 glEnable (GL_BLEND);
2149 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2150 glBindTexture (GL_TEXTURE_1D, state.stid);
2152 xoff -= state.pagedims[page->pdimno].bounds.x0;
2153 yoff -= state.pagedims[page->pdimno].bounds.y0;
2154 fz_translate (&tm, xoff, yoff);
2155 pm = pagectm (page);
2156 fz_concat (&ctm, &pm, &tm);
2158 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2159 glVertexPointer (2, GL_FLOAT, 0, vertices);
2161 for (link = links; link; link = link->next) {
2162 fz_point p1, p2, p3, p4;
2164 p1.x = link->rect.x0;
2165 p1.y = link->rect.y0;
2167 p2.x = link->rect.x1;
2168 p2.y = link->rect.y0;
2170 p3.x = link->rect.x1;
2171 p3.y = link->rect.y1;
2173 p4.x = link->rect.x0;
2174 p4.y = link->rect.y1;
2176 /* TODO: different colours for different schemes */
2177 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2178 else glColor3ub (255, 0, 0);
2180 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2183 for (i = 0; i < page->annotcount; ++i) {
2184 fz_point p1, p2, p3, p4;
2185 struct annot *annot = &page->annots[i];
2187 p1.x = annot->bbox.x0;
2188 p1.y = annot->bbox.y0;
2190 p2.x = annot->bbox.x1;
2191 p2.y = annot->bbox.y0;
2193 p3.x = annot->bbox.x1;
2194 p3.y = annot->bbox.y1;
2196 p4.x = annot->bbox.x0;
2197 p4.y = annot->bbox.y1;
2199 glColor3ub (0, 0, 128);
2200 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2203 glDisable (GL_BLEND);
2204 glDisable (GL_TEXTURE_1D);
2207 static int compareslinks (const void *l, const void *r)
2209 struct slink const *ls = l;
2210 struct slink const *rs = r;
2211 if (ls->bbox.y0 == rs->bbox.y0) {
2212 return rs->bbox.x0 - rs->bbox.x0;
2214 return ls->bbox.y0 - rs->bbox.y0;
2217 static void droptext (struct page *page)
2219 if (page->text) {
2220 fz_drop_stext_page (state.ctx, page->text);
2221 page->fmark.i = -1;
2222 page->lmark.i = -1;
2223 page->fmark.span = NULL;
2224 page->lmark.span = NULL;
2225 page->text = NULL;
2227 if (page->sheet) {
2228 fz_drop_stext_sheet (state.ctx, page->sheet);
2229 page->sheet = NULL;
2233 static void dropannots (struct page *page)
2235 if (page->annots) {
2236 free (page->annots);
2237 page->annots = NULL;
2238 page->annotcount = 0;
2242 static void ensureannots (struct page *page)
2244 int i, count = 0;
2245 size_t annotsize = sizeof (*page->annots);
2246 fz_annot *annot;
2248 if (state.gen != page->agen) {
2249 dropannots (page);
2250 page->agen = state.gen;
2252 if (page->annots) return;
2254 for (annot = fz_first_annot (state.ctx, page->fzpage);
2255 annot;
2256 annot = fz_next_annot (state.ctx, annot)) {
2257 count++;
2260 if (count > 0) {
2261 page->annotcount = count;
2262 page->annots = calloc (count, annotsize);
2263 if (!page->annots) {
2264 err (1, "calloc annots %d", count);
2267 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2268 annot;
2269 annot = fz_next_annot (state.ctx, annot), i++) {
2270 fz_rect rect;
2272 fz_bound_annot (state.ctx, annot, &rect);
2273 page->annots[i].annot = annot;
2274 fz_round_rect (&page->annots[i].bbox, &rect);
2279 static void dropslinks (struct page *page)
2281 if (page->slinks) {
2282 free (page->slinks);
2283 page->slinks = NULL;
2284 page->slinkcount = 0;
2288 static void ensureslinks (struct page *page)
2290 fz_matrix ctm;
2291 int i, count;
2292 size_t slinksize = sizeof (*page->slinks);
2293 fz_link *link, *links;
2295 ensureannots (page);
2296 if (state.gen != page->sgen) {
2297 dropslinks (page);
2298 page->sgen = state.gen;
2300 if (page->slinks) return;
2302 links = fz_load_links (state.ctx, page->fzpage);
2303 ctm = pagectm (page);
2305 count = page->annotcount;
2306 for (link = links; link; link = link->next) {
2307 count++;
2309 if (count > 0) {
2310 int j;
2312 page->slinkcount = count;
2313 page->slinks = calloc (count, slinksize);
2314 if (!page->slinks) {
2315 err (1, "calloc slinks %d", count);
2318 for (i = 0, link = links; link; ++i, link = link->next) {
2319 fz_rect rect;
2321 rect = link->rect;
2322 fz_transform_rect (&rect, &ctm);
2323 page->slinks[i].tag = SLINK;
2324 page->slinks[i].u.link = link;
2325 fz_round_rect (&page->slinks[i].bbox, &rect);
2327 for (j = 0; j < page->annotcount; ++j, ++i) {
2328 fz_rect rect;
2329 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2330 fz_transform_rect (&rect, &ctm);
2331 fz_round_rect (&page->slinks[i].bbox, &rect);
2333 page->slinks[i].tag = SANNOT;
2334 page->slinks[i].u.annot = page->annots[j].annot;
2336 qsort (page->slinks, count, slinksize, compareslinks);
2340 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2341 static void fmt_linkn (char *s, unsigned int u)
2343 unsigned int len; unsigned int q;
2344 unsigned int zma = 'z' - 'a' + 1;
2345 len = 1; q = u;
2346 while (q > zma - 1) { ++len; q /= zma; }
2347 if (s) {
2348 s += len;
2349 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2350 /* handles u == 0 */
2352 s[len] = 0;
2355 static void highlightslinks (struct page *page, int xoff, int yoff,
2356 int noff, char *targ, int tlen, int hfsize)
2358 int i;
2359 char buf[40];
2360 struct slink *slink;
2361 double x0, y0, x1, y1, w;
2363 ensureslinks (page);
2364 glColor3ub (0xc3, 0xb0, 0x91);
2365 for (i = 0; i < page->slinkcount; ++i) {
2366 fmt_linkn (buf, i + noff);
2367 if (!tlen || !strncmp (targ, buf, tlen)) {
2368 slink = &page->slinks[i];
2370 x0 = slink->bbox.x0 + xoff - 5;
2371 y1 = slink->bbox.y0 + yoff - 5;
2372 y0 = y1 + 10 + hfsize;
2373 w = measure_string (state.face, hfsize, buf);
2374 x1 = x0 + w + 10;
2375 recti (x0, y0, x1, y1);
2379 glEnable (GL_BLEND);
2380 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2381 glEnable (GL_TEXTURE_2D);
2382 glColor3ub (0, 0, 0);
2383 for (i = 0; i < page->slinkcount; ++i) {
2384 fmt_linkn (buf, i + noff);
2385 if (!tlen || !strncmp (targ, buf, tlen)) {
2386 slink = &page->slinks[i];
2388 x0 = slink->bbox.x0 + xoff;
2389 y0 = slink->bbox.y0 + yoff + hfsize;
2390 draw_string (state.face, hfsize, x0, y0, buf);
2393 glDisable (GL_TEXTURE_2D);
2394 glDisable (GL_BLEND);
2397 static void uploadslice (struct tile *tile, struct slice *slice)
2399 int offset;
2400 struct slice *slice1;
2401 unsigned char *texdata;
2403 offset = 0;
2404 for (slice1 = tile->slices; slice != slice1; slice1++) {
2405 offset += slice1->h * tile->w * tile->pixmap->n;
2407 if (slice->texindex != -1 && slice->texindex < state.texcount
2408 && state.texowners[slice->texindex].slice == slice) {
2409 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2411 else {
2412 int subimage = 0;
2413 int texindex = state.texindex++ % state.texcount;
2415 if (state.texowners[texindex].w == tile->w) {
2416 if (state.texowners[texindex].h >= slice->h) {
2417 subimage = 1;
2419 else {
2420 state.texowners[texindex].h = slice->h;
2423 else {
2424 state.texowners[texindex].h = slice->h;
2427 state.texowners[texindex].w = tile->w;
2428 state.texowners[texindex].slice = slice;
2429 slice->texindex = texindex;
2431 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2432 #if TEXT_TYPE == GL_TEXTURE_2D
2433 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2434 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2435 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2436 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2437 #endif
2438 if (tile->pbo) {
2439 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2440 texdata = 0;
2442 else {
2443 texdata = tile->pixmap->samples;
2445 if (subimage) {
2446 glTexSubImage2D (TEXT_TYPE,
2450 tile->w,
2451 slice->h,
2452 state.texform,
2453 state.texty,
2454 texdata+offset
2457 else {
2458 glTexImage2D (TEXT_TYPE,
2460 state.texiform,
2461 tile->w,
2462 slice->h,
2464 state.texform,
2465 state.texty,
2466 texdata+offset
2469 if (tile->pbo) {
2470 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2475 CAMLprim value ml_begintiles (value unit_v)
2477 CAMLparam1 (unit_v);
2478 glEnable (TEXT_TYPE);
2479 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2480 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2481 CAMLreturn (unit_v);
2484 CAMLprim value ml_endtiles (value unit_v)
2486 CAMLparam1 (unit_v);
2487 glDisable (TEXT_TYPE);
2488 CAMLreturn (unit_v);
2491 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2493 CAMLparam2 (args_v, ptr_v);
2494 int dispx = Int_val (Field (args_v, 0));
2495 int dispy = Int_val (Field (args_v, 1));
2496 int dispw = Int_val (Field (args_v, 2));
2497 int disph = Int_val (Field (args_v, 3));
2498 int tilex = Int_val (Field (args_v, 4));
2499 int tiley = Int_val (Field (args_v, 5));
2500 char *s = String_val (ptr_v);
2501 struct tile *tile = parse_pointer (__func__, s);
2502 int slicey, firstslice;
2503 struct slice *slice;
2504 GLfloat *texcoords = state.texcoords;
2505 GLfloat *vertices = state.vertices;
2507 firstslice = tiley / tile->sliceheight;
2508 slice = &tile->slices[firstslice];
2509 slicey = tiley % tile->sliceheight;
2511 while (disph > 0) {
2512 int dh;
2514 dh = slice->h - slicey;
2515 dh = fz_mini (disph, dh);
2516 uploadslice (tile, slice);
2518 texcoords[0] = tilex; texcoords[1] = slicey;
2519 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2520 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2521 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2523 vertices[0] = dispx; vertices[1] = dispy;
2524 vertices[2] = dispx+dispw; vertices[3] = dispy;
2525 vertices[4] = dispx; vertices[5] = dispy+dh;
2526 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2528 #if TEXT_TYPE == GL_TEXTURE_2D
2529 for (int i = 0; i < 8; ++i) {
2530 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2532 #endif
2534 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2535 dispy += dh;
2536 disph -= dh;
2537 slice++;
2538 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2539 slicey = 0;
2541 CAMLreturn0;
2544 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2546 fz_matrix ctm, tm, pm;
2547 fz_point p1, p2, p3, p4;
2548 GLfloat *vertices = state.vertices;
2549 double *v = (double *) rects_v;
2551 xoff -= state.pagedims[page->pdimno].bounds.x0;
2552 yoff -= state.pagedims[page->pdimno].bounds.y0;
2553 fz_translate (&tm, xoff, yoff);
2554 pm = pagectm (page);
2555 fz_concat (&ctm, &pm, &tm);
2557 glEnable (GL_BLEND);
2558 glVertexPointer (2, GL_FLOAT, 0, vertices);
2560 glColor4dv (v);
2561 p1.x = v[4];
2562 p1.y = v[5];
2564 p2.x = v[6];
2565 p2.y = v[5];
2567 p3.x = v[6];
2568 p3.y = v[7];
2570 p4.x = v[4];
2571 p4.y = v[7];
2572 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2573 glDisable (GL_BLEND);
2576 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2577 value xoff_v, value yoff_v,
2578 value li_v)
2580 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2581 int xoff = Int_val (xoff_v);
2582 int yoff = Int_val (yoff_v);
2583 int noff = Int_val (Field (li_v, 0));
2584 char *targ = String_val (Field (li_v, 1));
2585 int tlen = caml_string_length (Field (li_v, 1));
2586 int hfsize = Int_val (Field (li_v, 2));
2587 char *s = String_val (ptr_v);
2588 int hlmask = Int_val (hlinks_v);
2589 struct page *page = parse_pointer (__func__, s);
2591 if (!page->fzpage) {
2592 /* deal with loadpage failed pages */
2593 goto done;
2596 if (trylock (__func__)) {
2597 noff = -1;
2598 goto done;
2601 ensureannots (page);
2602 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2603 if (hlmask & 2) {
2604 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2605 noff = page->slinkcount;
2607 if (page->tgen == state.gen) {
2608 showsel (page, xoff, yoff);
2610 unlock (__func__);
2612 done:
2613 CAMLreturn (Val_int (noff));
2616 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2617 value rects_v)
2619 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2620 int xoff = Int_val (xoff_v);
2621 int yoff = Int_val (yoff_v);
2622 char *s = String_val (ptr_v);
2623 struct page *page = parse_pointer (__func__, s);
2625 drawprect (page, xoff, yoff, rects_v);
2626 CAMLreturn0;
2629 static struct annot *getannot (struct page *page, int x, int y)
2631 int i;
2632 fz_point p;
2633 fz_matrix ctm;
2634 const fz_matrix *tctm;
2635 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2637 if (!page->annots) return NULL;
2639 if (pdf) {
2640 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2641 tctm = &state.pagedims[page->pdimno].tctm;
2643 else {
2644 tctm = &fz_identity;
2647 p.x = x;
2648 p.y = y;
2650 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2651 fz_invert_matrix (&ctm, &ctm);
2652 fz_transform_point (&p, &ctm);
2654 if (pdf) {
2655 for (i = 0; i < page->annotcount; ++i) {
2656 struct annot *a = &page->annots[i];
2657 fz_rect rect;
2659 fz_bound_annot (state.ctx, a->annot, &rect);
2660 if (p.x >= rect.x0 && p.x <= rect.x1) {
2661 if (p.y >= rect.y0 && p.y <= rect.y1)
2662 return a;
2666 return NULL;
2669 static fz_link *getlink (struct page *page, int x, int y)
2671 fz_point p;
2672 fz_matrix ctm;
2673 fz_link *link, *links;
2675 links = fz_load_links (state.ctx, page->fzpage);
2677 p.x = x;
2678 p.y = y;
2680 ctm = pagectm (page);
2681 fz_invert_matrix (&ctm, &ctm);
2682 fz_transform_point (&p, &ctm);
2684 for (link = links; link; link = link->next) {
2685 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2686 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2687 return link;
2691 return NULL;
2694 static void ensuretext (struct page *page)
2696 if (state.gen != page->tgen) {
2697 droptext (page);
2698 page->tgen = state.gen;
2700 if (!page->text) {
2701 fz_matrix ctm;
2702 fz_device *tdev;
2704 page->text = fz_new_stext_page (state.ctx,
2705 &state.pagedims[page->pdimno].mediabox);
2706 page->sheet = fz_new_stext_sheet (state.ctx);
2707 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2708 ctm = pagectm (page);
2709 fz_run_display_list (state.ctx, page->dlist,
2710 tdev, &ctm, &fz_infinite_rect, NULL);
2711 qsort (page->text->blocks, page->text->len,
2712 sizeof (*page->text->blocks), compareblocks);
2713 fz_close_device (state.ctx, tdev);
2714 fz_drop_device (state.ctx, tdev);
2718 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2720 CAMLparam2 (start_page_v, dir_v);
2721 CAMLlocal1 (ret_v);
2722 int i, dir = Int_val (dir_v);
2723 int start_page = Int_val (start_page_v);
2724 int end_page = dir > 0 ? state.pagecount : -1;
2725 pdf_document *pdf;
2727 fz_var (end_page);
2728 ret_v = Val_int (0);
2729 lock (__func__);
2730 pdf = pdf_specifics (state.ctx, state.doc);
2731 for (i = start_page + dir; i != end_page; i += dir) {
2732 int found;
2734 fz_var (found);
2735 if (pdf) {
2736 pdf_page *page = NULL;
2738 fz_var (page);
2739 fz_try (state.ctx) {
2740 page = pdf_load_page (state.ctx, pdf, i);
2741 found = !!page->links || !!page->annots;
2743 fz_catch (state.ctx) {
2744 found = 0;
2746 if (page) {
2747 fz_drop_page (state.ctx, &page->super);
2750 else {
2751 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2752 found = !!fz_load_links (state.ctx, page);
2753 fz_drop_page (state.ctx, page);
2756 if (found) {
2757 ret_v = caml_alloc_small (1, 1);
2758 Field (ret_v, 0) = Val_int (i);
2759 goto unlock;
2762 unlock:
2763 unlock (__func__);
2764 CAMLreturn (ret_v);
2767 enum { dir_first, dir_last };
2768 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2770 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2772 CAMLparam2 (ptr_v, dir_v);
2773 CAMLlocal2 (ret_v, pos_v);
2774 struct page *page;
2775 int dirtag, i, slinkindex;
2776 struct slink *found = NULL ,*slink;
2777 char *s = String_val (ptr_v);
2779 page = parse_pointer (__func__, s);
2780 ret_v = Val_int (0);
2781 lock (__func__);
2782 ensureslinks (page);
2784 if (Is_block (dir_v)) {
2785 dirtag = Tag_val (dir_v);
2786 switch (dirtag) {
2787 case dir_first_visible:
2789 int x0, y0, dir, first_index, last_index;
2791 pos_v = Field (dir_v, 0);
2792 x0 = Int_val (Field (pos_v, 0));
2793 y0 = Int_val (Field (pos_v, 1));
2794 dir = Int_val (Field (pos_v, 2));
2796 if (dir >= 0) {
2797 dir = 1;
2798 first_index = 0;
2799 last_index = page->slinkcount;
2801 else {
2802 first_index = page->slinkcount - 1;
2803 last_index = -1;
2806 for (i = first_index; i != last_index; i += dir) {
2807 slink = &page->slinks[i];
2808 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2809 found = slink;
2810 break;
2814 break;
2816 case dir_left:
2817 slinkindex = Int_val (Field (dir_v, 0));
2818 found = &page->slinks[slinkindex];
2819 for (i = slinkindex - 1; i >= 0; --i) {
2820 slink = &page->slinks[i];
2821 if (slink->bbox.x0 < found->bbox.x0) {
2822 found = slink;
2823 break;
2826 break;
2828 case dir_right:
2829 slinkindex = Int_val (Field (dir_v, 0));
2830 found = &page->slinks[slinkindex];
2831 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2832 slink = &page->slinks[i];
2833 if (slink->bbox.x0 > found->bbox.x0) {
2834 found = slink;
2835 break;
2838 break;
2840 case dir_down:
2841 slinkindex = Int_val (Field (dir_v, 0));
2842 found = &page->slinks[slinkindex];
2843 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2844 slink = &page->slinks[i];
2845 if (slink->bbox.y0 >= found->bbox.y0) {
2846 found = slink;
2847 break;
2850 break;
2852 case dir_up:
2853 slinkindex = Int_val (Field (dir_v, 0));
2854 found = &page->slinks[slinkindex];
2855 for (i = slinkindex - 1; i >= 0; --i) {
2856 slink = &page->slinks[i];
2857 if (slink->bbox.y0 <= found->bbox.y0) {
2858 found = slink;
2859 break;
2862 break;
2865 else {
2866 dirtag = Int_val (dir_v);
2867 switch (dirtag) {
2868 case dir_first:
2869 found = page->slinks;
2870 break;
2872 case dir_last:
2873 if (page->slinks) {
2874 found = page->slinks + (page->slinkcount - 1);
2876 break;
2879 if (found) {
2880 ret_v = caml_alloc_small (2, 1);
2881 Field (ret_v, 0) = Val_int (found - page->slinks);
2884 unlock (__func__);
2885 CAMLreturn (ret_v);
2888 enum { uuri, utext, uannot };
2890 CAMLprim value ml_getlink (value ptr_v, value n_v)
2892 CAMLparam2 (ptr_v, n_v);
2893 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2894 fz_link *link;
2895 struct page *page;
2896 char *s = String_val (ptr_v);
2897 struct slink *slink;
2899 ret_v = Val_int (0);
2900 page = parse_pointer (__func__, s);
2902 lock (__func__);
2903 ensureslinks (page);
2904 slink = &page->slinks[Int_val (n_v)];
2905 if (slink->tag == SLINK) {
2906 link = slink->u.link;
2907 str_v = caml_copy_string (link->uri);
2908 ret_v = caml_alloc_small (1, uuri);
2909 Field (ret_v, 0) = str_v;
2911 else {
2912 ret_v = caml_alloc_small (1, uannot);
2913 tup_v = caml_alloc_tuple (2);
2914 Field (ret_v, 0) = tup_v;
2915 Field (tup_v, 0) = ptr_v;
2916 Field (tup_v, 1) = n_v;
2918 unlock (__func__);
2920 CAMLreturn (ret_v);
2923 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2925 CAMLparam2 (ptr_v, n_v);
2926 pdf_document *pdf;
2927 const char *contents = "";
2929 lock (__func__);
2930 pdf = pdf_specifics (state.ctx, state.doc);
2931 if (pdf) {
2932 char *s = String_val (ptr_v);
2933 struct page *page;
2934 struct slink *slink;
2936 page = parse_pointer (__func__, s);
2937 slink = &page->slinks[Int_val (n_v)];
2938 contents = pdf_annot_contents (state.ctx,
2939 (pdf_annot *) slink->u.annot);
2941 unlock (__func__);
2942 CAMLreturn (caml_copy_string (contents));
2945 CAMLprim value ml_getlinkcount (value ptr_v)
2947 CAMLparam1 (ptr_v);
2948 struct page *page;
2949 char *s = String_val (ptr_v);
2951 page = parse_pointer (__func__, s);
2952 CAMLreturn (Val_int (page->slinkcount));
2955 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2957 CAMLparam2 (ptr_v, n_v);
2958 CAMLlocal1 (ret_v);
2959 struct page *page;
2960 struct slink *slink;
2961 char *s = String_val (ptr_v);
2963 page = parse_pointer (__func__, s);
2964 ret_v = caml_alloc_tuple (4);
2965 lock (__func__);
2966 ensureslinks (page);
2968 slink = &page->slinks[Int_val (n_v)];
2969 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2970 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2971 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2972 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2973 unlock (__func__);
2974 CAMLreturn (ret_v);
2977 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2979 CAMLparam3 (ptr_v, x_v, y_v);
2980 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2981 fz_link *link;
2982 struct annot *annot;
2983 struct page *page;
2984 char *ptr = String_val (ptr_v);
2985 int x = Int_val (x_v), y = Int_val (y_v);
2986 struct pagedim *pdim;
2988 ret_v = Val_int (0);
2989 if (trylock (__func__)) {
2990 goto done;
2993 page = parse_pointer (__func__, ptr);
2994 pdim = &state.pagedims[page->pdimno];
2995 x += pdim->bounds.x0;
2996 y += pdim->bounds.y0;
2999 annot = getannot (page, x, y);
3000 if (annot) {
3001 int i, n = -1;
3003 ensureslinks (page);
3004 for (i = 0; i < page->slinkcount; ++i) {
3005 if (page->slinks[i].tag == SANNOT
3006 && page->slinks[i].u.annot == annot->annot) {
3007 n = i;
3008 break;
3011 ret_v = caml_alloc_small (1, uannot);
3012 tup_v = caml_alloc_tuple (2);
3013 Field (ret_v, 0) = tup_v;
3014 Field (tup_v, 0) = ptr_v;
3015 Field (tup_v, 1) = Val_int (n);
3016 goto unlock;
3020 link = getlink (page, x, y);
3021 if (link) {
3022 str_v = caml_copy_string (link->uri);
3023 ret_v = caml_alloc_small (1, uuri);
3024 Field (ret_v, 0) = str_v;
3026 else {
3027 fz_rect *b;
3028 fz_page_block *pageb;
3029 fz_stext_block *block;
3031 ensuretext (page);
3032 for (pageb = page->text->blocks;
3033 pageb < page->text->blocks + page->text->len;
3034 ++pageb) {
3035 fz_stext_line *line;
3036 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3037 block = pageb->u.text;
3039 b = &block->bbox;
3040 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3041 continue;
3043 for (line = block->lines;
3044 line < block->lines + block->len;
3045 ++line) {
3046 fz_stext_span *span;
3048 b = &line->bbox;
3049 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3050 continue;
3052 for (span = line->first_span; span; span = span->next) {
3053 int charnum;
3055 b = &span->bbox;
3056 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3057 continue;
3059 for (charnum = 0; charnum < span->len; ++charnum) {
3060 fz_rect bbox;
3061 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3062 b = &bbox;
3064 if (x >= b->x0 && x <= b->x1
3065 && y >= b->y0 && y <= b->y1) {
3066 fz_stext_style *style = span->text->style;
3067 const char *n2 =
3068 style->font
3069 ? fz_font_name (state.ctx, style->font)
3070 : "Span has no font name"
3072 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3073 style->font);
3074 if (face && face->family_name) {
3075 char *s;
3076 char *n1 = face->family_name;
3077 size_t l1 = strlen (n1);
3078 size_t l2 = strlen (n2);
3080 if (l1 != l2 || memcmp (n1, n2, l1)) {
3081 s = malloc (l1 + l2 + 2);
3082 if (s) {
3083 memcpy (s, n2, l2);
3084 s[l2] = '=';
3085 memcpy (s + l2 + 1, n1, l1 + 1);
3086 str_v = caml_copy_string (s);
3087 free (s);
3091 if (str_v == Val_unit) {
3092 str_v = caml_copy_string (n2);
3094 ret_v = caml_alloc_small (1, utext);
3095 Field (ret_v, 0) = str_v;
3096 goto unlock;
3103 unlock:
3104 unlock (__func__);
3106 done:
3107 CAMLreturn (ret_v);
3110 enum { mark_page, mark_block, mark_line, mark_word };
3112 static int uninteresting (int c)
3114 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3115 || ispunct (c);
3118 CAMLprim void ml_clearmark (value ptr_v)
3120 CAMLparam1 (ptr_v);
3121 char *s = String_val (ptr_v);
3122 struct page *page;
3124 if (trylock (__func__)) {
3125 goto done;
3128 page = parse_pointer (__func__, s);
3129 page->fmark.span = NULL;
3130 page->lmark.span = NULL;
3131 page->fmark.i = 0;
3132 page->lmark.i = 0;
3134 unlock (__func__);
3135 done:
3136 CAMLreturn0;
3139 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3141 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3142 CAMLlocal1 (ret_v);
3143 fz_rect *b;
3144 struct page *page;
3145 fz_stext_line *line;
3146 fz_page_block *pageb;
3147 fz_stext_block *block;
3148 struct pagedim *pdim;
3149 int mark = Int_val (mark_v);
3150 char *s = String_val (ptr_v);
3151 int x = Int_val (x_v), y = Int_val (y_v);
3153 ret_v = Val_bool (0);
3154 if (trylock (__func__)) {
3155 goto done;
3158 page = parse_pointer (__func__, s);
3159 pdim = &state.pagedims[page->pdimno];
3161 ensuretext (page);
3163 if (mark == mark_page) {
3164 int i;
3165 fz_page_block *pb1 = NULL, *pb2 = NULL;
3167 for (i = 0; i < page->text->len; ++i) {
3168 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3169 pb1 = &page->text->blocks[i];
3170 break;
3173 if (!pb1) goto unlock;
3175 for (i = page->text->len - 1; i >= 0; --i) {
3176 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3177 pb2 = &page->text->blocks[i];
3178 break;
3181 if (!pb2) goto unlock;
3183 block = pb1->u.text;
3185 page->fmark.i = 0;
3186 page->fmark.span = block->lines->first_span;
3188 block = pb2->u.text;
3189 line = &block->lines[block->len - 1];
3190 page->lmark.i = line->last_span->len - 1;
3191 page->lmark.span = line->last_span;
3192 ret_v = Val_bool (1);
3193 goto unlock;
3196 x += pdim->bounds.x0;
3197 y += pdim->bounds.y0;
3199 for (pageb = page->text->blocks;
3200 pageb < page->text->blocks + page->text->len;
3201 ++pageb) {
3202 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3203 block = pageb->u.text;
3205 b = &block->bbox;
3206 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3207 continue;
3209 if (mark == mark_block) {
3210 page->fmark.i = 0;
3211 page->fmark.span = block->lines->first_span;
3213 line = &block->lines[block->len - 1];
3214 page->lmark.i = line->last_span->len - 1;
3215 page->lmark.span = line->last_span;
3216 ret_v = Val_bool (1);
3217 goto unlock;
3220 for (line = block->lines;
3221 line < block->lines + block->len;
3222 ++line) {
3223 fz_stext_span *span;
3225 b = &line->bbox;
3226 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3227 continue;
3229 if (mark == mark_line) {
3230 page->fmark.i = 0;
3231 page->fmark.span = line->first_span;
3233 page->lmark.i = line->last_span->len - 1;
3234 page->lmark.span = line->last_span;
3235 ret_v = Val_bool (1);
3236 goto unlock;
3239 for (span = line->first_span; span; span = span->next) {
3240 int charnum;
3242 b = &span->bbox;
3243 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3244 continue;
3246 for (charnum = 0; charnum < span->len; ++charnum) {
3247 fz_rect bbox;
3248 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3249 b = &bbox;
3251 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3252 /* unicode ftw */
3253 int charnum2, charnum3 = -1, charnum4 = -1;
3255 if (uninteresting (span->text[charnum].c)) goto unlock;
3257 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3258 if (uninteresting (span->text[charnum2].c)) {
3259 charnum3 = charnum2 + 1;
3260 break;
3263 if (charnum3 == -1) charnum3 = 0;
3265 charnum4 = charnum;
3266 for (charnum2 = charnum + 1;
3267 charnum2 < span->len;
3268 ++charnum2) {
3269 if (uninteresting (span->text[charnum2].c)) break;
3270 charnum4 = charnum2;
3273 page->fmark.i = charnum3;
3274 page->fmark.span = span;
3276 page->lmark.i = charnum4;
3277 page->lmark.span = span;
3278 ret_v = Val_bool (1);
3279 goto unlock;
3285 unlock:
3286 if (!Bool_val (ret_v)) {
3287 page->fmark.span = NULL;
3288 page->lmark.span = NULL;
3289 page->fmark.i = 0;
3290 page->lmark.i = 0;
3292 unlock (__func__);
3294 done:
3295 CAMLreturn (ret_v);
3298 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3300 CAMLparam3 (ptr_v, x_v, y_v);
3301 CAMLlocal2 (ret_v, res_v);
3302 fz_rect *b = NULL;
3303 struct page *page;
3304 fz_page_block *pageb;
3305 struct pagedim *pdim;
3306 char *s = String_val (ptr_v);
3307 int x = Int_val (x_v), y = Int_val (y_v);
3309 ret_v = Val_int (0);
3310 if (trylock (__func__)) {
3311 goto done;
3314 page = parse_pointer (__func__, s);
3315 pdim = &state.pagedims[page->pdimno];
3316 x += pdim->bounds.x0;
3317 y += pdim->bounds.y0;
3319 ensuretext (page);
3321 for (pageb = page->text->blocks;
3322 pageb < page->text->blocks + page->text->len;
3323 ++pageb) {
3324 switch (pageb->type) {
3325 case FZ_PAGE_BLOCK_TEXT:
3326 b = &pageb->u.text->bbox;
3327 break;
3329 case FZ_PAGE_BLOCK_IMAGE:
3330 b = &pageb->u.image->bbox;
3331 break;
3333 default:
3334 continue;
3337 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3338 break;
3339 b = NULL;
3341 if (b) {
3342 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3343 ret_v = caml_alloc_small (1, 1);
3344 Store_double_field (res_v, 0, b->x0);
3345 Store_double_field (res_v, 1, b->x1);
3346 Store_double_field (res_v, 2, b->y0);
3347 Store_double_field (res_v, 3, b->y1);
3348 Field (ret_v, 0) = res_v;
3350 unlock (__func__);
3352 done:
3353 CAMLreturn (ret_v);
3356 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3358 CAMLparam2 (ptr_v, rect_v);
3359 fz_rect b;
3360 struct page *page;
3361 struct pagedim *pdim;
3362 char *s = String_val (ptr_v);
3363 int i, x0, x1, y0, y1, fi, li;
3364 fz_stext_line *line;
3365 fz_page_block *pageb;
3366 fz_stext_block *block;
3367 fz_stext_span *span, *fspan, *lspan;
3369 if (trylock (__func__)) {
3370 goto done;
3373 page = parse_pointer (__func__, s);
3374 ensuretext (page);
3376 pdim = &state.pagedims[page->pdimno];
3377 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3378 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3379 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3380 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3382 if (y0 > y1) {
3383 int t = y0;
3384 y0 = y1;
3385 y1 = t;
3386 x0 = x1;
3387 x1 = t;
3390 fi = page->fmark.i;
3391 fspan = page->fmark.span;
3393 li = page->lmark.i;
3394 lspan = page->lmark.span;
3396 for (pageb = page->text->blocks;
3397 pageb < page->text->blocks + page->text->len;
3398 ++pageb) {
3399 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3400 block = pageb->u.text;
3401 for (line = block->lines;
3402 line < block->lines + block->len;
3403 ++line) {
3405 for (span = line->first_span; span; span = span->next) {
3406 for (i = 0; i < span->len; ++i) {
3407 fz_stext_char_bbox (state.ctx, &b, span, i);
3409 if (x0 >= b.x0 && x0 <= b.x1
3410 && y0 >= b.y0 && y0 <= b.y1) {
3411 fspan = span;
3412 fi = i;
3414 if (x1 >= b.x0 && x1 <= b.x1
3415 && y1 >= b.y0 && y1 <= b.y1) {
3416 lspan = span;
3417 li = i;
3423 if (x1 < x0 && fspan == lspan) {
3424 i = fi;
3425 span = fspan;
3427 fi = li;
3428 fspan = lspan;
3430 li = i;
3431 lspan = span;
3434 page->fmark.i = fi;
3435 page->fmark.span = fspan;
3437 page->lmark.i = li;
3438 page->lmark.span = lspan;
3440 unlock (__func__);
3442 done:
3443 CAMLreturn0;
3446 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3448 char buf[4];
3449 int i, len, ret;
3451 for (i = a; i <= b; ++i) {
3452 len = fz_runetochar (buf, span->text[i].c);
3453 ret = fwrite (buf, len, 1, f);
3455 if (ret != 1) {
3456 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3457 len, ret, strerror (errno));
3458 return -1;
3461 return 0;
3464 #ifdef __CYGWIN__
3465 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3467 caml_failwith ("ml_popen not implemented under Cygwin");
3469 #else
3470 CAMLprim value ml_spawn (value command_v, value fds_v)
3472 CAMLparam2 (command_v, fds_v);
3473 CAMLlocal2 (l_v, tup_v);
3474 int ret, ret1;
3475 pid_t pid;
3476 char *msg = NULL;
3477 value earg_v = Nothing;
3478 posix_spawnattr_t attr;
3479 posix_spawn_file_actions_t fa;
3480 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3482 argv[2] = String_val (command_v);
3484 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3485 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3488 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3489 msg = "posix_spawnattr_init";
3490 goto fail1;
3493 #ifdef POSIX_SPAWN_USEVFORK
3494 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3495 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3496 goto fail;
3498 #endif
3500 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3501 int fd1, fd2;
3503 tup_v = Field (l_v, 0);
3504 fd1 = Int_val (Field (tup_v, 0));
3505 fd2 = Int_val (Field (tup_v, 1));
3506 if (fd2 < 0) {
3507 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3508 msg = "posix_spawn_file_actions_addclose";
3509 earg_v = tup_v;
3510 goto fail;
3513 else {
3514 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3515 msg = "posix_spawn_file_actions_adddup2";
3516 earg_v = tup_v;
3517 goto fail;
3522 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3523 msg = "posix_spawn";
3524 goto fail;
3527 fail:
3528 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3529 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3532 fail1:
3533 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3534 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3535 strerror (ret1));
3538 if (msg)
3539 unix_error (ret, msg, earg_v);
3541 CAMLreturn (Val_int (pid));
3543 #endif
3545 CAMLprim value ml_hassel (value ptr_v)
3547 CAMLparam1 (ptr_v);
3548 CAMLlocal1 (ret_v);
3549 struct page *page;
3550 char *s = String_val (ptr_v);
3552 ret_v = Val_bool (0);
3553 if (trylock (__func__)) {
3554 goto done;
3557 page = parse_pointer (__func__, s);
3558 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3559 unlock (__func__);
3560 done:
3561 CAMLreturn (ret_v);
3564 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3566 CAMLparam2 (fd_v, ptr_v);
3567 FILE *f;
3568 int seen = 0;
3569 struct page *page;
3570 fz_stext_line *line;
3571 fz_page_block *pageb;
3572 fz_stext_block *block;
3573 int fd = Int_val (fd_v);
3574 char *s = String_val (ptr_v);
3576 if (trylock (__func__)) {
3577 goto done;
3580 page = parse_pointer (__func__, s);
3582 if (!page->fmark.span || !page->lmark.span) {
3583 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3584 goto unlock;
3587 f = fdopen (fd, "w");
3588 if (!f) {
3589 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3590 fd, strerror (errno));
3591 f = stdout;
3594 for (pageb = page->text->blocks;
3595 pageb < page->text->blocks + page->text->len;
3596 ++pageb) {
3597 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3598 block = pageb->u.text;
3599 for (line = block->lines;
3600 line < block->lines + block->len;
3601 ++line) {
3602 fz_stext_span *span;
3604 for (span = line->first_span; span; span = span->next) {
3605 int a, b;
3607 seen |= span == page->fmark.span || span == page->lmark.span;
3608 a = span == page->fmark.span ? page->fmark.i : 0;
3609 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3611 if (seen) {
3612 if (pipespan (f, span, a, b)) {
3613 goto close;
3615 if (span == page->lmark.span) {
3616 goto close;
3618 if (span == line->last_span) {
3619 if (putc ('\n', f) == EOF) {
3620 fprintf (stderr,
3621 "failed break line on sel pipe: %s\n",
3622 strerror (errno));
3623 goto close;
3630 close:
3631 if (f != stdout) {
3632 int ret = fclose (f);
3633 fd = -1;
3634 if (ret == -1) {
3635 if (errno != ECHILD) {
3636 fprintf (stderr, "failed to close sel pipe: %s\n",
3637 strerror (errno));
3641 unlock:
3642 unlock (__func__);
3644 done:
3645 if (fd >= 0) {
3646 if (close (fd)) {
3647 fprintf (stderr, "failed to close sel pipe: %s\n",
3648 strerror (errno));
3651 CAMLreturn0;
3654 CAMLprim value ml_getpdimrect (value pagedimno_v)
3656 CAMLparam1 (pagedimno_v);
3657 CAMLlocal1 (ret_v);
3658 int pagedimno = Int_val (pagedimno_v);
3659 fz_rect box;
3661 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3662 if (trylock (__func__)) {
3663 box = fz_empty_rect;
3665 else {
3666 box = state.pagedims[pagedimno].mediabox;
3667 unlock (__func__);
3670 Store_double_field (ret_v, 0, box.x0);
3671 Store_double_field (ret_v, 1, box.x1);
3672 Store_double_field (ret_v, 2, box.y0);
3673 Store_double_field (ret_v, 3, box.y1);
3675 CAMLreturn (ret_v);
3678 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3679 value dw_v, value cols_v)
3681 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3682 CAMLlocal1 (ret_v);
3683 int i;
3684 double zoom = -1.;
3685 double maxh = 0.0;
3686 struct pagedim *p;
3687 double winw = Int_val (winw_v);
3688 double winh = Int_val (winh_v);
3689 double dw = Int_val (dw_v);
3690 double cols = Int_val (cols_v);
3691 double pw = 1.0, ph = 1.0;
3693 if (trylock (__func__)) {
3694 goto done;
3697 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3698 double w = p->pagebox.x1 / cols;
3699 double h = p->pagebox.y1;
3700 if (h > maxh) {
3701 maxh = h;
3702 ph = h;
3703 if (state.fitmodel != FitProportional) pw = w;
3705 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3708 zoom = (((winh / ph) * pw) + dw) / winw;
3709 unlock (__func__);
3710 done:
3711 ret_v = caml_copy_double (zoom);
3712 CAMLreturn (ret_v);
3715 CAMLprim value ml_getmaxw (value unit_v)
3717 CAMLparam1 (unit_v);
3718 CAMLlocal1 (ret_v);
3719 int i;
3720 double maxw = -1.;
3721 struct pagedim *p;
3723 if (trylock (__func__)) {
3724 goto done;
3727 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3728 double w = p->pagebox.x1;
3729 maxw = fz_max (maxw, w);
3732 unlock (__func__);
3733 done:
3734 ret_v = caml_copy_double (maxw);
3735 CAMLreturn (ret_v);
3738 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3740 CAMLparam4 (pt_v, x_v, y_v, string_v);
3741 CAMLlocal1 (ret_v);
3742 int pt = Int_val(pt_v);
3743 int x = Int_val (x_v);
3744 int y = Int_val (y_v);
3745 double w;
3747 w = draw_string (state.face, pt, x, y, String_val (string_v));
3748 ret_v = caml_copy_double (w);
3749 CAMLreturn (ret_v);
3752 CAMLprim value ml_measure_string (value pt_v, value string_v)
3754 CAMLparam2 (pt_v, string_v);
3755 CAMLlocal1 (ret_v);
3756 int pt = Int_val (pt_v);
3757 double w;
3759 w = measure_string (state.face, pt, String_val (string_v));
3760 ret_v = caml_copy_double (w);
3761 CAMLreturn (ret_v);
3764 CAMLprim value ml_getpagebox (value opaque_v)
3766 CAMLparam1 (opaque_v);
3767 CAMLlocal1 (ret_v);
3768 fz_rect rect;
3769 fz_irect bbox;
3770 fz_matrix ctm;
3771 fz_device *dev;
3772 char *s = String_val (opaque_v);
3773 struct page *page = parse_pointer (__func__, s);
3775 ret_v = caml_alloc_tuple (4);
3776 dev = fz_new_bbox_device (state.ctx, &rect);
3777 dev->hints |= FZ_IGNORE_SHADE;
3779 ctm = pagectm (page);
3780 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3782 fz_close_device (state.ctx, dev);
3783 fz_drop_device (state.ctx, dev);
3784 fz_round_rect (&bbox, &rect);
3785 Field (ret_v, 0) = Val_int (bbox.x0);
3786 Field (ret_v, 1) = Val_int (bbox.y0);
3787 Field (ret_v, 2) = Val_int (bbox.x1);
3788 Field (ret_v, 3) = Val_int (bbox.y1);
3790 CAMLreturn (ret_v);
3793 CAMLprim void ml_setaalevel (value level_v)
3795 CAMLparam1 (level_v);
3797 state.aalevel = Int_val (level_v);
3798 CAMLreturn0;
3801 #pragma GCC diagnostic push
3802 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3803 #include <X11/Xlib.h>
3804 #include <X11/cursorfont.h>
3805 #pragma GCC diagnostic pop
3807 #ifdef USE_EGL
3808 #include <EGL/egl.h>
3809 #else
3810 #include <GL/glx.h>
3811 #endif
3813 static const int shapes[] = {
3814 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3817 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3819 static struct {
3820 Window wid;
3821 Display *dpy;
3822 #ifdef USE_EGL
3823 EGLContext ctx;
3824 EGLConfig conf;
3825 EGLSurface win;
3826 EGLDisplay *edpy;
3827 #else
3828 GLXContext ctx;
3829 #endif
3830 XVisualInfo *visual;
3831 Cursor curs[CURS_COUNT];
3832 } glx;
3834 #ifdef VISAVIS
3835 static VisualID initvisual (void)
3837 /* On this system with: `Haswell-ULT Integrated Graphics
3838 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3839 using glX chosen visual and auto scrolling some document in
3840 fullscreen the power/energy-gpu is more than 1 joule bigger
3841 than when using hand picked visual that stands alone in glxinfo
3842 output: it's dead last in the list and it's the only one with
3843 `visual dep' (sic) of 32
3845 No clue what's going on here...
3847 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3849 XVisualInfo info;
3850 int ret = 1;
3852 info.depth = 32;
3853 info.class = TrueColor;
3854 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3855 &info, &ret);
3856 if (!ret || !glx.visual) {
3857 XCloseDisplay (glx.dpy);
3858 caml_failwith ("XGetVisualInfo");
3860 return glx.visual->visualid;
3862 #endif
3864 static void initcurs (void)
3866 for (size_t n = 0; n < CURS_COUNT; ++n) {
3867 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3871 CAMLprim void ml_setbgcol (value color_v)
3873 CAMLparam1 (color_v);
3874 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3875 CAMLreturn0;
3878 #ifdef USE_EGL
3879 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3881 CAMLparam3 (display_v, wid_v, screen_v);
3882 int major, minor;
3883 int num_conf;
3884 EGLint visid;
3885 EGLint attribs[] = {
3886 #ifdef VISAVIS
3887 EGL_NATIVE_VISUAL_ID, 0,
3888 #else
3889 EGL_DEPTH_SIZE, 24,
3890 #endif
3891 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3892 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3893 EGL_NONE
3895 EGLConfig conf;
3897 glx.dpy = XOpenDisplay (String_val (display_v));
3898 if (!glx.dpy) {
3899 caml_failwith ("XOpenDisplay");
3902 eglBindAPI (EGL_OPENGL_API);
3904 glx.edpy = eglGetDisplay (glx.dpy);
3905 if (glx.edpy == EGL_NO_DISPLAY) {
3906 caml_failwith ("eglGetDisplay");
3909 if (!eglInitialize (glx.edpy, &major, &minor)) {
3910 caml_failwith ("eglInitialize");
3913 #ifdef VISAVIS
3914 attribs[1] = visid = initvisual ();
3915 #endif
3917 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3918 !num_conf) {
3919 caml_failwith ("eglChooseConfig");
3922 glx.conf = conf;
3923 #ifndef VISAVIS
3924 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
3925 EGL_NATIVE_VISUAL_ID, &visid)) {
3926 caml_failwith ("eglGetConfigAttrib");
3928 #endif
3929 initcurs ();
3931 glx.wid = Int_val (wid_v);
3932 CAMLreturn (Val_int (visid));
3935 CAMLprim value ml_glxcompleteinit (value unit_v)
3937 CAMLparam1 (unit_v);
3939 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3940 if (!glx.ctx) {
3941 caml_failwith ("eglCreateContext");
3944 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3945 glx.wid, NULL);
3946 if (glx.win == EGL_NO_SURFACE) {
3947 caml_failwith ("eglCreateWindowSurface");
3950 XFree (glx.visual);
3951 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3952 glx.ctx = NULL;
3953 caml_failwith ("eglMakeCurrent");
3955 CAMLreturn (unit_v);
3957 #else
3958 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3960 CAMLparam3 (display_v, wid_v, screen_v);
3962 glx.dpy = XOpenDisplay (String_val (display_v));
3963 if (!glx.dpy) {
3964 caml_failwith ("XOpenDisplay");
3967 #ifdef VISAVIS
3968 initvisual ();
3969 #else
3970 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3971 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3972 if (!glx.visual) {
3973 XCloseDisplay (glx.dpy);
3974 caml_failwith ("glXChooseVisual");
3976 #endif
3977 initcurs ();
3979 glx.wid = Int_val (wid_v);
3980 CAMLreturn (Val_int (glx.visual->visualid));
3983 CAMLprim value ml_glxcompleteinit (value unit_v)
3985 CAMLparam1 (unit_v);
3987 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3988 if (!glx.ctx) {
3989 caml_failwith ("glXCreateContext");
3992 XFree (glx.visual);
3993 glx.visual = NULL;
3995 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3996 glXDestroyContext (glx.dpy, glx.ctx);
3997 glx.ctx = NULL;
3998 caml_failwith ("glXMakeCurrent");
4000 CAMLreturn (unit_v);
4002 #endif
4004 CAMLprim void ml_setcursor (value cursor_v)
4006 CAMLparam1 (cursor_v);
4007 size_t cursn = Int_val (cursor_v);
4009 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4010 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4011 XFlush (glx.dpy);
4012 CAMLreturn0;
4015 CAMLprim value ml_swapb (value unit_v)
4017 CAMLparam1 (unit_v);
4018 #ifdef USE_EGL
4019 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4020 caml_failwith ("eglSwapBuffers");
4022 #else
4023 glXSwapBuffers (glx.dpy, glx.wid);
4024 #endif
4025 CAMLreturn (unit_v);
4028 #include "keysym2ucs.c"
4030 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4032 CAMLparam1 (keysym_v);
4033 CAMLlocal1 (str_v);
4034 KeySym keysym = Int_val (keysym_v);
4035 Rune rune;
4036 int len;
4037 char buf[5];
4039 rune = keysym2ucs (keysym);
4040 len = fz_runetochar (buf, rune);
4041 buf[len] = 0;
4042 str_v = caml_copy_string (buf);
4043 CAMLreturn (str_v);
4046 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4048 CAMLprim value ml_platform (value unit_v)
4050 CAMLparam1 (unit_v);
4051 CAMLlocal2 (tup_v, arr_v);
4052 int platid = piunknown;
4053 struct utsname buf;
4055 #if defined __linux__
4056 platid = pilinux;
4057 #elif defined __CYGWIN__
4058 platid = picygwin;
4059 #elif defined __DragonFly__ || defined __FreeBSD__
4060 || defined __OpenBSD__ || defined __NetBSD__
4061 platid = pibsd;
4062 #elif defined __sun__
4063 platid = pisun;
4064 #elif defined __APPLE__
4065 platid = piosx;
4066 #endif
4067 if (uname (&buf)) err (1, "uname");
4069 tup_v = caml_alloc_tuple (2);
4071 char const *sar[] = {
4072 buf.sysname,
4073 buf.release,
4074 buf.version,
4075 buf.machine,
4076 NULL
4078 arr_v = caml_copy_string_array (sar);
4080 Field (tup_v, 0) = Val_int (platid);
4081 Field (tup_v, 1) = arr_v;
4082 CAMLreturn (tup_v);
4085 CAMLprim void ml_cloexec (value fd_v)
4087 CAMLparam1 (fd_v);
4088 int fd = Int_val (fd_v);
4090 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4091 uerror ("fcntl", Nothing);
4093 CAMLreturn0;
4096 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4098 CAMLparam2 (w_v, h_v);
4099 CAMLlocal1 (ret_v);
4100 struct bo *pbo;
4101 int w = Int_val (w_v);
4102 int h = Int_val (h_v);
4103 int cs = Int_val (cs_v);
4105 if (state.bo_usable) {
4106 pbo = calloc (sizeof (*pbo), 1);
4107 if (!pbo) {
4108 err (1, "calloc pbo");
4111 switch (cs) {
4112 case 0:
4113 case 1:
4114 pbo->size = w*h*4;
4115 break;
4116 case 2:
4117 pbo->size = w*h*2;
4118 break;
4119 default:
4120 errx (1, "%s: invalid colorspace %d", __func__, cs);
4123 state.glGenBuffersARB (1, &pbo->id);
4124 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4125 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4126 NULL, GL_STREAM_DRAW);
4127 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4128 GL_READ_WRITE);
4129 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4130 if (!pbo->ptr) {
4131 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4132 state.glDeleteBuffersARB (1, &pbo->id);
4133 free (pbo);
4134 ret_v = caml_copy_string ("0");
4136 else {
4137 int res;
4138 char *s;
4140 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4141 if (res < 0) {
4142 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4144 s = malloc (res+1);
4145 if (!s) {
4146 err (1, "malloc %d bytes failed", res+1);
4148 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4149 if (res < 0) {
4150 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4152 ret_v = caml_copy_string (s);
4153 free (s);
4156 else {
4157 ret_v = caml_copy_string ("0");
4159 CAMLreturn (ret_v);
4162 CAMLprim void ml_freepbo (value s_v)
4164 CAMLparam1 (s_v);
4165 char *s = String_val (s_v);
4166 struct tile *tile = parse_pointer (__func__, s);
4168 if (tile->pbo) {
4169 state.glDeleteBuffersARB (1, &tile->pbo->id);
4170 tile->pbo->id = -1;
4171 tile->pbo->ptr = NULL;
4172 tile->pbo->size = -1;
4174 CAMLreturn0;
4177 CAMLprim void ml_unmappbo (value s_v)
4179 CAMLparam1 (s_v);
4180 char *s = String_val (s_v);
4181 struct tile *tile = parse_pointer (__func__, s);
4183 if (tile->pbo) {
4184 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4185 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4186 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4188 tile->pbo->ptr = NULL;
4189 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4191 CAMLreturn0;
4194 static void setuppbo (void)
4196 #ifdef USE_EGL
4197 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4198 #else
4199 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4200 #endif
4201 state.bo_usable = GGPA (glBindBufferARB)
4202 && GGPA (glUnmapBufferARB)
4203 && GGPA (glMapBufferARB)
4204 && GGPA (glBufferDataARB)
4205 && GGPA (glGenBuffersARB)
4206 && GGPA (glDeleteBuffersARB);
4207 #undef GGPA
4210 CAMLprim value ml_bo_usable (value unit_v)
4212 CAMLparam1 (unit_v);
4213 CAMLreturn (Val_bool (state.bo_usable));
4216 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4218 CAMLparam3 (ptr_v, x_v, y_v);
4219 CAMLlocal2 (ret_v, tup_v);
4220 struct page *page;
4221 char *s = String_val (ptr_v);
4222 int x = Int_val (x_v), y = Int_val (y_v);
4223 struct pagedim *pdim;
4224 fz_point p;
4225 fz_matrix ctm;
4227 page = parse_pointer (__func__, s);
4228 pdim = &state.pagedims[page->pdimno];
4230 ret_v = Val_int (0);
4231 if (trylock (__func__)) {
4232 goto done;
4235 if (pdf_specifics (state.ctx, state.doc)) {
4236 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4237 ctm = state.pagedims[page->pdimno].tctm;
4239 else {
4240 ctm = fz_identity;
4242 p.x = x + pdim->bounds.x0;
4243 p.y = y + pdim->bounds.y0;
4245 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4246 fz_invert_matrix (&ctm, &ctm);
4247 fz_transform_point (&p, &ctm);
4249 tup_v = caml_alloc_tuple (2);
4250 ret_v = caml_alloc_small (1, 1);
4251 Field (tup_v, 0) = Val_int (p.x);
4252 Field (tup_v, 1) = Val_int (p.y);
4253 Field (ret_v, 0) = tup_v;
4255 unlock (__func__);
4256 done:
4257 CAMLreturn (ret_v);
4260 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4261 value x_v, value y_v)
4263 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4264 CAMLlocal1 (ret_v);
4265 struct page *page;
4266 char *s = String_val (ptr_v);
4267 int pageno = Int_val (pageno_v);
4268 int pdimno = Int_val (pdimno_v);
4269 double x = Double_val (x_v), y = Double_val (y_v);
4270 struct pagedim *pdim;
4271 fz_point p;
4272 fz_matrix ctm;
4274 ret_v = Val_int (0);
4275 lock (__func__);
4277 if (!*s) {
4278 page = loadpage (pageno, pdimno);
4280 else {
4281 page = parse_pointer (__func__, s);
4283 pdim = &state.pagedims[pdimno];
4285 if (pdf_specifics (state.ctx, state.doc)) {
4286 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4287 ctm = state.pagedims[page->pdimno].tctm;
4289 else {
4290 ctm = fz_identity;
4292 p.x = x + pdim->bounds.x0;
4293 p.y = y + pdim->bounds.y0;
4295 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4296 fz_transform_point (&p, &ctm);
4298 ret_v = caml_alloc_tuple (2);
4299 Field (ret_v, 0) = caml_copy_double (p.x);
4300 Field (ret_v, 1) = caml_copy_double (p.y);
4302 if (!*s) {
4303 freepage (page);
4305 unlock (__func__);
4306 CAMLreturn (ret_v);
4309 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4310 value contents_v)
4312 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4313 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4315 if (pdf) {
4316 pdf_annot *annot;
4317 struct page *page;
4318 fz_point p;
4319 char *s = String_val (ptr_v);
4321 page = parse_pointer (__func__, s);
4322 annot = pdf_create_annot (state.ctx,
4323 pdf_page_from_fz_page (state.ctx,
4324 page->fzpage),
4325 PDF_ANNOT_TEXT);
4326 p.x = Int_val (x_v);
4327 p.y = Int_val (y_v);
4328 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4329 pdf_set_text_annot_position (state.ctx, annot, p);
4330 state.dirty = 1;
4332 CAMLreturn0;
4335 CAMLprim void ml_delannot (value ptr_v, value n_v)
4337 CAMLparam2 (ptr_v, n_v);
4338 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4340 if (pdf) {
4341 struct page *page;
4342 char *s = String_val (ptr_v);
4343 struct slink *slink;
4345 page = parse_pointer (__func__, s);
4346 slink = &page->slinks[Int_val (n_v)];
4347 pdf_delete_annot (state.ctx,
4348 pdf_page_from_fz_page (state.ctx, page->fzpage),
4349 (pdf_annot *) slink->u.annot);
4350 state.dirty = 1;
4352 CAMLreturn0;
4355 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4357 CAMLparam3 (ptr_v, n_v, str_v);
4358 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4360 if (pdf) {
4361 struct page *page;
4362 char *s = String_val (ptr_v);
4363 struct slink *slink;
4365 page = parse_pointer (__func__, s);
4366 slink = &page->slinks[Int_val (n_v)];
4367 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4368 String_val (str_v));
4369 state.dirty = 1;
4371 CAMLreturn0;
4374 CAMLprim value ml_hasunsavedchanges (value unit_v)
4376 CAMLparam1 (unit_v);
4377 CAMLreturn (Val_bool (state.dirty));
4380 CAMLprim void ml_savedoc (value path_v)
4382 CAMLparam1 (path_v);
4383 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4385 if (pdf) {
4386 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4388 CAMLreturn0;
4391 static void makestippletex (void)
4393 const char pixels[] = "\xff\xff\0\0";
4394 glGenTextures (1, &state.stid);
4395 glBindTexture (GL_TEXTURE_1D, state.stid);
4396 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4397 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4398 glTexImage1D (
4399 GL_TEXTURE_1D,
4401 GL_ALPHA,
4404 GL_ALPHA,
4405 GL_UNSIGNED_BYTE,
4406 pixels
4410 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4412 return caml_copy_string (FZ_VERSION);
4415 #ifdef USE_FONTCONFIG
4416 static struct {
4417 int inited;
4418 FcConfig *config;
4419 } fc;
4421 static fz_font *fc_load_system_font_func (fz_context *ctx,
4422 const char *name,
4423 int bold,
4424 int italic,
4425 int UNUSED_ATTR needs_exact_metrics)
4427 char *buf;
4428 size_t i, size;
4429 fz_font *font;
4430 FcChar8 *path;
4431 FcResult result;
4432 FcPattern *pat, *pat1;
4434 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4435 name, bold, italic, needs_exact_metrics);
4436 if (!fc.inited) {
4437 fc.inited = 1;
4438 fc.config = FcInitLoadConfigAndFonts ();
4439 if (!fc.config) {
4440 lprintf ("FcInitLoadConfigAndFonts failed\n");
4441 return NULL;
4444 if (!fc.config) return NULL;
4446 size = strlen (name);
4447 if (bold) size += sizeof (":bold") - 1;
4448 if (italic) size += sizeof (":italic") - 1;
4449 size += 1;
4451 buf = malloc (size);
4452 if (!buf) {
4453 err (1, "malloc %zu failed", size);
4456 strcpy (buf, name);
4457 if (bold && italic) {
4458 strcat (buf, ":bold:italic");
4460 else {
4461 if (bold) strcat (buf, ":bold");
4462 if (italic) strcat (buf, ":italic");
4464 for (i = 0; i < size; ++i) {
4465 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4468 lprintf ("fcbuf=%s\n", buf);
4469 pat = FcNameParse ((FcChar8 *) buf);
4470 if (!pat) {
4471 printd ("emsg FcNameParse failed\n");
4472 free (buf);
4473 return NULL;
4476 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4477 printd ("emsg FcConfigSubstitute failed\n");
4478 free (buf);
4479 return NULL;
4481 FcDefaultSubstitute (pat);
4483 pat1 = FcFontMatch (fc.config, pat, &result);
4484 if (!pat1) {
4485 printd ("emsg FcFontMatch failed\n");
4486 FcPatternDestroy (pat);
4487 free (buf);
4488 return NULL;
4491 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4492 printd ("emsg FcPatternGetString failed\n");
4493 FcPatternDestroy (pat);
4494 FcPatternDestroy (pat1);
4495 free (buf);
4496 return NULL;
4499 #if 0
4500 printd ("emsg name=%s path=%s\n", name, path);
4501 #endif
4502 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4503 FcPatternDestroy (pat);
4504 FcPatternDestroy (pat1);
4505 free (buf);
4506 return font;
4508 #endif
4510 CAMLprim void ml_init (value csock_v, value params_v)
4512 CAMLparam2 (csock_v, params_v);
4513 CAMLlocal2 (trim_v, fuzz_v);
4514 int ret;
4515 int texcount;
4516 char *fontpath;
4517 int colorspace;
4518 int mustoresize;
4519 int haspboext;
4521 state.csock = Int_val (csock_v);
4522 state.rotate = Int_val (Field (params_v, 0));
4523 state.fitmodel = Int_val (Field (params_v, 1));
4524 trim_v = Field (params_v, 2);
4525 texcount = Int_val (Field (params_v, 3));
4526 state.sliceheight = Int_val (Field (params_v, 4));
4527 mustoresize = Int_val (Field (params_v, 5));
4528 colorspace = Int_val (Field (params_v, 6));
4529 fontpath = String_val (Field (params_v, 7));
4531 if (caml_string_length (Field (params_v, 8)) > 0) {
4532 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4534 if (!state.trimcachepath) {
4535 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4536 strerror (errno));
4540 haspboext = Bool_val (Field (params_v, 9));
4542 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4543 fz_register_document_handlers (state.ctx);
4545 #ifdef USE_FONTCONFIG
4546 if (Bool_val (Field (params_v, 11))) {
4547 fz_install_load_system_font_funcs (
4548 state.ctx, fc_load_system_font_func, NULL
4551 #endif
4553 state.trimmargins = Bool_val (Field (trim_v, 0));
4554 fuzz_v = Field (trim_v, 1);
4555 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4556 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4557 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4558 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4560 set_tex_params (colorspace);
4562 if (*fontpath) {
4563 #ifndef USE_FONTCONFIG
4564 state.face = load_font (fontpath);
4565 #else
4566 FcChar8 *path;
4567 FcResult result;
4568 char *buf = fontpath;
4569 FcPattern *pat, *pat1;
4571 fc.inited = 1;
4572 fc.config = FcInitLoadConfigAndFonts ();
4573 if (!fc.config) {
4574 errx (1, "FcInitLoadConfigAndFonts failed");
4577 pat = FcNameParse ((FcChar8 *) buf);
4578 if (!pat) {
4579 errx (1, "FcNameParse failed");
4582 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4583 errx (1, "FcConfigSubstitute failed");
4585 FcDefaultSubstitute (pat);
4587 pat1 = FcFontMatch (fc.config, pat, &result);
4588 if (!pat1) {
4589 errx (1, "FcFontMatch failed");
4592 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4593 errx (1, "FcPatternGetString failed");
4596 state.face = load_font ((char *) path);
4597 FcPatternDestroy (pat);
4598 FcPatternDestroy (pat1);
4599 #endif
4601 else {
4602 int len;
4603 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4604 0, 0, &len);
4605 state.face = load_builtin_font (data, len);
4607 if (!state.face) _exit (1);
4609 realloctexts (texcount);
4611 if (haspboext) {
4612 setuppbo ();
4615 makestippletex ();
4617 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4618 if (ret) {
4619 errx (1, "pthread_create: %s", strerror (ret));
4622 CAMLreturn0;