Proper handling of WM initiated full screen switch
[llpp.git] / link.c
blob136e16e41e4be61f9cfe0bd02fac13d11e6b6bd5
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>
8 #include <wchar.h>
10 #include <unistd.h>
11 #include <pthread.h>
12 #include <sys/time.h>
13 #include <sys/types.h>
14 #include <sys/ioctl.h>
16 #ifdef __CYGWIN__
17 #include <cygwin/socket.h> /* FIONREAD */
18 #else
19 #include <spawn.h>
20 #endif
22 #include <regex.h>
23 #include <ctype.h>
24 #include <stdarg.h>
25 #include <limits.h>
27 #include <GL/gl.h>
29 #include <caml/fail.h>
30 #include <caml/alloc.h>
31 #include <caml/memory.h>
32 #include <caml/unixsupport.h>
34 #include <fitz.h>
35 #include <mupdf.h>
36 #include <mupdf-internal.h>
37 #include <muxps.h>
38 #include <muxps-internal.h>
39 #include <mucbz.h>
41 #include FT_FREETYPE_H
43 #define PIGGYBACK
45 #ifndef __USE_GNU
46 extern char **environ;
47 #endif
49 #define MIN(a,b) ((a) < (b) ? (a) : (b))
50 #define MAX(a,b) ((a) > (b) ? (a) : (b))
52 #if defined __GNUC__
53 #define NORETURN_ATTR __attribute__ ((noreturn))
54 #define UNUSED_ATTR __attribute__ ((unused))
55 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
56 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
57 #else
58 #define NORETURN_ATTR
59 #define UNUSED_ATTR
60 #define OPTIMIZE_ATTR(n)
61 #define GCC_FMT_ATTR(a, b)
62 #endif
64 #define FMT_s "zu"
66 #define FMT_ptr "p"
67 #define FMT_ptr_cast(p) (p)
68 #define FMT_ptr_cast2(p) (p)
70 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
71 err (int exitcode, const char *fmt, ...)
73 va_list ap;
74 int savederrno;
76 savederrno = errno;
77 va_start (ap, fmt);
78 vfprintf (stderr, fmt, ap);
79 va_end (ap);
80 fprintf (stderr, ": %s\n", strerror (savederrno));
81 fflush (stderr);
82 _exit (exitcode);
85 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
86 errx (int exitcode, const char *fmt, ...)
88 va_list ap;
90 va_start (ap, fmt);
91 vfprintf (stderr, fmt, ap);
92 va_end (ap);
93 fputc ('\n', stderr);
94 fflush (stderr);
95 _exit (exitcode);
98 #ifndef GL_TEXTURE_RECTANGLE_ARB
99 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
100 #endif
102 #ifndef GL_BGRA
103 #define GL_BGRA 0x80E1
104 #endif
106 #ifndef GL_UNSIGNED_INT_8_8_8_8
107 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
108 #endif
110 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
111 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
112 #endif
114 #if 0
115 #define lprintf printf
116 #else
117 #define lprintf(...)
118 #endif
120 #define ARSERT(cond) for (;;) { \
121 if (!(cond)) { \
122 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
124 break; \
127 struct slice {
128 int h;
129 int texindex;
132 struct tile {
133 int x, y, w, h;
134 int slicecount;
135 int sliceheight;
136 struct pbo *pbo;
137 fz_pixmap *pixmap;
138 struct slice slices[1];
141 struct pagedim {
142 int pageno;
143 int rotate;
144 int left;
145 int tctmready;
146 fz_irect bounds;
147 fz_rect pagebox;
148 fz_rect mediabox;
149 fz_matrix ctm, zoomctm, lctm, tctm;
152 struct slink {
153 fz_irect bbox;
154 fz_link *link;
157 enum { DPDF, DXPS, DCBZ };
159 struct page {
160 int tgen;
161 int sgen;
162 int type;
163 int pageno;
164 int pdimno;
165 fz_text_page *text;
166 fz_text_sheet *sheet;
167 union {
168 void *ptr;
169 pdf_page *pdfpage;
170 xps_page *xpspage;
171 cbz_page *cbzpage;
172 } u;
173 fz_display_list *dlist;
174 int slinkcount;
175 struct slink *slinks;
176 struct mark {
177 int i;
178 fz_text_span *span;
179 } fmark, lmark;
180 void (*freepage) (void *);
183 struct {
184 int type;
185 int sliceheight;
186 struct pagedim *pagedims;
187 int pagecount;
188 int pagedimcount;
189 union {
190 pdf_document *pdf;
191 xps_document *xps;
192 cbz_document *cbz;
193 } u;
194 fz_context *ctx;
195 int w, h;
197 int texindex;
198 int texcount;
199 GLuint *texids;
201 GLenum texiform;
202 GLenum texform;
203 GLenum texty;
205 fz_colorspace *colorspace;
207 struct {
208 int w, h;
209 struct slice *slice;
210 } *texowners;
212 int rotate;
213 int proportional;
214 int trimmargins;
215 int needoutline;
216 int gen;
217 int aalevel;
219 int trimanew;
220 fz_irect trimfuzz;
221 fz_pixmap *pig;
223 pthread_t thread;
224 int cr, cw;
225 FT_Face face;
227 void (*closedoc) (void);
228 void (*freepage) (void *);
230 char *trimcachepath;
232 int pbo_usable;
233 void (*glBindBufferARB) (GLenum, GLuint);
234 GLboolean (*glUnmapBufferARB) (GLenum);
235 void *(*glMapBufferARB) (GLenum, GLenum);
236 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
237 void (*glGenBuffersARB) (GLsizei, GLuint *);
238 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
239 } state;
241 struct pbo {
242 GLuint id;
243 void *ptr;
244 size_t size;
247 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
249 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
252 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
254 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
257 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
259 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
260 m.a, m.b, m.c, m.d, m.e, m.f);
263 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
265 static void lock (const char *cap)
267 int ret = pthread_mutex_lock (&mutex);
268 if (ret) {
269 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
273 static void unlock (const char *cap)
275 int ret = pthread_mutex_unlock (&mutex);
276 if (ret) {
277 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
281 static int trylock (const char *cap)
283 int ret = pthread_mutex_trylock (&mutex);
284 if (ret && ret != EBUSY) {
285 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
287 return ret == EBUSY;
290 static void *parse_pointer (const char *cap, const char *s)
292 int ret;
293 void *ptr;
295 ret = sscanf (s, "%" FMT_ptr, FMT_ptr_cast (&ptr));
296 if (ret != 1) {
297 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
299 return ptr;
302 static double now (void)
304 struct timeval tv;
306 if (gettimeofday (&tv, NULL)) {
307 err (1, "gettimeofday");
309 return tv.tv_sec + tv.tv_usec*1e-6;
312 static int hasdata (void)
314 int ret, avail;
315 ret = ioctl (state.cr, FIONREAD, &avail);
316 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
317 return avail > 0;
320 CAMLprim value ml_hasdata (value fd_v)
322 CAMLparam1 (fd_v);
323 int ret, avail;
325 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
326 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
327 CAMLreturn (Val_bool (avail > 0));
330 static void readdata (void *p, int size)
332 ssize_t n;
334 again:
335 n = read (state.cr, p, size);
336 if (n < 0) {
337 if (errno == EINTR) goto again;
338 err (1, "read (req %d, ret %zd)", size, n);
340 if (n - size) {
341 if (!n) errx (1, "EOF while reading");
342 errx (1, "read (req %d, ret %zd)", size, n);
346 static void writedata (char *p, int size)
348 char buf[4];
349 ssize_t n;
351 buf[0] = (size >> 24) & 0xff;
352 buf[1] = (size >> 16) & 0xff;
353 buf[2] = (size >> 8) & 0xff;
354 buf[3] = (size >> 0) & 0xff;
356 n = write (state.cw, buf, 4);
357 if (n != 4) {
358 if (!n) errx (1, "EOF while writing length");
359 err (1, "write %zd", n);
362 n = write (state.cw, p, size);
363 if (n - size) {
364 if (!n) errx (1, "EOF while writing data");
365 err (1, "write (req %d, ret %zd)", size, n);
369 static int readlen (void)
371 unsigned char p[4];
373 readdata (p, 4);
374 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
377 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
379 int size = 200, len;
380 va_list ap;
381 char *buf;
383 buf = malloc (size);
384 for (;;) {
385 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
387 va_start (ap, fmt);
388 len = vsnprintf (buf, size, fmt, ap);
389 va_end (ap);
391 if (len > -1 && len < size) {
392 writedata (buf, len);
393 break;
396 if (len > -1) {
397 size = len + 1;
399 else {
400 size *= 2;
402 buf = realloc (buf, size);
404 free (buf);
407 static void closepdf (void)
409 if (state.u.pdf) {
410 pdf_close_document (state.u.pdf);
411 state.u.pdf = NULL;
415 static void closexps (void)
417 if (state.u.xps) {
418 xps_close_document (state.u.xps);
419 state.u.xps = NULL;
423 static void closecbz (void)
425 if (state.u.cbz) {
426 cbz_close_document (state.u.cbz);
427 state.u.cbz = NULL;
431 static void freepdfpage (void *ptr)
433 pdf_free_page (state.u.pdf, ptr);
436 static void freeemptyxxxpage (void *ptr)
438 (void) ptr;
441 static void freexpspage (void *ptr)
443 xps_free_page (state.u.xps, ptr);
446 static void freecbzpage (void *ptr)
448 cbz_free_page (state.u.cbz, ptr);
451 static void openxref (char *filename, char *password)
453 int i, len;
455 for (i = 0; i < state.texcount; ++i) {
456 state.texowners[i].w = -1;
457 state.texowners[i].slice = NULL;
460 if (state.closedoc) state.closedoc ();
462 len = strlen (filename);
464 state.type = DPDF;
465 if (len > 4) {
466 char ext[4];
468 ext[0] = tolower ((int) filename[len-3]);
469 ext[1] = tolower ((int) filename[len-2]);
470 ext[2] = tolower ((int) filename[len-1]);
472 /**/ if (ext[0] == 'x' && ext[1] == 'p' && ext[2] == 's') {
473 state.type = DXPS;
475 else if (ext[0] == 'c' && ext[1] == 'b' && ext[2] == 'z') {
476 state.type = DCBZ;
480 if (state.pagedims) {
481 free (state.pagedims);
482 state.pagedims = NULL;
484 state.pagedimcount = 0;
486 fz_set_aa_level (state.ctx, state.aalevel);
487 switch (state.type) {
488 case DPDF:
489 state.u.pdf = pdf_open_document (state.ctx, filename);
490 if (pdf_needs_password (state.u.pdf)) {
491 int okay = pdf_authenticate_password (state.u.pdf, password);
492 if (!okay) {
493 errx (1, "invalid password");
496 state.pagecount = pdf_count_pages (state.u.pdf);
497 state.closedoc = closepdf;
498 state.freepage = freepdfpage;
499 break;
501 case DXPS:
502 state.u.xps = xps_open_document (state.ctx, filename);
503 state.pagecount = xps_count_pages (state.u.xps);
504 state.closedoc = closexps;
505 state.freepage = freexpspage;
506 break;
508 case DCBZ:
509 state.u.cbz = cbz_open_document (state.ctx, filename);
510 state.pagecount = cbz_count_pages (state.u.cbz);
511 state.closedoc = closecbz;
512 state.freepage = freecbzpage;
513 break;
517 static void pdfinfo (void)
519 if (state.type == DPDF) {
520 pdf_obj *infoobj;
522 printd ("info PDF version\t%d.%d",
523 state.u.pdf->version / 10, state.u.pdf->version % 10);
525 infoobj = pdf_dict_gets (state.u.pdf->trailer, "Info");
526 if (infoobj) {
527 int i;
528 char *s;
529 char *items[] = { "Title", "Author", "Creator",
530 "Producer", "CreationDate" };
532 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
533 pdf_obj *obj = pdf_dict_gets (infoobj, items[i]);
534 s = pdf_to_utf8 (state.u.pdf, obj);
535 if (*s) {
536 if (i == 0) {
537 printd ("title %s", s);
539 printd ("info %s\t%s", items[i], s);
541 fz_free (state.ctx, s);
544 printd ("infoend");
548 static void unlinktile (struct tile *tile)
550 int i;
552 for (i = 0; i < tile->slicecount; ++i) {
553 struct slice *s = &tile->slices[i];
555 if (s->texindex != -1) {
556 if (state.texowners[s->texindex].slice == s) {
557 state.texowners[s->texindex].slice = NULL;
563 static void freepage (struct page *page)
565 if (page->text) {
566 fz_free_text_page (state.ctx, page->text);
568 if (page->sheet) {
569 fz_free_text_sheet (state.ctx, page->sheet);
571 if (page->slinks) {
572 free (page->slinks);
574 page->freepage (page->u.ptr);
575 fz_free_display_list (state.ctx, page->dlist);
576 free (page);
579 static void freetile (struct tile *tile)
581 unlinktile (tile);
582 if (!tile->pbo) {
583 #ifndef PIGGYBACK
584 fz_drop_pixmap (state.ctx, tile->pixmap);
585 #else
586 if (state.pig) {
587 fz_drop_pixmap (state.ctx, state.pig);
589 state.pig = tile->pixmap;
590 #endif
592 else {
593 free (tile->pbo);
594 fz_drop_pixmap (state.ctx, tile->pixmap);
596 free (tile);
599 #ifdef __ALTIVEC__
600 #include <altivec.h>
602 static int cacheline32bytes;
604 static void __attribute__ ((constructor)) clcheck (void)
606 char **envp = environ;
607 unsigned long *auxv;
609 while (*envp++);
611 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
612 if (*auxv == 19) {
613 cacheline32bytes = auxv[1] == 32;
614 return;
619 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
621 size_t size = pixmap->w * pixmap->h * pixmap->n;
622 if (cacheline32bytes && size > 32) {
623 intptr_t a1, a2, diff;
624 size_t sizea, i;
625 vector unsigned char v = vec_splat_u8 (-1);
626 vector unsigned char *p;
628 a1 = a2 = (intptr_t) pixmap->samples;
629 a2 = (a1 + 31) & ~31;
630 diff = a2 - a1;
631 sizea = size - diff;
632 p = (void *) a2;
634 while (a1 != a2) *(char *) a1++ = 0xff;
635 for (i = 0; i < (sizea & ~31); i += 32) {
636 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
637 vec_st (v, i, p);
638 vec_st (v, i + 16, p);
640 while (i < sizea) *((char *) a1 + i++) = 0xff;
642 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
644 #else
645 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
646 #endif
648 static void trimctm (pdf_page *page, int pindex)
650 fz_matrix ctm;
651 struct pagedim *pdim = &state.pagedims[pindex];
653 if (!pdim->tctmready) {
654 if (state.trimmargins) {
655 fz_rect realbox;
656 fz_matrix rm, sm, tm, im, ctm1;
658 fz_rotate (&rm, -pdim->rotate);
659 fz_scale (&sm, 1, -1);
660 fz_concat (&ctm, &rm, &sm);
661 realbox = pdim->mediabox;
662 fz_transform_rect (&realbox, &ctm);
663 fz_translate (&tm, -realbox.x0, -realbox.y0);
664 fz_concat (&ctm1, &ctm, &tm);
665 fz_invert_matrix (&im, &page->ctm);
666 fz_concat (&ctm, &im, &ctm1);
668 else {
669 ctm = fz_identity;
671 pdim->tctm = ctm;
672 pdim->tctmready = 1;
676 static fz_matrix pagectm (struct page *page)
678 fz_matrix ctm, tm;
680 if (page->type == DPDF) {
681 trimctm (page->u.pdfpage, page->pdimno);
682 fz_concat (&ctm,
683 &state.pagedims[page->pdimno].tctm,
684 &state.pagedims[page->pdimno].ctm);
686 else {
687 struct pagedim *pdim = &state.pagedims[page->pdimno];
689 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
690 fz_concat (&ctm, &tm, &state.pagedims[page->pdimno].ctm);
692 return ctm;
695 static void *loadpage (int pageno, int pindex)
697 fz_device *dev;
698 struct page *page = NULL;
700 page = calloc (sizeof (struct page), 1);
701 if (!page) {
702 err (1, "calloc page %d", pageno);
705 page->dlist = fz_new_display_list (state.ctx);
706 dev = fz_new_list_device (state.ctx, page->dlist);
707 fz_try (state.ctx) {
708 switch (state.type) {
709 case DPDF:
710 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
711 pdf_run_page (state.u.pdf, page->u.pdfpage, dev,
712 &fz_identity, NULL);
713 page->freepage = freepdfpage;
714 break;
716 case DXPS:
717 page->u.xpspage = xps_load_page (state.u.xps, pageno);
718 xps_run_page (state.u.xps, page->u.xpspage, dev,
719 &fz_identity, NULL);
720 page->freepage = freexpspage;
721 break;
723 case DCBZ:
724 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
725 cbz_run_page (state.u.cbz, page->u.cbzpage, dev,
726 &fz_identity, NULL);
727 page->freepage = freecbzpage;
728 break;
731 fz_catch (state.ctx) {
732 page->u.ptr = NULL;
733 page->freepage = freeemptyxxxpage;
735 fz_free_device (dev);
737 page->pdimno = pindex;
738 page->pageno = pageno;
739 page->sgen = state.gen;
740 page->tgen = state.gen;
741 page->type = state.type;
743 return page;
746 static struct tile *alloctile (int h)
748 int i;
749 int slicecount;
750 size_t tilesize;
751 struct tile *tile;
753 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
754 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
755 tile = calloc (tilesize, 1);
756 if (!tile) {
757 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
759 for (i = 0; i < slicecount; ++i) {
760 int sh = MIN (h, state.sliceheight);
761 tile->slices[i].h = sh;
762 tile->slices[i].texindex = -1;
763 h -= sh;
765 tile->slicecount = slicecount;
766 tile->sliceheight = state.sliceheight;
767 return tile;
770 #ifdef OBSCURED_OPT
771 struct obs {
772 int cured;
773 fz_irect b;
776 static void obs_fill_image (fz_device *dev, fz_image *image,
777 const fz_matrix *ctm, float alpha)
779 struct obs *obs = dev->user;
781 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
782 fz_irect b;
783 fz_rect rect = fz_unit_rect;
785 fz_transform_rect (&rect, ctm);
786 fz_round_rect (&b, &rect);
787 fz_intersect_irect (&b, &obs->b);
788 obs->cured = b.x0 == obs->b.x0
789 && b.x1 == obs->b.x1
790 && b.y0 == obs->b.y0
791 && b.y1 == obs->b.y1;
795 static int obscured (struct page *page, fz_irect bbox)
797 fz_rect rect;
798 fz_matrix ctm;
799 fz_device dev;
800 struct obs obs;
802 memset (&dev, 0, sizeof (dev));
803 memset (&obs, 0, sizeof (obs));
804 dev.hints = 0;
805 dev.flags = 0;
806 dev.user = &obs;
807 dev.ctx = state.ctx;
808 dev.fill_image = obs_fill_image;
809 obs.b = bbox;
810 fz_rect_from_irect (&rect, &bbox);
811 ctm = pagectm (page);
812 fz_run_display_list (page->dlist, &dev, &ctm, &rect, NULL);
813 return obs.cured;
815 #define OBSCURED obscured
816 #else
817 #define OBSCURED(a, b) 0
818 #endif
820 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
821 struct pbo *pbo)
823 fz_rect rect;
824 fz_irect bbox;
825 fz_matrix ctm;
826 fz_device *dev;
827 struct tile *tile;
828 struct pagedim *pdim;
830 tile = alloctile (h);
831 pdim = &state.pagedims[page->pdimno];
833 bbox = pdim->bounds;
834 bbox.x0 += x;
835 bbox.y0 += y;
836 bbox.x1 = bbox.x0 + w;
837 bbox.y1 = bbox.y0 + h;
839 if (state.pig) {
840 if (state.pig->w == w
841 && state.pig->h == h
842 && state.pig->colorspace == state.colorspace) {
843 tile->pixmap = state.pig;
844 tile->pixmap->x = bbox.x0;
845 tile->pixmap->y = bbox.y0;
847 else {
848 fz_drop_pixmap (state.ctx, state.pig);
850 state.pig = NULL;
852 if (!tile->pixmap) {
853 if (pbo) {
854 tile->pixmap =
855 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
856 &bbox, pbo->ptr);
857 tile->pbo = pbo;
859 else {
860 tile->pixmap =
861 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
865 tile->w = w;
866 tile->h = h;
867 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
868 clearpixmap (tile->pixmap);
870 dev = fz_new_draw_device (state.ctx, tile->pixmap);
871 ctm = pagectm (page);
872 fz_rect_from_irect (&rect, &bbox);
873 fz_run_display_list (page->dlist, dev, &ctm, &rect, NULL);
874 fz_free_device (dev);
876 return tile;
879 static void initpdims (void)
881 double start, end;
882 int pageno, trim, show;
883 FILE *trimf = NULL;
884 int trimw = 0;
886 start = now ();
888 if (state.trimmargins && state.trimcachepath) {
889 trimf = fopen (state.trimcachepath, "rb");
890 if (!trimf) {
891 trimf = fopen (state.trimcachepath, "wb");
892 trimw = 1;
895 for (pageno = 0; pageno < state.pagecount; ++pageno) {
896 int rotate = 0;
897 struct pagedim *p;
898 fz_rect mediabox;
900 switch (state.type) {
901 case DPDF: {
902 pdf_obj *pageobj = state.u.pdf->page_objs[pageno];
904 if (state.trimmargins) {
905 pdf_obj *obj;
906 pdf_page *page;
908 fz_try (state.ctx) {
909 page = pdf_load_page (state.u.pdf, pageno);
910 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
911 trim = state.trimanew || !obj;
912 if (trim) {
913 fz_rect rect;
914 fz_matrix ctm;
915 fz_device *dev;
917 dev = fz_new_bbox_device (state.ctx, &rect);
918 dev->hints |= FZ_IGNORE_SHADE;
919 fz_invert_matrix (&ctm, &page->ctm);
920 pdf_run_page (state.u.pdf, page, dev, &fz_identity, NULL);
921 fz_free_device (dev);
923 rect.x0 += state.trimfuzz.x0;
924 rect.x1 += state.trimfuzz.x1;
925 rect.y0 += state.trimfuzz.y0;
926 rect.y1 += state.trimfuzz.y1;
927 fz_transform_rect (&rect, &ctm);
928 fz_intersect_rect (&rect, &page->mediabox);
930 if (fz_is_empty_rect (&rect)) {
931 mediabox = page->mediabox;
933 else {
934 mediabox = rect;
937 obj = pdf_new_array (state.ctx, 4);
938 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x0));
939 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y0));
940 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x1));
941 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y1));
942 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
944 else {
945 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
946 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
947 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
948 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
951 rotate = page->rotate;
952 pdf_free_page (state.u.pdf, page);
954 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
955 if (show) {
956 printd ("progress %f Trimming %d",
957 (double) (pageno + 1) / state.pagecount,
958 pageno + 1);
961 fz_catch (state.ctx) {
962 fprintf (stderr, "failed to load page %d\n", pageno+1);
965 else {
966 fz_rect cropbox;
968 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "MediaBox"),
969 &mediabox);
970 if (fz_is_empty_rect (&mediabox)) {
971 fprintf (stderr, "cannot find page size for page %d\n",
972 pageno+1);
973 mediabox.x0 = 0;
974 mediabox.y0 = 0;
975 mediabox.x1 = 612;
976 mediabox.y1 = 792;
979 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "CropBox"),
980 &cropbox);
981 if (!fz_is_empty_rect (&cropbox)) {
982 fz_intersect_rect (&mediabox, &cropbox);
984 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
986 break;
989 case DXPS:
991 xps_page *page;
993 fz_try (state.ctx) {
994 page = xps_load_page (state.u.xps, pageno);
995 xps_bound_page (state.u.xps, page, &mediabox);
996 rotate = 0;
997 if (state.trimmargins) {
998 fz_rect rect;
999 fz_device *dev;
1001 dev = fz_new_bbox_device (state.ctx, &rect);
1002 dev->hints |= FZ_IGNORE_SHADE;
1003 xps_run_page (state.u.xps, page, dev,
1004 &fz_identity, NULL);
1005 fz_free_device (dev);
1007 rect.x0 += state.trimfuzz.x0;
1008 rect.x1 += state.trimfuzz.x1;
1009 rect.y0 += state.trimfuzz.y0;
1010 rect.y1 += state.trimfuzz.y1;
1011 fz_intersect_rect (&rect, &mediabox);
1013 if (!fz_is_empty_rect (&rect)) {
1014 mediabox = rect;
1017 xps_free_page (state.u.xps, page);
1018 printd ("progress %f loading %d",
1019 (double) (pageno + 1) / state.pagecount,
1020 pageno + 1);
1022 fz_catch (state.ctx) {
1025 break;
1027 case DCBZ:
1029 rotate = 0;
1030 if (state.trimmargins && trimw) {
1031 cbz_page *page;
1033 fz_try (state.ctx) {
1034 page = cbz_load_page (state.u.cbz, pageno);
1035 cbz_bound_page (state.u.cbz, page, &mediabox);
1036 cbz_free_page (state.u.cbz, page);
1037 printd ("progress %f Trimming %d",
1038 (double) (pageno + 1) / state.pagecount,
1039 pageno + 1);
1041 fz_catch (state.ctx) {
1042 fprintf (stderr, "failed to load page %d\n", pageno+1);
1043 mediabox.x0 = 0;
1044 mediabox.y0 = 0;
1045 mediabox.x1 = 900;
1046 mediabox.y1 = 900;
1048 if (trimf) {
1049 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1050 if (n - 1) {
1051 err (1, "fwrite trim mediabox");
1055 else {
1056 if (trimf) {
1057 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1058 if (n - 1) {
1059 err (1, "fread trim mediabox");
1062 else {
1063 mediabox.x0 = mediabox.y0 = 0;
1064 mediabox.x1 = 900;
1065 mediabox.y1 = 900;
1069 break;
1071 default:
1072 ARSERT (0 && state.type);
1075 if (state.pagedimcount == 0
1076 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1077 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1078 size_t size;
1080 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1081 state.pagedims = realloc (state.pagedims, size);
1082 if (!state.pagedims) {
1083 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1084 size, state.pagedimcount + 1);
1087 p = &state.pagedims[state.pagedimcount++];
1088 p->rotate = rotate;
1089 p->mediabox = mediabox;
1090 p->pageno = pageno;
1093 end = now ();
1094 if (state.trimmargins) {
1095 printd ("progress 1 Trimmed %d pages in %f seconds",
1096 state.pagecount, end - start);
1098 else {
1099 printd ("vmsg Processed %d pages in %f seconds",
1100 state.pagecount, end - start);
1102 state.trimanew = 0;
1103 if (trimf) {
1104 if (fclose (trimf)) {
1105 err (1, "fclose");
1110 static void layout (void)
1112 int pindex;
1113 fz_rect box;
1114 fz_matrix ctm;
1115 double zoom, w, maxw = 0;
1116 struct pagedim *p = state.pagedims;
1118 if (state.proportional) {
1119 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1120 fz_matrix rm;
1122 fz_rotate (&rm, p->rotate + state.rotate);
1123 box = p->mediabox;
1124 fz_transform_rect (&box, &rm);
1125 w = box.x1 - box.x0;
1126 maxw = MAX (w, maxw);
1130 p = state.pagedims;
1131 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1132 fz_rect rect;
1133 fz_matrix tm, sm, rm;
1135 fz_rotate (&ctm, state.rotate);
1136 fz_rotate (&rm, p->rotate + state.rotate);
1137 box = p->mediabox;
1138 fz_transform_rect (&box, &rm);
1139 w = box.x1 - box.x0;
1141 if (state.proportional) {
1142 double scale = w / maxw;
1143 zoom = (state.w / w) * scale;
1145 else {
1146 zoom = state.w / w;
1149 fz_scale (&p->zoomctm, zoom, zoom);
1150 fz_concat (&ctm, &p->zoomctm, &ctm);
1152 fz_rotate (&rm, p->rotate);
1153 p->pagebox = p->mediabox;
1154 fz_transform_rect (&p->pagebox, &rm);
1155 p->pagebox.x1 -= p->pagebox.x0;
1156 p->pagebox.y1 -= p->pagebox.y0;
1157 p->pagebox.x0 = 0;
1158 p->pagebox.y0 = 0;
1159 rect = p->pagebox;
1160 fz_transform_rect (&rect, &ctm);
1161 fz_round_rect (&p->bounds, &rect);
1163 p->left = state.proportional ? ((maxw - w) * zoom) / 2.0 : 0;
1164 p->ctm = ctm;
1166 fz_translate (&tm, 0, -p->mediabox.y1);
1167 fz_scale (&sm, zoom, -zoom);
1168 fz_concat (&ctm, &tm, &sm);
1169 fz_concat (&p->lctm, &ctm, &rm);
1171 p->tctmready = 0;
1174 while (p-- != state.pagedims) {
1175 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1176 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1177 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1178 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1179 int w = x1 - x0;
1180 int h = y1 - y0;
1182 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1186 static struct anchor { int n; int y; int h; } desttoanchor (fz_link_dest *dest)
1188 int i;
1189 struct anchor a;
1190 struct pagedim *pdim = state.pagedims;
1192 a.n = -1;
1193 a.y = 0;
1194 for (i = 0; i < state.pagedimcount; ++i) {
1195 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1196 break;
1197 pdim = &state.pagedims[i];
1199 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1200 fz_point p;
1201 p.x = 0;
1202 p.y = dest->ld.gotor.lt.y;
1203 fz_transform_point (&p, &pdim->lctm);
1204 a.y = p.y;
1206 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1207 double y0, y1;
1209 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1210 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1211 a.h = y1 - y0;
1212 a.n = dest->ld.gotor.page;
1214 return a;
1217 static void recurse_outline (fz_outline *outline, int level)
1219 while (outline) {
1220 struct anchor a = desttoanchor (&outline->dest);
1222 if (a.n >= 0) {
1223 printd ("o %d %d %d %d %s",
1224 level, a.n, a.y, a.h, outline->title);
1226 if (outline->down) {
1227 recurse_outline (outline->down, level + 1);
1229 outline = outline->next;
1233 static void process_outline (void)
1235 fz_outline *outline;
1237 if (!state.needoutline) return;
1239 state.needoutline = 0;
1240 switch (state.type) {
1241 case DPDF:
1242 outline = pdf_load_outline (state.u.pdf);
1243 break;
1244 case DXPS:
1245 outline = xps_load_outline (state.u.xps);
1246 break;
1247 default:
1248 outline = NULL;
1249 break;
1251 if (outline) {
1252 recurse_outline (outline, 0);
1253 fz_free_outline (state.ctx, outline);
1257 static char *strofspan (fz_text_span *span)
1259 char *p;
1260 char utf8[10];
1261 fz_text_char *ch;
1262 size_t size = 0, cap = 80;
1264 p = malloc (cap + 1);
1265 if (!p) return NULL;
1267 for (ch = span->text; ch < span->text + span->len; ++ch) {
1268 int n = fz_runetochar (utf8, ch->c);
1269 if (size + n > cap) {
1270 cap *= 2;
1271 p = realloc (p, cap + 1);
1272 if (!p) return NULL;
1275 memcpy (p + size, utf8, n);
1276 size += n;
1278 p[size] = 0;
1279 return p;
1282 static int matchspan (regex_t *re, fz_text_span *span, fz_matrix ctm,
1283 int stop, int pageno, double start)
1285 int ret;
1286 char *p;
1287 regmatch_t rm;
1288 int a, b, c;
1289 fz_rect *sb, *eb;
1290 fz_point p1, p2, p3, p4;
1292 p = strofspan (span);
1293 if (!p) return -1;
1295 ret = regexec (re, p, 1, &rm, 0);
1296 if (ret) {
1297 free (p);
1298 if (ret != REG_NOMATCH) {
1299 size_t size;
1300 char errbuf[80];
1301 size = regerror (ret, re, errbuf, sizeof (errbuf));
1302 printd ("msg regexec error `%.*s'",
1303 (int) size, errbuf);
1304 return -1;
1306 return 0;
1308 else {
1309 int l = span->len;
1310 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1311 c += fz_runelen (span->text[a].c);
1313 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1314 c += fz_runelen (span->text[b].c);
1317 if (fz_runelen (span->text[b].c) > 1) {
1318 b = MAX (0, b-1);
1320 sb = &span->text[MIN (a, l-1)].bbox;
1321 eb = &span->text[MIN (b, l-1)].bbox;
1323 p1.x = sb->x0;
1324 p1.y = sb->y0;
1325 p2.x = eb->x1;
1326 p2.y = sb->y0;
1327 p3.x = eb->x1;
1328 p3.y = eb->y1;
1329 p4.x = sb->x0;
1330 p4.y = eb->y1;
1332 if (!stop) {
1333 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1334 pageno, 1,
1335 p1.x, p1.y,
1336 p2.x, p2.y,
1337 p3.x, p3.y,
1338 p4.x, p4.y);
1340 printd ("progress 1 found at %d `%.*s' in %f sec",
1341 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1342 now () - start);
1344 else {
1345 printd ("match %d %d %f %f %f %f %f %f %f %f",
1346 pageno, 2,
1347 p1.x, p1.y,
1348 p2.x, p2.y,
1349 p3.x, p3.y,
1350 p4.x, p4.y);
1352 free (p);
1353 return 1;
1357 static int compareblocks (const void *l, const void *r)
1359 fz_text_block const *ls = l;
1360 fz_text_block const* rs = r;
1361 return ls->bbox.y0 - rs->bbox.y0;
1364 /* wishful thinking function */
1365 static void search (regex_t *re, int pageno, int y, int forward)
1367 int i, j;
1368 fz_matrix ctm;
1369 fz_device *tdev;
1370 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1371 fz_text_page *text;
1372 fz_text_sheet *sheet;
1373 struct pagedim *pdim, *pdimprev;
1374 int stop = 0, niters = 0;
1375 double start, end;
1377 if (!(state.type == DPDF || state.type == DXPS))
1378 return;
1380 start = now ();
1381 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1382 if (niters++ == 5) {
1383 niters = 0;
1384 if (hasdata ()) {
1385 printd ("progress 1 attention requested aborting search at %d",
1386 pageno);
1387 stop = 1;
1389 else {
1390 printd ("progress %f searching in page %d",
1391 (double) (pageno + 1) / state.pagecount,
1392 pageno);
1395 pdimprev = NULL;
1396 for (i = 0; i < state.pagedimcount; ++i) {
1397 pdim = &state.pagedims[i];
1398 if (pdim->pageno == pageno) {
1399 goto found;
1401 if (pdim->pageno > pageno) {
1402 pdim = pdimprev;
1403 goto found;
1405 pdimprev = pdim;
1407 pdim = pdimprev;
1408 found:
1410 sheet = fz_new_text_sheet (state.ctx);
1411 text = fz_new_text_page (state.ctx, &fz_infinite_rect);
1412 tdev = fz_new_text_device (state.ctx, sheet, text);
1414 switch (state.type) {
1415 case DPDF:
1416 u.ptr = NULL;
1417 fz_try (state.ctx) {
1418 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1419 trimctm (u.pdfpage, pdim - state.pagedims);
1420 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1421 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1423 fz_catch (state.ctx) {
1424 fz_free_device (tdev);
1425 u.ptr = NULL;
1426 goto nextiter;
1428 break;
1430 case DXPS:
1431 u.xpspage = xps_load_page (state.u.xps, pageno);
1432 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1433 break;
1435 default:
1436 ARSERT (0 && state.type);
1439 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1440 fz_free_device (tdev);
1442 for (j = 0; j < text->len; ++j) {
1443 int k;
1444 fz_text_block *block;
1446 block = &text->blocks[forward ? j : text->len - 1 - j];
1448 for (k = 0; k < block->len; ++k) {
1449 fz_text_line *line;
1450 fz_text_span *span;
1452 if (forward) {
1453 line = &block->lines[k];
1454 if (line->bbox.y0 < y + 1) continue;
1456 else {
1457 line = &block->lines[block->len - 1 - k];
1458 if (line->bbox.y0 > y - 1) continue;
1461 for (span = line->spans;
1462 span < line->spans + line->len;
1463 ++span) {
1465 switch (matchspan (re, span, ctm, stop, pageno, start)) {
1466 case 0: break;
1467 case 1: stop = 1; break;
1468 case -1: stop = 1; goto endloop;
1473 nextiter:
1474 if (forward) {
1475 pageno += 1;
1476 y = 0;
1478 else {
1479 pageno -= 1;
1480 y = INT_MAX;
1482 endloop:
1483 fz_free_text_page (state.ctx, text);
1484 fz_free_text_sheet (state.ctx, sheet);
1485 if (u.ptr) {
1486 state.freepage (u.ptr);
1489 end = now ();
1490 if (!stop) {
1491 printd ("progress 1 no matches %f sec", end - start);
1493 printd ("clearrects");
1496 static void set_tex_params (int colorspace)
1498 union {
1499 unsigned char b;
1500 unsigned int s;
1501 } endianness = {1};
1503 switch (colorspace) {
1504 case 0:
1505 state.texiform = GL_RGBA8;
1506 state.texform = GL_RGBA;
1507 state.texty = GL_UNSIGNED_BYTE;
1508 state.colorspace = fz_device_rgb;
1509 break;
1510 case 1:
1511 state.texiform = GL_RGBA8;
1512 state.texform = GL_BGRA;
1513 state.texty = endianness.s > 1
1514 ? GL_UNSIGNED_INT_8_8_8_8
1515 : GL_UNSIGNED_INT_8_8_8_8_REV;
1516 state.colorspace = fz_device_bgr;
1517 break;
1518 case 2:
1519 state.texiform = GL_LUMINANCE_ALPHA;
1520 state.texform = GL_LUMINANCE_ALPHA;
1521 state.texty = GL_UNSIGNED_BYTE;
1522 state.colorspace = fz_device_gray;
1523 break;
1524 default:
1525 errx (1, "invalid colorspce %d", colorspace);
1529 static void realloctexts (int texcount)
1531 size_t size;
1533 if (texcount == state.texcount) return;
1535 if (texcount < state.texcount) {
1536 glDeleteTextures (state.texcount - texcount,
1537 state.texids + texcount);
1540 size = texcount * sizeof (*state.texids);
1541 state.texids = realloc (state.texids, size);
1542 if (!state.texids) {
1543 err (1, "realloc texids %" FMT_s, size);
1546 size = texcount * sizeof (*state.texowners);
1547 state.texowners = realloc (state.texowners, size);
1548 if (!state.texowners) {
1549 err (1, "realloc texowners %" FMT_s, size);
1551 if (texcount > state.texcount) {
1552 int i;
1554 glGenTextures (texcount - state.texcount,
1555 state.texids + state.texcount);
1556 for (i = state.texcount; i < texcount; ++i) {
1557 state.texowners[i].w = -1;
1558 state.texowners[i].slice = NULL;
1561 state.texcount = texcount;
1562 state.texindex = 0;
1565 static char *mbtoutf8 (char *s)
1567 char *p, *r;
1568 wchar_t *tmp;
1569 size_t i, ret, len;
1571 len = mbstowcs (NULL, s, strlen (s));
1572 if (len == 0) {
1573 return s;
1575 else {
1576 if (len == (size_t) -1) {
1577 return s;
1581 tmp = malloc (len * sizeof (wchar_t));
1582 if (!tmp) {
1583 return s;
1586 ret = mbstowcs (tmp, s, len);
1587 if (ret == (size_t) -1) {
1588 free (tmp);
1589 return s;
1592 len = 0;
1593 for (i = 0; i < ret; ++i) {
1594 len += fz_runelen (tmp[i]);
1597 p = r = malloc (len + 1);
1598 if (!r) {
1599 free (tmp);
1600 return s;
1603 for (i = 0; i < ret; ++i) {
1604 p += fz_runetochar (p, tmp[i]);
1606 *p = 0;
1607 free (tmp);
1608 return r;
1611 CAMLprim value ml_mbtoutf8 (value s_v)
1613 CAMLparam1 (s_v);
1614 CAMLlocal1 (ret_v);
1615 char *s, *r;
1617 s = String_val (s_v);
1618 r = mbtoutf8 (s);
1619 if (r == s) {
1620 ret_v = s_v;
1622 else {
1623 ret_v = caml_copy_string (r);
1624 free (r);
1626 CAMLreturn (ret_v);
1629 static void * mainloop (void *unused)
1631 char *p = NULL;
1632 int len, ret, oldlen = 0;
1634 for (;;) {
1635 len = readlen ();
1636 if (len == 0) {
1637 errx (1, "readlen returned 0");
1640 if (oldlen < len + 1) {
1641 p = realloc (p, len + 1);
1642 if (!p) {
1643 err (1, "realloc %d failed", len + 1);
1645 oldlen = len + 1;
1647 readdata (p, len);
1648 p[len] = 0;
1650 if (!strncmp ("open", p, 4)) {
1651 size_t filenamelen;
1652 int wthack, off;
1653 char *password;
1654 char *filename;
1655 char *utf8filename;
1657 ret = sscanf (p + 5, " %d %n", &wthack, &off);
1658 if (ret != 1) {
1659 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1662 filename = p + 5 + off;
1663 filenamelen = strlen (filename);
1664 password = filename + filenamelen + 1;
1666 lock ("open");
1667 openxref (filename, password);
1668 pdfinfo ();
1669 initpdims ();
1670 unlock ("open");
1672 if (!wthack) {
1673 utf8filename = mbtoutf8 (filename);
1674 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1675 if (utf8filename != filename) {
1676 free (utf8filename);
1679 state.needoutline = 1;
1681 else if (!strncmp ("cs", p, 2)) {
1682 int i, colorspace;
1684 ret = sscanf (p + 2, " %d", &colorspace);
1685 if (ret != 1) {
1686 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1688 lock ("cs");
1689 set_tex_params (colorspace);
1690 for (i = 0; i < state.texcount; ++i) {
1691 state.texowners[i].w = -1;
1692 state.texowners[i].slice = NULL;
1694 unlock ("cs");
1696 else if (!strncmp ("freepage", p, 8)) {
1697 void *ptr;
1699 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1700 if (ret != 1) {
1701 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1703 freepage (ptr);
1705 else if (!strncmp ("freetile", p, 8)) {
1706 void *ptr;
1708 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1709 if (ret != 1) {
1710 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1712 freetile (ptr);
1714 else if (!strncmp ("search", p, 6)) {
1715 int icase, pageno, y, ret, len2, forward;
1716 char *pattern;
1717 regex_t re;
1719 ret = sscanf (p + 6, " %d %d %d %d,%n",
1720 &icase, &pageno, &y, &forward, &len2);
1721 if (ret != 4) {
1722 errx (1, "malformed search `%s' ret=%d", p, ret);
1725 pattern = p + 6 + len2;
1726 ret = regcomp (&re, pattern,
1727 REG_EXTENDED | (icase ? REG_ICASE : 0));
1728 if (ret) {
1729 char errbuf[80];
1730 size_t size;
1732 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1733 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1735 else {
1736 search (&re, pageno, y, forward);
1737 regfree (&re);
1740 else if (!strncmp ("geometry", p, 8)) {
1741 int w, h;
1743 printd ("clear");
1744 ret = sscanf (p + 8, " %d %d", &w, &h);
1745 if (ret != 2) {
1746 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1749 lock ("geometry");
1750 state.h = h;
1751 if (w != state.w) {
1752 int i;
1753 state.w = w;
1754 for (i = 0; i < state.texcount; ++i) {
1755 state.texowners[i].slice = NULL;
1758 layout ();
1759 process_outline ();
1761 state.gen++;
1762 unlock ("geometry");
1763 printd ("continue %d", state.pagecount);
1765 else if (!strncmp ("reqlayout", p, 9)) {
1766 char *nameddest;
1767 int rotate, proportional, off;
1769 printd ("clear");
1770 ret = sscanf (p + 9, " %d %d %n", &rotate, &proportional, &off);
1771 if (ret != 2) {
1772 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1774 lock ("reqlayout");
1775 if (state.rotate != rotate || state.proportional != proportional) {
1776 state.gen += 1;
1778 state.rotate = rotate;
1779 state.proportional = proportional;
1780 layout ();
1781 process_outline ();
1783 nameddest = p + 9 + off;
1784 if (state.type == DPDF && nameddest && *nameddest) {
1785 struct anchor a;
1786 fz_link_dest dest;
1787 pdf_obj *needle, *obj;
1789 needle = pdf_new_string (state.ctx, nameddest,
1790 strlen (nameddest));
1791 obj = pdf_lookup_dest (state.u.pdf, needle);
1792 if (obj) {
1793 dest = pdf_parse_link_dest (state.u.pdf, obj);
1795 a = desttoanchor (&dest);
1796 if (a.n >= 0) {
1797 printd ("a %d %d %d", a.n, a.y, a.h);
1799 else {
1800 printd ("emsg failed to parse destination `%s'\n",
1801 nameddest);
1804 else {
1805 printd ("emsg destination `%s' not found\n",
1806 nameddest);
1808 pdf_drop_obj (needle);
1811 state.gen++;
1812 unlock ("reqlayout");
1813 printd ("continue %d", state.pagecount);
1815 else if (!strncmp ("page", p, 4)) {
1816 double a, b;
1817 struct page *page;
1818 int pageno, pindex, ret;
1820 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1821 if (ret != 2) {
1822 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1825 lock ("page");
1826 a = now ();
1827 page = loadpage (pageno, pindex);
1828 b = now ();
1829 unlock ("page");
1831 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1833 else if (!strncmp ("tile", p, 4)) {
1834 int x, y, w, h, ret;
1835 struct page *page;
1836 struct tile *tile;
1837 double a, b;
1838 void *data;
1840 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
1841 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
1842 if (ret != 6) {
1843 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1846 lock ("tile");
1847 a = now ();
1848 tile = rendertile (page, x, y, w, h, data);
1849 b = now ();
1850 unlock ("tile");
1852 printd ("tile %d %d %" FMT_ptr " %u %f",
1853 x, y,
1854 FMT_ptr_cast2 (tile),
1855 tile->w * tile->h * tile->pixmap->n,
1856 b - a);
1858 else if (!strncmp ("settrim", p, 7)) {
1859 int trimmargins;
1860 fz_irect fuzz;
1862 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1863 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1864 if (ret != 5) {
1865 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1867 printd ("clear");
1868 lock ("settrim");
1869 state.trimmargins = trimmargins;
1870 state.needoutline = 1;
1871 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1872 state.trimanew = 1;
1873 state.trimfuzz = fuzz;
1875 state.pagedimcount = 0;
1876 free (state.pagedims);
1877 state.pagedims = NULL;
1878 initpdims ();
1879 layout ();
1880 process_outline ();
1881 unlock ("settrim");
1882 printd ("continue %d", state.pagecount);
1884 else if (!strncmp ("sliceh", p, 6)) {
1885 int h;
1887 ret = sscanf (p + 6, " %d", &h);
1888 if (ret != 1) {
1889 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1891 if (h != state.sliceheight) {
1892 int i;
1894 state.sliceheight = h;
1895 for (i = 0; i < state.texcount; ++i) {
1896 state.texowners[i].w = -1;
1897 state.texowners[i].h = -1;
1898 state.texowners[i].slice = NULL;
1902 else if (!strncmp ("interrupt", p, 9)) {
1903 printd ("vmsg interrupted");
1905 else {
1906 errx (1, "unknown command %.*s", len, p);
1909 return 0;
1912 CAMLprim value ml_realloctexts (value texcount_v)
1914 CAMLparam1 (texcount_v);
1915 int ok;
1917 if (trylock ("ml_realloctexts")) {
1918 ok = 0;
1919 goto done;
1921 realloctexts (Int_val (texcount_v));
1922 ok = 1;
1923 unlock ("ml_realloctexts");
1925 done:
1926 CAMLreturn (Val_bool (ok));
1929 static void showsel (struct page *page, int ox, int oy)
1931 int seen = 0;
1932 fz_irect bbox;
1933 fz_rect rect;
1934 fz_text_line *line;
1935 fz_text_span *span;
1936 fz_text_block *block;
1937 struct mark first, last;
1939 first = page->fmark;
1940 last = page->lmark;
1942 if (!first.span || !last.span) return;
1944 glEnable (GL_BLEND);
1945 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1946 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1948 ox += state.pagedims[page->pdimno].bounds.x0;
1949 oy += state.pagedims[page->pdimno].bounds.y0;
1950 for (block = page->text->blocks;
1951 block < page->text->blocks + page->text->len;
1952 ++block) {
1953 for (line = block->lines;
1954 line < block->lines + block->len;
1955 ++line) {
1956 rect = fz_empty_rect;
1957 for (span = line->spans;
1958 span < line->spans + line->len;
1959 ++span) {
1960 int i, j, k;
1962 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1964 j = 0;
1965 k = span->len - 1;
1967 if (span == page->fmark.span && span == page->lmark.span) {
1968 seen = 1;
1969 j = MIN (first.i, last.i);
1970 k = MAX (first.i, last.i);
1972 else if (span == first.span) {
1973 seen = 1;
1974 j = first.i;
1976 else if (span == last.span) {
1977 seen = 1;
1978 k = last.i;
1981 if (seen) {
1982 for (i = j; i <= k; ++i) {
1983 fz_union_rect (&rect, &span->text[i].bbox);
1985 fz_round_rect (&bbox, &rect);
1986 lprintf ("%d %d %d %d oy=%d ox=%d\n",
1987 bbox.x0,
1988 bbox.y0,
1989 bbox.x1,
1990 bbox.y1,
1991 oy, ox);
1993 glRecti (bbox.x0 + ox, bbox.y0 + oy,
1994 bbox.x1 + ox, bbox.y1 + oy);
1995 if (span == last.span) {
1996 goto done;
2002 done:
2003 glDisable (GL_BLEND);
2006 #include "glfont.c"
2008 static void highlightlinks (struct page *page, int xoff, int yoff)
2010 fz_matrix ctm, tm, pm;
2011 fz_link *link, *links;
2013 switch (page->type) {
2014 case DPDF:
2015 links = page->u.pdfpage->links;
2016 break;
2018 case DXPS:
2019 links = page->u.xpspage->links;
2020 break;
2022 default:
2023 return;
2026 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2027 glEnable (GL_LINE_STIPPLE);
2028 glLineStipple (0.5, 0xcccc);
2030 xoff -= state.pagedims[page->pdimno].bounds.x0;
2031 yoff -= state.pagedims[page->pdimno].bounds.y0;
2032 fz_translate (&tm, xoff, yoff);
2033 pm = pagectm (page);
2034 fz_concat (&ctm, &pm, &tm);
2036 glBegin (GL_QUADS);
2037 for (link = links; link; link = link->next) {
2038 fz_point p1, p2, p3, p4;
2040 p1.x = link->rect.x0;
2041 p1.y = link->rect.y0;
2043 p2.x = link->rect.x1;
2044 p2.y = link->rect.y0;
2046 p3.x = link->rect.x1;
2047 p3.y = link->rect.y1;
2049 p4.x = link->rect.x0;
2050 p4.y = link->rect.y1;
2052 fz_transform_point (&p1, &ctm);
2053 fz_transform_point (&p2, &ctm);
2054 fz_transform_point (&p3, &ctm);
2055 fz_transform_point (&p4, &ctm);
2057 switch (link->dest.kind) {
2058 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2059 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2060 default: glColor3ub (0, 0, 0); break;
2063 glVertex2f (p1.x, p1.y);
2064 glVertex2f (p2.x, p2.y);
2065 glVertex2f (p3.x, p3.y);
2066 glVertex2f (p4.x, p4.y);
2068 glEnd ();
2070 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2071 glDisable (GL_LINE_STIPPLE);
2074 static int compareslinks (const void *l, const void *r)
2076 struct slink const *ls = l;
2077 struct slink const *rs = r;
2078 if (ls->bbox.y0 == rs->bbox.y0) {
2079 return rs->bbox.x0 - rs->bbox.x0;
2081 return ls->bbox.y0 - rs->bbox.y0;
2084 static void droptext (struct page *page)
2086 if (page->text) {
2087 fz_free_text_page (state.ctx, page->text);
2088 page->fmark.i = -1;
2089 page->lmark.i = -1;
2090 page->fmark.span = NULL;
2091 page->lmark.span = NULL;
2092 page->text = NULL;
2094 if (page->sheet) {
2095 fz_free_text_sheet (state.ctx, page->sheet);
2099 static void dropslinks (struct page *page)
2101 if (page->slinks) {
2102 free (page->slinks);
2103 page->slinks = NULL;
2104 page->slinkcount = 0;
2108 static void ensureslinks (struct page *page)
2110 fz_matrix ctm;
2111 int i, count = 0;
2112 size_t slinksize = sizeof (*page->slinks);
2113 fz_link *link, *links;
2115 if (state.gen != page->sgen) {
2116 dropslinks (page);
2117 page->sgen = state.gen;
2119 if (page->slinks) return;
2121 switch (page->type) {
2122 case DPDF:
2123 links = page->u.pdfpage->links;
2124 trimctm (page->u.pdfpage, page->pdimno);
2125 fz_concat (&ctm,
2126 &state.pagedims[page->pdimno].tctm,
2127 &state.pagedims[page->pdimno].ctm);
2128 break;
2130 case DXPS:
2131 links = page->u.xpspage->links;
2132 ctm = state.pagedims[page->pdimno].ctm;
2133 break;
2135 default:
2136 return;
2139 for (link = links; link; link = link->next) {
2140 count++;
2142 if (count > 0) {
2143 page->slinkcount = count;
2144 page->slinks = calloc (count, slinksize);
2145 if (!page->slinks) {
2146 err (1, "realloc slinks %d", count);
2149 for (i = 0, link = links; link; ++i, link = link->next) {
2150 fz_rect rect;
2152 rect = link->rect;
2153 fz_transform_rect (&rect, &ctm);
2154 page->slinks[i].link = link;
2155 fz_round_rect (&page->slinks[i].bbox, &rect);
2157 qsort (page->slinks, count, slinksize, compareslinks);
2161 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2162 static void fmt_linkn (char *s, unsigned int u)
2164 unsigned int len; unsigned int q;
2165 int zma = 'z' - 'a' + 1;
2166 len = 1; q = u;
2167 while (q > zma - 1) { ++len; q /= zma; }
2168 if (s) {
2169 s += len;
2170 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2171 /* handles u == 0 */
2173 s[len] = 0;
2176 static void highlightslinks (struct page *page, int xoff, int yoff,
2177 int noff, char *targ, int tlen, int hfsize)
2179 int i;
2180 char buf[40];
2181 struct slink *slink;
2182 double x0, y0, x1, y1, w;
2184 ensureslinks (page);
2185 glColor3ub (0xc3, 0xb0, 0x91);
2186 for (i = 0; i < page->slinkcount; ++i) {
2187 fmt_linkn (buf, i + noff);
2188 if (!tlen || !strncmp (targ, buf, tlen)) {
2189 slink = &page->slinks[i];
2191 x0 = slink->bbox.x0 + xoff - 5;
2192 y1 = slink->bbox.y0 + yoff - 5;
2193 y0 = y1 + 10 + hfsize;
2194 w = measure_string (state.face, hfsize, buf);
2195 x1 = x0 + w + 10;
2196 glRectd (x0, y0, x1, y1);
2200 glEnable (GL_BLEND);
2201 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2202 glEnable (GL_TEXTURE_2D);
2203 glColor3ub (0, 0, 0);
2204 for (i = 0; i < page->slinkcount; ++i) {
2205 fmt_linkn (buf, i + noff);
2206 if (!tlen || !strncmp (targ, buf, tlen)) {
2207 slink = &page->slinks[i];
2209 x0 = slink->bbox.x0 + xoff;
2210 y0 = slink->bbox.y0 + yoff + hfsize;
2211 draw_string (state.face, hfsize, x0, y0, buf);
2214 glDisable (GL_TEXTURE_2D);
2215 glDisable (GL_BLEND);
2219 static void uploadslice (struct tile *tile, struct slice *slice)
2221 int offset;
2222 struct slice *slice1;
2223 unsigned char *texdata;
2225 offset = 0;
2226 for (slice1 = tile->slices; slice != slice1; slice1++) {
2227 offset += slice1->h * tile->w * tile->pixmap->n;
2229 if (slice->texindex != -1 && slice->texindex < state.texcount
2230 && state.texowners[slice->texindex].slice == slice) {
2231 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2233 else {
2234 int subimage = 0;
2235 int texindex = state.texindex++ % state.texcount;
2237 if (state.texowners[texindex].w == tile->w) {
2238 if (state.texowners[texindex].h >= slice->h) {
2239 subimage = 1;
2241 else {
2242 state.texowners[texindex].h = slice->h;
2245 else {
2246 state.texowners[texindex].h = slice->h;
2249 state.texowners[texindex].w = tile->w;
2250 state.texowners[texindex].slice = slice;
2251 slice->texindex = texindex;
2253 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2254 if (tile->pbo) {
2255 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2256 texdata = 0;
2258 else {
2259 texdata = tile->pixmap->samples;
2261 if (subimage) {
2262 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2266 tile->w,
2267 slice->h,
2268 state.texform,
2269 state.texty,
2270 texdata+offset
2273 else {
2274 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2276 state.texiform,
2277 tile->w,
2278 slice->h,
2280 state.texform,
2281 state.texty,
2282 texdata+offset
2285 if (tile->pbo) {
2286 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2291 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2293 CAMLparam2 (args_v, ptr_v);
2294 int dispx = Int_val (Field (args_v, 0));
2295 int dispy = Int_val (Field (args_v, 1));
2296 int dispw = Int_val (Field (args_v, 2));
2297 int disph = Int_val (Field (args_v, 3));
2298 int tilex = Int_val (Field (args_v, 4));
2299 int tiley = Int_val (Field (args_v, 5));
2300 char *s = String_val (ptr_v);
2301 struct tile *tile = parse_pointer ("ml_drawtile", s);
2303 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2305 int slicey, firstslice;
2306 struct slice *slice;
2308 firstslice = tiley / tile->sliceheight;
2309 slice = &tile->slices[firstslice];
2310 slicey = tiley % tile->sliceheight;
2312 while (disph > 0) {
2313 int dh;
2315 dh = slice->h - slicey;
2316 dh = MIN (disph, dh);
2317 uploadslice (tile, slice);
2319 glBegin (GL_QUADS);
2321 glTexCoord2i (tilex, slicey);
2322 glVertex2i (dispx, dispy);
2324 glTexCoord2i (tilex+dispw, slicey);
2325 glVertex2i (dispx+dispw, dispy);
2327 glTexCoord2i (tilex+dispw, slicey+dh);
2328 glVertex2i (dispx+dispw, dispy+dh);
2330 glTexCoord2i (tilex, slicey+dh);
2331 glVertex2i (dispx, dispy+dh);
2333 glEnd ();
2335 dispy += dh;
2336 disph -= dh;
2337 slice++;
2338 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2339 slicey = 0;
2342 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2343 CAMLreturn (Val_unit);
2346 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2347 value xoff_v, value yoff_v,
2348 value li_v)
2350 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2351 int xoff = Int_val (xoff_v);
2352 int yoff = Int_val (yoff_v);
2353 int noff = Int_val (Field (li_v, 0));
2354 char *targ = String_val (Field (li_v, 1));
2355 int tlen = caml_string_length (Field (li_v, 1));
2356 int hfsize = Int_val (Field (li_v, 2));
2357 char *s = String_val (ptr_v);
2358 int hlmask = Int_val (hlinks_v);
2359 struct page *page = parse_pointer ("ml_postprocess", s);
2361 if (!page->u.ptr) {
2362 /* deal with loadpage failed pages */
2363 goto done;
2366 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2367 if (trylock ("ml_postprocess")) {
2368 noff = 0;
2369 goto done;
2371 if (hlmask & 2) {
2372 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2373 noff = page->slinkcount;
2375 showsel (page, xoff, yoff);
2376 unlock ("ml_postprocess");
2378 done:
2379 CAMLreturn (Val_int (noff));
2382 static fz_link *getlink (struct page *page, int x, int y)
2384 fz_point p;
2385 fz_matrix ctm;
2386 const fz_matrix *tctm;
2387 fz_link *link, *links;
2389 switch (page->type) {
2390 case DPDF:
2391 trimctm (page->u.pdfpage, page->pdimno);
2392 tctm = &state.pagedims[page->pdimno].tctm;
2393 links = page->u.pdfpage->links;
2394 break;
2396 case DXPS:
2397 tctm = &fz_identity;
2398 links = page->u.xpspage->links;
2399 break;
2401 default:
2402 return NULL;
2404 p.x = x;
2405 p.y = y;
2407 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2408 fz_invert_matrix (&ctm, &ctm);
2409 fz_transform_point (&p, &ctm);
2411 for (link = links; link; link = link->next) {
2412 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2413 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2414 return link;
2418 return NULL;
2421 static void ensuretext (struct page *page)
2423 if (state.gen != page->tgen) {
2424 droptext (page);
2425 page->tgen = state.gen;
2427 if (!page->text) {
2428 fz_matrix ctm;
2429 fz_device *tdev;
2431 page->text = fz_new_text_page (state.ctx, &fz_infinite_rect);
2432 page->sheet = fz_new_text_sheet (state.ctx);
2433 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2434 ctm = pagectm (page);
2435 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2436 qsort (page->text->blocks, page->text->len,
2437 sizeof (*page->text->blocks), compareblocks);
2438 fz_free_device (tdev);
2442 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2444 CAMLparam2 (start_page_v, dir_v);
2445 CAMLlocal1 (ret_v);
2446 int i, dir = Int_val (dir_v);
2447 int start_page = Int_val (start_page_v);
2448 int end_page = dir > 0 ? state.pagecount : -1;
2450 ret_v = Val_int (0);
2451 if (!(state.type == DPDF || state.type == DXPS)) {
2452 goto done;
2455 lock ("ml_findpage_with_links");
2456 for (i = start_page + dir; i != end_page; i += dir) {
2457 int found;
2459 switch (state.type) {
2460 case DPDF:
2462 pdf_page *page = NULL;
2464 fz_try (state.ctx) {
2465 page = pdf_load_page (state.u.pdf, i);
2466 found = !!page->links;
2468 fz_catch (state.ctx) {
2469 found = 0;
2471 if (page) {
2472 freepdfpage (page);
2475 break;
2476 case DXPS:
2478 xps_page *page = xps_load_page (state.u.xps, i);
2479 found = !!page->links;
2480 freexpspage (page);
2482 break;
2484 default:
2485 ARSERT ("invalid document type");
2488 if (found) {
2489 ret_v = caml_alloc_small (1, 1);
2490 Field (ret_v, 0) = Val_int (i);
2491 goto unlock;
2494 unlock:
2495 unlock ("ml_findpage_with_links");
2497 done:
2498 CAMLreturn (ret_v);
2501 enum { dir_first, dir_last};
2502 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2504 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2506 CAMLparam2 (ptr_v, dir_v);
2507 CAMLlocal2 (ret_v, pos_v);
2508 struct page *page;
2509 int dirtag, i, slinkindex;
2510 struct slink *found = NULL ,*slink;
2511 char *s = String_val (ptr_v);
2513 page = parse_pointer ("ml_findlink", s);
2514 ret_v = Val_int (0);
2515 if (trylock ("ml_findlink")) {
2516 goto done;
2519 ensureslinks (page);
2521 if (Is_block (dir_v)) {
2522 dirtag = Tag_val (dir_v);
2523 switch (dirtag) {
2524 case dir_first_visible:
2526 int x0, y0, dir, first_index, last_index;
2528 pos_v = Field (dir_v, 0);
2529 x0 = Int_val (Field (pos_v, 0));
2530 y0 = Int_val (Field (pos_v, 1));
2531 dir = Int_val (Field (pos_v, 2));
2533 if (dir >= 0) {
2534 dir = 1;
2535 first_index = 0;
2536 last_index = page->slinkcount;
2538 else {
2539 first_index = page->slinkcount - 1;
2540 last_index = -1;
2543 for (i = first_index; i != last_index; i += dir) {
2544 slink = &page->slinks[i];
2545 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2546 found = slink;
2547 break;
2551 break;
2553 case dir_left:
2554 slinkindex = Int_val (Field (dir_v, 0));
2555 found = &page->slinks[slinkindex];
2556 for (i = slinkindex - 1; i >= 0; --i) {
2557 slink = &page->slinks[i];
2558 if (slink->bbox.x0 < found->bbox.x0) {
2559 found = slink;
2560 break;
2563 break;
2565 case dir_right:
2566 slinkindex = Int_val (Field (dir_v, 0));
2567 found = &page->slinks[slinkindex];
2568 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2569 slink = &page->slinks[i];
2570 if (slink->bbox.x0 > found->bbox.x0) {
2571 found = slink;
2572 break;
2575 break;
2577 case dir_down:
2578 slinkindex = Int_val (Field (dir_v, 0));
2579 found = &page->slinks[slinkindex];
2580 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2581 slink = &page->slinks[i];
2582 if (slink->bbox.y0 >= found->bbox.y0) {
2583 found = slink;
2584 break;
2587 break;
2589 case dir_up:
2590 slinkindex = Int_val (Field (dir_v, 0));
2591 found = &page->slinks[slinkindex];
2592 for (i = slinkindex - 1; i >= 0; --i) {
2593 slink = &page->slinks[i];
2594 if (slink->bbox.y0 <= found->bbox.y0) {
2595 found = slink;
2596 break;
2599 break;
2602 else {
2603 dirtag = Int_val (dir_v);
2604 switch (dirtag) {
2605 case dir_first:
2606 found = page->slinks;
2607 break;
2609 case dir_last:
2610 if (page->slinks) {
2611 found = page->slinks + (page->slinkcount - 1);
2613 break;
2616 if (found) {
2617 ret_v = caml_alloc_small (2, 1);
2618 Field (ret_v, 0) = Val_int (found - page->slinks);
2621 unlock ("ml_findlink");
2622 done:
2623 CAMLreturn (ret_v);
2626 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2628 #define LINKTOVAL \
2630 int pageno; \
2632 switch (link->dest.kind) { \
2633 case FZ_LINK_GOTO: \
2635 fz_point p; \
2637 pageno = link->dest.ld.gotor.page; \
2638 p.x = 0; \
2639 p.y = 0; \
2641 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2642 p.y = link->dest.ld.gotor.lt.y; \
2643 fz_transform_point (&p, &pdim->lctm); \
2645 tup_v = caml_alloc_tuple (2); \
2646 ret_v = caml_alloc_small (1, ugoto); \
2647 Field (tup_v, 0) = Val_int (pageno); \
2648 Field (tup_v, 1) = Val_int (p.y); \
2649 Field (ret_v, 0) = tup_v; \
2651 break; \
2653 case FZ_LINK_URI: \
2654 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2655 ret_v = caml_alloc_small (1, uuri); \
2656 Field (ret_v, 0) = str_v; \
2657 break; \
2659 case FZ_LINK_LAUNCH: \
2660 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2661 ret_v = caml_alloc_small (1, ulaunch); \
2662 Field (ret_v, 0) = str_v; \
2663 break; \
2665 case FZ_LINK_NAMED: \
2666 str_v = caml_copy_string (link->dest.ld.named.named); \
2667 ret_v = caml_alloc_small (1, unamed); \
2668 Field (ret_v, 0) = str_v; \
2669 break; \
2671 case FZ_LINK_GOTOR: \
2672 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2673 pageno = link->dest.ld.gotor.page; \
2674 tup_v = caml_alloc_tuple (2); \
2675 ret_v = caml_alloc_small (1, uremote); \
2676 Field (tup_v, 0) = str_v; \
2677 Field (tup_v, 1) = Val_int (pageno); \
2678 Field (ret_v, 0) = tup_v; \
2679 break; \
2681 default: \
2683 char buf[80]; \
2685 snprintf (buf, sizeof (buf), \
2686 "unhandled link kind %d", link->dest.kind); \
2687 str_v = caml_copy_string (buf); \
2688 ret_v = caml_alloc_small (1, uunexpected); \
2689 Field (ret_v, 0) = str_v; \
2691 break; \
2695 CAMLprim value ml_getlink (value ptr_v, value n_v)
2697 CAMLparam2 (ptr_v, n_v);
2698 CAMLlocal3 (ret_v, tup_v, str_v);
2699 fz_link *link;
2700 struct page *page;
2701 struct pagedim *pdim;
2702 char *s = String_val (ptr_v);
2704 ret_v = Val_int (0);
2705 if (trylock ("ml_getlink")) {
2706 goto done;
2709 page = parse_pointer ("ml_getlink", s);
2710 ensureslinks (page);
2711 pdim = &state.pagedims[page->pdimno];
2712 link = page->slinks[Int_val (n_v)].link;
2713 LINKTOVAL;
2715 unlock ("ml_getlink");
2716 done:
2717 CAMLreturn (ret_v);
2720 CAMLprim value ml_getlinkcount (value ptr_v)
2722 CAMLparam1 (ptr_v);
2723 struct page *page;
2724 char *s = String_val (ptr_v);
2726 page = parse_pointer ("ml_getlinkcount", s);
2727 CAMLreturn (Val_int (page->slinkcount));
2730 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2732 CAMLparam2 (ptr_v, n_v);
2733 CAMLlocal1 (ret_v);
2734 struct page *page;
2735 struct slink *slink;
2736 char *s = String_val (ptr_v);
2738 page = parse_pointer ("ml_getlinkrect", s);
2739 ret_v = caml_alloc_tuple (4);
2740 if (trylock ("ml_getlinkrect")) {
2741 Field (ret_v, 0) = Val_int (0);
2742 Field (ret_v, 1) = Val_int (0);
2743 Field (ret_v, 2) = Val_int (0);
2744 Field (ret_v, 3) = Val_int (0);
2745 goto done;
2747 ensureslinks (page);
2749 slink = &page->slinks[Int_val (n_v)];
2750 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2751 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2752 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2753 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2754 unlock ("ml_getlinkrect");
2756 done:
2757 CAMLreturn (ret_v);
2760 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2762 CAMLparam3 (ptr_v, x_v, y_v);
2763 CAMLlocal3 (ret_v, tup_v, str_v);
2764 fz_link *link;
2765 struct page *page;
2766 char *s = String_val (ptr_v);
2767 int x = Int_val (x_v), y = Int_val (y_v);
2768 struct pagedim *pdim;
2770 ret_v = Val_int (0);
2771 if (trylock ("ml_whatsunder")) {
2772 goto done;
2775 page = parse_pointer ("ml_whatsunder", s);
2776 pdim = &state.pagedims[page->pdimno];
2777 x += pdim->bounds.x0;
2778 y += pdim->bounds.y0;
2779 link = getlink (page, x, y);
2780 if (link) {
2781 LINKTOVAL;
2783 else {
2784 fz_rect *b;
2785 fz_text_block *block;
2787 ensuretext (page);
2788 for (block = page->text->blocks;
2789 block < page->text->blocks + page->text->len;
2790 ++block) {
2791 fz_text_line *line;
2793 b = &block->bbox;
2794 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2795 continue;
2797 for (line = block->lines;
2798 line < block->lines + block->len;
2799 ++line) {
2800 fz_text_span *span;
2802 b = &line->bbox;
2803 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2804 continue;
2806 for (span = line->spans;
2807 span < line->spans + line->len;
2808 ++span) {
2809 fz_text_char *ch;
2811 b = &span->bbox;
2812 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2813 continue;
2815 for (ch = span->text; ch < span->text + span->len; ++ch) {
2816 b = &ch->bbox;
2818 if (x >= b->x0 && x <= b->x1
2819 && y >= b->y0 && y <= b->y1) {
2820 const char *n2 =
2821 span->style->font && span->style->font->name
2822 ? span->style->font->name
2823 : "Span has no font name"
2825 FT_FaceRec *face = span->style->font->ft_face;
2826 if (face && face->family_name) {
2827 char *s;
2828 char *n1 = face->family_name;
2829 size_t l1 = strlen (n1);
2830 size_t l2 = strlen (n2);
2832 if (l1 != l2 || memcmp (n1, n2, l1)) {
2833 s = malloc (l1 + l2 + 2);
2834 if (s) {
2835 memcpy (s, n2, l2);
2836 s[l2] = '=';
2837 memcpy (s + l2 + 1, n1, l1 + 1);
2838 str_v = caml_copy_string (s);
2839 free (s);
2843 if (str_v == 0) {
2844 str_v = caml_copy_string (n2);
2846 ret_v = caml_alloc_small (1, utext);
2847 Field (ret_v, 0) = str_v;
2848 goto unlock;
2855 unlock:
2856 unlock ("ml_whatsunder");
2858 done:
2859 CAMLreturn (ret_v);
2862 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2864 CAMLparam2 (ptr_v, rect_v);
2865 fz_rect *b;
2866 struct page *page;
2867 struct pagedim *pdim;
2868 int i, x0, x1, y0, y1;
2869 char *s = String_val (ptr_v);
2870 int fi = 0, li = 0;
2871 fz_text_block *block;
2872 fz_text_span *span, *fspan, *lspan;
2873 fz_text_line *line, *fline = NULL, *lline = NULL;
2875 if (trylock ("ml_seltext")) {
2876 goto done;
2879 page = parse_pointer ("ml_seltext", s);
2880 ensuretext (page);
2882 pdim = &state.pagedims[page->pdimno];
2883 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2884 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2885 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2886 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2888 if (0) {
2889 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2890 glColor3ub (128, 128, 128);
2891 glRecti (x0, y0, x1, y1);
2892 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2895 fspan = lspan = NULL;
2897 for (block = page->text->blocks;
2898 block < page->text->blocks + page->text->len;
2899 ++block) {
2900 for (line = block->lines;
2901 line < block->lines + block->len;
2902 ++line) {
2903 for (span = line->spans;
2904 span < line->spans + line->len;
2905 ++span) {
2906 for (i = 0; i < span->len; ++i) {
2907 b = &span->text[i].bbox;
2908 int selected = 0;
2910 if (x0 >= b->x0 && x0 <= b->x1
2911 && y0 >= b->y0 && y0 <= b->y1) {
2912 fspan = span;
2913 fline = line;
2914 fi = i;
2915 selected = 1;
2917 if (x1 >= b->x0 && x1 <= b->x1
2918 && y1 >= b->y0 && y1 <= b->y1) {
2919 lspan = span;
2920 lline = line;
2921 li = i;
2922 selected = 1;
2924 if (0 && selected) {
2925 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2926 glColor3ub (128, 128, 128);
2927 glRecti (b->x0, b->y0, b->x1, b->y1);
2928 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2934 if (y1 < y0 || x1 < x0) {
2935 int swap = 0;
2937 if (fspan == lspan) {
2938 swap = 1;
2940 else {
2941 if (y1 < y0) {
2942 if (fline != lline) {
2943 swap = 1;
2948 if (swap) {
2949 i = fi;
2950 span = fspan;
2952 fi = li;
2953 fspan = lspan;
2955 li = i;
2956 lspan = span;
2960 page->fmark.i = fi;
2961 page->fmark.span = fspan;
2963 page->lmark.i = li;
2964 page->lmark.span = lspan;
2966 unlock ("ml_seltext");
2968 done:
2969 CAMLreturn (Val_unit);
2972 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
2974 char buf[4];
2975 int i, len, ret;
2977 for (i = a; i <= b; ++i) {
2978 len = fz_runetochar (buf, span->text[i].c);
2979 ret = fwrite (buf, len, 1, f);
2981 if (ret != 1) {
2982 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
2983 len, ret, strerror (errno));
2984 return -1;
2987 return 0;
2990 #ifdef __CYGWIN__
2991 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
2993 caml_failwith ("ml_popen not implemented under Cygwin");
2995 #else
2996 CAMLprim value ml_popen (value command_v, value fds_v)
2998 CAMLparam2 (command_v, fds_v);
2999 CAMLlocal2 (l_v, tup_v);
3000 int ret;
3001 char *msg = NULL;
3002 value earg_v = Nothing;
3003 posix_spawnattr_t attr;
3004 posix_spawn_file_actions_t fa;
3005 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
3007 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3008 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3011 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3012 msg = "posix_spawnattr_init";
3013 goto fail1;
3016 #ifdef POSIX_SPAWN_USEVFORK
3017 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3018 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3019 goto fail;
3021 #endif
3023 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3024 int fd1, fd2;
3026 tup_v = Field (l_v, 0);
3027 fd1 = Int_val (Field (tup_v, 0));
3028 fd2 = Int_val (Field (tup_v, 1));
3029 if (fd2 < 0) {
3030 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3031 msg = "posix_spawn_file_actions_addclose";
3032 earg_v = tup_v;
3033 goto fail;
3036 else {
3037 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3038 msg = "posix_spawn_file_actions_adddup2";
3039 earg_v = tup_v;
3040 goto fail;
3045 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3046 msg = "posix_spawn";
3047 goto fail;
3050 fail:
3051 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3052 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3055 fail1:
3056 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3057 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3058 strerror (ret));
3061 if (msg)
3062 unix_error (ret, msg, earg_v);
3064 CAMLreturn (Val_unit);
3066 #endif
3068 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3070 CAMLparam1 (ptr_v);
3071 FILE *f;
3072 int seen = 0;
3073 struct page *page;
3074 fz_text_line *line;
3075 fz_text_span *span;
3076 fz_text_block *block;
3077 int fd = Int_val (fd_v);
3078 char *s = String_val (ptr_v);
3080 if (trylock ("ml_copysel")) {
3081 goto done;
3084 page = parse_pointer ("ml_sopysel", s);
3086 if (!page->fmark.span || !page->lmark.span) {
3087 fprintf (stderr, "nothing to copy\n");
3088 goto unlock;
3091 f = fdopen (fd, "w");
3092 if (!f) {
3093 fprintf (stderr, "failed to fopen sel pipe: %s\n",
3094 strerror (errno));
3095 f = stdout;
3098 for (block = page->text->blocks;
3099 block < page->text->blocks + page->text->len;
3100 ++block) {
3101 for (line = block->lines;
3102 line < block->lines + block->len;
3103 ++line) {
3104 for (span = line->spans;
3105 span < line->spans + line->len;
3106 ++span) {
3107 int a, b;
3109 seen |= span == page->fmark.span || span == page->lmark.span;
3110 a = span == page->fmark.span ? page->fmark.i : 0;
3111 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3113 if (seen) {
3114 if (pipespan (f, span, a, b)) {
3115 goto close;
3117 if (span == line->spans + line->len - 1) {
3118 if (putc ('\n', f) == EOF) {
3119 fprintf (stderr,
3120 "failed break line on sel pipe: %s\n",
3121 strerror (errno));
3122 goto close;
3125 if (span == page->lmark.span) {
3126 goto endloop;
3132 endloop:
3133 page->lmark.span = NULL;
3134 page->fmark.span = NULL;
3136 close:
3137 if (f != stdout) {
3138 int ret = fclose (f);
3139 fd = -1;
3140 if (ret == -1) {
3141 if (errno != ECHILD) {
3142 fprintf (stderr, "failed to close sel pipe: %s\n",
3143 strerror (errno));
3147 unlock:
3148 unlock ("ml_copysel");
3150 done:
3151 if (fd >= 0) {
3152 if (close (fd)) {
3153 fprintf (stderr, "failed to close sel pipe: %s\n",
3154 strerror (errno));
3157 CAMLreturn (Val_unit);
3160 CAMLprim value ml_getpdimrect (value pagedimno_v)
3162 CAMLparam1 (pagedimno_v);
3163 CAMLlocal1 (ret_v);
3164 int pagedimno = Int_val (pagedimno_v);
3165 fz_rect box;
3167 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3168 if (trylock ("ml_getpdimrect")) {
3169 box = fz_empty_rect;
3171 else {
3172 box = state.pagedims[pagedimno].mediabox;
3173 unlock ("ml_getpdimrect");
3176 Store_double_field (ret_v, 0, box.x0);
3177 Store_double_field (ret_v, 1, box.x1);
3178 Store_double_field (ret_v, 2, box.y0);
3179 Store_double_field (ret_v, 3, box.y1);
3181 CAMLreturn (ret_v);
3184 static double getmaxw (void)
3186 int i;
3187 struct pagedim *p;
3188 double maxw = 0.0;
3190 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3191 double x0, x1, w;
3193 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
3194 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
3196 w = x1 - x0;
3197 maxw = MAX (w, maxw);
3199 return maxw;
3202 CAMLprim value ml_getmaxw (value unit_v)
3204 CAMLparam1 (unit_v);
3205 CAMLlocal1 (ret_v);
3206 double maxw = 0.0;
3208 if (trylock ("ml_getmaxw")) {
3209 goto done;
3211 maxw = getmaxw ();
3212 unlock ("ml_getmaxw");
3213 done:
3214 ret_v = caml_copy_double (maxw);
3215 CAMLreturn (ret_v);
3218 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3219 value dw_v, value cols_v)
3221 CAMLparam3 (winw_v, winh_v, dw_v);
3222 CAMLlocal1 (ret_v);
3223 int i;
3224 double zoom = 1.0;
3225 double maxw = 0.0, maxh = 0.0;
3226 struct pagedim *p;
3227 double winw = Int_val (winw_v);
3228 double winh = Int_val (winh_v);
3229 double dw = Int_val (dw_v);
3230 double cols = Int_val (cols_v);
3231 double pw = 1.0, ph = 1.0, aspect;
3233 if (trylock ("ml_zoom_for_height")) {
3234 goto done;
3237 if (state.proportional) {
3238 maxw = getmaxw () / cols;
3241 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3242 fz_rect rect;
3243 fz_matrix rm;
3244 double x0, x1, y0, y1, w, h, scaledh, scale;
3246 fz_rotate (&rm, p->rotate + state.rotate);
3247 rect = p->mediabox;
3248 fz_transform_rect (&rect, &rm);
3249 x0 = MIN (rect.x0, rect.x1);
3250 x1 = MAX (rect.x0, rect.x1);
3251 y0 = MIN (rect.y0, rect.y1);
3252 y1 = MAX (rect.y0, rect.y1);
3254 w = (x1 - x0) / cols;
3255 h = y1 - y0;
3257 if (state.proportional) {
3258 scale = w / maxw;
3259 scaledh = h * scale;
3261 else {
3262 scale = 1.0;
3263 scaledh = h;
3266 if (scaledh > maxh) {
3267 maxh = scaledh;
3268 ph = scaledh;
3269 pw = w * scale;
3273 aspect = pw / ph;
3274 zoom = (winh * aspect + dw) / winw;
3276 unlock ("ml_zoom_for_height");
3277 done:
3278 ret_v = caml_copy_double (zoom);
3279 CAMLreturn (ret_v);
3282 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3284 CAMLparam4 (pt_v, x_v, y_v, string_v);
3285 CAMLlocal1 (ret_v);
3286 int pt = Int_val(pt_v);
3287 int x = Int_val (x_v);
3288 int y = Int_val (y_v);
3289 double w;
3291 w = draw_string (state.face, pt, x, y, String_val (string_v));
3292 ret_v = caml_copy_double (w);
3293 CAMLreturn (ret_v);
3296 CAMLprim value ml_measure_string (value pt_v, value string_v)
3298 CAMLparam2 (pt_v, string_v);
3299 CAMLlocal1 (ret_v);
3300 int pt = Int_val (pt_v);
3301 double w;
3303 w = measure_string (state.face, pt, String_val (string_v));
3304 ret_v = caml_copy_double (w);
3305 CAMLreturn (ret_v);
3308 CAMLprim value ml_getpagebox (value opaque_v)
3310 CAMLparam1 (opaque_v);
3311 CAMLlocal1 (ret_v);
3312 fz_rect rect;
3313 fz_irect bbox;
3314 fz_matrix ctm;
3315 fz_device *dev;
3316 char *s = String_val (opaque_v);
3317 struct page *page = parse_pointer ("ml_getpagebox", s);
3319 ret_v = caml_alloc_tuple (4);
3320 dev = fz_new_bbox_device (state.ctx, &rect);
3321 dev->hints |= FZ_IGNORE_SHADE;
3323 switch (page->type) {
3324 case DPDF:
3325 ctm = pagectm (page);
3326 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3327 break;
3329 case DXPS:
3330 ctm = pagectm (page);
3331 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3332 break;
3334 default:
3335 rect = fz_infinite_rect;
3336 break;
3339 fz_free_device (dev);
3340 fz_round_rect (&bbox, &rect);
3341 Field (ret_v, 0) = Val_int (bbox.x0);
3342 Field (ret_v, 1) = Val_int (bbox.y0);
3343 Field (ret_v, 2) = Val_int (bbox.x1);
3344 Field (ret_v, 3) = Val_int (bbox.y1);
3346 CAMLreturn (ret_v);
3349 CAMLprim value ml_setaalevel (value level_v)
3351 CAMLparam1 (level_v);
3353 state.aalevel = Int_val (level_v);
3354 CAMLreturn (Val_unit);
3357 #undef pixel
3358 #include <X11/Xlib.h>
3359 #include <GL/glx.h>
3361 static struct {
3362 Display *dpy;
3363 GLXContext ctx;
3364 GLXDrawable drawable;
3365 } glx;
3367 #include "keysym2ucs.c"
3369 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3371 CAMLparam1 (keysym_v);
3372 CAMLlocal1 (str_v);
3373 KeySym keysym = Int_val (keysym_v);
3374 Rune rune;
3375 int len;
3376 char buf[5];
3378 rune = keysym2ucs (keysym);
3379 len = fz_runetochar (buf, rune);
3380 buf[len] = 0;
3381 str_v = caml_copy_string (buf);
3382 CAMLreturn (str_v);
3385 CAMLprim value ml_glx (value win_v)
3387 CAMLparam1 (win_v);
3388 XVisualInfo *visual;
3389 int screen, wid = Int_val (win_v);
3390 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3392 glx.dpy = XOpenDisplay (NULL);
3393 if (!glx.dpy) {
3394 caml_failwith ("XOpenDisplay");
3397 screen = DefaultScreen (glx.dpy);
3398 visual = glXChooseVisual (glx.dpy, screen, attributes);
3399 if (!visual) {
3400 XCloseDisplay (glx.dpy);
3401 glx.dpy = NULL;
3402 caml_failwith ("glXChooseVisual");
3405 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3406 XFree (visual);
3407 if (!glx.ctx) {
3408 XCloseDisplay (glx.dpy);
3409 glx.dpy = NULL;
3410 caml_failwith ("glXCreateContext");
3413 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3414 glXDestroyContext (glx.dpy, glx.ctx);
3415 XCloseDisplay (glx.dpy);
3416 glx.dpy = NULL;
3417 glx.ctx = NULL;
3418 caml_failwith ("glXMakeCurrent");
3420 glx.drawable = wid;
3421 CAMLreturn (Val_unit);
3424 CAMLprim value ml_swapb (value unit_v)
3426 CAMLparam1 (unit_v);
3427 glXSwapBuffers (glx.dpy, glx.drawable);
3428 CAMLreturn (Val_unit);
3431 CAMLprim value ml_glxsync (value unit_v)
3433 CAMLparam1 (unit_v);
3434 if (glx.dpy && glx.ctx) {
3435 glXWaitX ();
3436 glXWaitGL ();
3438 CAMLreturn (Val_unit);
3441 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3442 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3444 CAMLprim value ml_platform (value unit_v)
3446 CAMLparam1 (unit_v);
3447 int platid = piunknown;
3449 #if defined __linux__
3450 platid = pilinux;
3451 #elif defined __CYGWIN__
3452 platid = picygwin;
3453 #elif defined __DragonFly__
3454 platid = pidragonflybsd;
3455 #elif defined __FreeBSD__
3456 platid = pifreebsd;
3457 #elif defined __OpenBSD__
3458 platid = piopenbsd;
3459 #elif defined __NetBSD__
3460 platid = pinetbsd;
3461 #elif defined __sun__
3462 platid = pisun;
3463 #elif defined __APPLE__
3464 platid = piosx;
3465 #endif
3466 CAMLreturn (Val_int (platid));
3469 CAMLprim value ml_cloexec (value fd_v)
3471 CAMLparam1 (fd_v);
3472 int fd = Int_val (fd_v);
3474 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3475 uerror ("fcntl", Nothing);
3477 CAMLreturn (Val_unit);
3480 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3482 CAMLparam2 (w_v, h_v);
3483 CAMLlocal1 (ret_v);
3484 struct pbo *pbo;
3485 int w = Int_val (w_v);
3486 int h = Int_val (h_v);
3487 int cs = Int_val (cs_v);
3489 if (state.pbo_usable) {
3490 pbo = calloc (sizeof (*pbo), 1);
3491 if (!pbo) {
3492 err (1, "calloc pbo");
3495 switch (cs) {
3496 case 0:
3497 case 1:
3498 pbo->size = w*h*4;
3499 break;
3500 case 2:
3501 pbo->size = w*h*2;
3502 break;
3503 default:
3504 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3507 state.glGenBuffersARB (1, &pbo->id);
3508 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3509 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3510 NULL, GL_STREAM_DRAW);
3511 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3512 GL_READ_WRITE);
3513 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3514 if (!pbo->ptr) {
3515 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3516 state.glDeleteBuffersARB (1, &pbo->id);
3517 free (pbo);
3518 ret_v = caml_copy_string ("0");
3520 else {
3521 int res;
3522 char *s;
3524 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3525 if (res < 0) {
3526 err (1, "snprintf %" FMT_ptr " failed", pbo);
3528 s = malloc (res+1);
3529 if (!s) {
3530 err (1, "malloc %d bytes failed", res+1);
3532 res = sprintf (s, "%" FMT_ptr, pbo);
3533 if (res < 0) {
3534 err (1, "sprintf %" FMT_ptr " failed", pbo);
3536 ret_v = caml_copy_string (s);
3537 free (s);
3540 else {
3541 ret_v = caml_copy_string ("0");
3543 CAMLreturn (ret_v);
3546 CAMLprim value ml_freepbo (value s_v)
3548 CAMLparam1 (s_v);
3549 char *s = String_val (s_v);
3550 struct tile *tile = parse_pointer ("ml_freepbo", s);
3552 if (tile->pbo) {
3553 state.glDeleteBuffersARB (1, &tile->pbo->id);
3554 tile->pbo->id = -1;
3555 tile->pbo->ptr = NULL;
3556 tile->pbo->size = -1;
3558 CAMLreturn (Val_unit);
3561 CAMLprim value ml_unmappbo (value s_v)
3563 CAMLparam1 (s_v);
3564 char *s = String_val (s_v);
3565 struct tile *tile = parse_pointer ("ml_unmappbo", s);
3567 if (tile->pbo) {
3568 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3569 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3570 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3572 tile->pbo->ptr = NULL;
3573 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3575 CAMLreturn (Val_unit);
3578 static void setuppbo (void)
3580 #define GGPA(n) *(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n)
3581 GGPA (glBindBufferARB);
3582 if (state.glBindBufferARB) {
3583 GGPA (glUnmapBufferARB);
3584 if (state.glUnmapBufferARB) {
3585 GGPA (glMapBufferARB);
3586 if (state.glMapBufferARB) {
3587 GGPA (glBufferDataARB);
3588 if (state.glBufferDataARB) {
3589 GGPA (glGenBuffersARB);
3590 if (state.glGenBuffersARB) {
3591 GGPA (glDeleteBuffersARB);
3592 if (state.glDeleteBuffersARB) {
3593 state.pbo_usable = 1;
3600 #undef GGPA
3603 CAMLprim value ml_pbo_usable (value unit_v)
3605 CAMLparam1 (unit_v);
3606 CAMLreturn (Val_bool (state.pbo_usable));
3609 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3611 CAMLparam3 (ptr_v, x_v, y_v);
3612 CAMLlocal2 (ret_v, tup_v);
3613 struct page *page;
3614 char *s = String_val (ptr_v);
3615 int x = Int_val (x_v), y = Int_val (y_v);
3616 struct pagedim *pdim;
3617 fz_point p;
3618 fz_matrix ctm;
3620 page = parse_pointer ("ml_unproject", s);
3621 pdim = &state.pagedims[page->pdimno];
3623 ret_v = Val_int (0);
3624 if (trylock ("ml_unproject")) {
3625 goto done;
3628 switch (page->type) {
3629 case DPDF:
3630 trimctm (page->u.pdfpage, page->pdimno);
3631 break;
3633 default:
3634 break;
3636 p.x = x;
3637 p.y = y;
3639 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3640 fz_invert_matrix (&ctm, &ctm);
3641 fz_transform_point (&p, &ctm);
3643 tup_v = caml_alloc_tuple (2);
3644 ret_v = caml_alloc_small (1, 1);
3645 Field (tup_v, 0) = Val_int (p.x);
3646 Field (tup_v, 1) = Val_int (p.y);
3647 Field (ret_v, 0) = tup_v;
3649 unlock ("ml_unproject");
3650 done:
3651 CAMLreturn (ret_v);
3654 CAMLprim value ml_init (value pipe_v, value params_v)
3656 CAMLparam2 (pipe_v, params_v);
3657 CAMLlocal2 (trim_v, fuzz_v);
3658 int ret;
3659 int texcount;
3660 char *fontpath;
3661 int colorspace;
3662 int mustoresize;
3663 int haspboext;
3664 struct sigaction sa;
3666 state.cr = Int_val (Field (pipe_v, 0));
3667 state.cw = Int_val (Field (pipe_v, 1));
3668 state.rotate = Int_val (Field (params_v, 0));
3669 state.proportional = Bool_val (Field (params_v, 1));
3670 trim_v = Field (params_v, 2);
3671 texcount = Int_val (Field (params_v, 3));
3672 state.sliceheight = Int_val (Field (params_v, 4));
3673 mustoresize = Int_val (Field (params_v, 5));
3674 colorspace = Int_val (Field (params_v, 6));
3675 fontpath = String_val (Field (params_v, 7));
3676 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
3677 if (!state.trimcachepath) {
3678 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
3679 strerror (errno));
3681 haspboext = Bool_val (Field (params_v, 9));
3683 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3685 state.trimmargins = Bool_val (Field (trim_v, 0));
3686 fuzz_v = Field (trim_v, 1);
3687 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3688 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3689 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3690 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3692 set_tex_params (colorspace);
3694 if (*fontpath) {
3695 state.face = load_font (fontpath);
3697 else {
3698 unsigned int len;
3699 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
3701 state.face = load_builtin_font (base, len);
3703 if (!state.face) _exit (1);
3705 realloctexts (texcount);
3707 if (haspboext) {
3708 setuppbo ();
3711 #ifdef __CYGWIN__
3712 sa.sa_handler = SIG_IGN;
3713 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3714 #else
3715 sa.sa_handler = SIG_DFL;
3716 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
3717 #endif
3718 if (sigemptyset (&sa.sa_mask)) {
3719 err (1, "sigemptyset");
3721 if (sigaction (SIGCHLD, &sa, NULL)) {
3722 err (1, "sigaction");
3725 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3726 if (ret) {
3727 errx (1, "pthread_create: %s", strerror (ret));
3730 CAMLreturn (Val_unit);