Clear front buffer on expose if geometry changing command is pending
[llpp.git] / link.c
blob2d47bd43918996e1d066cd8a8850b5b927c24901
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 #ifdef __CYGWIN__
16 #include <cygwin/socket.h> /* FIONREAD */
17 #else
18 #include <spawn.h>
19 #endif
21 #include <regex.h>
22 #include <ctype.h>
23 #include <stdarg.h>
24 #include <limits.h>
26 #include <GL/gl.h>
28 #include <caml/fail.h>
29 #include <caml/alloc.h>
30 #include <caml/memory.h>
31 #include <caml/unixsupport.h>
33 #include <fitz.h>
34 #include <mupdf.h>
35 #include <muxps.h>
36 #include <mucbz.h>
38 #include FT_FREETYPE_H
40 #define PIGGYBACK
42 #ifndef __USE_GNU
43 extern char **environ;
44 #endif
46 #if defined __GNUC__
47 #define NORETURN __attribute__ ((noreturn))
48 #define UNUSED __attribute__ ((unused))
49 #define OPTIMIZE(n) __attribute__ ((optimize ("O"#n)))
50 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
51 #else
52 #define NORETURN
53 #define UNUSED
54 #define OPTIMIZE(n)
55 #define GCC_FMT_ATTR(a, b)
56 #endif
58 #define FMT_s "zu"
60 #define FMT_ptr "p"
61 #define FMT_ptr_cast(p) (p)
62 #define FMT_ptr_cast2(p) (p)
64 static void NORETURN GCC_FMT_ATTR (2, 3)
65 err (int exitcode, const char *fmt, ...)
67 va_list ap;
68 int savederrno;
70 savederrno = errno;
71 va_start (ap, fmt);
72 vfprintf (stderr, fmt, ap);
73 va_end (ap);
74 fprintf (stderr, ": %s\n", strerror (savederrno));
75 fflush (stderr);
76 _exit (exitcode);
79 static void NORETURN GCC_FMT_ATTR (2, 3)
80 errx (int exitcode, const char *fmt, ...)
82 va_list ap;
84 va_start (ap, fmt);
85 vfprintf (stderr, fmt, ap);
86 va_end (ap);
87 fputc ('\n', stderr);
88 fflush (stderr);
89 _exit (exitcode);
92 #ifndef GL_TEXTURE_RECTANGLE_ARB
93 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
94 #endif
96 #ifndef GL_BGRA
97 #define GL_BGRA 0x80E1
98 #endif
100 #ifndef GL_UNSIGNED_INT_8_8_8_8
101 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
102 #endif
104 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
105 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
106 #endif
108 #if 0
109 #define lprintf printf
110 #else
111 #define lprintf(...)
112 #endif
114 #define ARSERT(cond) for (;;) { \
115 if (!(cond)) { \
116 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
118 break; \
121 struct slice {
122 int h;
123 int texindex;
126 struct tile {
127 int x, y, w, h;
128 int slicecount;
129 int sliceheight;
130 fz_pixmap *pixmap;
131 struct slice slices[1];
134 struct pagedim {
135 int pageno;
136 int rotate;
137 int left;
138 int tctmready;
139 fz_bbox bounds;
140 fz_rect pagebox;
141 fz_rect mediabox;
142 fz_matrix ctm, zoomctm, lctm, tctm;
145 struct slink {
146 fz_bbox bbox;
147 fz_link *link;
150 enum { DPDF, DXPS, DCBZ };
152 struct page {
153 int tgen;
154 int sgen;
155 int type;
156 int pageno;
157 int pdimno;
158 fz_text_span *text;
159 union {
160 void *ptr;
161 pdf_page *pdfpage;
162 xps_page *xpspage;
163 cbz_page *cbzpage;
164 } u;
165 fz_display_list *dlist;
166 int slinkcount;
167 struct slink *slinks;
168 struct mark {
169 int i;
170 fz_text_span *span;
171 } fmark, lmark;
172 void (*freepage) (void *);
175 struct {
176 int type;
177 int sliceheight;
178 struct pagedim *pagedims;
179 int pagecount;
180 int pagedimcount;
181 union {
182 pdf_document *pdf;
183 xps_document *xps;
184 cbz_document *cbz;
185 } u;
186 fz_context *ctx;
187 int w, h;
189 int texindex;
190 int texcount;
191 GLuint *texids;
193 GLenum texiform;
194 GLenum texform;
195 GLenum texty;
197 fz_colorspace *colorspace;
199 struct {
200 int w, h;
201 struct slice *slice;
202 } *texowners;
204 int rotate;
205 int proportional;
206 int trimmargins;
207 int needoutline;
208 int gen;
209 int aalevel;
211 int trimanew;
212 fz_bbox trimfuzz;
213 fz_pixmap *pig;
215 pthread_t thread;
216 int cr, cw;
217 FT_Face face;
219 void (*closedoc) (void);
220 void (*freepage) (void *);
221 } state;
223 static void UNUSED debug_rect (const char *cap, fz_rect r)
225 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
228 static void UNUSED debug_bbox (const char *cap, fz_bbox r)
230 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
233 static void UNUSED debug_matrix (const char *cap, fz_matrix m)
235 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
236 m.a, m.b, m.c, m.d, m.e, m.f);
239 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
241 static void lock (const char *cap)
243 int ret = pthread_mutex_lock (&mutex);
244 if (ret) {
245 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
249 static void unlock (const char *cap)
251 int ret = pthread_mutex_unlock (&mutex);
252 if (ret) {
253 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
257 static int trylock (const char *cap)
259 int ret = pthread_mutex_trylock (&mutex);
261 if (ret && ret != EBUSY) {
262 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
264 return ret == EBUSY;
267 static void *parse_pointer (const char *cap, const char *s)
269 int ret;
270 void *ptr;
272 ret = sscanf (s, "%" FMT_ptr, FMT_ptr_cast (&ptr));
273 if (ret != 1) {
274 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
276 return ptr;
279 static double now (void)
281 struct timeval tv;
283 if (gettimeofday (&tv, NULL)) {
284 err (1, "gettimeofday");
286 return tv.tv_sec + tv.tv_usec*1e-6;
289 static int hasdata (void)
291 int ret, avail;
292 ret = ioctl (state.cr, FIONREAD, &avail);
293 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
294 return avail > 0;
297 CAMLprim value ml_hasdata (value fd_v)
299 CAMLparam1 (fd_v);
300 int ret, avail;
302 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
303 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
304 CAMLreturn (Val_bool (avail > 0));
307 static void readdata (void *p, int size)
309 ssize_t n;
311 n = read (state.cr, p, size);
312 if (n - size) {
313 if (!n) errx (1, "EOF while reading");
314 err (1, "read (req %d, ret %zd)", size, n);
318 static void writedata (char *p, int size)
320 char buf[4];
321 ssize_t n;
323 buf[0] = (size >> 24) & 0xff;
324 buf[1] = (size >> 16) & 0xff;
325 buf[2] = (size >> 8) & 0xff;
326 buf[3] = (size >> 0) & 0xff;
328 n = write (state.cw, buf, 4);
329 if (n != 4) {
330 if (!n) errx (1, "EOF while writing length");
331 err (1, "write %zd", n);
334 n = write (state.cw, p, size);
335 if (n - size) {
336 if (!n) errx (1, "EOF while writing data");
337 err (1, "write (req %d, ret %zd)", size, n);
341 static int readlen (void)
343 unsigned char p[4];
345 readdata (p, 4);
346 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
349 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
351 int size = 200, len;
352 va_list ap;
353 char *buf;
355 buf = malloc (size);
356 for (;;) {
357 if (!buf) err (errno, "malloc for temp buf (%d bytes) failed", size);
359 va_start (ap, fmt);
360 len = vsnprintf (buf, size, fmt, ap);
361 va_end (ap);
363 if (len > -1 && len < size) {
364 writedata (buf, len);
365 break;
368 if (len > -1) {
369 size = len + 1;
371 else {
372 size *= 2;
374 buf = realloc (buf, size);
376 free (buf);
379 static void closepdf (void)
381 if (state.u.pdf) {
382 pdf_close_document (state.u.pdf);
383 state.u.pdf = NULL;
387 static void closexps (void)
389 if (state.u.xps) {
390 xps_close_document (state.u.xps);
391 state.u.xps = NULL;
395 static void closecbz (void)
397 if (state.u.cbz) {
398 cbz_close_document (state.u.cbz);
399 state.u.cbz = NULL;
403 static void freepdfpage (void *ptr)
405 pdf_free_page (state.u.pdf, ptr);
408 static void freexpspage (void *ptr)
410 xps_free_page (state.u.xps, ptr);
413 static void freecbzpage (void *ptr)
415 cbz_free_page (state.u.cbz, ptr);
418 static void openxref (char *filename, char *password)
420 int i, len;
422 for (i = 0; i < state.texcount; ++i) {
423 state.texowners[i].w = -1;
424 state.texowners[i].slice = NULL;
427 if (state.closedoc) state.closedoc ();
429 len = strlen (filename);
431 state.type = DPDF;
432 if (len > 4) {
433 char ext[4];
435 ext[0] = tolower ((int) filename[len-3]);
436 ext[1] = tolower ((int) filename[len-2]);
437 ext[2] = tolower ((int) filename[len-1]);
439 /**/ if (ext[0] == 'x' && ext[1] == 'p' && ext[2] == 's') {
440 state.type = DXPS;
442 else if (ext[0] == 'c' && ext[1] == 'b' && ext[2] == 'z') {
443 state.type = DCBZ;
447 if (state.pagedims) {
448 free (state.pagedims);
449 state.pagedims = NULL;
451 state.pagedimcount = 0;
453 fz_set_aa_level (state.ctx, state.aalevel);
454 switch (state.type) {
455 case DPDF:
456 state.u.pdf = pdf_open_document (state.ctx, filename);
457 if (pdf_needs_password (state.u.pdf)) {
458 int okay = pdf_authenticate_password (state.u.pdf, password);
459 if (!okay) {
460 errx (1, "invalid password");
463 state.pagecount = pdf_count_pages (state.u.pdf);
464 state.closedoc = closepdf;
465 state.freepage = freepdfpage;
466 break;
468 case DXPS:
469 state.u.xps = xps_open_document (state.ctx, filename);
470 state.pagecount = xps_count_pages (state.u.xps);
471 state.closedoc = closexps;
472 state.freepage = freexpspage;
473 break;
475 case DCBZ:
476 state.u.cbz = cbz_open_document (state.ctx, filename);
477 state.pagecount = cbz_count_pages (state.u.cbz);
478 state.closedoc = closecbz;
479 state.freepage = freecbzpage;
480 break;
484 static void pdfinfo (void)
486 if (state.type == DPDF) {
487 pdf_obj *infoobj;
489 printd ("info PDF version\t%d.%d",
490 state.u.pdf->version / 10, state.u.pdf->version % 10);
492 infoobj = pdf_dict_gets (state.u.pdf->trailer, "Info");
493 if (infoobj) {
494 int i;
495 char *s;
496 char *items[] = { "Title", "Author", "Creator",
497 "Producer", "CreationDate" };
499 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
500 pdf_obj *obj = pdf_dict_gets (infoobj, items[i]);
501 s = pdf_to_utf8 (state.ctx, obj);
502 if (*s) {
503 if (i == 0) {
504 printd ("title %s", s);
506 printd ("info %s\t%s", items[i], s);
508 fz_free (state.ctx, s);
511 printd ("infoend");
515 static void unlinktile (struct tile *tile)
517 int i;
519 for (i = 0; i < tile->slicecount; ++i) {
520 struct slice *s = &tile->slices[i];
522 if (s->texindex != -1) {
523 if (state.texowners[s->texindex].slice == s) {
524 state.texowners[s->texindex].slice = NULL;
530 static void freepage (struct page *page)
532 if (page->text) {
533 fz_free_text_span (state.ctx, page->text);
535 if (page->slinks) {
536 free (page->slinks);
538 page->freepage (page->u.ptr);
539 fz_free_display_list (state.ctx, page->dlist);
540 free (page);
543 static void freetile (struct tile *tile)
545 unlinktile (tile);
546 #ifndef PIGGYBACK
547 fz_drop_pixmap (state.ctx, tile->pixmap);
548 #else
549 if (state.pig) {
550 fz_drop_pixmap (state.ctx, state.pig);
552 state.pig = tile->pixmap;
553 #endif
554 free (tile);
557 #ifdef __ALTIVEC__
558 #include <altivec.h>
560 static int cacheline32bytes;
561 extern char **environ;
563 static void __attribute__ ((constructor)) clcheck (void)
565 char **envp = environ;
566 unsigned long *auxv;
568 while (*envp++);
570 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
571 if (*auxv == 19) {
572 cacheline32bytes = auxv[1] == 32;
573 return;
578 static void OPTIMIZE (3) clearpixmap (fz_pixmap *pixmap)
580 if (cacheline32bytes) {
581 intptr_t a1, a2, diff;
582 size_t sizea, i, size = pixmap->w * pixmap->h * pixmap->n;
583 vector unsigned char v = vec_splat_u8 (-1);
584 vector unsigned char *p;
586 a1 = a2 = (intptr_t) pixmap->samples;
587 a2 = (a1 + 31) & ~31;
588 diff = a2 - a1;
589 sizea = size - diff;
590 p = (void *) a2;
592 while (a1 != a2) *(char *) a1++ = 0xff;
593 for (i = 0; i < (sizea & ~31); i += 32) {
594 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
595 vec_st (v, i, p);
596 vec_st (v, i + 16, p);
598 while (i < sizea) *((char *) a1 + i++) = 0xff;
600 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
602 #else
603 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
604 #endif
606 static fz_matrix trimctm (pdf_page *page, int pindex)
608 fz_matrix ctm;
609 struct pagedim *pdim = &state.pagedims[pindex];
611 if (!pdim->tctmready) {
612 if (state.trimmargins) {
613 fz_rect realbox;
615 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
616 realbox = fz_transform_rect (ctm, pdim->mediabox);
617 ctm = fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0));
618 ctm = fz_concat (fz_invert_matrix (page->ctm), ctm);
620 else {
621 ctm = fz_identity;
623 pdim->tctm = ctm;
624 pdim->tctmready = 1;
626 return pdim->tctm;
629 static fz_matrix pagectm (struct page *page)
631 if (page->type == DPDF) {
632 return fz_concat (trimctm (page->u.pdfpage, page->pdimno),
633 state.pagedims[page->pdimno].ctm);
635 else {
636 fz_matrix ctm;
637 struct pagedim *pdim = &state.pagedims[page->pdimno];
639 ctm = state.pagedims[page->pdimno].ctm;
640 ctm = fz_concat (fz_translate (-pdim->mediabox.x0,
641 -pdim->mediabox.y0), ctm);
642 return ctm;
646 static void *loadpage (int pageno, int pindex)
648 fz_device *dev;
649 struct page *page = NULL;
651 page = calloc (sizeof (struct page), 1);
652 if (!page) {
653 err (1, "calloc page %d", pageno);
656 page->dlist = fz_new_display_list (state.ctx);
657 dev = fz_new_list_device (state.ctx, page->dlist);
658 switch (state.type) {
659 case DPDF:
660 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
661 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, fz_identity, NULL);
662 page->freepage = freepdfpage;
663 break;
665 case DXPS:
666 page->u.xpspage = xps_load_page (state.u.xps, pageno);
667 xps_run_page (state.u.xps, page->u.xpspage, dev, fz_identity, NULL);
668 page->freepage = freexpspage;
669 break;
671 case DCBZ:
672 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
673 cbz_run_page (state.u.cbz, page->u.cbzpage, dev, fz_identity, NULL);
674 page->freepage = freecbzpage;
675 break;
677 fz_free_device (dev);
679 page->pdimno = pindex;
680 page->pageno = pageno;
681 page->sgen = state.gen;
682 page->tgen = state.gen;
683 page->type = state.type;
685 return page;
688 static struct tile *alloctile (int h)
690 int i;
691 int slicecount;
692 size_t tilesize;
693 struct tile *tile;
695 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
696 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
697 tile = calloc (tilesize, 1);
698 if (!tile) {
699 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
701 for (i = 0; i < slicecount; ++i) {
702 int sh = MIN (h, state.sliceheight);
703 tile->slices[i].h = sh;
704 tile->slices[i].texindex = -1;
705 h -= sh;
707 tile->slicecount = slicecount;
708 tile->sliceheight = state.sliceheight;
709 return tile;
712 struct obs {
713 int cured;
714 fz_bbox b;
717 static void obs_fill_image (fz_device *dev, fz_image *image, fz_matrix ctm,
718 float alpha)
720 struct obs *obs = dev->user;
722 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
723 fz_bbox b = fz_round_rect (fz_transform_rect (ctm, fz_unit_rect));
724 b = fz_intersect_bbox (b, obs->b);
725 obs->cured = b.x0 == obs->b.x0
726 && b.x1 == obs->b.x1
727 && b.y0 == obs->b.y0
728 && b.y1 == obs->b.y1;
732 static int obscured (struct page *page, fz_bbox bbox)
734 fz_device dev;
735 struct obs obs;
737 memset (&dev, 0, sizeof (dev));
738 memset (&obs, 0, sizeof (obs));
739 dev.hints = 0;
740 dev.flags = 0;
741 dev.user = &obs;
742 dev.fill_image = obs_fill_image;
743 obs.b = bbox;
744 fz_run_display_list (page->dlist, &dev, pagectm (page), bbox, NULL);
745 return obs.cured;
748 static struct tile *rendertile (struct page *page, int x, int y, int w, int h)
750 fz_bbox bbox;
751 fz_device *dev;
752 struct tile *tile;
753 struct pagedim *pdim;
755 tile = alloctile (h);
756 pdim = &state.pagedims[page->pdimno];
758 bbox = pdim->bounds;
759 bbox.x0 += x;
760 bbox.y0 += y;
761 bbox.x1 = bbox.x0 + w;
762 bbox.y1 = bbox.y0 + h;
764 if (state.pig) {
765 if (state.pig->w == w
766 && state.pig->h == h
767 && state.pig->colorspace == state.colorspace) {
768 tile->pixmap = state.pig;
769 tile->pixmap->x = bbox.x0;
770 tile->pixmap->y = bbox.y0;
772 else {
773 fz_drop_pixmap (state.ctx, state.pig);
775 state.pig = NULL;
777 if (!tile->pixmap) {
778 tile->pixmap =
779 fz_new_pixmap_with_rect (state.ctx, state.colorspace, bbox);
782 tile->w = w;
783 tile->h = h;
784 if ((w < 128 && h < 128) || !obscured (page, bbox)) {
785 clearpixmap (tile->pixmap);
787 dev = fz_new_draw_device (state.ctx, tile->pixmap);
788 fz_run_display_list (page->dlist, dev, pagectm (page), bbox, NULL);
789 fz_free_device (dev);
791 return tile;
794 static void initpdims (void)
796 int pageno;
797 double start, end;
799 start = now ();
800 for (pageno = 0; pageno < state.pagecount; ++pageno) {
801 int rotate;
802 struct pagedim *p;
803 fz_rect mediabox;
805 switch (state.type) {
806 case DPDF: {
807 pdf_obj *pageobj = state.u.pdf->page_objs[pageno];
809 if (state.trimmargins) {
810 pdf_obj *obj;
811 pdf_page *page;
813 page = pdf_load_page (state.u.pdf, pageno);
814 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
815 if (state.trimanew || !obj) {
816 fz_rect rect;
817 fz_bbox bbox;
818 fz_matrix ctm;
819 fz_device *dev;
821 dev = fz_new_bbox_device (state.ctx, &bbox);
822 dev->hints |= FZ_IGNORE_SHADE;
823 ctm = fz_invert_matrix (page->ctm);
824 pdf_run_page (state.u.pdf, page, dev, fz_identity, NULL);
825 fz_free_device (dev);
827 rect.x0 = bbox.x0 + state.trimfuzz.x0;
828 rect.x1 = bbox.x1 + state.trimfuzz.x1;
829 rect.y0 = bbox.y0 + state.trimfuzz.y0;
830 rect.y1 = bbox.y1 + state.trimfuzz.y1;
831 rect = fz_transform_rect (ctm, rect);
832 rect = fz_intersect_rect (rect, page->mediabox);
834 if (fz_is_empty_rect (rect)) {
835 mediabox = page->mediabox;
837 else {
838 mediabox = rect;
841 obj = pdf_new_array (state.ctx, 4);
842 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x0));
843 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y0));
844 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x1));
845 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y1));
846 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
848 else {
849 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
850 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
851 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
852 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
855 rotate = page->rotate;
856 pdf_free_page (state.u.pdf, page);
858 printd ("progress %f Trimming %d",
859 (double) (pageno + 1) / state.pagecount,
860 pageno + 1);
862 else {
863 fz_rect cropbox;
865 mediabox = pdf_to_rect (state.ctx,
866 pdf_dict_gets (pageobj, "MediaBox"));
867 if (fz_is_empty_rect (mediabox)) {
868 fprintf (stderr, "cannot find page size for page %d\n",
869 pageno+1);
870 mediabox.x0 = 0;
871 mediabox.y0 = 0;
872 mediabox.x1 = 612;
873 mediabox.y1 = 792;
876 cropbox = pdf_to_rect (state.ctx,
877 pdf_dict_gets (pageobj, "CropBox"));
878 if (!fz_is_empty_rect (cropbox)) {
879 mediabox = fz_intersect_rect (mediabox, cropbox);
881 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
883 break;
886 case DXPS:
888 xps_page *page;
890 page = xps_load_page (state.u.xps, pageno);
891 mediabox = xps_bound_page (state.u.xps, page);
892 rotate = 0;
893 if (state.trimmargins) {
894 fz_rect rect;
895 fz_bbox bbox;
896 fz_device *dev;
898 dev = fz_new_bbox_device (state.ctx, &bbox);
899 dev->hints |= FZ_IGNORE_SHADE;
900 xps_run_page (state.u.xps, page, dev, fz_identity, NULL);
901 fz_free_device (dev);
903 rect.x0 = bbox.x0 + state.trimfuzz.x0;
904 rect.x1 = bbox.x1 + state.trimfuzz.x1;
905 rect.y0 = bbox.y0 + state.trimfuzz.y0;
906 rect.y1 = bbox.y1 + state.trimfuzz.y1;
907 rect = fz_intersect_rect (rect, mediabox);
909 if (!fz_is_empty_rect (rect)) {
910 mediabox = rect;
913 xps_free_page (state.u.xps, page);
914 printd ("progress %f loading %d",
915 (double) (pageno + 1) / state.pagecount,
916 pageno + 1);
918 break;
920 case DCBZ:
922 rotate = 0;
923 if (state.trimmargins) {
924 cbz_page *page;
926 page = cbz_load_page (state.u.cbz, pageno);
927 mediabox = cbz_bound_page (state.u.cbz, page);
928 cbz_free_page (state.u.cbz, page);
929 printd ("progress %f Trimming %d",
930 (double) (pageno + 1) / state.pagecount,
931 pageno + 1);
933 else {
934 mediabox.x0 = mediabox.y0 = 0;
935 mediabox.x1 = 900;
936 mediabox.y1 = 900;
939 break;
941 default:
942 ARSERT (0 && state.type);
945 if (state.pagedimcount == 0
946 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
947 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
948 size_t size;
950 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
951 state.pagedims = realloc (state.pagedims, size);
952 if (!state.pagedims) {
953 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
954 size, state.pagedimcount + 1);
957 p = &state.pagedims[state.pagedimcount++];
958 p->rotate = rotate;
959 p->mediabox = mediabox;
960 p->pageno = pageno;
963 end = now ();
964 if (state.trimmargins) {
965 printd ("progress 1 Trimmed %d pages in %f seconds",
966 state.pagecount, end - start);
968 else {
969 printd ("vmsg Processed %d pages in %f seconds",
970 state.pagecount, end - start);
972 state.trimanew = 0;
975 static void layout (void)
977 int pindex;
978 fz_rect box;
979 fz_matrix ctm;
980 double zoom, w, maxw = 0;
981 struct pagedim *p = state.pagedims;
983 if (state.proportional) {
984 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
985 box = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
986 p->mediabox);
987 w = box.x1 - box.x0;
988 maxw = MAX (w, maxw);
992 p = state.pagedims;
993 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
994 fz_bbox bbox;
996 ctm = fz_rotate (state.rotate);
997 box = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
998 p->mediabox);
999 w = box.x1 - box.x0;
1001 if (state.proportional) {
1002 double scale = w / maxw;
1003 zoom = (state.w / w) * scale;
1005 else {
1006 zoom = state.w / w;
1009 p->zoomctm = fz_scale (zoom, zoom);
1010 ctm = fz_concat (p->zoomctm, ctm);
1012 p->pagebox = fz_transform_rect (fz_rotate (p->rotate), p->mediabox);
1013 p->pagebox.x1 -= p->pagebox.x0;
1014 p->pagebox.y1 -= p->pagebox.y0;
1015 p->pagebox.x0 = 0;
1016 p->pagebox.y0 = 0;
1017 bbox = fz_round_rect (fz_transform_rect (ctm, p->pagebox));
1019 p->bounds = bbox;
1020 p->left = state.proportional ? ((maxw - w) * zoom) / 2.0 : 0;
1021 p->ctm = ctm;
1023 ctm = fz_identity;
1024 ctm = fz_concat (ctm, fz_translate (0, -p->mediabox.y1));
1025 ctm = fz_concat (ctm, fz_scale (zoom, -zoom));
1026 ctm = fz_concat (ctm, fz_rotate (p->rotate + state.rotate));
1027 p->lctm = ctm;
1029 p->tctmready = 0;
1032 while (p-- != state.pagedims) {
1033 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1034 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1035 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1036 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1037 int w = x1 - x0;
1038 int h = y1 - y0;
1040 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1044 static void recurse_outline (fz_outline *outline, int level)
1046 while (outline) {
1047 fz_link_dest *dest;
1048 int i, top = 0;
1049 struct pagedim *pdim = state.pagedims;
1051 dest = &outline->dest;
1052 for (i = 0; i < state.pagedimcount; ++i) {
1053 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1054 break;
1055 pdim = &state.pagedims[i];
1057 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1058 fz_point p;
1059 p.x = 0;
1060 p.y = dest->ld.gotor.lt.y;
1061 p = fz_transform_point (pdim->lctm, p);
1062 top = p.y;
1064 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1065 int h;
1066 double y0, y1;
1068 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1069 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1070 h = y1 - y0;
1071 printd ("o %d %d %d %d %s",
1072 level, dest->ld.gotor.page, top, h, outline->title);
1074 if (outline->down) {
1075 recurse_outline (outline->down, level + 1);
1077 outline = outline->next;
1081 static void process_outline (void)
1083 fz_outline *outline;
1085 if (!state.needoutline) return;
1087 state.needoutline = 0;
1088 switch (state.type) {
1089 case DPDF:
1090 outline = pdf_load_outline (state.u.pdf);
1091 break;
1092 case DXPS:
1093 outline = xps_load_outline (state.u.xps);
1094 break;
1095 default:
1096 outline = NULL;
1097 break;
1099 if (outline) {
1100 recurse_outline (outline, 0);
1101 fz_free_outline (state.ctx, outline);
1105 static int comparespans (const void *l, const void *r)
1107 fz_text_span const *const*ls = l;
1108 fz_text_span const *const*rs = r;
1109 return (*ls)->text->bbox.y0 - (*rs)->text->bbox.y0;
1112 /* wishful thinking function */
1113 static void search (regex_t *re, int pageno, int y, int forward)
1115 int i, j;
1116 int ret;
1117 char *p;
1118 char buf[256];
1119 fz_matrix ctm;
1120 fz_device *tdev;
1121 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1122 fz_text_span *text, *span, **pspan;
1123 struct pagedim *pdim, *pdimprev;
1124 int stop = 0;
1125 int niters = 0;
1126 int nspans;
1127 double start, end;
1129 if (!(state.type == DPDF || state.type == DXPS))
1130 return;
1132 start = now ();
1133 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1134 if (niters++ == 5) {
1135 niters = 0;
1136 if (hasdata ()) {
1137 printd ("progress 1 attention requested aborting search at %d",
1138 pageno);
1139 stop = 1;
1141 else {
1142 printd ("progress %f searching in page %d",
1143 (double) (pageno + 1) / state.pagecount,
1144 pageno);
1147 pdimprev = NULL;
1148 for (i = 0; i < state.pagedimcount; ++i) {
1149 pdim = &state.pagedims[i];
1150 if (pdim->pageno == pageno) {
1151 goto found;
1153 if (pdim->pageno > pageno) {
1154 pdim = pdimprev;
1155 goto found;
1157 pdimprev = pdim;
1159 pdim = pdimprev;
1160 found:
1162 text = fz_new_text_span (state.ctx);
1163 tdev = fz_new_text_device (state.ctx, text);
1165 switch (state.type) {
1166 case DPDF:
1167 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1168 pdf_run_page (state.u.pdf, u.pdfpage, tdev, fz_identity, NULL);
1169 break;
1171 case DXPS:
1172 u.xpspage = xps_load_page (state.u.xps, pageno);
1173 xps_run_page (state.u.xps, u.xpspage, tdev, fz_identity, NULL);
1174 break;
1176 default:
1177 ARSERT (0 && state.type);
1180 fz_free_device (tdev);
1182 nspans = 0;
1183 for (span = text; span; span = span->next) {
1184 nspans++;
1186 pspan = malloc (sizeof (void *) * nspans);
1187 if (!pspan) {
1188 err (1, "malloc span pointers %" FMT_s, sizeof (void *) * nspans);
1190 for (i = 0, span = text; span; span = span->next, ++i) {
1191 pspan[i] = span;
1193 qsort (pspan, nspans, sizeof (fz_text_span *), comparespans);
1195 j = forward ? 0 : nspans - 1;
1196 while (nspans--) {
1197 regmatch_t rm;
1199 span = pspan[j];
1200 j += forward ? 1 : -1;
1201 p = buf;
1202 for (i = 0; i < span->len; ++i) {
1203 int len;
1204 char cbuf[4];
1206 if (forward) {
1207 if (span->text[i].bbox.y0 < y + 1) {
1208 continue;
1211 else {
1212 if (span->text[i].bbox.y0 > y - 1) {
1213 continue;
1216 len = runetochar (cbuf, &span->text[i].c);
1217 if (sizeof (buf) - 1 - (p - buf) > len) {
1218 int k;
1219 for (k = 0; k < len; ++k)
1220 *p++ = cbuf[k];
1222 else {
1223 break;
1226 if (p == buf) {
1227 continue;
1229 *p++ = 0;
1231 ret = regexec (re, buf, 1, &rm, 0);
1232 if (ret) {
1233 if (ret != REG_NOMATCH) {
1234 size_t size;
1235 char errbuf[80];
1236 size = regerror (ret, re, errbuf, sizeof (errbuf));
1237 printd ("msg regexec error `%.*s'",
1238 (int) size, errbuf);
1239 fz_free_text_span (state.ctx, text);
1240 state.freepage (u.ptr);
1241 free (pspan);
1242 return;
1245 else {
1246 fz_bbox *sb, *eb;
1247 fz_point p1, p2, p3, p4;
1248 int a, b, c, l;
1250 l = span->len;
1251 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1252 c += runelen (span->text[a].c);
1254 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1255 c += runelen (span->text[b].c);
1258 if (runelen (span->text[b].c) > 1) {
1259 b = MAX (0, b-1);
1261 sb = &span->text[MIN (a, l-1)].bbox;
1262 eb = &span->text[MIN (b, l-1)].bbox;
1264 p1.x = sb->x0;
1265 p1.y = sb->y0;
1266 p2.x = eb->x1;
1267 p2.y = sb->y0;
1268 p3.x = eb->x1;
1269 p3.y = eb->y1;
1270 p4.x = sb->x0;
1271 p4.y = eb->y1;
1273 switch (state.type) {
1274 case DPDF:
1275 trimctm (u.pdfpage, pdim - state.pagedims);
1276 ctm = fz_concat (pdim->tctm, pdim->zoomctm);
1277 break;
1279 case DXPS:
1280 ctm = pdim->ctm;
1281 break;
1284 p1 = fz_transform_point (ctm, p1);
1285 p2 = fz_transform_point (ctm, p2);
1286 p3 = fz_transform_point (ctm, p3);
1287 p4 = fz_transform_point (ctm, p4);
1289 if (!stop) {
1290 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1291 pageno, 1,
1292 p1.x, p1.y,
1293 p2.x, p2.y,
1294 p3.x, p3.y,
1295 p4.x, p4.y);
1297 printd ("progress 1 found at %d `%.*s' in %f sec",
1298 pageno, (int) (rm.rm_eo - rm.rm_so), &buf[rm.rm_so],
1299 now () - start);
1301 else {
1302 printd ("match %d %d %f %f %f %f %f %f %f %f",
1303 pageno, 2,
1304 p1.x, p1.y,
1305 p2.x, p2.y,
1306 p3.x, p3.y,
1307 p4.x, p4.y);
1309 stop = 1;
1312 if (forward) {
1313 pageno += 1;
1314 y = 0;
1316 else {
1317 pageno -= 1;
1318 y = INT_MAX;
1320 fz_free_text_span (state.ctx, text);
1321 state.freepage (u.ptr);
1322 free (pspan);
1324 end = now ();
1325 if (!stop) {
1326 printd ("progress 1 no matches %f sec", end - start);
1328 printd ("clearrects");
1331 static void set_tex_params (int colorspace)
1333 switch (colorspace) {
1334 case 0:
1335 state.texiform = GL_RGBA8;
1336 state.texform = GL_RGBA;
1337 state.texty = GL_UNSIGNED_BYTE;
1338 state.colorspace = fz_device_rgb;
1339 break;
1340 case 1:
1341 state.texiform = GL_RGBA8;
1342 state.texform = GL_BGRA;
1343 state.texty = fz_is_big_endian ()
1344 ? GL_UNSIGNED_INT_8_8_8_8
1345 : GL_UNSIGNED_INT_8_8_8_8_REV;
1346 state.colorspace = fz_device_bgr;
1347 break;
1348 case 2:
1349 state.texiform = GL_LUMINANCE_ALPHA;
1350 state.texform = GL_LUMINANCE_ALPHA;
1351 state.texty = GL_UNSIGNED_BYTE;
1352 state.colorspace = fz_device_gray;
1353 break;
1354 default:
1355 errx (1, "invalid colorspce %d", colorspace);
1359 static void realloctexts (int texcount)
1361 size_t size;
1363 if (texcount == state.texcount) return;
1365 if (texcount < state.texcount) {
1366 glDeleteTextures (state.texcount - texcount,
1367 state.texids + texcount);
1370 size = texcount * sizeof (*state.texids);
1371 state.texids = realloc (state.texids, size);
1372 if (!state.texids) {
1373 err (1, "realloc texids %" FMT_s, size);
1376 size = texcount * sizeof (*state.texowners);
1377 state.texowners = realloc (state.texowners, size);
1378 if (!state.texowners) {
1379 err (1, "realloc texowners %" FMT_s, size);
1381 if (texcount > state.texcount) {
1382 int i;
1384 glGenTextures (texcount - state.texcount,
1385 state.texids + state.texcount);
1386 for (i = state.texcount; i < texcount; ++i) {
1387 state.texowners[i].w = -1;
1388 state.texowners[i].slice = NULL;
1391 state.texcount = texcount;
1392 state.texindex = 0;
1395 static void * mainloop (void *unused)
1397 char *p = NULL;
1398 int len, ret, oldlen = 0;
1400 for (;;) {
1401 len = readlen ();
1402 if (len == 0) {
1403 errx (1, "readlen returned 0");
1406 if (oldlen < len + 1) {
1407 p = realloc (p, len + 1);
1408 if (!p) {
1409 err (1, "realloc %d failed", len + 1);
1411 oldlen = len + 1;
1413 readdata (p, len);
1414 p[len] = 0;
1416 if (!strncmp ("open", p, 4)) {
1417 size_t filenamelen;
1418 char *password;
1419 char *filename = p + 5;
1421 filenamelen = strlen (filename);
1422 password = filename + filenamelen + 1;
1424 openxref (filename, password);
1425 pdfinfo ();
1426 initpdims ();
1427 printd ("msg Opened %s (press h/F1 to get help)", filename);
1428 state.needoutline = 1;
1430 else if (!strncmp ("cs", p, 2)) {
1431 int i, colorspace;
1433 ret = sscanf (p + 2, " %d", &colorspace);
1434 if (ret != 1) {
1435 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1437 lock ("cs");
1438 set_tex_params (colorspace);
1439 for (i = 0; i < state.texcount; ++i) {
1440 state.texowners[i].w = -1;
1441 state.texowners[i].slice = NULL;
1443 unlock ("cs");
1445 else if (!strncmp ("freepage", p, 8)) {
1446 void *ptr;
1448 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1449 if (ret != 1) {
1450 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1452 freepage (ptr);
1454 else if (!strncmp ("freetile", p, 8)) {
1455 void *ptr;
1457 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1458 if (ret != 1) {
1459 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1461 freetile (ptr);
1463 else if (!strncmp ("search", p, 6)) {
1464 int icase, pageno, y, ret, len2, forward;
1465 char *pattern;
1466 regex_t re;
1468 ret = sscanf (p + 6, " %d %d %d %d,%n",
1469 &icase, &pageno, &y, &forward, &len2);
1470 if (ret != 4) {
1471 errx (1, "malformed search `%s' ret=%d", p, ret);
1474 pattern = p + 6 + len2;
1475 ret = regcomp (&re, pattern,
1476 REG_EXTENDED | (icase ? REG_ICASE : 0));
1477 if (ret) {
1478 char errbuf[80];
1479 size_t size;
1481 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1482 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1484 else {
1485 search (&re, pageno, y, forward);
1486 regfree (&re);
1489 else if (!strncmp ("geometry", p, 8)) {
1490 int w, h;
1492 printd ("clear");
1493 ret = sscanf (p + 8, " %d %d", &w, &h);
1494 if (ret != 2) {
1495 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1498 lock ("geometry");
1499 state.h = h;
1500 if (w != state.w) {
1501 int i;
1502 state.w = w;
1503 for (i = 0; i < state.texcount; ++i) {
1504 state.texowners[i].slice = NULL;
1507 layout ();
1508 process_outline ();
1509 state.gen++;
1510 unlock ("geometry");
1511 printd ("continue %d", state.pagecount);
1513 else if (!strncmp ("reqlayout", p, 9)) {
1514 int rotate, proportional;
1516 printd ("clear");
1517 ret = sscanf (p + 9, " %d %d", &rotate, &proportional);
1518 if (ret != 2) {
1519 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1521 lock ("reqlayout");
1522 if (state.rotate != rotate || state.proportional != proportional) {
1523 state.gen += 1;
1525 state.rotate = rotate;
1526 state.proportional = proportional;
1527 layout ();
1528 process_outline ();
1529 state.gen++;
1530 unlock ("reqlayout");
1531 printd ("continue %d", state.pagecount);
1533 else if (!strncmp ("page", p, 4)) {
1534 double a, b;
1535 struct page *page;
1536 int pageno, pindex, ret;
1538 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1539 if (ret != 2) {
1540 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1543 lock ("page");
1544 a = now ();
1545 page = loadpage (pageno, pindex);
1546 b = now ();
1547 unlock ("page");
1549 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1551 else if (!strncmp ("tile", p, 4)) {
1552 int x, y, w, h, ret;
1553 struct page *page;
1554 struct tile *tile;
1555 double a, b;
1557 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d",
1558 FMT_ptr_cast (&page), &x, &y, &w, &h);
1559 if (ret != 5) {
1560 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1563 lock ("tile");
1564 a = now ();
1565 tile = rendertile (page, x, y, w, h);
1566 b = now ();
1567 unlock ("tile");
1569 printd ("tile %d %d %" FMT_ptr " %u %f",
1570 x, y,
1571 FMT_ptr_cast2 (tile),
1572 tile->w * tile->h * tile->pixmap->n,
1573 b - a);
1575 else if (!strncmp ("settrim", p, 7)) {
1576 int trimmargins;
1577 fz_bbox fuzz;
1579 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1580 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1581 if (ret != 5) {
1582 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1584 printd ("clear");
1585 lock ("settrim");
1586 state.trimmargins = trimmargins;
1587 state.needoutline = 1;
1588 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1589 state.trimanew = 1;
1590 state.trimfuzz = fuzz;
1592 state.pagedimcount = 0;
1593 free (state.pagedims);
1594 state.pagedims = NULL;
1595 initpdims ();
1596 layout ();
1597 process_outline ();
1598 unlock ("settrim");
1599 printd ("continue %d", state.pagecount);
1601 else if (!strncmp ("sliceh", p, 6)) {
1602 int h;
1604 ret = sscanf (p + 6, " %d", &h);
1605 if (ret != 1) {
1606 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1608 if (h != state.sliceheight) {
1609 int i;
1611 state.sliceheight = h;
1612 for (i = 0; i < state.texcount; ++i) {
1613 state.texowners[i].w = -1;
1614 state.texowners[i].h = -1;
1615 state.texowners[i].slice = NULL;
1619 else if (!strncmp ("interrupt", p, 9)) {
1620 printd ("vmsg interrupted");
1622 else {
1623 errx (1, "unknown command %.*s", len, p);
1626 return 0;
1629 CAMLprim value ml_realloctexts (value texcount_v)
1631 CAMLparam1 (texcount_v);
1632 int ok;
1634 if (trylock ("ml_realloctexts")) {
1635 ok = 0;
1636 goto done;
1638 realloctexts (Int_val (texcount_v));
1639 ok = 1;
1640 unlock ("ml_realloctexts");
1642 done:
1643 CAMLreturn (Val_bool (ok));
1646 static void showsel (struct page *page, int ox, int oy)
1648 fz_bbox bbox;
1649 fz_text_span *span;
1650 struct mark first, last;
1652 first = page->fmark;
1653 last = page->lmark;
1655 if (!first.span || !last.span) return;
1657 glEnable (GL_BLEND);
1658 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1659 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1661 ox += state.pagedims[page->pdimno].bounds.x0;
1662 oy += state.pagedims[page->pdimno].bounds.y0;
1663 for (span = first.span; span; span = span->next) {
1664 int i, j, k;
1666 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1668 j = 0;
1669 k = span->len - 1;
1671 if (span == page->fmark.span && span == page->lmark.span) {
1672 j = MIN (first.i, last.i);
1673 k = MAX (first.i, last.i);
1675 else if (span == first.span) {
1676 j = first.i;
1678 else if (span == last.span) {
1679 k = last.i;
1682 for (i = j; i <= k; ++i) {
1683 bbox = fz_union_bbox (bbox, span->text[i].bbox);
1685 lprintf ("%d %d %d %d oy=%d ox=%d\n",
1686 bbox.x0,
1687 bbox.y0,
1688 bbox.x1,
1689 bbox.y1,
1690 oy, ox);
1692 glRecti (bbox.x0 + ox, bbox.y0 + oy, bbox.x1 + ox, bbox.y1 + oy);
1694 if (span == last.span) break;
1696 glDisable (GL_BLEND);
1699 #include "glfont.c"
1701 static void highlightlinks (struct page *page, int xoff, int yoff)
1703 fz_matrix ctm;
1704 fz_link *link, *links;
1706 switch (page->type) {
1707 case DPDF:
1708 links = page->u.pdfpage->links;
1709 break;
1711 case DXPS:
1712 links = page->u.xpspage->links;
1713 break;
1715 default:
1716 return;
1719 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
1720 glEnable (GL_LINE_STIPPLE);
1721 glLineStipple (0.5, 0xcccc);
1723 xoff -= state.pagedims[page->pdimno].bounds.x0;
1724 yoff -= state.pagedims[page->pdimno].bounds.y0;
1725 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1727 glBegin (GL_QUADS);
1728 for (link = links; link; link = link->next) {
1729 fz_point p1, p2, p3, p4;
1731 p1.x = link->rect.x0;
1732 p1.y = link->rect.y0;
1734 p2.x = link->rect.x1;
1735 p2.y = link->rect.y0;
1737 p3.x = link->rect.x1;
1738 p3.y = link->rect.y1;
1740 p4.x = link->rect.x0;
1741 p4.y = link->rect.y1;
1743 p1 = fz_transform_point (ctm, p1);
1744 p2 = fz_transform_point (ctm, p2);
1745 p3 = fz_transform_point (ctm, p3);
1746 p4 = fz_transform_point (ctm, p4);
1748 switch (link->dest.kind) {
1749 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
1750 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
1751 default: glColor3ub (0, 0, 0); break;
1754 glVertex2f (p1.x, p1.y);
1755 glVertex2f (p2.x, p2.y);
1756 glVertex2f (p3.x, p3.y);
1757 glVertex2f (p4.x, p4.y);
1759 glEnd ();
1761 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
1762 glDisable (GL_LINE_STIPPLE);
1765 static int compareslinks (const void *l, const void *r)
1767 struct slink const *ls = l;
1768 struct slink const *rs = r;
1769 if (ls->bbox.y0 == rs->bbox.y0) {
1770 return rs->bbox.x0 - rs->bbox.x0;
1772 return ls->bbox.y0 - rs->bbox.y0;
1775 static void droptext (struct page *page)
1777 if (page->text) {
1778 fz_free_text_span (state.ctx, page->text);
1779 page->fmark.i = -1;
1780 page->lmark.i = -1;
1781 page->fmark.span = NULL;
1782 page->lmark.span = NULL;
1783 page->text = NULL;
1787 static void dropslinks (struct page *page)
1789 if (page->slinks) {
1790 free (page->slinks);
1791 page->slinks = NULL;
1792 page->slinkcount = 0;
1796 static void ensureslinks (struct page *page)
1798 fz_matrix ctm;
1799 int i, count = 0;
1800 size_t slinksize = sizeof (*page->slinks);
1801 fz_link *link, *links;
1803 if (state.gen != page->sgen) {
1804 dropslinks (page);
1805 page->sgen = state.gen;
1807 if (page->slinks) return;
1809 switch (page->type) {
1810 case DPDF:
1811 links = page->u.pdfpage->links;
1812 ctm = fz_concat (trimctm (page->u.pdfpage, page->pdimno),
1813 state.pagedims[page->pdimno].ctm);
1814 break;
1816 case DXPS:
1817 links = page->u.xpspage->links;
1818 ctm = state.pagedims[page->pdimno].ctm;
1819 break;
1821 default:
1822 return;
1825 for (link = links; link; link = link->next) {
1826 count++;
1828 if (count > 0) {
1829 page->slinkcount = count;
1830 page->slinks = calloc (count, slinksize);
1831 if (!page->slinks) {
1832 err (1, "realloc slinks %d", count);
1835 for (i = 0, link = links; link; ++i, link = link->next) {
1836 page->slinks[i].link = link;
1837 page->slinks[i].bbox =
1838 fz_round_rect (fz_transform_rect (ctm, link->rect));
1840 qsort (page->slinks, count, slinksize, compareslinks);
1844 /* slightly tweaked fmt_ulong by D.J. Bernstein */
1845 static void fmt_linkn (char *s, unsigned int u)
1847 unsigned int len; unsigned int q;
1848 int zma = 'z' - 'a' + 1;
1849 len = 1; q = u;
1850 while (q > zma - 1) { ++len; q /= zma; }
1851 if (s) {
1852 s += len;
1853 do { *--s = 'a' + (u % zma); u /= zma; } while(u); /* handles u == 0 */
1855 s[len] = 0;
1858 static void highlightslinks (struct page *page, int xoff, int yoff, int noff)
1860 int i;
1861 char buf[40];
1862 struct slink *slink;
1863 double x0, y0, x1, y1, w;
1865 ensureslinks (page);
1866 glColor3ub (0xc3, 0xb0, 0x91);
1867 for (i = 0; i < page->slinkcount; ++i) {
1868 slink = &page->slinks[i];
1870 fmt_linkn (buf, i + noff);
1871 x0 = slink->bbox.x0 + xoff - 5;
1872 y1 = slink->bbox.y0 + yoff - 5;
1873 y0 = y1 + 22;
1874 w = measure_string (state.face, 12, buf);
1875 x1 = x0 + w + 10;
1876 glRectd (x0, y0, x1, y1);
1879 glEnable (GL_BLEND);
1880 glEnable (GL_TEXTURE_2D);
1881 glColor3ub (0, 0, 0);
1882 for (i = 0; i < page->slinkcount; ++i) {
1883 slink = &page->slinks[i];
1885 fmt_linkn (buf, i + noff);
1886 x0 = slink->bbox.x0 + xoff;
1887 y0 = slink->bbox.y0 + yoff + 12;
1888 draw_string (state.face, 12, x0, y0, buf);
1890 glDisable (GL_TEXTURE_2D);
1891 glDisable (GL_BLEND);
1894 static void uploadslice (struct tile *tile, struct slice *slice)
1896 int offset;
1897 struct slice *slice1;
1899 offset = 0;
1900 for (slice1 = tile->slices; slice != slice1; slice1++) {
1901 offset += slice1->h * tile->w * tile->pixmap->n;
1903 if (slice->texindex != -1 && slice->texindex < state.texcount
1904 && state.texowners[slice->texindex].slice == slice) {
1905 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
1907 else {
1908 int subimage = 0;
1909 int texindex = state.texindex++ % state.texcount;
1911 if (state.texowners[texindex].w == tile->w) {
1912 if (state.texowners[texindex].h >= slice->h) {
1913 subimage = 1;
1915 else {
1916 state.texowners[texindex].h = slice->h;
1919 else {
1920 state.texowners[texindex].h = slice->h;
1923 state.texowners[texindex].w = tile->w;
1924 state.texowners[texindex].slice = slice;
1925 slice->texindex = texindex;
1927 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
1928 if (subimage) {
1929 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
1933 tile->w,
1934 slice->h,
1935 state.texform,
1936 state.texty,
1937 tile->pixmap->samples+offset
1940 else {
1941 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
1943 state.texiform,
1944 tile->w,
1945 slice->h,
1947 state.texform,
1948 state.texty,
1949 tile->pixmap->samples+offset
1955 CAMLprim value ml_drawtile (value args_v, value ptr_v)
1957 CAMLparam2 (args_v, ptr_v);
1958 int dispx = Int_val (Field (args_v, 0));
1959 int dispy = Int_val (Field (args_v, 1));
1960 int dispw = Int_val (Field (args_v, 2));
1961 int disph = Int_val (Field (args_v, 3));
1962 int tilex = Int_val (Field (args_v, 4));
1963 int tiley = Int_val (Field (args_v, 5));
1964 char *s = String_val (ptr_v);
1965 struct tile *tile = parse_pointer ("ml_drawtile", s);
1967 glEnable (GL_TEXTURE_RECTANGLE_ARB);
1969 int slicey, firstslice;
1970 struct slice *slice;
1972 firstslice = tiley / tile->sliceheight;
1973 slice = &tile->slices[firstslice];
1974 slicey = tiley % tile->sliceheight;
1976 while (disph > 0) {
1977 int dh;
1979 dh = slice->h - slicey;
1980 dh = MIN (disph, dh);
1981 uploadslice (tile, slice);
1983 glBegin (GL_QUADS);
1985 glTexCoord2i (tilex, slicey);
1986 glVertex2i (dispx, dispy);
1988 glTexCoord2i (tilex+dispw, slicey);
1989 glVertex2i (dispx+dispw, dispy);
1991 glTexCoord2i (tilex+dispw, slicey+dh);
1992 glVertex2i (dispx+dispw, dispy+dh);
1994 glTexCoord2i (tilex, slicey+dh);
1995 glVertex2i (dispx, dispy+dh);
1997 glEnd ();
1999 dispy += dh;
2000 disph -= dh;
2001 slice++;
2002 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2003 slicey = 0;
2006 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2007 CAMLreturn (Val_unit);
2010 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2011 value xoff_v, value yoff_v,
2012 value noff_v)
2014 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, noff_v);
2015 int xoff = Int_val (xoff_v);
2016 int yoff = Int_val (yoff_v);
2017 int noff = Int_val (noff_v);
2018 char *s = String_val (ptr_v);
2019 int hlmask = Int_val (hlinks_v);
2020 struct page *page = parse_pointer ("ml_postprocess", s);
2022 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2023 if (trylock ("ml_postprocess")) {
2024 noff = 0;
2025 goto done;
2027 if (hlmask & 2) {
2028 highlightslinks (page, xoff, yoff, noff);
2029 noff = page->slinkcount;
2031 showsel (page, xoff, yoff);
2032 unlock ("ml_postprocess");
2034 done:
2035 CAMLreturn (Val_int (noff));
2038 static fz_link *getlink (struct page *page, int x, int y)
2040 fz_point p;
2041 fz_matrix ctm;
2042 fz_link *link, *links;
2044 switch (page->type) {
2045 case DPDF:
2046 ctm = trimctm (page->u.pdfpage, page->pdimno);
2047 links = page->u.pdfpage->links;
2048 break;
2050 case DXPS:
2051 ctm = fz_identity;
2052 links = page->u.xpspage->links;
2053 break;
2055 default:
2056 return NULL;
2058 p.x = x;
2059 p.y = y;
2061 ctm = fz_concat (ctm, state.pagedims[page->pdimno].ctm);
2062 ctm = fz_invert_matrix (ctm);
2063 p = fz_transform_point (ctm, p);
2065 for (link = links; link; link = link->next) {
2066 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2067 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2068 return link;
2072 return NULL;
2075 static void ensuretext (struct page *page)
2077 if (state.gen != page->tgen) {
2078 droptext (page);
2079 page->tgen = state.gen;
2081 if (!page->text) {
2082 fz_device *tdev;
2084 page->text = fz_new_text_span (state.ctx);
2085 tdev = fz_new_text_device (state.ctx, page->text);
2086 fz_run_display_list (page->dlist,
2087 tdev,
2088 pagectm (page),
2089 fz_infinite_bbox, NULL);
2090 fz_free_device (tdev);
2094 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2096 CAMLparam2 (start_page_v, dir_v);
2097 CAMLlocal1 (ret_v);
2098 int i, dir = Int_val (dir_v);
2099 int start_page = Int_val (start_page_v);
2100 int end_page = dir > 0 ? state.pagecount : -1;
2102 ret_v = Val_int (0);
2103 if (!(state.type == DPDF || state.type == DXPS)) {
2104 goto done;
2107 lock ("ml_findpage_with_links");
2108 for (i = start_page + dir; i != end_page; i += dir) {
2109 int found;
2111 switch (state.type) {
2112 case DPDF:
2114 pdf_page *page = pdf_load_page (state.u.pdf, i);
2115 found = !!page->links;
2116 freepdfpage (page);
2118 break;
2119 case DXPS:
2121 xps_page *page = xps_load_page (state.u.xps, i);
2122 found = !!page->links;
2123 freexpspage (page);
2125 break;
2127 default:
2128 ARSERT ("invalid document type");
2131 if (found) {
2132 ret_v = caml_alloc_small (1, 1);
2133 Field (ret_v, 0) = Val_int (i);
2134 goto unlock;
2137 unlock:
2138 unlock ("ml_findpage_with_links");
2140 done:
2141 CAMLreturn (ret_v);
2144 enum { dir_first, dir_last};
2145 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2147 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2149 CAMLparam2 (ptr_v, dir_v);
2150 CAMLlocal2 (ret_v, pos_v);
2151 struct page *page;
2152 int dirtag, i, slinkindex;
2153 struct slink *found = NULL ,*slink;
2154 char *s = String_val (ptr_v);
2156 page = parse_pointer ("ml_findlink", s);
2157 ret_v = Val_int (0);
2158 if (trylock ("ml_findlink")) {
2159 goto done;
2162 ensureslinks (page);
2164 if (Is_block (dir_v)) {
2165 dirtag = Tag_val (dir_v);
2166 switch (dirtag) {
2167 case dir_first_visible:
2169 int x0, y0, dir, first_index, last_index;
2171 pos_v = Field (dir_v, 0);
2172 x0 = Int_val (Field (pos_v, 0));
2173 y0 = Int_val (Field (pos_v, 1));
2174 dir = Int_val (Field (pos_v, 2));
2176 if (dir >= 0) {
2177 dir = 1;
2178 first_index = 0;
2179 last_index = page->slinkcount;
2181 else {
2182 first_index = page->slinkcount - 1;
2183 last_index = -1;
2186 for (i = first_index; i != last_index; i += dir) {
2187 slink = &page->slinks[i];
2188 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2189 found = slink;
2190 break;
2194 break;
2196 case dir_left:
2197 slinkindex = Int_val (Field (dir_v, 0));
2198 found = &page->slinks[slinkindex];
2199 for (i = slinkindex - 1; i >= 0; --i) {
2200 slink = &page->slinks[i];
2201 if (slink->bbox.x0 < found->bbox.x0) {
2202 found = slink;
2203 break;
2206 break;
2208 case dir_right:
2209 slinkindex = Int_val (Field (dir_v, 0));
2210 found = &page->slinks[slinkindex];
2211 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2212 slink = &page->slinks[i];
2213 if (slink->bbox.x0 > found->bbox.x0) {
2214 found = slink;
2215 break;
2218 break;
2220 case dir_down:
2221 slinkindex = Int_val (Field (dir_v, 0));
2222 found = &page->slinks[slinkindex];
2223 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2224 slink = &page->slinks[i];
2225 if (slink->bbox.y0 >= found->bbox.y0) {
2226 found = slink;
2227 break;
2230 break;
2232 case dir_up:
2233 slinkindex = Int_val (Field (dir_v, 0));
2234 found = &page->slinks[slinkindex];
2235 for (i = slinkindex - 1; i >= 0; --i) {
2236 slink = &page->slinks[i];
2237 if (slink->bbox.y0 <= found->bbox.y0) {
2238 found = slink;
2239 break;
2242 break;
2245 else {
2246 dirtag = Int_val (dir_v);
2247 switch (dirtag) {
2248 case dir_first:
2249 found = page->slinks;
2250 break;
2252 case dir_last:
2253 if (page->slinks) {
2254 found = page->slinks + (page->slinkcount - 1);
2256 break;
2259 if (found) {
2260 ret_v = caml_alloc_small (2, 1);
2261 Field (ret_v, 0) = Val_int (found - page->slinks);
2264 unlock ("ml_findlink");
2265 done:
2266 CAMLreturn (ret_v);
2269 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2271 #define LINKTOVAL \
2273 int pageno; \
2275 switch (link->dest.kind) { \
2276 case FZ_LINK_GOTO: \
2278 fz_point p; \
2280 pageno = link->dest.ld.gotor.page; \
2281 p.x = 0; \
2282 p.y = 0; \
2284 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2285 p.y = link->dest.ld.gotor.lt.y; \
2286 p = fz_transform_point (pdim->lctm, p); \
2288 tup_v = caml_alloc_tuple (2); \
2289 ret_v = caml_alloc_small (1, ugoto); \
2290 Field (tup_v, 0) = Val_int (pageno); \
2291 Field (tup_v, 1) = Val_int (p.y); \
2292 Field (ret_v, 0) = tup_v; \
2294 break; \
2296 case FZ_LINK_URI: \
2297 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2298 ret_v = caml_alloc_small (1, uuri); \
2299 Field (ret_v, 0) = str_v; \
2300 break; \
2302 case FZ_LINK_LAUNCH: \
2303 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2304 ret_v = caml_alloc_small (1, ulaunch); \
2305 Field (ret_v, 0) = str_v; \
2306 break; \
2308 case FZ_LINK_NAMED: \
2309 str_v = caml_copy_string (link->dest.ld.named.named); \
2310 ret_v = caml_alloc_small (1, unamed); \
2311 Field (ret_v, 0) = str_v; \
2312 break; \
2314 case FZ_LINK_GOTOR: \
2315 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2316 pageno = link->dest.ld.gotor.page; \
2317 tup_v = caml_alloc_tuple (2); \
2318 ret_v = caml_alloc_small (1, uremote); \
2319 Field (tup_v, 0) = str_v; \
2320 Field (tup_v, 1) = Val_int (pageno); \
2321 Field (ret_v, 0) = tup_v; \
2322 break; \
2324 default: \
2326 char buf[80]; \
2328 snprintf (buf, sizeof (buf), \
2329 "unhandled link kind %d", link->dest.kind); \
2330 str_v = caml_copy_string (buf); \
2331 ret_v = caml_alloc_small (1, uunexpected); \
2332 Field (ret_v, 0) = str_v; \
2334 break; \
2338 CAMLprim value ml_getlink (value ptr_v, value n_v)
2340 CAMLparam2 (ptr_v, n_v);
2341 CAMLlocal3 (ret_v, tup_v, str_v);
2342 fz_link *link;
2343 struct page *page;
2344 struct pagedim *pdim;
2345 char *s = String_val (ptr_v);
2347 ret_v = Val_int (0);
2348 if (trylock ("ml_getlink")) {
2349 goto done;
2352 page = parse_pointer ("ml_getlink", s);
2353 ensureslinks (page);
2354 pdim = &state.pagedims[page->pdimno];
2355 link = page->slinks[Int_val (n_v)].link;
2356 LINKTOVAL;
2358 unlock ("ml_getlink");
2359 done:
2360 CAMLreturn (ret_v);
2363 CAMLprim value ml_getlinkcount (value ptr_v)
2365 CAMLparam1 (ptr_v);
2366 struct page *page;
2367 char *s = String_val (ptr_v);
2369 page = parse_pointer ("ml_getlinkcount", s);
2370 CAMLreturn (Val_int (page->slinkcount));
2373 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2375 CAMLparam2 (ptr_v, n_v);
2376 CAMLlocal1 (ret_v);
2377 struct page *page;
2378 struct slink *slink;
2379 char *s = String_val (ptr_v);
2381 page = parse_pointer ("ml_getlinkrect", s);
2382 ret_v = caml_alloc_tuple (4);
2383 if (trylock ("ml_getlinkrect")) {
2384 Field (ret_v, 0) = Val_int (0);
2385 Field (ret_v, 1) = Val_int (0);
2386 Field (ret_v, 2) = Val_int (0);
2387 Field (ret_v, 3) = Val_int (0);
2388 goto done;
2390 ensureslinks (page);
2392 slink = &page->slinks[Int_val (n_v)];
2393 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2394 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2395 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2396 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2397 unlock ("ml_getlinkrect");
2399 done:
2400 CAMLreturn (ret_v);
2403 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2405 CAMLparam3 (ptr_v, x_v, y_v);
2406 CAMLlocal3 (ret_v, tup_v, str_v);
2407 fz_link *link;
2408 struct page *page;
2409 char *s = String_val (ptr_v);
2410 int x = Int_val (x_v), y = Int_val (y_v);
2411 struct pagedim *pdim;
2413 ret_v = Val_int (0);
2414 if (trylock ("ml_whatsunder")) {
2415 goto done;
2418 page = parse_pointer ("ml_whatsunder", s);
2419 pdim = &state.pagedims[page->pdimno];
2420 x += pdim->bounds.x0;
2421 y += pdim->bounds.y0;
2422 link = getlink (page, x, y);
2423 if (link) {
2424 LINKTOVAL;
2426 else {
2427 int i;
2428 fz_text_span *span;
2430 ensuretext (page);
2431 for (span = page->text; span; span = span->next) {
2432 for (i = 0; i < span->len; ++i) {
2433 fz_bbox *b;
2434 b = &span->text[i].bbox;
2435 if ((x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)) {
2436 const char *n2 =
2437 span->font && span->font->name
2438 ? span->font->name
2439 : "Span has no font name"
2441 FT_FaceRec *face = span->font->ft_face;
2442 if (face && face->family_name) {
2443 char *s;
2444 char *n1 = face->family_name;
2445 size_t l1 = strlen (n1);
2446 size_t l2 = strlen (n2);
2448 if (l1 != l2 || memcmp (n1, n2, l1)) {
2449 s = malloc (l1 + l2 + 2);
2450 if (s) {
2451 memcpy (s, n2, l2);
2452 s[l2] = '=';
2453 memcpy (s + l2 + 1, n1, l1 + 1);
2454 str_v = caml_copy_string (s);
2455 free (s);
2459 if (str_v == 0) {
2460 str_v = caml_copy_string (n2);
2462 ret_v = caml_alloc_small (1, utext);
2463 Field (ret_v, 0) = str_v;
2464 goto unlock;
2469 unlock:
2470 unlock ("ml_whatsunder");
2472 done:
2473 CAMLreturn (ret_v);
2476 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2478 CAMLparam2 (ptr_v, rect_v);
2479 fz_bbox *b;
2480 struct page *page;
2481 fz_text_span *span;
2482 struct mark first, last;
2483 struct pagedim *pdim;
2484 int i, x0, x1, y0, y1;
2485 char *s = String_val (ptr_v);
2487 if (trylock ("ml_seltext")) {
2488 goto done;
2491 page = parse_pointer ("ml_seltext", s);
2492 ensuretext (page);
2494 pdim = &state.pagedims[page->pdimno];
2495 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2496 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2497 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2498 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2500 if (0) {
2501 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2502 glColor3ub (128, 128, 128);
2503 glRecti (x0, y0, x1, y1);
2504 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2507 first.span = NULL;
2508 last.span = NULL;
2510 last.i = first.i = 0;
2511 first.span = page->text;
2512 for (span = page->text; span; span = span->next) {
2513 for (i = 0; i < span->len; ++i) {
2514 b = &span->text[i].bbox;
2515 int selected = 0;
2517 if (x0 >= b->x0 && x0 <= b->x1 && y0 >= b->y0 && y0 <= b->y1) {
2518 first.i = i;
2519 first.span = span;
2520 selected = 1;
2522 if (x1 >= b->x0 && x1 <= b->x1 && y1 >= b->y0 && y1 <= b->y1) {
2523 last.i = i;
2524 last.span = span;
2525 selected = 1;
2527 if (0 && selected) {
2528 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2529 glColor3ub (128, 128, 128);
2530 glRecti (b->x0, b->y0, b->x1, b->y1);
2531 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2536 if (y1 < y0 || x1 < x0) {
2537 int swap = 0;
2539 if (first.span == last.span) {
2540 swap = 1;
2542 else {
2543 if (y1 < y0) {
2544 for (span = first.span; span && span != last.span;
2545 span = span->next) {
2546 if (span->eol) {
2547 swap = 1;
2548 break;
2554 if (swap) {
2555 i = first.i;
2556 span = first.span;
2557 first.i = last.i;
2558 first.span = last.span;
2559 last.i = i;
2560 last.span = span;
2564 page->fmark = first;
2565 page->lmark = last;
2567 unlock ("ml_seltext");
2569 done:
2570 CAMLreturn (Val_unit);
2573 static int pipespan (FILE *f, fz_text_span *span, int a, int b)
2575 char buf[4];
2576 int i, len, ret;
2578 for (i = a; i <= b; ++i) {
2579 len = runetochar (buf, &span->text[i].c);
2580 ret = fwrite (buf, len, 1, f);
2582 if (ret != 1) {
2583 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
2584 len, ret, strerror (errno));
2585 return -1;
2588 return 0;
2591 #ifdef __CYGWIN__
2592 value ml_popen (value UNUSED u1, value UNUSED u2)
2594 caml_failwith ("ml_popen not implemented under Cygwin");
2596 #else
2597 CAMLprim value ml_popen (value command_v, value fds_v)
2599 CAMLparam2 (command_v, fds_v);
2600 CAMLlocal2 (l_v, tup_v);
2601 char *msg;
2602 value earg_v;
2603 int ret, ret2;
2604 posix_spawnattr_t attr;
2605 posix_spawn_file_actions_t fa;
2606 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
2608 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
2609 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
2612 if ((ret = posix_spawnattr_init (&attr)) != 0) {
2613 msg = "posix_spawnattr_init";
2614 earg_v = Nothing;
2615 goto fail1;
2618 #ifdef POSIX_SPAWN_USEVFORK
2619 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
2620 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
2621 earg_v = Nothing;
2622 goto fail;
2624 #endif
2626 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
2627 int fd1, fd2;
2629 tup_v = Field (l_v, 0);
2630 fd1 = Int_val (Field (tup_v, 0));
2631 fd2 = Int_val (Field (tup_v, 1));
2632 if (fd2 < 0) {
2633 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
2634 msg = "posix_spawn_file_actions_addclose";
2635 earg_v = tup_v;
2636 goto fail;
2639 else {
2640 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
2641 msg = "posix_spawn_file_actions_adddup2";
2642 earg_v = tup_v;
2643 goto fail;
2648 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
2649 msg = "posix_spawn";
2650 earg_v = Nothing;
2651 goto fail;
2654 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
2655 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
2658 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
2659 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
2660 strerror (ret));
2663 CAMLreturn (Val_unit);
2665 fail1:
2666 if ((ret2 = posix_spawn_file_actions_destroy (&fa)) != 0) {
2667 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
2668 strerror (ret2));
2670 fail:
2671 if ((ret2 = posix_spawnattr_destroy (&attr)) != 0) {
2672 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret2));
2675 unix_error (ret, msg, earg_v);
2677 #endif
2679 CAMLprim value ml_copysel (value fd_v, value ptr_v)
2681 CAMLparam1 (ptr_v);
2682 FILE *f;
2683 struct page *page;
2684 fz_text_span *span;
2685 int fd = Int_val (fd_v);
2686 char *s = String_val (ptr_v);
2688 if (trylock ("ml_copysel")) {
2689 goto done;
2692 page = parse_pointer ("ml_sopysel", s);
2694 if (!page->fmark.span || !page->lmark.span) {
2695 fprintf (stderr, "nothing to copy\n");
2696 goto unlock;
2699 f = fdopen (fd, "w");
2700 if (!f) {
2701 fprintf (stderr, "failed to fopen sel pipe: %s\n",
2702 strerror (errno));
2703 f = stdout;
2706 for (span = page->fmark.span;
2707 span && span != page->lmark.span->next;
2708 span = span->next) {
2709 int a = span == page->fmark.span ? page->fmark.i : 0;
2710 int b = span == page->lmark.span ? page->lmark.i : span->len - 1;
2711 if (pipespan (f, span, a, b)) {
2712 goto close;
2714 if (span->eol) {
2715 if (putc ('\n', f) == EOF) {
2716 fprintf (stderr, "failed break line on sel pipe: %s\n",
2717 strerror (errno));
2718 goto close;
2722 page->lmark.span = NULL;
2723 page->fmark.span = NULL;
2725 close:
2726 if (f != stdout) {
2727 int ret = fclose (f);
2728 fd = -1;
2729 if (ret == -1) {
2730 if (errno != ECHILD) {
2731 fprintf (stderr, "failed to close sel pipe: %s\n",
2732 strerror (errno));
2736 unlock:
2737 unlock ("ml_copysel");
2739 done:
2740 if (fd >= 0) {
2741 if (close (fd)) {
2742 fprintf (stderr, "failed to close sel pipe: %s\n",
2743 strerror (errno));
2746 CAMLreturn (Val_unit);
2749 CAMLprim value ml_getpdimrect (value pagedimno_v)
2751 CAMLparam1 (pagedimno_v);
2752 CAMLlocal1 (ret_v);
2753 int pagedimno = Int_val (pagedimno_v);
2754 fz_rect box;
2756 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2757 if (trylock ("ml_getpdimrect")) {
2758 box = fz_empty_rect;
2760 else {
2761 box = state.pagedims[pagedimno].mediabox;
2762 unlock ("ml_getpdimrect");
2765 Store_double_field (ret_v, 0, box.x0);
2766 Store_double_field (ret_v, 1, box.x1);
2767 Store_double_field (ret_v, 2, box.y0);
2768 Store_double_field (ret_v, 3, box.y1);
2770 CAMLreturn (ret_v);
2773 static double getmaxw (void)
2775 int i;
2776 struct pagedim *p;
2777 double maxw = 0.0;
2779 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
2780 double x0, x1, w;
2782 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
2783 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
2785 w = x1 - x0;
2786 maxw = MAX (w, maxw);
2788 return maxw;
2791 CAMLprim value ml_getmaxw (value unit_v)
2793 CAMLparam1 (unit_v);
2794 CAMLlocal1 (ret_v);
2795 double maxw = 0.0;
2797 if (trylock ("ml_getmaxw")) {
2798 goto done;
2800 maxw = getmaxw ();
2801 unlock ("ml_getmaxw");
2802 done:
2803 ret_v = caml_copy_double (maxw);
2804 CAMLreturn (ret_v);
2807 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v, value dw_v)
2809 CAMLparam3 (winw_v, winh_v, dw_v);
2810 CAMLlocal1 (ret_v);
2811 int i;
2812 double zoom = 1.0;
2813 double maxw = 0.0, maxh = 0.0;
2814 struct pagedim *p;
2815 double winw = Int_val (winw_v);
2816 double winh = Int_val (winh_v);
2817 double dw = Int_val (dw_v);
2818 double pw = 1.0, ph = 1.0, num, den;
2820 if (trylock ("ml_zoom_for_height")) {
2821 goto done;
2824 if (state.proportional) {
2825 maxw = getmaxw ();
2828 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
2829 double x0, x1, y0, y1, w, h, scaledh, scale;
2831 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
2832 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
2833 y0 = MIN (p->mediabox.y0, p->mediabox.y1);
2834 y1 = MAX (p->mediabox.y0, p->mediabox.y1);
2836 w = x1 - x0;
2837 h = y1 - y0;
2839 if (state.proportional) {
2840 scale = w / maxw;
2841 scaledh = h * scale;
2843 else {
2844 scale = 1.0;
2845 scaledh = h;
2848 if (scaledh > maxh) {
2849 maxh = scaledh;
2850 ph = scaledh;
2851 pw = w * scale;
2855 num = (winh * pw) + (ph * dw);
2856 den = ph * winw;
2857 zoom = num / den;
2859 unlock ("ml_zoom_for_height");
2860 done:
2861 ret_v = caml_copy_double (zoom);
2862 CAMLreturn (ret_v);
2865 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
2867 CAMLparam4 (pt_v, x_v, y_v, string_v);
2868 CAMLlocal1 (ret_v);
2869 int pt = Int_val(pt_v);
2870 int x = Int_val (x_v);
2871 int y = Int_val (y_v);
2872 double w;
2874 w = draw_string (state.face, pt, x, y, String_val (string_v));
2875 ret_v = caml_copy_double (w);
2876 CAMLreturn (ret_v);
2879 CAMLprim value ml_measure_string (value pt_v, value string_v)
2881 CAMLparam2 (pt_v, string_v);
2882 CAMLlocal1 (ret_v);
2883 int pt = Int_val (pt_v);
2884 double w;
2886 w = measure_string (state.face, pt, String_val (string_v));
2887 ret_v = caml_copy_double (w);
2888 CAMLreturn (ret_v);
2891 CAMLprim value ml_getpagebox (value opaque_v)
2893 CAMLparam1 (opaque_v);
2894 CAMLlocal1 (ret_v);
2895 fz_bbox bbox;
2896 fz_device *dev;
2897 char *s = String_val (opaque_v);
2898 struct page *page = parse_pointer ("ml_getpagebox", s);
2900 ret_v = caml_alloc_tuple (4);
2901 dev = fz_new_bbox_device (state.ctx, &bbox);
2902 dev->hints |= FZ_IGNORE_SHADE;
2904 switch (page->type) {
2905 case DPDF:
2906 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, pagectm (page), NULL);
2907 break;
2909 case DXPS:
2910 xps_run_page (state.u.xps, page->u.xpspage, dev, pagectm (page), NULL);
2911 break;
2913 default:
2914 bbox = fz_infinite_bbox;
2915 break;
2918 fz_free_device (dev);
2919 Field (ret_v, 0) = Val_int (bbox.x0);
2920 Field (ret_v, 1) = Val_int (bbox.y0);
2921 Field (ret_v, 2) = Val_int (bbox.x1);
2922 Field (ret_v, 3) = Val_int (bbox.y1);
2924 CAMLreturn (ret_v);
2927 CAMLprim value ml_setaalevel (value level_v)
2929 CAMLparam1 (level_v);
2931 state.aalevel = Int_val (level_v);
2932 CAMLreturn (Val_unit);
2935 #undef pixel
2936 #include <X11/Xlib.h>
2937 #include <GL/glx.h>
2939 static struct {
2940 Display *dpy;
2941 GLXContext ctx;
2942 GLXDrawable drawable;
2943 } glx;
2945 #include "keysym2ucs.c"
2947 CAMLprim value ml_keysymtoutf8 (value keysym_v)
2949 CAMLparam1 (keysym_v);
2950 CAMLlocal1 (str_v);
2951 KeySym keysym = Int_val (keysym_v);
2952 Rune rune;
2953 int len;
2954 char buf[5];
2956 rune = keysym2ucs (keysym);
2957 len = runetochar (buf, &rune);
2958 buf[len] = 0;
2959 str_v = caml_copy_string (buf);
2960 CAMLreturn (str_v);
2963 CAMLprim value ml_glx (value win_v)
2965 CAMLparam1 (win_v);
2966 XVisualInfo *visual;
2967 int screen, wid = Int_val (win_v);
2968 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
2970 glx.dpy = XOpenDisplay (NULL);
2971 if (!glx.dpy) {
2972 caml_failwith ("XOpenDisplay failed");
2975 screen = DefaultScreen (glx.dpy);
2976 visual = glXChooseVisual (glx.dpy, screen, attributes);
2977 if (!visual) {
2978 XCloseDisplay (glx.dpy);
2979 glx.dpy = NULL;
2980 caml_failwith ("glXChooseVisual");
2983 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
2984 if (!glx.ctx) {
2985 XCloseDisplay (glx.dpy);
2986 XFree (visual);
2987 glx.dpy = NULL;
2988 caml_failwith ("glXCreateContext");
2991 XFree (visual);
2992 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
2993 glXDestroyContext (glx.dpy, glx.ctx);
2994 XCloseDisplay (glx.dpy);
2995 glx.dpy = NULL;
2996 glx.ctx = NULL;
2997 caml_failwith ("glXMakeCurrent");
2999 glx.drawable = wid;
3001 CAMLreturn (Val_unit);
3004 CAMLprim value ml_swapb (value unit_v)
3006 CAMLparam1 (unit_v);
3007 glXSwapBuffers (glx.dpy, glx.drawable);
3008 CAMLreturn (Val_unit);
3011 CAMLprim value ml_glxsync (value unit_v)
3013 CAMLparam1 (unit_v);
3014 if (glx.dpy && glx.ctx) {
3015 glXWaitX ();
3016 glXWaitGL ();
3018 CAMLreturn (Val_unit);
3021 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3022 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3024 CAMLprim value ml_platform (value unit_v)
3026 CAMLparam1 (unit_v);
3027 int platid = piunknown;
3029 #if defined __linux__
3030 platid = pilinux;
3031 #elif defined __CYGWIN__
3032 platid = picygwin;
3033 #elif defined __DragonFly__
3034 platid = pidragonflybsd;
3035 #elif defined __FreeBSD__
3036 platid = pifreebsd;
3037 #elif defined __OpenBSD__
3038 platid = piopenbsd;
3039 #elif defined __NetBSD__
3040 platid = pinetbsd;
3041 #elif defined __sun__
3042 platid = pisun;
3043 #elif defined __APPLE__
3044 platid = piosx;
3045 #endif
3046 CAMLreturn (Val_int (platid));
3049 CAMLprim value ml_cloexec (value fd_v)
3051 CAMLparam1 (fd_v);
3052 int fd = Int_val (fd_v);
3054 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3055 uerror ("fcntl", Nothing);
3057 CAMLreturn (Val_unit);
3060 CAMLprim value ml_init (value pipe_v, value params_v)
3062 CAMLparam2 (pipe_v, params_v);
3063 CAMLlocal2 (trim_v, fuzz_v);
3064 int ret;
3065 int texcount;
3066 char *fontpath;
3067 int colorspace;
3068 int mustoresize;
3069 struct sigaction sa;
3071 state.cr = Int_val (Field (pipe_v, 0));
3072 state.cw = Int_val (Field (pipe_v, 1));
3073 state.rotate = Int_val (Field (params_v, 0));
3074 state.proportional = Bool_val (Field (params_v, 1));
3075 trim_v = Field (params_v, 2);
3076 texcount = Int_val (Field (params_v, 3));
3077 state.sliceheight = Int_val (Field (params_v, 4));
3078 mustoresize = Int_val (Field (params_v, 5));
3079 colorspace = Int_val (Field (params_v, 6));
3080 fontpath = String_val (Field (params_v, 7));
3082 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3084 state.trimmargins = Bool_val (Field (trim_v, 0));
3085 fuzz_v = Field (trim_v, 1);
3086 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3087 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3088 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3089 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3091 set_tex_params (colorspace);
3093 if (*fontpath) {
3094 state.face = load_font (fontpath);
3096 else {
3097 unsigned int len;
3098 void *base = pdf_find_substitute_font (0, 0, 0, 0, &len);
3100 state.face = load_builtin_font (base, len);
3102 if (!state.face) _exit (1);
3104 realloctexts (texcount);
3106 #ifdef __CYGWIN__
3107 sa.sa_handler = SIG_IGN;
3108 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3109 #else
3110 sa.sa_handler = SIG_DFL;
3111 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
3112 #endif
3113 if (sigemptyset (&sa.sa_mask)) {
3114 err (1, "sigemptyset");
3116 if (sigaction (SIGCHLD, &sa, NULL)) {
3117 err (1, "sigaction");
3120 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3121 if (ret) {
3122 errx (1, "pthread_create: %s", strerror (ret));
3125 CAMLreturn (Val_unit);