Cheap and dirty way to avoid text stomping over scroll area
[llpp.git] / link.c
blob2465ed674d53bde8b290f4f002b058f8e688f46b
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 unlock ("reqlayout");
1484 printd ("continue %d", state.pagecount);
1486 else if (!strncmp ("page", p, 4)) {
1487 double a, b;
1488 struct page *page;
1489 int pageno, pindex, ret;
1491 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1492 if (ret != 2) {
1493 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1496 lock ("page");
1497 a = now ();
1498 page = loadpage (pageno, pindex);
1499 b = now ();
1500 unlock ("page");
1502 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1504 else if (!strncmp ("tile", p, 4)) {
1505 int x, y, w, h, ret;
1506 struct page *page;
1507 struct tile *tile;
1508 double a, b;
1510 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d",
1511 FMT_ptr_cast (&page), &x, &y, &w, &h);
1512 if (ret != 5) {
1513 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1516 lock ("tile");
1517 a = now ();
1518 tile = rendertile (page, x, y, w, h);
1519 b = now ();
1520 unlock ("tile");
1522 printd ("tile %d %d %" FMT_ptr " %u %f",
1523 x, y,
1524 FMT_ptr_cast2 (tile),
1525 tile->w * tile->h * tile->pixmap->n,
1526 b - a);
1528 else if (!strncmp ("settrim", p, 7)) {
1529 int trimmargins;
1530 fz_bbox fuzz;
1532 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1533 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1534 if (ret != 5) {
1535 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1537 printd ("clear");
1538 lock ("settrim");
1539 state.trimmargins = trimmargins;
1540 state.needoutline = 1;
1541 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1542 state.trimanew = 1;
1543 state.trimfuzz = fuzz;
1545 state.pagedimcount = 0;
1546 free (state.pagedims);
1547 state.pagedims = NULL;
1548 initpdims ();
1549 layout ();
1550 process_outline ();
1551 unlock ("settrim");
1552 printd ("continue %d", state.pagecount);
1554 else if (!strncmp ("sliceh", p, 6)) {
1555 int h;
1557 ret = sscanf (p + 6, " %d", &h);
1558 if (ret != 1) {
1559 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1561 if (h != state.sliceheight) {
1562 int i;
1564 state.sliceheight = h;
1565 for (i = 0; i < state.texcount; ++i) {
1566 state.texowners[i].w = -1;
1567 state.texowners[i].h = -1;
1568 state.texowners[i].slice = NULL;
1572 else if (!strncmp ("interrupt", p, 9)) {
1573 printd ("vmsg interrupted");
1575 else if (!strncmp ("quit", p, 4)) {
1576 return 0;
1578 else {
1579 errx (1, "unknown command %.*s", len, p);
1582 return 0;
1585 CAMLprim value ml_realloctexts (value texcount_v)
1587 CAMLparam1 (texcount_v);
1588 int ok;
1590 if (trylock ("ml_realloctexts")) {
1591 ok = 0;
1592 goto done;
1594 realloctexts (Int_val (texcount_v));
1595 ok = 1;
1596 unlock ("ml_realloctexts");
1598 done:
1599 CAMLreturn (Val_bool (ok));
1602 static void showsel (struct page *page, int ox, int oy)
1604 fz_bbox bbox;
1605 fz_text_span *span;
1606 struct mark first, last;
1608 first = page->fmark;
1609 last = page->lmark;
1611 if (!first.span || !last.span) return;
1613 glEnable (GL_BLEND);
1614 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1615 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1617 ox += state.pagedims[page->pdimno].bounds.x0;
1618 oy += state.pagedims[page->pdimno].bounds.y0;
1619 for (span = first.span; span; span = span->next) {
1620 int i, j, k;
1622 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1624 j = 0;
1625 k = span->len - 1;
1627 if (span == page->fmark.span && span == page->lmark.span) {
1628 j = MIN (first.i, last.i);
1629 k = MAX (first.i, last.i);
1631 else if (span == first.span) {
1632 j = first.i;
1634 else if (span == last.span) {
1635 k = last.i;
1638 for (i = j; i <= k; ++i) {
1639 bbox = fz_union_bbox (bbox, span->text[i].bbox);
1641 lprintf ("%d %d %d %d oy=%d ox=%d\n",
1642 bbox.x0,
1643 bbox.y0,
1644 bbox.x1,
1645 bbox.y1,
1646 oy, ox);
1648 glRecti (bbox.x0 + ox, bbox.y0 + oy, bbox.x1 + ox, bbox.y1 + oy);
1650 if (span == last.span) break;
1652 glDisable (GL_BLEND);
1655 static void highlightlinks (struct page *page, int xoff, int yoff)
1657 fz_matrix ctm;
1658 fz_link *link, *links;
1660 switch (page->type) {
1661 case DPDF:
1662 links = page->u.pdfpage->links;
1663 break;
1665 case DXPS:
1666 links = page->u.xpspage->links;
1667 break;
1669 default:
1670 return;
1673 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
1674 glEnable (GL_LINE_STIPPLE);
1675 glLineStipple (0.5, 0xcccc);
1677 xoff -= state.pagedims[page->pdimno].bounds.x0;
1678 yoff -= state.pagedims[page->pdimno].bounds.y0;
1679 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1681 glBegin (GL_QUADS);
1682 for (link = links; link; link = link->next) {
1683 fz_point p1, p2, p3, p4;
1685 p1.x = link->rect.x0;
1686 p1.y = link->rect.y0;
1688 p2.x = link->rect.x1;
1689 p2.y = link->rect.y0;
1691 p3.x = link->rect.x1;
1692 p3.y = link->rect.y1;
1694 p4.x = link->rect.x0;
1695 p4.y = link->rect.y1;
1697 p1 = fz_transform_point (ctm, p1);
1698 p2 = fz_transform_point (ctm, p2);
1699 p3 = fz_transform_point (ctm, p3);
1700 p4 = fz_transform_point (ctm, p4);
1702 switch (link->dest.kind) {
1703 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
1704 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
1705 default: glColor3ub (0, 0, 0); break;
1708 glVertex2f (p1.x, p1.y);
1709 glVertex2f (p2.x, p2.y);
1710 glVertex2f (p3.x, p3.y);
1711 glVertex2f (p4.x, p4.y);
1713 glEnd ();
1715 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1716 glDisable (GL_LINE_STIPPLE);
1719 static void uploadslice (struct tile *tile, struct slice *slice)
1721 int offset;
1722 struct slice *slice1;
1724 offset = 0;
1725 for (slice1 = tile->slices; slice != slice1; slice1++) {
1726 offset += slice1->h * tile->w * tile->pixmap->n;
1728 if (slice->texindex != -1 && slice->texindex < state.texcount
1729 && state.texowners[slice->texindex].slice == slice) {
1730 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
1732 else {
1733 int subimage = 0;
1734 int texindex = state.texindex++ % state.texcount;
1736 if (state.texowners[texindex].w == tile->w) {
1737 if (state.texowners[texindex].h >= slice->h) {
1738 subimage = 1;
1740 else {
1741 state.texowners[texindex].h = slice->h;
1744 else {
1745 state.texowners[texindex].h = slice->h;
1748 state.texowners[texindex].w = tile->w;
1749 state.texowners[texindex].slice = slice;
1750 slice->texindex = texindex;
1752 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
1753 if (subimage) {
1754 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
1758 tile->w,
1759 slice->h,
1760 state.texform,
1761 state.texty,
1762 tile->pixmap->samples+offset
1765 else {
1766 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
1768 state.texiform,
1769 tile->w,
1770 slice->h,
1772 state.texform,
1773 state.texty,
1774 tile->pixmap->samples+offset
1780 CAMLprim value ml_drawtile (value args_v, value ptr_v)
1782 CAMLparam2 (args_v, ptr_v);
1783 int dispx = Int_val (Field (args_v, 0));
1784 int dispy = Int_val (Field (args_v, 1));
1785 int dispw = Int_val (Field (args_v, 2));
1786 int disph = Int_val (Field (args_v, 3));
1787 int tilex = Int_val (Field (args_v, 4));
1788 int tiley = Int_val (Field (args_v, 5));
1789 char *s = String_val (ptr_v);
1790 struct tile *tile = parse_pointer ("ml_drawtile", s);
1792 glEnable (GL_TEXTURE_RECTANGLE_ARB);
1794 int slicey, firstslice;
1795 struct slice *slice;
1797 firstslice = tiley / tile->sliceheight;
1798 slice = &tile->slices[firstslice];
1799 slicey = tiley % tile->sliceheight;
1801 while (disph > 0) {
1802 int dh;
1804 dh = slice->h - slicey;
1805 dh = MIN (disph, dh);
1806 uploadslice (tile, slice);
1808 glBegin (GL_QUADS);
1810 glTexCoord2i (tilex, slicey);
1811 glVertex2i (dispx, dispy);
1813 glTexCoord2i (tilex+dispw, slicey);
1814 glVertex2i (dispx+dispw, dispy);
1816 glTexCoord2i (tilex+dispw, slicey+dh);
1817 glVertex2i (dispx+dispw, dispy+dh);
1819 glTexCoord2i (tilex, slicey+dh);
1820 glVertex2i (dispx, dispy+dh);
1822 glEnd ();
1824 dispy += dh;
1825 disph -= dh;
1826 slice++;
1827 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
1828 slicey = 0;
1831 glDisable (GL_TEXTURE_RECTANGLE_ARB);
1832 CAMLreturn (Val_unit);
1835 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
1836 value xoff_v, value yoff_v)
1838 CAMLparam4 (ptr_v, hlinks_v, xoff_v, yoff_v);
1839 int xoff = Int_val (xoff_v);
1840 int yoff = Int_val (yoff_v);
1841 char *s = String_val (ptr_v);
1842 struct page *page = parse_pointer ("ml_postprocess", s);
1844 if (Bool_val (hlinks_v)) highlightlinks (page, xoff, yoff);
1846 if (trylock ("ml_postprocess")) {
1847 goto done;
1849 showsel (page, xoff, yoff);
1850 unlock ("ml_postprocess");
1852 done:
1853 CAMLreturn (Val_unit);
1856 static fz_link *getlink (struct page *page, int x, int y)
1858 fz_point p;
1859 fz_matrix ctm;
1860 fz_link *link, *links;
1862 switch (page->type) {
1863 case DPDF:
1864 ctm = trimctm (page->u.pdfpage, page->pdimno);
1865 links = page->u.pdfpage->links;
1866 break;
1868 case DXPS:
1869 ctm = fz_identity;
1870 links = page->u.xpspage->links;
1871 break;
1873 default:
1874 return NULL;
1876 p.x = x;
1877 p.y = y;
1879 ctm = fz_concat (ctm, state.pagedims[page->pdimno].ctm);
1880 ctm = fz_invert_matrix (ctm);
1881 p = fz_transform_point (ctm, p);
1883 for (link = links; link; link = link->next) {
1884 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
1885 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
1886 return link;
1890 return NULL;
1893 static void droptext (struct page *page)
1895 if (page->text) {
1896 fz_free_text_span (state.ctx, page->text);
1897 page->fmark.i = -1;
1898 page->lmark.i = -1;
1899 page->fmark.span = NULL;
1900 page->lmark.span = NULL;
1901 page->text = NULL;
1905 static void ensuretext (struct page *page)
1907 if (state.gen != page->gen) {
1908 droptext (page);
1909 page->gen = state.gen;
1911 if (!page->text) {
1912 fz_device *tdev;
1914 page->text = fz_new_text_span (state.ctx);
1915 tdev = fz_new_text_device (state.ctx, page->text);
1916 fz_run_display_list (page->dlist,
1917 tdev,
1918 pagectm (page),
1919 fz_infinite_bbox, NULL);
1920 fz_free_device (tdev);
1924 static int compareslinks (const void *l, const void *r)
1926 struct slink const *ls = l;
1927 struct slink const *rs = r;
1928 if (ls->bbox.y0 == rs->bbox.y0) {
1929 return rs->bbox.x0 - rs->bbox.x0;
1931 return ls->bbox.y0 - rs->bbox.y0;
1934 static void ensureslinks (struct page *page)
1936 fz_matrix ctm;
1937 int i, count = 0;
1938 size_t slinksize = sizeof (*page->slinks);
1939 fz_link *link, *links;
1941 if (page->slinks) return;
1943 switch (page->type) {
1944 case DPDF:
1945 links = page->u.pdfpage->links;
1946 ctm = fz_concat (trimctm (page->u.pdfpage, page->pdimno),
1947 state.pagedims[page->pdimno].ctm);
1948 break;
1950 case DXPS:
1951 links = page->u.xpspage->links;
1952 ctm = state.pagedims[page->pdimno].ctm;
1953 break;
1955 default:
1956 return;
1959 for (link = links; link; link = link->next) {
1960 count++;
1962 if (count > 0) {
1963 page->slinkcount = count;
1964 page->slinks = calloc (count, slinksize);
1965 if (!page->slinks) {
1966 err (1, "realloc slinks %d", count);
1969 for (i = 0, link = links; link; ++i, link = link->next) {
1970 page->slinks[i].link = link;
1971 page->slinks[i].bbox =
1972 fz_round_rect (fz_transform_rect (ctm, link->rect));
1974 qsort (page->slinks, count, slinksize, compareslinks);
1978 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
1980 CAMLparam2 (start_page_v, dir_v);
1981 CAMLlocal1 (ret_v);
1982 int i, dir = Int_val (dir_v);
1983 int start_page = Int_val (start_page_v);
1984 int end_page = dir > 0 ? state.pagecount : -1;
1986 ret_v = Val_int (0);
1987 if (!(state.type == DPDF || state.type == DXPS)) {
1988 goto done;
1991 lock ("ml_findpage_with_links");
1992 for (i = start_page + dir; i != end_page; i += dir) {
1993 int found;
1995 switch (state.type) {
1996 case DPDF:
1998 pdf_page *page = pdf_load_page (state.u.pdf, i);
1999 found = !!page->links;
2000 freepdfpage (page);
2002 break;
2003 case DXPS:
2005 xps_page *page = xps_load_page (state.u.xps, i);
2006 found = !!page->links;
2007 freexpspage (page);
2009 break;
2011 default:
2012 ARSERT ("invalid document type");
2015 if (found) {
2016 ret_v = caml_alloc_small (1, 1);
2017 Field (ret_v, 0) = Val_int (i);
2018 goto unlock;
2021 unlock:
2022 unlock ("ml_findpage_with_links");
2024 done:
2025 CAMLreturn (ret_v);
2028 enum { dir_first, dir_last};
2029 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2031 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2033 CAMLparam2 (ptr_v, dir_v);
2034 CAMLlocal3 (ret_v, tup_v, pos_v);
2035 struct page *page;
2036 int dirtag, i, slinkindex;
2037 struct slink *found = NULL ,*slink;
2038 char *s = String_val (ptr_v);
2040 page = parse_pointer ("ml_findlink", s);
2041 ensureslinks (page);
2043 ret_v = Val_int (0);
2044 if (Is_block (dir_v)) {
2045 dirtag = Tag_val (dir_v);
2046 switch (dirtag) {
2047 case dir_first_visible:
2049 int x0, y0, dir, first_index, last_index;
2051 pos_v = Field (dir_v, 0);
2052 x0 = Int_val (Field (pos_v, 0));
2053 y0 = Int_val (Field (pos_v, 1));
2054 dir = Int_val (Field (pos_v, 2));
2056 if (dir >= 0) {
2057 dir = 1;
2058 first_index = 0;
2059 last_index = page->slinkcount;
2061 else {
2062 first_index = page->slinkcount - 1;
2063 last_index = -1;
2066 for (i = first_index; i != last_index; i += dir) {
2067 slink = &page->slinks[i];
2068 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2069 found = slink;
2070 break;
2074 break;
2076 case dir_left:
2077 slinkindex = Int_val (Field (dir_v, 0));
2078 found = &page->slinks[slinkindex];
2079 for (i = slinkindex - 1; i >= 0; --i) {
2080 slink = &page->slinks[i];
2081 if (slink->bbox.x0 < found->bbox.x0) {
2082 found = slink;
2083 break;
2086 break;
2088 case dir_right:
2089 slinkindex = Int_val (Field (dir_v, 0));
2090 found = &page->slinks[slinkindex];
2091 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2092 slink = &page->slinks[i];
2093 if (slink->bbox.x0 > found->bbox.x0) {
2094 found = slink;
2095 break;
2098 break;
2100 case dir_down:
2101 slinkindex = Int_val (Field (dir_v, 0));
2102 found = &page->slinks[slinkindex];
2103 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2104 slink = &page->slinks[i];
2105 if (slink->bbox.y0 >= found->bbox.y0) {
2106 found = slink;
2107 break;
2110 break;
2112 case dir_up:
2113 slinkindex = Int_val (Field (dir_v, 0));
2114 found = &page->slinks[slinkindex];
2115 for (i = slinkindex - 1; i >= 0; --i) {
2116 slink = &page->slinks[i];
2117 if (slink->bbox.y0 <= found->bbox.y0) {
2118 found = slink;
2119 break;
2122 break;
2125 else {
2126 dirtag = Int_val (dir_v);
2127 switch (dirtag) {
2128 case dir_first:
2129 found = page->slinks;
2130 break;
2132 case dir_last:
2133 if (page->slinks) {
2134 found = page->slinks + (page->slinkcount - 1);
2136 break;
2139 if (found) {
2140 tup_v = caml_alloc_tuple (5);
2141 ret_v = caml_alloc_small (2, 1);
2142 Field (tup_v, 0) = Val_int (found - page->slinks);
2143 Field (tup_v, 1) = Val_int (found->bbox.x0);
2144 Field (tup_v, 2) = Val_int (found->bbox.y0);
2145 Field (tup_v, 3) = Val_int (found->bbox.x1);
2146 Field (tup_v, 4) = Val_int (found->bbox.y1);
2147 Field (ret_v, 0) = tup_v;
2150 CAMLreturn (ret_v);
2153 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2155 #define LINKTOVAL \
2157 int pageno; \
2159 switch (link->dest.kind) { \
2160 case FZ_LINK_GOTO: \
2162 fz_point p; \
2164 pageno = link->dest.ld.gotor.page; \
2165 p.x = 0; \
2166 p.y = 0; \
2168 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2169 p.y = link->dest.ld.gotor.lt.y; \
2170 p = fz_transform_point (pdim->lctm, p); \
2172 tup_v = caml_alloc_tuple (2); \
2173 ret_v = caml_alloc_small (1, ugoto); \
2174 Field (tup_v, 0) = Val_int (pageno); \
2175 Field (tup_v, 1) = Val_int (p.y); \
2176 Field (ret_v, 0) = tup_v; \
2178 break; \
2180 case FZ_LINK_URI: \
2181 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2182 ret_v = caml_alloc_small (1, uuri); \
2183 Field (ret_v, 0) = str_v; \
2184 break; \
2186 case FZ_LINK_LAUNCH: \
2187 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2188 ret_v = caml_alloc_small (1, ulaunch); \
2189 Field (ret_v, 0) = str_v; \
2190 break; \
2192 case FZ_LINK_NAMED: \
2193 str_v = caml_copy_string (link->dest.ld.named.named); \
2194 ret_v = caml_alloc_small (1, unamed); \
2195 Field (ret_v, 0) = str_v; \
2196 break; \
2198 case FZ_LINK_GOTOR: \
2199 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2200 pageno = link->dest.ld.gotor.page; \
2201 tup_v = caml_alloc_tuple (2); \
2202 ret_v = caml_alloc_small (1, uremote); \
2203 Field (tup_v, 0) = str_v; \
2204 Field (tup_v, 1) = Val_int (pageno); \
2205 Field (ret_v, 0) = tup_v; \
2206 break; \
2208 default: \
2210 char buf[80]; \
2212 snprintf (buf, sizeof (buf), \
2213 "unhandled link kind %d", link->dest.kind); \
2214 str_v = caml_copy_string (buf); \
2215 ret_v = caml_alloc_small (1, uunexpected); \
2216 Field (ret_v, 0) = str_v; \
2218 break; \
2222 CAMLprim value ml_getlink (value ptr_v, value n_v)
2224 CAMLparam2 (ptr_v, n_v);
2225 CAMLlocal3 (ret_v, tup_v, str_v);
2226 fz_link *link;
2227 struct page *page;
2228 struct pagedim *pdim;
2229 char *s = String_val (ptr_v);
2231 ret_v = Val_int (0);
2232 page = parse_pointer ("ml_getlink", s);
2233 pdim = &state.pagedims[page->pdimno];
2234 link = page->slinks[Int_val (n_v)].link;
2235 LINKTOVAL;
2236 CAMLreturn (ret_v);
2239 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2241 CAMLparam3 (ptr_v, x_v, y_v);
2242 CAMLlocal3 (ret_v, tup_v, str_v);
2243 fz_link *link;
2244 struct page *page;
2245 char *s = String_val (ptr_v);
2246 int x = Int_val (x_v), y = Int_val (y_v);
2247 struct pagedim *pdim;
2249 ret_v = Val_int (0);
2250 if (trylock ("ml_whatsunder")) {
2251 goto done;
2254 page = parse_pointer ("ml_whatsunder", s);
2255 pdim = &state.pagedims[page->pdimno];
2256 x += pdim->bounds.x0;
2257 y += pdim->bounds.y0;
2258 link = getlink (page, x, y);
2259 if (link) {
2260 LINKTOVAL;
2262 else {
2263 int i;
2264 fz_text_span *span;
2266 ensuretext (page);
2267 for (span = page->text; span; span = span->next) {
2268 for (i = 0; i < span->len; ++i) {
2269 fz_bbox *b;
2270 b = &span->text[i].bbox;
2271 if ((x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)) {
2272 const char *n2 =
2273 span->font && span->font->name
2274 ? span->font->name
2275 : "Span has no font name"
2277 FT_FaceRec *face = span->font->ft_face;
2278 if (face && face->family_name) {
2279 char *s;
2280 char *n1 = face->family_name;
2281 size_t l1 = strlen (n1);
2282 size_t l2 = strlen (n2);
2284 if (l1 != l2 || memcmp (n1, n2, l1)) {
2285 s = malloc (l1 + l2 + 2);
2286 if (s) {
2287 memcpy (s, n2, l2);
2288 s[l2] = '=';
2289 memcpy (s + l2 + 1, n1, l1 + 1);
2290 str_v = caml_copy_string (s);
2291 free (s);
2295 if (str_v == 0) {
2296 str_v = caml_copy_string (n2);
2298 ret_v = caml_alloc_small (1, utext);
2299 Field (ret_v, 0) = str_v;
2300 goto unlock;
2305 unlock:
2306 unlock ("ml_whatsunder");
2308 done:
2309 CAMLreturn (ret_v);
2312 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2314 CAMLparam2 (ptr_v, rect_v);
2315 fz_bbox *b;
2316 struct page *page;
2317 fz_text_span *span;
2318 struct mark first, last;
2319 struct pagedim *pdim;
2320 int i, x0, x1, y0, y1;
2321 char *s = String_val (ptr_v);
2323 if (trylock ("ml_seltext")) {
2324 goto done;
2327 page = parse_pointer ("ml_seltext", s);
2328 ensuretext (page);
2330 pdim = &state.pagedims[page->pdimno];
2331 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2332 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2333 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2334 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2336 if (0) {
2337 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2338 glColor3ub (128, 128, 128);
2339 glRecti (x0, y0, x1, y1);
2340 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2343 first.span = NULL;
2344 last.span = NULL;
2346 last.i = first.i = 0;
2347 first.span = page->text;
2348 for (span = page->text; span; span = span->next) {
2349 for (i = 0; i < span->len; ++i) {
2350 b = &span->text[i].bbox;
2351 int selected = 0;
2353 if (x0 >= b->x0 && x0 <= b->x1 && y0 >= b->y0 && y0 <= b->y1) {
2354 first.i = i;
2355 first.span = span;
2356 selected = 1;
2358 if (x1 >= b->x0 && x1 <= b->x1 && y1 >= b->y0 && y1 <= b->y1) {
2359 last.i = i;
2360 last.span = span;
2361 selected = 1;
2363 if (0 && selected) {
2364 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2365 glColor3ub (128, 128, 128);
2366 glRecti (b->x0, b->y0, b->x1, b->y1);
2367 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2372 if (y1 < y0 || x1 < x0) {
2373 int swap = 0;
2375 if (first.span == last.span) {
2376 swap = 1;
2378 else {
2379 if (y1 < y0) {
2380 for (span = first.span; span && span != last.span;
2381 span = span->next) {
2382 if (span->eol) {
2383 swap = 1;
2384 break;
2390 if (swap) {
2391 i = first.i;
2392 span = first.span;
2393 first.i = last.i;
2394 first.span = last.span;
2395 last.i = i;
2396 last.span = span;
2400 page->fmark = first;
2401 page->lmark = last;
2403 unlock ("ml_seltext");
2405 done:
2406 CAMLreturn (Val_unit);
2409 static int pipespan (FILE *f, fz_text_span *span, int a, int b)
2411 char buf[4];
2412 int i, len, ret;
2414 for (i = a; i <= b; ++i) {
2415 len = runetochar (buf, &span->text[i].c);
2416 ret = fwrite (buf, len, 1, f);
2418 if (ret != 1) {
2419 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
2420 len, ret, strerror (errno));
2421 return -1;
2424 return 0;
2427 CAMLprim value ml_copysel (value command_v, value ptr_v)
2429 CAMLparam1 (ptr_v);
2430 FILE *f;
2431 struct page *page;
2432 fz_text_span *span;
2433 char *s = String_val (ptr_v);
2434 char *command = String_val (command_v);
2436 if (trylock ("ml_copysel")) {
2437 goto done;
2440 page = parse_pointer ("ml_sopysel", s);
2442 if (!page->fmark.span || !page->lmark.span) {
2443 fprintf (stderr, "nothing to copy\n");
2444 goto unlock;
2447 f = popen (command, "w");
2448 if (!f) {
2449 fprintf (stderr, "failed to open sel pipe: %s\n",
2450 strerror (errno));
2451 f = stdout;
2454 for (span = page->fmark.span;
2455 span && span != page->lmark.span->next;
2456 span = span->next) {
2457 int a = span == page->fmark.span ? page->fmark.i : 0;
2458 int b = span == page->lmark.span ? page->lmark.i : span->len - 1;
2459 if (pipespan (f, span, a, b)) {
2460 goto close;
2462 if (span->eol) {
2463 if (putc ('\n', f) == EOF) {
2464 fprintf (stderr, "failed break line on sel pipe: %s\n",
2465 strerror (errno));
2466 goto close;
2470 page->lmark.span = NULL;
2471 page->fmark.span = NULL;
2473 close:
2474 if (f != stdout) {
2475 int ret = pclose (f);
2476 if (ret == -1) {
2477 if (errno != ECHILD) {
2478 fprintf (stderr, "failed to close sel pipe: %s\n",
2479 strerror (errno));
2483 unlock:
2484 unlock ("ml_copysel");
2486 done:
2487 CAMLreturn (Val_unit);
2490 CAMLprim value ml_getpdimrect (value pagedimno_v)
2492 CAMLparam1 (pagedimno_v);
2493 CAMLlocal1 (ret_v);
2494 int pagedimno = Int_val (pagedimno_v);
2495 fz_rect box;
2497 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2498 if (trylock ("ml_getpdimrect")) {
2499 box = fz_empty_rect;
2501 else {
2502 box = state.pagedims[pagedimno].mediabox;
2503 unlock ("ml_getpdimrect");
2506 Store_double_field (ret_v, 0, box.x0);
2507 Store_double_field (ret_v, 1, box.x1);
2508 Store_double_field (ret_v, 2, box.y0);
2509 Store_double_field (ret_v, 3, box.y1);
2511 CAMLreturn (ret_v);
2514 static double getmaxw (void)
2516 int i;
2517 struct pagedim *p;
2518 double maxw = 0.0;
2520 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
2521 double x0, x1, w;
2523 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
2524 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
2526 w = x1 - x0;
2527 maxw = MAX (w, maxw);
2529 return maxw;
2532 CAMLprim value ml_getmaxw (value unit_v)
2534 CAMLparam1 (unit_v);
2535 CAMLlocal1 (ret_v);
2536 double maxw = 0.0;
2538 if (trylock ("ml_getmaxw")) {
2539 goto done;
2541 maxw = getmaxw ();
2542 unlock ("ml_getmaxw");
2543 done:
2544 ret_v = caml_copy_double (maxw);
2545 CAMLreturn (ret_v);
2548 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v, value dw_v)
2550 CAMLparam3 (winw_v, winh_v, dw_v);
2551 CAMLlocal1 (ret_v);
2552 int i;
2553 double zoom = 1.0;
2554 double maxw = 0.0, maxh = 0.0;
2555 struct pagedim *p;
2556 double winw = Int_val (winw_v);
2557 double winh = Int_val (winh_v);
2558 double dw = Int_val (dw_v);
2559 double pw = 1.0, ph = 1.0, num, den;
2561 if (trylock ("ml_zoom_for_height")) {
2562 goto done;
2565 if (state.proportional) {
2566 maxw = getmaxw ();
2569 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
2570 double x0, x1, y0, y1, w, h, scaledh, scale;
2572 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
2573 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
2574 y0 = MIN (p->mediabox.y0, p->mediabox.y1);
2575 y1 = MAX (p->mediabox.y0, p->mediabox.y1);
2577 w = x1 - x0;
2578 h = y1 - y0;
2580 if (state.proportional) {
2581 scale = w / maxw;
2582 scaledh = h * scale;
2584 else {
2585 scale = 1.0;
2586 scaledh = h;
2589 if (scaledh > maxh) {
2590 maxh = scaledh;
2591 ph = scaledh;
2592 pw = w * scale;
2596 num = (winh * pw) + (ph * dw);
2597 den = ph * winw;
2598 zoom = num / den;
2600 unlock ("ml_zoom_for_height");
2601 done:
2602 ret_v = caml_copy_double (zoom);
2603 CAMLreturn (ret_v);
2606 #include "glfont.c"
2608 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
2610 CAMLparam4 (pt_v, x_v, y_v, string_v);
2611 CAMLlocal1 (ret_v);
2612 int pt = Int_val(pt_v);
2613 int x = Int_val (x_v);
2614 int y = Int_val (y_v);
2615 double w;
2617 w = draw_string (state.face, pt, x, y, String_val (string_v));
2618 ret_v = caml_copy_double (w);
2619 CAMLreturn (ret_v);
2622 CAMLprim value ml_measure_string (value pt_v, value string_v)
2624 CAMLparam2 (pt_v, string_v);
2625 CAMLlocal1 (ret_v);
2626 int pt = Int_val (pt_v);
2627 double w;
2629 w = measure_string (state.face, pt, String_val (string_v));
2630 ret_v = caml_copy_double (w);
2631 CAMLreturn (ret_v);
2634 CAMLprim value ml_getpagebox (value opaque_v)
2636 CAMLparam1 (opaque_v);
2637 CAMLlocal1 (ret_v);
2638 fz_bbox bbox;
2639 fz_device *dev;
2640 char *s = String_val (opaque_v);
2641 struct page *page = parse_pointer ("ml_getpagebox", s);
2643 ret_v = caml_alloc_tuple (4);
2644 dev = fz_new_bbox_device (state.ctx, &bbox);
2645 dev->hints |= FZ_IGNORE_SHADE;
2647 switch (page->type) {
2648 case DPDF:
2649 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, pagectm (page), NULL);
2650 break;
2652 case DXPS:
2653 xps_run_page (state.u.xps, page->u.xpspage, dev, pagectm (page), NULL);
2654 break;
2656 default:
2657 bbox = fz_infinite_bbox;
2658 break;
2661 fz_free_device (dev);
2662 Field (ret_v, 0) = Val_int (bbox.x0);
2663 Field (ret_v, 1) = Val_int (bbox.y0);
2664 Field (ret_v, 2) = Val_int (bbox.x1);
2665 Field (ret_v, 3) = Val_int (bbox.y1);
2667 CAMLreturn (ret_v);
2670 CAMLprim value ml_setaalevel (value level_v)
2672 CAMLparam1 (level_v);
2674 state.aalevel = Int_val (level_v);
2675 CAMLreturn (Val_unit);
2678 #undef pixel
2679 #include <X11/Xlib.h>
2680 #include <GL/glx.h>
2682 static struct {
2683 Display *dpy;
2684 GLXContext ctx;
2685 GLXDrawable drawable;
2686 } glx;
2688 #include "keysym2ucs.c"
2690 CAMLprim value ml_keysymtoutf8 (value keysym_v)
2692 CAMLparam1 (keysym_v);
2693 CAMLlocal1 (str_v);
2694 KeySym keysym = Int_val (keysym_v);
2695 Rune rune;
2696 int len;
2697 char buf[5];
2699 rune = keysym2ucs (keysym);
2700 len = runetochar (buf, &rune);
2701 buf[len] = 0;
2702 str_v = caml_copy_string (buf);
2703 CAMLreturn (str_v);
2706 CAMLprim value ml_glx (value win_v)
2708 CAMLparam1 (win_v);
2709 int screen;
2710 XVisualInfo *visual;
2711 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
2713 glx.dpy = XOpenDisplay (NULL);
2714 if (!glx.dpy) {
2715 caml_failwith ("XOpenDisplay failed");
2718 screen = DefaultScreen (glx.dpy);
2719 visual = glXChooseVisual (glx.dpy, screen, attributes);
2720 if (!visual) {
2721 XCloseDisplay (glx.dpy);
2722 glx.dpy = NULL;
2723 caml_failwith ("glXChooseVisual");
2726 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
2727 if (!glx.ctx) {
2728 XCloseDisplay (glx.dpy);
2729 XFree (visual);
2730 glx.dpy = NULL;
2731 caml_failwith ("glXCreateContext");
2734 XFree (visual);
2735 if (!glXMakeCurrent (glx.dpy, Int_val (win_v), glx.ctx)) {
2736 glXDestroyContext (glx.dpy, glx.ctx);
2737 XCloseDisplay (glx.dpy);
2738 glx.dpy = NULL;
2739 glx.ctx = NULL;
2740 caml_failwith ("glXMakeCurrent");
2742 glx.drawable = Int_val (win_v);
2744 CAMLreturn (Val_unit);
2747 CAMLprim value ml_swapb (value unit_v)
2749 CAMLparam1 (unit_v);
2750 glXSwapBuffers (glx.dpy, glx.drawable);
2751 CAMLreturn (Val_unit);
2754 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
2755 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
2757 CAMLprim value ml_platform (value unit_v)
2759 CAMLparam1 (unit_v);
2760 int platid = piunknown;
2762 #if defined __linux__
2763 platid = pilinux;
2764 #elif defined __CYGWIN__
2765 platid = picygwin;
2766 #elif defined __DragonFly__
2767 platid = pidragonflybsd;
2768 #elif defined __FreeBSD__
2769 platid = pifreebsd;
2770 #elif defined __OpenBSD__
2771 platid = piopenbsd;
2772 #elif defined __NetBSD__
2773 platid = pinetbsd;
2774 #elif defined __sun__
2775 platid = pisun;
2776 #elif defined __APPLE__
2777 platid = piosx;
2778 #endif
2779 CAMLreturn (Val_int (platid));
2782 CAMLprim value ml_cloexec (value fd_v)
2784 CAMLparam1 (fd_v);
2785 int fd = Int_val (fd_v);
2787 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
2788 uerror ("fcntl", Nothing);
2790 CAMLreturn (Val_unit);
2793 CAMLprim value ml_init (value pipe_v, value params_v)
2795 CAMLparam2 (pipe_v, params_v);
2796 CAMLlocal2 (trim_v, fuzz_v);
2797 int ret;
2798 int texcount;
2799 char *fontpath;
2800 int colorspace;
2801 int mustoresize;
2802 struct sigaction sa;
2804 state.cr = Int_val (Field (pipe_v, 0));
2805 state.cw = Int_val (Field (pipe_v, 1));
2806 state.rotate = Int_val (Field (params_v, 0));
2807 state.proportional = Bool_val (Field (params_v, 1));
2808 trim_v = Field (params_v, 2);
2809 texcount = Int_val (Field (params_v, 3));
2810 state.sliceheight = Int_val (Field (params_v, 4));
2811 mustoresize = Int_val (Field (params_v, 5));
2812 colorspace = Int_val (Field (params_v, 6));
2813 fontpath = String_val (Field (params_v, 7));
2815 state.ctx = fz_new_context (NULL, NULL, mustoresize);
2816 state.trimmargins = Bool_val (Field (trim_v, 0));
2818 fuzz_v = Field (trim_v, 1);
2819 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
2820 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
2821 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
2822 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
2824 set_tex_params (colorspace);
2826 if (*fontpath) {
2827 state.face = load_font (fontpath);
2829 else {
2830 unsigned int len;
2831 void *base = pdf_find_substitute_font (0, 0, 0, 0, &len);
2833 state.face = load_builtin_font (base, len);
2835 if (!state.face) _exit (1);
2837 realloctexts (texcount);
2839 sa.sa_handler = SIG_DFL;
2840 if (sigemptyset (&sa.sa_mask)) {
2841 err (1, "sigemptyset");
2843 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
2844 if (sigaction (SIGCHLD, &sa, NULL)) {
2845 err (1, "sigaction");
2848 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
2849 if (ret) {
2850 errx (1, "pthread_create: %s", strerror (ret));
2853 CAMLreturn (Val_unit);