Refactor
[llpp/slowscroll.git] / link.c
blobc178603f81f095e099bba49c7334ced39aec3423
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 double getmaxw (void)
1113 int i;
1114 struct pagedim *p;
1115 double maxw = 0.0;
1117 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
1118 fz_rect rect;
1119 fz_matrix rm;
1120 double x0, x1, w;
1122 fz_rotate (&rm, p->rotate + state.rotate);
1123 rect = p->mediabox;
1124 fz_transform_rect (&rect, &rm);
1126 x0 = MIN (rect.x0, rect.x1);
1127 x1 = MAX (rect.x0, rect.x1);
1129 w = x1 - x0;
1130 maxw = MAX (w, maxw);
1132 return maxw;
1135 static void layout (void)
1137 int pindex;
1138 fz_rect box;
1139 fz_matrix ctm;
1140 double zoom, w, maxw = 0;
1141 struct pagedim *p = state.pagedims;
1143 if (state.proportional) {
1144 maxw = getmaxw ();
1147 p = state.pagedims;
1148 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1149 fz_rect rect;
1150 fz_matrix tm, sm, rm;
1152 fz_rotate (&ctm, state.rotate);
1153 fz_rotate (&rm, p->rotate + state.rotate);
1154 box = p->mediabox;
1155 fz_transform_rect (&box, &rm);
1156 w = box.x1 - box.x0;
1158 if (state.proportional) {
1159 double scale = w / maxw;
1160 zoom = (state.w / w) * scale;
1162 else {
1163 zoom = state.w / w;
1166 fz_scale (&p->zoomctm, zoom, zoom);
1167 fz_concat (&ctm, &p->zoomctm, &ctm);
1169 fz_rotate (&rm, p->rotate);
1170 p->pagebox = p->mediabox;
1171 fz_transform_rect (&p->pagebox, &rm);
1172 p->pagebox.x1 -= p->pagebox.x0;
1173 p->pagebox.y1 -= p->pagebox.y0;
1174 p->pagebox.x0 = 0;
1175 p->pagebox.y0 = 0;
1176 rect = p->pagebox;
1177 fz_transform_rect (&rect, &ctm);
1178 fz_round_rect (&p->bounds, &rect);
1180 p->left = state.proportional ? ((maxw - w) * zoom) / 2.0 : 0;
1181 p->ctm = ctm;
1183 fz_translate (&tm, 0, -p->mediabox.y1);
1184 fz_scale (&sm, zoom, -zoom);
1185 fz_concat (&ctm, &tm, &sm);
1186 fz_concat (&p->lctm, &ctm, &rm);
1188 p->tctmready = 0;
1191 while (p-- != state.pagedims) {
1192 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1193 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1194 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1195 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1196 int w = x1 - x0;
1197 int h = y1 - y0;
1199 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1203 static
1204 struct anchor { int n; int x; int y; int w; int h; }
1205 desttoanchor (fz_link_dest *dest)
1207 int i;
1208 struct anchor a;
1209 struct pagedim *pdim = state.pagedims;
1211 a.n = -1;
1212 a.x = 0;
1213 a.y = 0;
1214 for (i = 0; i < state.pagedimcount; ++i) {
1215 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1216 break;
1217 pdim = &state.pagedims[i];
1219 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1220 fz_point p;
1221 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1222 p.x = dest->ld.gotor.lt.x;
1223 p.y = dest->ld.gotor.lt.y;
1224 fz_transform_point (&p, &pdim->lctm);
1225 a.y = p.y;
1226 a.x = p.x;
1228 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1229 double x0, x1, y0, y1;
1231 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1232 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1233 a.w = x1 - x0;
1234 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1235 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1236 a.h = y1 - y0;
1237 a.n = dest->ld.gotor.page;
1239 return a;
1242 static void recurse_outline (fz_outline *outline, int level)
1244 while (outline) {
1245 struct anchor a = desttoanchor (&outline->dest);
1247 if (a.n >= 0) {
1248 printd ("o %d %d %d %d %s",
1249 level, a.n, a.y, a.h, outline->title);
1251 if (outline->down) {
1252 recurse_outline (outline->down, level + 1);
1254 outline = outline->next;
1258 static void process_outline (void)
1260 fz_outline *outline;
1262 if (!state.needoutline) return;
1264 state.needoutline = 0;
1265 switch (state.type) {
1266 case DPDF:
1267 outline = pdf_load_outline (state.u.pdf);
1268 break;
1269 case DXPS:
1270 outline = xps_load_outline (state.u.xps);
1271 break;
1272 default:
1273 outline = NULL;
1274 break;
1276 if (outline) {
1277 recurse_outline (outline, 0);
1278 fz_free_outline (state.ctx, outline);
1282 static char *strofspan (fz_text_span *span)
1284 char *p;
1285 char utf8[10];
1286 fz_text_char *ch;
1287 size_t size = 0, cap = 80;
1289 p = malloc (cap + 1);
1290 if (!p) return NULL;
1292 for (ch = span->text; ch < span->text + span->len; ++ch) {
1293 int n = fz_runetochar (utf8, ch->c);
1294 if (size + n > cap) {
1295 cap *= 2;
1296 p = realloc (p, cap + 1);
1297 if (!p) return NULL;
1300 memcpy (p + size, utf8, n);
1301 size += n;
1303 p[size] = 0;
1304 return p;
1307 static int matchspan (regex_t *re, fz_text_span *span, fz_matrix ctm,
1308 int stop, int pageno, double start)
1310 int ret;
1311 char *p;
1312 regmatch_t rm;
1313 int a, b, c;
1314 fz_rect *sb, *eb;
1315 fz_point p1, p2, p3, p4;
1317 p = strofspan (span);
1318 if (!p) return -1;
1320 ret = regexec (re, p, 1, &rm, 0);
1321 if (ret) {
1322 free (p);
1323 if (ret != REG_NOMATCH) {
1324 size_t size;
1325 char errbuf[80];
1326 size = regerror (ret, re, errbuf, sizeof (errbuf));
1327 printd ("msg regexec error `%.*s'",
1328 (int) size, errbuf);
1329 return -1;
1331 return 0;
1333 else {
1334 int l = span->len;
1335 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1336 c += fz_runelen (span->text[a].c);
1338 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1339 c += fz_runelen (span->text[b].c);
1342 if (fz_runelen (span->text[b].c) > 1) {
1343 b = MAX (0, b-1);
1345 sb = &span->text[MIN (a, l-1)].bbox;
1346 eb = &span->text[MIN (b, l-1)].bbox;
1348 p1.x = sb->x0;
1349 p1.y = sb->y0;
1350 p2.x = eb->x1;
1351 p2.y = sb->y0;
1352 p3.x = eb->x1;
1353 p3.y = eb->y1;
1354 p4.x = sb->x0;
1355 p4.y = eb->y1;
1357 if (!stop) {
1358 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1359 pageno, 1,
1360 p1.x, p1.y,
1361 p2.x, p2.y,
1362 p3.x, p3.y,
1363 p4.x, p4.y);
1365 printd ("progress 1 found at %d `%.*s' in %f sec",
1366 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1367 now () - start);
1369 else {
1370 printd ("match %d %d %f %f %f %f %f %f %f %f",
1371 pageno, 2,
1372 p1.x, p1.y,
1373 p2.x, p2.y,
1374 p3.x, p3.y,
1375 p4.x, p4.y);
1377 free (p);
1378 return 1;
1382 static int compareblocks (const void *l, const void *r)
1384 fz_text_block const *ls = l;
1385 fz_text_block const* rs = r;
1386 return ls->bbox.y0 - rs->bbox.y0;
1389 /* wishful thinking function */
1390 static void search (regex_t *re, int pageno, int y, int forward)
1392 int i, j;
1393 fz_matrix ctm;
1394 fz_device *tdev;
1395 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1396 fz_text_page *text;
1397 fz_text_sheet *sheet;
1398 struct pagedim *pdim, *pdimprev;
1399 int stop = 0, niters = 0;
1400 double start, end;
1402 if (!(state.type == DPDF || state.type == DXPS))
1403 return;
1405 start = now ();
1406 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1407 if (niters++ == 5) {
1408 niters = 0;
1409 if (hasdata ()) {
1410 printd ("progress 1 attention requested aborting search at %d",
1411 pageno);
1412 stop = 1;
1414 else {
1415 printd ("progress %f searching in page %d",
1416 (double) (pageno + 1) / state.pagecount,
1417 pageno);
1420 pdimprev = NULL;
1421 for (i = 0; i < state.pagedimcount; ++i) {
1422 pdim = &state.pagedims[i];
1423 if (pdim->pageno == pageno) {
1424 goto found;
1426 if (pdim->pageno > pageno) {
1427 pdim = pdimprev;
1428 goto found;
1430 pdimprev = pdim;
1432 pdim = pdimprev;
1433 found:
1435 sheet = fz_new_text_sheet (state.ctx);
1436 text = fz_new_text_page (state.ctx, &fz_infinite_rect);
1437 tdev = fz_new_text_device (state.ctx, sheet, text);
1439 switch (state.type) {
1440 case DPDF:
1441 u.ptr = NULL;
1442 fz_try (state.ctx) {
1443 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1444 trimctm (u.pdfpage, pdim - state.pagedims);
1445 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1446 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1448 fz_catch (state.ctx) {
1449 fz_free_device (tdev);
1450 u.ptr = NULL;
1451 goto nextiter;
1453 break;
1455 case DXPS:
1456 u.xpspage = xps_load_page (state.u.xps, pageno);
1457 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1458 break;
1460 default:
1461 ARSERT (0 && state.type);
1464 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1465 fz_free_device (tdev);
1467 for (j = 0; j < text->len; ++j) {
1468 int k;
1469 fz_text_block *block;
1471 block = &text->blocks[forward ? j : text->len - 1 - j];
1473 for (k = 0; k < block->len; ++k) {
1474 fz_text_line *line;
1475 fz_text_span *span;
1477 if (forward) {
1478 line = &block->lines[k];
1479 if (line->bbox.y0 < y + 1) continue;
1481 else {
1482 line = &block->lines[block->len - 1 - k];
1483 if (line->bbox.y0 > y - 1) continue;
1486 for (span = line->spans;
1487 span < line->spans + line->len;
1488 ++span) {
1490 switch (matchspan (re, span, ctm, stop, pageno, start)) {
1491 case 0: break;
1492 case 1: stop = 1; break;
1493 case -1: stop = 1; goto endloop;
1498 nextiter:
1499 if (forward) {
1500 pageno += 1;
1501 y = 0;
1503 else {
1504 pageno -= 1;
1505 y = INT_MAX;
1507 endloop:
1508 fz_free_text_page (state.ctx, text);
1509 fz_free_text_sheet (state.ctx, sheet);
1510 if (u.ptr) {
1511 state.freepage (u.ptr);
1514 end = now ();
1515 if (!stop) {
1516 printd ("progress 1 no matches %f sec", end - start);
1518 printd ("clearrects");
1521 static void set_tex_params (int colorspace)
1523 union {
1524 unsigned char b;
1525 unsigned int s;
1526 } endianness = {1};
1528 switch (colorspace) {
1529 case 0:
1530 state.texiform = GL_RGBA8;
1531 state.texform = GL_RGBA;
1532 state.texty = GL_UNSIGNED_BYTE;
1533 state.colorspace = fz_device_rgb;
1534 break;
1535 case 1:
1536 state.texiform = GL_RGBA8;
1537 state.texform = GL_BGRA;
1538 state.texty = endianness.s > 1
1539 ? GL_UNSIGNED_INT_8_8_8_8
1540 : GL_UNSIGNED_INT_8_8_8_8_REV;
1541 state.colorspace = fz_device_bgr;
1542 break;
1543 case 2:
1544 state.texiform = GL_LUMINANCE_ALPHA;
1545 state.texform = GL_LUMINANCE_ALPHA;
1546 state.texty = GL_UNSIGNED_BYTE;
1547 state.colorspace = fz_device_gray;
1548 break;
1549 default:
1550 errx (1, "invalid colorspce %d", colorspace);
1554 static void realloctexts (int texcount)
1556 size_t size;
1558 if (texcount == state.texcount) return;
1560 if (texcount < state.texcount) {
1561 glDeleteTextures (state.texcount - texcount,
1562 state.texids + texcount);
1565 size = texcount * sizeof (*state.texids);
1566 state.texids = realloc (state.texids, size);
1567 if (!state.texids) {
1568 err (1, "realloc texids %" FMT_s, size);
1571 size = texcount * sizeof (*state.texowners);
1572 state.texowners = realloc (state.texowners, size);
1573 if (!state.texowners) {
1574 err (1, "realloc texowners %" FMT_s, size);
1576 if (texcount > state.texcount) {
1577 int i;
1579 glGenTextures (texcount - state.texcount,
1580 state.texids + state.texcount);
1581 for (i = state.texcount; i < texcount; ++i) {
1582 state.texowners[i].w = -1;
1583 state.texowners[i].slice = NULL;
1586 state.texcount = texcount;
1587 state.texindex = 0;
1590 static char *mbtoutf8 (char *s)
1592 char *p, *r;
1593 wchar_t *tmp;
1594 size_t i, ret, len;
1596 len = mbstowcs (NULL, s, strlen (s));
1597 if (len == 0) {
1598 return s;
1600 else {
1601 if (len == (size_t) -1) {
1602 return s;
1606 tmp = malloc (len * sizeof (wchar_t));
1607 if (!tmp) {
1608 return s;
1611 ret = mbstowcs (tmp, s, len);
1612 if (ret == (size_t) -1) {
1613 free (tmp);
1614 return s;
1617 len = 0;
1618 for (i = 0; i < ret; ++i) {
1619 len += fz_runelen (tmp[i]);
1622 p = r = malloc (len + 1);
1623 if (!r) {
1624 free (tmp);
1625 return s;
1628 for (i = 0; i < ret; ++i) {
1629 p += fz_runetochar (p, tmp[i]);
1631 *p = 0;
1632 free (tmp);
1633 return r;
1636 CAMLprim value ml_mbtoutf8 (value s_v)
1638 CAMLparam1 (s_v);
1639 CAMLlocal1 (ret_v);
1640 char *s, *r;
1642 s = String_val (s_v);
1643 r = mbtoutf8 (s);
1644 if (r == s) {
1645 ret_v = s_v;
1647 else {
1648 ret_v = caml_copy_string (r);
1649 free (r);
1651 CAMLreturn (ret_v);
1654 static void * mainloop (void *unused)
1656 char *p = NULL;
1657 int len, ret, oldlen = 0;
1659 for (;;) {
1660 len = readlen ();
1661 if (len == 0) {
1662 errx (1, "readlen returned 0");
1665 if (oldlen < len + 1) {
1666 p = realloc (p, len + 1);
1667 if (!p) {
1668 err (1, "realloc %d failed", len + 1);
1670 oldlen = len + 1;
1672 readdata (p, len);
1673 p[len] = 0;
1675 if (!strncmp ("open", p, 4)) {
1676 size_t filenamelen;
1677 int wthack, off;
1678 char *password;
1679 char *filename;
1680 char *utf8filename;
1682 ret = sscanf (p + 5, " %d %n", &wthack, &off);
1683 if (ret != 1) {
1684 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1687 filename = p + 5 + off;
1688 filenamelen = strlen (filename);
1689 password = filename + filenamelen + 1;
1691 lock ("open");
1692 openxref (filename, password);
1693 pdfinfo ();
1694 initpdims ();
1695 unlock ("open");
1697 if (!wthack) {
1698 utf8filename = mbtoutf8 (filename);
1699 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1700 if (utf8filename != filename) {
1701 free (utf8filename);
1704 state.needoutline = 1;
1706 else if (!strncmp ("cs", p, 2)) {
1707 int i, colorspace;
1709 ret = sscanf (p + 2, " %d", &colorspace);
1710 if (ret != 1) {
1711 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1713 lock ("cs");
1714 set_tex_params (colorspace);
1715 for (i = 0; i < state.texcount; ++i) {
1716 state.texowners[i].w = -1;
1717 state.texowners[i].slice = NULL;
1719 unlock ("cs");
1721 else if (!strncmp ("freepage", p, 8)) {
1722 void *ptr;
1724 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1725 if (ret != 1) {
1726 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1728 freepage (ptr);
1730 else if (!strncmp ("freetile", p, 8)) {
1731 void *ptr;
1733 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1734 if (ret != 1) {
1735 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1737 freetile (ptr);
1739 else if (!strncmp ("search", p, 6)) {
1740 int icase, pageno, y, ret, len2, forward;
1741 char *pattern;
1742 regex_t re;
1744 ret = sscanf (p + 6, " %d %d %d %d,%n",
1745 &icase, &pageno, &y, &forward, &len2);
1746 if (ret != 4) {
1747 errx (1, "malformed search `%s' ret=%d", p, ret);
1750 pattern = p + 6 + len2;
1751 ret = regcomp (&re, pattern,
1752 REG_EXTENDED | (icase ? REG_ICASE : 0));
1753 if (ret) {
1754 char errbuf[80];
1755 size_t size;
1757 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1758 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1760 else {
1761 search (&re, pageno, y, forward);
1762 regfree (&re);
1765 else if (!strncmp ("geometry", p, 8)) {
1766 int w, h;
1768 printd ("clear");
1769 ret = sscanf (p + 8, " %d %d", &w, &h);
1770 if (ret != 2) {
1771 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1774 lock ("geometry");
1775 state.h = h;
1776 if (w != state.w) {
1777 int i;
1778 state.w = w;
1779 for (i = 0; i < state.texcount; ++i) {
1780 state.texowners[i].slice = NULL;
1783 layout ();
1784 process_outline ();
1786 state.gen++;
1787 unlock ("geometry");
1788 printd ("continue %d", state.pagecount);
1790 else if (!strncmp ("reqlayout", p, 9)) {
1791 char *nameddest;
1792 int rotate, proportional, off;
1794 printd ("clear");
1795 ret = sscanf (p + 9, " %d %d %n", &rotate, &proportional, &off);
1796 if (ret != 2) {
1797 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1799 lock ("reqlayout");
1800 if (state.rotate != rotate || state.proportional != proportional) {
1801 state.gen += 1;
1803 state.rotate = rotate;
1804 state.proportional = proportional;
1805 layout ();
1806 process_outline ();
1808 nameddest = p + 9 + off;
1809 if (state.type == DPDF && nameddest && *nameddest) {
1810 struct anchor a;
1811 fz_link_dest dest;
1812 pdf_obj *needle, *obj;
1814 needle = pdf_new_string (state.ctx, nameddest,
1815 strlen (nameddest));
1816 obj = pdf_lookup_dest (state.u.pdf, needle);
1817 if (obj) {
1818 dest = pdf_parse_link_dest (state.u.pdf, obj);
1820 a = desttoanchor (&dest);
1821 if (a.n >= 0) {
1822 printd ("a %d %d %d", a.n, a.x, a.y);
1824 else {
1825 printd ("emsg failed to parse destination `%s'\n",
1826 nameddest);
1829 else {
1830 printd ("emsg destination `%s' not found\n",
1831 nameddest);
1833 pdf_drop_obj (needle);
1836 state.gen++;
1837 unlock ("reqlayout");
1838 printd ("continue %d", state.pagecount);
1840 else if (!strncmp ("page", p, 4)) {
1841 double a, b;
1842 struct page *page;
1843 int pageno, pindex, ret;
1845 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1846 if (ret != 2) {
1847 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1850 lock ("page");
1851 a = now ();
1852 page = loadpage (pageno, pindex);
1853 b = now ();
1854 unlock ("page");
1856 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1858 else if (!strncmp ("tile", p, 4)) {
1859 int x, y, w, h, ret;
1860 struct page *page;
1861 struct tile *tile;
1862 double a, b;
1863 void *data;
1865 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
1866 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
1867 if (ret != 6) {
1868 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1871 lock ("tile");
1872 a = now ();
1873 tile = rendertile (page, x, y, w, h, data);
1874 b = now ();
1875 unlock ("tile");
1877 printd ("tile %d %d %" FMT_ptr " %u %f",
1878 x, y,
1879 FMT_ptr_cast2 (tile),
1880 tile->w * tile->h * tile->pixmap->n,
1881 b - a);
1883 else if (!strncmp ("settrim", p, 7)) {
1884 int trimmargins;
1885 fz_irect fuzz;
1887 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1888 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1889 if (ret != 5) {
1890 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1892 printd ("clear");
1893 lock ("settrim");
1894 state.trimmargins = trimmargins;
1895 state.needoutline = 1;
1896 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1897 state.trimanew = 1;
1898 state.trimfuzz = fuzz;
1900 state.pagedimcount = 0;
1901 free (state.pagedims);
1902 state.pagedims = NULL;
1903 initpdims ();
1904 layout ();
1905 process_outline ();
1906 unlock ("settrim");
1907 printd ("continue %d", state.pagecount);
1909 else if (!strncmp ("sliceh", p, 6)) {
1910 int h;
1912 ret = sscanf (p + 6, " %d", &h);
1913 if (ret != 1) {
1914 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1916 if (h != state.sliceheight) {
1917 int i;
1919 state.sliceheight = h;
1920 for (i = 0; i < state.texcount; ++i) {
1921 state.texowners[i].w = -1;
1922 state.texowners[i].h = -1;
1923 state.texowners[i].slice = NULL;
1927 else if (!strncmp ("interrupt", p, 9)) {
1928 printd ("vmsg interrupted");
1930 else {
1931 errx (1, "unknown command %.*s", len, p);
1934 return 0;
1937 CAMLprim value ml_realloctexts (value texcount_v)
1939 CAMLparam1 (texcount_v);
1940 int ok;
1942 if (trylock ("ml_realloctexts")) {
1943 ok = 0;
1944 goto done;
1946 realloctexts (Int_val (texcount_v));
1947 ok = 1;
1948 unlock ("ml_realloctexts");
1950 done:
1951 CAMLreturn (Val_bool (ok));
1954 static void showsel (struct page *page, int ox, int oy)
1956 int seen = 0;
1957 fz_irect bbox;
1958 fz_rect rect;
1959 fz_text_line *line;
1960 fz_text_span *span;
1961 fz_text_block *block;
1962 struct mark first, last;
1964 first = page->fmark;
1965 last = page->lmark;
1967 if (!first.span || !last.span) return;
1969 glEnable (GL_BLEND);
1970 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1971 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1973 ox += state.pagedims[page->pdimno].bounds.x0;
1974 oy += state.pagedims[page->pdimno].bounds.y0;
1975 for (block = page->text->blocks;
1976 block < page->text->blocks + page->text->len;
1977 ++block) {
1978 for (line = block->lines;
1979 line < block->lines + block->len;
1980 ++line) {
1981 rect = fz_empty_rect;
1982 for (span = line->spans;
1983 span < line->spans + line->len;
1984 ++span) {
1985 int i, j, k;
1987 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1989 j = 0;
1990 k = span->len - 1;
1992 if (span == page->fmark.span && span == page->lmark.span) {
1993 seen = 1;
1994 j = MIN (first.i, last.i);
1995 k = MAX (first.i, last.i);
1997 else if (span == first.span) {
1998 seen = 1;
1999 j = first.i;
2001 else if (span == last.span) {
2002 seen = 1;
2003 k = last.i;
2006 if (seen) {
2007 for (i = j; i <= k; ++i) {
2008 fz_union_rect (&rect, &span->text[i].bbox);
2010 fz_round_rect (&bbox, &rect);
2011 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2012 bbox.x0,
2013 bbox.y0,
2014 bbox.x1,
2015 bbox.y1,
2016 oy, ox);
2018 glRecti (bbox.x0 + ox, bbox.y0 + oy,
2019 bbox.x1 + ox, bbox.y1 + oy);
2020 if (span == last.span) {
2021 goto done;
2027 done:
2028 glDisable (GL_BLEND);
2031 #include "glfont.c"
2033 static void highlightlinks (struct page *page, int xoff, int yoff)
2035 fz_matrix ctm, tm, pm;
2036 fz_link *link, *links;
2038 switch (page->type) {
2039 case DPDF:
2040 links = page->u.pdfpage->links;
2041 break;
2043 case DXPS:
2044 links = page->u.xpspage->links;
2045 break;
2047 default:
2048 return;
2051 glEnable (GL_TEXTURE_1D);
2052 glEnable (GL_BLEND);
2053 glBindTexture (GL_TEXTURE_1D, state.stid);
2055 xoff -= state.pagedims[page->pdimno].bounds.x0;
2056 yoff -= state.pagedims[page->pdimno].bounds.y0;
2057 fz_translate (&tm, xoff, yoff);
2058 pm = pagectm (page);
2059 fz_concat (&ctm, &pm, &tm);
2061 glBegin (GL_LINES);
2062 for (link = links; link; link = link->next) {
2063 fz_point p1, p2, p3, p4;
2065 p1.x = link->rect.x0;
2066 p1.y = link->rect.y0;
2068 p2.x = link->rect.x1;
2069 p2.y = link->rect.y0;
2071 p3.x = link->rect.x1;
2072 p3.y = link->rect.y1;
2074 p4.x = link->rect.x0;
2075 p4.y = link->rect.y1;
2077 fz_transform_point (&p1, &ctm);
2078 fz_transform_point (&p2, &ctm);
2079 fz_transform_point (&p3, &ctm);
2080 fz_transform_point (&p4, &ctm);
2082 switch (link->dest.kind) {
2083 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2084 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2085 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2086 default: glColor3ub (0, 0, 0); break;
2090 float w, h, s, t;
2092 w = p2.x - p1.x;
2093 h = p2.y - p1.y;
2094 t = sqrtf (w*w + h*h) * .25f;
2096 w = p3.x - p2.x;
2097 h = p3.y - p2.y;
2098 s = sqrtf (w*w + h*h) * .25f;
2100 glTexCoord1i (0);
2101 glVertex2f (p1.x, p1.y);
2102 glTexCoord1f (t);
2103 glVertex2f (p2.x, p2.y);
2105 glTexCoord1i (0);
2106 glVertex2f (p2.x, p2.y);
2107 glTexCoord1f (s);
2108 glVertex2f (p3.x, p3.y);
2110 glTexCoord1i (0);
2111 glVertex2f (p3.x, p3.y);
2112 glTexCoord1f (t);
2113 glVertex2f (p4.x, p4.y);
2115 glTexCoord1i (0);
2116 glVertex2f (p4.x, p4.y);
2117 glTexCoord1f (s);
2118 glVertex2f (p1.x, p1.y);
2121 glEnd ();
2123 glDisable (GL_BLEND);
2124 glDisable (GL_TEXTURE_1D);
2127 static int compareslinks (const void *l, const void *r)
2129 struct slink const *ls = l;
2130 struct slink const *rs = r;
2131 if (ls->bbox.y0 == rs->bbox.y0) {
2132 return rs->bbox.x0 - rs->bbox.x0;
2134 return ls->bbox.y0 - rs->bbox.y0;
2137 static void droptext (struct page *page)
2139 if (page->text) {
2140 fz_free_text_page (state.ctx, page->text);
2141 page->fmark.i = -1;
2142 page->lmark.i = -1;
2143 page->fmark.span = NULL;
2144 page->lmark.span = NULL;
2145 page->text = NULL;
2147 if (page->sheet) {
2148 fz_free_text_sheet (state.ctx, page->sheet);
2152 static void dropslinks (struct page *page)
2154 if (page->slinks) {
2155 free (page->slinks);
2156 page->slinks = NULL;
2157 page->slinkcount = 0;
2161 static void ensureslinks (struct page *page)
2163 fz_matrix ctm;
2164 int i, count = 0;
2165 size_t slinksize = sizeof (*page->slinks);
2166 fz_link *link, *links;
2168 if (state.gen != page->sgen) {
2169 dropslinks (page);
2170 page->sgen = state.gen;
2172 if (page->slinks) return;
2174 switch (page->type) {
2175 case DPDF:
2176 links = page->u.pdfpage->links;
2177 trimctm (page->u.pdfpage, page->pdimno);
2178 fz_concat (&ctm,
2179 &state.pagedims[page->pdimno].tctm,
2180 &state.pagedims[page->pdimno].ctm);
2181 break;
2183 case DXPS:
2184 links = page->u.xpspage->links;
2185 ctm = state.pagedims[page->pdimno].ctm;
2186 break;
2188 default:
2189 return;
2192 for (link = links; link; link = link->next) {
2193 count++;
2195 if (count > 0) {
2196 page->slinkcount = count;
2197 page->slinks = calloc (count, slinksize);
2198 if (!page->slinks) {
2199 err (1, "realloc slinks %d", count);
2202 for (i = 0, link = links; link; ++i, link = link->next) {
2203 fz_rect rect;
2205 rect = link->rect;
2206 fz_transform_rect (&rect, &ctm);
2207 page->slinks[i].link = link;
2208 fz_round_rect (&page->slinks[i].bbox, &rect);
2210 qsort (page->slinks, count, slinksize, compareslinks);
2214 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2215 static void fmt_linkn (char *s, unsigned int u)
2217 unsigned int len; unsigned int q;
2218 int zma = 'z' - 'a' + 1;
2219 len = 1; q = u;
2220 while (q > zma - 1) { ++len; q /= zma; }
2221 if (s) {
2222 s += len;
2223 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2224 /* handles u == 0 */
2226 s[len] = 0;
2229 static void highlightslinks (struct page *page, int xoff, int yoff,
2230 int noff, char *targ, int tlen, int hfsize)
2232 int i;
2233 char buf[40];
2234 struct slink *slink;
2235 double x0, y0, x1, y1, w;
2237 ensureslinks (page);
2238 glColor3ub (0xc3, 0xb0, 0x91);
2239 for (i = 0; i < page->slinkcount; ++i) {
2240 fmt_linkn (buf, i + noff);
2241 if (!tlen || !strncmp (targ, buf, tlen)) {
2242 slink = &page->slinks[i];
2244 x0 = slink->bbox.x0 + xoff - 5;
2245 y1 = slink->bbox.y0 + yoff - 5;
2246 y0 = y1 + 10 + hfsize;
2247 w = measure_string (state.face, hfsize, buf);
2248 x1 = x0 + w + 10;
2249 glRectd (x0, y0, x1, y1);
2253 glEnable (GL_BLEND);
2254 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2255 glEnable (GL_TEXTURE_2D);
2256 glColor3ub (0, 0, 0);
2257 for (i = 0; i < page->slinkcount; ++i) {
2258 fmt_linkn (buf, i + noff);
2259 if (!tlen || !strncmp (targ, buf, tlen)) {
2260 slink = &page->slinks[i];
2262 x0 = slink->bbox.x0 + xoff;
2263 y0 = slink->bbox.y0 + yoff + hfsize;
2264 draw_string (state.face, hfsize, x0, y0, buf);
2267 glDisable (GL_TEXTURE_2D);
2268 glDisable (GL_BLEND);
2272 static void uploadslice (struct tile *tile, struct slice *slice)
2274 int offset;
2275 struct slice *slice1;
2276 unsigned char *texdata;
2278 offset = 0;
2279 for (slice1 = tile->slices; slice != slice1; slice1++) {
2280 offset += slice1->h * tile->w * tile->pixmap->n;
2282 if (slice->texindex != -1 && slice->texindex < state.texcount
2283 && state.texowners[slice->texindex].slice == slice) {
2284 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2286 else {
2287 int subimage = 0;
2288 int texindex = state.texindex++ % state.texcount;
2290 if (state.texowners[texindex].w == tile->w) {
2291 if (state.texowners[texindex].h >= slice->h) {
2292 subimage = 1;
2294 else {
2295 state.texowners[texindex].h = slice->h;
2298 else {
2299 state.texowners[texindex].h = slice->h;
2302 state.texowners[texindex].w = tile->w;
2303 state.texowners[texindex].slice = slice;
2304 slice->texindex = texindex;
2306 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2307 if (tile->pbo) {
2308 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2309 texdata = 0;
2311 else {
2312 texdata = tile->pixmap->samples;
2314 if (subimage) {
2315 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2319 tile->w,
2320 slice->h,
2321 state.texform,
2322 state.texty,
2323 texdata+offset
2326 else {
2327 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2329 state.texiform,
2330 tile->w,
2331 slice->h,
2333 state.texform,
2334 state.texty,
2335 texdata+offset
2338 if (tile->pbo) {
2339 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2344 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2346 CAMLparam2 (args_v, ptr_v);
2347 int dispx = Int_val (Field (args_v, 0));
2348 int dispy = Int_val (Field (args_v, 1));
2349 int dispw = Int_val (Field (args_v, 2));
2350 int disph = Int_val (Field (args_v, 3));
2351 int tilex = Int_val (Field (args_v, 4));
2352 int tiley = Int_val (Field (args_v, 5));
2353 char *s = String_val (ptr_v);
2354 struct tile *tile = parse_pointer ("ml_drawtile", s);
2356 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2358 int slicey, firstslice;
2359 struct slice *slice;
2361 firstslice = tiley / tile->sliceheight;
2362 slice = &tile->slices[firstslice];
2363 slicey = tiley % tile->sliceheight;
2365 while (disph > 0) {
2366 int dh;
2368 dh = slice->h - slicey;
2369 dh = MIN (disph, dh);
2370 uploadslice (tile, slice);
2372 glBegin (GL_QUADS);
2374 glTexCoord2i (tilex, slicey);
2375 glVertex2i (dispx, dispy);
2377 glTexCoord2i (tilex+dispw, slicey);
2378 glVertex2i (dispx+dispw, dispy);
2380 glTexCoord2i (tilex+dispw, slicey+dh);
2381 glVertex2i (dispx+dispw, dispy+dh);
2383 glTexCoord2i (tilex, slicey+dh);
2384 glVertex2i (dispx, dispy+dh);
2386 glEnd ();
2388 dispy += dh;
2389 disph -= dh;
2390 slice++;
2391 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2392 slicey = 0;
2395 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2396 CAMLreturn (Val_unit);
2399 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2400 value xoff_v, value yoff_v,
2401 value li_v)
2403 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2404 int xoff = Int_val (xoff_v);
2405 int yoff = Int_val (yoff_v);
2406 int noff = Int_val (Field (li_v, 0));
2407 char *targ = String_val (Field (li_v, 1));
2408 int tlen = caml_string_length (Field (li_v, 1));
2409 int hfsize = Int_val (Field (li_v, 2));
2410 char *s = String_val (ptr_v);
2411 int hlmask = Int_val (hlinks_v);
2412 struct page *page = parse_pointer ("ml_postprocess", s);
2414 if (!page->u.ptr) {
2415 /* deal with loadpage failed pages */
2416 goto done;
2419 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2420 if (trylock ("ml_postprocess")) {
2421 noff = 0;
2422 goto done;
2424 if (hlmask & 2) {
2425 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2426 noff = page->slinkcount;
2428 showsel (page, xoff, yoff);
2429 unlock ("ml_postprocess");
2431 done:
2432 CAMLreturn (Val_int (noff));
2435 static fz_link *getlink (struct page *page, int x, int y)
2437 fz_point p;
2438 fz_matrix ctm;
2439 const fz_matrix *tctm;
2440 fz_link *link, *links;
2442 switch (page->type) {
2443 case DPDF:
2444 trimctm (page->u.pdfpage, page->pdimno);
2445 tctm = &state.pagedims[page->pdimno].tctm;
2446 links = page->u.pdfpage->links;
2447 break;
2449 case DXPS:
2450 tctm = &fz_identity;
2451 links = page->u.xpspage->links;
2452 break;
2454 default:
2455 return NULL;
2457 p.x = x;
2458 p.y = y;
2460 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2461 fz_invert_matrix (&ctm, &ctm);
2462 fz_transform_point (&p, &ctm);
2464 for (link = links; link; link = link->next) {
2465 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2466 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2467 return link;
2471 return NULL;
2474 static void ensuretext (struct page *page)
2476 if (state.gen != page->tgen) {
2477 droptext (page);
2478 page->tgen = state.gen;
2480 if (!page->text) {
2481 fz_matrix ctm;
2482 fz_device *tdev;
2484 page->text = fz_new_text_page (state.ctx, &fz_infinite_rect);
2485 page->sheet = fz_new_text_sheet (state.ctx);
2486 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2487 ctm = pagectm (page);
2488 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2489 qsort (page->text->blocks, page->text->len,
2490 sizeof (*page->text->blocks), compareblocks);
2491 fz_free_device (tdev);
2495 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2497 CAMLparam2 (start_page_v, dir_v);
2498 CAMLlocal1 (ret_v);
2499 int i, dir = Int_val (dir_v);
2500 int start_page = Int_val (start_page_v);
2501 int end_page = dir > 0 ? state.pagecount : -1;
2503 ret_v = Val_int (0);
2504 if (!(state.type == DPDF || state.type == DXPS)) {
2505 goto done;
2508 lock ("ml_findpage_with_links");
2509 for (i = start_page + dir; i != end_page; i += dir) {
2510 int found;
2512 switch (state.type) {
2513 case DPDF:
2515 pdf_page *page = NULL;
2517 fz_try (state.ctx) {
2518 page = pdf_load_page (state.u.pdf, i);
2519 found = !!page->links;
2521 fz_catch (state.ctx) {
2522 found = 0;
2524 if (page) {
2525 freepdfpage (page);
2528 break;
2529 case DXPS:
2531 xps_page *page = xps_load_page (state.u.xps, i);
2532 found = !!page->links;
2533 freexpspage (page);
2535 break;
2537 default:
2538 ARSERT ("invalid document type");
2541 if (found) {
2542 ret_v = caml_alloc_small (1, 1);
2543 Field (ret_v, 0) = Val_int (i);
2544 goto unlock;
2547 unlock:
2548 unlock ("ml_findpage_with_links");
2550 done:
2551 CAMLreturn (ret_v);
2554 enum { dir_first, dir_last};
2555 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2557 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2559 CAMLparam2 (ptr_v, dir_v);
2560 CAMLlocal2 (ret_v, pos_v);
2561 struct page *page;
2562 int dirtag, i, slinkindex;
2563 struct slink *found = NULL ,*slink;
2564 char *s = String_val (ptr_v);
2566 page = parse_pointer ("ml_findlink", s);
2567 ret_v = Val_int (0);
2568 if (trylock ("ml_findlink")) {
2569 goto done;
2572 ensureslinks (page);
2574 if (Is_block (dir_v)) {
2575 dirtag = Tag_val (dir_v);
2576 switch (dirtag) {
2577 case dir_first_visible:
2579 int x0, y0, dir, first_index, last_index;
2581 pos_v = Field (dir_v, 0);
2582 x0 = Int_val (Field (pos_v, 0));
2583 y0 = Int_val (Field (pos_v, 1));
2584 dir = Int_val (Field (pos_v, 2));
2586 if (dir >= 0) {
2587 dir = 1;
2588 first_index = 0;
2589 last_index = page->slinkcount;
2591 else {
2592 first_index = page->slinkcount - 1;
2593 last_index = -1;
2596 for (i = first_index; i != last_index; i += dir) {
2597 slink = &page->slinks[i];
2598 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2599 found = slink;
2600 break;
2604 break;
2606 case dir_left:
2607 slinkindex = Int_val (Field (dir_v, 0));
2608 found = &page->slinks[slinkindex];
2609 for (i = slinkindex - 1; i >= 0; --i) {
2610 slink = &page->slinks[i];
2611 if (slink->bbox.x0 < found->bbox.x0) {
2612 found = slink;
2613 break;
2616 break;
2618 case dir_right:
2619 slinkindex = Int_val (Field (dir_v, 0));
2620 found = &page->slinks[slinkindex];
2621 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2622 slink = &page->slinks[i];
2623 if (slink->bbox.x0 > found->bbox.x0) {
2624 found = slink;
2625 break;
2628 break;
2630 case dir_down:
2631 slinkindex = Int_val (Field (dir_v, 0));
2632 found = &page->slinks[slinkindex];
2633 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2634 slink = &page->slinks[i];
2635 if (slink->bbox.y0 >= found->bbox.y0) {
2636 found = slink;
2637 break;
2640 break;
2642 case dir_up:
2643 slinkindex = Int_val (Field (dir_v, 0));
2644 found = &page->slinks[slinkindex];
2645 for (i = slinkindex - 1; i >= 0; --i) {
2646 slink = &page->slinks[i];
2647 if (slink->bbox.y0 <= found->bbox.y0) {
2648 found = slink;
2649 break;
2652 break;
2655 else {
2656 dirtag = Int_val (dir_v);
2657 switch (dirtag) {
2658 case dir_first:
2659 found = page->slinks;
2660 break;
2662 case dir_last:
2663 if (page->slinks) {
2664 found = page->slinks + (page->slinkcount - 1);
2666 break;
2669 if (found) {
2670 ret_v = caml_alloc_small (2, 1);
2671 Field (ret_v, 0) = Val_int (found - page->slinks);
2674 unlock ("ml_findlink");
2675 done:
2676 CAMLreturn (ret_v);
2679 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2681 #define LINKTOVAL \
2683 int pageno; \
2685 switch (link->dest.kind) { \
2686 case FZ_LINK_GOTO: \
2688 fz_point p; \
2690 pageno = link->dest.ld.gotor.page; \
2691 p.x = 0; \
2692 p.y = 0; \
2694 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2695 p.y = link->dest.ld.gotor.lt.y; \
2696 fz_transform_point (&p, &pdim->lctm); \
2698 tup_v = caml_alloc_tuple (2); \
2699 ret_v = caml_alloc_small (1, ugoto); \
2700 Field (tup_v, 0) = Val_int (pageno); \
2701 Field (tup_v, 1) = Val_int (p.y); \
2702 Field (ret_v, 0) = tup_v; \
2704 break; \
2706 case FZ_LINK_URI: \
2707 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2708 ret_v = caml_alloc_small (1, uuri); \
2709 Field (ret_v, 0) = str_v; \
2710 break; \
2712 case FZ_LINK_LAUNCH: \
2713 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2714 ret_v = caml_alloc_small (1, ulaunch); \
2715 Field (ret_v, 0) = str_v; \
2716 break; \
2718 case FZ_LINK_NAMED: \
2719 str_v = caml_copy_string (link->dest.ld.named.named); \
2720 ret_v = caml_alloc_small (1, unamed); \
2721 Field (ret_v, 0) = str_v; \
2722 break; \
2724 case FZ_LINK_GOTOR: \
2725 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2726 pageno = link->dest.ld.gotor.page; \
2727 tup_v = caml_alloc_tuple (2); \
2728 ret_v = caml_alloc_small (1, uremote); \
2729 Field (tup_v, 0) = str_v; \
2730 Field (tup_v, 1) = Val_int (pageno); \
2731 Field (ret_v, 0) = tup_v; \
2732 break; \
2734 default: \
2736 char buf[80]; \
2738 snprintf (buf, sizeof (buf), \
2739 "unhandled link kind %d", link->dest.kind); \
2740 str_v = caml_copy_string (buf); \
2741 ret_v = caml_alloc_small (1, uunexpected); \
2742 Field (ret_v, 0) = str_v; \
2744 break; \
2748 CAMLprim value ml_getlink (value ptr_v, value n_v)
2750 CAMLparam2 (ptr_v, n_v);
2751 CAMLlocal3 (ret_v, tup_v, str_v);
2752 fz_link *link;
2753 struct page *page;
2754 struct pagedim *pdim;
2755 char *s = String_val (ptr_v);
2757 ret_v = Val_int (0);
2758 if (trylock ("ml_getlink")) {
2759 goto done;
2762 page = parse_pointer ("ml_getlink", s);
2763 ensureslinks (page);
2764 pdim = &state.pagedims[page->pdimno];
2765 link = page->slinks[Int_val (n_v)].link;
2766 LINKTOVAL;
2768 unlock ("ml_getlink");
2769 done:
2770 CAMLreturn (ret_v);
2773 CAMLprim value ml_getlinkcount (value ptr_v)
2775 CAMLparam1 (ptr_v);
2776 struct page *page;
2777 char *s = String_val (ptr_v);
2779 page = parse_pointer ("ml_getlinkcount", s);
2780 CAMLreturn (Val_int (page->slinkcount));
2783 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2785 CAMLparam2 (ptr_v, n_v);
2786 CAMLlocal1 (ret_v);
2787 struct page *page;
2788 struct slink *slink;
2789 char *s = String_val (ptr_v);
2791 page = parse_pointer ("ml_getlinkrect", s);
2792 ret_v = caml_alloc_tuple (4);
2793 if (trylock ("ml_getlinkrect")) {
2794 Field (ret_v, 0) = Val_int (0);
2795 Field (ret_v, 1) = Val_int (0);
2796 Field (ret_v, 2) = Val_int (0);
2797 Field (ret_v, 3) = Val_int (0);
2798 goto done;
2800 ensureslinks (page);
2802 slink = &page->slinks[Int_val (n_v)];
2803 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2804 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2805 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2806 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2807 unlock ("ml_getlinkrect");
2809 done:
2810 CAMLreturn (ret_v);
2813 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2815 CAMLparam3 (ptr_v, x_v, y_v);
2816 CAMLlocal3 (ret_v, tup_v, str_v);
2817 fz_link *link;
2818 struct page *page;
2819 char *s = String_val (ptr_v);
2820 int x = Int_val (x_v), y = Int_val (y_v);
2821 struct pagedim *pdim;
2823 ret_v = Val_int (0);
2824 if (trylock ("ml_whatsunder")) {
2825 goto done;
2828 page = parse_pointer ("ml_whatsunder", s);
2829 pdim = &state.pagedims[page->pdimno];
2830 x += pdim->bounds.x0;
2831 y += pdim->bounds.y0;
2832 link = getlink (page, x, y);
2833 if (link) {
2834 LINKTOVAL;
2836 else {
2837 fz_rect *b;
2838 fz_text_block *block;
2840 ensuretext (page);
2841 for (block = page->text->blocks;
2842 block < page->text->blocks + page->text->len;
2843 ++block) {
2844 fz_text_line *line;
2846 b = &block->bbox;
2847 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2848 continue;
2850 for (line = block->lines;
2851 line < block->lines + block->len;
2852 ++line) {
2853 fz_text_span *span;
2855 b = &line->bbox;
2856 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2857 continue;
2859 for (span = line->spans;
2860 span < line->spans + line->len;
2861 ++span) {
2862 fz_text_char *ch;
2864 b = &span->bbox;
2865 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2866 continue;
2868 for (ch = span->text; ch < span->text + span->len; ++ch) {
2869 b = &ch->bbox;
2871 if (x >= b->x0 && x <= b->x1
2872 && y >= b->y0 && y <= b->y1) {
2873 const char *n2 =
2874 span->style->font && span->style->font->name
2875 ? span->style->font->name
2876 : "Span has no font name"
2878 FT_FaceRec *face = span->style->font->ft_face;
2879 if (face && face->family_name) {
2880 char *s;
2881 char *n1 = face->family_name;
2882 size_t l1 = strlen (n1);
2883 size_t l2 = strlen (n2);
2885 if (l1 != l2 || memcmp (n1, n2, l1)) {
2886 s = malloc (l1 + l2 + 2);
2887 if (s) {
2888 memcpy (s, n2, l2);
2889 s[l2] = '=';
2890 memcpy (s + l2 + 1, n1, l1 + 1);
2891 str_v = caml_copy_string (s);
2892 free (s);
2896 if (str_v == 0) {
2897 str_v = caml_copy_string (n2);
2899 ret_v = caml_alloc_small (1, utext);
2900 Field (ret_v, 0) = str_v;
2901 goto unlock;
2908 unlock:
2909 unlock ("ml_whatsunder");
2911 done:
2912 CAMLreturn (ret_v);
2915 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2917 CAMLparam2 (ptr_v, rect_v);
2918 fz_rect *b;
2919 struct page *page;
2920 struct pagedim *pdim;
2921 int i, x0, x1, y0, y1;
2922 char *s = String_val (ptr_v);
2923 int fi = 0, li = 0;
2924 fz_text_block *block;
2925 fz_text_span *span, *fspan, *lspan;
2926 fz_text_line *line, *fline = NULL, *lline = NULL;
2928 if (trylock ("ml_seltext")) {
2929 goto done;
2932 page = parse_pointer ("ml_seltext", s);
2933 ensuretext (page);
2935 pdim = &state.pagedims[page->pdimno];
2936 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2937 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2938 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2939 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2941 if (0) {
2942 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2943 glColor3ub (128, 128, 128);
2944 glRecti (x0, y0, x1, y1);
2945 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2948 fspan = lspan = NULL;
2950 for (block = page->text->blocks;
2951 block < page->text->blocks + page->text->len;
2952 ++block) {
2953 for (line = block->lines;
2954 line < block->lines + block->len;
2955 ++line) {
2956 for (span = line->spans;
2957 span < line->spans + line->len;
2958 ++span) {
2959 for (i = 0; i < span->len; ++i) {
2960 b = &span->text[i].bbox;
2961 int selected = 0;
2963 if (x0 >= b->x0 && x0 <= b->x1
2964 && y0 >= b->y0 && y0 <= b->y1) {
2965 fspan = span;
2966 fline = line;
2967 fi = i;
2968 selected = 1;
2970 if (x1 >= b->x0 && x1 <= b->x1
2971 && y1 >= b->y0 && y1 <= b->y1) {
2972 lspan = span;
2973 lline = line;
2974 li = i;
2975 selected = 1;
2977 if (0 && selected) {
2978 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2979 glColor3ub (128, 128, 128);
2980 glRecti (b->x0, b->y0, b->x1, b->y1);
2981 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2987 if (y1 < y0 || x1 < x0) {
2988 int swap = 0;
2990 if (fspan == lspan) {
2991 swap = 1;
2993 else {
2994 if (y1 < y0) {
2995 if (fline != lline) {
2996 swap = 1;
3001 if (swap) {
3002 i = fi;
3003 span = fspan;
3005 fi = li;
3006 fspan = lspan;
3008 li = i;
3009 lspan = span;
3013 page->fmark.i = fi;
3014 page->fmark.span = fspan;
3016 page->lmark.i = li;
3017 page->lmark.span = lspan;
3019 unlock ("ml_seltext");
3021 done:
3022 CAMLreturn (Val_unit);
3025 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3027 char buf[4];
3028 int i, len, ret;
3030 for (i = a; i <= b; ++i) {
3031 len = fz_runetochar (buf, span->text[i].c);
3032 ret = fwrite (buf, len, 1, f);
3034 if (ret != 1) {
3035 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3036 len, ret, strerror (errno));
3037 return -1;
3040 return 0;
3043 #ifdef __CYGWIN__
3044 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3046 caml_failwith ("ml_popen not implemented under Cygwin");
3048 #else
3049 CAMLprim value ml_popen (value command_v, value fds_v)
3051 CAMLparam2 (command_v, fds_v);
3052 CAMLlocal2 (l_v, tup_v);
3053 int ret;
3054 char *msg = NULL;
3055 value earg_v = Nothing;
3056 posix_spawnattr_t attr;
3057 posix_spawn_file_actions_t fa;
3058 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
3060 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3061 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3064 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3065 msg = "posix_spawnattr_init";
3066 goto fail1;
3069 #ifdef POSIX_SPAWN_USEVFORK
3070 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3071 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3072 goto fail;
3074 #endif
3076 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3077 int fd1, fd2;
3079 tup_v = Field (l_v, 0);
3080 fd1 = Int_val (Field (tup_v, 0));
3081 fd2 = Int_val (Field (tup_v, 1));
3082 if (fd2 < 0) {
3083 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3084 msg = "posix_spawn_file_actions_addclose";
3085 earg_v = tup_v;
3086 goto fail;
3089 else {
3090 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3091 msg = "posix_spawn_file_actions_adddup2";
3092 earg_v = tup_v;
3093 goto fail;
3098 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3099 msg = "posix_spawn";
3100 goto fail;
3103 fail:
3104 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3105 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3108 fail1:
3109 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3110 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3111 strerror (ret));
3114 if (msg)
3115 unix_error (ret, msg, earg_v);
3117 CAMLreturn (Val_unit);
3119 #endif
3121 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3123 CAMLparam1 (ptr_v);
3124 FILE *f;
3125 int seen = 0;
3126 struct page *page;
3127 fz_text_line *line;
3128 fz_text_span *span;
3129 fz_text_block *block;
3130 int fd = Int_val (fd_v);
3131 char *s = String_val (ptr_v);
3133 if (trylock ("ml_copysel")) {
3134 goto done;
3137 page = parse_pointer ("ml_sopysel", s);
3139 if (!page->fmark.span || !page->lmark.span) {
3140 fprintf (stderr, "nothing to copy\n");
3141 goto unlock;
3144 f = fdopen (fd, "w");
3145 if (!f) {
3146 fprintf (stderr, "failed to fopen sel pipe: %s\n",
3147 strerror (errno));
3148 f = stdout;
3151 for (block = page->text->blocks;
3152 block < page->text->blocks + page->text->len;
3153 ++block) {
3154 for (line = block->lines;
3155 line < block->lines + block->len;
3156 ++line) {
3157 for (span = line->spans;
3158 span < line->spans + line->len;
3159 ++span) {
3160 int a, b;
3162 seen |= span == page->fmark.span || span == page->lmark.span;
3163 a = span == page->fmark.span ? page->fmark.i : 0;
3164 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3166 if (seen) {
3167 if (pipespan (f, span, a, b)) {
3168 goto close;
3170 if (span == line->spans + line->len - 1) {
3171 if (putc ('\n', f) == EOF) {
3172 fprintf (stderr,
3173 "failed break line on sel pipe: %s\n",
3174 strerror (errno));
3175 goto close;
3178 if (span == page->lmark.span) {
3179 goto endloop;
3185 endloop:
3186 page->lmark.span = NULL;
3187 page->fmark.span = NULL;
3189 close:
3190 if (f != stdout) {
3191 int ret = fclose (f);
3192 fd = -1;
3193 if (ret == -1) {
3194 if (errno != ECHILD) {
3195 fprintf (stderr, "failed to close sel pipe: %s\n",
3196 strerror (errno));
3200 unlock:
3201 unlock ("ml_copysel");
3203 done:
3204 if (fd >= 0) {
3205 if (close (fd)) {
3206 fprintf (stderr, "failed to close sel pipe: %s\n",
3207 strerror (errno));
3210 CAMLreturn (Val_unit);
3213 CAMLprim value ml_getpdimrect (value pagedimno_v)
3215 CAMLparam1 (pagedimno_v);
3216 CAMLlocal1 (ret_v);
3217 int pagedimno = Int_val (pagedimno_v);
3218 fz_rect box;
3220 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3221 if (trylock ("ml_getpdimrect")) {
3222 box = fz_empty_rect;
3224 else {
3225 box = state.pagedims[pagedimno].mediabox;
3226 unlock ("ml_getpdimrect");
3229 Store_double_field (ret_v, 0, box.x0);
3230 Store_double_field (ret_v, 1, box.x1);
3231 Store_double_field (ret_v, 2, box.y0);
3232 Store_double_field (ret_v, 3, box.y1);
3234 CAMLreturn (ret_v);
3237 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3238 value dw_v, value cols_v)
3240 CAMLparam3 (winw_v, winh_v, dw_v);
3241 CAMLlocal1 (ret_v);
3242 int i;
3243 double zoom = 1.0;
3244 double maxw = 0.0, maxh = 0.0;
3245 struct pagedim *p;
3246 double winw = Int_val (winw_v);
3247 double winh = Int_val (winh_v);
3248 double dw = Int_val (dw_v);
3249 double cols = Int_val (cols_v);
3250 double pw = 1.0, ph = 1.0, aspect;
3252 if (trylock ("ml_zoom_for_height")) {
3253 goto done;
3256 if (state.proportional) {
3257 maxw = getmaxw () / cols;
3260 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3261 fz_rect rect;
3262 fz_matrix rm;
3263 double x0, x1, y0, y1, w, h, scaledh, scale;
3265 fz_rotate (&rm, p->rotate + state.rotate);
3266 rect = p->mediabox;
3267 fz_transform_rect (&rect, &rm);
3268 x0 = MIN (rect.x0, rect.x1);
3269 x1 = MAX (rect.x0, rect.x1);
3270 y0 = MIN (rect.y0, rect.y1);
3271 y1 = MAX (rect.y0, rect.y1);
3273 w = (x1 - x0) / cols;
3274 h = y1 - y0;
3276 if (state.proportional) {
3277 scale = w / maxw;
3278 scaledh = h * scale;
3280 else {
3281 scale = 1.0;
3282 scaledh = h;
3285 if (scaledh > maxh) {
3286 maxh = scaledh;
3287 ph = scaledh;
3288 pw = w * scale;
3292 aspect = pw / ph;
3293 zoom = (winh * aspect + dw) / winw;
3295 unlock ("ml_zoom_for_height");
3296 done:
3297 ret_v = caml_copy_double (zoom);
3298 CAMLreturn (ret_v);
3301 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3303 CAMLparam4 (pt_v, x_v, y_v, string_v);
3304 CAMLlocal1 (ret_v);
3305 int pt = Int_val(pt_v);
3306 int x = Int_val (x_v);
3307 int y = Int_val (y_v);
3308 double w;
3310 w = draw_string (state.face, pt, x, y, String_val (string_v));
3311 ret_v = caml_copy_double (w);
3312 CAMLreturn (ret_v);
3315 CAMLprim value ml_measure_string (value pt_v, value string_v)
3317 CAMLparam2 (pt_v, string_v);
3318 CAMLlocal1 (ret_v);
3319 int pt = Int_val (pt_v);
3320 double w;
3322 w = measure_string (state.face, pt, String_val (string_v));
3323 ret_v = caml_copy_double (w);
3324 CAMLreturn (ret_v);
3327 CAMLprim value ml_getpagebox (value opaque_v)
3329 CAMLparam1 (opaque_v);
3330 CAMLlocal1 (ret_v);
3331 fz_rect rect;
3332 fz_irect bbox;
3333 fz_matrix ctm;
3334 fz_device *dev;
3335 char *s = String_val (opaque_v);
3336 struct page *page = parse_pointer ("ml_getpagebox", s);
3338 ret_v = caml_alloc_tuple (4);
3339 dev = fz_new_bbox_device (state.ctx, &rect);
3340 dev->hints |= FZ_IGNORE_SHADE;
3342 switch (page->type) {
3343 case DPDF:
3344 ctm = pagectm (page);
3345 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3346 break;
3348 case DXPS:
3349 ctm = pagectm (page);
3350 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3351 break;
3353 default:
3354 rect = fz_infinite_rect;
3355 break;
3358 fz_free_device (dev);
3359 fz_round_rect (&bbox, &rect);
3360 Field (ret_v, 0) = Val_int (bbox.x0);
3361 Field (ret_v, 1) = Val_int (bbox.y0);
3362 Field (ret_v, 2) = Val_int (bbox.x1);
3363 Field (ret_v, 3) = Val_int (bbox.y1);
3365 CAMLreturn (ret_v);
3368 CAMLprim value ml_setaalevel (value level_v)
3370 CAMLparam1 (level_v);
3372 state.aalevel = Int_val (level_v);
3373 CAMLreturn (Val_unit);
3376 #undef pixel
3377 #include <X11/Xlib.h>
3378 #include <GL/glx.h>
3380 static struct {
3381 Display *dpy;
3382 GLXContext ctx;
3383 GLXDrawable drawable;
3384 } glx;
3386 #include "keysym2ucs.c"
3388 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3390 CAMLparam1 (keysym_v);
3391 CAMLlocal1 (str_v);
3392 KeySym keysym = Int_val (keysym_v);
3393 Rune rune;
3394 int len;
3395 char buf[5];
3397 rune = keysym2ucs (keysym);
3398 len = fz_runetochar (buf, rune);
3399 buf[len] = 0;
3400 str_v = caml_copy_string (buf);
3401 CAMLreturn (str_v);
3404 CAMLprim value ml_glx (value win_v)
3406 CAMLparam1 (win_v);
3407 XVisualInfo *visual;
3408 int screen, wid = Int_val (win_v);
3409 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3411 glx.dpy = XOpenDisplay (NULL);
3412 if (!glx.dpy) {
3413 caml_failwith ("XOpenDisplay");
3416 screen = DefaultScreen (glx.dpy);
3417 visual = glXChooseVisual (glx.dpy, screen, attributes);
3418 if (!visual) {
3419 XCloseDisplay (glx.dpy);
3420 glx.dpy = NULL;
3421 caml_failwith ("glXChooseVisual");
3424 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3425 XFree (visual);
3426 if (!glx.ctx) {
3427 XCloseDisplay (glx.dpy);
3428 glx.dpy = NULL;
3429 caml_failwith ("glXCreateContext");
3432 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3433 glXDestroyContext (glx.dpy, glx.ctx);
3434 XCloseDisplay (glx.dpy);
3435 glx.dpy = NULL;
3436 glx.ctx = NULL;
3437 caml_failwith ("glXMakeCurrent");
3439 glx.drawable = wid;
3440 CAMLreturn (Val_unit);
3443 CAMLprim value ml_swapb (value unit_v)
3445 CAMLparam1 (unit_v);
3446 glXSwapBuffers (glx.dpy, glx.drawable);
3447 CAMLreturn (Val_unit);
3450 CAMLprim value ml_glxsync (value unit_v)
3452 CAMLparam1 (unit_v);
3453 if (glx.dpy && glx.ctx) {
3454 glXWaitX ();
3455 glXWaitGL ();
3457 CAMLreturn (Val_unit);
3460 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3461 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3463 CAMLprim value ml_platform (value unit_v)
3465 CAMLparam1 (unit_v);
3466 int platid = piunknown;
3468 #if defined __linux__
3469 platid = pilinux;
3470 #elif defined __CYGWIN__
3471 platid = picygwin;
3472 #elif defined __DragonFly__
3473 platid = pidragonflybsd;
3474 #elif defined __FreeBSD__
3475 platid = pifreebsd;
3476 #elif defined __OpenBSD__
3477 platid = piopenbsd;
3478 #elif defined __NetBSD__
3479 platid = pinetbsd;
3480 #elif defined __sun__
3481 platid = pisun;
3482 #elif defined __APPLE__
3483 platid = piosx;
3484 #endif
3485 CAMLreturn (Val_int (platid));
3488 CAMLprim value ml_cloexec (value fd_v)
3490 CAMLparam1 (fd_v);
3491 int fd = Int_val (fd_v);
3493 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3494 uerror ("fcntl", Nothing);
3496 CAMLreturn (Val_unit);
3499 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3501 CAMLparam2 (w_v, h_v);
3502 CAMLlocal1 (ret_v);
3503 struct pbo *pbo;
3504 int w = Int_val (w_v);
3505 int h = Int_val (h_v);
3506 int cs = Int_val (cs_v);
3508 if (state.pbo_usable) {
3509 pbo = calloc (sizeof (*pbo), 1);
3510 if (!pbo) {
3511 err (1, "calloc pbo");
3514 switch (cs) {
3515 case 0:
3516 case 1:
3517 pbo->size = w*h*4;
3518 break;
3519 case 2:
3520 pbo->size = w*h*2;
3521 break;
3522 default:
3523 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3526 state.glGenBuffersARB (1, &pbo->id);
3527 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3528 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3529 NULL, GL_STREAM_DRAW);
3530 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3531 GL_READ_WRITE);
3532 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3533 if (!pbo->ptr) {
3534 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3535 state.glDeleteBuffersARB (1, &pbo->id);
3536 free (pbo);
3537 ret_v = caml_copy_string ("0");
3539 else {
3540 int res;
3541 char *s;
3543 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3544 if (res < 0) {
3545 err (1, "snprintf %" FMT_ptr " failed", pbo);
3547 s = malloc (res+1);
3548 if (!s) {
3549 err (1, "malloc %d bytes failed", res+1);
3551 res = sprintf (s, "%" FMT_ptr, pbo);
3552 if (res < 0) {
3553 err (1, "sprintf %" FMT_ptr " failed", pbo);
3555 ret_v = caml_copy_string (s);
3556 free (s);
3559 else {
3560 ret_v = caml_copy_string ("0");
3562 CAMLreturn (ret_v);
3565 CAMLprim value ml_freepbo (value s_v)
3567 CAMLparam1 (s_v);
3568 char *s = String_val (s_v);
3569 struct tile *tile = parse_pointer ("ml_freepbo", s);
3571 if (tile->pbo) {
3572 state.glDeleteBuffersARB (1, &tile->pbo->id);
3573 tile->pbo->id = -1;
3574 tile->pbo->ptr = NULL;
3575 tile->pbo->size = -1;
3577 CAMLreturn (Val_unit);
3580 CAMLprim value ml_unmappbo (value s_v)
3582 CAMLparam1 (s_v);
3583 char *s = String_val (s_v);
3584 struct tile *tile = parse_pointer ("ml_unmappbo", s);
3586 if (tile->pbo) {
3587 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3588 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3589 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3591 tile->pbo->ptr = NULL;
3592 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3594 CAMLreturn (Val_unit);
3597 static void setuppbo (void)
3599 #define GGPA(n) *(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n)
3600 GGPA (glBindBufferARB);
3601 if (state.glBindBufferARB) {
3602 GGPA (glUnmapBufferARB);
3603 if (state.glUnmapBufferARB) {
3604 GGPA (glMapBufferARB);
3605 if (state.glMapBufferARB) {
3606 GGPA (glBufferDataARB);
3607 if (state.glBufferDataARB) {
3608 GGPA (glGenBuffersARB);
3609 if (state.glGenBuffersARB) {
3610 GGPA (glDeleteBuffersARB);
3611 if (state.glDeleteBuffersARB) {
3612 state.pbo_usable = 1;
3619 #undef GGPA
3622 CAMLprim value ml_pbo_usable (value unit_v)
3624 CAMLparam1 (unit_v);
3625 CAMLreturn (Val_bool (state.pbo_usable));
3628 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3630 CAMLparam3 (ptr_v, x_v, y_v);
3631 CAMLlocal2 (ret_v, tup_v);
3632 struct page *page;
3633 char *s = String_val (ptr_v);
3634 int x = Int_val (x_v), y = Int_val (y_v);
3635 struct pagedim *pdim;
3636 fz_point p;
3637 fz_matrix ctm;
3639 page = parse_pointer ("ml_unproject", s);
3640 pdim = &state.pagedims[page->pdimno];
3642 ret_v = Val_int (0);
3643 if (trylock ("ml_unproject")) {
3644 goto done;
3647 switch (page->type) {
3648 case DPDF:
3649 trimctm (page->u.pdfpage, page->pdimno);
3650 break;
3652 default:
3653 break;
3655 p.x = x;
3656 p.y = y;
3658 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3659 fz_invert_matrix (&ctm, &ctm);
3660 fz_transform_point (&p, &ctm);
3662 tup_v = caml_alloc_tuple (2);
3663 ret_v = caml_alloc_small (1, 1);
3664 Field (tup_v, 0) = Val_int (p.x);
3665 Field (tup_v, 1) = Val_int (p.y);
3666 Field (ret_v, 0) = tup_v;
3668 unlock ("ml_unproject");
3669 done:
3670 CAMLreturn (ret_v);
3673 static void makestippletex (void)
3675 const char *pixels = "\xff\xff\0\0";
3676 glGenTextures (1, &state.stid);
3677 glBindTexture (GL_TEXTURE_1D, state.stid);
3678 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3679 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3680 glTexImage1D (
3681 GL_TEXTURE_1D,
3683 GL_ALPHA,
3686 GL_ALPHA,
3687 GL_UNSIGNED_BYTE,
3688 pixels
3692 CAMLprim value ml_init (value pipe_v, value params_v)
3694 CAMLparam2 (pipe_v, params_v);
3695 CAMLlocal2 (trim_v, fuzz_v);
3696 int ret;
3697 int texcount;
3698 char *fontpath;
3699 int colorspace;
3700 int mustoresize;
3701 int haspboext;
3702 struct sigaction sa;
3704 state.cr = Int_val (Field (pipe_v, 0));
3705 state.cw = Int_val (Field (pipe_v, 1));
3706 state.rotate = Int_val (Field (params_v, 0));
3707 state.proportional = Bool_val (Field (params_v, 1));
3708 trim_v = Field (params_v, 2);
3709 texcount = Int_val (Field (params_v, 3));
3710 state.sliceheight = Int_val (Field (params_v, 4));
3711 mustoresize = Int_val (Field (params_v, 5));
3712 colorspace = Int_val (Field (params_v, 6));
3713 fontpath = String_val (Field (params_v, 7));
3714 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
3715 if (!state.trimcachepath) {
3716 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
3717 strerror (errno));
3719 haspboext = Bool_val (Field (params_v, 9));
3721 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3723 state.trimmargins = Bool_val (Field (trim_v, 0));
3724 fuzz_v = Field (trim_v, 1);
3725 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3726 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3727 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3728 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3730 set_tex_params (colorspace);
3732 if (*fontpath) {
3733 state.face = load_font (fontpath);
3735 else {
3736 unsigned int len;
3737 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
3739 state.face = load_builtin_font (base, len);
3741 if (!state.face) _exit (1);
3743 realloctexts (texcount);
3745 if (haspboext) {
3746 setuppbo ();
3749 makestippletex ();
3750 #ifdef __CYGWIN__
3751 sa.sa_handler = SIG_IGN;
3752 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3753 #else
3754 sa.sa_handler = SIG_DFL;
3755 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
3756 #endif
3757 if (sigemptyset (&sa.sa_mask)) {
3758 err (1, "sigemptyset");
3760 if (sigaction (SIGCHLD, &sa, NULL)) {
3761 err (1, "sigaction");
3764 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3765 if (ret) {
3766 errx (1, "pthread_create: %s", strerror (ret));
3769 CAMLreturn (Val_unit);