Clarify
[llpp.git] / link.c
blob1d3d93c210ce5f1cae2d04da1134aef444024a58
1 /* lots of code c&p-ed directly from mupdf */
2 #include <errno.h>
3 #include <stdio.h>
4 #include <ctype.h>
5 #include <string.h>
6 #include <stdlib.h>
7 #include <signal.h>
8 #include <wchar.h>
10 #include <unistd.h>
11 #include <pthread.h>
12 #include <sys/time.h>
13 #include <sys/types.h>
14 #include <sys/ioctl.h>
16 #ifdef __CYGWIN__
17 #include <cygwin/socket.h> /* FIONREAD */
18 #else
19 #include <spawn.h>
20 #endif
22 #include <regex.h>
23 #include <ctype.h>
24 #include <stdarg.h>
25 #include <limits.h>
27 #include <GL/gl.h>
29 #include <caml/fail.h>
30 #include <caml/alloc.h>
31 #include <caml/memory.h>
32 #include <caml/unixsupport.h>
34 #include <fitz.h>
35 #include <mupdf.h>
36 #include <mupdf-internal.h>
37 #include <muxps.h>
38 #include <muxps-internal.h>
39 #include <mucbz.h>
41 #include FT_FREETYPE_H
43 #define PIGGYBACK
45 #ifndef __USE_GNU
46 extern char **environ;
47 #endif
49 #define MIN(a,b) ((a) < (b) ? (a) : (b))
50 #define MAX(a,b) ((a) > (b) ? (a) : (b))
52 #if defined __GNUC__
53 #define NORETURN_ATTR __attribute__ ((noreturn))
54 #define UNUSED_ATTR __attribute__ ((unused))
55 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
56 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
57 #else
58 #define NORETURN_ATTR
59 #define UNUSED_ATTR
60 #define OPTIMIZE_ATTR(n)
61 #define GCC_FMT_ATTR(a, b)
62 #endif
64 #define FMT_s "zu"
66 #define FMT_ptr "p"
67 #define FMT_ptr_cast(p) (p)
68 #define FMT_ptr_cast2(p) (p)
70 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
71 err (int exitcode, const char *fmt, ...)
73 va_list ap;
74 int savederrno;
76 savederrno = errno;
77 va_start (ap, fmt);
78 vfprintf (stderr, fmt, ap);
79 va_end (ap);
80 fprintf (stderr, ": %s\n", strerror (savederrno));
81 fflush (stderr);
82 _exit (exitcode);
85 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
86 errx (int exitcode, const char *fmt, ...)
88 va_list ap;
90 va_start (ap, fmt);
91 vfprintf (stderr, fmt, ap);
92 va_end (ap);
93 fputc ('\n', stderr);
94 fflush (stderr);
95 _exit (exitcode);
98 #ifndef GL_TEXTURE_RECTANGLE_ARB
99 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
100 #endif
102 #ifndef GL_BGRA
103 #define GL_BGRA 0x80E1
104 #endif
106 #ifndef GL_UNSIGNED_INT_8_8_8_8
107 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
108 #endif
110 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
111 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
112 #endif
114 #if 0
115 #define lprintf printf
116 #else
117 #define lprintf(...)
118 #endif
120 #define ARSERT(cond) for (;;) { \
121 if (!(cond)) { \
122 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
124 break; \
127 struct slice {
128 int h;
129 int texindex;
132 struct tile {
133 int x, y, w, h;
134 int slicecount;
135 int sliceheight;
136 struct pbo *pbo;
137 fz_pixmap *pixmap;
138 struct slice slices[1];
141 struct pagedim {
142 int pageno;
143 int rotate;
144 int left;
145 int tctmready;
146 fz_irect bounds;
147 fz_rect pagebox;
148 fz_rect mediabox;
149 fz_matrix ctm, zoomctm, lctm, tctm;
152 struct slink {
153 fz_irect bbox;
154 fz_link *link;
157 enum { DPDF, DXPS, DCBZ };
159 struct page {
160 int tgen;
161 int sgen;
162 int type;
163 int pageno;
164 int pdimno;
165 fz_text_page *text;
166 fz_text_sheet *sheet;
167 union {
168 void *ptr;
169 pdf_page *pdfpage;
170 xps_page *xpspage;
171 cbz_page *cbzpage;
172 } u;
173 fz_display_list *dlist;
174 int slinkcount;
175 struct slink *slinks;
176 struct mark {
177 int i;
178 fz_text_span *span;
179 } fmark, lmark;
180 void (*freepage) (void *);
183 struct {
184 int type;
185 int sliceheight;
186 struct pagedim *pagedims;
187 int pagecount;
188 int pagedimcount;
189 union {
190 pdf_document *pdf;
191 xps_document *xps;
192 cbz_document *cbz;
193 } u;
194 fz_context *ctx;
195 int w, h;
197 int texindex;
198 int texcount;
199 GLuint *texids;
201 GLenum texiform;
202 GLenum texform;
203 GLenum texty;
205 fz_colorspace *colorspace;
207 struct {
208 int w, h;
209 struct slice *slice;
210 } *texowners;
212 int rotate;
213 int proportional;
214 int trimmargins;
215 int needoutline;
216 int gen;
217 int aalevel;
219 int trimanew;
220 fz_irect trimfuzz;
221 fz_pixmap *pig;
223 pthread_t thread;
224 int cr, cw;
225 FT_Face face;
227 void (*closedoc) (void);
228 void (*freepage) (void *);
230 char *trimcachepath;
232 int pbo_usable;
233 void (*glBindBufferARB) (GLenum, GLuint);
234 GLboolean (*glUnmapBufferARB) (GLenum);
235 void *(*glMapBufferARB) (GLenum, GLenum);
236 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
237 void (*glGenBuffersARB) (GLsizei, GLuint *);
238 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
239 } state;
241 struct pbo {
242 GLuint id;
243 void *ptr;
244 size_t size;
247 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
249 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
252 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
254 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
257 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
259 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
260 m.a, m.b, m.c, m.d, m.e, m.f);
263 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
265 static void lock (const char *cap)
267 int ret = pthread_mutex_lock (&mutex);
268 if (ret) {
269 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
273 static void unlock (const char *cap)
275 int ret = pthread_mutex_unlock (&mutex);
276 if (ret) {
277 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
281 static int trylock (const char *cap)
283 int ret = pthread_mutex_trylock (&mutex);
284 if (ret && ret != EBUSY) {
285 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
287 return ret == EBUSY;
290 static void *parse_pointer (const char *cap, const char *s)
292 int ret;
293 void *ptr;
295 ret = sscanf (s, "%" FMT_ptr, FMT_ptr_cast (&ptr));
296 if (ret != 1) {
297 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
299 return ptr;
302 static double now (void)
304 struct timeval tv;
306 if (gettimeofday (&tv, NULL)) {
307 err (1, "gettimeofday");
309 return tv.tv_sec + tv.tv_usec*1e-6;
312 static int hasdata (void)
314 int ret, avail;
315 ret = ioctl (state.cr, FIONREAD, &avail);
316 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
317 return avail > 0;
320 CAMLprim value ml_hasdata (value fd_v)
322 CAMLparam1 (fd_v);
323 int ret, avail;
325 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
326 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
327 CAMLreturn (Val_bool (avail > 0));
330 static void readdata (void *p, int size)
332 ssize_t n;
334 again:
335 n = read (state.cr, p, size);
336 if (n < 0) {
337 if (errno == EINTR) goto again;
338 err (1, "read (req %d, ret %zd)", size, n);
340 if (n - size) {
341 if (!n) errx (1, "EOF while reading");
342 errx (1, "read (req %d, ret %zd)", size, n);
346 static void writedata (char *p, int size)
348 char buf[4];
349 ssize_t n;
351 buf[0] = (size >> 24) & 0xff;
352 buf[1] = (size >> 16) & 0xff;
353 buf[2] = (size >> 8) & 0xff;
354 buf[3] = (size >> 0) & 0xff;
356 n = write (state.cw, buf, 4);
357 if (n != 4) {
358 if (!n) errx (1, "EOF while writing length");
359 err (1, "write %zd", n);
362 n = write (state.cw, p, size);
363 if (n - size) {
364 if (!n) errx (1, "EOF while writing data");
365 err (1, "write (req %d, ret %zd)", size, n);
369 static int readlen (void)
371 unsigned char p[4];
373 readdata (p, 4);
374 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
377 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
379 int size = 200, len;
380 va_list ap;
381 char *buf;
383 buf = malloc (size);
384 for (;;) {
385 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
387 va_start (ap, fmt);
388 len = vsnprintf (buf, size, fmt, ap);
389 va_end (ap);
391 if (len > -1 && len < size) {
392 writedata (buf, len);
393 break;
396 if (len > -1) {
397 size = len + 1;
399 else {
400 size *= 2;
402 buf = realloc (buf, size);
404 free (buf);
407 static void closepdf (void)
409 if (state.u.pdf) {
410 pdf_close_document (state.u.pdf);
411 state.u.pdf = NULL;
415 static void closexps (void)
417 if (state.u.xps) {
418 xps_close_document (state.u.xps);
419 state.u.xps = NULL;
423 static void closecbz (void)
425 if (state.u.cbz) {
426 cbz_close_document (state.u.cbz);
427 state.u.cbz = NULL;
431 static void freepdfpage (void *ptr)
433 pdf_free_page (state.u.pdf, ptr);
436 static void freeemptyxxxpage (void *ptr)
438 (void) ptr;
441 static void freexpspage (void *ptr)
443 xps_free_page (state.u.xps, ptr);
446 static void freecbzpage (void *ptr)
448 cbz_free_page (state.u.cbz, ptr);
451 static void openxref (char *filename, char *password)
453 int i, len;
455 for (i = 0; i < state.texcount; ++i) {
456 state.texowners[i].w = -1;
457 state.texowners[i].slice = NULL;
460 if (state.closedoc) state.closedoc ();
462 len = strlen (filename);
464 state.type = DPDF;
465 if (len > 4) {
466 char ext[4];
468 ext[0] = tolower ((int) filename[len-3]);
469 ext[1] = tolower ((int) filename[len-2]);
470 ext[2] = tolower ((int) filename[len-1]);
472 /**/ if (ext[0] == 'x' && ext[1] == 'p' && ext[2] == 's') {
473 state.type = DXPS;
475 else if (ext[0] == 'c' && ext[1] == 'b' && ext[2] == 'z') {
476 state.type = DCBZ;
480 if (state.pagedims) {
481 free (state.pagedims);
482 state.pagedims = NULL;
484 state.pagedimcount = 0;
486 fz_set_aa_level (state.ctx, state.aalevel);
487 switch (state.type) {
488 case DPDF:
489 state.u.pdf = pdf_open_document (state.ctx, filename);
490 if (pdf_needs_password (state.u.pdf)) {
491 int okay = pdf_authenticate_password (state.u.pdf, password);
492 if (!okay) {
493 errx (1, "invalid password");
496 state.pagecount = pdf_count_pages (state.u.pdf);
497 state.closedoc = closepdf;
498 state.freepage = freepdfpage;
499 break;
501 case DXPS:
502 state.u.xps = xps_open_document (state.ctx, filename);
503 state.pagecount = xps_count_pages (state.u.xps);
504 state.closedoc = closexps;
505 state.freepage = freexpspage;
506 break;
508 case DCBZ:
509 state.u.cbz = cbz_open_document (state.ctx, filename);
510 state.pagecount = cbz_count_pages (state.u.cbz);
511 state.closedoc = closecbz;
512 state.freepage = freecbzpage;
513 break;
517 static void pdfinfo (void)
519 if (state.type == DPDF) {
520 pdf_obj *infoobj;
522 printd ("info PDF version\t%d.%d",
523 state.u.pdf->version / 10, state.u.pdf->version % 10);
525 infoobj = pdf_dict_gets (state.u.pdf->trailer, "Info");
526 if (infoobj) {
527 int i;
528 char *s;
529 char *items[] = { "Title", "Author", "Creator",
530 "Producer", "CreationDate" };
532 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
533 pdf_obj *obj = pdf_dict_gets (infoobj, items[i]);
534 s = pdf_to_utf8 (state.u.pdf, obj);
535 if (*s) {
536 if (i == 0) {
537 printd ("title %s", s);
539 printd ("info %s\t%s", items[i], s);
541 fz_free (state.ctx, s);
544 printd ("infoend");
548 static void unlinktile (struct tile *tile)
550 int i;
552 for (i = 0; i < tile->slicecount; ++i) {
553 struct slice *s = &tile->slices[i];
555 if (s->texindex != -1) {
556 if (state.texowners[s->texindex].slice == s) {
557 state.texowners[s->texindex].slice = NULL;
563 static void freepage (struct page *page)
565 if (page->text) {
566 fz_free_text_page (state.ctx, page->text);
568 if (page->sheet) {
569 fz_free_text_sheet (state.ctx, page->sheet);
571 if (page->slinks) {
572 free (page->slinks);
574 page->freepage (page->u.ptr);
575 fz_free_display_list (state.ctx, page->dlist);
576 free (page);
579 static void freetile (struct tile *tile)
581 unlinktile (tile);
582 if (!tile->pbo) {
583 #ifndef PIGGYBACK
584 fz_drop_pixmap (state.ctx, tile->pixmap);
585 #else
586 if (state.pig) {
587 fz_drop_pixmap (state.ctx, state.pig);
589 state.pig = tile->pixmap;
590 #endif
592 else {
593 free (tile->pbo);
594 fz_drop_pixmap (state.ctx, tile->pixmap);
596 free (tile);
599 #ifdef __ALTIVEC__
600 #include <altivec.h>
602 static int cacheline32bytes;
604 static void __attribute__ ((constructor)) clcheck (void)
606 char **envp = environ;
607 unsigned long *auxv;
609 while (*envp++);
611 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
612 if (*auxv == 19) {
613 cacheline32bytes = auxv[1] == 32;
614 return;
619 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
621 size_t size = pixmap->w * pixmap->h * pixmap->n;
622 if (cacheline32bytes && size > 32) {
623 intptr_t a1, a2, diff;
624 size_t sizea, i;
625 vector unsigned char v = vec_splat_u8 (-1);
626 vector unsigned char *p;
628 a1 = a2 = (intptr_t) pixmap->samples;
629 a2 = (a1 + 31) & ~31;
630 diff = a2 - a1;
631 sizea = size - diff;
632 p = (void *) a2;
634 while (a1 != a2) *(char *) a1++ = 0xff;
635 for (i = 0; i < (sizea & ~31); i += 32) {
636 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
637 vec_st (v, i, p);
638 vec_st (v, i + 16, p);
640 while (i < sizea) *((char *) a1 + i++) = 0xff;
642 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
644 #else
645 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
646 #endif
648 static void trimctm (pdf_page *page, int pindex)
650 fz_matrix ctm;
651 struct pagedim *pdim = &state.pagedims[pindex];
653 if (!pdim->tctmready) {
654 if (state.trimmargins) {
655 fz_rect realbox;
656 fz_matrix rm, sm, tm, im, ctm1;
658 fz_rotate (&rm, -pdim->rotate);
659 fz_scale (&sm, 1, -1);
660 fz_concat (&ctm, &rm, &sm);
661 realbox = pdim->mediabox;
662 fz_transform_rect (&realbox, &ctm);
663 fz_translate (&tm, -realbox.x0, -realbox.y0);
664 fz_concat (&ctm1, &ctm, &tm);
665 fz_invert_matrix (&im, &page->ctm);
666 fz_concat (&ctm, &im, &ctm1);
668 else {
669 ctm = fz_identity;
671 pdim->tctm = ctm;
672 pdim->tctmready = 1;
676 static fz_matrix pagectm (struct page *page)
678 fz_matrix ctm, tm;
680 if (page->type == DPDF) {
681 trimctm (page->u.pdfpage, page->pdimno);
682 fz_concat (&ctm,
683 &state.pagedims[page->pdimno].tctm,
684 &state.pagedims[page->pdimno].ctm);
686 else {
687 struct pagedim *pdim = &state.pagedims[page->pdimno];
689 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
690 fz_concat (&ctm, &tm, &state.pagedims[page->pdimno].ctm);
692 return ctm;
695 static void *loadpage (int pageno, int pindex)
697 fz_device *dev;
698 struct page *page = NULL;
700 page = calloc (sizeof (struct page), 1);
701 if (!page) {
702 err (1, "calloc page %d", pageno);
705 page->dlist = fz_new_display_list (state.ctx);
706 dev = fz_new_list_device (state.ctx, page->dlist);
707 fz_try (state.ctx) {
708 switch (state.type) {
709 case DPDF:
710 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
711 pdf_run_page (state.u.pdf, page->u.pdfpage, dev,
712 &fz_identity, NULL);
713 page->freepage = freepdfpage;
714 break;
716 case DXPS:
717 page->u.xpspage = xps_load_page (state.u.xps, pageno);
718 xps_run_page (state.u.xps, page->u.xpspage, dev,
719 &fz_identity, NULL);
720 page->freepage = freexpspage;
721 break;
723 case DCBZ:
724 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
725 cbz_run_page (state.u.cbz, page->u.cbzpage, dev,
726 &fz_identity, NULL);
727 page->freepage = freecbzpage;
728 break;
731 fz_catch (state.ctx) {
732 page->u.ptr = NULL;
733 page->freepage = freeemptyxxxpage;
735 fz_free_device (dev);
737 page->pdimno = pindex;
738 page->pageno = pageno;
739 page->sgen = state.gen;
740 page->tgen = state.gen;
741 page->type = state.type;
743 return page;
746 static struct tile *alloctile (int h)
748 int i;
749 int slicecount;
750 size_t tilesize;
751 struct tile *tile;
753 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
754 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
755 tile = calloc (tilesize, 1);
756 if (!tile) {
757 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
759 for (i = 0; i < slicecount; ++i) {
760 int sh = MIN (h, state.sliceheight);
761 tile->slices[i].h = sh;
762 tile->slices[i].texindex = -1;
763 h -= sh;
765 tile->slicecount = slicecount;
766 tile->sliceheight = state.sliceheight;
767 return tile;
770 #ifdef OBSCURED_OPT
771 struct obs {
772 int cured;
773 fz_irect b;
776 static void obs_fill_image (fz_device *dev, fz_image *image,
777 const fz_matrix *ctm, float alpha)
779 struct obs *obs = dev->user;
781 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
782 fz_irect b;
783 fz_rect rect = fz_unit_rect;
785 fz_transform_rect (&rect, ctm);
786 fz_round_rect (&b, &rect);
787 fz_intersect_irect (&b, &obs->b);
788 obs->cured = b.x0 == obs->b.x0
789 && b.x1 == obs->b.x1
790 && b.y0 == obs->b.y0
791 && b.y1 == obs->b.y1;
795 static int obscured (struct page *page, fz_irect bbox)
797 fz_rect rect;
798 fz_matrix ctm;
799 fz_device dev;
800 struct obs obs;
802 memset (&dev, 0, sizeof (dev));
803 memset (&obs, 0, sizeof (obs));
804 dev.hints = 0;
805 dev.flags = 0;
806 dev.user = &obs;
807 dev.ctx = state.ctx;
808 dev.fill_image = obs_fill_image;
809 obs.b = bbox;
810 fz_rect_from_irect (&rect, &bbox);
811 ctm = pagectm (page);
812 fz_run_display_list (page->dlist, &dev, &ctm, &rect, NULL);
813 return obs.cured;
815 #define OBSCURED obscured
816 #else
817 #define OBSCURED(a, b) 0
818 #endif
820 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
821 struct pbo *pbo)
823 fz_rect rect;
824 fz_irect bbox;
825 fz_matrix ctm;
826 fz_device *dev;
827 struct tile *tile;
828 struct pagedim *pdim;
830 tile = alloctile (h);
831 pdim = &state.pagedims[page->pdimno];
833 bbox = pdim->bounds;
834 bbox.x0 += x;
835 bbox.y0 += y;
836 bbox.x1 = bbox.x0 + w;
837 bbox.y1 = bbox.y0 + h;
839 if (state.pig) {
840 if (state.pig->w == w
841 && state.pig->h == h
842 && state.pig->colorspace == state.colorspace) {
843 tile->pixmap = state.pig;
844 tile->pixmap->x = bbox.x0;
845 tile->pixmap->y = bbox.y0;
847 else {
848 fz_drop_pixmap (state.ctx, state.pig);
850 state.pig = NULL;
852 if (!tile->pixmap) {
853 if (pbo) {
854 tile->pixmap =
855 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
856 &bbox, pbo->ptr);
857 tile->pbo = pbo;
859 else {
860 tile->pixmap =
861 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
865 tile->w = w;
866 tile->h = h;
867 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
868 clearpixmap (tile->pixmap);
870 dev = fz_new_draw_device (state.ctx, tile->pixmap);
871 ctm = pagectm (page);
872 fz_rect_from_irect (&rect, &bbox);
873 fz_run_display_list (page->dlist, dev, &ctm, &rect, NULL);
874 fz_free_device (dev);
876 return tile;
879 static void initpdims (void)
881 double start, end;
882 int pageno, trim, show;
883 FILE *trimf = NULL;
884 int trimw = 0;
886 start = now ();
888 if (state.trimmargins && state.trimcachepath) {
889 trimf = fopen (state.trimcachepath, "rb");
890 if (!trimf) {
891 trimf = fopen (state.trimcachepath, "wb");
892 trimw = 1;
895 for (pageno = 0; pageno < state.pagecount; ++pageno) {
896 int rotate = 0;
897 struct pagedim *p;
898 fz_rect mediabox;
900 switch (state.type) {
901 case DPDF: {
902 pdf_obj *pageobj = state.u.pdf->page_objs[pageno];
904 if (state.trimmargins) {
905 pdf_obj *obj;
906 pdf_page *page;
908 fz_try (state.ctx) {
909 page = pdf_load_page (state.u.pdf, pageno);
910 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
911 trim = state.trimanew || !obj;
912 if (trim) {
913 fz_rect rect;
914 fz_matrix ctm;
915 fz_device *dev;
917 dev = fz_new_bbox_device (state.ctx, &rect);
918 dev->hints |= FZ_IGNORE_SHADE;
919 fz_invert_matrix (&ctm, &page->ctm);
920 pdf_run_page (state.u.pdf, page, dev, &fz_identity, NULL);
921 fz_free_device (dev);
923 rect.x0 += state.trimfuzz.x0;
924 rect.x1 += state.trimfuzz.x1;
925 rect.y0 += state.trimfuzz.y0;
926 rect.y1 += state.trimfuzz.y1;
927 fz_transform_rect (&rect, &ctm);
928 fz_intersect_rect (&rect, &page->mediabox);
930 if (fz_is_empty_rect (&rect)) {
931 mediabox = page->mediabox;
933 else {
934 mediabox = rect;
937 obj = pdf_new_array (state.ctx, 4);
938 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x0));
939 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y0));
940 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x1));
941 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y1));
942 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
944 else {
945 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
946 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
947 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
948 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
951 rotate = page->rotate;
952 pdf_free_page (state.u.pdf, page);
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 fz_rect cropbox;
968 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "MediaBox"),
969 &mediabox);
970 if (fz_is_empty_rect (&mediabox)) {
971 fprintf (stderr, "cannot find page size for page %d\n",
972 pageno+1);
973 mediabox.x0 = 0;
974 mediabox.y0 = 0;
975 mediabox.x1 = 612;
976 mediabox.y1 = 792;
979 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "CropBox"),
980 &cropbox);
981 if (!fz_is_empty_rect (&cropbox)) {
982 fz_intersect_rect (&mediabox, &cropbox);
984 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
986 break;
989 case DXPS:
991 xps_page *page;
993 fz_try (state.ctx) {
994 page = xps_load_page (state.u.xps, pageno);
995 xps_bound_page (state.u.xps, page, &mediabox);
996 rotate = 0;
997 if (state.trimmargins) {
998 fz_rect rect;
999 fz_device *dev;
1001 dev = fz_new_bbox_device (state.ctx, &rect);
1002 dev->hints |= FZ_IGNORE_SHADE;
1003 xps_run_page (state.u.xps, page, dev,
1004 &fz_identity, NULL);
1005 fz_free_device (dev);
1007 rect.x0 += state.trimfuzz.x0;
1008 rect.x1 += state.trimfuzz.x1;
1009 rect.y0 += state.trimfuzz.y0;
1010 rect.y1 += state.trimfuzz.y1;
1011 fz_intersect_rect (&rect, &mediabox);
1013 if (!fz_is_empty_rect (&rect)) {
1014 mediabox = rect;
1017 xps_free_page (state.u.xps, page);
1018 printd ("progress %f loading %d",
1019 (double) (pageno + 1) / state.pagecount,
1020 pageno + 1);
1022 fz_catch (state.ctx) {
1025 break;
1027 case DCBZ:
1029 rotate = 0;
1030 if (state.trimmargins && trimw) {
1031 cbz_page *page;
1033 fz_try (state.ctx) {
1034 page = cbz_load_page (state.u.cbz, pageno);
1035 cbz_bound_page (state.u.cbz, page, &mediabox);
1036 cbz_free_page (state.u.cbz, page);
1037 printd ("progress %f Trimming %d",
1038 (double) (pageno + 1) / state.pagecount,
1039 pageno + 1);
1041 fz_catch (state.ctx) {
1042 fprintf (stderr, "failed to load page %d\n", pageno+1);
1043 mediabox.x0 = 0;
1044 mediabox.y0 = 0;
1045 mediabox.x1 = 900;
1046 mediabox.y1 = 900;
1048 if (trimf) {
1049 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1050 if (n - 1) {
1051 err (1, "fwrite trim mediabox");
1055 else {
1056 if (trimf) {
1057 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1058 if (n - 1) {
1059 err (1, "fread trim mediabox");
1062 else {
1063 mediabox.x0 = mediabox.y0 = 0;
1064 mediabox.x1 = 900;
1065 mediabox.y1 = 900;
1069 break;
1071 default:
1072 ARSERT (0 && state.type);
1075 if (state.pagedimcount == 0
1076 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1077 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1078 size_t size;
1080 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1081 state.pagedims = realloc (state.pagedims, size);
1082 if (!state.pagedims) {
1083 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1084 size, state.pagedimcount + 1);
1087 p = &state.pagedims[state.pagedimcount++];
1088 p->rotate = rotate;
1089 p->mediabox = mediabox;
1090 p->pageno = pageno;
1093 end = now ();
1094 if (state.trimmargins) {
1095 printd ("progress 1 Trimmed %d pages in %f seconds",
1096 state.pagecount, end - start);
1098 else {
1099 printd ("vmsg Processed %d pages in %f seconds",
1100 state.pagecount, end - start);
1102 state.trimanew = 0;
1103 if (trimf) {
1104 if (fclose (trimf)) {
1105 err (1, "fclose");
1110 static void layout (void)
1112 int pindex;
1113 fz_rect box;
1114 fz_matrix ctm;
1115 double zoom, w, maxw = 0;
1116 struct pagedim *p = state.pagedims;
1118 if (state.proportional) {
1119 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1120 fz_matrix rm;
1122 fz_rotate (&rm, p->rotate + state.rotate);
1123 box = p->mediabox;
1124 fz_transform_rect (&box, &rm);
1125 w = box.x1 - box.x0;
1126 maxw = MAX (w, maxw);
1130 p = state.pagedims;
1131 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1132 fz_rect rect;
1133 fz_matrix tm, sm, rm;
1135 fz_rotate (&ctm, state.rotate);
1136 fz_rotate (&rm, p->rotate + state.rotate);
1137 box = p->mediabox;
1138 fz_transform_rect (&box, &rm);
1139 w = box.x1 - box.x0;
1141 if (state.proportional) {
1142 double scale = w / maxw;
1143 zoom = (state.w / w) * scale;
1145 else {
1146 zoom = state.w / w;
1149 fz_scale (&p->zoomctm, zoom, zoom);
1150 fz_concat (&ctm, &p->zoomctm, &ctm);
1152 fz_rotate (&rm, p->rotate);
1153 p->pagebox = p->mediabox;
1154 fz_transform_rect (&p->pagebox, &rm);
1155 p->pagebox.x1 -= p->pagebox.x0;
1156 p->pagebox.y1 -= p->pagebox.y0;
1157 p->pagebox.x0 = 0;
1158 p->pagebox.y0 = 0;
1159 rect = p->pagebox;
1160 fz_transform_rect (&rect, &ctm);
1161 fz_round_rect (&p->bounds, &rect);
1163 p->left = state.proportional ? ((maxw - w) * zoom) / 2.0 : 0;
1164 p->ctm = ctm;
1166 fz_translate (&tm, 0, -p->mediabox.y1);
1167 fz_scale (&sm, zoom, -zoom);
1168 fz_concat (&ctm, &tm, &sm);
1169 fz_concat (&p->lctm, &ctm, &rm);
1171 p->tctmready = 0;
1174 while (p-- != state.pagedims) {
1175 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1176 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1177 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1178 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1179 int w = x1 - x0;
1180 int h = y1 - y0;
1182 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1186 static
1187 struct anchor { int n; int x; int y; int w; int h; }
1188 desttoanchor (fz_link_dest *dest)
1190 int i;
1191 struct anchor a;
1192 struct pagedim *pdim = state.pagedims;
1194 a.n = -1;
1195 a.x = 0;
1196 a.y = 0;
1197 for (i = 0; i < state.pagedimcount; ++i) {
1198 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1199 break;
1200 pdim = &state.pagedims[i];
1202 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1203 fz_point p;
1204 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1205 p.x = dest->ld.gotor.lt.x;
1206 p.y = dest->ld.gotor.lt.y;
1207 fz_transform_point (&p, &pdim->lctm);
1208 a.y = p.y;
1209 a.x = p.x;
1211 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1212 double x0, x1, y0, y1;
1214 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1215 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1216 a.w = x1 - x0;
1217 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1218 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1219 a.h = y1 - y0;
1220 a.n = dest->ld.gotor.page;
1222 return a;
1225 static void recurse_outline (fz_outline *outline, int level)
1227 while (outline) {
1228 struct anchor a = desttoanchor (&outline->dest);
1230 if (a.n >= 0) {
1231 printd ("o %d %d %d %d %s",
1232 level, a.n, a.y, a.h, outline->title);
1234 if (outline->down) {
1235 recurse_outline (outline->down, level + 1);
1237 outline = outline->next;
1241 static void process_outline (void)
1243 fz_outline *outline;
1245 if (!state.needoutline) return;
1247 state.needoutline = 0;
1248 switch (state.type) {
1249 case DPDF:
1250 outline = pdf_load_outline (state.u.pdf);
1251 break;
1252 case DXPS:
1253 outline = xps_load_outline (state.u.xps);
1254 break;
1255 default:
1256 outline = NULL;
1257 break;
1259 if (outline) {
1260 recurse_outline (outline, 0);
1261 fz_free_outline (state.ctx, outline);
1265 static char *strofspan (fz_text_span *span)
1267 char *p;
1268 char utf8[10];
1269 fz_text_char *ch;
1270 size_t size = 0, cap = 80;
1272 p = malloc (cap + 1);
1273 if (!p) return NULL;
1275 for (ch = span->text; ch < span->text + span->len; ++ch) {
1276 int n = fz_runetochar (utf8, ch->c);
1277 if (size + n > cap) {
1278 cap *= 2;
1279 p = realloc (p, cap + 1);
1280 if (!p) return NULL;
1283 memcpy (p + size, utf8, n);
1284 size += n;
1286 p[size] = 0;
1287 return p;
1290 static int matchspan (regex_t *re, fz_text_span *span, fz_matrix ctm,
1291 int stop, int pageno, double start)
1293 int ret;
1294 char *p;
1295 regmatch_t rm;
1296 int a, b, c;
1297 fz_rect *sb, *eb;
1298 fz_point p1, p2, p3, p4;
1300 p = strofspan (span);
1301 if (!p) return -1;
1303 ret = regexec (re, p, 1, &rm, 0);
1304 if (ret) {
1305 free (p);
1306 if (ret != REG_NOMATCH) {
1307 size_t size;
1308 char errbuf[80];
1309 size = regerror (ret, re, errbuf, sizeof (errbuf));
1310 printd ("msg regexec error `%.*s'",
1311 (int) size, errbuf);
1312 return -1;
1314 return 0;
1316 else {
1317 int l = span->len;
1318 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1319 c += fz_runelen (span->text[a].c);
1321 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1322 c += fz_runelen (span->text[b].c);
1325 if (fz_runelen (span->text[b].c) > 1) {
1326 b = MAX (0, b-1);
1328 sb = &span->text[MIN (a, l-1)].bbox;
1329 eb = &span->text[MIN (b, l-1)].bbox;
1331 p1.x = sb->x0;
1332 p1.y = sb->y0;
1333 p2.x = eb->x1;
1334 p2.y = sb->y0;
1335 p3.x = eb->x1;
1336 p3.y = eb->y1;
1337 p4.x = sb->x0;
1338 p4.y = eb->y1;
1340 if (!stop) {
1341 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1342 pageno, 1,
1343 p1.x, p1.y,
1344 p2.x, p2.y,
1345 p3.x, p3.y,
1346 p4.x, p4.y);
1348 printd ("progress 1 found at %d `%.*s' in %f sec",
1349 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1350 now () - start);
1352 else {
1353 printd ("match %d %d %f %f %f %f %f %f %f %f",
1354 pageno, 2,
1355 p1.x, p1.y,
1356 p2.x, p2.y,
1357 p3.x, p3.y,
1358 p4.x, p4.y);
1360 free (p);
1361 return 1;
1365 static int compareblocks (const void *l, const void *r)
1367 fz_text_block const *ls = l;
1368 fz_text_block const* rs = r;
1369 return ls->bbox.y0 - rs->bbox.y0;
1372 /* wishful thinking function */
1373 static void search (regex_t *re, int pageno, int y, int forward)
1375 int i, j;
1376 fz_matrix ctm;
1377 fz_device *tdev;
1378 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1379 fz_text_page *text;
1380 fz_text_sheet *sheet;
1381 struct pagedim *pdim, *pdimprev;
1382 int stop = 0, niters = 0;
1383 double start, end;
1385 if (!(state.type == DPDF || state.type == DXPS))
1386 return;
1388 start = now ();
1389 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1390 if (niters++ == 5) {
1391 niters = 0;
1392 if (hasdata ()) {
1393 printd ("progress 1 attention requested aborting search at %d",
1394 pageno);
1395 stop = 1;
1397 else {
1398 printd ("progress %f searching in page %d",
1399 (double) (pageno + 1) / state.pagecount,
1400 pageno);
1403 pdimprev = NULL;
1404 for (i = 0; i < state.pagedimcount; ++i) {
1405 pdim = &state.pagedims[i];
1406 if (pdim->pageno == pageno) {
1407 goto found;
1409 if (pdim->pageno > pageno) {
1410 pdim = pdimprev;
1411 goto found;
1413 pdimprev = pdim;
1415 pdim = pdimprev;
1416 found:
1418 sheet = fz_new_text_sheet (state.ctx);
1419 text = fz_new_text_page (state.ctx, &fz_infinite_rect);
1420 tdev = fz_new_text_device (state.ctx, sheet, text);
1422 switch (state.type) {
1423 case DPDF:
1424 u.ptr = NULL;
1425 fz_try (state.ctx) {
1426 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1427 trimctm (u.pdfpage, pdim - state.pagedims);
1428 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1429 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1431 fz_catch (state.ctx) {
1432 fz_free_device (tdev);
1433 u.ptr = NULL;
1434 goto nextiter;
1436 break;
1438 case DXPS:
1439 u.xpspage = xps_load_page (state.u.xps, pageno);
1440 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1441 break;
1443 default:
1444 ARSERT (0 && state.type);
1447 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1448 fz_free_device (tdev);
1450 for (j = 0; j < text->len; ++j) {
1451 int k;
1452 fz_text_block *block;
1454 block = &text->blocks[forward ? j : text->len - 1 - j];
1456 for (k = 0; k < block->len; ++k) {
1457 fz_text_line *line;
1458 fz_text_span *span;
1460 if (forward) {
1461 line = &block->lines[k];
1462 if (line->bbox.y0 < y + 1) continue;
1464 else {
1465 line = &block->lines[block->len - 1 - k];
1466 if (line->bbox.y0 > y - 1) continue;
1469 for (span = line->spans;
1470 span < line->spans + line->len;
1471 ++span) {
1473 switch (matchspan (re, span, ctm, stop, pageno, start)) {
1474 case 0: break;
1475 case 1: stop = 1; break;
1476 case -1: stop = 1; goto endloop;
1481 nextiter:
1482 if (forward) {
1483 pageno += 1;
1484 y = 0;
1486 else {
1487 pageno -= 1;
1488 y = INT_MAX;
1490 endloop:
1491 fz_free_text_page (state.ctx, text);
1492 fz_free_text_sheet (state.ctx, sheet);
1493 if (u.ptr) {
1494 state.freepage (u.ptr);
1497 end = now ();
1498 if (!stop) {
1499 printd ("progress 1 no matches %f sec", end - start);
1501 printd ("clearrects");
1504 static void set_tex_params (int colorspace)
1506 union {
1507 unsigned char b;
1508 unsigned int s;
1509 } endianness = {1};
1511 switch (colorspace) {
1512 case 0:
1513 state.texiform = GL_RGBA8;
1514 state.texform = GL_RGBA;
1515 state.texty = GL_UNSIGNED_BYTE;
1516 state.colorspace = fz_device_rgb;
1517 break;
1518 case 1:
1519 state.texiform = GL_RGBA8;
1520 state.texform = GL_BGRA;
1521 state.texty = endianness.s > 1
1522 ? GL_UNSIGNED_INT_8_8_8_8
1523 : GL_UNSIGNED_INT_8_8_8_8_REV;
1524 state.colorspace = fz_device_bgr;
1525 break;
1526 case 2:
1527 state.texiform = GL_LUMINANCE_ALPHA;
1528 state.texform = GL_LUMINANCE_ALPHA;
1529 state.texty = GL_UNSIGNED_BYTE;
1530 state.colorspace = fz_device_gray;
1531 break;
1532 default:
1533 errx (1, "invalid colorspce %d", colorspace);
1537 static void realloctexts (int texcount)
1539 size_t size;
1541 if (texcount == state.texcount) return;
1543 if (texcount < state.texcount) {
1544 glDeleteTextures (state.texcount - texcount,
1545 state.texids + texcount);
1548 size = texcount * sizeof (*state.texids);
1549 state.texids = realloc (state.texids, size);
1550 if (!state.texids) {
1551 err (1, "realloc texids %" FMT_s, size);
1554 size = texcount * sizeof (*state.texowners);
1555 state.texowners = realloc (state.texowners, size);
1556 if (!state.texowners) {
1557 err (1, "realloc texowners %" FMT_s, size);
1559 if (texcount > state.texcount) {
1560 int i;
1562 glGenTextures (texcount - state.texcount,
1563 state.texids + state.texcount);
1564 for (i = state.texcount; i < texcount; ++i) {
1565 state.texowners[i].w = -1;
1566 state.texowners[i].slice = NULL;
1569 state.texcount = texcount;
1570 state.texindex = 0;
1573 static char *mbtoutf8 (char *s)
1575 char *p, *r;
1576 wchar_t *tmp;
1577 size_t i, ret, len;
1579 len = mbstowcs (NULL, s, strlen (s));
1580 if (len == 0) {
1581 return s;
1583 else {
1584 if (len == (size_t) -1) {
1585 return s;
1589 tmp = malloc (len * sizeof (wchar_t));
1590 if (!tmp) {
1591 return s;
1594 ret = mbstowcs (tmp, s, len);
1595 if (ret == (size_t) -1) {
1596 free (tmp);
1597 return s;
1600 len = 0;
1601 for (i = 0; i < ret; ++i) {
1602 len += fz_runelen (tmp[i]);
1605 p = r = malloc (len + 1);
1606 if (!r) {
1607 free (tmp);
1608 return s;
1611 for (i = 0; i < ret; ++i) {
1612 p += fz_runetochar (p, tmp[i]);
1614 *p = 0;
1615 free (tmp);
1616 return r;
1619 CAMLprim value ml_mbtoutf8 (value s_v)
1621 CAMLparam1 (s_v);
1622 CAMLlocal1 (ret_v);
1623 char *s, *r;
1625 s = String_val (s_v);
1626 r = mbtoutf8 (s);
1627 if (r == s) {
1628 ret_v = s_v;
1630 else {
1631 ret_v = caml_copy_string (r);
1632 free (r);
1634 CAMLreturn (ret_v);
1637 static void * mainloop (void *unused)
1639 char *p = NULL;
1640 int len, ret, oldlen = 0;
1642 for (;;) {
1643 len = readlen ();
1644 if (len == 0) {
1645 errx (1, "readlen returned 0");
1648 if (oldlen < len + 1) {
1649 p = realloc (p, len + 1);
1650 if (!p) {
1651 err (1, "realloc %d failed", len + 1);
1653 oldlen = len + 1;
1655 readdata (p, len);
1656 p[len] = 0;
1658 if (!strncmp ("open", p, 4)) {
1659 size_t filenamelen;
1660 int wthack, off;
1661 char *password;
1662 char *filename;
1663 char *utf8filename;
1665 ret = sscanf (p + 5, " %d %n", &wthack, &off);
1666 if (ret != 1) {
1667 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1670 filename = p + 5 + off;
1671 filenamelen = strlen (filename);
1672 password = filename + filenamelen + 1;
1674 lock ("open");
1675 openxref (filename, password);
1676 pdfinfo ();
1677 initpdims ();
1678 unlock ("open");
1680 if (!wthack) {
1681 utf8filename = mbtoutf8 (filename);
1682 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1683 if (utf8filename != filename) {
1684 free (utf8filename);
1687 state.needoutline = 1;
1689 else if (!strncmp ("cs", p, 2)) {
1690 int i, colorspace;
1692 ret = sscanf (p + 2, " %d", &colorspace);
1693 if (ret != 1) {
1694 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1696 lock ("cs");
1697 set_tex_params (colorspace);
1698 for (i = 0; i < state.texcount; ++i) {
1699 state.texowners[i].w = -1;
1700 state.texowners[i].slice = NULL;
1702 unlock ("cs");
1704 else if (!strncmp ("freepage", p, 8)) {
1705 void *ptr;
1707 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1708 if (ret != 1) {
1709 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1711 freepage (ptr);
1713 else if (!strncmp ("freetile", p, 8)) {
1714 void *ptr;
1716 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1717 if (ret != 1) {
1718 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1720 freetile (ptr);
1722 else if (!strncmp ("search", p, 6)) {
1723 int icase, pageno, y, ret, len2, forward;
1724 char *pattern;
1725 regex_t re;
1727 ret = sscanf (p + 6, " %d %d %d %d,%n",
1728 &icase, &pageno, &y, &forward, &len2);
1729 if (ret != 4) {
1730 errx (1, "malformed search `%s' ret=%d", p, ret);
1733 pattern = p + 6 + len2;
1734 ret = regcomp (&re, pattern,
1735 REG_EXTENDED | (icase ? REG_ICASE : 0));
1736 if (ret) {
1737 char errbuf[80];
1738 size_t size;
1740 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1741 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1743 else {
1744 search (&re, pageno, y, forward);
1745 regfree (&re);
1748 else if (!strncmp ("geometry", p, 8)) {
1749 int w, h;
1751 printd ("clear");
1752 ret = sscanf (p + 8, " %d %d", &w, &h);
1753 if (ret != 2) {
1754 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1757 lock ("geometry");
1758 state.h = h;
1759 if (w != state.w) {
1760 int i;
1761 state.w = w;
1762 for (i = 0; i < state.texcount; ++i) {
1763 state.texowners[i].slice = NULL;
1766 layout ();
1767 process_outline ();
1769 state.gen++;
1770 unlock ("geometry");
1771 printd ("continue %d", state.pagecount);
1773 else if (!strncmp ("reqlayout", p, 9)) {
1774 char *nameddest;
1775 int rotate, proportional, off;
1777 printd ("clear");
1778 ret = sscanf (p + 9, " %d %d %n", &rotate, &proportional, &off);
1779 if (ret != 2) {
1780 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1782 lock ("reqlayout");
1783 if (state.rotate != rotate || state.proportional != proportional) {
1784 state.gen += 1;
1786 state.rotate = rotate;
1787 state.proportional = proportional;
1788 layout ();
1789 process_outline ();
1791 nameddest = p + 9 + off;
1792 if (state.type == DPDF && nameddest && *nameddest) {
1793 struct anchor a;
1794 fz_link_dest dest;
1795 pdf_obj *needle, *obj;
1797 needle = pdf_new_string (state.ctx, nameddest,
1798 strlen (nameddest));
1799 obj = pdf_lookup_dest (state.u.pdf, needle);
1800 if (obj) {
1801 dest = pdf_parse_link_dest (state.u.pdf, obj);
1803 a = desttoanchor (&dest);
1804 if (a.n >= 0) {
1805 printd ("a %d %d %d", a.n, a.x, a.y);
1807 else {
1808 printd ("emsg failed to parse destination `%s'\n",
1809 nameddest);
1812 else {
1813 printd ("emsg destination `%s' not found\n",
1814 nameddest);
1816 pdf_drop_obj (needle);
1819 state.gen++;
1820 unlock ("reqlayout");
1821 printd ("continue %d", state.pagecount);
1823 else if (!strncmp ("page", p, 4)) {
1824 double a, b;
1825 struct page *page;
1826 int pageno, pindex, ret;
1828 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1829 if (ret != 2) {
1830 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1833 lock ("page");
1834 a = now ();
1835 page = loadpage (pageno, pindex);
1836 b = now ();
1837 unlock ("page");
1839 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1841 else if (!strncmp ("tile", p, 4)) {
1842 int x, y, w, h, ret;
1843 struct page *page;
1844 struct tile *tile;
1845 double a, b;
1846 void *data;
1848 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
1849 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
1850 if (ret != 6) {
1851 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1854 lock ("tile");
1855 a = now ();
1856 tile = rendertile (page, x, y, w, h, data);
1857 b = now ();
1858 unlock ("tile");
1860 printd ("tile %d %d %" FMT_ptr " %u %f",
1861 x, y,
1862 FMT_ptr_cast2 (tile),
1863 tile->w * tile->h * tile->pixmap->n,
1864 b - a);
1866 else if (!strncmp ("settrim", p, 7)) {
1867 int trimmargins;
1868 fz_irect fuzz;
1870 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1871 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1872 if (ret != 5) {
1873 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1875 printd ("clear");
1876 lock ("settrim");
1877 state.trimmargins = trimmargins;
1878 state.needoutline = 1;
1879 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1880 state.trimanew = 1;
1881 state.trimfuzz = fuzz;
1883 state.pagedimcount = 0;
1884 free (state.pagedims);
1885 state.pagedims = NULL;
1886 initpdims ();
1887 layout ();
1888 process_outline ();
1889 unlock ("settrim");
1890 printd ("continue %d", state.pagecount);
1892 else if (!strncmp ("sliceh", p, 6)) {
1893 int h;
1895 ret = sscanf (p + 6, " %d", &h);
1896 if (ret != 1) {
1897 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1899 if (h != state.sliceheight) {
1900 int i;
1902 state.sliceheight = h;
1903 for (i = 0; i < state.texcount; ++i) {
1904 state.texowners[i].w = -1;
1905 state.texowners[i].h = -1;
1906 state.texowners[i].slice = NULL;
1910 else if (!strncmp ("interrupt", p, 9)) {
1911 printd ("vmsg interrupted");
1913 else {
1914 errx (1, "unknown command %.*s", len, p);
1917 return 0;
1920 CAMLprim value ml_realloctexts (value texcount_v)
1922 CAMLparam1 (texcount_v);
1923 int ok;
1925 if (trylock ("ml_realloctexts")) {
1926 ok = 0;
1927 goto done;
1929 realloctexts (Int_val (texcount_v));
1930 ok = 1;
1931 unlock ("ml_realloctexts");
1933 done:
1934 CAMLreturn (Val_bool (ok));
1937 static void showsel (struct page *page, int ox, int oy)
1939 int seen = 0;
1940 fz_irect bbox;
1941 fz_rect rect;
1942 fz_text_line *line;
1943 fz_text_span *span;
1944 fz_text_block *block;
1945 struct mark first, last;
1947 first = page->fmark;
1948 last = page->lmark;
1950 if (!first.span || !last.span) return;
1952 glEnable (GL_BLEND);
1953 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1954 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1956 ox += state.pagedims[page->pdimno].bounds.x0;
1957 oy += state.pagedims[page->pdimno].bounds.y0;
1958 for (block = page->text->blocks;
1959 block < page->text->blocks + page->text->len;
1960 ++block) {
1961 for (line = block->lines;
1962 line < block->lines + block->len;
1963 ++line) {
1964 rect = fz_empty_rect;
1965 for (span = line->spans;
1966 span < line->spans + line->len;
1967 ++span) {
1968 int i, j, k;
1970 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1972 j = 0;
1973 k = span->len - 1;
1975 if (span == page->fmark.span && span == page->lmark.span) {
1976 seen = 1;
1977 j = MIN (first.i, last.i);
1978 k = MAX (first.i, last.i);
1980 else if (span == first.span) {
1981 seen = 1;
1982 j = first.i;
1984 else if (span == last.span) {
1985 seen = 1;
1986 k = last.i;
1989 if (seen) {
1990 for (i = j; i <= k; ++i) {
1991 fz_union_rect (&rect, &span->text[i].bbox);
1993 fz_round_rect (&bbox, &rect);
1994 lprintf ("%d %d %d %d oy=%d ox=%d\n",
1995 bbox.x0,
1996 bbox.y0,
1997 bbox.x1,
1998 bbox.y1,
1999 oy, ox);
2001 glRecti (bbox.x0 + ox, bbox.y0 + oy,
2002 bbox.x1 + ox, bbox.y1 + oy);
2003 if (span == last.span) {
2004 goto done;
2010 done:
2011 glDisable (GL_BLEND);
2014 #include "glfont.c"
2016 static void highlightlinks (struct page *page, int xoff, int yoff)
2018 fz_matrix ctm, tm, pm;
2019 fz_link *link, *links;
2021 switch (page->type) {
2022 case DPDF:
2023 links = page->u.pdfpage->links;
2024 break;
2026 case DXPS:
2027 links = page->u.xpspage->links;
2028 break;
2030 default:
2031 return;
2034 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2035 glEnable (GL_LINE_STIPPLE);
2036 glLineStipple (0.5, 0xcccc);
2038 xoff -= state.pagedims[page->pdimno].bounds.x0;
2039 yoff -= state.pagedims[page->pdimno].bounds.y0;
2040 fz_translate (&tm, xoff, yoff);
2041 pm = pagectm (page);
2042 fz_concat (&ctm, &pm, &tm);
2044 glBegin (GL_QUADS);
2045 for (link = links; link; link = link->next) {
2046 fz_point p1, p2, p3, p4;
2048 p1.x = link->rect.x0;
2049 p1.y = link->rect.y0;
2051 p2.x = link->rect.x1;
2052 p2.y = link->rect.y0;
2054 p3.x = link->rect.x1;
2055 p3.y = link->rect.y1;
2057 p4.x = link->rect.x0;
2058 p4.y = link->rect.y1;
2060 fz_transform_point (&p1, &ctm);
2061 fz_transform_point (&p2, &ctm);
2062 fz_transform_point (&p3, &ctm);
2063 fz_transform_point (&p4, &ctm);
2065 switch (link->dest.kind) {
2066 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2067 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2068 default: glColor3ub (0, 0, 0); break;
2071 glVertex2f (p1.x, p1.y);
2072 glVertex2f (p2.x, p2.y);
2073 glVertex2f (p3.x, p3.y);
2074 glVertex2f (p4.x, p4.y);
2076 glEnd ();
2078 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2079 glDisable (GL_LINE_STIPPLE);
2082 static int compareslinks (const void *l, const void *r)
2084 struct slink const *ls = l;
2085 struct slink const *rs = r;
2086 if (ls->bbox.y0 == rs->bbox.y0) {
2087 return rs->bbox.x0 - rs->bbox.x0;
2089 return ls->bbox.y0 - rs->bbox.y0;
2092 static void droptext (struct page *page)
2094 if (page->text) {
2095 fz_free_text_page (state.ctx, page->text);
2096 page->fmark.i = -1;
2097 page->lmark.i = -1;
2098 page->fmark.span = NULL;
2099 page->lmark.span = NULL;
2100 page->text = NULL;
2102 if (page->sheet) {
2103 fz_free_text_sheet (state.ctx, page->sheet);
2107 static void dropslinks (struct page *page)
2109 if (page->slinks) {
2110 free (page->slinks);
2111 page->slinks = NULL;
2112 page->slinkcount = 0;
2116 static void ensureslinks (struct page *page)
2118 fz_matrix ctm;
2119 int i, count = 0;
2120 size_t slinksize = sizeof (*page->slinks);
2121 fz_link *link, *links;
2123 if (state.gen != page->sgen) {
2124 dropslinks (page);
2125 page->sgen = state.gen;
2127 if (page->slinks) return;
2129 switch (page->type) {
2130 case DPDF:
2131 links = page->u.pdfpage->links;
2132 trimctm (page->u.pdfpage, page->pdimno);
2133 fz_concat (&ctm,
2134 &state.pagedims[page->pdimno].tctm,
2135 &state.pagedims[page->pdimno].ctm);
2136 break;
2138 case DXPS:
2139 links = page->u.xpspage->links;
2140 ctm = state.pagedims[page->pdimno].ctm;
2141 break;
2143 default:
2144 return;
2147 for (link = links; link; link = link->next) {
2148 count++;
2150 if (count > 0) {
2151 page->slinkcount = count;
2152 page->slinks = calloc (count, slinksize);
2153 if (!page->slinks) {
2154 err (1, "realloc slinks %d", count);
2157 for (i = 0, link = links; link; ++i, link = link->next) {
2158 fz_rect rect;
2160 rect = link->rect;
2161 fz_transform_rect (&rect, &ctm);
2162 page->slinks[i].link = link;
2163 fz_round_rect (&page->slinks[i].bbox, &rect);
2165 qsort (page->slinks, count, slinksize, compareslinks);
2169 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2170 static void fmt_linkn (char *s, unsigned int u)
2172 unsigned int len; unsigned int q;
2173 int zma = 'z' - 'a' + 1;
2174 len = 1; q = u;
2175 while (q > zma - 1) { ++len; q /= zma; }
2176 if (s) {
2177 s += len;
2178 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2179 /* handles u == 0 */
2181 s[len] = 0;
2184 static void highlightslinks (struct page *page, int xoff, int yoff,
2185 int noff, char *targ, int tlen, int hfsize)
2187 int i;
2188 char buf[40];
2189 struct slink *slink;
2190 double x0, y0, x1, y1, w;
2192 ensureslinks (page);
2193 glColor3ub (0xc3, 0xb0, 0x91);
2194 for (i = 0; i < page->slinkcount; ++i) {
2195 fmt_linkn (buf, i + noff);
2196 if (!tlen || !strncmp (targ, buf, tlen)) {
2197 slink = &page->slinks[i];
2199 x0 = slink->bbox.x0 + xoff - 5;
2200 y1 = slink->bbox.y0 + yoff - 5;
2201 y0 = y1 + 10 + hfsize;
2202 w = measure_string (state.face, hfsize, buf);
2203 x1 = x0 + w + 10;
2204 glRectd (x0, y0, x1, y1);
2208 glEnable (GL_BLEND);
2209 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2210 glEnable (GL_TEXTURE_2D);
2211 glColor3ub (0, 0, 0);
2212 for (i = 0; i < page->slinkcount; ++i) {
2213 fmt_linkn (buf, i + noff);
2214 if (!tlen || !strncmp (targ, buf, tlen)) {
2215 slink = &page->slinks[i];
2217 x0 = slink->bbox.x0 + xoff;
2218 y0 = slink->bbox.y0 + yoff + hfsize;
2219 draw_string (state.face, hfsize, x0, y0, buf);
2222 glDisable (GL_TEXTURE_2D);
2223 glDisable (GL_BLEND);
2227 static void uploadslice (struct tile *tile, struct slice *slice)
2229 int offset;
2230 struct slice *slice1;
2231 unsigned char *texdata;
2233 offset = 0;
2234 for (slice1 = tile->slices; slice != slice1; slice1++) {
2235 offset += slice1->h * tile->w * tile->pixmap->n;
2237 if (slice->texindex != -1 && slice->texindex < state.texcount
2238 && state.texowners[slice->texindex].slice == slice) {
2239 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2241 else {
2242 int subimage = 0;
2243 int texindex = state.texindex++ % state.texcount;
2245 if (state.texowners[texindex].w == tile->w) {
2246 if (state.texowners[texindex].h >= slice->h) {
2247 subimage = 1;
2249 else {
2250 state.texowners[texindex].h = slice->h;
2253 else {
2254 state.texowners[texindex].h = slice->h;
2257 state.texowners[texindex].w = tile->w;
2258 state.texowners[texindex].slice = slice;
2259 slice->texindex = texindex;
2261 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2262 if (tile->pbo) {
2263 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2264 texdata = 0;
2266 else {
2267 texdata = tile->pixmap->samples;
2269 if (subimage) {
2270 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2274 tile->w,
2275 slice->h,
2276 state.texform,
2277 state.texty,
2278 texdata+offset
2281 else {
2282 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2284 state.texiform,
2285 tile->w,
2286 slice->h,
2288 state.texform,
2289 state.texty,
2290 texdata+offset
2293 if (tile->pbo) {
2294 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2299 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2301 CAMLparam2 (args_v, ptr_v);
2302 int dispx = Int_val (Field (args_v, 0));
2303 int dispy = Int_val (Field (args_v, 1));
2304 int dispw = Int_val (Field (args_v, 2));
2305 int disph = Int_val (Field (args_v, 3));
2306 int tilex = Int_val (Field (args_v, 4));
2307 int tiley = Int_val (Field (args_v, 5));
2308 char *s = String_val (ptr_v);
2309 struct tile *tile = parse_pointer ("ml_drawtile", s);
2311 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2313 int slicey, firstslice;
2314 struct slice *slice;
2316 firstslice = tiley / tile->sliceheight;
2317 slice = &tile->slices[firstslice];
2318 slicey = tiley % tile->sliceheight;
2320 while (disph > 0) {
2321 int dh;
2323 dh = slice->h - slicey;
2324 dh = MIN (disph, dh);
2325 uploadslice (tile, slice);
2327 glBegin (GL_QUADS);
2329 glTexCoord2i (tilex, slicey);
2330 glVertex2i (dispx, dispy);
2332 glTexCoord2i (tilex+dispw, slicey);
2333 glVertex2i (dispx+dispw, dispy);
2335 glTexCoord2i (tilex+dispw, slicey+dh);
2336 glVertex2i (dispx+dispw, dispy+dh);
2338 glTexCoord2i (tilex, slicey+dh);
2339 glVertex2i (dispx, dispy+dh);
2341 glEnd ();
2343 dispy += dh;
2344 disph -= dh;
2345 slice++;
2346 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2347 slicey = 0;
2350 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2351 CAMLreturn (Val_unit);
2354 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2355 value xoff_v, value yoff_v,
2356 value li_v)
2358 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2359 int xoff = Int_val (xoff_v);
2360 int yoff = Int_val (yoff_v);
2361 int noff = Int_val (Field (li_v, 0));
2362 char *targ = String_val (Field (li_v, 1));
2363 int tlen = caml_string_length (Field (li_v, 1));
2364 int hfsize = Int_val (Field (li_v, 2));
2365 char *s = String_val (ptr_v);
2366 int hlmask = Int_val (hlinks_v);
2367 struct page *page = parse_pointer ("ml_postprocess", s);
2369 if (!page->u.ptr) {
2370 /* deal with loadpage failed pages */
2371 goto done;
2374 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2375 if (trylock ("ml_postprocess")) {
2376 noff = 0;
2377 goto done;
2379 if (hlmask & 2) {
2380 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2381 noff = page->slinkcount;
2383 showsel (page, xoff, yoff);
2384 unlock ("ml_postprocess");
2386 done:
2387 CAMLreturn (Val_int (noff));
2390 static fz_link *getlink (struct page *page, int x, int y)
2392 fz_point p;
2393 fz_matrix ctm;
2394 const fz_matrix *tctm;
2395 fz_link *link, *links;
2397 switch (page->type) {
2398 case DPDF:
2399 trimctm (page->u.pdfpage, page->pdimno);
2400 tctm = &state.pagedims[page->pdimno].tctm;
2401 links = page->u.pdfpage->links;
2402 break;
2404 case DXPS:
2405 tctm = &fz_identity;
2406 links = page->u.xpspage->links;
2407 break;
2409 default:
2410 return NULL;
2412 p.x = x;
2413 p.y = y;
2415 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2416 fz_invert_matrix (&ctm, &ctm);
2417 fz_transform_point (&p, &ctm);
2419 for (link = links; link; link = link->next) {
2420 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2421 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2422 return link;
2426 return NULL;
2429 static void ensuretext (struct page *page)
2431 if (state.gen != page->tgen) {
2432 droptext (page);
2433 page->tgen = state.gen;
2435 if (!page->text) {
2436 fz_matrix ctm;
2437 fz_device *tdev;
2439 page->text = fz_new_text_page (state.ctx, &fz_infinite_rect);
2440 page->sheet = fz_new_text_sheet (state.ctx);
2441 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2442 ctm = pagectm (page);
2443 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2444 qsort (page->text->blocks, page->text->len,
2445 sizeof (*page->text->blocks), compareblocks);
2446 fz_free_device (tdev);
2450 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2452 CAMLparam2 (start_page_v, dir_v);
2453 CAMLlocal1 (ret_v);
2454 int i, dir = Int_val (dir_v);
2455 int start_page = Int_val (start_page_v);
2456 int end_page = dir > 0 ? state.pagecount : -1;
2458 ret_v = Val_int (0);
2459 if (!(state.type == DPDF || state.type == DXPS)) {
2460 goto done;
2463 lock ("ml_findpage_with_links");
2464 for (i = start_page + dir; i != end_page; i += dir) {
2465 int found;
2467 switch (state.type) {
2468 case DPDF:
2470 pdf_page *page = NULL;
2472 fz_try (state.ctx) {
2473 page = pdf_load_page (state.u.pdf, i);
2474 found = !!page->links;
2476 fz_catch (state.ctx) {
2477 found = 0;
2479 if (page) {
2480 freepdfpage (page);
2483 break;
2484 case DXPS:
2486 xps_page *page = xps_load_page (state.u.xps, i);
2487 found = !!page->links;
2488 freexpspage (page);
2490 break;
2492 default:
2493 ARSERT ("invalid document type");
2496 if (found) {
2497 ret_v = caml_alloc_small (1, 1);
2498 Field (ret_v, 0) = Val_int (i);
2499 goto unlock;
2502 unlock:
2503 unlock ("ml_findpage_with_links");
2505 done:
2506 CAMLreturn (ret_v);
2509 enum { dir_first, dir_last};
2510 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2512 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2514 CAMLparam2 (ptr_v, dir_v);
2515 CAMLlocal2 (ret_v, pos_v);
2516 struct page *page;
2517 int dirtag, i, slinkindex;
2518 struct slink *found = NULL ,*slink;
2519 char *s = String_val (ptr_v);
2521 page = parse_pointer ("ml_findlink", s);
2522 ret_v = Val_int (0);
2523 if (trylock ("ml_findlink")) {
2524 goto done;
2527 ensureslinks (page);
2529 if (Is_block (dir_v)) {
2530 dirtag = Tag_val (dir_v);
2531 switch (dirtag) {
2532 case dir_first_visible:
2534 int x0, y0, dir, first_index, last_index;
2536 pos_v = Field (dir_v, 0);
2537 x0 = Int_val (Field (pos_v, 0));
2538 y0 = Int_val (Field (pos_v, 1));
2539 dir = Int_val (Field (pos_v, 2));
2541 if (dir >= 0) {
2542 dir = 1;
2543 first_index = 0;
2544 last_index = page->slinkcount;
2546 else {
2547 first_index = page->slinkcount - 1;
2548 last_index = -1;
2551 for (i = first_index; i != last_index; i += dir) {
2552 slink = &page->slinks[i];
2553 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2554 found = slink;
2555 break;
2559 break;
2561 case dir_left:
2562 slinkindex = Int_val (Field (dir_v, 0));
2563 found = &page->slinks[slinkindex];
2564 for (i = slinkindex - 1; i >= 0; --i) {
2565 slink = &page->slinks[i];
2566 if (slink->bbox.x0 < found->bbox.x0) {
2567 found = slink;
2568 break;
2571 break;
2573 case dir_right:
2574 slinkindex = Int_val (Field (dir_v, 0));
2575 found = &page->slinks[slinkindex];
2576 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2577 slink = &page->slinks[i];
2578 if (slink->bbox.x0 > found->bbox.x0) {
2579 found = slink;
2580 break;
2583 break;
2585 case dir_down:
2586 slinkindex = Int_val (Field (dir_v, 0));
2587 found = &page->slinks[slinkindex];
2588 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2589 slink = &page->slinks[i];
2590 if (slink->bbox.y0 >= found->bbox.y0) {
2591 found = slink;
2592 break;
2595 break;
2597 case dir_up:
2598 slinkindex = Int_val (Field (dir_v, 0));
2599 found = &page->slinks[slinkindex];
2600 for (i = slinkindex - 1; i >= 0; --i) {
2601 slink = &page->slinks[i];
2602 if (slink->bbox.y0 <= found->bbox.y0) {
2603 found = slink;
2604 break;
2607 break;
2610 else {
2611 dirtag = Int_val (dir_v);
2612 switch (dirtag) {
2613 case dir_first:
2614 found = page->slinks;
2615 break;
2617 case dir_last:
2618 if (page->slinks) {
2619 found = page->slinks + (page->slinkcount - 1);
2621 break;
2624 if (found) {
2625 ret_v = caml_alloc_small (2, 1);
2626 Field (ret_v, 0) = Val_int (found - page->slinks);
2629 unlock ("ml_findlink");
2630 done:
2631 CAMLreturn (ret_v);
2634 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2636 #define LINKTOVAL \
2638 int pageno; \
2640 switch (link->dest.kind) { \
2641 case FZ_LINK_GOTO: \
2643 fz_point p; \
2645 pageno = link->dest.ld.gotor.page; \
2646 p.x = 0; \
2647 p.y = 0; \
2649 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2650 p.y = link->dest.ld.gotor.lt.y; \
2651 fz_transform_point (&p, &pdim->lctm); \
2653 tup_v = caml_alloc_tuple (2); \
2654 ret_v = caml_alloc_small (1, ugoto); \
2655 Field (tup_v, 0) = Val_int (pageno); \
2656 Field (tup_v, 1) = Val_int (p.y); \
2657 Field (ret_v, 0) = tup_v; \
2659 break; \
2661 case FZ_LINK_URI: \
2662 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2663 ret_v = caml_alloc_small (1, uuri); \
2664 Field (ret_v, 0) = str_v; \
2665 break; \
2667 case FZ_LINK_LAUNCH: \
2668 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2669 ret_v = caml_alloc_small (1, ulaunch); \
2670 Field (ret_v, 0) = str_v; \
2671 break; \
2673 case FZ_LINK_NAMED: \
2674 str_v = caml_copy_string (link->dest.ld.named.named); \
2675 ret_v = caml_alloc_small (1, unamed); \
2676 Field (ret_v, 0) = str_v; \
2677 break; \
2679 case FZ_LINK_GOTOR: \
2680 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2681 pageno = link->dest.ld.gotor.page; \
2682 tup_v = caml_alloc_tuple (2); \
2683 ret_v = caml_alloc_small (1, uremote); \
2684 Field (tup_v, 0) = str_v; \
2685 Field (tup_v, 1) = Val_int (pageno); \
2686 Field (ret_v, 0) = tup_v; \
2687 break; \
2689 default: \
2691 char buf[80]; \
2693 snprintf (buf, sizeof (buf), \
2694 "unhandled link kind %d", link->dest.kind); \
2695 str_v = caml_copy_string (buf); \
2696 ret_v = caml_alloc_small (1, uunexpected); \
2697 Field (ret_v, 0) = str_v; \
2699 break; \
2703 CAMLprim value ml_getlink (value ptr_v, value n_v)
2705 CAMLparam2 (ptr_v, n_v);
2706 CAMLlocal3 (ret_v, tup_v, str_v);
2707 fz_link *link;
2708 struct page *page;
2709 struct pagedim *pdim;
2710 char *s = String_val (ptr_v);
2712 ret_v = Val_int (0);
2713 if (trylock ("ml_getlink")) {
2714 goto done;
2717 page = parse_pointer ("ml_getlink", s);
2718 ensureslinks (page);
2719 pdim = &state.pagedims[page->pdimno];
2720 link = page->slinks[Int_val (n_v)].link;
2721 LINKTOVAL;
2723 unlock ("ml_getlink");
2724 done:
2725 CAMLreturn (ret_v);
2728 CAMLprim value ml_getlinkcount (value ptr_v)
2730 CAMLparam1 (ptr_v);
2731 struct page *page;
2732 char *s = String_val (ptr_v);
2734 page = parse_pointer ("ml_getlinkcount", s);
2735 CAMLreturn (Val_int (page->slinkcount));
2738 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2740 CAMLparam2 (ptr_v, n_v);
2741 CAMLlocal1 (ret_v);
2742 struct page *page;
2743 struct slink *slink;
2744 char *s = String_val (ptr_v);
2746 page = parse_pointer ("ml_getlinkrect", s);
2747 ret_v = caml_alloc_tuple (4);
2748 if (trylock ("ml_getlinkrect")) {
2749 Field (ret_v, 0) = Val_int (0);
2750 Field (ret_v, 1) = Val_int (0);
2751 Field (ret_v, 2) = Val_int (0);
2752 Field (ret_v, 3) = Val_int (0);
2753 goto done;
2755 ensureslinks (page);
2757 slink = &page->slinks[Int_val (n_v)];
2758 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2759 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2760 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2761 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2762 unlock ("ml_getlinkrect");
2764 done:
2765 CAMLreturn (ret_v);
2768 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2770 CAMLparam3 (ptr_v, x_v, y_v);
2771 CAMLlocal3 (ret_v, tup_v, str_v);
2772 fz_link *link;
2773 struct page *page;
2774 char *s = String_val (ptr_v);
2775 int x = Int_val (x_v), y = Int_val (y_v);
2776 struct pagedim *pdim;
2778 ret_v = Val_int (0);
2779 if (trylock ("ml_whatsunder")) {
2780 goto done;
2783 page = parse_pointer ("ml_whatsunder", s);
2784 pdim = &state.pagedims[page->pdimno];
2785 x += pdim->bounds.x0;
2786 y += pdim->bounds.y0;
2787 link = getlink (page, x, y);
2788 if (link) {
2789 LINKTOVAL;
2791 else {
2792 fz_rect *b;
2793 fz_text_block *block;
2795 ensuretext (page);
2796 for (block = page->text->blocks;
2797 block < page->text->blocks + page->text->len;
2798 ++block) {
2799 fz_text_line *line;
2801 b = &block->bbox;
2802 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2803 continue;
2805 for (line = block->lines;
2806 line < block->lines + block->len;
2807 ++line) {
2808 fz_text_span *span;
2810 b = &line->bbox;
2811 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2812 continue;
2814 for (span = line->spans;
2815 span < line->spans + line->len;
2816 ++span) {
2817 fz_text_char *ch;
2819 b = &span->bbox;
2820 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2821 continue;
2823 for (ch = span->text; ch < span->text + span->len; ++ch) {
2824 b = &ch->bbox;
2826 if (x >= b->x0 && x <= b->x1
2827 && y >= b->y0 && y <= b->y1) {
2828 const char *n2 =
2829 span->style->font && span->style->font->name
2830 ? span->style->font->name
2831 : "Span has no font name"
2833 FT_FaceRec *face = span->style->font->ft_face;
2834 if (face && face->family_name) {
2835 char *s;
2836 char *n1 = face->family_name;
2837 size_t l1 = strlen (n1);
2838 size_t l2 = strlen (n2);
2840 if (l1 != l2 || memcmp (n1, n2, l1)) {
2841 s = malloc (l1 + l2 + 2);
2842 if (s) {
2843 memcpy (s, n2, l2);
2844 s[l2] = '=';
2845 memcpy (s + l2 + 1, n1, l1 + 1);
2846 str_v = caml_copy_string (s);
2847 free (s);
2851 if (str_v == 0) {
2852 str_v = caml_copy_string (n2);
2854 ret_v = caml_alloc_small (1, utext);
2855 Field (ret_v, 0) = str_v;
2856 goto unlock;
2863 unlock:
2864 unlock ("ml_whatsunder");
2866 done:
2867 CAMLreturn (ret_v);
2870 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2872 CAMLparam2 (ptr_v, rect_v);
2873 fz_rect *b;
2874 struct page *page;
2875 struct pagedim *pdim;
2876 int i, x0, x1, y0, y1;
2877 char *s = String_val (ptr_v);
2878 int fi = 0, li = 0;
2879 fz_text_block *block;
2880 fz_text_span *span, *fspan, *lspan;
2881 fz_text_line *line, *fline = NULL, *lline = NULL;
2883 if (trylock ("ml_seltext")) {
2884 goto done;
2887 page = parse_pointer ("ml_seltext", s);
2888 ensuretext (page);
2890 pdim = &state.pagedims[page->pdimno];
2891 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2892 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2893 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2894 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2896 if (0) {
2897 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2898 glColor3ub (128, 128, 128);
2899 glRecti (x0, y0, x1, y1);
2900 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2903 fspan = lspan = NULL;
2905 for (block = page->text->blocks;
2906 block < page->text->blocks + page->text->len;
2907 ++block) {
2908 for (line = block->lines;
2909 line < block->lines + block->len;
2910 ++line) {
2911 for (span = line->spans;
2912 span < line->spans + line->len;
2913 ++span) {
2914 for (i = 0; i < span->len; ++i) {
2915 b = &span->text[i].bbox;
2916 int selected = 0;
2918 if (x0 >= b->x0 && x0 <= b->x1
2919 && y0 >= b->y0 && y0 <= b->y1) {
2920 fspan = span;
2921 fline = line;
2922 fi = i;
2923 selected = 1;
2925 if (x1 >= b->x0 && x1 <= b->x1
2926 && y1 >= b->y0 && y1 <= b->y1) {
2927 lspan = span;
2928 lline = line;
2929 li = i;
2930 selected = 1;
2932 if (0 && selected) {
2933 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2934 glColor3ub (128, 128, 128);
2935 glRecti (b->x0, b->y0, b->x1, b->y1);
2936 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2942 if (y1 < y0 || x1 < x0) {
2943 int swap = 0;
2945 if (fspan == lspan) {
2946 swap = 1;
2948 else {
2949 if (y1 < y0) {
2950 if (fline != lline) {
2951 swap = 1;
2956 if (swap) {
2957 i = fi;
2958 span = fspan;
2960 fi = li;
2961 fspan = lspan;
2963 li = i;
2964 lspan = span;
2968 page->fmark.i = fi;
2969 page->fmark.span = fspan;
2971 page->lmark.i = li;
2972 page->lmark.span = lspan;
2974 unlock ("ml_seltext");
2976 done:
2977 CAMLreturn (Val_unit);
2980 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
2982 char buf[4];
2983 int i, len, ret;
2985 for (i = a; i <= b; ++i) {
2986 len = fz_runetochar (buf, span->text[i].c);
2987 ret = fwrite (buf, len, 1, f);
2989 if (ret != 1) {
2990 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
2991 len, ret, strerror (errno));
2992 return -1;
2995 return 0;
2998 #ifdef __CYGWIN__
2999 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3001 caml_failwith ("ml_popen not implemented under Cygwin");
3003 #else
3004 CAMLprim value ml_popen (value command_v, value fds_v)
3006 CAMLparam2 (command_v, fds_v);
3007 CAMLlocal2 (l_v, tup_v);
3008 int ret;
3009 char *msg = NULL;
3010 value earg_v = Nothing;
3011 posix_spawnattr_t attr;
3012 posix_spawn_file_actions_t fa;
3013 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
3015 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3016 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3019 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3020 msg = "posix_spawnattr_init";
3021 goto fail1;
3024 #ifdef POSIX_SPAWN_USEVFORK
3025 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3026 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3027 goto fail;
3029 #endif
3031 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3032 int fd1, fd2;
3034 tup_v = Field (l_v, 0);
3035 fd1 = Int_val (Field (tup_v, 0));
3036 fd2 = Int_val (Field (tup_v, 1));
3037 if (fd2 < 0) {
3038 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3039 msg = "posix_spawn_file_actions_addclose";
3040 earg_v = tup_v;
3041 goto fail;
3044 else {
3045 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3046 msg = "posix_spawn_file_actions_adddup2";
3047 earg_v = tup_v;
3048 goto fail;
3053 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3054 msg = "posix_spawn";
3055 goto fail;
3058 fail:
3059 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3060 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3063 fail1:
3064 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3065 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3066 strerror (ret));
3069 if (msg)
3070 unix_error (ret, msg, earg_v);
3072 CAMLreturn (Val_unit);
3074 #endif
3076 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3078 CAMLparam1 (ptr_v);
3079 FILE *f;
3080 int seen = 0;
3081 struct page *page;
3082 fz_text_line *line;
3083 fz_text_span *span;
3084 fz_text_block *block;
3085 int fd = Int_val (fd_v);
3086 char *s = String_val (ptr_v);
3088 if (trylock ("ml_copysel")) {
3089 goto done;
3092 page = parse_pointer ("ml_sopysel", s);
3094 if (!page->fmark.span || !page->lmark.span) {
3095 fprintf (stderr, "nothing to copy\n");
3096 goto unlock;
3099 f = fdopen (fd, "w");
3100 if (!f) {
3101 fprintf (stderr, "failed to fopen sel pipe: %s\n",
3102 strerror (errno));
3103 f = stdout;
3106 for (block = page->text->blocks;
3107 block < page->text->blocks + page->text->len;
3108 ++block) {
3109 for (line = block->lines;
3110 line < block->lines + block->len;
3111 ++line) {
3112 for (span = line->spans;
3113 span < line->spans + line->len;
3114 ++span) {
3115 int a, b;
3117 seen |= span == page->fmark.span || span == page->lmark.span;
3118 a = span == page->fmark.span ? page->fmark.i : 0;
3119 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3121 if (seen) {
3122 if (pipespan (f, span, a, b)) {
3123 goto close;
3125 if (span == line->spans + line->len - 1) {
3126 if (putc ('\n', f) == EOF) {
3127 fprintf (stderr,
3128 "failed break line on sel pipe: %s\n",
3129 strerror (errno));
3130 goto close;
3133 if (span == page->lmark.span) {
3134 goto endloop;
3140 endloop:
3141 page->lmark.span = NULL;
3142 page->fmark.span = NULL;
3144 close:
3145 if (f != stdout) {
3146 int ret = fclose (f);
3147 fd = -1;
3148 if (ret == -1) {
3149 if (errno != ECHILD) {
3150 fprintf (stderr, "failed to close sel pipe: %s\n",
3151 strerror (errno));
3155 unlock:
3156 unlock ("ml_copysel");
3158 done:
3159 if (fd >= 0) {
3160 if (close (fd)) {
3161 fprintf (stderr, "failed to close sel pipe: %s\n",
3162 strerror (errno));
3165 CAMLreturn (Val_unit);
3168 CAMLprim value ml_getpdimrect (value pagedimno_v)
3170 CAMLparam1 (pagedimno_v);
3171 CAMLlocal1 (ret_v);
3172 int pagedimno = Int_val (pagedimno_v);
3173 fz_rect box;
3175 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3176 if (trylock ("ml_getpdimrect")) {
3177 box = fz_empty_rect;
3179 else {
3180 box = state.pagedims[pagedimno].mediabox;
3181 unlock ("ml_getpdimrect");
3184 Store_double_field (ret_v, 0, box.x0);
3185 Store_double_field (ret_v, 1, box.x1);
3186 Store_double_field (ret_v, 2, box.y0);
3187 Store_double_field (ret_v, 3, box.y1);
3189 CAMLreturn (ret_v);
3192 static double getmaxw (void)
3194 int i;
3195 struct pagedim *p;
3196 double maxw = 0.0;
3198 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3199 double x0, x1, w;
3201 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
3202 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
3204 w = x1 - x0;
3205 maxw = MAX (w, maxw);
3207 return maxw;
3210 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3211 value dw_v, value cols_v)
3213 CAMLparam3 (winw_v, winh_v, dw_v);
3214 CAMLlocal1 (ret_v);
3215 int i;
3216 double zoom = 1.0;
3217 double maxw = 0.0, maxh = 0.0;
3218 struct pagedim *p;
3219 double winw = Int_val (winw_v);
3220 double winh = Int_val (winh_v);
3221 double dw = Int_val (dw_v);
3222 double cols = Int_val (cols_v);
3223 double pw = 1.0, ph = 1.0, aspect;
3225 if (trylock ("ml_zoom_for_height")) {
3226 goto done;
3229 if (state.proportional) {
3230 maxw = getmaxw () / cols;
3233 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3234 fz_rect rect;
3235 fz_matrix rm;
3236 double x0, x1, y0, y1, w, h, scaledh, scale;
3238 fz_rotate (&rm, p->rotate + state.rotate);
3239 rect = p->mediabox;
3240 fz_transform_rect (&rect, &rm);
3241 x0 = MIN (rect.x0, rect.x1);
3242 x1 = MAX (rect.x0, rect.x1);
3243 y0 = MIN (rect.y0, rect.y1);
3244 y1 = MAX (rect.y0, rect.y1);
3246 w = (x1 - x0) / cols;
3247 h = y1 - y0;
3249 if (state.proportional) {
3250 scale = w / maxw;
3251 scaledh = h * scale;
3253 else {
3254 scale = 1.0;
3255 scaledh = h;
3258 if (scaledh > maxh) {
3259 maxh = scaledh;
3260 ph = scaledh;
3261 pw = w * scale;
3265 aspect = pw / ph;
3266 zoom = (winh * aspect + dw) / winw;
3268 unlock ("ml_zoom_for_height");
3269 done:
3270 ret_v = caml_copy_double (zoom);
3271 CAMLreturn (ret_v);
3274 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3276 CAMLparam4 (pt_v, x_v, y_v, string_v);
3277 CAMLlocal1 (ret_v);
3278 int pt = Int_val(pt_v);
3279 int x = Int_val (x_v);
3280 int y = Int_val (y_v);
3281 double w;
3283 w = draw_string (state.face, pt, x, y, String_val (string_v));
3284 ret_v = caml_copy_double (w);
3285 CAMLreturn (ret_v);
3288 CAMLprim value ml_measure_string (value pt_v, value string_v)
3290 CAMLparam2 (pt_v, string_v);
3291 CAMLlocal1 (ret_v);
3292 int pt = Int_val (pt_v);
3293 double w;
3295 w = measure_string (state.face, pt, String_val (string_v));
3296 ret_v = caml_copy_double (w);
3297 CAMLreturn (ret_v);
3300 CAMLprim value ml_getpagebox (value opaque_v)
3302 CAMLparam1 (opaque_v);
3303 CAMLlocal1 (ret_v);
3304 fz_rect rect;
3305 fz_irect bbox;
3306 fz_matrix ctm;
3307 fz_device *dev;
3308 char *s = String_val (opaque_v);
3309 struct page *page = parse_pointer ("ml_getpagebox", s);
3311 ret_v = caml_alloc_tuple (4);
3312 dev = fz_new_bbox_device (state.ctx, &rect);
3313 dev->hints |= FZ_IGNORE_SHADE;
3315 switch (page->type) {
3316 case DPDF:
3317 ctm = pagectm (page);
3318 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3319 break;
3321 case DXPS:
3322 ctm = pagectm (page);
3323 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3324 break;
3326 default:
3327 rect = fz_infinite_rect;
3328 break;
3331 fz_free_device (dev);
3332 fz_round_rect (&bbox, &rect);
3333 Field (ret_v, 0) = Val_int (bbox.x0);
3334 Field (ret_v, 1) = Val_int (bbox.y0);
3335 Field (ret_v, 2) = Val_int (bbox.x1);
3336 Field (ret_v, 3) = Val_int (bbox.y1);
3338 CAMLreturn (ret_v);
3341 CAMLprim value ml_setaalevel (value level_v)
3343 CAMLparam1 (level_v);
3345 state.aalevel = Int_val (level_v);
3346 CAMLreturn (Val_unit);
3349 #undef pixel
3350 #include <X11/Xlib.h>
3351 #include <GL/glx.h>
3353 static struct {
3354 Display *dpy;
3355 GLXContext ctx;
3356 GLXDrawable drawable;
3357 } glx;
3359 #include "keysym2ucs.c"
3361 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3363 CAMLparam1 (keysym_v);
3364 CAMLlocal1 (str_v);
3365 KeySym keysym = Int_val (keysym_v);
3366 Rune rune;
3367 int len;
3368 char buf[5];
3370 rune = keysym2ucs (keysym);
3371 len = fz_runetochar (buf, rune);
3372 buf[len] = 0;
3373 str_v = caml_copy_string (buf);
3374 CAMLreturn (str_v);
3377 CAMLprim value ml_glx (value win_v)
3379 CAMLparam1 (win_v);
3380 XVisualInfo *visual;
3381 int screen, wid = Int_val (win_v);
3382 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3384 glx.dpy = XOpenDisplay (NULL);
3385 if (!glx.dpy) {
3386 caml_failwith ("XOpenDisplay");
3389 screen = DefaultScreen (glx.dpy);
3390 visual = glXChooseVisual (glx.dpy, screen, attributes);
3391 if (!visual) {
3392 XCloseDisplay (glx.dpy);
3393 glx.dpy = NULL;
3394 caml_failwith ("glXChooseVisual");
3397 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3398 XFree (visual);
3399 if (!glx.ctx) {
3400 XCloseDisplay (glx.dpy);
3401 glx.dpy = NULL;
3402 caml_failwith ("glXCreateContext");
3405 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3406 glXDestroyContext (glx.dpy, glx.ctx);
3407 XCloseDisplay (glx.dpy);
3408 glx.dpy = NULL;
3409 glx.ctx = NULL;
3410 caml_failwith ("glXMakeCurrent");
3412 glx.drawable = wid;
3413 CAMLreturn (Val_unit);
3416 CAMLprim value ml_swapb (value unit_v)
3418 CAMLparam1 (unit_v);
3419 glXSwapBuffers (glx.dpy, glx.drawable);
3420 CAMLreturn (Val_unit);
3423 CAMLprim value ml_glxsync (value unit_v)
3425 CAMLparam1 (unit_v);
3426 if (glx.dpy && glx.ctx) {
3427 glXWaitX ();
3428 glXWaitGL ();
3430 CAMLreturn (Val_unit);
3433 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3434 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3436 CAMLprim value ml_platform (value unit_v)
3438 CAMLparam1 (unit_v);
3439 int platid = piunknown;
3441 #if defined __linux__
3442 platid = pilinux;
3443 #elif defined __CYGWIN__
3444 platid = picygwin;
3445 #elif defined __DragonFly__
3446 platid = pidragonflybsd;
3447 #elif defined __FreeBSD__
3448 platid = pifreebsd;
3449 #elif defined __OpenBSD__
3450 platid = piopenbsd;
3451 #elif defined __NetBSD__
3452 platid = pinetbsd;
3453 #elif defined __sun__
3454 platid = pisun;
3455 #elif defined __APPLE__
3456 platid = piosx;
3457 #endif
3458 CAMLreturn (Val_int (platid));
3461 CAMLprim value ml_cloexec (value fd_v)
3463 CAMLparam1 (fd_v);
3464 int fd = Int_val (fd_v);
3466 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3467 uerror ("fcntl", Nothing);
3469 CAMLreturn (Val_unit);
3472 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3474 CAMLparam2 (w_v, h_v);
3475 CAMLlocal1 (ret_v);
3476 struct pbo *pbo;
3477 int w = Int_val (w_v);
3478 int h = Int_val (h_v);
3479 int cs = Int_val (cs_v);
3481 if (state.pbo_usable) {
3482 pbo = calloc (sizeof (*pbo), 1);
3483 if (!pbo) {
3484 err (1, "calloc pbo");
3487 switch (cs) {
3488 case 0:
3489 case 1:
3490 pbo->size = w*h*4;
3491 break;
3492 case 2:
3493 pbo->size = w*h*2;
3494 break;
3495 default:
3496 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3499 state.glGenBuffersARB (1, &pbo->id);
3500 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3501 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3502 NULL, GL_STREAM_DRAW);
3503 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3504 GL_READ_WRITE);
3505 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3506 if (!pbo->ptr) {
3507 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3508 state.glDeleteBuffersARB (1, &pbo->id);
3509 free (pbo);
3510 ret_v = caml_copy_string ("0");
3512 else {
3513 int res;
3514 char *s;
3516 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3517 if (res < 0) {
3518 err (1, "snprintf %" FMT_ptr " failed", pbo);
3520 s = malloc (res+1);
3521 if (!s) {
3522 err (1, "malloc %d bytes failed", res+1);
3524 res = sprintf (s, "%" FMT_ptr, pbo);
3525 if (res < 0) {
3526 err (1, "sprintf %" FMT_ptr " failed", pbo);
3528 ret_v = caml_copy_string (s);
3529 free (s);
3532 else {
3533 ret_v = caml_copy_string ("0");
3535 CAMLreturn (ret_v);
3538 CAMLprim value ml_freepbo (value s_v)
3540 CAMLparam1 (s_v);
3541 char *s = String_val (s_v);
3542 struct tile *tile = parse_pointer ("ml_freepbo", s);
3544 if (tile->pbo) {
3545 state.glDeleteBuffersARB (1, &tile->pbo->id);
3546 tile->pbo->id = -1;
3547 tile->pbo->ptr = NULL;
3548 tile->pbo->size = -1;
3550 CAMLreturn (Val_unit);
3553 CAMLprim value ml_unmappbo (value s_v)
3555 CAMLparam1 (s_v);
3556 char *s = String_val (s_v);
3557 struct tile *tile = parse_pointer ("ml_unmappbo", s);
3559 if (tile->pbo) {
3560 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3561 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3562 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3564 tile->pbo->ptr = NULL;
3565 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3567 CAMLreturn (Val_unit);
3570 static void setuppbo (void)
3572 #define GGPA(n) *(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n)
3573 GGPA (glBindBufferARB);
3574 if (state.glBindBufferARB) {
3575 GGPA (glUnmapBufferARB);
3576 if (state.glUnmapBufferARB) {
3577 GGPA (glMapBufferARB);
3578 if (state.glMapBufferARB) {
3579 GGPA (glBufferDataARB);
3580 if (state.glBufferDataARB) {
3581 GGPA (glGenBuffersARB);
3582 if (state.glGenBuffersARB) {
3583 GGPA (glDeleteBuffersARB);
3584 if (state.glDeleteBuffersARB) {
3585 state.pbo_usable = 1;
3592 #undef GGPA
3595 CAMLprim value ml_pbo_usable (value unit_v)
3597 CAMLparam1 (unit_v);
3598 CAMLreturn (Val_bool (state.pbo_usable));
3601 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3603 CAMLparam3 (ptr_v, x_v, y_v);
3604 CAMLlocal2 (ret_v, tup_v);
3605 struct page *page;
3606 char *s = String_val (ptr_v);
3607 int x = Int_val (x_v), y = Int_val (y_v);
3608 struct pagedim *pdim;
3609 fz_point p;
3610 fz_matrix ctm;
3612 page = parse_pointer ("ml_unproject", s);
3613 pdim = &state.pagedims[page->pdimno];
3615 ret_v = Val_int (0);
3616 if (trylock ("ml_unproject")) {
3617 goto done;
3620 switch (page->type) {
3621 case DPDF:
3622 trimctm (page->u.pdfpage, page->pdimno);
3623 break;
3625 default:
3626 break;
3628 p.x = x;
3629 p.y = y;
3631 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3632 fz_invert_matrix (&ctm, &ctm);
3633 fz_transform_point (&p, &ctm);
3635 tup_v = caml_alloc_tuple (2);
3636 ret_v = caml_alloc_small (1, 1);
3637 Field (tup_v, 0) = Val_int (p.x);
3638 Field (tup_v, 1) = Val_int (p.y);
3639 Field (ret_v, 0) = tup_v;
3641 unlock ("ml_unproject");
3642 done:
3643 CAMLreturn (ret_v);
3646 CAMLprim value ml_init (value pipe_v, value params_v)
3648 CAMLparam2 (pipe_v, params_v);
3649 CAMLlocal2 (trim_v, fuzz_v);
3650 int ret;
3651 int texcount;
3652 char *fontpath;
3653 int colorspace;
3654 int mustoresize;
3655 int haspboext;
3656 struct sigaction sa;
3658 state.cr = Int_val (Field (pipe_v, 0));
3659 state.cw = Int_val (Field (pipe_v, 1));
3660 state.rotate = Int_val (Field (params_v, 0));
3661 state.proportional = Bool_val (Field (params_v, 1));
3662 trim_v = Field (params_v, 2);
3663 texcount = Int_val (Field (params_v, 3));
3664 state.sliceheight = Int_val (Field (params_v, 4));
3665 mustoresize = Int_val (Field (params_v, 5));
3666 colorspace = Int_val (Field (params_v, 6));
3667 fontpath = String_val (Field (params_v, 7));
3668 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
3669 if (!state.trimcachepath) {
3670 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
3671 strerror (errno));
3673 haspboext = Bool_val (Field (params_v, 9));
3675 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3677 state.trimmargins = Bool_val (Field (trim_v, 0));
3678 fuzz_v = Field (trim_v, 1);
3679 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3680 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3681 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3682 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3684 set_tex_params (colorspace);
3686 if (*fontpath) {
3687 state.face = load_font (fontpath);
3689 else {
3690 unsigned int len;
3691 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
3693 state.face = load_builtin_font (base, len);
3695 if (!state.face) _exit (1);
3697 realloctexts (texcount);
3699 if (haspboext) {
3700 setuppbo ();
3703 #ifdef __CYGWIN__
3704 sa.sa_handler = SIG_IGN;
3705 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3706 #else
3707 sa.sa_handler = SIG_DFL;
3708 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
3709 #endif
3710 if (sigemptyset (&sa.sa_mask)) {
3711 err (1, "sigemptyset");
3713 if (sigaction (SIGCHLD, &sa, NULL)) {
3714 err (1, "sigaction");
3717 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3718 if (ret) {
3719 errx (1, "pthread_create: %s", strerror (ret));
3722 CAMLreturn (Val_unit);