Change the way color inversion is implemented
[llpp.git] / link.c
blobc4c3ccdf3ba13667c9e3b6fdaae32b372cc44e36
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 <stdarg.h>
24 #include <limits.h>
26 #include <GL/gl.h>
28 #include <caml/fail.h>
29 #include <caml/alloc.h>
30 #include <caml/memory.h>
31 #include <caml/unixsupport.h>
33 #include <mupdf/fitz.h>
34 #include <mupdf/cbz.h>
35 #include <mupdf/pdf.h>
36 #include <mupdf/xps.h>
37 #include <mupdf/img.h>
39 #include FT_FREETYPE_H
41 #define PIGGYBACK
43 #ifndef __USE_GNU
44 extern char **environ;
45 #endif
47 #define MIN(a,b) ((a) < (b) ? (a) : (b))
48 #define MAX(a,b) ((a) > (b) ? (a) : (b))
50 #if defined __GNUC__
51 #define NORETURN_ATTR __attribute__ ((noreturn))
52 #define UNUSED_ATTR __attribute__ ((unused))
53 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
54 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
55 #else
56 #define NORETURN_ATTR
57 #define UNUSED_ATTR
58 #define OPTIMIZE_ATTR(n)
59 #define GCC_FMT_ATTR(a, b)
60 #endif
62 #define FMT_s "zu"
64 #define FMT_ptr "p"
65 #define FMT_ptr_cast(p) (p)
66 #define FMT_ptr_cast2(p) (p)
68 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
69 err (int exitcode, const char *fmt, ...)
71 va_list ap;
72 int savederrno;
74 savederrno = errno;
75 va_start (ap, fmt);
76 vfprintf (stderr, fmt, ap);
77 va_end (ap);
78 fprintf (stderr, ": %s\n", strerror (savederrno));
79 fflush (stderr);
80 _exit (exitcode);
83 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
84 errx (int exitcode, const char *fmt, ...)
86 va_list ap;
88 va_start (ap, fmt);
89 vfprintf (stderr, fmt, ap);
90 va_end (ap);
91 fputc ('\n', stderr);
92 fflush (stderr);
93 _exit (exitcode);
96 #ifndef GL_TEXTURE_RECTANGLE_ARB
97 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
98 #endif
100 #ifndef GL_BGRA
101 #define GL_BGRA 0x80E1
102 #endif
104 #ifndef GL_UNSIGNED_INT_8_8_8_8
105 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
106 #endif
108 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
109 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
110 #endif
112 #if 0
113 #define lprintf printf
114 #else
115 #define lprintf(...)
116 #endif
118 #define ARSERT(cond) for (;;) { \
119 if (!(cond)) { \
120 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
122 break; \
125 struct slice {
126 int h;
127 int texindex;
130 struct tile {
131 int w, h;
132 int slicecount;
133 int sliceheight;
134 struct pbo *pbo;
135 fz_pixmap *pixmap;
136 struct slice slices[1];
139 struct pagedim {
140 int pageno;
141 int rotate;
142 int left;
143 int tctmready;
144 fz_irect bounds;
145 fz_rect pagebox;
146 fz_rect mediabox;
147 fz_matrix ctm, zoomctm, lctm, tctm;
150 struct slink {
151 fz_irect bbox;
152 fz_link *link;
155 enum { DPDF, DXPS, DCBZ, DIMG };
157 struct page {
158 int tgen;
159 int sgen;
160 int type;
161 int pageno;
162 int pdimno;
163 fz_text_page *text;
164 fz_text_sheet *sheet;
165 union {
166 void *ptr;
167 pdf_page *pdfpage;
168 xps_page *xpspage;
169 cbz_page *cbzpage;
170 image_page *imgpage;
171 } u;
172 fz_display_list *dlist;
173 int slinkcount;
174 struct slink *slinks;
175 struct mark {
176 int i;
177 fz_text_span *span;
178 } fmark, lmark;
179 void (*freepage) (void *);
182 struct {
183 int type;
184 int sliceheight;
185 struct pagedim *pagedims;
186 int pagecount;
187 int pagedimcount;
188 union {
189 pdf_document *pdf;
190 xps_document *xps;
191 cbz_document *cbz;
192 image_document *img;
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 enum { FitWidth, FitProportional, FitPage } fitmodel;
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;
231 int cxack;
233 GLuint stid;
235 int pbo_usable;
236 void (*glBindBufferARB) (GLenum, GLuint);
237 GLboolean (*glUnmapBufferARB) (GLenum);
238 void *(*glMapBufferARB) (GLenum, GLenum);
239 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
240 void (*glGenBuffersARB) (GLsizei, GLuint *);
241 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
243 GLfloat texcoords[8];
244 GLfloat vertices[16];
245 } state;
247 struct pbo {
248 GLuint id;
249 void *ptr;
250 size_t size;
253 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
255 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
258 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
260 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
263 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
265 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
266 m.a, m.b, m.c, m.d, m.e, m.f);
269 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
271 static void lock (const char *cap)
273 int ret = pthread_mutex_lock (&mutex);
274 if (ret) {
275 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
279 static void unlock (const char *cap)
281 int ret = pthread_mutex_unlock (&mutex);
282 if (ret) {
283 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
287 static int trylock (const char *cap)
289 int ret = pthread_mutex_trylock (&mutex);
290 if (ret && ret != EBUSY) {
291 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
293 return ret == EBUSY;
296 static void *parse_pointer (const char *cap, const char *s)
298 int ret;
299 void *ptr;
301 ret = sscanf (s, "%" FMT_ptr, FMT_ptr_cast (&ptr));
302 if (ret != 1) {
303 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
305 return ptr;
308 static double now (void)
310 struct timeval tv;
312 if (gettimeofday (&tv, NULL)) {
313 err (1, "gettimeofday");
315 return tv.tv_sec + tv.tv_usec*1e-6;
318 static int hasdata (void)
320 int ret, avail;
321 ret = ioctl (state.cr, FIONREAD, &avail);
322 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
323 return avail > 0;
326 CAMLprim value ml_hasdata (value fd_v)
328 CAMLparam1 (fd_v);
329 int ret, avail;
331 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
332 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
333 CAMLreturn (Val_bool (avail > 0));
336 static void readdata (void *p, int size)
338 ssize_t n;
340 again:
341 n = read (state.cr, p, size);
342 if (n < 0) {
343 if (errno == EINTR) goto again;
344 err (1, "read (req %d, ret %zd)", size, n);
346 if (n - size) {
347 if (!n) errx (1, "EOF while reading");
348 errx (1, "read (req %d, ret %zd)", size, n);
352 static void writedata (char *p, int size)
354 ssize_t n;
356 p[0] = (size >> 24) & 0xff;
357 p[1] = (size >> 16) & 0xff;
358 p[2] = (size >> 8) & 0xff;
359 p[3] = (size >> 0) & 0xff;
361 n = write (state.cw, p, size + 4);
362 if (n - size - 4) {
363 if (!n) errx (1, "EOF while writing data");
364 err (1, "write (req %d, ret %zd)", size + 4, n);
368 static int readlen (void)
370 unsigned char p[4];
372 readdata (p, 4);
373 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
376 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
378 int size = 200, len;
379 va_list ap;
380 char *buf;
382 buf = malloc (size);
383 for (;;) {
384 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
386 va_start (ap, fmt);
387 len = vsnprintf (buf + 4, size - 4, fmt, ap);
388 va_end (ap);
390 if (len > -1) {
391 if (len < size - 4) {
392 writedata (buf, len);
393 break;
395 else size = len + 5;
397 else {
398 err (1, "vsnprintf for `%s' failed", fmt);
400 buf = realloc (buf, size);
402 free (buf);
405 static void closepdf (void)
407 if (state.u.pdf) {
408 pdf_close_document (state.u.pdf);
409 state.u.pdf = NULL;
413 static void closexps (void)
415 if (state.u.xps) {
416 xps_close_document (state.u.xps);
417 state.u.xps = NULL;
421 static void closecbz (void)
423 if (state.u.cbz) {
424 cbz_close_document (state.u.cbz);
425 state.u.cbz = NULL;
429 static void closeimg (void)
431 if (state.u.img) {
432 image_close_document (state.u.img);
433 state.u.img = NULL;
437 static void freepdfpage (void *ptr)
439 pdf_free_page (state.u.pdf, ptr);
442 static void freeemptyxxxpage (void *ptr)
444 (void) ptr;
447 static void freexpspage (void *ptr)
449 xps_free_page (state.u.xps, ptr);
452 static void freecbzpage (void *ptr)
454 cbz_free_page (state.u.cbz, ptr);
457 static void freeimgpage (void *ptr)
459 image_free_page (state.u.img, ptr);
462 static void openxref (char *filename, char *password)
464 int i, len;
466 for (i = 0; i < state.texcount; ++i) {
467 state.texowners[i].w = -1;
468 state.texowners[i].slice = NULL;
471 if (state.closedoc) state.closedoc ();
473 len = strlen (filename);
475 state.type = DPDF;
477 int i;
478 struct {
479 char *ext;
480 int type;
481 } tbl[] = {
482 { "pdf", DPDF },
483 { "xps", DXPS },
484 { "cbz", DCBZ },
485 { "jpg", DIMG },
486 { "jpeg", DIMG },
487 { "png", DIMG }
490 for (i = 0; i < sizeof (tbl) / sizeof (*tbl); ++i) {
491 int len2 = strlen (tbl[i].ext);
493 if (len2 < len && !strcasecmp (tbl[i].ext, filename + len - len2)) {
494 state.type = tbl[i].type;
495 break;
500 if (state.pagedims) {
501 free (state.pagedims);
502 state.pagedims = NULL;
504 state.pagedimcount = 0;
506 fz_set_aa_level (state.ctx, state.aalevel);
507 switch (state.type) {
508 case DPDF:
509 state.u.pdf = pdf_open_document (state.ctx, filename);
510 if (pdf_needs_password (state.u.pdf)) {
511 int okay = pdf_authenticate_password (state.u.pdf, password);
512 if (!okay) {
513 errx (1, "invalid password");
516 state.pagecount = pdf_count_pages (state.u.pdf);
517 state.closedoc = closepdf;
518 state.freepage = freepdfpage;
519 break;
521 case DXPS:
522 state.u.xps = xps_open_document (state.ctx, filename);
523 state.pagecount = xps_count_pages (state.u.xps);
524 state.closedoc = closexps;
525 state.freepage = freexpspage;
526 break;
528 case DCBZ:
529 state.u.cbz = cbz_open_document (state.ctx, filename);
530 state.pagecount = cbz_count_pages (state.u.cbz);
531 state.closedoc = closecbz;
532 state.freepage = freecbzpage;
533 break;
535 case DIMG:
536 state.u.img = image_open_document (state.ctx, filename);
537 state.pagecount = 1;
538 state.closedoc = closeimg;
539 state.freepage = freeimgpage;
540 break;
544 static void pdfinfo (void)
546 if (state.type == DPDF) {
547 pdf_obj *infoobj;
549 printd ("info PDF version\t%d.%d",
550 state.u.pdf->version / 10, state.u.pdf->version % 10);
552 infoobj = pdf_dict_gets (pdf_trailer (state.u.pdf), "Info");
553 if (infoobj) {
554 int i;
555 char *s;
556 char *items[] = { "Title", "Author", "Creator",
557 "Producer", "CreationDate" };
559 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
560 pdf_obj *obj = pdf_dict_gets (infoobj, items[i]);
561 s = pdf_to_utf8 (state.u.pdf, obj);
562 if (*s) {
563 if (i == 0) {
564 printd ("title %s", s);
566 printd ("info %s\t%s", items[i], s);
568 fz_free (state.ctx, s);
571 printd ("infoend");
575 static void unlinktile (struct tile *tile)
577 int i;
579 for (i = 0; i < tile->slicecount; ++i) {
580 struct slice *s = &tile->slices[i];
582 if (s->texindex != -1) {
583 if (state.texowners[s->texindex].slice == s) {
584 state.texowners[s->texindex].slice = NULL;
590 static void freepage (struct page *page)
592 if (page->text) {
593 fz_free_text_page (state.ctx, page->text);
595 if (page->sheet) {
596 fz_free_text_sheet (state.ctx, page->sheet);
598 if (page->slinks) {
599 free (page->slinks);
601 fz_drop_display_list (state.ctx, page->dlist);
602 page->freepage (page->u.ptr);
603 free (page);
606 static void freetile (struct tile *tile)
608 unlinktile (tile);
609 if (!tile->pbo) {
610 #ifndef PIGGYBACK
611 fz_drop_pixmap (state.ctx, tile->pixmap);
612 #else
613 if (state.pig) {
614 fz_drop_pixmap (state.ctx, state.pig);
616 state.pig = tile->pixmap;
617 #endif
619 else {
620 free (tile->pbo);
621 fz_drop_pixmap (state.ctx, tile->pixmap);
623 free (tile);
626 #ifdef __ALTIVEC__
627 #include <stdint.h>
628 #include <altivec.h>
630 static int cacheline32bytes;
632 static void __attribute__ ((constructor)) clcheck (void)
634 char **envp = environ;
635 unsigned long *auxv;
637 while (*envp++);
639 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
640 if (*auxv == 19) {
641 cacheline32bytes = auxv[1] == 32;
642 return;
647 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
649 size_t size = pixmap->w * pixmap->h * pixmap->n;
650 if (cacheline32bytes && size > 32) {
651 intptr_t a1, a2, diff;
652 size_t sizea, i;
653 vector unsigned char v = vec_splat_u8 (-1);
654 vector unsigned char *p;
656 a1 = a2 = (intptr_t) pixmap->samples;
657 a2 = (a1 + 31) & ~31;
658 diff = a2 - a1;
659 sizea = size - diff;
660 p = (void *) a2;
662 while (a1 != a2) *(char *) a1++ = 0xff;
663 for (i = 0; i < (sizea & ~31); i += 32) {
664 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
665 vec_st (v, i, p);
666 vec_st (v, i + 16, p);
668 while (i < sizea) *((char *) a1 + i++) = 0xff;
670 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
672 #else
673 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
674 #endif
676 static void trimctm (pdf_page *page, int pindex)
678 fz_matrix ctm;
679 struct pagedim *pdim = &state.pagedims[pindex];
681 if (!pdim->tctmready) {
682 if (state.trimmargins) {
683 fz_rect realbox;
684 fz_matrix rm, sm, tm, im, ctm1;
686 fz_rotate (&rm, -pdim->rotate);
687 fz_scale (&sm, 1, -1);
688 fz_concat (&ctm, &rm, &sm);
689 realbox = pdim->mediabox;
690 fz_transform_rect (&realbox, &ctm);
691 fz_translate (&tm, -realbox.x0, -realbox.y0);
692 fz_concat (&ctm1, &ctm, &tm);
693 fz_invert_matrix (&im, &page->ctm);
694 fz_concat (&ctm, &im, &ctm1);
696 else {
697 ctm = fz_identity;
699 pdim->tctm = ctm;
700 pdim->tctmready = 1;
704 static fz_matrix pagectm (struct page *page)
706 fz_matrix ctm, tm;
708 if (page->type == DPDF) {
709 trimctm (page->u.pdfpage, page->pdimno);
710 fz_concat (&ctm,
711 &state.pagedims[page->pdimno].tctm,
712 &state.pagedims[page->pdimno].ctm);
714 else {
715 struct pagedim *pdim = &state.pagedims[page->pdimno];
717 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
718 fz_concat (&ctm, &tm, &state.pagedims[page->pdimno].ctm);
720 return ctm;
723 static void *loadpage (int pageno, int pindex)
725 fz_device *dev;
726 struct page *page;
728 page = calloc (sizeof (struct page), 1);
729 if (!page) {
730 err (1, "calloc page %d", pageno);
733 page->dlist = fz_new_display_list (state.ctx);
734 dev = fz_new_list_device (state.ctx, page->dlist);
735 fz_try (state.ctx) {
736 switch (state.type) {
737 case DPDF:
738 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
739 pdf_run_page (state.u.pdf, page->u.pdfpage, dev,
740 &fz_identity, NULL);
741 page->freepage = freepdfpage;
742 break;
744 case DXPS:
745 page->u.xpspage = xps_load_page (state.u.xps, pageno);
746 xps_run_page (state.u.xps, page->u.xpspage, dev,
747 &fz_identity, NULL);
748 page->freepage = freexpspage;
749 break;
751 case DCBZ:
752 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
753 cbz_run_page (state.u.cbz, page->u.cbzpage, dev,
754 &fz_identity, NULL);
755 page->freepage = freecbzpage;
756 break;
758 case DIMG:
759 page->u.imgpage = image_load_page (state.u.img, pageno);
760 image_run_page (state.u.img, page->u.imgpage, dev,
761 &fz_identity, NULL);
762 page->freepage = freeimgpage;
763 break;
766 fz_catch (state.ctx) {
767 page->u.ptr = NULL;
768 page->freepage = freeemptyxxxpage;
770 fz_free_device (dev);
772 page->pdimno = pindex;
773 page->pageno = pageno;
774 page->sgen = state.gen;
775 page->tgen = state.gen;
776 page->type = state.type;
778 return page;
781 static struct tile *alloctile (int h)
783 int i;
784 int slicecount;
785 size_t tilesize;
786 struct tile *tile;
788 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
789 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
790 tile = calloc (tilesize, 1);
791 if (!tile) {
792 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
794 for (i = 0; i < slicecount; ++i) {
795 int sh = MIN (h, state.sliceheight);
796 tile->slices[i].h = sh;
797 tile->slices[i].texindex = -1;
798 h -= sh;
800 tile->slicecount = slicecount;
801 tile->sliceheight = state.sliceheight;
802 return tile;
805 #ifdef OBSCURED_OPT
806 struct obs {
807 int cured;
808 fz_irect b;
811 static void obs_fill_image (fz_device *dev, fz_image *image,
812 const fz_matrix *ctm, float alpha)
814 struct obs *obs = dev->user;
816 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
817 fz_irect b;
818 fz_rect rect = fz_unit_rect;
820 fz_transform_rect (&rect, ctm);
821 fz_round_rect (&b, &rect);
822 fz_intersect_irect (&b, &obs->b);
823 obs->cured = b.x0 == obs->b.x0
824 && b.x1 == obs->b.x1
825 && b.y0 == obs->b.y0
826 && b.y1 == obs->b.y1;
830 static int obscured (struct page *page, fz_irect bbox)
832 fz_rect rect;
833 fz_matrix ctm;
834 fz_device dev;
835 struct obs obs;
837 memset (&dev, 0, sizeof (dev));
838 memset (&obs, 0, sizeof (obs));
839 dev.hints = 0;
840 dev.flags = 0;
841 dev.user = &obs;
842 dev.ctx = state.ctx;
843 dev.fill_image = obs_fill_image;
844 obs.b = bbox;
845 fz_rect_from_irect (&rect, &bbox);
846 ctm = pagectm (page);
847 fz_run_display_list (page->dlist, &dev, &ctm, &rect, NULL);
848 return obs.cured;
850 #define OBSCURED obscured
851 #else
852 #define OBSCURED(a, b) 0
853 #endif
855 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
856 struct pbo *pbo)
858 fz_rect rect;
859 fz_irect bbox;
860 fz_matrix ctm;
861 fz_device *dev;
862 struct tile *tile;
863 struct pagedim *pdim;
865 tile = alloctile (h);
866 pdim = &state.pagedims[page->pdimno];
868 bbox = pdim->bounds;
869 bbox.x0 += x;
870 bbox.y0 += y;
871 bbox.x1 = bbox.x0 + w;
872 bbox.y1 = bbox.y0 + h;
874 if (state.pig) {
875 if (state.pig->w == w
876 && state.pig->h == h
877 && state.pig->colorspace == state.colorspace) {
878 tile->pixmap = state.pig;
879 tile->pixmap->x = bbox.x0;
880 tile->pixmap->y = bbox.y0;
882 else {
883 fz_drop_pixmap (state.ctx, state.pig);
885 state.pig = NULL;
887 if (!tile->pixmap) {
888 if (pbo) {
889 tile->pixmap =
890 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
891 &bbox, pbo->ptr);
892 tile->pbo = pbo;
894 else {
895 tile->pixmap =
896 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
900 tile->w = w;
901 tile->h = h;
902 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
903 clearpixmap (tile->pixmap);
905 dev = fz_new_draw_device (state.ctx, tile->pixmap);
906 ctm = pagectm (page);
907 fz_rect_from_irect (&rect, &bbox);
908 fz_run_display_list (page->dlist, dev, &ctm, &rect, NULL);
909 fz_free_device (dev);
911 return tile;
914 static void initpdims (void)
916 double start, end;
917 FILE *trimf = NULL;
918 fz_rect rootmediabox;
919 int pageno, trim, show;
920 int trimw = 0, cxcount;
922 start = now ();
924 if (state.trimmargins && state.trimcachepath) {
925 trimf = fopen (state.trimcachepath, "rb");
926 if (!trimf) {
927 trimf = fopen (state.trimcachepath, "wb");
928 trimw = 1;
932 if (state.trimmargins || state.type == DPDF || !state.cxack)
933 cxcount = state.pagecount;
934 else
935 cxcount = MIN (state.pagecount, 1);
937 if (state.type == DPDF) {
938 pdf_obj *obj;
939 obj = pdf_dict_getp (pdf_trailer (state.u.pdf),
940 "Root/Pages/MediaBox");
941 pdf_to_rect (state.ctx, obj, &rootmediabox);
944 for (pageno = 0; pageno < cxcount; ++pageno) {
945 int rotate = 0;
946 struct pagedim *p;
947 fz_rect mediabox;
949 switch (state.type) {
950 case DPDF: {
951 pdf_document *pdf = state.u.pdf;
952 pdf_obj *pageref = pdf_lookup_page_obj (pdf, pageno);
953 pdf_obj *pageobj = pdf_resolve_indirect (pageref);
955 if (state.trimmargins) {
956 pdf_obj *obj;
957 pdf_page *page;
959 fz_try (state.ctx) {
960 page = pdf_load_page (pdf, pageno);
961 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
962 trim = state.trimanew || !obj;
963 if (trim) {
964 fz_rect rect;
965 fz_matrix ctm;
966 fz_device *dev;
968 dev = fz_new_bbox_device (state.ctx, &rect);
969 dev->hints |= FZ_IGNORE_SHADE;
970 fz_invert_matrix (&ctm, &page->ctm);
971 pdf_run_page (pdf, page, dev, &fz_identity, NULL);
972 fz_free_device (dev);
974 rect.x0 += state.trimfuzz.x0;
975 rect.x1 += state.trimfuzz.x1;
976 rect.y0 += state.trimfuzz.y0;
977 rect.y1 += state.trimfuzz.y1;
978 fz_transform_rect (&rect, &ctm);
979 fz_intersect_rect (&rect, &page->mediabox);
981 if (fz_is_empty_rect (&rect)) {
982 mediabox = page->mediabox;
984 else {
985 mediabox = rect;
988 obj = pdf_new_array (pdf, 4);
989 pdf_array_push (obj, pdf_new_real (pdf, mediabox.x0));
990 pdf_array_push (obj, pdf_new_real (pdf, mediabox.y0));
991 pdf_array_push (obj, pdf_new_real (pdf, mediabox.x1));
992 pdf_array_push (obj, pdf_new_real (pdf, mediabox.y1));
993 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
995 else {
996 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
997 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
998 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
999 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
1002 rotate = page->rotate;
1003 pdf_free_page (pdf, page);
1005 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
1006 if (show) {
1007 printd ("progress %f Trimming %d",
1008 (double) (pageno + 1) / state.pagecount,
1009 pageno + 1);
1012 fz_catch (state.ctx) {
1013 fprintf (stderr, "failed to load page %d\n", pageno+1);
1016 else {
1017 int empty = 0;
1018 fz_rect cropbox;
1020 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "MediaBox"),
1021 &mediabox);
1022 if (fz_is_empty_rect (&mediabox)) {
1023 mediabox.x0 = 0;
1024 mediabox.y0 = 0;
1025 mediabox.x1 = 612;
1026 mediabox.y1 = 792;
1027 empty = 1;
1030 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "CropBox"),
1031 &cropbox);
1032 if (!fz_is_empty_rect (&cropbox)) {
1033 if (empty) {
1034 mediabox = cropbox;
1036 else {
1037 fz_intersect_rect (&mediabox, &cropbox);
1040 else {
1041 if (empty) {
1042 if (fz_is_empty_rect (&rootmediabox)) {
1043 fprintf (stderr,
1044 "cannot find page size for page %d\n",
1045 pageno+1);
1047 else {
1048 mediabox = rootmediabox;
1052 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
1054 break;
1057 case DXPS:
1059 xps_page *page;
1061 fz_try (state.ctx) {
1062 page = xps_load_page (state.u.xps, pageno);
1063 xps_bound_page (state.u.xps, page, &mediabox);
1064 rotate = 0;
1065 if (state.trimmargins) {
1066 fz_rect rect;
1067 fz_device *dev;
1069 dev = fz_new_bbox_device (state.ctx, &rect);
1070 dev->hints |= FZ_IGNORE_SHADE;
1071 xps_run_page (state.u.xps, page, dev,
1072 &fz_identity, NULL);
1073 fz_free_device (dev);
1075 rect.x0 += state.trimfuzz.x0;
1076 rect.x1 += state.trimfuzz.x1;
1077 rect.y0 += state.trimfuzz.y0;
1078 rect.y1 += state.trimfuzz.y1;
1079 fz_intersect_rect (&rect, &mediabox);
1081 if (!fz_is_empty_rect (&rect)) {
1082 mediabox = rect;
1085 xps_free_page (state.u.xps, page);
1086 if (!state.cxack) {
1087 printd ("progress %f loading %d",
1088 (double) (pageno + 1) / state.pagecount,
1089 pageno + 1);
1092 fz_catch (state.ctx) {
1095 break;
1097 case DCBZ:
1099 rotate = 0;
1100 mediabox.x0 = 0;
1101 mediabox.y0 = 0;
1102 mediabox.x1 = 900;
1103 mediabox.y1 = 900;
1104 if (state.trimmargins && trimw) {
1105 cbz_page *page;
1107 fz_try (state.ctx) {
1108 page = cbz_load_page (state.u.cbz, pageno);
1109 cbz_bound_page (state.u.cbz, page, &mediabox);
1110 cbz_free_page (state.u.cbz, page);
1111 printd ("progress %f Trimming %d",
1112 (double) (pageno + 1) / state.pagecount,
1113 pageno + 1);
1115 fz_catch (state.ctx) {
1116 fprintf (stderr, "failed to load page %d\n", pageno+1);
1118 if (trimf) {
1119 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1120 if (n - 1) {
1121 err (1, "fwrite trim mediabox");
1125 else {
1126 if (trimf) {
1127 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1128 if (n - 1) {
1129 err (1, "fread trim mediabox");
1132 else {
1133 if (state.cxack) {
1134 cbz_page *page;
1135 fz_try (state.ctx) {
1136 page = cbz_load_page (state.u.cbz, pageno);
1137 cbz_bound_page (state.u.cbz, page, &mediabox);
1138 cbz_free_page (state.u.cbz, page);
1140 fz_catch (state.ctx) {
1141 fprintf (stderr, "failed to load cbz page\n");
1147 break;
1149 case DIMG:
1151 image_page *page;
1153 rotate = 0;
1154 mediabox.x0 = 0;
1155 mediabox.y0 = 0;
1156 mediabox.x1 = 900;
1157 mediabox.y1 = 900;
1159 fz_try (state.ctx) {
1160 page = image_load_page (state.u.img, pageno);
1161 image_bound_page (state.u.img, page, &mediabox);
1162 image_free_page (state.u.img, page);
1164 fz_catch (state.ctx) {
1165 fprintf (stderr, "failed to load page %d\n", pageno+1);
1168 break;
1170 default:
1171 ARSERT (0 && state.type);
1174 if (state.pagedimcount == 0
1175 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1176 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1177 size_t size;
1179 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1180 state.pagedims = realloc (state.pagedims, size);
1181 if (!state.pagedims) {
1182 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1183 size, state.pagedimcount + 1);
1186 p = &state.pagedims[state.pagedimcount++];
1187 p->rotate = rotate;
1188 p->mediabox = mediabox;
1189 p->pageno = pageno;
1192 end = now ();
1193 if (state.trimmargins) {
1194 printd ("progress 1 Trimmed %d pages in %f seconds",
1195 state.pagecount, end - start);
1197 else {
1198 printd ("vmsg Processed %d pages in %f seconds",
1199 state.pagecount, end - start);
1201 state.trimanew = 0;
1202 if (trimf) {
1203 if (fclose (trimf)) {
1204 err (1, "fclose");
1209 static void layout (void)
1211 int pindex;
1212 fz_rect box;
1213 fz_matrix ctm, rm;
1214 struct pagedim *p = p;
1215 double zw, w, maxw = 0.0, zoom = zoom;
1217 if (state.pagedimcount == 0) return;
1219 switch (state.fitmodel) {
1220 case FitProportional:
1221 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1222 double x0, x1;
1224 p = &state.pagedims[pindex];
1225 fz_rotate (&rm, p->rotate + state.rotate);
1226 box = p->mediabox;
1227 fz_transform_rect (&box, &rm);
1229 x0 = MIN (box.x0, box.x1);
1230 x1 = MAX (box.x0, box.x1);
1232 w = x1 - x0;
1233 maxw = MAX (w, maxw);
1234 zoom = state.w / maxw;
1236 break;
1238 case FitPage:
1239 maxw = state.w;
1240 break;
1242 case FitWidth:
1243 break;
1245 default:
1246 ARSERT (0 && state.fitmodel);
1249 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1250 fz_rect rect;
1251 fz_matrix tm, sm;
1253 p = &state.pagedims[pindex];
1254 fz_rotate (&ctm, state.rotate);
1255 fz_rotate (&rm, p->rotate + state.rotate);
1256 box = p->mediabox;
1257 fz_transform_rect (&box, &rm);
1258 w = box.x1 - box.x0;
1259 switch (state.fitmodel) {
1260 case FitProportional:
1261 p->left = ((maxw - w) * zoom) / 2.0;
1262 break;
1263 case FitPage:
1265 double zh, h;
1266 zw = maxw / w;
1267 h = box.y1 - box.y0;
1268 zh = state.h / h;
1269 zoom = MIN (zw, zh);
1270 p->left = (maxw - (w * zoom)) / 2.0;
1272 break;
1273 case FitWidth:
1274 p->left = 0;
1275 zoom = state.w / w;
1276 break;
1279 fz_scale (&p->zoomctm, zoom, zoom);
1280 fz_concat (&ctm, &p->zoomctm, &ctm);
1282 fz_rotate (&rm, p->rotate);
1283 p->pagebox = p->mediabox;
1284 fz_transform_rect (&p->pagebox, &rm);
1285 p->pagebox.x1 -= p->pagebox.x0;
1286 p->pagebox.y1 -= p->pagebox.y0;
1287 p->pagebox.x0 = 0;
1288 p->pagebox.y0 = 0;
1289 rect = p->pagebox;
1290 fz_transform_rect (&rect, &ctm);
1291 fz_round_rect (&p->bounds, &rect);
1292 p->ctm = ctm;
1294 fz_translate (&tm, 0, -p->mediabox.y1);
1295 fz_scale (&sm, zoom, -zoom);
1296 fz_concat (&ctm, &tm, &sm);
1297 fz_concat (&p->lctm, &ctm, &rm);
1299 p->tctmready = 0;
1302 do {
1303 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1304 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1305 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1306 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1307 int w = x1 - x0;
1308 int h = y1 - y0;
1310 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1311 } while (p-- != state.pagedims);
1314 static
1315 struct anchor { int n; int x; int y; int w; int h; }
1316 desttoanchor (fz_link_dest *dest)
1318 int i;
1319 struct anchor a;
1320 struct pagedim *pdim = state.pagedims;
1322 a.n = -1;
1323 a.x = 0;
1324 a.y = 0;
1325 for (i = 0; i < state.pagedimcount; ++i) {
1326 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1327 break;
1328 pdim = &state.pagedims[i];
1330 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1331 fz_point p;
1332 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1333 p.x = dest->ld.gotor.lt.x;
1334 else
1335 p.x = 0.0;
1336 p.y = dest->ld.gotor.lt.y;
1337 fz_transform_point (&p, &pdim->lctm);
1338 a.y = p.y;
1339 a.x = p.x;
1341 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1342 double x0, x1, y0, y1;
1344 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1345 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1346 a.w = x1 - x0;
1347 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1348 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1349 a.h = y1 - y0;
1350 a.n = dest->ld.gotor.page;
1352 return a;
1355 static void recurse_outline (fz_outline *outline, int level)
1357 while (outline) {
1358 switch (outline->dest.kind) {
1359 case FZ_LINK_GOTO:
1361 struct anchor a = desttoanchor (&outline->dest);
1363 if (a.n >= 0) {
1364 printd ("o %d %d %d %d %s",
1365 level, a.n, a.y, a.h, outline->title);
1368 break;
1370 case FZ_LINK_URI:
1371 printd ("ou %d %" FMT_s " %s %s", level,
1372 strlen (outline->title), outline->title,
1373 outline->dest.ld.uri.uri);
1374 break;
1376 case FZ_LINK_NONE:
1377 printd ("on %d %s", level, outline->title);
1378 break;
1380 default:
1381 printd ("emsg Unhandled outline kind %d for %s\n",
1382 outline->dest.kind, outline->title);
1383 break;
1385 if (outline->down) {
1386 recurse_outline (outline->down, level + 1);
1388 outline = outline->next;
1392 static void process_outline (void)
1394 fz_outline *outline;
1396 if (!state.needoutline) return;
1398 state.needoutline = 0;
1399 switch (state.type) {
1400 case DPDF:
1401 outline = pdf_load_outline (state.u.pdf);
1402 break;
1403 case DXPS:
1404 outline = xps_load_outline (state.u.xps);
1405 break;
1406 default:
1407 outline = NULL;
1408 break;
1410 if (outline) {
1411 recurse_outline (outline, 0);
1412 fz_free_outline (state.ctx, outline);
1416 static char *strofspan (fz_text_span *span)
1418 char *p;
1419 char utf8[10];
1420 fz_text_char *ch;
1421 size_t size = 0, cap = 80;
1423 p = malloc (cap + 1);
1424 if (!p) return NULL;
1426 for (ch = span->text; ch < span->text + span->len; ++ch) {
1427 int n = fz_runetochar (utf8, ch->c);
1428 if (size + n > cap) {
1429 cap *= 2;
1430 p = realloc (p, cap + 1);
1431 if (!p) return NULL;
1434 memcpy (p + size, utf8, n);
1435 size += n;
1437 p[size] = 0;
1438 return p;
1441 static int matchspan (regex_t *re, fz_text_page *page,
1442 fz_text_span *span, fz_matrix ctm,
1443 int stop, int pageno, double start)
1445 int ret;
1446 char *p;
1447 regmatch_t rm;
1448 int a, b, c;
1449 fz_rect sb, eb;
1450 fz_point p1, p2, p3, p4;
1452 p = strofspan (span);
1453 if (!p) return -1;
1455 ret = regexec (re, p, 1, &rm, 0);
1456 if (ret) {
1457 free (p);
1458 if (ret != REG_NOMATCH) {
1459 size_t size;
1460 char errbuf[80];
1461 size = regerror (ret, re, errbuf, sizeof (errbuf));
1462 printd ("msg regexec error `%.*s'",
1463 (int) size, errbuf);
1464 return -1;
1466 return 0;
1468 else {
1469 int l = span->len;
1471 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1472 c += fz_runelen (span->text[a].c);
1474 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1475 c += fz_runelen (span->text[b].c);
1478 if (fz_runelen (span->text[b].c) > 1) {
1479 b = MAX (0, b-1);
1482 fz_text_char_bbox (&sb, span, a);
1483 fz_text_char_bbox (&eb, span, b);
1485 p1.x = sb.x0;
1486 p1.y = sb.y0;
1487 p2.x = eb.x1;
1488 p2.y = sb.y0;
1489 p3.x = eb.x1;
1490 p3.y = eb.y1;
1491 p4.x = sb.x0;
1492 p4.y = eb.y1;
1494 if (!stop) {
1495 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1496 pageno, 1,
1497 p1.x, p1.y,
1498 p2.x, p2.y,
1499 p3.x, p3.y,
1500 p4.x, p4.y);
1502 printd ("progress 1 found at %d `%.*s' in %f sec",
1503 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1504 now () - start);
1506 else {
1507 printd ("match %d %d %f %f %f %f %f %f %f %f",
1508 pageno, 2,
1509 p1.x, p1.y,
1510 p2.x, p2.y,
1511 p3.x, p3.y,
1512 p4.x, p4.y);
1514 free (p);
1515 return 1;
1519 static int compareblocks (const void *l, const void *r)
1521 fz_text_block const *ls = l;
1522 fz_text_block const* rs = r;
1523 return ls->bbox.y0 - rs->bbox.y0;
1526 /* wishful thinking function */
1527 static void search (regex_t *re, int pageno, int y, int forward)
1529 int i, j;
1530 fz_matrix ctm;
1531 fz_device *tdev;
1532 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1533 fz_text_page *text;
1534 fz_text_sheet *sheet;
1535 struct pagedim *pdim, *pdimprev;
1536 int stop = 0, niters = 0;
1537 double start, end;
1539 if (!(state.type == DPDF || state.type == DXPS))
1540 return;
1542 start = now ();
1543 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1544 if (niters++ == 5) {
1545 niters = 0;
1546 if (hasdata ()) {
1547 printd ("progress 1 attention requested aborting search at %d",
1548 pageno);
1549 stop = 1;
1551 else {
1552 printd ("progress %f searching in page %d",
1553 (double) (pageno + 1) / state.pagecount,
1554 pageno);
1557 pdimprev = NULL;
1558 for (i = 0; i < state.pagedimcount; ++i) {
1559 pdim = &state.pagedims[i];
1560 if (pdim->pageno == pageno) {
1561 goto found;
1563 if (pdim->pageno > pageno) {
1564 pdim = pdimprev;
1565 goto found;
1567 pdimprev = pdim;
1569 pdim = pdimprev;
1570 found:
1572 sheet = fz_new_text_sheet (state.ctx);
1573 text = fz_new_text_page (state.ctx);
1574 tdev = fz_new_text_device (state.ctx, sheet, text);
1576 switch (state.type) {
1577 case DPDF:
1578 u.ptr = NULL;
1579 fz_try (state.ctx) {
1580 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1581 trimctm (u.pdfpage, pdim - state.pagedims);
1582 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1583 fz_begin_page (tdev, &fz_infinite_rect, &ctm);
1584 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1585 fz_end_page (tdev);
1587 fz_catch (state.ctx) {
1588 fz_free_device (tdev);
1589 u.ptr = NULL;
1590 goto nextiter;
1592 break;
1594 case DXPS:
1595 u.xpspage = xps_load_page (state.u.xps, pageno);
1596 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1597 break;
1599 default:
1600 ARSERT (0 && state.type);
1603 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1604 fz_free_device (tdev);
1606 for (j = 0; j < text->len; ++j) {
1607 int k;
1608 fz_page_block *pb;
1609 fz_text_block *block;
1611 pb = &text->blocks[forward ? j : text->len - 1 - j];
1612 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1613 block = pb->u.text;
1615 for (k = 0; k < block->len; ++k) {
1616 fz_text_line *line;
1617 fz_text_span *span;
1619 if (forward) {
1620 line = &block->lines[k];
1621 if (line->bbox.y0 < y + 1) continue;
1623 else {
1624 line = &block->lines[block->len - 1 - k];
1625 if (line->bbox.y0 > y - 1) continue;
1628 for (span = line->first_span; span; span = span->next) {
1629 switch (matchspan (re, text, span, ctm,
1630 stop, pageno, start)) {
1631 case 0: break;
1632 case 1: stop = 1; break;
1633 case -1: stop = 1; goto endloop;
1638 nextiter:
1639 if (forward) {
1640 pageno += 1;
1641 y = 0;
1643 else {
1644 pageno -= 1;
1645 y = INT_MAX;
1647 endloop:
1648 fz_free_text_page (state.ctx, text);
1649 fz_free_text_sheet (state.ctx, sheet);
1650 if (u.ptr) {
1651 state.freepage (u.ptr);
1654 end = now ();
1655 if (!stop) {
1656 printd ("progress 1 no matches %f sec", end - start);
1658 printd ("clearrects");
1661 static void set_tex_params (int colorspace)
1663 union {
1664 unsigned char b;
1665 unsigned int s;
1666 } endianness = {1};
1668 switch (colorspace) {
1669 case 0:
1670 state.texiform = GL_RGBA8;
1671 state.texform = GL_RGBA;
1672 state.texty = GL_UNSIGNED_BYTE;
1673 state.colorspace = fz_device_rgb (state.ctx);
1674 break;
1675 case 1:
1676 state.texiform = GL_RGBA8;
1677 state.texform = GL_BGRA;
1678 state.texty = endianness.s > 1
1679 ? GL_UNSIGNED_INT_8_8_8_8
1680 : GL_UNSIGNED_INT_8_8_8_8_REV;
1681 state.colorspace = fz_device_bgr (state.ctx);
1682 break;
1683 case 2:
1684 state.texiform = GL_LUMINANCE_ALPHA;
1685 state.texform = GL_LUMINANCE_ALPHA;
1686 state.texty = GL_UNSIGNED_BYTE;
1687 state.colorspace = fz_device_gray (state.ctx);
1688 break;
1689 default:
1690 errx (1, "invalid colorspce %d", colorspace);
1694 static void realloctexts (int texcount)
1696 size_t size;
1698 if (texcount == state.texcount) return;
1700 if (texcount < state.texcount) {
1701 glDeleteTextures (state.texcount - texcount,
1702 state.texids + texcount);
1705 size = texcount * sizeof (*state.texids);
1706 state.texids = realloc (state.texids, size);
1707 if (!state.texids) {
1708 err (1, "realloc texids %" FMT_s, size);
1711 size = texcount * sizeof (*state.texowners);
1712 state.texowners = realloc (state.texowners, size);
1713 if (!state.texowners) {
1714 err (1, "realloc texowners %" FMT_s, size);
1716 if (texcount > state.texcount) {
1717 int i;
1719 glGenTextures (texcount - state.texcount,
1720 state.texids + state.texcount);
1721 for (i = state.texcount; i < texcount; ++i) {
1722 state.texowners[i].w = -1;
1723 state.texowners[i].slice = NULL;
1726 state.texcount = texcount;
1727 state.texindex = 0;
1730 static char *mbtoutf8 (char *s)
1732 char *p, *r;
1733 wchar_t *tmp;
1734 size_t i, ret, len;
1736 len = mbstowcs (NULL, s, strlen (s));
1737 if (len == 0) {
1738 return s;
1740 else {
1741 if (len == (size_t) -1) {
1742 return s;
1746 tmp = malloc (len * sizeof (wchar_t));
1747 if (!tmp) {
1748 return s;
1751 ret = mbstowcs (tmp, s, len);
1752 if (ret == (size_t) -1) {
1753 free (tmp);
1754 return s;
1757 len = 0;
1758 for (i = 0; i < ret; ++i) {
1759 len += fz_runelen (tmp[i]);
1762 p = r = malloc (len + 1);
1763 if (!r) {
1764 free (tmp);
1765 return s;
1768 for (i = 0; i < ret; ++i) {
1769 p += fz_runetochar (p, tmp[i]);
1771 *p = 0;
1772 free (tmp);
1773 return r;
1776 CAMLprim value ml_mbtoutf8 (value s_v)
1778 CAMLparam1 (s_v);
1779 CAMLlocal1 (ret_v);
1780 char *s, *r;
1782 s = String_val (s_v);
1783 r = mbtoutf8 (s);
1784 if (r == s) {
1785 ret_v = s_v;
1787 else {
1788 ret_v = caml_copy_string (r);
1789 free (r);
1791 CAMLreturn (ret_v);
1794 static void * mainloop (void *unused)
1796 char *p = NULL;
1797 int len, ret, oldlen = 0;
1799 for (;;) {
1800 len = readlen ();
1801 if (len == 0) {
1802 errx (1, "readlen returned 0");
1805 if (oldlen < len + 1) {
1806 p = realloc (p, len + 1);
1807 if (!p) {
1808 err (1, "realloc %d failed", len + 1);
1810 oldlen = len + 1;
1812 readdata (p, len);
1813 p[len] = 0;
1815 if (!strncmp ("open", p, 4)) {
1816 int wthack, off;
1817 char *password;
1818 char *filename;
1819 char *utf8filename;
1820 size_t filenamelen;
1822 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1823 if (ret != 2) {
1824 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1827 filename = p + 5 + off;
1828 filenamelen = strlen (filename);
1829 password = filename + filenamelen + 1;
1831 lock ("open");
1832 openxref (filename, password);
1833 pdfinfo ();
1834 initpdims ();
1835 unlock ("open");
1837 if (!wthack) {
1838 utf8filename = mbtoutf8 (filename);
1839 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1840 if (utf8filename != filename) {
1841 free (utf8filename);
1844 state.needoutline = 1;
1846 else if (!strncmp ("cs", p, 2)) {
1847 int i, colorspace;
1849 ret = sscanf (p + 2, " %d", &colorspace);
1850 if (ret != 1) {
1851 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1853 lock ("cs");
1854 set_tex_params (colorspace);
1855 for (i = 0; i < state.texcount; ++i) {
1856 state.texowners[i].w = -1;
1857 state.texowners[i].slice = NULL;
1859 unlock ("cs");
1861 else if (!strncmp ("freepage", p, 8)) {
1862 void *ptr;
1864 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1865 if (ret != 1) {
1866 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1868 freepage (ptr);
1870 else if (!strncmp ("freetile", p, 8)) {
1871 void *ptr;
1873 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1874 if (ret != 1) {
1875 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1877 freetile (ptr);
1879 else if (!strncmp ("search", p, 6)) {
1880 int icase, pageno, y, ret, len2, forward;
1881 char *pattern;
1882 regex_t re;
1884 ret = sscanf (p + 6, " %d %d %d %d,%n",
1885 &icase, &pageno, &y, &forward, &len2);
1886 if (ret != 4) {
1887 errx (1, "malformed search `%s' ret=%d", p, ret);
1890 pattern = p + 6 + len2;
1891 ret = regcomp (&re, pattern,
1892 REG_EXTENDED | (icase ? REG_ICASE : 0));
1893 if (ret) {
1894 char errbuf[80];
1895 size_t size;
1897 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1898 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1900 else {
1901 search (&re, pageno, y, forward);
1902 regfree (&re);
1905 else if (!strncmp ("geometry", p, 8)) {
1906 int w, h, fitmodel;
1908 printd ("clear");
1909 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1910 if (ret != 3) {
1911 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1914 lock ("geometry");
1915 state.h = h;
1916 if (w != state.w) {
1917 int i;
1918 state.w = w;
1919 for (i = 0; i < state.texcount; ++i) {
1920 state.texowners[i].slice = NULL;
1923 state.fitmodel = fitmodel;
1924 layout ();
1925 process_outline ();
1927 state.gen++;
1928 unlock ("geometry");
1929 printd ("continue %d", state.pagecount);
1931 else if (!strncmp ("reqlayout", p, 9)) {
1932 char *nameddest;
1933 int rotate, fitmodel, off, h;
1935 printd ("clear");
1936 ret = sscanf (p + 9, " %d %d %d %n",
1937 &rotate, &fitmodel, &h, &off);
1938 if (ret != 3) {
1939 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1941 lock ("reqlayout");
1942 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1943 state.gen += 1;
1945 state.rotate = rotate;
1946 state.fitmodel = fitmodel;
1947 state.h = h;
1948 layout ();
1949 process_outline ();
1951 nameddest = p + 9 + off;
1952 if (state.type == DPDF && nameddest && *nameddest) {
1953 struct anchor a;
1954 fz_link_dest dest;
1955 pdf_obj *needle, *obj;
1957 needle = pdf_new_string (state.u.pdf, nameddest,
1958 strlen (nameddest));
1959 obj = pdf_lookup_dest (state.u.pdf, needle);
1960 if (obj) {
1961 dest = pdf_parse_link_dest (state.u.pdf, FZ_LINK_GOTO, obj);
1963 a = desttoanchor (&dest);
1964 if (a.n >= 0) {
1965 printd ("a %d %d %d", a.n, a.x, a.y);
1967 else {
1968 printd ("emsg failed to parse destination `%s'\n",
1969 nameddest);
1972 else {
1973 printd ("emsg destination `%s' not found\n",
1974 nameddest);
1976 pdf_drop_obj (needle);
1979 state.gen++;
1980 unlock ("reqlayout");
1981 printd ("continue %d", state.pagecount);
1983 else if (!strncmp ("page", p, 4)) {
1984 double a, b;
1985 struct page *page;
1986 int pageno, pindex, ret;
1988 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1989 if (ret != 2) {
1990 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1993 lock ("page");
1994 a = now ();
1995 page = loadpage (pageno, pindex);
1996 b = now ();
1997 unlock ("page");
1999 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
2001 else if (!strncmp ("tile", p, 4)) {
2002 int x, y, w, h, ret;
2003 struct page *page;
2004 struct tile *tile;
2005 double a, b;
2006 void *data;
2008 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
2009 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
2010 if (ret != 6) {
2011 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
2014 lock ("tile");
2015 a = now ();
2016 tile = rendertile (page, x, y, w, h, data);
2017 b = now ();
2018 unlock ("tile");
2020 printd ("tile %d %d %" FMT_ptr " %u %f",
2021 x, y,
2022 FMT_ptr_cast2 (tile),
2023 tile->w * tile->h * tile->pixmap->n,
2024 b - a);
2026 else if (!strncmp ("settrim", p, 7)) {
2027 fz_irect fuzz;
2028 int trimmargins;
2030 ret = sscanf (p + 7, " %d %d %d %d %d",
2031 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
2032 if (ret != 5) {
2033 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
2035 printd ("clear");
2036 lock ("settrim");
2037 state.trimmargins = trimmargins;
2038 state.needoutline = 1;
2039 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
2040 state.trimanew = 1;
2041 state.trimfuzz = fuzz;
2043 state.pagedimcount = 0;
2044 free (state.pagedims);
2045 state.pagedims = NULL;
2046 initpdims ();
2047 layout ();
2048 process_outline ();
2049 unlock ("settrim");
2050 printd ("continue %d", state.pagecount);
2052 else if (!strncmp ("sliceh", p, 6)) {
2053 int h;
2055 ret = sscanf (p + 6, " %d", &h);
2056 if (ret != 1) {
2057 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
2059 if (h != state.sliceheight) {
2060 int i;
2062 state.sliceheight = h;
2063 for (i = 0; i < state.texcount; ++i) {
2064 state.texowners[i].w = -1;
2065 state.texowners[i].h = -1;
2066 state.texowners[i].slice = NULL;
2070 else if (!strncmp ("interrupt", p, 9)) {
2071 printd ("vmsg interrupted");
2073 else {
2074 errx (1, "unknown command %.*s", len, p);
2077 return 0;
2080 CAMLprim value ml_realloctexts (value texcount_v)
2082 CAMLparam1 (texcount_v);
2083 int ok;
2085 if (trylock ("ml_realloctexts")) {
2086 ok = 0;
2087 goto done;
2089 realloctexts (Int_val (texcount_v));
2090 ok = 1;
2091 unlock ("ml_realloctexts");
2093 done:
2094 CAMLreturn (Val_bool (ok));
2097 static void recti (int x0, int y0, int x1, int y1)
2099 GLfloat *v = state.vertices;
2101 glVertexPointer (2, GL_FLOAT, 0, v);
2102 v[0] = x0; v[1] = y0;
2103 v[2] = x1; v[3] = y0;
2104 v[4] = x0; v[5] = y1;
2105 v[6] = x1; v[7] = y1;
2106 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2109 static void showsel (struct page *page, int ox, int oy)
2111 int seen = 0;
2112 fz_irect bbox;
2113 fz_rect rect;
2114 fz_text_line *line;
2115 fz_page_block *pageb;
2116 fz_text_block *block;
2117 struct mark first, last;
2119 first = page->fmark;
2120 last = page->lmark;
2122 if (!first.span || !last.span) return;
2124 glEnable (GL_BLEND);
2125 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2126 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
2128 ox += state.pagedims[page->pdimno].bounds.x0;
2129 oy += state.pagedims[page->pdimno].bounds.y0;
2130 for (pageb = page->text->blocks;
2131 pageb < page->text->blocks + page->text->len;
2132 ++pageb) {
2133 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2134 block = pageb->u.text;
2136 for (line = block->lines;
2137 line < block->lines + block->len;
2138 ++line) {
2139 fz_text_span *span;
2140 rect = fz_empty_rect;
2142 for (span = line->first_span; span; span = span->next) {
2143 int i, j, k;
2144 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2146 j = 0;
2147 k = span->len - 1;
2149 if (span == page->fmark.span && span == page->lmark.span) {
2150 seen = 1;
2151 j = MIN (first.i, last.i);
2152 k = MAX (first.i, last.i);
2154 else {
2155 if (span == first.span) {
2156 seen = 1;
2157 j = first.i;
2159 else if (span == last.span) {
2160 seen = 1;
2161 k = last.i;
2165 if (seen) {
2166 for (i = j; i <= k; ++i) {
2167 fz_rect bbox;
2168 fz_union_rect (&rect,
2169 fz_text_char_bbox (&bbox, span, i));
2171 fz_round_rect (&bbox, &rect);
2172 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2173 bbox.x0,
2174 bbox.y0,
2175 bbox.x1,
2176 bbox.y1,
2177 oy, ox);
2179 recti (bbox.x0 + ox, bbox.y0 + oy,
2180 bbox.x1 + ox, bbox.y1 + oy);
2181 if (span == last.span) {
2182 goto done;
2184 rect = fz_empty_rect;
2189 done:
2190 glDisable (GL_BLEND);
2193 #include "glfont.c"
2195 static void highlightlinks (struct page *page, int xoff, int yoff)
2197 fz_matrix ctm, tm, pm;
2198 fz_link *link, *links;
2199 GLfloat *texcoords = state.texcoords;
2200 GLfloat *vertices = state.vertices;
2202 switch (page->type) {
2203 case DPDF:
2204 links = page->u.pdfpage->links;
2205 break;
2207 case DXPS:
2208 links = page->u.xpspage->links;
2209 break;
2211 default:
2212 return;
2215 glEnable (GL_TEXTURE_1D);
2216 glEnable (GL_BLEND);
2217 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2218 glBindTexture (GL_TEXTURE_1D, state.stid);
2220 xoff -= state.pagedims[page->pdimno].bounds.x0;
2221 yoff -= state.pagedims[page->pdimno].bounds.y0;
2222 fz_translate (&tm, xoff, yoff);
2223 pm = pagectm (page);
2224 fz_concat (&ctm, &pm, &tm);
2226 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2227 glVertexPointer (2, GL_FLOAT, 0, vertices);
2229 for (link = links; link; link = link->next) {
2230 fz_point p1, p2, p3, p4;
2232 p1.x = link->rect.x0;
2233 p1.y = link->rect.y0;
2235 p2.x = link->rect.x1;
2236 p2.y = link->rect.y0;
2238 p3.x = link->rect.x1;
2239 p3.y = link->rect.y1;
2241 p4.x = link->rect.x0;
2242 p4.y = link->rect.y1;
2244 fz_transform_point (&p1, &ctm);
2245 fz_transform_point (&p2, &ctm);
2246 fz_transform_point (&p3, &ctm);
2247 fz_transform_point (&p4, &ctm);
2249 switch (link->dest.kind) {
2250 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2251 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2252 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2253 default: glColor3ub (0, 0, 0); break;
2257 float w, h, s, t;
2259 w = p2.x - p1.x;
2260 h = p2.y - p1.y;
2261 t = sqrtf (w*w + h*h) * .25f;
2263 w = p3.x - p2.x;
2264 h = p3.y - p2.y;
2265 s = sqrtf (w*w + h*h) * .25f;
2267 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
2268 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
2270 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
2271 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
2273 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
2274 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
2276 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
2277 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
2279 glDrawArrays (GL_LINES, 0, 8);
2282 glDisable (GL_BLEND);
2283 glDisable (GL_TEXTURE_1D);
2286 static int compareslinks (const void *l, const void *r)
2288 struct slink const *ls = l;
2289 struct slink const *rs = r;
2290 if (ls->bbox.y0 == rs->bbox.y0) {
2291 return rs->bbox.x0 - rs->bbox.x0;
2293 return ls->bbox.y0 - rs->bbox.y0;
2296 static void droptext (struct page *page)
2298 if (page->text) {
2299 fz_free_text_page (state.ctx, page->text);
2300 page->fmark.i = -1;
2301 page->lmark.i = -1;
2302 page->fmark.span = NULL;
2303 page->lmark.span = NULL;
2304 page->text = NULL;
2306 if (page->sheet) {
2307 fz_free_text_sheet (state.ctx, page->sheet);
2308 page->sheet = NULL;
2312 static void dropslinks (struct page *page)
2314 if (page->slinks) {
2315 free (page->slinks);
2316 page->slinks = NULL;
2317 page->slinkcount = 0;
2321 static void ensureslinks (struct page *page)
2323 fz_matrix ctm;
2324 int i, count = 0;
2325 size_t slinksize = sizeof (*page->slinks);
2326 fz_link *link, *links;
2328 if (state.gen != page->sgen) {
2329 dropslinks (page);
2330 page->sgen = state.gen;
2332 if (page->slinks) return;
2334 switch (page->type) {
2335 case DPDF:
2336 links = page->u.pdfpage->links;
2337 trimctm (page->u.pdfpage, page->pdimno);
2338 fz_concat (&ctm,
2339 &state.pagedims[page->pdimno].tctm,
2340 &state.pagedims[page->pdimno].ctm);
2341 break;
2343 case DXPS:
2344 links = page->u.xpspage->links;
2345 ctm = state.pagedims[page->pdimno].ctm;
2346 break;
2348 default:
2349 return;
2352 for (link = links; link; link = link->next) {
2353 count++;
2355 if (count > 0) {
2356 page->slinkcount = count;
2357 page->slinks = calloc (count, slinksize);
2358 if (!page->slinks) {
2359 err (1, "realloc slinks %d", count);
2362 for (i = 0, link = links; link; ++i, link = link->next) {
2363 fz_rect rect;
2365 rect = link->rect;
2366 fz_transform_rect (&rect, &ctm);
2367 page->slinks[i].link = link;
2368 fz_round_rect (&page->slinks[i].bbox, &rect);
2370 qsort (page->slinks, count, slinksize, compareslinks);
2374 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2375 static void fmt_linkn (char *s, unsigned int u)
2377 unsigned int len; unsigned int q;
2378 int zma = 'z' - 'a' + 1;
2379 len = 1; q = u;
2380 while (q > zma - 1) { ++len; q /= zma; }
2381 if (s) {
2382 s += len;
2383 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2384 /* handles u == 0 */
2386 s[len] = 0;
2389 static void highlightslinks (struct page *page, int xoff, int yoff,
2390 int noff, char *targ, int tlen, int hfsize)
2392 int i;
2393 char buf[40];
2394 struct slink *slink;
2395 double x0, y0, x1, y1, w;
2397 ensureslinks (page);
2398 glColor3ub (0xc3, 0xb0, 0x91);
2399 for (i = 0; i < page->slinkcount; ++i) {
2400 fmt_linkn (buf, i + noff);
2401 if (!tlen || !strncmp (targ, buf, tlen)) {
2402 slink = &page->slinks[i];
2404 x0 = slink->bbox.x0 + xoff - 5;
2405 y1 = slink->bbox.y0 + yoff - 5;
2406 y0 = y1 + 10 + hfsize;
2407 w = measure_string (state.face, hfsize, buf);
2408 x1 = x0 + w + 10;
2409 recti (x0, y0, x1, y1);
2413 glEnable (GL_BLEND);
2414 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2415 glEnable (GL_TEXTURE_2D);
2416 glColor3ub (0, 0, 0);
2417 for (i = 0; i < page->slinkcount; ++i) {
2418 fmt_linkn (buf, i + noff);
2419 if (!tlen || !strncmp (targ, buf, tlen)) {
2420 slink = &page->slinks[i];
2422 x0 = slink->bbox.x0 + xoff;
2423 y0 = slink->bbox.y0 + yoff + hfsize;
2424 draw_string (state.face, hfsize, x0, y0, buf);
2427 glDisable (GL_TEXTURE_2D);
2428 glDisable (GL_BLEND);
2432 static void uploadslice (struct tile *tile, struct slice *slice)
2434 int offset;
2435 struct slice *slice1;
2436 unsigned char *texdata;
2438 offset = 0;
2439 for (slice1 = tile->slices; slice != slice1; slice1++) {
2440 offset += slice1->h * tile->w * tile->pixmap->n;
2442 if (slice->texindex != -1 && slice->texindex < state.texcount
2443 && state.texowners[slice->texindex].slice == slice) {
2444 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2446 else {
2447 int subimage = 0;
2448 int texindex = state.texindex++ % state.texcount;
2450 if (state.texowners[texindex].w == tile->w) {
2451 if (state.texowners[texindex].h >= slice->h) {
2452 subimage = 1;
2454 else {
2455 state.texowners[texindex].h = slice->h;
2458 else {
2459 state.texowners[texindex].h = slice->h;
2462 state.texowners[texindex].w = tile->w;
2463 state.texowners[texindex].slice = slice;
2464 slice->texindex = texindex;
2466 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2467 if (tile->pbo) {
2468 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2469 texdata = 0;
2471 else {
2472 texdata = tile->pixmap->samples;
2474 if (subimage) {
2475 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2479 tile->w,
2480 slice->h,
2481 state.texform,
2482 state.texty,
2483 texdata+offset
2486 else {
2487 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2489 state.texiform,
2490 tile->w,
2491 slice->h,
2493 state.texform,
2494 state.texty,
2495 texdata+offset
2498 if (tile->pbo) {
2499 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2504 CAMLprim value ml_begintiles (value unit_v)
2506 CAMLparam1 (unit_v);
2507 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2508 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2509 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2510 CAMLreturn (unit_v);
2513 CAMLprim value ml_endtiles (value unit_v)
2515 CAMLparam1 (unit_v);
2516 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2517 CAMLreturn (unit_v);
2520 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2522 CAMLparam2 (args_v, ptr_v);
2523 int dispx = Int_val (Field (args_v, 0));
2524 int dispy = Int_val (Field (args_v, 1));
2525 int dispw = Int_val (Field (args_v, 2));
2526 int disph = Int_val (Field (args_v, 3));
2527 int tilex = Int_val (Field (args_v, 4));
2528 int tiley = Int_val (Field (args_v, 5));
2529 char *s = String_val (ptr_v);
2530 struct tile *tile = parse_pointer ("ml_drawtile", s);
2531 int slicey, firstslice;
2532 struct slice *slice;
2533 GLfloat *texcoords = state.texcoords;
2534 GLfloat *vertices = state.vertices;
2536 firstslice = tiley / tile->sliceheight;
2537 slice = &tile->slices[firstslice];
2538 slicey = tiley % tile->sliceheight;
2540 while (disph > 0) {
2541 int dh;
2543 dh = slice->h - slicey;
2544 dh = MIN (disph, dh);
2545 uploadslice (tile, slice);
2547 texcoords[0] = tilex; texcoords[1] = slicey;
2548 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2549 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2550 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2552 vertices[0] = dispx; vertices[1] = dispy;
2553 vertices[2] = dispx+dispw; vertices[3] = dispy;
2554 vertices[4] = dispx; vertices[5] = dispy+dh;
2555 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2557 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2558 dispy += dh;
2559 disph -= dh;
2560 slice++;
2561 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2562 slicey = 0;
2564 CAMLreturn (Val_unit);
2567 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2568 value xoff_v, value yoff_v,
2569 value li_v)
2571 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2572 int xoff = Int_val (xoff_v);
2573 int yoff = Int_val (yoff_v);
2574 int noff = Int_val (Field (li_v, 0));
2575 char *targ = String_val (Field (li_v, 1));
2576 int tlen = caml_string_length (Field (li_v, 1));
2577 int hfsize = Int_val (Field (li_v, 2));
2578 char *s = String_val (ptr_v);
2579 int hlmask = Int_val (hlinks_v);
2580 struct page *page = parse_pointer ("ml_postprocess", s);
2582 if (!page->u.ptr) {
2583 /* deal with loadpage failed pages */
2584 goto done;
2587 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2588 if (trylock ("ml_postprocess")) {
2589 noff = 0;
2590 goto done;
2592 if (hlmask & 2) {
2593 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2594 noff = page->slinkcount;
2596 if (page->tgen == state.gen) {
2597 showsel (page, xoff, yoff);
2599 unlock ("ml_postprocess");
2601 done:
2602 CAMLreturn (Val_int (noff));
2605 static fz_link *getlink (struct page *page, int x, int y)
2607 fz_point p;
2608 fz_matrix ctm;
2609 const fz_matrix *tctm;
2610 fz_link *link, *links;
2612 switch (page->type) {
2613 case DPDF:
2614 trimctm (page->u.pdfpage, page->pdimno);
2615 tctm = &state.pagedims[page->pdimno].tctm;
2616 links = page->u.pdfpage->links;
2617 break;
2619 case DXPS:
2620 tctm = &fz_identity;
2621 links = page->u.xpspage->links;
2622 break;
2624 default:
2625 return NULL;
2627 p.x = x;
2628 p.y = y;
2630 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2631 fz_invert_matrix (&ctm, &ctm);
2632 fz_transform_point (&p, &ctm);
2634 for (link = links; link; link = link->next) {
2635 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2636 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2637 return link;
2641 return NULL;
2644 static void ensuretext (struct page *page)
2646 if (state.gen != page->tgen) {
2647 droptext (page);
2648 page->tgen = state.gen;
2650 if (!page->text) {
2651 fz_matrix ctm;
2652 fz_device *tdev;
2654 page->text = fz_new_text_page (state.ctx);
2655 page->sheet = fz_new_text_sheet (state.ctx);
2656 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2657 ctm = pagectm (page);
2658 fz_begin_page (tdev, &fz_infinite_rect, &ctm);
2659 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2660 qsort (page->text->blocks, page->text->len,
2661 sizeof (*page->text->blocks), compareblocks);
2662 fz_end_page (tdev);
2663 fz_free_device (tdev);
2667 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2669 CAMLparam2 (start_page_v, dir_v);
2670 CAMLlocal1 (ret_v);
2671 int i, dir = Int_val (dir_v);
2672 int start_page = Int_val (start_page_v);
2673 int end_page = dir > 0 ? state.pagecount : -1;
2675 ret_v = Val_int (0);
2676 if (!(state.type == DPDF || state.type == DXPS)) {
2677 goto done;
2680 lock ("ml_findpage_with_links");
2681 for (i = start_page + dir; i != end_page; i += dir) {
2682 int found;
2684 switch (state.type) {
2685 case DPDF:
2687 pdf_page *page = NULL;
2689 fz_try (state.ctx) {
2690 page = pdf_load_page (state.u.pdf, i);
2691 found = !!page->links;
2693 fz_catch (state.ctx) {
2694 found = 0;
2696 if (page) {
2697 freepdfpage (page);
2700 break;
2701 case DXPS:
2703 xps_page *page = xps_load_page (state.u.xps, i);
2704 found = !!page->links;
2705 freexpspage (page);
2707 break;
2709 default:
2710 ARSERT (0 && "invalid document type");
2713 if (found) {
2714 ret_v = caml_alloc_small (1, 1);
2715 Field (ret_v, 0) = Val_int (i);
2716 goto unlock;
2719 unlock:
2720 unlock ("ml_findpage_with_links");
2722 done:
2723 CAMLreturn (ret_v);
2726 enum { dir_first, dir_last };
2727 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2729 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2731 CAMLparam2 (ptr_v, dir_v);
2732 CAMLlocal2 (ret_v, pos_v);
2733 struct page *page;
2734 int dirtag, i, slinkindex;
2735 struct slink *found = NULL ,*slink;
2736 char *s = String_val (ptr_v);
2738 page = parse_pointer ("ml_findlink", s);
2739 ret_v = Val_int (0);
2740 if (trylock ("ml_findlink")) {
2741 goto done;
2744 ensureslinks (page);
2746 if (Is_block (dir_v)) {
2747 dirtag = Tag_val (dir_v);
2748 switch (dirtag) {
2749 case dir_first_visible:
2751 int x0, y0, dir, first_index, last_index;
2753 pos_v = Field (dir_v, 0);
2754 x0 = Int_val (Field (pos_v, 0));
2755 y0 = Int_val (Field (pos_v, 1));
2756 dir = Int_val (Field (pos_v, 2));
2758 if (dir >= 0) {
2759 dir = 1;
2760 first_index = 0;
2761 last_index = page->slinkcount;
2763 else {
2764 first_index = page->slinkcount - 1;
2765 last_index = -1;
2768 for (i = first_index; i != last_index; i += dir) {
2769 slink = &page->slinks[i];
2770 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2771 found = slink;
2772 break;
2776 break;
2778 case dir_left:
2779 slinkindex = Int_val (Field (dir_v, 0));
2780 found = &page->slinks[slinkindex];
2781 for (i = slinkindex - 1; i >= 0; --i) {
2782 slink = &page->slinks[i];
2783 if (slink->bbox.x0 < found->bbox.x0) {
2784 found = slink;
2785 break;
2788 break;
2790 case dir_right:
2791 slinkindex = Int_val (Field (dir_v, 0));
2792 found = &page->slinks[slinkindex];
2793 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2794 slink = &page->slinks[i];
2795 if (slink->bbox.x0 > found->bbox.x0) {
2796 found = slink;
2797 break;
2800 break;
2802 case dir_down:
2803 slinkindex = Int_val (Field (dir_v, 0));
2804 found = &page->slinks[slinkindex];
2805 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2806 slink = &page->slinks[i];
2807 if (slink->bbox.y0 >= found->bbox.y0) {
2808 found = slink;
2809 break;
2812 break;
2814 case dir_up:
2815 slinkindex = Int_val (Field (dir_v, 0));
2816 found = &page->slinks[slinkindex];
2817 for (i = slinkindex - 1; i >= 0; --i) {
2818 slink = &page->slinks[i];
2819 if (slink->bbox.y0 <= found->bbox.y0) {
2820 found = slink;
2821 break;
2824 break;
2827 else {
2828 dirtag = Int_val (dir_v);
2829 switch (dirtag) {
2830 case dir_first:
2831 found = page->slinks;
2832 break;
2834 case dir_last:
2835 if (page->slinks) {
2836 found = page->slinks + (page->slinkcount - 1);
2838 break;
2841 if (found) {
2842 ret_v = caml_alloc_small (2, 1);
2843 Field (ret_v, 0) = Val_int (found - page->slinks);
2846 unlock ("ml_findlink");
2847 done:
2848 CAMLreturn (ret_v);
2851 enum { uuri, ugoto, utext, uunexpected,
2852 ulaunch, unamed, uremote, uremotedest };
2854 #define LINKTOVAL \
2856 int pageno; \
2858 switch (link->dest.kind) { \
2859 case FZ_LINK_GOTO: \
2861 fz_point p; \
2863 pageno = link->dest.ld.gotor.page; \
2864 p.x = 0; \
2865 p.y = 0; \
2867 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2868 p.y = link->dest.ld.gotor.lt.y; \
2869 fz_transform_point (&p, &pdim->lctm); \
2871 tup_v = caml_alloc_tuple (2); \
2872 ret_v = caml_alloc_small (1, ugoto); \
2873 Field (tup_v, 0) = Val_int (pageno); \
2874 Field (tup_v, 1) = Val_int (p.y); \
2875 Field (ret_v, 0) = tup_v; \
2877 break; \
2879 case FZ_LINK_URI: \
2880 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2881 ret_v = caml_alloc_small (1, uuri); \
2882 Field (ret_v, 0) = str_v; \
2883 break; \
2885 case FZ_LINK_LAUNCH: \
2886 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2887 ret_v = caml_alloc_small (1, ulaunch); \
2888 Field (ret_v, 0) = str_v; \
2889 break; \
2891 case FZ_LINK_NAMED: \
2892 str_v = caml_copy_string (link->dest.ld.named.named); \
2893 ret_v = caml_alloc_small (1, unamed); \
2894 Field (ret_v, 0) = str_v; \
2895 break; \
2897 case FZ_LINK_GOTOR: \
2899 int rty; \
2901 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2902 pageno = link->dest.ld.gotor.page; \
2903 if (pageno == -1) { \
2904 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2905 rty = uremotedest; \
2907 else { \
2908 gr_v = Val_int (pageno); \
2909 rty = uremote; \
2911 tup_v = caml_alloc_tuple (2); \
2912 ret_v = caml_alloc_small (1, rty); \
2913 Field (tup_v, 0) = str_v; \
2914 Field (tup_v, 1) = gr_v; \
2915 Field (ret_v, 0) = tup_v; \
2917 break; \
2919 default: \
2921 char buf[80]; \
2923 snprintf (buf, sizeof (buf), \
2924 "unhandled link kind %d", link->dest.kind); \
2925 str_v = caml_copy_string (buf); \
2926 ret_v = caml_alloc_small (1, uunexpected); \
2927 Field (ret_v, 0) = str_v; \
2929 break; \
2933 CAMLprim value ml_getlink (value ptr_v, value n_v)
2935 CAMLparam2 (ptr_v, n_v);
2936 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2937 fz_link *link;
2938 struct page *page;
2939 struct pagedim *pdim;
2940 char *s = String_val (ptr_v);
2942 ret_v = Val_int (0);
2943 if (trylock ("ml_getlink")) {
2944 goto done;
2947 page = parse_pointer ("ml_getlink", s);
2948 ensureslinks (page);
2949 pdim = &state.pagedims[page->pdimno];
2950 link = page->slinks[Int_val (n_v)].link;
2951 LINKTOVAL;
2953 unlock ("ml_getlink");
2954 done:
2955 CAMLreturn (ret_v);
2958 CAMLprim value ml_getlinkcount (value ptr_v)
2960 CAMLparam1 (ptr_v);
2961 struct page *page;
2962 char *s = String_val (ptr_v);
2964 page = parse_pointer ("ml_getlinkcount", s);
2965 CAMLreturn (Val_int (page->slinkcount));
2968 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2970 CAMLparam2 (ptr_v, n_v);
2971 CAMLlocal1 (ret_v);
2972 struct page *page;
2973 struct slink *slink;
2974 char *s = String_val (ptr_v);
2976 page = parse_pointer ("ml_getlinkrect", s);
2977 ret_v = caml_alloc_tuple (4);
2978 if (trylock ("ml_getlinkrect")) {
2979 Field (ret_v, 0) = Val_int (0);
2980 Field (ret_v, 1) = Val_int (0);
2981 Field (ret_v, 2) = Val_int (0);
2982 Field (ret_v, 3) = Val_int (0);
2983 goto done;
2985 ensureslinks (page);
2987 slink = &page->slinks[Int_val (n_v)];
2988 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2989 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2990 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2991 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2992 unlock ("ml_getlinkrect");
2994 done:
2995 CAMLreturn (ret_v);
2998 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3000 CAMLparam3 (ptr_v, x_v, y_v);
3001 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3002 fz_link *link;
3003 struct page *page;
3004 char *s = String_val (ptr_v);
3005 int x = Int_val (x_v), y = Int_val (y_v);
3006 struct pagedim *pdim;
3008 ret_v = Val_int (0);
3009 if (trylock ("ml_whatsunder")) {
3010 goto done;
3013 page = parse_pointer ("ml_whatsunder", s);
3014 pdim = &state.pagedims[page->pdimno];
3015 x += pdim->bounds.x0;
3016 y += pdim->bounds.y0;
3017 link = getlink (page, x, y);
3018 if (link) {
3019 LINKTOVAL;
3021 else {
3022 fz_rect *b;
3023 fz_page_block *pageb;
3024 fz_text_block *block;
3026 ensuretext (page);
3027 for (pageb = page->text->blocks;
3028 pageb < page->text->blocks + page->text->len;
3029 ++pageb) {
3030 fz_text_line *line;
3031 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3032 block = pageb->u.text;
3034 b = &block->bbox;
3035 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3036 continue;
3038 for (line = block->lines;
3039 line < block->lines + block->len;
3040 ++line) {
3041 fz_text_span *span;
3043 b = &line->bbox;
3044 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3045 continue;
3047 for (span = line->first_span; span; span = span->next) {
3048 int charnum;
3050 b = &span->bbox;
3051 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3052 continue;
3054 for (charnum = 0; charnum < span->len; ++charnum) {
3055 fz_rect bbox;
3056 fz_text_char_bbox (&bbox, span, charnum);
3057 b = &bbox;
3059 if (x >= b->x0 && x <= b->x1
3060 && y >= b->y0 && y <= b->y1) {
3061 fz_text_style *style = span->text->style;
3062 const char *n2 =
3063 style->font && style->font->name
3064 ? style->font->name
3065 : "Span has no font name"
3067 FT_FaceRec *face = style->font->ft_face;
3068 if (face && face->family_name) {
3069 char *s;
3070 char *n1 = face->family_name;
3071 size_t l1 = strlen (n1);
3072 size_t l2 = strlen (n2);
3074 if (l1 != l2 || memcmp (n1, n2, l1)) {
3075 s = malloc (l1 + l2 + 2);
3076 if (s) {
3077 memcpy (s, n2, l2);
3078 s[l2] = '=';
3079 memcpy (s + l2 + 1, n1, l1 + 1);
3080 str_v = caml_copy_string (s);
3081 free (s);
3085 if (str_v == 0) {
3086 str_v = caml_copy_string (n2);
3088 ret_v = caml_alloc_small (1, utext);
3089 Field (ret_v, 0) = str_v;
3090 goto unlock;
3097 unlock:
3098 unlock ("ml_whatsunder");
3100 done:
3101 CAMLreturn (ret_v);
3104 enum { mark_page, mark_block, mark_line, mark_word };
3106 static int uninteresting (int c)
3108 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3109 || ispunct (c);
3112 CAMLprim value ml_clearmark (value ptr_v)
3114 CAMLparam1 (ptr_v);
3115 char *s = String_val (ptr_v);
3116 struct page *page;
3118 if (trylock ("ml_clearmark")) {
3119 goto done;
3122 page = parse_pointer ("ml_clearmark", s);
3123 page->fmark.span = NULL;
3124 page->lmark.span = NULL;
3125 page->fmark.i = 0;
3126 page->lmark.i = 0;
3128 unlock ("ml_clearmark");
3129 done:
3130 CAMLreturn (Val_unit);
3133 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3135 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3136 CAMLlocal1 (ret_v);
3137 fz_rect *b;
3138 struct page *page;
3139 fz_text_line *line;
3140 fz_page_block *pageb;
3141 fz_text_block *block;
3142 struct pagedim *pdim;
3143 int mark = Int_val (mark_v);
3144 char *s = String_val (ptr_v);
3145 int x = Int_val (x_v), y = Int_val (y_v);
3147 ret_v = Val_bool (0);
3148 if (trylock ("ml_markunder")) {
3149 goto done;
3152 page = parse_pointer ("ml_markunder", s);
3153 pdim = &state.pagedims[page->pdimno];
3155 ensuretext (page);
3157 if (mark == mark_page) {
3158 int i;
3159 fz_page_block *pb1 = NULL, *pb2 = NULL;
3161 for (i = 0; i < page->text->len; ++i) {
3162 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3163 pb1 = &page->text->blocks[i];
3164 break;
3167 if (!pb1) goto unlock;
3169 for (i = page->text->len - 1; i >= 0; --i) {
3170 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3171 pb2 = &page->text->blocks[i];
3172 break;
3175 if (!pb2) goto unlock;
3177 block = pb1->u.text;
3179 page->fmark.i = 0;
3180 page->fmark.span = block->lines->first_span;
3182 block = pb2->u.text;
3183 line = &block->lines[block->len - 1];
3184 page->lmark.i = line->last_span->len - 1;
3185 page->lmark.span = line->last_span;
3186 ret_v = Val_bool (1);
3187 goto unlock;
3190 x += pdim->bounds.x0;
3191 y += pdim->bounds.y0;
3193 for (pageb = page->text->blocks;
3194 pageb < page->text->blocks + page->text->len;
3195 ++pageb) {
3196 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3197 block = pageb->u.text;
3199 b = &block->bbox;
3200 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3201 continue;
3203 if (mark == mark_block) {
3204 page->fmark.i = 0;
3205 page->fmark.span = block->lines->first_span;
3207 line = &block->lines[block->len - 1];
3208 page->lmark.i = line->last_span->len - 1;
3209 page->lmark.span = line->last_span;
3210 ret_v = Val_bool (1);
3211 goto unlock;
3214 for (line = block->lines;
3215 line < block->lines + block->len;
3216 ++line) {
3217 fz_text_span *span;
3219 b = &line->bbox;
3220 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3221 continue;
3223 if (mark == mark_line) {
3224 page->fmark.i = 0;
3225 page->fmark.span = line->first_span;
3227 page->lmark.i = line->last_span->len - 1;
3228 page->lmark.span = line->last_span;
3229 ret_v = Val_bool (1);
3230 goto unlock;
3233 for (span = line->first_span; span; span = span->next) {
3234 int charnum;
3236 b = &span->bbox;
3237 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3238 continue;
3240 for (charnum = 0; charnum < span->len; ++charnum) {
3241 fz_rect bbox;
3242 fz_text_char_bbox (&bbox, span, charnum);
3243 b = &bbox;
3245 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3246 /* unicode ftw */
3247 int charnum2, charnum3 = -1, charnum4 = -1;
3249 if (uninteresting (span->text[charnum].c)) goto unlock;
3251 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3252 if (uninteresting (span->text[charnum2].c)) {
3253 charnum3 = charnum2 + 1;
3254 break;
3257 if (charnum3 == -1) charnum3 = 0;
3259 for (charnum2 = charnum + 1;
3260 charnum2 < span->len;
3261 ++charnum2) {
3262 if (uninteresting (span->text[charnum2].c)) break;
3263 charnum4 = charnum2;
3265 if (charnum4 == -1) goto unlock;
3267 page->fmark.i = charnum3;
3268 page->fmark.span = span;
3270 page->lmark.i = charnum4;
3271 page->lmark.span = span;
3272 ret_v = Val_bool (1);
3273 goto unlock;
3279 unlock:
3280 if (!Bool_val (ret_v)) {
3281 page->fmark.span = NULL;
3282 page->lmark.span = NULL;
3283 page->fmark.i = 0;
3284 page->lmark.i = 0;
3286 unlock ("ml_markunder");
3288 done:
3289 CAMLreturn (ret_v);
3292 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3294 CAMLparam3 (ptr_v, x_v, y_v);
3295 CAMLlocal2 (ret_v, res_v);
3296 fz_rect *b = NULL;
3297 struct page *page;
3298 fz_page_block *pageb;
3299 struct pagedim *pdim;
3300 char *s = String_val (ptr_v);
3301 int x = Int_val (x_v), y = Int_val (y_v);
3303 ret_v = Val_int (0);
3304 if (trylock ("ml_rectofblock")) {
3305 goto done;
3308 page = parse_pointer ("ml_rectofblock", s);
3309 pdim = &state.pagedims[page->pdimno];
3310 x += pdim->bounds.x0;
3311 y += pdim->bounds.y0;
3313 ensuretext (page);
3315 for (pageb = page->text->blocks;
3316 pageb < page->text->blocks + page->text->len;
3317 ++pageb) {
3318 switch (pageb->type) {
3319 case FZ_PAGE_BLOCK_TEXT:
3320 b = &pageb->u.text->bbox;
3321 break;
3323 case FZ_PAGE_BLOCK_IMAGE:
3324 b = &pageb->u.image->bbox;
3325 break;
3327 default:
3328 continue;
3331 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3332 break;
3333 b = NULL;
3335 if (b) {
3336 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3337 ret_v = caml_alloc_small (1, 1);
3338 Store_double_field (res_v, 0, b->x0);
3339 Store_double_field (res_v, 1, b->x1);
3340 Store_double_field (res_v, 2, b->y0);
3341 Store_double_field (res_v, 3, b->y1);
3342 Field (ret_v, 0) = res_v;
3344 unlock ("ml_rectofblock");
3346 done:
3347 CAMLreturn (ret_v);
3350 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3352 CAMLparam2 (ptr_v, rect_v);
3353 fz_rect b;
3354 struct page *page;
3355 struct pagedim *pdim;
3356 char *s = String_val (ptr_v);
3357 int i, x0, x1, y0, y1, fi, li;
3358 fz_text_line *line;
3359 fz_page_block *pageb;
3360 fz_text_block *block;
3361 fz_text_span *span, *fspan, *lspan;
3363 if (trylock ("ml_seltext")) {
3364 goto done;
3367 page = parse_pointer ("ml_seltext", s);
3368 ensuretext (page);
3370 pdim = &state.pagedims[page->pdimno];
3371 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3372 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3373 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3374 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3376 if (y0 > y1) {
3377 int t = y0;
3378 y0 = y1;
3379 y1 = t;
3380 x0 = x1;
3381 x1 = t;
3384 if (0) {
3385 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3386 glColor3ub (128, 128, 128);
3387 recti (x0, y0, x1, y1);
3388 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3391 fi = page->fmark.i;
3392 fspan = page->fmark.span;
3394 li = page->lmark.i;
3395 lspan = page->lmark.span;
3397 for (pageb = page->text->blocks;
3398 pageb < page->text->blocks + page->text->len;
3399 ++pageb) {
3400 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3401 block = pageb->u.text;
3402 for (line = block->lines;
3403 line < block->lines + block->len;
3404 ++line) {
3405 fz_text_span *span;
3407 for (span = line->first_span; span; span = span->next) {
3408 for (i = 0; i < span->len; ++i) {
3409 int selected = 0;
3411 fz_text_char_bbox (&b, span, i);
3413 if (x0 >= b.x0 && x0 <= b.x1
3414 && y0 >= b.y0 && y0 <= b.y1) {
3415 fspan = span;
3416 fi = i;
3417 selected = 1;
3419 if (x1 >= b.x0 && x1 <= b.x1
3420 && y1 >= b.y0 && y1 <= b.y1) {
3421 lspan = span;
3422 li = i;
3423 selected = 1;
3425 if (0 && selected) {
3426 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3427 glColor3ub (128, 128, 128);
3428 recti (b.x0, b.y0, b.x1, b.y1);
3429 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3435 if (x1 < x0 && fspan == lspan) {
3436 i = fi;
3437 span = fspan;
3439 fi = li;
3440 fspan = lspan;
3442 li = i;
3443 lspan = span;
3446 page->fmark.i = fi;
3447 page->fmark.span = fspan;
3449 page->lmark.i = li;
3450 page->lmark.span = lspan;
3452 unlock ("ml_seltext");
3454 done:
3455 CAMLreturn (Val_unit);
3458 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3460 char buf[4];
3461 int i, len, ret;
3463 for (i = a; i <= b; ++i) {
3464 len = fz_runetochar (buf, span->text[i].c);
3465 ret = fwrite (buf, len, 1, f);
3467 if (ret != 1) {
3468 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3469 len, ret, strerror (errno));
3470 return -1;
3473 return 0;
3476 #ifdef __CYGWIN__
3477 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3479 caml_failwith ("ml_popen not implemented under Cygwin");
3481 #else
3482 CAMLprim value ml_popen (value command_v, value fds_v)
3484 CAMLparam2 (command_v, fds_v);
3485 CAMLlocal2 (l_v, tup_v);
3486 int ret;
3487 char *msg = NULL;
3488 value earg_v = Nothing;
3489 posix_spawnattr_t attr;
3490 posix_spawn_file_actions_t fa;
3491 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
3493 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3494 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3497 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3498 msg = "posix_spawnattr_init";
3499 goto fail1;
3502 #ifdef POSIX_SPAWN_USEVFORK
3503 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3504 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3505 goto fail;
3507 #endif
3509 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3510 int fd1, fd2;
3512 tup_v = Field (l_v, 0);
3513 fd1 = Int_val (Field (tup_v, 0));
3514 fd2 = Int_val (Field (tup_v, 1));
3515 if (fd2 < 0) {
3516 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3517 msg = "posix_spawn_file_actions_addclose";
3518 earg_v = tup_v;
3519 goto fail;
3522 else {
3523 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3524 msg = "posix_spawn_file_actions_adddup2";
3525 earg_v = tup_v;
3526 goto fail;
3531 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3532 msg = "posix_spawn";
3533 goto fail;
3536 fail:
3537 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3538 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3541 fail1:
3542 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3543 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3544 strerror (ret));
3547 if (msg)
3548 unix_error (ret, msg, earg_v);
3550 CAMLreturn (Val_unit);
3552 #endif
3554 CAMLprim value ml_hassel (value ptr_v)
3556 CAMLparam1 (ptr_v);
3557 CAMLlocal1 (ret_v);
3558 struct page *page;
3559 char *s = String_val (ptr_v);
3561 ret_v = Val_bool (0);
3562 if (trylock ("ml_hassel")) {
3563 goto done;
3566 page = parse_pointer ("ml_hassel", s);
3567 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3568 unlock ("ml_hassel");
3569 done:
3570 CAMLreturn (ret_v);
3573 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3575 CAMLparam2 (fd_v, ptr_v);
3576 FILE *f;
3577 int seen = 0;
3578 struct page *page;
3579 fz_text_line *line;
3580 fz_page_block *pageb;
3581 fz_text_block *block;
3582 int fd = Int_val (fd_v);
3583 char *s = String_val (ptr_v);
3585 if (trylock ("ml_copysel")) {
3586 goto done;
3589 page = parse_pointer ("ml_copysel", s);
3591 if (!page->fmark.span || !page->lmark.span) {
3592 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3593 goto unlock;
3596 f = fdopen (fd, "w");
3597 if (!f) {
3598 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3599 fd, strerror (errno));
3600 f = stdout;
3603 for (pageb = page->text->blocks;
3604 pageb < page->text->blocks + page->text->len;
3605 ++pageb) {
3606 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3607 block = pageb->u.text;
3608 for (line = block->lines;
3609 line < block->lines + block->len;
3610 ++line) {
3611 fz_text_span *span;
3613 for (span = line->first_span; span; span = span->next) {
3614 int a, b;
3616 seen |= span == page->fmark.span || span == page->lmark.span;
3617 a = span == page->fmark.span ? page->fmark.i : 0;
3618 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3620 if (seen) {
3621 if (pipespan (f, span, a, b)) {
3622 goto close;
3624 if (span == page->lmark.span) {
3625 goto close;
3627 if (span == line->last_span) {
3628 if (putc ('\n', f) == EOF) {
3629 fprintf (stderr,
3630 "failed break line on sel pipe: %s\n",
3631 strerror (errno));
3632 goto close;
3639 close:
3640 if (f != stdout) {
3641 int ret = fclose (f);
3642 fd = -1;
3643 if (ret == -1) {
3644 if (errno != ECHILD) {
3645 fprintf (stderr, "failed to close sel pipe: %s\n",
3646 strerror (errno));
3650 unlock:
3651 unlock ("ml_copysel");
3653 done:
3654 if (fd >= 0) {
3655 if (close (fd)) {
3656 fprintf (stderr, "failed to close sel pipe: %s\n",
3657 strerror (errno));
3660 CAMLreturn (Val_unit);
3663 CAMLprim value ml_getpdimrect (value pagedimno_v)
3665 CAMLparam1 (pagedimno_v);
3666 CAMLlocal1 (ret_v);
3667 int pagedimno = Int_val (pagedimno_v);
3668 fz_rect box;
3670 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3671 if (trylock ("ml_getpdimrect")) {
3672 box = fz_empty_rect;
3674 else {
3675 box = state.pagedims[pagedimno].mediabox;
3676 unlock ("ml_getpdimrect");
3679 Store_double_field (ret_v, 0, box.x0);
3680 Store_double_field (ret_v, 1, box.x1);
3681 Store_double_field (ret_v, 2, box.y0);
3682 Store_double_field (ret_v, 3, box.y1);
3684 CAMLreturn (ret_v);
3687 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3688 value dw_v, value cols_v)
3690 CAMLparam3 (winw_v, winh_v, dw_v);
3691 CAMLlocal1 (ret_v);
3692 int i;
3693 double zoom = -1.;
3694 double maxh = 0.0;
3695 struct pagedim *p;
3696 double winw = Int_val (winw_v);
3697 double winh = Int_val (winh_v);
3698 double dw = Int_val (dw_v);
3699 double cols = Int_val (cols_v);
3700 double pw = 1.0, ph = 1.0;
3702 if (trylock ("ml_zoom_for_height")) {
3703 goto done;
3706 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3707 double w = p->pagebox.x1 / cols;
3708 double h = p->pagebox.y1;
3709 if (h > maxh) {
3710 maxh = h;
3711 ph = h;
3712 if (state.fitmodel != FitProportional) pw = w;
3714 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3717 zoom = (((winh / ph) * pw) + dw) / winw;
3718 unlock ("ml_zoom_for_height");
3719 done:
3720 ret_v = caml_copy_double (zoom);
3721 CAMLreturn (ret_v);
3724 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3726 CAMLparam4 (pt_v, x_v, y_v, string_v);
3727 CAMLlocal1 (ret_v);
3728 int pt = Int_val(pt_v);
3729 int x = Int_val (x_v);
3730 int y = Int_val (y_v);
3731 double w;
3733 w = draw_string (state.face, pt, x, y, String_val (string_v));
3734 ret_v = caml_copy_double (w);
3735 CAMLreturn (ret_v);
3738 CAMLprim value ml_measure_string (value pt_v, value string_v)
3740 CAMLparam2 (pt_v, string_v);
3741 CAMLlocal1 (ret_v);
3742 int pt = Int_val (pt_v);
3743 double w;
3745 w = measure_string (state.face, pt, String_val (string_v));
3746 ret_v = caml_copy_double (w);
3747 CAMLreturn (ret_v);
3750 CAMLprim value ml_getpagebox (value opaque_v)
3752 CAMLparam1 (opaque_v);
3753 CAMLlocal1 (ret_v);
3754 fz_rect rect;
3755 fz_irect bbox;
3756 fz_matrix ctm;
3757 fz_device *dev;
3758 char *s = String_val (opaque_v);
3759 struct page *page = parse_pointer ("ml_getpagebox", s);
3761 ret_v = caml_alloc_tuple (4);
3762 dev = fz_new_bbox_device (state.ctx, &rect);
3763 dev->hints |= FZ_IGNORE_SHADE;
3765 switch (page->type) {
3766 case DPDF:
3767 ctm = pagectm (page);
3768 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3769 break;
3771 case DXPS:
3772 ctm = pagectm (page);
3773 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3774 break;
3776 default:
3777 rect = fz_infinite_rect;
3778 break;
3781 fz_free_device (dev);
3782 fz_round_rect (&bbox, &rect);
3783 Field (ret_v, 0) = Val_int (bbox.x0);
3784 Field (ret_v, 1) = Val_int (bbox.y0);
3785 Field (ret_v, 2) = Val_int (bbox.x1);
3786 Field (ret_v, 3) = Val_int (bbox.y1);
3788 CAMLreturn (ret_v);
3791 CAMLprim value ml_setaalevel (value level_v)
3793 CAMLparam1 (level_v);
3795 state.aalevel = Int_val (level_v);
3796 CAMLreturn (Val_unit);
3799 #undef pixel
3800 #include <X11/Xlib.h>
3801 #include <GL/glx.h>
3803 static struct {
3804 Display *dpy;
3805 GLXContext ctx;
3806 GLXDrawable drawable;
3807 } glx;
3809 #include "keysym2ucs.c"
3811 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3813 CAMLparam1 (keysym_v);
3814 CAMLlocal1 (str_v);
3815 KeySym keysym = Int_val (keysym_v);
3816 Rune rune;
3817 int len;
3818 char buf[5];
3820 rune = keysym2ucs (keysym);
3821 len = fz_runetochar (buf, rune);
3822 buf[len] = 0;
3823 str_v = caml_copy_string (buf);
3824 CAMLreturn (str_v);
3827 CAMLprim value ml_glx (value win_v)
3829 CAMLparam1 (win_v);
3830 XVisualInfo *visual;
3831 int screen, wid = Int_val (win_v);
3832 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3834 glx.dpy = XOpenDisplay (NULL);
3835 if (!glx.dpy) {
3836 caml_failwith ("XOpenDisplay");
3839 screen = DefaultScreen (glx.dpy);
3840 visual = glXChooseVisual (glx.dpy, screen, attributes);
3841 if (!visual) {
3842 XCloseDisplay (glx.dpy);
3843 glx.dpy = NULL;
3844 caml_failwith ("glXChooseVisual");
3847 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3848 XFree (visual);
3849 if (!glx.ctx) {
3850 XCloseDisplay (glx.dpy);
3851 glx.dpy = NULL;
3852 caml_failwith ("glXCreateContext");
3855 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3856 glXDestroyContext (glx.dpy, glx.ctx);
3857 XCloseDisplay (glx.dpy);
3858 glx.dpy = NULL;
3859 glx.ctx = NULL;
3860 caml_failwith ("glXMakeCurrent");
3862 glx.drawable = wid;
3863 CAMLreturn (Val_unit);
3866 CAMLprim value ml_swapb (value unit_v)
3868 CAMLparam1 (unit_v);
3869 glXSwapBuffers (glx.dpy, glx.drawable);
3870 CAMLreturn (Val_unit);
3873 CAMLprim value ml_glxsync (value unit_v)
3875 CAMLparam1 (unit_v);
3876 if (glx.dpy && glx.ctx) {
3877 glXWaitX ();
3878 glXWaitGL ();
3880 CAMLreturn (Val_unit);
3883 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3884 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3886 CAMLprim value ml_platform (value unit_v)
3888 CAMLparam1 (unit_v);
3889 int platid = piunknown;
3891 #if defined __linux__
3892 platid = pilinux;
3893 #elif defined __CYGWIN__
3894 platid = picygwin;
3895 #elif defined __DragonFly__
3896 platid = pidragonflybsd;
3897 #elif defined __FreeBSD__
3898 platid = pifreebsd;
3899 #elif defined __OpenBSD__
3900 platid = piopenbsd;
3901 #elif defined __NetBSD__
3902 platid = pinetbsd;
3903 #elif defined __sun__
3904 platid = pisun;
3905 #elif defined __APPLE__
3906 platid = piosx;
3907 #endif
3908 CAMLreturn (Val_int (platid));
3911 CAMLprim value ml_cloexec (value fd_v)
3913 CAMLparam1 (fd_v);
3914 int fd = Int_val (fd_v);
3916 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3917 uerror ("fcntl", Nothing);
3919 CAMLreturn (Val_unit);
3922 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3924 CAMLparam2 (w_v, h_v);
3925 CAMLlocal1 (ret_v);
3926 struct pbo *pbo;
3927 int w = Int_val (w_v);
3928 int h = Int_val (h_v);
3929 int cs = Int_val (cs_v);
3931 if (state.pbo_usable) {
3932 pbo = calloc (sizeof (*pbo), 1);
3933 if (!pbo) {
3934 err (1, "calloc pbo");
3937 switch (cs) {
3938 case 0:
3939 case 1:
3940 pbo->size = w*h*4;
3941 break;
3942 case 2:
3943 pbo->size = w*h*2;
3944 break;
3945 default:
3946 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3949 state.glGenBuffersARB (1, &pbo->id);
3950 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3951 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3952 NULL, GL_STREAM_DRAW);
3953 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3954 GL_READ_WRITE);
3955 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3956 if (!pbo->ptr) {
3957 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3958 state.glDeleteBuffersARB (1, &pbo->id);
3959 free (pbo);
3960 ret_v = caml_copy_string ("0");
3962 else {
3963 int res;
3964 char *s;
3966 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3967 if (res < 0) {
3968 err (1, "snprintf %" FMT_ptr " failed", pbo);
3970 s = malloc (res+1);
3971 if (!s) {
3972 err (1, "malloc %d bytes failed", res+1);
3974 res = sprintf (s, "%" FMT_ptr, pbo);
3975 if (res < 0) {
3976 err (1, "sprintf %" FMT_ptr " failed", pbo);
3978 ret_v = caml_copy_string (s);
3979 free (s);
3982 else {
3983 ret_v = caml_copy_string ("0");
3985 CAMLreturn (ret_v);
3988 CAMLprim value ml_freepbo (value s_v)
3990 CAMLparam1 (s_v);
3991 char *s = String_val (s_v);
3992 struct tile *tile = parse_pointer ("ml_freepbo", s);
3994 if (tile->pbo) {
3995 state.glDeleteBuffersARB (1, &tile->pbo->id);
3996 tile->pbo->id = -1;
3997 tile->pbo->ptr = NULL;
3998 tile->pbo->size = -1;
4000 CAMLreturn (Val_unit);
4003 CAMLprim value ml_unmappbo (value s_v)
4005 CAMLparam1 (s_v);
4006 char *s = String_val (s_v);
4007 struct tile *tile = parse_pointer ("ml_unmappbo", s);
4009 if (tile->pbo) {
4010 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4011 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4012 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4014 tile->pbo->ptr = NULL;
4015 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4017 CAMLreturn (Val_unit);
4020 static void setuppbo (void)
4022 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4023 state.pbo_usable = GGPA (glBindBufferARB)
4024 && GGPA (glUnmapBufferARB)
4025 && GGPA (glMapBufferARB)
4026 && GGPA (glBufferDataARB)
4027 && GGPA (glGenBuffersARB)
4028 && GGPA (glDeleteBuffersARB);
4029 #undef GGPA
4032 CAMLprim value ml_pbo_usable (value unit_v)
4034 CAMLparam1 (unit_v);
4035 CAMLreturn (Val_bool (state.pbo_usable));
4038 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4040 CAMLparam3 (ptr_v, x_v, y_v);
4041 CAMLlocal2 (ret_v, tup_v);
4042 struct page *page;
4043 char *s = String_val (ptr_v);
4044 int x = Int_val (x_v), y = Int_val (y_v);
4045 struct pagedim *pdim;
4046 fz_point p;
4047 fz_matrix ctm;
4049 page = parse_pointer ("ml_unproject", s);
4050 pdim = &state.pagedims[page->pdimno];
4052 ret_v = Val_int (0);
4053 if (trylock ("ml_unproject")) {
4054 goto done;
4057 switch (page->type) {
4058 case DPDF:
4059 trimctm (page->u.pdfpage, page->pdimno);
4060 break;
4062 default:
4063 break;
4065 p.x = x;
4066 p.y = y;
4068 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4069 fz_invert_matrix (&ctm, &ctm);
4070 fz_transform_point (&p, &ctm);
4072 tup_v = caml_alloc_tuple (2);
4073 ret_v = caml_alloc_small (1, 1);
4074 Field (tup_v, 0) = Val_int (p.x);
4075 Field (tup_v, 1) = Val_int (p.y);
4076 Field (ret_v, 0) = tup_v;
4078 unlock ("ml_unproject");
4079 done:
4080 CAMLreturn (ret_v);
4083 static void makestippletex (void)
4085 const char pixels[] = "\xff\xff\0\0";
4086 glGenTextures (1, &state.stid);
4087 glBindTexture (GL_TEXTURE_1D, state.stid);
4088 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4089 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4090 glTexImage1D (
4091 GL_TEXTURE_1D,
4093 GL_ALPHA,
4096 GL_ALPHA,
4097 GL_UNSIGNED_BYTE,
4098 pixels
4102 CAMLprim value ml_fz_version (value unit_v)
4104 return caml_copy_string (FZ_VERSION);
4107 CAMLprim value ml_init (value pipe_v, value params_v)
4109 CAMLparam2 (pipe_v, params_v);
4110 CAMLlocal2 (trim_v, fuzz_v);
4111 int ret;
4112 int texcount;
4113 char *fontpath;
4114 int colorspace;
4115 int mustoresize;
4116 int haspboext;
4117 struct sigaction sa;
4119 state.cr = Int_val (Field (pipe_v, 0));
4120 state.cw = Int_val (Field (pipe_v, 1));
4121 state.rotate = Int_val (Field (params_v, 0));
4122 state.fitmodel = Int_val (Field (params_v, 1));
4123 trim_v = Field (params_v, 2);
4124 texcount = Int_val (Field (params_v, 3));
4125 state.sliceheight = Int_val (Field (params_v, 4));
4126 mustoresize = Int_val (Field (params_v, 5));
4127 colorspace = Int_val (Field (params_v, 6));
4128 fontpath = String_val (Field (params_v, 7));
4130 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4131 if (!state.trimcachepath) {
4132 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4133 strerror (errno));
4135 haspboext = Bool_val (Field (params_v, 9));
4137 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4139 state.trimmargins = Bool_val (Field (trim_v, 0));
4140 fuzz_v = Field (trim_v, 1);
4141 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4142 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4143 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4144 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4146 set_tex_params (colorspace);
4148 if (*fontpath) {
4149 state.face = load_font (fontpath);
4151 else {
4152 unsigned int len;
4153 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
4155 state.face = load_builtin_font (base, len);
4157 if (!state.face) _exit (1);
4159 realloctexts (texcount);
4161 if (haspboext) {
4162 setuppbo ();
4165 makestippletex ();
4167 #ifdef __CYGWIN__
4168 sa.sa_handler = SIG_IGN;
4169 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4170 #else
4171 sa.sa_handler = SIG_DFL;
4172 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
4173 #endif
4174 if (sigemptyset (&sa.sa_mask)) {
4175 err (1, "sigemptyset");
4177 if (sigaction (SIGCHLD, &sa, NULL)) {
4178 err (1, "sigaction");
4181 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4182 if (ret) {
4183 errx (1, "pthread_create: %s", strerror (ret));
4186 CAMLreturn (Val_unit);