Slightly more intuitive
[llpp.git] / link.c
blobfa4b5f71508a4a4fbce2e300a8247e16ebc7bddc
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 enum { FitWidth, FitProportional, FitPage } fitmodel;
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 GLuint stid;
233 int pbo_usable;
234 void (*glBindBufferARB) (GLenum, GLuint);
235 GLboolean (*glUnmapBufferARB) (GLenum);
236 void *(*glMapBufferARB) (GLenum, GLenum);
237 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
238 void (*glGenBuffersARB) (GLsizei, GLuint *);
239 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
240 } state;
242 struct pbo {
243 GLuint id;
244 void *ptr;
245 size_t size;
248 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
250 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
253 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
255 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
258 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
260 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
261 m.a, m.b, m.c, m.d, m.e, m.f);
264 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
266 static void lock (const char *cap)
268 int ret = pthread_mutex_lock (&mutex);
269 if (ret) {
270 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
274 static void unlock (const char *cap)
276 int ret = pthread_mutex_unlock (&mutex);
277 if (ret) {
278 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
282 static int trylock (const char *cap)
284 int ret = pthread_mutex_trylock (&mutex);
285 if (ret && ret != EBUSY) {
286 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
288 return ret == EBUSY;
291 static void *parse_pointer (const char *cap, const char *s)
293 int ret;
294 void *ptr;
296 ret = sscanf (s, "%" FMT_ptr, FMT_ptr_cast (&ptr));
297 if (ret != 1) {
298 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
300 return ptr;
303 static double now (void)
305 struct timeval tv;
307 if (gettimeofday (&tv, NULL)) {
308 err (1, "gettimeofday");
310 return tv.tv_sec + tv.tv_usec*1e-6;
313 static int hasdata (void)
315 int ret, avail;
316 ret = ioctl (state.cr, FIONREAD, &avail);
317 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
318 return avail > 0;
321 CAMLprim value ml_hasdata (value fd_v)
323 CAMLparam1 (fd_v);
324 int ret, avail;
326 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
327 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
328 CAMLreturn (Val_bool (avail > 0));
331 static void readdata (void *p, int size)
333 ssize_t n;
335 again:
336 n = read (state.cr, p, size);
337 if (n < 0) {
338 if (errno == EINTR) goto again;
339 err (1, "read (req %d, ret %zd)", size, n);
341 if (n - size) {
342 if (!n) errx (1, "EOF while reading");
343 errx (1, "read (req %d, ret %zd)", size, n);
347 static void writedata (char *p, int size)
349 char buf[4];
350 ssize_t n;
352 buf[0] = (size >> 24) & 0xff;
353 buf[1] = (size >> 16) & 0xff;
354 buf[2] = (size >> 8) & 0xff;
355 buf[3] = (size >> 0) & 0xff;
357 n = write (state.cw, buf, 4);
358 if (n != 4) {
359 if (!n) errx (1, "EOF while writing length");
360 err (1, "write %zd", n);
363 n = write (state.cw, p, size);
364 if (n - size) {
365 if (!n) errx (1, "EOF while writing data");
366 err (1, "write (req %d, ret %zd)", size, n);
370 static int readlen (void)
372 unsigned char p[4];
374 readdata (p, 4);
375 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
378 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
380 int size = 200, len;
381 va_list ap;
382 char *buf;
384 buf = malloc (size);
385 for (;;) {
386 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
388 va_start (ap, fmt);
389 len = vsnprintf (buf, size, fmt, ap);
390 va_end (ap);
392 if (len > -1 && len < size) {
393 writedata (buf, len);
394 break;
397 if (len > -1) {
398 size = len + 1;
400 else {
401 size *= 2;
403 buf = realloc (buf, size);
405 free (buf);
408 static void closepdf (void)
410 if (state.u.pdf) {
411 pdf_close_document (state.u.pdf);
412 state.u.pdf = NULL;
416 static void closexps (void)
418 if (state.u.xps) {
419 xps_close_document (state.u.xps);
420 state.u.xps = NULL;
424 static void closecbz (void)
426 if (state.u.cbz) {
427 cbz_close_document (state.u.cbz);
428 state.u.cbz = NULL;
432 static void freepdfpage (void *ptr)
434 pdf_free_page (state.u.pdf, ptr);
437 static void freeemptyxxxpage (void *ptr)
439 (void) ptr;
442 static void freexpspage (void *ptr)
444 xps_free_page (state.u.xps, ptr);
447 static void freecbzpage (void *ptr)
449 cbz_free_page (state.u.cbz, ptr);
452 static void openxref (char *filename, char *password)
454 int i, len;
456 for (i = 0; i < state.texcount; ++i) {
457 state.texowners[i].w = -1;
458 state.texowners[i].slice = NULL;
461 if (state.closedoc) state.closedoc ();
463 len = strlen (filename);
465 state.type = DPDF;
466 if (len > 4) {
467 char ext[4];
469 ext[0] = tolower ((int) filename[len-3]);
470 ext[1] = tolower ((int) filename[len-2]);
471 ext[2] = tolower ((int) filename[len-1]);
473 /**/ if (ext[0] == 'x' && ext[1] == 'p' && ext[2] == 's') {
474 state.type = DXPS;
476 else if (ext[0] == 'c' && ext[1] == 'b' && ext[2] == 'z') {
477 state.type = DCBZ;
481 if (state.pagedims) {
482 free (state.pagedims);
483 state.pagedims = NULL;
485 state.pagedimcount = 0;
487 fz_set_aa_level (state.ctx, state.aalevel);
488 switch (state.type) {
489 case DPDF:
490 state.u.pdf = pdf_open_document (state.ctx, filename);
491 if (pdf_needs_password (state.u.pdf)) {
492 int okay = pdf_authenticate_password (state.u.pdf, password);
493 if (!okay) {
494 errx (1, "invalid password");
497 state.pagecount = pdf_count_pages (state.u.pdf);
498 state.closedoc = closepdf;
499 state.freepage = freepdfpage;
500 break;
502 case DXPS:
503 state.u.xps = xps_open_document (state.ctx, filename);
504 state.pagecount = xps_count_pages (state.u.xps);
505 state.closedoc = closexps;
506 state.freepage = freexpspage;
507 break;
509 case DCBZ:
510 state.u.cbz = cbz_open_document (state.ctx, filename);
511 state.pagecount = cbz_count_pages (state.u.cbz);
512 state.closedoc = closecbz;
513 state.freepage = freecbzpage;
514 break;
518 static void pdfinfo (void)
520 if (state.type == DPDF) {
521 pdf_obj *infoobj;
523 printd ("info PDF version\t%d.%d",
524 state.u.pdf->version / 10, state.u.pdf->version % 10);
526 infoobj = pdf_dict_gets (state.u.pdf->trailer, "Info");
527 if (infoobj) {
528 int i;
529 char *s;
530 char *items[] = { "Title", "Author", "Creator",
531 "Producer", "CreationDate" };
533 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
534 pdf_obj *obj = pdf_dict_gets (infoobj, items[i]);
535 s = pdf_to_utf8 (state.u.pdf, obj);
536 if (*s) {
537 if (i == 0) {
538 printd ("title %s", s);
540 printd ("info %s\t%s", items[i], s);
542 fz_free (state.ctx, s);
545 printd ("infoend");
549 static void unlinktile (struct tile *tile)
551 int i;
553 for (i = 0; i < tile->slicecount; ++i) {
554 struct slice *s = &tile->slices[i];
556 if (s->texindex != -1) {
557 if (state.texowners[s->texindex].slice == s) {
558 state.texowners[s->texindex].slice = NULL;
564 static void freepage (struct page *page)
566 if (page->text) {
567 fz_free_text_page (state.ctx, page->text);
569 if (page->sheet) {
570 fz_free_text_sheet (state.ctx, page->sheet);
572 if (page->slinks) {
573 free (page->slinks);
575 page->freepage (page->u.ptr);
576 fz_free_display_list (state.ctx, page->dlist);
577 free (page);
580 static void freetile (struct tile *tile)
582 unlinktile (tile);
583 if (!tile->pbo) {
584 #ifndef PIGGYBACK
585 fz_drop_pixmap (state.ctx, tile->pixmap);
586 #else
587 if (state.pig) {
588 fz_drop_pixmap (state.ctx, state.pig);
590 state.pig = tile->pixmap;
591 #endif
593 else {
594 free (tile->pbo);
595 fz_drop_pixmap (state.ctx, tile->pixmap);
597 free (tile);
600 #ifdef __ALTIVEC__
601 #include <stdint.h>
602 #include <altivec.h>
604 static int cacheline32bytes;
606 static void __attribute__ ((constructor)) clcheck (void)
608 char **envp = environ;
609 unsigned long *auxv;
611 while (*envp++);
613 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
614 if (*auxv == 19) {
615 cacheline32bytes = auxv[1] == 32;
616 return;
621 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
623 size_t size = pixmap->w * pixmap->h * pixmap->n;
624 if (cacheline32bytes && size > 32) {
625 intptr_t a1, a2, diff;
626 size_t sizea, i;
627 vector unsigned char v = vec_splat_u8 (-1);
628 vector unsigned char *p;
630 a1 = a2 = (intptr_t) pixmap->samples;
631 a2 = (a1 + 31) & ~31;
632 diff = a2 - a1;
633 sizea = size - diff;
634 p = (void *) a2;
636 while (a1 != a2) *(char *) a1++ = 0xff;
637 for (i = 0; i < (sizea & ~31); i += 32) {
638 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
639 vec_st (v, i, p);
640 vec_st (v, i + 16, p);
642 while (i < sizea) *((char *) a1 + i++) = 0xff;
644 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
646 #else
647 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
648 #endif
650 static void trimctm (pdf_page *page, int pindex)
652 fz_matrix ctm;
653 struct pagedim *pdim = &state.pagedims[pindex];
655 if (!pdim->tctmready) {
656 if (state.trimmargins) {
657 fz_rect realbox;
658 fz_matrix rm, sm, tm, im, ctm1;
660 fz_rotate (&rm, -pdim->rotate);
661 fz_scale (&sm, 1, -1);
662 fz_concat (&ctm, &rm, &sm);
663 realbox = pdim->mediabox;
664 fz_transform_rect (&realbox, &ctm);
665 fz_translate (&tm, -realbox.x0, -realbox.y0);
666 fz_concat (&ctm1, &ctm, &tm);
667 fz_invert_matrix (&im, &page->ctm);
668 fz_concat (&ctm, &im, &ctm1);
670 else {
671 ctm = fz_identity;
673 pdim->tctm = ctm;
674 pdim->tctmready = 1;
678 static fz_matrix pagectm (struct page *page)
680 fz_matrix ctm, tm;
682 if (page->type == DPDF) {
683 trimctm (page->u.pdfpage, page->pdimno);
684 fz_concat (&ctm,
685 &state.pagedims[page->pdimno].tctm,
686 &state.pagedims[page->pdimno].ctm);
688 else {
689 struct pagedim *pdim = &state.pagedims[page->pdimno];
691 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
692 fz_concat (&ctm, &tm, &state.pagedims[page->pdimno].ctm);
694 return ctm;
697 static void *loadpage (int pageno, int pindex)
699 fz_device *dev;
700 struct page *page = NULL;
702 page = calloc (sizeof (struct page), 1);
703 if (!page) {
704 err (1, "calloc page %d", pageno);
707 page->dlist = fz_new_display_list (state.ctx);
708 dev = fz_new_list_device (state.ctx, page->dlist);
709 fz_try (state.ctx) {
710 switch (state.type) {
711 case DPDF:
712 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
713 pdf_run_page (state.u.pdf, page->u.pdfpage, dev,
714 &fz_identity, NULL);
715 page->freepage = freepdfpage;
716 break;
718 case DXPS:
719 page->u.xpspage = xps_load_page (state.u.xps, pageno);
720 xps_run_page (state.u.xps, page->u.xpspage, dev,
721 &fz_identity, NULL);
722 page->freepage = freexpspage;
723 break;
725 case DCBZ:
726 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
727 cbz_run_page (state.u.cbz, page->u.cbzpage, dev,
728 &fz_identity, NULL);
729 page->freepage = freecbzpage;
730 break;
733 fz_catch (state.ctx) {
734 page->u.ptr = NULL;
735 page->freepage = freeemptyxxxpage;
737 fz_free_device (dev);
739 page->pdimno = pindex;
740 page->pageno = pageno;
741 page->sgen = state.gen;
742 page->tgen = state.gen;
743 page->type = state.type;
745 return page;
748 static struct tile *alloctile (int h)
750 int i;
751 int slicecount;
752 size_t tilesize;
753 struct tile *tile;
755 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
756 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
757 tile = calloc (tilesize, 1);
758 if (!tile) {
759 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
761 for (i = 0; i < slicecount; ++i) {
762 int sh = MIN (h, state.sliceheight);
763 tile->slices[i].h = sh;
764 tile->slices[i].texindex = -1;
765 h -= sh;
767 tile->slicecount = slicecount;
768 tile->sliceheight = state.sliceheight;
769 return tile;
772 #ifdef OBSCURED_OPT
773 struct obs {
774 int cured;
775 fz_irect b;
778 static void obs_fill_image (fz_device *dev, fz_image *image,
779 const fz_matrix *ctm, float alpha)
781 struct obs *obs = dev->user;
783 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
784 fz_irect b;
785 fz_rect rect = fz_unit_rect;
787 fz_transform_rect (&rect, ctm);
788 fz_round_rect (&b, &rect);
789 fz_intersect_irect (&b, &obs->b);
790 obs->cured = b.x0 == obs->b.x0
791 && b.x1 == obs->b.x1
792 && b.y0 == obs->b.y0
793 && b.y1 == obs->b.y1;
797 static int obscured (struct page *page, fz_irect bbox)
799 fz_rect rect;
800 fz_matrix ctm;
801 fz_device dev;
802 struct obs obs;
804 memset (&dev, 0, sizeof (dev));
805 memset (&obs, 0, sizeof (obs));
806 dev.hints = 0;
807 dev.flags = 0;
808 dev.user = &obs;
809 dev.ctx = state.ctx;
810 dev.fill_image = obs_fill_image;
811 obs.b = bbox;
812 fz_rect_from_irect (&rect, &bbox);
813 ctm = pagectm (page);
814 fz_run_display_list (page->dlist, &dev, &ctm, &rect, NULL);
815 return obs.cured;
817 #define OBSCURED obscured
818 #else
819 #define OBSCURED(a, b) 0
820 #endif
822 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
823 struct pbo *pbo)
825 fz_rect rect;
826 fz_irect bbox;
827 fz_matrix ctm;
828 fz_device *dev;
829 struct tile *tile;
830 struct pagedim *pdim;
832 tile = alloctile (h);
833 pdim = &state.pagedims[page->pdimno];
835 bbox = pdim->bounds;
836 bbox.x0 += x;
837 bbox.y0 += y;
838 bbox.x1 = bbox.x0 + w;
839 bbox.y1 = bbox.y0 + h;
841 if (state.pig) {
842 if (state.pig->w == w
843 && state.pig->h == h
844 && state.pig->colorspace == state.colorspace) {
845 tile->pixmap = state.pig;
846 tile->pixmap->x = bbox.x0;
847 tile->pixmap->y = bbox.y0;
849 else {
850 fz_drop_pixmap (state.ctx, state.pig);
852 state.pig = NULL;
854 if (!tile->pixmap) {
855 if (pbo) {
856 tile->pixmap =
857 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
858 &bbox, pbo->ptr);
859 tile->pbo = pbo;
861 else {
862 tile->pixmap =
863 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
867 tile->w = w;
868 tile->h = h;
869 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
870 clearpixmap (tile->pixmap);
872 dev = fz_new_draw_device (state.ctx, tile->pixmap);
873 ctm = pagectm (page);
874 fz_rect_from_irect (&rect, &bbox);
875 fz_run_display_list (page->dlist, dev, &ctm, &rect, NULL);
876 fz_free_device (dev);
878 return tile;
881 static void initpdims (void)
883 double start, end;
884 int pageno, trim, show;
885 FILE *trimf = NULL;
886 int trimw = 0;
888 start = now ();
890 if (state.trimmargins && state.trimcachepath) {
891 trimf = fopen (state.trimcachepath, "rb");
892 if (!trimf) {
893 trimf = fopen (state.trimcachepath, "wb");
894 trimw = 1;
897 for (pageno = 0; pageno < state.pagecount; ++pageno) {
898 int rotate = 0;
899 struct pagedim *p;
900 fz_rect mediabox;
902 switch (state.type) {
903 case DPDF: {
904 pdf_obj *pageobj = state.u.pdf->page_objs[pageno];
906 if (state.trimmargins) {
907 pdf_obj *obj;
908 pdf_page *page;
910 fz_try (state.ctx) {
911 page = pdf_load_page (state.u.pdf, pageno);
912 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
913 trim = state.trimanew || !obj;
914 if (trim) {
915 fz_rect rect;
916 fz_matrix ctm;
917 fz_device *dev;
919 dev = fz_new_bbox_device (state.ctx, &rect);
920 dev->hints |= FZ_IGNORE_SHADE;
921 fz_invert_matrix (&ctm, &page->ctm);
922 pdf_run_page (state.u.pdf, page, dev, &fz_identity, NULL);
923 fz_free_device (dev);
925 rect.x0 += state.trimfuzz.x0;
926 rect.x1 += state.trimfuzz.x1;
927 rect.y0 += state.trimfuzz.y0;
928 rect.y1 += state.trimfuzz.y1;
929 fz_transform_rect (&rect, &ctm);
930 fz_intersect_rect (&rect, &page->mediabox);
932 if (fz_is_empty_rect (&rect)) {
933 mediabox = page->mediabox;
935 else {
936 mediabox = rect;
939 obj = pdf_new_array (state.ctx, 4);
940 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x0));
941 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y0));
942 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x1));
943 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y1));
944 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
946 else {
947 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
948 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
949 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
950 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
953 rotate = page->rotate;
954 pdf_free_page (state.u.pdf, page);
956 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
957 if (show) {
958 printd ("progress %f Trimming %d",
959 (double) (pageno + 1) / state.pagecount,
960 pageno + 1);
963 fz_catch (state.ctx) {
964 fprintf (stderr, "failed to load page %d\n", pageno+1);
967 else {
968 fz_rect cropbox;
970 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "MediaBox"),
971 &mediabox);
972 if (fz_is_empty_rect (&mediabox)) {
973 fprintf (stderr, "cannot find page size for page %d\n",
974 pageno+1);
975 mediabox.x0 = 0;
976 mediabox.y0 = 0;
977 mediabox.x1 = 612;
978 mediabox.y1 = 792;
981 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "CropBox"),
982 &cropbox);
983 if (!fz_is_empty_rect (&cropbox)) {
984 fz_intersect_rect (&mediabox, &cropbox);
986 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
988 break;
991 case DXPS:
993 xps_page *page;
995 fz_try (state.ctx) {
996 page = xps_load_page (state.u.xps, pageno);
997 xps_bound_page (state.u.xps, page, &mediabox);
998 rotate = 0;
999 if (state.trimmargins) {
1000 fz_rect rect;
1001 fz_device *dev;
1003 dev = fz_new_bbox_device (state.ctx, &rect);
1004 dev->hints |= FZ_IGNORE_SHADE;
1005 xps_run_page (state.u.xps, page, dev,
1006 &fz_identity, NULL);
1007 fz_free_device (dev);
1009 rect.x0 += state.trimfuzz.x0;
1010 rect.x1 += state.trimfuzz.x1;
1011 rect.y0 += state.trimfuzz.y0;
1012 rect.y1 += state.trimfuzz.y1;
1013 fz_intersect_rect (&rect, &mediabox);
1015 if (!fz_is_empty_rect (&rect)) {
1016 mediabox = rect;
1019 xps_free_page (state.u.xps, page);
1020 printd ("progress %f loading %d",
1021 (double) (pageno + 1) / state.pagecount,
1022 pageno + 1);
1024 fz_catch (state.ctx) {
1027 break;
1029 case DCBZ:
1031 rotate = 0;
1032 if (state.trimmargins && trimw) {
1033 cbz_page *page;
1035 fz_try (state.ctx) {
1036 page = cbz_load_page (state.u.cbz, pageno);
1037 cbz_bound_page (state.u.cbz, page, &mediabox);
1038 cbz_free_page (state.u.cbz, page);
1039 printd ("progress %f Trimming %d",
1040 (double) (pageno + 1) / state.pagecount,
1041 pageno + 1);
1043 fz_catch (state.ctx) {
1044 fprintf (stderr, "failed to load page %d\n", pageno+1);
1045 mediabox.x0 = 0;
1046 mediabox.y0 = 0;
1047 mediabox.x1 = 900;
1048 mediabox.y1 = 900;
1050 if (trimf) {
1051 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1052 if (n - 1) {
1053 err (1, "fwrite trim mediabox");
1057 else {
1058 if (trimf) {
1059 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1060 if (n - 1) {
1061 err (1, "fread trim mediabox");
1064 else {
1065 mediabox.x0 = mediabox.y0 = 0;
1066 mediabox.x1 = 900;
1067 mediabox.y1 = 900;
1071 break;
1073 default:
1074 ARSERT (0 && state.type);
1077 if (state.pagedimcount == 0
1078 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1079 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1080 size_t size;
1082 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1083 state.pagedims = realloc (state.pagedims, size);
1084 if (!state.pagedims) {
1085 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1086 size, state.pagedimcount + 1);
1089 p = &state.pagedims[state.pagedimcount++];
1090 p->rotate = rotate;
1091 p->mediabox = mediabox;
1092 p->pageno = pageno;
1095 end = now ();
1096 if (state.trimmargins) {
1097 printd ("progress 1 Trimmed %d pages in %f seconds",
1098 state.pagecount, end - start);
1100 else {
1101 printd ("vmsg Processed %d pages in %f seconds",
1102 state.pagecount, end - start);
1104 state.trimanew = 0;
1105 if (trimf) {
1106 if (fclose (trimf)) {
1107 err (1, "fclose");
1112 static void layout (double zoom1)
1114 int pindex;
1115 fz_rect box;
1116 fz_matrix ctm;
1117 double zoom, w, maxw = 0.0;
1118 struct pagedim *p = state.pagedims;
1120 if (state.fitmodel == FitProportional) {
1121 int i;
1122 struct pagedim *p;
1124 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
1125 fz_rect rect;
1126 fz_matrix rm;
1127 double x0, x1;
1129 fz_rotate (&rm, p->rotate + state.rotate);
1130 rect = p->mediabox;
1131 fz_transform_rect (&rect, &rm);
1133 x0 = MIN (rect.x0, rect.x1);
1134 x1 = MAX (rect.x0, rect.x1);
1136 w = x1 - x0;
1137 maxw = MAX (w, maxw);
1141 p = state.pagedims;
1142 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1143 fz_rect rect;
1144 fz_matrix tm, sm, rm;
1146 fz_rotate (&ctm, state.rotate);
1147 fz_rotate (&rm, p->rotate + state.rotate);
1148 box = p->mediabox;
1149 fz_transform_rect (&box, &rm);
1150 w = box.x1 - box.x0;
1151 zoom = state.w / w;
1152 switch (state.fitmodel) {
1153 case FitProportional:
1154 zoom *= w / maxw;
1155 break;
1156 case FitPage:
1158 double z1, h;
1159 h = box.y1 - box.y0;
1160 z1 = state.h / h;
1161 if (z1 < zoom) {
1162 zoom = z1;
1164 zoom *= zoom1;
1166 break;
1167 case FitWidth:
1168 break;
1169 default:
1170 ARSERT (0 && state.fitmodel);
1173 fz_scale (&p->zoomctm, zoom, zoom);
1174 fz_concat (&ctm, &p->zoomctm, &ctm);
1176 fz_rotate (&rm, p->rotate);
1177 p->pagebox = p->mediabox;
1178 fz_transform_rect (&p->pagebox, &rm);
1179 p->pagebox.x1 -= p->pagebox.x0;
1180 p->pagebox.y1 -= p->pagebox.y0;
1181 p->pagebox.x0 = 0;
1182 p->pagebox.y0 = 0;
1183 rect = p->pagebox;
1184 fz_transform_rect (&rect, &ctm);
1185 fz_round_rect (&p->bounds, &rect);
1187 p->left = (state.fitmodel == FitProportional)
1188 ? ((maxw - w) * zoom) / 2.0
1189 : 0;
1190 p->ctm = ctm;
1192 fz_translate (&tm, 0, -p->mediabox.y1);
1193 fz_scale (&sm, zoom, -zoom);
1194 fz_concat (&ctm, &tm, &sm);
1195 fz_concat (&p->lctm, &ctm, &rm);
1197 p->tctmready = 0;
1200 while (p-- != state.pagedims) {
1201 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1202 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1203 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1204 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1205 int w = x1 - x0;
1206 int h = y1 - y0;
1208 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1212 static
1213 struct anchor { int n; int x; int y; int w; int h; }
1214 desttoanchor (fz_link_dest *dest)
1216 int i;
1217 struct anchor a;
1218 struct pagedim *pdim = state.pagedims;
1220 a.n = -1;
1221 a.x = 0;
1222 a.y = 0;
1223 for (i = 0; i < state.pagedimcount; ++i) {
1224 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1225 break;
1226 pdim = &state.pagedims[i];
1228 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1229 fz_point p;
1230 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1231 p.x = dest->ld.gotor.lt.x;
1232 p.y = dest->ld.gotor.lt.y;
1233 fz_transform_point (&p, &pdim->lctm);
1234 a.y = p.y;
1235 a.x = p.x;
1237 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1238 double x0, x1, y0, y1;
1240 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1241 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1242 a.w = x1 - x0;
1243 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1244 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1245 a.h = y1 - y0;
1246 a.n = dest->ld.gotor.page;
1248 return a;
1251 static void recurse_outline (fz_outline *outline, int level)
1253 while (outline) {
1254 struct anchor a = desttoanchor (&outline->dest);
1256 if (a.n >= 0) {
1257 printd ("o %d %d %d %d %s",
1258 level, a.n, a.y, a.h, outline->title);
1260 if (outline->down) {
1261 recurse_outline (outline->down, level + 1);
1263 outline = outline->next;
1267 static void process_outline (void)
1269 fz_outline *outline;
1271 if (!state.needoutline) return;
1273 state.needoutline = 0;
1274 switch (state.type) {
1275 case DPDF:
1276 outline = pdf_load_outline (state.u.pdf);
1277 break;
1278 case DXPS:
1279 outline = xps_load_outline (state.u.xps);
1280 break;
1281 default:
1282 outline = NULL;
1283 break;
1285 if (outline) {
1286 recurse_outline (outline, 0);
1287 fz_free_outline (state.ctx, outline);
1291 static char *strofspan (fz_text_span *span)
1293 char *p;
1294 char utf8[10];
1295 fz_text_char *ch;
1296 size_t size = 0, cap = 80;
1298 p = malloc (cap + 1);
1299 if (!p) return NULL;
1301 for (ch = span->text; ch < span->text + span->len; ++ch) {
1302 int n = fz_runetochar (utf8, ch->c);
1303 if (size + n > cap) {
1304 cap *= 2;
1305 p = realloc (p, cap + 1);
1306 if (!p) return NULL;
1309 memcpy (p + size, utf8, n);
1310 size += n;
1312 p[size] = 0;
1313 return p;
1316 static int matchspan (regex_t *re, fz_text_span *span, fz_matrix ctm,
1317 int stop, int pageno, double start)
1319 int ret;
1320 char *p;
1321 regmatch_t rm;
1322 int a, b, c;
1323 fz_rect *sb, *eb;
1324 fz_point p1, p2, p3, p4;
1326 p = strofspan (span);
1327 if (!p) return -1;
1329 ret = regexec (re, p, 1, &rm, 0);
1330 if (ret) {
1331 free (p);
1332 if (ret != REG_NOMATCH) {
1333 size_t size;
1334 char errbuf[80];
1335 size = regerror (ret, re, errbuf, sizeof (errbuf));
1336 printd ("msg regexec error `%.*s'",
1337 (int) size, errbuf);
1338 return -1;
1340 return 0;
1342 else {
1343 int l = span->len;
1344 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1345 c += fz_runelen (span->text[a].c);
1347 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1348 c += fz_runelen (span->text[b].c);
1351 if (fz_runelen (span->text[b].c) > 1) {
1352 b = MAX (0, b-1);
1354 sb = &span->text[MIN (a, l-1)].bbox;
1355 eb = &span->text[MIN (b, l-1)].bbox;
1357 p1.x = sb->x0;
1358 p1.y = sb->y0;
1359 p2.x = eb->x1;
1360 p2.y = sb->y0;
1361 p3.x = eb->x1;
1362 p3.y = eb->y1;
1363 p4.x = sb->x0;
1364 p4.y = eb->y1;
1366 if (!stop) {
1367 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1368 pageno, 1,
1369 p1.x, p1.y,
1370 p2.x, p2.y,
1371 p3.x, p3.y,
1372 p4.x, p4.y);
1374 printd ("progress 1 found at %d `%.*s' in %f sec",
1375 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1376 now () - start);
1378 else {
1379 printd ("match %d %d %f %f %f %f %f %f %f %f",
1380 pageno, 2,
1381 p1.x, p1.y,
1382 p2.x, p2.y,
1383 p3.x, p3.y,
1384 p4.x, p4.y);
1386 free (p);
1387 return 1;
1391 static int compareblocks (const void *l, const void *r)
1393 fz_text_block const *ls = l;
1394 fz_text_block const* rs = r;
1395 return ls->bbox.y0 - rs->bbox.y0;
1398 /* wishful thinking function */
1399 static void search (regex_t *re, int pageno, int y, int forward)
1401 int i, j;
1402 fz_matrix ctm;
1403 fz_device *tdev;
1404 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1405 fz_text_page *text;
1406 fz_text_sheet *sheet;
1407 struct pagedim *pdim, *pdimprev;
1408 int stop = 0, niters = 0;
1409 double start, end;
1411 if (!(state.type == DPDF || state.type == DXPS))
1412 return;
1414 start = now ();
1415 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1416 if (niters++ == 5) {
1417 niters = 0;
1418 if (hasdata ()) {
1419 printd ("progress 1 attention requested aborting search at %d",
1420 pageno);
1421 stop = 1;
1423 else {
1424 printd ("progress %f searching in page %d",
1425 (double) (pageno + 1) / state.pagecount,
1426 pageno);
1429 pdimprev = NULL;
1430 for (i = 0; i < state.pagedimcount; ++i) {
1431 pdim = &state.pagedims[i];
1432 if (pdim->pageno == pageno) {
1433 goto found;
1435 if (pdim->pageno > pageno) {
1436 pdim = pdimprev;
1437 goto found;
1439 pdimprev = pdim;
1441 pdim = pdimprev;
1442 found:
1444 sheet = fz_new_text_sheet (state.ctx);
1445 text = fz_new_text_page (state.ctx, &fz_infinite_rect);
1446 tdev = fz_new_text_device (state.ctx, sheet, text);
1448 switch (state.type) {
1449 case DPDF:
1450 u.ptr = NULL;
1451 fz_try (state.ctx) {
1452 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1453 trimctm (u.pdfpage, pdim - state.pagedims);
1454 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1455 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1457 fz_catch (state.ctx) {
1458 fz_free_device (tdev);
1459 u.ptr = NULL;
1460 goto nextiter;
1462 break;
1464 case DXPS:
1465 u.xpspage = xps_load_page (state.u.xps, pageno);
1466 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1467 break;
1469 default:
1470 ARSERT (0 && state.type);
1473 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1474 fz_free_device (tdev);
1476 for (j = 0; j < text->len; ++j) {
1477 int k;
1478 fz_text_block *block;
1480 block = &text->blocks[forward ? j : text->len - 1 - j];
1482 for (k = 0; k < block->len; ++k) {
1483 fz_text_line *line;
1484 fz_text_span *span;
1486 if (forward) {
1487 line = &block->lines[k];
1488 if (line->bbox.y0 < y + 1) continue;
1490 else {
1491 line = &block->lines[block->len - 1 - k];
1492 if (line->bbox.y0 > y - 1) continue;
1495 for (span = line->spans;
1496 span < line->spans + line->len;
1497 ++span) {
1499 switch (matchspan (re, span, ctm, stop, pageno, start)) {
1500 case 0: break;
1501 case 1: stop = 1; break;
1502 case -1: stop = 1; goto endloop;
1507 nextiter:
1508 if (forward) {
1509 pageno += 1;
1510 y = 0;
1512 else {
1513 pageno -= 1;
1514 y = INT_MAX;
1516 endloop:
1517 fz_free_text_page (state.ctx, text);
1518 fz_free_text_sheet (state.ctx, sheet);
1519 if (u.ptr) {
1520 state.freepage (u.ptr);
1523 end = now ();
1524 if (!stop) {
1525 printd ("progress 1 no matches %f sec", end - start);
1527 printd ("clearrects");
1530 static void set_tex_params (int colorspace)
1532 union {
1533 unsigned char b;
1534 unsigned int s;
1535 } endianness = {1};
1537 switch (colorspace) {
1538 case 0:
1539 state.texiform = GL_RGBA8;
1540 state.texform = GL_RGBA;
1541 state.texty = GL_UNSIGNED_BYTE;
1542 state.colorspace = fz_device_rgb;
1543 break;
1544 case 1:
1545 state.texiform = GL_RGBA8;
1546 state.texform = GL_BGRA;
1547 state.texty = endianness.s > 1
1548 ? GL_UNSIGNED_INT_8_8_8_8
1549 : GL_UNSIGNED_INT_8_8_8_8_REV;
1550 state.colorspace = fz_device_bgr;
1551 break;
1552 case 2:
1553 state.texiform = GL_LUMINANCE_ALPHA;
1554 state.texform = GL_LUMINANCE_ALPHA;
1555 state.texty = GL_UNSIGNED_BYTE;
1556 state.colorspace = fz_device_gray;
1557 break;
1558 default:
1559 errx (1, "invalid colorspce %d", colorspace);
1563 static void realloctexts (int texcount)
1565 size_t size;
1567 if (texcount == state.texcount) return;
1569 if (texcount < state.texcount) {
1570 glDeleteTextures (state.texcount - texcount,
1571 state.texids + texcount);
1574 size = texcount * sizeof (*state.texids);
1575 state.texids = realloc (state.texids, size);
1576 if (!state.texids) {
1577 err (1, "realloc texids %" FMT_s, size);
1580 size = texcount * sizeof (*state.texowners);
1581 state.texowners = realloc (state.texowners, size);
1582 if (!state.texowners) {
1583 err (1, "realloc texowners %" FMT_s, size);
1585 if (texcount > state.texcount) {
1586 int i;
1588 glGenTextures (texcount - state.texcount,
1589 state.texids + state.texcount);
1590 for (i = state.texcount; i < texcount; ++i) {
1591 state.texowners[i].w = -1;
1592 state.texowners[i].slice = NULL;
1595 state.texcount = texcount;
1596 state.texindex = 0;
1599 static char *mbtoutf8 (char *s)
1601 char *p, *r;
1602 wchar_t *tmp;
1603 size_t i, ret, len;
1605 len = mbstowcs (NULL, s, strlen (s));
1606 if (len == 0) {
1607 return s;
1609 else {
1610 if (len == (size_t) -1) {
1611 return s;
1615 tmp = malloc (len * sizeof (wchar_t));
1616 if (!tmp) {
1617 return s;
1620 ret = mbstowcs (tmp, s, len);
1621 if (ret == (size_t) -1) {
1622 free (tmp);
1623 return s;
1626 len = 0;
1627 for (i = 0; i < ret; ++i) {
1628 len += fz_runelen (tmp[i]);
1631 p = r = malloc (len + 1);
1632 if (!r) {
1633 free (tmp);
1634 return s;
1637 for (i = 0; i < ret; ++i) {
1638 p += fz_runetochar (p, tmp[i]);
1640 *p = 0;
1641 free (tmp);
1642 return r;
1645 CAMLprim value ml_mbtoutf8 (value s_v)
1647 CAMLparam1 (s_v);
1648 CAMLlocal1 (ret_v);
1649 char *s, *r;
1651 s = String_val (s_v);
1652 r = mbtoutf8 (s);
1653 if (r == s) {
1654 ret_v = s_v;
1656 else {
1657 ret_v = caml_copy_string (r);
1658 free (r);
1660 CAMLreturn (ret_v);
1663 static void * mainloop (void *unused)
1665 char *p = NULL;
1666 int len, ret, oldlen = 0;
1668 for (;;) {
1669 len = readlen ();
1670 if (len == 0) {
1671 errx (1, "readlen returned 0");
1674 if (oldlen < len + 1) {
1675 p = realloc (p, len + 1);
1676 if (!p) {
1677 err (1, "realloc %d failed", len + 1);
1679 oldlen = len + 1;
1681 readdata (p, len);
1682 p[len] = 0;
1684 if (!strncmp ("open", p, 4)) {
1685 size_t filenamelen;
1686 int wthack, off;
1687 char *password;
1688 char *filename;
1689 char *utf8filename;
1691 ret = sscanf (p + 5, " %d %n", &wthack, &off);
1692 if (ret != 1) {
1693 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1696 filename = p + 5 + off;
1697 filenamelen = strlen (filename);
1698 password = filename + filenamelen + 1;
1700 lock ("open");
1701 openxref (filename, password);
1702 pdfinfo ();
1703 initpdims ();
1704 unlock ("open");
1706 if (!wthack) {
1707 utf8filename = mbtoutf8 (filename);
1708 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1709 if (utf8filename != filename) {
1710 free (utf8filename);
1713 state.needoutline = 1;
1715 else if (!strncmp ("cs", p, 2)) {
1716 int i, colorspace;
1718 ret = sscanf (p + 2, " %d", &colorspace);
1719 if (ret != 1) {
1720 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1722 lock ("cs");
1723 set_tex_params (colorspace);
1724 for (i = 0; i < state.texcount; ++i) {
1725 state.texowners[i].w = -1;
1726 state.texowners[i].slice = NULL;
1728 unlock ("cs");
1730 else if (!strncmp ("freepage", p, 8)) {
1731 void *ptr;
1733 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1734 if (ret != 1) {
1735 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1737 freepage (ptr);
1739 else if (!strncmp ("freetile", p, 8)) {
1740 void *ptr;
1742 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1743 if (ret != 1) {
1744 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1746 freetile (ptr);
1748 else if (!strncmp ("search", p, 6)) {
1749 int icase, pageno, y, ret, len2, forward;
1750 char *pattern;
1751 regex_t re;
1753 ret = sscanf (p + 6, " %d %d %d %d,%n",
1754 &icase, &pageno, &y, &forward, &len2);
1755 if (ret != 4) {
1756 errx (1, "malformed search `%s' ret=%d", p, ret);
1759 pattern = p + 6 + len2;
1760 ret = regcomp (&re, pattern,
1761 REG_EXTENDED | (icase ? REG_ICASE : 0));
1762 if (ret) {
1763 char errbuf[80];
1764 size_t size;
1766 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1767 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1769 else {
1770 search (&re, pageno, y, forward);
1771 regfree (&re);
1774 else if (!strncmp ("geometry", p, 8)) {
1775 int w, h;
1776 float zoom;
1778 printd ("clear");
1779 ret = sscanf (p + 8, " %d %d %f", &w, &h, &zoom);
1780 if (ret != 3) {
1781 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1784 lock ("geometry");
1785 state.h = h;
1786 if (w != state.w) {
1787 int i;
1788 state.w = w;
1789 for (i = 0; i < state.texcount; ++i) {
1790 state.texowners[i].slice = NULL;
1793 layout (zoom);
1794 process_outline ();
1796 state.gen++;
1797 unlock ("geometry");
1798 printd ("continue %d", state.pagecount);
1800 else if (!strncmp ("reqlayout", p, 9)) {
1801 float zoom;
1802 char *nameddest;
1803 int rotate, fitmodel, off;
1805 printd ("clear");
1806 ret = sscanf (p + 9, " %d %d %f %n",
1807 &rotate, &fitmodel, &zoom, &off);
1808 if (ret != 3) {
1809 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1811 lock ("reqlayout");
1812 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1813 state.gen += 1;
1815 state.rotate = rotate;
1816 state.fitmodel = fitmodel;
1817 layout (zoom);
1818 process_outline ();
1820 nameddest = p + 9 + off;
1821 if (state.type == DPDF && nameddest && *nameddest) {
1822 struct anchor a;
1823 fz_link_dest dest;
1824 pdf_obj *needle, *obj;
1826 needle = pdf_new_string (state.ctx, nameddest,
1827 strlen (nameddest));
1828 obj = pdf_lookup_dest (state.u.pdf, needle);
1829 if (obj) {
1830 dest = pdf_parse_link_dest (state.u.pdf, obj);
1832 a = desttoanchor (&dest);
1833 if (a.n >= 0) {
1834 printd ("a %d %d %d", a.n, a.x, a.y);
1836 else {
1837 printd ("emsg failed to parse destination `%s'\n",
1838 nameddest);
1841 else {
1842 printd ("emsg destination `%s' not found\n",
1843 nameddest);
1845 pdf_drop_obj (needle);
1848 state.gen++;
1849 unlock ("reqlayout");
1850 printd ("continue %d", state.pagecount);
1852 else if (!strncmp ("page", p, 4)) {
1853 double a, b;
1854 struct page *page;
1855 int pageno, pindex, ret;
1857 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1858 if (ret != 2) {
1859 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1862 lock ("page");
1863 a = now ();
1864 page = loadpage (pageno, pindex);
1865 b = now ();
1866 unlock ("page");
1868 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1870 else if (!strncmp ("tile", p, 4)) {
1871 int x, y, w, h, ret;
1872 struct page *page;
1873 struct tile *tile;
1874 double a, b;
1875 void *data;
1877 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
1878 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
1879 if (ret != 6) {
1880 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1883 lock ("tile");
1884 a = now ();
1885 tile = rendertile (page, x, y, w, h, data);
1886 b = now ();
1887 unlock ("tile");
1889 printd ("tile %d %d %" FMT_ptr " %u %f",
1890 x, y,
1891 FMT_ptr_cast2 (tile),
1892 tile->w * tile->h * tile->pixmap->n,
1893 b - a);
1895 else if (!strncmp ("settrim", p, 7)) {
1896 float zoom;
1897 fz_irect fuzz;
1898 int trimmargins;
1900 ret = sscanf (p + 7, " %d %d %d %d %d %f",
1901 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1,
1902 &zoom);
1903 if (ret != 5) {
1904 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1906 printd ("clear");
1907 lock ("settrim");
1908 state.trimmargins = trimmargins;
1909 state.needoutline = 1;
1910 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1911 state.trimanew = 1;
1912 state.trimfuzz = fuzz;
1914 state.pagedimcount = 0;
1915 free (state.pagedims);
1916 state.pagedims = NULL;
1917 initpdims ();
1918 layout (zoom);
1919 process_outline ();
1920 unlock ("settrim");
1921 printd ("continue %d", state.pagecount);
1923 else if (!strncmp ("sliceh", p, 6)) {
1924 int h;
1926 ret = sscanf (p + 6, " %d", &h);
1927 if (ret != 1) {
1928 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1930 if (h != state.sliceheight) {
1931 int i;
1933 state.sliceheight = h;
1934 for (i = 0; i < state.texcount; ++i) {
1935 state.texowners[i].w = -1;
1936 state.texowners[i].h = -1;
1937 state.texowners[i].slice = NULL;
1941 else if (!strncmp ("interrupt", p, 9)) {
1942 printd ("vmsg interrupted");
1944 else {
1945 errx (1, "unknown command %.*s", len, p);
1948 return 0;
1951 CAMLprim value ml_realloctexts (value texcount_v)
1953 CAMLparam1 (texcount_v);
1954 int ok;
1956 if (trylock ("ml_realloctexts")) {
1957 ok = 0;
1958 goto done;
1960 realloctexts (Int_val (texcount_v));
1961 ok = 1;
1962 unlock ("ml_realloctexts");
1964 done:
1965 CAMLreturn (Val_bool (ok));
1968 static void showsel (struct page *page, int ox, int oy)
1970 int seen = 0;
1971 fz_irect bbox;
1972 fz_rect rect;
1973 fz_text_line *line;
1974 fz_text_span *span;
1975 fz_text_block *block;
1976 struct mark first, last;
1978 first = page->fmark;
1979 last = page->lmark;
1981 if (!first.span || !last.span) return;
1983 glEnable (GL_BLEND);
1984 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1985 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1987 ox += state.pagedims[page->pdimno].bounds.x0;
1988 oy += state.pagedims[page->pdimno].bounds.y0;
1989 for (block = page->text->blocks;
1990 block < page->text->blocks + page->text->len;
1991 ++block) {
1992 for (line = block->lines;
1993 line < block->lines + block->len;
1994 ++line) {
1995 rect = fz_empty_rect;
1996 for (span = line->spans;
1997 span < line->spans + line->len;
1998 ++span) {
1999 int i, j, k;
2001 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2003 j = 0;
2004 k = span->len - 1;
2006 if (span == page->fmark.span && span == page->lmark.span) {
2007 seen = 1;
2008 j = MIN (first.i, last.i);
2009 k = MAX (first.i, last.i);
2011 else if (span == first.span) {
2012 seen = 1;
2013 j = first.i;
2015 else if (span == last.span) {
2016 seen = 1;
2017 k = last.i;
2020 if (seen) {
2021 for (i = j; i <= k; ++i) {
2022 fz_union_rect (&rect, &span->text[i].bbox);
2024 fz_round_rect (&bbox, &rect);
2025 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2026 bbox.x0,
2027 bbox.y0,
2028 bbox.x1,
2029 bbox.y1,
2030 oy, ox);
2032 glRecti (bbox.x0 + ox, bbox.y0 + oy,
2033 bbox.x1 + ox, bbox.y1 + oy);
2034 if (span == last.span) {
2035 goto done;
2041 done:
2042 glDisable (GL_BLEND);
2045 #include "glfont.c"
2047 static void highlightlinks (struct page *page, int xoff, int yoff)
2049 fz_matrix ctm, tm, pm;
2050 fz_link *link, *links;
2052 switch (page->type) {
2053 case DPDF:
2054 links = page->u.pdfpage->links;
2055 break;
2057 case DXPS:
2058 links = page->u.xpspage->links;
2059 break;
2061 default:
2062 return;
2065 glEnable (GL_TEXTURE_1D);
2066 glEnable (GL_BLEND);
2067 glBindTexture (GL_TEXTURE_1D, state.stid);
2069 xoff -= state.pagedims[page->pdimno].bounds.x0;
2070 yoff -= state.pagedims[page->pdimno].bounds.y0;
2071 fz_translate (&tm, xoff, yoff);
2072 pm = pagectm (page);
2073 fz_concat (&ctm, &pm, &tm);
2075 glBegin (GL_LINES);
2076 for (link = links; link; link = link->next) {
2077 fz_point p1, p2, p3, p4;
2079 p1.x = link->rect.x0;
2080 p1.y = link->rect.y0;
2082 p2.x = link->rect.x1;
2083 p2.y = link->rect.y0;
2085 p3.x = link->rect.x1;
2086 p3.y = link->rect.y1;
2088 p4.x = link->rect.x0;
2089 p4.y = link->rect.y1;
2091 fz_transform_point (&p1, &ctm);
2092 fz_transform_point (&p2, &ctm);
2093 fz_transform_point (&p3, &ctm);
2094 fz_transform_point (&p4, &ctm);
2096 switch (link->dest.kind) {
2097 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2098 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2099 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2100 default: glColor3ub (0, 0, 0); break;
2104 float w, h, s, t;
2106 w = p2.x - p1.x;
2107 h = p2.y - p1.y;
2108 t = sqrtf (w*w + h*h) * .25f;
2110 w = p3.x - p2.x;
2111 h = p3.y - p2.y;
2112 s = sqrtf (w*w + h*h) * .25f;
2114 glTexCoord1i (0);
2115 glVertex2f (p1.x, p1.y);
2116 glTexCoord1f (t);
2117 glVertex2f (p2.x, p2.y);
2119 glTexCoord1i (0);
2120 glVertex2f (p2.x, p2.y);
2121 glTexCoord1f (s);
2122 glVertex2f (p3.x, p3.y);
2124 glTexCoord1i (0);
2125 glVertex2f (p3.x, p3.y);
2126 glTexCoord1f (t);
2127 glVertex2f (p4.x, p4.y);
2129 glTexCoord1i (0);
2130 glVertex2f (p4.x, p4.y);
2131 glTexCoord1f (s);
2132 glVertex2f (p1.x, p1.y);
2135 glEnd ();
2137 glDisable (GL_BLEND);
2138 glDisable (GL_TEXTURE_1D);
2141 static int compareslinks (const void *l, const void *r)
2143 struct slink const *ls = l;
2144 struct slink const *rs = r;
2145 if (ls->bbox.y0 == rs->bbox.y0) {
2146 return rs->bbox.x0 - rs->bbox.x0;
2148 return ls->bbox.y0 - rs->bbox.y0;
2151 static void droptext (struct page *page)
2153 if (page->text) {
2154 fz_free_text_page (state.ctx, page->text);
2155 page->fmark.i = -1;
2156 page->lmark.i = -1;
2157 page->fmark.span = NULL;
2158 page->lmark.span = NULL;
2159 page->text = NULL;
2161 if (page->sheet) {
2162 fz_free_text_sheet (state.ctx, page->sheet);
2166 static void dropslinks (struct page *page)
2168 if (page->slinks) {
2169 free (page->slinks);
2170 page->slinks = NULL;
2171 page->slinkcount = 0;
2175 static void ensureslinks (struct page *page)
2177 fz_matrix ctm;
2178 int i, count = 0;
2179 size_t slinksize = sizeof (*page->slinks);
2180 fz_link *link, *links;
2182 if (state.gen != page->sgen) {
2183 dropslinks (page);
2184 page->sgen = state.gen;
2186 if (page->slinks) return;
2188 switch (page->type) {
2189 case DPDF:
2190 links = page->u.pdfpage->links;
2191 trimctm (page->u.pdfpage, page->pdimno);
2192 fz_concat (&ctm,
2193 &state.pagedims[page->pdimno].tctm,
2194 &state.pagedims[page->pdimno].ctm);
2195 break;
2197 case DXPS:
2198 links = page->u.xpspage->links;
2199 ctm = state.pagedims[page->pdimno].ctm;
2200 break;
2202 default:
2203 return;
2206 for (link = links; link; link = link->next) {
2207 count++;
2209 if (count > 0) {
2210 page->slinkcount = count;
2211 page->slinks = calloc (count, slinksize);
2212 if (!page->slinks) {
2213 err (1, "realloc slinks %d", count);
2216 for (i = 0, link = links; link; ++i, link = link->next) {
2217 fz_rect rect;
2219 rect = link->rect;
2220 fz_transform_rect (&rect, &ctm);
2221 page->slinks[i].link = link;
2222 fz_round_rect (&page->slinks[i].bbox, &rect);
2224 qsort (page->slinks, count, slinksize, compareslinks);
2228 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2229 static void fmt_linkn (char *s, unsigned int u)
2231 unsigned int len; unsigned int q;
2232 int zma = 'z' - 'a' + 1;
2233 len = 1; q = u;
2234 while (q > zma - 1) { ++len; q /= zma; }
2235 if (s) {
2236 s += len;
2237 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2238 /* handles u == 0 */
2240 s[len] = 0;
2243 static void highlightslinks (struct page *page, int xoff, int yoff,
2244 int noff, char *targ, int tlen, int hfsize)
2246 int i;
2247 char buf[40];
2248 struct slink *slink;
2249 double x0, y0, x1, y1, w;
2251 ensureslinks (page);
2252 glColor3ub (0xc3, 0xb0, 0x91);
2253 for (i = 0; i < page->slinkcount; ++i) {
2254 fmt_linkn (buf, i + noff);
2255 if (!tlen || !strncmp (targ, buf, tlen)) {
2256 slink = &page->slinks[i];
2258 x0 = slink->bbox.x0 + xoff - 5;
2259 y1 = slink->bbox.y0 + yoff - 5;
2260 y0 = y1 + 10 + hfsize;
2261 w = measure_string (state.face, hfsize, buf);
2262 x1 = x0 + w + 10;
2263 glRectd (x0, y0, x1, y1);
2267 glEnable (GL_BLEND);
2268 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2269 glEnable (GL_TEXTURE_2D);
2270 glColor3ub (0, 0, 0);
2271 for (i = 0; i < page->slinkcount; ++i) {
2272 fmt_linkn (buf, i + noff);
2273 if (!tlen || !strncmp (targ, buf, tlen)) {
2274 slink = &page->slinks[i];
2276 x0 = slink->bbox.x0 + xoff;
2277 y0 = slink->bbox.y0 + yoff + hfsize;
2278 draw_string (state.face, hfsize, x0, y0, buf);
2281 glDisable (GL_TEXTURE_2D);
2282 glDisable (GL_BLEND);
2286 static void uploadslice (struct tile *tile, struct slice *slice)
2288 int offset;
2289 struct slice *slice1;
2290 unsigned char *texdata;
2292 offset = 0;
2293 for (slice1 = tile->slices; slice != slice1; slice1++) {
2294 offset += slice1->h * tile->w * tile->pixmap->n;
2296 if (slice->texindex != -1 && slice->texindex < state.texcount
2297 && state.texowners[slice->texindex].slice == slice) {
2298 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2300 else {
2301 int subimage = 0;
2302 int texindex = state.texindex++ % state.texcount;
2304 if (state.texowners[texindex].w == tile->w) {
2305 if (state.texowners[texindex].h >= slice->h) {
2306 subimage = 1;
2308 else {
2309 state.texowners[texindex].h = slice->h;
2312 else {
2313 state.texowners[texindex].h = slice->h;
2316 state.texowners[texindex].w = tile->w;
2317 state.texowners[texindex].slice = slice;
2318 slice->texindex = texindex;
2320 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2321 if (tile->pbo) {
2322 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2323 texdata = 0;
2325 else {
2326 texdata = tile->pixmap->samples;
2328 if (subimage) {
2329 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2333 tile->w,
2334 slice->h,
2335 state.texform,
2336 state.texty,
2337 texdata+offset
2340 else {
2341 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2343 state.texiform,
2344 tile->w,
2345 slice->h,
2347 state.texform,
2348 state.texty,
2349 texdata+offset
2352 if (tile->pbo) {
2353 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2358 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2360 CAMLparam2 (args_v, ptr_v);
2361 int dispx = Int_val (Field (args_v, 0));
2362 int dispy = Int_val (Field (args_v, 1));
2363 int dispw = Int_val (Field (args_v, 2));
2364 int disph = Int_val (Field (args_v, 3));
2365 int tilex = Int_val (Field (args_v, 4));
2366 int tiley = Int_val (Field (args_v, 5));
2367 char *s = String_val (ptr_v);
2368 struct tile *tile = parse_pointer ("ml_drawtile", s);
2370 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2372 int slicey, firstslice;
2373 struct slice *slice;
2375 firstslice = tiley / tile->sliceheight;
2376 slice = &tile->slices[firstslice];
2377 slicey = tiley % tile->sliceheight;
2379 while (disph > 0) {
2380 int dh;
2382 dh = slice->h - slicey;
2383 dh = MIN (disph, dh);
2384 uploadslice (tile, slice);
2386 glBegin (GL_QUADS);
2388 glTexCoord2i (tilex, slicey);
2389 glVertex2i (dispx, dispy);
2391 glTexCoord2i (tilex+dispw, slicey);
2392 glVertex2i (dispx+dispw, dispy);
2394 glTexCoord2i (tilex+dispw, slicey+dh);
2395 glVertex2i (dispx+dispw, dispy+dh);
2397 glTexCoord2i (tilex, slicey+dh);
2398 glVertex2i (dispx, dispy+dh);
2400 glEnd ();
2402 dispy += dh;
2403 disph -= dh;
2404 slice++;
2405 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2406 slicey = 0;
2409 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2410 CAMLreturn (Val_unit);
2413 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2414 value xoff_v, value yoff_v,
2415 value li_v)
2417 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2418 int xoff = Int_val (xoff_v);
2419 int yoff = Int_val (yoff_v);
2420 int noff = Int_val (Field (li_v, 0));
2421 char *targ = String_val (Field (li_v, 1));
2422 int tlen = caml_string_length (Field (li_v, 1));
2423 int hfsize = Int_val (Field (li_v, 2));
2424 char *s = String_val (ptr_v);
2425 int hlmask = Int_val (hlinks_v);
2426 struct page *page = parse_pointer ("ml_postprocess", s);
2428 if (!page->u.ptr) {
2429 /* deal with loadpage failed pages */
2430 goto done;
2433 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2434 if (trylock ("ml_postprocess")) {
2435 noff = 0;
2436 goto done;
2438 if (hlmask & 2) {
2439 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2440 noff = page->slinkcount;
2442 showsel (page, xoff, yoff);
2443 unlock ("ml_postprocess");
2445 done:
2446 CAMLreturn (Val_int (noff));
2449 static fz_link *getlink (struct page *page, int x, int y)
2451 fz_point p;
2452 fz_matrix ctm;
2453 const fz_matrix *tctm;
2454 fz_link *link, *links;
2456 switch (page->type) {
2457 case DPDF:
2458 trimctm (page->u.pdfpage, page->pdimno);
2459 tctm = &state.pagedims[page->pdimno].tctm;
2460 links = page->u.pdfpage->links;
2461 break;
2463 case DXPS:
2464 tctm = &fz_identity;
2465 links = page->u.xpspage->links;
2466 break;
2468 default:
2469 return NULL;
2471 p.x = x;
2472 p.y = y;
2474 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2475 fz_invert_matrix (&ctm, &ctm);
2476 fz_transform_point (&p, &ctm);
2478 for (link = links; link; link = link->next) {
2479 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2480 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2481 return link;
2485 return NULL;
2488 static void ensuretext (struct page *page)
2490 if (state.gen != page->tgen) {
2491 droptext (page);
2492 page->tgen = state.gen;
2494 if (!page->text) {
2495 fz_matrix ctm;
2496 fz_device *tdev;
2498 page->text = fz_new_text_page (state.ctx, &fz_infinite_rect);
2499 page->sheet = fz_new_text_sheet (state.ctx);
2500 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2501 ctm = pagectm (page);
2502 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2503 qsort (page->text->blocks, page->text->len,
2504 sizeof (*page->text->blocks), compareblocks);
2505 fz_free_device (tdev);
2509 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2511 CAMLparam2 (start_page_v, dir_v);
2512 CAMLlocal1 (ret_v);
2513 int i, dir = Int_val (dir_v);
2514 int start_page = Int_val (start_page_v);
2515 int end_page = dir > 0 ? state.pagecount : -1;
2517 ret_v = Val_int (0);
2518 if (!(state.type == DPDF || state.type == DXPS)) {
2519 goto done;
2522 lock ("ml_findpage_with_links");
2523 for (i = start_page + dir; i != end_page; i += dir) {
2524 int found;
2526 switch (state.type) {
2527 case DPDF:
2529 pdf_page *page = NULL;
2531 fz_try (state.ctx) {
2532 page = pdf_load_page (state.u.pdf, i);
2533 found = !!page->links;
2535 fz_catch (state.ctx) {
2536 found = 0;
2538 if (page) {
2539 freepdfpage (page);
2542 break;
2543 case DXPS:
2545 xps_page *page = xps_load_page (state.u.xps, i);
2546 found = !!page->links;
2547 freexpspage (page);
2549 break;
2551 default:
2552 ARSERT ("invalid document type");
2555 if (found) {
2556 ret_v = caml_alloc_small (1, 1);
2557 Field (ret_v, 0) = Val_int (i);
2558 goto unlock;
2561 unlock:
2562 unlock ("ml_findpage_with_links");
2564 done:
2565 CAMLreturn (ret_v);
2568 enum { dir_first, dir_last};
2569 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2571 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2573 CAMLparam2 (ptr_v, dir_v);
2574 CAMLlocal2 (ret_v, pos_v);
2575 struct page *page;
2576 int dirtag, i, slinkindex;
2577 struct slink *found = NULL ,*slink;
2578 char *s = String_val (ptr_v);
2580 page = parse_pointer ("ml_findlink", s);
2581 ret_v = Val_int (0);
2582 if (trylock ("ml_findlink")) {
2583 goto done;
2586 ensureslinks (page);
2588 if (Is_block (dir_v)) {
2589 dirtag = Tag_val (dir_v);
2590 switch (dirtag) {
2591 case dir_first_visible:
2593 int x0, y0, dir, first_index, last_index;
2595 pos_v = Field (dir_v, 0);
2596 x0 = Int_val (Field (pos_v, 0));
2597 y0 = Int_val (Field (pos_v, 1));
2598 dir = Int_val (Field (pos_v, 2));
2600 if (dir >= 0) {
2601 dir = 1;
2602 first_index = 0;
2603 last_index = page->slinkcount;
2605 else {
2606 first_index = page->slinkcount - 1;
2607 last_index = -1;
2610 for (i = first_index; i != last_index; i += dir) {
2611 slink = &page->slinks[i];
2612 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2613 found = slink;
2614 break;
2618 break;
2620 case dir_left:
2621 slinkindex = Int_val (Field (dir_v, 0));
2622 found = &page->slinks[slinkindex];
2623 for (i = slinkindex - 1; i >= 0; --i) {
2624 slink = &page->slinks[i];
2625 if (slink->bbox.x0 < found->bbox.x0) {
2626 found = slink;
2627 break;
2630 break;
2632 case dir_right:
2633 slinkindex = Int_val (Field (dir_v, 0));
2634 found = &page->slinks[slinkindex];
2635 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2636 slink = &page->slinks[i];
2637 if (slink->bbox.x0 > found->bbox.x0) {
2638 found = slink;
2639 break;
2642 break;
2644 case dir_down:
2645 slinkindex = Int_val (Field (dir_v, 0));
2646 found = &page->slinks[slinkindex];
2647 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2648 slink = &page->slinks[i];
2649 if (slink->bbox.y0 >= found->bbox.y0) {
2650 found = slink;
2651 break;
2654 break;
2656 case dir_up:
2657 slinkindex = Int_val (Field (dir_v, 0));
2658 found = &page->slinks[slinkindex];
2659 for (i = slinkindex - 1; i >= 0; --i) {
2660 slink = &page->slinks[i];
2661 if (slink->bbox.y0 <= found->bbox.y0) {
2662 found = slink;
2663 break;
2666 break;
2669 else {
2670 dirtag = Int_val (dir_v);
2671 switch (dirtag) {
2672 case dir_first:
2673 found = page->slinks;
2674 break;
2676 case dir_last:
2677 if (page->slinks) {
2678 found = page->slinks + (page->slinkcount - 1);
2680 break;
2683 if (found) {
2684 ret_v = caml_alloc_small (2, 1);
2685 Field (ret_v, 0) = Val_int (found - page->slinks);
2688 unlock ("ml_findlink");
2689 done:
2690 CAMLreturn (ret_v);
2693 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2695 #define LINKTOVAL \
2697 int pageno; \
2699 switch (link->dest.kind) { \
2700 case FZ_LINK_GOTO: \
2702 fz_point p; \
2704 pageno = link->dest.ld.gotor.page; \
2705 p.x = 0; \
2706 p.y = 0; \
2708 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2709 p.y = link->dest.ld.gotor.lt.y; \
2710 fz_transform_point (&p, &pdim->lctm); \
2712 tup_v = caml_alloc_tuple (2); \
2713 ret_v = caml_alloc_small (1, ugoto); \
2714 Field (tup_v, 0) = Val_int (pageno); \
2715 Field (tup_v, 1) = Val_int (p.y); \
2716 Field (ret_v, 0) = tup_v; \
2718 break; \
2720 case FZ_LINK_URI: \
2721 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2722 ret_v = caml_alloc_small (1, uuri); \
2723 Field (ret_v, 0) = str_v; \
2724 break; \
2726 case FZ_LINK_LAUNCH: \
2727 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2728 ret_v = caml_alloc_small (1, ulaunch); \
2729 Field (ret_v, 0) = str_v; \
2730 break; \
2732 case FZ_LINK_NAMED: \
2733 str_v = caml_copy_string (link->dest.ld.named.named); \
2734 ret_v = caml_alloc_small (1, unamed); \
2735 Field (ret_v, 0) = str_v; \
2736 break; \
2738 case FZ_LINK_GOTOR: \
2739 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2740 pageno = link->dest.ld.gotor.page; \
2741 tup_v = caml_alloc_tuple (2); \
2742 ret_v = caml_alloc_small (1, uremote); \
2743 Field (tup_v, 0) = str_v; \
2744 Field (tup_v, 1) = Val_int (pageno); \
2745 Field (ret_v, 0) = tup_v; \
2746 break; \
2748 default: \
2750 char buf[80]; \
2752 snprintf (buf, sizeof (buf), \
2753 "unhandled link kind %d", link->dest.kind); \
2754 str_v = caml_copy_string (buf); \
2755 ret_v = caml_alloc_small (1, uunexpected); \
2756 Field (ret_v, 0) = str_v; \
2758 break; \
2762 CAMLprim value ml_getlink (value ptr_v, value n_v)
2764 CAMLparam2 (ptr_v, n_v);
2765 CAMLlocal3 (ret_v, tup_v, str_v);
2766 fz_link *link;
2767 struct page *page;
2768 struct pagedim *pdim;
2769 char *s = String_val (ptr_v);
2771 ret_v = Val_int (0);
2772 if (trylock ("ml_getlink")) {
2773 goto done;
2776 page = parse_pointer ("ml_getlink", s);
2777 ensureslinks (page);
2778 pdim = &state.pagedims[page->pdimno];
2779 link = page->slinks[Int_val (n_v)].link;
2780 LINKTOVAL;
2782 unlock ("ml_getlink");
2783 done:
2784 CAMLreturn (ret_v);
2787 CAMLprim value ml_getlinkcount (value ptr_v)
2789 CAMLparam1 (ptr_v);
2790 struct page *page;
2791 char *s = String_val (ptr_v);
2793 page = parse_pointer ("ml_getlinkcount", s);
2794 CAMLreturn (Val_int (page->slinkcount));
2797 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2799 CAMLparam2 (ptr_v, n_v);
2800 CAMLlocal1 (ret_v);
2801 struct page *page;
2802 struct slink *slink;
2803 char *s = String_val (ptr_v);
2805 page = parse_pointer ("ml_getlinkrect", s);
2806 ret_v = caml_alloc_tuple (4);
2807 if (trylock ("ml_getlinkrect")) {
2808 Field (ret_v, 0) = Val_int (0);
2809 Field (ret_v, 1) = Val_int (0);
2810 Field (ret_v, 2) = Val_int (0);
2811 Field (ret_v, 3) = Val_int (0);
2812 goto done;
2814 ensureslinks (page);
2816 slink = &page->slinks[Int_val (n_v)];
2817 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2818 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2819 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2820 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2821 unlock ("ml_getlinkrect");
2823 done:
2824 CAMLreturn (ret_v);
2827 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2829 CAMLparam3 (ptr_v, x_v, y_v);
2830 CAMLlocal3 (ret_v, tup_v, str_v);
2831 fz_link *link;
2832 struct page *page;
2833 char *s = String_val (ptr_v);
2834 int x = Int_val (x_v), y = Int_val (y_v);
2835 struct pagedim *pdim;
2837 ret_v = Val_int (0);
2838 if (trylock ("ml_whatsunder")) {
2839 goto done;
2842 page = parse_pointer ("ml_whatsunder", s);
2843 pdim = &state.pagedims[page->pdimno];
2844 x += pdim->bounds.x0;
2845 y += pdim->bounds.y0;
2846 link = getlink (page, x, y);
2847 if (link) {
2848 LINKTOVAL;
2850 else {
2851 fz_rect *b;
2852 fz_text_block *block;
2854 ensuretext (page);
2855 for (block = page->text->blocks;
2856 block < page->text->blocks + page->text->len;
2857 ++block) {
2858 fz_text_line *line;
2860 b = &block->bbox;
2861 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2862 continue;
2864 for (line = block->lines;
2865 line < block->lines + block->len;
2866 ++line) {
2867 fz_text_span *span;
2869 b = &line->bbox;
2870 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2871 continue;
2873 for (span = line->spans;
2874 span < line->spans + line->len;
2875 ++span) {
2876 fz_text_char *ch;
2878 b = &span->bbox;
2879 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2880 continue;
2882 for (ch = span->text; ch < span->text + span->len; ++ch) {
2883 b = &ch->bbox;
2885 if (x >= b->x0 && x <= b->x1
2886 && y >= b->y0 && y <= b->y1) {
2887 const char *n2 =
2888 span->style->font && span->style->font->name
2889 ? span->style->font->name
2890 : "Span has no font name"
2892 FT_FaceRec *face = span->style->font->ft_face;
2893 if (face && face->family_name) {
2894 char *s;
2895 char *n1 = face->family_name;
2896 size_t l1 = strlen (n1);
2897 size_t l2 = strlen (n2);
2899 if (l1 != l2 || memcmp (n1, n2, l1)) {
2900 s = malloc (l1 + l2 + 2);
2901 if (s) {
2902 memcpy (s, n2, l2);
2903 s[l2] = '=';
2904 memcpy (s + l2 + 1, n1, l1 + 1);
2905 str_v = caml_copy_string (s);
2906 free (s);
2910 if (str_v == 0) {
2911 str_v = caml_copy_string (n2);
2913 ret_v = caml_alloc_small (1, utext);
2914 Field (ret_v, 0) = str_v;
2915 goto unlock;
2922 unlock:
2923 unlock ("ml_whatsunder");
2925 done:
2926 CAMLreturn (ret_v);
2929 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2931 CAMLparam2 (ptr_v, rect_v);
2932 fz_rect *b;
2933 struct page *page;
2934 struct pagedim *pdim;
2935 int i, x0, x1, y0, y1;
2936 char *s = String_val (ptr_v);
2937 int fi = 0, li = 0;
2938 fz_text_block *block;
2939 fz_text_span *span, *fspan, *lspan;
2940 fz_text_line *line, *fline = NULL, *lline = NULL;
2942 if (trylock ("ml_seltext")) {
2943 goto done;
2946 page = parse_pointer ("ml_seltext", s);
2947 ensuretext (page);
2949 pdim = &state.pagedims[page->pdimno];
2950 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2951 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2952 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2953 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2955 if (0) {
2956 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2957 glColor3ub (128, 128, 128);
2958 glRecti (x0, y0, x1, y1);
2959 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2962 fspan = lspan = NULL;
2964 for (block = page->text->blocks;
2965 block < page->text->blocks + page->text->len;
2966 ++block) {
2967 for (line = block->lines;
2968 line < block->lines + block->len;
2969 ++line) {
2970 for (span = line->spans;
2971 span < line->spans + line->len;
2972 ++span) {
2973 for (i = 0; i < span->len; ++i) {
2974 b = &span->text[i].bbox;
2975 int selected = 0;
2977 if (x0 >= b->x0 && x0 <= b->x1
2978 && y0 >= b->y0 && y0 <= b->y1) {
2979 fspan = span;
2980 fline = line;
2981 fi = i;
2982 selected = 1;
2984 if (x1 >= b->x0 && x1 <= b->x1
2985 && y1 >= b->y0 && y1 <= b->y1) {
2986 lspan = span;
2987 lline = line;
2988 li = i;
2989 selected = 1;
2991 if (0 && selected) {
2992 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2993 glColor3ub (128, 128, 128);
2994 glRecti (b->x0, b->y0, b->x1, b->y1);
2995 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3001 if (y1 < y0 || x1 < x0) {
3002 int swap = 0;
3004 if (fspan == lspan) {
3005 swap = 1;
3007 else {
3008 if (y1 < y0) {
3009 if (fline != lline) {
3010 swap = 1;
3015 if (swap) {
3016 i = fi;
3017 span = fspan;
3019 fi = li;
3020 fspan = lspan;
3022 li = i;
3023 lspan = span;
3027 page->fmark.i = fi;
3028 page->fmark.span = fspan;
3030 page->lmark.i = li;
3031 page->lmark.span = lspan;
3033 unlock ("ml_seltext");
3035 done:
3036 CAMLreturn (Val_unit);
3039 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3041 char buf[4];
3042 int i, len, ret;
3044 for (i = a; i <= b; ++i) {
3045 len = fz_runetochar (buf, span->text[i].c);
3046 ret = fwrite (buf, len, 1, f);
3048 if (ret != 1) {
3049 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3050 len, ret, strerror (errno));
3051 return -1;
3054 return 0;
3057 #ifdef __CYGWIN__
3058 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3060 caml_failwith ("ml_popen not implemented under Cygwin");
3062 #else
3063 CAMLprim value ml_popen (value command_v, value fds_v)
3065 CAMLparam2 (command_v, fds_v);
3066 CAMLlocal2 (l_v, tup_v);
3067 int ret;
3068 char *msg = NULL;
3069 value earg_v = Nothing;
3070 posix_spawnattr_t attr;
3071 posix_spawn_file_actions_t fa;
3072 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
3074 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3075 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3078 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3079 msg = "posix_spawnattr_init";
3080 goto fail1;
3083 #ifdef POSIX_SPAWN_USEVFORK
3084 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3085 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3086 goto fail;
3088 #endif
3090 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3091 int fd1, fd2;
3093 tup_v = Field (l_v, 0);
3094 fd1 = Int_val (Field (tup_v, 0));
3095 fd2 = Int_val (Field (tup_v, 1));
3096 if (fd2 < 0) {
3097 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3098 msg = "posix_spawn_file_actions_addclose";
3099 earg_v = tup_v;
3100 goto fail;
3103 else {
3104 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3105 msg = "posix_spawn_file_actions_adddup2";
3106 earg_v = tup_v;
3107 goto fail;
3112 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3113 msg = "posix_spawn";
3114 goto fail;
3117 fail:
3118 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3119 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3122 fail1:
3123 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3124 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3125 strerror (ret));
3128 if (msg)
3129 unix_error (ret, msg, earg_v);
3131 CAMLreturn (Val_unit);
3133 #endif
3135 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3137 CAMLparam1 (ptr_v);
3138 FILE *f;
3139 int seen = 0;
3140 struct page *page;
3141 fz_text_line *line;
3142 fz_text_span *span;
3143 fz_text_block *block;
3144 int fd = Int_val (fd_v);
3145 char *s = String_val (ptr_v);
3147 if (trylock ("ml_copysel")) {
3148 goto done;
3151 page = parse_pointer ("ml_sopysel", s);
3153 if (!page->fmark.span || !page->lmark.span) {
3154 fprintf (stderr, "nothing to copy\n");
3155 goto unlock;
3158 f = fdopen (fd, "w");
3159 if (!f) {
3160 fprintf (stderr, "failed to fopen sel pipe: %s\n",
3161 strerror (errno));
3162 f = stdout;
3165 for (block = page->text->blocks;
3166 block < page->text->blocks + page->text->len;
3167 ++block) {
3168 for (line = block->lines;
3169 line < block->lines + block->len;
3170 ++line) {
3171 for (span = line->spans;
3172 span < line->spans + line->len;
3173 ++span) {
3174 int a, b;
3176 seen |= span == page->fmark.span || span == page->lmark.span;
3177 a = span == page->fmark.span ? page->fmark.i : 0;
3178 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3180 if (seen) {
3181 if (pipespan (f, span, a, b)) {
3182 goto close;
3184 if (span == line->spans + line->len - 1) {
3185 if (putc ('\n', f) == EOF) {
3186 fprintf (stderr,
3187 "failed break line on sel pipe: %s\n",
3188 strerror (errno));
3189 goto close;
3192 if (span == page->lmark.span) {
3193 goto endloop;
3199 endloop:
3200 page->lmark.span = NULL;
3201 page->fmark.span = NULL;
3203 close:
3204 if (f != stdout) {
3205 int ret = fclose (f);
3206 fd = -1;
3207 if (ret == -1) {
3208 if (errno != ECHILD) {
3209 fprintf (stderr, "failed to close sel pipe: %s\n",
3210 strerror (errno));
3214 unlock:
3215 unlock ("ml_copysel");
3217 done:
3218 if (fd >= 0) {
3219 if (close (fd)) {
3220 fprintf (stderr, "failed to close sel pipe: %s\n",
3221 strerror (errno));
3224 CAMLreturn (Val_unit);
3227 CAMLprim value ml_getpdimrect (value pagedimno_v)
3229 CAMLparam1 (pagedimno_v);
3230 CAMLlocal1 (ret_v);
3231 int pagedimno = Int_val (pagedimno_v);
3232 fz_rect box;
3234 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3235 if (trylock ("ml_getpdimrect")) {
3236 box = fz_empty_rect;
3238 else {
3239 box = state.pagedims[pagedimno].mediabox;
3240 unlock ("ml_getpdimrect");
3243 Store_double_field (ret_v, 0, box.x0);
3244 Store_double_field (ret_v, 1, box.x1);
3245 Store_double_field (ret_v, 2, box.y0);
3246 Store_double_field (ret_v, 3, box.y1);
3248 CAMLreturn (ret_v);
3251 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3252 value dw_v, value cols_v)
3254 CAMLparam3 (winw_v, winh_v, dw_v);
3255 CAMLlocal1 (ret_v);
3256 int i;
3257 double zoom = -1.;
3258 double maxh = 0.0;
3259 struct pagedim *p;
3260 double winw = Int_val (winw_v);
3261 double winh = Int_val (winh_v);
3262 double dw = Int_val (dw_v);
3263 double cols = Int_val (cols_v);
3264 double pw = 1.0, ph = 1.0;
3266 if (trylock ("ml_zoom_for_height")) {
3267 goto done;
3270 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3271 double w = p->pagebox.x1 / cols;
3272 double h = p->pagebox.y1;
3273 if (h > maxh) {
3274 maxh = h;
3275 ph = h;
3276 if (state.fitmodel != FitProportional) pw = w;
3278 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3281 zoom = (((winh / ph) * pw) + dw) / winw;
3282 unlock ("ml_zoom_for_height");
3283 done:
3284 ret_v = caml_copy_double (zoom);
3285 CAMLreturn (ret_v);
3288 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3290 CAMLparam4 (pt_v, x_v, y_v, string_v);
3291 CAMLlocal1 (ret_v);
3292 int pt = Int_val(pt_v);
3293 int x = Int_val (x_v);
3294 int y = Int_val (y_v);
3295 double w;
3297 w = draw_string (state.face, pt, x, y, String_val (string_v));
3298 ret_v = caml_copy_double (w);
3299 CAMLreturn (ret_v);
3302 CAMLprim value ml_measure_string (value pt_v, value string_v)
3304 CAMLparam2 (pt_v, string_v);
3305 CAMLlocal1 (ret_v);
3306 int pt = Int_val (pt_v);
3307 double w;
3309 w = measure_string (state.face, pt, String_val (string_v));
3310 ret_v = caml_copy_double (w);
3311 CAMLreturn (ret_v);
3314 CAMLprim value ml_getpagebox (value opaque_v)
3316 CAMLparam1 (opaque_v);
3317 CAMLlocal1 (ret_v);
3318 fz_rect rect;
3319 fz_irect bbox;
3320 fz_matrix ctm;
3321 fz_device *dev;
3322 char *s = String_val (opaque_v);
3323 struct page *page = parse_pointer ("ml_getpagebox", s);
3325 ret_v = caml_alloc_tuple (4);
3326 dev = fz_new_bbox_device (state.ctx, &rect);
3327 dev->hints |= FZ_IGNORE_SHADE;
3329 switch (page->type) {
3330 case DPDF:
3331 ctm = pagectm (page);
3332 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3333 break;
3335 case DXPS:
3336 ctm = pagectm (page);
3337 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3338 break;
3340 default:
3341 rect = fz_infinite_rect;
3342 break;
3345 fz_free_device (dev);
3346 fz_round_rect (&bbox, &rect);
3347 Field (ret_v, 0) = Val_int (bbox.x0);
3348 Field (ret_v, 1) = Val_int (bbox.y0);
3349 Field (ret_v, 2) = Val_int (bbox.x1);
3350 Field (ret_v, 3) = Val_int (bbox.y1);
3352 CAMLreturn (ret_v);
3355 CAMLprim value ml_setaalevel (value level_v)
3357 CAMLparam1 (level_v);
3359 state.aalevel = Int_val (level_v);
3360 CAMLreturn (Val_unit);
3363 #undef pixel
3364 #include <X11/Xlib.h>
3365 #include <GL/glx.h>
3367 static struct {
3368 Display *dpy;
3369 GLXContext ctx;
3370 GLXDrawable drawable;
3371 } glx;
3373 #include "keysym2ucs.c"
3375 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3377 CAMLparam1 (keysym_v);
3378 CAMLlocal1 (str_v);
3379 KeySym keysym = Int_val (keysym_v);
3380 Rune rune;
3381 int len;
3382 char buf[5];
3384 rune = keysym2ucs (keysym);
3385 len = fz_runetochar (buf, rune);
3386 buf[len] = 0;
3387 str_v = caml_copy_string (buf);
3388 CAMLreturn (str_v);
3391 CAMLprim value ml_glx (value win_v)
3393 CAMLparam1 (win_v);
3394 XVisualInfo *visual;
3395 int screen, wid = Int_val (win_v);
3396 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3398 glx.dpy = XOpenDisplay (NULL);
3399 if (!glx.dpy) {
3400 caml_failwith ("XOpenDisplay");
3403 screen = DefaultScreen (glx.dpy);
3404 visual = glXChooseVisual (glx.dpy, screen, attributes);
3405 if (!visual) {
3406 XCloseDisplay (glx.dpy);
3407 glx.dpy = NULL;
3408 caml_failwith ("glXChooseVisual");
3411 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3412 XFree (visual);
3413 if (!glx.ctx) {
3414 XCloseDisplay (glx.dpy);
3415 glx.dpy = NULL;
3416 caml_failwith ("glXCreateContext");
3419 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3420 glXDestroyContext (glx.dpy, glx.ctx);
3421 XCloseDisplay (glx.dpy);
3422 glx.dpy = NULL;
3423 glx.ctx = NULL;
3424 caml_failwith ("glXMakeCurrent");
3426 glx.drawable = wid;
3427 CAMLreturn (Val_unit);
3430 CAMLprim value ml_swapb (value unit_v)
3432 CAMLparam1 (unit_v);
3433 glXSwapBuffers (glx.dpy, glx.drawable);
3434 CAMLreturn (Val_unit);
3437 CAMLprim value ml_glxsync (value unit_v)
3439 CAMLparam1 (unit_v);
3440 if (glx.dpy && glx.ctx) {
3441 glXWaitX ();
3442 glXWaitGL ();
3444 CAMLreturn (Val_unit);
3447 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3448 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3450 CAMLprim value ml_platform (value unit_v)
3452 CAMLparam1 (unit_v);
3453 int platid = piunknown;
3455 #if defined __linux__
3456 platid = pilinux;
3457 #elif defined __CYGWIN__
3458 platid = picygwin;
3459 #elif defined __DragonFly__
3460 platid = pidragonflybsd;
3461 #elif defined __FreeBSD__
3462 platid = pifreebsd;
3463 #elif defined __OpenBSD__
3464 platid = piopenbsd;
3465 #elif defined __NetBSD__
3466 platid = pinetbsd;
3467 #elif defined __sun__
3468 platid = pisun;
3469 #elif defined __APPLE__
3470 platid = piosx;
3471 #endif
3472 CAMLreturn (Val_int (platid));
3475 CAMLprim value ml_cloexec (value fd_v)
3477 CAMLparam1 (fd_v);
3478 int fd = Int_val (fd_v);
3480 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3481 uerror ("fcntl", Nothing);
3483 CAMLreturn (Val_unit);
3486 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3488 CAMLparam2 (w_v, h_v);
3489 CAMLlocal1 (ret_v);
3490 struct pbo *pbo;
3491 int w = Int_val (w_v);
3492 int h = Int_val (h_v);
3493 int cs = Int_val (cs_v);
3495 if (state.pbo_usable) {
3496 pbo = calloc (sizeof (*pbo), 1);
3497 if (!pbo) {
3498 err (1, "calloc pbo");
3501 switch (cs) {
3502 case 0:
3503 case 1:
3504 pbo->size = w*h*4;
3505 break;
3506 case 2:
3507 pbo->size = w*h*2;
3508 break;
3509 default:
3510 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3513 state.glGenBuffersARB (1, &pbo->id);
3514 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3515 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3516 NULL, GL_STREAM_DRAW);
3517 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3518 GL_READ_WRITE);
3519 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3520 if (!pbo->ptr) {
3521 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3522 state.glDeleteBuffersARB (1, &pbo->id);
3523 free (pbo);
3524 ret_v = caml_copy_string ("0");
3526 else {
3527 int res;
3528 char *s;
3530 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3531 if (res < 0) {
3532 err (1, "snprintf %" FMT_ptr " failed", pbo);
3534 s = malloc (res+1);
3535 if (!s) {
3536 err (1, "malloc %d bytes failed", res+1);
3538 res = sprintf (s, "%" FMT_ptr, pbo);
3539 if (res < 0) {
3540 err (1, "sprintf %" FMT_ptr " failed", pbo);
3542 ret_v = caml_copy_string (s);
3543 free (s);
3546 else {
3547 ret_v = caml_copy_string ("0");
3549 CAMLreturn (ret_v);
3552 CAMLprim value ml_freepbo (value s_v)
3554 CAMLparam1 (s_v);
3555 char *s = String_val (s_v);
3556 struct tile *tile = parse_pointer ("ml_freepbo", s);
3558 if (tile->pbo) {
3559 state.glDeleteBuffersARB (1, &tile->pbo->id);
3560 tile->pbo->id = -1;
3561 tile->pbo->ptr = NULL;
3562 tile->pbo->size = -1;
3564 CAMLreturn (Val_unit);
3567 CAMLprim value ml_unmappbo (value s_v)
3569 CAMLparam1 (s_v);
3570 char *s = String_val (s_v);
3571 struct tile *tile = parse_pointer ("ml_unmappbo", s);
3573 if (tile->pbo) {
3574 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3575 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3576 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3578 tile->pbo->ptr = NULL;
3579 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3581 CAMLreturn (Val_unit);
3584 static void setuppbo (void)
3586 #define GGPA(n) *(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n)
3587 GGPA (glBindBufferARB);
3588 if (state.glBindBufferARB) {
3589 GGPA (glUnmapBufferARB);
3590 if (state.glUnmapBufferARB) {
3591 GGPA (glMapBufferARB);
3592 if (state.glMapBufferARB) {
3593 GGPA (glBufferDataARB);
3594 if (state.glBufferDataARB) {
3595 GGPA (glGenBuffersARB);
3596 if (state.glGenBuffersARB) {
3597 GGPA (glDeleteBuffersARB);
3598 if (state.glDeleteBuffersARB) {
3599 state.pbo_usable = 1;
3606 #undef GGPA
3609 CAMLprim value ml_pbo_usable (value unit_v)
3611 CAMLparam1 (unit_v);
3612 CAMLreturn (Val_bool (state.pbo_usable));
3615 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3617 CAMLparam3 (ptr_v, x_v, y_v);
3618 CAMLlocal2 (ret_v, tup_v);
3619 struct page *page;
3620 char *s = String_val (ptr_v);
3621 int x = Int_val (x_v), y = Int_val (y_v);
3622 struct pagedim *pdim;
3623 fz_point p;
3624 fz_matrix ctm;
3626 page = parse_pointer ("ml_unproject", s);
3627 pdim = &state.pagedims[page->pdimno];
3629 ret_v = Val_int (0);
3630 if (trylock ("ml_unproject")) {
3631 goto done;
3634 switch (page->type) {
3635 case DPDF:
3636 trimctm (page->u.pdfpage, page->pdimno);
3637 break;
3639 default:
3640 break;
3642 p.x = x;
3643 p.y = y;
3645 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3646 fz_invert_matrix (&ctm, &ctm);
3647 fz_transform_point (&p, &ctm);
3649 tup_v = caml_alloc_tuple (2);
3650 ret_v = caml_alloc_small (1, 1);
3651 Field (tup_v, 0) = Val_int (p.x);
3652 Field (tup_v, 1) = Val_int (p.y);
3653 Field (ret_v, 0) = tup_v;
3655 unlock ("ml_unproject");
3656 done:
3657 CAMLreturn (ret_v);
3660 static void makestippletex (void)
3662 const char *pixels = "\xff\xff\0\0";
3663 glGenTextures (1, &state.stid);
3664 glBindTexture (GL_TEXTURE_1D, state.stid);
3665 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3666 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3667 glTexImage1D (
3668 GL_TEXTURE_1D,
3670 GL_ALPHA,
3673 GL_ALPHA,
3674 GL_UNSIGNED_BYTE,
3675 pixels
3679 CAMLprim value ml_init (value pipe_v, value params_v)
3681 CAMLparam2 (pipe_v, params_v);
3682 CAMLlocal2 (trim_v, fuzz_v);
3683 int ret;
3684 int texcount;
3685 char *fontpath;
3686 int colorspace;
3687 int mustoresize;
3688 int haspboext;
3689 struct sigaction sa;
3691 state.cr = Int_val (Field (pipe_v, 0));
3692 state.cw = Int_val (Field (pipe_v, 1));
3693 state.rotate = Int_val (Field (params_v, 0));
3694 state.fitmodel = Int_val (Field (params_v, 1));
3695 trim_v = Field (params_v, 2);
3696 texcount = Int_val (Field (params_v, 3));
3697 state.sliceheight = Int_val (Field (params_v, 4));
3698 mustoresize = Int_val (Field (params_v, 5));
3699 colorspace = Int_val (Field (params_v, 6));
3700 fontpath = String_val (Field (params_v, 7));
3701 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
3702 if (!state.trimcachepath) {
3703 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
3704 strerror (errno));
3706 haspboext = Bool_val (Field (params_v, 9));
3708 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3710 state.trimmargins = Bool_val (Field (trim_v, 0));
3711 fuzz_v = Field (trim_v, 1);
3712 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3713 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3714 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3715 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3717 set_tex_params (colorspace);
3719 if (*fontpath) {
3720 state.face = load_font (fontpath);
3722 else {
3723 unsigned int len;
3724 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
3726 state.face = load_builtin_font (base, len);
3728 if (!state.face) _exit (1);
3730 realloctexts (texcount);
3732 if (haspboext) {
3733 setuppbo ();
3736 makestippletex ();
3737 #ifdef __CYGWIN__
3738 sa.sa_handler = SIG_IGN;
3739 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3740 #else
3741 sa.sa_handler = SIG_DFL;
3742 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
3743 #endif
3744 if (sigemptyset (&sa.sa_mask)) {
3745 err (1, "sigemptyset");
3747 if (sigaction (SIGCHLD, &sa, NULL)) {
3748 err (1, "sigaction");
3751 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3752 if (ret) {
3753 errx (1, "pthread_create: %s", strerror (ret));
3756 CAMLreturn (Val_unit);