And some more
[llpp/slowscroll.git] / link.c
blob63b77bf80c665bfabb24f354fd02970e268831b4
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 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 <altivec.h>
603 static int cacheline32bytes;
605 static void __attribute__ ((constructor)) clcheck (void)
607 char **envp = environ;
608 unsigned long *auxv;
610 while (*envp++);
612 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
613 if (*auxv == 19) {
614 cacheline32bytes = auxv[1] == 32;
615 return;
620 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
622 size_t size = pixmap->w * pixmap->h * pixmap->n;
623 if (cacheline32bytes && size > 32) {
624 intptr_t a1, a2, diff;
625 size_t sizea, i;
626 vector unsigned char v = vec_splat_u8 (-1);
627 vector unsigned char *p;
629 a1 = a2 = (intptr_t) pixmap->samples;
630 a2 = (a1 + 31) & ~31;
631 diff = a2 - a1;
632 sizea = size - diff;
633 p = (void *) a2;
635 while (a1 != a2) *(char *) a1++ = 0xff;
636 for (i = 0; i < (sizea & ~31); i += 32) {
637 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
638 vec_st (v, i, p);
639 vec_st (v, i + 16, p);
641 while (i < sizea) *((char *) a1 + i++) = 0xff;
643 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
645 #else
646 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
647 #endif
649 static void trimctm (pdf_page *page, int pindex)
651 fz_matrix ctm;
652 struct pagedim *pdim = &state.pagedims[pindex];
654 if (!pdim->tctmready) {
655 if (state.trimmargins) {
656 fz_rect realbox;
657 fz_matrix rm, sm, tm, im, ctm1;
659 fz_rotate (&rm, -pdim->rotate);
660 fz_scale (&sm, 1, -1);
661 fz_concat (&ctm, &rm, &sm);
662 realbox = pdim->mediabox;
663 fz_transform_rect (&realbox, &ctm);
664 fz_translate (&tm, -realbox.x0, -realbox.y0);
665 fz_concat (&ctm1, &ctm, &tm);
666 fz_invert_matrix (&im, &page->ctm);
667 fz_concat (&ctm, &im, &ctm1);
669 else {
670 ctm = fz_identity;
672 pdim->tctm = ctm;
673 pdim->tctmready = 1;
677 static fz_matrix pagectm (struct page *page)
679 fz_matrix ctm, tm;
681 if (page->type == DPDF) {
682 trimctm (page->u.pdfpage, page->pdimno);
683 fz_concat (&ctm,
684 &state.pagedims[page->pdimno].tctm,
685 &state.pagedims[page->pdimno].ctm);
687 else {
688 struct pagedim *pdim = &state.pagedims[page->pdimno];
690 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
691 fz_concat (&ctm, &tm, &state.pagedims[page->pdimno].ctm);
693 return ctm;
696 static void *loadpage (int pageno, int pindex)
698 fz_device *dev;
699 struct page *page = NULL;
701 page = calloc (sizeof (struct page), 1);
702 if (!page) {
703 err (1, "calloc page %d", pageno);
706 page->dlist = fz_new_display_list (state.ctx);
707 dev = fz_new_list_device (state.ctx, page->dlist);
708 fz_try (state.ctx) {
709 switch (state.type) {
710 case DPDF:
711 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
712 pdf_run_page (state.u.pdf, page->u.pdfpage, dev,
713 &fz_identity, NULL);
714 page->freepage = freepdfpage;
715 break;
717 case DXPS:
718 page->u.xpspage = xps_load_page (state.u.xps, pageno);
719 xps_run_page (state.u.xps, page->u.xpspage, dev,
720 &fz_identity, NULL);
721 page->freepage = freexpspage;
722 break;
724 case DCBZ:
725 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
726 cbz_run_page (state.u.cbz, page->u.cbzpage, dev,
727 &fz_identity, NULL);
728 page->freepage = freecbzpage;
729 break;
732 fz_catch (state.ctx) {
733 page->u.ptr = NULL;
734 page->freepage = freeemptyxxxpage;
736 fz_free_device (dev);
738 page->pdimno = pindex;
739 page->pageno = pageno;
740 page->sgen = state.gen;
741 page->tgen = state.gen;
742 page->type = state.type;
744 return page;
747 static struct tile *alloctile (int h)
749 int i;
750 int slicecount;
751 size_t tilesize;
752 struct tile *tile;
754 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
755 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
756 tile = calloc (tilesize, 1);
757 if (!tile) {
758 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
760 for (i = 0; i < slicecount; ++i) {
761 int sh = MIN (h, state.sliceheight);
762 tile->slices[i].h = sh;
763 tile->slices[i].texindex = -1;
764 h -= sh;
766 tile->slicecount = slicecount;
767 tile->sliceheight = state.sliceheight;
768 return tile;
771 #ifdef OBSCURED_OPT
772 struct obs {
773 int cured;
774 fz_irect b;
777 static void obs_fill_image (fz_device *dev, fz_image *image,
778 const fz_matrix *ctm, float alpha)
780 struct obs *obs = dev->user;
782 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
783 fz_irect b;
784 fz_rect rect = fz_unit_rect;
786 fz_transform_rect (&rect, ctm);
787 fz_round_rect (&b, &rect);
788 fz_intersect_irect (&b, &obs->b);
789 obs->cured = b.x0 == obs->b.x0
790 && b.x1 == obs->b.x1
791 && b.y0 == obs->b.y0
792 && b.y1 == obs->b.y1;
796 static int obscured (struct page *page, fz_irect bbox)
798 fz_rect rect;
799 fz_matrix ctm;
800 fz_device dev;
801 struct obs obs;
803 memset (&dev, 0, sizeof (dev));
804 memset (&obs, 0, sizeof (obs));
805 dev.hints = 0;
806 dev.flags = 0;
807 dev.user = &obs;
808 dev.ctx = state.ctx;
809 dev.fill_image = obs_fill_image;
810 obs.b = bbox;
811 fz_rect_from_irect (&rect, &bbox);
812 ctm = pagectm (page);
813 fz_run_display_list (page->dlist, &dev, &ctm, &rect, NULL);
814 return obs.cured;
816 #define OBSCURED obscured
817 #else
818 #define OBSCURED(a, b) 0
819 #endif
821 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
822 struct pbo *pbo)
824 fz_rect rect;
825 fz_irect bbox;
826 fz_matrix ctm;
827 fz_device *dev;
828 struct tile *tile;
829 struct pagedim *pdim;
831 tile = alloctile (h);
832 pdim = &state.pagedims[page->pdimno];
834 bbox = pdim->bounds;
835 bbox.x0 += x;
836 bbox.y0 += y;
837 bbox.x1 = bbox.x0 + w;
838 bbox.y1 = bbox.y0 + h;
840 if (state.pig) {
841 if (state.pig->w == w
842 && state.pig->h == h
843 && state.pig->colorspace == state.colorspace) {
844 tile->pixmap = state.pig;
845 tile->pixmap->x = bbox.x0;
846 tile->pixmap->y = bbox.y0;
848 else {
849 fz_drop_pixmap (state.ctx, state.pig);
851 state.pig = NULL;
853 if (!tile->pixmap) {
854 if (pbo) {
855 tile->pixmap =
856 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
857 &bbox, pbo->ptr);
858 tile->pbo = pbo;
860 else {
861 tile->pixmap =
862 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
866 tile->w = w;
867 tile->h = h;
868 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
869 clearpixmap (tile->pixmap);
871 dev = fz_new_draw_device (state.ctx, tile->pixmap);
872 ctm = pagectm (page);
873 fz_rect_from_irect (&rect, &bbox);
874 fz_run_display_list (page->dlist, dev, &ctm, &rect, NULL);
875 fz_free_device (dev);
877 return tile;
880 static void initpdims (void)
882 double start, end;
883 int pageno, trim, show;
884 FILE *trimf = NULL;
885 int trimw = 0;
887 start = now ();
889 if (state.trimmargins && state.trimcachepath) {
890 trimf = fopen (state.trimcachepath, "rb");
891 if (!trimf) {
892 trimf = fopen (state.trimcachepath, "wb");
893 trimw = 1;
896 for (pageno = 0; pageno < state.pagecount; ++pageno) {
897 int rotate = 0;
898 struct pagedim *p;
899 fz_rect mediabox;
901 switch (state.type) {
902 case DPDF: {
903 pdf_obj *pageobj = state.u.pdf->page_objs[pageno];
905 if (state.trimmargins) {
906 pdf_obj *obj;
907 pdf_page *page;
909 fz_try (state.ctx) {
910 page = pdf_load_page (state.u.pdf, pageno);
911 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
912 trim = state.trimanew || !obj;
913 if (trim) {
914 fz_rect rect;
915 fz_matrix ctm;
916 fz_device *dev;
918 dev = fz_new_bbox_device (state.ctx, &rect);
919 dev->hints |= FZ_IGNORE_SHADE;
920 fz_invert_matrix (&ctm, &page->ctm);
921 pdf_run_page (state.u.pdf, page, dev, &fz_identity, NULL);
922 fz_free_device (dev);
924 rect.x0 += state.trimfuzz.x0;
925 rect.x1 += state.trimfuzz.x1;
926 rect.y0 += state.trimfuzz.y0;
927 rect.y1 += state.trimfuzz.y1;
928 fz_transform_rect (&rect, &ctm);
929 fz_intersect_rect (&rect, &page->mediabox);
931 if (fz_is_empty_rect (&rect)) {
932 mediabox = page->mediabox;
934 else {
935 mediabox = rect;
938 obj = pdf_new_array (state.ctx, 4);
939 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x0));
940 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y0));
941 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x1));
942 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y1));
943 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
945 else {
946 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
947 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
948 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
949 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
952 rotate = page->rotate;
953 pdf_free_page (state.u.pdf, page);
955 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
956 if (show) {
957 printd ("progress %f Trimming %d",
958 (double) (pageno + 1) / state.pagecount,
959 pageno + 1);
962 fz_catch (state.ctx) {
963 fprintf (stderr, "failed to load page %d\n", pageno+1);
966 else {
967 fz_rect cropbox;
969 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "MediaBox"),
970 &mediabox);
971 if (fz_is_empty_rect (&mediabox)) {
972 fprintf (stderr, "cannot find page size for page %d\n",
973 pageno+1);
974 mediabox.x0 = 0;
975 mediabox.y0 = 0;
976 mediabox.x1 = 612;
977 mediabox.y1 = 792;
980 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "CropBox"),
981 &cropbox);
982 if (!fz_is_empty_rect (&cropbox)) {
983 fz_intersect_rect (&mediabox, &cropbox);
985 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
987 break;
990 case DXPS:
992 xps_page *page;
994 fz_try (state.ctx) {
995 page = xps_load_page (state.u.xps, pageno);
996 xps_bound_page (state.u.xps, page, &mediabox);
997 rotate = 0;
998 if (state.trimmargins) {
999 fz_rect rect;
1000 fz_device *dev;
1002 dev = fz_new_bbox_device (state.ctx, &rect);
1003 dev->hints |= FZ_IGNORE_SHADE;
1004 xps_run_page (state.u.xps, page, dev,
1005 &fz_identity, NULL);
1006 fz_free_device (dev);
1008 rect.x0 += state.trimfuzz.x0;
1009 rect.x1 += state.trimfuzz.x1;
1010 rect.y0 += state.trimfuzz.y0;
1011 rect.y1 += state.trimfuzz.y1;
1012 fz_intersect_rect (&rect, &mediabox);
1014 if (!fz_is_empty_rect (&rect)) {
1015 mediabox = rect;
1018 xps_free_page (state.u.xps, page);
1019 printd ("progress %f loading %d",
1020 (double) (pageno + 1) / state.pagecount,
1021 pageno + 1);
1023 fz_catch (state.ctx) {
1026 break;
1028 case DCBZ:
1030 rotate = 0;
1031 if (state.trimmargins && trimw) {
1032 cbz_page *page;
1034 fz_try (state.ctx) {
1035 page = cbz_load_page (state.u.cbz, pageno);
1036 cbz_bound_page (state.u.cbz, page, &mediabox);
1037 cbz_free_page (state.u.cbz, page);
1038 printd ("progress %f Trimming %d",
1039 (double) (pageno + 1) / state.pagecount,
1040 pageno + 1);
1042 fz_catch (state.ctx) {
1043 fprintf (stderr, "failed to load page %d\n", pageno+1);
1044 mediabox.x0 = 0;
1045 mediabox.y0 = 0;
1046 mediabox.x1 = 900;
1047 mediabox.y1 = 900;
1049 if (trimf) {
1050 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1051 if (n - 1) {
1052 err (1, "fwrite trim mediabox");
1056 else {
1057 if (trimf) {
1058 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1059 if (n - 1) {
1060 err (1, "fread trim mediabox");
1063 else {
1064 mediabox.x0 = mediabox.y0 = 0;
1065 mediabox.x1 = 900;
1066 mediabox.y1 = 900;
1070 break;
1072 default:
1073 ARSERT (0 && state.type);
1076 if (state.pagedimcount == 0
1077 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1078 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1079 size_t size;
1081 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1082 state.pagedims = realloc (state.pagedims, size);
1083 if (!state.pagedims) {
1084 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1085 size, state.pagedimcount + 1);
1088 p = &state.pagedims[state.pagedimcount++];
1089 p->rotate = rotate;
1090 p->mediabox = mediabox;
1091 p->pageno = pageno;
1094 end = now ();
1095 if (state.trimmargins) {
1096 printd ("progress 1 Trimmed %d pages in %f seconds",
1097 state.pagecount, end - start);
1099 else {
1100 printd ("vmsg Processed %d pages in %f seconds",
1101 state.pagecount, end - start);
1103 state.trimanew = 0;
1104 if (trimf) {
1105 if (fclose (trimf)) {
1106 err (1, "fclose");
1111 static void layout (void)
1113 int pindex;
1114 fz_rect box;
1115 fz_matrix ctm;
1116 double zoom, w, maxw = 0.0;
1117 struct pagedim *p = state.pagedims;
1119 if (state.proportional) {
1120 int i;
1121 struct pagedim *p;
1123 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
1124 fz_rect rect;
1125 fz_matrix rm;
1126 double x0, x1, w;
1128 fz_rotate (&rm, p->rotate + state.rotate);
1129 rect = p->mediabox;
1130 fz_transform_rect (&rect, &rm);
1132 x0 = MIN (rect.x0, rect.x1);
1133 x1 = MAX (rect.x0, rect.x1);
1135 w = x1 - x0;
1136 maxw = MAX (w, maxw);
1140 p = state.pagedims;
1141 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1142 fz_rect rect;
1143 fz_matrix tm, sm, rm;
1145 fz_rotate (&ctm, state.rotate);
1146 fz_rotate (&rm, p->rotate + state.rotate);
1147 box = p->mediabox;
1148 fz_transform_rect (&box, &rm);
1149 w = box.x1 - box.x0;
1151 if (state.proportional) {
1152 double scale = w / maxw;
1153 zoom = (state.w / w) * scale;
1155 else {
1156 zoom = state.w / w;
1159 fz_scale (&p->zoomctm, zoom, zoom);
1160 fz_concat (&ctm, &p->zoomctm, &ctm);
1162 fz_rotate (&rm, p->rotate);
1163 p->pagebox = p->mediabox;
1164 fz_transform_rect (&p->pagebox, &rm);
1165 p->pagebox.x1 -= p->pagebox.x0;
1166 p->pagebox.y1 -= p->pagebox.y0;
1167 p->pagebox.x0 = 0;
1168 p->pagebox.y0 = 0;
1169 rect = p->pagebox;
1170 fz_transform_rect (&rect, &ctm);
1171 fz_round_rect (&p->bounds, &rect);
1173 p->left = state.proportional ? ((maxw - w) * zoom) / 2.0 : 0;
1174 p->ctm = ctm;
1176 fz_translate (&tm, 0, -p->mediabox.y1);
1177 fz_scale (&sm, zoom, -zoom);
1178 fz_concat (&ctm, &tm, &sm);
1179 fz_concat (&p->lctm, &ctm, &rm);
1181 p->tctmready = 0;
1184 while (p-- != state.pagedims) {
1185 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1186 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1187 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1188 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1189 int w = x1 - x0;
1190 int h = y1 - y0;
1192 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1196 static
1197 struct anchor { int n; int x; int y; int w; int h; }
1198 desttoanchor (fz_link_dest *dest)
1200 int i;
1201 struct anchor a;
1202 struct pagedim *pdim = state.pagedims;
1204 a.n = -1;
1205 a.x = 0;
1206 a.y = 0;
1207 for (i = 0; i < state.pagedimcount; ++i) {
1208 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1209 break;
1210 pdim = &state.pagedims[i];
1212 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1213 fz_point p;
1214 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1215 p.x = dest->ld.gotor.lt.x;
1216 p.y = dest->ld.gotor.lt.y;
1217 fz_transform_point (&p, &pdim->lctm);
1218 a.y = p.y;
1219 a.x = p.x;
1221 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1222 double x0, x1, y0, y1;
1224 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1225 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1226 a.w = x1 - x0;
1227 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1228 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1229 a.h = y1 - y0;
1230 a.n = dest->ld.gotor.page;
1232 return a;
1235 static void recurse_outline (fz_outline *outline, int level)
1237 while (outline) {
1238 struct anchor a = desttoanchor (&outline->dest);
1240 if (a.n >= 0) {
1241 printd ("o %d %d %d %d %s",
1242 level, a.n, a.y, a.h, outline->title);
1244 if (outline->down) {
1245 recurse_outline (outline->down, level + 1);
1247 outline = outline->next;
1251 static void process_outline (void)
1253 fz_outline *outline;
1255 if (!state.needoutline) return;
1257 state.needoutline = 0;
1258 switch (state.type) {
1259 case DPDF:
1260 outline = pdf_load_outline (state.u.pdf);
1261 break;
1262 case DXPS:
1263 outline = xps_load_outline (state.u.xps);
1264 break;
1265 default:
1266 outline = NULL;
1267 break;
1269 if (outline) {
1270 recurse_outline (outline, 0);
1271 fz_free_outline (state.ctx, outline);
1275 static char *strofspan (fz_text_span *span)
1277 char *p;
1278 char utf8[10];
1279 fz_text_char *ch;
1280 size_t size = 0, cap = 80;
1282 p = malloc (cap + 1);
1283 if (!p) return NULL;
1285 for (ch = span->text; ch < span->text + span->len; ++ch) {
1286 int n = fz_runetochar (utf8, ch->c);
1287 if (size + n > cap) {
1288 cap *= 2;
1289 p = realloc (p, cap + 1);
1290 if (!p) return NULL;
1293 memcpy (p + size, utf8, n);
1294 size += n;
1296 p[size] = 0;
1297 return p;
1300 static int matchspan (regex_t *re, fz_text_span *span, fz_matrix ctm,
1301 int stop, int pageno, double start)
1303 int ret;
1304 char *p;
1305 regmatch_t rm;
1306 int a, b, c;
1307 fz_rect *sb, *eb;
1308 fz_point p1, p2, p3, p4;
1310 p = strofspan (span);
1311 if (!p) return -1;
1313 ret = regexec (re, p, 1, &rm, 0);
1314 if (ret) {
1315 free (p);
1316 if (ret != REG_NOMATCH) {
1317 size_t size;
1318 char errbuf[80];
1319 size = regerror (ret, re, errbuf, sizeof (errbuf));
1320 printd ("msg regexec error `%.*s'",
1321 (int) size, errbuf);
1322 return -1;
1324 return 0;
1326 else {
1327 int l = span->len;
1328 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1329 c += fz_runelen (span->text[a].c);
1331 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1332 c += fz_runelen (span->text[b].c);
1335 if (fz_runelen (span->text[b].c) > 1) {
1336 b = MAX (0, b-1);
1338 sb = &span->text[MIN (a, l-1)].bbox;
1339 eb = &span->text[MIN (b, l-1)].bbox;
1341 p1.x = sb->x0;
1342 p1.y = sb->y0;
1343 p2.x = eb->x1;
1344 p2.y = sb->y0;
1345 p3.x = eb->x1;
1346 p3.y = eb->y1;
1347 p4.x = sb->x0;
1348 p4.y = eb->y1;
1350 if (!stop) {
1351 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1352 pageno, 1,
1353 p1.x, p1.y,
1354 p2.x, p2.y,
1355 p3.x, p3.y,
1356 p4.x, p4.y);
1358 printd ("progress 1 found at %d `%.*s' in %f sec",
1359 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1360 now () - start);
1362 else {
1363 printd ("match %d %d %f %f %f %f %f %f %f %f",
1364 pageno, 2,
1365 p1.x, p1.y,
1366 p2.x, p2.y,
1367 p3.x, p3.y,
1368 p4.x, p4.y);
1370 free (p);
1371 return 1;
1375 static int compareblocks (const void *l, const void *r)
1377 fz_text_block const *ls = l;
1378 fz_text_block const* rs = r;
1379 return ls->bbox.y0 - rs->bbox.y0;
1382 /* wishful thinking function */
1383 static void search (regex_t *re, int pageno, int y, int forward)
1385 int i, j;
1386 fz_matrix ctm;
1387 fz_device *tdev;
1388 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1389 fz_text_page *text;
1390 fz_text_sheet *sheet;
1391 struct pagedim *pdim, *pdimprev;
1392 int stop = 0, niters = 0;
1393 double start, end;
1395 if (!(state.type == DPDF || state.type == DXPS))
1396 return;
1398 start = now ();
1399 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1400 if (niters++ == 5) {
1401 niters = 0;
1402 if (hasdata ()) {
1403 printd ("progress 1 attention requested aborting search at %d",
1404 pageno);
1405 stop = 1;
1407 else {
1408 printd ("progress %f searching in page %d",
1409 (double) (pageno + 1) / state.pagecount,
1410 pageno);
1413 pdimprev = NULL;
1414 for (i = 0; i < state.pagedimcount; ++i) {
1415 pdim = &state.pagedims[i];
1416 if (pdim->pageno == pageno) {
1417 goto found;
1419 if (pdim->pageno > pageno) {
1420 pdim = pdimprev;
1421 goto found;
1423 pdimprev = pdim;
1425 pdim = pdimprev;
1426 found:
1428 sheet = fz_new_text_sheet (state.ctx);
1429 text = fz_new_text_page (state.ctx, &fz_infinite_rect);
1430 tdev = fz_new_text_device (state.ctx, sheet, text);
1432 switch (state.type) {
1433 case DPDF:
1434 u.ptr = NULL;
1435 fz_try (state.ctx) {
1436 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1437 trimctm (u.pdfpage, pdim - state.pagedims);
1438 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1439 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1441 fz_catch (state.ctx) {
1442 fz_free_device (tdev);
1443 u.ptr = NULL;
1444 goto nextiter;
1446 break;
1448 case DXPS:
1449 u.xpspage = xps_load_page (state.u.xps, pageno);
1450 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1451 break;
1453 default:
1454 ARSERT (0 && state.type);
1457 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1458 fz_free_device (tdev);
1460 for (j = 0; j < text->len; ++j) {
1461 int k;
1462 fz_text_block *block;
1464 block = &text->blocks[forward ? j : text->len - 1 - j];
1466 for (k = 0; k < block->len; ++k) {
1467 fz_text_line *line;
1468 fz_text_span *span;
1470 if (forward) {
1471 line = &block->lines[k];
1472 if (line->bbox.y0 < y + 1) continue;
1474 else {
1475 line = &block->lines[block->len - 1 - k];
1476 if (line->bbox.y0 > y - 1) continue;
1479 for (span = line->spans;
1480 span < line->spans + line->len;
1481 ++span) {
1483 switch (matchspan (re, span, ctm, stop, pageno, start)) {
1484 case 0: break;
1485 case 1: stop = 1; break;
1486 case -1: stop = 1; goto endloop;
1491 nextiter:
1492 if (forward) {
1493 pageno += 1;
1494 y = 0;
1496 else {
1497 pageno -= 1;
1498 y = INT_MAX;
1500 endloop:
1501 fz_free_text_page (state.ctx, text);
1502 fz_free_text_sheet (state.ctx, sheet);
1503 if (u.ptr) {
1504 state.freepage (u.ptr);
1507 end = now ();
1508 if (!stop) {
1509 printd ("progress 1 no matches %f sec", end - start);
1511 printd ("clearrects");
1514 static void set_tex_params (int colorspace)
1516 union {
1517 unsigned char b;
1518 unsigned int s;
1519 } endianness = {1};
1521 switch (colorspace) {
1522 case 0:
1523 state.texiform = GL_RGBA8;
1524 state.texform = GL_RGBA;
1525 state.texty = GL_UNSIGNED_BYTE;
1526 state.colorspace = fz_device_rgb;
1527 break;
1528 case 1:
1529 state.texiform = GL_RGBA8;
1530 state.texform = GL_BGRA;
1531 state.texty = endianness.s > 1
1532 ? GL_UNSIGNED_INT_8_8_8_8
1533 : GL_UNSIGNED_INT_8_8_8_8_REV;
1534 state.colorspace = fz_device_bgr;
1535 break;
1536 case 2:
1537 state.texiform = GL_LUMINANCE_ALPHA;
1538 state.texform = GL_LUMINANCE_ALPHA;
1539 state.texty = GL_UNSIGNED_BYTE;
1540 state.colorspace = fz_device_gray;
1541 break;
1542 default:
1543 errx (1, "invalid colorspce %d", colorspace);
1547 static void realloctexts (int texcount)
1549 size_t size;
1551 if (texcount == state.texcount) return;
1553 if (texcount < state.texcount) {
1554 glDeleteTextures (state.texcount - texcount,
1555 state.texids + texcount);
1558 size = texcount * sizeof (*state.texids);
1559 state.texids = realloc (state.texids, size);
1560 if (!state.texids) {
1561 err (1, "realloc texids %" FMT_s, size);
1564 size = texcount * sizeof (*state.texowners);
1565 state.texowners = realloc (state.texowners, size);
1566 if (!state.texowners) {
1567 err (1, "realloc texowners %" FMT_s, size);
1569 if (texcount > state.texcount) {
1570 int i;
1572 glGenTextures (texcount - state.texcount,
1573 state.texids + state.texcount);
1574 for (i = state.texcount; i < texcount; ++i) {
1575 state.texowners[i].w = -1;
1576 state.texowners[i].slice = NULL;
1579 state.texcount = texcount;
1580 state.texindex = 0;
1583 static char *mbtoutf8 (char *s)
1585 char *p, *r;
1586 wchar_t *tmp;
1587 size_t i, ret, len;
1589 len = mbstowcs (NULL, s, strlen (s));
1590 if (len == 0) {
1591 return s;
1593 else {
1594 if (len == (size_t) -1) {
1595 return s;
1599 tmp = malloc (len * sizeof (wchar_t));
1600 if (!tmp) {
1601 return s;
1604 ret = mbstowcs (tmp, s, len);
1605 if (ret == (size_t) -1) {
1606 free (tmp);
1607 return s;
1610 len = 0;
1611 for (i = 0; i < ret; ++i) {
1612 len += fz_runelen (tmp[i]);
1615 p = r = malloc (len + 1);
1616 if (!r) {
1617 free (tmp);
1618 return s;
1621 for (i = 0; i < ret; ++i) {
1622 p += fz_runetochar (p, tmp[i]);
1624 *p = 0;
1625 free (tmp);
1626 return r;
1629 CAMLprim value ml_mbtoutf8 (value s_v)
1631 CAMLparam1 (s_v);
1632 CAMLlocal1 (ret_v);
1633 char *s, *r;
1635 s = String_val (s_v);
1636 r = mbtoutf8 (s);
1637 if (r == s) {
1638 ret_v = s_v;
1640 else {
1641 ret_v = caml_copy_string (r);
1642 free (r);
1644 CAMLreturn (ret_v);
1647 static void * mainloop (void *unused)
1649 char *p = NULL;
1650 int len, ret, oldlen = 0;
1652 for (;;) {
1653 len = readlen ();
1654 if (len == 0) {
1655 errx (1, "readlen returned 0");
1658 if (oldlen < len + 1) {
1659 p = realloc (p, len + 1);
1660 if (!p) {
1661 err (1, "realloc %d failed", len + 1);
1663 oldlen = len + 1;
1665 readdata (p, len);
1666 p[len] = 0;
1668 if (!strncmp ("open", p, 4)) {
1669 size_t filenamelen;
1670 int wthack, off;
1671 char *password;
1672 char *filename;
1673 char *utf8filename;
1675 ret = sscanf (p + 5, " %d %n", &wthack, &off);
1676 if (ret != 1) {
1677 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1680 filename = p + 5 + off;
1681 filenamelen = strlen (filename);
1682 password = filename + filenamelen + 1;
1684 lock ("open");
1685 openxref (filename, password);
1686 pdfinfo ();
1687 initpdims ();
1688 unlock ("open");
1690 if (!wthack) {
1691 utf8filename = mbtoutf8 (filename);
1692 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1693 if (utf8filename != filename) {
1694 free (utf8filename);
1697 state.needoutline = 1;
1699 else if (!strncmp ("cs", p, 2)) {
1700 int i, colorspace;
1702 ret = sscanf (p + 2, " %d", &colorspace);
1703 if (ret != 1) {
1704 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1706 lock ("cs");
1707 set_tex_params (colorspace);
1708 for (i = 0; i < state.texcount; ++i) {
1709 state.texowners[i].w = -1;
1710 state.texowners[i].slice = NULL;
1712 unlock ("cs");
1714 else if (!strncmp ("freepage", p, 8)) {
1715 void *ptr;
1717 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1718 if (ret != 1) {
1719 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1721 freepage (ptr);
1723 else if (!strncmp ("freetile", p, 8)) {
1724 void *ptr;
1726 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1727 if (ret != 1) {
1728 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1730 freetile (ptr);
1732 else if (!strncmp ("search", p, 6)) {
1733 int icase, pageno, y, ret, len2, forward;
1734 char *pattern;
1735 regex_t re;
1737 ret = sscanf (p + 6, " %d %d %d %d,%n",
1738 &icase, &pageno, &y, &forward, &len2);
1739 if (ret != 4) {
1740 errx (1, "malformed search `%s' ret=%d", p, ret);
1743 pattern = p + 6 + len2;
1744 ret = regcomp (&re, pattern,
1745 REG_EXTENDED | (icase ? REG_ICASE : 0));
1746 if (ret) {
1747 char errbuf[80];
1748 size_t size;
1750 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1751 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1753 else {
1754 search (&re, pageno, y, forward);
1755 regfree (&re);
1758 else if (!strncmp ("geometry", p, 8)) {
1759 int w, h;
1761 printd ("clear");
1762 ret = sscanf (p + 8, " %d %d", &w, &h);
1763 if (ret != 2) {
1764 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1767 lock ("geometry");
1768 state.h = h;
1769 if (w != state.w) {
1770 int i;
1771 state.w = w;
1772 for (i = 0; i < state.texcount; ++i) {
1773 state.texowners[i].slice = NULL;
1776 layout ();
1777 process_outline ();
1779 state.gen++;
1780 unlock ("geometry");
1781 printd ("continue %d", state.pagecount);
1783 else if (!strncmp ("reqlayout", p, 9)) {
1784 char *nameddest;
1785 int rotate, proportional, off;
1787 printd ("clear");
1788 ret = sscanf (p + 9, " %d %d %n", &rotate, &proportional, &off);
1789 if (ret != 2) {
1790 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1792 lock ("reqlayout");
1793 if (state.rotate != rotate || state.proportional != proportional) {
1794 state.gen += 1;
1796 state.rotate = rotate;
1797 state.proportional = proportional;
1798 layout ();
1799 process_outline ();
1801 nameddest = p + 9 + off;
1802 if (state.type == DPDF && nameddest && *nameddest) {
1803 struct anchor a;
1804 fz_link_dest dest;
1805 pdf_obj *needle, *obj;
1807 needle = pdf_new_string (state.ctx, nameddest,
1808 strlen (nameddest));
1809 obj = pdf_lookup_dest (state.u.pdf, needle);
1810 if (obj) {
1811 dest = pdf_parse_link_dest (state.u.pdf, obj);
1813 a = desttoanchor (&dest);
1814 if (a.n >= 0) {
1815 printd ("a %d %d %d", a.n, a.x, a.y);
1817 else {
1818 printd ("emsg failed to parse destination `%s'\n",
1819 nameddest);
1822 else {
1823 printd ("emsg destination `%s' not found\n",
1824 nameddest);
1826 pdf_drop_obj (needle);
1829 state.gen++;
1830 unlock ("reqlayout");
1831 printd ("continue %d", state.pagecount);
1833 else if (!strncmp ("page", p, 4)) {
1834 double a, b;
1835 struct page *page;
1836 int pageno, pindex, ret;
1838 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1839 if (ret != 2) {
1840 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1843 lock ("page");
1844 a = now ();
1845 page = loadpage (pageno, pindex);
1846 b = now ();
1847 unlock ("page");
1849 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1851 else if (!strncmp ("tile", p, 4)) {
1852 int x, y, w, h, ret;
1853 struct page *page;
1854 struct tile *tile;
1855 double a, b;
1856 void *data;
1858 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
1859 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
1860 if (ret != 6) {
1861 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1864 lock ("tile");
1865 a = now ();
1866 tile = rendertile (page, x, y, w, h, data);
1867 b = now ();
1868 unlock ("tile");
1870 printd ("tile %d %d %" FMT_ptr " %u %f",
1871 x, y,
1872 FMT_ptr_cast2 (tile),
1873 tile->w * tile->h * tile->pixmap->n,
1874 b - a);
1876 else if (!strncmp ("settrim", p, 7)) {
1877 int trimmargins;
1878 fz_irect fuzz;
1880 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1881 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1882 if (ret != 5) {
1883 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1885 printd ("clear");
1886 lock ("settrim");
1887 state.trimmargins = trimmargins;
1888 state.needoutline = 1;
1889 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1890 state.trimanew = 1;
1891 state.trimfuzz = fuzz;
1893 state.pagedimcount = 0;
1894 free (state.pagedims);
1895 state.pagedims = NULL;
1896 initpdims ();
1897 layout ();
1898 process_outline ();
1899 unlock ("settrim");
1900 printd ("continue %d", state.pagecount);
1902 else if (!strncmp ("sliceh", p, 6)) {
1903 int h;
1905 ret = sscanf (p + 6, " %d", &h);
1906 if (ret != 1) {
1907 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1909 if (h != state.sliceheight) {
1910 int i;
1912 state.sliceheight = h;
1913 for (i = 0; i < state.texcount; ++i) {
1914 state.texowners[i].w = -1;
1915 state.texowners[i].h = -1;
1916 state.texowners[i].slice = NULL;
1920 else if (!strncmp ("interrupt", p, 9)) {
1921 printd ("vmsg interrupted");
1923 else {
1924 errx (1, "unknown command %.*s", len, p);
1927 return 0;
1930 CAMLprim value ml_realloctexts (value texcount_v)
1932 CAMLparam1 (texcount_v);
1933 int ok;
1935 if (trylock ("ml_realloctexts")) {
1936 ok = 0;
1937 goto done;
1939 realloctexts (Int_val (texcount_v));
1940 ok = 1;
1941 unlock ("ml_realloctexts");
1943 done:
1944 CAMLreturn (Val_bool (ok));
1947 static void showsel (struct page *page, int ox, int oy)
1949 int seen = 0;
1950 fz_irect bbox;
1951 fz_rect rect;
1952 fz_text_line *line;
1953 fz_text_span *span;
1954 fz_text_block *block;
1955 struct mark first, last;
1957 first = page->fmark;
1958 last = page->lmark;
1960 if (!first.span || !last.span) return;
1962 glEnable (GL_BLEND);
1963 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1964 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1966 ox += state.pagedims[page->pdimno].bounds.x0;
1967 oy += state.pagedims[page->pdimno].bounds.y0;
1968 for (block = page->text->blocks;
1969 block < page->text->blocks + page->text->len;
1970 ++block) {
1971 for (line = block->lines;
1972 line < block->lines + block->len;
1973 ++line) {
1974 rect = fz_empty_rect;
1975 for (span = line->spans;
1976 span < line->spans + line->len;
1977 ++span) {
1978 int i, j, k;
1980 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1982 j = 0;
1983 k = span->len - 1;
1985 if (span == page->fmark.span && span == page->lmark.span) {
1986 seen = 1;
1987 j = MIN (first.i, last.i);
1988 k = MAX (first.i, last.i);
1990 else if (span == first.span) {
1991 seen = 1;
1992 j = first.i;
1994 else if (span == last.span) {
1995 seen = 1;
1996 k = last.i;
1999 if (seen) {
2000 for (i = j; i <= k; ++i) {
2001 fz_union_rect (&rect, &span->text[i].bbox);
2003 fz_round_rect (&bbox, &rect);
2004 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2005 bbox.x0,
2006 bbox.y0,
2007 bbox.x1,
2008 bbox.y1,
2009 oy, ox);
2011 glRecti (bbox.x0 + ox, bbox.y0 + oy,
2012 bbox.x1 + ox, bbox.y1 + oy);
2013 if (span == last.span) {
2014 goto done;
2020 done:
2021 glDisable (GL_BLEND);
2024 #include "glfont.c"
2026 static void highlightlinks (struct page *page, int xoff, int yoff)
2028 fz_matrix ctm, tm, pm;
2029 fz_link *link, *links;
2031 switch (page->type) {
2032 case DPDF:
2033 links = page->u.pdfpage->links;
2034 break;
2036 case DXPS:
2037 links = page->u.xpspage->links;
2038 break;
2040 default:
2041 return;
2044 glEnable (GL_TEXTURE_1D);
2045 glEnable (GL_BLEND);
2046 glBindTexture (GL_TEXTURE_1D, state.stid);
2048 xoff -= state.pagedims[page->pdimno].bounds.x0;
2049 yoff -= state.pagedims[page->pdimno].bounds.y0;
2050 fz_translate (&tm, xoff, yoff);
2051 pm = pagectm (page);
2052 fz_concat (&ctm, &pm, &tm);
2054 glBegin (GL_LINES);
2055 for (link = links; link; link = link->next) {
2056 fz_point p1, p2, p3, p4;
2058 p1.x = link->rect.x0;
2059 p1.y = link->rect.y0;
2061 p2.x = link->rect.x1;
2062 p2.y = link->rect.y0;
2064 p3.x = link->rect.x1;
2065 p3.y = link->rect.y1;
2067 p4.x = link->rect.x0;
2068 p4.y = link->rect.y1;
2070 fz_transform_point (&p1, &ctm);
2071 fz_transform_point (&p2, &ctm);
2072 fz_transform_point (&p3, &ctm);
2073 fz_transform_point (&p4, &ctm);
2075 switch (link->dest.kind) {
2076 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2077 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2078 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2079 default: glColor3ub (0, 0, 0); break;
2083 float w, h, s, t;
2085 w = p2.x - p1.x;
2086 h = p2.y - p1.y;
2087 t = sqrtf (w*w + h*h) * .25f;
2089 w = p3.x - p2.x;
2090 h = p3.y - p2.y;
2091 s = sqrtf (w*w + h*h) * .25f;
2093 glTexCoord1i (0);
2094 glVertex2f (p1.x, p1.y);
2095 glTexCoord1f (t);
2096 glVertex2f (p2.x, p2.y);
2098 glTexCoord1i (0);
2099 glVertex2f (p2.x, p2.y);
2100 glTexCoord1f (s);
2101 glVertex2f (p3.x, p3.y);
2103 glTexCoord1i (0);
2104 glVertex2f (p3.x, p3.y);
2105 glTexCoord1f (t);
2106 glVertex2f (p4.x, p4.y);
2108 glTexCoord1i (0);
2109 glVertex2f (p4.x, p4.y);
2110 glTexCoord1f (s);
2111 glVertex2f (p1.x, p1.y);
2114 glEnd ();
2116 glDisable (GL_BLEND);
2117 glDisable (GL_TEXTURE_1D);
2120 static int compareslinks (const void *l, const void *r)
2122 struct slink const *ls = l;
2123 struct slink const *rs = r;
2124 if (ls->bbox.y0 == rs->bbox.y0) {
2125 return rs->bbox.x0 - rs->bbox.x0;
2127 return ls->bbox.y0 - rs->bbox.y0;
2130 static void droptext (struct page *page)
2132 if (page->text) {
2133 fz_free_text_page (state.ctx, page->text);
2134 page->fmark.i = -1;
2135 page->lmark.i = -1;
2136 page->fmark.span = NULL;
2137 page->lmark.span = NULL;
2138 page->text = NULL;
2140 if (page->sheet) {
2141 fz_free_text_sheet (state.ctx, page->sheet);
2145 static void dropslinks (struct page *page)
2147 if (page->slinks) {
2148 free (page->slinks);
2149 page->slinks = NULL;
2150 page->slinkcount = 0;
2154 static void ensureslinks (struct page *page)
2156 fz_matrix ctm;
2157 int i, count = 0;
2158 size_t slinksize = sizeof (*page->slinks);
2159 fz_link *link, *links;
2161 if (state.gen != page->sgen) {
2162 dropslinks (page);
2163 page->sgen = state.gen;
2165 if (page->slinks) return;
2167 switch (page->type) {
2168 case DPDF:
2169 links = page->u.pdfpage->links;
2170 trimctm (page->u.pdfpage, page->pdimno);
2171 fz_concat (&ctm,
2172 &state.pagedims[page->pdimno].tctm,
2173 &state.pagedims[page->pdimno].ctm);
2174 break;
2176 case DXPS:
2177 links = page->u.xpspage->links;
2178 ctm = state.pagedims[page->pdimno].ctm;
2179 break;
2181 default:
2182 return;
2185 for (link = links; link; link = link->next) {
2186 count++;
2188 if (count > 0) {
2189 page->slinkcount = count;
2190 page->slinks = calloc (count, slinksize);
2191 if (!page->slinks) {
2192 err (1, "realloc slinks %d", count);
2195 for (i = 0, link = links; link; ++i, link = link->next) {
2196 fz_rect rect;
2198 rect = link->rect;
2199 fz_transform_rect (&rect, &ctm);
2200 page->slinks[i].link = link;
2201 fz_round_rect (&page->slinks[i].bbox, &rect);
2203 qsort (page->slinks, count, slinksize, compareslinks);
2207 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2208 static void fmt_linkn (char *s, unsigned int u)
2210 unsigned int len; unsigned int q;
2211 int zma = 'z' - 'a' + 1;
2212 len = 1; q = u;
2213 while (q > zma - 1) { ++len; q /= zma; }
2214 if (s) {
2215 s += len;
2216 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2217 /* handles u == 0 */
2219 s[len] = 0;
2222 static void highlightslinks (struct page *page, int xoff, int yoff,
2223 int noff, char *targ, int tlen, int hfsize)
2225 int i;
2226 char buf[40];
2227 struct slink *slink;
2228 double x0, y0, x1, y1, w;
2230 ensureslinks (page);
2231 glColor3ub (0xc3, 0xb0, 0x91);
2232 for (i = 0; i < page->slinkcount; ++i) {
2233 fmt_linkn (buf, i + noff);
2234 if (!tlen || !strncmp (targ, buf, tlen)) {
2235 slink = &page->slinks[i];
2237 x0 = slink->bbox.x0 + xoff - 5;
2238 y1 = slink->bbox.y0 + yoff - 5;
2239 y0 = y1 + 10 + hfsize;
2240 w = measure_string (state.face, hfsize, buf);
2241 x1 = x0 + w + 10;
2242 glRectd (x0, y0, x1, y1);
2246 glEnable (GL_BLEND);
2247 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2248 glEnable (GL_TEXTURE_2D);
2249 glColor3ub (0, 0, 0);
2250 for (i = 0; i < page->slinkcount; ++i) {
2251 fmt_linkn (buf, i + noff);
2252 if (!tlen || !strncmp (targ, buf, tlen)) {
2253 slink = &page->slinks[i];
2255 x0 = slink->bbox.x0 + xoff;
2256 y0 = slink->bbox.y0 + yoff + hfsize;
2257 draw_string (state.face, hfsize, x0, y0, buf);
2260 glDisable (GL_TEXTURE_2D);
2261 glDisable (GL_BLEND);
2265 static void uploadslice (struct tile *tile, struct slice *slice)
2267 int offset;
2268 struct slice *slice1;
2269 unsigned char *texdata;
2271 offset = 0;
2272 for (slice1 = tile->slices; slice != slice1; slice1++) {
2273 offset += slice1->h * tile->w * tile->pixmap->n;
2275 if (slice->texindex != -1 && slice->texindex < state.texcount
2276 && state.texowners[slice->texindex].slice == slice) {
2277 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2279 else {
2280 int subimage = 0;
2281 int texindex = state.texindex++ % state.texcount;
2283 if (state.texowners[texindex].w == tile->w) {
2284 if (state.texowners[texindex].h >= slice->h) {
2285 subimage = 1;
2287 else {
2288 state.texowners[texindex].h = slice->h;
2291 else {
2292 state.texowners[texindex].h = slice->h;
2295 state.texowners[texindex].w = tile->w;
2296 state.texowners[texindex].slice = slice;
2297 slice->texindex = texindex;
2299 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2300 if (tile->pbo) {
2301 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2302 texdata = 0;
2304 else {
2305 texdata = tile->pixmap->samples;
2307 if (subimage) {
2308 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2312 tile->w,
2313 slice->h,
2314 state.texform,
2315 state.texty,
2316 texdata+offset
2319 else {
2320 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2322 state.texiform,
2323 tile->w,
2324 slice->h,
2326 state.texform,
2327 state.texty,
2328 texdata+offset
2331 if (tile->pbo) {
2332 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2337 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2339 CAMLparam2 (args_v, ptr_v);
2340 int dispx = Int_val (Field (args_v, 0));
2341 int dispy = Int_val (Field (args_v, 1));
2342 int dispw = Int_val (Field (args_v, 2));
2343 int disph = Int_val (Field (args_v, 3));
2344 int tilex = Int_val (Field (args_v, 4));
2345 int tiley = Int_val (Field (args_v, 5));
2346 char *s = String_val (ptr_v);
2347 struct tile *tile = parse_pointer ("ml_drawtile", s);
2349 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2351 int slicey, firstslice;
2352 struct slice *slice;
2354 firstslice = tiley / tile->sliceheight;
2355 slice = &tile->slices[firstslice];
2356 slicey = tiley % tile->sliceheight;
2358 while (disph > 0) {
2359 int dh;
2361 dh = slice->h - slicey;
2362 dh = MIN (disph, dh);
2363 uploadslice (tile, slice);
2365 glBegin (GL_QUADS);
2367 glTexCoord2i (tilex, slicey);
2368 glVertex2i (dispx, dispy);
2370 glTexCoord2i (tilex+dispw, slicey);
2371 glVertex2i (dispx+dispw, dispy);
2373 glTexCoord2i (tilex+dispw, slicey+dh);
2374 glVertex2i (dispx+dispw, dispy+dh);
2376 glTexCoord2i (tilex, slicey+dh);
2377 glVertex2i (dispx, dispy+dh);
2379 glEnd ();
2381 dispy += dh;
2382 disph -= dh;
2383 slice++;
2384 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2385 slicey = 0;
2388 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2389 CAMLreturn (Val_unit);
2392 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2393 value xoff_v, value yoff_v,
2394 value li_v)
2396 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2397 int xoff = Int_val (xoff_v);
2398 int yoff = Int_val (yoff_v);
2399 int noff = Int_val (Field (li_v, 0));
2400 char *targ = String_val (Field (li_v, 1));
2401 int tlen = caml_string_length (Field (li_v, 1));
2402 int hfsize = Int_val (Field (li_v, 2));
2403 char *s = String_val (ptr_v);
2404 int hlmask = Int_val (hlinks_v);
2405 struct page *page = parse_pointer ("ml_postprocess", s);
2407 if (!page->u.ptr) {
2408 /* deal with loadpage failed pages */
2409 goto done;
2412 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2413 if (trylock ("ml_postprocess")) {
2414 noff = 0;
2415 goto done;
2417 if (hlmask & 2) {
2418 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2419 noff = page->slinkcount;
2421 showsel (page, xoff, yoff);
2422 unlock ("ml_postprocess");
2424 done:
2425 CAMLreturn (Val_int (noff));
2428 static fz_link *getlink (struct page *page, int x, int y)
2430 fz_point p;
2431 fz_matrix ctm;
2432 const fz_matrix *tctm;
2433 fz_link *link, *links;
2435 switch (page->type) {
2436 case DPDF:
2437 trimctm (page->u.pdfpage, page->pdimno);
2438 tctm = &state.pagedims[page->pdimno].tctm;
2439 links = page->u.pdfpage->links;
2440 break;
2442 case DXPS:
2443 tctm = &fz_identity;
2444 links = page->u.xpspage->links;
2445 break;
2447 default:
2448 return NULL;
2450 p.x = x;
2451 p.y = y;
2453 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2454 fz_invert_matrix (&ctm, &ctm);
2455 fz_transform_point (&p, &ctm);
2457 for (link = links; link; link = link->next) {
2458 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2459 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2460 return link;
2464 return NULL;
2467 static void ensuretext (struct page *page)
2469 if (state.gen != page->tgen) {
2470 droptext (page);
2471 page->tgen = state.gen;
2473 if (!page->text) {
2474 fz_matrix ctm;
2475 fz_device *tdev;
2477 page->text = fz_new_text_page (state.ctx, &fz_infinite_rect);
2478 page->sheet = fz_new_text_sheet (state.ctx);
2479 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2480 ctm = pagectm (page);
2481 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2482 qsort (page->text->blocks, page->text->len,
2483 sizeof (*page->text->blocks), compareblocks);
2484 fz_free_device (tdev);
2488 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2490 CAMLparam2 (start_page_v, dir_v);
2491 CAMLlocal1 (ret_v);
2492 int i, dir = Int_val (dir_v);
2493 int start_page = Int_val (start_page_v);
2494 int end_page = dir > 0 ? state.pagecount : -1;
2496 ret_v = Val_int (0);
2497 if (!(state.type == DPDF || state.type == DXPS)) {
2498 goto done;
2501 lock ("ml_findpage_with_links");
2502 for (i = start_page + dir; i != end_page; i += dir) {
2503 int found;
2505 switch (state.type) {
2506 case DPDF:
2508 pdf_page *page = NULL;
2510 fz_try (state.ctx) {
2511 page = pdf_load_page (state.u.pdf, i);
2512 found = !!page->links;
2514 fz_catch (state.ctx) {
2515 found = 0;
2517 if (page) {
2518 freepdfpage (page);
2521 break;
2522 case DXPS:
2524 xps_page *page = xps_load_page (state.u.xps, i);
2525 found = !!page->links;
2526 freexpspage (page);
2528 break;
2530 default:
2531 ARSERT ("invalid document type");
2534 if (found) {
2535 ret_v = caml_alloc_small (1, 1);
2536 Field (ret_v, 0) = Val_int (i);
2537 goto unlock;
2540 unlock:
2541 unlock ("ml_findpage_with_links");
2543 done:
2544 CAMLreturn (ret_v);
2547 enum { dir_first, dir_last};
2548 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2550 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2552 CAMLparam2 (ptr_v, dir_v);
2553 CAMLlocal2 (ret_v, pos_v);
2554 struct page *page;
2555 int dirtag, i, slinkindex;
2556 struct slink *found = NULL ,*slink;
2557 char *s = String_val (ptr_v);
2559 page = parse_pointer ("ml_findlink", s);
2560 ret_v = Val_int (0);
2561 if (trylock ("ml_findlink")) {
2562 goto done;
2565 ensureslinks (page);
2567 if (Is_block (dir_v)) {
2568 dirtag = Tag_val (dir_v);
2569 switch (dirtag) {
2570 case dir_first_visible:
2572 int x0, y0, dir, first_index, last_index;
2574 pos_v = Field (dir_v, 0);
2575 x0 = Int_val (Field (pos_v, 0));
2576 y0 = Int_val (Field (pos_v, 1));
2577 dir = Int_val (Field (pos_v, 2));
2579 if (dir >= 0) {
2580 dir = 1;
2581 first_index = 0;
2582 last_index = page->slinkcount;
2584 else {
2585 first_index = page->slinkcount - 1;
2586 last_index = -1;
2589 for (i = first_index; i != last_index; i += dir) {
2590 slink = &page->slinks[i];
2591 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2592 found = slink;
2593 break;
2597 break;
2599 case dir_left:
2600 slinkindex = Int_val (Field (dir_v, 0));
2601 found = &page->slinks[slinkindex];
2602 for (i = slinkindex - 1; i >= 0; --i) {
2603 slink = &page->slinks[i];
2604 if (slink->bbox.x0 < found->bbox.x0) {
2605 found = slink;
2606 break;
2609 break;
2611 case dir_right:
2612 slinkindex = Int_val (Field (dir_v, 0));
2613 found = &page->slinks[slinkindex];
2614 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2615 slink = &page->slinks[i];
2616 if (slink->bbox.x0 > found->bbox.x0) {
2617 found = slink;
2618 break;
2621 break;
2623 case dir_down:
2624 slinkindex = Int_val (Field (dir_v, 0));
2625 found = &page->slinks[slinkindex];
2626 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2627 slink = &page->slinks[i];
2628 if (slink->bbox.y0 >= found->bbox.y0) {
2629 found = slink;
2630 break;
2633 break;
2635 case dir_up:
2636 slinkindex = Int_val (Field (dir_v, 0));
2637 found = &page->slinks[slinkindex];
2638 for (i = slinkindex - 1; i >= 0; --i) {
2639 slink = &page->slinks[i];
2640 if (slink->bbox.y0 <= found->bbox.y0) {
2641 found = slink;
2642 break;
2645 break;
2648 else {
2649 dirtag = Int_val (dir_v);
2650 switch (dirtag) {
2651 case dir_first:
2652 found = page->slinks;
2653 break;
2655 case dir_last:
2656 if (page->slinks) {
2657 found = page->slinks + (page->slinkcount - 1);
2659 break;
2662 if (found) {
2663 ret_v = caml_alloc_small (2, 1);
2664 Field (ret_v, 0) = Val_int (found - page->slinks);
2667 unlock ("ml_findlink");
2668 done:
2669 CAMLreturn (ret_v);
2672 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2674 #define LINKTOVAL \
2676 int pageno; \
2678 switch (link->dest.kind) { \
2679 case FZ_LINK_GOTO: \
2681 fz_point p; \
2683 pageno = link->dest.ld.gotor.page; \
2684 p.x = 0; \
2685 p.y = 0; \
2687 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2688 p.y = link->dest.ld.gotor.lt.y; \
2689 fz_transform_point (&p, &pdim->lctm); \
2691 tup_v = caml_alloc_tuple (2); \
2692 ret_v = caml_alloc_small (1, ugoto); \
2693 Field (tup_v, 0) = Val_int (pageno); \
2694 Field (tup_v, 1) = Val_int (p.y); \
2695 Field (ret_v, 0) = tup_v; \
2697 break; \
2699 case FZ_LINK_URI: \
2700 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2701 ret_v = caml_alloc_small (1, uuri); \
2702 Field (ret_v, 0) = str_v; \
2703 break; \
2705 case FZ_LINK_LAUNCH: \
2706 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2707 ret_v = caml_alloc_small (1, ulaunch); \
2708 Field (ret_v, 0) = str_v; \
2709 break; \
2711 case FZ_LINK_NAMED: \
2712 str_v = caml_copy_string (link->dest.ld.named.named); \
2713 ret_v = caml_alloc_small (1, unamed); \
2714 Field (ret_v, 0) = str_v; \
2715 break; \
2717 case FZ_LINK_GOTOR: \
2718 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2719 pageno = link->dest.ld.gotor.page; \
2720 tup_v = caml_alloc_tuple (2); \
2721 ret_v = caml_alloc_small (1, uremote); \
2722 Field (tup_v, 0) = str_v; \
2723 Field (tup_v, 1) = Val_int (pageno); \
2724 Field (ret_v, 0) = tup_v; \
2725 break; \
2727 default: \
2729 char buf[80]; \
2731 snprintf (buf, sizeof (buf), \
2732 "unhandled link kind %d", link->dest.kind); \
2733 str_v = caml_copy_string (buf); \
2734 ret_v = caml_alloc_small (1, uunexpected); \
2735 Field (ret_v, 0) = str_v; \
2737 break; \
2741 CAMLprim value ml_getlink (value ptr_v, value n_v)
2743 CAMLparam2 (ptr_v, n_v);
2744 CAMLlocal3 (ret_v, tup_v, str_v);
2745 fz_link *link;
2746 struct page *page;
2747 struct pagedim *pdim;
2748 char *s = String_val (ptr_v);
2750 ret_v = Val_int (0);
2751 if (trylock ("ml_getlink")) {
2752 goto done;
2755 page = parse_pointer ("ml_getlink", s);
2756 ensureslinks (page);
2757 pdim = &state.pagedims[page->pdimno];
2758 link = page->slinks[Int_val (n_v)].link;
2759 LINKTOVAL;
2761 unlock ("ml_getlink");
2762 done:
2763 CAMLreturn (ret_v);
2766 CAMLprim value ml_getlinkcount (value ptr_v)
2768 CAMLparam1 (ptr_v);
2769 struct page *page;
2770 char *s = String_val (ptr_v);
2772 page = parse_pointer ("ml_getlinkcount", s);
2773 CAMLreturn (Val_int (page->slinkcount));
2776 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2778 CAMLparam2 (ptr_v, n_v);
2779 CAMLlocal1 (ret_v);
2780 struct page *page;
2781 struct slink *slink;
2782 char *s = String_val (ptr_v);
2784 page = parse_pointer ("ml_getlinkrect", s);
2785 ret_v = caml_alloc_tuple (4);
2786 if (trylock ("ml_getlinkrect")) {
2787 Field (ret_v, 0) = Val_int (0);
2788 Field (ret_v, 1) = Val_int (0);
2789 Field (ret_v, 2) = Val_int (0);
2790 Field (ret_v, 3) = Val_int (0);
2791 goto done;
2793 ensureslinks (page);
2795 slink = &page->slinks[Int_val (n_v)];
2796 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2797 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2798 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2799 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2800 unlock ("ml_getlinkrect");
2802 done:
2803 CAMLreturn (ret_v);
2806 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2808 CAMLparam3 (ptr_v, x_v, y_v);
2809 CAMLlocal3 (ret_v, tup_v, str_v);
2810 fz_link *link;
2811 struct page *page;
2812 char *s = String_val (ptr_v);
2813 int x = Int_val (x_v), y = Int_val (y_v);
2814 struct pagedim *pdim;
2816 ret_v = Val_int (0);
2817 if (trylock ("ml_whatsunder")) {
2818 goto done;
2821 page = parse_pointer ("ml_whatsunder", s);
2822 pdim = &state.pagedims[page->pdimno];
2823 x += pdim->bounds.x0;
2824 y += pdim->bounds.y0;
2825 link = getlink (page, x, y);
2826 if (link) {
2827 LINKTOVAL;
2829 else {
2830 fz_rect *b;
2831 fz_text_block *block;
2833 ensuretext (page);
2834 for (block = page->text->blocks;
2835 block < page->text->blocks + page->text->len;
2836 ++block) {
2837 fz_text_line *line;
2839 b = &block->bbox;
2840 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2841 continue;
2843 for (line = block->lines;
2844 line < block->lines + block->len;
2845 ++line) {
2846 fz_text_span *span;
2848 b = &line->bbox;
2849 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2850 continue;
2852 for (span = line->spans;
2853 span < line->spans + line->len;
2854 ++span) {
2855 fz_text_char *ch;
2857 b = &span->bbox;
2858 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2859 continue;
2861 for (ch = span->text; ch < span->text + span->len; ++ch) {
2862 b = &ch->bbox;
2864 if (x >= b->x0 && x <= b->x1
2865 && y >= b->y0 && y <= b->y1) {
2866 const char *n2 =
2867 span->style->font && span->style->font->name
2868 ? span->style->font->name
2869 : "Span has no font name"
2871 FT_FaceRec *face = span->style->font->ft_face;
2872 if (face && face->family_name) {
2873 char *s;
2874 char *n1 = face->family_name;
2875 size_t l1 = strlen (n1);
2876 size_t l2 = strlen (n2);
2878 if (l1 != l2 || memcmp (n1, n2, l1)) {
2879 s = malloc (l1 + l2 + 2);
2880 if (s) {
2881 memcpy (s, n2, l2);
2882 s[l2] = '=';
2883 memcpy (s + l2 + 1, n1, l1 + 1);
2884 str_v = caml_copy_string (s);
2885 free (s);
2889 if (str_v == 0) {
2890 str_v = caml_copy_string (n2);
2892 ret_v = caml_alloc_small (1, utext);
2893 Field (ret_v, 0) = str_v;
2894 goto unlock;
2901 unlock:
2902 unlock ("ml_whatsunder");
2904 done:
2905 CAMLreturn (ret_v);
2908 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2910 CAMLparam2 (ptr_v, rect_v);
2911 fz_rect *b;
2912 struct page *page;
2913 struct pagedim *pdim;
2914 int i, x0, x1, y0, y1;
2915 char *s = String_val (ptr_v);
2916 int fi = 0, li = 0;
2917 fz_text_block *block;
2918 fz_text_span *span, *fspan, *lspan;
2919 fz_text_line *line, *fline = NULL, *lline = NULL;
2921 if (trylock ("ml_seltext")) {
2922 goto done;
2925 page = parse_pointer ("ml_seltext", s);
2926 ensuretext (page);
2928 pdim = &state.pagedims[page->pdimno];
2929 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2930 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2931 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2932 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2934 if (0) {
2935 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2936 glColor3ub (128, 128, 128);
2937 glRecti (x0, y0, x1, y1);
2938 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2941 fspan = lspan = NULL;
2943 for (block = page->text->blocks;
2944 block < page->text->blocks + page->text->len;
2945 ++block) {
2946 for (line = block->lines;
2947 line < block->lines + block->len;
2948 ++line) {
2949 for (span = line->spans;
2950 span < line->spans + line->len;
2951 ++span) {
2952 for (i = 0; i < span->len; ++i) {
2953 b = &span->text[i].bbox;
2954 int selected = 0;
2956 if (x0 >= b->x0 && x0 <= b->x1
2957 && y0 >= b->y0 && y0 <= b->y1) {
2958 fspan = span;
2959 fline = line;
2960 fi = i;
2961 selected = 1;
2963 if (x1 >= b->x0 && x1 <= b->x1
2964 && y1 >= b->y0 && y1 <= b->y1) {
2965 lspan = span;
2966 lline = line;
2967 li = i;
2968 selected = 1;
2970 if (0 && selected) {
2971 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2972 glColor3ub (128, 128, 128);
2973 glRecti (b->x0, b->y0, b->x1, b->y1);
2974 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2980 if (y1 < y0 || x1 < x0) {
2981 int swap = 0;
2983 if (fspan == lspan) {
2984 swap = 1;
2986 else {
2987 if (y1 < y0) {
2988 if (fline != lline) {
2989 swap = 1;
2994 if (swap) {
2995 i = fi;
2996 span = fspan;
2998 fi = li;
2999 fspan = lspan;
3001 li = i;
3002 lspan = span;
3006 page->fmark.i = fi;
3007 page->fmark.span = fspan;
3009 page->lmark.i = li;
3010 page->lmark.span = lspan;
3012 unlock ("ml_seltext");
3014 done:
3015 CAMLreturn (Val_unit);
3018 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3020 char buf[4];
3021 int i, len, ret;
3023 for (i = a; i <= b; ++i) {
3024 len = fz_runetochar (buf, span->text[i].c);
3025 ret = fwrite (buf, len, 1, f);
3027 if (ret != 1) {
3028 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3029 len, ret, strerror (errno));
3030 return -1;
3033 return 0;
3036 #ifdef __CYGWIN__
3037 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3039 caml_failwith ("ml_popen not implemented under Cygwin");
3041 #else
3042 CAMLprim value ml_popen (value command_v, value fds_v)
3044 CAMLparam2 (command_v, fds_v);
3045 CAMLlocal2 (l_v, tup_v);
3046 int ret;
3047 char *msg = NULL;
3048 value earg_v = Nothing;
3049 posix_spawnattr_t attr;
3050 posix_spawn_file_actions_t fa;
3051 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
3053 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3054 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3057 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3058 msg = "posix_spawnattr_init";
3059 goto fail1;
3062 #ifdef POSIX_SPAWN_USEVFORK
3063 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3064 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3065 goto fail;
3067 #endif
3069 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3070 int fd1, fd2;
3072 tup_v = Field (l_v, 0);
3073 fd1 = Int_val (Field (tup_v, 0));
3074 fd2 = Int_val (Field (tup_v, 1));
3075 if (fd2 < 0) {
3076 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3077 msg = "posix_spawn_file_actions_addclose";
3078 earg_v = tup_v;
3079 goto fail;
3082 else {
3083 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3084 msg = "posix_spawn_file_actions_adddup2";
3085 earg_v = tup_v;
3086 goto fail;
3091 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3092 msg = "posix_spawn";
3093 goto fail;
3096 fail:
3097 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3098 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3101 fail1:
3102 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3103 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3104 strerror (ret));
3107 if (msg)
3108 unix_error (ret, msg, earg_v);
3110 CAMLreturn (Val_unit);
3112 #endif
3114 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3116 CAMLparam1 (ptr_v);
3117 FILE *f;
3118 int seen = 0;
3119 struct page *page;
3120 fz_text_line *line;
3121 fz_text_span *span;
3122 fz_text_block *block;
3123 int fd = Int_val (fd_v);
3124 char *s = String_val (ptr_v);
3126 if (trylock ("ml_copysel")) {
3127 goto done;
3130 page = parse_pointer ("ml_sopysel", s);
3132 if (!page->fmark.span || !page->lmark.span) {
3133 fprintf (stderr, "nothing to copy\n");
3134 goto unlock;
3137 f = fdopen (fd, "w");
3138 if (!f) {
3139 fprintf (stderr, "failed to fopen sel pipe: %s\n",
3140 strerror (errno));
3141 f = stdout;
3144 for (block = page->text->blocks;
3145 block < page->text->blocks + page->text->len;
3146 ++block) {
3147 for (line = block->lines;
3148 line < block->lines + block->len;
3149 ++line) {
3150 for (span = line->spans;
3151 span < line->spans + line->len;
3152 ++span) {
3153 int a, b;
3155 seen |= span == page->fmark.span || span == page->lmark.span;
3156 a = span == page->fmark.span ? page->fmark.i : 0;
3157 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3159 if (seen) {
3160 if (pipespan (f, span, a, b)) {
3161 goto close;
3163 if (span == line->spans + line->len - 1) {
3164 if (putc ('\n', f) == EOF) {
3165 fprintf (stderr,
3166 "failed break line on sel pipe: %s\n",
3167 strerror (errno));
3168 goto close;
3171 if (span == page->lmark.span) {
3172 goto endloop;
3178 endloop:
3179 page->lmark.span = NULL;
3180 page->fmark.span = NULL;
3182 close:
3183 if (f != stdout) {
3184 int ret = fclose (f);
3185 fd = -1;
3186 if (ret == -1) {
3187 if (errno != ECHILD) {
3188 fprintf (stderr, "failed to close sel pipe: %s\n",
3189 strerror (errno));
3193 unlock:
3194 unlock ("ml_copysel");
3196 done:
3197 if (fd >= 0) {
3198 if (close (fd)) {
3199 fprintf (stderr, "failed to close sel pipe: %s\n",
3200 strerror (errno));
3203 CAMLreturn (Val_unit);
3206 CAMLprim value ml_getpdimrect (value pagedimno_v)
3208 CAMLparam1 (pagedimno_v);
3209 CAMLlocal1 (ret_v);
3210 int pagedimno = Int_val (pagedimno_v);
3211 fz_rect box;
3213 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3214 if (trylock ("ml_getpdimrect")) {
3215 box = fz_empty_rect;
3217 else {
3218 box = state.pagedims[pagedimno].mediabox;
3219 unlock ("ml_getpdimrect");
3222 Store_double_field (ret_v, 0, box.x0);
3223 Store_double_field (ret_v, 1, box.x1);
3224 Store_double_field (ret_v, 2, box.y0);
3225 Store_double_field (ret_v, 3, box.y1);
3227 CAMLreturn (ret_v);
3230 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3231 value dw_v, value cols_v)
3233 CAMLparam3 (winw_v, winh_v, dw_v);
3234 CAMLlocal1 (ret_v);
3235 int i;
3236 double zoom = -1.;
3237 double maxh = 0.0;
3238 struct pagedim *p;
3239 double winw = Int_val (winw_v);
3240 double winh = Int_val (winh_v);
3241 double dw = Int_val (dw_v);
3242 double cols = Int_val (cols_v);
3243 double pw = 1.0, ph = 1.0;
3245 if (trylock ("ml_zoom_for_height")) {
3246 goto done;
3249 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3250 double w = p->pagebox.x1 / cols;
3251 double h = p->pagebox.y1;
3252 if (h > maxh) {
3253 maxh = h;
3254 ph = h;
3255 if (!state.proportional) pw = w;
3257 if (state.proportional && w > pw) pw = w;
3260 zoom = (((winh / ph) * pw) + dw) / winw;
3261 unlock ("ml_zoom_for_height");
3262 done:
3263 ret_v = caml_copy_double (zoom);
3264 CAMLreturn (ret_v);
3267 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3269 CAMLparam4 (pt_v, x_v, y_v, string_v);
3270 CAMLlocal1 (ret_v);
3271 int pt = Int_val(pt_v);
3272 int x = Int_val (x_v);
3273 int y = Int_val (y_v);
3274 double w;
3276 w = draw_string (state.face, pt, x, y, String_val (string_v));
3277 ret_v = caml_copy_double (w);
3278 CAMLreturn (ret_v);
3281 CAMLprim value ml_measure_string (value pt_v, value string_v)
3283 CAMLparam2 (pt_v, string_v);
3284 CAMLlocal1 (ret_v);
3285 int pt = Int_val (pt_v);
3286 double w;
3288 w = measure_string (state.face, pt, String_val (string_v));
3289 ret_v = caml_copy_double (w);
3290 CAMLreturn (ret_v);
3293 CAMLprim value ml_getpagebox (value opaque_v)
3295 CAMLparam1 (opaque_v);
3296 CAMLlocal1 (ret_v);
3297 fz_rect rect;
3298 fz_irect bbox;
3299 fz_matrix ctm;
3300 fz_device *dev;
3301 char *s = String_val (opaque_v);
3302 struct page *page = parse_pointer ("ml_getpagebox", s);
3304 ret_v = caml_alloc_tuple (4);
3305 dev = fz_new_bbox_device (state.ctx, &rect);
3306 dev->hints |= FZ_IGNORE_SHADE;
3308 switch (page->type) {
3309 case DPDF:
3310 ctm = pagectm (page);
3311 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3312 break;
3314 case DXPS:
3315 ctm = pagectm (page);
3316 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3317 break;
3319 default:
3320 rect = fz_infinite_rect;
3321 break;
3324 fz_free_device (dev);
3325 fz_round_rect (&bbox, &rect);
3326 Field (ret_v, 0) = Val_int (bbox.x0);
3327 Field (ret_v, 1) = Val_int (bbox.y0);
3328 Field (ret_v, 2) = Val_int (bbox.x1);
3329 Field (ret_v, 3) = Val_int (bbox.y1);
3331 CAMLreturn (ret_v);
3334 CAMLprim value ml_setaalevel (value level_v)
3336 CAMLparam1 (level_v);
3338 state.aalevel = Int_val (level_v);
3339 CAMLreturn (Val_unit);
3342 #undef pixel
3343 #include <X11/Xlib.h>
3344 #include <GL/glx.h>
3346 static struct {
3347 Display *dpy;
3348 GLXContext ctx;
3349 GLXDrawable drawable;
3350 } glx;
3352 #include "keysym2ucs.c"
3354 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3356 CAMLparam1 (keysym_v);
3357 CAMLlocal1 (str_v);
3358 KeySym keysym = Int_val (keysym_v);
3359 Rune rune;
3360 int len;
3361 char buf[5];
3363 rune = keysym2ucs (keysym);
3364 len = fz_runetochar (buf, rune);
3365 buf[len] = 0;
3366 str_v = caml_copy_string (buf);
3367 CAMLreturn (str_v);
3370 CAMLprim value ml_glx (value win_v)
3372 CAMLparam1 (win_v);
3373 XVisualInfo *visual;
3374 int screen, wid = Int_val (win_v);
3375 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3377 glx.dpy = XOpenDisplay (NULL);
3378 if (!glx.dpy) {
3379 caml_failwith ("XOpenDisplay");
3382 screen = DefaultScreen (glx.dpy);
3383 visual = glXChooseVisual (glx.dpy, screen, attributes);
3384 if (!visual) {
3385 XCloseDisplay (glx.dpy);
3386 glx.dpy = NULL;
3387 caml_failwith ("glXChooseVisual");
3390 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3391 XFree (visual);
3392 if (!glx.ctx) {
3393 XCloseDisplay (glx.dpy);
3394 glx.dpy = NULL;
3395 caml_failwith ("glXCreateContext");
3398 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3399 glXDestroyContext (glx.dpy, glx.ctx);
3400 XCloseDisplay (glx.dpy);
3401 glx.dpy = NULL;
3402 glx.ctx = NULL;
3403 caml_failwith ("glXMakeCurrent");
3405 glx.drawable = wid;
3406 CAMLreturn (Val_unit);
3409 CAMLprim value ml_swapb (value unit_v)
3411 CAMLparam1 (unit_v);
3412 glXSwapBuffers (glx.dpy, glx.drawable);
3413 CAMLreturn (Val_unit);
3416 CAMLprim value ml_glxsync (value unit_v)
3418 CAMLparam1 (unit_v);
3419 if (glx.dpy && glx.ctx) {
3420 glXWaitX ();
3421 glXWaitGL ();
3423 CAMLreturn (Val_unit);
3426 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3427 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3429 CAMLprim value ml_platform (value unit_v)
3431 CAMLparam1 (unit_v);
3432 int platid = piunknown;
3434 #if defined __linux__
3435 platid = pilinux;
3436 #elif defined __CYGWIN__
3437 platid = picygwin;
3438 #elif defined __DragonFly__
3439 platid = pidragonflybsd;
3440 #elif defined __FreeBSD__
3441 platid = pifreebsd;
3442 #elif defined __OpenBSD__
3443 platid = piopenbsd;
3444 #elif defined __NetBSD__
3445 platid = pinetbsd;
3446 #elif defined __sun__
3447 platid = pisun;
3448 #elif defined __APPLE__
3449 platid = piosx;
3450 #endif
3451 CAMLreturn (Val_int (platid));
3454 CAMLprim value ml_cloexec (value fd_v)
3456 CAMLparam1 (fd_v);
3457 int fd = Int_val (fd_v);
3459 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3460 uerror ("fcntl", Nothing);
3462 CAMLreturn (Val_unit);
3465 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3467 CAMLparam2 (w_v, h_v);
3468 CAMLlocal1 (ret_v);
3469 struct pbo *pbo;
3470 int w = Int_val (w_v);
3471 int h = Int_val (h_v);
3472 int cs = Int_val (cs_v);
3474 if (state.pbo_usable) {
3475 pbo = calloc (sizeof (*pbo), 1);
3476 if (!pbo) {
3477 err (1, "calloc pbo");
3480 switch (cs) {
3481 case 0:
3482 case 1:
3483 pbo->size = w*h*4;
3484 break;
3485 case 2:
3486 pbo->size = w*h*2;
3487 break;
3488 default:
3489 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3492 state.glGenBuffersARB (1, &pbo->id);
3493 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3494 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3495 NULL, GL_STREAM_DRAW);
3496 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3497 GL_READ_WRITE);
3498 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3499 if (!pbo->ptr) {
3500 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3501 state.glDeleteBuffersARB (1, &pbo->id);
3502 free (pbo);
3503 ret_v = caml_copy_string ("0");
3505 else {
3506 int res;
3507 char *s;
3509 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3510 if (res < 0) {
3511 err (1, "snprintf %" FMT_ptr " failed", pbo);
3513 s = malloc (res+1);
3514 if (!s) {
3515 err (1, "malloc %d bytes failed", res+1);
3517 res = sprintf (s, "%" FMT_ptr, pbo);
3518 if (res < 0) {
3519 err (1, "sprintf %" FMT_ptr " failed", pbo);
3521 ret_v = caml_copy_string (s);
3522 free (s);
3525 else {
3526 ret_v = caml_copy_string ("0");
3528 CAMLreturn (ret_v);
3531 CAMLprim value ml_freepbo (value s_v)
3533 CAMLparam1 (s_v);
3534 char *s = String_val (s_v);
3535 struct tile *tile = parse_pointer ("ml_freepbo", s);
3537 if (tile->pbo) {
3538 state.glDeleteBuffersARB (1, &tile->pbo->id);
3539 tile->pbo->id = -1;
3540 tile->pbo->ptr = NULL;
3541 tile->pbo->size = -1;
3543 CAMLreturn (Val_unit);
3546 CAMLprim value ml_unmappbo (value s_v)
3548 CAMLparam1 (s_v);
3549 char *s = String_val (s_v);
3550 struct tile *tile = parse_pointer ("ml_unmappbo", s);
3552 if (tile->pbo) {
3553 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3554 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3555 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3557 tile->pbo->ptr = NULL;
3558 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3560 CAMLreturn (Val_unit);
3563 static void setuppbo (void)
3565 #define GGPA(n) *(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n)
3566 GGPA (glBindBufferARB);
3567 if (state.glBindBufferARB) {
3568 GGPA (glUnmapBufferARB);
3569 if (state.glUnmapBufferARB) {
3570 GGPA (glMapBufferARB);
3571 if (state.glMapBufferARB) {
3572 GGPA (glBufferDataARB);
3573 if (state.glBufferDataARB) {
3574 GGPA (glGenBuffersARB);
3575 if (state.glGenBuffersARB) {
3576 GGPA (glDeleteBuffersARB);
3577 if (state.glDeleteBuffersARB) {
3578 state.pbo_usable = 1;
3585 #undef GGPA
3588 CAMLprim value ml_pbo_usable (value unit_v)
3590 CAMLparam1 (unit_v);
3591 CAMLreturn (Val_bool (state.pbo_usable));
3594 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3596 CAMLparam3 (ptr_v, x_v, y_v);
3597 CAMLlocal2 (ret_v, tup_v);
3598 struct page *page;
3599 char *s = String_val (ptr_v);
3600 int x = Int_val (x_v), y = Int_val (y_v);
3601 struct pagedim *pdim;
3602 fz_point p;
3603 fz_matrix ctm;
3605 page = parse_pointer ("ml_unproject", s);
3606 pdim = &state.pagedims[page->pdimno];
3608 ret_v = Val_int (0);
3609 if (trylock ("ml_unproject")) {
3610 goto done;
3613 switch (page->type) {
3614 case DPDF:
3615 trimctm (page->u.pdfpage, page->pdimno);
3616 break;
3618 default:
3619 break;
3621 p.x = x;
3622 p.y = y;
3624 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3625 fz_invert_matrix (&ctm, &ctm);
3626 fz_transform_point (&p, &ctm);
3628 tup_v = caml_alloc_tuple (2);
3629 ret_v = caml_alloc_small (1, 1);
3630 Field (tup_v, 0) = Val_int (p.x);
3631 Field (tup_v, 1) = Val_int (p.y);
3632 Field (ret_v, 0) = tup_v;
3634 unlock ("ml_unproject");
3635 done:
3636 CAMLreturn (ret_v);
3639 static void makestippletex (void)
3641 const char *pixels = "\xff\xff\0\0";
3642 glGenTextures (1, &state.stid);
3643 glBindTexture (GL_TEXTURE_1D, state.stid);
3644 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3645 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3646 glTexImage1D (
3647 GL_TEXTURE_1D,
3649 GL_ALPHA,
3652 GL_ALPHA,
3653 GL_UNSIGNED_BYTE,
3654 pixels
3658 CAMLprim value ml_init (value pipe_v, value params_v)
3660 CAMLparam2 (pipe_v, params_v);
3661 CAMLlocal2 (trim_v, fuzz_v);
3662 int ret;
3663 int texcount;
3664 char *fontpath;
3665 int colorspace;
3666 int mustoresize;
3667 int haspboext;
3668 struct sigaction sa;
3670 state.cr = Int_val (Field (pipe_v, 0));
3671 state.cw = Int_val (Field (pipe_v, 1));
3672 state.rotate = Int_val (Field (params_v, 0));
3673 state.proportional = Bool_val (Field (params_v, 1));
3674 trim_v = Field (params_v, 2);
3675 texcount = Int_val (Field (params_v, 3));
3676 state.sliceheight = Int_val (Field (params_v, 4));
3677 mustoresize = Int_val (Field (params_v, 5));
3678 colorspace = Int_val (Field (params_v, 6));
3679 fontpath = String_val (Field (params_v, 7));
3680 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
3681 if (!state.trimcachepath) {
3682 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
3683 strerror (errno));
3685 haspboext = Bool_val (Field (params_v, 9));
3687 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3689 state.trimmargins = Bool_val (Field (trim_v, 0));
3690 fuzz_v = Field (trim_v, 1);
3691 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3692 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3693 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3694 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3696 set_tex_params (colorspace);
3698 if (*fontpath) {
3699 state.face = load_font (fontpath);
3701 else {
3702 unsigned int len;
3703 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
3705 state.face = load_builtin_font (base, len);
3707 if (!state.face) _exit (1);
3709 realloctexts (texcount);
3711 if (haspboext) {
3712 setuppbo ();
3715 makestippletex ();
3716 #ifdef __CYGWIN__
3717 sa.sa_handler = SIG_IGN;
3718 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3719 #else
3720 sa.sa_handler = SIG_DFL;
3721 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
3722 #endif
3723 if (sigemptyset (&sa.sa_mask)) {
3724 err (1, "sigemptyset");
3726 if (sigaction (SIGCHLD, &sa, NULL)) {
3727 err (1, "sigaction");
3730 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3731 if (ret) {
3732 errx (1, "pthread_create: %s", strerror (ret));
3735 CAMLreturn (Val_unit);