Do the right thing
[llpp.git] / link.c
blob066da76032dfe285de2e9977294e0596ef66ba26
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>
9 #include <unistd.h>
10 #include <pthread.h>
11 #include <sys/time.h>
12 #include <sys/types.h>
13 #include <sys/ioctl.h>
15 #include <regex.h>
16 #include <ctype.h>
17 #include <stdarg.h>
18 #include <limits.h>
20 #ifdef __APPLE__
21 #include <OpenGL/gl.h>
22 #else
23 #include <GL/gl.h>
24 #endif
26 #include <caml/fail.h>
27 #include <caml/alloc.h>
28 #include <caml/memory.h>
29 #include <caml/unixsupport.h>
31 #include <fitz.h>
32 #include <mupdf.h>
33 #include <muxps.h>
34 #include <mucbz.h>
36 #include FT_FREETYPE_H
38 #define PIGGYBACK
40 #if defined __GNUC__
41 #define NORETURN __attribute__ ((noreturn))
42 #define UNUSED __attribute__ ((unused))
43 #define OPTIMIZE(n) __attribute__ ((optimize ("O"#n)))
44 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
45 #else
46 #define NORETURN
47 #define UNUSED
48 #define OPTIMIZE(n)
49 #define GCC_FMT_ATTR(a, b)
50 #endif
52 #define FMT_s "zu"
54 #define FMT_ptr "p"
55 #define FMT_ptr_cast(p) (p)
56 #define FMT_ptr_cast2(p) (p)
58 static void NORETURN GCC_FMT_ATTR (2, 3)
59 err (int exitcode, const char *fmt, ...)
61 va_list ap;
62 int savederrno;
64 savederrno = errno;
65 va_start (ap, fmt);
66 vfprintf (stderr, fmt, ap);
67 va_end (ap);
68 fprintf (stderr, ": %s\n", strerror (savederrno));
69 fflush (stderr);
70 _exit (exitcode);
73 static void NORETURN GCC_FMT_ATTR (2, 3)
74 errx (int exitcode, const char *fmt, ...)
76 va_list ap;
78 va_start (ap, fmt);
79 vfprintf (stderr, fmt, ap);
80 va_end (ap);
81 fputc ('\n', stderr);
82 fflush (stderr);
83 _exit (exitcode);
86 #ifndef GL_TEXTURE_RECTANGLE_ARB
87 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
88 #endif
90 #ifndef GL_BGRA
91 #define GL_BGRA 0x80E1
92 #endif
94 #ifndef GL_UNSIGNED_INT_8_8_8_8
95 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
96 #endif
98 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
99 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
100 #endif
102 #if 0
103 #define lprintf printf
104 #else
105 #define lprintf(...)
106 #endif
108 #define ARSERT(cond) for (;;) { \
109 if (!(cond)) { \
110 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
112 break; \
115 struct slice {
116 int h;
117 int texindex;
120 struct tile {
121 int x, y, w, h;
122 int slicecount;
123 int sliceheight;
124 fz_pixmap *pixmap;
125 struct slice slices[1];
128 struct pagedim {
129 int pageno;
130 int rotate;
131 int left;
132 int tctmready;
133 fz_bbox bounds;
134 fz_rect pagebox;
135 fz_rect mediabox;
136 fz_matrix ctm, zoomctm, lctm, tctm;
139 struct slink {
140 fz_bbox bbox;
141 fz_link *link;
144 enum { DPDF, DXPS, DCBZ };
146 struct page {
147 int gen;
148 int type;
149 int pageno;
150 int pdimno;
151 fz_text_span *text;
152 union {
153 void *ptr;
154 pdf_page *pdfpage;
155 xps_page *xpspage;
156 cbz_page *cbzpage;
157 } u;
158 fz_display_list *dlist;
159 int slinkcount;
160 struct slink *slinks;
161 struct mark {
162 int i;
163 fz_text_span *span;
164 } fmark, lmark;
165 void (*freepage) (void *);
168 struct {
169 int type;
170 int sliceheight;
171 struct pagedim *pagedims;
172 int pagecount;
173 int pagedimcount;
174 union {
175 pdf_document *pdf;
176 xps_document *xps;
177 cbz_document *cbz;
178 } u;
179 fz_context *ctx;
180 fz_glyph_cache *cache;
181 int w, h;
183 int texindex;
184 int texcount;
185 GLuint *texids;
187 GLenum texiform;
188 GLenum texform;
189 GLenum texty;
191 fz_colorspace *colorspace;
193 struct {
194 int w, h;
195 struct slice *slice;
196 } *texowners;
198 int rotate;
199 int proportional;
200 int trimmargins;
201 int needoutline;
202 int gen;
203 int aalevel;
205 int trimanew;
206 fz_bbox trimfuzz;
207 fz_pixmap *pig;
209 pthread_t thread;
210 int cr, cw;
211 FT_Face face;
213 void (*closedoc) (void);
214 void (*freepage) (void *);
215 } state;
217 static void UNUSED debug_rect (const char *cap, fz_rect r)
219 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
222 static void UNUSED debug_bbox (const char *cap, fz_bbox r)
224 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
227 static void UNUSED debug_matrix (const char *cap, fz_matrix m)
229 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
230 m.a, m.b, m.c, m.d, m.e, m.f);
233 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
235 static void lock (const char *cap)
237 int ret = pthread_mutex_lock (&mutex);
238 if (ret) {
239 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
243 static void unlock (const char *cap)
245 int ret = pthread_mutex_unlock (&mutex);
246 if (ret) {
247 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
251 static int trylock (const char *cap)
253 int ret = pthread_mutex_trylock (&mutex);
255 if (ret && ret != EBUSY) {
256 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
258 return ret == EBUSY;
261 static void *parse_pointer (const char *cap, const char *s)
263 int ret;
264 void *ptr;
266 ret = sscanf (s, "%" FMT_ptr, FMT_ptr_cast (&ptr));
267 if (ret != 1) {
268 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
270 return ptr;
273 static double now (void)
275 struct timeval tv;
277 if (gettimeofday (&tv, NULL)) {
278 err (1, "gettimeofday");
280 return tv.tv_sec + tv.tv_usec*1e-6;
283 static int hasdata (void)
285 int ret, avail;
286 ret = ioctl (state.cr, FIONREAD, &avail);
287 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
288 return avail > 0;
291 CAMLprim value ml_hasdata (value fd_v)
293 CAMLparam1 (fd_v);
294 int ret, avail;
296 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
297 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
298 CAMLreturn (Val_bool (avail > 0));
301 static void readdata (void *p, int size)
303 ssize_t n;
305 n = read (state.cr, p, size);
306 if (n - size) {
307 if (!n) errx (1, "EOF while reading");
308 err (1, "read (req %d, ret %zd)", size, n);
312 static void writedata (char *p, int size)
314 char buf[4];
315 ssize_t n;
317 buf[0] = (size >> 24) & 0xff;
318 buf[1] = (size >> 16) & 0xff;
319 buf[2] = (size >> 8) & 0xff;
320 buf[3] = (size >> 0) & 0xff;
322 n = write (state.cw, buf, 4);
323 if (n != 4) {
324 if (!n) errx (1, "EOF while writing length");
325 err (1, "write %zd", n);
328 n = write (state.cw, p, size);
329 if (n - size) {
330 if (!n) errx (1, "EOF while writing data");
331 err (1, "write (req %d, ret %zd)", size, n);
335 static int readlen (void)
337 unsigned char p[4];
339 readdata (p, 4);
340 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
343 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
345 int size = 200, len;
346 va_list ap;
347 char *buf;
349 buf = malloc (size);
350 for (;;) {
351 if (!buf) err (errno, "malloc for temp buf (%d bytes) failed", size);
353 va_start (ap, fmt);
354 len = vsnprintf (buf, size, fmt, ap);
355 va_end (ap);
357 if (len > -1 && len < size) {
358 writedata (buf, len);
359 break;
362 if (len > -1) {
363 size = len + 1;
365 else {
366 size *= 2;
368 buf = realloc (buf, size);
370 free (buf);
373 static void closepdf (void)
375 if (state.u.pdf) {
376 pdf_close_document (state.u.pdf);
377 state.u.pdf = NULL;
381 static void closexps (void)
383 if (state.u.xps) {
384 xps_close_document (state.u.xps);
385 state.u.xps = NULL;
389 static void closecbz (void)
391 if (state.u.cbz) {
392 cbz_close_document (state.u.cbz);
393 state.u.cbz = NULL;
397 static void freepdfpage (void *ptr)
399 pdf_free_page (state.u.pdf, ptr);
402 static void freexpspage (void *ptr)
404 xps_free_page (state.u.xps, ptr);
407 static void freecbzpage (void *ptr)
409 cbz_free_page (state.u.cbz, ptr);
412 static void openxref (char *filename, char *password)
414 int i, len;
416 for (i = 0; i < state.texcount; ++i) {
417 state.texowners[i].w = -1;
418 state.texowners[i].slice = NULL;
421 if (state.closedoc) state.closedoc ();
423 len = strlen (filename);
425 state.type = DPDF;
426 if (len > 4) {
427 char ext[4];
429 ext[0] = tolower (filename[len-3]);
430 ext[1] = tolower (filename[len-2]);
431 ext[2] = tolower (filename[len-1]);
433 /**/ if (ext[0] == 'x' && ext[1] == 'p' && ext[2] == 's') {
434 state.type = DXPS;
436 else if (ext[0] == 'c' && ext[1] == 'b' && ext[2] == 'z') {
437 state.type = DCBZ;
441 if (state.pagedims) {
442 free (state.pagedims);
443 state.pagedims = NULL;
445 state.pagedimcount = 0;
447 fz_set_aa_level (state.ctx, state.aalevel);
448 switch (state.type) {
449 case DPDF:
450 state.u.pdf = pdf_open_document (state.ctx, filename);
451 if (pdf_needs_password (state.u.pdf)) {
452 int okay = pdf_authenticate_password (state.u.pdf, password);
453 if (!okay) {
454 errx (1, "invalid password");
457 state.pagecount = pdf_count_pages (state.u.pdf);
458 state.closedoc = closepdf;
459 state.freepage = freepdfpage;
460 break;
462 case DXPS:
463 state.u.xps = xps_open_document (state.ctx, filename);
464 state.pagecount = xps_count_pages (state.u.xps);
465 state.closedoc = closexps;
466 state.freepage = freexpspage;
467 break;
469 case DCBZ:
470 state.u.cbz = cbz_open_document (state.ctx, filename);
471 state.pagecount = cbz_count_pages (state.u.cbz);
472 state.closedoc = closecbz;
473 state.freepage = freecbzpage;
474 break;
478 static void pdfinfo (void)
480 if (state.type == DPDF) {
481 fz_obj *infoobj;
483 printd ("info PDF version\t%d.%d",
484 state.u.pdf->version / 10, state.u.pdf->version % 10);
486 infoobj = fz_dict_gets (state.u.pdf->trailer, "Info");
487 if (infoobj) {
488 int i;
489 char *s;
490 char *items[] = { "Title", "Author", "Creator",
491 "Producer", "CreationDate" };
493 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
494 fz_obj *obj = fz_dict_gets (infoobj, items[i]);
495 s = pdf_to_utf8 (state.ctx, obj);
496 if (*s) {
497 if (i == 0) {
498 printd ("title %s", s);
500 printd ("info %s\t%s", items[i], s);
502 fz_free (state.ctx, s);
505 printd ("infoend");
509 static void unlinktile (struct tile *tile)
511 int i;
513 for (i = 0; i < tile->slicecount; ++i) {
514 struct slice *s = &tile->slices[i];
516 if (s->texindex != -1) {
517 if (state.texowners[s->texindex].slice == s) {
518 state.texowners[s->texindex].slice = NULL;
524 static void freepage (struct page *page)
526 if (page->text) {
527 fz_free_text_span (state.ctx, page->text);
529 if (page->slinks) {
530 free (page->slinks);
532 page->freepage (page->u.ptr);
533 fz_free_display_list (state.ctx, page->dlist);
534 free (page);
537 static void freetile (struct tile *tile)
539 unlinktile (tile);
540 #ifndef PIGGYBACK
541 fz_drop_pixmap (state.ctx, tile->pixmap);
542 #else
543 if (state.pig) {
544 fz_drop_pixmap (state.ctx, state.pig);
546 state.pig = tile->pixmap;
547 #endif
548 free (tile);
551 #ifdef __ALTIVEC__
552 #include <altivec.h>
554 static int cacheline32bytes;
555 extern char **environ;
557 static void __attribute__ ((constructor)) clcheck (void)
559 char **envp = environ;
560 unsigned long *auxv;
562 while (*envp++);
564 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
565 if (*auxv == 19) {
566 cacheline32bytes = auxv[1] == 32;
567 return;
572 static void OPTIMIZE (3) clearpixmap (fz_pixmap *pixmap)
574 if (cacheline32bytes) {
575 intptr_t a1, a2, diff;
576 size_t sizea, i, size = pixmap->w * pixmap->h * pixmap->n;
577 vector unsigned char v = vec_splat_u8 (-1);
578 vector unsigned char *p;
580 a1 = a2 = (intptr_t) pixmap->samples;
581 a2 = (a1 + 31) & ~31;
582 diff = a2 - a1;
583 sizea = size - diff;
584 p = (void *) a2;
586 while (a1 != a2) *(char *) a1++ = 0xff;
587 for (i = 0; i < (sizea & ~31); i += 32) {
588 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
589 vec_st (v, i, p);
590 vec_st (v, i + 16, p);
592 while (i < sizea) *((char *) a1 + i++) = 0xff;
594 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
596 #else
597 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
598 #endif
600 static fz_matrix trimctm (pdf_page *page, int pindex)
602 fz_matrix ctm;
603 struct pagedim *pdim = &state.pagedims[pindex];
605 if (!pdim->tctmready) {
606 if (state.trimmargins) {
607 fz_rect realbox;
609 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
610 realbox = fz_transform_rect (ctm, pdim->mediabox);
611 ctm = fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0));
612 ctm = fz_concat (fz_invert_matrix (page->ctm), ctm);
614 else {
615 ctm = fz_identity;
617 pdim->tctm = ctm;
618 pdim->tctmready = 1;
620 return pdim->tctm;
623 static fz_matrix pagectm (struct page *page)
625 if (page->type == DPDF) {
626 return fz_concat (trimctm (page->u.pdfpage, page->pdimno),
627 state.pagedims[page->pdimno].ctm);
629 else {
630 fz_matrix ctm;
631 struct pagedim *pdim = &state.pagedims[page->pdimno];
633 ctm = state.pagedims[page->pdimno].ctm;
634 ctm = fz_concat (fz_translate (-pdim->mediabox.x0,
635 -pdim->mediabox.y0), ctm);
636 return ctm;
640 static void *loadpage (int pageno, int pindex)
642 fz_device *dev;
643 struct page *page = NULL;
645 page = calloc (sizeof (struct page), 1);
646 if (!page) {
647 err (1, "calloc page %d", pageno);
650 page->dlist = fz_new_display_list (state.ctx);
651 dev = fz_new_list_device (state.ctx, page->dlist);
652 switch (state.type) {
653 case DPDF:
654 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
655 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, fz_identity, NULL);
656 page->freepage = freepdfpage;
657 break;
659 case DXPS:
660 page->u.xpspage = xps_load_page (state.u.xps, pageno);
661 xps_run_page (state.u.xps, page->u.xpspage, dev, fz_identity, NULL);
662 page->freepage = freexpspage;
663 break;
665 case DCBZ:
666 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
667 cbz_run_page (state.u.cbz, page->u.cbzpage, dev, fz_identity, NULL);
668 page->freepage = freecbzpage;
669 break;
671 fz_free_device (dev);
673 page->pdimno = pindex;
674 page->pageno = pageno;
675 page->gen = state.gen;
676 page->type = state.type;
678 return page;
681 static struct tile *alloctile (int h)
683 int i;
684 int slicecount;
685 size_t tilesize;
686 struct tile *tile;
688 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
689 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
690 tile = calloc (tilesize, 1);
691 if (!tile) {
692 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
694 for (i = 0; i < slicecount; ++i) {
695 int sh = MIN (h, state.sliceheight);
696 tile->slices[i].h = sh;
697 tile->slices[i].texindex = -1;
698 h -= sh;
700 tile->slicecount = slicecount;
701 tile->sliceheight = state.sliceheight;
702 return tile;
705 static struct tile *rendertile (struct page *page, int x, int y, int w, int h)
707 fz_bbox bbox;
708 fz_device *dev;
709 struct tile *tile;
710 struct pagedim *pdim;
712 tile = alloctile (h);
713 pdim = &state.pagedims[page->pdimno];
715 bbox = pdim->bounds;
716 bbox.x0 += x;
717 bbox.y0 += y;
718 bbox.x1 = bbox.x0 + w;
719 bbox.y1 = bbox.y0 + h;
721 if (state.pig) {
722 if (state.pig->w == w
723 && state.pig->h == h
724 && state.pig->colorspace == state.colorspace) {
725 tile->pixmap = state.pig;
726 tile->pixmap->x = bbox.x0;
727 tile->pixmap->y = bbox.y0;
729 else {
730 fz_drop_pixmap (state.ctx, state.pig);
732 state.pig = NULL;
734 if (!tile->pixmap) {
735 tile->pixmap =
736 fz_new_pixmap_with_rect (state.ctx, state.colorspace, bbox);
739 tile->w = w;
740 tile->h = h;
741 clearpixmap (tile->pixmap);
742 dev = fz_new_draw_device (state.ctx, tile->pixmap);
743 fz_run_display_list (page->dlist, dev, pagectm (page), bbox, NULL);
744 fz_free_device (dev);
746 return tile;
749 static void initpdims (void)
751 int pageno;
752 double start, end;
754 start = now ();
755 for (pageno = 0; pageno < state.pagecount; ++pageno) {
756 int rotate;
757 fz_obj *pageobj;
758 struct pagedim *p;
759 fz_rect mediabox;
761 switch (state.type) {
762 case DPDF:
763 pageobj = state.u.pdf->page_objs[pageno];
765 if (state.trimmargins) {
766 fz_obj *obj;
767 pdf_page *page;
769 page = pdf_load_page (state.u.pdf, pageno);
770 obj = fz_dict_gets (pageobj, "llpp.TrimBox");
771 if (state.trimanew || !obj) {
772 fz_rect rect;
773 fz_bbox bbox;
774 fz_matrix ctm;
775 fz_device *dev;
777 dev = fz_new_bbox_device (state.ctx, &bbox);
778 dev->hints |= FZ_IGNORE_SHADE;
779 ctm = fz_invert_matrix (page->ctm);
780 pdf_run_page (state.u.pdf, page, dev, fz_identity, NULL);
781 fz_free_device (dev);
783 rect.x0 = bbox.x0 + state.trimfuzz.x0;
784 rect.x1 = bbox.x1 + state.trimfuzz.x1;
785 rect.y0 = bbox.y0 + state.trimfuzz.y0;
786 rect.y1 = bbox.y1 + state.trimfuzz.y1;
787 rect = fz_transform_rect (ctm, rect);
788 rect = fz_intersect_rect (rect, page->mediabox);
790 if (fz_is_empty_rect (rect)) {
791 mediabox = page->mediabox;
793 else {
794 mediabox = rect;
797 obj = fz_new_array (state.ctx, 4);
798 fz_array_push (obj, fz_new_real (state.ctx, mediabox.x0));
799 fz_array_push (obj, fz_new_real (state.ctx, mediabox.y0));
800 fz_array_push (obj, fz_new_real (state.ctx, mediabox.x1));
801 fz_array_push (obj, fz_new_real (state.ctx, mediabox.y1));
802 fz_dict_puts (pageobj, "llpp.TrimBox", obj);
804 else {
805 mediabox.x0 = fz_to_real (fz_array_get (obj, 0));
806 mediabox.y0 = fz_to_real (fz_array_get (obj, 1));
807 mediabox.x1 = fz_to_real (fz_array_get (obj, 2));
808 mediabox.y1 = fz_to_real (fz_array_get (obj, 3));
811 rotate = page->rotate;
812 pdf_free_page (state.u.pdf, page);
814 printd ("progress %f Trimming %d",
815 (double) (pageno + 1) / state.pagecount,
816 pageno + 1);
818 else {
819 fz_rect cropbox;
821 mediabox = pdf_to_rect (state.ctx,
822 fz_dict_gets (pageobj, "MediaBox"));
823 if (fz_is_empty_rect (mediabox)) {
824 fprintf (stderr, "cannot find page size for page %d\n",
825 pageno+1);
826 mediabox.x0 = 0;
827 mediabox.y0 = 0;
828 mediabox.x1 = 612;
829 mediabox.y1 = 792;
832 cropbox = pdf_to_rect (state.ctx,
833 fz_dict_gets (pageobj, "CropBox"));
834 if (!fz_is_empty_rect (cropbox)) {
835 mediabox = fz_intersect_rect (mediabox, cropbox);
837 rotate = fz_to_int (fz_dict_gets (pageobj, "Rotate"));
839 break;
841 case DXPS:
843 xps_page *page;
845 page = xps_load_page (state.u.xps, pageno);
846 mediabox = xps_bound_page (state.u.xps, page);
847 rotate = 0;
848 if (state.trimmargins) {
849 fz_rect rect;
850 fz_bbox bbox;
851 fz_device *dev;
853 dev = fz_new_bbox_device (state.ctx, &bbox);
854 dev->hints |= FZ_IGNORE_SHADE;
855 xps_run_page (state.u.xps, page, dev, fz_identity, NULL);
856 fz_free_device (dev);
858 rect.x0 = bbox.x0 + state.trimfuzz.x0;
859 rect.x1 = bbox.x1 + state.trimfuzz.x1;
860 rect.y0 = bbox.y0 + state.trimfuzz.y0;
861 rect.y1 = bbox.y1 + state.trimfuzz.y1;
862 rect = fz_intersect_rect (rect, mediabox);
864 if (!fz_is_empty_rect (rect)) {
865 mediabox = rect;
868 xps_free_page (state.u.xps, page);
869 printd ("progress %f loading %d",
870 (double) (pageno + 1) / state.pagecount,
871 pageno + 1);
873 break;
875 case DCBZ:
877 rotate = 0;
878 if (state.trimmargins) {
879 cbz_page *page;
881 page = cbz_load_page (state.u.cbz, pageno);
882 mediabox = cbz_bound_page (state.u.cbz, page);
883 cbz_free_page (state.u.cbz, page);
884 printd ("progress %f Trimming %d",
885 (double) (pageno + 1) / state.pagecount,
886 pageno + 1);
888 else {
889 mediabox.x0 = mediabox.y0 = 0;
890 mediabox.x1 = 900;
891 mediabox.y1 = 900;
894 break;
896 default:
897 ARSERT (0 && state.type);
900 if (state.pagedimcount == 0
901 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
902 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
903 size_t size;
905 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
906 state.pagedims = realloc (state.pagedims, size);
907 if (!state.pagedims) {
908 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
909 size, state.pagedimcount + 1);
912 p = &state.pagedims[state.pagedimcount++];
913 p->rotate = rotate;
914 p->mediabox = mediabox;
915 p->pageno = pageno;
918 end = now ();
919 if (state.trimmargins) {
920 printd ("progress 1 Trimmed %d pages in %f seconds",
921 state.pagecount, end - start);
923 else {
924 printd ("vmsg Processed %d pages in %f seconds",
925 state.pagecount, end - start);
927 state.trimanew = 0;
930 static void layout (void)
932 int pindex;
933 fz_rect box;
934 fz_matrix ctm;
935 double zoom, w, maxw = 0;
936 struct pagedim *p = state.pagedims;
938 if (state.proportional) {
939 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
940 box = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
941 p->mediabox);
942 w = box.x1 - box.x0;
943 maxw = MAX (w, maxw);
947 p = state.pagedims;
948 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
949 fz_bbox bbox;
951 ctm = fz_rotate (state.rotate);
952 box = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
953 p->mediabox);
954 w = box.x1 - box.x0;
956 if (state.proportional) {
957 double scale = w / maxw;
958 zoom = (state.w / w) * scale;
960 else {
961 zoom = state.w / w;
964 p->zoomctm = fz_scale (zoom, zoom);
965 ctm = fz_concat (p->zoomctm, ctm);
967 p->pagebox = fz_transform_rect (fz_rotate (p->rotate), p->mediabox);
968 p->pagebox.x1 -= p->pagebox.x0;
969 p->pagebox.y1 -= p->pagebox.y0;
970 p->pagebox.x0 = 0;
971 p->pagebox.y0 = 0;
972 bbox = fz_round_rect (fz_transform_rect (ctm, p->pagebox));
974 p->bounds = bbox;
975 p->left = state.proportional ? ((maxw - w) * zoom) / 2.0 : 0;
976 p->ctm = ctm;
978 ctm = fz_identity;
979 ctm = fz_concat (ctm, fz_translate (0, -p->mediabox.y1));
980 ctm = fz_concat (ctm, fz_scale (zoom, -zoom));
981 ctm = fz_concat (ctm, fz_rotate (p->rotate + state.rotate));
982 p->lctm = ctm;
984 p->tctmready = 0;
987 while (p-- != state.pagedims) {
988 int x0 = MIN (p->bounds.x0, p->bounds.x1);
989 int y0 = MIN (p->bounds.y0, p->bounds.y1);
990 int x1 = MAX (p->bounds.x0, p->bounds.x1);
991 int y1 = MAX (p->bounds.y0, p->bounds.y1);
992 int w = x1 - x0;
993 int h = y1 - y0;
995 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
999 static void recurse_outline (fz_outline *outline, int level)
1001 while (outline) {
1002 fz_link_dest *dest;
1003 int i, top = 0;
1004 struct pagedim *pdim = state.pagedims;
1006 dest = &outline->dest;
1007 for (i = 0; i < state.pagedimcount; ++i) {
1008 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1009 break;
1010 pdim = &state.pagedims[i];
1012 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1013 fz_point p;
1014 p.x = 0;
1015 p.y = dest->ld.gotor.lt.y;
1016 p = fz_transform_point (pdim->lctm, p);
1017 top = p.y;
1019 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1020 int h;
1021 double y0, y1;
1023 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1024 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1025 h = y1 - y0;
1026 printd ("o %d %d %d %d %s",
1027 level, dest->ld.gotor.page, top, h, outline->title);
1029 if (outline->down) {
1030 recurse_outline (outline->down, level + 1);
1032 outline = outline->next;
1036 static void process_outline (void)
1038 fz_outline *outline;
1040 if (!state.needoutline) return;
1042 state.needoutline = 0;
1043 switch (state.type) {
1044 case DPDF:
1045 outline = pdf_load_outline (state.u.pdf);
1046 break;
1047 case DXPS:
1048 outline = xps_load_outline (state.u.xps);
1049 break;
1050 default:
1051 outline = NULL;
1052 break;
1054 if (outline) {
1055 recurse_outline (outline, 0);
1056 fz_free_outline (state.ctx, outline);
1060 static int comparespans (const void *l, const void *r)
1062 fz_text_span const *const*ls = l;
1063 fz_text_span const *const*rs = r;
1064 return (*ls)->text->bbox.y0 - (*rs)->text->bbox.y0;
1067 /* wishful thinking function */
1068 static void search (regex_t *re, int pageno, int y, int forward)
1070 int i, j;
1071 int ret;
1072 char *p;
1073 char buf[256];
1074 fz_matrix ctm;
1075 fz_device *tdev;
1076 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1077 fz_text_span *text, *span, **pspan;
1078 struct pagedim *pdim, *pdimprev;
1079 int stop = 0;
1080 int niters = 0;
1081 int nspans;
1082 double start, end;
1084 if (!(state.type == DPDF || state.type == DXPS))
1085 return;
1087 start = now ();
1088 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1089 if (niters++ == 5) {
1090 niters = 0;
1091 if (hasdata ()) {
1092 printd ("progress 1 attention requested aborting search at %d",
1093 pageno);
1094 stop = 1;
1096 else {
1097 printd ("progress %f searching in page %d",
1098 (double) (pageno + 1) / state.pagecount,
1099 pageno);
1102 pdimprev = NULL;
1103 for (i = 0; i < state.pagedimcount; ++i) {
1104 pdim = &state.pagedims[i];
1105 if (pdim->pageno == pageno) {
1106 goto found;
1108 if (pdim->pageno > pageno) {
1109 pdim = pdimprev;
1110 goto found;
1112 pdimprev = pdim;
1114 pdim = pdimprev;
1115 found:
1117 text = fz_new_text_span (state.ctx);
1118 tdev = fz_new_text_device (state.ctx, text);
1120 switch (state.type) {
1121 case DPDF:
1122 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1123 pdf_run_page (state.u.pdf, u.pdfpage, tdev, fz_identity, NULL);
1124 break;
1126 case DXPS:
1127 u.xpspage = xps_load_page (state.u.xps, pageno);
1128 xps_run_page (state.u.xps, u.xpspage, tdev, fz_identity, NULL);
1129 break;
1131 default:
1132 ARSERT (0 && state.type);
1135 fz_free_device (tdev);
1137 nspans = 0;
1138 for (span = text; span; span = span->next) {
1139 nspans++;
1141 pspan = malloc (sizeof (void *) * nspans);
1142 if (!pspan) {
1143 err (1, "malloc span pointers %" FMT_s, sizeof (void *) * nspans);
1145 for (i = 0, span = text; span; span = span->next, ++i) {
1146 pspan[i] = span;
1148 qsort (pspan, nspans, sizeof (fz_text_span *), comparespans);
1150 j = forward ? 0 : nspans - 1;
1151 while (nspans--) {
1152 regmatch_t rm;
1154 span = pspan[j];
1155 j += forward ? 1 : -1;
1156 p = buf;
1157 for (i = 0; i < span->len; ++i) {
1158 int len;
1159 char cbuf[4];
1161 if (forward) {
1162 if (span->text[i].bbox.y0 < y + 1) {
1163 continue;
1166 else {
1167 if (span->text[i].bbox.y0 > y - 1) {
1168 continue;
1171 len = runetochar (cbuf, &span->text[i].c);
1172 if (sizeof (buf) - 1 - (p - buf) > len) {
1173 int k;
1174 for (k = 0; k < len; ++k)
1175 *p++ = cbuf[k];
1177 else {
1178 break;
1181 if (p == buf) {
1182 continue;
1184 *p++ = 0;
1186 ret = regexec (re, buf, 1, &rm, 0);
1187 if (ret) {
1188 if (ret != REG_NOMATCH) {
1189 size_t size;
1190 char errbuf[80];
1191 size = regerror (ret, re, errbuf, sizeof (errbuf));
1192 printd ("msg regexec error `%.*s'",
1193 (int) size, errbuf);
1194 fz_free_text_span (state.ctx, text);
1195 state.freepage (u.ptr);
1196 free (pspan);
1197 return;
1200 else {
1201 fz_bbox *sb, *eb;
1202 fz_point p1, p2, p3, p4;
1203 int a, b, c, l;
1205 l = span->len;
1206 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1207 c += runelen (span->text[a].c);
1209 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1210 c += runelen (span->text[b].c);
1213 if (runelen (span->text[b].c) > 1) {
1214 b = MAX (0, b-1);
1216 sb = &span->text[MIN (a, l-1)].bbox;
1217 eb = &span->text[MIN (b, l-1)].bbox;
1219 p1.x = sb->x0;
1220 p1.y = sb->y0;
1221 p2.x = eb->x1;
1222 p2.y = sb->y0;
1223 p3.x = eb->x1;
1224 p3.y = eb->y1;
1225 p4.x = sb->x0;
1226 p4.y = eb->y1;
1228 switch (state.type) {
1229 case DPDF:
1230 trimctm (u.pdfpage, pdim - state.pagedims);
1231 ctm = fz_concat (pdim->tctm, pdim->zoomctm);
1232 break;
1234 case DXPS:
1235 ctm = pdim->ctm;
1236 break;
1239 p1 = fz_transform_point (ctm, p1);
1240 p2 = fz_transform_point (ctm, p2);
1241 p3 = fz_transform_point (ctm, p3);
1242 p4 = fz_transform_point (ctm, p4);
1244 if (!stop) {
1245 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1246 pageno, 1,
1247 p1.x, p1.y,
1248 p2.x, p2.y,
1249 p3.x, p3.y,
1250 p4.x, p4.y);
1252 printd ("progress 1 found at %d `%.*s' in %f sec",
1253 pageno, (int) (rm.rm_eo - rm.rm_so), &buf[rm.rm_so],
1254 now () - start);
1256 else {
1257 printd ("match %d %d %f %f %f %f %f %f %f %f",
1258 pageno, 2,
1259 p1.x, p1.y,
1260 p2.x, p2.y,
1261 p3.x, p3.y,
1262 p4.x, p4.y);
1264 stop = 1;
1267 if (forward) {
1268 pageno += 1;
1269 y = 0;
1271 else {
1272 pageno -= 1;
1273 y = INT_MAX;
1275 fz_free_text_span (state.ctx, text);
1276 state.freepage (u.ptr);
1277 free (pspan);
1279 end = now ();
1280 if (!stop) {
1281 printd ("progress 1 no matches %f sec", end - start);
1283 printd ("clearrects");
1286 static void set_tex_params (int colorspace)
1288 switch (colorspace) {
1289 case 0:
1290 state.texiform = GL_RGBA8;
1291 state.texform = GL_RGBA;
1292 state.texty = GL_UNSIGNED_BYTE;
1293 state.colorspace = fz_device_rgb;
1294 break;
1295 case 1:
1296 state.texiform = GL_RGBA8;
1297 state.texform = GL_BGRA;
1298 state.texty = fz_is_big_endian ()
1299 ? GL_UNSIGNED_INT_8_8_8_8
1300 : GL_UNSIGNED_INT_8_8_8_8_REV;
1301 state.colorspace = fz_device_bgr;
1302 break;
1303 case 2:
1304 state.texiform = GL_LUMINANCE_ALPHA;
1305 state.texform = GL_LUMINANCE_ALPHA;
1306 state.texty = GL_UNSIGNED_BYTE;
1307 state.colorspace = fz_device_gray;
1308 break;
1309 default:
1310 errx (1, "invalid colorspce %d", colorspace);
1314 static void realloctexts (int texcount)
1316 size_t size;
1318 if (texcount == state.texcount) return;
1320 if (texcount < state.texcount) {
1321 glDeleteTextures (state.texcount - texcount,
1322 state.texids + texcount);
1325 size = texcount * sizeof (*state.texids);
1326 state.texids = realloc (state.texids, size);
1327 if (!state.texids) {
1328 err (1, "realloc texids %" FMT_s, size);
1331 size = texcount * sizeof (*state.texowners);
1332 state.texowners = realloc (state.texowners, size);
1333 if (!state.texowners) {
1334 err (1, "realloc texowners %" FMT_s, size);
1336 if (texcount > state.texcount) {
1337 int i;
1339 glGenTextures (texcount - state.texcount,
1340 state.texids + state.texcount);
1341 for (i = state.texcount; i < texcount; ++i) {
1342 state.texowners[i].w = -1;
1343 state.texowners[i].slice = NULL;
1346 state.texcount = texcount;
1347 state.texindex = 0;
1350 static void * mainloop (void *unused)
1352 char *p = NULL;
1353 int len, ret, oldlen = 0;
1355 for (;;) {
1356 len = readlen ();
1357 if (len == 0) {
1358 errx (1, "readlen returned 0");
1361 if (oldlen < len + 1) {
1362 p = realloc (p, len + 1);
1363 if (!p) {
1364 err (1, "realloc %d failed", len + 1);
1366 oldlen = len + 1;
1368 readdata (p, len);
1369 p[len] = 0;
1371 if (!strncmp ("open", p, 4)) {
1372 size_t filenamelen;
1373 char *password;
1374 char *filename = p + 5;
1376 filenamelen = strlen (filename);
1377 password = filename + filenamelen + 1;
1379 openxref (filename, password);
1380 pdfinfo ();
1381 initpdims ();
1382 printd ("msg Opened %s (press h/F1 to get help)", filename);
1383 state.needoutline = 1;
1385 else if (!strncmp ("cs", p, 2)) {
1386 int i, colorspace;
1388 ret = sscanf (p + 2, " %d", &colorspace);
1389 if (ret != 1) {
1390 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1392 lock ("cs");
1393 set_tex_params (colorspace);
1394 for (i = 0; i < state.texcount; ++i) {
1395 state.texowners[i].w = -1;
1396 state.texowners[i].slice = NULL;
1398 unlock ("cs");
1400 else if (!strncmp ("freepage", p, 8)) {
1401 void *ptr;
1403 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1404 if (ret != 1) {
1405 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1407 freepage (ptr);
1409 else if (!strncmp ("freetile", p, 8)) {
1410 void *ptr;
1412 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1413 if (ret != 1) {
1414 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1416 freetile (ptr);
1418 else if (!strncmp ("search", p, 6)) {
1419 int icase, pageno, y, ret, len2, forward;
1420 char *pattern;
1421 regex_t re;
1423 ret = sscanf (p + 6, " %d %d %d %d,%n",
1424 &icase, &pageno, &y, &forward, &len2);
1425 if (ret != 4) {
1426 errx (1, "malformed search `%s' ret=%d", p, ret);
1429 pattern = p + 6 + len2;
1430 ret = regcomp (&re, pattern,
1431 REG_EXTENDED | (icase ? REG_ICASE : 0));
1432 if (ret) {
1433 char errbuf[80];
1434 size_t size;
1436 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1437 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1439 else {
1440 search (&re, pageno, y, forward);
1441 regfree (&re);
1444 else if (!strncmp ("geometry", p, 8)) {
1445 int w, h;
1447 printd ("clear");
1448 ret = sscanf (p + 8, " %d %d", &w, &h);
1449 if (ret != 2) {
1450 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1453 lock ("geometry");
1454 state.h = h;
1455 if (w != state.w) {
1456 int i;
1457 state.w = w;
1458 for (i = 0; i < state.texcount; ++i) {
1459 state.texowners[i].slice = NULL;
1462 layout ();
1463 process_outline ();
1464 state.gen++;
1465 unlock ("geometry");
1466 printd ("continue %d", state.pagecount);
1468 else if (!strncmp ("reqlayout", p, 9)) {
1469 int rotate, proportional;
1471 printd ("clear");
1472 ret = sscanf (p + 9, " %d %d", &rotate, &proportional);
1473 if (ret != 2) {
1474 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1476 lock ("reqlayout");
1477 state.rotate = rotate;
1478 state.proportional = proportional;
1479 layout ();
1480 state.gen += 1;
1481 unlock ("reqlayout");
1482 printd ("continue %d", state.pagecount);
1484 else if (!strncmp ("page", p, 4)) {
1485 double a, b;
1486 struct page *page;
1487 int pageno, pindex, ret;
1489 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1490 if (ret != 2) {
1491 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1494 lock ("page");
1495 a = now ();
1496 page = loadpage (pageno, pindex);
1497 b = now ();
1498 unlock ("page");
1500 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1502 else if (!strncmp ("tile", p, 4)) {
1503 int x, y, w, h, ret;
1504 struct page *page;
1505 struct tile *tile;
1506 double a, b;
1508 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d",
1509 FMT_ptr_cast (&page), &x, &y, &w, &h);
1510 if (ret != 5) {
1511 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1514 lock ("tile");
1515 a = now ();
1516 tile = rendertile (page, x, y, w, h);
1517 b = now ();
1518 unlock ("tile");
1520 printd ("tile %d %d %" FMT_ptr " %u %f",
1521 x, y,
1522 FMT_ptr_cast2 (tile),
1523 tile->w * tile->h * tile->pixmap->n,
1524 b - a);
1526 else if (!strncmp ("settrim", p, 7)) {
1527 int trimmargins;
1528 fz_bbox fuzz;
1530 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1531 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1532 if (ret != 5) {
1533 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1535 printd ("clear");
1536 lock ("settrim");
1537 state.trimmargins = trimmargins;
1538 state.needoutline = 1;
1539 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1540 state.trimanew = 1;
1541 state.trimfuzz = fuzz;
1543 state.pagedimcount = 0;
1544 free (state.pagedims);
1545 state.pagedims = NULL;
1546 initpdims ();
1547 layout ();
1548 process_outline ();
1549 unlock ("settrim");
1550 printd ("continue %d", state.pagecount);
1552 else if (!strncmp ("sliceh", p, 6)) {
1553 int h;
1555 ret = sscanf (p + 6, " %d", &h);
1556 if (ret != 1) {
1557 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1559 if (h != state.sliceheight) {
1560 int i;
1562 state.sliceheight = h;
1563 for (i = 0; i < state.texcount; ++i) {
1564 state.texowners[i].w = -1;
1565 state.texowners[i].h = -1;
1566 state.texowners[i].slice = NULL;
1570 else if (!strncmp ("interrupt", p, 9)) {
1571 printd ("vmsg interrupted");
1573 else if (!strncmp ("quit", p, 4)) {
1574 return 0;
1576 else {
1577 errx (1, "unknown command %.*s", len, p);
1580 return 0;
1583 CAMLprim value ml_realloctexts (value texcount_v)
1585 CAMLparam1 (texcount_v);
1586 int ok;
1588 if (trylock ("ml_realloctexts")) {
1589 ok = 0;
1590 goto done;
1592 realloctexts (Int_val (texcount_v));
1593 ok = 1;
1594 unlock ("ml_realloctexts");
1596 done:
1597 CAMLreturn (Val_bool (ok));
1600 static void showsel (struct page *page, int ox, int oy)
1602 fz_bbox bbox;
1603 fz_text_span *span;
1604 struct mark first, last;
1606 first = page->fmark;
1607 last = page->lmark;
1609 if (!first.span || !last.span) return;
1611 glEnable (GL_BLEND);
1612 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1613 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1615 ox += state.pagedims[page->pdimno].bounds.x0;
1616 oy += state.pagedims[page->pdimno].bounds.y0;
1617 for (span = first.span; span; span = span->next) {
1618 int i, j, k;
1620 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1622 j = 0;
1623 k = span->len - 1;
1625 if (span == page->fmark.span && span == page->lmark.span) {
1626 j = MIN (first.i, last.i);
1627 k = MAX (first.i, last.i);
1629 else if (span == first.span) {
1630 j = first.i;
1632 else if (span == last.span) {
1633 k = last.i;
1636 for (i = j; i <= k; ++i) {
1637 bbox = fz_union_bbox (bbox, span->text[i].bbox);
1639 lprintf ("%d %d %d %d oy=%d ox=%d\n",
1640 bbox.x0,
1641 bbox.y0,
1642 bbox.x1,
1643 bbox.y1,
1644 oy, ox);
1646 glRecti (bbox.x0 + ox, bbox.y0 + oy, bbox.x1 + ox, bbox.y1 + oy);
1648 if (span == last.span) break;
1650 glDisable (GL_BLEND);
1653 static void highlightlinks (struct page *page, int xoff, int yoff)
1655 fz_matrix ctm;
1656 fz_link *link, *links;
1658 switch (page->type) {
1659 case DPDF:
1660 links = page->u.pdfpage->links;
1661 break;
1663 case DXPS:
1664 links = page->u.xpspage->links;
1665 break;
1667 default:
1668 return;
1671 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
1672 glEnable (GL_LINE_STIPPLE);
1673 glLineStipple (0.5, 0xcccc);
1675 xoff -= state.pagedims[page->pdimno].bounds.x0;
1676 yoff -= state.pagedims[page->pdimno].bounds.y0;
1677 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1679 glBegin (GL_QUADS);
1680 for (link = links; link; link = link->next) {
1681 fz_point p1, p2, p3, p4;
1683 p1.x = link->rect.x0;
1684 p1.y = link->rect.y0;
1686 p2.x = link->rect.x1;
1687 p2.y = link->rect.y0;
1689 p3.x = link->rect.x1;
1690 p3.y = link->rect.y1;
1692 p4.x = link->rect.x0;
1693 p4.y = link->rect.y1;
1695 p1 = fz_transform_point (ctm, p1);
1696 p2 = fz_transform_point (ctm, p2);
1697 p3 = fz_transform_point (ctm, p3);
1698 p4 = fz_transform_point (ctm, p4);
1700 switch (link->dest.kind) {
1701 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
1702 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
1703 default: glColor3ub (0, 0, 0); break;
1706 glVertex2f (p1.x, p1.y);
1707 glVertex2f (p2.x, p2.y);
1708 glVertex2f (p3.x, p3.y);
1709 glVertex2f (p4.x, p4.y);
1711 glEnd ();
1713 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1714 glDisable (GL_LINE_STIPPLE);
1717 static void uploadslice (struct tile *tile, struct slice *slice)
1719 int offset;
1720 struct slice *slice1;
1722 offset = 0;
1723 for (slice1 = tile->slices; slice != slice1; slice1++) {
1724 offset += slice1->h * tile->w * tile->pixmap->n;
1726 if (slice->texindex != -1 && slice->texindex < state.texcount
1727 && state.texowners[slice->texindex].slice == slice) {
1728 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
1730 else {
1731 int subimage = 0;
1732 int texindex = state.texindex++ % state.texcount;
1734 if (state.texowners[texindex].w == tile->w) {
1735 if (state.texowners[texindex].h >= slice->h) {
1736 subimage = 1;
1738 else {
1739 state.texowners[texindex].h = slice->h;
1742 else {
1743 state.texowners[texindex].h = slice->h;
1746 state.texowners[texindex].w = tile->w;
1747 state.texowners[texindex].slice = slice;
1748 slice->texindex = texindex;
1750 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
1751 if (subimage) {
1752 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
1756 tile->w,
1757 slice->h,
1758 state.texform,
1759 state.texty,
1760 tile->pixmap->samples+offset
1763 else {
1764 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
1766 state.texiform,
1767 tile->w,
1768 slice->h,
1770 state.texform,
1771 state.texty,
1772 tile->pixmap->samples+offset
1778 CAMLprim value ml_drawtile (value args_v, value ptr_v)
1780 CAMLparam2 (args_v, ptr_v);
1781 int dispx = Int_val (Field (args_v, 0));
1782 int dispy = Int_val (Field (args_v, 1));
1783 int dispw = Int_val (Field (args_v, 2));
1784 int disph = Int_val (Field (args_v, 3));
1785 int tilex = Int_val (Field (args_v, 4));
1786 int tiley = Int_val (Field (args_v, 5));
1787 char *s = String_val (ptr_v);
1788 struct tile *tile = parse_pointer ("ml_drawtile", s);
1790 glEnable (GL_TEXTURE_RECTANGLE_ARB);
1792 int slicey, firstslice;
1793 struct slice *slice;
1795 firstslice = tiley / tile->sliceheight;
1796 slice = &tile->slices[firstslice];
1797 slicey = tiley % tile->sliceheight;
1799 while (disph > 0) {
1800 int dh;
1802 dh = slice->h - slicey;
1803 dh = MIN (disph, dh);
1804 uploadslice (tile, slice);
1806 glBegin (GL_QUADS);
1808 glTexCoord2i (tilex, slicey);
1809 glVertex2i (dispx, dispy);
1811 glTexCoord2i (tilex+dispw, slicey);
1812 glVertex2i (dispx+dispw, dispy);
1814 glTexCoord2i (tilex+dispw, slicey+dh);
1815 glVertex2i (dispx+dispw, dispy+dh);
1817 glTexCoord2i (tilex, slicey+dh);
1818 glVertex2i (dispx, dispy+dh);
1820 glEnd ();
1822 dispy += dh;
1823 disph -= dh;
1824 slice++;
1825 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
1826 slicey = 0;
1829 glDisable (GL_TEXTURE_RECTANGLE_ARB);
1830 CAMLreturn (Val_unit);
1833 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
1834 value xoff_v, value yoff_v)
1836 CAMLparam4 (ptr_v, hlinks_v, xoff_v, yoff_v);
1837 int xoff = Int_val (xoff_v);
1838 int yoff = Int_val (yoff_v);
1839 char *s = String_val (ptr_v);
1840 struct page *page = parse_pointer ("ml_postprocess", s);
1842 if (Bool_val (hlinks_v)) highlightlinks (page, xoff, yoff);
1844 if (trylock ("ml_postprocess")) {
1845 goto done;
1847 showsel (page, xoff, yoff);
1848 unlock ("ml_postprocess");
1850 done:
1851 CAMLreturn (Val_unit);
1854 static fz_link *getlink (struct page *page, int x, int y)
1856 fz_point p;
1857 fz_matrix ctm;
1858 fz_link *link, *links;
1860 switch (page->type) {
1861 case DPDF:
1862 ctm = trimctm (page->u.pdfpage, page->pdimno);
1863 links = page->u.pdfpage->links;
1864 break;
1866 case DXPS:
1867 ctm = fz_identity;
1868 links = page->u.xpspage->links;
1869 break;
1871 default:
1872 return NULL;
1874 p.x = x;
1875 p.y = y;
1877 ctm = fz_concat (ctm, state.pagedims[page->pdimno].ctm);
1878 ctm = fz_invert_matrix (ctm);
1879 p = fz_transform_point (ctm, p);
1881 for (link = links; link; link = link->next) {
1882 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
1883 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
1884 return link;
1888 return NULL;
1891 static void droptext (struct page *page)
1893 if (page->text) {
1894 fz_free_text_span (state.ctx, page->text);
1895 page->fmark.i = -1;
1896 page->lmark.i = -1;
1897 page->fmark.span = NULL;
1898 page->lmark.span = NULL;
1899 page->text = NULL;
1903 static void ensuretext (struct page *page)
1905 if (state.gen != page->gen) {
1906 droptext (page);
1907 page->gen = state.gen;
1909 if (!page->text) {
1910 fz_device *tdev;
1912 page->text = fz_new_text_span (state.ctx);
1913 tdev = fz_new_text_device (state.ctx, page->text);
1914 fz_run_display_list (page->dlist,
1915 tdev,
1916 pagectm (page),
1917 fz_infinite_bbox, NULL);
1918 fz_free_device (tdev);
1922 static int compareslinks (const void *l, const void *r)
1924 struct slink const *ls = l;
1925 struct slink const *rs = r;
1926 if (ls->bbox.y0 == rs->bbox.y0) {
1927 return rs->bbox.x0 - rs->bbox.x0;
1929 return ls->bbox.y0 - rs->bbox.y0;
1932 static void ensureslinks (struct page *page)
1934 fz_matrix ctm;
1935 int i, count = 0;
1936 size_t slinksize = sizeof (*page->slinks);
1937 fz_link *link, *links;
1939 if (page->slinks) return;
1941 switch (page->type) {
1942 case DPDF:
1943 links = page->u.pdfpage->links;
1944 ctm = fz_concat (trimctm (page->u.pdfpage, page->pdimno),
1945 state.pagedims[page->pdimno].ctm);
1946 break;
1948 case DXPS:
1949 links = page->u.xpspage->links;
1950 ctm = state.pagedims[page->pdimno].ctm;
1951 break;
1953 default:
1954 return;
1957 for (link = links; link; link = link->next) {
1958 count++;
1960 if (count > 0) {
1961 page->slinkcount = count;
1962 page->slinks = calloc (count, slinksize);
1963 if (!page->slinks) {
1964 err (1, "realloc slinks %d", count);
1967 for (i = 0, link = links; link; ++i, link = link->next) {
1968 page->slinks[i].link = link;
1969 page->slinks[i].bbox =
1970 fz_round_rect (fz_transform_rect (ctm, link->rect));
1972 qsort (page->slinks, count, slinksize, compareslinks);
1976 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
1978 CAMLparam2 (start_page_v, dir_v);
1979 CAMLlocal1 (ret_v);
1980 int i, dir = Int_val (dir_v);
1981 int start_page = Int_val (start_page_v);
1982 int end_page = dir > 0 ? state.pagecount : -1;
1984 ret_v = Val_int (0);
1985 if (!(state.type == DPDF || state.type == DXPS)) {
1986 goto done;
1989 lock ("ml_findpage_with_links");
1990 for (i = start_page + dir; i != end_page; i += dir) {
1991 int found;
1993 switch (state.type) {
1994 case DPDF:
1996 pdf_page *page = pdf_load_page (state.u.pdf, i);
1997 found = !!page->links;
1998 freepdfpage (page);
2000 break;
2001 case DXPS:
2003 xps_page *page = xps_load_page (state.u.xps, i);
2004 found = !!page->links;
2005 freexpspage (page);
2007 break;
2009 default:
2010 ARSERT ("invalid document type");
2013 if (found) {
2014 ret_v = caml_alloc_small (1, 1);
2015 Field (ret_v, 0) = Val_int (i);
2016 goto unlock;
2019 unlock:
2020 unlock ("ml_findpage_with_links");
2022 done:
2023 CAMLreturn (ret_v);
2026 enum { dir_first, dir_last};
2027 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2029 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2031 CAMLparam2 (ptr_v, dir_v);
2032 CAMLlocal3 (ret_v, tup_v, pos_v);
2033 struct page *page;
2034 int dirtag, i, slinkindex;
2035 struct slink *found = NULL ,*slink;
2036 char *s = String_val (ptr_v);
2038 if (trylock ("ml_findlink")) {
2039 ret_v = Val_int (0);
2040 goto done;
2043 page = parse_pointer ("ml_findlink", s);
2044 ensureslinks (page);
2046 ret_v = Val_int (1);
2047 if (Is_block (dir_v)) {
2048 dirtag = Tag_val (dir_v);
2049 switch (dirtag) {
2050 case dir_first_visible:
2052 int x0, y0, dir, first_index, last_index;
2054 pos_v = Field (dir_v, 0);
2055 x0 = Int_val (Field (pos_v, 0));
2056 y0 = Int_val (Field (pos_v, 1));
2057 dir = Int_val (Field (pos_v, 2));
2059 if (dir >= 0) {
2060 dir = 1;
2061 first_index = 0;
2062 last_index = page->slinkcount;
2064 else {
2065 first_index = page->slinkcount - 1;
2066 last_index = -1;
2069 for (i = first_index; i != last_index; i += dir) {
2070 slink = &page->slinks[i];
2071 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2072 found = slink;
2073 break;
2077 break;
2079 case dir_left:
2080 slinkindex = Int_val (Field (dir_v, 0));
2081 found = &page->slinks[slinkindex];
2082 for (i = slinkindex - 1; i >= 0; --i) {
2083 slink = &page->slinks[i];
2084 if (slink->bbox.x0 < found->bbox.x0) {
2085 found = slink;
2086 break;
2089 break;
2091 case dir_right:
2092 slinkindex = Int_val (Field (dir_v, 0));
2093 found = &page->slinks[slinkindex];
2094 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2095 slink = &page->slinks[i];
2096 if (slink->bbox.x0 > found->bbox.x0) {
2097 found = slink;
2098 break;
2101 break;
2103 case dir_down:
2104 slinkindex = Int_val (Field (dir_v, 0));
2105 found = &page->slinks[slinkindex];
2106 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2107 slink = &page->slinks[i];
2108 if (slink->bbox.y0 >= found->bbox.y0) {
2109 found = slink;
2110 break;
2113 break;
2115 case dir_up:
2116 slinkindex = Int_val (Field (dir_v, 0));
2117 found = &page->slinks[slinkindex];
2118 for (i = slinkindex - 1; i >= 0; --i) {
2119 slink = &page->slinks[i];
2120 if (slink->bbox.y0 <= found->bbox.y0) {
2121 found = slink;
2122 break;
2125 break;
2128 else {
2129 dirtag = Int_val (dir_v);
2130 switch (dirtag) {
2131 case dir_first:
2132 found = page->slinks;
2133 break;
2135 case dir_last:
2136 if (page->slinks) {
2137 found = page->slinks + (page->slinkcount - 1);
2139 break;
2142 if (found) {
2143 tup_v = caml_alloc_tuple (5);
2144 ret_v = caml_alloc_small (2, 1);
2145 Field (tup_v, 0) = Val_int (found - page->slinks);
2146 Field (tup_v, 1) = Val_int (found->bbox.x0);
2147 Field (tup_v, 2) = Val_int (found->bbox.y0);
2148 Field (tup_v, 3) = Val_int (found->bbox.x1);
2149 Field (tup_v, 4) = Val_int (found->bbox.y1);
2150 Field (ret_v, 0) = tup_v;
2153 unlock ("ml_findlink");
2154 done:
2155 CAMLreturn (ret_v);
2158 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2160 #define LINKTOVAL \
2162 int pageno; \
2164 switch (link->dest.kind) { \
2165 case FZ_LINK_GOTO: \
2167 fz_point p; \
2169 pageno = link->dest.ld.gotor.page; \
2170 p.x = 0; \
2171 p.y = 0; \
2173 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2174 p.y = link->dest.ld.gotor.lt.y; \
2175 p = fz_transform_point (pdim->lctm, p); \
2177 tup_v = caml_alloc_tuple (2); \
2178 ret_v = caml_alloc_small (1, ugoto); \
2179 Field (tup_v, 0) = Val_int (pageno); \
2180 Field (tup_v, 1) = Val_int (p.y); \
2181 Field (ret_v, 0) = tup_v; \
2183 break; \
2185 case FZ_LINK_URI: \
2186 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2187 ret_v = caml_alloc_small (1, uuri); \
2188 Field (ret_v, 0) = str_v; \
2189 break; \
2191 case FZ_LINK_LAUNCH: \
2192 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2193 ret_v = caml_alloc_small (1, ulaunch); \
2194 Field (ret_v, 0) = str_v; \
2195 break; \
2197 case FZ_LINK_NAMED: \
2198 str_v = caml_copy_string (link->dest.ld.named.named); \
2199 ret_v = caml_alloc_small (1, unamed); \
2200 Field (ret_v, 0) = str_v; \
2201 break; \
2203 case FZ_LINK_GOTOR: \
2204 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2205 pageno = link->dest.ld.gotor.page; \
2206 tup_v = caml_alloc_tuple (2); \
2207 ret_v = caml_alloc_small (1, uremote); \
2208 Field (tup_v, 0) = str_v; \
2209 Field (tup_v, 1) = Val_int (pageno); \
2210 Field (ret_v, 0) = tup_v; \
2211 break; \
2213 default: \
2215 char buf[80]; \
2217 snprintf (buf, sizeof (buf), \
2218 "unhandled link kind %d", link->dest.kind); \
2219 str_v = caml_copy_string (buf); \
2220 ret_v = caml_alloc_small (1, uunexpected); \
2221 Field (ret_v, 0) = str_v; \
2223 break; \
2227 CAMLprim value ml_getlink (value ptr_v, value n_v)
2229 CAMLparam2 (ptr_v, n_v);
2230 CAMLlocal3 (ret_v, tup_v, str_v);
2231 fz_link *link;
2232 struct page *page;
2233 struct pagedim *pdim;
2234 char *s = String_val (ptr_v);
2236 ret_v = Val_int (0);
2237 page = parse_pointer ("ml_getlink", s);
2238 pdim = &state.pagedims[page->pdimno];
2239 link = page->slinks[Int_val (n_v)].link;
2240 LINKTOVAL;
2241 CAMLreturn (ret_v);
2244 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2246 CAMLparam3 (ptr_v, x_v, y_v);
2247 CAMLlocal3 (ret_v, tup_v, str_v);
2248 fz_link *link;
2249 struct page *page;
2250 char *s = String_val (ptr_v);
2251 int x = Int_val (x_v), y = Int_val (y_v);
2252 struct pagedim *pdim;
2254 ret_v = Val_int (0);
2255 if (trylock ("ml_whatsunder")) {
2256 goto done;
2259 page = parse_pointer ("ml_whatsunder", s);
2260 pdim = &state.pagedims[page->pdimno];
2261 x += pdim->bounds.x0;
2262 y += pdim->bounds.y0;
2263 link = getlink (page, x, y);
2264 if (link) {
2265 LINKTOVAL;
2267 else {
2268 int i;
2269 fz_text_span *span;
2271 ensuretext (page);
2272 for (span = page->text; span; span = span->next) {
2273 for (i = 0; i < span->len; ++i) {
2274 fz_bbox *b;
2275 b = &span->text[i].bbox;
2276 if ((x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)) {
2277 const char *n2 =
2278 span->font && span->font->name
2279 ? span->font->name
2280 : "Span has no font name"
2282 FT_FaceRec *face = span->font->ft_face;
2283 if (face && face->family_name) {
2284 char *s;
2285 char *n1 = face->family_name;
2286 size_t l1 = strlen (n1);
2287 size_t l2 = strlen (n2);
2289 if (l1 != l2 || memcmp (n1, n2, l1)) {
2290 s = malloc (l1 + l2 + 2);
2291 if (s) {
2292 memcpy (s, n2, l2);
2293 s[l2] = '=';
2294 memcpy (s + l2 + 1, n1, l1 + 1);
2295 str_v = caml_copy_string (s);
2296 free (s);
2300 if (str_v == 0) {
2301 str_v = caml_copy_string (n2);
2303 ret_v = caml_alloc_small (1, utext);
2304 Field (ret_v, 0) = str_v;
2305 goto unlock;
2310 unlock:
2311 unlock ("ml_whatsunder");
2313 done:
2314 CAMLreturn (ret_v);
2317 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2319 CAMLparam2 (ptr_v, rect_v);
2320 fz_bbox *b;
2321 struct page *page;
2322 fz_text_span *span;
2323 struct mark first, last;
2324 struct pagedim *pdim;
2325 int i, x0, x1, y0, y1;
2326 char *s = String_val (ptr_v);
2328 if (trylock ("ml_seltext")) {
2329 goto done;
2332 page = parse_pointer ("ml_seltext", s);
2333 ensuretext (page);
2335 pdim = &state.pagedims[page->pdimno];
2336 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2337 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2338 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2339 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2341 if (0) {
2342 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2343 glColor3ub (128, 128, 128);
2344 glRecti (x0, y0, x1, y1);
2345 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2348 first.span = NULL;
2349 last.span = NULL;
2351 last.i = first.i = 0;
2352 first.span = page->text;
2353 for (span = page->text; span; span = span->next) {
2354 for (i = 0; i < span->len; ++i) {
2355 b = &span->text[i].bbox;
2356 int selected = 0;
2358 if (x0 >= b->x0 && x0 <= b->x1 && y0 >= b->y0 && y0 <= b->y1) {
2359 first.i = i;
2360 first.span = span;
2361 selected = 1;
2363 if (x1 >= b->x0 && x1 <= b->x1 && y1 >= b->y0 && y1 <= b->y1) {
2364 last.i = i;
2365 last.span = span;
2366 selected = 1;
2368 if (0 && selected) {
2369 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2370 glColor3ub (128, 128, 128);
2371 glRecti (b->x0, b->y0, b->x1, b->y1);
2372 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2377 if (y1 < y0 || x1 < x0) {
2378 int swap = 0;
2380 if (first.span == last.span) {
2381 swap = 1;
2383 else {
2384 if (y1 < y0) {
2385 for (span = first.span; span && span != last.span;
2386 span = span->next) {
2387 if (span->eol) {
2388 swap = 1;
2389 break;
2395 if (swap) {
2396 i = first.i;
2397 span = first.span;
2398 first.i = last.i;
2399 first.span = last.span;
2400 last.i = i;
2401 last.span = span;
2405 page->fmark = first;
2406 page->lmark = last;
2408 unlock ("ml_seltext");
2410 done:
2411 CAMLreturn (Val_unit);
2414 static int pipespan (FILE *f, fz_text_span *span, int a, int b)
2416 char buf[4];
2417 int i, len, ret;
2419 for (i = a; i <= b; ++i) {
2420 len = runetochar (buf, &span->text[i].c);
2421 ret = fwrite (buf, len, 1, f);
2423 if (ret != 1) {
2424 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
2425 len, ret, strerror (errno));
2426 return -1;
2429 return 0;
2432 CAMLprim value ml_copysel (value command_v, value ptr_v)
2434 CAMLparam1 (ptr_v);
2435 FILE *f;
2436 struct page *page;
2437 fz_text_span *span;
2438 char *s = String_val (ptr_v);
2439 char *command = String_val (command_v);
2441 if (trylock ("ml_copysel")) {
2442 goto done;
2445 page = parse_pointer ("ml_sopysel", s);
2447 if (!page->fmark.span || !page->lmark.span) {
2448 fprintf (stderr, "nothing to copy\n");
2449 goto unlock;
2452 f = popen (command, "w");
2453 if (!f) {
2454 fprintf (stderr, "failed to open sel pipe: %s\n",
2455 strerror (errno));
2456 f = stdout;
2459 for (span = page->fmark.span;
2460 span && span != page->lmark.span->next;
2461 span = span->next) {
2462 int a = span == page->fmark.span ? page->fmark.i : 0;
2463 int b = span == page->lmark.span ? page->lmark.i : span->len - 1;
2464 if (pipespan (f, span, a, b)) {
2465 goto close;
2467 if (span->eol) {
2468 if (putc ('\n', f) == EOF) {
2469 fprintf (stderr, "failed break line on sel pipe: %s\n",
2470 strerror (errno));
2471 goto close;
2475 page->lmark.span = NULL;
2476 page->fmark.span = NULL;
2478 close:
2479 if (f != stdout) {
2480 int ret = pclose (f);
2481 if (ret == -1) {
2482 if (errno != ECHILD) {
2483 fprintf (stderr, "failed to close sel pipe: %s\n",
2484 strerror (errno));
2488 unlock:
2489 unlock ("ml_copysel");
2491 done:
2492 CAMLreturn (Val_unit);
2495 CAMLprim value ml_getpdimrect (value pagedimno_v)
2497 CAMLparam1 (pagedimno_v);
2498 CAMLlocal1 (ret_v);
2499 int pagedimno = Int_val (pagedimno_v);
2500 fz_rect box;
2502 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2503 if (trylock ("ml_getpdimrect")) {
2504 box = fz_empty_rect;
2506 else {
2507 box = state.pagedims[pagedimno].mediabox;
2508 unlock ("ml_getpdimrect");
2511 Store_double_field (ret_v, 0, box.x0);
2512 Store_double_field (ret_v, 1, box.x1);
2513 Store_double_field (ret_v, 2, box.y0);
2514 Store_double_field (ret_v, 3, box.y1);
2516 CAMLreturn (ret_v);
2519 static double getmaxw (void)
2521 int i;
2522 struct pagedim *p;
2523 double maxw = 0.0;
2525 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
2526 double x0, x1, w;
2528 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
2529 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
2531 w = x1 - x0;
2532 maxw = MAX (w, maxw);
2534 return maxw;
2537 CAMLprim value ml_getmaxw (value unit_v)
2539 CAMLparam1 (unit_v);
2540 CAMLlocal1 (ret_v);
2541 double maxw = 0.0;
2543 if (trylock ("ml_getmaxw")) {
2544 goto done;
2546 maxw = getmaxw ();
2547 unlock ("ml_getmaxw");
2548 done:
2549 ret_v = caml_copy_double (maxw);
2550 CAMLreturn (ret_v);
2553 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v, value dw_v)
2555 CAMLparam3 (winw_v, winh_v, dw_v);
2556 CAMLlocal1 (ret_v);
2557 int i;
2558 double zoom = 1.0;
2559 double maxw = 0.0, maxh = 0.0;
2560 struct pagedim *p;
2561 double winw = Int_val (winw_v);
2562 double winh = Int_val (winh_v);
2563 double dw = Int_val (dw_v);
2564 double pw = 1.0, ph = 1.0, num, den;
2566 if (trylock ("ml_zoom_for_height")) {
2567 goto done;
2570 if (state.proportional) {
2571 maxw = getmaxw ();
2574 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
2575 double x0, x1, y0, y1, w, h, scaledh, scale;
2577 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
2578 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
2579 y0 = MIN (p->mediabox.y0, p->mediabox.y1);
2580 y1 = MAX (p->mediabox.y0, p->mediabox.y1);
2582 w = x1 - x0;
2583 h = y1 - y0;
2585 if (state.proportional) {
2586 scale = w / maxw;
2587 scaledh = h * scale;
2589 else {
2590 scale = 1.0;
2591 scaledh = h;
2594 if (scaledh > maxh) {
2595 maxh = scaledh;
2596 ph = scaledh;
2597 pw = w * scale;
2601 num = (winh * pw) + (ph * dw);
2602 den = ph * winw;
2603 zoom = num / den;
2605 unlock ("ml_zoom_for_height");
2606 done:
2607 ret_v = caml_copy_double (zoom);
2608 CAMLreturn (ret_v);
2611 #include "glfont.c"
2613 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
2615 CAMLparam4 (pt_v, x_v, y_v, string_v);
2616 CAMLlocal1 (ret_v);
2617 int pt = Int_val(pt_v);
2618 int x = Int_val (x_v);
2619 int y = Int_val (y_v);
2620 double w;
2622 w = draw_string (state.face, pt, x, y, String_val (string_v));
2623 ret_v = caml_copy_double (w);
2624 CAMLreturn (ret_v);
2627 CAMLprim value ml_measure_string (value pt_v, value string_v)
2629 CAMLparam2 (pt_v, string_v);
2630 CAMLlocal1 (ret_v);
2631 int pt = Int_val (pt_v);
2632 double w;
2634 w = measure_string (state.face, pt, String_val (string_v));
2635 ret_v = caml_copy_double (w);
2636 CAMLreturn (ret_v);
2639 CAMLprim value ml_getpagebox (value opaque_v)
2641 CAMLparam1 (opaque_v);
2642 CAMLlocal1 (ret_v);
2643 fz_bbox bbox;
2644 fz_device *dev;
2645 char *s = String_val (opaque_v);
2646 struct page *page = parse_pointer ("ml_getpagebox", s);
2648 ret_v = caml_alloc_tuple (4);
2649 dev = fz_new_bbox_device (state.ctx, &bbox);
2650 dev->hints |= FZ_IGNORE_SHADE;
2652 switch (page->type) {
2653 case DPDF:
2654 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, pagectm (page), NULL);
2655 break;
2657 case DXPS:
2658 xps_run_page (state.u.xps, page->u.xpspage, dev, pagectm (page), NULL);
2659 break;
2661 default:
2662 bbox = fz_infinite_bbox;
2663 break;
2666 fz_free_device (dev);
2667 Field (ret_v, 0) = Val_int (bbox.x0);
2668 Field (ret_v, 1) = Val_int (bbox.y0);
2669 Field (ret_v, 2) = Val_int (bbox.x1);
2670 Field (ret_v, 3) = Val_int (bbox.y1);
2672 CAMLreturn (ret_v);
2675 CAMLprim value ml_setaalevel (value level_v)
2677 CAMLparam1 (level_v);
2679 state.aalevel = Int_val (level_v);
2680 CAMLreturn (Val_unit);
2683 #undef pixel
2684 #include <X11/Xlib.h>
2685 #include <GL/glx.h>
2687 static struct {
2688 Display *dpy;
2689 GLXContext ctx;
2690 GLXDrawable drawable;
2691 } glx;
2693 #include "keysym2ucs.c"
2695 CAMLprim value ml_keysymtoutf8 (value keysym_v)
2697 CAMLparam1 (keysym_v);
2698 CAMLlocal1 (str_v);
2699 KeySym keysym = Int_val (keysym_v);
2700 Rune rune;
2701 int len;
2702 char buf[5];
2704 rune = keysym2ucs (keysym);
2705 len = runetochar (buf, &rune);
2706 buf[len] = 0;
2707 str_v = caml_copy_string (buf);
2708 CAMLreturn (str_v);
2711 CAMLprim value ml_glx (value win_v)
2713 CAMLparam1 (win_v);
2714 int screen;
2715 XVisualInfo *visual;
2716 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
2718 glx.dpy = XOpenDisplay (NULL);
2719 if (!glx.dpy) {
2720 caml_failwith ("XOpenDisplay failed");
2723 screen = DefaultScreen (glx.dpy);
2724 visual = glXChooseVisual (glx.dpy, screen, attributes);
2725 if (!visual) {
2726 XCloseDisplay (glx.dpy);
2727 glx.dpy = NULL;
2728 caml_failwith ("glXChooseVisual");
2731 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
2732 if (!glx.ctx) {
2733 XCloseDisplay (glx.dpy);
2734 XFree (visual);
2735 glx.dpy = NULL;
2736 caml_failwith ("glXCreateContext");
2739 XFree (visual);
2740 if (!glXMakeCurrent (glx.dpy, Int_val (win_v), glx.ctx)) {
2741 glXDestroyContext (glx.dpy, glx.ctx);
2742 XCloseDisplay (glx.dpy);
2743 glx.dpy = NULL;
2744 glx.ctx = NULL;
2745 caml_failwith ("glXMakeCurrent");
2747 glx.drawable = Int_val (win_v);
2749 CAMLreturn (Val_unit);
2752 CAMLprim value ml_swapb (value unit_v)
2754 CAMLparam1 (unit_v);
2755 glXSwapBuffers (glx.dpy, glx.drawable);
2756 CAMLreturn (Val_unit);
2759 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
2760 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
2762 CAMLprim value ml_platform (value unit_v)
2764 CAMLparam1 (unit_v);
2765 int platid = piunknown;
2767 #if defined __linux__
2768 platid = pilinux;
2769 #elif defined __CYGWIN__
2770 platid = picygwin;
2771 #elif defined __DragonFly__
2772 platid = pidragonflybsd;
2773 #elif defined __FreeBSD__
2774 platid = pifreebsd;
2775 #elif defined __OpenBSD__
2776 platid = piopenbsd;
2777 #elif defined __NetBSD__
2778 platid = pinetbsd;
2779 #elif defined __sun__
2780 platid = pisun;
2781 #elif defined __APPLE__
2782 platid = piosx;
2783 #endif
2784 CAMLreturn (Val_int (platid));
2787 CAMLprim value ml_cloexec (value fd_v)
2789 CAMLparam1 (fd_v);
2790 int fd = Int_val (fd_v);
2792 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
2793 uerror ("fcntl", Nothing);
2795 CAMLreturn (Val_unit);
2798 CAMLprim value ml_init (value pipe_v, value params_v)
2800 CAMLparam2 (pipe_v, params_v);
2801 CAMLlocal2 (trim_v, fuzz_v);
2802 int ret;
2803 int texcount;
2804 char *fontpath;
2805 int colorspace;
2806 int mustoresize;
2807 struct sigaction sa;
2809 state.cr = Int_val (Field (pipe_v, 0));
2810 state.cw = Int_val (Field (pipe_v, 1));
2811 state.rotate = Int_val (Field (params_v, 0));
2812 state.proportional = Bool_val (Field (params_v, 1));
2813 trim_v = Field (params_v, 2);
2814 texcount = Int_val (Field (params_v, 3));
2815 state.sliceheight = Int_val (Field (params_v, 4));
2816 mustoresize = Int_val (Field (params_v, 5));
2817 colorspace = Int_val (Field (params_v, 6));
2818 fontpath = String_val (Field (params_v, 7));
2820 state.ctx = fz_new_context (NULL, NULL, mustoresize);
2821 state.trimmargins = Bool_val (Field (trim_v, 0));
2823 fuzz_v = Field (trim_v, 1);
2824 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
2825 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
2826 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
2827 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
2829 set_tex_params (colorspace);
2831 if (*fontpath) {
2832 state.face = load_font (fontpath);
2834 else {
2835 unsigned int len;
2836 void *base = pdf_find_substitute_font (0, 0, 0, 0, &len);
2838 state.face = load_builtin_font (base, len);
2840 if (!state.face) _exit (1);
2842 realloctexts (texcount);
2844 sa.sa_handler = SIG_DFL;
2845 if (sigemptyset (&sa.sa_mask)) {
2846 err (1, "sigemptyset");
2848 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
2849 if (sigaction (SIGCHLD, &sa, NULL)) {
2850 err (1, "sigaction");
2853 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
2854 if (ret) {
2855 errx (1, "pthread_create: %s", strerror (ret));
2858 CAMLreturn (Val_unit);