Robustify
[llpp.git] / link.c
blobdbc0c2d9abefddbf7e66ef7180876ea6f2d6a3e8
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
4 #include <errno.h>
5 #include <stdio.h>
6 #include <ctype.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <signal.h>
10 #include <wchar.h>
12 #include <unistd.h>
13 #include <pthread.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/utsname.h>
19 #ifdef __CYGWIN__
20 #include <cygwin/socket.h> /* FIONREAD */
21 #else
22 #include <spawn.h>
23 #endif
25 #include <regex.h>
26 #include <stdarg.h>
27 #include <limits.h>
28 #include <inttypes.h>
30 #include <GL/gl.h>
32 #include <caml/fail.h>
33 #include <caml/alloc.h>
34 #include <caml/memory.h>
35 #include <caml/unixsupport.h>
37 #if __GNUC__ < 5
38 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
39 clobbered diagnostics */
40 #pragma GCC diagnostic ignored "-Wclobbered"
41 #endif
43 #pragma GCC diagnostic push
44 #pragma GCC diagnostic ignored "-Wunused-parameter"
45 #pragma GCC diagnostic ignored "-Wshadow"
46 #include <mupdf/fitz.h>
47 #pragma GCC diagnostic pop
48 #include <mupdf/pdf.h>
50 #include <ft2build.h>
51 #include FT_FREETYPE_H
53 #ifdef USE_FONTCONFIG
54 #include <fontconfig/fontconfig.h>
55 #endif
57 #define PIGGYBACK
58 #define CACHE_PAGEREFS
60 #ifndef __USE_GNU
61 extern char **environ;
62 #endif
64 #define MIN(a,b) ((a) < (b) ? (a) : (b))
65 #define MAX(a,b) ((a) > (b) ? (a) : (b))
67 #if defined __GNUC__
68 #define NORETURN_ATTR __attribute__ ((noreturn))
69 #define UNUSED_ATTR __attribute__ ((unused))
70 #if !defined __clang__
71 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
72 #else
73 #define OPTIMIZE_ATTR(n)
74 #endif
75 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
76 #else
77 #define NORETURN_ATTR
78 #define UNUSED_ATTR
79 #define OPTIMIZE_ATTR(n)
80 #define GCC_FMT_ATTR(a, b)
81 #endif
83 #define FMT_s "zu"
85 #define FMT_ptr PRIxPTR
86 #define SCN_ptr SCNxPTR
87 #define FMT_ptr_cast(p) ((uintptr_t) (p))
88 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
90 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
91 err (int exitcode, const char *fmt, ...)
93 va_list ap;
94 int savederrno;
96 savederrno = errno;
97 va_start (ap, fmt);
98 vfprintf (stderr, fmt, ap);
99 va_end (ap);
100 fprintf (stderr, ": %s\n", strerror (savederrno));
101 fflush (stderr);
102 _exit (exitcode);
105 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
106 errx (int exitcode, const char *fmt, ...)
108 va_list ap;
110 va_start (ap, fmt);
111 vfprintf (stderr, fmt, ap);
112 va_end (ap);
113 fputc ('\n', stderr);
114 fflush (stderr);
115 _exit (exitcode);
118 #ifndef GL_TEXTURE_RECTANGLE_ARB
119 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
120 #endif
122 #ifndef GL_BGRA
123 #define GL_BGRA 0x80E1
124 #endif
126 #ifndef GL_UNSIGNED_INT_8_8_8_8
127 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
128 #endif
130 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
131 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
132 #endif
134 #if 0
135 #define lprintf printf
136 #else
137 #define lprintf(...)
138 #endif
140 #define ARSERT(cond) for (;;) { \
141 if (!(cond)) { \
142 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
144 break; \
147 struct slice {
148 int h;
149 int texindex;
152 struct tile {
153 int w, h;
154 int slicecount;
155 int sliceheight;
156 struct pbo *pbo;
157 fz_pixmap *pixmap;
158 struct slice slices[1];
161 struct pagedim {
162 int pageno;
163 int rotate;
164 int left;
165 int tctmready;
166 fz_irect bounds;
167 fz_rect pagebox;
168 fz_rect mediabox;
169 fz_matrix ctm, zoomctm, lctm, tctm;
172 struct slink {
173 enum { SLINK, SANNOT } tag;
174 fz_irect bbox;
175 union {
176 fz_link *link;
177 fz_annot *annot;
178 } u;
181 struct annot {
182 fz_irect bbox;
183 fz_annot *annot;
186 struct page {
187 int tgen;
188 int sgen;
189 int agen;
190 int pageno;
191 int pdimno;
192 fz_text_page *text;
193 fz_text_sheet *sheet;
194 fz_page *fzpage;
195 fz_display_list *dlist;
196 int slinkcount;
197 struct slink *slinks;
198 int annotcount;
199 struct annot *annots;
200 struct mark {
201 int i;
202 fz_text_span *span;
203 } fmark, lmark;
206 struct {
207 int sliceheight;
208 struct pagedim *pagedims;
209 int pagecount;
210 int pagedimcount;
211 fz_document *doc;
212 fz_context *ctx;
213 int w, h;
215 int texindex;
216 int texcount;
217 GLuint *texids;
219 GLenum texiform;
220 GLenum texform;
221 GLenum texty;
223 fz_colorspace *colorspace;
225 struct {
226 int w, h;
227 struct slice *slice;
228 } *texowners;
230 int rotate;
231 enum { FitWidth, FitProportional, FitPage } fitmodel;
232 int trimmargins;
233 int needoutline;
234 int gen;
235 int aalevel;
237 int trimanew;
238 fz_irect trimfuzz;
239 fz_pixmap *pig;
241 pthread_t thread;
242 int csock;
243 FT_Face face;
245 char *trimcachepath;
246 int cxack;
247 int dirty;
249 GLuint stid;
251 int pbo_usable;
252 void (*glBindBufferARB) (GLenum, GLuint);
253 GLboolean (*glUnmapBufferARB) (GLenum);
254 void *(*glMapBufferARB) (GLenum, GLenum);
255 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
256 void (*glGenBuffersARB) (GLsizei, GLuint *);
257 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
259 GLfloat texcoords[8];
260 GLfloat vertices[16];
262 #ifdef CACHE_PAGEREFS
263 struct {
264 int idx;
265 int count;
266 pdf_obj **objs;
267 pdf_document *pdf;
268 } pdflut;
269 #endif
270 } state;
272 struct pbo {
273 GLuint id;
274 void *ptr;
275 size_t size;
278 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
280 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
283 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
285 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
288 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
290 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
291 m.a, m.b, m.c, m.d, m.e, m.f);
294 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
296 static void lock (const char *cap)
298 int ret = pthread_mutex_lock (&mutex);
299 if (ret) {
300 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
304 static void unlock (const char *cap)
306 int ret = pthread_mutex_unlock (&mutex);
307 if (ret) {
308 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
312 static int trylock (const char *cap)
314 int ret = pthread_mutex_trylock (&mutex);
315 if (ret && ret != EBUSY) {
316 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
318 return ret == EBUSY;
321 static void *parse_pointer (const char *cap, const char *s)
323 int ret;
324 void *ptr;
326 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
327 if (ret != 1) {
328 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
330 return ptr;
333 static double now (void)
335 struct timeval tv;
337 if (gettimeofday (&tv, NULL)) {
338 err (1, "gettimeofday");
340 return tv.tv_sec + tv.tv_usec*1e-6;
343 static int hasdata (void)
345 int ret, avail;
346 ret = ioctl (state.csock, FIONREAD, &avail);
347 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
348 return avail > 0;
351 CAMLprim value ml_hasdata (value fd_v)
353 CAMLparam1 (fd_v);
354 int ret, avail;
356 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
357 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
358 CAMLreturn (Val_bool (avail > 0));
361 static void readdata (void *p, int size)
363 ssize_t n;
365 again:
366 n = read (state.csock, p, size);
367 if (n < 0) {
368 if (errno == EINTR) goto again;
369 err (1, "read (req %d, ret %zd)", size, n);
371 if (n - size) {
372 if (!n) errx (1, "EOF while reading");
373 errx (1, "read (req %d, ret %zd)", size, n);
377 static void writedata (char *p, int size)
379 ssize_t n;
381 p[0] = (size >> 24) & 0xff;
382 p[1] = (size >> 16) & 0xff;
383 p[2] = (size >> 8) & 0xff;
384 p[3] = (size >> 0) & 0xff;
386 n = write (state.csock, p, size + 4);
387 if (n - size - 4) {
388 if (!n) errx (1, "EOF while writing data");
389 err (1, "write (req %d, ret %zd)", size + 4, n);
393 static int readlen (void)
395 unsigned char p[4];
397 readdata (p, 4);
398 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
401 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
403 int size = 200, len;
404 va_list ap;
405 char *buf;
407 buf = malloc (size);
408 for (;;) {
409 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
411 va_start (ap, fmt);
412 len = vsnprintf (buf + 4, size - 4, fmt, ap);
413 va_end (ap);
415 if (len > -1) {
416 if (len < size - 4) {
417 writedata (buf, len);
418 break;
420 else size = len + 5;
422 else {
423 err (1, "vsnprintf for `%s' failed", fmt);
425 buf = realloc (buf, size);
427 free (buf);
430 static void closedoc (void)
432 #ifdef CACHE_PAGEREFS
433 if (state.pdflut.objs) {
434 int i;
436 for (i = 0; i < state.pdflut.count; ++i) {
437 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
439 free (state.pdflut.objs);
440 state.pdflut.objs = NULL;
441 state.pdflut.idx = 0;
443 #endif
444 if (state.doc) {
445 fz_drop_document (state.ctx, state.doc);
446 state.doc = NULL;
450 static int openxref (char *filename, char *password)
452 int i;
454 for (i = 0; i < state.texcount; ++i) {
455 state.texowners[i].w = -1;
456 state.texowners[i].slice = NULL;
459 closedoc ();
461 state.dirty = 0;
462 if (state.pagedims) {
463 free (state.pagedims);
464 state.pagedims = NULL;
466 state.pagedimcount = 0;
468 fz_set_aa_level (state.ctx, state.aalevel);
469 state.doc = fz_open_document (state.ctx, filename);
470 if (fz_needs_password (state.ctx, state.doc)) {
471 if (password && !*password) {
472 printd ("pass");
473 return 0;
475 else {
476 int ok = fz_authenticate_password (state.ctx, state.doc, password);
477 if (!ok) {
478 printd ("pass fail");
479 return 0;
483 state.pagecount = fz_count_pages (state.ctx, state.doc);
484 return 1;
487 static void pdfinfo (void)
489 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
490 if (pdf) {
491 pdf_obj *infoobj;
493 printd ("info PDF version\t%d.%d",
494 pdf->version / 10, pdf->version % 10);
496 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
497 pdf), "Info");
498 if (infoobj) {
499 unsigned int i;
500 char *s;
501 char *items[] = { "Title", "Author", "Creator",
502 "Producer", "CreationDate" };
504 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
505 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
506 s = pdf_to_utf8 (state.ctx, pdf, obj);
507 if (*s) printd ("info %s\t%s", items[i], s);
508 fz_free (state.ctx, s);
511 printd ("infoend");
515 static void unlinktile (struct tile *tile)
517 int i;
519 for (i = 0; i < tile->slicecount; ++i) {
520 struct slice *s = &tile->slices[i];
522 if (s->texindex != -1) {
523 if (state.texowners[s->texindex].slice == s) {
524 state.texowners[s->texindex].slice = NULL;
530 static void freepage (struct page *page)
532 if (!page) return;
533 if (page->text) {
534 fz_drop_text_page (state.ctx, page->text);
536 if (page->sheet) {
537 fz_drop_text_sheet (state.ctx, page->sheet);
539 if (page->slinks) {
540 free (page->slinks);
542 fz_drop_display_list (state.ctx, page->dlist);
543 fz_drop_page (state.ctx, page->fzpage);
544 free (page);
547 static void freetile (struct tile *tile)
549 unlinktile (tile);
550 if (!tile->pbo) {
551 #ifndef PIGGYBACK
552 fz_drop_pixmap (state.ctx, tile->pixmap);
553 #else
554 if (state.pig) {
555 fz_drop_pixmap (state.ctx, state.pig);
557 state.pig = tile->pixmap;
558 #endif
560 else {
561 free (tile->pbo);
562 fz_drop_pixmap (state.ctx, tile->pixmap);
564 free (tile);
567 #ifdef __ALTIVEC__
568 #include <stdint.h>
569 #include <altivec.h>
571 static int cacheline32bytes;
573 static void __attribute__ ((constructor)) clcheck (void)
575 char **envp = environ;
576 unsigned long *auxv;
578 while (*envp++);
580 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
581 if (*auxv == 19) {
582 cacheline32bytes = auxv[1] == 32;
583 return;
588 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
590 size_t size = pixmap->w * pixmap->h * pixmap->n;
591 if (cacheline32bytes && size > 32) {
592 intptr_t a1, a2, diff;
593 size_t sizea, i;
594 vector unsigned char v = vec_splat_u8 (-1);
595 vector unsigned char *p;
597 a1 = a2 = (intptr_t) pixmap->samples;
598 a2 = (a1 + 31) & ~31;
599 diff = a2 - a1;
600 sizea = size - diff;
601 p = (void *) a2;
603 while (a1 != a2) *(char *) a1++ = 0xff;
604 for (i = 0; i < (sizea & ~31); i += 32) {
605 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
606 vec_st (v, i, p);
607 vec_st (v, i + 16, p);
609 while (i < sizea) *((char *) a1 + i++) = 0xff;
611 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
613 #else
614 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
615 #endif
617 static void trimctm (pdf_page *page, int pindex)
619 fz_matrix ctm;
620 struct pagedim *pdim = &state.pagedims[pindex];
622 if (!pdim->tctmready) {
623 if (state.trimmargins) {
624 fz_rect realbox;
625 fz_matrix rm, sm, tm, im, ctm1;
627 fz_rotate (&rm, -pdim->rotate);
628 fz_scale (&sm, 1, -1);
629 fz_concat (&ctm, &rm, &sm);
630 realbox = pdim->mediabox;
631 fz_transform_rect (&realbox, &ctm);
632 fz_translate (&tm, -realbox.x0, -realbox.y0);
633 fz_concat (&ctm1, &ctm, &tm);
634 fz_invert_matrix (&im, &page->ctm);
635 fz_concat (&ctm, &im, &ctm1);
637 else {
638 ctm = fz_identity;
640 pdim->tctm = ctm;
641 pdim->tctmready = 1;
645 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
647 fz_matrix ctm, tm;
648 int pdimno = pdim - state.pagedims;
650 if (pdf_specifics (state.ctx, state.doc)) {
651 trimctm ((pdf_page *) fzpage, pdimno);
652 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
654 else {
655 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
656 fz_concat (&ctm, &tm, &pdim->ctm);
658 return ctm;
661 static fz_matrix pagectm (struct page *page)
663 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
666 static void *loadpage (int pageno, int pindex)
668 fz_device *dev;
669 struct page *page;
671 page = calloc (sizeof (struct page), 1);
672 if (!page) {
673 err (1, "calloc page %d", pageno);
676 page->dlist = fz_new_display_list (state.ctx);
677 dev = fz_new_list_device (state.ctx, page->dlist);
678 fz_try (state.ctx) {
679 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
680 fz_run_page (state.ctx, page->fzpage, dev,
681 &fz_identity, NULL);
683 fz_catch (state.ctx) {
684 page->fzpage = NULL;
686 fz_drop_device (state.ctx, dev);
688 page->pdimno = pindex;
689 page->pageno = pageno;
690 page->sgen = state.gen;
691 page->agen = state.gen;
692 page->tgen = state.gen;
693 return page;
696 static struct tile *alloctile (int h)
698 int i;
699 int slicecount;
700 size_t tilesize;
701 struct tile *tile;
703 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
704 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
705 tile = calloc (tilesize, 1);
706 if (!tile) {
707 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
709 for (i = 0; i < slicecount; ++i) {
710 int sh = MIN (h, state.sliceheight);
711 tile->slices[i].h = sh;
712 tile->slices[i].texindex = -1;
713 h -= sh;
715 tile->slicecount = slicecount;
716 tile->sliceheight = state.sliceheight;
717 return tile;
720 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
721 struct pbo *pbo)
723 fz_rect rect;
724 fz_irect bbox;
725 fz_matrix ctm;
726 fz_device *dev;
727 struct tile *tile;
728 struct pagedim *pdim;
730 tile = alloctile (h);
731 pdim = &state.pagedims[page->pdimno];
733 bbox = pdim->bounds;
734 bbox.x0 += x;
735 bbox.y0 += y;
736 bbox.x1 = bbox.x0 + w;
737 bbox.y1 = bbox.y0 + h;
739 if (state.pig) {
740 if (state.pig->w == w
741 && state.pig->h == h
742 && state.pig->colorspace == state.colorspace) {
743 tile->pixmap = state.pig;
744 tile->pixmap->x = bbox.x0;
745 tile->pixmap->y = bbox.y0;
747 else {
748 fz_drop_pixmap (state.ctx, state.pig);
750 state.pig = NULL;
752 if (!tile->pixmap) {
753 if (pbo) {
754 tile->pixmap =
755 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
756 &bbox, pbo->ptr);
757 tile->pbo = pbo;
759 else {
760 tile->pixmap =
761 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
765 tile->w = w;
766 tile->h = h;
767 clearpixmap (tile->pixmap);
769 dev = fz_new_draw_device (state.ctx, tile->pixmap);
770 ctm = pagectm (page);
771 fz_rect_from_irect (&rect, &bbox);
772 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
773 fz_drop_device (state.ctx, dev);
775 return tile;
778 #ifdef CACHE_PAGEREFS
779 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
780 thanks to Robin Watts */
781 static void
782 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
784 fz_context *ctx = state.ctx; /* doc->ctx; */
785 pdf_obj *kids;
786 int i, len;
788 if (state.pdflut.idx == state.pagecount) return;
790 kids = pdf_dict_gets (ctx, node, "Kids");
791 len = pdf_array_len (ctx, kids);
793 if (len == 0)
794 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
796 if (pdf_mark_obj (ctx, node))
797 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
798 for (i = 0; i < len; i++) {
799 pdf_obj *kid = pdf_array_get (ctx, kids, i);
800 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
801 if (*type
802 ? !strcmp (type, "Pages")
803 : pdf_dict_gets (ctx, kid, "Kids")
804 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
805 pdf_collect_pages (doc, kid);
807 else {
808 if (*type
809 ? strcmp (type, "Page") != 0
810 : !pdf_dict_gets (ctx, kid, "MediaBox"))
811 fz_warn (ctx, "non-page object in page tree (%s)", type);
812 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
815 pdf_unmark_obj (ctx, node);
818 static void
819 pdf_load_page_objs (pdf_document *doc)
821 pdf_obj *root = pdf_dict_gets (state.ctx,
822 pdf_trailer (state.ctx, doc), "Root");
823 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
825 if (!node)
826 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
828 state.pdflut.idx = 0;
829 pdf_collect_pages (doc, node);
831 #endif
833 static void initpdims (int wthack)
835 double start, end;
836 FILE *trimf = NULL;
837 fz_rect rootmediabox;
838 int pageno, trim, show;
839 int trimw = 0, cxcount;
840 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
842 fz_var (trimw);
843 fz_var (cxcount);
844 start = now ();
846 if (state.trimmargins && state.trimcachepath) {
847 trimf = fopen (state.trimcachepath, "rb");
848 if (!trimf) {
849 trimf = fopen (state.trimcachepath, "wb");
850 trimw = 1;
854 if (state.trimmargins || pdf || !state.cxack)
855 cxcount = state.pagecount;
856 else
857 cxcount = MIN (state.pagecount, 1);
859 if (pdf) {
860 pdf_obj *obj;
861 obj = pdf_dict_getp (state.ctx, pdf_trailer (state.ctx, pdf),
862 "Root/Pages/MediaBox");
863 pdf_to_rect (state.ctx, obj, &rootmediabox);
866 #ifdef CACHE_PAGEREFS
867 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
868 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
869 if (!state.pdflut.objs) {
870 err (1, "malloc pageobjs %zu %d %zu failed",
871 sizeof (*state.pdflut.objs), cxcount,
872 sizeof (*state.pdflut.objs) * cxcount);
874 state.pdflut.count = cxcount;
875 pdf_load_page_objs (pdf);
876 state.pdflut.pdf = pdf;
878 #endif
880 for (pageno = 0; pageno < cxcount; ++pageno) {
881 int rotate = 0;
882 struct pagedim *p;
883 fz_rect mediabox;
885 if (pdf) {
886 pdf_obj *pageref, *pageobj;
888 #ifdef CACHE_PAGEREFS
889 pageref = state.pdflut.objs[pageno];
890 #else
891 pageref = pdf_lookup_page_obj (state.ctx, pdf, pageno);
892 #endif
893 pageobj = pdf_resolve_indirect (state.ctx, pageref);
895 if (state.trimmargins) {
896 fz_context *ctx = state.ctx;
897 pdf_obj *obj;
898 pdf_page *page;
900 fz_try (state.ctx) {
901 page = pdf_load_page (ctx, pdf, pageno);
902 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
903 trim = state.trimanew || !obj;
904 if (trim) {
905 fz_rect rect;
906 fz_matrix ctm;
907 fz_device *dev;
909 dev = fz_new_bbox_device (ctx, &rect);
910 dev->hints |= FZ_IGNORE_SHADE;
911 fz_invert_matrix (&ctm, &page->ctm);
912 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
913 fz_drop_device (ctx, dev);
915 rect.x0 += state.trimfuzz.x0;
916 rect.x1 += state.trimfuzz.x1;
917 rect.y0 += state.trimfuzz.y0;
918 rect.y1 += state.trimfuzz.y1;
919 fz_transform_rect (&rect, &ctm);
920 fz_intersect_rect (&rect, &page->mediabox);
922 if (fz_is_empty_rect (&rect)) {
923 mediabox = page->mediabox;
925 else {
926 mediabox = rect;
929 obj = pdf_new_array (ctx, pdf, 4);
930 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
931 mediabox.x0));
932 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
933 mediabox.y0));
934 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
935 mediabox.x1));
936 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
937 mediabox.y1));
938 pdf_dict_puts (state.ctx, pageobj, "llpp.TrimBox", obj);
940 else {
941 mediabox.x0 = pdf_to_real (ctx,
942 pdf_array_get (ctx, obj, 0));
943 mediabox.y0 = pdf_to_real (ctx,
944 pdf_array_get (ctx, obj, 1));
945 mediabox.x1 = pdf_to_real (ctx,
946 pdf_array_get (ctx, obj, 2));
947 mediabox.y1 = pdf_to_real (ctx,
948 pdf_array_get (ctx, obj, 3));
951 rotate = page->rotate;
952 fz_drop_page (ctx, &page->super);
954 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
955 if (show) {
956 printd ("progress %f Trimming %d",
957 (double) (pageno + 1) / state.pagecount,
958 pageno + 1);
961 fz_catch (state.ctx) {
962 fprintf (stderr, "failed to load page %d\n", pageno+1);
965 else {
966 int empty = 0;
967 fz_rect cropbox;
969 pdf_to_rect (state.ctx,
970 pdf_dict_gets (state.ctx, pageobj, "MediaBox"),
971 &mediabox);
972 if (fz_is_empty_rect (&mediabox)) {
973 mediabox.x0 = 0;
974 mediabox.y0 = 0;
975 mediabox.x1 = 612;
976 mediabox.y1 = 792;
977 empty = 1;
980 pdf_to_rect (state.ctx,
981 pdf_dict_gets (state.ctx, pageobj, "CropBox"),
982 &cropbox);
983 if (!fz_is_empty_rect (&cropbox)) {
984 if (empty) {
985 mediabox = cropbox;
987 else {
988 fz_intersect_rect (&mediabox, &cropbox);
991 else {
992 if (empty) {
993 if (fz_is_empty_rect (&rootmediabox)) {
994 fprintf (stderr,
995 "cannot find page size for page %d\n",
996 pageno+1);
998 else {
999 mediabox = rootmediabox;
1003 rotate = pdf_to_int (state.ctx,
1004 pdf_dict_gets (state.ctx,
1005 pageobj, "Rotate"));
1008 else {
1009 if (state.trimmargins && trimw) {
1010 fz_page *page;
1012 fz_try (state.ctx) {
1013 page = fz_load_page (state.ctx, state.doc, pageno);
1014 fz_bound_page (state.ctx, page, &mediabox);
1015 rotate = 0;
1016 if (state.trimmargins) {
1017 fz_rect rect;
1018 fz_device *dev;
1020 dev = fz_new_bbox_device (state.ctx, &rect);
1021 dev->hints |= FZ_IGNORE_SHADE;
1022 fz_run_page (state.ctx, page, dev,
1023 &fz_identity, NULL);
1024 fz_drop_device (state.ctx, dev);
1026 rect.x0 += state.trimfuzz.x0;
1027 rect.x1 += state.trimfuzz.x1;
1028 rect.y0 += state.trimfuzz.y0;
1029 rect.y1 += state.trimfuzz.y1;
1030 fz_intersect_rect (&rect, &mediabox);
1032 if (!fz_is_empty_rect (&rect)) {
1033 mediabox = rect;
1036 fz_drop_page (state.ctx, page);
1037 if (!state.cxack) {
1038 printd ("progress %f loading %d",
1039 (double) (pageno + 1) / state.pagecount,
1040 pageno + 1);
1043 fz_catch (state.ctx) {
1045 if (trimf) {
1046 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1047 if (n - 1) {
1048 err (1, "fwrite trim mediabox");
1052 else {
1053 if (trimf) {
1054 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1055 if (n - 1) {
1056 err (1, "fread trim mediabox %d", pageno);
1059 else {
1060 fz_page *page;
1061 fz_try (state.ctx) {
1062 page = fz_load_page (state.ctx,
1063 state.doc, pageno);
1064 fz_bound_page (state.ctx, page, &mediabox);
1065 fz_drop_page (state.ctx, page);
1067 show = !state.trimmargins && pageno % 20 == 0;
1068 if (show) {
1069 printd ("progress %f Gathering dimensions %d",
1070 (double) (pageno) / state.pagecount,
1071 pageno);
1074 fz_catch (state.ctx) {
1075 fprintf (stderr, "failed to load page %d\n", pageno);
1081 if (state.pagedimcount == 0
1082 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1083 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1084 size_t size;
1086 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1087 state.pagedims = realloc (state.pagedims, size);
1088 if (!state.pagedims) {
1089 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1090 size, state.pagedimcount + 1);
1093 p = &state.pagedims[state.pagedimcount++];
1094 p->rotate = rotate;
1095 p->mediabox = mediabox;
1096 p->pageno = pageno;
1099 end = now ();
1100 if (!wthack) {
1101 printd ("progress 1 %s %d pages in %f seconds",
1102 state.trimmargins ? "Trimmed" : "Processed",
1103 state.pagecount, end - start);
1105 state.trimanew = 0;
1106 if (trimf) {
1107 if (fclose (trimf)) {
1108 err (1, "fclose");
1113 static void layout (void)
1115 int pindex;
1116 fz_rect box;
1117 fz_matrix ctm, rm;
1118 struct pagedim *p = p;
1119 double zw, w, maxw = 0.0, zoom = zoom;
1121 if (state.pagedimcount == 0) return;
1123 switch (state.fitmodel) {
1124 case FitProportional:
1125 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1126 double x0, x1;
1128 p = &state.pagedims[pindex];
1129 fz_rotate (&rm, p->rotate + state.rotate);
1130 box = p->mediabox;
1131 fz_transform_rect (&box, &rm);
1133 x0 = MIN (box.x0, box.x1);
1134 x1 = MAX (box.x0, box.x1);
1136 w = x1 - x0;
1137 maxw = MAX (w, maxw);
1138 zoom = state.w / maxw;
1140 break;
1142 case FitPage:
1143 maxw = state.w;
1144 break;
1146 case FitWidth:
1147 break;
1149 default:
1150 ARSERT (0 && state.fitmodel);
1153 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1154 fz_rect rect;
1155 fz_matrix tm, sm;
1157 p = &state.pagedims[pindex];
1158 fz_rotate (&ctm, state.rotate);
1159 fz_rotate (&rm, p->rotate + state.rotate);
1160 box = p->mediabox;
1161 fz_transform_rect (&box, &rm);
1162 w = box.x1 - box.x0;
1163 switch (state.fitmodel) {
1164 case FitProportional:
1165 p->left = ((maxw - w) * zoom) / 2.0;
1166 break;
1167 case FitPage:
1169 double zh, h;
1170 zw = maxw / w;
1171 h = box.y1 - box.y0;
1172 zh = state.h / h;
1173 zoom = MIN (zw, zh);
1174 p->left = (maxw - (w * zoom)) / 2.0;
1176 break;
1177 case FitWidth:
1178 p->left = 0;
1179 zoom = state.w / w;
1180 break;
1183 fz_scale (&p->zoomctm, zoom, zoom);
1184 fz_concat (&ctm, &p->zoomctm, &ctm);
1186 fz_rotate (&rm, p->rotate);
1187 p->pagebox = p->mediabox;
1188 fz_transform_rect (&p->pagebox, &rm);
1189 p->pagebox.x1 -= p->pagebox.x0;
1190 p->pagebox.y1 -= p->pagebox.y0;
1191 p->pagebox.x0 = 0;
1192 p->pagebox.y0 = 0;
1193 rect = p->pagebox;
1194 fz_transform_rect (&rect, &ctm);
1195 fz_round_rect (&p->bounds, &rect);
1196 p->ctm = ctm;
1198 fz_translate (&tm, 0, -p->mediabox.y1);
1199 fz_scale (&sm, zoom, -zoom);
1200 fz_concat (&ctm, &tm, &sm);
1201 fz_concat (&p->lctm, &ctm, &rm);
1203 p->tctmready = 0;
1206 do {
1207 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1208 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1209 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1210 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1211 int boundw = x1 - x0;
1212 int boundh = y1 - y0;
1214 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1215 } while (p-- != state.pagedims);
1218 static
1219 struct anchor { int n; int x; int y; int w; int h; }
1220 desttoanchor (fz_link_dest *dest)
1222 int i;
1223 struct anchor a;
1224 struct pagedim *pdim = state.pagedims;
1226 a.n = -1;
1227 a.x = 0;
1228 a.y = 0;
1229 for (i = 0; i < state.pagedimcount; ++i) {
1230 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1231 break;
1232 pdim = &state.pagedims[i];
1234 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1235 fz_point p;
1236 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1237 p.x = dest->ld.gotor.lt.x;
1238 else
1239 p.x = 0.0;
1240 p.y = dest->ld.gotor.lt.y;
1241 fz_transform_point (&p, &pdim->lctm);
1242 a.x = p.x;
1243 a.y = p.y;
1245 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1246 double x0, x1, y0, y1;
1248 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1249 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1250 a.w = x1 - x0;
1251 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1252 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1253 a.h = y1 - y0;
1254 a.n = dest->ld.gotor.page;
1256 return a;
1259 static void recurse_outline (fz_outline *outline, int level)
1261 while (outline) {
1262 switch (outline->dest.kind) {
1263 case FZ_LINK_GOTO:
1265 struct anchor a = desttoanchor (&outline->dest);
1267 if (a.n >= 0) {
1268 printd ("o %d %d %d %d %s",
1269 level, a.n, a.y, a.h, outline->title);
1272 break;
1274 case FZ_LINK_URI:
1275 printd ("ou %d %" FMT_s " %s %s", level,
1276 strlen (outline->title), outline->title,
1277 outline->dest.ld.uri.uri);
1278 break;
1280 case FZ_LINK_NONE:
1281 printd ("on %d %s", level, outline->title);
1282 break;
1284 default:
1285 printd ("emsg Unhandled outline kind %d for %s\n",
1286 outline->dest.kind, outline->title);
1287 break;
1289 if (outline->down) {
1290 recurse_outline (outline->down, level + 1);
1292 outline = outline->next;
1296 static void process_outline (void)
1298 fz_outline *outline;
1300 if (!state.needoutline || !state.pagedimcount) return;
1302 state.needoutline = 0;
1303 outline = fz_load_outline (state.ctx, state.doc);
1304 if (outline) {
1305 recurse_outline (outline, 0);
1306 fz_drop_outline (state.ctx, outline);
1310 static char *strofspan (fz_text_span *span)
1312 char *p;
1313 char utf8[10];
1314 fz_text_char *ch;
1315 size_t size = 0, cap = 80;
1317 p = malloc (cap + 1);
1318 if (!p) return NULL;
1320 for (ch = span->text; ch < span->text + span->len; ++ch) {
1321 int n = fz_runetochar (utf8, ch->c);
1322 if (size + n > cap) {
1323 cap *= 2;
1324 p = realloc (p, cap + 1);
1325 if (!p) return NULL;
1328 memcpy (p + size, utf8, n);
1329 size += n;
1331 p[size] = 0;
1332 return p;
1335 static int matchspan (regex_t *re, fz_text_span *span,
1336 int stop, int pageno, double start)
1338 int ret;
1339 char *p;
1340 regmatch_t rm;
1341 int a, b, c;
1342 fz_rect sb, eb;
1343 fz_point p1, p2, p3, p4;
1345 p = strofspan (span);
1346 if (!p) return -1;
1348 ret = regexec (re, p, 1, &rm, 0);
1349 if (ret) {
1350 free (p);
1351 if (ret != REG_NOMATCH) {
1352 size_t size;
1353 char errbuf[80];
1354 size = regerror (ret, re, errbuf, sizeof (errbuf));
1355 printd ("msg regexec error `%.*s'",
1356 (int) size, errbuf);
1357 return -1;
1359 return 0;
1361 else {
1362 int l = span->len;
1364 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1365 c += fz_runelen (span->text[a].c);
1367 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1368 c += fz_runelen (span->text[b].c);
1371 if (fz_runelen (span->text[b].c) > 1) {
1372 b = MAX (0, b-1);
1375 fz_text_char_bbox (state.ctx, &sb, span, a);
1376 fz_text_char_bbox (state.ctx, &eb, span, b);
1378 p1.x = sb.x0;
1379 p1.y = sb.y0;
1380 p2.x = eb.x1;
1381 p2.y = sb.y0;
1382 p3.x = eb.x1;
1383 p3.y = eb.y1;
1384 p4.x = sb.x0;
1385 p4.y = eb.y1;
1387 if (!stop) {
1388 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1389 pageno, 1,
1390 p1.x, p1.y,
1391 p2.x, p2.y,
1392 p3.x, p3.y,
1393 p4.x, p4.y);
1395 printd ("progress 1 found at %d `%.*s' in %f sec",
1396 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1397 now () - start);
1399 else {
1400 printd ("match %d %d %f %f %f %f %f %f %f %f",
1401 pageno, 2,
1402 p1.x, p1.y,
1403 p2.x, p2.y,
1404 p3.x, p3.y,
1405 p4.x, p4.y);
1407 free (p);
1408 return 1;
1412 static int compareblocks (const void *l, const void *r)
1414 fz_text_block const *ls = l;
1415 fz_text_block const *rs = r;
1416 return ls->bbox.y0 - rs->bbox.y0;
1419 /* wishful thinking function */
1420 static void search (regex_t *re, int pageno, int y, int forward)
1422 int i, j;
1423 fz_device *tdev;
1424 fz_text_page *text;
1425 fz_text_sheet *sheet;
1426 struct pagedim *pdim, *pdimprev;
1427 int stop = 0, niters = 0;
1428 double start, end;
1429 fz_page *page;
1431 start = now ();
1432 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1433 if (niters++ == 5) {
1434 niters = 0;
1435 if (hasdata ()) {
1436 printd ("progress 1 attention requested aborting search at %d",
1437 pageno);
1438 stop = 1;
1440 else {
1441 printd ("progress %f searching in page %d",
1442 (double) (pageno + 1) / state.pagecount,
1443 pageno);
1446 pdimprev = NULL;
1447 for (i = 0; i < state.pagedimcount; ++i) {
1448 pdim = &state.pagedims[i];
1449 if (pdim->pageno == pageno) {
1450 goto found;
1452 if (pdim->pageno > pageno) {
1453 pdim = pdimprev;
1454 goto found;
1456 pdimprev = pdim;
1458 pdim = pdimprev;
1459 found:
1461 sheet = fz_new_text_sheet (state.ctx);
1462 text = fz_new_text_page (state.ctx);
1463 tdev = fz_new_text_device (state.ctx, sheet, text);
1465 page = fz_load_page (state.ctx, state.doc, pageno);
1467 fz_matrix ctm = pagectm1 (page, pdim);
1468 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1471 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1472 fz_drop_device (state.ctx, tdev);
1474 for (j = 0; j < text->len; ++j) {
1475 int k;
1476 fz_page_block *pb;
1477 fz_text_block *block;
1479 pb = &text->blocks[forward ? j : text->len - 1 - j];
1480 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1481 block = pb->u.text;
1483 for (k = 0; k < block->len; ++k) {
1484 fz_text_line *line;
1485 fz_text_span *span;
1487 if (forward) {
1488 line = &block->lines[k];
1489 if (line->bbox.y0 < y + 1) continue;
1491 else {
1492 line = &block->lines[block->len - 1 - k];
1493 if (line->bbox.y0 > y - 1) continue;
1496 for (span = line->first_span; span; span = span->next) {
1497 switch (matchspan (re, span, stop, pageno, start)) {
1498 case 0: break;
1499 case 1: stop = 1; break;
1500 case -1: stop = 1; goto endloop;
1505 if (forward) {
1506 pageno += 1;
1507 y = 0;
1509 else {
1510 pageno -= 1;
1511 y = INT_MAX;
1513 endloop:
1514 fz_drop_text_page (state.ctx, text);
1515 fz_drop_text_sheet (state.ctx, sheet);
1516 fz_drop_page (state.ctx, page);
1518 end = now ();
1519 if (!stop) {
1520 printd ("progress 1 no matches %f sec", end - start);
1522 printd ("clearrects");
1525 static void set_tex_params (int colorspace)
1527 union {
1528 unsigned char b;
1529 unsigned int s;
1530 } endianness = {1};
1532 switch (colorspace) {
1533 case 0:
1534 state.texiform = GL_RGBA8;
1535 state.texform = GL_RGBA;
1536 state.texty = GL_UNSIGNED_BYTE;
1537 state.colorspace = fz_device_rgb (state.ctx);
1538 break;
1539 case 1:
1540 state.texiform = GL_RGBA8;
1541 state.texform = GL_BGRA;
1542 state.texty = endianness.s > 1
1543 ? GL_UNSIGNED_INT_8_8_8_8
1544 : GL_UNSIGNED_INT_8_8_8_8_REV;
1545 state.colorspace = fz_device_bgr (state.ctx);
1546 break;
1547 case 2:
1548 state.texiform = GL_LUMINANCE_ALPHA;
1549 state.texform = GL_LUMINANCE_ALPHA;
1550 state.texty = GL_UNSIGNED_BYTE;
1551 state.colorspace = fz_device_gray (state.ctx);
1552 break;
1553 default:
1554 errx (1, "invalid colorspce %d", colorspace);
1558 static void realloctexts (int texcount)
1560 size_t size;
1562 if (texcount == state.texcount) return;
1564 if (texcount < state.texcount) {
1565 glDeleteTextures (state.texcount - texcount,
1566 state.texids + texcount);
1569 size = texcount * sizeof (*state.texids);
1570 state.texids = realloc (state.texids, size);
1571 if (!state.texids) {
1572 err (1, "realloc texids %" FMT_s, size);
1575 size = texcount * sizeof (*state.texowners);
1576 state.texowners = realloc (state.texowners, size);
1577 if (!state.texowners) {
1578 err (1, "realloc texowners %" FMT_s, size);
1580 if (texcount > state.texcount) {
1581 int i;
1583 glGenTextures (texcount - state.texcount,
1584 state.texids + state.texcount);
1585 for (i = state.texcount; i < texcount; ++i) {
1586 state.texowners[i].w = -1;
1587 state.texowners[i].slice = NULL;
1590 state.texcount = texcount;
1591 state.texindex = 0;
1594 static char *mbtoutf8 (char *s)
1596 char *p, *r;
1597 wchar_t *tmp;
1598 size_t i, ret, len;
1600 len = mbstowcs (NULL, s, strlen (s));
1601 if (len == 0) {
1602 return s;
1604 else {
1605 if (len == (size_t) -1) {
1606 return s;
1610 tmp = malloc (len * sizeof (wchar_t));
1611 if (!tmp) {
1612 return s;
1615 ret = mbstowcs (tmp, s, len);
1616 if (ret == (size_t) -1) {
1617 free (tmp);
1618 return s;
1621 len = 0;
1622 for (i = 0; i < ret; ++i) {
1623 len += fz_runelen (tmp[i]);
1626 p = r = malloc (len + 1);
1627 if (!r) {
1628 free (tmp);
1629 return s;
1632 for (i = 0; i < ret; ++i) {
1633 p += fz_runetochar (p, tmp[i]);
1635 *p = 0;
1636 free (tmp);
1637 return r;
1640 CAMLprim value ml_mbtoutf8 (value s_v)
1642 CAMLparam1 (s_v);
1643 CAMLlocal1 (ret_v);
1644 char *s, *r;
1646 s = String_val (s_v);
1647 r = mbtoutf8 (s);
1648 if (r == s) {
1649 ret_v = s_v;
1651 else {
1652 ret_v = caml_copy_string (r);
1653 free (r);
1655 CAMLreturn (ret_v);
1658 static void * mainloop (void UNUSED_ATTR *unused)
1660 char *p = NULL;
1661 int len, ret, oldlen = 0;
1663 fz_var (p);
1664 fz_var (oldlen);
1665 for (;;) {
1666 len = readlen ();
1667 if (len == 0) {
1668 errx (1, "readlen returned 0");
1671 if (oldlen < len + 1) {
1672 p = realloc (p, len + 1);
1673 if (!p) {
1674 err (1, "realloc %d failed", len + 1);
1676 oldlen = len + 1;
1678 readdata (p, len);
1679 p[len] = 0;
1681 if (!strncmp ("open", p, 4)) {
1682 int wthack, off, ok = 0;
1683 char *password;
1684 char *filename;
1685 char *utf8filename;
1686 size_t filenamelen;
1688 fz_var (ok);
1689 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1690 if (ret != 2) {
1691 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1694 filename = p + 5 + off;
1695 filenamelen = strlen (filename);
1696 password = filename + filenamelen + 1;
1698 lock ("open");
1699 fz_try (state.ctx) {
1700 ok = openxref (filename, password);
1702 fz_catch (state.ctx) {
1703 utf8filename = mbtoutf8 (filename);
1704 printd ("msg Could not open %s", utf8filename);
1706 if (ok) {
1707 pdfinfo ();
1708 initpdims (wthack);
1710 unlock ("open");
1712 if (ok) {
1713 if (!wthack) {
1714 utf8filename = mbtoutf8 (filename);
1715 printd ("msg Opened %s (press h/F1 to get help)",
1716 utf8filename);
1717 if (utf8filename != filename) {
1718 free (utf8filename);
1721 state.needoutline = 1;
1724 else if (!strncmp ("cs", p, 2)) {
1725 int i, colorspace;
1727 ret = sscanf (p + 2, " %d", &colorspace);
1728 if (ret != 1) {
1729 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1731 lock ("cs");
1732 set_tex_params (colorspace);
1733 for (i = 0; i < state.texcount; ++i) {
1734 state.texowners[i].w = -1;
1735 state.texowners[i].slice = NULL;
1737 unlock ("cs");
1739 else if (!strncmp ("freepage", p, 8)) {
1740 void *ptr;
1742 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1743 if (ret != 1) {
1744 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1746 freepage (ptr);
1748 else if (!strncmp ("freetile", p, 8)) {
1749 void *ptr;
1751 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1752 if (ret != 1) {
1753 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1755 freetile (ptr);
1757 else if (!strncmp ("search", p, 6)) {
1758 int icase, pageno, y, len2, forward;
1759 char *pattern;
1760 regex_t re;
1762 ret = sscanf (p + 6, " %d %d %d %d,%n",
1763 &icase, &pageno, &y, &forward, &len2);
1764 if (ret != 4) {
1765 errx (1, "malformed search `%s' ret=%d", p, ret);
1768 pattern = p + 6 + len2;
1769 ret = regcomp (&re, pattern,
1770 REG_EXTENDED | (icase ? REG_ICASE : 0));
1771 if (ret) {
1772 char errbuf[80];
1773 size_t size;
1775 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1776 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1778 else {
1779 search (&re, pageno, y, forward);
1780 regfree (&re);
1783 else if (!strncmp ("geometry", p, 8)) {
1784 int w, h, fitmodel;
1786 printd ("clear");
1787 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1788 if (ret != 3) {
1789 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1792 lock ("geometry");
1793 state.h = h;
1794 if (w != state.w) {
1795 int i;
1796 state.w = w;
1797 for (i = 0; i < state.texcount; ++i) {
1798 state.texowners[i].slice = NULL;
1801 state.fitmodel = fitmodel;
1802 layout ();
1803 process_outline ();
1805 state.gen++;
1806 unlock ("geometry");
1807 printd ("continue %d", state.pagecount);
1809 else if (!strncmp ("reqlayout", p, 9)) {
1810 char *nameddest;
1811 int rotate, off, h;
1812 unsigned int fitmodel;
1813 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1815 printd ("clear");
1816 ret = sscanf (p + 9, " %d %u %d %n",
1817 &rotate, &fitmodel, &h, &off);
1818 if (ret != 3) {
1819 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1821 lock ("reqlayout");
1822 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1823 state.gen += 1;
1825 state.rotate = rotate;
1826 state.fitmodel = fitmodel;
1827 state.h = h;
1828 layout ();
1829 process_outline ();
1831 nameddest = p + 9 + off;
1832 if (pdf && nameddest && *nameddest) {
1833 struct anchor a;
1834 fz_link_dest dest;
1835 pdf_obj *needle, *obj;
1837 needle = pdf_new_string (state.ctx, pdf, nameddest,
1838 strlen (nameddest));
1839 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1840 if (obj) {
1841 dest = pdf_parse_link_dest (state.ctx, pdf,
1842 FZ_LINK_GOTO, obj);
1844 a = desttoanchor (&dest);
1845 if (a.n >= 0) {
1846 printd ("a %d %d %d", a.n, a.x, a.y);
1848 else {
1849 printd ("emsg failed to parse destination `%s'\n",
1850 nameddest);
1853 else {
1854 printd ("emsg destination `%s' not found\n",
1855 nameddest);
1857 pdf_drop_obj (state.ctx, needle);
1860 state.gen++;
1861 unlock ("reqlayout");
1862 printd ("continue %d", state.pagecount);
1864 else if (!strncmp ("page", p, 4)) {
1865 double a, b;
1866 struct page *page;
1867 int pageno, pindex;
1869 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1870 if (ret != 2) {
1871 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1874 lock ("page");
1875 a = now ();
1876 page = loadpage (pageno, pindex);
1877 b = now ();
1878 unlock ("page");
1880 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1882 else if (!strncmp ("tile", p, 4)) {
1883 int x, y, w, h;
1884 struct page *page;
1885 struct tile *tile;
1886 double a, b;
1887 void *data;
1889 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1890 SCN_ptr_cast (&page), &x, &y, &w, &h,
1891 SCN_ptr_cast (&data));
1892 if (ret != 6) {
1893 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1896 lock ("tile");
1897 a = now ();
1898 tile = rendertile (page, x, y, w, h, data);
1899 b = now ();
1900 unlock ("tile");
1902 printd ("tile %d %d %" FMT_ptr " %u %f",
1903 x, y,
1904 FMT_ptr_cast (tile),
1905 tile->w * tile->h * tile->pixmap->n,
1906 b - a);
1908 else if (!strncmp ("trimset", p, 7)) {
1909 fz_irect fuzz;
1910 int trimmargins;
1912 ret = sscanf (p + 7, " %d %d %d %d %d",
1913 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1914 if (ret != 5) {
1915 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1917 lock ("trimset");
1918 state.trimmargins = trimmargins;
1919 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1920 state.trimanew = 1;
1921 state.trimfuzz = fuzz;
1923 unlock ("trimset");
1925 else if (!strncmp ("settrim", p, 7)) {
1926 fz_irect fuzz;
1927 int trimmargins;
1929 ret = sscanf (p + 7, " %d %d %d %d %d",
1930 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1931 if (ret != 5) {
1932 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1934 printd ("clear");
1935 lock ("settrim");
1936 state.trimmargins = trimmargins;
1937 state.needoutline = 1;
1938 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1939 state.trimanew = 1;
1940 state.trimfuzz = fuzz;
1942 state.pagedimcount = 0;
1943 free (state.pagedims);
1944 state.pagedims = NULL;
1945 initpdims (0);
1946 layout ();
1947 process_outline ();
1948 unlock ("settrim");
1949 printd ("continue %d", state.pagecount);
1951 else if (!strncmp ("sliceh", p, 6)) {
1952 int h;
1954 ret = sscanf (p + 6, " %d", &h);
1955 if (ret != 1) {
1956 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1958 if (h != state.sliceheight) {
1959 int i;
1961 state.sliceheight = h;
1962 for (i = 0; i < state.texcount; ++i) {
1963 state.texowners[i].w = -1;
1964 state.texowners[i].h = -1;
1965 state.texowners[i].slice = NULL;
1969 else if (!strncmp ("interrupt", p, 9)) {
1970 printd ("vmsg interrupted");
1972 else {
1973 errx (1, "unknown command %.*s", len, p);
1976 return 0;
1979 CAMLprim value ml_realloctexts (value texcount_v)
1981 CAMLparam1 (texcount_v);
1982 int ok;
1984 if (trylock (__func__)) {
1985 ok = 0;
1986 goto done;
1988 realloctexts (Int_val (texcount_v));
1989 ok = 1;
1990 unlock (__func__);
1992 done:
1993 CAMLreturn (Val_bool (ok));
1996 static void recti (int x0, int y0, int x1, int y1)
1998 GLfloat *v = state.vertices;
2000 glVertexPointer (2, GL_FLOAT, 0, v);
2001 v[0] = x0; v[1] = y0;
2002 v[2] = x1; v[3] = y0;
2003 v[4] = x0; v[5] = y1;
2004 v[6] = x1; v[7] = y1;
2005 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2008 static void showsel (struct page *page, int ox, int oy)
2010 int seen = 0;
2011 fz_irect bbox;
2012 fz_rect rect;
2013 fz_text_line *line;
2014 fz_page_block *pageb;
2015 fz_text_block *block;
2016 struct mark first, last;
2017 unsigned char selcolor[] = {15,15,15,140};
2019 first = page->fmark;
2020 last = page->lmark;
2022 if (!first.span || !last.span) return;
2024 glEnable (GL_BLEND);
2025 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2026 glColor4ubv (selcolor);
2028 ox += state.pagedims[page->pdimno].bounds.x0;
2029 oy += state.pagedims[page->pdimno].bounds.y0;
2030 for (pageb = page->text->blocks;
2031 pageb < page->text->blocks + page->text->len;
2032 ++pageb) {
2033 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2034 block = pageb->u.text;
2036 for (line = block->lines;
2037 line < block->lines + block->len;
2038 ++line) {
2039 fz_text_span *span;
2040 rect = fz_empty_rect;
2042 for (span = line->first_span; span; span = span->next) {
2043 int i, j, k;
2044 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2046 j = 0;
2047 k = span->len - 1;
2049 if (span == page->fmark.span && span == page->lmark.span) {
2050 seen = 1;
2051 j = MIN (first.i, last.i);
2052 k = MAX (first.i, last.i);
2054 else {
2055 if (span == first.span) {
2056 seen = 1;
2057 j = first.i;
2059 else if (span == last.span) {
2060 seen = 1;
2061 k = last.i;
2065 if (seen) {
2066 for (i = j; i <= k; ++i) {
2067 fz_rect bbox1;
2068 fz_union_rect (&rect,
2069 fz_text_char_bbox (state.ctx, &bbox1,
2070 span, i));
2072 fz_round_rect (&bbox, &rect);
2073 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2074 bbox.x0,
2075 bbox.y0,
2076 bbox.x1,
2077 bbox.y1,
2078 oy, ox);
2080 recti (bbox.x0 + ox, bbox.y0 + oy,
2081 bbox.x1 + ox, bbox.y1 + oy);
2082 if (span == last.span) {
2083 goto done;
2085 rect = fz_empty_rect;
2090 done:
2091 glDisable (GL_BLEND);
2094 #include "glfont.c"
2096 static void stipplerect (fz_matrix *m,
2097 fz_point *p1,
2098 fz_point *p2,
2099 fz_point *p3,
2100 fz_point *p4,
2101 GLfloat *texcoords,
2102 GLfloat *vertices)
2104 fz_transform_point (p1, m);
2105 fz_transform_point (p2, m);
2106 fz_transform_point (p3, m);
2107 fz_transform_point (p4, m);
2109 float w, h, s, t;
2111 w = p2->x - p1->x;
2112 h = p2->y - p1->y;
2113 t = sqrtf (w*w + h*h) * .25f;
2115 w = p3->x - p2->x;
2116 h = p3->y - p2->y;
2117 s = sqrtf (w*w + h*h) * .25f;
2119 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2120 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2122 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2123 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2125 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2126 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2128 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2129 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2131 glDrawArrays (GL_LINES, 0, 8);
2134 static void solidrect (fz_matrix *m,
2135 fz_point *p1,
2136 fz_point *p2,
2137 fz_point *p3,
2138 fz_point *p4,
2139 GLfloat *vertices)
2141 fz_transform_point (p1, m);
2142 fz_transform_point (p2, m);
2143 fz_transform_point (p3, m);
2144 fz_transform_point (p4, m);
2145 vertices[0] = p1->x; vertices[1] = p1->y;
2146 vertices[2] = p2->x; vertices[3] = p2->y;
2148 vertices[4] = p3->x; vertices[5] = p3->y;
2149 vertices[6] = p4->x; vertices[7] = p4->y;
2150 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2153 static void highlightlinks (struct page *page, int xoff, int yoff)
2155 int i;
2156 fz_matrix ctm, tm, pm;
2157 fz_link *link, *links;
2158 GLfloat *texcoords = state.texcoords;
2159 GLfloat *vertices = state.vertices;
2161 links = fz_load_links (state.ctx, page->fzpage);
2163 glEnable (GL_TEXTURE_1D);
2164 glEnable (GL_BLEND);
2165 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2166 glBindTexture (GL_TEXTURE_1D, state.stid);
2168 xoff -= state.pagedims[page->pdimno].bounds.x0;
2169 yoff -= state.pagedims[page->pdimno].bounds.y0;
2170 fz_translate (&tm, xoff, yoff);
2171 pm = pagectm (page);
2172 fz_concat (&ctm, &pm, &tm);
2174 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2175 glVertexPointer (2, GL_FLOAT, 0, vertices);
2177 for (link = links; link; link = link->next) {
2178 fz_point p1, p2, p3, p4;
2180 p1.x = link->rect.x0;
2181 p1.y = link->rect.y0;
2183 p2.x = link->rect.x1;
2184 p2.y = link->rect.y0;
2186 p3.x = link->rect.x1;
2187 p3.y = link->rect.y1;
2189 p4.x = link->rect.x0;
2190 p4.y = link->rect.y1;
2192 switch (link->dest.kind) {
2193 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2194 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2195 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2196 default: glColor3ub (0, 0, 0); break;
2198 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2201 for (i = 0; i < page->annotcount; ++i) {
2202 fz_point p1, p2, p3, p4;
2203 struct annot *annot = &page->annots[i];
2205 p1.x = annot->bbox.x0;
2206 p1.y = annot->bbox.y0;
2208 p2.x = annot->bbox.x1;
2209 p2.y = annot->bbox.y0;
2211 p3.x = annot->bbox.x1;
2212 p3.y = annot->bbox.y1;
2214 p4.x = annot->bbox.x0;
2215 p4.y = annot->bbox.y1;
2217 glColor3ub (0, 0, 128);
2218 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2221 glDisable (GL_BLEND);
2222 glDisable (GL_TEXTURE_1D);
2225 static int compareslinks (const void *l, const void *r)
2227 struct slink const *ls = l;
2228 struct slink const *rs = r;
2229 if (ls->bbox.y0 == rs->bbox.y0) {
2230 return rs->bbox.x0 - rs->bbox.x0;
2232 return ls->bbox.y0 - rs->bbox.y0;
2235 static void droptext (struct page *page)
2237 if (page->text) {
2238 fz_drop_text_page (state.ctx, page->text);
2239 page->fmark.i = -1;
2240 page->lmark.i = -1;
2241 page->fmark.span = NULL;
2242 page->lmark.span = NULL;
2243 page->text = NULL;
2245 if (page->sheet) {
2246 fz_drop_text_sheet (state.ctx, page->sheet);
2247 page->sheet = NULL;
2251 static void dropannots (struct page *page)
2253 if (page->annots) {
2254 free (page->annots);
2255 page->annots = NULL;
2256 page->annotcount = 0;
2260 static void ensureannots (struct page *page)
2262 int i, count = 0;
2263 size_t annotsize = sizeof (*page->annots);
2264 fz_annot *annot;
2266 if (state.gen != page->agen) {
2267 dropannots (page);
2268 page->agen = state.gen;
2270 if (page->annots) return;
2272 for (annot = fz_first_annot (state.ctx, page->fzpage);
2273 annot;
2274 annot = fz_next_annot (state.ctx, page->fzpage, annot)) {
2275 count++;
2278 if (count > 0) {
2279 page->annotcount = count;
2280 page->annots = calloc (count, annotsize);
2281 if (!page->annots) {
2282 err (1, "calloc annots %d", count);
2285 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2286 annot;
2287 annot = fz_next_annot (state.ctx, page->fzpage, annot), i++) {
2288 fz_rect rect;
2290 fz_bound_annot (state.ctx, page->fzpage, annot, &rect);
2291 page->annots[i].annot = annot;
2292 fz_round_rect (&page->annots[i].bbox, &rect);
2297 static void dropslinks (struct page *page)
2299 if (page->slinks) {
2300 free (page->slinks);
2301 page->slinks = NULL;
2302 page->slinkcount = 0;
2306 static void ensureslinks (struct page *page)
2308 fz_matrix ctm;
2309 int i, count;
2310 size_t slinksize = sizeof (*page->slinks);
2311 fz_link *link, *links;
2313 ensureannots (page);
2314 if (state.gen != page->sgen) {
2315 dropslinks (page);
2316 page->sgen = state.gen;
2318 if (page->slinks) return;
2320 links = fz_load_links (state.ctx, page->fzpage);
2321 ctm = state.pagedims[page->pdimno].ctm;
2323 count = page->annotcount;
2324 for (link = links; link; link = link->next) {
2325 count++;
2327 if (count > 0) {
2328 int j;
2330 page->slinkcount = count;
2331 page->slinks = calloc (count, slinksize);
2332 if (!page->slinks) {
2333 err (1, "calloc slinks %d", count);
2336 for (i = 0, link = links; link; ++i, link = link->next) {
2337 fz_rect rect;
2339 rect = link->rect;
2340 fz_transform_rect (&rect, &ctm);
2341 page->slinks[i].tag = SLINK;
2342 page->slinks[i].u.link = link;
2343 fz_round_rect (&page->slinks[i].bbox, &rect);
2345 for (j = 0; j < page->annotcount; ++j, ++i) {
2346 fz_rect rect;
2347 fz_bound_annot (state.ctx,
2348 page->fzpage,
2349 page->annots[j].annot,
2350 &rect);
2351 fz_transform_rect (&rect, &ctm);
2352 fz_round_rect (&page->slinks[i].bbox, &rect);
2354 page->slinks[i].tag = SANNOT;
2355 page->slinks[i].u.annot = page->annots[j].annot;
2357 qsort (page->slinks, count, slinksize, compareslinks);
2361 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2362 static void fmt_linkn (char *s, unsigned int u)
2364 unsigned int len; unsigned int q;
2365 unsigned int zma = 'z' - 'a' + 1;
2366 len = 1; q = u;
2367 while (q > zma - 1) { ++len; q /= zma; }
2368 if (s) {
2369 s += len;
2370 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2371 /* handles u == 0 */
2373 s[len] = 0;
2376 static void highlightslinks (struct page *page, int xoff, int yoff,
2377 int noff, char *targ, int tlen, int hfsize)
2379 int i;
2380 char buf[40];
2381 struct slink *slink;
2382 double x0, y0, x1, y1, w;
2384 ensureslinks (page);
2385 glColor3ub (0xc3, 0xb0, 0x91);
2386 for (i = 0; i < page->slinkcount; ++i) {
2387 fmt_linkn (buf, i + noff);
2388 if (!tlen || !strncmp (targ, buf, tlen)) {
2389 slink = &page->slinks[i];
2391 x0 = slink->bbox.x0 + xoff - 5;
2392 y1 = slink->bbox.y0 + yoff - 5;
2393 y0 = y1 + 10 + hfsize;
2394 w = measure_string (state.face, hfsize, buf);
2395 x1 = x0 + w + 10;
2396 recti (x0, y0, x1, y1);
2400 glEnable (GL_BLEND);
2401 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2402 glEnable (GL_TEXTURE_2D);
2403 glColor3ub (0, 0, 0);
2404 for (i = 0; i < page->slinkcount; ++i) {
2405 fmt_linkn (buf, i + noff);
2406 if (!tlen || !strncmp (targ, buf, tlen)) {
2407 slink = &page->slinks[i];
2409 x0 = slink->bbox.x0 + xoff;
2410 y0 = slink->bbox.y0 + yoff + hfsize;
2411 draw_string (state.face, hfsize, x0, y0, buf);
2414 glDisable (GL_TEXTURE_2D);
2415 glDisable (GL_BLEND);
2418 static void uploadslice (struct tile *tile, struct slice *slice)
2420 int offset;
2421 struct slice *slice1;
2422 unsigned char *texdata;
2424 offset = 0;
2425 for (slice1 = tile->slices; slice != slice1; slice1++) {
2426 offset += slice1->h * tile->w * tile->pixmap->n;
2428 if (slice->texindex != -1 && slice->texindex < state.texcount
2429 && state.texowners[slice->texindex].slice == slice) {
2430 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2432 else {
2433 int subimage = 0;
2434 int texindex = state.texindex++ % state.texcount;
2436 if (state.texowners[texindex].w == tile->w) {
2437 if (state.texowners[texindex].h >= slice->h) {
2438 subimage = 1;
2440 else {
2441 state.texowners[texindex].h = slice->h;
2444 else {
2445 state.texowners[texindex].h = slice->h;
2448 state.texowners[texindex].w = tile->w;
2449 state.texowners[texindex].slice = slice;
2450 slice->texindex = texindex;
2452 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2453 if (tile->pbo) {
2454 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2455 texdata = 0;
2457 else {
2458 texdata = tile->pixmap->samples;
2460 if (subimage) {
2461 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2465 tile->w,
2466 slice->h,
2467 state.texform,
2468 state.texty,
2469 texdata+offset
2472 else {
2473 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2475 state.texiform,
2476 tile->w,
2477 slice->h,
2479 state.texform,
2480 state.texty,
2481 texdata+offset
2484 if (tile->pbo) {
2485 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2490 CAMLprim value ml_begintiles (value unit_v)
2492 CAMLparam1 (unit_v);
2493 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2494 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2495 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2496 CAMLreturn (unit_v);
2499 CAMLprim value ml_endtiles (value unit_v)
2501 CAMLparam1 (unit_v);
2502 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2503 CAMLreturn (unit_v);
2506 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2508 CAMLparam2 (args_v, ptr_v);
2509 int dispx = Int_val (Field (args_v, 0));
2510 int dispy = Int_val (Field (args_v, 1));
2511 int dispw = Int_val (Field (args_v, 2));
2512 int disph = Int_val (Field (args_v, 3));
2513 int tilex = Int_val (Field (args_v, 4));
2514 int tiley = Int_val (Field (args_v, 5));
2515 char *s = String_val (ptr_v);
2516 struct tile *tile = parse_pointer (__func__, s);
2517 int slicey, firstslice;
2518 struct slice *slice;
2519 GLfloat *texcoords = state.texcoords;
2520 GLfloat *vertices = state.vertices;
2522 firstslice = tiley / tile->sliceheight;
2523 slice = &tile->slices[firstslice];
2524 slicey = tiley % tile->sliceheight;
2526 while (disph > 0) {
2527 int dh;
2529 dh = slice->h - slicey;
2530 dh = MIN (disph, dh);
2531 uploadslice (tile, slice);
2533 texcoords[0] = tilex; texcoords[1] = slicey;
2534 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2535 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2536 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2538 vertices[0] = dispx; vertices[1] = dispy;
2539 vertices[2] = dispx+dispw; vertices[3] = dispy;
2540 vertices[4] = dispx; vertices[5] = dispy+dh;
2541 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2543 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2544 dispy += dh;
2545 disph -= dh;
2546 slice++;
2547 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2548 slicey = 0;
2550 CAMLreturn (Val_unit);
2553 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2555 fz_matrix ctm, tm, pm;
2556 fz_point p1, p2, p3, p4;
2557 GLfloat *vertices = state.vertices;
2558 double *v = (double *) rects_v;
2560 xoff -= state.pagedims[page->pdimno].bounds.x0;
2561 yoff -= state.pagedims[page->pdimno].bounds.y0;
2562 fz_translate (&tm, xoff, yoff);
2563 pm = pagectm (page);
2564 fz_concat (&ctm, &pm, &tm);
2566 glEnable (GL_BLEND);
2567 glVertexPointer (2, GL_FLOAT, 0, vertices);
2569 glColor4dv (v);
2570 p1.x = v[4];
2571 p1.y = v[5];
2573 p2.x = v[6];
2574 p2.y = v[5];
2576 p3.x = v[6];
2577 p3.y = v[7];
2579 p4.x = v[4];
2580 p4.y = v[7];
2581 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2582 glDisable (GL_BLEND);
2585 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2586 value xoff_v, value yoff_v,
2587 value li_v)
2589 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2590 int xoff = Int_val (xoff_v);
2591 int yoff = Int_val (yoff_v);
2592 int noff = Int_val (Field (li_v, 0));
2593 char *targ = String_val (Field (li_v, 1));
2594 int tlen = caml_string_length (Field (li_v, 1));
2595 int hfsize = Int_val (Field (li_v, 2));
2596 char *s = String_val (ptr_v);
2597 int hlmask = Int_val (hlinks_v);
2598 struct page *page = parse_pointer (__func__, s);
2600 if (!page->fzpage) {
2601 /* deal with loadpage failed pages */
2602 goto done;
2605 ensureannots (page);
2607 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2608 if (trylock (__func__)) {
2609 noff = 0;
2610 goto done;
2612 if (hlmask & 2) {
2613 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2614 noff = page->slinkcount;
2616 if (page->tgen == state.gen) {
2617 showsel (page, xoff, yoff);
2619 unlock (__func__);
2621 done:
2622 CAMLreturn (Val_int (noff));
2625 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2626 value rects_v)
2628 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2629 int xoff = Int_val (xoff_v);
2630 int yoff = Int_val (yoff_v);
2631 char *s = String_val (ptr_v);
2632 struct page *page = parse_pointer (__func__, s);
2634 drawprect (page, xoff, yoff, rects_v);
2635 CAMLreturn (Val_unit);
2638 static struct annot *getannot (struct page *page, int x, int y)
2640 int i;
2641 fz_point p;
2642 fz_matrix ctm;
2643 const fz_matrix *tctm;
2644 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2646 if (!page->annots) return NULL;
2648 if (pdf) {
2649 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2650 tctm = &state.pagedims[page->pdimno].tctm;
2652 else {
2653 tctm = &fz_identity;
2656 p.x = x;
2657 p.y = y;
2659 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2660 fz_invert_matrix (&ctm, &ctm);
2661 fz_transform_point (&p, &ctm);
2663 if (pdf) {
2664 for (i = 0; i < page->annotcount; ++i) {
2665 struct annot *a = &page->annots[i];
2666 pdf_annot *annot = (pdf_annot *) a->annot;
2667 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2668 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2669 return a;
2674 return NULL;
2677 static fz_link *getlink (struct page *page, int x, int y)
2679 fz_point p;
2680 fz_matrix ctm;
2681 const fz_matrix *tctm;
2682 fz_link *link, *links;
2684 tctm = &fz_identity;
2685 links = fz_load_links (state.ctx, page->fzpage);
2687 p.x = x;
2688 p.y = y;
2690 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2691 fz_invert_matrix (&ctm, &ctm);
2692 fz_transform_point (&p, &ctm);
2694 for (link = links; link; link = link->next) {
2695 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2696 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2697 return link;
2701 return NULL;
2704 static void ensuretext (struct page *page)
2706 if (state.gen != page->tgen) {
2707 droptext (page);
2708 page->tgen = state.gen;
2710 if (!page->text) {
2711 fz_matrix ctm;
2712 fz_device *tdev;
2714 page->text = fz_new_text_page (state.ctx);
2715 page->sheet = fz_new_text_sheet (state.ctx);
2716 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2717 ctm = pagectm (page);
2718 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2719 fz_run_display_list (state.ctx, page->dlist,
2720 tdev, &ctm, &fz_infinite_rect, NULL);
2721 qsort (page->text->blocks, page->text->len,
2722 sizeof (*page->text->blocks), compareblocks);
2723 fz_end_page (state.ctx, tdev);
2724 fz_drop_device (state.ctx, tdev);
2728 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2730 CAMLparam2 (start_page_v, dir_v);
2731 CAMLlocal1 (ret_v);
2732 int i, dir = Int_val (dir_v);
2733 int start_page = Int_val (start_page_v);
2734 int end_page = dir > 0 ? state.pagecount : -1;
2735 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2737 fz_var (end_page);
2738 ret_v = Val_int (0);
2739 lock (__func__);
2740 for (i = start_page + dir; i != end_page; i += dir) {
2741 int found;
2743 fz_var (found);
2744 if (pdf) {
2745 pdf_page *page = NULL;
2747 fz_try (state.ctx) {
2748 page = pdf_load_page (state.ctx, pdf, i);
2749 found = !!page->links || !!page->annots;
2751 fz_catch (state.ctx) {
2752 found = 0;
2754 if (page) {
2755 fz_drop_page (state.ctx, &page->super);
2758 else {
2759 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2760 found = !!fz_load_links (state.ctx, page);
2761 fz_drop_page (state.ctx, page);
2764 if (found) {
2765 ret_v = caml_alloc_small (1, 1);
2766 Field (ret_v, 0) = Val_int (i);
2767 goto unlock;
2770 unlock:
2771 unlock (__func__);
2772 CAMLreturn (ret_v);
2775 enum { dir_first, dir_last };
2776 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2778 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2780 CAMLparam2 (ptr_v, dir_v);
2781 CAMLlocal2 (ret_v, pos_v);
2782 struct page *page;
2783 int dirtag, i, slinkindex;
2784 struct slink *found = NULL ,*slink;
2785 char *s = String_val (ptr_v);
2787 page = parse_pointer (__func__, s);
2788 ret_v = Val_int (0);
2789 /* This is scary we are not taking locks here ensureslinks does
2790 not modify state and given that we obtained the page it can not
2791 disappear under us either */
2792 lock (__func__);
2793 ensureslinks (page);
2795 if (Is_block (dir_v)) {
2796 dirtag = Tag_val (dir_v);
2797 switch (dirtag) {
2798 case dir_first_visible:
2800 int x0, y0, dir, first_index, last_index;
2802 pos_v = Field (dir_v, 0);
2803 x0 = Int_val (Field (pos_v, 0));
2804 y0 = Int_val (Field (pos_v, 1));
2805 dir = Int_val (Field (pos_v, 2));
2807 if (dir >= 0) {
2808 dir = 1;
2809 first_index = 0;
2810 last_index = page->slinkcount;
2812 else {
2813 first_index = page->slinkcount - 1;
2814 last_index = -1;
2817 for (i = first_index; i != last_index; i += dir) {
2818 slink = &page->slinks[i];
2819 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2820 found = slink;
2821 break;
2825 break;
2827 case dir_left:
2828 slinkindex = Int_val (Field (dir_v, 0));
2829 found = &page->slinks[slinkindex];
2830 for (i = slinkindex - 1; i >= 0; --i) {
2831 slink = &page->slinks[i];
2832 if (slink->bbox.x0 < found->bbox.x0) {
2833 found = slink;
2834 break;
2837 break;
2839 case dir_right:
2840 slinkindex = Int_val (Field (dir_v, 0));
2841 found = &page->slinks[slinkindex];
2842 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2843 slink = &page->slinks[i];
2844 if (slink->bbox.x0 > found->bbox.x0) {
2845 found = slink;
2846 break;
2849 break;
2851 case dir_down:
2852 slinkindex = Int_val (Field (dir_v, 0));
2853 found = &page->slinks[slinkindex];
2854 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2855 slink = &page->slinks[i];
2856 if (slink->bbox.y0 >= found->bbox.y0) {
2857 found = slink;
2858 break;
2861 break;
2863 case dir_up:
2864 slinkindex = Int_val (Field (dir_v, 0));
2865 found = &page->slinks[slinkindex];
2866 for (i = slinkindex - 1; i >= 0; --i) {
2867 slink = &page->slinks[i];
2868 if (slink->bbox.y0 <= found->bbox.y0) {
2869 found = slink;
2870 break;
2873 break;
2876 else {
2877 dirtag = Int_val (dir_v);
2878 switch (dirtag) {
2879 case dir_first:
2880 found = page->slinks;
2881 break;
2883 case dir_last:
2884 if (page->slinks) {
2885 found = page->slinks + (page->slinkcount - 1);
2887 break;
2890 if (found) {
2891 ret_v = caml_alloc_small (2, 1);
2892 Field (ret_v, 0) = Val_int (found - page->slinks);
2895 unlock (__func__);
2896 CAMLreturn (ret_v);
2899 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2900 unamed, uremote, uremotedest, uannot };
2902 #define LINKTOVAL \
2904 int pageno; \
2906 switch (link->dest.kind) { \
2907 case FZ_LINK_GOTO: \
2909 fz_point p; \
2911 pageno = link->dest.ld.gotor.page; \
2912 p.x = 0; \
2913 p.y = 0; \
2915 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2916 p.y = link->dest.ld.gotor.lt.y; \
2917 fz_transform_point (&p, &pdim->lctm); \
2918 if (p.y < 0) p.y = 0; \
2920 tup_v = caml_alloc_tuple (2); \
2921 ret_v = caml_alloc_small (1, ugoto); \
2922 Field (tup_v, 0) = Val_int (pageno); \
2923 Field (tup_v, 1) = Val_int (p.y); \
2924 Field (ret_v, 0) = tup_v; \
2926 break; \
2928 case FZ_LINK_URI: \
2929 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2930 ret_v = caml_alloc_small (1, uuri); \
2931 Field (ret_v, 0) = str_v; \
2932 break; \
2934 case FZ_LINK_LAUNCH: \
2935 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2936 ret_v = caml_alloc_small (1, ulaunch); \
2937 Field (ret_v, 0) = str_v; \
2938 break; \
2940 case FZ_LINK_NAMED: \
2941 str_v = caml_copy_string (link->dest.ld.named.named); \
2942 ret_v = caml_alloc_small (1, unamed); \
2943 Field (ret_v, 0) = str_v; \
2944 break; \
2946 case FZ_LINK_GOTOR: \
2948 int rty; \
2950 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2951 pageno = link->dest.ld.gotor.page; \
2952 if (pageno == -1) { \
2953 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2954 rty = uremotedest; \
2956 else { \
2957 gr_v = Val_int (pageno); \
2958 rty = uremote; \
2960 tup_v = caml_alloc_tuple (2); \
2961 ret_v = caml_alloc_small (1, rty); \
2962 Field (tup_v, 0) = str_v; \
2963 Field (tup_v, 1) = gr_v; \
2964 Field (ret_v, 0) = tup_v; \
2966 break; \
2968 default: \
2970 char buf[80]; \
2972 snprintf (buf, sizeof (buf), \
2973 "unhandled link kind %d", link->dest.kind); \
2974 str_v = caml_copy_string (buf); \
2975 ret_v = caml_alloc_small (1, uunexpected); \
2976 Field (ret_v, 0) = str_v; \
2978 break; \
2982 CAMLprim value ml_getlink (value ptr_v, value n_v)
2984 CAMLparam2 (ptr_v, n_v);
2985 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2986 fz_link *link;
2987 struct page *page;
2988 struct pagedim *pdim;
2989 char *s = String_val (ptr_v);
2990 struct slink *slink;
2992 /* See ml_findlink for caveat */
2994 ret_v = Val_int (0);
2995 page = parse_pointer (__func__, s);
2996 ensureslinks (page);
2997 pdim = &state.pagedims[page->pdimno];
2998 slink = &page->slinks[Int_val (n_v)];
2999 if (slink->tag == SLINK) {
3000 link = slink->u.link;
3001 LINKTOVAL;
3003 else {
3004 ret_v = caml_alloc_small (1, uannot);
3005 tup_v = caml_alloc_tuple (2);
3006 Field (ret_v, 0) = tup_v;
3007 Field (tup_v, 0) = ptr_v;
3008 Field (tup_v, 1) = n_v;
3011 CAMLreturn (ret_v);
3014 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3016 CAMLparam2 (ptr_v, n_v);
3017 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3018 if (pdf) {
3019 char *s = String_val (ptr_v);
3020 struct page *page;
3021 struct slink *slink;
3023 page = parse_pointer (__func__, s);
3024 slink = &page->slinks[Int_val (n_v)];
3025 CAMLreturn (caml_copy_string (
3026 pdf_annot_contents (state.ctx, pdf,
3027 (pdf_annot *) slink->u.annot)));
3029 else {
3030 CAMLreturn (caml_copy_string (""));
3034 CAMLprim value ml_getlinkcount (value ptr_v)
3036 CAMLparam1 (ptr_v);
3037 struct page *page;
3038 char *s = String_val (ptr_v);
3040 page = parse_pointer (__func__, s);
3041 CAMLreturn (Val_int (page->slinkcount));
3044 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3046 CAMLparam2 (ptr_v, n_v);
3047 CAMLlocal1 (ret_v);
3048 struct page *page;
3049 struct slink *slink;
3050 char *s = String_val (ptr_v);
3051 /* See ml_findlink for caveat */
3053 page = parse_pointer (__func__, s);
3054 ret_v = caml_alloc_tuple (4);
3055 ensureslinks (page);
3057 slink = &page->slinks[Int_val (n_v)];
3058 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3059 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3060 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3061 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3062 unlock ("ml_getlinkrect");
3063 CAMLreturn (ret_v);
3066 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3068 CAMLparam3 (ptr_v, x_v, y_v);
3069 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3070 fz_link *link;
3071 struct annot *annot;
3072 struct page *page;
3073 char *ptr = String_val (ptr_v);
3074 int x = Int_val (x_v), y = Int_val (y_v);
3075 struct pagedim *pdim;
3077 ret_v = Val_int (0);
3078 if (trylock (__func__)) {
3079 goto done;
3082 page = parse_pointer (__func__, ptr);
3083 pdim = &state.pagedims[page->pdimno];
3084 x += pdim->bounds.x0;
3085 y += pdim->bounds.y0;
3088 annot = getannot (page, x, y);
3089 if (annot) {
3090 int i, n = -1;
3092 ensureslinks (page);
3093 for (i = 0; i < page->slinkcount; ++i) {
3094 if (page->slinks[i].tag == SANNOT
3095 && page->slinks[i].u.annot == annot->annot) {
3096 n = i;
3097 break;
3100 ret_v = caml_alloc_small (1, uannot);
3101 tup_v = caml_alloc_tuple (2);
3102 Field (ret_v, 0) = tup_v;
3103 Field (tup_v, 0) = ptr_v;
3104 Field (tup_v, 1) = Val_int (n);
3105 goto unlock;
3109 link = getlink (page, x, y);
3110 if (link) {
3111 LINKTOVAL;
3113 else {
3114 fz_rect *b;
3115 fz_page_block *pageb;
3116 fz_text_block *block;
3118 ensuretext (page);
3119 for (pageb = page->text->blocks;
3120 pageb < page->text->blocks + page->text->len;
3121 ++pageb) {
3122 fz_text_line *line;
3123 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3124 block = pageb->u.text;
3126 b = &block->bbox;
3127 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3128 continue;
3130 for (line = block->lines;
3131 line < block->lines + block->len;
3132 ++line) {
3133 fz_text_span *span;
3135 b = &line->bbox;
3136 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3137 continue;
3139 for (span = line->first_span; span; span = span->next) {
3140 int charnum;
3142 b = &span->bbox;
3143 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3144 continue;
3146 for (charnum = 0; charnum < span->len; ++charnum) {
3147 fz_rect bbox;
3148 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3149 b = &bbox;
3151 if (x >= b->x0 && x <= b->x1
3152 && y >= b->y0 && y <= b->y1) {
3153 fz_text_style *style = span->text->style;
3154 const char *n2 =
3155 style->font
3156 ? style->font->name
3157 : "Span has no font name"
3159 FT_FaceRec *face = style->font->ft_face;
3160 if (face && face->family_name) {
3161 char *s;
3162 char *n1 = face->family_name;
3163 size_t l1 = strlen (n1);
3164 size_t l2 = strlen (n2);
3166 if (l1 != l2 || memcmp (n1, n2, l1)) {
3167 s = malloc (l1 + l2 + 2);
3168 if (s) {
3169 memcpy (s, n2, l2);
3170 s[l2] = '=';
3171 memcpy (s + l2 + 1, n1, l1 + 1);
3172 str_v = caml_copy_string (s);
3173 free (s);
3177 if (str_v == Val_unit) {
3178 str_v = caml_copy_string (n2);
3180 ret_v = caml_alloc_small (1, utext);
3181 Field (ret_v, 0) = str_v;
3182 goto unlock;
3189 unlock:
3190 unlock (__func__);
3192 done:
3193 CAMLreturn (ret_v);
3196 enum { mark_page, mark_block, mark_line, mark_word };
3198 static int uninteresting (int c)
3200 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3201 || ispunct (c);
3204 CAMLprim value ml_clearmark (value ptr_v)
3206 CAMLparam1 (ptr_v);
3207 char *s = String_val (ptr_v);
3208 struct page *page;
3210 if (trylock (__func__)) {
3211 goto done;
3214 page = parse_pointer (__func__, s);
3215 page->fmark.span = NULL;
3216 page->lmark.span = NULL;
3217 page->fmark.i = 0;
3218 page->lmark.i = 0;
3220 unlock (__func__);
3221 done:
3222 CAMLreturn (Val_unit);
3225 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3227 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3228 CAMLlocal1 (ret_v);
3229 fz_rect *b;
3230 struct page *page;
3231 fz_text_line *line;
3232 fz_page_block *pageb;
3233 fz_text_block *block;
3234 struct pagedim *pdim;
3235 int mark = Int_val (mark_v);
3236 char *s = String_val (ptr_v);
3237 int x = Int_val (x_v), y = Int_val (y_v);
3239 ret_v = Val_bool (0);
3240 if (trylock (__func__)) {
3241 goto done;
3244 page = parse_pointer (__func__, s);
3245 pdim = &state.pagedims[page->pdimno];
3247 ensuretext (page);
3249 if (mark == mark_page) {
3250 int i;
3251 fz_page_block *pb1 = NULL, *pb2 = NULL;
3253 for (i = 0; i < page->text->len; ++i) {
3254 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3255 pb1 = &page->text->blocks[i];
3256 break;
3259 if (!pb1) goto unlock;
3261 for (i = page->text->len - 1; i >= 0; --i) {
3262 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3263 pb2 = &page->text->blocks[i];
3264 break;
3267 if (!pb2) goto unlock;
3269 block = pb1->u.text;
3271 page->fmark.i = 0;
3272 page->fmark.span = block->lines->first_span;
3274 block = pb2->u.text;
3275 line = &block->lines[block->len - 1];
3276 page->lmark.i = line->last_span->len - 1;
3277 page->lmark.span = line->last_span;
3278 ret_v = Val_bool (1);
3279 goto unlock;
3282 x += pdim->bounds.x0;
3283 y += pdim->bounds.y0;
3285 for (pageb = page->text->blocks;
3286 pageb < page->text->blocks + page->text->len;
3287 ++pageb) {
3288 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3289 block = pageb->u.text;
3291 b = &block->bbox;
3292 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3293 continue;
3295 if (mark == mark_block) {
3296 page->fmark.i = 0;
3297 page->fmark.span = block->lines->first_span;
3299 line = &block->lines[block->len - 1];
3300 page->lmark.i = line->last_span->len - 1;
3301 page->lmark.span = line->last_span;
3302 ret_v = Val_bool (1);
3303 goto unlock;
3306 for (line = block->lines;
3307 line < block->lines + block->len;
3308 ++line) {
3309 fz_text_span *span;
3311 b = &line->bbox;
3312 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3313 continue;
3315 if (mark == mark_line) {
3316 page->fmark.i = 0;
3317 page->fmark.span = line->first_span;
3319 page->lmark.i = line->last_span->len - 1;
3320 page->lmark.span = line->last_span;
3321 ret_v = Val_bool (1);
3322 goto unlock;
3325 for (span = line->first_span; span; span = span->next) {
3326 int charnum;
3328 b = &span->bbox;
3329 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3330 continue;
3332 for (charnum = 0; charnum < span->len; ++charnum) {
3333 fz_rect bbox;
3334 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3335 b = &bbox;
3337 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3338 /* unicode ftw */
3339 int charnum2, charnum3 = -1, charnum4 = -1;
3341 if (uninteresting (span->text[charnum].c)) goto unlock;
3343 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3344 if (uninteresting (span->text[charnum2].c)) {
3345 charnum3 = charnum2 + 1;
3346 break;
3349 if (charnum3 == -1) charnum3 = 0;
3351 for (charnum2 = charnum + 1;
3352 charnum2 < span->len;
3353 ++charnum2) {
3354 if (uninteresting (span->text[charnum2].c)) break;
3355 charnum4 = charnum2;
3357 if (charnum4 == -1) goto unlock;
3359 page->fmark.i = charnum3;
3360 page->fmark.span = span;
3362 page->lmark.i = charnum4;
3363 page->lmark.span = span;
3364 ret_v = Val_bool (1);
3365 goto unlock;
3371 unlock:
3372 if (!Bool_val (ret_v)) {
3373 page->fmark.span = NULL;
3374 page->lmark.span = NULL;
3375 page->fmark.i = 0;
3376 page->lmark.i = 0;
3378 unlock (__func__);
3380 done:
3381 CAMLreturn (ret_v);
3384 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3386 CAMLparam3 (ptr_v, x_v, y_v);
3387 CAMLlocal2 (ret_v, res_v);
3388 fz_rect *b = NULL;
3389 struct page *page;
3390 fz_page_block *pageb;
3391 struct pagedim *pdim;
3392 char *s = String_val (ptr_v);
3393 int x = Int_val (x_v), y = Int_val (y_v);
3395 ret_v = Val_int (0);
3396 if (trylock (__func__)) {
3397 goto done;
3400 page = parse_pointer (__func__, s);
3401 pdim = &state.pagedims[page->pdimno];
3402 x += pdim->bounds.x0;
3403 y += pdim->bounds.y0;
3405 ensuretext (page);
3407 for (pageb = page->text->blocks;
3408 pageb < page->text->blocks + page->text->len;
3409 ++pageb) {
3410 switch (pageb->type) {
3411 case FZ_PAGE_BLOCK_TEXT:
3412 b = &pageb->u.text->bbox;
3413 break;
3415 case FZ_PAGE_BLOCK_IMAGE:
3416 b = &pageb->u.image->bbox;
3417 break;
3419 default:
3420 continue;
3423 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3424 break;
3425 b = NULL;
3427 if (b) {
3428 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3429 ret_v = caml_alloc_small (1, 1);
3430 Store_double_field (res_v, 0, b->x0);
3431 Store_double_field (res_v, 1, b->x1);
3432 Store_double_field (res_v, 2, b->y0);
3433 Store_double_field (res_v, 3, b->y1);
3434 Field (ret_v, 0) = res_v;
3436 unlock (__func__);
3438 done:
3439 CAMLreturn (ret_v);
3442 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3444 CAMLparam2 (ptr_v, rect_v);
3445 fz_rect b;
3446 struct page *page;
3447 struct pagedim *pdim;
3448 char *s = String_val (ptr_v);
3449 int i, x0, x1, y0, y1, fi, li;
3450 fz_text_line *line;
3451 fz_page_block *pageb;
3452 fz_text_block *block;
3453 fz_text_span *span, *fspan, *lspan;
3455 if (trylock (__func__)) {
3456 goto done;
3459 page = parse_pointer (__func__, s);
3460 ensuretext (page);
3462 pdim = &state.pagedims[page->pdimno];
3463 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3464 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3465 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3466 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3468 if (y0 > y1) {
3469 int t = y0;
3470 y0 = y1;
3471 y1 = t;
3472 x0 = x1;
3473 x1 = t;
3476 fi = page->fmark.i;
3477 fspan = page->fmark.span;
3479 li = page->lmark.i;
3480 lspan = page->lmark.span;
3482 for (pageb = page->text->blocks;
3483 pageb < page->text->blocks + page->text->len;
3484 ++pageb) {
3485 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3486 block = pageb->u.text;
3487 for (line = block->lines;
3488 line < block->lines + block->len;
3489 ++line) {
3491 for (span = line->first_span; span; span = span->next) {
3492 for (i = 0; i < span->len; ++i) {
3493 fz_text_char_bbox (state.ctx, &b, span, i);
3495 if (x0 >= b.x0 && x0 <= b.x1
3496 && y0 >= b.y0 && y0 <= b.y1) {
3497 fspan = span;
3498 fi = i;
3500 if (x1 >= b.x0 && x1 <= b.x1
3501 && y1 >= b.y0 && y1 <= b.y1) {
3502 lspan = span;
3503 li = i;
3509 if (x1 < x0 && fspan == lspan) {
3510 i = fi;
3511 span = fspan;
3513 fi = li;
3514 fspan = lspan;
3516 li = i;
3517 lspan = span;
3520 page->fmark.i = fi;
3521 page->fmark.span = fspan;
3523 page->lmark.i = li;
3524 page->lmark.span = lspan;
3526 unlock (__func__);
3528 done:
3529 CAMLreturn (Val_unit);
3532 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3534 char buf[4];
3535 int i, len, ret;
3537 for (i = a; i <= b; ++i) {
3538 len = fz_runetochar (buf, span->text[i].c);
3539 ret = fwrite (buf, len, 1, f);
3541 if (ret != 1) {
3542 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3543 len, ret, strerror (errno));
3544 return -1;
3547 return 0;
3550 #ifdef __CYGWIN__
3551 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3553 caml_failwith ("ml_popen not implemented under Cygwin");
3555 #else
3556 CAMLprim value ml_spawn (value command_v, value fds_v)
3558 CAMLparam2 (command_v, fds_v);
3559 CAMLlocal2 (l_v, tup_v);
3560 int ret, ret1;
3561 pid_t pid;
3562 char *msg = NULL;
3563 value earg_v = Nothing;
3564 posix_spawnattr_t attr;
3565 posix_spawn_file_actions_t fa;
3566 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3568 argv[2] = String_val (command_v);
3570 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3571 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3574 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3575 msg = "posix_spawnattr_init";
3576 goto fail1;
3579 #ifdef POSIX_SPAWN_USEVFORK
3580 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3581 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3582 goto fail;
3584 #endif
3586 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3587 int fd1, fd2;
3589 tup_v = Field (l_v, 0);
3590 fd1 = Int_val (Field (tup_v, 0));
3591 fd2 = Int_val (Field (tup_v, 1));
3592 if (fd2 < 0) {
3593 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3594 msg = "posix_spawn_file_actions_addclose";
3595 earg_v = tup_v;
3596 goto fail;
3599 else {
3600 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3601 msg = "posix_spawn_file_actions_adddup2";
3602 earg_v = tup_v;
3603 goto fail;
3608 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3609 msg = "posix_spawn";
3610 goto fail;
3613 fail:
3614 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3615 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3618 fail1:
3619 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3620 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3621 strerror (ret1));
3624 if (msg)
3625 unix_error (ret, msg, earg_v);
3627 CAMLreturn (Val_int (pid));
3629 #endif
3631 CAMLprim value ml_hassel (value ptr_v)
3633 CAMLparam1 (ptr_v);
3634 CAMLlocal1 (ret_v);
3635 struct page *page;
3636 char *s = String_val (ptr_v);
3638 ret_v = Val_bool (0);
3639 if (trylock (__func__)) {
3640 goto done;
3643 page = parse_pointer (__func__, s);
3644 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3645 unlock (__func__);
3646 done:
3647 CAMLreturn (ret_v);
3650 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3652 CAMLparam2 (fd_v, ptr_v);
3653 FILE *f;
3654 int seen = 0;
3655 struct page *page;
3656 fz_text_line *line;
3657 fz_page_block *pageb;
3658 fz_text_block *block;
3659 int fd = Int_val (fd_v);
3660 char *s = String_val (ptr_v);
3662 if (trylock (__func__)) {
3663 goto done;
3666 page = parse_pointer (__func__, s);
3668 if (!page->fmark.span || !page->lmark.span) {
3669 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3670 goto unlock;
3673 f = fdopen (fd, "w");
3674 if (!f) {
3675 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3676 fd, strerror (errno));
3677 f = stdout;
3680 for (pageb = page->text->blocks;
3681 pageb < page->text->blocks + page->text->len;
3682 ++pageb) {
3683 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3684 block = pageb->u.text;
3685 for (line = block->lines;
3686 line < block->lines + block->len;
3687 ++line) {
3688 fz_text_span *span;
3690 for (span = line->first_span; span; span = span->next) {
3691 int a, b;
3693 seen |= span == page->fmark.span || span == page->lmark.span;
3694 a = span == page->fmark.span ? page->fmark.i : 0;
3695 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3697 if (seen) {
3698 if (pipespan (f, span, a, b)) {
3699 goto close;
3701 if (span == page->lmark.span) {
3702 goto close;
3704 if (span == line->last_span) {
3705 if (putc ('\n', f) == EOF) {
3706 fprintf (stderr,
3707 "failed break line on sel pipe: %s\n",
3708 strerror (errno));
3709 goto close;
3716 close:
3717 if (f != stdout) {
3718 int ret = fclose (f);
3719 fd = -1;
3720 if (ret == -1) {
3721 if (errno != ECHILD) {
3722 fprintf (stderr, "failed to close sel pipe: %s\n",
3723 strerror (errno));
3727 unlock:
3728 unlock (__func__);
3730 done:
3731 if (fd >= 0) {
3732 if (close (fd)) {
3733 fprintf (stderr, "failed to close sel pipe: %s\n",
3734 strerror (errno));
3737 CAMLreturn (Val_unit);
3740 CAMLprim value ml_getpdimrect (value pagedimno_v)
3742 CAMLparam1 (pagedimno_v);
3743 CAMLlocal1 (ret_v);
3744 int pagedimno = Int_val (pagedimno_v);
3745 fz_rect box;
3747 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3748 if (trylock (__func__)) {
3749 box = fz_empty_rect;
3751 else {
3752 box = state.pagedims[pagedimno].mediabox;
3753 unlock (__func__);
3756 Store_double_field (ret_v, 0, box.x0);
3757 Store_double_field (ret_v, 1, box.x1);
3758 Store_double_field (ret_v, 2, box.y0);
3759 Store_double_field (ret_v, 3, box.y1);
3761 CAMLreturn (ret_v);
3764 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3765 value dw_v, value cols_v)
3767 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3768 CAMLlocal1 (ret_v);
3769 int i;
3770 double zoom = -1.;
3771 double maxh = 0.0;
3772 struct pagedim *p;
3773 double winw = Int_val (winw_v);
3774 double winh = Int_val (winh_v);
3775 double dw = Int_val (dw_v);
3776 double cols = Int_val (cols_v);
3777 double pw = 1.0, ph = 1.0;
3779 if (trylock (__func__)) {
3780 goto done;
3783 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3784 double w = p->pagebox.x1 / cols;
3785 double h = p->pagebox.y1;
3786 if (h > maxh) {
3787 maxh = h;
3788 ph = h;
3789 if (state.fitmodel != FitProportional) pw = w;
3791 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3794 zoom = (((winh / ph) * pw) + dw) / winw;
3795 unlock (__func__);
3796 done:
3797 ret_v = caml_copy_double (zoom);
3798 CAMLreturn (ret_v);
3801 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3803 CAMLparam4 (pt_v, x_v, y_v, string_v);
3804 CAMLlocal1 (ret_v);
3805 int pt = Int_val(pt_v);
3806 int x = Int_val (x_v);
3807 int y = Int_val (y_v);
3808 double w;
3810 w = draw_string (state.face, pt, x, y, String_val (string_v));
3811 ret_v = caml_copy_double (w);
3812 CAMLreturn (ret_v);
3815 CAMLprim value ml_measure_string (value pt_v, value string_v)
3817 CAMLparam2 (pt_v, string_v);
3818 CAMLlocal1 (ret_v);
3819 int pt = Int_val (pt_v);
3820 double w;
3822 w = measure_string (state.face, pt, String_val (string_v));
3823 ret_v = caml_copy_double (w);
3824 CAMLreturn (ret_v);
3827 CAMLprim value ml_getpagebox (value opaque_v)
3829 CAMLparam1 (opaque_v);
3830 CAMLlocal1 (ret_v);
3831 fz_rect rect;
3832 fz_irect bbox;
3833 fz_matrix ctm;
3834 fz_device *dev;
3835 char *s = String_val (opaque_v);
3836 struct page *page = parse_pointer (__func__, s);
3838 ret_v = caml_alloc_tuple (4);
3839 dev = fz_new_bbox_device (state.ctx, &rect);
3840 dev->hints |= FZ_IGNORE_SHADE;
3842 ctm = pagectm (page);
3843 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3845 fz_drop_device (state.ctx, dev);
3846 fz_round_rect (&bbox, &rect);
3847 Field (ret_v, 0) = Val_int (bbox.x0);
3848 Field (ret_v, 1) = Val_int (bbox.y0);
3849 Field (ret_v, 2) = Val_int (bbox.x1);
3850 Field (ret_v, 3) = Val_int (bbox.y1);
3852 CAMLreturn (ret_v);
3855 CAMLprim value ml_setaalevel (value level_v)
3857 CAMLparam1 (level_v);
3859 state.aalevel = Int_val (level_v);
3860 CAMLreturn (Val_unit);
3863 #pragma GCC diagnostic push
3864 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3865 #include <X11/Xlib.h>
3866 #include <X11/cursorfont.h>
3867 #pragma GCC diagnostic pop
3869 #include <GL/glx.h>
3871 static const int shapes[] = {
3872 XC_arrow, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3875 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3877 static struct {
3878 Window wid;
3879 Display *dpy;
3880 GLXContext ctx;
3881 XVisualInfo *visual;
3882 Cursor curs[CURS_COUNT];
3883 } glx;
3885 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3887 CAMLparam3 (display_v, wid_v, screen_v);
3888 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3890 glx.dpy = XOpenDisplay (String_val (display_v));
3891 if (!glx.dpy) {
3892 caml_failwith ("XOpenDisplay");
3895 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3896 if (!glx.visual) {
3897 XCloseDisplay (glx.dpy);
3898 caml_failwith ("glXChooseVisual");
3901 for (size_t n = 0; n < CURS_COUNT; ++n) {
3902 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3905 glx.wid = Int_val (wid_v);
3906 CAMLreturn (Val_int (glx.visual->visualid));
3909 CAMLprim value ml_glxcompleteinit (value unit_v)
3911 CAMLparam1 (unit_v);
3913 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3914 if (!glx.ctx) {
3915 caml_failwith ("glXCreateContext");
3918 XFree (glx.visual);
3919 glx.visual = NULL;
3921 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3922 glXDestroyContext (glx.dpy, glx.ctx);
3923 glx.ctx = NULL;
3924 caml_failwith ("glXMakeCurrent");
3926 CAMLreturn (Val_unit);
3929 CAMLprim value ml_setcursor (value cursor_v)
3931 CAMLparam1 (cursor_v);
3932 size_t cursn = Int_val (cursor_v);
3933 XSetWindowAttributes wa;
3935 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3936 wa.cursor = glx.curs[cursn];
3937 XChangeWindowAttributes (glx.dpy, glx.wid, CWCursor, &wa);
3938 XFlush (glx.dpy);
3939 CAMLreturn (Val_unit);
3942 CAMLprim value ml_swapb (value unit_v)
3944 CAMLparam1 (unit_v);
3945 glXSwapBuffers (glx.dpy, glx.wid);
3946 CAMLreturn (Val_unit);
3949 #include "keysym2ucs.c"
3951 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3953 CAMLparam1 (keysym_v);
3954 CAMLlocal1 (str_v);
3955 KeySym keysym = Int_val (keysym_v);
3956 Rune rune;
3957 int len;
3958 char buf[5];
3960 rune = keysym2ucs (keysym);
3961 len = fz_runetochar (buf, rune);
3962 buf[len] = 0;
3963 str_v = caml_copy_string (buf);
3964 CAMLreturn (str_v);
3967 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3969 CAMLprim value ml_platform (value unit_v)
3971 CAMLparam1 (unit_v);
3972 CAMLlocal2 (tup_v, arr_v);
3973 int platid = piunknown;
3974 struct utsname buf;
3976 #if defined __linux__
3977 platid = pilinux;
3978 #elif defined __CYGWIN__
3979 platid = picygwin;
3980 #elif defined __DragonFly__ || defined __FreeBSD__
3981 || defined __OpenBSD__ || defined __NetBSD__
3982 platid = pibsd;
3983 #elif defined __sun__
3984 platid = pisun;
3985 #elif defined __APPLE__
3986 platid = piosx;
3987 #endif
3988 if (uname (&buf)) err (1, "uname");
3990 tup_v = caml_alloc_tuple (2);
3992 char const *sar[] = {
3993 buf.sysname,
3994 buf.release,
3995 buf.version,
3996 buf.machine,
3997 NULL
3999 arr_v = caml_copy_string_array (sar);
4001 Field (tup_v, 0) = Val_int (platid);
4002 Field (tup_v, 1) = arr_v;
4003 CAMLreturn (tup_v);
4006 CAMLprim value ml_cloexec (value fd_v)
4008 CAMLparam1 (fd_v);
4009 int fd = Int_val (fd_v);
4011 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4012 uerror ("fcntl", Nothing);
4014 CAMLreturn (Val_unit);
4017 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4019 CAMLparam2 (w_v, h_v);
4020 CAMLlocal1 (ret_v);
4021 struct pbo *pbo;
4022 int w = Int_val (w_v);
4023 int h = Int_val (h_v);
4024 int cs = Int_val (cs_v);
4026 if (state.pbo_usable) {
4027 pbo = calloc (sizeof (*pbo), 1);
4028 if (!pbo) {
4029 err (1, "calloc pbo");
4032 switch (cs) {
4033 case 0:
4034 case 1:
4035 pbo->size = w*h*4;
4036 break;
4037 case 2:
4038 pbo->size = w*h*2;
4039 break;
4040 default:
4041 errx (1, "ml_getpbo: invalid colorspace %d", cs);
4044 state.glGenBuffersARB (1, &pbo->id);
4045 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4046 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4047 NULL, GL_STREAM_DRAW);
4048 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4049 GL_READ_WRITE);
4050 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4051 if (!pbo->ptr) {
4052 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4053 state.glDeleteBuffersARB (1, &pbo->id);
4054 free (pbo);
4055 ret_v = caml_copy_string ("0");
4057 else {
4058 int res;
4059 char *s;
4061 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4062 if (res < 0) {
4063 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4065 s = malloc (res+1);
4066 if (!s) {
4067 err (1, "malloc %d bytes failed", res+1);
4069 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4070 if (res < 0) {
4071 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4073 ret_v = caml_copy_string (s);
4074 free (s);
4077 else {
4078 ret_v = caml_copy_string ("0");
4080 CAMLreturn (ret_v);
4083 CAMLprim value ml_freepbo (value s_v)
4085 CAMLparam1 (s_v);
4086 char *s = String_val (s_v);
4087 struct tile *tile = parse_pointer (__func__, s);
4089 if (tile->pbo) {
4090 state.glDeleteBuffersARB (1, &tile->pbo->id);
4091 tile->pbo->id = -1;
4092 tile->pbo->ptr = NULL;
4093 tile->pbo->size = -1;
4095 CAMLreturn (Val_unit);
4098 CAMLprim value ml_unmappbo (value s_v)
4100 CAMLparam1 (s_v);
4101 char *s = String_val (s_v);
4102 struct tile *tile = parse_pointer (__func__, s);
4104 if (tile->pbo) {
4105 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4106 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4107 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4109 tile->pbo->ptr = NULL;
4110 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4112 CAMLreturn (Val_unit);
4115 static void setuppbo (void)
4117 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4118 state.pbo_usable = GGPA (glBindBufferARB)
4119 && GGPA (glUnmapBufferARB)
4120 && GGPA (glMapBufferARB)
4121 && GGPA (glBufferDataARB)
4122 && GGPA (glGenBuffersARB)
4123 && GGPA (glDeleteBuffersARB);
4124 #undef GGPA
4127 CAMLprim value ml_pbo_usable (value unit_v)
4129 CAMLparam1 (unit_v);
4130 CAMLreturn (Val_bool (state.pbo_usable));
4133 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4135 CAMLparam3 (ptr_v, x_v, y_v);
4136 CAMLlocal2 (ret_v, tup_v);
4137 struct page *page;
4138 char *s = String_val (ptr_v);
4139 int x = Int_val (x_v), y = Int_val (y_v);
4140 struct pagedim *pdim;
4141 fz_point p;
4142 fz_matrix ctm;
4144 page = parse_pointer (__func__, s);
4145 pdim = &state.pagedims[page->pdimno];
4147 ret_v = Val_int (0);
4148 if (trylock (__func__)) {
4149 goto done;
4152 if (pdf_specifics (state.ctx, state.doc)) {
4153 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4154 ctm = state.pagedims[page->pdimno].tctm;
4156 else {
4157 ctm = fz_identity;
4159 p.x = x + pdim->bounds.x0;
4160 p.y = y + pdim->bounds.y0;
4162 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4163 fz_invert_matrix (&ctm, &ctm);
4164 fz_transform_point (&p, &ctm);
4166 tup_v = caml_alloc_tuple (2);
4167 ret_v = caml_alloc_small (1, 1);
4168 Field (tup_v, 0) = Val_int (p.x);
4169 Field (tup_v, 1) = Val_int (p.y);
4170 Field (ret_v, 0) = tup_v;
4172 unlock (__func__);
4173 done:
4174 CAMLreturn (ret_v);
4177 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4178 value x_v, value y_v)
4180 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4181 CAMLlocal1 (ret_v);
4182 int cleanup = 0;
4183 struct page *page;
4184 char *s = String_val (ptr_v);
4185 int pageno = Int_val (pageno_v);
4186 int pdimno = Int_val (pdimno_v);
4187 double x = Double_val (x_v), y = Double_val (y_v);
4188 struct pagedim *pdim;
4189 fz_point p;
4190 fz_matrix ctm;
4192 ret_v = Val_int (0);
4193 lock (__func__);
4195 if (caml_string_length (ptr_v) == 0) {
4196 cleanup = 1;
4197 page = loadpage (pageno, pdimno);
4199 else {
4200 page = parse_pointer (__func__, s);
4202 pdim = &state.pagedims[pdimno];
4204 if (pdf_specifics (state.ctx, state.doc)) {
4205 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4206 ctm = state.pagedims[page->pdimno].tctm;
4208 else {
4209 ctm = fz_identity;
4211 p.x = x + pdim->bounds.x0;
4212 p.y = y + pdim->bounds.y0;
4214 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4215 fz_transform_point (&p, &ctm);
4217 ret_v = caml_alloc_tuple (2);
4218 Field (ret_v, 0) = caml_copy_double (p.x);
4219 Field (ret_v, 1) = caml_copy_double (p.y);
4221 if (cleanup) {
4222 freepage (page);
4224 unlock (__func__);
4225 CAMLreturn (ret_v);
4228 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4229 value contents_v)
4231 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4232 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4234 if (pdf) {
4235 pdf_annot *annot;
4236 struct page *page;
4237 fz_point p;
4238 char *s = String_val (ptr_v);
4240 page = parse_pointer (__func__, s);
4241 annot = pdf_create_annot (state.ctx, pdf,
4242 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4243 p.x = Int_val (x_v);
4244 p.y = Int_val (y_v);
4245 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4246 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4247 state.dirty = 1;
4249 CAMLreturn (Val_unit);
4252 CAMLprim value ml_delannot (value ptr_v, value n_v)
4254 CAMLparam2 (ptr_v, n_v);
4255 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4257 if (pdf) {
4258 struct page *page;
4259 char *s = String_val (ptr_v);
4260 struct slink *slink;
4262 page = parse_pointer (__func__, s);
4263 slink = &page->slinks[Int_val (n_v)];
4264 pdf_delete_annot (state.ctx, pdf,
4265 (pdf_page *) page->fzpage,
4266 (pdf_annot *) slink->u.annot);
4267 state.dirty = 1;
4269 CAMLreturn (Val_unit);
4272 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4274 CAMLparam3 (ptr_v, n_v, str_v);
4275 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4277 if (pdf) {
4278 struct page *page;
4279 char *s = String_val (ptr_v);
4280 struct slink *slink;
4282 page = parse_pointer (__func__, s);
4283 slink = &page->slinks[Int_val (n_v)];
4284 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4285 String_val (str_v));
4286 state.dirty = 1;
4288 CAMLreturn (Val_unit);
4291 CAMLprim value ml_hasunsavedchanges (value unit_v)
4293 CAMLparam1 (unit_v);
4294 CAMLreturn (Val_bool (state.dirty));
4297 CAMLprim value ml_savedoc (value path_v)
4299 CAMLparam1 (path_v);
4300 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4302 if (pdf) {
4303 pdf_write_document (state.ctx, pdf, String_val (path_v), NULL);
4305 CAMLreturn (Val_unit);
4308 static void makestippletex (void)
4310 const char pixels[] = "\xff\xff\0\0";
4311 glGenTextures (1, &state.stid);
4312 glBindTexture (GL_TEXTURE_1D, state.stid);
4313 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4314 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4315 glTexImage1D (
4316 GL_TEXTURE_1D,
4318 GL_ALPHA,
4321 GL_ALPHA,
4322 GL_UNSIGNED_BYTE,
4323 pixels
4327 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4329 return caml_copy_string (FZ_VERSION);
4332 #ifdef USE_FONTCONFIG
4333 static struct {
4334 int inited;
4335 FcConfig *config;
4336 } fc;
4338 static fz_font *fc_load_system_font_func (fz_context *ctx,
4339 const char *name,
4340 int bold,
4341 int italic,
4342 int UNUSED_ATTR needs_exact_metrics)
4344 char *buf;
4345 size_t i, size;
4346 fz_font *font;
4347 FcChar8 *path;
4348 FcResult result;
4349 FcPattern *pat, *pat1;
4351 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4352 name, bold, italic, needs_exact_metrics);
4353 if (!fc.inited) {
4354 fc.inited = 1;
4355 fc.config = FcInitLoadConfigAndFonts ();
4356 if (!fc.config) {
4357 lprintf ("FcInitLoadConfigAndFonts failed\n");
4358 return NULL;
4361 if (!fc.config) return NULL;
4363 size = strlen (name);
4364 if (bold) size += sizeof (":bold") - 1;
4365 if (italic) size += sizeof (":italic") - 1;
4366 size += 1;
4368 buf = malloc (size);
4369 if (!buf) {
4370 err (1, "malloc %zu failed", size);
4373 strcpy (buf, name);
4374 if (bold && italic) {
4375 strcat (buf, ":bold:italic");
4377 else {
4378 if (bold) strcat (buf, ":bold");
4379 if (italic) strcat (buf, ":italic");
4381 for (i = 0; i < size; ++i) {
4382 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4385 lprintf ("fcbuf=%s\n", buf);
4386 pat = FcNameParse ((FcChar8 *) buf);
4387 if (!pat) {
4388 printd ("emsg FcNameParse failed\n");
4389 free (buf);
4390 return NULL;
4393 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4394 printd ("emsg FcConfigSubstitute failed\n");
4395 free (buf);
4396 return NULL;
4398 FcDefaultSubstitute (pat);
4400 pat1 = FcFontMatch (fc.config, pat, &result);
4401 if (!pat1) {
4402 printd ("emsg FcFontMatch failed\n");
4403 FcPatternDestroy (pat);
4404 free (buf);
4405 return NULL;
4408 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4409 printd ("emsg FcPatternGetString failed\n");
4410 FcPatternDestroy (pat);
4411 FcPatternDestroy (pat1);
4412 free (buf);
4413 return NULL;
4416 #if 0
4417 printd ("emsg name=%s path=%s\n", name, path);
4418 #endif
4419 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4420 FcPatternDestroy (pat);
4421 FcPatternDestroy (pat1);
4422 free (buf);
4423 return font;
4425 #endif
4427 CAMLprim value ml_init (value csock_v, value params_v)
4429 CAMLparam2 (csock_v, params_v);
4430 CAMLlocal2 (trim_v, fuzz_v);
4431 int ret;
4432 int texcount;
4433 char *fontpath;
4434 int colorspace;
4435 int mustoresize;
4436 int haspboext;
4438 state.csock = Int_val (csock_v);
4439 state.rotate = Int_val (Field (params_v, 0));
4440 state.fitmodel = Int_val (Field (params_v, 1));
4441 trim_v = Field (params_v, 2);
4442 texcount = Int_val (Field (params_v, 3));
4443 state.sliceheight = Int_val (Field (params_v, 4));
4444 mustoresize = Int_val (Field (params_v, 5));
4445 colorspace = Int_val (Field (params_v, 6));
4446 fontpath = String_val (Field (params_v, 7));
4448 if (caml_string_length (Field (params_v, 8)) > 0) {
4449 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4451 if (!state.trimcachepath) {
4452 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4453 strerror (errno));
4456 haspboext = Bool_val (Field (params_v, 9));
4458 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4459 fz_register_document_handlers (state.ctx);
4461 #ifdef USE_FONTCONFIG
4462 if (Bool_val (Field (params_v, 10))) {
4463 fz_install_load_system_font_funcs (
4464 state.ctx, fc_load_system_font_func, NULL
4467 #endif
4469 state.trimmargins = Bool_val (Field (trim_v, 0));
4470 fuzz_v = Field (trim_v, 1);
4471 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4472 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4473 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4474 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4476 set_tex_params (colorspace);
4478 if (*fontpath) {
4479 #ifndef USE_FONTCONFIG
4480 state.face = load_font (fontpath);
4481 #else
4482 FcChar8 *path;
4483 FcResult result;
4484 char *buf = fontpath;
4485 FcPattern *pat, *pat1;
4487 fc.inited = 1;
4488 fc.config = FcInitLoadConfigAndFonts ();
4489 if (!fc.config) {
4490 errx (1, "FcInitLoadConfigAndFonts failed");
4493 pat = FcNameParse ((FcChar8 *) buf);
4494 if (!pat) {
4495 errx (1, "FcNameParse failed");
4498 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4499 errx (1, "FcConfigSubstitute failed");
4501 FcDefaultSubstitute (pat);
4503 pat1 = FcFontMatch (fc.config, pat, &result);
4504 if (!pat1) {
4505 errx (1, "FcFontMatch failed");
4508 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4509 errx (1, "FcPatternGetString failed");
4512 state.face = load_font ((char *) path);
4513 FcPatternDestroy (pat);
4514 FcPatternDestroy (pat1);
4515 #endif
4517 else {
4518 unsigned int len;
4519 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4521 state.face = load_builtin_font (base, len);
4523 if (!state.face) _exit (1);
4525 realloctexts (texcount);
4527 if (haspboext) {
4528 setuppbo ();
4531 makestippletex ();
4533 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4534 if (ret) {
4535 errx (1, "pthread_create: %s", strerror (ret));
4538 CAMLreturn (Val_unit);