2bd4ec4c229bb4ea09fb0bb69810c8da417614f3
[llpp.git] / link.c
blob2bd4ec4c229bb4ea09fb0bb69810c8da417614f3
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 <stdarg.h>
24 #include <limits.h>
26 #include <GL/gl.h>
28 #include <caml/fail.h>
29 #include <caml/alloc.h>
30 #include <caml/memory.h>
31 #include <caml/unixsupport.h>
33 #include <fitz.h>
34 #include <mupdf.h>
35 #include <mupdf-internal.h>
36 #include <muxps.h>
37 #include <muxps-internal.h>
38 #include <mucbz.h>
40 #include FT_FREETYPE_H
42 #define PIGGYBACK
44 #ifndef __USE_GNU
45 extern char **environ;
46 #endif
48 #define MIN(a,b) ((a) < (b) ? (a) : (b))
49 #define MAX(a,b) ((a) > (b) ? (a) : (b))
51 #if defined __GNUC__
52 #define NORETURN_ATTR __attribute__ ((noreturn))
53 #define UNUSED_ATTR __attribute__ ((unused))
54 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
55 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
56 #else
57 #define NORETURN_ATTR
58 #define UNUSED_ATTR
59 #define OPTIMIZE_ATTR(n)
60 #define GCC_FMT_ATTR(a, b)
61 #endif
63 #define FMT_s "zu"
65 #define FMT_ptr "p"
66 #define FMT_ptr_cast(p) (p)
67 #define FMT_ptr_cast2(p) (p)
69 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
70 err (int exitcode, const char *fmt, ...)
72 va_list ap;
73 int savederrno;
75 savederrno = errno;
76 va_start (ap, fmt);
77 vfprintf (stderr, fmt, ap);
78 va_end (ap);
79 fprintf (stderr, ": %s\n", strerror (savederrno));
80 fflush (stderr);
81 _exit (exitcode);
84 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
85 errx (int exitcode, const char *fmt, ...)
87 va_list ap;
89 va_start (ap, fmt);
90 vfprintf (stderr, fmt, ap);
91 va_end (ap);
92 fputc ('\n', stderr);
93 fflush (stderr);
94 _exit (exitcode);
97 #ifndef GL_TEXTURE_RECTANGLE_ARB
98 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
99 #endif
101 #ifndef GL_BGRA
102 #define GL_BGRA 0x80E1
103 #endif
105 #ifndef GL_UNSIGNED_INT_8_8_8_8
106 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
107 #endif
109 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
110 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
111 #endif
113 #if 0
114 #define lprintf printf
115 #else
116 #define lprintf(...)
117 #endif
119 #define ARSERT(cond) for (;;) { \
120 if (!(cond)) { \
121 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
123 break; \
126 struct slice {
127 int h;
128 int texindex;
131 struct tile {
132 int x, y, w, h;
133 int slicecount;
134 int sliceheight;
135 struct pbo *pbo;
136 fz_pixmap *pixmap;
137 struct slice slices[1];
140 struct pagedim {
141 int pageno;
142 int rotate;
143 int left;
144 int tctmready;
145 fz_irect bounds;
146 fz_rect pagebox;
147 fz_rect mediabox;
148 fz_matrix ctm, zoomctm, lctm, tctm;
151 struct slink {
152 fz_irect bbox;
153 fz_link *link;
156 enum { DPDF, DXPS, DCBZ };
158 struct page {
159 int tgen;
160 int sgen;
161 int type;
162 int pageno;
163 int pdimno;
164 fz_text_page *text;
165 fz_text_sheet *sheet;
166 union {
167 void *ptr;
168 pdf_page *pdfpage;
169 xps_page *xpspage;
170 cbz_page *cbzpage;
171 } u;
172 fz_display_list *dlist;
173 int slinkcount;
174 struct slink *slinks;
175 struct mark {
176 int i;
177 fz_text_span *span;
178 } fmark, lmark;
179 void (*freepage) (void *);
182 struct {
183 int type;
184 int sliceheight;
185 struct pagedim *pagedims;
186 int pagecount;
187 int pagedimcount;
188 union {
189 pdf_document *pdf;
190 xps_document *xps;
191 cbz_document *cbz;
192 } u;
193 fz_context *ctx;
194 int w, h;
196 int texindex;
197 int texcount;
198 GLuint *texids;
200 GLenum texiform;
201 GLenum texform;
202 GLenum texty;
204 fz_colorspace *colorspace;
206 struct {
207 int w, h;
208 struct slice *slice;
209 } *texowners;
211 int rotate;
212 int proportional;
213 int trimmargins;
214 int needoutline;
215 int gen;
216 int aalevel;
218 int trimanew;
219 fz_irect trimfuzz;
220 fz_pixmap *pig;
222 pthread_t thread;
223 int cr, cw;
224 FT_Face face;
226 void (*closedoc) (void);
227 void (*freepage) (void *);
229 char *trimcachepath;
231 int pbo_usable;
232 void (*glBindBufferARB) (GLenum, GLuint);
233 GLboolean (*glUnmapBufferARB) (GLenum);
234 void *(*glMapBufferARB) (GLenum, GLenum);
235 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
236 void (*glGenBuffersARB) (GLsizei, GLuint *);
237 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
238 } state;
240 struct pbo {
241 GLuint id;
242 void *ptr;
243 size_t size;
246 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
248 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
251 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
253 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
256 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
258 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
259 m.a, m.b, m.c, m.d, m.e, m.f);
262 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
264 static void lock (const char *cap)
266 int ret = pthread_mutex_lock (&mutex);
267 if (ret) {
268 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
272 static void unlock (const char *cap)
274 int ret = pthread_mutex_unlock (&mutex);
275 if (ret) {
276 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
280 static int trylock (const char *cap)
282 int ret = pthread_mutex_trylock (&mutex);
283 if (ret && ret != EBUSY) {
284 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
286 return ret == EBUSY;
289 static void *parse_pointer (const char *cap, const char *s)
291 int ret;
292 void *ptr;
294 ret = sscanf (s, "%" FMT_ptr, FMT_ptr_cast (&ptr));
295 if (ret != 1) {
296 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
298 return ptr;
301 static double now (void)
303 struct timeval tv;
305 if (gettimeofday (&tv, NULL)) {
306 err (1, "gettimeofday");
308 return tv.tv_sec + tv.tv_usec*1e-6;
311 static int hasdata (void)
313 int ret, avail;
314 ret = ioctl (state.cr, FIONREAD, &avail);
315 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
316 return avail > 0;
319 CAMLprim value ml_hasdata (value fd_v)
321 CAMLparam1 (fd_v);
322 int ret, avail;
324 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
325 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
326 CAMLreturn (Val_bool (avail > 0));
329 static void readdata (void *p, int size)
331 ssize_t n;
333 again:
334 n = read (state.cr, p, size);
335 if (n < 0) {
336 if (errno == EINTR) goto again;
337 err (1, "read (req %d, ret %zd)", size, n);
339 if (n - size) {
340 if (!n) errx (1, "EOF while reading");
341 errx (1, "read (req %d, ret %zd)", size, n);
345 static void writedata (char *p, int size)
347 char buf[4];
348 ssize_t n;
350 buf[0] = (size >> 24) & 0xff;
351 buf[1] = (size >> 16) & 0xff;
352 buf[2] = (size >> 8) & 0xff;
353 buf[3] = (size >> 0) & 0xff;
355 n = write (state.cw, buf, 4);
356 if (n != 4) {
357 if (!n) errx (1, "EOF while writing length");
358 err (1, "write %zd", n);
361 n = write (state.cw, p, size);
362 if (n - size) {
363 if (!n) errx (1, "EOF while writing data");
364 err (1, "write (req %d, ret %zd)", size, n);
368 static int readlen (void)
370 unsigned char p[4];
372 readdata (p, 4);
373 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
376 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
378 int size = 200, len;
379 va_list ap;
380 char *buf;
382 buf = malloc (size);
383 for (;;) {
384 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
386 va_start (ap, fmt);
387 len = vsnprintf (buf, size, fmt, ap);
388 va_end (ap);
390 if (len > -1 && len < size) {
391 writedata (buf, len);
392 break;
395 if (len > -1) {
396 size = len + 1;
398 else {
399 size *= 2;
401 buf = realloc (buf, size);
403 free (buf);
406 static void closepdf (void)
408 if (state.u.pdf) {
409 pdf_close_document (state.u.pdf);
410 state.u.pdf = NULL;
414 static void closexps (void)
416 if (state.u.xps) {
417 xps_close_document (state.u.xps);
418 state.u.xps = NULL;
422 static void closecbz (void)
424 if (state.u.cbz) {
425 cbz_close_document (state.u.cbz);
426 state.u.cbz = NULL;
430 static void freepdfpage (void *ptr)
432 pdf_free_page (state.u.pdf, ptr);
435 static void freeemptyxxxpage (void *ptr)
437 (void) ptr;
440 static void freexpspage (void *ptr)
442 xps_free_page (state.u.xps, ptr);
445 static void freecbzpage (void *ptr)
447 cbz_free_page (state.u.cbz, ptr);
450 static void openxref (char *filename, char *password)
452 int i, len;
454 for (i = 0; i < state.texcount; ++i) {
455 state.texowners[i].w = -1;
456 state.texowners[i].slice = NULL;
459 if (state.closedoc) state.closedoc ();
461 len = strlen (filename);
463 state.type = DPDF;
464 if (len > 4) {
465 char ext[4];
467 ext[0] = tolower ((int) filename[len-3]);
468 ext[1] = tolower ((int) filename[len-2]);
469 ext[2] = tolower ((int) filename[len-1]);
471 /**/ if (ext[0] == 'x' && ext[1] == 'p' && ext[2] == 's') {
472 state.type = DXPS;
474 else if (ext[0] == 'c' && ext[1] == 'b' && ext[2] == 'z') {
475 state.type = DCBZ;
479 if (state.pagedims) {
480 free (state.pagedims);
481 state.pagedims = NULL;
483 state.pagedimcount = 0;
485 fz_set_aa_level (state.ctx, state.aalevel);
486 switch (state.type) {
487 case DPDF:
488 state.u.pdf = pdf_open_document (state.ctx, filename);
489 if (pdf_needs_password (state.u.pdf)) {
490 int okay = pdf_authenticate_password (state.u.pdf, password);
491 if (!okay) {
492 errx (1, "invalid password");
495 state.pagecount = pdf_count_pages (state.u.pdf);
496 state.closedoc = closepdf;
497 state.freepage = freepdfpage;
498 break;
500 case DXPS:
501 state.u.xps = xps_open_document (state.ctx, filename);
502 state.pagecount = xps_count_pages (state.u.xps);
503 state.closedoc = closexps;
504 state.freepage = freexpspage;
505 break;
507 case DCBZ:
508 state.u.cbz = cbz_open_document (state.ctx, filename);
509 state.pagecount = cbz_count_pages (state.u.cbz);
510 state.closedoc = closecbz;
511 state.freepage = freecbzpage;
512 break;
516 static void pdfinfo (void)
518 if (state.type == DPDF) {
519 pdf_obj *infoobj;
521 printd ("info PDF version\t%d.%d",
522 state.u.pdf->version / 10, state.u.pdf->version % 10);
524 infoobj = pdf_dict_gets (state.u.pdf->trailer, "Info");
525 if (infoobj) {
526 int i;
527 char *s;
528 char *items[] = { "Title", "Author", "Creator",
529 "Producer", "CreationDate" };
531 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
532 pdf_obj *obj = pdf_dict_gets (infoobj, items[i]);
533 s = pdf_to_utf8 (state.u.pdf, obj);
534 if (*s) {
535 if (i == 0) {
536 printd ("title %s", s);
538 printd ("info %s\t%s", items[i], s);
540 fz_free (state.ctx, s);
543 printd ("infoend");
547 static void unlinktile (struct tile *tile)
549 int i;
551 for (i = 0; i < tile->slicecount; ++i) {
552 struct slice *s = &tile->slices[i];
554 if (s->texindex != -1) {
555 if (state.texowners[s->texindex].slice == s) {
556 state.texowners[s->texindex].slice = NULL;
562 static void freepage (struct page *page)
564 if (page->text) {
565 fz_free_text_page (state.ctx, page->text);
567 if (page->sheet) {
568 fz_free_text_sheet (state.ctx, page->sheet);
570 if (page->slinks) {
571 free (page->slinks);
573 page->freepage (page->u.ptr);
574 fz_free_display_list (state.ctx, page->dlist);
575 free (page);
578 static void freetile (struct tile *tile)
580 unlinktile (tile);
581 if (!tile->pbo) {
582 #ifndef PIGGYBACK
583 fz_drop_pixmap (state.ctx, tile->pixmap);
584 #else
585 if (state.pig) {
586 fz_drop_pixmap (state.ctx, state.pig);
588 state.pig = tile->pixmap;
589 #endif
591 else {
592 free (tile->pbo);
593 fz_drop_pixmap (state.ctx, tile->pixmap);
595 free (tile);
598 #ifdef __ALTIVEC__
599 #include <altivec.h>
601 static int cacheline32bytes;
603 static void __attribute__ ((constructor)) clcheck (void)
605 char **envp = environ;
606 unsigned long *auxv;
608 while (*envp++);
610 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
611 if (*auxv == 19) {
612 cacheline32bytes = auxv[1] == 32;
613 return;
618 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
620 size_t size = pixmap->w * pixmap->h * pixmap->n;
621 if (cacheline32bytes && size > 32) {
622 intptr_t a1, a2, diff;
623 size_t sizea, i;
624 vector unsigned char v = vec_splat_u8 (-1);
625 vector unsigned char *p;
627 a1 = a2 = (intptr_t) pixmap->samples;
628 a2 = (a1 + 31) & ~31;
629 diff = a2 - a1;
630 sizea = size - diff;
631 p = (void *) a2;
633 while (a1 != a2) *(char *) a1++ = 0xff;
634 for (i = 0; i < (sizea & ~31); i += 32) {
635 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
636 vec_st (v, i, p);
637 vec_st (v, i + 16, p);
639 while (i < sizea) *((char *) a1 + i++) = 0xff;
641 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
643 #else
644 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
645 #endif
647 static void trimctm (pdf_page *page, int pindex)
649 fz_matrix ctm;
650 struct pagedim *pdim = &state.pagedims[pindex];
652 if (!pdim->tctmready) {
653 if (state.trimmargins) {
654 fz_rect realbox;
655 fz_matrix rm, sm, tm, im, ctm1;
657 fz_rotate (&rm, -pdim->rotate);
658 fz_scale (&sm, 1, -1);
659 fz_concat (&ctm, &rm, &sm);
660 realbox = pdim->mediabox;
661 fz_transform_rect (&realbox, &ctm);
662 fz_translate (&tm, -realbox.x0, -realbox.y0);
663 fz_concat (&ctm1, &ctm, &tm);
664 fz_invert_matrix (&im, &page->ctm);
665 fz_concat (&ctm, &im, &ctm1);
667 else {
668 ctm = fz_identity;
670 pdim->tctm = ctm;
671 pdim->tctmready = 1;
675 static fz_matrix pagectm (struct page *page)
677 fz_matrix ctm, tm;
679 if (page->type == DPDF) {
680 trimctm (page->u.pdfpage, page->pdimno);
681 fz_concat (&ctm,
682 &state.pagedims[page->pdimno].tctm,
683 &state.pagedims[page->pdimno].ctm);
685 else {
686 struct pagedim *pdim = &state.pagedims[page->pdimno];
688 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
689 fz_concat (&ctm, &tm, &state.pagedims[page->pdimno].ctm);
691 return ctm;
694 static void *loadpage (int pageno, int pindex)
696 fz_device *dev;
697 struct page *page = NULL;
699 page = calloc (sizeof (struct page), 1);
700 if (!page) {
701 err (1, "calloc page %d", pageno);
704 page->dlist = fz_new_display_list (state.ctx);
705 dev = fz_new_list_device (state.ctx, page->dlist);
706 fz_try (state.ctx) {
707 switch (state.type) {
708 case DPDF:
709 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
710 pdf_run_page (state.u.pdf, page->u.pdfpage, dev,
711 &fz_identity, NULL);
712 page->freepage = freepdfpage;
713 break;
715 case DXPS:
716 page->u.xpspage = xps_load_page (state.u.xps, pageno);
717 xps_run_page (state.u.xps, page->u.xpspage, dev,
718 &fz_identity, NULL);
719 page->freepage = freexpspage;
720 break;
722 case DCBZ:
723 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
724 cbz_run_page (state.u.cbz, page->u.cbzpage, dev,
725 &fz_identity, NULL);
726 page->freepage = freecbzpage;
727 break;
730 fz_catch (state.ctx) {
731 page->u.ptr = NULL;
732 page->freepage = freeemptyxxxpage;
734 fz_free_device (dev);
736 page->pdimno = pindex;
737 page->pageno = pageno;
738 page->sgen = state.gen;
739 page->tgen = state.gen;
740 page->type = state.type;
742 return page;
745 static struct tile *alloctile (int h)
747 int i;
748 int slicecount;
749 size_t tilesize;
750 struct tile *tile;
752 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
753 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
754 tile = calloc (tilesize, 1);
755 if (!tile) {
756 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
758 for (i = 0; i < slicecount; ++i) {
759 int sh = MIN (h, state.sliceheight);
760 tile->slices[i].h = sh;
761 tile->slices[i].texindex = -1;
762 h -= sh;
764 tile->slicecount = slicecount;
765 tile->sliceheight = state.sliceheight;
766 return tile;
769 #ifdef OBSCURED_OPT
770 struct obs {
771 int cured;
772 fz_irect b;
775 static void obs_fill_image (fz_device *dev, fz_image *image,
776 const fz_matrix *ctm, float alpha)
778 struct obs *obs = dev->user;
780 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
781 fz_irect b;
782 fz_rect rect = fz_unit_rect;
784 fz_transform_rect (&rect, ctm);
785 fz_round_rect (&b, &rect);
786 fz_intersect_irect (&b, &obs->b);
787 obs->cured = b.x0 == obs->b.x0
788 && b.x1 == obs->b.x1
789 && b.y0 == obs->b.y0
790 && b.y1 == obs->b.y1;
794 static int obscured (struct page *page, fz_irect bbox)
796 fz_rect rect;
797 fz_matrix ctm;
798 fz_device dev;
799 struct obs obs;
801 memset (&dev, 0, sizeof (dev));
802 memset (&obs, 0, sizeof (obs));
803 dev.hints = 0;
804 dev.flags = 0;
805 dev.user = &obs;
806 dev.ctx = state.ctx;
807 dev.fill_image = obs_fill_image;
808 obs.b = bbox;
809 fz_rect_from_irect (&rect, &bbox);
810 ctm = pagectm (page);
811 fz_run_display_list (page->dlist, &dev, &ctm, &rect, NULL);
812 return obs.cured;
814 #define OBSCURED obscured
815 #else
816 #define OBSCURED(a, b) 0
817 #endif
819 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
820 struct pbo *pbo)
822 fz_rect rect;
823 fz_irect bbox;
824 fz_matrix ctm;
825 fz_device *dev;
826 struct tile *tile;
827 struct pagedim *pdim;
829 tile = alloctile (h);
830 pdim = &state.pagedims[page->pdimno];
832 bbox = pdim->bounds;
833 bbox.x0 += x;
834 bbox.y0 += y;
835 bbox.x1 = bbox.x0 + w;
836 bbox.y1 = bbox.y0 + h;
838 if (state.pig) {
839 if (state.pig->w == w
840 && state.pig->h == h
841 && state.pig->colorspace == state.colorspace) {
842 tile->pixmap = state.pig;
843 tile->pixmap->x = bbox.x0;
844 tile->pixmap->y = bbox.y0;
846 else {
847 fz_drop_pixmap (state.ctx, state.pig);
849 state.pig = NULL;
851 if (!tile->pixmap) {
852 if (pbo) {
853 tile->pixmap =
854 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
855 &bbox, pbo->ptr);
856 tile->pbo = pbo;
858 else {
859 tile->pixmap =
860 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
864 tile->w = w;
865 tile->h = h;
866 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
867 clearpixmap (tile->pixmap);
869 dev = fz_new_draw_device (state.ctx, tile->pixmap);
870 ctm = pagectm (page);
871 fz_rect_from_irect (&rect, &bbox);
872 fz_run_display_list (page->dlist, dev, &ctm, &rect, NULL);
873 fz_free_device (dev);
875 return tile;
878 static void initpdims (void)
880 double start, end;
881 int pageno, trim, show;
882 FILE *trimf = NULL;
883 int trimw = 0;
885 start = now ();
887 if (state.trimmargins && state.trimcachepath) {
888 trimf = fopen (state.trimcachepath, "rb");
889 if (!trimf) {
890 trimf = fopen (state.trimcachepath, "wb");
891 trimw = 1;
894 for (pageno = 0; pageno < state.pagecount; ++pageno) {
895 int rotate = 0;
896 struct pagedim *p;
897 fz_rect mediabox;
899 switch (state.type) {
900 case DPDF: {
901 pdf_obj *pageobj = state.u.pdf->page_objs[pageno];
903 if (state.trimmargins) {
904 pdf_obj *obj;
905 pdf_page *page;
907 fz_try (state.ctx) {
908 page = pdf_load_page (state.u.pdf, pageno);
909 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
910 trim = state.trimanew || !obj;
911 if (trim) {
912 fz_rect rect;
913 fz_matrix ctm;
914 fz_device *dev;
916 dev = fz_new_bbox_device (state.ctx, &rect);
917 dev->hints |= FZ_IGNORE_SHADE;
918 fz_invert_matrix (&ctm, &page->ctm);
919 pdf_run_page (state.u.pdf, page, dev, &fz_identity, NULL);
920 fz_free_device (dev);
922 rect.x0 += state.trimfuzz.x0;
923 rect.x1 += state.trimfuzz.x1;
924 rect.y0 += state.trimfuzz.y0;
925 rect.y1 += state.trimfuzz.y1;
926 fz_transform_rect (&rect, &ctm);
927 fz_intersect_rect (&rect, &page->mediabox);
929 if (fz_is_empty_rect (&rect)) {
930 mediabox = page->mediabox;
932 else {
933 mediabox = rect;
936 obj = pdf_new_array (state.ctx, 4);
937 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x0));
938 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y0));
939 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x1));
940 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y1));
941 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
943 else {
944 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
945 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
946 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
947 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
950 rotate = page->rotate;
951 pdf_free_page (state.u.pdf, page);
953 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
954 if (show) {
955 printd ("progress %f Trimming %d",
956 (double) (pageno + 1) / state.pagecount,
957 pageno + 1);
960 fz_catch (state.ctx) {
961 fprintf (stderr, "failed to load page %d\n", pageno+1);
964 else {
965 fz_rect cropbox;
967 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "MediaBox"),
968 &mediabox);
969 if (fz_is_empty_rect (&mediabox)) {
970 fprintf (stderr, "cannot find page size for page %d\n",
971 pageno+1);
972 mediabox.x0 = 0;
973 mediabox.y0 = 0;
974 mediabox.x1 = 612;
975 mediabox.y1 = 792;
978 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "CropBox"),
979 &cropbox);
980 if (!fz_is_empty_rect (&cropbox)) {
981 fz_intersect_rect (&mediabox, &cropbox);
983 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
985 break;
988 case DXPS:
990 xps_page *page;
992 fz_try (state.ctx) {
993 page = xps_load_page (state.u.xps, pageno);
994 xps_bound_page (state.u.xps, page, &mediabox);
995 rotate = 0;
996 if (state.trimmargins) {
997 fz_rect rect;
998 fz_device *dev;
1000 dev = fz_new_bbox_device (state.ctx, &rect);
1001 dev->hints |= FZ_IGNORE_SHADE;
1002 xps_run_page (state.u.xps, page, dev,
1003 &fz_identity, NULL);
1004 fz_free_device (dev);
1006 rect.x0 += state.trimfuzz.x0;
1007 rect.x1 += state.trimfuzz.x1;
1008 rect.y0 += state.trimfuzz.y0;
1009 rect.y1 += state.trimfuzz.y1;
1010 fz_intersect_rect (&rect, &mediabox);
1012 if (!fz_is_empty_rect (&rect)) {
1013 mediabox = rect;
1016 xps_free_page (state.u.xps, page);
1017 printd ("progress %f loading %d",
1018 (double) (pageno + 1) / state.pagecount,
1019 pageno + 1);
1021 fz_catch (state.ctx) {
1024 break;
1026 case DCBZ:
1028 rotate = 0;
1029 if (state.trimmargins && trimw) {
1030 cbz_page *page;
1032 fz_try (state.ctx) {
1033 page = cbz_load_page (state.u.cbz, pageno);
1034 cbz_bound_page (state.u.cbz, page, &mediabox);
1035 cbz_free_page (state.u.cbz, page);
1036 printd ("progress %f Trimming %d",
1037 (double) (pageno + 1) / state.pagecount,
1038 pageno + 1);
1040 fz_catch (state.ctx) {
1041 fprintf (stderr, "failed to load page %d\n", pageno+1);
1042 mediabox.x0 = 0;
1043 mediabox.y0 = 0;
1044 mediabox.x1 = 900;
1045 mediabox.y1 = 900;
1047 if (trimf) {
1048 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1049 if (n - 1) {
1050 err (1, "fwrite trim mediabox");
1054 else {
1055 if (trimf) {
1056 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1057 if (n - 1) {
1058 err (1, "fread trim mediabox");
1061 else {
1062 mediabox.x0 = mediabox.y0 = 0;
1063 mediabox.x1 = 900;
1064 mediabox.y1 = 900;
1068 break;
1070 default:
1071 ARSERT (0 && state.type);
1074 if (state.pagedimcount == 0
1075 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1076 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1077 size_t size;
1079 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1080 state.pagedims = realloc (state.pagedims, size);
1081 if (!state.pagedims) {
1082 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1083 size, state.pagedimcount + 1);
1086 p = &state.pagedims[state.pagedimcount++];
1087 p->rotate = rotate;
1088 p->mediabox = mediabox;
1089 p->pageno = pageno;
1092 end = now ();
1093 if (state.trimmargins) {
1094 printd ("progress 1 Trimmed %d pages in %f seconds",
1095 state.pagecount, end - start);
1097 else {
1098 printd ("vmsg Processed %d pages in %f seconds",
1099 state.pagecount, end - start);
1101 state.trimanew = 0;
1102 if (trimf) {
1103 if (fclose (trimf)) {
1104 err (1, "fclose");
1109 static void layout (void)
1111 int pindex;
1112 fz_rect box;
1113 fz_matrix ctm;
1114 double zoom, w, maxw = 0;
1115 struct pagedim *p = state.pagedims;
1117 if (state.proportional) {
1118 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1119 fz_matrix rm;
1121 fz_rotate (&rm, p->rotate + state.rotate);
1122 box = p->mediabox;
1123 fz_transform_rect (&box, &rm);
1124 w = box.x1 - box.x0;
1125 maxw = MAX (w, maxw);
1129 p = state.pagedims;
1130 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1131 fz_rect rect;
1132 fz_matrix tm, sm, rm;
1134 fz_rotate (&ctm, state.rotate);
1135 fz_rotate (&rm, p->rotate + state.rotate);
1136 box = p->mediabox;
1137 fz_transform_rect (&box, &rm);
1138 w = box.x1 - box.x0;
1140 if (state.proportional) {
1141 double scale = w / maxw;
1142 zoom = (state.w / w) * scale;
1144 else {
1145 zoom = state.w / w;
1148 fz_scale (&p->zoomctm, zoom, zoom);
1149 fz_concat (&ctm, &p->zoomctm, &ctm);
1151 fz_rotate (&rm, p->rotate);
1152 p->pagebox = p->mediabox;
1153 fz_transform_rect (&p->pagebox, &rm);
1154 p->pagebox.x1 -= p->pagebox.x0;
1155 p->pagebox.y1 -= p->pagebox.y0;
1156 p->pagebox.x0 = 0;
1157 p->pagebox.y0 = 0;
1158 rect = p->pagebox;
1159 fz_transform_rect (&rect, &ctm);
1160 fz_round_rect (&p->bounds, &rect);
1162 p->left = state.proportional ? ((maxw - w) * zoom) / 2.0 : 0;
1163 p->ctm = ctm;
1165 fz_translate (&tm, 0, -p->mediabox.y1);
1166 fz_scale (&sm, zoom, -zoom);
1167 fz_concat (&ctm, &tm, &sm);
1168 fz_concat (&p->lctm, &ctm, &rm);
1170 p->tctmready = 0;
1173 while (p-- != state.pagedims) {
1174 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1175 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1176 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1177 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1178 int w = x1 - x0;
1179 int h = y1 - y0;
1181 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1185 static
1186 struct anchor { int n; int x; int y; int w; int h; }
1187 desttoanchor (fz_link_dest *dest)
1189 int i;
1190 struct anchor a;
1191 struct pagedim *pdim = state.pagedims;
1193 a.n = -1;
1194 a.x = 0;
1195 a.y = 0;
1196 for (i = 0; i < state.pagedimcount; ++i) {
1197 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1198 break;
1199 pdim = &state.pagedims[i];
1201 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1202 fz_point p;
1203 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1204 p.x = dest->ld.gotor.lt.x;
1205 p.y = dest->ld.gotor.lt.y;
1206 fz_transform_point (&p, &pdim->lctm);
1207 a.y = p.y;
1208 a.x = p.x;
1210 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1211 double x0, x1, y0, y1;
1213 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1214 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1215 a.w = x1 - x0;
1216 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1217 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1218 a.h = y1 - y0;
1219 a.n = dest->ld.gotor.page;
1221 return a;
1224 static void recurse_outline (fz_outline *outline, int level)
1226 while (outline) {
1227 struct anchor a = desttoanchor (&outline->dest);
1229 if (a.n >= 0) {
1230 printd ("o %d %d %d %d %s",
1231 level, a.n, a.y, a.h, outline->title);
1233 if (outline->down) {
1234 recurse_outline (outline->down, level + 1);
1236 outline = outline->next;
1240 static void process_outline (void)
1242 fz_outline *outline;
1244 if (!state.needoutline) return;
1246 state.needoutline = 0;
1247 switch (state.type) {
1248 case DPDF:
1249 outline = pdf_load_outline (state.u.pdf);
1250 break;
1251 case DXPS:
1252 outline = xps_load_outline (state.u.xps);
1253 break;
1254 default:
1255 outline = NULL;
1256 break;
1258 if (outline) {
1259 recurse_outline (outline, 0);
1260 fz_free_outline (state.ctx, outline);
1264 static char *strofspan (fz_text_span *span)
1266 char *p;
1267 char utf8[10];
1268 fz_text_char *ch;
1269 size_t size = 0, cap = 80;
1271 p = malloc (cap + 1);
1272 if (!p) return NULL;
1274 for (ch = span->text; ch < span->text + span->len; ++ch) {
1275 int n = fz_runetochar (utf8, ch->c);
1276 if (size + n > cap) {
1277 cap *= 2;
1278 p = realloc (p, cap + 1);
1279 if (!p) return NULL;
1282 memcpy (p + size, utf8, n);
1283 size += n;
1285 p[size] = 0;
1286 return p;
1289 static int matchspan (regex_t *re, fz_text_span *span, fz_matrix ctm,
1290 int stop, int pageno, double start)
1292 int ret;
1293 char *p;
1294 regmatch_t rm;
1295 int a, b, c;
1296 fz_rect *sb, *eb;
1297 fz_point p1, p2, p3, p4;
1299 p = strofspan (span);
1300 if (!p) return -1;
1302 ret = regexec (re, p, 1, &rm, 0);
1303 if (ret) {
1304 free (p);
1305 if (ret != REG_NOMATCH) {
1306 size_t size;
1307 char errbuf[80];
1308 size = regerror (ret, re, errbuf, sizeof (errbuf));
1309 printd ("msg regexec error `%.*s'",
1310 (int) size, errbuf);
1311 return -1;
1313 return 0;
1315 else {
1316 int l = span->len;
1317 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1318 c += fz_runelen (span->text[a].c);
1320 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1321 c += fz_runelen (span->text[b].c);
1324 if (fz_runelen (span->text[b].c) > 1) {
1325 b = MAX (0, b-1);
1327 sb = &span->text[MIN (a, l-1)].bbox;
1328 eb = &span->text[MIN (b, l-1)].bbox;
1330 p1.x = sb->x0;
1331 p1.y = sb->y0;
1332 p2.x = eb->x1;
1333 p2.y = sb->y0;
1334 p3.x = eb->x1;
1335 p3.y = eb->y1;
1336 p4.x = sb->x0;
1337 p4.y = eb->y1;
1339 if (!stop) {
1340 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1341 pageno, 1,
1342 p1.x, p1.y,
1343 p2.x, p2.y,
1344 p3.x, p3.y,
1345 p4.x, p4.y);
1347 printd ("progress 1 found at %d `%.*s' in %f sec",
1348 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1349 now () - start);
1351 else {
1352 printd ("match %d %d %f %f %f %f %f %f %f %f",
1353 pageno, 2,
1354 p1.x, p1.y,
1355 p2.x, p2.y,
1356 p3.x, p3.y,
1357 p4.x, p4.y);
1359 free (p);
1360 return 1;
1364 static int compareblocks (const void *l, const void *r)
1366 fz_text_block const *ls = l;
1367 fz_text_block const* rs = r;
1368 return ls->bbox.y0 - rs->bbox.y0;
1371 /* wishful thinking function */
1372 static void search (regex_t *re, int pageno, int y, int forward)
1374 int i, j;
1375 fz_matrix ctm;
1376 fz_device *tdev;
1377 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1378 fz_text_page *text;
1379 fz_text_sheet *sheet;
1380 struct pagedim *pdim, *pdimprev;
1381 int stop = 0, niters = 0;
1382 double start, end;
1384 if (!(state.type == DPDF || state.type == DXPS))
1385 return;
1387 start = now ();
1388 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1389 if (niters++ == 5) {
1390 niters = 0;
1391 if (hasdata ()) {
1392 printd ("progress 1 attention requested aborting search at %d",
1393 pageno);
1394 stop = 1;
1396 else {
1397 printd ("progress %f searching in page %d",
1398 (double) (pageno + 1) / state.pagecount,
1399 pageno);
1402 pdimprev = NULL;
1403 for (i = 0; i < state.pagedimcount; ++i) {
1404 pdim = &state.pagedims[i];
1405 if (pdim->pageno == pageno) {
1406 goto found;
1408 if (pdim->pageno > pageno) {
1409 pdim = pdimprev;
1410 goto found;
1412 pdimprev = pdim;
1414 pdim = pdimprev;
1415 found:
1417 sheet = fz_new_text_sheet (state.ctx);
1418 text = fz_new_text_page (state.ctx, &fz_infinite_rect);
1419 tdev = fz_new_text_device (state.ctx, sheet, text);
1421 switch (state.type) {
1422 case DPDF:
1423 u.ptr = NULL;
1424 fz_try (state.ctx) {
1425 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1426 trimctm (u.pdfpage, pdim - state.pagedims);
1427 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1428 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1430 fz_catch (state.ctx) {
1431 fz_free_device (tdev);
1432 u.ptr = NULL;
1433 goto nextiter;
1435 break;
1437 case DXPS:
1438 u.xpspage = xps_load_page (state.u.xps, pageno);
1439 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1440 break;
1442 default:
1443 ARSERT (0 && state.type);
1446 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1447 fz_free_device (tdev);
1449 for (j = 0; j < text->len; ++j) {
1450 int k;
1451 fz_text_block *block;
1453 block = &text->blocks[forward ? j : text->len - 1 - j];
1455 for (k = 0; k < block->len; ++k) {
1456 fz_text_line *line;
1457 fz_text_span *span;
1459 if (forward) {
1460 line = &block->lines[k];
1461 if (line->bbox.y0 < y + 1) continue;
1463 else {
1464 line = &block->lines[block->len - 1 - k];
1465 if (line->bbox.y0 > y - 1) continue;
1468 for (span = line->spans;
1469 span < line->spans + line->len;
1470 ++span) {
1472 switch (matchspan (re, span, ctm, stop, pageno, start)) {
1473 case 0: break;
1474 case 1: stop = 1; break;
1475 case -1: stop = 1; goto endloop;
1480 nextiter:
1481 if (forward) {
1482 pageno += 1;
1483 y = 0;
1485 else {
1486 pageno -= 1;
1487 y = INT_MAX;
1489 endloop:
1490 fz_free_text_page (state.ctx, text);
1491 fz_free_text_sheet (state.ctx, sheet);
1492 if (u.ptr) {
1493 state.freepage (u.ptr);
1496 end = now ();
1497 if (!stop) {
1498 printd ("progress 1 no matches %f sec", end - start);
1500 printd ("clearrects");
1503 static void set_tex_params (int colorspace)
1505 union {
1506 unsigned char b;
1507 unsigned int s;
1508 } endianness = {1};
1510 switch (colorspace) {
1511 case 0:
1512 state.texiform = GL_RGBA8;
1513 state.texform = GL_RGBA;
1514 state.texty = GL_UNSIGNED_BYTE;
1515 state.colorspace = fz_device_rgb;
1516 break;
1517 case 1:
1518 state.texiform = GL_RGBA8;
1519 state.texform = GL_BGRA;
1520 state.texty = endianness.s > 1
1521 ? GL_UNSIGNED_INT_8_8_8_8
1522 : GL_UNSIGNED_INT_8_8_8_8_REV;
1523 state.colorspace = fz_device_bgr;
1524 break;
1525 case 2:
1526 state.texiform = GL_LUMINANCE_ALPHA;
1527 state.texform = GL_LUMINANCE_ALPHA;
1528 state.texty = GL_UNSIGNED_BYTE;
1529 state.colorspace = fz_device_gray;
1530 break;
1531 default:
1532 errx (1, "invalid colorspce %d", colorspace);
1536 static void realloctexts (int texcount)
1538 size_t size;
1540 if (texcount == state.texcount) return;
1542 if (texcount < state.texcount) {
1543 glDeleteTextures (state.texcount - texcount,
1544 state.texids + texcount);
1547 size = texcount * sizeof (*state.texids);
1548 state.texids = realloc (state.texids, size);
1549 if (!state.texids) {
1550 err (1, "realloc texids %" FMT_s, size);
1553 size = texcount * sizeof (*state.texowners);
1554 state.texowners = realloc (state.texowners, size);
1555 if (!state.texowners) {
1556 err (1, "realloc texowners %" FMT_s, size);
1558 if (texcount > state.texcount) {
1559 int i;
1561 glGenTextures (texcount - state.texcount,
1562 state.texids + state.texcount);
1563 for (i = state.texcount; i < texcount; ++i) {
1564 state.texowners[i].w = -1;
1565 state.texowners[i].slice = NULL;
1568 state.texcount = texcount;
1569 state.texindex = 0;
1572 static char *mbtoutf8 (char *s)
1574 char *p, *r;
1575 wchar_t *tmp;
1576 size_t i, ret, len;
1578 len = mbstowcs (NULL, s, strlen (s));
1579 if (len == 0) {
1580 return s;
1582 else {
1583 if (len == (size_t) -1) {
1584 return s;
1588 tmp = malloc (len * sizeof (wchar_t));
1589 if (!tmp) {
1590 return s;
1593 ret = mbstowcs (tmp, s, len);
1594 if (ret == (size_t) -1) {
1595 free (tmp);
1596 return s;
1599 len = 0;
1600 for (i = 0; i < ret; ++i) {
1601 len += fz_runelen (tmp[i]);
1604 p = r = malloc (len + 1);
1605 if (!r) {
1606 free (tmp);
1607 return s;
1610 for (i = 0; i < ret; ++i) {
1611 p += fz_runetochar (p, tmp[i]);
1613 *p = 0;
1614 free (tmp);
1615 return r;
1618 CAMLprim value ml_mbtoutf8 (value s_v)
1620 CAMLparam1 (s_v);
1621 CAMLlocal1 (ret_v);
1622 char *s, *r;
1624 s = String_val (s_v);
1625 r = mbtoutf8 (s);
1626 if (r == s) {
1627 ret_v = s_v;
1629 else {
1630 ret_v = caml_copy_string (r);
1631 free (r);
1633 CAMLreturn (ret_v);
1636 static void * mainloop (void *unused)
1638 char *p = NULL;
1639 int len, ret, oldlen = 0;
1641 for (;;) {
1642 len = readlen ();
1643 if (len == 0) {
1644 errx (1, "readlen returned 0");
1647 if (oldlen < len + 1) {
1648 p = realloc (p, len + 1);
1649 if (!p) {
1650 err (1, "realloc %d failed", len + 1);
1652 oldlen = len + 1;
1654 readdata (p, len);
1655 p[len] = 0;
1657 if (!strncmp ("open", p, 4)) {
1658 size_t filenamelen;
1659 int wthack, off;
1660 char *password;
1661 char *filename;
1662 char *utf8filename;
1664 ret = sscanf (p + 5, " %d %n", &wthack, &off);
1665 if (ret != 1) {
1666 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1669 filename = p + 5 + off;
1670 filenamelen = strlen (filename);
1671 password = filename + filenamelen + 1;
1673 lock ("open");
1674 openxref (filename, password);
1675 pdfinfo ();
1676 initpdims ();
1677 unlock ("open");
1679 if (!wthack) {
1680 utf8filename = mbtoutf8 (filename);
1681 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1682 if (utf8filename != filename) {
1683 free (utf8filename);
1686 state.needoutline = 1;
1688 else if (!strncmp ("cs", p, 2)) {
1689 int i, colorspace;
1691 ret = sscanf (p + 2, " %d", &colorspace);
1692 if (ret != 1) {
1693 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1695 lock ("cs");
1696 set_tex_params (colorspace);
1697 for (i = 0; i < state.texcount; ++i) {
1698 state.texowners[i].w = -1;
1699 state.texowners[i].slice = NULL;
1701 unlock ("cs");
1703 else if (!strncmp ("freepage", p, 8)) {
1704 void *ptr;
1706 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1707 if (ret != 1) {
1708 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1710 freepage (ptr);
1712 else if (!strncmp ("freetile", p, 8)) {
1713 void *ptr;
1715 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1716 if (ret != 1) {
1717 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1719 freetile (ptr);
1721 else if (!strncmp ("search", p, 6)) {
1722 int icase, pageno, y, ret, len2, forward;
1723 char *pattern;
1724 regex_t re;
1726 ret = sscanf (p + 6, " %d %d %d %d,%n",
1727 &icase, &pageno, &y, &forward, &len2);
1728 if (ret != 4) {
1729 errx (1, "malformed search `%s' ret=%d", p, ret);
1732 pattern = p + 6 + len2;
1733 ret = regcomp (&re, pattern,
1734 REG_EXTENDED | (icase ? REG_ICASE : 0));
1735 if (ret) {
1736 char errbuf[80];
1737 size_t size;
1739 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1740 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1742 else {
1743 search (&re, pageno, y, forward);
1744 regfree (&re);
1747 else if (!strncmp ("geometry", p, 8)) {
1748 int w, h;
1750 printd ("clear");
1751 ret = sscanf (p + 8, " %d %d", &w, &h);
1752 if (ret != 2) {
1753 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1756 lock ("geometry");
1757 state.h = h;
1758 if (w != state.w) {
1759 int i;
1760 state.w = w;
1761 for (i = 0; i < state.texcount; ++i) {
1762 state.texowners[i].slice = NULL;
1765 layout ();
1766 process_outline ();
1768 state.gen++;
1769 unlock ("geometry");
1770 printd ("continue %d", state.pagecount);
1772 else if (!strncmp ("reqlayout", p, 9)) {
1773 char *nameddest;
1774 int rotate, proportional, off;
1776 printd ("clear");
1777 ret = sscanf (p + 9, " %d %d %n", &rotate, &proportional, &off);
1778 if (ret != 2) {
1779 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1781 lock ("reqlayout");
1782 if (state.rotate != rotate || state.proportional != proportional) {
1783 state.gen += 1;
1785 state.rotate = rotate;
1786 state.proportional = proportional;
1787 layout ();
1788 process_outline ();
1790 nameddest = p + 9 + off;
1791 if (state.type == DPDF && nameddest && *nameddest) {
1792 struct anchor a;
1793 fz_link_dest dest;
1794 pdf_obj *needle, *obj;
1796 needle = pdf_new_string (state.ctx, nameddest,
1797 strlen (nameddest));
1798 obj = pdf_lookup_dest (state.u.pdf, needle);
1799 if (obj) {
1800 dest = pdf_parse_link_dest (state.u.pdf, obj);
1802 a = desttoanchor (&dest);
1803 if (a.n >= 0) {
1804 printd ("a %d %d %d", a.n, a.x, a.y);
1806 else {
1807 printd ("emsg failed to parse destination `%s'\n",
1808 nameddest);
1811 else {
1812 printd ("emsg destination `%s' not found\n",
1813 nameddest);
1815 pdf_drop_obj (needle);
1818 state.gen++;
1819 unlock ("reqlayout");
1820 printd ("continue %d", state.pagecount);
1822 else if (!strncmp ("page", p, 4)) {
1823 double a, b;
1824 struct page *page;
1825 int pageno, pindex, ret;
1827 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1828 if (ret != 2) {
1829 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1832 lock ("page");
1833 a = now ();
1834 page = loadpage (pageno, pindex);
1835 b = now ();
1836 unlock ("page");
1838 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1840 else if (!strncmp ("tile", p, 4)) {
1841 int x, y, w, h, ret;
1842 struct page *page;
1843 struct tile *tile;
1844 double a, b;
1845 void *data;
1847 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
1848 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
1849 if (ret != 6) {
1850 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1853 lock ("tile");
1854 a = now ();
1855 tile = rendertile (page, x, y, w, h, data);
1856 b = now ();
1857 unlock ("tile");
1859 printd ("tile %d %d %" FMT_ptr " %u %f",
1860 x, y,
1861 FMT_ptr_cast2 (tile),
1862 tile->w * tile->h * tile->pixmap->n,
1863 b - a);
1865 else if (!strncmp ("settrim", p, 7)) {
1866 int trimmargins;
1867 fz_irect fuzz;
1869 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1870 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1871 if (ret != 5) {
1872 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1874 printd ("clear");
1875 lock ("settrim");
1876 state.trimmargins = trimmargins;
1877 state.needoutline = 1;
1878 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1879 state.trimanew = 1;
1880 state.trimfuzz = fuzz;
1882 state.pagedimcount = 0;
1883 free (state.pagedims);
1884 state.pagedims = NULL;
1885 initpdims ();
1886 layout ();
1887 process_outline ();
1888 unlock ("settrim");
1889 printd ("continue %d", state.pagecount);
1891 else if (!strncmp ("sliceh", p, 6)) {
1892 int h;
1894 ret = sscanf (p + 6, " %d", &h);
1895 if (ret != 1) {
1896 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1898 if (h != state.sliceheight) {
1899 int i;
1901 state.sliceheight = h;
1902 for (i = 0; i < state.texcount; ++i) {
1903 state.texowners[i].w = -1;
1904 state.texowners[i].h = -1;
1905 state.texowners[i].slice = NULL;
1909 else if (!strncmp ("interrupt", p, 9)) {
1910 printd ("vmsg interrupted");
1912 else {
1913 errx (1, "unknown command %.*s", len, p);
1916 return 0;
1919 CAMLprim value ml_realloctexts (value texcount_v)
1921 CAMLparam1 (texcount_v);
1922 int ok;
1924 if (trylock ("ml_realloctexts")) {
1925 ok = 0;
1926 goto done;
1928 realloctexts (Int_val (texcount_v));
1929 ok = 1;
1930 unlock ("ml_realloctexts");
1932 done:
1933 CAMLreturn (Val_bool (ok));
1936 static void showsel (struct page *page, int ox, int oy)
1938 int seen = 0;
1939 fz_irect bbox;
1940 fz_rect rect;
1941 fz_text_line *line;
1942 fz_text_span *span;
1943 fz_text_block *block;
1944 struct mark first, last;
1946 first = page->fmark;
1947 last = page->lmark;
1949 if (!first.span || !last.span) return;
1951 glEnable (GL_BLEND);
1952 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1953 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1955 ox += state.pagedims[page->pdimno].bounds.x0;
1956 oy += state.pagedims[page->pdimno].bounds.y0;
1957 for (block = page->text->blocks;
1958 block < page->text->blocks + page->text->len;
1959 ++block) {
1960 for (line = block->lines;
1961 line < block->lines + block->len;
1962 ++line) {
1963 rect = fz_empty_rect;
1964 for (span = line->spans;
1965 span < line->spans + line->len;
1966 ++span) {
1967 int i, j, k;
1969 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1971 j = 0;
1972 k = span->len - 1;
1974 if (span == page->fmark.span && span == page->lmark.span) {
1975 seen = 1;
1976 j = MIN (first.i, last.i);
1977 k = MAX (first.i, last.i);
1979 else if (span == first.span) {
1980 seen = 1;
1981 j = first.i;
1983 else if (span == last.span) {
1984 seen = 1;
1985 k = last.i;
1988 if (seen) {
1989 for (i = j; i <= k; ++i) {
1990 fz_union_rect (&rect, &span->text[i].bbox);
1992 fz_round_rect (&bbox, &rect);
1993 lprintf ("%d %d %d %d oy=%d ox=%d\n",
1994 bbox.x0,
1995 bbox.y0,
1996 bbox.x1,
1997 bbox.y1,
1998 oy, ox);
2000 glRecti (bbox.x0 + ox, bbox.y0 + oy,
2001 bbox.x1 + ox, bbox.y1 + oy);
2002 if (span == last.span) {
2003 goto done;
2009 done:
2010 glDisable (GL_BLEND);
2013 #include "glfont.c"
2015 static void highlightlinks (struct page *page, int xoff, int yoff)
2017 fz_matrix ctm, tm, pm;
2018 fz_link *link, *links;
2020 switch (page->type) {
2021 case DPDF:
2022 links = page->u.pdfpage->links;
2023 break;
2025 case DXPS:
2026 links = page->u.xpspage->links;
2027 break;
2029 default:
2030 return;
2033 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2034 glEnable (GL_LINE_STIPPLE);
2035 glLineStipple (0.5, 0xcccc);
2037 xoff -= state.pagedims[page->pdimno].bounds.x0;
2038 yoff -= state.pagedims[page->pdimno].bounds.y0;
2039 fz_translate (&tm, xoff, yoff);
2040 pm = pagectm (page);
2041 fz_concat (&ctm, &pm, &tm);
2043 glBegin (GL_QUADS);
2044 for (link = links; link; link = link->next) {
2045 fz_point p1, p2, p3, p4;
2047 p1.x = link->rect.x0;
2048 p1.y = link->rect.y0;
2050 p2.x = link->rect.x1;
2051 p2.y = link->rect.y0;
2053 p3.x = link->rect.x1;
2054 p3.y = link->rect.y1;
2056 p4.x = link->rect.x0;
2057 p4.y = link->rect.y1;
2059 fz_transform_point (&p1, &ctm);
2060 fz_transform_point (&p2, &ctm);
2061 fz_transform_point (&p3, &ctm);
2062 fz_transform_point (&p4, &ctm);
2064 switch (link->dest.kind) {
2065 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2066 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2067 default: glColor3ub (0, 0, 0); break;
2070 glVertex2f (p1.x, p1.y);
2071 glVertex2f (p2.x, p2.y);
2072 glVertex2f (p3.x, p3.y);
2073 glVertex2f (p4.x, p4.y);
2075 glEnd ();
2077 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2078 glDisable (GL_LINE_STIPPLE);
2081 static int compareslinks (const void *l, const void *r)
2083 struct slink const *ls = l;
2084 struct slink const *rs = r;
2085 if (ls->bbox.y0 == rs->bbox.y0) {
2086 return rs->bbox.x0 - rs->bbox.x0;
2088 return ls->bbox.y0 - rs->bbox.y0;
2091 static void droptext (struct page *page)
2093 if (page->text) {
2094 fz_free_text_page (state.ctx, page->text);
2095 page->fmark.i = -1;
2096 page->lmark.i = -1;
2097 page->fmark.span = NULL;
2098 page->lmark.span = NULL;
2099 page->text = NULL;
2101 if (page->sheet) {
2102 fz_free_text_sheet (state.ctx, page->sheet);
2106 static void dropslinks (struct page *page)
2108 if (page->slinks) {
2109 free (page->slinks);
2110 page->slinks = NULL;
2111 page->slinkcount = 0;
2115 static void ensureslinks (struct page *page)
2117 fz_matrix ctm;
2118 int i, count = 0;
2119 size_t slinksize = sizeof (*page->slinks);
2120 fz_link *link, *links;
2122 if (state.gen != page->sgen) {
2123 dropslinks (page);
2124 page->sgen = state.gen;
2126 if (page->slinks) return;
2128 switch (page->type) {
2129 case DPDF:
2130 links = page->u.pdfpage->links;
2131 trimctm (page->u.pdfpage, page->pdimno);
2132 fz_concat (&ctm,
2133 &state.pagedims[page->pdimno].tctm,
2134 &state.pagedims[page->pdimno].ctm);
2135 break;
2137 case DXPS:
2138 links = page->u.xpspage->links;
2139 ctm = state.pagedims[page->pdimno].ctm;
2140 break;
2142 default:
2143 return;
2146 for (link = links; link; link = link->next) {
2147 count++;
2149 if (count > 0) {
2150 page->slinkcount = count;
2151 page->slinks = calloc (count, slinksize);
2152 if (!page->slinks) {
2153 err (1, "realloc slinks %d", count);
2156 for (i = 0, link = links; link; ++i, link = link->next) {
2157 fz_rect rect;
2159 rect = link->rect;
2160 fz_transform_rect (&rect, &ctm);
2161 page->slinks[i].link = link;
2162 fz_round_rect (&page->slinks[i].bbox, &rect);
2164 qsort (page->slinks, count, slinksize, compareslinks);
2168 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2169 static void fmt_linkn (char *s, unsigned int u)
2171 unsigned int len; unsigned int q;
2172 int zma = 'z' - 'a' + 1;
2173 len = 1; q = u;
2174 while (q > zma - 1) { ++len; q /= zma; }
2175 if (s) {
2176 s += len;
2177 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2178 /* handles u == 0 */
2180 s[len] = 0;
2183 static void highlightslinks (struct page *page, int xoff, int yoff,
2184 int noff, char *targ, int tlen, int hfsize)
2186 int i;
2187 char buf[40];
2188 struct slink *slink;
2189 double x0, y0, x1, y1, w;
2191 ensureslinks (page);
2192 glColor3ub (0xc3, 0xb0, 0x91);
2193 for (i = 0; i < page->slinkcount; ++i) {
2194 fmt_linkn (buf, i + noff);
2195 if (!tlen || !strncmp (targ, buf, tlen)) {
2196 slink = &page->slinks[i];
2198 x0 = slink->bbox.x0 + xoff - 5;
2199 y1 = slink->bbox.y0 + yoff - 5;
2200 y0 = y1 + 10 + hfsize;
2201 w = measure_string (state.face, hfsize, buf);
2202 x1 = x0 + w + 10;
2203 glRectd (x0, y0, x1, y1);
2207 glEnable (GL_BLEND);
2208 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2209 glEnable (GL_TEXTURE_2D);
2210 glColor3ub (0, 0, 0);
2211 for (i = 0; i < page->slinkcount; ++i) {
2212 fmt_linkn (buf, i + noff);
2213 if (!tlen || !strncmp (targ, buf, tlen)) {
2214 slink = &page->slinks[i];
2216 x0 = slink->bbox.x0 + xoff;
2217 y0 = slink->bbox.y0 + yoff + hfsize;
2218 draw_string (state.face, hfsize, x0, y0, buf);
2221 glDisable (GL_TEXTURE_2D);
2222 glDisable (GL_BLEND);
2226 static void uploadslice (struct tile *tile, struct slice *slice)
2228 int offset;
2229 struct slice *slice1;
2230 unsigned char *texdata;
2232 offset = 0;
2233 for (slice1 = tile->slices; slice != slice1; slice1++) {
2234 offset += slice1->h * tile->w * tile->pixmap->n;
2236 if (slice->texindex != -1 && slice->texindex < state.texcount
2237 && state.texowners[slice->texindex].slice == slice) {
2238 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2240 else {
2241 int subimage = 0;
2242 int texindex = state.texindex++ % state.texcount;
2244 if (state.texowners[texindex].w == tile->w) {
2245 if (state.texowners[texindex].h >= slice->h) {
2246 subimage = 1;
2248 else {
2249 state.texowners[texindex].h = slice->h;
2252 else {
2253 state.texowners[texindex].h = slice->h;
2256 state.texowners[texindex].w = tile->w;
2257 state.texowners[texindex].slice = slice;
2258 slice->texindex = texindex;
2260 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2261 if (tile->pbo) {
2262 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2263 texdata = 0;
2265 else {
2266 texdata = tile->pixmap->samples;
2268 if (subimage) {
2269 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2273 tile->w,
2274 slice->h,
2275 state.texform,
2276 state.texty,
2277 texdata+offset
2280 else {
2281 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2283 state.texiform,
2284 tile->w,
2285 slice->h,
2287 state.texform,
2288 state.texty,
2289 texdata+offset
2292 if (tile->pbo) {
2293 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2298 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2300 CAMLparam2 (args_v, ptr_v);
2301 int dispx = Int_val (Field (args_v, 0));
2302 int dispy = Int_val (Field (args_v, 1));
2303 int dispw = Int_val (Field (args_v, 2));
2304 int disph = Int_val (Field (args_v, 3));
2305 int tilex = Int_val (Field (args_v, 4));
2306 int tiley = Int_val (Field (args_v, 5));
2307 char *s = String_val (ptr_v);
2308 struct tile *tile = parse_pointer ("ml_drawtile", s);
2310 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2312 int slicey, firstslice;
2313 struct slice *slice;
2315 firstslice = tiley / tile->sliceheight;
2316 slice = &tile->slices[firstslice];
2317 slicey = tiley % tile->sliceheight;
2319 while (disph > 0) {
2320 int dh;
2322 dh = slice->h - slicey;
2323 dh = MIN (disph, dh);
2324 uploadslice (tile, slice);
2326 glBegin (GL_QUADS);
2328 glTexCoord2i (tilex, slicey);
2329 glVertex2i (dispx, dispy);
2331 glTexCoord2i (tilex+dispw, slicey);
2332 glVertex2i (dispx+dispw, dispy);
2334 glTexCoord2i (tilex+dispw, slicey+dh);
2335 glVertex2i (dispx+dispw, dispy+dh);
2337 glTexCoord2i (tilex, slicey+dh);
2338 glVertex2i (dispx, dispy+dh);
2340 glEnd ();
2342 dispy += dh;
2343 disph -= dh;
2344 slice++;
2345 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2346 slicey = 0;
2349 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2350 CAMLreturn (Val_unit);
2353 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2354 value xoff_v, value yoff_v,
2355 value li_v)
2357 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2358 int xoff = Int_val (xoff_v);
2359 int yoff = Int_val (yoff_v);
2360 int noff = Int_val (Field (li_v, 0));
2361 char *targ = String_val (Field (li_v, 1));
2362 int tlen = caml_string_length (Field (li_v, 1));
2363 int hfsize = Int_val (Field (li_v, 2));
2364 char *s = String_val (ptr_v);
2365 int hlmask = Int_val (hlinks_v);
2366 struct page *page = parse_pointer ("ml_postprocess", s);
2368 if (!page->u.ptr) {
2369 /* deal with loadpage failed pages */
2370 goto done;
2373 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2374 if (trylock ("ml_postprocess")) {
2375 noff = 0;
2376 goto done;
2378 if (hlmask & 2) {
2379 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2380 noff = page->slinkcount;
2382 showsel (page, xoff, yoff);
2383 unlock ("ml_postprocess");
2385 done:
2386 CAMLreturn (Val_int (noff));
2389 static fz_link *getlink (struct page *page, int x, int y)
2391 fz_point p;
2392 fz_matrix ctm;
2393 const fz_matrix *tctm;
2394 fz_link *link, *links;
2396 switch (page->type) {
2397 case DPDF:
2398 trimctm (page->u.pdfpage, page->pdimno);
2399 tctm = &state.pagedims[page->pdimno].tctm;
2400 links = page->u.pdfpage->links;
2401 break;
2403 case DXPS:
2404 tctm = &fz_identity;
2405 links = page->u.xpspage->links;
2406 break;
2408 default:
2409 return NULL;
2411 p.x = x;
2412 p.y = y;
2414 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2415 fz_invert_matrix (&ctm, &ctm);
2416 fz_transform_point (&p, &ctm);
2418 for (link = links; link; link = link->next) {
2419 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2420 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2421 return link;
2425 return NULL;
2428 static void ensuretext (struct page *page)
2430 if (state.gen != page->tgen) {
2431 droptext (page);
2432 page->tgen = state.gen;
2434 if (!page->text) {
2435 fz_matrix ctm;
2436 fz_device *tdev;
2438 page->text = fz_new_text_page (state.ctx, &fz_infinite_rect);
2439 page->sheet = fz_new_text_sheet (state.ctx);
2440 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2441 ctm = pagectm (page);
2442 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2443 qsort (page->text->blocks, page->text->len,
2444 sizeof (*page->text->blocks), compareblocks);
2445 fz_free_device (tdev);
2449 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2451 CAMLparam2 (start_page_v, dir_v);
2452 CAMLlocal1 (ret_v);
2453 int i, dir = Int_val (dir_v);
2454 int start_page = Int_val (start_page_v);
2455 int end_page = dir > 0 ? state.pagecount : -1;
2457 ret_v = Val_int (0);
2458 if (!(state.type == DPDF || state.type == DXPS)) {
2459 goto done;
2462 lock ("ml_findpage_with_links");
2463 for (i = start_page + dir; i != end_page; i += dir) {
2464 int found;
2466 switch (state.type) {
2467 case DPDF:
2469 pdf_page *page = NULL;
2471 fz_try (state.ctx) {
2472 page = pdf_load_page (state.u.pdf, i);
2473 found = !!page->links;
2475 fz_catch (state.ctx) {
2476 found = 0;
2478 if (page) {
2479 freepdfpage (page);
2482 break;
2483 case DXPS:
2485 xps_page *page = xps_load_page (state.u.xps, i);
2486 found = !!page->links;
2487 freexpspage (page);
2489 break;
2491 default:
2492 ARSERT ("invalid document type");
2495 if (found) {
2496 ret_v = caml_alloc_small (1, 1);
2497 Field (ret_v, 0) = Val_int (i);
2498 goto unlock;
2501 unlock:
2502 unlock ("ml_findpage_with_links");
2504 done:
2505 CAMLreturn (ret_v);
2508 enum { dir_first, dir_last};
2509 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2511 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2513 CAMLparam2 (ptr_v, dir_v);
2514 CAMLlocal2 (ret_v, pos_v);
2515 struct page *page;
2516 int dirtag, i, slinkindex;
2517 struct slink *found = NULL ,*slink;
2518 char *s = String_val (ptr_v);
2520 page = parse_pointer ("ml_findlink", s);
2521 ret_v = Val_int (0);
2522 if (trylock ("ml_findlink")) {
2523 goto done;
2526 ensureslinks (page);
2528 if (Is_block (dir_v)) {
2529 dirtag = Tag_val (dir_v);
2530 switch (dirtag) {
2531 case dir_first_visible:
2533 int x0, y0, dir, first_index, last_index;
2535 pos_v = Field (dir_v, 0);
2536 x0 = Int_val (Field (pos_v, 0));
2537 y0 = Int_val (Field (pos_v, 1));
2538 dir = Int_val (Field (pos_v, 2));
2540 if (dir >= 0) {
2541 dir = 1;
2542 first_index = 0;
2543 last_index = page->slinkcount;
2545 else {
2546 first_index = page->slinkcount - 1;
2547 last_index = -1;
2550 for (i = first_index; i != last_index; i += dir) {
2551 slink = &page->slinks[i];
2552 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2553 found = slink;
2554 break;
2558 break;
2560 case dir_left:
2561 slinkindex = Int_val (Field (dir_v, 0));
2562 found = &page->slinks[slinkindex];
2563 for (i = slinkindex - 1; i >= 0; --i) {
2564 slink = &page->slinks[i];
2565 if (slink->bbox.x0 < found->bbox.x0) {
2566 found = slink;
2567 break;
2570 break;
2572 case dir_right:
2573 slinkindex = Int_val (Field (dir_v, 0));
2574 found = &page->slinks[slinkindex];
2575 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2576 slink = &page->slinks[i];
2577 if (slink->bbox.x0 > found->bbox.x0) {
2578 found = slink;
2579 break;
2582 break;
2584 case dir_down:
2585 slinkindex = Int_val (Field (dir_v, 0));
2586 found = &page->slinks[slinkindex];
2587 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2588 slink = &page->slinks[i];
2589 if (slink->bbox.y0 >= found->bbox.y0) {
2590 found = slink;
2591 break;
2594 break;
2596 case dir_up:
2597 slinkindex = Int_val (Field (dir_v, 0));
2598 found = &page->slinks[slinkindex];
2599 for (i = slinkindex - 1; i >= 0; --i) {
2600 slink = &page->slinks[i];
2601 if (slink->bbox.y0 <= found->bbox.y0) {
2602 found = slink;
2603 break;
2606 break;
2609 else {
2610 dirtag = Int_val (dir_v);
2611 switch (dirtag) {
2612 case dir_first:
2613 found = page->slinks;
2614 break;
2616 case dir_last:
2617 if (page->slinks) {
2618 found = page->slinks + (page->slinkcount - 1);
2620 break;
2623 if (found) {
2624 ret_v = caml_alloc_small (2, 1);
2625 Field (ret_v, 0) = Val_int (found - page->slinks);
2628 unlock ("ml_findlink");
2629 done:
2630 CAMLreturn (ret_v);
2633 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2635 #define LINKTOVAL \
2637 int pageno; \
2639 switch (link->dest.kind) { \
2640 case FZ_LINK_GOTO: \
2642 fz_point p; \
2644 pageno = link->dest.ld.gotor.page; \
2645 p.x = 0; \
2646 p.y = 0; \
2648 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2649 p.y = link->dest.ld.gotor.lt.y; \
2650 fz_transform_point (&p, &pdim->lctm); \
2652 tup_v = caml_alloc_tuple (2); \
2653 ret_v = caml_alloc_small (1, ugoto); \
2654 Field (tup_v, 0) = Val_int (pageno); \
2655 Field (tup_v, 1) = Val_int (p.y); \
2656 Field (ret_v, 0) = tup_v; \
2658 break; \
2660 case FZ_LINK_URI: \
2661 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2662 ret_v = caml_alloc_small (1, uuri); \
2663 Field (ret_v, 0) = str_v; \
2664 break; \
2666 case FZ_LINK_LAUNCH: \
2667 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2668 ret_v = caml_alloc_small (1, ulaunch); \
2669 Field (ret_v, 0) = str_v; \
2670 break; \
2672 case FZ_LINK_NAMED: \
2673 str_v = caml_copy_string (link->dest.ld.named.named); \
2674 ret_v = caml_alloc_small (1, unamed); \
2675 Field (ret_v, 0) = str_v; \
2676 break; \
2678 case FZ_LINK_GOTOR: \
2679 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2680 pageno = link->dest.ld.gotor.page; \
2681 tup_v = caml_alloc_tuple (2); \
2682 ret_v = caml_alloc_small (1, uremote); \
2683 Field (tup_v, 0) = str_v; \
2684 Field (tup_v, 1) = Val_int (pageno); \
2685 Field (ret_v, 0) = tup_v; \
2686 break; \
2688 default: \
2690 char buf[80]; \
2692 snprintf (buf, sizeof (buf), \
2693 "unhandled link kind %d", link->dest.kind); \
2694 str_v = caml_copy_string (buf); \
2695 ret_v = caml_alloc_small (1, uunexpected); \
2696 Field (ret_v, 0) = str_v; \
2698 break; \
2702 CAMLprim value ml_getlink (value ptr_v, value n_v)
2704 CAMLparam2 (ptr_v, n_v);
2705 CAMLlocal3 (ret_v, tup_v, str_v);
2706 fz_link *link;
2707 struct page *page;
2708 struct pagedim *pdim;
2709 char *s = String_val (ptr_v);
2711 ret_v = Val_int (0);
2712 if (trylock ("ml_getlink")) {
2713 goto done;
2716 page = parse_pointer ("ml_getlink", s);
2717 ensureslinks (page);
2718 pdim = &state.pagedims[page->pdimno];
2719 link = page->slinks[Int_val (n_v)].link;
2720 LINKTOVAL;
2722 unlock ("ml_getlink");
2723 done:
2724 CAMLreturn (ret_v);
2727 CAMLprim value ml_getlinkcount (value ptr_v)
2729 CAMLparam1 (ptr_v);
2730 struct page *page;
2731 char *s = String_val (ptr_v);
2733 page = parse_pointer ("ml_getlinkcount", s);
2734 CAMLreturn (Val_int (page->slinkcount));
2737 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2739 CAMLparam2 (ptr_v, n_v);
2740 CAMLlocal1 (ret_v);
2741 struct page *page;
2742 struct slink *slink;
2743 char *s = String_val (ptr_v);
2745 page = parse_pointer ("ml_getlinkrect", s);
2746 ret_v = caml_alloc_tuple (4);
2747 if (trylock ("ml_getlinkrect")) {
2748 Field (ret_v, 0) = Val_int (0);
2749 Field (ret_v, 1) = Val_int (0);
2750 Field (ret_v, 2) = Val_int (0);
2751 Field (ret_v, 3) = Val_int (0);
2752 goto done;
2754 ensureslinks (page);
2756 slink = &page->slinks[Int_val (n_v)];
2757 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2758 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2759 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2760 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2761 unlock ("ml_getlinkrect");
2763 done:
2764 CAMLreturn (ret_v);
2767 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2769 CAMLparam3 (ptr_v, x_v, y_v);
2770 CAMLlocal3 (ret_v, tup_v, str_v);
2771 fz_link *link;
2772 struct page *page;
2773 char *s = String_val (ptr_v);
2774 int x = Int_val (x_v), y = Int_val (y_v);
2775 struct pagedim *pdim;
2777 ret_v = Val_int (0);
2778 if (trylock ("ml_whatsunder")) {
2779 goto done;
2782 page = parse_pointer ("ml_whatsunder", s);
2783 pdim = &state.pagedims[page->pdimno];
2784 x += pdim->bounds.x0;
2785 y += pdim->bounds.y0;
2786 link = getlink (page, x, y);
2787 if (link) {
2788 LINKTOVAL;
2790 else {
2791 fz_rect *b;
2792 fz_text_block *block;
2794 ensuretext (page);
2795 for (block = page->text->blocks;
2796 block < page->text->blocks + page->text->len;
2797 ++block) {
2798 fz_text_line *line;
2800 b = &block->bbox;
2801 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2802 continue;
2804 for (line = block->lines;
2805 line < block->lines + block->len;
2806 ++line) {
2807 fz_text_span *span;
2809 b = &line->bbox;
2810 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2811 continue;
2813 for (span = line->spans;
2814 span < line->spans + line->len;
2815 ++span) {
2816 fz_text_char *ch;
2818 b = &span->bbox;
2819 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2820 continue;
2822 for (ch = span->text; ch < span->text + span->len; ++ch) {
2823 b = &ch->bbox;
2825 if (x >= b->x0 && x <= b->x1
2826 && y >= b->y0 && y <= b->y1) {
2827 const char *n2 =
2828 span->style->font && span->style->font->name
2829 ? span->style->font->name
2830 : "Span has no font name"
2832 FT_FaceRec *face = span->style->font->ft_face;
2833 if (face && face->family_name) {
2834 char *s;
2835 char *n1 = face->family_name;
2836 size_t l1 = strlen (n1);
2837 size_t l2 = strlen (n2);
2839 if (l1 != l2 || memcmp (n1, n2, l1)) {
2840 s = malloc (l1 + l2 + 2);
2841 if (s) {
2842 memcpy (s, n2, l2);
2843 s[l2] = '=';
2844 memcpy (s + l2 + 1, n1, l1 + 1);
2845 str_v = caml_copy_string (s);
2846 free (s);
2850 if (str_v == 0) {
2851 str_v = caml_copy_string (n2);
2853 ret_v = caml_alloc_small (1, utext);
2854 Field (ret_v, 0) = str_v;
2855 goto unlock;
2862 unlock:
2863 unlock ("ml_whatsunder");
2865 done:
2866 CAMLreturn (ret_v);
2869 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2871 CAMLparam2 (ptr_v, rect_v);
2872 fz_rect *b;
2873 struct page *page;
2874 struct pagedim *pdim;
2875 int i, x0, x1, y0, y1;
2876 char *s = String_val (ptr_v);
2877 int fi = 0, li = 0;
2878 fz_text_block *block;
2879 fz_text_span *span, *fspan, *lspan;
2880 fz_text_line *line, *fline = NULL, *lline = NULL;
2882 if (trylock ("ml_seltext")) {
2883 goto done;
2886 page = parse_pointer ("ml_seltext", s);
2887 ensuretext (page);
2889 pdim = &state.pagedims[page->pdimno];
2890 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2891 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2892 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2893 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2895 if (0) {
2896 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2897 glColor3ub (128, 128, 128);
2898 glRecti (x0, y0, x1, y1);
2899 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2902 fspan = lspan = NULL;
2904 for (block = page->text->blocks;
2905 block < page->text->blocks + page->text->len;
2906 ++block) {
2907 for (line = block->lines;
2908 line < block->lines + block->len;
2909 ++line) {
2910 for (span = line->spans;
2911 span < line->spans + line->len;
2912 ++span) {
2913 for (i = 0; i < span->len; ++i) {
2914 b = &span->text[i].bbox;
2915 int selected = 0;
2917 if (x0 >= b->x0 && x0 <= b->x1
2918 && y0 >= b->y0 && y0 <= b->y1) {
2919 fspan = span;
2920 fline = line;
2921 fi = i;
2922 selected = 1;
2924 if (x1 >= b->x0 && x1 <= b->x1
2925 && y1 >= b->y0 && y1 <= b->y1) {
2926 lspan = span;
2927 lline = line;
2928 li = i;
2929 selected = 1;
2931 if (0 && selected) {
2932 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2933 glColor3ub (128, 128, 128);
2934 glRecti (b->x0, b->y0, b->x1, b->y1);
2935 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2941 if (y1 < y0 || x1 < x0) {
2942 int swap = 0;
2944 if (fspan == lspan) {
2945 swap = 1;
2947 else {
2948 if (y1 < y0) {
2949 if (fline != lline) {
2950 swap = 1;
2955 if (swap) {
2956 i = fi;
2957 span = fspan;
2959 fi = li;
2960 fspan = lspan;
2962 li = i;
2963 lspan = span;
2967 page->fmark.i = fi;
2968 page->fmark.span = fspan;
2970 page->lmark.i = li;
2971 page->lmark.span = lspan;
2973 unlock ("ml_seltext");
2975 done:
2976 CAMLreturn (Val_unit);
2979 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
2981 char buf[4];
2982 int i, len, ret;
2984 for (i = a; i <= b; ++i) {
2985 len = fz_runetochar (buf, span->text[i].c);
2986 ret = fwrite (buf, len, 1, f);
2988 if (ret != 1) {
2989 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
2990 len, ret, strerror (errno));
2991 return -1;
2994 return 0;
2997 #ifdef __CYGWIN__
2998 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3000 caml_failwith ("ml_popen not implemented under Cygwin");
3002 #else
3003 CAMLprim value ml_popen (value command_v, value fds_v)
3005 CAMLparam2 (command_v, fds_v);
3006 CAMLlocal2 (l_v, tup_v);
3007 int ret;
3008 char *msg = NULL;
3009 value earg_v = Nothing;
3010 posix_spawnattr_t attr;
3011 posix_spawn_file_actions_t fa;
3012 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
3014 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3015 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3018 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3019 msg = "posix_spawnattr_init";
3020 goto fail1;
3023 #ifdef POSIX_SPAWN_USEVFORK
3024 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3025 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3026 goto fail;
3028 #endif
3030 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3031 int fd1, fd2;
3033 tup_v = Field (l_v, 0);
3034 fd1 = Int_val (Field (tup_v, 0));
3035 fd2 = Int_val (Field (tup_v, 1));
3036 if (fd2 < 0) {
3037 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3038 msg = "posix_spawn_file_actions_addclose";
3039 earg_v = tup_v;
3040 goto fail;
3043 else {
3044 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3045 msg = "posix_spawn_file_actions_adddup2";
3046 earg_v = tup_v;
3047 goto fail;
3052 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3053 msg = "posix_spawn";
3054 goto fail;
3057 fail:
3058 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3059 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3062 fail1:
3063 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3064 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3065 strerror (ret));
3068 if (msg)
3069 unix_error (ret, msg, earg_v);
3071 CAMLreturn (Val_unit);
3073 #endif
3075 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3077 CAMLparam1 (ptr_v);
3078 FILE *f;
3079 int seen = 0;
3080 struct page *page;
3081 fz_text_line *line;
3082 fz_text_span *span;
3083 fz_text_block *block;
3084 int fd = Int_val (fd_v);
3085 char *s = String_val (ptr_v);
3087 if (trylock ("ml_copysel")) {
3088 goto done;
3091 page = parse_pointer ("ml_sopysel", s);
3093 if (!page->fmark.span || !page->lmark.span) {
3094 fprintf (stderr, "nothing to copy\n");
3095 goto unlock;
3098 f = fdopen (fd, "w");
3099 if (!f) {
3100 fprintf (stderr, "failed to fopen sel pipe: %s\n",
3101 strerror (errno));
3102 f = stdout;
3105 for (block = page->text->blocks;
3106 block < page->text->blocks + page->text->len;
3107 ++block) {
3108 for (line = block->lines;
3109 line < block->lines + block->len;
3110 ++line) {
3111 for (span = line->spans;
3112 span < line->spans + line->len;
3113 ++span) {
3114 int a, b;
3116 seen |= span == page->fmark.span || span == page->lmark.span;
3117 a = span == page->fmark.span ? page->fmark.i : 0;
3118 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3120 if (seen) {
3121 if (pipespan (f, span, a, b)) {
3122 goto close;
3124 if (span == line->spans + line->len - 1) {
3125 if (putc ('\n', f) == EOF) {
3126 fprintf (stderr,
3127 "failed break line on sel pipe: %s\n",
3128 strerror (errno));
3129 goto close;
3132 if (span == page->lmark.span) {
3133 goto endloop;
3139 endloop:
3140 page->lmark.span = NULL;
3141 page->fmark.span = NULL;
3143 close:
3144 if (f != stdout) {
3145 int ret = fclose (f);
3146 fd = -1;
3147 if (ret == -1) {
3148 if (errno != ECHILD) {
3149 fprintf (stderr, "failed to close sel pipe: %s\n",
3150 strerror (errno));
3154 unlock:
3155 unlock ("ml_copysel");
3157 done:
3158 if (fd >= 0) {
3159 if (close (fd)) {
3160 fprintf (stderr, "failed to close sel pipe: %s\n",
3161 strerror (errno));
3164 CAMLreturn (Val_unit);
3167 CAMLprim value ml_getpdimrect (value pagedimno_v)
3169 CAMLparam1 (pagedimno_v);
3170 CAMLlocal1 (ret_v);
3171 int pagedimno = Int_val (pagedimno_v);
3172 fz_rect box;
3174 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3175 if (trylock ("ml_getpdimrect")) {
3176 box = fz_empty_rect;
3178 else {
3179 box = state.pagedims[pagedimno].mediabox;
3180 unlock ("ml_getpdimrect");
3183 Store_double_field (ret_v, 0, box.x0);
3184 Store_double_field (ret_v, 1, box.x1);
3185 Store_double_field (ret_v, 2, box.y0);
3186 Store_double_field (ret_v, 3, box.y1);
3188 CAMLreturn (ret_v);
3191 static double getmaxw (void)
3193 int i;
3194 struct pagedim *p;
3195 double maxw = 0.0;
3197 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3198 double x0, x1, w;
3200 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
3201 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
3203 w = x1 - x0;
3204 maxw = MAX (w, maxw);
3206 return maxw;
3209 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3210 value dw_v, value cols_v)
3212 CAMLparam3 (winw_v, winh_v, dw_v);
3213 CAMLlocal1 (ret_v);
3214 int i;
3215 double zoom = 1.0;
3216 double maxw = 0.0, maxh = 0.0;
3217 struct pagedim *p;
3218 double winw = Int_val (winw_v);
3219 double winh = Int_val (winh_v);
3220 double dw = Int_val (dw_v);
3221 double cols = Int_val (cols_v);
3222 double pw = 1.0, ph = 1.0, aspect;
3224 if (trylock ("ml_zoom_for_height")) {
3225 goto done;
3228 if (state.proportional) {
3229 maxw = getmaxw () / cols;
3232 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3233 fz_rect rect;
3234 fz_matrix rm;
3235 double x0, x1, y0, y1, w, h, scaledh, scale;
3237 fz_rotate (&rm, p->rotate + state.rotate);
3238 rect = p->mediabox;
3239 fz_transform_rect (&rect, &rm);
3240 x0 = MIN (rect.x0, rect.x1);
3241 x1 = MAX (rect.x0, rect.x1);
3242 y0 = MIN (rect.y0, rect.y1);
3243 y1 = MAX (rect.y0, rect.y1);
3245 w = (x1 - x0) / cols;
3246 h = y1 - y0;
3248 if (state.proportional) {
3249 scale = w / maxw;
3250 scaledh = h * scale;
3252 else {
3253 scale = 1.0;
3254 scaledh = h;
3257 if (scaledh > maxh) {
3258 maxh = scaledh;
3259 ph = scaledh;
3260 pw = w * scale;
3264 aspect = pw / ph;
3265 zoom = (winh * aspect + dw) / winw;
3267 unlock ("ml_zoom_for_height");
3268 done:
3269 ret_v = caml_copy_double (zoom);
3270 CAMLreturn (ret_v);
3273 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3275 CAMLparam4 (pt_v, x_v, y_v, string_v);
3276 CAMLlocal1 (ret_v);
3277 int pt = Int_val(pt_v);
3278 int x = Int_val (x_v);
3279 int y = Int_val (y_v);
3280 double w;
3282 w = draw_string (state.face, pt, x, y, String_val (string_v));
3283 ret_v = caml_copy_double (w);
3284 CAMLreturn (ret_v);
3287 CAMLprim value ml_measure_string (value pt_v, value string_v)
3289 CAMLparam2 (pt_v, string_v);
3290 CAMLlocal1 (ret_v);
3291 int pt = Int_val (pt_v);
3292 double w;
3294 w = measure_string (state.face, pt, String_val (string_v));
3295 ret_v = caml_copy_double (w);
3296 CAMLreturn (ret_v);
3299 CAMLprim value ml_getpagebox (value opaque_v)
3301 CAMLparam1 (opaque_v);
3302 CAMLlocal1 (ret_v);
3303 fz_rect rect;
3304 fz_irect bbox;
3305 fz_matrix ctm;
3306 fz_device *dev;
3307 char *s = String_val (opaque_v);
3308 struct page *page = parse_pointer ("ml_getpagebox", s);
3310 ret_v = caml_alloc_tuple (4);
3311 dev = fz_new_bbox_device (state.ctx, &rect);
3312 dev->hints |= FZ_IGNORE_SHADE;
3314 switch (page->type) {
3315 case DPDF:
3316 ctm = pagectm (page);
3317 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3318 break;
3320 case DXPS:
3321 ctm = pagectm (page);
3322 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3323 break;
3325 default:
3326 rect = fz_infinite_rect;
3327 break;
3330 fz_free_device (dev);
3331 fz_round_rect (&bbox, &rect);
3332 Field (ret_v, 0) = Val_int (bbox.x0);
3333 Field (ret_v, 1) = Val_int (bbox.y0);
3334 Field (ret_v, 2) = Val_int (bbox.x1);
3335 Field (ret_v, 3) = Val_int (bbox.y1);
3337 CAMLreturn (ret_v);
3340 CAMLprim value ml_setaalevel (value level_v)
3342 CAMLparam1 (level_v);
3344 state.aalevel = Int_val (level_v);
3345 CAMLreturn (Val_unit);
3348 #undef pixel
3349 #include <X11/Xlib.h>
3350 #include <GL/glx.h>
3352 static struct {
3353 Display *dpy;
3354 GLXContext ctx;
3355 GLXDrawable drawable;
3356 } glx;
3358 #include "keysym2ucs.c"
3360 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3362 CAMLparam1 (keysym_v);
3363 CAMLlocal1 (str_v);
3364 KeySym keysym = Int_val (keysym_v);
3365 Rune rune;
3366 int len;
3367 char buf[5];
3369 rune = keysym2ucs (keysym);
3370 len = fz_runetochar (buf, rune);
3371 buf[len] = 0;
3372 str_v = caml_copy_string (buf);
3373 CAMLreturn (str_v);
3376 CAMLprim value ml_glx (value win_v)
3378 CAMLparam1 (win_v);
3379 XVisualInfo *visual;
3380 int screen, wid = Int_val (win_v);
3381 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3383 glx.dpy = XOpenDisplay (NULL);
3384 if (!glx.dpy) {
3385 caml_failwith ("XOpenDisplay");
3388 screen = DefaultScreen (glx.dpy);
3389 visual = glXChooseVisual (glx.dpy, screen, attributes);
3390 if (!visual) {
3391 XCloseDisplay (glx.dpy);
3392 glx.dpy = NULL;
3393 caml_failwith ("glXChooseVisual");
3396 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3397 XFree (visual);
3398 if (!glx.ctx) {
3399 XCloseDisplay (glx.dpy);
3400 glx.dpy = NULL;
3401 caml_failwith ("glXCreateContext");
3404 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3405 glXDestroyContext (glx.dpy, glx.ctx);
3406 XCloseDisplay (glx.dpy);
3407 glx.dpy = NULL;
3408 glx.ctx = NULL;
3409 caml_failwith ("glXMakeCurrent");
3411 glx.drawable = wid;
3412 CAMLreturn (Val_unit);
3415 CAMLprim value ml_swapb (value unit_v)
3417 CAMLparam1 (unit_v);
3418 glXSwapBuffers (glx.dpy, glx.drawable);
3419 CAMLreturn (Val_unit);
3422 CAMLprim value ml_glxsync (value unit_v)
3424 CAMLparam1 (unit_v);
3425 if (glx.dpy && glx.ctx) {
3426 glXWaitX ();
3427 glXWaitGL ();
3429 CAMLreturn (Val_unit);
3432 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3433 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3435 CAMLprim value ml_platform (value unit_v)
3437 CAMLparam1 (unit_v);
3438 int platid = piunknown;
3440 #if defined __linux__
3441 platid = pilinux;
3442 #elif defined __CYGWIN__
3443 platid = picygwin;
3444 #elif defined __DragonFly__
3445 platid = pidragonflybsd;
3446 #elif defined __FreeBSD__
3447 platid = pifreebsd;
3448 #elif defined __OpenBSD__
3449 platid = piopenbsd;
3450 #elif defined __NetBSD__
3451 platid = pinetbsd;
3452 #elif defined __sun__
3453 platid = pisun;
3454 #elif defined __APPLE__
3455 platid = piosx;
3456 #endif
3457 CAMLreturn (Val_int (platid));
3460 CAMLprim value ml_cloexec (value fd_v)
3462 CAMLparam1 (fd_v);
3463 int fd = Int_val (fd_v);
3465 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3466 uerror ("fcntl", Nothing);
3468 CAMLreturn (Val_unit);
3471 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3473 CAMLparam2 (w_v, h_v);
3474 CAMLlocal1 (ret_v);
3475 struct pbo *pbo;
3476 int w = Int_val (w_v);
3477 int h = Int_val (h_v);
3478 int cs = Int_val (cs_v);
3480 if (state.pbo_usable) {
3481 pbo = calloc (sizeof (*pbo), 1);
3482 if (!pbo) {
3483 err (1, "calloc pbo");
3486 switch (cs) {
3487 case 0:
3488 case 1:
3489 pbo->size = w*h*4;
3490 break;
3491 case 2:
3492 pbo->size = w*h*2;
3493 break;
3494 default:
3495 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3498 state.glGenBuffersARB (1, &pbo->id);
3499 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3500 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3501 NULL, GL_STREAM_DRAW);
3502 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3503 GL_READ_WRITE);
3504 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3505 if (!pbo->ptr) {
3506 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3507 state.glDeleteBuffersARB (1, &pbo->id);
3508 free (pbo);
3509 ret_v = caml_copy_string ("0");
3511 else {
3512 int res;
3513 char *s;
3515 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3516 if (res < 0) {
3517 err (1, "snprintf %" FMT_ptr " failed", pbo);
3519 s = malloc (res+1);
3520 if (!s) {
3521 err (1, "malloc %d bytes failed", res+1);
3523 res = sprintf (s, "%" FMT_ptr, pbo);
3524 if (res < 0) {
3525 err (1, "sprintf %" FMT_ptr " failed", pbo);
3527 ret_v = caml_copy_string (s);
3528 free (s);
3531 else {
3532 ret_v = caml_copy_string ("0");
3534 CAMLreturn (ret_v);
3537 CAMLprim value ml_freepbo (value s_v)
3539 CAMLparam1 (s_v);
3540 char *s = String_val (s_v);
3541 struct tile *tile = parse_pointer ("ml_freepbo", s);
3543 if (tile->pbo) {
3544 state.glDeleteBuffersARB (1, &tile->pbo->id);
3545 tile->pbo->id = -1;
3546 tile->pbo->ptr = NULL;
3547 tile->pbo->size = -1;
3549 CAMLreturn (Val_unit);
3552 CAMLprim value ml_unmappbo (value s_v)
3554 CAMLparam1 (s_v);
3555 char *s = String_val (s_v);
3556 struct tile *tile = parse_pointer ("ml_unmappbo", s);
3558 if (tile->pbo) {
3559 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3560 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3561 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3563 tile->pbo->ptr = NULL;
3564 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3566 CAMLreturn (Val_unit);
3569 static void setuppbo (void)
3571 #define GGPA(n) *(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n)
3572 GGPA (glBindBufferARB);
3573 if (state.glBindBufferARB) {
3574 GGPA (glUnmapBufferARB);
3575 if (state.glUnmapBufferARB) {
3576 GGPA (glMapBufferARB);
3577 if (state.glMapBufferARB) {
3578 GGPA (glBufferDataARB);
3579 if (state.glBufferDataARB) {
3580 GGPA (glGenBuffersARB);
3581 if (state.glGenBuffersARB) {
3582 GGPA (glDeleteBuffersARB);
3583 if (state.glDeleteBuffersARB) {
3584 state.pbo_usable = 1;
3591 #undef GGPA
3594 CAMLprim value ml_pbo_usable (value unit_v)
3596 CAMLparam1 (unit_v);
3597 CAMLreturn (Val_bool (state.pbo_usable));
3600 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3602 CAMLparam3 (ptr_v, x_v, y_v);
3603 CAMLlocal2 (ret_v, tup_v);
3604 struct page *page;
3605 char *s = String_val (ptr_v);
3606 int x = Int_val (x_v), y = Int_val (y_v);
3607 struct pagedim *pdim;
3608 fz_point p;
3609 fz_matrix ctm;
3611 page = parse_pointer ("ml_unproject", s);
3612 pdim = &state.pagedims[page->pdimno];
3614 ret_v = Val_int (0);
3615 if (trylock ("ml_unproject")) {
3616 goto done;
3619 switch (page->type) {
3620 case DPDF:
3621 trimctm (page->u.pdfpage, page->pdimno);
3622 break;
3624 default:
3625 break;
3627 p.x = x;
3628 p.y = y;
3630 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3631 fz_invert_matrix (&ctm, &ctm);
3632 fz_transform_point (&p, &ctm);
3634 tup_v = caml_alloc_tuple (2);
3635 ret_v = caml_alloc_small (1, 1);
3636 Field (tup_v, 0) = Val_int (p.x);
3637 Field (tup_v, 1) = Val_int (p.y);
3638 Field (ret_v, 0) = tup_v;
3640 unlock ("ml_unproject");
3641 done:
3642 CAMLreturn (ret_v);
3645 CAMLprim value ml_init (value pipe_v, value params_v)
3647 CAMLparam2 (pipe_v, params_v);
3648 CAMLlocal2 (trim_v, fuzz_v);
3649 int ret;
3650 int texcount;
3651 char *fontpath;
3652 int colorspace;
3653 int mustoresize;
3654 int haspboext;
3655 struct sigaction sa;
3657 state.cr = Int_val (Field (pipe_v, 0));
3658 state.cw = Int_val (Field (pipe_v, 1));
3659 state.rotate = Int_val (Field (params_v, 0));
3660 state.proportional = Bool_val (Field (params_v, 1));
3661 trim_v = Field (params_v, 2);
3662 texcount = Int_val (Field (params_v, 3));
3663 state.sliceheight = Int_val (Field (params_v, 4));
3664 mustoresize = Int_val (Field (params_v, 5));
3665 colorspace = Int_val (Field (params_v, 6));
3666 fontpath = String_val (Field (params_v, 7));
3667 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
3668 if (!state.trimcachepath) {
3669 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
3670 strerror (errno));
3672 haspboext = Bool_val (Field (params_v, 9));
3674 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3676 state.trimmargins = Bool_val (Field (trim_v, 0));
3677 fuzz_v = Field (trim_v, 1);
3678 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3679 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3680 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3681 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3683 set_tex_params (colorspace);
3685 if (*fontpath) {
3686 state.face = load_font (fontpath);
3688 else {
3689 unsigned int len;
3690 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
3692 state.face = load_builtin_font (base, len);
3694 if (!state.face) _exit (1);
3696 realloctexts (texcount);
3698 if (haspboext) {
3699 setuppbo ();
3702 #ifdef __CYGWIN__
3703 sa.sa_handler = SIG_IGN;
3704 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3705 #else
3706 sa.sa_handler = SIG_DFL;
3707 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
3708 #endif
3709 if (sigemptyset (&sa.sa_mask)) {
3710 err (1, "sigemptyset");
3712 if (sigaction (SIGCHLD, &sa, NULL)) {
3713 err (1, "sigaction");
3716 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3717 if (ret) {
3718 errx (1, "pthread_create: %s", strerror (ret));
3721 CAMLreturn (Val_unit);