Improve comment
[llpp/slowscroll.git] / link.c
blobd16365e19ef7d8de36eda0a9e631d362431b5fd2
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_bbox bounds;
147 fz_rect pagebox;
148 fz_rect mediabox;
149 fz_matrix ctm, zoomctm, lctm, tctm;
152 struct slink {
153 fz_bbox 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_bbox 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_bbox 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 fz_matrix 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;
657 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
658 realbox = fz_transform_rect (ctm, pdim->mediabox);
659 ctm = fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0));
660 ctm = fz_concat (fz_invert_matrix (page->ctm), ctm);
662 else {
663 ctm = fz_identity;
665 pdim->tctm = ctm;
666 pdim->tctmready = 1;
668 return pdim->tctm;
671 static fz_matrix pagectm (struct page *page)
673 if (page->type == DPDF) {
674 return fz_concat (trimctm (page->u.pdfpage, page->pdimno),
675 state.pagedims[page->pdimno].ctm);
677 else {
678 fz_matrix ctm;
679 struct pagedim *pdim = &state.pagedims[page->pdimno];
681 ctm = state.pagedims[page->pdimno].ctm;
682 ctm = fz_concat (fz_translate (-pdim->mediabox.x0,
683 -pdim->mediabox.y0), ctm);
684 return ctm;
688 static void *loadpage (int pageno, int pindex)
690 fz_device *dev;
691 struct page *page = NULL;
693 page = calloc (sizeof (struct page), 1);
694 if (!page) {
695 err (1, "calloc page %d", pageno);
698 page->dlist = fz_new_display_list (state.ctx);
699 dev = fz_new_list_device (state.ctx, page->dlist);
700 fz_try (state.ctx) {
701 switch (state.type) {
702 case DPDF:
703 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
704 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, fz_identity, NULL);
705 page->freepage = freepdfpage;
706 break;
708 case DXPS:
709 page->u.xpspage = xps_load_page (state.u.xps, pageno);
710 xps_run_page (state.u.xps, page->u.xpspage, dev, fz_identity, NULL);
711 page->freepage = freexpspage;
712 break;
714 case DCBZ:
715 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
716 cbz_run_page (state.u.cbz, page->u.cbzpage, dev, fz_identity, NULL);
717 page->freepage = freecbzpage;
718 break;
721 fz_catch (state.ctx) {
722 page->u.ptr = NULL;
723 page->freepage = freeemptyxxxpage;
725 fz_free_device (dev);
727 page->pdimno = pindex;
728 page->pageno = pageno;
729 page->sgen = state.gen;
730 page->tgen = state.gen;
731 page->type = state.type;
733 return page;
736 static struct tile *alloctile (int h)
738 int i;
739 int slicecount;
740 size_t tilesize;
741 struct tile *tile;
743 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
744 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
745 tile = calloc (tilesize, 1);
746 if (!tile) {
747 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
749 for (i = 0; i < slicecount; ++i) {
750 int sh = MIN (h, state.sliceheight);
751 tile->slices[i].h = sh;
752 tile->slices[i].texindex = -1;
753 h -= sh;
755 tile->slicecount = slicecount;
756 tile->sliceheight = state.sliceheight;
757 return tile;
760 #ifdef OBSCURED_OPT
761 struct obs {
762 int cured;
763 fz_bbox b;
766 static void obs_fill_image (fz_device *dev, fz_image *image, fz_matrix ctm,
767 float alpha)
769 struct obs *obs = dev->user;
771 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
772 fz_bbox b = fz_round_rect (fz_transform_rect (ctm, fz_unit_rect));
773 b = fz_intersect_bbox (b, obs->b);
774 obs->cured = b.x0 == obs->b.x0
775 && b.x1 == obs->b.x1
776 && b.y0 == obs->b.y0
777 && b.y1 == obs->b.y1;
781 static int obscured (struct page *page, fz_bbox bbox)
783 fz_device dev;
784 struct obs obs;
786 memset (&dev, 0, sizeof (dev));
787 memset (&obs, 0, sizeof (obs));
788 dev.hints = 0;
789 dev.flags = 0;
790 dev.user = &obs;
791 dev.ctx = state.ctx;
792 dev.fill_image = obs_fill_image;
793 obs.b = bbox;
794 fz_run_display_list (page->dlist, &dev, pagectm (page), bbox, NULL);
795 return obs.cured;
797 #define OBSCURED obscured
798 #else
799 #define OBSCURED(a, b) 0
800 #endif
802 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
803 struct pbo *pbo)
805 fz_bbox bbox;
806 fz_device *dev;
807 struct tile *tile;
808 struct pagedim *pdim;
810 tile = alloctile (h);
811 pdim = &state.pagedims[page->pdimno];
813 bbox = pdim->bounds;
814 bbox.x0 += x;
815 bbox.y0 += y;
816 bbox.x1 = bbox.x0 + w;
817 bbox.y1 = bbox.y0 + h;
819 if (state.pig) {
820 if (state.pig->w == w
821 && state.pig->h == h
822 && state.pig->colorspace == state.colorspace) {
823 tile->pixmap = state.pig;
824 tile->pixmap->x = bbox.x0;
825 tile->pixmap->y = bbox.y0;
827 else {
828 fz_drop_pixmap (state.ctx, state.pig);
830 state.pig = NULL;
832 if (!tile->pixmap) {
833 if (pbo) {
834 tile->pixmap =
835 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
836 bbox, pbo->ptr);
837 tile->pbo = pbo;
839 else {
840 tile->pixmap =
841 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox);
845 tile->w = w;
846 tile->h = h;
847 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
848 clearpixmap (tile->pixmap);
850 dev = fz_new_draw_device (state.ctx, tile->pixmap);
851 fz_run_display_list (page->dlist, dev, pagectm (page), bbox, NULL);
852 fz_free_device (dev);
854 return tile;
857 static void initpdims (void)
859 double start, end;
860 int pageno, trim, show;
861 FILE *trimf = NULL;
862 int trimw = 0;
864 start = now ();
866 if (state.trimmargins && state.trimcachepath) {
867 trimf = fopen (state.trimcachepath, "rb");
868 if (!trimf) {
869 trimf = fopen (state.trimcachepath, "wb");
870 trimw = 1;
873 for (pageno = 0; pageno < state.pagecount; ++pageno) {
874 int rotate = 0;
875 struct pagedim *p;
876 fz_rect mediabox;
878 switch (state.type) {
879 case DPDF: {
880 pdf_obj *pageobj = state.u.pdf->page_objs[pageno];
882 if (state.trimmargins) {
883 pdf_obj *obj;
884 pdf_page *page;
886 fz_try (state.ctx) {
887 page = pdf_load_page (state.u.pdf, pageno);
888 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
889 trim = state.trimanew || !obj;
890 if (trim) {
891 fz_rect rect;
892 fz_bbox bbox;
893 fz_matrix ctm;
894 fz_device *dev;
896 dev = fz_new_bbox_device (state.ctx, &bbox);
897 dev->hints |= FZ_IGNORE_SHADE;
898 ctm = fz_invert_matrix (page->ctm);
899 pdf_run_page (state.u.pdf, page, dev, fz_identity, NULL);
900 fz_free_device (dev);
902 rect.x0 = bbox.x0 + state.trimfuzz.x0;
903 rect.x1 = bbox.x1 + state.trimfuzz.x1;
904 rect.y0 = bbox.y0 + state.trimfuzz.y0;
905 rect.y1 = bbox.y1 + state.trimfuzz.y1;
906 rect = fz_transform_rect (ctm, rect);
907 rect = fz_intersect_rect (rect, page->mediabox);
909 if (fz_is_empty_rect (rect)) {
910 mediabox = page->mediabox;
912 else {
913 mediabox = rect;
916 obj = pdf_new_array (state.ctx, 4);
917 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x0));
918 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y0));
919 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.x1));
920 pdf_array_push (obj, pdf_new_real (state.ctx, mediabox.y1));
921 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
923 else {
924 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
925 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
926 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
927 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
930 rotate = page->rotate;
931 pdf_free_page (state.u.pdf, page);
933 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
934 if (show) {
935 printd ("progress %f Trimming %d",
936 (double) (pageno + 1) / state.pagecount,
937 pageno + 1);
940 fz_catch (state.ctx) {
941 fprintf (stderr, "failed to load page %d\n", pageno+1);
944 else {
945 fz_rect cropbox;
947 mediabox = pdf_to_rect (state.ctx,
948 pdf_dict_gets (pageobj, "MediaBox"));
949 if (fz_is_empty_rect (mediabox)) {
950 fprintf (stderr, "cannot find page size for page %d\n",
951 pageno+1);
952 mediabox.x0 = 0;
953 mediabox.y0 = 0;
954 mediabox.x1 = 612;
955 mediabox.y1 = 792;
958 cropbox = pdf_to_rect (state.ctx,
959 pdf_dict_gets (pageobj, "CropBox"));
960 if (!fz_is_empty_rect (cropbox)) {
961 mediabox = fz_intersect_rect (mediabox, cropbox);
963 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
965 break;
968 case DXPS:
970 xps_page *page;
972 fz_try (state.ctx) {
973 page = xps_load_page (state.u.xps, pageno);
974 mediabox = xps_bound_page (state.u.xps, page);
975 rotate = 0;
976 if (state.trimmargins) {
977 fz_rect rect;
978 fz_bbox bbox;
979 fz_device *dev;
981 dev = fz_new_bbox_device (state.ctx, &bbox);
982 dev->hints |= FZ_IGNORE_SHADE;
983 xps_run_page (state.u.xps, page, dev, fz_identity, NULL);
984 fz_free_device (dev);
986 rect.x0 = bbox.x0 + state.trimfuzz.x0;
987 rect.x1 = bbox.x1 + state.trimfuzz.x1;
988 rect.y0 = bbox.y0 + state.trimfuzz.y0;
989 rect.y1 = bbox.y1 + state.trimfuzz.y1;
990 rect = fz_intersect_rect (rect, mediabox);
992 if (!fz_is_empty_rect (rect)) {
993 mediabox = rect;
996 xps_free_page (state.u.xps, page);
997 printd ("progress %f loading %d",
998 (double) (pageno + 1) / state.pagecount,
999 pageno + 1);
1001 fz_catch (state.ctx) {
1004 break;
1006 case DCBZ:
1008 rotate = 0;
1009 if (state.trimmargins && trimw) {
1010 cbz_page *page;
1012 fz_try (state.ctx) {
1013 page = cbz_load_page (state.u.cbz, pageno);
1014 mediabox = cbz_bound_page (state.u.cbz, page);
1015 cbz_free_page (state.u.cbz, page);
1016 printd ("progress %f Trimming %d",
1017 (double) (pageno + 1) / state.pagecount,
1018 pageno + 1);
1020 fz_catch (state.ctx) {
1021 fprintf (stderr, "failed to load page %d\n", pageno+1);
1022 mediabox.x0 = 0;
1023 mediabox.y0 = 0;
1024 mediabox.x1 = 900;
1025 mediabox.y1 = 900;
1027 if (trimf) {
1028 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1029 if (n - 1) {
1030 err (1, "fwrite trim mediabox");
1034 else {
1035 if (trimf) {
1036 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1037 if (n - 1) {
1038 err (1, "fread trim mediabox");
1041 else {
1042 mediabox.x0 = mediabox.y0 = 0;
1043 mediabox.x1 = 900;
1044 mediabox.y1 = 900;
1048 break;
1050 default:
1051 ARSERT (0 && state.type);
1054 if (state.pagedimcount == 0
1055 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1056 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1057 size_t size;
1059 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1060 state.pagedims = realloc (state.pagedims, size);
1061 if (!state.pagedims) {
1062 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1063 size, state.pagedimcount + 1);
1066 p = &state.pagedims[state.pagedimcount++];
1067 p->rotate = rotate;
1068 p->mediabox = mediabox;
1069 p->pageno = pageno;
1072 end = now ();
1073 if (state.trimmargins) {
1074 printd ("progress 1 Trimmed %d pages in %f seconds",
1075 state.pagecount, end - start);
1077 else {
1078 printd ("vmsg Processed %d pages in %f seconds",
1079 state.pagecount, end - start);
1081 state.trimanew = 0;
1082 if (trimf) {
1083 if (fclose (trimf)) {
1084 err (1, "fclose");
1089 static void layout (void)
1091 int pindex;
1092 fz_rect box;
1093 fz_matrix ctm;
1094 double zoom, w, maxw = 0;
1095 struct pagedim *p = state.pagedims;
1097 if (state.proportional) {
1098 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1099 box = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
1100 p->mediabox);
1101 w = box.x1 - box.x0;
1102 maxw = MAX (w, maxw);
1106 p = state.pagedims;
1107 for (pindex = 0; pindex < state.pagedimcount; ++pindex, ++p) {
1108 fz_bbox bbox;
1110 ctm = fz_rotate (state.rotate);
1111 box = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
1112 p->mediabox);
1113 w = box.x1 - box.x0;
1115 if (state.proportional) {
1116 double scale = w / maxw;
1117 zoom = (state.w / w) * scale;
1119 else {
1120 zoom = state.w / w;
1123 p->zoomctm = fz_scale (zoom, zoom);
1124 ctm = fz_concat (p->zoomctm, ctm);
1126 p->pagebox = fz_transform_rect (fz_rotate (p->rotate), p->mediabox);
1127 p->pagebox.x1 -= p->pagebox.x0;
1128 p->pagebox.y1 -= p->pagebox.y0;
1129 p->pagebox.x0 = 0;
1130 p->pagebox.y0 = 0;
1131 bbox = fz_round_rect (fz_transform_rect (ctm, p->pagebox));
1133 p->bounds = bbox;
1134 p->left = state.proportional ? ((maxw - w) * zoom) / 2.0 : 0;
1135 p->ctm = ctm;
1137 ctm = fz_identity;
1138 ctm = fz_concat (ctm, fz_translate (0, -p->mediabox.y1));
1139 ctm = fz_concat (ctm, fz_scale (zoom, -zoom));
1140 ctm = fz_concat (ctm, fz_rotate (p->rotate + state.rotate));
1141 p->lctm = ctm;
1143 p->tctmready = 0;
1146 while (p-- != state.pagedims) {
1147 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1148 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1149 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1150 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1151 int w = x1 - x0;
1152 int h = y1 - y0;
1154 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1158 static struct anchor { int n; int y; int h; } desttoanchor (fz_link_dest *dest)
1160 int i;
1161 struct anchor a;
1162 struct pagedim *pdim = state.pagedims;
1164 a.n = -1;
1165 a.y = 0;
1166 for (i = 0; i < state.pagedimcount; ++i) {
1167 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1168 break;
1169 pdim = &state.pagedims[i];
1171 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1172 fz_point p;
1173 p.x = 0;
1174 p.y = dest->ld.gotor.lt.y;
1175 p = fz_transform_point (pdim->lctm, p);
1176 a.y = p.y;
1178 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1179 double y0, y1;
1181 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1182 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1183 a.h = y1 - y0;
1184 a.n = dest->ld.gotor.page;
1186 return a;
1189 static void recurse_outline (fz_outline *outline, int level)
1191 while (outline) {
1192 struct anchor a = desttoanchor (&outline->dest);
1194 if (a.n >= 0) {
1195 printd ("o %d %d %d %d %s",
1196 level, a.n, a.y, a.h, outline->title);
1198 if (outline->down) {
1199 recurse_outline (outline->down, level + 1);
1201 outline = outline->next;
1205 static void process_outline (void)
1207 fz_outline *outline;
1209 if (!state.needoutline) return;
1211 state.needoutline = 0;
1212 switch (state.type) {
1213 case DPDF:
1214 outline = pdf_load_outline (state.u.pdf);
1215 break;
1216 case DXPS:
1217 outline = xps_load_outline (state.u.xps);
1218 break;
1219 default:
1220 outline = NULL;
1221 break;
1223 if (outline) {
1224 recurse_outline (outline, 0);
1225 fz_free_outline (state.ctx, outline);
1229 static char *strofspan (fz_text_span *span)
1231 char *p;
1232 char utf8[10];
1233 fz_text_char *ch;
1234 size_t size = 0, cap = 80;
1236 p = malloc (cap + 1);
1237 if (!p) return NULL;
1239 for (ch = span->text; ch < span->text + span->len; ++ch) {
1240 int n = fz_runetochar (utf8, ch->c);
1241 if (size + n > cap) {
1242 cap *= 2;
1243 p = realloc (p, cap + 1);
1244 if (!p) return NULL;
1247 memcpy (p + size, utf8, n);
1248 size += n;
1250 p[size] = 0;
1251 return p;
1254 static int matchspan (regex_t *re, fz_text_span *span, fz_matrix ctm,
1255 int stop, int pageno, double start)
1257 int ret;
1258 char *p;
1259 regmatch_t rm;
1260 int a, b, c;
1261 fz_rect *sb, *eb;
1262 fz_point p1, p2, p3, p4;
1264 p = strofspan (span);
1265 if (!p) return -1;
1267 ret = regexec (re, p, 1, &rm, 0);
1268 if (ret) {
1269 free (p);
1270 if (ret != REG_NOMATCH) {
1271 size_t size;
1272 char errbuf[80];
1273 size = regerror (ret, re, errbuf, sizeof (errbuf));
1274 printd ("msg regexec error `%.*s'",
1275 (int) size, errbuf);
1276 return -1;
1278 return 0;
1280 else {
1281 int l = span->len;
1282 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1283 c += fz_runelen (span->text[a].c);
1285 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1286 c += fz_runelen (span->text[b].c);
1289 if (fz_runelen (span->text[b].c) > 1) {
1290 b = MAX (0, b-1);
1292 sb = &span->text[MIN (a, l-1)].bbox;
1293 eb = &span->text[MIN (b, l-1)].bbox;
1295 p1.x = sb->x0;
1296 p1.y = sb->y0;
1297 p2.x = eb->x1;
1298 p2.y = sb->y0;
1299 p3.x = eb->x1;
1300 p3.y = eb->y1;
1301 p4.x = sb->x0;
1302 p4.y = eb->y1;
1304 if (!stop) {
1305 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1306 pageno, 1,
1307 p1.x, p1.y,
1308 p2.x, p2.y,
1309 p3.x, p3.y,
1310 p4.x, p4.y);
1312 printd ("progress 1 found at %d `%.*s' in %f sec",
1313 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1314 now () - start);
1316 else {
1317 printd ("match %d %d %f %f %f %f %f %f %f %f",
1318 pageno, 2,
1319 p1.x, p1.y,
1320 p2.x, p2.y,
1321 p3.x, p3.y,
1322 p4.x, p4.y);
1324 free (p);
1325 return 1;
1329 static int compareblocks (const void *l, const void *r)
1331 fz_text_block const *ls = l;
1332 fz_text_block const* rs = r;
1333 return ls->bbox.y0 - rs->bbox.y0;
1336 /* wishful thinking function */
1337 static void search (regex_t *re, int pageno, int y, int forward)
1339 int i, j;
1340 fz_matrix ctm;
1341 fz_device *tdev;
1342 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1343 fz_text_page *text;
1344 fz_text_sheet *sheet;
1345 struct pagedim *pdim, *pdimprev;
1346 int stop = 0, niters = 0;
1347 double start, end;
1349 if (!(state.type == DPDF || state.type == DXPS))
1350 return;
1352 start = now ();
1353 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1354 if (niters++ == 5) {
1355 niters = 0;
1356 if (hasdata ()) {
1357 printd ("progress 1 attention requested aborting search at %d",
1358 pageno);
1359 stop = 1;
1361 else {
1362 printd ("progress %f searching in page %d",
1363 (double) (pageno + 1) / state.pagecount,
1364 pageno);
1367 pdimprev = NULL;
1368 for (i = 0; i < state.pagedimcount; ++i) {
1369 pdim = &state.pagedims[i];
1370 if (pdim->pageno == pageno) {
1371 goto found;
1373 if (pdim->pageno > pageno) {
1374 pdim = pdimprev;
1375 goto found;
1377 pdimprev = pdim;
1379 pdim = pdimprev;
1380 found:
1382 sheet = fz_new_text_sheet (state.ctx);
1383 text = fz_new_text_page (state.ctx, fz_infinite_rect);
1384 tdev = fz_new_text_device (state.ctx, sheet, text);
1386 switch (state.type) {
1387 case DPDF:
1388 u.ptr = NULL;
1389 fz_try (state.ctx) {
1390 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1391 trimctm (u.pdfpage, pdim - state.pagedims);
1392 ctm = fz_concat (pdim->tctm, pdim->zoomctm);
1393 pdf_run_page (state.u.pdf, u.pdfpage, tdev, ctm, NULL);
1395 fz_catch (state.ctx) {
1396 fz_free_device (tdev);
1397 u.ptr = NULL;
1398 goto nextiter;
1400 break;
1402 case DXPS:
1403 u.xpspage = xps_load_page (state.u.xps, pageno);
1404 ctm = pdim->ctm;
1405 xps_run_page (state.u.xps, u.xpspage, tdev, ctm, NULL);
1406 break;
1408 default:
1409 ARSERT (0 && state.type);
1412 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1413 fz_free_device (tdev);
1415 for (j = 0; j < text->len; ++j) {
1416 int k;
1417 fz_text_block *block;
1419 block = &text->blocks[forward ? j : text->len - 1 - j];
1421 for (k = 0; k < block->len; ++k) {
1422 fz_text_line *line;
1423 fz_text_span *span;
1425 if (forward) {
1426 line = &block->lines[k];
1427 if (line->bbox.y0 < y + 1) continue;
1429 else {
1430 line = &block->lines[block->len - 1 - k];
1431 if (line->bbox.y0 > y - 1) continue;
1434 for (span = line->spans;
1435 span < line->spans + line->len;
1436 ++span) {
1438 switch (matchspan (re, span, ctm, stop, pageno, start)) {
1439 case 0: break;
1440 case 1: stop = 1; break;
1441 case -1: stop = 1; goto endloop;
1446 nextiter:
1447 if (forward) {
1448 pageno += 1;
1449 y = 0;
1451 else {
1452 pageno -= 1;
1453 y = INT_MAX;
1455 endloop:
1456 fz_free_text_page (state.ctx, text);
1457 fz_free_text_sheet (state.ctx, sheet);
1458 if (u.ptr) {
1459 state.freepage (u.ptr);
1462 end = now ();
1463 if (!stop) {
1464 printd ("progress 1 no matches %f sec", end - start);
1466 printd ("clearrects");
1469 static void set_tex_params (int colorspace)
1471 union {
1472 unsigned char b;
1473 unsigned int s;
1474 } endianness = {1};
1476 switch (colorspace) {
1477 case 0:
1478 state.texiform = GL_RGBA8;
1479 state.texform = GL_RGBA;
1480 state.texty = GL_UNSIGNED_BYTE;
1481 state.colorspace = fz_device_rgb;
1482 break;
1483 case 1:
1484 state.texiform = GL_RGBA8;
1485 state.texform = GL_BGRA;
1486 state.texty = endianness.s > 1
1487 ? GL_UNSIGNED_INT_8_8_8_8
1488 : GL_UNSIGNED_INT_8_8_8_8_REV;
1489 state.colorspace = fz_device_bgr;
1490 break;
1491 case 2:
1492 state.texiform = GL_LUMINANCE_ALPHA;
1493 state.texform = GL_LUMINANCE_ALPHA;
1494 state.texty = GL_UNSIGNED_BYTE;
1495 state.colorspace = fz_device_gray;
1496 break;
1497 default:
1498 errx (1, "invalid colorspce %d", colorspace);
1502 static void realloctexts (int texcount)
1504 size_t size;
1506 if (texcount == state.texcount) return;
1508 if (texcount < state.texcount) {
1509 glDeleteTextures (state.texcount - texcount,
1510 state.texids + texcount);
1513 size = texcount * sizeof (*state.texids);
1514 state.texids = realloc (state.texids, size);
1515 if (!state.texids) {
1516 err (1, "realloc texids %" FMT_s, size);
1519 size = texcount * sizeof (*state.texowners);
1520 state.texowners = realloc (state.texowners, size);
1521 if (!state.texowners) {
1522 err (1, "realloc texowners %" FMT_s, size);
1524 if (texcount > state.texcount) {
1525 int i;
1527 glGenTextures (texcount - state.texcount,
1528 state.texids + state.texcount);
1529 for (i = state.texcount; i < texcount; ++i) {
1530 state.texowners[i].w = -1;
1531 state.texowners[i].slice = NULL;
1534 state.texcount = texcount;
1535 state.texindex = 0;
1538 static char *mbtoutf8 (char *s)
1540 char *p, *r;
1541 wchar_t *tmp;
1542 size_t i, ret, len;
1544 len = mbstowcs (NULL, s, strlen (s));
1545 if (len == 0) {
1546 return s;
1548 else {
1549 if (len == (size_t) -1) {
1550 return s;
1554 tmp = malloc (len * sizeof (wchar_t));
1555 if (!tmp) {
1556 return s;
1559 ret = mbstowcs (tmp, s, len);
1560 if (ret == (size_t) -1) {
1561 free (tmp);
1562 return s;
1565 len = 0;
1566 for (i = 0; i < ret; ++i) {
1567 len += fz_runelen (tmp[i]);
1570 p = r = malloc (len + 1);
1571 if (!r) {
1572 free (tmp);
1573 return s;
1576 for (i = 0; i < ret; ++i) {
1577 p += fz_runetochar (p, tmp[i]);
1579 *p = 0;
1580 free (tmp);
1581 return r;
1584 CAMLprim value ml_mbtoutf8 (value s_v)
1586 CAMLparam1 (s_v);
1587 CAMLlocal1 (ret_v);
1588 char *s, *r;
1590 s = String_val (s_v);
1591 r = mbtoutf8 (s);
1592 if (r == s) {
1593 ret_v = s_v;
1595 else {
1596 ret_v = caml_copy_string (r);
1597 free (r);
1599 CAMLreturn (ret_v);
1602 static void * mainloop (void *unused)
1604 char *p = NULL;
1605 int len, ret, oldlen = 0;
1607 for (;;) {
1608 len = readlen ();
1609 if (len == 0) {
1610 errx (1, "readlen returned 0");
1613 if (oldlen < len + 1) {
1614 p = realloc (p, len + 1);
1615 if (!p) {
1616 err (1, "realloc %d failed", len + 1);
1618 oldlen = len + 1;
1620 readdata (p, len);
1621 p[len] = 0;
1623 if (!strncmp ("open", p, 4)) {
1624 size_t filenamelen;
1625 int wthack, off;
1626 char *password;
1627 char *filename;
1628 char *utf8filename;
1630 ret = sscanf (p + 5, " %d %n", &wthack, &off);
1631 if (ret != 1) {
1632 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1635 filename = p + 5 + off;
1636 filenamelen = strlen (filename);
1637 password = filename + filenamelen + 1;
1639 openxref (filename, password);
1640 pdfinfo ();
1641 initpdims ();
1642 if (!wthack) {
1643 utf8filename = mbtoutf8 (filename);
1644 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1645 if (utf8filename != filename) {
1646 free (utf8filename);
1649 state.needoutline = 1;
1651 else if (!strncmp ("cs", p, 2)) {
1652 int i, colorspace;
1654 ret = sscanf (p + 2, " %d", &colorspace);
1655 if (ret != 1) {
1656 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1658 lock ("cs");
1659 set_tex_params (colorspace);
1660 for (i = 0; i < state.texcount; ++i) {
1661 state.texowners[i].w = -1;
1662 state.texowners[i].slice = NULL;
1664 unlock ("cs");
1666 else if (!strncmp ("freepage", p, 8)) {
1667 void *ptr;
1669 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1670 if (ret != 1) {
1671 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1673 freepage (ptr);
1675 else if (!strncmp ("freetile", p, 8)) {
1676 void *ptr;
1678 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1679 if (ret != 1) {
1680 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1682 freetile (ptr);
1684 else if (!strncmp ("search", p, 6)) {
1685 int icase, pageno, y, ret, len2, forward;
1686 char *pattern;
1687 regex_t re;
1689 ret = sscanf (p + 6, " %d %d %d %d,%n",
1690 &icase, &pageno, &y, &forward, &len2);
1691 if (ret != 4) {
1692 errx (1, "malformed search `%s' ret=%d", p, ret);
1695 pattern = p + 6 + len2;
1696 ret = regcomp (&re, pattern,
1697 REG_EXTENDED | (icase ? REG_ICASE : 0));
1698 if (ret) {
1699 char errbuf[80];
1700 size_t size;
1702 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1703 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1705 else {
1706 search (&re, pageno, y, forward);
1707 regfree (&re);
1710 else if (!strncmp ("geometry", p, 8)) {
1711 int w, h;
1713 printd ("clear");
1714 ret = sscanf (p + 8, " %d %d", &w, &h);
1715 if (ret != 2) {
1716 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1719 lock ("geometry");
1720 state.h = h;
1721 if (w != state.w) {
1722 int i;
1723 state.w = w;
1724 for (i = 0; i < state.texcount; ++i) {
1725 state.texowners[i].slice = NULL;
1728 layout ();
1729 process_outline ();
1731 state.gen++;
1732 unlock ("geometry");
1733 printd ("continue %d", state.pagecount);
1735 else if (!strncmp ("reqlayout", p, 9)) {
1736 char *nameddest;
1737 int rotate, proportional, off;
1739 printd ("clear");
1740 ret = sscanf (p + 9, " %d %d %n", &rotate, &proportional, &off);
1741 if (ret != 2) {
1742 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1744 lock ("reqlayout");
1745 if (state.rotate != rotate || state.proportional != proportional) {
1746 state.gen += 1;
1748 state.rotate = rotate;
1749 state.proportional = proportional;
1750 layout ();
1751 process_outline ();
1753 nameddest = p + 9 + off;
1754 if (state.type == DPDF && nameddest && *nameddest) {
1755 struct anchor a;
1756 fz_link_dest dest;
1757 pdf_obj *needle, *obj;
1759 needle = pdf_new_string (state.ctx, nameddest,
1760 strlen (nameddest));
1761 obj = pdf_lookup_dest (state.u.pdf, needle);
1762 if (obj) {
1763 dest = pdf_parse_link_dest (state.u.pdf, obj);
1765 a = desttoanchor (&dest);
1766 if (a.n >= 0) {
1767 printd ("a %d %d %d", a.n, a.y, a.h);
1769 else {
1770 printd ("emsg failed to parse destination `%s'\n",
1771 nameddest);
1774 else {
1775 printd ("emsg destination `%s' not found\n",
1776 nameddest);
1778 pdf_drop_obj (needle);
1781 state.gen++;
1782 unlock ("reqlayout");
1783 printd ("continue %d", state.pagecount);
1785 else if (!strncmp ("page", p, 4)) {
1786 double a, b;
1787 struct page *page;
1788 int pageno, pindex, ret;
1790 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1791 if (ret != 2) {
1792 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1795 lock ("page");
1796 a = now ();
1797 page = loadpage (pageno, pindex);
1798 b = now ();
1799 unlock ("page");
1801 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1803 else if (!strncmp ("tile", p, 4)) {
1804 int x, y, w, h, ret;
1805 struct page *page;
1806 struct tile *tile;
1807 double a, b;
1808 void *data;
1810 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
1811 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
1812 if (ret != 6) {
1813 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1816 lock ("tile");
1817 a = now ();
1818 tile = rendertile (page, x, y, w, h, data);
1819 b = now ();
1820 unlock ("tile");
1822 printd ("tile %d %d %" FMT_ptr " %u %f",
1823 x, y,
1824 FMT_ptr_cast2 (tile),
1825 tile->w * tile->h * tile->pixmap->n,
1826 b - a);
1828 else if (!strncmp ("settrim", p, 7)) {
1829 int trimmargins;
1830 fz_bbox fuzz;
1832 ret = sscanf (p + 7, " %d %d %d %d %d", &trimmargins,
1833 &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1834 if (ret != 5) {
1835 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1837 printd ("clear");
1838 lock ("settrim");
1839 state.trimmargins = trimmargins;
1840 state.needoutline = 1;
1841 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1842 state.trimanew = 1;
1843 state.trimfuzz = fuzz;
1845 state.pagedimcount = 0;
1846 free (state.pagedims);
1847 state.pagedims = NULL;
1848 initpdims ();
1849 layout ();
1850 process_outline ();
1851 unlock ("settrim");
1852 printd ("continue %d", state.pagecount);
1854 else if (!strncmp ("sliceh", p, 6)) {
1855 int h;
1857 ret = sscanf (p + 6, " %d", &h);
1858 if (ret != 1) {
1859 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1861 if (h != state.sliceheight) {
1862 int i;
1864 state.sliceheight = h;
1865 for (i = 0; i < state.texcount; ++i) {
1866 state.texowners[i].w = -1;
1867 state.texowners[i].h = -1;
1868 state.texowners[i].slice = NULL;
1872 else if (!strncmp ("interrupt", p, 9)) {
1873 printd ("vmsg interrupted");
1875 else {
1876 errx (1, "unknown command %.*s", len, p);
1879 return 0;
1882 CAMLprim value ml_realloctexts (value texcount_v)
1884 CAMLparam1 (texcount_v);
1885 int ok;
1887 if (trylock ("ml_realloctexts")) {
1888 ok = 0;
1889 goto done;
1891 realloctexts (Int_val (texcount_v));
1892 ok = 1;
1893 unlock ("ml_realloctexts");
1895 done:
1896 CAMLreturn (Val_bool (ok));
1899 static void showsel (struct page *page, int ox, int oy)
1901 int seen = 0;
1902 fz_bbox bbox;
1903 fz_text_line *line;
1904 fz_text_span *span;
1905 fz_text_block *block;
1906 struct mark first, last;
1908 first = page->fmark;
1909 last = page->lmark;
1911 if (!first.span || !last.span) return;
1913 glEnable (GL_BLEND);
1914 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1915 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1917 ox += state.pagedims[page->pdimno].bounds.x0;
1918 oy += state.pagedims[page->pdimno].bounds.y0;
1919 for (block = page->text->blocks;
1920 block < page->text->blocks + page->text->len;
1921 ++block) {
1922 for (line = block->lines;
1923 line < block->lines + block->len;
1924 ++line) {
1925 for (span = line->spans;
1926 span < line->spans + line->len;
1927 ++span) {
1928 int i, j, k;
1930 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
1932 j = 0;
1933 k = span->len - 1;
1935 if (span == page->fmark.span && span == page->lmark.span) {
1936 seen = 1;
1937 j = MIN (first.i, last.i);
1938 k = MAX (first.i, last.i);
1940 else if (span == first.span) {
1941 seen = 1;
1942 j = first.i;
1944 else if (span == last.span) {
1945 seen = 1;
1946 k = last.i;
1949 if (seen) {
1950 for (i = j; i <= k; ++i) {
1951 fz_bbox b = fz_round_rect (span->text[i].bbox);
1952 bbox = fz_union_bbox (bbox, b);
1954 lprintf ("%d %d %d %d oy=%d ox=%d\n",
1955 bbox.x0,
1956 bbox.y0,
1957 bbox.x1,
1958 bbox.y1,
1959 oy, ox);
1961 glRecti (bbox.x0 + ox, bbox.y0 + oy,
1962 bbox.x1 + ox, bbox.y1 + oy);
1963 if (span == last.span) {
1964 goto done;
1970 done:
1971 glDisable (GL_BLEND);
1974 #include "glfont.c"
1976 static void highlightlinks (struct page *page, int xoff, int yoff)
1978 fz_matrix ctm;
1979 fz_link *link, *links;
1981 switch (page->type) {
1982 case DPDF:
1983 links = page->u.pdfpage->links;
1984 break;
1986 case DXPS:
1987 links = page->u.xpspage->links;
1988 break;
1990 default:
1991 return;
1994 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
1995 glEnable (GL_LINE_STIPPLE);
1996 glLineStipple (0.5, 0xcccc);
1998 xoff -= state.pagedims[page->pdimno].bounds.x0;
1999 yoff -= state.pagedims[page->pdimno].bounds.y0;
2000 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2002 glBegin (GL_QUADS);
2003 for (link = links; link; link = link->next) {
2004 fz_point p1, p2, p3, p4;
2006 p1.x = link->rect.x0;
2007 p1.y = link->rect.y0;
2009 p2.x = link->rect.x1;
2010 p2.y = link->rect.y0;
2012 p3.x = link->rect.x1;
2013 p3.y = link->rect.y1;
2015 p4.x = link->rect.x0;
2016 p4.y = link->rect.y1;
2018 p1 = fz_transform_point (ctm, p1);
2019 p2 = fz_transform_point (ctm, p2);
2020 p3 = fz_transform_point (ctm, p3);
2021 p4 = fz_transform_point (ctm, p4);
2023 switch (link->dest.kind) {
2024 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2025 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2026 default: glColor3ub (0, 0, 0); break;
2029 glVertex2f (p1.x, p1.y);
2030 glVertex2f (p2.x, p2.y);
2031 glVertex2f (p3.x, p3.y);
2032 glVertex2f (p4.x, p4.y);
2034 glEnd ();
2036 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2037 glDisable (GL_LINE_STIPPLE);
2040 static int compareslinks (const void *l, const void *r)
2042 struct slink const *ls = l;
2043 struct slink const *rs = r;
2044 if (ls->bbox.y0 == rs->bbox.y0) {
2045 return rs->bbox.x0 - rs->bbox.x0;
2047 return ls->bbox.y0 - rs->bbox.y0;
2050 static void droptext (struct page *page)
2052 if (page->text) {
2053 fz_free_text_page (state.ctx, page->text);
2054 page->fmark.i = -1;
2055 page->lmark.i = -1;
2056 page->fmark.span = NULL;
2057 page->lmark.span = NULL;
2058 page->text = NULL;
2060 if (page->sheet) {
2061 fz_free_text_sheet (state.ctx, page->sheet);
2065 static void dropslinks (struct page *page)
2067 if (page->slinks) {
2068 free (page->slinks);
2069 page->slinks = NULL;
2070 page->slinkcount = 0;
2074 static void ensureslinks (struct page *page)
2076 fz_matrix ctm;
2077 int i, count = 0;
2078 size_t slinksize = sizeof (*page->slinks);
2079 fz_link *link, *links;
2081 if (state.gen != page->sgen) {
2082 dropslinks (page);
2083 page->sgen = state.gen;
2085 if (page->slinks) return;
2087 switch (page->type) {
2088 case DPDF:
2089 links = page->u.pdfpage->links;
2090 ctm = fz_concat (trimctm (page->u.pdfpage, page->pdimno),
2091 state.pagedims[page->pdimno].ctm);
2092 break;
2094 case DXPS:
2095 links = page->u.xpspage->links;
2096 ctm = state.pagedims[page->pdimno].ctm;
2097 break;
2099 default:
2100 return;
2103 for (link = links; link; link = link->next) {
2104 count++;
2106 if (count > 0) {
2107 page->slinkcount = count;
2108 page->slinks = calloc (count, slinksize);
2109 if (!page->slinks) {
2110 err (1, "realloc slinks %d", count);
2113 for (i = 0, link = links; link; ++i, link = link->next) {
2114 page->slinks[i].link = link;
2115 page->slinks[i].bbox =
2116 fz_round_rect (fz_transform_rect (ctm, link->rect));
2118 qsort (page->slinks, count, slinksize, compareslinks);
2122 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2123 static void fmt_linkn (char *s, unsigned int u)
2125 unsigned int len; unsigned int q;
2126 int zma = 'z' - 'a' + 1;
2127 len = 1; q = u;
2128 while (q > zma - 1) { ++len; q /= zma; }
2129 if (s) {
2130 s += len;
2131 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2132 /* handles u == 0 */
2134 s[len] = 0;
2137 static void highlightslinks (struct page *page, int xoff, int yoff,
2138 int noff, char *targ, int tlen, int hfsize)
2140 int i;
2141 char buf[40];
2142 struct slink *slink;
2143 double x0, y0, x1, y1, w;
2145 ensureslinks (page);
2146 glColor3ub (0xc3, 0xb0, 0x91);
2147 for (i = 0; i < page->slinkcount; ++i) {
2148 fmt_linkn (buf, i + noff);
2149 if (!tlen || !strncmp (targ, buf, tlen)) {
2150 slink = &page->slinks[i];
2152 x0 = slink->bbox.x0 + xoff - 5;
2153 y1 = slink->bbox.y0 + yoff - 5;
2154 y0 = y1 + 10 + hfsize;
2155 w = measure_string (state.face, hfsize, buf);
2156 x1 = x0 + w + 10;
2157 glRectd (x0, y0, x1, y1);
2161 glEnable (GL_BLEND);
2162 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2163 glEnable (GL_TEXTURE_2D);
2164 glColor3ub (0, 0, 0);
2165 for (i = 0; i < page->slinkcount; ++i) {
2166 fmt_linkn (buf, i + noff);
2167 if (!tlen || !strncmp (targ, buf, tlen)) {
2168 slink = &page->slinks[i];
2170 x0 = slink->bbox.x0 + xoff;
2171 y0 = slink->bbox.y0 + yoff + hfsize;
2172 draw_string (state.face, hfsize, x0, y0, buf);
2175 glDisable (GL_TEXTURE_2D);
2176 glDisable (GL_BLEND);
2180 static void uploadslice (struct tile *tile, struct slice *slice)
2182 int offset;
2183 struct slice *slice1;
2184 unsigned char *texdata;
2186 offset = 0;
2187 for (slice1 = tile->slices; slice != slice1; slice1++) {
2188 offset += slice1->h * tile->w * tile->pixmap->n;
2190 if (slice->texindex != -1 && slice->texindex < state.texcount
2191 && state.texowners[slice->texindex].slice == slice) {
2192 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2194 else {
2195 int subimage = 0;
2196 int texindex = state.texindex++ % state.texcount;
2198 if (state.texowners[texindex].w == tile->w) {
2199 if (state.texowners[texindex].h >= slice->h) {
2200 subimage = 1;
2202 else {
2203 state.texowners[texindex].h = slice->h;
2206 else {
2207 state.texowners[texindex].h = slice->h;
2210 state.texowners[texindex].w = tile->w;
2211 state.texowners[texindex].slice = slice;
2212 slice->texindex = texindex;
2214 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2215 if (tile->pbo) {
2216 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2217 texdata = 0;
2219 else {
2220 texdata = tile->pixmap->samples;
2222 if (subimage) {
2223 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2227 tile->w,
2228 slice->h,
2229 state.texform,
2230 state.texty,
2231 texdata+offset
2234 else {
2235 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2237 state.texiform,
2238 tile->w,
2239 slice->h,
2241 state.texform,
2242 state.texty,
2243 texdata+offset
2246 if (tile->pbo) {
2247 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2252 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2254 CAMLparam2 (args_v, ptr_v);
2255 int dispx = Int_val (Field (args_v, 0));
2256 int dispy = Int_val (Field (args_v, 1));
2257 int dispw = Int_val (Field (args_v, 2));
2258 int disph = Int_val (Field (args_v, 3));
2259 int tilex = Int_val (Field (args_v, 4));
2260 int tiley = Int_val (Field (args_v, 5));
2261 char *s = String_val (ptr_v);
2262 struct tile *tile = parse_pointer ("ml_drawtile", s);
2264 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2266 int slicey, firstslice;
2267 struct slice *slice;
2269 firstslice = tiley / tile->sliceheight;
2270 slice = &tile->slices[firstslice];
2271 slicey = tiley % tile->sliceheight;
2273 while (disph > 0) {
2274 int dh;
2276 dh = slice->h - slicey;
2277 dh = MIN (disph, dh);
2278 uploadslice (tile, slice);
2280 glBegin (GL_QUADS);
2282 glTexCoord2i (tilex, slicey);
2283 glVertex2i (dispx, dispy);
2285 glTexCoord2i (tilex+dispw, slicey);
2286 glVertex2i (dispx+dispw, dispy);
2288 glTexCoord2i (tilex+dispw, slicey+dh);
2289 glVertex2i (dispx+dispw, dispy+dh);
2291 glTexCoord2i (tilex, slicey+dh);
2292 glVertex2i (dispx, dispy+dh);
2294 glEnd ();
2296 dispy += dh;
2297 disph -= dh;
2298 slice++;
2299 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2300 slicey = 0;
2303 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2304 CAMLreturn (Val_unit);
2307 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2308 value xoff_v, value yoff_v,
2309 value li_v)
2311 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2312 int xoff = Int_val (xoff_v);
2313 int yoff = Int_val (yoff_v);
2314 int noff = Int_val (Field (li_v, 0));
2315 char *targ = String_val (Field (li_v, 1));
2316 int tlen = caml_string_length (Field (li_v, 1));
2317 int hfsize = Int_val (Field (li_v, 2));
2318 char *s = String_val (ptr_v);
2319 int hlmask = Int_val (hlinks_v);
2320 struct page *page = parse_pointer ("ml_postprocess", s);
2322 if (!page->u.ptr) {
2323 /* deal with loadpage failed pages */
2324 goto done;
2327 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2328 if (trylock ("ml_postprocess")) {
2329 noff = 0;
2330 goto done;
2332 if (hlmask & 2) {
2333 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2334 noff = page->slinkcount;
2336 showsel (page, xoff, yoff);
2337 unlock ("ml_postprocess");
2339 done:
2340 CAMLreturn (Val_int (noff));
2343 static fz_link *getlink (struct page *page, int x, int y)
2345 fz_point p;
2346 fz_matrix ctm;
2347 fz_link *link, *links;
2349 switch (page->type) {
2350 case DPDF:
2351 ctm = trimctm (page->u.pdfpage, page->pdimno);
2352 links = page->u.pdfpage->links;
2353 break;
2355 case DXPS:
2356 ctm = fz_identity;
2357 links = page->u.xpspage->links;
2358 break;
2360 default:
2361 return NULL;
2363 p.x = x;
2364 p.y = y;
2366 ctm = fz_concat (ctm, state.pagedims[page->pdimno].ctm);
2367 ctm = fz_invert_matrix (ctm);
2368 p = fz_transform_point (ctm, p);
2370 for (link = links; link; link = link->next) {
2371 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2372 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2373 return link;
2377 return NULL;
2380 static void ensuretext (struct page *page)
2382 if (state.gen != page->tgen) {
2383 droptext (page);
2384 page->tgen = state.gen;
2386 if (!page->text) {
2387 fz_device *tdev;
2389 page->text = fz_new_text_page (state.ctx, fz_infinite_rect);
2390 page->sheet = fz_new_text_sheet (state.ctx);
2391 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2392 fz_run_display_list (page->dlist,
2393 tdev,
2394 pagectm (page),
2395 fz_infinite_bbox, NULL);
2396 qsort (page->text->blocks, page->text->len,
2397 sizeof (*page->text->blocks), compareblocks);
2398 fz_free_device (tdev);
2402 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2404 CAMLparam2 (start_page_v, dir_v);
2405 CAMLlocal1 (ret_v);
2406 int i, dir = Int_val (dir_v);
2407 int start_page = Int_val (start_page_v);
2408 int end_page = dir > 0 ? state.pagecount : -1;
2410 ret_v = Val_int (0);
2411 if (!(state.type == DPDF || state.type == DXPS)) {
2412 goto done;
2415 lock ("ml_findpage_with_links");
2416 for (i = start_page + dir; i != end_page; i += dir) {
2417 int found;
2419 switch (state.type) {
2420 case DPDF:
2422 pdf_page *page = NULL;
2424 fz_try (state.ctx) {
2425 page = pdf_load_page (state.u.pdf, i);
2426 found = !!page->links;
2428 fz_catch (state.ctx) {
2429 found = 0;
2431 if (page) {
2432 freepdfpage (page);
2435 break;
2436 case DXPS:
2438 xps_page *page = xps_load_page (state.u.xps, i);
2439 found = !!page->links;
2440 freexpspage (page);
2442 break;
2444 default:
2445 ARSERT ("invalid document type");
2448 if (found) {
2449 ret_v = caml_alloc_small (1, 1);
2450 Field (ret_v, 0) = Val_int (i);
2451 goto unlock;
2454 unlock:
2455 unlock ("ml_findpage_with_links");
2457 done:
2458 CAMLreturn (ret_v);
2461 enum { dir_first, dir_last};
2462 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2464 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2466 CAMLparam2 (ptr_v, dir_v);
2467 CAMLlocal2 (ret_v, pos_v);
2468 struct page *page;
2469 int dirtag, i, slinkindex;
2470 struct slink *found = NULL ,*slink;
2471 char *s = String_val (ptr_v);
2473 page = parse_pointer ("ml_findlink", s);
2474 ret_v = Val_int (0);
2475 if (trylock ("ml_findlink")) {
2476 goto done;
2479 ensureslinks (page);
2481 if (Is_block (dir_v)) {
2482 dirtag = Tag_val (dir_v);
2483 switch (dirtag) {
2484 case dir_first_visible:
2486 int x0, y0, dir, first_index, last_index;
2488 pos_v = Field (dir_v, 0);
2489 x0 = Int_val (Field (pos_v, 0));
2490 y0 = Int_val (Field (pos_v, 1));
2491 dir = Int_val (Field (pos_v, 2));
2493 if (dir >= 0) {
2494 dir = 1;
2495 first_index = 0;
2496 last_index = page->slinkcount;
2498 else {
2499 first_index = page->slinkcount - 1;
2500 last_index = -1;
2503 for (i = first_index; i != last_index; i += dir) {
2504 slink = &page->slinks[i];
2505 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2506 found = slink;
2507 break;
2511 break;
2513 case dir_left:
2514 slinkindex = Int_val (Field (dir_v, 0));
2515 found = &page->slinks[slinkindex];
2516 for (i = slinkindex - 1; i >= 0; --i) {
2517 slink = &page->slinks[i];
2518 if (slink->bbox.x0 < found->bbox.x0) {
2519 found = slink;
2520 break;
2523 break;
2525 case dir_right:
2526 slinkindex = Int_val (Field (dir_v, 0));
2527 found = &page->slinks[slinkindex];
2528 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2529 slink = &page->slinks[i];
2530 if (slink->bbox.x0 > found->bbox.x0) {
2531 found = slink;
2532 break;
2535 break;
2537 case dir_down:
2538 slinkindex = Int_val (Field (dir_v, 0));
2539 found = &page->slinks[slinkindex];
2540 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2541 slink = &page->slinks[i];
2542 if (slink->bbox.y0 >= found->bbox.y0) {
2543 found = slink;
2544 break;
2547 break;
2549 case dir_up:
2550 slinkindex = Int_val (Field (dir_v, 0));
2551 found = &page->slinks[slinkindex];
2552 for (i = slinkindex - 1; i >= 0; --i) {
2553 slink = &page->slinks[i];
2554 if (slink->bbox.y0 <= found->bbox.y0) {
2555 found = slink;
2556 break;
2559 break;
2562 else {
2563 dirtag = Int_val (dir_v);
2564 switch (dirtag) {
2565 case dir_first:
2566 found = page->slinks;
2567 break;
2569 case dir_last:
2570 if (page->slinks) {
2571 found = page->slinks + (page->slinkcount - 1);
2573 break;
2576 if (found) {
2577 ret_v = caml_alloc_small (2, 1);
2578 Field (ret_v, 0) = Val_int (found - page->slinks);
2581 unlock ("ml_findlink");
2582 done:
2583 CAMLreturn (ret_v);
2586 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2588 #define LINKTOVAL \
2590 int pageno; \
2592 switch (link->dest.kind) { \
2593 case FZ_LINK_GOTO: \
2595 fz_point p; \
2597 pageno = link->dest.ld.gotor.page; \
2598 p.x = 0; \
2599 p.y = 0; \
2601 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2602 p.y = link->dest.ld.gotor.lt.y; \
2603 p = fz_transform_point (pdim->lctm, p); \
2605 tup_v = caml_alloc_tuple (2); \
2606 ret_v = caml_alloc_small (1, ugoto); \
2607 Field (tup_v, 0) = Val_int (pageno); \
2608 Field (tup_v, 1) = Val_int (p.y); \
2609 Field (ret_v, 0) = tup_v; \
2611 break; \
2613 case FZ_LINK_URI: \
2614 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2615 ret_v = caml_alloc_small (1, uuri); \
2616 Field (ret_v, 0) = str_v; \
2617 break; \
2619 case FZ_LINK_LAUNCH: \
2620 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2621 ret_v = caml_alloc_small (1, ulaunch); \
2622 Field (ret_v, 0) = str_v; \
2623 break; \
2625 case FZ_LINK_NAMED: \
2626 str_v = caml_copy_string (link->dest.ld.named.named); \
2627 ret_v = caml_alloc_small (1, unamed); \
2628 Field (ret_v, 0) = str_v; \
2629 break; \
2631 case FZ_LINK_GOTOR: \
2632 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2633 pageno = link->dest.ld.gotor.page; \
2634 tup_v = caml_alloc_tuple (2); \
2635 ret_v = caml_alloc_small (1, uremote); \
2636 Field (tup_v, 0) = str_v; \
2637 Field (tup_v, 1) = Val_int (pageno); \
2638 Field (ret_v, 0) = tup_v; \
2639 break; \
2641 default: \
2643 char buf[80]; \
2645 snprintf (buf, sizeof (buf), \
2646 "unhandled link kind %d", link->dest.kind); \
2647 str_v = caml_copy_string (buf); \
2648 ret_v = caml_alloc_small (1, uunexpected); \
2649 Field (ret_v, 0) = str_v; \
2651 break; \
2655 CAMLprim value ml_getlink (value ptr_v, value n_v)
2657 CAMLparam2 (ptr_v, n_v);
2658 CAMLlocal3 (ret_v, tup_v, str_v);
2659 fz_link *link;
2660 struct page *page;
2661 struct pagedim *pdim;
2662 char *s = String_val (ptr_v);
2664 ret_v = Val_int (0);
2665 if (trylock ("ml_getlink")) {
2666 goto done;
2669 page = parse_pointer ("ml_getlink", s);
2670 ensureslinks (page);
2671 pdim = &state.pagedims[page->pdimno];
2672 link = page->slinks[Int_val (n_v)].link;
2673 LINKTOVAL;
2675 unlock ("ml_getlink");
2676 done:
2677 CAMLreturn (ret_v);
2680 CAMLprim value ml_getlinkcount (value ptr_v)
2682 CAMLparam1 (ptr_v);
2683 struct page *page;
2684 char *s = String_val (ptr_v);
2686 page = parse_pointer ("ml_getlinkcount", s);
2687 CAMLreturn (Val_int (page->slinkcount));
2690 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2692 CAMLparam2 (ptr_v, n_v);
2693 CAMLlocal1 (ret_v);
2694 struct page *page;
2695 struct slink *slink;
2696 char *s = String_val (ptr_v);
2698 page = parse_pointer ("ml_getlinkrect", s);
2699 ret_v = caml_alloc_tuple (4);
2700 if (trylock ("ml_getlinkrect")) {
2701 Field (ret_v, 0) = Val_int (0);
2702 Field (ret_v, 1) = Val_int (0);
2703 Field (ret_v, 2) = Val_int (0);
2704 Field (ret_v, 3) = Val_int (0);
2705 goto done;
2707 ensureslinks (page);
2709 slink = &page->slinks[Int_val (n_v)];
2710 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2711 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2712 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2713 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2714 unlock ("ml_getlinkrect");
2716 done:
2717 CAMLreturn (ret_v);
2720 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2722 CAMLparam3 (ptr_v, x_v, y_v);
2723 CAMLlocal3 (ret_v, tup_v, str_v);
2724 fz_link *link;
2725 struct page *page;
2726 char *s = String_val (ptr_v);
2727 int x = Int_val (x_v), y = Int_val (y_v);
2728 struct pagedim *pdim;
2730 ret_v = Val_int (0);
2731 if (trylock ("ml_whatsunder")) {
2732 goto done;
2735 page = parse_pointer ("ml_whatsunder", s);
2736 pdim = &state.pagedims[page->pdimno];
2737 x += pdim->bounds.x0;
2738 y += pdim->bounds.y0;
2739 link = getlink (page, x, y);
2740 if (link) {
2741 LINKTOVAL;
2743 else {
2744 fz_rect *b;
2745 fz_text_block *block;
2747 ensuretext (page);
2748 for (block = page->text->blocks;
2749 block < page->text->blocks + page->text->len;
2750 ++block) {
2751 fz_text_line *line;
2753 b = &block->bbox;
2754 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2755 continue;
2757 for (line = block->lines;
2758 line < block->lines + block->len;
2759 ++line) {
2760 fz_text_span *span;
2762 b = &line->bbox;
2763 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2764 continue;
2766 for (span = line->spans;
2767 span < line->spans + line->len;
2768 ++span) {
2769 fz_text_char *ch;
2771 b = &span->bbox;
2772 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2773 continue;
2775 for (ch = span->text; ch < span->text + span->len; ++ch) {
2776 b = &ch->bbox;
2778 if (x >= b->x0 && x <= b->x1
2779 && y >= b->y0 && y <= b->y1) {
2780 const char *n2 =
2781 span->style->font && span->style->font->name
2782 ? span->style->font->name
2783 : "Span has no font name"
2785 FT_FaceRec *face = span->style->font->ft_face;
2786 if (face && face->family_name) {
2787 char *s;
2788 char *n1 = face->family_name;
2789 size_t l1 = strlen (n1);
2790 size_t l2 = strlen (n2);
2792 if (l1 != l2 || memcmp (n1, n2, l1)) {
2793 s = malloc (l1 + l2 + 2);
2794 if (s) {
2795 memcpy (s, n2, l2);
2796 s[l2] = '=';
2797 memcpy (s + l2 + 1, n1, l1 + 1);
2798 str_v = caml_copy_string (s);
2799 free (s);
2803 if (str_v == 0) {
2804 str_v = caml_copy_string (n2);
2806 ret_v = caml_alloc_small (1, utext);
2807 Field (ret_v, 0) = str_v;
2808 goto unlock;
2815 unlock:
2816 unlock ("ml_whatsunder");
2818 done:
2819 CAMLreturn (ret_v);
2822 CAMLprim value ml_seltext (value ptr_v, value rect_v)
2824 CAMLparam2 (ptr_v, rect_v);
2825 fz_rect *b;
2826 struct page *page;
2827 struct pagedim *pdim;
2828 int i, x0, x1, y0, y1;
2829 char *s = String_val (ptr_v);
2830 int fi = 0, li = 0;
2831 fz_text_block *block;
2832 fz_text_span *span, *fspan, *lspan;
2833 fz_text_line *line, *fline = NULL, *lline = NULL;
2835 if (trylock ("ml_seltext")) {
2836 goto done;
2839 page = parse_pointer ("ml_seltext", s);
2840 ensuretext (page);
2842 pdim = &state.pagedims[page->pdimno];
2843 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
2844 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2845 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2846 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2848 if (0) {
2849 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2850 glColor3ub (128, 128, 128);
2851 glRecti (x0, y0, x1, y1);
2852 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2855 fspan = lspan = NULL;
2857 for (block = page->text->blocks;
2858 block < page->text->blocks + page->text->len;
2859 ++block) {
2860 for (line = block->lines;
2861 line < block->lines + block->len;
2862 ++line) {
2863 for (span = line->spans;
2864 span < line->spans + line->len;
2865 ++span) {
2866 for (i = 0; i < span->len; ++i) {
2867 b = &span->text[i].bbox;
2868 int selected = 0;
2870 if (x0 >= b->x0 && x0 <= b->x1
2871 && y0 >= b->y0 && y0 <= b->y1) {
2872 fspan = span;
2873 fline = line;
2874 fi = i;
2875 selected = 1;
2877 if (x1 >= b->x0 && x1 <= b->x1
2878 && y1 >= b->y0 && y1 <= b->y1) {
2879 lspan = span;
2880 lline = line;
2881 li = i;
2882 selected = 1;
2884 if (0 && selected) {
2885 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
2886 glColor3ub (128, 128, 128);
2887 glRecti (b->x0, b->y0, b->x1, b->y1);
2888 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
2894 if (y1 < y0 || x1 < x0) {
2895 int swap = 0;
2897 if (fspan == lspan) {
2898 swap = 1;
2900 else {
2901 if (y1 < y0) {
2902 if (fline != lline) {
2903 swap = 1;
2908 if (swap) {
2909 i = fi;
2910 span = fspan;
2912 fi = li;
2913 fspan = lspan;
2915 li = i;
2916 lspan = span;
2920 page->fmark.i = fi;
2921 page->fmark.span = fspan;
2923 page->lmark.i = li;
2924 page->lmark.span = lspan;
2926 unlock ("ml_seltext");
2928 done:
2929 CAMLreturn (Val_unit);
2932 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
2934 char buf[4];
2935 int i, len, ret;
2937 for (i = a; i <= b; ++i) {
2938 len = fz_runetochar (buf, span->text[i].c);
2939 ret = fwrite (buf, len, 1, f);
2941 if (ret != 1) {
2942 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
2943 len, ret, strerror (errno));
2944 return -1;
2947 return 0;
2950 #ifdef __CYGWIN__
2951 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
2953 caml_failwith ("ml_popen not implemented under Cygwin");
2955 #else
2956 CAMLprim value ml_popen (value command_v, value fds_v)
2958 CAMLparam2 (command_v, fds_v);
2959 CAMLlocal2 (l_v, tup_v);
2960 int ret;
2961 char *msg = NULL;
2962 value earg_v = Nothing;
2963 posix_spawnattr_t attr;
2964 posix_spawn_file_actions_t fa;
2965 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
2967 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
2968 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
2971 if ((ret = posix_spawnattr_init (&attr)) != 0) {
2972 msg = "posix_spawnattr_init";
2973 goto fail1;
2976 #ifdef POSIX_SPAWN_USEVFORK
2977 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
2978 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
2979 goto fail;
2981 #endif
2983 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
2984 int fd1, fd2;
2986 tup_v = Field (l_v, 0);
2987 fd1 = Int_val (Field (tup_v, 0));
2988 fd2 = Int_val (Field (tup_v, 1));
2989 if (fd2 < 0) {
2990 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
2991 msg = "posix_spawn_file_actions_addclose";
2992 earg_v = tup_v;
2993 goto fail;
2996 else {
2997 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
2998 msg = "posix_spawn_file_actions_adddup2";
2999 earg_v = tup_v;
3000 goto fail;
3005 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3006 msg = "posix_spawn";
3007 goto fail;
3010 fail:
3011 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3012 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3015 fail1:
3016 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3017 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3018 strerror (ret));
3021 if (msg)
3022 unix_error (ret, msg, earg_v);
3024 CAMLreturn (Val_unit);
3026 #endif
3028 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3030 CAMLparam1 (ptr_v);
3031 FILE *f;
3032 int seen = 0;
3033 struct page *page;
3034 fz_text_line *line;
3035 fz_text_span *span;
3036 fz_text_block *block;
3037 int fd = Int_val (fd_v);
3038 char *s = String_val (ptr_v);
3040 if (trylock ("ml_copysel")) {
3041 goto done;
3044 page = parse_pointer ("ml_sopysel", s);
3046 if (!page->fmark.span || !page->lmark.span) {
3047 fprintf (stderr, "nothing to copy\n");
3048 goto unlock;
3051 f = fdopen (fd, "w");
3052 if (!f) {
3053 fprintf (stderr, "failed to fopen sel pipe: %s\n",
3054 strerror (errno));
3055 f = stdout;
3058 for (block = page->text->blocks;
3059 block < page->text->blocks + page->text->len;
3060 ++block) {
3061 for (line = block->lines;
3062 line < block->lines + block->len;
3063 ++line) {
3064 for (span = line->spans;
3065 span < line->spans + line->len;
3066 ++span) {
3067 int a, b;
3069 seen |= span == page->fmark.span || span == page->lmark.span;
3070 a = span == page->fmark.span ? page->fmark.i : 0;
3071 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3073 if (seen) {
3074 if (pipespan (f, span, a, b)) {
3075 goto close;
3077 if (span == line->spans + line->len - 1) {
3078 if (putc ('\n', f) == EOF) {
3079 fprintf (stderr,
3080 "failed break line on sel pipe: %s\n",
3081 strerror (errno));
3082 goto close;
3085 if (span == page->lmark.span) {
3086 goto endloop;
3092 endloop:
3093 page->lmark.span = NULL;
3094 page->fmark.span = NULL;
3096 close:
3097 if (f != stdout) {
3098 int ret = fclose (f);
3099 fd = -1;
3100 if (ret == -1) {
3101 if (errno != ECHILD) {
3102 fprintf (stderr, "failed to close sel pipe: %s\n",
3103 strerror (errno));
3107 unlock:
3108 unlock ("ml_copysel");
3110 done:
3111 if (fd >= 0) {
3112 if (close (fd)) {
3113 fprintf (stderr, "failed to close sel pipe: %s\n",
3114 strerror (errno));
3117 CAMLreturn (Val_unit);
3120 CAMLprim value ml_getpdimrect (value pagedimno_v)
3122 CAMLparam1 (pagedimno_v);
3123 CAMLlocal1 (ret_v);
3124 int pagedimno = Int_val (pagedimno_v);
3125 fz_rect box;
3127 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3128 if (trylock ("ml_getpdimrect")) {
3129 box = fz_empty_rect;
3131 else {
3132 box = state.pagedims[pagedimno].mediabox;
3133 unlock ("ml_getpdimrect");
3136 Store_double_field (ret_v, 0, box.x0);
3137 Store_double_field (ret_v, 1, box.x1);
3138 Store_double_field (ret_v, 2, box.y0);
3139 Store_double_field (ret_v, 3, box.y1);
3141 CAMLreturn (ret_v);
3144 static double getmaxw (void)
3146 int i;
3147 struct pagedim *p;
3148 double maxw = 0.0;
3150 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3151 double x0, x1, w;
3153 x0 = MIN (p->mediabox.x0, p->mediabox.x1);
3154 x1 = MAX (p->mediabox.x0, p->mediabox.x1);
3156 w = x1 - x0;
3157 maxw = MAX (w, maxw);
3159 return maxw;
3162 CAMLprim value ml_getmaxw (value unit_v)
3164 CAMLparam1 (unit_v);
3165 CAMLlocal1 (ret_v);
3166 double maxw = 0.0;
3168 if (trylock ("ml_getmaxw")) {
3169 goto done;
3171 maxw = getmaxw ();
3172 unlock ("ml_getmaxw");
3173 done:
3174 ret_v = caml_copy_double (maxw);
3175 CAMLreturn (ret_v);
3178 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3179 value dw_v, value cols_v)
3181 CAMLparam3 (winw_v, winh_v, dw_v);
3182 CAMLlocal1 (ret_v);
3183 int i;
3184 double zoom = 1.0;
3185 double maxw = 0.0, maxh = 0.0;
3186 struct pagedim *p;
3187 double winw = Int_val (winw_v);
3188 double winh = Int_val (winh_v);
3189 double dw = Int_val (dw_v);
3190 double cols = Int_val (cols_v);
3191 double pw = 1.0, ph = 1.0, aspect;
3193 if (trylock ("ml_zoom_for_height")) {
3194 goto done;
3197 if (state.proportional) {
3198 maxw = getmaxw () / cols;
3201 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3202 double x0, x1, y0, y1, w, h, scaledh, scale;
3203 fz_rect rect;
3205 rect = fz_transform_rect (fz_rotate (p->rotate + state.rotate),
3206 p->mediabox);
3207 x0 = MIN (rect.x0, rect.x1);
3208 x1 = MAX (rect.x0, rect.x1);
3209 y0 = MIN (rect.y0, rect.y1);
3210 y1 = MAX (rect.y0, rect.y1);
3212 w = (x1 - x0) / cols;
3213 h = y1 - y0;
3215 if (state.proportional) {
3216 scale = w / maxw;
3217 scaledh = h * scale;
3219 else {
3220 scale = 1.0;
3221 scaledh = h;
3224 if (scaledh > maxh) {
3225 maxh = scaledh;
3226 ph = scaledh;
3227 pw = w * scale;
3231 aspect = pw / ph;
3232 zoom = (winh * aspect + dw) / winw;
3234 unlock ("ml_zoom_for_height");
3235 done:
3236 ret_v = caml_copy_double (zoom);
3237 CAMLreturn (ret_v);
3240 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3242 CAMLparam4 (pt_v, x_v, y_v, string_v);
3243 CAMLlocal1 (ret_v);
3244 int pt = Int_val(pt_v);
3245 int x = Int_val (x_v);
3246 int y = Int_val (y_v);
3247 double w;
3249 w = draw_string (state.face, pt, x, y, String_val (string_v));
3250 ret_v = caml_copy_double (w);
3251 CAMLreturn (ret_v);
3254 CAMLprim value ml_measure_string (value pt_v, value string_v)
3256 CAMLparam2 (pt_v, string_v);
3257 CAMLlocal1 (ret_v);
3258 int pt = Int_val (pt_v);
3259 double w;
3261 w = measure_string (state.face, pt, String_val (string_v));
3262 ret_v = caml_copy_double (w);
3263 CAMLreturn (ret_v);
3266 CAMLprim value ml_getpagebox (value opaque_v)
3268 CAMLparam1 (opaque_v);
3269 CAMLlocal1 (ret_v);
3270 fz_bbox bbox;
3271 fz_device *dev;
3272 char *s = String_val (opaque_v);
3273 struct page *page = parse_pointer ("ml_getpagebox", s);
3275 ret_v = caml_alloc_tuple (4);
3276 dev = fz_new_bbox_device (state.ctx, &bbox);
3277 dev->hints |= FZ_IGNORE_SHADE;
3279 switch (page->type) {
3280 case DPDF:
3281 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, pagectm (page), NULL);
3282 break;
3284 case DXPS:
3285 xps_run_page (state.u.xps, page->u.xpspage, dev, pagectm (page), NULL);
3286 break;
3288 default:
3289 bbox = fz_infinite_bbox;
3290 break;
3293 fz_free_device (dev);
3294 Field (ret_v, 0) = Val_int (bbox.x0);
3295 Field (ret_v, 1) = Val_int (bbox.y0);
3296 Field (ret_v, 2) = Val_int (bbox.x1);
3297 Field (ret_v, 3) = Val_int (bbox.y1);
3299 CAMLreturn (ret_v);
3302 CAMLprim value ml_setaalevel (value level_v)
3304 CAMLparam1 (level_v);
3306 state.aalevel = Int_val (level_v);
3307 CAMLreturn (Val_unit);
3310 #undef pixel
3311 #include <X11/Xlib.h>
3312 #include <GL/glx.h>
3314 static struct {
3315 Display *dpy;
3316 GLXContext ctx;
3317 GLXDrawable drawable;
3318 } glx;
3320 #include "keysym2ucs.c"
3322 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3324 CAMLparam1 (keysym_v);
3325 CAMLlocal1 (str_v);
3326 KeySym keysym = Int_val (keysym_v);
3327 Rune rune;
3328 int len;
3329 char buf[5];
3331 rune = keysym2ucs (keysym);
3332 len = fz_runetochar (buf, rune);
3333 buf[len] = 0;
3334 str_v = caml_copy_string (buf);
3335 CAMLreturn (str_v);
3338 CAMLprim value ml_glx (value win_v)
3340 CAMLparam1 (win_v);
3341 XVisualInfo *visual;
3342 int screen, wid = Int_val (win_v);
3343 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3345 glx.dpy = XOpenDisplay (NULL);
3346 if (!glx.dpy) {
3347 caml_failwith ("XOpenDisplay");
3350 screen = DefaultScreen (glx.dpy);
3351 visual = glXChooseVisual (glx.dpy, screen, attributes);
3352 if (!visual) {
3353 XCloseDisplay (glx.dpy);
3354 glx.dpy = NULL;
3355 caml_failwith ("glXChooseVisual");
3358 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3359 XFree (visual);
3360 if (!glx.ctx) {
3361 XCloseDisplay (glx.dpy);
3362 glx.dpy = NULL;
3363 caml_failwith ("glXCreateContext");
3366 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3367 glXDestroyContext (glx.dpy, glx.ctx);
3368 XCloseDisplay (glx.dpy);
3369 glx.dpy = NULL;
3370 glx.ctx = NULL;
3371 caml_failwith ("glXMakeCurrent");
3373 glx.drawable = wid;
3374 CAMLreturn (Val_unit);
3377 CAMLprim value ml_swapb (value unit_v)
3379 CAMLparam1 (unit_v);
3380 glXSwapBuffers (glx.dpy, glx.drawable);
3381 CAMLreturn (Val_unit);
3384 CAMLprim value ml_glxsync (value unit_v)
3386 CAMLparam1 (unit_v);
3387 if (glx.dpy && glx.ctx) {
3388 glXWaitX ();
3389 glXWaitGL ();
3391 CAMLreturn (Val_unit);
3394 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3395 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3397 CAMLprim value ml_platform (value unit_v)
3399 CAMLparam1 (unit_v);
3400 int platid = piunknown;
3402 #if defined __linux__
3403 platid = pilinux;
3404 #elif defined __CYGWIN__
3405 platid = picygwin;
3406 #elif defined __DragonFly__
3407 platid = pidragonflybsd;
3408 #elif defined __FreeBSD__
3409 platid = pifreebsd;
3410 #elif defined __OpenBSD__
3411 platid = piopenbsd;
3412 #elif defined __NetBSD__
3413 platid = pinetbsd;
3414 #elif defined __sun__
3415 platid = pisun;
3416 #elif defined __APPLE__
3417 platid = piosx;
3418 #endif
3419 CAMLreturn (Val_int (platid));
3422 CAMLprim value ml_cloexec (value fd_v)
3424 CAMLparam1 (fd_v);
3425 int fd = Int_val (fd_v);
3427 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3428 uerror ("fcntl", Nothing);
3430 CAMLreturn (Val_unit);
3433 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3435 CAMLparam2 (w_v, h_v);
3436 CAMLlocal1 (ret_v);
3437 struct pbo *pbo;
3438 int w = Int_val (w_v);
3439 int h = Int_val (h_v);
3440 int cs = Int_val (cs_v);
3442 if (state.pbo_usable) {
3443 pbo = calloc (sizeof (*pbo), 1);
3444 if (!pbo) {
3445 err (1, "calloc pbo");
3448 switch (cs) {
3449 case 0:
3450 case 1:
3451 pbo->size = w*h*4;
3452 break;
3453 case 2:
3454 pbo->size = w*h*2;
3455 break;
3456 default:
3457 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3460 state.glGenBuffersARB (1, &pbo->id);
3461 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3462 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3463 NULL, GL_STREAM_DRAW);
3464 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3465 GL_READ_WRITE);
3466 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3467 if (!pbo->ptr) {
3468 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3469 state.glDeleteBuffersARB (1, &pbo->id);
3470 free (pbo);
3471 ret_v = caml_copy_string ("0");
3473 else {
3474 int res;
3475 char *s;
3477 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3478 if (res < 0) {
3479 err (1, "snprintf %" FMT_ptr " failed", pbo);
3481 s = malloc (res+1);
3482 if (!s) {
3483 err (1, "malloc %d bytes failed", res+1);
3485 res = sprintf (s, "%" FMT_ptr, pbo);
3486 if (res < 0) {
3487 err (1, "sprintf %" FMT_ptr " failed", pbo);
3489 ret_v = caml_copy_string (s);
3490 free (s);
3493 else {
3494 ret_v = caml_copy_string ("0");
3496 CAMLreturn (ret_v);
3499 CAMLprim value ml_freepbo (value s_v)
3501 CAMLparam1 (s_v);
3502 char *s = String_val (s_v);
3503 struct tile *tile = parse_pointer ("ml_freepbo", s);
3505 if (tile->pbo) {
3506 state.glDeleteBuffersARB (1, &tile->pbo->id);
3507 tile->pbo->id = -1;
3508 tile->pbo->ptr = NULL;
3509 tile->pbo->size = -1;
3511 CAMLreturn (Val_unit);
3514 CAMLprim value ml_unmappbo (value s_v)
3516 CAMLparam1 (s_v);
3517 char *s = String_val (s_v);
3518 struct tile *tile = parse_pointer ("ml_unmappbo", s);
3520 if (tile->pbo) {
3521 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3522 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3523 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3525 tile->pbo->ptr = NULL;
3526 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3528 CAMLreturn (Val_unit);
3531 static void setuppbo (void)
3533 #define GGPA(n) *(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n)
3534 GGPA (glBindBufferARB);
3535 if (state.glBindBufferARB) {
3536 GGPA (glUnmapBufferARB);
3537 if (state.glUnmapBufferARB) {
3538 GGPA (glMapBufferARB);
3539 if (state.glMapBufferARB) {
3540 GGPA (glBufferDataARB);
3541 if (state.glBufferDataARB) {
3542 GGPA (glGenBuffersARB);
3543 if (state.glGenBuffersARB) {
3544 GGPA (glDeleteBuffersARB);
3545 if (state.glDeleteBuffersARB) {
3546 state.pbo_usable = 1;
3553 #undef GGPA
3556 CAMLprim value ml_pbo_usable (value unit_v)
3558 CAMLparam1 (unit_v);
3559 CAMLreturn (Val_bool (state.pbo_usable));
3562 CAMLprim value ml_init (value pipe_v, value params_v)
3564 CAMLparam2 (pipe_v, params_v);
3565 CAMLlocal2 (trim_v, fuzz_v);
3566 int ret;
3567 int texcount;
3568 char *fontpath;
3569 int colorspace;
3570 int mustoresize;
3571 int haspboext;
3572 struct sigaction sa;
3574 state.cr = Int_val (Field (pipe_v, 0));
3575 state.cw = Int_val (Field (pipe_v, 1));
3576 state.rotate = Int_val (Field (params_v, 0));
3577 state.proportional = Bool_val (Field (params_v, 1));
3578 trim_v = Field (params_v, 2);
3579 texcount = Int_val (Field (params_v, 3));
3580 state.sliceheight = Int_val (Field (params_v, 4));
3581 mustoresize = Int_val (Field (params_v, 5));
3582 colorspace = Int_val (Field (params_v, 6));
3583 fontpath = String_val (Field (params_v, 7));
3584 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
3585 if (!state.trimcachepath) {
3586 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
3587 strerror (errno));
3589 haspboext = Bool_val (Field (params_v, 9));
3591 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3593 state.trimmargins = Bool_val (Field (trim_v, 0));
3594 fuzz_v = Field (trim_v, 1);
3595 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3596 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3597 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3598 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3600 set_tex_params (colorspace);
3602 if (*fontpath) {
3603 state.face = load_font (fontpath);
3605 else {
3606 unsigned int len;
3607 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
3609 state.face = load_builtin_font (base, len);
3611 if (!state.face) _exit (1);
3613 realloctexts (texcount);
3615 if (haspboext) {
3616 setuppbo ();
3619 #ifdef __CYGWIN__
3620 sa.sa_handler = SIG_IGN;
3621 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3622 #else
3623 sa.sa_handler = SIG_DFL;
3624 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
3625 #endif
3626 if (sigemptyset (&sa.sa_mask)) {
3627 err (1, "sigemptyset");
3629 if (sigaction (SIGCHLD, &sa, NULL)) {
3630 err (1, "sigaction");
3633 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3634 if (ret) {
3635 errx (1, "pthread_create: %s", strerror (ret));
3638 CAMLreturn (Val_unit);