Remove band-aid
[llpp.git] / link.c
blob10a9ebab5ab423a73a49cf642056a872b2c1cdc5
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 if (state.rotate != rotate || state.proportional != proportional) {
1478 state.gen += 1;
1480 state.rotate = rotate;
1481 state.proportional = proportional;
1482 layout ();
1483 process_outline ();
1484 state.gen++;
1485 unlock ("reqlayout");
1486 printd ("continue %d", state.pagecount);
1488 else if (!strncmp ("page", p, 4)) {
1489 double a, b;
1490 struct page *page;
1491 int pageno, pindex, ret;
1493 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1494 if (ret != 2) {
1495 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1498 lock ("page");
1499 a = now ();
1500 page = loadpage (pageno, pindex);
1501 b = now ();
1502 unlock ("page");
1504 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1506 else if (!strncmp ("tile", p, 4)) {
1507 int x, y, w, h, ret;
1508 struct page *page;
1509 struct tile *tile;
1510 double a, b;
1512 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d",
1513 FMT_ptr_cast (&page), &x, &y, &w, &h);
1514 if (ret != 5) {
1515 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1518 lock ("tile");
1519 a = now ();
1520 tile = rendertile (page, x, y, w, h);
1521 b = now ();
1522 unlock ("tile");
1524 printd ("tile %d %d %" FMT_ptr " %u %f",
1525 x, y,
1526 FMT_ptr_cast2 (tile),
1527 tile->w * tile->h * tile->pixmap->n,
1528 b - a);
1530 else if (!strncmp ("settrim", p, 7)) {
1531 int trimmargins;
1532 fz_bbox fuzz;
1534 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1535 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1536 if (ret != 5) {
1537 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1539 printd ("clear");
1540 lock ("settrim");
1541 state.trimmargins = trimmargins;
1542 state.needoutline = 1;
1543 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1544 state.trimanew = 1;
1545 state.trimfuzz = fuzz;
1547 state.pagedimcount = 0;
1548 free (state.pagedims);
1549 state.pagedims = NULL;
1550 initpdims ();
1551 layout ();
1552 process_outline ();
1553 unlock ("settrim");
1554 printd ("continue %d", state.pagecount);
1556 else if (!strncmp ("sliceh", p, 6)) {
1557 int h;
1559 ret = sscanf (p + 6, " %d", &h);
1560 if (ret != 1) {
1561 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1563 if (h != state.sliceheight) {
1564 int i;
1566 state.sliceheight = h;
1567 for (i = 0; i < state.texcount; ++i) {
1568 state.texowners[i].w = -1;
1569 state.texowners[i].h = -1;
1570 state.texowners[i].slice = NULL;
1574 else if (!strncmp ("interrupt", p, 9)) {
1575 printd ("vmsg interrupted");
1577 else if (!strncmp ("quit", p, 4)) {
1578 return 0;
1580 else {
1581 errx (1, "unknown command %.*s", len, p);
1584 return 0;
1587 CAMLprim value ml_realloctexts (value texcount_v)
1589 CAMLparam1 (texcount_v);
1590 int ok;
1592 if (trylock ("ml_realloctexts")) {
1593 ok = 0;
1594 goto done;
1596 realloctexts (Int_val (texcount_v));
1597 ok = 1;
1598 unlock ("ml_realloctexts");
1600 done:
1601 CAMLreturn (Val_bool (ok));
1604 static void showsel (struct page *page, int ox, int oy)
1606 fz_bbox bbox;
1607 fz_text_span *span;
1608 struct mark first, last;
1610 first = page->fmark;
1611 last = page->lmark;
1613 if (!first.span || !last.span) return;
1615 glEnable (GL_BLEND);
1616 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1617 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1619 ox += state.pagedims[page->pdimno].bounds.x0;
1620 oy += state.pagedims[page->pdimno].bounds.y0;
1621 for (span = first.span; span; span = span->next) {
1622 int i, j, k;
1624 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1626 j = 0;
1627 k = span->len - 1;
1629 if (span == page->fmark.span && span == page->lmark.span) {
1630 j = MIN (first.i, last.i);
1631 k = MAX (first.i, last.i);
1633 else if (span == first.span) {
1634 j = first.i;
1636 else if (span == last.span) {
1637 k = last.i;
1640 for (i = j; i <= k; ++i) {
1641 bbox = fz_union_bbox (bbox, span->text[i].bbox);
1643 lprintf ("%d %d %d %d oy=%d ox=%d\n",
1644 bbox.x0,
1645 bbox.y0,
1646 bbox.x1,
1647 bbox.y1,
1648 oy, ox);
1650 glRecti (bbox.x0 + ox, bbox.y0 + oy, bbox.x1 + ox, bbox.y1 + oy);
1652 if (span == last.span) break;
1654 glDisable (GL_BLEND);
1657 static void highlightlinks (struct page *page, int xoff, int yoff)
1659 fz_matrix ctm;
1660 fz_link *link, *links;
1662 switch (page->type) {
1663 case DPDF:
1664 links = page->u.pdfpage->links;
1665 break;
1667 case DXPS:
1668 links = page->u.xpspage->links;
1669 break;
1671 default:
1672 return;
1675 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
1676 glEnable (GL_LINE_STIPPLE);
1677 glLineStipple (0.5, 0xcccc);
1679 xoff -= state.pagedims[page->pdimno].bounds.x0;
1680 yoff -= state.pagedims[page->pdimno].bounds.y0;
1681 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1683 glBegin (GL_QUADS);
1684 for (link = links; link; link = link->next) {
1685 fz_point p1, p2, p3, p4;
1687 p1.x = link->rect.x0;
1688 p1.y = link->rect.y0;
1690 p2.x = link->rect.x1;
1691 p2.y = link->rect.y0;
1693 p3.x = link->rect.x1;
1694 p3.y = link->rect.y1;
1696 p4.x = link->rect.x0;
1697 p4.y = link->rect.y1;
1699 p1 = fz_transform_point (ctm, p1);
1700 p2 = fz_transform_point (ctm, p2);
1701 p3 = fz_transform_point (ctm, p3);
1702 p4 = fz_transform_point (ctm, p4);
1704 switch (link->dest.kind) {
1705 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
1706 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
1707 default: glColor3ub (0, 0, 0); break;
1710 glVertex2f (p1.x, p1.y);
1711 glVertex2f (p2.x, p2.y);
1712 glVertex2f (p3.x, p3.y);
1713 glVertex2f (p4.x, p4.y);
1715 glEnd ();
1717 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1718 glDisable (GL_LINE_STIPPLE);
1721 static void uploadslice (struct tile *tile, struct slice *slice)
1723 int offset;
1724 struct slice *slice1;
1726 offset = 0;
1727 for (slice1 = tile->slices; slice != slice1; slice1++) {
1728 offset += slice1->h * tile->w * tile->pixmap->n;
1730 if (slice->texindex != -1 && slice->texindex < state.texcount
1731 && state.texowners[slice->texindex].slice == slice) {
1732 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
1734 else {
1735 int subimage = 0;
1736 int texindex = state.texindex++ % state.texcount;
1738 if (state.texowners[texindex].w == tile->w) {
1739 if (state.texowners[texindex].h >= slice->h) {
1740 subimage = 1;
1742 else {
1743 state.texowners[texindex].h = slice->h;
1746 else {
1747 state.texowners[texindex].h = slice->h;
1750 state.texowners[texindex].w = tile->w;
1751 state.texowners[texindex].slice = slice;
1752 slice->texindex = texindex;
1754 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
1755 if (subimage) {
1756 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
1760 tile->w,
1761 slice->h,
1762 state.texform,
1763 state.texty,
1764 tile->pixmap->samples+offset
1767 else {
1768 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
1770 state.texiform,
1771 tile->w,
1772 slice->h,
1774 state.texform,
1775 state.texty,
1776 tile->pixmap->samples+offset
1782 CAMLprim value ml_drawtile (value args_v, value ptr_v)
1784 CAMLparam2 (args_v, ptr_v);
1785 int dispx = Int_val (Field (args_v, 0));
1786 int dispy = Int_val (Field (args_v, 1));
1787 int dispw = Int_val (Field (args_v, 2));
1788 int disph = Int_val (Field (args_v, 3));
1789 int tilex = Int_val (Field (args_v, 4));
1790 int tiley = Int_val (Field (args_v, 5));
1791 char *s = String_val (ptr_v);
1792 struct tile *tile = parse_pointer ("ml_drawtile", s);
1794 glEnable (GL_TEXTURE_RECTANGLE_ARB);
1796 int slicey, firstslice;
1797 struct slice *slice;
1799 firstslice = tiley / tile->sliceheight;
1800 slice = &tile->slices[firstslice];
1801 slicey = tiley % tile->sliceheight;
1803 while (disph > 0) {
1804 int dh;
1806 dh = slice->h - slicey;
1807 dh = MIN (disph, dh);
1808 uploadslice (tile, slice);
1810 glBegin (GL_QUADS);
1812 glTexCoord2i (tilex, slicey);
1813 glVertex2i (dispx, dispy);
1815 glTexCoord2i (tilex+dispw, slicey);
1816 glVertex2i (dispx+dispw, dispy);
1818 glTexCoord2i (tilex+dispw, slicey+dh);
1819 glVertex2i (dispx+dispw, dispy+dh);
1821 glTexCoord2i (tilex, slicey+dh);
1822 glVertex2i (dispx, dispy+dh);
1824 glEnd ();
1826 dispy += dh;
1827 disph -= dh;
1828 slice++;
1829 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
1830 slicey = 0;
1833 glDisable (GL_TEXTURE_RECTANGLE_ARB);
1834 CAMLreturn (Val_unit);
1837 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
1838 value xoff_v, value yoff_v)
1840 CAMLparam4 (ptr_v, hlinks_v, xoff_v, yoff_v);
1841 int xoff = Int_val (xoff_v);
1842 int yoff = Int_val (yoff_v);
1843 char *s = String_val (ptr_v);
1844 struct page *page = parse_pointer ("ml_postprocess", s);
1846 if (Bool_val (hlinks_v)) highlightlinks (page, xoff, yoff);
1848 if (trylock ("ml_postprocess")) {
1849 goto done;
1851 showsel (page, xoff, yoff);
1852 unlock ("ml_postprocess");
1854 done:
1855 CAMLreturn (Val_unit);
1858 static fz_link *getlink (struct page *page, int x, int y)
1860 fz_point p;
1861 fz_matrix ctm;
1862 fz_link *link, *links;
1864 switch (page->type) {
1865 case DPDF:
1866 ctm = trimctm (page->u.pdfpage, page->pdimno);
1867 links = page->u.pdfpage->links;
1868 break;
1870 case DXPS:
1871 ctm = fz_identity;
1872 links = page->u.xpspage->links;
1873 break;
1875 default:
1876 return NULL;
1878 p.x = x;
1879 p.y = y;
1881 ctm = fz_concat (ctm, state.pagedims[page->pdimno].ctm);
1882 ctm = fz_invert_matrix (ctm);
1883 p = fz_transform_point (ctm, p);
1885 for (link = links; link; link = link->next) {
1886 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
1887 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
1888 return link;
1892 return NULL;
1895 static void droptext (struct page *page)
1897 if (page->text) {
1898 fz_free_text_span (state.ctx, page->text);
1899 page->fmark.i = -1;
1900 page->lmark.i = -1;
1901 page->fmark.span = NULL;
1902 page->lmark.span = NULL;
1903 page->text = NULL;
1907 static void ensuretext (struct page *page)
1909 if (state.gen != page->gen) {
1910 droptext (page);
1911 page->gen = state.gen;
1913 if (!page->text) {
1914 fz_device *tdev;
1916 page->text = fz_new_text_span (state.ctx);
1917 tdev = fz_new_text_device (state.ctx, page->text);
1918 fz_run_display_list (page->dlist,
1919 tdev,
1920 pagectm (page),
1921 fz_infinite_bbox, NULL);
1922 fz_free_device (tdev);
1926 static int compareslinks (const void *l, const void *r)
1928 struct slink const *ls = l;
1929 struct slink const *rs = r;
1930 if (ls->bbox.y0 == rs->bbox.y0) {
1931 return rs->bbox.x0 - rs->bbox.x0;
1933 return ls->bbox.y0 - rs->bbox.y0;
1936 static void ensureslinks (struct page *page)
1938 fz_matrix ctm;
1939 int i, count = 0;
1940 size_t slinksize = sizeof (*page->slinks);
1941 fz_link *link, *links;
1943 if (page->slinks) return;
1945 switch (page->type) {
1946 case DPDF:
1947 links = page->u.pdfpage->links;
1948 ctm = fz_concat (trimctm (page->u.pdfpage, page->pdimno),
1949 state.pagedims[page->pdimno].ctm);
1950 break;
1952 case DXPS:
1953 links = page->u.xpspage->links;
1954 ctm = state.pagedims[page->pdimno].ctm;
1955 break;
1957 default:
1958 return;
1961 for (link = links; link; link = link->next) {
1962 count++;
1964 if (count > 0) {
1965 page->slinkcount = count;
1966 page->slinks = calloc (count, slinksize);
1967 if (!page->slinks) {
1968 err (1, "realloc slinks %d", count);
1971 for (i = 0, link = links; link; ++i, link = link->next) {
1972 page->slinks[i].link = link;
1973 page->slinks[i].bbox =
1974 fz_round_rect (fz_transform_rect (ctm, link->rect));
1976 qsort (page->slinks, count, slinksize, compareslinks);
1980 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
1982 CAMLparam2 (start_page_v, dir_v);
1983 CAMLlocal1 (ret_v);
1984 int i, dir = Int_val (dir_v);
1985 int start_page = Int_val (start_page_v);
1986 int end_page = dir > 0 ? state.pagecount : -1;
1988 ret_v = Val_int (0);
1989 if (!(state.type == DPDF || state.type == DXPS)) {
1990 goto done;
1993 lock ("ml_findpage_with_links");
1994 for (i = start_page + dir; i != end_page; i += dir) {
1995 int found;
1997 switch (state.type) {
1998 case DPDF:
2000 pdf_page *page = pdf_load_page (state.u.pdf, i);
2001 found = !!page->links;
2002 freepdfpage (page);
2004 break;
2005 case DXPS:
2007 xps_page *page = xps_load_page (state.u.xps, i);
2008 found = !!page->links;
2009 freexpspage (page);
2011 break;
2013 default:
2014 ARSERT ("invalid document type");
2017 if (found) {
2018 ret_v = caml_alloc_small (1, 1);
2019 Field (ret_v, 0) = Val_int (i);
2020 goto unlock;
2023 unlock:
2024 unlock ("ml_findpage_with_links");
2026 done:
2027 CAMLreturn (ret_v);
2030 enum { dir_first, dir_last};
2031 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2033 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2035 CAMLparam2 (ptr_v, dir_v);
2036 CAMLlocal3 (ret_v, tup_v, pos_v);
2037 struct page *page;
2038 int dirtag, i, slinkindex;
2039 struct slink *found = NULL ,*slink;
2040 char *s = String_val (ptr_v);
2042 page = parse_pointer ("ml_findlink", s);
2043 ensureslinks (page);
2045 ret_v = Val_int (0);
2046 if (Is_block (dir_v)) {
2047 dirtag = Tag_val (dir_v);
2048 switch (dirtag) {
2049 case dir_first_visible:
2051 int x0, y0, dir, first_index, last_index;
2053 pos_v = Field (dir_v, 0);
2054 x0 = Int_val (Field (pos_v, 0));
2055 y0 = Int_val (Field (pos_v, 1));
2056 dir = Int_val (Field (pos_v, 2));
2058 if (dir >= 0) {
2059 dir = 1;
2060 first_index = 0;
2061 last_index = page->slinkcount;
2063 else {
2064 first_index = page->slinkcount - 1;
2065 last_index = -1;
2068 for (i = first_index; i != last_index; i += dir) {
2069 slink = &page->slinks[i];
2070 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2071 found = slink;
2072 break;
2076 break;
2078 case dir_left:
2079 slinkindex = Int_val (Field (dir_v, 0));
2080 found = &page->slinks[slinkindex];
2081 for (i = slinkindex - 1; i >= 0; --i) {
2082 slink = &page->slinks[i];
2083 if (slink->bbox.x0 < found->bbox.x0) {
2084 found = slink;
2085 break;
2088 break;
2090 case dir_right:
2091 slinkindex = Int_val (Field (dir_v, 0));
2092 found = &page->slinks[slinkindex];
2093 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2094 slink = &page->slinks[i];
2095 if (slink->bbox.x0 > found->bbox.x0) {
2096 found = slink;
2097 break;
2100 break;
2102 case dir_down:
2103 slinkindex = Int_val (Field (dir_v, 0));
2104 found = &page->slinks[slinkindex];
2105 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2106 slink = &page->slinks[i];
2107 if (slink->bbox.y0 >= found->bbox.y0) {
2108 found = slink;
2109 break;
2112 break;
2114 case dir_up:
2115 slinkindex = Int_val (Field (dir_v, 0));
2116 found = &page->slinks[slinkindex];
2117 for (i = slinkindex - 1; i >= 0; --i) {
2118 slink = &page->slinks[i];
2119 if (slink->bbox.y0 <= found->bbox.y0) {
2120 found = slink;
2121 break;
2124 break;
2127 else {
2128 dirtag = Int_val (dir_v);
2129 switch (dirtag) {
2130 case dir_first:
2131 found = page->slinks;
2132 break;
2134 case dir_last:
2135 if (page->slinks) {
2136 found = page->slinks + (page->slinkcount - 1);
2138 break;
2141 if (found) {
2142 tup_v = caml_alloc_tuple (5);
2143 ret_v = caml_alloc_small (2, 1);
2144 Field (tup_v, 0) = Val_int (found - page->slinks);
2145 Field (tup_v, 1) = Val_int (found->bbox.x0);
2146 Field (tup_v, 2) = Val_int (found->bbox.y0);
2147 Field (tup_v, 3) = Val_int (found->bbox.x1);
2148 Field (tup_v, 4) = Val_int (found->bbox.y1);
2149 Field (ret_v, 0) = tup_v;
2152 CAMLreturn (ret_v);
2155 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2157 #define LINKTOVAL \
2159 int pageno; \
2161 switch (link->dest.kind) { \
2162 case FZ_LINK_GOTO: \
2164 fz_point p; \
2166 pageno = link->dest.ld.gotor.page; \
2167 p.x = 0; \
2168 p.y = 0; \
2170 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2171 p.y = link->dest.ld.gotor.lt.y; \
2172 p = fz_transform_point (pdim->lctm, p); \
2174 tup_v = caml_alloc_tuple (2); \
2175 ret_v = caml_alloc_small (1, ugoto); \
2176 Field (tup_v, 0) = Val_int (pageno); \
2177 Field (tup_v, 1) = Val_int (p.y); \
2178 Field (ret_v, 0) = tup_v; \
2180 break; \
2182 case FZ_LINK_URI: \
2183 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2184 ret_v = caml_alloc_small (1, uuri); \
2185 Field (ret_v, 0) = str_v; \
2186 break; \
2188 case FZ_LINK_LAUNCH: \
2189 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2190 ret_v = caml_alloc_small (1, ulaunch); \
2191 Field (ret_v, 0) = str_v; \
2192 break; \
2194 case FZ_LINK_NAMED: \
2195 str_v = caml_copy_string (link->dest.ld.named.named); \
2196 ret_v = caml_alloc_small (1, unamed); \
2197 Field (ret_v, 0) = str_v; \
2198 break; \
2200 case FZ_LINK_GOTOR: \
2201 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2202 pageno = link->dest.ld.gotor.page; \
2203 tup_v = caml_alloc_tuple (2); \
2204 ret_v = caml_alloc_small (1, uremote); \
2205 Field (tup_v, 0) = str_v; \
2206 Field (tup_v, 1) = Val_int (pageno); \
2207 Field (ret_v, 0) = tup_v; \
2208 break; \
2210 default: \
2212 char buf[80]; \
2214 snprintf (buf, sizeof (buf), \
2215 "unhandled link kind %d", link->dest.kind); \
2216 str_v = caml_copy_string (buf); \
2217 ret_v = caml_alloc_small (1, uunexpected); \
2218 Field (ret_v, 0) = str_v; \
2220 break; \
2224 CAMLprim value ml_getlink (value ptr_v, value n_v)
2226 CAMLparam2 (ptr_v, n_v);
2227 CAMLlocal3 (ret_v, tup_v, str_v);
2228 fz_link *link;
2229 struct page *page;
2230 struct pagedim *pdim;
2231 char *s = String_val (ptr_v);
2233 ret_v = Val_int (0);
2234 page = parse_pointer ("ml_getlink", s);
2235 pdim = &state.pagedims[page->pdimno];
2236 link = page->slinks[Int_val (n_v)].link;
2237 LINKTOVAL;
2238 CAMLreturn (ret_v);
2241 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2243 CAMLparam3 (ptr_v, x_v, y_v);
2244 CAMLlocal3 (ret_v, tup_v, str_v);
2245 fz_link *link;
2246 struct page *page;
2247 char *s = String_val (ptr_v);
2248 int x = Int_val (x_v), y = Int_val (y_v);
2249 struct pagedim *pdim;
2251 ret_v = Val_int (0);
2252 if (trylock ("ml_whatsunder")) {
2253 goto done;
2256 page = parse_pointer ("ml_whatsunder", s);
2257 pdim = &state.pagedims[page->pdimno];
2258 x += pdim->bounds.x0;
2259 y += pdim->bounds.y0;
2260 link = getlink (page, x, y);
2261 if (link) {
2262 LINKTOVAL;
2264 else {
2265 int i;
2266 fz_text_span *span;
2268 ensuretext (page);
2269 for (span = page->text; span; span = span->next) {
2270 for (i = 0; i < span->len; ++i) {
2271 fz_bbox *b;
2272 b = &span->text[i].bbox;
2273 if ((x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)) {
2274 const char *n2 =
2275 span->font && span->font->name
2276 ? span->font->name
2277 : "Span has no font name"
2279 FT_FaceRec *face = span->font->ft_face;
2280 if (face && face->family_name) {
2281 char *s;
2282 char *n1 = face->family_name;
2283 size_t l1 = strlen (n1);
2284 size_t l2 = strlen (n2);
2286 if (l1 != l2 || memcmp (n1, n2, l1)) {
2287 s = malloc (l1 + l2 + 2);
2288 if (s) {
2289 memcpy (s, n2, l2);
2290 s[l2] = '=';
2291 memcpy (s + l2 + 1, n1, l1 + 1);
2292 str_v = caml_copy_string (s);
2293 free (s);
2297 if (str_v == 0) {
2298 str_v = caml_copy_string (n2);
2300 ret_v = caml_alloc_small (1, utext);
2301 Field (ret_v, 0) = str_v;
2302 goto unlock;
2307 unlock:
2308 unlock ("ml_whatsunder");
2310 done:
2311 CAMLreturn (ret_v);
2314 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2316 CAMLparam2 (ptr_v, rect_v);
2317 fz_bbox *b;
2318 struct page *page;
2319 fz_text_span *span;
2320 struct mark first, last;
2321 struct pagedim *pdim;
2322 int i, x0, x1, y0, y1;
2323 char *s = String_val (ptr_v);
2325 if (trylock ("ml_seltext")) {
2326 goto done;
2329 page = parse_pointer ("ml_seltext", s);
2330 ensuretext (page);
2332 pdim = &state.pagedims[page->pdimno];
2333 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2334 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2335 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2336 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2338 if (0) {
2339 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2340 glColor3ub (128, 128, 128);
2341 glRecti (x0, y0, x1, y1);
2342 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2345 first.span = NULL;
2346 last.span = NULL;
2348 last.i = first.i = 0;
2349 first.span = page->text;
2350 for (span = page->text; span; span = span->next) {
2351 for (i = 0; i < span->len; ++i) {
2352 b = &span->text[i].bbox;
2353 int selected = 0;
2355 if (x0 >= b->x0 && x0 <= b->x1 && y0 >= b->y0 && y0 <= b->y1) {
2356 first.i = i;
2357 first.span = span;
2358 selected = 1;
2360 if (x1 >= b->x0 && x1 <= b->x1 && y1 >= b->y0 && y1 <= b->y1) {
2361 last.i = i;
2362 last.span = span;
2363 selected = 1;
2365 if (0 && selected) {
2366 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2367 glColor3ub (128, 128, 128);
2368 glRecti (b->x0, b->y0, b->x1, b->y1);
2369 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2374 if (y1 < y0 || x1 < x0) {
2375 int swap = 0;
2377 if (first.span == last.span) {
2378 swap = 1;
2380 else {
2381 if (y1 < y0) {
2382 for (span = first.span; span && span != last.span;
2383 span = span->next) {
2384 if (span->eol) {
2385 swap = 1;
2386 break;
2392 if (swap) {
2393 i = first.i;
2394 span = first.span;
2395 first.i = last.i;
2396 first.span = last.span;
2397 last.i = i;
2398 last.span = span;
2402 page->fmark = first;
2403 page->lmark = last;
2405 unlock ("ml_seltext");
2407 done:
2408 CAMLreturn (Val_unit);
2411 static int pipespan (FILE *f, fz_text_span *span, int a, int b)
2413 char buf[4];
2414 int i, len, ret;
2416 for (i = a; i <= b; ++i) {
2417 len = runetochar (buf, &span->text[i].c);
2418 ret = fwrite (buf, len, 1, f);
2420 if (ret != 1) {
2421 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
2422 len, ret, strerror (errno));
2423 return -1;
2426 return 0;
2429 CAMLprim value ml_copysel (value command_v, value ptr_v)
2431 CAMLparam1 (ptr_v);
2432 FILE *f;
2433 struct page *page;
2434 fz_text_span *span;
2435 char *s = String_val (ptr_v);
2436 char *command = String_val (command_v);
2438 if (trylock ("ml_copysel")) {
2439 goto done;
2442 page = parse_pointer ("ml_sopysel", s);
2444 if (!page->fmark.span || !page->lmark.span) {
2445 fprintf (stderr, "nothing to copy\n");
2446 goto unlock;
2449 f = popen (command, "w");
2450 if (!f) {
2451 fprintf (stderr, "failed to open sel pipe: %s\n",
2452 strerror (errno));
2453 f = stdout;
2456 for (span = page->fmark.span;
2457 span && span != page->lmark.span->next;
2458 span = span->next) {
2459 int a = span == page->fmark.span ? page->fmark.i : 0;
2460 int b = span == page->lmark.span ? page->lmark.i : span->len - 1;
2461 if (pipespan (f, span, a, b)) {
2462 goto close;
2464 if (span->eol) {
2465 if (putc ('\n', f) == EOF) {
2466 fprintf (stderr, "failed break line on sel pipe: %s\n",
2467 strerror (errno));
2468 goto close;
2472 page->lmark.span = NULL;
2473 page->fmark.span = NULL;
2475 close:
2476 if (f != stdout) {
2477 int ret = pclose (f);
2478 if (ret == -1) {
2479 if (errno != ECHILD) {
2480 fprintf (stderr, "failed to close sel pipe: %s\n",
2481 strerror (errno));
2485 unlock:
2486 unlock ("ml_copysel");
2488 done:
2489 CAMLreturn (Val_unit);
2492 CAMLprim value ml_getpdimrect (value pagedimno_v)
2494 CAMLparam1 (pagedimno_v);
2495 CAMLlocal1 (ret_v);
2496 int pagedimno = Int_val (pagedimno_v);
2497 fz_rect box;
2499 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2500 if (trylock ("ml_getpdimrect")) {
2501 box = fz_empty_rect;
2503 else {
2504 box = state.pagedims[pagedimno].mediabox;
2505 unlock ("ml_getpdimrect");
2508 Store_double_field (ret_v, 0, box.x0);
2509 Store_double_field (ret_v, 1, box.x1);
2510 Store_double_field (ret_v, 2, box.y0);
2511 Store_double_field (ret_v, 3, box.y1);
2513 CAMLreturn (ret_v);
2516 static double getmaxw (void)
2518 int i;
2519 struct pagedim *p;
2520 double maxw = 0.0;
2522 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
2523 double x0, x1, w;
2525 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
2526 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
2528 w = x1 - x0;
2529 maxw = MAX (w, maxw);
2531 return maxw;
2534 CAMLprim value ml_getmaxw (value unit_v)
2536 CAMLparam1 (unit_v);
2537 CAMLlocal1 (ret_v);
2538 double maxw = 0.0;
2540 if (trylock ("ml_getmaxw")) {
2541 goto done;
2543 maxw = getmaxw ();
2544 unlock ("ml_getmaxw");
2545 done:
2546 ret_v = caml_copy_double (maxw);
2547 CAMLreturn (ret_v);
2550 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v, value dw_v)
2552 CAMLparam3 (winw_v, winh_v, dw_v);
2553 CAMLlocal1 (ret_v);
2554 int i;
2555 double zoom = 1.0;
2556 double maxw = 0.0, maxh = 0.0;
2557 struct pagedim *p;
2558 double winw = Int_val (winw_v);
2559 double winh = Int_val (winh_v);
2560 double dw = Int_val (dw_v);
2561 double pw = 1.0, ph = 1.0, num, den;
2563 if (trylock ("ml_zoom_for_height")) {
2564 goto done;
2567 if (state.proportional) {
2568 maxw = getmaxw ();
2571 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
2572 double x0, x1, y0, y1, w, h, scaledh, scale;
2574 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
2575 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
2576 y0 = MIN (p->mediabox.y0, p->mediabox.y1);
2577 y1 = MAX (p->mediabox.y0, p->mediabox.y1);
2579 w = x1 - x0;
2580 h = y1 - y0;
2582 if (state.proportional) {
2583 scale = w / maxw;
2584 scaledh = h * scale;
2586 else {
2587 scale = 1.0;
2588 scaledh = h;
2591 if (scaledh > maxh) {
2592 maxh = scaledh;
2593 ph = scaledh;
2594 pw = w * scale;
2598 num = (winh * pw) + (ph * dw);
2599 den = ph * winw;
2600 zoom = num / den;
2602 unlock ("ml_zoom_for_height");
2603 done:
2604 ret_v = caml_copy_double (zoom);
2605 CAMLreturn (ret_v);
2608 #include "glfont.c"
2610 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
2612 CAMLparam4 (pt_v, x_v, y_v, string_v);
2613 CAMLlocal1 (ret_v);
2614 int pt = Int_val(pt_v);
2615 int x = Int_val (x_v);
2616 int y = Int_val (y_v);
2617 double w;
2619 w = draw_string (state.face, pt, x, y, String_val (string_v));
2620 ret_v = caml_copy_double (w);
2621 CAMLreturn (ret_v);
2624 CAMLprim value ml_measure_string (value pt_v, value string_v)
2626 CAMLparam2 (pt_v, string_v);
2627 CAMLlocal1 (ret_v);
2628 int pt = Int_val (pt_v);
2629 double w;
2631 w = measure_string (state.face, pt, String_val (string_v));
2632 ret_v = caml_copy_double (w);
2633 CAMLreturn (ret_v);
2636 CAMLprim value ml_getpagebox (value opaque_v)
2638 CAMLparam1 (opaque_v);
2639 CAMLlocal1 (ret_v);
2640 fz_bbox bbox;
2641 fz_device *dev;
2642 char *s = String_val (opaque_v);
2643 struct page *page = parse_pointer ("ml_getpagebox", s);
2645 ret_v = caml_alloc_tuple (4);
2646 dev = fz_new_bbox_device (state.ctx, &bbox);
2647 dev->hints |= FZ_IGNORE_SHADE;
2649 switch (page->type) {
2650 case DPDF:
2651 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, pagectm (page), NULL);
2652 break;
2654 case DXPS:
2655 xps_run_page (state.u.xps, page->u.xpspage, dev, pagectm (page), NULL);
2656 break;
2658 default:
2659 bbox = fz_infinite_bbox;
2660 break;
2663 fz_free_device (dev);
2664 Field (ret_v, 0) = Val_int (bbox.x0);
2665 Field (ret_v, 1) = Val_int (bbox.y0);
2666 Field (ret_v, 2) = Val_int (bbox.x1);
2667 Field (ret_v, 3) = Val_int (bbox.y1);
2669 CAMLreturn (ret_v);
2672 CAMLprim value ml_setaalevel (value level_v)
2674 CAMLparam1 (level_v);
2676 state.aalevel = Int_val (level_v);
2677 CAMLreturn (Val_unit);
2680 #undef pixel
2681 #include <X11/Xlib.h>
2682 #include <GL/glx.h>
2684 static struct {
2685 Display *dpy;
2686 GLXContext ctx;
2687 GLXDrawable drawable;
2688 } glx;
2690 #include "keysym2ucs.c"
2692 CAMLprim value ml_keysymtoutf8 (value keysym_v)
2694 CAMLparam1 (keysym_v);
2695 CAMLlocal1 (str_v);
2696 KeySym keysym = Int_val (keysym_v);
2697 Rune rune;
2698 int len;
2699 char buf[5];
2701 rune = keysym2ucs (keysym);
2702 len = runetochar (buf, &rune);
2703 buf[len] = 0;
2704 str_v = caml_copy_string (buf);
2705 CAMLreturn (str_v);
2708 CAMLprim value ml_glx (value win_v)
2710 CAMLparam1 (win_v);
2711 int screen;
2712 XVisualInfo *visual;
2713 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
2715 glx.dpy = XOpenDisplay (NULL);
2716 if (!glx.dpy) {
2717 caml_failwith ("XOpenDisplay failed");
2720 screen = DefaultScreen (glx.dpy);
2721 visual = glXChooseVisual (glx.dpy, screen, attributes);
2722 if (!visual) {
2723 XCloseDisplay (glx.dpy);
2724 glx.dpy = NULL;
2725 caml_failwith ("glXChooseVisual");
2728 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
2729 if (!glx.ctx) {
2730 XCloseDisplay (glx.dpy);
2731 XFree (visual);
2732 glx.dpy = NULL;
2733 caml_failwith ("glXCreateContext");
2736 XFree (visual);
2737 if (!glXMakeCurrent (glx.dpy, Int_val (win_v), glx.ctx)) {
2738 glXDestroyContext (glx.dpy, glx.ctx);
2739 XCloseDisplay (glx.dpy);
2740 glx.dpy = NULL;
2741 glx.ctx = NULL;
2742 caml_failwith ("glXMakeCurrent");
2744 glx.drawable = Int_val (win_v);
2746 CAMLreturn (Val_unit);
2749 CAMLprim value ml_swapb (value unit_v)
2751 CAMLparam1 (unit_v);
2752 glXSwapBuffers (glx.dpy, glx.drawable);
2753 CAMLreturn (Val_unit);
2756 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
2757 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
2759 CAMLprim value ml_platform (value unit_v)
2761 CAMLparam1 (unit_v);
2762 int platid = piunknown;
2764 #if defined __linux__
2765 platid = pilinux;
2766 #elif defined __CYGWIN__
2767 platid = picygwin;
2768 #elif defined __DragonFly__
2769 platid = pidragonflybsd;
2770 #elif defined __FreeBSD__
2771 platid = pifreebsd;
2772 #elif defined __OpenBSD__
2773 platid = piopenbsd;
2774 #elif defined __NetBSD__
2775 platid = pinetbsd;
2776 #elif defined __sun__
2777 platid = pisun;
2778 #elif defined __APPLE__
2779 platid = piosx;
2780 #endif
2781 CAMLreturn (Val_int (platid));
2784 CAMLprim value ml_cloexec (value fd_v)
2786 CAMLparam1 (fd_v);
2787 int fd = Int_val (fd_v);
2789 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
2790 uerror ("fcntl", Nothing);
2792 CAMLreturn (Val_unit);
2795 CAMLprim value ml_init (value pipe_v, value params_v)
2797 CAMLparam2 (pipe_v, params_v);
2798 CAMLlocal2 (trim_v, fuzz_v);
2799 int ret;
2800 int texcount;
2801 char *fontpath;
2802 int colorspace;
2803 int mustoresize;
2804 struct sigaction sa;
2806 state.cr = Int_val (Field (pipe_v, 0));
2807 state.cw = Int_val (Field (pipe_v, 1));
2808 state.rotate = Int_val (Field (params_v, 0));
2809 state.proportional = Bool_val (Field (params_v, 1));
2810 trim_v = Field (params_v, 2);
2811 texcount = Int_val (Field (params_v, 3));
2812 state.sliceheight = Int_val (Field (params_v, 4));
2813 mustoresize = Int_val (Field (params_v, 5));
2814 colorspace = Int_val (Field (params_v, 6));
2815 fontpath = String_val (Field (params_v, 7));
2817 state.ctx = fz_new_context (NULL, NULL, mustoresize);
2818 state.trimmargins = Bool_val (Field (trim_v, 0));
2820 fuzz_v = Field (trim_v, 1);
2821 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
2822 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
2823 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
2824 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
2826 set_tex_params (colorspace);
2828 if (*fontpath) {
2829 state.face = load_font (fontpath);
2831 else {
2832 unsigned int len;
2833 void *base = pdf_find_substitute_font (0, 0, 0, 0, &len);
2835 state.face = load_builtin_font (base, len);
2837 if (!state.face) _exit (1);
2839 realloctexts (texcount);
2841 sa.sa_handler = SIG_DFL;
2842 if (sigemptyset (&sa.sa_mask)) {
2843 err (1, "sigemptyset");
2845 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
2846 if (sigaction (SIGCHLD, &sa, NULL)) {
2847 err (1, "sigaction");
2850 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
2851 if (ret) {
2852 errx (1, "pthread_create: %s", strerror (ret));
2855 CAMLreturn (Val_unit);