Refactor
[llpp.git] / link.c
blobb90d5879f11d1f4a7eef057c77df11e2f9e3d2f9
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 char *text;
141 fz_bbox bbox;
142 fz_link *link;
145 enum { DPDF, DXPS, DCBZ };
147 struct page {
148 int gen;
149 int type;
150 int pageno;
151 int pdimno;
152 fz_text_span *text;
153 union {
154 void *ptr;
155 pdf_page *pdfpage;
156 xps_page *xpspage;
157 cbz_page *cbzpage;
158 } u;
159 fz_display_list *dlist;
160 int slinkcount;
161 struct slink *slinks;
162 struct mark {
163 int i;
164 fz_text_span *span;
165 } fmark, lmark;
166 void (*freepage) (void *);
169 struct {
170 int type;
171 int sliceheight;
172 struct pagedim *pagedims;
173 int pagecount;
174 int pagedimcount;
175 union {
176 pdf_document *pdf;
177 xps_document *xps;
178 cbz_document *cbz;
179 } u;
180 fz_context *ctx;
181 fz_glyph_cache *cache;
182 int w, h;
184 int texindex;
185 int texcount;
186 GLuint *texids;
188 GLenum texiform;
189 GLenum texform;
190 GLenum texty;
192 fz_colorspace *colorspace;
194 struct {
195 int w, h;
196 struct slice *slice;
197 } *texowners;
199 int rotate;
200 int proportional;
201 int trimmargins;
202 int needoutline;
203 int gen;
204 int aalevel;
206 int trimanew;
207 fz_bbox trimfuzz;
208 fz_pixmap *pig;
210 pthread_t thread;
211 int cr, cw;
212 FT_Face face;
214 void (*closedoc) (void);
215 void (*freepage) (void *);
216 } state;
218 static void UNUSED debug_rect (const char *cap, fz_rect r)
220 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
223 static void UNUSED debug_bbox (const char *cap, fz_bbox r)
225 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
228 static void UNUSED debug_matrix (const char *cap, fz_matrix m)
230 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
231 m.a, m.b, m.c, m.d, m.e, m.f);
234 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
236 static void lock (const char *cap)
238 int ret = pthread_mutex_lock (&mutex);
239 if (ret) {
240 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
244 static void unlock (const char *cap)
246 int ret = pthread_mutex_unlock (&mutex);
247 if (ret) {
248 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
252 static int trylock (const char *cap)
254 int ret = pthread_mutex_trylock (&mutex);
256 if (ret && ret != EBUSY) {
257 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
259 return ret == EBUSY;
262 static void *parse_pointer (const char *cap, const char *s)
264 int ret;
265 void *ptr;
267 ret = sscanf (s, "%" FMT_ptr, FMT_ptr_cast (&ptr));
268 if (ret != 1) {
269 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
271 return ptr;
274 static double now (void)
276 struct timeval tv;
278 if (gettimeofday (&tv, NULL)) {
279 err (1, "gettimeofday");
281 return tv.tv_sec + tv.tv_usec*1e-6;
284 static int hasdata (void)
286 int ret, avail;
287 ret = ioctl (state.cr, FIONREAD, &avail);
288 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
289 return avail > 0;
292 CAMLprim value ml_hasdata (value fd_v)
294 CAMLparam1 (fd_v);
295 int ret, avail;
297 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
298 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
299 CAMLreturn (Val_bool (avail > 0));
302 static void readdata (void *p, int size)
304 ssize_t n;
306 n = read (state.cr, p, size);
307 if (n - size) {
308 if (!n) errx (1, "EOF while reading");
309 err (1, "read (req %d, ret %zd)", size, n);
313 static void writedata (char *p, int size)
315 char buf[4];
316 ssize_t n;
318 buf[0] = (size >> 24) & 0xff;
319 buf[1] = (size >> 16) & 0xff;
320 buf[2] = (size >> 8) & 0xff;
321 buf[3] = (size >> 0) & 0xff;
323 n = write (state.cw, buf, 4);
324 if (n != 4) {
325 if (!n) errx (1, "EOF while writing length");
326 err (1, "write %zd", n);
329 n = write (state.cw, p, size);
330 if (n - size) {
331 if (!n) errx (1, "EOF while writing data");
332 err (1, "write (req %d, ret %zd)", size, n);
336 static int readlen (void)
338 unsigned char p[4];
340 readdata (p, 4);
341 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
344 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
346 int size = 200, len;
347 va_list ap;
348 char *buf;
350 buf = malloc (size);
351 for (;;) {
352 if (!buf) err (errno, "malloc for temp buf (%d bytes) failed", size);
354 va_start (ap, fmt);
355 len = vsnprintf (buf, size, fmt, ap);
356 va_end (ap);
358 if (len > -1 && len < size) {
359 writedata (buf, len);
360 break;
363 if (len > -1) {
364 size = len + 1;
366 else {
367 size *= 2;
369 buf = realloc (buf, size);
371 free (buf);
374 static void closepdf (void)
376 if (state.u.pdf) {
377 pdf_close_document (state.u.pdf);
378 state.u.pdf = NULL;
382 static void closexps (void)
384 if (state.u.xps) {
385 xps_close_document (state.u.xps);
386 state.u.xps = NULL;
390 static void closecbz (void)
392 if (state.u.cbz) {
393 cbz_close_document (state.u.cbz);
394 state.u.cbz = NULL;
398 static void freepdfpage (void *ptr)
400 pdf_free_page (state.u.pdf, ptr);
403 static void freexpspage (void *ptr)
405 xps_free_page (state.u.xps, ptr);
408 static void freecbzpage (void *ptr)
410 cbz_free_page (state.u.cbz, ptr);
413 static void openxref (char *filename, char *password)
415 int i, len;
417 for (i = 0; i < state.texcount; ++i) {
418 state.texowners[i].w = -1;
419 state.texowners[i].slice = NULL;
422 if (state.closedoc) state.closedoc ();
424 len = strlen (filename);
426 state.type = DPDF;
427 if (len > 4) {
428 char ext[4];
430 ext[0] = tolower (filename[len-3]);
431 ext[1] = tolower (filename[len-2]);
432 ext[2] = tolower (filename[len-1]);
434 /**/ if (ext[0] == 'x' && ext[1] == 'p' && ext[2] == 's') {
435 state.type = DXPS;
437 else if (ext[0] == 'c' && ext[1] == 'b' && ext[2] == 'z') {
438 state.type = DCBZ;
442 if (state.pagedims) {
443 free (state.pagedims);
444 state.pagedims = NULL;
446 state.pagedimcount = 0;
448 fz_set_aa_level (state.ctx, state.aalevel);
449 switch (state.type) {
450 case DPDF:
451 state.u.pdf = pdf_open_document (state.ctx, filename);
452 if (pdf_needs_password (state.u.pdf)) {
453 int okay = pdf_authenticate_password (state.u.pdf, password);
454 if (!okay) {
455 errx (1, "invalid password");
458 state.pagecount = pdf_count_pages (state.u.pdf);
459 state.closedoc = closepdf;
460 state.freepage = freepdfpage;
461 break;
463 case DXPS:
464 state.u.xps = xps_open_document (state.ctx, filename);
465 state.pagecount = xps_count_pages (state.u.xps);
466 state.closedoc = closexps;
467 state.freepage = freexpspage;
468 break;
470 case DCBZ:
471 state.u.cbz = cbz_open_document (state.ctx, filename);
472 state.pagecount = cbz_count_pages (state.u.cbz);
473 state.closedoc = closecbz;
474 state.freepage = freecbzpage;
475 break;
479 static void pdfinfo (void)
481 if (state.type == DPDF) {
482 fz_obj *infoobj;
484 printd ("info PDF version\t%d.%d",
485 state.u.pdf->version / 10, state.u.pdf->version % 10);
487 infoobj = fz_dict_gets (state.u.pdf->trailer, "Info");
488 if (infoobj) {
489 int i;
490 char *s;
491 char *items[] = { "Title", "Author", "Creator",
492 "Producer", "CreationDate" };
494 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
495 fz_obj *obj = fz_dict_gets (infoobj, items[i]);
496 s = pdf_to_utf8 (state.ctx, obj);
497 if (*s) {
498 if (i == 0) {
499 printd ("title %s", s);
501 printd ("info %s\t%s", items[i], s);
503 fz_free (state.ctx, s);
506 printd ("infoend");
510 static void unlinktile (struct tile *tile)
512 int i;
514 for (i = 0; i < tile->slicecount; ++i) {
515 struct slice *s = &tile->slices[i];
517 if (s->texindex != -1) {
518 if (state.texowners[s->texindex].slice == s) {
519 state.texowners[s->texindex].slice = NULL;
525 static void freepage (struct page *page)
527 if (page->text) {
528 fz_free_text_span (state.ctx, page->text);
530 if (page->slinks) {
531 free (page->slinks);
533 page->freepage (page->u.ptr);
534 fz_free_display_list (state.ctx, page->dlist);
535 free (page);
538 static void freetile (struct tile *tile)
540 unlinktile (tile);
541 #ifndef PIGGYBACK
542 fz_drop_pixmap (state.ctx, tile->pixmap);
543 #else
544 if (state.pig) {
545 fz_drop_pixmap (state.ctx, state.pig);
547 state.pig = tile->pixmap;
548 #endif
549 free (tile);
552 #ifdef __ALTIVEC__
553 #include <altivec.h>
555 static int cacheline32bytes;
556 extern char **environ;
558 static void __attribute__ ((constructor)) clcheck (void)
560 char **envp = environ;
561 unsigned long *auxv;
563 while (*envp++);
565 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
566 if (*auxv == 19) {
567 cacheline32bytes = auxv[1] == 32;
568 return;
573 static void OPTIMIZE (3) clearpixmap (fz_pixmap *pixmap)
575 if (cacheline32bytes) {
576 intptr_t a1, a2, diff;
577 size_t sizea, i, size = pixmap->w * pixmap->h * pixmap->n;
578 vector unsigned char v = vec_splat_u8 (-1);
579 vector unsigned char *p;
581 a1 = a2 = (intptr_t) pixmap->samples;
582 a2 = (a1 + 31) & ~31;
583 diff = a2 - a1;
584 sizea = size - diff;
585 p = (void *) a2;
587 while (a1 != a2) *(char *) a1++ = 0xff;
588 for (i = 0; i < (sizea & ~31); i += 32) {
589 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
590 vec_st (v, i, p);
591 vec_st (v, i + 16, p);
593 while (i < sizea) *((char *) a1 + i++) = 0xff;
595 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
597 #else
598 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
599 #endif
601 static fz_matrix trimctm (pdf_page *page, int pindex)
603 fz_matrix ctm;
604 struct pagedim *pdim = &state.pagedims[pindex];
606 if (!pdim->tctmready) {
607 if (state.trimmargins) {
608 fz_rect realbox;
610 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
611 realbox = fz_transform_rect (ctm, pdim->mediabox);
612 ctm = fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0));
613 ctm = fz_concat (fz_invert_matrix (page->ctm), ctm);
615 else {
616 ctm = fz_identity;
618 pdim->tctm = ctm;
619 pdim->tctmready = 1;
621 return pdim->tctm;
624 static fz_matrix pagectm (struct page *page)
626 if (page->type == DPDF) {
627 return fz_concat (trimctm (page->u.pdfpage, page->pdimno),
628 state.pagedims[page->pdimno].ctm);
630 else {
631 fz_matrix ctm;
632 struct pagedim *pdim = &state.pagedims[page->pdimno];
634 ctm = state.pagedims[page->pdimno].ctm;
635 ctm = fz_concat (fz_translate (-pdim->mediabox.x0,
636 -pdim->mediabox.y0), ctm);
637 return ctm;
641 static void *loadpage (int pageno, int pindex)
643 fz_device *dev;
644 struct page *page = NULL;
646 page = calloc (sizeof (struct page), 1);
647 if (!page) {
648 err (1, "calloc page %d", pageno);
651 page->dlist = fz_new_display_list (state.ctx);
652 dev = fz_new_list_device (state.ctx, page->dlist);
653 switch (state.type) {
654 case DPDF:
655 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
656 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, fz_identity, NULL);
657 page->freepage = freepdfpage;
658 break;
660 case DXPS:
661 page->u.xpspage = xps_load_page (state.u.xps, pageno);
662 xps_run_page (state.u.xps, page->u.xpspage, dev, fz_identity, NULL);
663 page->freepage = freexpspage;
664 break;
666 case DCBZ:
667 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
668 cbz_run_page (state.u.cbz, page->u.cbzpage, dev, fz_identity, NULL);
669 page->freepage = freecbzpage;
670 break;
672 fz_free_device (dev);
674 page->pdimno = pindex;
675 page->pageno = pageno;
676 page->gen = state.gen;
677 page->type = state.type;
679 return page;
682 static struct tile *alloctile (int h)
684 int i;
685 int slicecount;
686 size_t tilesize;
687 struct tile *tile;
689 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
690 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
691 tile = calloc (tilesize, 1);
692 if (!tile) {
693 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
695 for (i = 0; i < slicecount; ++i) {
696 int sh = MIN (h, state.sliceheight);
697 tile->slices[i].h = sh;
698 tile->slices[i].texindex = -1;
699 h -= sh;
701 tile->slicecount = slicecount;
702 tile->sliceheight = state.sliceheight;
703 return tile;
706 static struct tile *rendertile (struct page *page, int x, int y, int w, int h)
708 fz_bbox bbox;
709 fz_device *dev;
710 struct tile *tile;
711 struct pagedim *pdim;
713 tile = alloctile (h);
714 pdim = &state.pagedims[page->pdimno];
716 bbox = pdim->bounds;
717 bbox.x0 += x;
718 bbox.y0 += y;
719 bbox.x1 = bbox.x0 + w;
720 bbox.y1 = bbox.y0 + h;
722 if (state.pig) {
723 if (state.pig->w == w
724 && state.pig->h == h
725 && state.pig->colorspace == state.colorspace) {
726 tile->pixmap = state.pig;
727 tile->pixmap->x = bbox.x0;
728 tile->pixmap->y = bbox.y0;
730 else {
731 fz_drop_pixmap (state.ctx, state.pig);
733 state.pig = NULL;
735 if (!tile->pixmap) {
736 tile->pixmap =
737 fz_new_pixmap_with_rect (state.ctx, state.colorspace, bbox);
740 tile->w = w;
741 tile->h = h;
742 clearpixmap (tile->pixmap);
743 dev = fz_new_draw_device (state.ctx, tile->pixmap);
744 fz_run_display_list (page->dlist, dev, pagectm (page), bbox, NULL);
745 fz_free_device (dev);
747 return tile;
750 static void initpdims (void)
752 int pageno;
753 double start, end;
755 start = now ();
756 for (pageno = 0; pageno < state.pagecount; ++pageno) {
757 int rotate;
758 fz_obj *pageobj;
759 struct pagedim *p;
760 fz_rect mediabox;
762 switch (state.type) {
763 case DPDF:
764 pageobj = state.u.pdf->page_objs[pageno];
766 if (state.trimmargins) {
767 fz_obj *obj;
768 pdf_page *page;
770 page = pdf_load_page (state.u.pdf, pageno);
771 obj = fz_dict_gets (pageobj, "llpp.TrimBox");
772 if (state.trimanew || !obj) {
773 fz_rect rect;
774 fz_bbox bbox;
775 fz_matrix ctm;
776 fz_device *dev;
778 dev = fz_new_bbox_device (state.ctx, &bbox);
779 dev->hints |= FZ_IGNORE_SHADE;
780 ctm = fz_invert_matrix (page->ctm);
781 pdf_run_page (state.u.pdf, page, dev, fz_identity, NULL);
782 fz_free_device (dev);
784 rect.x0 = bbox.x0 + state.trimfuzz.x0;
785 rect.x1 = bbox.x1 + state.trimfuzz.x1;
786 rect.y0 = bbox.y0 + state.trimfuzz.y0;
787 rect.y1 = bbox.y1 + state.trimfuzz.y1;
788 rect = fz_transform_rect (ctm, rect);
789 rect = fz_intersect_rect (rect, page->mediabox);
791 if (fz_is_empty_rect (rect)) {
792 mediabox = page->mediabox;
794 else {
795 mediabox = rect;
798 obj = fz_new_array (state.ctx, 4);
799 fz_array_push (obj, fz_new_real (state.ctx, mediabox.x0));
800 fz_array_push (obj, fz_new_real (state.ctx, mediabox.y0));
801 fz_array_push (obj, fz_new_real (state.ctx, mediabox.x1));
802 fz_array_push (obj, fz_new_real (state.ctx, mediabox.y1));
803 fz_dict_puts (pageobj, "llpp.TrimBox", obj);
805 else {
806 mediabox.x0 = fz_to_real (fz_array_get (obj, 0));
807 mediabox.y0 = fz_to_real (fz_array_get (obj, 1));
808 mediabox.x1 = fz_to_real (fz_array_get (obj, 2));
809 mediabox.y1 = fz_to_real (fz_array_get (obj, 3));
812 rotate = page->rotate;
813 pdf_free_page (state.u.pdf, page);
815 printd ("progress %f Trimming %d",
816 (double) (pageno + 1) / state.pagecount,
817 pageno + 1);
819 else {
820 fz_rect cropbox;
822 mediabox = pdf_to_rect (state.ctx,
823 fz_dict_gets (pageobj, "MediaBox"));
824 if (fz_is_empty_rect (mediabox)) {
825 fprintf (stderr, "cannot find page size for page %d\n",
826 pageno+1);
827 mediabox.x0 = 0;
828 mediabox.y0 = 0;
829 mediabox.x1 = 612;
830 mediabox.y1 = 792;
833 cropbox = pdf_to_rect (state.ctx,
834 fz_dict_gets (pageobj, "CropBox"));
835 if (!fz_is_empty_rect (cropbox)) {
836 mediabox = fz_intersect_rect (mediabox, cropbox);
838 rotate = fz_to_int (fz_dict_gets (pageobj, "Rotate"));
840 break;
842 case DXPS:
844 xps_page *page;
846 page = xps_load_page (state.u.xps, pageno);
847 mediabox = xps_bound_page (state.u.xps, page);
848 rotate = 0;
849 if (state.trimmargins) {
850 fz_rect rect;
851 fz_bbox bbox;
852 fz_device *dev;
854 dev = fz_new_bbox_device (state.ctx, &bbox);
855 dev->hints |= FZ_IGNORE_SHADE;
856 xps_run_page (state.u.xps, page, dev, fz_identity, NULL);
857 fz_free_device (dev);
859 rect.x0 = bbox.x0 + state.trimfuzz.x0;
860 rect.x1 = bbox.x1 + state.trimfuzz.x1;
861 rect.y0 = bbox.y0 + state.trimfuzz.y0;
862 rect.y1 = bbox.y1 + state.trimfuzz.y1;
863 rect = fz_intersect_rect (rect, mediabox);
865 if (!fz_is_empty_rect (rect)) {
866 mediabox = rect;
869 xps_free_page (state.u.xps, page);
870 printd ("progress %f loading %d",
871 (double) (pageno + 1) / state.pagecount,
872 pageno + 1);
874 break;
876 case DCBZ:
878 rotate = 0;
879 if (state.trimmargins) {
880 cbz_page *page;
882 page = cbz_load_page (state.u.cbz, pageno);
883 mediabox = cbz_bound_page (state.u.cbz, page);
884 cbz_free_page (state.u.cbz, page);
885 printd ("progress %f Trimming %d",
886 (double) (pageno + 1) / state.pagecount,
887 pageno + 1);
889 else {
890 mediabox.x0 = mediabox.y0 = 0;
891 mediabox.x1 = 900;
892 mediabox.y1 = 900;
895 break;
897 default:
898 ARSERT (0 && state.type);
901 if (state.pagedimcount == 0
902 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
903 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
904 size_t size;
906 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
907 state.pagedims = realloc (state.pagedims, size);
908 if (!state.pagedims) {
909 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
910 size, state.pagedimcount + 1);
913 p = &state.pagedims[state.pagedimcount++];
914 p->rotate = rotate;
915 p->mediabox = mediabox;
916 p->pageno = pageno;
919 end = now ();
920 if (state.trimmargins) {
921 printd ("progress 1 Trimmed %d pages in %f seconds",
922 state.pagecount, end - start);
924 else {
925 printd ("vmsg Processed %d pages in %f seconds",
926 state.pagecount, end - start);
928 state.trimanew = 0;
931 static void layout (void)
933 int pindex;
934 fz_rect box;
935 fz_matrix ctm;
936 double zoom, w, maxw = 0;
937 struct pagedim *p = state.pagedims;
939 if (state.proportional) {
940 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
941 box = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
942 p->mediabox);
943 w = box.x1 - box.x0;
944 maxw = MAX (w, maxw);
948 p = state.pagedims;
949 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
950 fz_bbox bbox;
952 ctm = fz_rotate (state.rotate);
953 box = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
954 p->mediabox);
955 w = box.x1 - box.x0;
957 if (state.proportional) {
958 double scale = w / maxw;
959 zoom = (state.w / w) * scale;
961 else {
962 zoom = state.w / w;
965 p->zoomctm = fz_scale (zoom, zoom);
966 ctm = fz_concat (p->zoomctm, ctm);
968 p->pagebox = fz_transform_rect (fz_rotate (p->rotate), p->mediabox);
969 p->pagebox.x1 -= p->pagebox.x0;
970 p->pagebox.y1 -= p->pagebox.y0;
971 p->pagebox.x0 = 0;
972 p->pagebox.y0 = 0;
973 bbox = fz_round_rect (fz_transform_rect (ctm, p->pagebox));
975 p->bounds = bbox;
976 p->left = state.proportional ? ((maxw - w) * zoom) / 2.0 : 0;
977 p->ctm = ctm;
979 ctm = fz_identity;
980 ctm = fz_concat (ctm, fz_translate (0, -p->mediabox.y1));
981 ctm = fz_concat (ctm, fz_scale (zoom, -zoom));
982 ctm = fz_concat (ctm, fz_rotate (p->rotate + state.rotate));
983 p->lctm = ctm;
985 p->tctmready = 0;
988 while (p-- != state.pagedims) {
989 int w = p->bounds.x1;
990 int h = p->bounds.y1;
992 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
996 static void recurse_outline (fz_outline *outline, int level)
998 while (outline) {
999 fz_link_dest *dest;
1000 int i, top = 0;
1001 struct pagedim *pdim = state.pagedims;
1003 dest = &outline->dest;
1004 for (i = 0; i < state.pagedimcount; ++i) {
1005 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1006 break;
1007 pdim = &state.pagedims[i];
1009 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1010 fz_point p;
1011 p.x = 0;
1012 p.y = dest->ld.gotor.lt.y;
1013 p = fz_transform_point (pdim->lctm, p);
1014 top = p.y;
1016 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1017 int h;
1018 double y0, y1;
1020 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1021 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1022 h = y1 - y0;
1023 printd ("o %d %d %d %d %s",
1024 level, dest->ld.gotor.page, top, h, outline->title);
1026 if (outline->down) {
1027 recurse_outline (outline->down, level + 1);
1029 outline = outline->next;
1033 static void process_outline (void)
1035 fz_outline *outline;
1037 if (!state.needoutline) return;
1039 state.needoutline = 0;
1040 switch (state.type) {
1041 case DPDF:
1042 outline = pdf_load_outline (state.u.pdf);
1043 break;
1044 case DXPS:
1045 outline = xps_load_outline (state.u.xps);
1046 break;
1047 default:
1048 outline = NULL;
1049 break;
1051 if (outline) {
1052 recurse_outline (outline, 0);
1053 fz_free_outline (state.ctx, outline);
1057 static int comparespans (const void *l, const void *r)
1059 fz_text_span const *const*ls = l;
1060 fz_text_span const *const*rs = r;
1061 return (*ls)->text->bbox.y0 - (*rs)->text->bbox.y0;
1064 /* wishful thinking function */
1065 static void search (regex_t *re, int pageno, int y, int forward)
1067 int i, j;
1068 int ret;
1069 char *p;
1070 char buf[256];
1071 fz_matrix ctm;
1072 fz_device *tdev;
1073 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1074 fz_text_span *text, *span, **pspan;
1075 struct pagedim *pdim, *pdimprev;
1076 int stop = 0;
1077 int niters = 0;
1078 int nspans;
1079 double start, end;
1081 if (!(state.type == DPDF || state.type == DXPS))
1082 return;
1084 start = now ();
1085 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1086 if (niters++ == 5) {
1087 niters = 0;
1088 if (hasdata ()) {
1089 printd ("progress 1 attention requested aborting search at %d",
1090 pageno);
1091 stop = 1;
1093 else {
1094 printd ("progress %f searching in page %d",
1095 (double) (pageno + 1) / state.pagecount,
1096 pageno);
1099 pdimprev = NULL;
1100 for (i = 0; i < state.pagedimcount; ++i) {
1101 pdim = &state.pagedims[i];
1102 if (pdim->pageno == pageno) {
1103 goto found;
1105 if (pdim->pageno > pageno) {
1106 pdim = pdimprev;
1107 goto found;
1109 pdimprev = pdim;
1111 pdim = pdimprev;
1112 found:
1114 text = fz_new_text_span (state.ctx);
1115 tdev = fz_new_text_device (state.ctx, text);
1117 switch (state.type) {
1118 case DPDF:
1119 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1120 pdf_run_page (state.u.pdf, u.pdfpage, tdev, fz_identity, NULL);
1121 break;
1123 case DXPS:
1124 u.xpspage = xps_load_page (state.u.xps, pageno);
1125 xps_run_page (state.u.xps, u.xpspage, tdev, fz_identity, NULL);
1126 break;
1128 default:
1129 ARSERT (0 && state.type);
1132 fz_free_device (tdev);
1134 nspans = 0;
1135 for (span = text; span; span = span->next) {
1136 nspans++;
1138 pspan = malloc (sizeof (void *) * nspans);
1139 if (!pspan) {
1140 err (1, "malloc span pointers %" FMT_s, sizeof (void *) * nspans);
1142 for (i = 0, span = text; span; span = span->next, ++i) {
1143 pspan[i] = span;
1145 qsort (pspan, nspans, sizeof (fz_text_span *), comparespans);
1147 j = forward ? 0 : nspans - 1;
1148 while (nspans--) {
1149 regmatch_t rm;
1151 span = pspan[j];
1152 j += forward ? 1 : -1;
1153 p = buf;
1154 for (i = 0; i < span->len; ++i) {
1155 int len;
1156 char cbuf[4];
1158 if (forward) {
1159 if (span->text[i].bbox.y0 < y + 1) {
1160 continue;
1163 else {
1164 if (span->text[i].bbox.y0 > y - 1) {
1165 continue;
1168 len = runetochar (cbuf, &span->text[i].c);
1169 if (sizeof (buf) - 1 - (p - buf) > len) {
1170 int k;
1171 for (k = 0; k < len; ++k)
1172 *p++ = cbuf[k];
1174 else {
1175 break;
1178 if (p == buf) {
1179 continue;
1181 *p++ = 0;
1183 ret = regexec (re, buf, 1, &rm, 0);
1184 if (ret) {
1185 if (ret != REG_NOMATCH) {
1186 size_t size;
1187 char errbuf[80];
1188 size = regerror (ret, re, errbuf, sizeof (errbuf));
1189 printd ("msg regexec error `%.*s'",
1190 (int) size, errbuf);
1191 fz_free_text_span (state.ctx, text);
1192 state.freepage (u.ptr);
1193 free (pspan);
1194 return;
1197 else {
1198 fz_bbox *sb, *eb;
1199 fz_point p1, p2, p3, p4;
1200 int a, b, c, l;
1202 l = span->len;
1203 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1204 c += runelen (span->text[a].c);
1206 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1207 c += runelen (span->text[b].c);
1210 if (runelen (span->text[b].c) > 1) {
1211 b = MAX (0, b-1);
1213 sb = &span->text[MIN (a, l-1)].bbox;
1214 eb = &span->text[MIN (b, l-1)].bbox;
1216 p1.x = sb->x0;
1217 p1.y = sb->y0;
1218 p2.x = eb->x1;
1219 p2.y = sb->y0;
1220 p3.x = eb->x1;
1221 p3.y = eb->y1;
1222 p4.x = sb->x0;
1223 p4.y = eb->y1;
1225 switch (state.type) {
1226 case DPDF:
1227 trimctm (u.pdfpage, pdim - state.pagedims);
1228 ctm = fz_concat (pdim->tctm, pdim->zoomctm);
1229 break;
1231 case DXPS:
1232 ctm = pdim->ctm;
1233 break;
1236 p1 = fz_transform_point (ctm, p1);
1237 p2 = fz_transform_point (ctm, p2);
1238 p3 = fz_transform_point (ctm, p3);
1239 p4 = fz_transform_point (ctm, p4);
1241 if (!stop) {
1242 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1243 pageno, 1,
1244 p1.x, p1.y,
1245 p2.x, p2.y,
1246 p3.x, p3.y,
1247 p4.x, p4.y);
1249 printd ("progress 1 found at %d `%.*s' in %f sec",
1250 pageno, (int) (rm.rm_eo - rm.rm_so), &buf[rm.rm_so],
1251 now () - start);
1253 else {
1254 printd ("match %d %d %f %f %f %f %f %f %f %f",
1255 pageno, 2,
1256 p1.x, p1.y,
1257 p2.x, p2.y,
1258 p3.x, p3.y,
1259 p4.x, p4.y);
1261 stop = 1;
1264 if (forward) {
1265 pageno += 1;
1266 y = 0;
1268 else {
1269 pageno -= 1;
1270 y = INT_MAX;
1272 fz_free_text_span (state.ctx, text);
1273 state.freepage (u.ptr);
1274 free (pspan);
1276 end = now ();
1277 if (!stop) {
1278 printd ("progress 1 no matches %f sec", end - start);
1280 printd ("clearrects");
1283 static void set_tex_params (int colorspace)
1285 switch (colorspace) {
1286 case 0:
1287 state.texiform = GL_RGBA8;
1288 state.texform = GL_RGBA;
1289 state.texty = GL_UNSIGNED_BYTE;
1290 state.colorspace = fz_device_rgb;
1291 break;
1292 case 1:
1293 state.texiform = GL_RGBA8;
1294 state.texform = GL_BGRA;
1295 state.texty = fz_is_big_endian ()
1296 ? GL_UNSIGNED_INT_8_8_8_8
1297 : GL_UNSIGNED_INT_8_8_8_8_REV;
1298 state.colorspace = fz_device_bgr;
1299 break;
1300 case 2:
1301 state.texiform = GL_LUMINANCE_ALPHA;
1302 state.texform = GL_LUMINANCE_ALPHA;
1303 state.texty = GL_UNSIGNED_BYTE;
1304 state.colorspace = fz_device_gray;
1305 break;
1306 default:
1307 errx (1, "invalid colorspce %d", colorspace);
1311 static void realloctexts (int texcount)
1313 size_t size;
1315 if (texcount == state.texcount) return;
1317 if (texcount < state.texcount) {
1318 glDeleteTextures (state.texcount - texcount,
1319 state.texids + texcount);
1322 size = texcount * sizeof (*state.texids);
1323 state.texids = realloc (state.texids, size);
1324 if (!state.texids) {
1325 err (1, "realloc texids %" FMT_s, size);
1328 size = texcount * sizeof (*state.texowners);
1329 state.texowners = realloc (state.texowners, size);
1330 if (!state.texowners) {
1331 err (1, "realloc texowners %" FMT_s, size);
1333 if (texcount > state.texcount) {
1334 int i;
1336 glGenTextures (texcount - state.texcount,
1337 state.texids + state.texcount);
1338 for (i = state.texcount; i < texcount; ++i) {
1339 state.texowners[i].w = -1;
1340 state.texowners[i].slice = NULL;
1343 state.texcount = texcount;
1344 state.texindex = 0;
1347 static void * mainloop (void *unused)
1349 char *p = NULL;
1350 int len, ret, oldlen = 0;
1352 for (;;) {
1353 len = readlen ();
1354 if (len == 0) {
1355 errx (1, "readlen returned 0");
1358 if (oldlen < len + 1) {
1359 p = realloc (p, len + 1);
1360 if (!p) {
1361 err (1, "realloc %d failed", len + 1);
1363 oldlen = len + 1;
1365 readdata (p, len);
1366 p[len] = 0;
1368 if (!strncmp ("open", p, 4)) {
1369 size_t filenamelen;
1370 char *password;
1371 char *filename = p + 5;
1373 filenamelen = strlen (filename);
1374 password = filename + filenamelen + 1;
1376 openxref (filename, password);
1377 pdfinfo ();
1378 initpdims ();
1379 printd ("msg Opened %s (press h/F1 to get help)", filename);
1380 state.needoutline = 1;
1382 else if (!strncmp ("cs", p, 2)) {
1383 int i, colorspace;
1385 ret = sscanf (p + 2, " %d", &colorspace);
1386 if (ret != 1) {
1387 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1389 lock ("cs");
1390 set_tex_params (colorspace);
1391 for (i = 0; i < state.texcount; ++i) {
1392 state.texowners[i].w = -1;
1393 state.texowners[i].slice = NULL;
1395 unlock ("cs");
1397 else if (!strncmp ("freepage", p, 8)) {
1398 void *ptr;
1400 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1401 if (ret != 1) {
1402 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1404 freepage (ptr);
1406 else if (!strncmp ("freetile", p, 8)) {
1407 void *ptr;
1409 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1410 if (ret != 1) {
1411 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1413 freetile (ptr);
1415 else if (!strncmp ("search", p, 6)) {
1416 int icase, pageno, y, ret, len2, forward;
1417 char *pattern;
1418 regex_t re;
1420 ret = sscanf (p + 6, " %d %d %d %d,%n",
1421 &icase, &pageno, &y, &forward, &len2);
1422 if (ret != 4) {
1423 errx (1, "malformed search `%s' ret=%d", p, ret);
1426 pattern = p + 6 + len2;
1427 ret = regcomp (&re, pattern,
1428 REG_EXTENDED | (icase ? REG_ICASE : 0));
1429 if (ret) {
1430 char errbuf[80];
1431 size_t size;
1433 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1434 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1436 else {
1437 search (&re, pageno, y, forward);
1438 regfree (&re);
1441 else if (!strncmp ("geometry", p, 8)) {
1442 int w, h;
1444 printd ("clear");
1445 ret = sscanf (p + 8, " %d %d", &w, &h);
1446 if (ret != 2) {
1447 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1450 lock ("geometry");
1451 state.h = h;
1452 if (w != state.w) {
1453 int i;
1454 state.w = w;
1455 for (i = 0; i < state.texcount; ++i) {
1456 state.texowners[i].slice = NULL;
1459 layout ();
1460 process_outline ();
1461 state.gen++;
1462 unlock ("geometry");
1463 printd ("continue %d", state.pagecount);
1465 else if (!strncmp ("reqlayout", p, 9)) {
1466 int rotate, proportional;
1468 printd ("clear");
1469 ret = sscanf (p + 9, " %d %d", &rotate, &proportional);
1470 if (ret != 2) {
1471 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1473 lock ("reqlayout");
1474 state.rotate = rotate;
1475 state.proportional = proportional;
1476 layout ();
1477 unlock ("reqlayout");
1478 printd ("continue %d", state.pagecount);
1480 else if (!strncmp ("page", p, 4)) {
1481 double a, b;
1482 struct page *page;
1483 int pageno, pindex, ret;
1485 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1486 if (ret != 2) {
1487 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1490 lock ("page");
1491 a = now ();
1492 page = loadpage (pageno, pindex);
1493 b = now ();
1494 unlock ("page");
1496 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1498 else if (!strncmp ("tile", p, 4)) {
1499 int x, y, w, h, ret;
1500 struct page *page;
1501 struct tile *tile;
1502 double a, b;
1504 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d",
1505 FMT_ptr_cast (&page), &x, &y, &w, &h);
1506 if (ret != 5) {
1507 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1510 lock ("tile");
1511 a = now ();
1512 tile = rendertile (page, x, y, w, h);
1513 b = now ();
1514 unlock ("tile");
1516 printd ("tile %d %d %" FMT_ptr " %u %f",
1517 x, y,
1518 FMT_ptr_cast2 (tile),
1519 tile->w * tile->h * tile->pixmap->n,
1520 b - a);
1522 else if (!strncmp ("settrim", p, 7)) {
1523 int trimmargins;
1524 fz_bbox fuzz;
1526 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1527 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1528 if (ret != 5) {
1529 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1531 printd ("clear");
1532 lock ("settrim");
1533 state.trimmargins = trimmargins;
1534 state.needoutline = 1;
1535 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1536 state.trimanew = 1;
1537 state.trimfuzz = fuzz;
1539 state.pagedimcount = 0;
1540 free (state.pagedims);
1541 state.pagedims = NULL;
1542 initpdims ();
1543 layout ();
1544 process_outline ();
1545 unlock ("settrim");
1546 printd ("continue %d", state.pagecount);
1548 else if (!strncmp ("sliceh", p, 6)) {
1549 int h;
1551 ret = sscanf (p + 6, " %d", &h);
1552 if (ret != 1) {
1553 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1555 if (h != state.sliceheight) {
1556 int i;
1558 state.sliceheight = h;
1559 for (i = 0; i < state.texcount; ++i) {
1560 state.texowners[i].w = -1;
1561 state.texowners[i].h = -1;
1562 state.texowners[i].slice = NULL;
1566 else if (!strncmp ("interrupt", p, 9)) {
1567 printd ("vmsg interrupted");
1569 else if (!strncmp ("quit", p, 4)) {
1570 return 0;
1572 else {
1573 errx (1, "unknown command %.*s", len, p);
1576 return 0;
1579 CAMLprim value ml_realloctexts (value texcount_v)
1581 CAMLparam1 (texcount_v);
1582 int ok;
1584 if (trylock ("ml_realloctexts")) {
1585 ok = 0;
1586 goto done;
1588 realloctexts (Int_val (texcount_v));
1589 ok = 1;
1590 unlock ("ml_realloctexts");
1592 done:
1593 CAMLreturn (Val_bool (ok));
1596 static void showsel (struct page *page, int ox, int oy)
1598 fz_bbox bbox;
1599 fz_text_span *span;
1600 struct mark first, last;
1602 first = page->fmark;
1603 last = page->lmark;
1605 if (!first.span || !last.span) return;
1607 glEnable (GL_BLEND);
1608 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1609 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1611 for (span = first.span; span; span = span->next) {
1612 int i, j, k;
1614 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1616 j = 0;
1617 k = span->len - 1;
1619 if (span == page->fmark.span && span == page->lmark.span) {
1620 j = MIN (first.i, last.i);
1621 k = MAX (first.i, last.i);
1623 else if (span == first.span) {
1624 j = first.i;
1626 else if (span == last.span) {
1627 k = last.i;
1630 for (i = j; i <= k; ++i) {
1631 bbox = fz_union_bbox (bbox, span->text[i].bbox);
1633 lprintf ("%d %d %d %d oy=%d ox=%d\n",
1634 bbox.x0,
1635 bbox.y0,
1636 bbox.x1,
1637 bbox.y1,
1638 oy, ox);
1640 glRecti (bbox.x0 + ox, bbox.y0 + oy, bbox.x1 + ox, bbox.y1 + oy);
1642 if (span == last.span) break;
1644 glDisable (GL_BLEND);
1647 static void highlightlinks (struct page *page, int xoff, int yoff)
1649 fz_matrix ctm;
1650 fz_link *link, *links;
1652 switch (page->type) {
1653 case DPDF:
1654 links = page->u.pdfpage->links;
1655 break;
1657 case DXPS:
1658 links = page->u.xpspage->links;
1659 break;
1661 default:
1662 return;
1665 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
1666 glEnable (GL_LINE_STIPPLE);
1667 glLineStipple (0.5, 0xcccc);
1669 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1671 glBegin (GL_QUADS);
1672 for (link = links; link; link = link->next) {
1673 fz_point p1, p2, p3, p4;
1675 p1.x = link->rect.x0;
1676 p1.y = link->rect.y0;
1678 p2.x = link->rect.x1;
1679 p2.y = link->rect.y0;
1681 p3.x = link->rect.x1;
1682 p3.y = link->rect.y1;
1684 p4.x = link->rect.x0;
1685 p4.y = link->rect.y1;
1687 p1 = fz_transform_point (ctm, p1);
1688 p2 = fz_transform_point (ctm, p2);
1689 p3 = fz_transform_point (ctm, p3);
1690 p4 = fz_transform_point (ctm, p4);
1692 switch (link->dest.kind) {
1693 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
1694 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
1695 default: glColor3ub (0, 0, 0); break;
1698 glVertex2f (p1.x, p1.y);
1699 glVertex2f (p2.x, p2.y);
1700 glVertex2f (p3.x, p3.y);
1701 glVertex2f (p4.x, p4.y);
1703 glEnd ();
1705 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1706 glDisable (GL_LINE_STIPPLE);
1709 static void uploadslice (struct tile *tile, struct slice *slice)
1711 int offset;
1712 struct slice *slice1;
1714 offset = 0;
1715 for (slice1 = tile->slices; slice != slice1; slice1++) {
1716 offset += slice1->h * tile->w * tile->pixmap->n;
1718 if (slice->texindex != -1 && slice->texindex < state.texcount
1719 && state.texowners[slice->texindex].slice == slice) {
1720 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
1722 else {
1723 int subimage = 0;
1724 int texindex = state.texindex++ % state.texcount;
1726 if (state.texowners[texindex].w == tile->w) {
1727 if (state.texowners[texindex].h >= slice->h) {
1728 subimage = 1;
1730 else {
1731 state.texowners[texindex].h = slice->h;
1734 else {
1735 state.texowners[texindex].h = slice->h;
1738 state.texowners[texindex].w = tile->w;
1739 state.texowners[texindex].slice = slice;
1740 slice->texindex = texindex;
1742 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
1743 if (subimage) {
1744 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
1748 tile->w,
1749 slice->h,
1750 state.texform,
1751 state.texty,
1752 tile->pixmap->samples+offset
1755 else {
1756 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
1758 state.texiform,
1759 tile->w,
1760 slice->h,
1762 state.texform,
1763 state.texty,
1764 tile->pixmap->samples+offset
1770 CAMLprim value ml_drawtile (value args_v, value ptr_v)
1772 CAMLparam2 (args_v, ptr_v);
1773 int dispx = Int_val (Field (args_v, 0));
1774 int dispy = Int_val (Field (args_v, 1));
1775 int dispw = Int_val (Field (args_v, 2));
1776 int disph = Int_val (Field (args_v, 3));
1777 int tilex = Int_val (Field (args_v, 4));
1778 int tiley = Int_val (Field (args_v, 5));
1779 char *s = String_val (ptr_v);
1780 struct tile *tile = parse_pointer ("ml_drawtile", s);
1782 glEnable (GL_TEXTURE_RECTANGLE_ARB);
1784 int slicey, firstslice;
1785 struct slice *slice;
1787 firstslice = tiley / tile->sliceheight;
1788 slice = &tile->slices[firstslice];
1789 slicey = tiley % tile->sliceheight;
1791 while (disph > 0) {
1792 int dh;
1794 dh = slice->h - slicey;
1795 dh = MIN (disph, dh);
1796 uploadslice (tile, slice);
1798 glBegin (GL_QUADS);
1800 glTexCoord2i (tilex, slicey);
1801 glVertex2i (dispx, dispy);
1803 glTexCoord2i (tilex+dispw, slicey);
1804 glVertex2i (dispx+dispw, dispy);
1806 glTexCoord2i (tilex+dispw, slicey+dh);
1807 glVertex2i (dispx+dispw, dispy+dh);
1809 glTexCoord2i (tilex, slicey+dh);
1810 glVertex2i (dispx, dispy+dh);
1812 glEnd ();
1814 dispy += dh;
1815 disph -= dh;
1816 slice++;
1817 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
1818 slicey = 0;
1821 glDisable (GL_TEXTURE_RECTANGLE_ARB);
1822 CAMLreturn (Val_unit);
1825 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
1826 value xoff_v, value yoff_v)
1828 CAMLparam4 (ptr_v, hlinks_v, xoff_v, yoff_v);
1829 int xoff = Int_val (xoff_v);
1830 int yoff = Int_val (yoff_v);
1831 char *s = String_val (ptr_v);
1832 struct page *page = parse_pointer ("ml_postprocess", s);
1834 if (Bool_val (hlinks_v)) highlightlinks (page, xoff, yoff);
1836 if (trylock ("ml_postprocess")) {
1837 goto done;
1839 showsel (page, xoff, yoff);
1840 unlock ("ml_postprocess");
1842 done:
1843 CAMLreturn (Val_unit);
1846 static fz_link *getlink (struct page *page, int x, int y)
1848 fz_point p;
1849 fz_matrix ctm;
1850 fz_link *link, *links;
1852 switch (page->type) {
1853 case DPDF:
1854 ctm = trimctm (page->u.pdfpage, page->pdimno);
1855 links = page->u.pdfpage->links;
1856 break;
1858 case DXPS:
1859 ctm = fz_identity;
1860 links = page->u.xpspage->links;
1861 break;
1863 default:
1864 return NULL;
1866 p.x = x;
1867 p.y = y;
1869 ctm = fz_concat (ctm, state.pagedims[page->pdimno].ctm);
1870 ctm = fz_invert_matrix (ctm);
1871 p = fz_transform_point (ctm, p);
1873 for (link = links; link; link = link->next) {
1874 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
1875 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
1876 return link;
1880 return NULL;
1883 static void droptext (struct page *page)
1885 if (page->text) {
1886 fz_free_text_span (state.ctx, page->text);
1887 page->fmark.i = -1;
1888 page->lmark.i = -1;
1889 page->fmark.span = NULL;
1890 page->lmark.span = NULL;
1891 page->text = NULL;
1895 static void ensuretext (struct page *page)
1897 if (state.gen != page->gen) {
1898 droptext (page);
1899 page->gen = state.gen;
1901 if (!page->text) {
1902 fz_device *tdev;
1904 page->text = fz_new_text_span (state.ctx);
1905 tdev = fz_new_text_device (state.ctx, page->text);
1906 fz_run_display_list (page->dlist,
1907 tdev,
1908 pagectm (page),
1909 fz_infinite_bbox, NULL);
1910 fz_free_device (tdev);
1914 static int compareslinks (const void *l, const void *r)
1916 struct slink const *ls = l;
1917 struct slink const *rs = r;
1918 if (ls->bbox.y0 == rs->bbox.y0) {
1919 return rs->bbox.x0 - rs->bbox.x0;
1921 return ls->bbox.y0 - rs->bbox.y0;
1924 static char *regiontext (struct page *page, fz_bbox bbox)
1926 char *buf = NULL;
1927 fz_text_span *span;
1928 int bufcap = 0, buflen = 0;
1930 ensuretext (page);
1931 for (span = page->text; span; span = span->next) {
1932 int i;
1934 for (i = 0; i < span->len; ++i) {
1935 fz_bbox b, tb;
1937 tb = span->text[i].bbox;
1938 b = fz_intersect_bbox (bbox, tb);
1939 if (fz_is_empty_bbox (b)) {
1940 int len;
1941 char utf8[4];
1943 len = runetochar (utf8, &span->text[i].c);
1944 if (buflen + len + 1 >= bufcap) {
1945 size_t size;
1946 bufcap = bufcap + len + 1;
1947 size = bufcap;
1948 buf = realloc (buf, size);
1949 if (!buf) {
1950 err (1, "realloc %" FMT_s, size);
1953 memcpy (buf + buflen, utf8, len);
1954 buflen += len;
1958 if (buf) {
1959 buf[buflen] = 0;
1961 return buf;
1964 static void ensureslinks (struct page *page)
1966 fz_matrix ctm;
1967 int i, count = 0;
1968 size_t slinksize = sizeof (*page->slinks);
1969 fz_link *link, *links;
1971 if (page->slinks) return;
1973 switch (page->type) {
1974 case DPDF:
1975 links = page->u.pdfpage->links;
1976 ctm = fz_concat (trimctm (page->u.pdfpage, page->pdimno),
1977 state.pagedims[page->pdimno].ctm);
1978 break;
1980 case DXPS:
1981 links = page->u.xpspage->links;
1982 ctm = state.pagedims[page->pdimno].ctm;
1983 break;
1985 default:
1986 return;
1989 for (link = links; link; link = link->next) {
1990 count++;
1992 if (count > 0) {
1993 page->slinkcount = count;
1994 page->slinks = calloc (count, slinksize);
1995 if (!page->slinks) {
1996 err (1, "realloc slinks %d", count);
1999 for (i = 0, link = links; link; ++i, link = link->next) {
2000 page->slinks[i].link = link;
2001 page->slinks[i].bbox =
2002 fz_round_rect (fz_transform_rect (ctm, link->rect));
2003 page->slinks[i].text = regiontext (page, page->slinks[i].bbox);
2005 qsort (page->slinks, count, slinksize, compareslinks);
2009 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2011 CAMLparam2 (start_page_v, dir_v);
2012 CAMLlocal1 (ret_v);
2013 int i, dir = Int_val (dir_v);
2014 int start_page = Int_val (start_page_v);
2015 int end_page = dir > 0 ? state.pagecount : -1;
2017 ret_v = Val_int (0);
2018 if (!(state.type == DPDF || state.type == DXPS)) {
2019 goto done;
2022 lock ("ml_findpage_with_links");
2023 for (i = start_page + dir; i != end_page; i += dir) {
2024 int found;
2026 switch (state.type) {
2027 case DPDF:
2029 pdf_page *page = pdf_load_page (state.u.pdf, i);
2030 found = !!page->links;
2031 freepdfpage (page);
2033 break;
2034 case DXPS:
2036 xps_page *page = xps_load_page (state.u.xps, i);
2037 found = !!page->links;
2038 freexpspage (page);
2040 break;
2042 default:
2043 ARSERT ("invalid document type");
2046 if (found) {
2047 ret_v = caml_alloc_small (1, 1);
2048 Field (ret_v, 0) = Val_int (i);
2049 goto unlock;
2052 unlock:
2053 unlock ("ml_findpage_with_links");
2055 done:
2056 CAMLreturn (ret_v);
2059 enum { dir_first, dir_last};
2060 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2062 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2064 CAMLparam2 (ptr_v, dir_v);
2065 CAMLlocal3 (ret_v, tup_v, pos_v);
2066 struct page *page;
2067 int dirtag, i, slinkindex;
2068 struct slink *found = NULL ,*slink;
2069 char *s = String_val (ptr_v);
2071 lock ("ml_findlink");
2073 page = parse_pointer ("ml_findlink", s);
2074 ensureslinks (page);
2076 ret_v = Val_int (0);
2077 if (Is_block (dir_v)) {
2078 dirtag = Tag_val (dir_v);
2079 switch (dirtag) {
2080 case dir_first_visible:
2082 int x0, y0, dir;
2084 pos_v = Field (dir_v, 0);
2085 x0 = Int_val (Field (pos_v, 0));
2086 y0 = Int_val (Field (pos_v, 1));
2087 dir = Int_val (Field (pos_v, 2));
2089 if (dir >= 0) {
2090 for (i = 0; i < page->slinkcount; ++i) {
2091 slink = &page->slinks[i];
2092 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2093 found = slink;
2094 break;
2098 else {
2099 for (i = page->slinkcount - 1; i >= 0; --i) {
2100 slink = &page->slinks[i];
2101 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2102 found = slink;
2103 break;
2108 break;
2110 case dir_left:
2111 slinkindex = Int_val (Field (dir_v, 0));
2112 found = &page->slinks[slinkindex];
2113 for (i = slinkindex - 1; i >= 0; --i) {
2114 slink = &page->slinks[i];
2115 if (slink->bbox.x0 < found->bbox.x0) {
2116 found = slink;
2117 break;
2120 break;
2122 case dir_right:
2123 slinkindex = Int_val (Field (dir_v, 0));
2124 found = &page->slinks[slinkindex];
2125 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2126 slink = &page->slinks[i];
2127 if (slink->bbox.x0 > found->bbox.x0) {
2128 found = slink;
2129 break;
2132 break;
2134 case dir_down:
2135 slinkindex = Int_val (Field (dir_v, 0));
2136 found = &page->slinks[slinkindex];
2137 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2138 slink = &page->slinks[i];
2139 if (slink->bbox.y0 > found->bbox.y0) {
2140 found = slink;
2141 break;
2144 break;
2146 case dir_up:
2147 slinkindex = Int_val (Field (dir_v, 0));
2148 found = &page->slinks[slinkindex];
2149 for (i = slinkindex - 1; i >= 0; --i) {
2150 slink = &page->slinks[i];
2151 if (slink->bbox.y0 < found->bbox.y0) {
2152 found = slink;
2153 break;
2156 break;
2159 else {
2160 dirtag = Int_val (dir_v);
2161 switch (dirtag) {
2162 case dir_first:
2163 found = page->slinks;
2164 break;
2166 case dir_last:
2167 if (page->slinks) {
2168 found = page->slinks + (page->slinkcount - 1);
2170 break;
2173 if (found) {
2174 tup_v = caml_alloc_tuple (5);
2175 ret_v = caml_alloc_small (2, 1);
2176 Field (tup_v, 0) = Val_int (found - page->slinks);
2177 Field (tup_v, 1) = Val_int (found->bbox.x0);
2178 Field (tup_v, 2) = Val_int (found->bbox.y0);
2179 Field (tup_v, 3) = Val_int (found->bbox.x1);
2180 Field (tup_v, 4) = Val_int (found->bbox.y1);
2181 Field (ret_v, 0) = tup_v;
2184 unlock ("ml_findlink");
2185 CAMLreturn (ret_v);
2188 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2190 #define LINKTOVAL \
2192 int pageno; \
2194 switch (link->dest.kind) { \
2195 case FZ_LINK_GOTO: \
2197 fz_point p; \
2199 pageno = link->dest.ld.gotor.page; \
2200 p.x = 0; \
2201 p.y = 0; \
2203 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2204 p.y = link->dest.ld.gotor.lt.y; \
2205 p = fz_transform_point (pdim->lctm, p); \
2207 tup_v = caml_alloc_tuple (2); \
2208 ret_v = caml_alloc_small (1, ugoto); \
2209 Field (tup_v, 0) = Val_int (pageno); \
2210 Field (tup_v, 1) = Val_int (p.y); \
2211 Field (ret_v, 0) = tup_v; \
2213 break; \
2215 case FZ_LINK_URI: \
2216 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2217 ret_v = caml_alloc_small (1, uuri); \
2218 Field (ret_v, 0) = str_v; \
2219 break; \
2221 case FZ_LINK_LAUNCH: \
2222 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2223 ret_v = caml_alloc_small (1, ulaunch); \
2224 Field (ret_v, 0) = str_v; \
2225 break; \
2227 case FZ_LINK_NAMED: \
2228 str_v = caml_copy_string (link->dest.ld.named.named); \
2229 ret_v = caml_alloc_small (1, unamed); \
2230 Field (ret_v, 0) = str_v; \
2231 break; \
2233 case FZ_LINK_GOTOR: \
2234 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2235 pageno = link->dest.ld.gotor.page; \
2236 tup_v = caml_alloc_tuple (2); \
2237 ret_v = caml_alloc_small (1, uremote); \
2238 Field (tup_v, 0) = str_v; \
2239 Field (tup_v, 1) = Val_int (pageno); \
2240 Field (ret_v, 0) = tup_v; \
2241 break; \
2243 default: \
2245 char buf[80]; \
2247 snprintf (buf, sizeof (buf), \
2248 "unhandled link kind %d", link->dest.kind); \
2249 str_v = caml_copy_string (buf); \
2250 ret_v = caml_alloc_small (1, uunexpected); \
2251 Field (ret_v, 0) = str_v; \
2253 break; \
2257 CAMLprim value ml_getlink (value ptr_v, value n_v)
2259 CAMLparam2 (ptr_v, n_v);
2260 CAMLlocal3 (ret_v, tup_v, str_v);
2261 fz_link *link;
2262 struct page *page;
2263 struct pagedim *pdim;
2264 char *s = String_val (ptr_v);
2266 ret_v = Val_int (0);
2267 page = parse_pointer ("ml_getlink", s);
2268 pdim = &state.pagedims[page->pdimno];
2269 link = page->slinks[Int_val (n_v)].link;
2270 LINKTOVAL;
2271 CAMLreturn (ret_v);
2274 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2276 CAMLparam3 (ptr_v, x_v, y_v);
2277 CAMLlocal3 (ret_v, tup_v, str_v);
2278 fz_link *link;
2279 struct page *page;
2280 char *s = String_val (ptr_v);
2281 int x = Int_val (x_v), y = Int_val (y_v);
2282 struct pagedim *pdim;
2284 ret_v = Val_int (0);
2285 if (trylock ("ml_whatsunder")) {
2286 goto done;
2289 page = parse_pointer ("ml_whatsunder", s);
2290 pdim = &state.pagedims[page->pdimno];
2291 link = getlink (page, x, y);
2292 if (link) {
2293 LINKTOVAL;
2295 else {
2296 int i;
2297 fz_text_span *span;
2299 ensuretext (page);
2300 for (span = page->text; span; span = span->next) {
2301 for (i = 0; i < span->len; ++i) {
2302 fz_bbox *b;
2303 b = &span->text[i].bbox;
2304 if ((x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)) {
2305 const char *n2 =
2306 span->font && span->font->name
2307 ? span->font->name
2308 : "Span has no font name"
2310 FT_FaceRec *face = span->font->ft_face;
2311 if (face && face->family_name) {
2312 char *s;
2313 char *n1 = face->family_name;
2314 size_t l1 = strlen (n1);
2315 size_t l2 = strlen (n2);
2317 if (l1 != l2 || memcmp (n1, n2, l1)) {
2318 s = malloc (l1 + l2 + 2);
2319 if (s) {
2320 memcpy (s, n2, l2);
2321 s[l2] = '=';
2322 memcpy (s + l2 + 1, n1, l1 + 1);
2323 str_v = caml_copy_string (s);
2324 free (s);
2328 if (str_v == 0) {
2329 str_v = caml_copy_string (n2);
2331 ret_v = caml_alloc_small (1, utext);
2332 Field (ret_v, 0) = str_v;
2333 goto unlock;
2338 unlock:
2339 unlock ("ml_whatsunder");
2341 done:
2342 CAMLreturn (ret_v);
2345 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2347 CAMLparam2 (ptr_v, rect_v);
2348 fz_bbox *b;
2349 struct page *page;
2350 fz_text_span *span;
2351 struct mark first, last;
2352 int i, x0, x1, y0, y1;
2353 char *s = String_val (ptr_v);
2355 if (trylock ("ml_seltext")) {
2356 goto done;
2359 page = parse_pointer ("ml_seltext", s);
2360 ensuretext (page);
2362 x0 = Int_val (Field (rect_v, 0));
2363 y0 = Int_val (Field (rect_v, 1));
2364 x1 = Int_val (Field (rect_v, 2));
2365 y1 = Int_val (Field (rect_v, 3));
2367 if (0) {
2368 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2369 glColor3ub (128, 128, 128);
2370 glRecti (x0, y0, x1, y1);
2371 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2374 first.span = NULL;
2375 last.span = NULL;
2377 last.i = first.i = 0;
2378 first.span = page->text;
2379 for (span = page->text; span; span = span->next) {
2380 for (i = 0; i < span->len; ++i) {
2381 b = &span->text[i].bbox;
2382 int selected = 0;
2384 if (x0 >= b->x0 && x0 <= b->x1 && y0 >= b->y0 && y0 <= b->y1) {
2385 first.i = i;
2386 first.span = span;
2387 selected = 1;
2389 if (x1 >= b->x0 && x1 <= b->x1 && y1 >= b->y0 && y1 <= b->y1) {
2390 last.i = i;
2391 last.span = span;
2392 selected = 1;
2394 if (0 && selected) {
2395 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2396 glColor3ub (128, 128, 128);
2397 glRecti (b->x0, b->y0, b->x1, b->y1);
2398 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2403 if (y1 < y0 || x1 < x0) {
2404 int swap = 0;
2406 if (first.span == last.span) {
2407 swap = 1;
2409 else {
2410 if (y1 < y0) {
2411 for (span = first.span; span && span != last.span;
2412 span = span->next) {
2413 if (span->eol) {
2414 swap = 1;
2415 break;
2421 if (swap) {
2422 i = first.i;
2423 span = first.span;
2424 first.i = last.i;
2425 first.span = last.span;
2426 last.i = i;
2427 last.span = span;
2431 page->fmark = first;
2432 page->lmark = last;
2434 unlock ("ml_seltext");
2436 done:
2437 CAMLreturn (Val_unit);
2440 static int pipespan (FILE *f, fz_text_span *span, int a, int b)
2442 char buf[4];
2443 int i, len, ret;
2445 for (i = a; i <= b; ++i) {
2446 len = runetochar (buf, &span->text[i].c);
2447 ret = fwrite (buf, len, 1, f);
2449 if (ret != 1) {
2450 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
2451 len, ret, strerror (errno));
2452 return -1;
2455 return 0;
2458 CAMLprim value ml_copysel (value command_v, value ptr_v)
2460 CAMLparam1 (ptr_v);
2461 FILE *f;
2462 struct page *page;
2463 fz_text_span *span;
2464 char *s = String_val (ptr_v);
2465 char *command = String_val (command_v);
2467 if (trylock ("ml_copysel")) {
2468 goto done;
2471 page = parse_pointer ("ml_sopysel", s);
2473 if (!page->fmark.span || !page->lmark.span) {
2474 fprintf (stderr, "nothing to copy\n");
2475 goto unlock;
2478 f = popen (command, "w");
2479 if (!f) {
2480 fprintf (stderr, "failed to open sel pipe: %s\n",
2481 strerror (errno));
2482 f = stdout;
2485 for (span = page->fmark.span;
2486 span && span != page->lmark.span->next;
2487 span = span->next) {
2488 int a = span == page->fmark.span ? page->fmark.i : 0;
2489 int b = span == page->lmark.span ? page->lmark.i : span->len - 1;
2490 if (pipespan (f, span, a, b)) {
2491 goto close;
2493 if (span->eol) {
2494 if (putc ('\n', f) == EOF) {
2495 fprintf (stderr, "failed break line on sel pipe: %s\n",
2496 strerror (errno));
2497 goto close;
2501 page->lmark.span = NULL;
2502 page->fmark.span = NULL;
2504 close:
2505 if (f != stdout) {
2506 int ret = pclose (f);
2507 if (ret == -1) {
2508 if (errno != ECHILD) {
2509 fprintf (stderr, "failed to close sel pipe: %s\n",
2510 strerror (errno));
2514 unlock:
2515 unlock ("ml_copysel");
2517 done:
2518 CAMLreturn (Val_unit);
2521 CAMLprim value ml_getpdimrect (value pagedimno_v)
2523 CAMLparam1 (pagedimno_v);
2524 CAMLlocal1 (ret_v);
2525 int pagedimno = Int_val (pagedimno_v);
2526 fz_rect box;
2528 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2529 if (trylock ("ml_getpdimrect")) {
2530 box = fz_empty_rect;
2532 else {
2533 box = state.pagedims[pagedimno].mediabox;
2534 unlock ("ml_getpdimrect");
2537 Store_double_field (ret_v, 0, box.x0);
2538 Store_double_field (ret_v, 1, box.x1);
2539 Store_double_field (ret_v, 2, box.y0);
2540 Store_double_field (ret_v, 3, box.y1);
2542 CAMLreturn (ret_v);
2545 static double getmaxw (void)
2547 int i;
2548 struct pagedim *p;
2549 double maxw = 0.0;
2551 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
2552 double x0, x1, w;
2554 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
2555 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
2557 w = x1 - x0;
2558 maxw = MAX (w, maxw);
2560 return maxw;
2563 CAMLprim value ml_getmaxw (value unit_v)
2565 CAMLparam1 (unit_v);
2566 CAMLlocal1 (ret_v);
2567 double maxw = 0.0;
2569 if (trylock ("ml_getmaxw")) {
2570 goto done;
2572 maxw = getmaxw ();
2573 unlock ("ml_getmaxw");
2574 done:
2575 ret_v = caml_copy_double (maxw);
2576 CAMLreturn (ret_v);
2579 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v, value dw_v)
2581 CAMLparam3 (winw_v, winh_v, dw_v);
2582 CAMLlocal1 (ret_v);
2583 int i;
2584 double zoom = 1.0;
2585 double maxw = 0.0, maxh = 0.0;
2586 struct pagedim *p;
2587 double winw = Int_val (winw_v);
2588 double winh = Int_val (winh_v);
2589 double dw = Int_val (dw_v);
2590 double pw = 1.0, ph = 1.0, num, den;
2592 if (trylock ("ml_zoom_for_height")) {
2593 goto done;
2596 if (state.proportional) {
2597 maxw = getmaxw ();
2600 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
2601 double x0, x1, y0, y1, w, h, scaledh, scale;
2603 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
2604 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
2605 y0 = MIN (p->mediabox.y0, p->mediabox.y1);
2606 y1 = MAX (p->mediabox.y0, p->mediabox.y1);
2608 w = x1 - x0;
2609 h = y1 - y0;
2611 if (state.proportional) {
2612 scale = w / maxw;
2613 scaledh = h * scale;
2615 else {
2616 scale = 1.0;
2617 scaledh = h;
2620 if (scaledh > maxh) {
2621 maxh = scaledh;
2622 ph = scaledh;
2623 pw = w * scale;
2627 num = (winh * pw) + (ph * dw);
2628 den = ph * winw;
2629 zoom = num / den;
2631 unlock ("ml_zoom_for_height");
2632 done:
2633 ret_v = caml_copy_double (zoom);
2634 CAMLreturn (ret_v);
2637 #include "glfont.c"
2639 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
2641 CAMLparam4 (pt_v, x_v, y_v, string_v);
2642 CAMLlocal1 (ret_v);
2643 int pt = Int_val(pt_v);
2644 int x = Int_val (x_v);
2645 int y = Int_val (y_v);
2646 double w;
2648 w = draw_string (state.face, pt, x, y, String_val (string_v));
2649 ret_v = caml_copy_double (w);
2650 CAMLreturn (ret_v);
2653 CAMLprim value ml_measure_string (value pt_v, value string_v)
2655 CAMLparam2 (pt_v, string_v);
2656 CAMLlocal1 (ret_v);
2657 int pt = Int_val (pt_v);
2658 double w;
2660 w = measure_string (state.face, pt, String_val (string_v));
2661 ret_v = caml_copy_double (w);
2662 CAMLreturn (ret_v);
2665 CAMLprim value ml_getpagebox (value opaque_v)
2667 CAMLparam1 (opaque_v);
2668 CAMLlocal1 (ret_v);
2669 fz_bbox bbox;
2670 fz_device *dev;
2671 char *s = String_val (opaque_v);
2672 struct page *page = parse_pointer ("ml_getpagebox", s);
2674 ret_v = caml_alloc_tuple (4);
2675 dev = fz_new_bbox_device (state.ctx, &bbox);
2676 dev->hints |= FZ_IGNORE_SHADE;
2678 switch (page->type) {
2679 case DPDF:
2680 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, pagectm (page), NULL);
2681 break;
2683 case DXPS:
2684 xps_run_page (state.u.xps, page->u.xpspage, dev, pagectm (page), NULL);
2685 break;
2687 default:
2688 bbox = fz_infinite_bbox;
2689 break;
2692 fz_free_device (dev);
2693 Field (ret_v, 0) = Val_int (bbox.x0);
2694 Field (ret_v, 1) = Val_int (bbox.y0);
2695 Field (ret_v, 2) = Val_int (bbox.x1);
2696 Field (ret_v, 3) = Val_int (bbox.y1);
2698 CAMLreturn (ret_v);
2701 CAMLprim value ml_setaalevel (value level_v)
2703 CAMLparam1 (level_v);
2705 state.aalevel = Int_val (level_v);
2706 CAMLreturn (Val_unit);
2709 #undef pixel
2710 #include <X11/Xlib.h>
2711 #include <GL/glx.h>
2713 static struct {
2714 Display *dpy;
2715 GLXContext ctx;
2716 GLXDrawable drawable;
2717 } glx;
2719 #include "keysym2ucs.c"
2721 CAMLprim value ml_keysymtoutf8 (value keysym_v)
2723 CAMLparam1 (keysym_v);
2724 CAMLlocal1 (str_v);
2725 KeySym keysym = Int_val (keysym_v);
2726 Rune rune;
2727 int len;
2728 char buf[5];
2730 rune = keysym2ucs (keysym);
2731 len = runetochar (buf, &rune);
2732 buf[len] = 0;
2733 str_v = caml_copy_string (buf);
2734 CAMLreturn (str_v);
2737 CAMLprim value ml_glx (value win_v)
2739 CAMLparam1 (win_v);
2740 int screen;
2741 XVisualInfo *visual;
2742 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
2744 glx.dpy = XOpenDisplay (NULL);
2745 if (!glx.dpy) {
2746 caml_failwith ("XOpenDisplay failed");
2749 screen = DefaultScreen (glx.dpy);
2750 visual = glXChooseVisual (glx.dpy, screen, attributes);
2751 if (!visual) {
2752 XCloseDisplay (glx.dpy);
2753 glx.dpy = NULL;
2754 caml_failwith ("glXChooseVisual");
2757 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
2758 if (!glx.ctx) {
2759 XCloseDisplay (glx.dpy);
2760 XFree (visual);
2761 glx.dpy = NULL;
2762 caml_failwith ("glXCreateContext");
2765 XFree (visual);
2766 if (!glXMakeCurrent (glx.dpy, Int_val (win_v), glx.ctx)) {
2767 glXDestroyContext (glx.dpy, glx.ctx);
2768 XCloseDisplay (glx.dpy);
2769 glx.dpy = NULL;
2770 glx.ctx = NULL;
2771 caml_failwith ("glXMakeCurrent");
2773 glx.drawable = Int_val (win_v);
2775 CAMLreturn (Val_unit);
2778 CAMLprim value ml_swapb (value unit_v)
2780 CAMLparam1 (unit_v);
2781 glXSwapBuffers (glx.dpy, glx.drawable);
2782 CAMLreturn (Val_unit);
2785 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
2786 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
2788 CAMLprim value ml_platform (value unit_v)
2790 CAMLparam1 (unit_v);
2791 int platid = piunknown;
2793 #if defined __linux__
2794 platid = pilinux;
2795 #elif defined __CYGWIN__
2796 platid = picygwin;
2797 #elif defined __DragonFly__
2798 platid = pidragonflybsd;
2799 #elif defined __FreeBSD__
2800 platid = pifreebsd;
2801 #elif defined __OpenBSD__
2802 platid = piopenbsd;
2803 #elif defined __NetBSD__
2804 platid = pinetbsd;
2805 #elif defined __sun__
2806 platid = pisun;
2807 #elif defined __APPLE__
2808 platid = piosx;
2809 #endif
2810 CAMLreturn (Val_int (platid));
2813 CAMLprim value ml_cloexec (value fd_v)
2815 CAMLparam1 (fd_v);
2816 int fd = Int_val (fd_v);
2818 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
2819 uerror ("fcntl", Nothing);
2821 CAMLreturn (Val_unit);
2824 CAMLprim value ml_init (value pipe_v, value params_v)
2826 CAMLparam2 (pipe_v, params_v);
2827 CAMLlocal2 (trim_v, fuzz_v);
2828 int ret;
2829 int texcount;
2830 char *fontpath;
2831 int colorspace;
2832 int mustoresize;
2833 struct sigaction sa;
2835 state.cr = Int_val (Field (pipe_v, 0));
2836 state.cw = Int_val (Field (pipe_v, 1));
2837 state.rotate = Int_val (Field (params_v, 0));
2838 state.proportional = Bool_val (Field (params_v, 1));
2839 trim_v = Field (params_v, 2);
2840 texcount = Int_val (Field (params_v, 3));
2841 state.sliceheight = Int_val (Field (params_v, 4));
2842 mustoresize = Int_val (Field (params_v, 5));
2843 colorspace = Int_val (Field (params_v, 6));
2844 fontpath = String_val (Field (params_v, 7));
2846 state.ctx = fz_new_context (NULL, NULL, mustoresize);
2847 state.trimmargins = Bool_val (Field (trim_v, 0));
2849 fuzz_v = Field (trim_v, 1);
2850 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
2851 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
2852 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
2853 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
2855 set_tex_params (colorspace);
2857 if (*fontpath) {
2858 state.face = load_font (fontpath);
2860 else {
2861 unsigned int len;
2862 void *base = pdf_find_substitute_font (0, 0, 0, 0, &len);
2864 state.face = load_builtin_font (base, len);
2866 if (!state.face) _exit (1);
2868 realloctexts (texcount);
2870 sa.sa_handler = SIG_DFL;
2871 if (sigemptyset (&sa.sa_mask)) {
2872 err (1, "sigemptyset");
2874 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
2875 if (sigaction (SIGCHLD, &sa, NULL)) {
2876 err (1, "sigaction");
2879 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
2880 if (ret) {
2881 errx (1, "pthread_create: %s", strerror (ret));
2884 CAMLreturn (Val_unit);