Cosmetics
[llpp.git] / link.c
blob515b769d60da064fa5623794cd7e6d030cfeb8cd
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] = {
382 { .iov_base = &size4, .iov_len = 4 },
383 { .iov_base = p, .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 for (int i = 0; i < state.pdflut.count; ++i) {
455 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
457 free (state.pdflut.objs);
458 state.pdflut.objs = NULL;
459 state.pdflut.idx = 0;
461 #endif
462 if (state.doc) {
463 fz_drop_document (state.ctx, state.doc);
464 state.doc = NULL;
468 static int openxref (char *filename, char *password)
470 for (int i = 0; i < state.texcount; ++i) {
471 state.texowners[i].w = -1;
472 state.texowners[i].slice = NULL;
475 closedoc ();
477 state.dirty = 0;
478 if (state.pagedims) {
479 free (state.pagedims);
480 state.pagedims = NULL;
482 state.pagedimcount = 0;
484 fz_set_aa_level (state.ctx, state.aalevel);
485 state.doc = fz_open_document (state.ctx, filename);
486 if (fz_needs_password (state.ctx, state.doc)) {
487 if (password && !*password) {
488 printd ("pass");
489 return 0;
491 else {
492 int ok = fz_authenticate_password (state.ctx, state.doc, password);
493 if (!ok) {
494 printd ("pass fail");
495 return 0;
499 state.pagecount = fz_count_pages (state.ctx, state.doc);
500 return 1;
503 static void pdfinfo (void)
505 struct { char *tag; char *name; } metatbl[] = {
506 { FZ_META_INFO_TITLE, "Title" },
507 { FZ_META_INFO_AUTHOR, "Author" },
508 { FZ_META_FORMAT, "Format" },
509 { FZ_META_ENCRYPTION, "Encryption" },
510 { "info:Creator", "Creator" },
511 { "info:Producer", "Producer" },
512 { "info:CreationDate", "Creation date" },
514 int len = 0;
515 char *buf = NULL;
517 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
518 int need;
519 again:
520 need = fz_lookup_metadata (state.ctx, state.doc,
521 metatbl[i].tag, buf, len);
522 if (need > 0) {
523 if (need <= len) {
524 printd ("info %s\t%s", metatbl[i].name, buf);
526 else {
527 buf = realloc (buf, need);
528 if (!buf) err (1, "pdfinfo realloc %d", need);
529 len = need;
530 goto again;
534 free (buf);
536 printd ("infoend");
539 static void unlinktile (struct tile *tile)
541 for (int i = 0; i < tile->slicecount; ++i) {
542 struct slice *s = &tile->slices[i];
544 if (s->texindex != -1) {
545 if (state.texowners[s->texindex].slice == s) {
546 state.texowners[s->texindex].slice = NULL;
552 static void freepage (struct page *page)
554 if (!page) return;
555 if (page->text) {
556 fz_drop_stext_page (state.ctx, page->text);
558 if (page->sheet) {
559 fz_drop_stext_sheet (state.ctx, page->sheet);
561 if (page->slinks) {
562 free (page->slinks);
564 fz_drop_display_list (state.ctx, page->dlist);
565 fz_drop_page (state.ctx, page->fzpage);
566 free (page);
569 static void freetile (struct tile *tile)
571 unlinktile (tile);
572 if (!tile->pbo) {
573 #ifndef PIGGYBACK
574 fz_drop_pixmap (state.ctx, tile->pixmap);
575 #else
576 if (state.pig) {
577 fz_drop_pixmap (state.ctx, state.pig);
579 state.pig = tile->pixmap;
580 #endif
582 else {
583 free (tile->pbo);
584 fz_drop_pixmap (state.ctx, tile->pixmap);
586 free (tile);
589 #ifdef __ALTIVEC__
590 #include <stdint.h>
591 #include <altivec.h>
593 static int cacheline32bytes;
595 static void __attribute__ ((constructor)) clcheck (void)
597 char **envp = environ;
598 unsigned long *auxv;
600 while (*envp++);
602 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
603 if (*auxv == 19) {
604 cacheline32bytes = auxv[1] == 32;
605 return;
610 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
612 size_t size = pixmap->w * pixmap->h * pixmap->n;
613 if (cacheline32bytes && size > 32) {
614 intptr_t a1, a2, diff;
615 size_t sizea, i;
616 vector unsigned char v = vec_splat_u8 (-1);
617 vector unsigned char *p;
619 a1 = a2 = (intptr_t) pixmap->samples;
620 a2 = (a1 + 31) & ~31;
621 diff = a2 - a1;
622 sizea = size - diff;
623 p = (void *) a2;
625 while (a1 != a2) *(char *) a1++ = 0xff;
626 for (i = 0; i < (sizea & ~31); i += 32) {
627 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
628 vec_st (v, i, p);
629 vec_st (v, i + 16, p);
631 while (i < sizea) *((char *) a1 + i++) = 0xff;
633 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
635 #else
636 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
637 #endif
639 static void trimctm (pdf_page *page, int pindex)
641 fz_matrix ctm;
642 struct pagedim *pdim = &state.pagedims[pindex];
644 if (!page) return;
645 if (!pdim->tctmready) {
646 fz_rect realbox, mediabox;
647 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
649 fz_rotate (&rm, -pdim->rotate);
650 fz_scale (&sm, 1, -1);
651 fz_concat (&ctm, &rm, &sm);
652 realbox = pdim->mediabox;
653 fz_transform_rect (&realbox, &ctm);
654 fz_translate (&tm, -realbox.x0, -realbox.y0);
655 fz_concat (&ctm1, &ctm, &tm);
656 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
657 fz_invert_matrix (&im, &page_ctm);
658 fz_concat (&ctm, &im, &ctm1);
659 pdim->tctm = ctm;
660 pdim->tctmready = 1;
664 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
666 fz_matrix ctm, tm;
667 int pdimno = pdim - state.pagedims;
669 if (pdf_specifics (state.ctx, state.doc)) {
670 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
671 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
673 else {
674 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
675 fz_concat (&ctm, &tm, &pdim->ctm);
677 return ctm;
680 static fz_matrix pagectm (struct page *page)
682 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
685 static void *loadpage (int pageno, int pindex)
687 fz_device *dev;
688 struct page *page;
690 page = calloc (sizeof (struct page), 1);
691 if (!page) {
692 err (1, "calloc page %d", pageno);
695 page->dlist = fz_new_display_list (state.ctx, NULL);
696 dev = fz_new_list_device (state.ctx, page->dlist);
697 fz_try (state.ctx) {
698 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
699 fz_run_page (state.ctx, page->fzpage, dev,
700 &fz_identity, NULL);
702 fz_catch (state.ctx) {
703 page->fzpage = NULL;
705 fz_close_device (state.ctx, dev);
706 fz_drop_device (state.ctx, dev);
708 page->pdimno = pindex;
709 page->pageno = pageno;
710 page->sgen = state.gen;
711 page->agen = state.gen;
712 page->tgen = state.gen;
713 return page;
716 static struct tile *alloctile (int h)
718 int slicecount;
719 size_t tilesize;
720 struct tile *tile;
722 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
723 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
724 tile = calloc (tilesize, 1);
725 if (!tile) {
726 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
728 for (int i = 0; i < slicecount; ++i) {
729 int sh = fz_mini (h, state.sliceheight);
730 tile->slices[i].h = sh;
731 tile->slices[i].texindex = -1;
732 h -= sh;
734 tile->slicecount = slicecount;
735 tile->sliceheight = state.sliceheight;
736 return tile;
739 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
740 struct bo *pbo)
742 fz_rect rect;
743 fz_irect bbox;
744 fz_matrix ctm;
745 fz_device *dev;
746 struct tile *tile;
747 struct pagedim *pdim;
749 tile = alloctile (h);
750 pdim = &state.pagedims[page->pdimno];
752 bbox = pdim->bounds;
753 bbox.x0 += x;
754 bbox.y0 += y;
755 bbox.x1 = bbox.x0 + w;
756 bbox.y1 = bbox.y0 + h;
758 if (state.pig) {
759 if (state.pig->w == w
760 && state.pig->h == h
761 && state.pig->colorspace == state.colorspace) {
762 tile->pixmap = state.pig;
763 tile->pixmap->x = bbox.x0;
764 tile->pixmap->y = bbox.y0;
766 else {
767 fz_drop_pixmap (state.ctx, state.pig);
769 state.pig = NULL;
771 if (!tile->pixmap) {
772 if (pbo) {
773 tile->pixmap =
774 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
775 &bbox, 1, pbo->ptr);
776 tile->pbo = pbo;
778 else {
779 tile->pixmap =
780 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
784 tile->w = w;
785 tile->h = h;
786 clearpixmap (tile->pixmap);
788 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
789 ctm = pagectm (page);
790 fz_rect_from_irect (&rect, &bbox);
791 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
792 fz_close_device (state.ctx, dev);
793 fz_drop_device (state.ctx, dev);
795 return tile;
798 #ifdef CACHE_PAGEREFS
799 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
800 thanks to Robin Watts */
801 static void
802 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
804 fz_context *ctx = state.ctx; /* doc->ctx; */
805 pdf_obj *kids;
806 int len;
808 if (state.pdflut.idx == state.pagecount) return;
810 kids = pdf_dict_gets (ctx, node, "Kids");
811 len = pdf_array_len (ctx, kids);
813 if (len == 0)
814 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
816 if (pdf_mark_obj (ctx, node))
817 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
818 for (int i = 0; i < len; i++) {
819 pdf_obj *kid = pdf_array_get (ctx, kids, i);
820 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
821 if (*type
822 ? !strcmp (type, "Pages")
823 : pdf_dict_gets (ctx, kid, "Kids")
824 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
825 pdf_collect_pages (doc, kid);
827 else {
828 if (*type
829 ? strcmp (type, "Page") != 0
830 : !pdf_dict_gets (ctx, kid, "MediaBox"))
831 fz_warn (ctx, "non-page object in page tree (%s)", type);
832 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
835 pdf_unmark_obj (ctx, node);
838 static void
839 pdf_load_page_objs (pdf_document *doc)
841 pdf_obj *root = pdf_dict_gets (state.ctx,
842 pdf_trailer (state.ctx, doc), "Root");
843 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
845 if (!node)
846 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
848 state.pdflut.idx = 0;
849 pdf_collect_pages (doc, node);
851 #endif
853 static void initpdims (int wthack)
855 double start, end;
856 FILE *trimf = NULL;
857 fz_rect rootmediabox;
858 int pageno, trim, show;
859 int trimw = 0, cxcount;
860 fz_context *ctx = state.ctx;
861 pdf_document *pdf = pdf_specifics (ctx, state.doc);
863 fz_var (trimw);
864 fz_var (trimf);
865 fz_var (cxcount);
866 start = now ();
868 if (state.trimmargins && state.trimcachepath) {
869 trimf = fopen (state.trimcachepath, "rb");
870 if (!trimf) {
871 trimf = fopen (state.trimcachepath, "wb");
872 trimw = 1;
876 if (state.trimmargins || pdf || !state.cxack)
877 cxcount = state.pagecount;
878 else
879 cxcount = fz_mini (state.pagecount, 1);
881 if (pdf) {
882 pdf_obj *obj;
883 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
884 "Root/Pages/MediaBox");
885 pdf_to_rect (ctx, obj, &rootmediabox);
888 #ifdef CACHE_PAGEREFS
889 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
890 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
891 if (!state.pdflut.objs) {
892 err (1, "malloc pageobjs %zu %d %zu failed",
893 sizeof (*state.pdflut.objs), cxcount,
894 sizeof (*state.pdflut.objs) * cxcount);
896 state.pdflut.count = cxcount;
897 pdf_load_page_objs (pdf);
898 state.pdflut.pdf = pdf;
900 #endif
902 for (pageno = 0; pageno < cxcount; ++pageno) {
903 int rotate = 0;
904 struct pagedim *p;
905 fz_rect mediabox;
907 fz_var (rotate);
908 if (pdf) {
909 pdf_obj *pageref, *pageobj;
911 #ifdef CACHE_PAGEREFS
912 pageref = state.pdflut.objs[pageno];
913 #else
914 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
915 #endif
916 pageobj = pdf_resolve_indirect (ctx, pageref);
917 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
919 if (state.trimmargins) {
920 pdf_obj *obj;
921 pdf_page *page;
923 fz_try (ctx) {
924 page = pdf_load_page (ctx, pdf, pageno);
925 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
926 trim = state.trimanew || !obj;
927 if (trim) {
928 fz_rect rect;
929 fz_device *dev;
930 fz_matrix ctm, page_ctm;
932 dev = fz_new_bbox_device (ctx, &rect);
933 dev->hints |= FZ_IGNORE_SHADE;
934 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
935 fz_invert_matrix (&ctm, &page_ctm);
936 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
937 fz_close_device (ctx, dev);
938 fz_drop_device (ctx, dev);
940 rect.x0 += state.trimfuzz.x0;
941 rect.x1 += state.trimfuzz.x1;
942 rect.y0 += state.trimfuzz.y0;
943 rect.y1 += state.trimfuzz.y1;
944 fz_transform_rect (&rect, &ctm);
945 fz_intersect_rect (&rect, &mediabox);
947 if (!fz_is_empty_rect (&rect)) {
948 mediabox = rect;
951 obj = pdf_new_array (ctx, pdf, 4);
952 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
953 mediabox.x0));
954 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
955 mediabox.y0));
956 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
957 mediabox.x1));
958 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
959 mediabox.y1));
960 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
962 else {
963 mediabox.x0 = pdf_to_real (ctx,
964 pdf_array_get (ctx, obj, 0));
965 mediabox.y0 = pdf_to_real (ctx,
966 pdf_array_get (ctx, obj, 1));
967 mediabox.x1 = pdf_to_real (ctx,
968 pdf_array_get (ctx, obj, 2));
969 mediabox.y1 = pdf_to_real (ctx,
970 pdf_array_get (ctx, obj, 3));
973 fz_drop_page (ctx, &page->super);
974 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
975 if (show) {
976 printd ("progress %f Trimming %d",
977 (double) (pageno + 1) / state.pagecount,
978 pageno + 1);
981 fz_catch (ctx) {
982 fprintf (stderr, "failed to load page %d\n", pageno+1);
985 else {
986 int empty = 0;
987 fz_rect cropbox;
989 pdf_to_rect (ctx,
990 pdf_dict_gets (ctx, pageobj, "MediaBox"),
991 &mediabox);
992 if (fz_is_empty_rect (&mediabox)) {
993 mediabox.x0 = 0;
994 mediabox.y0 = 0;
995 mediabox.x1 = 612;
996 mediabox.y1 = 792;
997 empty = 1;
1000 pdf_to_rect (ctx,
1001 pdf_dict_gets (ctx, pageobj, "CropBox"),
1002 &cropbox);
1003 if (!fz_is_empty_rect (&cropbox)) {
1004 if (empty) {
1005 mediabox = cropbox;
1007 else {
1008 fz_intersect_rect (&mediabox, &cropbox);
1011 else {
1012 if (empty) {
1013 if (fz_is_empty_rect (&rootmediabox)) {
1014 fprintf (stderr,
1015 "cannot find page size for page %d\n",
1016 pageno+1);
1018 else {
1019 mediabox = rootmediabox;
1025 else {
1026 if (state.trimmargins && trimw) {
1027 fz_page *page;
1029 fz_try (ctx) {
1030 page = fz_load_page (ctx, state.doc, pageno);
1031 fz_bound_page (ctx, page, &mediabox);
1032 if (state.trimmargins) {
1033 fz_rect rect;
1034 fz_device *dev;
1036 dev = fz_new_bbox_device (ctx, &rect);
1037 dev->hints |= FZ_IGNORE_SHADE;
1038 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1039 fz_close_device (ctx, dev);
1040 fz_drop_device (ctx, dev);
1042 rect.x0 += state.trimfuzz.x0;
1043 rect.x1 += state.trimfuzz.x1;
1044 rect.y0 += state.trimfuzz.y0;
1045 rect.y1 += state.trimfuzz.y1;
1046 fz_intersect_rect (&rect, &mediabox);
1048 if (!fz_is_empty_rect (&rect)) {
1049 mediabox = rect;
1052 fz_drop_page (ctx, page);
1053 if (!state.cxack) {
1054 printd ("progress %f loading %d",
1055 (double) (pageno + 1) / state.pagecount,
1056 pageno + 1);
1059 fz_catch (ctx) {
1061 if (trimf) {
1062 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1063 if (n - 1) {
1064 err (1, "fwrite trim mediabox");
1068 else {
1069 if (trimf) {
1070 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1071 if (n - 1) {
1072 err (1, "fread trim mediabox %d", pageno);
1075 else {
1076 fz_page *page;
1077 fz_try (ctx) {
1078 page = fz_load_page (ctx, state.doc, pageno);
1079 fz_bound_page (ctx, page, &mediabox);
1080 fz_drop_page (ctx, page);
1082 show = !state.trimmargins && pageno % 20 == 0;
1083 if (show) {
1084 printd ("progress %f Gathering dimensions %d",
1085 (double) (pageno) / state.pagecount,
1086 pageno);
1089 fz_catch (ctx) {
1090 fprintf (stderr, "failed to load page %d\n", pageno);
1096 if (state.pagedimcount == 0
1097 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1098 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1099 size_t size;
1101 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1102 state.pagedims = realloc (state.pagedims, size);
1103 if (!state.pagedims) {
1104 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1105 size, state.pagedimcount + 1);
1108 p = &state.pagedims[state.pagedimcount++];
1109 p->rotate = rotate;
1110 p->mediabox = mediabox;
1111 p->pageno = pageno;
1114 end = now ();
1115 if (!wthack) {
1116 printd ("progress 1 %s %d pages in %f seconds",
1117 state.trimmargins ? "Trimmed" : "Processed",
1118 state.pagecount, end - start);
1120 state.trimanew = 0;
1121 if (trimf) {
1122 if (fclose (trimf)) {
1123 err (1, "fclose");
1128 static void layout (void)
1130 int pindex;
1131 fz_rect box;
1132 fz_matrix ctm, rm;
1133 struct pagedim *p = p;
1134 double zw, w, maxw = 0.0, zoom = zoom;
1136 if (state.pagedimcount == 0) return;
1138 switch (state.fitmodel) {
1139 case FitProportional:
1140 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1141 double x0, x1;
1143 p = &state.pagedims[pindex];
1144 fz_rotate (&rm, p->rotate + state.rotate);
1145 box = p->mediabox;
1146 fz_transform_rect (&box, &rm);
1148 x0 = fz_min (box.x0, box.x1);
1149 x1 = fz_max (box.x0, box.x1);
1151 w = x1 - x0;
1152 maxw = fz_max (w, maxw);
1153 zoom = state.w / maxw;
1155 break;
1157 case FitPage:
1158 maxw = state.w;
1159 break;
1161 case FitWidth:
1162 break;
1164 default:
1165 ARSERT (0 && state.fitmodel);
1168 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1169 fz_rect rect;
1170 fz_matrix tm, sm;
1172 p = &state.pagedims[pindex];
1173 fz_rotate (&ctm, state.rotate);
1174 fz_rotate (&rm, p->rotate + state.rotate);
1175 box = p->mediabox;
1176 fz_transform_rect (&box, &rm);
1177 w = box.x1 - box.x0;
1178 switch (state.fitmodel) {
1179 case FitProportional:
1180 p->left = ((maxw - w) * zoom) / 2.0;
1181 break;
1182 case FitPage:
1184 double zh, h;
1185 zw = maxw / w;
1186 h = box.y1 - box.y0;
1187 zh = state.h / h;
1188 zoom = fz_min (zw, zh);
1189 p->left = (maxw - (w * zoom)) / 2.0;
1191 break;
1192 case FitWidth:
1193 p->left = 0;
1194 zoom = state.w / w;
1195 break;
1198 fz_scale (&p->zoomctm, zoom, zoom);
1199 fz_concat (&ctm, &p->zoomctm, &ctm);
1201 fz_rotate (&rm, p->rotate);
1202 p->pagebox = p->mediabox;
1203 fz_transform_rect (&p->pagebox, &rm);
1204 p->pagebox.x1 -= p->pagebox.x0;
1205 p->pagebox.y1 -= p->pagebox.y0;
1206 p->pagebox.x0 = 0;
1207 p->pagebox.y0 = 0;
1208 rect = p->pagebox;
1209 fz_transform_rect (&rect, &ctm);
1210 fz_round_rect (&p->bounds, &rect);
1211 p->ctm = ctm;
1213 fz_translate (&tm, 0, -p->mediabox.y1);
1214 fz_scale (&sm, zoom, -zoom);
1215 fz_concat (&ctm, &tm, &sm);
1217 p->tctmready = 0;
1220 do {
1221 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1222 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1223 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1224 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1225 int boundw = x1 - x0;
1226 int boundh = y1 - y0;
1228 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1229 } while (p-- != state.pagedims);
1232 struct pagedim *pdimofpageno (int pageno)
1234 struct pagedim *pdim = state.pagedims;
1236 for (int 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 glGenTextures (texcount - state.texcount,
1553 state.texids + state.texcount);
1554 for (int i = state.texcount; i < texcount; ++i) {
1555 state.texowners[i].w = -1;
1556 state.texowners[i].slice = NULL;
1559 state.texcount = texcount;
1560 state.texindex = 0;
1563 static char *mbtoutf8 (char *s)
1565 char *p, *r;
1566 wchar_t *tmp;
1567 size_t i, ret, len;
1569 len = mbstowcs (NULL, s, strlen (s));
1570 if (len == 0) {
1571 return s;
1573 else {
1574 if (len == (size_t) -1) {
1575 return s;
1579 tmp = malloc (len * sizeof (wchar_t));
1580 if (!tmp) {
1581 return s;
1584 ret = mbstowcs (tmp, s, len);
1585 if (ret == (size_t) -1) {
1586 free (tmp);
1587 return s;
1590 len = 0;
1591 for (i = 0; i < ret; ++i) {
1592 len += fz_runelen (tmp[i]);
1595 p = r = malloc (len + 1);
1596 if (!r) {
1597 free (tmp);
1598 return s;
1601 for (i = 0; i < ret; ++i) {
1602 p += fz_runetochar (p, tmp[i]);
1604 *p = 0;
1605 free (tmp);
1606 return r;
1609 CAMLprim value ml_mbtoutf8 (value s_v)
1611 CAMLparam1 (s_v);
1612 CAMLlocal1 (ret_v);
1613 char *s, *r;
1615 s = String_val (s_v);
1616 r = mbtoutf8 (s);
1617 if (r == s) {
1618 ret_v = s_v;
1620 else {
1621 ret_v = caml_copy_string (r);
1622 free (r);
1624 CAMLreturn (ret_v);
1627 static void * mainloop (void UNUSED_ATTR *unused)
1629 char *p = NULL;
1630 int len, ret, oldlen = 0;
1632 fz_var (p);
1633 fz_var (oldlen);
1634 for (;;) {
1635 len = readlen (state.csock);
1636 if (len == 0) {
1637 errx (1, "readlen returned 0");
1640 if (oldlen < len + 1) {
1641 p = realloc (p, len + 1);
1642 if (!p) {
1643 err (1, "realloc %d failed", len + 1);
1645 oldlen = len + 1;
1647 readdata (state.csock, p, len);
1648 p[len] = 0;
1650 if (!strncmp ("open", p, 4)) {
1651 int wthack, off, usedoccss, ok = 0;
1652 char *password;
1653 char *filename;
1654 char *utf8filename;
1655 size_t filenamelen;
1657 fz_var (ok);
1658 ret = sscanf (p + 5, " %d %d %d %n",
1659 &wthack, &state.cxack, &usedoccss, &off);
1660 if (ret != 3) {
1661 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1664 filename = p + 5 + off;
1665 filenamelen = strlen (filename);
1666 password = filename + filenamelen + 1;
1668 if (password[strlen (password) + 1]) {
1669 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1672 lock ("open");
1673 fz_set_use_document_css (state.ctx, usedoccss);
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 state.w = w;
1771 for (int i = 0; i < state.texcount; ++i) {
1772 state.texowners[i].slice = NULL;
1775 state.fitmodel = fitmodel;
1776 layout ();
1777 process_outline ();
1779 state.gen++;
1780 unlock ("geometry");
1781 printd ("continue %d", state.pagecount);
1783 else if (!strncmp ("reqlayout", p, 9)) {
1784 char *nameddest;
1785 int rotate, off, h;
1786 unsigned int fitmodel;
1787 pdf_document *pdf;
1789 printd ("clear");
1790 ret = sscanf (p + 9, " %d %u %d %n",
1791 &rotate, &fitmodel, &h, &off);
1792 if (ret != 3) {
1793 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1795 lock ("reqlayout");
1796 pdf = pdf_specifics (state.ctx, state.doc);
1797 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1798 state.gen += 1;
1800 state.rotate = rotate;
1801 state.fitmodel = fitmodel;
1802 state.h = h;
1803 layout ();
1804 process_outline ();
1806 nameddest = p + 9 + off;
1807 if (pdf && nameddest && *nameddest) {
1808 fz_point xy;
1809 struct pagedim *pdim;
1810 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1811 &xy.x, &xy.y);
1812 pdim = pdimofpageno (pageno);
1813 fz_transform_point (&xy, &pdim->ctm);
1814 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1817 state.gen++;
1818 unlock ("reqlayout");
1819 printd ("continue %d", state.pagecount);
1821 else if (!strncmp ("page", p, 4)) {
1822 double a, b;
1823 struct page *page;
1824 int pageno, pindex;
1826 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1827 if (ret != 2) {
1828 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1831 lock ("page");
1832 a = now ();
1833 page = loadpage (pageno, pindex);
1834 b = now ();
1835 unlock ("page");
1837 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1839 else if (!strncmp ("tile", p, 4)) {
1840 int x, y, w, h;
1841 struct page *page;
1842 struct tile *tile;
1843 double a, b;
1844 void *data;
1846 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1847 SCN_ptr_cast (&page), &x, &y, &w, &h,
1848 SCN_ptr_cast (&data));
1849 if (ret != 6) {
1850 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1853 lock ("tile");
1854 a = now ();
1855 tile = rendertile (page, x, y, w, h, data);
1856 b = now ();
1857 unlock ("tile");
1859 printd ("tile %d %d %" FMT_ptr " %u %f",
1860 x, y,
1861 FMT_ptr_cast (tile),
1862 tile->w * tile->h * tile->pixmap->n,
1863 b - a);
1865 else if (!strncmp ("trimset", p, 7)) {
1866 fz_irect fuzz;
1867 int trimmargins;
1869 ret = sscanf (p + 7, " %d %d %d %d %d",
1870 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1871 if (ret != 5) {
1872 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1874 lock ("trimset");
1875 state.trimmargins = trimmargins;
1876 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1877 state.trimanew = 1;
1878 state.trimfuzz = fuzz;
1880 unlock ("trimset");
1882 else if (!strncmp ("settrim", p, 7)) {
1883 fz_irect fuzz;
1884 int trimmargins;
1886 ret = sscanf (p + 7, " %d %d %d %d %d",
1887 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1888 if (ret != 5) {
1889 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1891 printd ("clear");
1892 lock ("settrim");
1893 state.trimmargins = trimmargins;
1894 state.needoutline = 1;
1895 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1896 state.trimanew = 1;
1897 state.trimfuzz = fuzz;
1899 state.pagedimcount = 0;
1900 free (state.pagedims);
1901 state.pagedims = NULL;
1902 initpdims (0);
1903 layout ();
1904 process_outline ();
1905 unlock ("settrim");
1906 printd ("continue %d", state.pagecount);
1908 else if (!strncmp ("sliceh", p, 6)) {
1909 int h;
1911 ret = sscanf (p + 6, " %d", &h);
1912 if (ret != 1) {
1913 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1915 if (h != state.sliceheight) {
1916 state.sliceheight = h;
1917 for (int i = 0; i < state.texcount; ++i) {
1918 state.texowners[i].w = -1;
1919 state.texowners[i].h = -1;
1920 state.texowners[i].slice = NULL;
1924 else if (!strncmp ("interrupt", p, 9)) {
1925 printd ("vmsg interrupted");
1927 else {
1928 errx (1, "unknown command %.*s", len, p);
1931 return 0;
1934 CAMLprim value ml_isexternallink (value uri_v)
1936 CAMLparam1 (uri_v);
1937 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1938 CAMLreturn (Val_bool (ext));
1941 CAMLprim value ml_uritolocation (value uri_v)
1943 CAMLparam1 (uri_v);
1944 CAMLlocal1 (ret_v);
1945 int pageno;
1946 fz_point xy;
1947 struct pagedim *pdim;
1949 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1950 &xy.x, &xy.y);
1951 pdim = pdimofpageno (pageno);
1952 fz_transform_point (&xy, &pdim->ctm);
1953 ret_v = caml_alloc_tuple (3);
1954 Field (ret_v, 0) = Val_int (pageno);
1955 Field (ret_v, 1) = caml_copy_double (xy.x);
1956 Field (ret_v, 2) = caml_copy_double (xy.y);
1957 CAMLreturn (ret_v);
1960 CAMLprim value ml_realloctexts (value texcount_v)
1962 CAMLparam1 (texcount_v);
1963 int ok;
1965 if (trylock (__func__)) {
1966 ok = 0;
1967 goto done;
1969 realloctexts (Int_val (texcount_v));
1970 ok = 1;
1971 unlock (__func__);
1973 done:
1974 CAMLreturn (Val_bool (ok));
1977 static void recti (int x0, int y0, int x1, int y1)
1979 GLfloat *v = state.vertices;
1981 glVertexPointer (2, GL_FLOAT, 0, v);
1982 v[0] = x0; v[1] = y0;
1983 v[2] = x1; v[3] = y0;
1984 v[4] = x0; v[5] = y1;
1985 v[6] = x1; v[7] = y1;
1986 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1989 static void showsel (struct page *page, int ox, int oy)
1991 int seen = 0;
1992 fz_irect bbox;
1993 fz_rect rect;
1994 fz_stext_line *line;
1995 fz_page_block *pageb;
1996 fz_stext_block *block;
1997 struct mark first, last;
1998 unsigned char selcolor[] = {15,15,15,140};
2000 first = page->fmark;
2001 last = page->lmark;
2003 if (!first.span || !last.span) return;
2005 glEnable (GL_BLEND);
2006 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2007 glColor4ubv (selcolor);
2009 ox += state.pagedims[page->pdimno].bounds.x0;
2010 oy += state.pagedims[page->pdimno].bounds.y0;
2011 for (pageb = page->text->blocks;
2012 pageb < page->text->blocks + page->text->len;
2013 ++pageb) {
2014 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2015 block = pageb->u.text;
2017 for (line = block->lines;
2018 line < block->lines + block->len;
2019 ++line) {
2020 fz_stext_span *span;
2021 rect = fz_empty_rect;
2023 for (span = line->first_span; span; span = span->next) {
2024 int i, j, k;
2025 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2027 j = 0;
2028 k = span->len - 1;
2030 if (span == page->fmark.span && span == page->lmark.span) {
2031 seen = 1;
2032 j = fz_mini (first.i, last.i);
2033 k = fz_maxi (first.i, last.i);
2035 else {
2036 if (span == first.span) {
2037 seen = 1;
2038 j = first.i;
2040 else if (span == last.span) {
2041 seen = 1;
2042 k = last.i;
2046 if (seen) {
2047 for (i = j; i <= k; ++i) {
2048 fz_rect bbox1;
2049 fz_union_rect (&rect,
2050 fz_stext_char_bbox (state.ctx, &bbox1,
2051 span, i));
2053 fz_round_rect (&bbox, &rect);
2054 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2055 bbox.x0,
2056 bbox.y0,
2057 bbox.x1,
2058 bbox.y1,
2059 oy, ox);
2061 recti (bbox.x0 + ox, bbox.y0 + oy,
2062 bbox.x1 + ox, bbox.y1 + oy);
2063 if (span == last.span) {
2064 goto done;
2066 rect = fz_empty_rect;
2071 done:
2072 glDisable (GL_BLEND);
2075 #include "glfont.c"
2077 static void stipplerect (fz_matrix *m,
2078 fz_point *p1,
2079 fz_point *p2,
2080 fz_point *p3,
2081 fz_point *p4,
2082 GLfloat *texcoords,
2083 GLfloat *vertices)
2085 fz_transform_point (p1, m);
2086 fz_transform_point (p2, m);
2087 fz_transform_point (p3, m);
2088 fz_transform_point (p4, m);
2090 float w, h, s, t;
2092 w = p2->x - p1->x;
2093 h = p2->y - p1->y;
2094 t = hypotf (w, h) * .25f;
2096 w = p3->x - p2->x;
2097 h = p3->y - p2->y;
2098 s = hypotf (w, h) * .25f;
2100 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2101 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2103 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2104 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2106 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2107 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2109 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2110 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2112 glDrawArrays (GL_LINES, 0, 8);
2115 static void solidrect (fz_matrix *m,
2116 fz_point *p1,
2117 fz_point *p2,
2118 fz_point *p3,
2119 fz_point *p4,
2120 GLfloat *vertices)
2122 fz_transform_point (p1, m);
2123 fz_transform_point (p2, m);
2124 fz_transform_point (p3, m);
2125 fz_transform_point (p4, m);
2126 vertices[0] = p1->x; vertices[1] = p1->y;
2127 vertices[2] = p2->x; vertices[3] = p2->y;
2129 vertices[4] = p3->x; vertices[5] = p3->y;
2130 vertices[6] = p4->x; vertices[7] = p4->y;
2131 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2134 static void highlightlinks (struct page *page, int xoff, int yoff)
2136 fz_matrix ctm, tm, pm;
2137 fz_link *link, *links;
2138 GLfloat *texcoords = state.texcoords;
2139 GLfloat *vertices = state.vertices;
2141 links = fz_load_links (state.ctx, page->fzpage);
2143 glEnable (GL_TEXTURE_1D);
2144 glEnable (GL_BLEND);
2145 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2146 glBindTexture (GL_TEXTURE_1D, state.stid);
2148 xoff -= state.pagedims[page->pdimno].bounds.x0;
2149 yoff -= state.pagedims[page->pdimno].bounds.y0;
2150 fz_translate (&tm, xoff, yoff);
2151 pm = pagectm (page);
2152 fz_concat (&ctm, &pm, &tm);
2154 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2155 glVertexPointer (2, GL_FLOAT, 0, vertices);
2157 for (link = links; link; link = link->next) {
2158 fz_point p1, p2, p3, p4;
2160 p1.x = link->rect.x0;
2161 p1.y = link->rect.y0;
2163 p2.x = link->rect.x1;
2164 p2.y = link->rect.y0;
2166 p3.x = link->rect.x1;
2167 p3.y = link->rect.y1;
2169 p4.x = link->rect.x0;
2170 p4.y = link->rect.y1;
2172 /* TODO: different colours for different schemes */
2173 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2174 else glColor3ub (255, 0, 0);
2176 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2179 for (int i = 0; i < page->annotcount; ++i) {
2180 fz_point p1, p2, p3, p4;
2181 struct annot *annot = &page->annots[i];
2183 p1.x = annot->bbox.x0;
2184 p1.y = annot->bbox.y0;
2186 p2.x = annot->bbox.x1;
2187 p2.y = annot->bbox.y0;
2189 p3.x = annot->bbox.x1;
2190 p3.y = annot->bbox.y1;
2192 p4.x = annot->bbox.x0;
2193 p4.y = annot->bbox.y1;
2195 glColor3ub (0, 0, 128);
2196 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2199 glDisable (GL_BLEND);
2200 glDisable (GL_TEXTURE_1D);
2203 static int compareslinks (const void *l, const void *r)
2205 struct slink const *ls = l;
2206 struct slink const *rs = r;
2207 if (ls->bbox.y0 == rs->bbox.y0) {
2208 return rs->bbox.x0 - rs->bbox.x0;
2210 return ls->bbox.y0 - rs->bbox.y0;
2213 static void droptext (struct page *page)
2215 if (page->text) {
2216 fz_drop_stext_page (state.ctx, page->text);
2217 page->fmark.i = -1;
2218 page->lmark.i = -1;
2219 page->fmark.span = NULL;
2220 page->lmark.span = NULL;
2221 page->text = NULL;
2223 if (page->sheet) {
2224 fz_drop_stext_sheet (state.ctx, page->sheet);
2225 page->sheet = NULL;
2229 static void dropannots (struct page *page)
2231 if (page->annots) {
2232 free (page->annots);
2233 page->annots = NULL;
2234 page->annotcount = 0;
2238 static void ensureannots (struct page *page)
2240 int i, count = 0;
2241 size_t annotsize = sizeof (*page->annots);
2242 fz_annot *annot;
2244 if (state.gen != page->agen) {
2245 dropannots (page);
2246 page->agen = state.gen;
2248 if (page->annots) return;
2250 for (annot = fz_first_annot (state.ctx, page->fzpage);
2251 annot;
2252 annot = fz_next_annot (state.ctx, annot)) {
2253 count++;
2256 if (count > 0) {
2257 page->annotcount = count;
2258 page->annots = calloc (count, annotsize);
2259 if (!page->annots) {
2260 err (1, "calloc annots %d", count);
2263 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2264 annot;
2265 annot = fz_next_annot (state.ctx, annot), i++) {
2266 fz_rect rect;
2268 fz_bound_annot (state.ctx, annot, &rect);
2269 page->annots[i].annot = annot;
2270 fz_round_rect (&page->annots[i].bbox, &rect);
2275 static void dropslinks (struct page *page)
2277 if (page->slinks) {
2278 free (page->slinks);
2279 page->slinks = NULL;
2280 page->slinkcount = 0;
2284 static void ensureslinks (struct page *page)
2286 fz_matrix ctm;
2287 int i, count;
2288 size_t slinksize = sizeof (*page->slinks);
2289 fz_link *link, *links;
2291 ensureannots (page);
2292 if (state.gen != page->sgen) {
2293 dropslinks (page);
2294 page->sgen = state.gen;
2296 if (page->slinks) return;
2298 links = fz_load_links (state.ctx, page->fzpage);
2299 ctm = pagectm (page);
2301 count = page->annotcount;
2302 for (link = links; link; link = link->next) {
2303 count++;
2305 if (count > 0) {
2306 int j;
2308 page->slinkcount = count;
2309 page->slinks = calloc (count, slinksize);
2310 if (!page->slinks) {
2311 err (1, "calloc slinks %d", count);
2314 for (i = 0, link = links; link; ++i, link = link->next) {
2315 fz_rect rect;
2317 rect = link->rect;
2318 fz_transform_rect (&rect, &ctm);
2319 page->slinks[i].tag = SLINK;
2320 page->slinks[i].u.link = link;
2321 fz_round_rect (&page->slinks[i].bbox, &rect);
2323 for (j = 0; j < page->annotcount; ++j, ++i) {
2324 fz_rect rect;
2325 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2326 fz_transform_rect (&rect, &ctm);
2327 fz_round_rect (&page->slinks[i].bbox, &rect);
2329 page->slinks[i].tag = SANNOT;
2330 page->slinks[i].u.annot = page->annots[j].annot;
2332 qsort (page->slinks, count, slinksize, compareslinks);
2336 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2337 static void fmt_linkn (char *s, unsigned int u)
2339 unsigned int len; unsigned int q;
2340 unsigned int zma = 'z' - 'a' + 1;
2341 len = 1; q = u;
2342 while (q > zma - 1) { ++len; q /= zma; }
2343 if (s) {
2344 s += len;
2345 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2346 /* handles u == 0 */
2348 s[len] = 0;
2351 static void highlightslinks (struct page *page, int xoff, int yoff,
2352 int noff, char *targ, int tlen, int hfsize)
2354 char buf[40];
2355 struct slink *slink;
2356 double x0, y0, x1, y1, w;
2358 ensureslinks (page);
2359 glColor3ub (0xc3, 0xb0, 0x91);
2360 for (int i = 0; i < page->slinkcount; ++i) {
2361 fmt_linkn (buf, i + noff);
2362 if (!tlen || !strncmp (targ, buf, tlen)) {
2363 slink = &page->slinks[i];
2365 x0 = slink->bbox.x0 + xoff - 5;
2366 y1 = slink->bbox.y0 + yoff - 5;
2367 y0 = y1 + 10 + hfsize;
2368 w = measure_string (state.face, hfsize, buf);
2369 x1 = x0 + w + 10;
2370 recti (x0, y0, x1, y1);
2374 glEnable (GL_BLEND);
2375 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2376 glEnable (GL_TEXTURE_2D);
2377 glColor3ub (0, 0, 0);
2378 for (int i = 0; i < page->slinkcount; ++i) {
2379 fmt_linkn (buf, i + noff);
2380 if (!tlen || !strncmp (targ, buf, tlen)) {
2381 slink = &page->slinks[i];
2383 x0 = slink->bbox.x0 + xoff;
2384 y0 = slink->bbox.y0 + yoff + hfsize;
2385 draw_string (state.face, hfsize, x0, y0, buf);
2388 glDisable (GL_TEXTURE_2D);
2389 glDisable (GL_BLEND);
2392 static void uploadslice (struct tile *tile, struct slice *slice)
2394 int offset;
2395 struct slice *slice1;
2396 unsigned char *texdata;
2398 offset = 0;
2399 for (slice1 = tile->slices; slice != slice1; slice1++) {
2400 offset += slice1->h * tile->w * tile->pixmap->n;
2402 if (slice->texindex != -1 && slice->texindex < state.texcount
2403 && state.texowners[slice->texindex].slice == slice) {
2404 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2406 else {
2407 int subimage = 0;
2408 int texindex = state.texindex++ % state.texcount;
2410 if (state.texowners[texindex].w == tile->w) {
2411 if (state.texowners[texindex].h >= slice->h) {
2412 subimage = 1;
2414 else {
2415 state.texowners[texindex].h = slice->h;
2418 else {
2419 state.texowners[texindex].h = slice->h;
2422 state.texowners[texindex].w = tile->w;
2423 state.texowners[texindex].slice = slice;
2424 slice->texindex = texindex;
2426 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2427 #if TEXT_TYPE == GL_TEXTURE_2D
2428 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2429 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2430 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2431 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2432 #endif
2433 if (tile->pbo) {
2434 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2435 texdata = 0;
2437 else {
2438 texdata = tile->pixmap->samples;
2440 if (subimage) {
2441 glTexSubImage2D (TEXT_TYPE,
2445 tile->w,
2446 slice->h,
2447 state.texform,
2448 state.texty,
2449 texdata+offset
2452 else {
2453 glTexImage2D (TEXT_TYPE,
2455 state.texiform,
2456 tile->w,
2457 slice->h,
2459 state.texform,
2460 state.texty,
2461 texdata+offset
2464 if (tile->pbo) {
2465 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2470 CAMLprim value ml_begintiles (value unit_v)
2472 CAMLparam1 (unit_v);
2473 glEnable (TEXT_TYPE);
2474 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2475 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2476 CAMLreturn (unit_v);
2479 CAMLprim value ml_endtiles (value unit_v)
2481 CAMLparam1 (unit_v);
2482 glDisable (TEXT_TYPE);
2483 CAMLreturn (unit_v);
2486 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2488 CAMLparam2 (args_v, ptr_v);
2489 int dispx = Int_val (Field (args_v, 0));
2490 int dispy = Int_val (Field (args_v, 1));
2491 int dispw = Int_val (Field (args_v, 2));
2492 int disph = Int_val (Field (args_v, 3));
2493 int tilex = Int_val (Field (args_v, 4));
2494 int tiley = Int_val (Field (args_v, 5));
2495 char *s = String_val (ptr_v);
2496 struct tile *tile = parse_pointer (__func__, s);
2497 int slicey, firstslice;
2498 struct slice *slice;
2499 GLfloat *texcoords = state.texcoords;
2500 GLfloat *vertices = state.vertices;
2502 firstslice = tiley / tile->sliceheight;
2503 slice = &tile->slices[firstslice];
2504 slicey = tiley % tile->sliceheight;
2506 while (disph > 0) {
2507 int dh;
2509 dh = slice->h - slicey;
2510 dh = fz_mini (disph, dh);
2511 uploadslice (tile, slice);
2513 texcoords[0] = tilex; texcoords[1] = slicey;
2514 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2515 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2516 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2518 vertices[0] = dispx; vertices[1] = dispy;
2519 vertices[2] = dispx+dispw; vertices[3] = dispy;
2520 vertices[4] = dispx; vertices[5] = dispy+dh;
2521 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2523 #if TEXT_TYPE == GL_TEXTURE_2D
2524 for (int i = 0; i < 8; ++i) {
2525 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2527 #endif
2529 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2530 dispy += dh;
2531 disph -= dh;
2532 slice++;
2533 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2534 slicey = 0;
2536 CAMLreturn0;
2539 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2541 fz_matrix ctm, tm, pm;
2542 fz_point p1, p2, p3, p4;
2543 GLfloat *vertices = state.vertices;
2544 double *v = (double *) rects_v;
2546 xoff -= state.pagedims[page->pdimno].bounds.x0;
2547 yoff -= state.pagedims[page->pdimno].bounds.y0;
2548 fz_translate (&tm, xoff, yoff);
2549 pm = pagectm (page);
2550 fz_concat (&ctm, &pm, &tm);
2552 glEnable (GL_BLEND);
2553 glVertexPointer (2, GL_FLOAT, 0, vertices);
2555 glColor4dv (v);
2556 p1.x = v[4];
2557 p1.y = v[5];
2559 p2.x = v[6];
2560 p2.y = v[5];
2562 p3.x = v[6];
2563 p3.y = v[7];
2565 p4.x = v[4];
2566 p4.y = v[7];
2567 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2568 glDisable (GL_BLEND);
2571 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2572 value xoff_v, value yoff_v,
2573 value li_v)
2575 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2576 int xoff = Int_val (xoff_v);
2577 int yoff = Int_val (yoff_v);
2578 int noff = Int_val (Field (li_v, 0));
2579 char *targ = String_val (Field (li_v, 1));
2580 int tlen = caml_string_length (Field (li_v, 1));
2581 int hfsize = Int_val (Field (li_v, 2));
2582 char *s = String_val (ptr_v);
2583 int hlmask = Int_val (hlinks_v);
2584 struct page *page = parse_pointer (__func__, s);
2586 if (!page->fzpage) {
2587 /* deal with loadpage failed pages */
2588 goto done;
2591 if (trylock (__func__)) {
2592 noff = -1;
2593 goto done;
2596 ensureannots (page);
2597 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2598 if (hlmask & 2) {
2599 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2600 noff = page->slinkcount;
2602 if (page->tgen == state.gen) {
2603 showsel (page, xoff, yoff);
2605 unlock (__func__);
2607 done:
2608 CAMLreturn (Val_int (noff));
2611 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2612 value rects_v)
2614 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2615 int xoff = Int_val (xoff_v);
2616 int yoff = Int_val (yoff_v);
2617 char *s = String_val (ptr_v);
2618 struct page *page = parse_pointer (__func__, s);
2620 drawprect (page, xoff, yoff, rects_v);
2621 CAMLreturn0;
2624 static struct annot *getannot (struct page *page, int x, int y)
2626 fz_point p;
2627 fz_matrix ctm;
2628 const fz_matrix *tctm;
2629 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2631 if (!page->annots) return NULL;
2633 if (pdf) {
2634 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2635 tctm = &state.pagedims[page->pdimno].tctm;
2637 else {
2638 tctm = &fz_identity;
2641 p.x = x;
2642 p.y = y;
2644 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2645 fz_invert_matrix (&ctm, &ctm);
2646 fz_transform_point (&p, &ctm);
2648 if (pdf) {
2649 for (int i = 0; i < page->annotcount; ++i) {
2650 struct annot *a = &page->annots[i];
2651 fz_rect rect;
2653 fz_bound_annot (state.ctx, a->annot, &rect);
2654 if (p.x >= rect.x0 && p.x <= rect.x1) {
2655 if (p.y >= rect.y0 && p.y <= rect.y1)
2656 return a;
2660 return NULL;
2663 static fz_link *getlink (struct page *page, int x, int y)
2665 fz_point p;
2666 fz_matrix ctm;
2667 fz_link *link, *links;
2669 links = fz_load_links (state.ctx, page->fzpage);
2671 p.x = x;
2672 p.y = y;
2674 ctm = pagectm (page);
2675 fz_invert_matrix (&ctm, &ctm);
2676 fz_transform_point (&p, &ctm);
2678 for (link = links; link; link = link->next) {
2679 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2680 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2681 return link;
2685 return NULL;
2688 static void ensuretext (struct page *page)
2690 if (state.gen != page->tgen) {
2691 droptext (page);
2692 page->tgen = state.gen;
2694 if (!page->text) {
2695 fz_matrix ctm;
2696 fz_device *tdev;
2698 page->text = fz_new_stext_page (state.ctx,
2699 &state.pagedims[page->pdimno].mediabox);
2700 page->sheet = fz_new_stext_sheet (state.ctx);
2701 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2702 ctm = pagectm (page);
2703 fz_run_display_list (state.ctx, page->dlist,
2704 tdev, &ctm, &fz_infinite_rect, NULL);
2705 qsort (page->text->blocks, page->text->len,
2706 sizeof (*page->text->blocks), compareblocks);
2707 fz_close_device (state.ctx, tdev);
2708 fz_drop_device (state.ctx, tdev);
2712 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2714 CAMLparam2 (start_page_v, dir_v);
2715 CAMLlocal1 (ret_v);
2716 int i, dir = Int_val (dir_v);
2717 int start_page = Int_val (start_page_v);
2718 int end_page = dir > 0 ? state.pagecount : -1;
2719 pdf_document *pdf;
2721 fz_var (end_page);
2722 ret_v = Val_int (0);
2723 lock (__func__);
2724 pdf = pdf_specifics (state.ctx, state.doc);
2725 for (i = start_page + dir; i != end_page; i += dir) {
2726 int found;
2728 fz_var (found);
2729 if (pdf) {
2730 pdf_page *page = NULL;
2732 fz_var (page);
2733 fz_try (state.ctx) {
2734 page = pdf_load_page (state.ctx, pdf, i);
2735 found = !!page->links || !!page->annots;
2737 fz_catch (state.ctx) {
2738 found = 0;
2740 if (page) {
2741 fz_drop_page (state.ctx, &page->super);
2744 else {
2745 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2746 found = !!fz_load_links (state.ctx, page);
2747 fz_drop_page (state.ctx, page);
2750 if (found) {
2751 ret_v = caml_alloc_small (1, 1);
2752 Field (ret_v, 0) = Val_int (i);
2753 goto unlock;
2756 unlock:
2757 unlock (__func__);
2758 CAMLreturn (ret_v);
2761 enum { dir_first, dir_last };
2762 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2764 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2766 CAMLparam2 (ptr_v, dir_v);
2767 CAMLlocal2 (ret_v, pos_v);
2768 struct page *page;
2769 int dirtag, i, slinkindex;
2770 struct slink *found = NULL ,*slink;
2771 char *s = String_val (ptr_v);
2773 page = parse_pointer (__func__, s);
2774 ret_v = Val_int (0);
2775 lock (__func__);
2776 ensureslinks (page);
2778 if (Is_block (dir_v)) {
2779 dirtag = Tag_val (dir_v);
2780 switch (dirtag) {
2781 case dir_first_visible:
2783 int x0, y0, dir, first_index, last_index;
2785 pos_v = Field (dir_v, 0);
2786 x0 = Int_val (Field (pos_v, 0));
2787 y0 = Int_val (Field (pos_v, 1));
2788 dir = Int_val (Field (pos_v, 2));
2790 if (dir >= 0) {
2791 dir = 1;
2792 first_index = 0;
2793 last_index = page->slinkcount;
2795 else {
2796 first_index = page->slinkcount - 1;
2797 last_index = -1;
2800 for (i = first_index; i != last_index; i += dir) {
2801 slink = &page->slinks[i];
2802 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2803 found = slink;
2804 break;
2808 break;
2810 case dir_left:
2811 slinkindex = Int_val (Field (dir_v, 0));
2812 found = &page->slinks[slinkindex];
2813 for (i = slinkindex - 1; i >= 0; --i) {
2814 slink = &page->slinks[i];
2815 if (slink->bbox.x0 < found->bbox.x0) {
2816 found = slink;
2817 break;
2820 break;
2822 case dir_right:
2823 slinkindex = Int_val (Field (dir_v, 0));
2824 found = &page->slinks[slinkindex];
2825 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2826 slink = &page->slinks[i];
2827 if (slink->bbox.x0 > found->bbox.x0) {
2828 found = slink;
2829 break;
2832 break;
2834 case dir_down:
2835 slinkindex = Int_val (Field (dir_v, 0));
2836 found = &page->slinks[slinkindex];
2837 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2838 slink = &page->slinks[i];
2839 if (slink->bbox.y0 >= found->bbox.y0) {
2840 found = slink;
2841 break;
2844 break;
2846 case dir_up:
2847 slinkindex = Int_val (Field (dir_v, 0));
2848 found = &page->slinks[slinkindex];
2849 for (i = slinkindex - 1; i >= 0; --i) {
2850 slink = &page->slinks[i];
2851 if (slink->bbox.y0 <= found->bbox.y0) {
2852 found = slink;
2853 break;
2856 break;
2859 else {
2860 dirtag = Int_val (dir_v);
2861 switch (dirtag) {
2862 case dir_first:
2863 found = page->slinks;
2864 break;
2866 case dir_last:
2867 if (page->slinks) {
2868 found = page->slinks + (page->slinkcount - 1);
2870 break;
2873 if (found) {
2874 ret_v = caml_alloc_small (2, 1);
2875 Field (ret_v, 0) = Val_int (found - page->slinks);
2878 unlock (__func__);
2879 CAMLreturn (ret_v);
2882 enum { uuri, utext, uannot };
2884 CAMLprim value ml_getlink (value ptr_v, value n_v)
2886 CAMLparam2 (ptr_v, n_v);
2887 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2888 fz_link *link;
2889 struct page *page;
2890 char *s = String_val (ptr_v);
2891 struct slink *slink;
2893 ret_v = Val_int (0);
2894 page = parse_pointer (__func__, s);
2896 lock (__func__);
2897 ensureslinks (page);
2898 slink = &page->slinks[Int_val (n_v)];
2899 if (slink->tag == SLINK) {
2900 link = slink->u.link;
2901 str_v = caml_copy_string (link->uri);
2902 ret_v = caml_alloc_small (1, uuri);
2903 Field (ret_v, 0) = str_v;
2905 else {
2906 ret_v = caml_alloc_small (1, uannot);
2907 tup_v = caml_alloc_tuple (2);
2908 Field (ret_v, 0) = tup_v;
2909 Field (tup_v, 0) = ptr_v;
2910 Field (tup_v, 1) = n_v;
2912 unlock (__func__);
2914 CAMLreturn (ret_v);
2917 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2919 CAMLparam2 (ptr_v, n_v);
2920 pdf_document *pdf;
2921 const char *contents = "";
2923 lock (__func__);
2924 pdf = pdf_specifics (state.ctx, state.doc);
2925 if (pdf) {
2926 char *s = String_val (ptr_v);
2927 struct page *page;
2928 struct slink *slink;
2930 page = parse_pointer (__func__, s);
2931 slink = &page->slinks[Int_val (n_v)];
2932 contents = pdf_annot_contents (state.ctx,
2933 (pdf_annot *) slink->u.annot);
2935 unlock (__func__);
2936 CAMLreturn (caml_copy_string (contents));
2939 CAMLprim value ml_getlinkcount (value ptr_v)
2941 CAMLparam1 (ptr_v);
2942 struct page *page;
2943 char *s = String_val (ptr_v);
2945 page = parse_pointer (__func__, s);
2946 CAMLreturn (Val_int (page->slinkcount));
2949 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2951 CAMLparam2 (ptr_v, n_v);
2952 CAMLlocal1 (ret_v);
2953 struct page *page;
2954 struct slink *slink;
2955 char *s = String_val (ptr_v);
2957 page = parse_pointer (__func__, s);
2958 ret_v = caml_alloc_tuple (4);
2959 lock (__func__);
2960 ensureslinks (page);
2962 slink = &page->slinks[Int_val (n_v)];
2963 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2964 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2965 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2966 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2967 unlock (__func__);
2968 CAMLreturn (ret_v);
2971 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2973 CAMLparam3 (ptr_v, x_v, y_v);
2974 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2975 fz_link *link;
2976 struct annot *annot;
2977 struct page *page;
2978 char *ptr = String_val (ptr_v);
2979 int x = Int_val (x_v), y = Int_val (y_v);
2980 struct pagedim *pdim;
2982 ret_v = Val_int (0);
2983 if (trylock (__func__)) {
2984 goto done;
2987 page = parse_pointer (__func__, ptr);
2988 pdim = &state.pagedims[page->pdimno];
2989 x += pdim->bounds.x0;
2990 y += pdim->bounds.y0;
2993 annot = getannot (page, x, y);
2994 if (annot) {
2995 int i, n = -1;
2997 ensureslinks (page);
2998 for (i = 0; i < page->slinkcount; ++i) {
2999 if (page->slinks[i].tag == SANNOT
3000 && page->slinks[i].u.annot == annot->annot) {
3001 n = i;
3002 break;
3005 ret_v = caml_alloc_small (1, uannot);
3006 tup_v = caml_alloc_tuple (2);
3007 Field (ret_v, 0) = tup_v;
3008 Field (tup_v, 0) = ptr_v;
3009 Field (tup_v, 1) = Val_int (n);
3010 goto unlock;
3014 link = getlink (page, x, y);
3015 if (link) {
3016 str_v = caml_copy_string (link->uri);
3017 ret_v = caml_alloc_small (1, uuri);
3018 Field (ret_v, 0) = str_v;
3020 else {
3021 fz_rect *b;
3022 fz_page_block *pageb;
3023 fz_stext_block *block;
3025 ensuretext (page);
3026 for (pageb = page->text->blocks;
3027 pageb < page->text->blocks + page->text->len;
3028 ++pageb) {
3029 fz_stext_line *line;
3030 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3031 block = pageb->u.text;
3033 b = &block->bbox;
3034 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3035 continue;
3037 for (line = block->lines;
3038 line < block->lines + block->len;
3039 ++line) {
3040 fz_stext_span *span;
3042 b = &line->bbox;
3043 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3044 continue;
3046 for (span = line->first_span; span; span = span->next) {
3047 int charnum;
3049 b = &span->bbox;
3050 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3051 continue;
3053 for (charnum = 0; charnum < span->len; ++charnum) {
3054 fz_rect bbox;
3055 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3056 b = &bbox;
3058 if (x >= b->x0 && x <= b->x1
3059 && y >= b->y0 && y <= b->y1) {
3060 fz_stext_style *style = span->text->style;
3061 const char *n2 =
3062 style->font
3063 ? fz_font_name (state.ctx, style->font)
3064 : "Span has no font name"
3066 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3067 style->font);
3068 if (face && face->family_name) {
3069 char *s;
3070 char *n1 = face->family_name;
3071 size_t l1 = strlen (n1);
3072 size_t l2 = strlen (n2);
3074 if (l1 != l2 || memcmp (n1, n2, l1)) {
3075 s = malloc (l1 + l2 + 2);
3076 if (s) {
3077 memcpy (s, n2, l2);
3078 s[l2] = '=';
3079 memcpy (s + l2 + 1, n1, l1 + 1);
3080 str_v = caml_copy_string (s);
3081 free (s);
3085 if (str_v == Val_unit) {
3086 str_v = caml_copy_string (n2);
3088 ret_v = caml_alloc_small (1, utext);
3089 Field (ret_v, 0) = str_v;
3090 goto unlock;
3097 unlock:
3098 unlock (__func__);
3100 done:
3101 CAMLreturn (ret_v);
3104 enum { mark_page, mark_block, mark_line, mark_word };
3106 static int uninteresting (int c)
3108 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3109 || ispunct (c);
3112 CAMLprim void ml_clearmark (value ptr_v)
3114 CAMLparam1 (ptr_v);
3115 char *s = String_val (ptr_v);
3116 struct page *page;
3118 if (trylock (__func__)) {
3119 goto done;
3122 page = parse_pointer (__func__, s);
3123 page->fmark.span = NULL;
3124 page->lmark.span = NULL;
3125 page->fmark.i = 0;
3126 page->lmark.i = 0;
3128 unlock (__func__);
3129 done:
3130 CAMLreturn0;
3133 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3135 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3136 CAMLlocal1 (ret_v);
3137 fz_rect *b;
3138 struct page *page;
3139 fz_stext_line *line;
3140 fz_page_block *pageb;
3141 fz_stext_block *block;
3142 struct pagedim *pdim;
3143 int mark = Int_val (mark_v);
3144 char *s = String_val (ptr_v);
3145 int x = Int_val (x_v), y = Int_val (y_v);
3147 ret_v = Val_bool (0);
3148 if (trylock (__func__)) {
3149 goto done;
3152 page = parse_pointer (__func__, s);
3153 pdim = &state.pagedims[page->pdimno];
3155 ensuretext (page);
3157 if (mark == mark_page) {
3158 int i;
3159 fz_page_block *pb1 = NULL, *pb2 = NULL;
3161 for (i = 0; i < page->text->len; ++i) {
3162 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3163 pb1 = &page->text->blocks[i];
3164 break;
3167 if (!pb1) goto unlock;
3169 for (i = page->text->len - 1; i >= 0; --i) {
3170 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3171 pb2 = &page->text->blocks[i];
3172 break;
3175 if (!pb2) goto unlock;
3177 block = pb1->u.text;
3179 page->fmark.i = 0;
3180 page->fmark.span = block->lines->first_span;
3182 block = pb2->u.text;
3183 line = &block->lines[block->len - 1];
3184 page->lmark.i = line->last_span->len - 1;
3185 page->lmark.span = line->last_span;
3186 ret_v = Val_bool (1);
3187 goto unlock;
3190 x += pdim->bounds.x0;
3191 y += pdim->bounds.y0;
3193 for (pageb = page->text->blocks;
3194 pageb < page->text->blocks + page->text->len;
3195 ++pageb) {
3196 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3197 block = pageb->u.text;
3199 b = &block->bbox;
3200 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3201 continue;
3203 if (mark == mark_block) {
3204 page->fmark.i = 0;
3205 page->fmark.span = block->lines->first_span;
3207 line = &block->lines[block->len - 1];
3208 page->lmark.i = line->last_span->len - 1;
3209 page->lmark.span = line->last_span;
3210 ret_v = Val_bool (1);
3211 goto unlock;
3214 for (line = block->lines;
3215 line < block->lines + block->len;
3216 ++line) {
3217 fz_stext_span *span;
3219 b = &line->bbox;
3220 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3221 continue;
3223 if (mark == mark_line) {
3224 page->fmark.i = 0;
3225 page->fmark.span = line->first_span;
3227 page->lmark.i = line->last_span->len - 1;
3228 page->lmark.span = line->last_span;
3229 ret_v = Val_bool (1);
3230 goto unlock;
3233 for (span = line->first_span; span; span = span->next) {
3234 int charnum;
3236 b = &span->bbox;
3237 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3238 continue;
3240 for (charnum = 0; charnum < span->len; ++charnum) {
3241 fz_rect bbox;
3242 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3243 b = &bbox;
3245 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3246 /* unicode ftw */
3247 int charnum2, charnum3 = -1, charnum4 = -1;
3249 if (uninteresting (span->text[charnum].c)) goto unlock;
3251 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3252 if (uninteresting (span->text[charnum2].c)) {
3253 charnum3 = charnum2 + 1;
3254 break;
3257 if (charnum3 == -1) charnum3 = 0;
3259 charnum4 = charnum;
3260 for (charnum2 = charnum + 1;
3261 charnum2 < span->len;
3262 ++charnum2) {
3263 if (uninteresting (span->text[charnum2].c)) break;
3264 charnum4 = charnum2;
3267 page->fmark.i = charnum3;
3268 page->fmark.span = span;
3270 page->lmark.i = charnum4;
3271 page->lmark.span = span;
3272 ret_v = Val_bool (1);
3273 goto unlock;
3279 unlock:
3280 if (!Bool_val (ret_v)) {
3281 page->fmark.span = NULL;
3282 page->lmark.span = NULL;
3283 page->fmark.i = 0;
3284 page->lmark.i = 0;
3286 unlock (__func__);
3288 done:
3289 CAMLreturn (ret_v);
3292 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3294 CAMLparam3 (ptr_v, x_v, y_v);
3295 CAMLlocal2 (ret_v, res_v);
3296 fz_rect *b = NULL;
3297 struct page *page;
3298 fz_page_block *pageb;
3299 struct pagedim *pdim;
3300 char *s = String_val (ptr_v);
3301 int x = Int_val (x_v), y = Int_val (y_v);
3303 ret_v = Val_int (0);
3304 if (trylock (__func__)) {
3305 goto done;
3308 page = parse_pointer (__func__, s);
3309 pdim = &state.pagedims[page->pdimno];
3310 x += pdim->bounds.x0;
3311 y += pdim->bounds.y0;
3313 ensuretext (page);
3315 for (pageb = page->text->blocks;
3316 pageb < page->text->blocks + page->text->len;
3317 ++pageb) {
3318 switch (pageb->type) {
3319 case FZ_PAGE_BLOCK_TEXT:
3320 b = &pageb->u.text->bbox;
3321 break;
3323 case FZ_PAGE_BLOCK_IMAGE:
3324 b = &pageb->u.image->bbox;
3325 break;
3327 default:
3328 continue;
3331 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3332 break;
3333 b = NULL;
3335 if (b) {
3336 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3337 ret_v = caml_alloc_small (1, 1);
3338 Store_double_field (res_v, 0, b->x0);
3339 Store_double_field (res_v, 1, b->x1);
3340 Store_double_field (res_v, 2, b->y0);
3341 Store_double_field (res_v, 3, b->y1);
3342 Field (ret_v, 0) = res_v;
3344 unlock (__func__);
3346 done:
3347 CAMLreturn (ret_v);
3350 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3352 CAMLparam2 (ptr_v, rect_v);
3353 fz_rect b;
3354 struct page *page;
3355 struct pagedim *pdim;
3356 char *s = String_val (ptr_v);
3357 int i, x0, x1, y0, y1, fi, li;
3358 fz_stext_line *line;
3359 fz_page_block *pageb;
3360 fz_stext_block *block;
3361 fz_stext_span *span, *fspan, *lspan;
3363 if (trylock (__func__)) {
3364 goto done;
3367 page = parse_pointer (__func__, s);
3368 ensuretext (page);
3370 pdim = &state.pagedims[page->pdimno];
3371 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3372 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3373 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3374 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3376 if (y0 > y1) {
3377 int t = y0;
3378 y0 = y1;
3379 y1 = t;
3380 x0 = x1;
3381 x1 = t;
3384 fi = page->fmark.i;
3385 fspan = page->fmark.span;
3387 li = page->lmark.i;
3388 lspan = page->lmark.span;
3390 for (pageb = page->text->blocks;
3391 pageb < page->text->blocks + page->text->len;
3392 ++pageb) {
3393 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3394 block = pageb->u.text;
3395 for (line = block->lines;
3396 line < block->lines + block->len;
3397 ++line) {
3399 for (span = line->first_span; span; span = span->next) {
3400 for (i = 0; i < span->len; ++i) {
3401 fz_stext_char_bbox (state.ctx, &b, span, i);
3403 if (x0 >= b.x0 && x0 <= b.x1
3404 && y0 >= b.y0 && y0 <= b.y1) {
3405 fspan = span;
3406 fi = i;
3408 if (x1 >= b.x0 && x1 <= b.x1
3409 && y1 >= b.y0 && y1 <= b.y1) {
3410 lspan = span;
3411 li = i;
3417 if (x1 < x0 && fspan == lspan) {
3418 i = fi;
3419 span = fspan;
3421 fi = li;
3422 fspan = lspan;
3424 li = i;
3425 lspan = span;
3428 page->fmark.i = fi;
3429 page->fmark.span = fspan;
3431 page->lmark.i = li;
3432 page->lmark.span = lspan;
3434 unlock (__func__);
3436 done:
3437 CAMLreturn0;
3440 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3442 char buf[4];
3443 int i, len, ret;
3445 for (i = a; i <= b; ++i) {
3446 len = fz_runetochar (buf, span->text[i].c);
3447 ret = fwrite (buf, len, 1, f);
3449 if (ret != 1) {
3450 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3451 len, ret, strerror (errno));
3452 return -1;
3455 return 0;
3458 #ifdef __CYGWIN__
3459 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3461 caml_failwith ("ml_popen not implemented under Cygwin");
3463 #else
3464 CAMLprim value ml_spawn (value command_v, value fds_v)
3466 CAMLparam2 (command_v, fds_v);
3467 CAMLlocal2 (l_v, tup_v);
3468 int ret, ret1;
3469 pid_t pid;
3470 char *msg = NULL;
3471 value earg_v = Nothing;
3472 posix_spawnattr_t attr;
3473 posix_spawn_file_actions_t fa;
3474 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3476 argv[2] = String_val (command_v);
3478 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3479 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3482 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3483 msg = "posix_spawnattr_init";
3484 goto fail1;
3487 #ifdef POSIX_SPAWN_USEVFORK
3488 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3489 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3490 goto fail;
3492 #endif
3494 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3495 int fd1, fd2;
3497 tup_v = Field (l_v, 0);
3498 fd1 = Int_val (Field (tup_v, 0));
3499 fd2 = Int_val (Field (tup_v, 1));
3500 if (fd2 < 0) {
3501 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3502 msg = "posix_spawn_file_actions_addclose";
3503 earg_v = tup_v;
3504 goto fail;
3507 else {
3508 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3509 msg = "posix_spawn_file_actions_adddup2";
3510 earg_v = tup_v;
3511 goto fail;
3516 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3517 msg = "posix_spawn";
3518 goto fail;
3521 fail:
3522 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3523 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3526 fail1:
3527 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3528 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3529 strerror (ret1));
3532 if (msg)
3533 unix_error (ret, msg, earg_v);
3535 CAMLreturn (Val_int (pid));
3537 #endif
3539 CAMLprim value ml_hassel (value ptr_v)
3541 CAMLparam1 (ptr_v);
3542 CAMLlocal1 (ret_v);
3543 struct page *page;
3544 char *s = String_val (ptr_v);
3546 ret_v = Val_bool (0);
3547 if (trylock (__func__)) {
3548 goto done;
3551 page = parse_pointer (__func__, s);
3552 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3553 unlock (__func__);
3554 done:
3555 CAMLreturn (ret_v);
3558 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3560 CAMLparam2 (fd_v, ptr_v);
3561 FILE *f;
3562 int seen = 0;
3563 struct page *page;
3564 fz_stext_line *line;
3565 fz_page_block *pageb;
3566 fz_stext_block *block;
3567 int fd = Int_val (fd_v);
3568 char *s = String_val (ptr_v);
3570 if (trylock (__func__)) {
3571 goto done;
3574 page = parse_pointer (__func__, s);
3576 if (!page->fmark.span || !page->lmark.span) {
3577 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3578 goto unlock;
3581 f = fdopen (fd, "w");
3582 if (!f) {
3583 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3584 fd, strerror (errno));
3585 f = stdout;
3588 for (pageb = page->text->blocks;
3589 pageb < page->text->blocks + page->text->len;
3590 ++pageb) {
3591 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3592 block = pageb->u.text;
3593 for (line = block->lines;
3594 line < block->lines + block->len;
3595 ++line) {
3596 fz_stext_span *span;
3598 for (span = line->first_span; span; span = span->next) {
3599 int a, b;
3601 seen |= span == page->fmark.span || span == page->lmark.span;
3602 a = span == page->fmark.span ? page->fmark.i : 0;
3603 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3605 if (seen) {
3606 if (pipespan (f, span, a, b)) {
3607 goto close;
3609 if (span == page->lmark.span) {
3610 goto close;
3612 if (span == line->last_span) {
3613 if (putc ('\n', f) == EOF) {
3614 fprintf (stderr,
3615 "failed break line on sel pipe: %s\n",
3616 strerror (errno));
3617 goto close;
3624 close:
3625 if (f != stdout) {
3626 int ret = fclose (f);
3627 fd = -1;
3628 if (ret == -1) {
3629 if (errno != ECHILD) {
3630 fprintf (stderr, "failed to close sel pipe: %s\n",
3631 strerror (errno));
3635 unlock:
3636 unlock (__func__);
3638 done:
3639 if (fd >= 0) {
3640 if (close (fd)) {
3641 fprintf (stderr, "failed to close sel pipe: %s\n",
3642 strerror (errno));
3645 CAMLreturn0;
3648 CAMLprim value ml_getpdimrect (value pagedimno_v)
3650 CAMLparam1 (pagedimno_v);
3651 CAMLlocal1 (ret_v);
3652 int pagedimno = Int_val (pagedimno_v);
3653 fz_rect box;
3655 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3656 if (trylock (__func__)) {
3657 box = fz_empty_rect;
3659 else {
3660 box = state.pagedims[pagedimno].mediabox;
3661 unlock (__func__);
3664 Store_double_field (ret_v, 0, box.x0);
3665 Store_double_field (ret_v, 1, box.x1);
3666 Store_double_field (ret_v, 2, box.y0);
3667 Store_double_field (ret_v, 3, box.y1);
3669 CAMLreturn (ret_v);
3672 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3673 value dw_v, value cols_v)
3675 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3676 CAMLlocal1 (ret_v);
3677 int i;
3678 double zoom = -1.;
3679 double maxh = 0.0;
3680 struct pagedim *p;
3681 double winw = Int_val (winw_v);
3682 double winh = Int_val (winh_v);
3683 double dw = Int_val (dw_v);
3684 double cols = Int_val (cols_v);
3685 double pw = 1.0, ph = 1.0;
3687 if (trylock (__func__)) {
3688 goto done;
3691 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3692 double w = p->pagebox.x1 / cols;
3693 double h = p->pagebox.y1;
3694 if (h > maxh) {
3695 maxh = h;
3696 ph = h;
3697 if (state.fitmodel != FitProportional) pw = w;
3699 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3702 zoom = (((winh / ph) * pw) + dw) / winw;
3703 unlock (__func__);
3704 done:
3705 ret_v = caml_copy_double (zoom);
3706 CAMLreturn (ret_v);
3709 CAMLprim value ml_getmaxw (value unit_v)
3711 CAMLparam1 (unit_v);
3712 CAMLlocal1 (ret_v);
3713 int i;
3714 double maxw = -1.;
3715 struct pagedim *p;
3717 if (trylock (__func__)) {
3718 goto done;
3721 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3722 double w = p->pagebox.x1;
3723 maxw = fz_max (maxw, w);
3726 unlock (__func__);
3727 done:
3728 ret_v = caml_copy_double (maxw);
3729 CAMLreturn (ret_v);
3732 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3734 CAMLparam4 (pt_v, x_v, y_v, string_v);
3735 CAMLlocal1 (ret_v);
3736 int pt = Int_val(pt_v);
3737 int x = Int_val (x_v);
3738 int y = Int_val (y_v);
3739 double w;
3741 w = draw_string (state.face, pt, x, y, String_val (string_v));
3742 ret_v = caml_copy_double (w);
3743 CAMLreturn (ret_v);
3746 CAMLprim value ml_measure_string (value pt_v, value string_v)
3748 CAMLparam2 (pt_v, string_v);
3749 CAMLlocal1 (ret_v);
3750 int pt = Int_val (pt_v);
3751 double w;
3753 w = measure_string (state.face, pt, String_val (string_v));
3754 ret_v = caml_copy_double (w);
3755 CAMLreturn (ret_v);
3758 CAMLprim value ml_getpagebox (value opaque_v)
3760 CAMLparam1 (opaque_v);
3761 CAMLlocal1 (ret_v);
3762 fz_rect rect;
3763 fz_irect bbox;
3764 fz_matrix ctm;
3765 fz_device *dev;
3766 char *s = String_val (opaque_v);
3767 struct page *page = parse_pointer (__func__, s);
3769 ret_v = caml_alloc_tuple (4);
3770 dev = fz_new_bbox_device (state.ctx, &rect);
3771 dev->hints |= FZ_IGNORE_SHADE;
3773 ctm = pagectm (page);
3774 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3776 fz_close_device (state.ctx, dev);
3777 fz_drop_device (state.ctx, dev);
3778 fz_round_rect (&bbox, &rect);
3779 Field (ret_v, 0) = Val_int (bbox.x0);
3780 Field (ret_v, 1) = Val_int (bbox.y0);
3781 Field (ret_v, 2) = Val_int (bbox.x1);
3782 Field (ret_v, 3) = Val_int (bbox.y1);
3784 CAMLreturn (ret_v);
3787 CAMLprim void ml_setaalevel (value level_v)
3789 CAMLparam1 (level_v);
3791 state.aalevel = Int_val (level_v);
3792 CAMLreturn0;
3795 #pragma GCC diagnostic push
3796 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3797 #include <X11/Xlib.h>
3798 #include <X11/cursorfont.h>
3799 #pragma GCC diagnostic pop
3801 #ifdef USE_EGL
3802 #include <EGL/egl.h>
3803 #else
3804 #include <GL/glx.h>
3805 #endif
3807 static const int shapes[] = {
3808 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3811 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3813 static struct {
3814 Window wid;
3815 Display *dpy;
3816 #ifdef USE_EGL
3817 EGLContext ctx;
3818 EGLConfig conf;
3819 EGLSurface win;
3820 EGLDisplay *edpy;
3821 #else
3822 GLXContext ctx;
3823 #endif
3824 XVisualInfo *visual;
3825 Cursor curs[CURS_COUNT];
3826 } glx;
3829 static void initcurs (void)
3831 for (size_t n = 0; n < CURS_COUNT; ++n) {
3832 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3836 CAMLprim void ml_setbgcol (value color_v)
3838 CAMLparam1 (color_v);
3839 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3840 CAMLreturn0;
3843 #ifdef USE_EGL
3844 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3846 CAMLparam3 (display_v, wid_v, screen_v);
3847 int major, minor;
3848 int num_conf;
3849 EGLint visid;
3850 EGLint attribs[] = {
3851 EGL_DEPTH_SIZE, 24,
3852 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3853 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3854 EGL_NONE
3856 EGLConfig conf;
3858 glx.dpy = XOpenDisplay (String_val (display_v));
3859 if (!glx.dpy) {
3860 caml_failwith ("XOpenDisplay");
3863 eglBindAPI (EGL_OPENGL_API);
3865 glx.edpy = eglGetDisplay (glx.dpy);
3866 if (glx.edpy == EGL_NO_DISPLAY) {
3867 caml_failwith ("eglGetDisplay");
3870 if (!eglInitialize (glx.edpy, &major, &minor)) {
3871 caml_failwith ("eglInitialize");
3874 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3875 !num_conf) {
3876 caml_failwith ("eglChooseConfig");
3879 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3880 caml_failwith ("eglGetConfigAttrib");
3883 glx.conf = conf;
3884 initcurs ();
3886 glx.wid = Int_val (wid_v);
3887 CAMLreturn (Val_int (visid));
3890 CAMLprim value ml_glxcompleteinit (value unit_v)
3892 CAMLparam1 (unit_v);
3894 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3895 if (!glx.ctx) {
3896 caml_failwith ("eglCreateContext");
3899 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3900 glx.wid, NULL);
3901 if (glx.win == EGL_NO_SURFACE) {
3902 caml_failwith ("eglCreateWindowSurface");
3905 XFree (glx.visual);
3906 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3907 glx.ctx = NULL;
3908 caml_failwith ("eglMakeCurrent");
3910 CAMLreturn (unit_v);
3912 #else
3913 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3915 CAMLparam3 (display_v, wid_v, screen_v);
3917 glx.dpy = XOpenDisplay (String_val (display_v));
3918 if (!glx.dpy) {
3919 caml_failwith ("XOpenDisplay");
3922 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3923 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3924 if (!glx.visual) {
3925 XCloseDisplay (glx.dpy);
3926 caml_failwith ("glXChooseVisual");
3929 initcurs ();
3931 glx.wid = Int_val (wid_v);
3932 CAMLreturn (Val_int (glx.visual->visualid));
3935 CAMLprim value ml_glxcompleteinit (value unit_v)
3937 CAMLparam1 (unit_v);
3939 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3940 if (!glx.ctx) {
3941 caml_failwith ("glXCreateContext");
3944 XFree (glx.visual);
3945 glx.visual = NULL;
3947 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3948 glXDestroyContext (glx.dpy, glx.ctx);
3949 glx.ctx = NULL;
3950 caml_failwith ("glXMakeCurrent");
3952 CAMLreturn (unit_v);
3954 #endif
3956 CAMLprim void ml_setcursor (value cursor_v)
3958 CAMLparam1 (cursor_v);
3959 size_t cursn = Int_val (cursor_v);
3961 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3962 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3963 XFlush (glx.dpy);
3964 CAMLreturn0;
3967 CAMLprim value ml_swapb (value unit_v)
3969 CAMLparam1 (unit_v);
3970 #ifdef USE_EGL
3971 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3972 caml_failwith ("eglSwapBuffers");
3974 #else
3975 glXSwapBuffers (glx.dpy, glx.wid);
3976 #endif
3977 CAMLreturn (unit_v);
3980 #include "keysym2ucs.c"
3982 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3984 CAMLparam1 (keysym_v);
3985 CAMLlocal1 (str_v);
3986 KeySym keysym = Int_val (keysym_v);
3987 Rune rune;
3988 int len;
3989 char buf[5];
3991 rune = keysym2ucs (keysym);
3992 len = fz_runetochar (buf, rune);
3993 buf[len] = 0;
3994 str_v = caml_copy_string (buf);
3995 CAMLreturn (str_v);
3998 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4000 CAMLprim value ml_platform (value unit_v)
4002 CAMLparam1 (unit_v);
4003 CAMLlocal2 (tup_v, arr_v);
4004 int platid = piunknown;
4005 struct utsname buf;
4007 #if defined __linux__
4008 platid = pilinux;
4009 #elif defined __CYGWIN__
4010 platid = picygwin;
4011 #elif defined __DragonFly__ || defined __FreeBSD__
4012 || defined __OpenBSD__ || defined __NetBSD__
4013 platid = pibsd;
4014 #elif defined __sun__
4015 platid = pisun;
4016 #elif defined __APPLE__
4017 platid = piosx;
4018 #endif
4019 if (uname (&buf)) err (1, "uname");
4021 tup_v = caml_alloc_tuple (2);
4023 char const *sar[] = {
4024 buf.sysname,
4025 buf.release,
4026 buf.version,
4027 buf.machine,
4028 NULL
4030 arr_v = caml_copy_string_array (sar);
4032 Field (tup_v, 0) = Val_int (platid);
4033 Field (tup_v, 1) = arr_v;
4034 CAMLreturn (tup_v);
4037 CAMLprim void ml_cloexec (value fd_v)
4039 CAMLparam1 (fd_v);
4040 int fd = Int_val (fd_v);
4042 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4043 uerror ("fcntl", Nothing);
4045 CAMLreturn0;
4048 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4050 CAMLparam2 (w_v, h_v);
4051 CAMLlocal1 (ret_v);
4052 struct bo *pbo;
4053 int w = Int_val (w_v);
4054 int h = Int_val (h_v);
4055 int cs = Int_val (cs_v);
4057 if (state.bo_usable) {
4058 pbo = calloc (sizeof (*pbo), 1);
4059 if (!pbo) {
4060 err (1, "calloc pbo");
4063 switch (cs) {
4064 case 0:
4065 case 1:
4066 pbo->size = w*h*4;
4067 break;
4068 case 2:
4069 pbo->size = w*h*2;
4070 break;
4071 default:
4072 errx (1, "%s: invalid colorspace %d", __func__, cs);
4075 state.glGenBuffersARB (1, &pbo->id);
4076 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4077 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4078 NULL, GL_STREAM_DRAW);
4079 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4080 GL_READ_WRITE);
4081 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4082 if (!pbo->ptr) {
4083 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4084 state.glDeleteBuffersARB (1, &pbo->id);
4085 free (pbo);
4086 ret_v = caml_copy_string ("0");
4088 else {
4089 int res;
4090 char *s;
4092 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4093 if (res < 0) {
4094 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4096 s = malloc (res+1);
4097 if (!s) {
4098 err (1, "malloc %d bytes failed", res+1);
4100 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4101 if (res < 0) {
4102 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4104 ret_v = caml_copy_string (s);
4105 free (s);
4108 else {
4109 ret_v = caml_copy_string ("0");
4111 CAMLreturn (ret_v);
4114 CAMLprim void ml_freepbo (value s_v)
4116 CAMLparam1 (s_v);
4117 char *s = String_val (s_v);
4118 struct tile *tile = parse_pointer (__func__, s);
4120 if (tile->pbo) {
4121 state.glDeleteBuffersARB (1, &tile->pbo->id);
4122 tile->pbo->id = -1;
4123 tile->pbo->ptr = NULL;
4124 tile->pbo->size = -1;
4126 CAMLreturn0;
4129 CAMLprim void ml_unmappbo (value s_v)
4131 CAMLparam1 (s_v);
4132 char *s = String_val (s_v);
4133 struct tile *tile = parse_pointer (__func__, s);
4135 if (tile->pbo) {
4136 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4137 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4138 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4140 tile->pbo->ptr = NULL;
4141 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4143 CAMLreturn0;
4146 static void setuppbo (void)
4148 #ifdef USE_EGL
4149 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4150 #else
4151 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4152 #endif
4153 state.bo_usable = GGPA (glBindBufferARB)
4154 && GGPA (glUnmapBufferARB)
4155 && GGPA (glMapBufferARB)
4156 && GGPA (glBufferDataARB)
4157 && GGPA (glGenBuffersARB)
4158 && GGPA (glDeleteBuffersARB);
4159 #undef GGPA
4162 CAMLprim value ml_bo_usable (value unit_v)
4164 CAMLparam1 (unit_v);
4165 CAMLreturn (Val_bool (state.bo_usable));
4168 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4170 CAMLparam3 (ptr_v, x_v, y_v);
4171 CAMLlocal2 (ret_v, tup_v);
4172 struct page *page;
4173 char *s = String_val (ptr_v);
4174 int x = Int_val (x_v), y = Int_val (y_v);
4175 struct pagedim *pdim;
4176 fz_point p;
4177 fz_matrix ctm;
4179 page = parse_pointer (__func__, s);
4180 pdim = &state.pagedims[page->pdimno];
4182 ret_v = Val_int (0);
4183 if (trylock (__func__)) {
4184 goto done;
4187 if (pdf_specifics (state.ctx, state.doc)) {
4188 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4189 ctm = state.pagedims[page->pdimno].tctm;
4191 else {
4192 ctm = fz_identity;
4194 p.x = x + pdim->bounds.x0;
4195 p.y = y + pdim->bounds.y0;
4197 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4198 fz_invert_matrix (&ctm, &ctm);
4199 fz_transform_point (&p, &ctm);
4201 tup_v = caml_alloc_tuple (2);
4202 ret_v = caml_alloc_small (1, 1);
4203 Field (tup_v, 0) = Val_int (p.x);
4204 Field (tup_v, 1) = Val_int (p.y);
4205 Field (ret_v, 0) = tup_v;
4207 unlock (__func__);
4208 done:
4209 CAMLreturn (ret_v);
4212 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4213 value x_v, value y_v)
4215 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4216 CAMLlocal1 (ret_v);
4217 struct page *page;
4218 char *s = String_val (ptr_v);
4219 int pageno = Int_val (pageno_v);
4220 int pdimno = Int_val (pdimno_v);
4221 double x = Double_val (x_v), y = Double_val (y_v);
4222 struct pagedim *pdim;
4223 fz_point p;
4224 fz_matrix ctm;
4226 ret_v = Val_int (0);
4227 lock (__func__);
4229 if (!*s) {
4230 page = loadpage (pageno, pdimno);
4232 else {
4233 page = parse_pointer (__func__, s);
4235 pdim = &state.pagedims[pdimno];
4237 if (pdf_specifics (state.ctx, state.doc)) {
4238 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4239 ctm = state.pagedims[page->pdimno].tctm;
4241 else {
4242 ctm = fz_identity;
4244 p.x = x + pdim->bounds.x0;
4245 p.y = y + pdim->bounds.y0;
4247 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4248 fz_transform_point (&p, &ctm);
4250 ret_v = caml_alloc_tuple (2);
4251 Field (ret_v, 0) = caml_copy_double (p.x);
4252 Field (ret_v, 1) = caml_copy_double (p.y);
4254 if (!*s) {
4255 freepage (page);
4257 unlock (__func__);
4258 CAMLreturn (ret_v);
4261 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4262 value contents_v)
4264 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4265 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4267 if (pdf) {
4268 pdf_annot *annot;
4269 struct page *page;
4270 fz_point p;
4271 char *s = String_val (ptr_v);
4273 page = parse_pointer (__func__, s);
4274 annot = pdf_create_annot (state.ctx,
4275 pdf_page_from_fz_page (state.ctx,
4276 page->fzpage),
4277 PDF_ANNOT_TEXT);
4278 p.x = Int_val (x_v);
4279 p.y = Int_val (y_v);
4280 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4281 pdf_set_text_annot_position (state.ctx, annot, p);
4282 state.dirty = 1;
4284 CAMLreturn0;
4287 CAMLprim void ml_delannot (value ptr_v, value n_v)
4289 CAMLparam2 (ptr_v, n_v);
4290 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4292 if (pdf) {
4293 struct page *page;
4294 char *s = String_val (ptr_v);
4295 struct slink *slink;
4297 page = parse_pointer (__func__, s);
4298 slink = &page->slinks[Int_val (n_v)];
4299 pdf_delete_annot (state.ctx,
4300 pdf_page_from_fz_page (state.ctx, page->fzpage),
4301 (pdf_annot *) slink->u.annot);
4302 state.dirty = 1;
4304 CAMLreturn0;
4307 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4309 CAMLparam3 (ptr_v, n_v, str_v);
4310 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4312 if (pdf) {
4313 struct page *page;
4314 char *s = String_val (ptr_v);
4315 struct slink *slink;
4317 page = parse_pointer (__func__, s);
4318 slink = &page->slinks[Int_val (n_v)];
4319 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4320 String_val (str_v));
4321 state.dirty = 1;
4323 CAMLreturn0;
4326 CAMLprim value ml_hasunsavedchanges (value unit_v)
4328 CAMLparam1 (unit_v);
4329 CAMLreturn (Val_bool (state.dirty));
4332 CAMLprim void ml_savedoc (value path_v)
4334 CAMLparam1 (path_v);
4335 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4337 if (pdf) {
4338 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4340 CAMLreturn0;
4343 static void makestippletex (void)
4345 const char pixels[] = "\xff\xff\0\0";
4346 glGenTextures (1, &state.stid);
4347 glBindTexture (GL_TEXTURE_1D, state.stid);
4348 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4349 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4350 glTexImage1D (
4351 GL_TEXTURE_1D,
4353 GL_ALPHA,
4356 GL_ALPHA,
4357 GL_UNSIGNED_BYTE,
4358 pixels
4362 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4364 return caml_copy_string (FZ_VERSION);
4367 #ifdef USE_FONTCONFIG
4368 static struct {
4369 int inited;
4370 FcConfig *config;
4371 } fc;
4373 static fz_font *fc_load_system_font_func (fz_context *ctx,
4374 const char *name,
4375 int bold,
4376 int italic,
4377 int UNUSED_ATTR needs_exact_metrics)
4379 char *buf;
4380 size_t i, size;
4381 fz_font *font;
4382 FcChar8 *path;
4383 FcResult result;
4384 FcPattern *pat, *pat1;
4386 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4387 name, bold, italic, needs_exact_metrics);
4388 if (!fc.inited) {
4389 fc.inited = 1;
4390 fc.config = FcInitLoadConfigAndFonts ();
4391 if (!fc.config) {
4392 lprintf ("FcInitLoadConfigAndFonts failed\n");
4393 return NULL;
4396 if (!fc.config) return NULL;
4398 size = strlen (name);
4399 if (bold) size += sizeof (":bold") - 1;
4400 if (italic) size += sizeof (":italic") - 1;
4401 size += 1;
4403 buf = malloc (size);
4404 if (!buf) {
4405 err (1, "malloc %zu failed", size);
4408 strcpy (buf, name);
4409 if (bold && italic) {
4410 strcat (buf, ":bold:italic");
4412 else {
4413 if (bold) strcat (buf, ":bold");
4414 if (italic) strcat (buf, ":italic");
4416 for (i = 0; i < size; ++i) {
4417 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4420 lprintf ("fcbuf=%s\n", buf);
4421 pat = FcNameParse ((FcChar8 *) buf);
4422 if (!pat) {
4423 printd ("emsg FcNameParse failed\n");
4424 free (buf);
4425 return NULL;
4428 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4429 printd ("emsg FcConfigSubstitute failed\n");
4430 free (buf);
4431 return NULL;
4433 FcDefaultSubstitute (pat);
4435 pat1 = FcFontMatch (fc.config, pat, &result);
4436 if (!pat1) {
4437 printd ("emsg FcFontMatch failed\n");
4438 FcPatternDestroy (pat);
4439 free (buf);
4440 return NULL;
4443 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4444 printd ("emsg FcPatternGetString failed\n");
4445 FcPatternDestroy (pat);
4446 FcPatternDestroy (pat1);
4447 free (buf);
4448 return NULL;
4451 #if 0
4452 printd ("emsg name=%s path=%s\n", name, path);
4453 #endif
4454 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4455 FcPatternDestroy (pat);
4456 FcPatternDestroy (pat1);
4457 free (buf);
4458 return font;
4460 #endif
4462 CAMLprim void ml_init (value csock_v, value params_v)
4464 CAMLparam2 (csock_v, params_v);
4465 CAMLlocal2 (trim_v, fuzz_v);
4466 int ret;
4467 int texcount;
4468 char *fontpath;
4469 int colorspace;
4470 int mustoresize;
4471 int haspboext;
4473 state.csock = Int_val (csock_v);
4474 state.rotate = Int_val (Field (params_v, 0));
4475 state.fitmodel = Int_val (Field (params_v, 1));
4476 trim_v = Field (params_v, 2);
4477 texcount = Int_val (Field (params_v, 3));
4478 state.sliceheight = Int_val (Field (params_v, 4));
4479 mustoresize = Int_val (Field (params_v, 5));
4480 colorspace = Int_val (Field (params_v, 6));
4481 fontpath = String_val (Field (params_v, 7));
4483 if (caml_string_length (Field (params_v, 8)) > 0) {
4484 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4486 if (!state.trimcachepath) {
4487 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4488 strerror (errno));
4492 haspboext = Bool_val (Field (params_v, 9));
4494 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4495 fz_register_document_handlers (state.ctx);
4497 #ifdef USE_FONTCONFIG
4498 if (Bool_val (Field (params_v, 11))) {
4499 fz_install_load_system_font_funcs (
4500 state.ctx, fc_load_system_font_func, NULL
4503 #endif
4505 state.trimmargins = Bool_val (Field (trim_v, 0));
4506 fuzz_v = Field (trim_v, 1);
4507 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4508 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4509 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4510 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4512 set_tex_params (colorspace);
4514 if (*fontpath) {
4515 #ifndef USE_FONTCONFIG
4516 state.face = load_font (fontpath);
4517 #else
4518 FcChar8 *path;
4519 FcResult result;
4520 char *buf = fontpath;
4521 FcPattern *pat, *pat1;
4523 fc.inited = 1;
4524 fc.config = FcInitLoadConfigAndFonts ();
4525 if (!fc.config) {
4526 errx (1, "FcInitLoadConfigAndFonts failed");
4529 pat = FcNameParse ((FcChar8 *) buf);
4530 if (!pat) {
4531 errx (1, "FcNameParse failed");
4534 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4535 errx (1, "FcConfigSubstitute failed");
4537 FcDefaultSubstitute (pat);
4539 pat1 = FcFontMatch (fc.config, pat, &result);
4540 if (!pat1) {
4541 errx (1, "FcFontMatch failed");
4544 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4545 errx (1, "FcPatternGetString failed");
4548 state.face = load_font ((char *) path);
4549 FcPatternDestroy (pat);
4550 FcPatternDestroy (pat1);
4551 #endif
4553 else {
4554 int len;
4555 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4556 0, 0, &len);
4557 state.face = load_builtin_font (data, len);
4559 if (!state.face) _exit (1);
4561 realloctexts (texcount);
4563 if (haspboext) {
4564 setuppbo ();
4567 makestippletex ();
4569 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4570 if (ret) {
4571 errx (1, "pthread_create: %s", strerror (ret));
4574 CAMLreturn0;