Madness
[llpp/slowscroll.git] / link.c
blobad4561ef67ecd0ca2ff69209dab1d96051367732
1 /* lots of code c&p-ed directly from mupdf */
2 #include <errno.h>
3 #include <stdio.h>
4 #include <ctype.h>
5 #include <string.h>
6 #include <stdlib.h>
7 #include <signal.h>
8 #include <wchar.h>
10 #include <unistd.h>
11 #include <pthread.h>
12 #include <sys/time.h>
13 #include <sys/types.h>
14 #include <sys/ioctl.h>
16 #ifdef __CYGWIN__
17 #include <cygwin/socket.h> /* FIONREAD */
18 #else
19 #include <spawn.h>
20 #endif
22 #include <regex.h>
23 #include <ctype.h>
24 #include <stdarg.h>
25 #include <limits.h>
27 #include <GL/gl.h>
29 #include <caml/fail.h>
30 #include <caml/alloc.h>
31 #include <caml/memory.h>
32 #include <caml/unixsupport.h>
34 #include <fitz.h>
35 #include <mupdf.h>
36 #include <mupdf-internal.h>
37 #include <muxps.h>
38 #include <muxps-internal.h>
39 #include <mucbz.h>
41 #include FT_FREETYPE_H
43 #define PIGGYBACK
45 #ifndef __USE_GNU
46 extern char **environ;
47 #endif
49 #define MIN(a,b) ((a) < (b) ? (a) : (b))
50 #define MAX(a,b) ((a) > (b) ? (a) : (b))
52 #if defined __GNUC__
53 #define NORETURN_ATTR __attribute__ ((noreturn))
54 #define UNUSED_ATTR __attribute__ ((unused))
55 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
56 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
57 #else
58 #define NORETURN_ATTR
59 #define UNUSED_ATTR
60 #define OPTIMIZE_ATTR(n)
61 #define GCC_FMT_ATTR(a, b)
62 #endif
64 #define FMT_s "zu"
66 #define FMT_ptr "p"
67 #define FMT_ptr_cast(p) (p)
68 #define FMT_ptr_cast2(p) (p)
70 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
71 err (int exitcode, const char *fmt, ...)
73 va_list ap;
74 int savederrno;
76 savederrno = errno;
77 va_start (ap, fmt);
78 vfprintf (stderr, fmt, ap);
79 va_end (ap);
80 fprintf (stderr, ": %s\n", strerror (savederrno));
81 fflush (stderr);
82 _exit (exitcode);
85 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
86 errx (int exitcode, const char *fmt, ...)
88 va_list ap;
90 va_start (ap, fmt);
91 vfprintf (stderr, fmt, ap);
92 va_end (ap);
93 fputc ('\n', stderr);
94 fflush (stderr);
95 _exit (exitcode);
98 #ifndef GL_TEXTURE_RECTANGLE_ARB
99 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
100 #endif
102 #ifndef GL_BGRA
103 #define GL_BGRA 0x80E1
104 #endif
106 #ifndef GL_UNSIGNED_INT_8_8_8_8
107 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
108 #endif
110 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
111 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
112 #endif
114 #if 0
115 #define lprintf printf
116 #else
117 #define lprintf(...)
118 #endif
120 #define ARSERT(cond) for (;;) { \
121 if (!(cond)) { \
122 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
124 break; \
127 struct slice {
128 int h;
129 int texindex;
132 struct tile {
133 int x, y, w, h;
134 int slicecount;
135 int sliceheight;
136 struct pbo *pbo;
137 fz_pixmap *pixmap;
138 struct slice slices[1];
141 struct pagedim {
142 int pageno;
143 int rotate;
144 int left;
145 int tctmready;
146 fz_bbox bounds;
147 fz_rect pagebox;
148 fz_rect mediabox;
149 fz_matrix ctm, zoomctm, lctm, tctm;
152 struct slink {
153 fz_bbox bbox;
154 fz_link *link;
157 enum { DPDF, DXPS, DCBZ };
159 struct page {
160 int tgen;
161 int sgen;
162 int type;
163 int pageno;
164 int pdimno;
165 fz_text_page *text;
166 fz_text_sheet *sheet;
167 union {
168 void *ptr;
169 pdf_page *pdfpage;
170 xps_page *xpspage;
171 cbz_page *cbzpage;
172 } u;
173 fz_display_list *dlist;
174 int slinkcount;
175 struct slink *slinks;
176 struct mark {
177 int i;
178 fz_text_span *span;
179 } fmark, lmark;
180 void (*freepage) (void *);
183 struct {
184 int type;
185 int sliceheight;
186 struct pagedim *pagedims;
187 int pagecount;
188 int pagedimcount;
189 union {
190 pdf_document *pdf;
191 xps_document *xps;
192 cbz_document *cbz;
193 } u;
194 fz_context *ctx;
195 int w, h;
197 int texindex;
198 int texcount;
199 GLuint *texids;
201 GLenum texiform;
202 GLenum texform;
203 GLenum texty;
205 fz_colorspace *colorspace;
207 struct {
208 int w, h;
209 struct slice *slice;
210 } *texowners;
212 int rotate;
213 int proportional;
214 int trimmargins;
215 int needoutline;
216 int gen;
217 int aalevel;
219 int trimanew;
220 fz_bbox trimfuzz;
221 fz_pixmap *pig;
223 pthread_t thread;
224 int cr, cw;
225 FT_Face face;
227 void (*closedoc) (void);
228 void (*freepage) (void *);
230 char *trimcachepath;
232 int pbo_usable;
233 void (*glBindBufferARB) (GLenum, GLuint);
234 GLboolean (*glUnmapBufferARB) (GLenum);
235 void *(*glMapBufferARB) (GLenum, GLenum);
236 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
237 void (*glGenBuffersARB) (GLsizei, GLuint *);
238 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
239 } state;
241 struct pbo {
242 GLuint id;
243 void *ptr;
244 size_t size;
247 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
249 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
252 static void UNUSED_ATTR debug_bbox (const char *cap, fz_bbox r)
254 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
257 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
259 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
260 m.a, m.b, m.c, m.d, m.e, m.f);
263 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
265 static void lock (const char *cap)
267 int ret = pthread_mutex_lock (&mutex);
268 if (ret) {
269 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
273 static void unlock (const char *cap)
275 int ret = pthread_mutex_unlock (&mutex);
276 if (ret) {
277 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
281 static int trylock (const char *cap)
283 int ret = pthread_mutex_trylock (&mutex);
284 if (ret && ret != EBUSY) {
285 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
287 return ret == EBUSY;
290 static void *parse_pointer (const char *cap, const char *s)
292 int ret;
293 void *ptr;
295 ret = sscanf (s, "%" FMT_ptr, FMT_ptr_cast (&ptr));
296 if (ret != 1) {
297 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
299 return ptr;
302 static double now (void)
304 struct timeval tv;
306 if (gettimeofday (&tv, NULL)) {
307 err (1, "gettimeofday");
309 return tv.tv_sec + tv.tv_usec*1e-6;
312 static int hasdata (void)
314 int ret, avail;
315 ret = ioctl (state.cr, FIONREAD, &avail);
316 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
317 return avail > 0;
320 CAMLprim value ml_hasdata (value fd_v)
322 CAMLparam1 (fd_v);
323 int ret, avail;
325 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
326 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
327 CAMLreturn (Val_bool (avail > 0));
330 static void readdata (void *p, int size)
332 ssize_t n;
334 again:
335 n = read (state.cr, p, size);
336 if (n < 0) {
337 if (errno == EINTR) goto again;
338 err (1, "read (req %d, ret %zd)", size, n);
340 if (n - size) {
341 if (!n) errx (1, "EOF while reading");
342 errx (1, "read (req %d, ret %zd)", size, n);
346 static void writedata (char *p, int size)
348 char buf[4];
349 ssize_t n;
351 buf[0] = (size >> 24) & 0xff;
352 buf[1] = (size >> 16) & 0xff;
353 buf[2] = (size >> 8) & 0xff;
354 buf[3] = (size >> 0) & 0xff;
356 n = write (state.cw, buf, 4);
357 if (n != 4) {
358 if (!n) errx (1, "EOF while writing length");
359 err (1, "write %zd", n);
362 n = write (state.cw, p, size);
363 if (n - size) {
364 if (!n) errx (1, "EOF while writing data");
365 err (1, "write (req %d, ret %zd)", size, n);
369 static int readlen (void)
371 unsigned char p[4];
373 readdata (p, 4);
374 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
377 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
379 int size = 200, len;
380 va_list ap;
381 char *buf;
383 buf = malloc (size);
384 for (;;) {
385 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
387 va_start (ap, fmt);
388 len = vsnprintf (buf, size, fmt, ap);
389 va_end (ap);
391 if (len > -1 && len < size) {
392 writedata (buf, len);
393 break;
396 if (len > -1) {
397 size = len + 1;
399 else {
400 size *= 2;
402 buf = realloc (buf, size);
404 free (buf);
407 static void closepdf (void)
409 if (state.u.pdf) {
410 pdf_close_document (state.u.pdf);
411 state.u.pdf = NULL;
415 static void closexps (void)
417 if (state.u.xps) {
418 xps_close_document (state.u.xps);
419 state.u.xps = NULL;
423 static void closecbz (void)
425 if (state.u.cbz) {
426 cbz_close_document (state.u.cbz);
427 state.u.cbz = NULL;
431 static void freepdfpage (void *ptr)
433 pdf_free_page (state.u.pdf, ptr);
436 static void freeemptypdfpage (void *ptr)
438 (void) ptr;
441 static void freexpspage (void *ptr)
443 xps_free_page (state.u.xps, ptr);
446 static void freecbzpage (void *ptr)
448 cbz_free_page (state.u.cbz, ptr);
451 static void openxref (char *filename, char *password)
453 int i, len;
455 for (i = 0; i < state.texcount; ++i) {
456 state.texowners[i].w = -1;
457 state.texowners[i].slice = NULL;
460 if (state.closedoc) state.closedoc ();
462 len = strlen (filename);
464 state.type = DPDF;
465 if (len > 4) {
466 char ext[4];
468 ext[0] = tolower ((int) filename[len-3]);
469 ext[1] = tolower ((int) filename[len-2]);
470 ext[2] = tolower ((int) filename[len-1]);
472 /**/ if (ext[0] == 'x' && ext[1] == 'p' && ext[2] == 's') {
473 state.type = DXPS;
475 else if (ext[0] == 'c' && ext[1] == 'b' && ext[2] == 'z') {
476 state.type = DCBZ;
480 if (state.pagedims) {
481 free (state.pagedims);
482 state.pagedims = NULL;
484 state.pagedimcount = 0;
486 fz_set_aa_level (state.ctx, state.aalevel);
487 switch (state.type) {
488 case DPDF:
489 state.u.pdf = pdf_open_document (state.ctx, filename);
490 if (pdf_needs_password (state.u.pdf)) {
491 int okay = pdf_authenticate_password (state.u.pdf, password);
492 if (!okay) {
493 errx (1, "invalid password");
496 state.pagecount = pdf_count_pages (state.u.pdf);
497 state.closedoc = closepdf;
498 state.freepage = freepdfpage;
499 break;
501 case DXPS:
502 state.u.xps = xps_open_document (state.ctx, filename);
503 state.pagecount = xps_count_pages (state.u.xps);
504 state.closedoc = closexps;
505 state.freepage = freexpspage;
506 break;
508 case DCBZ:
509 state.u.cbz = cbz_open_document (state.ctx, filename);
510 state.pagecount = cbz_count_pages (state.u.cbz);
511 state.closedoc = closecbz;
512 state.freepage = freecbzpage;
513 break;
517 static void pdfinfo (void)
519 if (state.type == DPDF) {
520 pdf_obj *infoobj;
522 printd ("info PDF version\t%d.%d",
523 state.u.pdf->version / 10, state.u.pdf->version % 10);
525 infoobj = pdf_dict_gets (state.u.pdf->trailer, "Info");
526 if (infoobj) {
527 int i;
528 char *s;
529 char *items[] = { "Title", "Author", "Creator",
530 "Producer", "CreationDate" };
532 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
533 pdf_obj *obj = pdf_dict_gets (infoobj, items[i]);
534 s = pdf_to_utf8 (state.u.pdf, obj);
535 if (*s) {
536 if (i == 0) {
537 printd ("title %s", s);
539 printd ("info %s\t%s", items[i], s);
541 fz_free (state.ctx, s);
544 printd ("infoend");
548 static void unlinktile (struct tile *tile)
550 int i;
552 for (i = 0; i < tile->slicecount; ++i) {
553 struct slice *s = &tile->slices[i];
555 if (s->texindex != -1) {
556 if (state.texowners[s->texindex].slice == s) {
557 state.texowners[s->texindex].slice = NULL;
563 static void freepage (struct page *page)
565 if (page->text) {
566 fz_free_text_page (state.ctx, page->text);
568 if (page->sheet) {
569 fz_free_text_sheet (state.ctx, page->sheet);
571 if (page->slinks) {
572 free (page->slinks);
574 page->freepage (page->u.ptr);
575 fz_free_display_list (state.ctx, page->dlist);
576 free (page);
579 static void freetile (struct tile *tile)
581 unlinktile (tile);
582 if (!tile->pbo) {
583 #ifndef PIGGYBACK
584 fz_drop_pixmap (state.ctx, tile->pixmap);
585 #else
586 if (state.pig) {
587 fz_drop_pixmap (state.ctx, state.pig);
589 state.pig = tile->pixmap;
590 #endif
592 else {
593 free (tile->pbo);
594 fz_drop_pixmap (state.ctx, tile->pixmap);
596 free (tile);
599 #ifdef __ALTIVEC__
600 #include <altivec.h>
602 static int cacheline32bytes;
604 static void __attribute__ ((constructor)) clcheck (void)
606 char **envp = environ;
607 unsigned long *auxv;
609 while (*envp++);
611 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
612 if (*auxv == 19) {
613 cacheline32bytes = auxv[1] == 32;
614 return;
619 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
621 size_t size = pixmap->w * pixmap->h * pixmap->n;
622 if (cacheline32bytes && size > 32) {
623 intptr_t a1, a2, diff;
624 size_t sizea, i;
625 vector unsigned char v = vec_splat_u8 (-1);
626 vector unsigned char *p;
628 a1 = a2 = (intptr_t) pixmap->samples;
629 a2 = (a1 + 31) & ~31;
630 diff = a2 - a1;
631 sizea = size - diff;
632 p = (void *) a2;
634 while (a1 != a2) *(char *) a1++ = 0xff;
635 for (i = 0; i < (sizea & ~31); i += 32) {
636 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
637 vec_st (v, i, p);
638 vec_st (v, i + 16, p);
640 while (i < sizea) *((char *) a1 + i++) = 0xff;
642 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
644 #else
645 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
646 #endif
648 static fz_matrix trimctm (pdf_page *page, int pindex)
650 fz_matrix ctm;
651 struct pagedim *pdim = &state.pagedims[pindex];
653 if (!pdim->tctmready) {
654 if (state.trimmargins) {
655 fz_rect realbox;
657 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
658 realbox = fz_transform_rect (ctm, pdim->mediabox);
659 ctm = fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0));
660 ctm = fz_concat (fz_invert_matrix (page->ctm), ctm);
662 else {
663 ctm = fz_identity;
665 pdim->tctm = ctm;
666 pdim->tctmready = 1;
668 return pdim->tctm;
671 static fz_matrix pagectm (struct page *page)
673 if (page->type == DPDF) {
674 return fz_concat (trimctm (page->u.pdfpage, page->pdimno),
675 state.pagedims[page->pdimno].ctm);
677 else {
678 fz_matrix ctm;
679 struct pagedim *pdim = &state.pagedims[page->pdimno];
681 ctm = state.pagedims[page->pdimno].ctm;
682 ctm = fz_concat (fz_translate (-pdim->mediabox.x0,
683 -pdim->mediabox.y0), ctm);
684 return ctm;
688 static void *loadpage (int pageno, int pindex)
690 fz_device *dev;
691 struct page *page = NULL;
693 page = calloc (sizeof (struct page), 1);
694 if (!page) {
695 err (1, "calloc page %d", pageno);
698 page->dlist = fz_new_display_list (state.ctx);
699 dev = fz_new_list_device (state.ctx, page->dlist);
700 switch (state.type) {
701 case DPDF:
702 fz_try (state.ctx) {
703 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
704 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, fz_identity, NULL);
705 page->freepage = freepdfpage;
707 fz_catch (state.ctx) {
708 page->u.ptr = NULL;
709 page->freepage = freeemptypdfpage;
711 break;
713 case DXPS:
714 page->u.xpspage = xps_load_page (state.u.xps, pageno);
715 xps_run_page (state.u.xps, page->u.xpspage, dev, fz_identity, NULL);
716 page->freepage = freexpspage;
717 break;
719 case DCBZ:
720 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
721 cbz_run_page (state.u.cbz, page->u.cbzpage, dev, fz_identity, NULL);
722 page->freepage = freecbzpage;
723 break;
725 fz_free_device (dev);
727 page->pdimno = pindex;
728 page->pageno = pageno;
729 page->sgen = state.gen;
730 page->tgen = state.gen;
731 page->type = state.type;
733 return page;
736 static struct tile *alloctile (int h)
738 int i;
739 int slicecount;
740 size_t tilesize;
741 struct tile *tile;
743 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
744 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
745 tile = calloc (tilesize, 1);
746 if (!tile) {
747 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
749 for (i = 0; i < slicecount; ++i) {
750 int sh = MIN (h, state.sliceheight);
751 tile->slices[i].h = sh;
752 tile->slices[i].texindex = -1;
753 h -= sh;
755 tile->slicecount = slicecount;
756 tile->sliceheight = state.sliceheight;
757 return tile;
760 #ifdef OBSCURED_OPT
761 struct obs {
762 int cured;
763 fz_bbox b;
766 static void obs_fill_image (fz_device *dev, fz_image *image, fz_matrix ctm,
767 float alpha)
769 struct obs *obs = dev->user;
771 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
772 fz_bbox b = fz_round_rect (fz_transform_rect (ctm, fz_unit_rect));
773 b = fz_intersect_bbox (b, obs->b);
774 obs->cured = b.x0 == obs->b.x0
775 && b.x1 == obs->b.x1
776 && b.y0 == obs->b.y0
777 && b.y1 == obs->b.y1;
781 static int obscured (struct page *page, fz_bbox bbox)
783 fz_device dev;
784 struct obs obs;
786 memset (&dev, 0, sizeof (dev));
787 memset (&obs, 0, sizeof (obs));
788 dev.hints = 0;
789 dev.flags = 0;
790 dev.user = &obs;
791 dev.ctx = state.ctx;
792 dev.fill_image = obs_fill_image;
793 obs.b = bbox;
794 fz_run_display_list (page->dlist, &dev, pagectm (page), bbox, NULL);
795 return obs.cured;
797 #define OBSCURED obscured
798 #else
799 #define OBSCURED(a, b) 0
800 #endif
802 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
803 struct pbo *pbo)
805 fz_bbox bbox;
806 fz_device *dev;
807 struct tile *tile;
808 struct pagedim *pdim;
810 tile = alloctile (h);
811 pdim = &state.pagedims[page->pdimno];
813 bbox = pdim->bounds;
814 bbox.x0 += x;
815 bbox.y0 += y;
816 bbox.x1 = bbox.x0 + w;
817 bbox.y1 = bbox.y0 + h;
819 if (state.pig) {
820 if (state.pig->w == w
821 && state.pig->h == h
822 && state.pig->colorspace == state.colorspace) {
823 tile->pixmap = state.pig;
824 tile->pixmap->x = bbox.x0;
825 tile->pixmap->y = bbox.y0;
827 else {
828 fz_drop_pixmap (state.ctx, state.pig);
830 state.pig = NULL;
832 if (!tile->pixmap) {
833 if (pbo) {
834 tile->pixmap =
835 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
836 bbox, pbo->ptr);
837 tile->pbo = pbo;
839 else {
840 tile->pixmap =
841 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox);
845 tile->w = w;
846 tile->h = h;
847 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
848 clearpixmap (tile->pixmap);
850 dev = fz_new_draw_device (state.ctx, tile->pixmap);
851 fz_run_display_list (page->dlist, dev, pagectm (page), bbox, NULL);
852 fz_free_device (dev);
854 return tile;
857 static void initpdims (void)
859 double start, end;
860 int pageno, trim, show;
861 FILE *trimf = NULL;
862 int trimw = 0;
864 start = now ();
866 if (state.trimmargins && state.trimcachepath) {
867 trimf = fopen (state.trimcachepath, "rb");
868 if (!trimf) {
869 trimf = fopen (state.trimcachepath, "wb");
870 trimw = 1;
873 for (pageno = 0; pageno < state.pagecount; ++pageno) {
874 int rotate = 0;
875 struct pagedim *p;
876 fz_rect mediabox;
878 switch (state.type) {
879 case DPDF: {
880 pdf_obj *pageobj = state.u.pdf->page_objs[pageno];
882 if (state.trimmargins) {
883 pdf_obj *obj;
884 pdf_page *page;
886 fz_try (state.ctx) {
887 page = pdf_load_page (state.u.pdf, pageno);
888 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
889 trim = state.trimanew || !obj;
890 if (trim) {
891 fz_rect rect;
892 fz_bbox bbox;
893 fz_matrix ctm;
894 fz_device *dev;
896 dev = fz_new_bbox_device (state.ctx, &bbox);
897 dev->hints |= FZ_IGNORE_SHADE;
898 ctm = fz_invert_matrix (page->ctm);
899 pdf_run_page (state.u.pdf, page, dev, fz_identity, NULL);
900 fz_free_device (dev);
902 rect.x0 = bbox.x0 + state.trimfuzz.x0;
903 rect.x1 = bbox.x1 + state.trimfuzz.x1;
904 rect.y0 = bbox.y0 + state.trimfuzz.y0;
905 rect.y1 = bbox.y1 + state.trimfuzz.y1;
906 rect = fz_transform_rect (ctm, rect);
907 rect = fz_intersect_rect (rect, page->mediabox);
909 if (fz_is_empty_rect (rect)) {
910 mediabox = page->mediabox;
912 else {
913 mediabox = rect;
916 obj = pdf_new_array (state.ctx, 4);
917 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x0));
918 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y0));
919 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x1));
920 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y1));
921 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
923 else {
924 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
925 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
926 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
927 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
930 rotate = page->rotate;
931 pdf_free_page (state.u.pdf, page);
933 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
934 if (show) {
935 printd ("progress %f Trimming %d",
936 (double) (pageno + 1) / state.pagecount,
937 pageno + 1);
940 fz_catch (state.ctx) {
943 else {
944 fz_rect cropbox;
946 mediabox = pdf_to_rect (state.ctx,
947 pdf_dict_gets (pageobj, "MediaBox"));
948 if (fz_is_empty_rect (mediabox)) {
949 fprintf (stderr, "cannot find page size for page %d\n",
950 pageno+1);
951 mediabox.x0 = 0;
952 mediabox.y0 = 0;
953 mediabox.x1 = 612;
954 mediabox.y1 = 792;
957 cropbox = pdf_to_rect (state.ctx,
958 pdf_dict_gets (pageobj, "CropBox"));
959 if (!fz_is_empty_rect (cropbox)) {
960 mediabox = fz_intersect_rect (mediabox, cropbox);
962 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
964 break;
967 case DXPS:
969 xps_page *page;
971 page = xps_load_page (state.u.xps, pageno);
972 mediabox = xps_bound_page (state.u.xps, page);
973 rotate = 0;
974 if (state.trimmargins) {
975 fz_rect rect;
976 fz_bbox bbox;
977 fz_device *dev;
979 dev = fz_new_bbox_device (state.ctx, &bbox);
980 dev->hints |= FZ_IGNORE_SHADE;
981 xps_run_page (state.u.xps, page, dev, fz_identity, NULL);
982 fz_free_device (dev);
984 rect.x0 = bbox.x0 + state.trimfuzz.x0;
985 rect.x1 = bbox.x1 + state.trimfuzz.x1;
986 rect.y0 = bbox.y0 + state.trimfuzz.y0;
987 rect.y1 = bbox.y1 + state.trimfuzz.y1;
988 rect = fz_intersect_rect (rect, mediabox);
990 if (!fz_is_empty_rect (rect)) {
991 mediabox = rect;
994 xps_free_page (state.u.xps, page);
995 printd ("progress %f loading %d",
996 (double) (pageno + 1) / state.pagecount,
997 pageno + 1);
999 break;
1001 case DCBZ:
1003 rotate = 0;
1004 if (state.trimmargins && trimw) {
1005 cbz_page *page;
1007 page = cbz_load_page (state.u.cbz, pageno);
1008 mediabox = cbz_bound_page (state.u.cbz, page);
1009 cbz_free_page (state.u.cbz, page);
1010 printd ("progress %f Trimming %d",
1011 (double) (pageno + 1) / state.pagecount,
1012 pageno + 1);
1013 if (trimf) {
1014 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1015 if (n - 1) {
1016 err (1, "fwrite trim mediabox");
1020 else {
1021 if (trimf) {
1022 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1023 if (n - 1) {
1024 err (1, "fread trim mediabox");
1027 else {
1028 mediabox.x0 = mediabox.y0 = 0;
1029 mediabox.x1 = 900;
1030 mediabox.y1 = 900;
1034 break;
1036 default:
1037 ARSERT (0 && state.type);
1040 if (state.pagedimcount == 0
1041 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1042 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1043 size_t size;
1045 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1046 state.pagedims = realloc (state.pagedims, size);
1047 if (!state.pagedims) {
1048 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1049 size, state.pagedimcount + 1);
1052 p = &state.pagedims[state.pagedimcount++];
1053 p->rotate = rotate;
1054 p->mediabox = mediabox;
1055 p->pageno = pageno;
1058 end = now ();
1059 if (state.trimmargins) {
1060 printd ("progress 1 Trimmed %d pages in %f seconds",
1061 state.pagecount, end - start);
1063 else {
1064 printd ("vmsg Processed %d pages in %f seconds",
1065 state.pagecount, end - start);
1067 state.trimanew = 0;
1068 if (trimf) {
1069 if (fclose (trimf)) {
1070 err (1, "fclose");
1075 static void layout (void)
1077 int pindex;
1078 fz_rect box;
1079 fz_matrix ctm;
1080 double zoom, w, maxw = 0;
1081 struct pagedim *p = state.pagedims;
1083 if (state.proportional) {
1084 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1085 box = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
1086 p->mediabox);
1087 w = box.x1 - box.x0;
1088 maxw = MAX (w, maxw);
1092 p = state.pagedims;
1093 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1094 fz_bbox bbox;
1096 ctm = fz_rotate (state.rotate);
1097 box = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
1098 p->mediabox);
1099 w = box.x1 - box.x0;
1101 if (state.proportional) {
1102 double scale = w / maxw;
1103 zoom = (state.w / w) * scale;
1105 else {
1106 zoom = state.w / w;
1109 p->zoomctm = fz_scale (zoom, zoom);
1110 ctm = fz_concat (p->zoomctm, ctm);
1112 p->pagebox = fz_transform_rect (fz_rotate (p->rotate), p->mediabox);
1113 p->pagebox.x1 -= p->pagebox.x0;
1114 p->pagebox.y1 -= p->pagebox.y0;
1115 p->pagebox.x0 = 0;
1116 p->pagebox.y0 = 0;
1117 bbox = fz_round_rect (fz_transform_rect (ctm, p->pagebox));
1119 p->bounds = bbox;
1120 p->left = state.proportional ? ((maxw - w) * zoom) / 2.0 : 0;
1121 p->ctm = ctm;
1123 ctm = fz_identity;
1124 ctm = fz_concat (ctm, fz_translate (0, -p->mediabox.y1));
1125 ctm = fz_concat (ctm, fz_scale (zoom, -zoom));
1126 ctm = fz_concat (ctm, fz_rotate (p->rotate + state.rotate));
1127 p->lctm = ctm;
1129 p->tctmready = 0;
1132 while (p-- != state.pagedims) {
1133 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1134 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1135 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1136 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1137 int w = x1 - x0;
1138 int h = y1 - y0;
1140 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1144 static void recurse_outline (fz_outline *outline, int level)
1146 while (outline) {
1147 fz_link_dest *dest;
1148 int i, top = 0;
1149 struct pagedim *pdim = state.pagedims;
1151 dest = &outline->dest;
1152 for (i = 0; i < state.pagedimcount; ++i) {
1153 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1154 break;
1155 pdim = &state.pagedims[i];
1157 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1158 fz_point p;
1159 p.x = 0;
1160 p.y = dest->ld.gotor.lt.y;
1161 p = fz_transform_point (pdim->lctm, p);
1162 top = p.y;
1164 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1165 int h;
1166 double y0, y1;
1168 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1169 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1170 h = y1 - y0;
1171 printd ("o %d %d %d %d %s",
1172 level, dest->ld.gotor.page, top, h, outline->title);
1174 if (outline->down) {
1175 recurse_outline (outline->down, level + 1);
1177 outline = outline->next;
1181 static void process_outline (void)
1183 fz_outline *outline;
1185 if (!state.needoutline) return;
1187 state.needoutline = 0;
1188 switch (state.type) {
1189 case DPDF:
1190 outline = pdf_load_outline (state.u.pdf);
1191 break;
1192 case DXPS:
1193 outline = xps_load_outline (state.u.xps);
1194 break;
1195 default:
1196 outline = NULL;
1197 break;
1199 if (outline) {
1200 recurse_outline (outline, 0);
1201 fz_free_outline (state.ctx, outline);
1205 static char *strofspan (fz_text_span *span)
1207 char *p;
1208 char utf8[10];
1209 fz_text_char *ch;
1210 size_t size = 0, cap = 80;
1212 p = malloc (cap + 1);
1213 if (!p) return NULL;
1215 for (ch = span->text; ch < span->text + span->len; ++ch) {
1216 int n = fz_runetochar (utf8, ch->c);
1217 if (size + n > cap) {
1218 cap *= 2;
1219 p = realloc (p, cap + 1);
1220 if (!p) return NULL;
1223 memcpy (p + size, utf8, n);
1224 size += n;
1226 p[size] = 0;
1227 return p;
1230 static int matchspan (regex_t *re, fz_text_span *span, fz_matrix ctm,
1231 int stop, int pageno, double start)
1233 int ret;
1234 char *p;
1235 regmatch_t rm;
1236 int a, b, c;
1237 fz_rect *sb, *eb;
1238 fz_point p1, p2, p3, p4;
1240 p = strofspan (span);
1241 if (!p) return -1;
1243 ret = regexec (re, p, 1, &rm, 0);
1244 if (ret) {
1245 free (p);
1246 if (ret != REG_NOMATCH) {
1247 size_t size;
1248 char errbuf[80];
1249 size = regerror (ret, re, errbuf, sizeof (errbuf));
1250 printd ("msg regexec error `%.*s'",
1251 (int) size, errbuf);
1252 return -1;
1254 return 0;
1256 else {
1257 int l = span->len;
1258 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1259 c += fz_runelen (span->text[a].c);
1261 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1262 c += fz_runelen (span->text[b].c);
1265 if (fz_runelen (span->text[b].c) > 1) {
1266 b = MAX (0, b-1);
1268 sb = &span->text[MIN (a, l-1)].bbox;
1269 eb = &span->text[MIN (b, l-1)].bbox;
1271 p1.x = sb->x0;
1272 p1.y = sb->y0;
1273 p2.x = eb->x1;
1274 p2.y = sb->y0;
1275 p3.x = eb->x1;
1276 p3.y = eb->y1;
1277 p4.x = sb->x0;
1278 p4.y = eb->y1;
1280 if (!stop) {
1281 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1282 pageno, 1,
1283 p1.x, p1.y,
1284 p2.x, p2.y,
1285 p3.x, p3.y,
1286 p4.x, p4.y);
1288 printd ("progress 1 found at %d `%.*s' in %f sec",
1289 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1290 now () - start);
1292 else {
1293 printd ("match %d %d %f %f %f %f %f %f %f %f",
1294 pageno, 2,
1295 p1.x, p1.y,
1296 p2.x, p2.y,
1297 p3.x, p3.y,
1298 p4.x, p4.y);
1300 free (p);
1301 return 1;
1305 static int compareblocks (const void *l, const void *r)
1307 fz_text_block const *ls = l;
1308 fz_text_block const* rs = r;
1309 return ls->bbox.y0 - rs->bbox.y0;
1312 /* wishful thinking function */
1313 static void search (regex_t *re, int pageno, int y, int forward)
1315 int i, j;
1316 fz_matrix ctm;
1317 fz_device *tdev;
1318 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1319 fz_text_page *text;
1320 fz_text_sheet *sheet;
1321 struct pagedim *pdim, *pdimprev;
1322 int stop = 0, niters = 0;
1323 double start, end;
1325 if (!(state.type == DPDF || state.type == DXPS))
1326 return;
1328 start = now ();
1329 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1330 if (niters++ == 5) {
1331 niters = 0;
1332 if (hasdata ()) {
1333 printd ("progress 1 attention requested aborting search at %d",
1334 pageno);
1335 stop = 1;
1337 else {
1338 printd ("progress %f searching in page %d",
1339 (double) (pageno + 1) / state.pagecount,
1340 pageno);
1343 pdimprev = NULL;
1344 for (i = 0; i < state.pagedimcount; ++i) {
1345 pdim = &state.pagedims[i];
1346 if (pdim->pageno == pageno) {
1347 goto found;
1349 if (pdim->pageno > pageno) {
1350 pdim = pdimprev;
1351 goto found;
1353 pdimprev = pdim;
1355 pdim = pdimprev;
1356 found:
1358 sheet = fz_new_text_sheet (state.ctx);
1359 text = fz_new_text_page (state.ctx, fz_infinite_rect);
1360 tdev = fz_new_text_device (state.ctx, sheet, text);
1362 switch (state.type) {
1363 case DPDF:
1364 u.ptr = NULL;
1365 fz_try (state.ctx) {
1366 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1367 trimctm (u.pdfpage, pdim - state.pagedims);
1368 ctm = fz_concat (pdim->tctm, pdim->zoomctm);
1369 pdf_run_page (state.u.pdf, u.pdfpage, tdev, ctm, NULL);
1371 fz_catch (state.ctx) {
1372 fz_free_device (tdev);
1373 u.ptr = NULL;
1374 goto nextiter;
1376 break;
1378 case DXPS:
1379 u.xpspage = xps_load_page (state.u.xps, pageno);
1380 ctm = pdim->ctm;
1381 xps_run_page (state.u.xps, u.xpspage, tdev, ctm, NULL);
1382 break;
1384 default:
1385 ARSERT (0 && state.type);
1388 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1389 fz_free_device (tdev);
1391 for (j = 0; j < text->len; ++j) {
1392 int k;
1393 fz_text_block *block;
1395 block = &text->blocks[forward ? j : text->len - 1 - j];
1397 for (k = 0; k < block->len; ++k) {
1398 fz_text_line *line;
1399 fz_text_span *span;
1401 if (forward) {
1402 line = &block->lines[k];
1403 if (line->bbox.y0 < y + 1) continue;
1405 else {
1406 line = &block->lines[block->len - 1 - k];
1407 if (line->bbox.y0 > y - 1) continue;
1410 for (span = line->spans;
1411 span < line->spans + line->len;
1412 ++span) {
1414 switch (matchspan (re, span, ctm, stop, pageno, start)) {
1415 case 0: break;
1416 case 1: stop = 1; break;
1417 case -1: stop = 1; goto endloop;
1422 nextiter:
1423 if (forward) {
1424 pageno += 1;
1425 y = 0;
1427 else {
1428 pageno -= 1;
1429 y = INT_MAX;
1431 endloop:
1432 fz_free_text_page (state.ctx, text);
1433 fz_free_text_sheet (state.ctx, sheet);
1434 if (u.ptr) {
1435 state.freepage (u.ptr);
1438 end = now ();
1439 if (!stop) {
1440 printd ("progress 1 no matches %f sec", end - start);
1442 printd ("clearrects");
1445 static void set_tex_params (int colorspace)
1447 union {
1448 unsigned char b;
1449 unsigned int s;
1450 } endianness = {1};
1452 switch (colorspace) {
1453 case 0:
1454 state.texiform = GL_RGBA8;
1455 state.texform = GL_RGBA;
1456 state.texty = GL_UNSIGNED_BYTE;
1457 state.colorspace = fz_device_rgb;
1458 break;
1459 case 1:
1460 state.texiform = GL_RGBA8;
1461 state.texform = GL_BGRA;
1462 state.texty = endianness.s > 1
1463 ? GL_UNSIGNED_INT_8_8_8_8
1464 : GL_UNSIGNED_INT_8_8_8_8_REV;
1465 state.colorspace = fz_device_bgr;
1466 break;
1467 case 2:
1468 state.texiform = GL_LUMINANCE_ALPHA;
1469 state.texform = GL_LUMINANCE_ALPHA;
1470 state.texty = GL_UNSIGNED_BYTE;
1471 state.colorspace = fz_device_gray;
1472 break;
1473 default:
1474 errx (1, "invalid colorspce %d", colorspace);
1478 static void realloctexts (int texcount)
1480 size_t size;
1482 if (texcount == state.texcount) return;
1484 if (texcount < state.texcount) {
1485 glDeleteTextures (state.texcount - texcount,
1486 state.texids + texcount);
1489 size = texcount * sizeof (*state.texids);
1490 state.texids = realloc (state.texids, size);
1491 if (!state.texids) {
1492 err (1, "realloc texids %" FMT_s, size);
1495 size = texcount * sizeof (*state.texowners);
1496 state.texowners = realloc (state.texowners, size);
1497 if (!state.texowners) {
1498 err (1, "realloc texowners %" FMT_s, size);
1500 if (texcount > state.texcount) {
1501 int i;
1503 glGenTextures (texcount - state.texcount,
1504 state.texids + state.texcount);
1505 for (i = state.texcount; i < texcount; ++i) {
1506 state.texowners[i].w = -1;
1507 state.texowners[i].slice = NULL;
1510 state.texcount = texcount;
1511 state.texindex = 0;
1514 static char *mbtoutf8 (char *s)
1516 char *p, *r;
1517 wchar_t *tmp;
1518 size_t i, ret, len;
1520 len = mbstowcs (NULL, s, strlen (s));
1521 if (len == 0) {
1522 return s;
1524 else {
1525 if (len == (size_t) -1) {
1526 return s;
1530 tmp = malloc (len * sizeof (wchar_t));
1531 if (!tmp) {
1532 return s;
1535 ret = mbstowcs (tmp, s, len);
1536 if (ret == (size_t) -1) {
1537 free (tmp);
1538 return s;
1541 len = 0;
1542 for (i = 0; i < ret; ++i) {
1543 len += fz_runelen (tmp[i]);
1546 p = r = malloc (len + 1);
1547 if (!r) {
1548 free (tmp);
1549 return s;
1552 for (i = 0; i < ret; ++i) {
1553 p += fz_runetochar (p, tmp[i]);
1555 *p = 0;
1556 free (tmp);
1557 return r;
1560 CAMLprim value ml_mbtoutf8 (value s_v)
1562 CAMLparam1 (s_v);
1563 CAMLlocal1 (ret_v);
1564 char *s, *r;
1566 s = String_val (s_v);
1567 r = mbtoutf8 (s);
1568 if (r == s) {
1569 ret_v = s_v;
1571 else {
1572 ret_v = caml_copy_string (r);
1573 free (r);
1575 CAMLreturn (ret_v);
1578 static void * mainloop (void *unused)
1580 char *p = NULL;
1581 int len, ret, oldlen = 0;
1583 for (;;) {
1584 len = readlen ();
1585 if (len == 0) {
1586 errx (1, "readlen returned 0");
1589 if (oldlen < len + 1) {
1590 p = realloc (p, len + 1);
1591 if (!p) {
1592 err (1, "realloc %d failed", len + 1);
1594 oldlen = len + 1;
1596 readdata (p, len);
1597 p[len] = 0;
1599 if (!strncmp ("open", p, 4)) {
1600 size_t filenamelen;
1601 char *password;
1602 char *filename = p + 5;
1603 char *utf8filename;
1605 filenamelen = strlen (filename);
1606 password = filename + filenamelen + 1;
1608 openxref (filename, password);
1609 pdfinfo ();
1610 initpdims ();
1611 utf8filename = mbtoutf8 (filename);
1612 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1613 if (utf8filename != filename) {
1614 free (utf8filename);
1616 state.needoutline = 1;
1618 else if (!strncmp ("cs", p, 2)) {
1619 int i, colorspace;
1621 ret = sscanf (p + 2, " %d", &colorspace);
1622 if (ret != 1) {
1623 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1625 lock ("cs");
1626 set_tex_params (colorspace);
1627 for (i = 0; i < state.texcount; ++i) {
1628 state.texowners[i].w = -1;
1629 state.texowners[i].slice = NULL;
1631 unlock ("cs");
1633 else if (!strncmp ("freepage", p, 8)) {
1634 void *ptr;
1636 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1637 if (ret != 1) {
1638 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1640 freepage (ptr);
1642 else if (!strncmp ("freetile", p, 8)) {
1643 void *ptr;
1645 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1646 if (ret != 1) {
1647 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1649 freetile (ptr);
1651 else if (!strncmp ("search", p, 6)) {
1652 int icase, pageno, y, ret, len2, forward;
1653 char *pattern;
1654 regex_t re;
1656 ret = sscanf (p + 6, " %d %d %d %d,%n",
1657 &icase, &pageno, &y, &forward, &len2);
1658 if (ret != 4) {
1659 errx (1, "malformed search `%s' ret=%d", p, ret);
1662 pattern = p + 6 + len2;
1663 ret = regcomp (&re, pattern,
1664 REG_EXTENDED | (icase ? REG_ICASE : 0));
1665 if (ret) {
1666 char errbuf[80];
1667 size_t size;
1669 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1670 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1672 else {
1673 search (&re, pageno, y, forward);
1674 regfree (&re);
1677 else if (!strncmp ("geometry", p, 8)) {
1678 int w, h;
1680 printd ("clear");
1681 ret = sscanf (p + 8, " %d %d", &w, &h);
1682 if (ret != 2) {
1683 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1686 lock ("geometry");
1687 state.h = h;
1688 if (w != state.w) {
1689 int i;
1690 state.w = w;
1691 for (i = 0; i < state.texcount; ++i) {
1692 state.texowners[i].slice = NULL;
1695 layout ();
1696 process_outline ();
1697 state.gen++;
1698 unlock ("geometry");
1699 printd ("continue %d", state.pagecount);
1701 else if (!strncmp ("reqlayout", p, 9)) {
1702 int rotate, proportional;
1704 printd ("clear");
1705 ret = sscanf (p + 9, " %d %d", &rotate, &proportional);
1706 if (ret != 2) {
1707 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1709 lock ("reqlayout");
1710 if (state.rotate != rotate || state.proportional != proportional) {
1711 state.gen += 1;
1713 state.rotate = rotate;
1714 state.proportional = proportional;
1715 layout ();
1716 process_outline ();
1717 state.gen++;
1718 unlock ("reqlayout");
1719 printd ("continue %d", state.pagecount);
1721 else if (!strncmp ("page", p, 4)) {
1722 double a, b;
1723 struct page *page;
1724 int pageno, pindex, ret;
1726 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1727 if (ret != 2) {
1728 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1731 lock ("page");
1732 a = now ();
1733 page = loadpage (pageno, pindex);
1734 b = now ();
1735 unlock ("page");
1737 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1739 else if (!strncmp ("tile", p, 4)) {
1740 int x, y, w, h, ret;
1741 struct page *page;
1742 struct tile *tile;
1743 double a, b;
1744 void *data;
1746 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
1747 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
1748 if (ret != 6) {
1749 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1752 lock ("tile");
1753 a = now ();
1754 tile = rendertile (page, x, y, w, h, data);
1755 b = now ();
1756 unlock ("tile");
1758 printd ("tile %d %d %" FMT_ptr " %u %f",
1759 x, y,
1760 FMT_ptr_cast2 (tile),
1761 tile->w * tile->h * tile->pixmap->n,
1762 b - a);
1764 else if (!strncmp ("settrim", p, 7)) {
1765 int trimmargins;
1766 fz_bbox fuzz;
1768 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1769 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1770 if (ret != 5) {
1771 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1773 printd ("clear");
1774 lock ("settrim");
1775 state.trimmargins = trimmargins;
1776 state.needoutline = 1;
1777 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1778 state.trimanew = 1;
1779 state.trimfuzz = fuzz;
1781 state.pagedimcount = 0;
1782 free (state.pagedims);
1783 state.pagedims = NULL;
1784 initpdims ();
1785 layout ();
1786 process_outline ();
1787 unlock ("settrim");
1788 printd ("continue %d", state.pagecount);
1790 else if (!strncmp ("sliceh", p, 6)) {
1791 int h;
1793 ret = sscanf (p + 6, " %d", &h);
1794 if (ret != 1) {
1795 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1797 if (h != state.sliceheight) {
1798 int i;
1800 state.sliceheight = h;
1801 for (i = 0; i < state.texcount; ++i) {
1802 state.texowners[i].w = -1;
1803 state.texowners[i].h = -1;
1804 state.texowners[i].slice = NULL;
1808 else if (!strncmp ("interrupt", p, 9)) {
1809 printd ("vmsg interrupted");
1811 else {
1812 errx (1, "unknown command %.*s", len, p);
1815 return 0;
1818 CAMLprim value ml_realloctexts (value texcount_v)
1820 CAMLparam1 (texcount_v);
1821 int ok;
1823 if (trylock ("ml_realloctexts")) {
1824 ok = 0;
1825 goto done;
1827 realloctexts (Int_val (texcount_v));
1828 ok = 1;
1829 unlock ("ml_realloctexts");
1831 done:
1832 CAMLreturn (Val_bool (ok));
1835 static void showsel (struct page *page, int ox, int oy)
1837 int seen = 0;
1838 fz_bbox bbox;
1839 fz_text_line *line;
1840 fz_text_span *span;
1841 fz_text_block *block;
1842 struct mark first, last;
1844 first = page->fmark;
1845 last = page->lmark;
1847 if (!first.span || !last.span) return;
1849 glEnable (GL_BLEND);
1850 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1851 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1853 ox += state.pagedims[page->pdimno].bounds.x0;
1854 oy += state.pagedims[page->pdimno].bounds.y0;
1855 for (block = page->text->blocks;
1856 block < page->text->blocks + page->text->len;
1857 ++block) {
1858 for (line = block->lines;
1859 line < block->lines + block->len;
1860 ++line) {
1861 for (span = line->spans;
1862 span < line->spans + line->len;
1863 ++span) {
1864 int i, j, k;
1866 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1868 j = 0;
1869 k = span->len - 1;
1871 if (span == page->fmark.span && span == page->lmark.span) {
1872 seen = 1;
1873 j = MIN (first.i, last.i);
1874 k = MAX (first.i, last.i);
1876 else if (span == first.span) {
1877 seen = 1;
1878 j = first.i;
1880 else if (span == last.span) {
1881 seen = 1;
1882 k = last.i;
1885 if (seen) {
1886 for (i = j; i <= k; ++i) {
1887 fz_bbox b = fz_round_rect (span->text[i].bbox);
1888 bbox = fz_union_bbox (bbox, b);
1890 lprintf ("%d %d %d %d oy=%d ox=%d\n",
1891 bbox.x0,
1892 bbox.y0,
1893 bbox.x1,
1894 bbox.y1,
1895 oy, ox);
1897 glRecti (bbox.x0 + ox, bbox.y0 + oy,
1898 bbox.x1 + ox, bbox.y1 + oy);
1899 if (span == last.span) {
1900 goto done;
1906 done:
1907 glDisable (GL_BLEND);
1910 #include "glfont.c"
1912 static void highlightlinks (struct page *page, int xoff, int yoff)
1914 fz_matrix ctm;
1915 fz_link *link, *links;
1917 switch (page->type) {
1918 case DPDF:
1919 links = page->u.pdfpage->links;
1920 break;
1922 case DXPS:
1923 links = page->u.xpspage->links;
1924 break;
1926 default:
1927 return;
1930 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
1931 glEnable (GL_LINE_STIPPLE);
1932 glLineStipple (0.5, 0xcccc);
1934 xoff -= state.pagedims[page->pdimno].bounds.x0;
1935 yoff -= state.pagedims[page->pdimno].bounds.y0;
1936 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1938 glBegin (GL_QUADS);
1939 for (link = links; link; link = link->next) {
1940 fz_point p1, p2, p3, p4;
1942 p1.x = link->rect.x0;
1943 p1.y = link->rect.y0;
1945 p2.x = link->rect.x1;
1946 p2.y = link->rect.y0;
1948 p3.x = link->rect.x1;
1949 p3.y = link->rect.y1;
1951 p4.x = link->rect.x0;
1952 p4.y = link->rect.y1;
1954 p1 = fz_transform_point (ctm, p1);
1955 p2 = fz_transform_point (ctm, p2);
1956 p3 = fz_transform_point (ctm, p3);
1957 p4 = fz_transform_point (ctm, p4);
1959 switch (link->dest.kind) {
1960 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
1961 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
1962 default: glColor3ub (0, 0, 0); break;
1965 glVertex2f (p1.x, p1.y);
1966 glVertex2f (p2.x, p2.y);
1967 glVertex2f (p3.x, p3.y);
1968 glVertex2f (p4.x, p4.y);
1970 glEnd ();
1972 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1973 glDisable (GL_LINE_STIPPLE);
1976 static int compareslinks (const void *l, const void *r)
1978 struct slink const *ls = l;
1979 struct slink const *rs = r;
1980 if (ls->bbox.y0 == rs->bbox.y0) {
1981 return rs->bbox.x0 - rs->bbox.x0;
1983 return ls->bbox.y0 - rs->bbox.y0;
1986 static void droptext (struct page *page)
1988 if (page->text) {
1989 fz_free_text_page (state.ctx, page->text);
1990 page->fmark.i = -1;
1991 page->lmark.i = -1;
1992 page->fmark.span = NULL;
1993 page->lmark.span = NULL;
1994 page->text = NULL;
1996 if (page->sheet) {
1997 fz_free_text_sheet (state.ctx, page->sheet);
2001 static void dropslinks (struct page *page)
2003 if (page->slinks) {
2004 free (page->slinks);
2005 page->slinks = NULL;
2006 page->slinkcount = 0;
2010 static void ensureslinks (struct page *page)
2012 fz_matrix ctm;
2013 int i, count = 0;
2014 size_t slinksize = sizeof (*page->slinks);
2015 fz_link *link, *links;
2017 if (state.gen != page->sgen) {
2018 dropslinks (page);
2019 page->sgen = state.gen;
2021 if (page->slinks) return;
2023 switch (page->type) {
2024 case DPDF:
2025 links = page->u.pdfpage->links;
2026 ctm = fz_concat (trimctm (page->u.pdfpage, page->pdimno),
2027 state.pagedims[page->pdimno].ctm);
2028 break;
2030 case DXPS:
2031 links = page->u.xpspage->links;
2032 ctm = state.pagedims[page->pdimno].ctm;
2033 break;
2035 default:
2036 return;
2039 for (link = links; link; link = link->next) {
2040 count++;
2042 if (count > 0) {
2043 page->slinkcount = count;
2044 page->slinks = calloc (count, slinksize);
2045 if (!page->slinks) {
2046 err (1, "realloc slinks %d", count);
2049 for (i = 0, link = links; link; ++i, link = link->next) {
2050 page->slinks[i].link = link;
2051 page->slinks[i].bbox =
2052 fz_round_rect (fz_transform_rect (ctm, link->rect));
2054 qsort (page->slinks, count, slinksize, compareslinks);
2058 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2059 static void fmt_linkn (char *s, unsigned int u)
2061 unsigned int len; unsigned int q;
2062 int zma = 'z' - 'a' + 1;
2063 len = 1; q = u;
2064 while (q > zma - 1) { ++len; q /= zma; }
2065 if (s) {
2066 s += len;
2067 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2068 /* handles u == 0 */
2070 s[len] = 0;
2073 static void highlightslinks (struct page *page, int xoff, int yoff,
2074 int noff, char *targ, int tlen, int hfsize)
2076 int i;
2077 char buf[40];
2078 struct slink *slink;
2079 double x0, y0, x1, y1, w;
2081 ensureslinks (page);
2082 glColor3ub (0xc3, 0xb0, 0x91);
2083 for (i = 0; i < page->slinkcount; ++i) {
2084 fmt_linkn (buf, i + noff);
2085 if (!tlen || !strncmp (targ, buf, tlen)) {
2086 slink = &page->slinks[i];
2088 x0 = slink->bbox.x0 + xoff - 5;
2089 y1 = slink->bbox.y0 + yoff - 5;
2090 y0 = y1 + 10 + hfsize;
2091 w = measure_string (state.face, hfsize, buf);
2092 x1 = x0 + w + 10;
2093 glRectd (x0, y0, x1, y1);
2097 glEnable (GL_BLEND);
2098 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2099 glEnable (GL_TEXTURE_2D);
2100 glColor3ub (0, 0, 0);
2101 for (i = 0; i < page->slinkcount; ++i) {
2102 fmt_linkn (buf, i + noff);
2103 if (!tlen || !strncmp (targ, buf, tlen)) {
2104 slink = &page->slinks[i];
2106 x0 = slink->bbox.x0 + xoff;
2107 y0 = slink->bbox.y0 + yoff + hfsize;
2108 draw_string (state.face, hfsize, x0, y0, buf);
2111 glDisable (GL_TEXTURE_2D);
2112 glDisable (GL_BLEND);
2116 static void uploadslice (struct tile *tile, struct slice *slice)
2118 int offset;
2119 struct slice *slice1;
2120 unsigned char *texdata;
2122 offset = 0;
2123 for (slice1 = tile->slices; slice != slice1; slice1++) {
2124 offset += slice1->h * tile->w * tile->pixmap->n;
2126 if (slice->texindex != -1 && slice->texindex < state.texcount
2127 && state.texowners[slice->texindex].slice == slice) {
2128 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2130 else {
2131 int subimage = 0;
2132 int texindex = state.texindex++ % state.texcount;
2134 if (state.texowners[texindex].w == tile->w) {
2135 if (state.texowners[texindex].h >= slice->h) {
2136 subimage = 1;
2138 else {
2139 state.texowners[texindex].h = slice->h;
2142 else {
2143 state.texowners[texindex].h = slice->h;
2146 state.texowners[texindex].w = tile->w;
2147 state.texowners[texindex].slice = slice;
2148 slice->texindex = texindex;
2150 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2151 if (tile->pbo) {
2152 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2153 texdata = 0;
2155 else {
2156 texdata = tile->pixmap->samples;
2158 if (subimage) {
2159 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2163 tile->w,
2164 slice->h,
2165 state.texform,
2166 state.texty,
2167 texdata+offset
2170 else {
2171 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2173 state.texiform,
2174 tile->w,
2175 slice->h,
2177 state.texform,
2178 state.texty,
2179 texdata+offset
2182 if (tile->pbo) {
2183 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2188 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2190 CAMLparam2 (args_v, ptr_v);
2191 int dispx = Int_val (Field (args_v, 0));
2192 int dispy = Int_val (Field (args_v, 1));
2193 int dispw = Int_val (Field (args_v, 2));
2194 int disph = Int_val (Field (args_v, 3));
2195 int tilex = Int_val (Field (args_v, 4));
2196 int tiley = Int_val (Field (args_v, 5));
2197 char *s = String_val (ptr_v);
2198 struct tile *tile = parse_pointer ("ml_drawtile", s);
2200 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2202 int slicey, firstslice;
2203 struct slice *slice;
2205 firstslice = tiley / tile->sliceheight;
2206 slice = &tile->slices[firstslice];
2207 slicey = tiley % tile->sliceheight;
2209 while (disph > 0) {
2210 int dh;
2212 dh = slice->h - slicey;
2213 dh = MIN (disph, dh);
2214 uploadslice (tile, slice);
2216 glBegin (GL_QUADS);
2218 glTexCoord2i (tilex, slicey);
2219 glVertex2i (dispx, dispy);
2221 glTexCoord2i (tilex+dispw, slicey);
2222 glVertex2i (dispx+dispw, dispy);
2224 glTexCoord2i (tilex+dispw, slicey+dh);
2225 glVertex2i (dispx+dispw, dispy+dh);
2227 glTexCoord2i (tilex, slicey+dh);
2228 glVertex2i (dispx, dispy+dh);
2230 glEnd ();
2232 dispy += dh;
2233 disph -= dh;
2234 slice++;
2235 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2236 slicey = 0;
2239 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2240 CAMLreturn (Val_unit);
2243 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2244 value xoff_v, value yoff_v,
2245 value li_v)
2247 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2248 int xoff = Int_val (xoff_v);
2249 int yoff = Int_val (yoff_v);
2250 int noff = Int_val (Field (li_v, 0));
2251 char *targ = String_val (Field (li_v, 1));
2252 int tlen = caml_string_length (Field (li_v, 1));
2253 int hfsize = Int_val (Field (li_v, 2));
2254 char *s = String_val (ptr_v);
2255 int hlmask = Int_val (hlinks_v);
2256 struct page *page = parse_pointer ("ml_postprocess", s);
2258 if (!page->u.ptr) {
2259 /* deal with loadpage failed pages */
2260 goto done;
2263 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2264 if (trylock ("ml_postprocess")) {
2265 noff = 0;
2266 goto done;
2268 if (hlmask & 2) {
2269 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2270 noff = page->slinkcount;
2272 showsel (page, xoff, yoff);
2273 unlock ("ml_postprocess");
2275 done:
2276 CAMLreturn (Val_int (noff));
2279 static fz_link *getlink (struct page *page, int x, int y)
2281 fz_point p;
2282 fz_matrix ctm;
2283 fz_link *link, *links;
2285 switch (page->type) {
2286 case DPDF:
2287 ctm = trimctm (page->u.pdfpage, page->pdimno);
2288 links = page->u.pdfpage->links;
2289 break;
2291 case DXPS:
2292 ctm = fz_identity;
2293 links = page->u.xpspage->links;
2294 break;
2296 default:
2297 return NULL;
2299 p.x = x;
2300 p.y = y;
2302 ctm = fz_concat (ctm, state.pagedims[page->pdimno].ctm);
2303 ctm = fz_invert_matrix (ctm);
2304 p = fz_transform_point (ctm, p);
2306 for (link = links; link; link = link->next) {
2307 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2308 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2309 return link;
2313 return NULL;
2316 static void ensuretext (struct page *page)
2318 if (state.gen != page->tgen) {
2319 droptext (page);
2320 page->tgen = state.gen;
2322 if (!page->text) {
2323 fz_device *tdev;
2325 page->text = fz_new_text_page (state.ctx, fz_infinite_rect);
2326 page->sheet = fz_new_text_sheet (state.ctx);
2327 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2328 fz_run_display_list (page->dlist,
2329 tdev,
2330 pagectm (page),
2331 fz_infinite_bbox, NULL);
2332 qsort (page->text->blocks, page->text->len,
2333 sizeof (*page->text->blocks), compareblocks);
2334 fz_free_device (tdev);
2338 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2340 CAMLparam2 (start_page_v, dir_v);
2341 CAMLlocal1 (ret_v);
2342 int i, dir = Int_val (dir_v);
2343 int start_page = Int_val (start_page_v);
2344 int end_page = dir > 0 ? state.pagecount : -1;
2346 ret_v = Val_int (0);
2347 if (!(state.type == DPDF || state.type == DXPS)) {
2348 goto done;
2351 lock ("ml_findpage_with_links");
2352 for (i = start_page + dir; i != end_page; i += dir) {
2353 int found;
2355 switch (state.type) {
2356 case DPDF:
2358 pdf_page *page = NULL;
2360 fz_try (state.ctx) {
2361 page = pdf_load_page (state.u.pdf, i);
2362 found = !!page->links;
2364 fz_catch (state.ctx) {
2365 found = 0;
2367 if (page) {
2368 freepdfpage (page);
2371 break;
2372 case DXPS:
2374 xps_page *page = xps_load_page (state.u.xps, i);
2375 found = !!page->links;
2376 freexpspage (page);
2378 break;
2380 default:
2381 ARSERT ("invalid document type");
2384 if (found) {
2385 ret_v = caml_alloc_small (1, 1);
2386 Field (ret_v, 0) = Val_int (i);
2387 goto unlock;
2390 unlock:
2391 unlock ("ml_findpage_with_links");
2393 done:
2394 CAMLreturn (ret_v);
2397 enum { dir_first, dir_last};
2398 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2400 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2402 CAMLparam2 (ptr_v, dir_v);
2403 CAMLlocal2 (ret_v, pos_v);
2404 struct page *page;
2405 int dirtag, i, slinkindex;
2406 struct slink *found = NULL ,*slink;
2407 char *s = String_val (ptr_v);
2409 page = parse_pointer ("ml_findlink", s);
2410 ret_v = Val_int (0);
2411 if (trylock ("ml_findlink")) {
2412 goto done;
2415 ensureslinks (page);
2417 if (Is_block (dir_v)) {
2418 dirtag = Tag_val (dir_v);
2419 switch (dirtag) {
2420 case dir_first_visible:
2422 int x0, y0, dir, first_index, last_index;
2424 pos_v = Field (dir_v, 0);
2425 x0 = Int_val (Field (pos_v, 0));
2426 y0 = Int_val (Field (pos_v, 1));
2427 dir = Int_val (Field (pos_v, 2));
2429 if (dir >= 0) {
2430 dir = 1;
2431 first_index = 0;
2432 last_index = page->slinkcount;
2434 else {
2435 first_index = page->slinkcount - 1;
2436 last_index = -1;
2439 for (i = first_index; i != last_index; i += dir) {
2440 slink = &page->slinks[i];
2441 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2442 found = slink;
2443 break;
2447 break;
2449 case dir_left:
2450 slinkindex = Int_val (Field (dir_v, 0));
2451 found = &page->slinks[slinkindex];
2452 for (i = slinkindex - 1; i >= 0; --i) {
2453 slink = &page->slinks[i];
2454 if (slink->bbox.x0 < found->bbox.x0) {
2455 found = slink;
2456 break;
2459 break;
2461 case dir_right:
2462 slinkindex = Int_val (Field (dir_v, 0));
2463 found = &page->slinks[slinkindex];
2464 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2465 slink = &page->slinks[i];
2466 if (slink->bbox.x0 > found->bbox.x0) {
2467 found = slink;
2468 break;
2471 break;
2473 case dir_down:
2474 slinkindex = Int_val (Field (dir_v, 0));
2475 found = &page->slinks[slinkindex];
2476 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2477 slink = &page->slinks[i];
2478 if (slink->bbox.y0 >= found->bbox.y0) {
2479 found = slink;
2480 break;
2483 break;
2485 case dir_up:
2486 slinkindex = Int_val (Field (dir_v, 0));
2487 found = &page->slinks[slinkindex];
2488 for (i = slinkindex - 1; i >= 0; --i) {
2489 slink = &page->slinks[i];
2490 if (slink->bbox.y0 <= found->bbox.y0) {
2491 found = slink;
2492 break;
2495 break;
2498 else {
2499 dirtag = Int_val (dir_v);
2500 switch (dirtag) {
2501 case dir_first:
2502 found = page->slinks;
2503 break;
2505 case dir_last:
2506 if (page->slinks) {
2507 found = page->slinks + (page->slinkcount - 1);
2509 break;
2512 if (found) {
2513 ret_v = caml_alloc_small (2, 1);
2514 Field (ret_v, 0) = Val_int (found - page->slinks);
2517 unlock ("ml_findlink");
2518 done:
2519 CAMLreturn (ret_v);
2522 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2524 #define LINKTOVAL \
2526 int pageno; \
2528 switch (link->dest.kind) { \
2529 case FZ_LINK_GOTO: \
2531 fz_point p; \
2533 pageno = link->dest.ld.gotor.page; \
2534 p.x = 0; \
2535 p.y = 0; \
2537 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2538 p.y = link->dest.ld.gotor.lt.y; \
2539 p = fz_transform_point (pdim->lctm, p); \
2541 tup_v = caml_alloc_tuple (2); \
2542 ret_v = caml_alloc_small (1, ugoto); \
2543 Field (tup_v, 0) = Val_int (pageno); \
2544 Field (tup_v, 1) = Val_int (p.y); \
2545 Field (ret_v, 0) = tup_v; \
2547 break; \
2549 case FZ_LINK_URI: \
2550 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2551 ret_v = caml_alloc_small (1, uuri); \
2552 Field (ret_v, 0) = str_v; \
2553 break; \
2555 case FZ_LINK_LAUNCH: \
2556 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2557 ret_v = caml_alloc_small (1, ulaunch); \
2558 Field (ret_v, 0) = str_v; \
2559 break; \
2561 case FZ_LINK_NAMED: \
2562 str_v = caml_copy_string (link->dest.ld.named.named); \
2563 ret_v = caml_alloc_small (1, unamed); \
2564 Field (ret_v, 0) = str_v; \
2565 break; \
2567 case FZ_LINK_GOTOR: \
2568 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2569 pageno = link->dest.ld.gotor.page; \
2570 tup_v = caml_alloc_tuple (2); \
2571 ret_v = caml_alloc_small (1, uremote); \
2572 Field (tup_v, 0) = str_v; \
2573 Field (tup_v, 1) = Val_int (pageno); \
2574 Field (ret_v, 0) = tup_v; \
2575 break; \
2577 default: \
2579 char buf[80]; \
2581 snprintf (buf, sizeof (buf), \
2582 "unhandled link kind %d", link->dest.kind); \
2583 str_v = caml_copy_string (buf); \
2584 ret_v = caml_alloc_small (1, uunexpected); \
2585 Field (ret_v, 0) = str_v; \
2587 break; \
2591 CAMLprim value ml_getlink (value ptr_v, value n_v)
2593 CAMLparam2 (ptr_v, n_v);
2594 CAMLlocal3 (ret_v, tup_v, str_v);
2595 fz_link *link;
2596 struct page *page;
2597 struct pagedim *pdim;
2598 char *s = String_val (ptr_v);
2600 ret_v = Val_int (0);
2601 if (trylock ("ml_getlink")) {
2602 goto done;
2605 page = parse_pointer ("ml_getlink", s);
2606 ensureslinks (page);
2607 pdim = &state.pagedims[page->pdimno];
2608 link = page->slinks[Int_val (n_v)].link;
2609 LINKTOVAL;
2611 unlock ("ml_getlink");
2612 done:
2613 CAMLreturn (ret_v);
2616 CAMLprim value ml_getlinkcount (value ptr_v)
2618 CAMLparam1 (ptr_v);
2619 struct page *page;
2620 char *s = String_val (ptr_v);
2622 page = parse_pointer ("ml_getlinkcount", s);
2623 CAMLreturn (Val_int (page->slinkcount));
2626 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2628 CAMLparam2 (ptr_v, n_v);
2629 CAMLlocal1 (ret_v);
2630 struct page *page;
2631 struct slink *slink;
2632 char *s = String_val (ptr_v);
2634 page = parse_pointer ("ml_getlinkrect", s);
2635 ret_v = caml_alloc_tuple (4);
2636 if (trylock ("ml_getlinkrect")) {
2637 Field (ret_v, 0) = Val_int (0);
2638 Field (ret_v, 1) = Val_int (0);
2639 Field (ret_v, 2) = Val_int (0);
2640 Field (ret_v, 3) = Val_int (0);
2641 goto done;
2643 ensureslinks (page);
2645 slink = &page->slinks[Int_val (n_v)];
2646 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2647 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2648 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2649 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2650 unlock ("ml_getlinkrect");
2652 done:
2653 CAMLreturn (ret_v);
2656 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2658 CAMLparam3 (ptr_v, x_v, y_v);
2659 CAMLlocal3 (ret_v, tup_v, str_v);
2660 fz_link *link;
2661 struct page *page;
2662 char *s = String_val (ptr_v);
2663 int x = Int_val (x_v), y = Int_val (y_v);
2664 struct pagedim *pdim;
2666 ret_v = Val_int (0);
2667 if (trylock ("ml_whatsunder")) {
2668 goto done;
2671 page = parse_pointer ("ml_whatsunder", s);
2672 pdim = &state.pagedims[page->pdimno];
2673 x += pdim->bounds.x0;
2674 y += pdim->bounds.y0;
2675 link = getlink (page, x, y);
2676 if (link) {
2677 LINKTOVAL;
2679 else {
2680 fz_rect *b;
2681 fz_text_block *block;
2683 ensuretext (page);
2684 for (block = page->text->blocks;
2685 block < page->text->blocks + page->text->len;
2686 ++block) {
2687 fz_text_line *line;
2689 b = &block->bbox;
2690 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2691 continue;
2693 for (line = block->lines;
2694 line < block->lines + block->len;
2695 ++line) {
2696 fz_text_span *span;
2698 b = &line->bbox;
2699 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2700 continue;
2702 for (span = line->spans;
2703 span < line->spans + line->len;
2704 ++span) {
2705 fz_text_char *ch;
2707 b = &span->bbox;
2708 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2709 continue;
2711 for (ch = span->text; ch < span->text + span->len; ++ch) {
2712 b = &ch->bbox;
2714 if (x >= b->x0 && x <= b->x1
2715 && y >= b->y0 && y <= b->y1) {
2716 const char *n2 =
2717 span->style->font && span->style->font->name
2718 ? span->style->font->name
2719 : "Span has no font name"
2721 FT_FaceRec *face = span->style->font->ft_face;
2722 if (face && face->family_name) {
2723 char *s;
2724 char *n1 = face->family_name;
2725 size_t l1 = strlen (n1);
2726 size_t l2 = strlen (n2);
2728 if (l1 != l2 || memcmp (n1, n2, l1)) {
2729 s = malloc (l1 + l2 + 2);
2730 if (s) {
2731 memcpy (s, n2, l2);
2732 s[l2] = '=';
2733 memcpy (s + l2 + 1, n1, l1 + 1);
2734 str_v = caml_copy_string (s);
2735 free (s);
2739 if (str_v == 0) {
2740 str_v = caml_copy_string (n2);
2742 ret_v = caml_alloc_small (1, utext);
2743 Field (ret_v, 0) = str_v;
2744 goto unlock;
2751 unlock:
2752 unlock ("ml_whatsunder");
2754 done:
2755 CAMLreturn (ret_v);
2758 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2760 CAMLparam2 (ptr_v, rect_v);
2761 fz_rect *b;
2762 struct page *page;
2763 struct pagedim *pdim;
2764 int i, x0, x1, y0, y1;
2765 char *s = String_val (ptr_v);
2766 int fi = 0, li = 0;
2767 fz_text_block *block;
2768 fz_text_span *span, *fspan, *lspan;
2769 fz_text_line *line, *fline = NULL, *lline = NULL;
2771 if (trylock ("ml_seltext")) {
2772 goto done;
2775 page = parse_pointer ("ml_seltext", s);
2776 ensuretext (page);
2778 pdim = &state.pagedims[page->pdimno];
2779 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2780 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2781 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2782 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2784 if (0) {
2785 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2786 glColor3ub (128, 128, 128);
2787 glRecti (x0, y0, x1, y1);
2788 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2791 fspan = lspan = NULL;
2793 for (block = page->text->blocks;
2794 block < page->text->blocks + page->text->len;
2795 ++block) {
2796 for (line = block->lines;
2797 line < block->lines + block->len;
2798 ++line) {
2799 for (span = line->spans;
2800 span < line->spans + line->len;
2801 ++span) {
2802 for (i = 0; i < span->len; ++i) {
2803 b = &span->text[i].bbox;
2804 int selected = 0;
2806 if (x0 >= b->x0 && x0 <= b->x1
2807 && y0 >= b->y0 && y0 <= b->y1) {
2808 fspan = span;
2809 fline = line;
2810 fi = i;
2811 selected = 1;
2813 if (x1 >= b->x0 && x1 <= b->x1
2814 && y1 >= b->y0 && y1 <= b->y1) {
2815 lspan = span;
2816 lline = line;
2817 li = i;
2818 selected = 1;
2820 if (0 && selected) {
2821 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2822 glColor3ub (128, 128, 128);
2823 glRecti (b->x0, b->y0, b->x1, b->y1);
2824 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2830 if (y1 < y0 || x1 < x0) {
2831 int swap = 0;
2833 if (fspan == lspan) {
2834 swap = 1;
2836 else {
2837 if (y1 < y0) {
2838 if (fline != lline) {
2839 swap = 1;
2844 if (swap) {
2845 i = fi;
2846 span = fspan;
2848 fi = li;
2849 fspan = lspan;
2851 li = i;
2852 lspan = span;
2856 page->fmark.i = fi;
2857 page->fmark.span = fspan;
2859 page->lmark.i = li;
2860 page->lmark.span = lspan;
2862 unlock ("ml_seltext");
2864 done:
2865 CAMLreturn (Val_unit);
2868 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
2870 char buf[4];
2871 int i, len, ret;
2873 for (i = a; i <= b; ++i) {
2874 len = fz_runetochar (buf, span->text[i].c);
2875 ret = fwrite (buf, len, 1, f);
2877 if (ret != 1) {
2878 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
2879 len, ret, strerror (errno));
2880 return -1;
2883 return 0;
2886 #ifdef __CYGWIN__
2887 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
2889 caml_failwith ("ml_popen not implemented under Cygwin");
2891 #else
2892 CAMLprim value ml_popen (value command_v, value fds_v)
2894 CAMLparam2 (command_v, fds_v);
2895 CAMLlocal2 (l_v, tup_v);
2896 int ret;
2897 char *msg = NULL;
2898 value earg_v = Nothing;
2899 posix_spawnattr_t attr;
2900 posix_spawn_file_actions_t fa;
2901 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
2903 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
2904 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
2907 if ((ret = posix_spawnattr_init (&attr)) != 0) {
2908 msg = "posix_spawnattr_init";
2909 goto fail1;
2912 #ifdef POSIX_SPAWN_USEVFORK
2913 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
2914 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
2915 goto fail;
2917 #endif
2919 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
2920 int fd1, fd2;
2922 tup_v = Field (l_v, 0);
2923 fd1 = Int_val (Field (tup_v, 0));
2924 fd2 = Int_val (Field (tup_v, 1));
2925 if (fd2 < 0) {
2926 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
2927 msg = "posix_spawn_file_actions_addclose";
2928 earg_v = tup_v;
2929 goto fail;
2932 else {
2933 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
2934 msg = "posix_spawn_file_actions_adddup2";
2935 earg_v = tup_v;
2936 goto fail;
2941 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
2942 msg = "posix_spawn";
2943 goto fail;
2946 fail:
2947 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
2948 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
2951 fail1:
2952 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
2953 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
2954 strerror (ret));
2957 if (msg)
2958 unix_error (ret, msg, earg_v);
2960 CAMLreturn (Val_unit);
2962 #endif
2964 CAMLprim value ml_copysel (value fd_v, value ptr_v)
2966 CAMLparam1 (ptr_v);
2967 FILE *f;
2968 int seen = 0;
2969 struct page *page;
2970 fz_text_line *line;
2971 fz_text_span *span;
2972 fz_text_block *block;
2973 int fd = Int_val (fd_v);
2974 char *s = String_val (ptr_v);
2976 if (trylock ("ml_copysel")) {
2977 goto done;
2980 page = parse_pointer ("ml_sopysel", s);
2982 if (!page->fmark.span || !page->lmark.span) {
2983 fprintf (stderr, "nothing to copy\n");
2984 goto unlock;
2987 f = fdopen (fd, "w");
2988 if (!f) {
2989 fprintf (stderr, "failed to fopen sel pipe: %s\n",
2990 strerror (errno));
2991 f = stdout;
2994 for (block = page->text->blocks;
2995 block < page->text->blocks + page->text->len;
2996 ++block) {
2997 for (line = block->lines;
2998 line < block->lines + block->len;
2999 ++line) {
3000 for (span = line->spans;
3001 span < line->spans + line->len;
3002 ++span) {
3003 int a, b;
3005 seen |= span == page->fmark.span || span == page->lmark.span;
3006 a = span == page->fmark.span ? page->fmark.i : 0;
3007 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3009 if (seen) {
3010 if (pipespan (f, span, a, b)) {
3011 goto close;
3013 if (span == line->spans + line->len - 1) {
3014 if (putc ('\n', f) == EOF) {
3015 fprintf (stderr,
3016 "failed break line on sel pipe: %s\n",
3017 strerror (errno));
3018 goto close;
3021 if (span == page->lmark.span) {
3022 goto endloop;
3028 endloop:
3029 page->lmark.span = NULL;
3030 page->fmark.span = NULL;
3032 close:
3033 if (f != stdout) {
3034 int ret = fclose (f);
3035 fd = -1;
3036 if (ret == -1) {
3037 if (errno != ECHILD) {
3038 fprintf (stderr, "failed to close sel pipe: %s\n",
3039 strerror (errno));
3043 unlock:
3044 unlock ("ml_copysel");
3046 done:
3047 if (fd >= 0) {
3048 if (close (fd)) {
3049 fprintf (stderr, "failed to close sel pipe: %s\n",
3050 strerror (errno));
3053 CAMLreturn (Val_unit);
3056 CAMLprim value ml_getpdimrect (value pagedimno_v)
3058 CAMLparam1 (pagedimno_v);
3059 CAMLlocal1 (ret_v);
3060 int pagedimno = Int_val (pagedimno_v);
3061 fz_rect box;
3063 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3064 if (trylock ("ml_getpdimrect")) {
3065 box = fz_empty_rect;
3067 else {
3068 box = state.pagedims[pagedimno].mediabox;
3069 unlock ("ml_getpdimrect");
3072 Store_double_field (ret_v, 0, box.x0);
3073 Store_double_field (ret_v, 1, box.x1);
3074 Store_double_field (ret_v, 2, box.y0);
3075 Store_double_field (ret_v, 3, box.y1);
3077 CAMLreturn (ret_v);
3080 static double getmaxw (void)
3082 int i;
3083 struct pagedim *p;
3084 double maxw = 0.0;
3086 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3087 double x0, x1, w;
3089 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
3090 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
3092 w = x1 - x0;
3093 maxw = MAX (w, maxw);
3095 return maxw;
3098 CAMLprim value ml_getmaxw (value unit_v)
3100 CAMLparam1 (unit_v);
3101 CAMLlocal1 (ret_v);
3102 double maxw = 0.0;
3104 if (trylock ("ml_getmaxw")) {
3105 goto done;
3107 maxw = getmaxw ();
3108 unlock ("ml_getmaxw");
3109 done:
3110 ret_v = caml_copy_double (maxw);
3111 CAMLreturn (ret_v);
3114 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3115 value dw_v, value cols_v)
3117 CAMLparam3 (winw_v, winh_v, dw_v);
3118 CAMLlocal1 (ret_v);
3119 int i;
3120 double zoom = 1.0;
3121 double maxw = 0.0, maxh = 0.0;
3122 struct pagedim *p;
3123 double winw = Int_val (winw_v);
3124 double winh = Int_val (winh_v);
3125 double dw = Int_val (dw_v);
3126 double cols = Int_val (cols_v);
3127 double pw = 1.0, ph = 1.0, aspect;
3129 if (trylock ("ml_zoom_for_height")) {
3130 goto done;
3133 if (state.proportional) {
3134 maxw = getmaxw () / cols;
3137 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3138 double x0, x1, y0, y1, w, h, scaledh, scale;
3139 fz_rect rect;
3141 rect = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
3142 p->mediabox);
3143 x0 = MIN (rect.x0, rect.x1);
3144 x1 = MAX (rect.x0, rect.x1);
3145 y0 = MIN (rect.y0, rect.y1);
3146 y1 = MAX (rect.y0, rect.y1);
3148 w = (x1 - x0) / cols;
3149 h = y1 - y0;
3151 if (state.proportional) {
3152 scale = w / maxw;
3153 scaledh = h * scale;
3155 else {
3156 scale = 1.0;
3157 scaledh = h;
3160 if (scaledh > maxh) {
3161 maxh = scaledh;
3162 ph = scaledh;
3163 pw = w * scale;
3167 aspect = pw / ph;
3168 zoom = (winh * aspect + dw) / winw;
3170 unlock ("ml_zoom_for_height");
3171 done:
3172 ret_v = caml_copy_double (zoom);
3173 CAMLreturn (ret_v);
3176 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3178 CAMLparam4 (pt_v, x_v, y_v, string_v);
3179 CAMLlocal1 (ret_v);
3180 int pt = Int_val(pt_v);
3181 int x = Int_val (x_v);
3182 int y = Int_val (y_v);
3183 double w;
3185 w = draw_string (state.face, pt, x, y, String_val (string_v));
3186 ret_v = caml_copy_double (w);
3187 CAMLreturn (ret_v);
3190 CAMLprim value ml_measure_string (value pt_v, value string_v)
3192 CAMLparam2 (pt_v, string_v);
3193 CAMLlocal1 (ret_v);
3194 int pt = Int_val (pt_v);
3195 double w;
3197 w = measure_string (state.face, pt, String_val (string_v));
3198 ret_v = caml_copy_double (w);
3199 CAMLreturn (ret_v);
3202 CAMLprim value ml_getpagebox (value opaque_v)
3204 CAMLparam1 (opaque_v);
3205 CAMLlocal1 (ret_v);
3206 fz_bbox bbox;
3207 fz_device *dev;
3208 char *s = String_val (opaque_v);
3209 struct page *page = parse_pointer ("ml_getpagebox", s);
3211 ret_v = caml_alloc_tuple (4);
3212 dev = fz_new_bbox_device (state.ctx, &bbox);
3213 dev->hints |= FZ_IGNORE_SHADE;
3215 switch (page->type) {
3216 case DPDF:
3217 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, pagectm (page), NULL);
3218 break;
3220 case DXPS:
3221 xps_run_page (state.u.xps, page->u.xpspage, dev, pagectm (page), NULL);
3222 break;
3224 default:
3225 bbox = fz_infinite_bbox;
3226 break;
3229 fz_free_device (dev);
3230 Field (ret_v, 0) = Val_int (bbox.x0);
3231 Field (ret_v, 1) = Val_int (bbox.y0);
3232 Field (ret_v, 2) = Val_int (bbox.x1);
3233 Field (ret_v, 3) = Val_int (bbox.y1);
3235 CAMLreturn (ret_v);
3238 CAMLprim value ml_setaalevel (value level_v)
3240 CAMLparam1 (level_v);
3242 state.aalevel = Int_val (level_v);
3243 CAMLreturn (Val_unit);
3246 #undef pixel
3247 #include <X11/Xlib.h>
3248 #include <GL/glx.h>
3250 static struct {
3251 Display *dpy;
3252 GLXContext ctx;
3253 GLXDrawable drawable;
3254 } glx;
3256 #include "keysym2ucs.c"
3258 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3260 CAMLparam1 (keysym_v);
3261 CAMLlocal1 (str_v);
3262 KeySym keysym = Int_val (keysym_v);
3263 Rune rune;
3264 int len;
3265 char buf[5];
3267 rune = keysym2ucs (keysym);
3268 len = fz_runetochar (buf, rune);
3269 buf[len] = 0;
3270 str_v = caml_copy_string (buf);
3271 CAMLreturn (str_v);
3274 CAMLprim value ml_glx (value win_v)
3276 CAMLparam1 (win_v);
3277 XVisualInfo *visual;
3278 int screen, wid = Int_val (win_v);
3279 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3281 glx.dpy = XOpenDisplay (NULL);
3282 if (!glx.dpy) {
3283 caml_failwith ("XOpenDisplay");
3286 screen = DefaultScreen (glx.dpy);
3287 visual = glXChooseVisual (glx.dpy, screen, attributes);
3288 if (!visual) {
3289 XCloseDisplay (glx.dpy);
3290 glx.dpy = NULL;
3291 caml_failwith ("glXChooseVisual");
3294 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3295 XFree (visual);
3296 if (!glx.ctx) {
3297 XCloseDisplay (glx.dpy);
3298 glx.dpy = NULL;
3299 caml_failwith ("glXCreateContext");
3302 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3303 glXDestroyContext (glx.dpy, glx.ctx);
3304 XCloseDisplay (glx.dpy);
3305 glx.dpy = NULL;
3306 glx.ctx = NULL;
3307 caml_failwith ("glXMakeCurrent");
3309 glx.drawable = wid;
3310 CAMLreturn (Val_unit);
3313 CAMLprim value ml_swapb (value unit_v)
3315 CAMLparam1 (unit_v);
3316 glXSwapBuffers (glx.dpy, glx.drawable);
3317 CAMLreturn (Val_unit);
3320 CAMLprim value ml_glxsync (value unit_v)
3322 CAMLparam1 (unit_v);
3323 if (glx.dpy && glx.ctx) {
3324 glXWaitX ();
3325 glXWaitGL ();
3327 CAMLreturn (Val_unit);
3330 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3331 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3333 CAMLprim value ml_platform (value unit_v)
3335 CAMLparam1 (unit_v);
3336 int platid = piunknown;
3338 #if defined __linux__
3339 platid = pilinux;
3340 #elif defined __CYGWIN__
3341 platid = picygwin;
3342 #elif defined __DragonFly__
3343 platid = pidragonflybsd;
3344 #elif defined __FreeBSD__
3345 platid = pifreebsd;
3346 #elif defined __OpenBSD__
3347 platid = piopenbsd;
3348 #elif defined __NetBSD__
3349 platid = pinetbsd;
3350 #elif defined __sun__
3351 platid = pisun;
3352 #elif defined __APPLE__
3353 platid = piosx;
3354 #endif
3355 CAMLreturn (Val_int (platid));
3358 CAMLprim value ml_cloexec (value fd_v)
3360 CAMLparam1 (fd_v);
3361 int fd = Int_val (fd_v);
3363 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3364 uerror ("fcntl", Nothing);
3366 CAMLreturn (Val_unit);
3369 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3371 CAMLparam2 (w_v, h_v);
3372 CAMLlocal1 (ret_v);
3373 struct pbo *pbo;
3374 int w = Int_val (w_v);
3375 int h = Int_val (h_v);
3376 int cs = Int_val (cs_v);
3378 if (state.pbo_usable) {
3379 pbo = calloc (sizeof (*pbo), 1);
3380 if (!pbo) {
3381 err (1, "calloc pbo");
3384 switch (cs) {
3385 case 0:
3386 case 1:
3387 pbo->size = w*h*4;
3388 break;
3389 case 2:
3390 pbo->size = w*h*2;
3391 break;
3392 default:
3393 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3396 state.glGenBuffersARB (1, &pbo->id);
3397 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3398 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3399 NULL, GL_STREAM_DRAW);
3400 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3401 GL_READ_WRITE);
3402 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3403 if (!pbo->ptr) {
3404 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3405 state.glDeleteBuffersARB (1, &pbo->id);
3406 free (pbo);
3407 ret_v = caml_copy_string ("0");
3409 else {
3410 int res;
3411 char *s;
3413 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3414 if (res < 0) {
3415 err (1, "snprintf %" FMT_ptr " failed", pbo);
3417 s = malloc (res+1);
3418 if (!s) {
3419 err (1, "malloc %d bytes failed", res+1);
3421 res = sprintf (s, "%" FMT_ptr, pbo);
3422 if (res < 0) {
3423 err (1, "sprintf %" FMT_ptr " failed", pbo);
3425 ret_v = caml_copy_string (s);
3426 free (s);
3429 else {
3430 ret_v = caml_copy_string ("0");
3432 CAMLreturn (ret_v);
3435 CAMLprim value ml_freepbo (value s_v)
3437 CAMLparam1 (s_v);
3438 char *s = String_val (s_v);
3439 struct tile *tile = parse_pointer ("ml_freepbo", s);
3441 if (tile->pbo) {
3442 state.glDeleteBuffersARB (1, &tile->pbo->id);
3443 tile->pbo->id = -1;
3444 tile->pbo->ptr = NULL;
3445 tile->pbo->size = -1;
3447 CAMLreturn (Val_unit);
3450 CAMLprim value ml_unmappbo (value s_v)
3452 CAMLparam1 (s_v);
3453 char *s = String_val (s_v);
3454 struct tile *tile = parse_pointer ("ml_unmappbo", s);
3456 if (tile->pbo) {
3457 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3458 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3459 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3461 tile->pbo->ptr = NULL;
3462 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3464 CAMLreturn (Val_unit);
3467 static void setuppbo (void)
3469 #define GGPA(n) *(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n)
3470 GGPA (glBindBufferARB);
3471 if (state.glBindBufferARB) {
3472 GGPA (glUnmapBufferARB);
3473 if (state.glUnmapBufferARB) {
3474 GGPA (glMapBufferARB);
3475 if (state.glMapBufferARB) {
3476 GGPA (glBufferDataARB);
3477 if (state.glBufferDataARB) {
3478 GGPA (glGenBuffersARB);
3479 if (state.glGenBuffersARB) {
3480 GGPA (glDeleteBuffersARB);
3481 if (state.glDeleteBuffersARB) {
3482 state.pbo_usable = 1;
3489 #undef GGPA
3492 CAMLprim value ml_pbo_usable (value unit_v)
3494 CAMLparam1 (unit_v);
3495 CAMLreturn (Val_bool (state.pbo_usable));
3498 CAMLprim value ml_init (value pipe_v, value params_v)
3500 CAMLparam2 (pipe_v, params_v);
3501 CAMLlocal2 (trim_v, fuzz_v);
3502 int ret;
3503 int texcount;
3504 char *fontpath;
3505 int colorspace;
3506 int mustoresize;
3507 int haspboext;
3508 struct sigaction sa;
3510 state.cr = Int_val (Field (pipe_v, 0));
3511 state.cw = Int_val (Field (pipe_v, 1));
3512 state.rotate = Int_val (Field (params_v, 0));
3513 state.proportional = Bool_val (Field (params_v, 1));
3514 trim_v = Field (params_v, 2);
3515 texcount = Int_val (Field (params_v, 3));
3516 state.sliceheight = Int_val (Field (params_v, 4));
3517 mustoresize = Int_val (Field (params_v, 5));
3518 colorspace = Int_val (Field (params_v, 6));
3519 fontpath = String_val (Field (params_v, 7));
3520 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
3521 if (!state.trimcachepath) {
3522 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
3523 strerror (errno));
3525 haspboext = Bool_val (Field (params_v, 9));
3527 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3529 state.trimmargins = Bool_val (Field (trim_v, 0));
3530 fuzz_v = Field (trim_v, 1);
3531 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3532 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3533 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3534 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3536 set_tex_params (colorspace);
3538 if (*fontpath) {
3539 state.face = load_font (fontpath);
3541 else {
3542 unsigned int len;
3543 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
3545 state.face = load_builtin_font (base, len);
3547 if (!state.face) _exit (1);
3549 realloctexts (texcount);
3551 if (haspboext) {
3552 setuppbo ();
3555 #ifdef __CYGWIN__
3556 sa.sa_handler = SIG_IGN;
3557 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3558 #else
3559 sa.sa_handler = SIG_DFL;
3560 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
3561 #endif
3562 if (sigemptyset (&sa.sa_mask)) {
3563 err (1, "sigemptyset");
3565 if (sigaction (SIGCHLD, &sa, NULL)) {
3566 err (1, "sigaction");
3569 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3570 if (ret) {
3571 errx (1, "pthread_create: %s", strerror (ret));
3574 CAMLreturn (Val_unit);