Make N-clicked pax really work
[llpp.git] / link.c
blobfad0f0fc9afbf8982237bafa5135b8da84d62d2d
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 fz_intersect_rect (&mediabox, &cropbox);
1035 else {
1036 if (empty) {
1037 if (fz_is_empty_rect (&rootmediabox)) {
1038 fprintf (stderr,
1039 "cannot find page size for page %d\n",
1040 pageno+1);
1042 else {
1043 mediabox = rootmediabox;
1047 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
1049 break;
1052 case DXPS:
1054 xps_page *page;
1056 fz_try (state.ctx) {
1057 page = xps_load_page (state.u.xps, pageno);
1058 xps_bound_page (state.u.xps, page, &mediabox);
1059 rotate = 0;
1060 if (state.trimmargins) {
1061 fz_rect rect;
1062 fz_device *dev;
1064 dev = fz_new_bbox_device (state.ctx, &rect);
1065 dev->hints |= FZ_IGNORE_SHADE;
1066 xps_run_page (state.u.xps, page, dev,
1067 &fz_identity, NULL);
1068 fz_free_device (dev);
1070 rect.x0 += state.trimfuzz.x0;
1071 rect.x1 += state.trimfuzz.x1;
1072 rect.y0 += state.trimfuzz.y0;
1073 rect.y1 += state.trimfuzz.y1;
1074 fz_intersect_rect (&rect, &mediabox);
1076 if (!fz_is_empty_rect (&rect)) {
1077 mediabox = rect;
1080 xps_free_page (state.u.xps, page);
1081 if (!state.cxack) {
1082 printd ("progress %f loading %d",
1083 (double) (pageno + 1) / state.pagecount,
1084 pageno + 1);
1087 fz_catch (state.ctx) {
1090 break;
1092 case DCBZ:
1094 rotate = 0;
1095 mediabox.x0 = 0;
1096 mediabox.y0 = 0;
1097 mediabox.x1 = 900;
1098 mediabox.y1 = 900;
1099 if (state.trimmargins && trimw) {
1100 cbz_page *page;
1102 fz_try (state.ctx) {
1103 page = cbz_load_page (state.u.cbz, pageno);
1104 cbz_bound_page (state.u.cbz, page, &mediabox);
1105 cbz_free_page (state.u.cbz, page);
1106 printd ("progress %f Trimming %d",
1107 (double) (pageno + 1) / state.pagecount,
1108 pageno + 1);
1110 fz_catch (state.ctx) {
1111 fprintf (stderr, "failed to load page %d\n", pageno+1);
1113 if (trimf) {
1114 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1115 if (n - 1) {
1116 err (1, "fwrite trim mediabox");
1120 else {
1121 if (trimf) {
1122 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1123 if (n - 1) {
1124 err (1, "fread trim mediabox");
1127 else {
1128 if (state.cxack) {
1129 cbz_page *page;
1130 fz_try (state.ctx) {
1131 page = cbz_load_page (state.u.cbz, pageno);
1132 cbz_bound_page (state.u.cbz, page, &mediabox);
1133 cbz_free_page (state.u.cbz, page);
1135 fz_catch (state.ctx) {
1136 fprintf (stderr, "failed to load cbz page\n");
1142 break;
1144 case DIMG:
1146 image_page *page;
1148 rotate = 0;
1149 mediabox.x0 = 0;
1150 mediabox.y0 = 0;
1151 mediabox.x1 = 900;
1152 mediabox.y1 = 900;
1154 fz_try (state.ctx) {
1155 page = image_load_page (state.u.img, pageno);
1156 image_bound_page (state.u.img, page, &mediabox);
1157 image_free_page (state.u.img, page);
1159 fz_catch (state.ctx) {
1160 fprintf (stderr, "failed to load page %d\n", pageno+1);
1163 break;
1165 default:
1166 ARSERT (0 && state.type);
1169 if (state.pagedimcount == 0
1170 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1171 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1172 size_t size;
1174 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1175 state.pagedims = realloc (state.pagedims, size);
1176 if (!state.pagedims) {
1177 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1178 size, state.pagedimcount + 1);
1181 p = &state.pagedims[state.pagedimcount++];
1182 p->rotate = rotate;
1183 p->mediabox = mediabox;
1184 p->pageno = pageno;
1187 end = now ();
1188 if (state.trimmargins) {
1189 printd ("progress 1 Trimmed %d pages in %f seconds",
1190 state.pagecount, end - start);
1192 else {
1193 printd ("vmsg Processed %d pages in %f seconds",
1194 state.pagecount, end - start);
1196 state.trimanew = 0;
1197 if (trimf) {
1198 if (fclose (trimf)) {
1199 err (1, "fclose");
1204 static void layout (void)
1206 int pindex;
1207 fz_rect box;
1208 fz_matrix ctm, rm;
1209 struct pagedim *p = p;
1210 double zw, w, maxw = 0.0, zoom = zoom;
1212 if (state.pagedimcount == 0) return;
1214 switch (state.fitmodel) {
1215 case FitProportional:
1216 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1217 double x0, x1;
1219 p = &state.pagedims[pindex];
1220 fz_rotate (&rm, p->rotate + state.rotate);
1221 box = p->mediabox;
1222 fz_transform_rect (&box, &rm);
1224 x0 = MIN (box.x0, box.x1);
1225 x1 = MAX (box.x0, box.x1);
1227 w = x1 - x0;
1228 maxw = MAX (w, maxw);
1229 zoom = state.w / maxw;
1231 break;
1233 case FitPage:
1234 maxw = state.w;
1235 break;
1237 case FitWidth:
1238 break;
1240 default:
1241 ARSERT (0 && state.fitmodel);
1244 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1245 fz_rect rect;
1246 fz_matrix tm, sm;
1248 p = &state.pagedims[pindex];
1249 fz_rotate (&ctm, state.rotate);
1250 fz_rotate (&rm, p->rotate + state.rotate);
1251 box = p->mediabox;
1252 fz_transform_rect (&box, &rm);
1253 w = box.x1 - box.x0;
1254 switch (state.fitmodel) {
1255 case FitProportional:
1256 p->left = ((maxw - w) * zoom) / 2.0;
1257 break;
1258 case FitPage:
1260 double zh, h;
1261 zw = maxw / w;
1262 h = box.y1 - box.y0;
1263 zh = state.h / h;
1264 zoom = MIN (zw, zh);
1265 p->left = (maxw - (w * zoom)) / 2.0;
1267 break;
1268 case FitWidth:
1269 p->left = 0;
1270 zoom = state.w / w;
1271 break;
1274 fz_scale (&p->zoomctm, zoom, zoom);
1275 fz_concat (&ctm, &p->zoomctm, &ctm);
1277 fz_rotate (&rm, p->rotate);
1278 p->pagebox = p->mediabox;
1279 fz_transform_rect (&p->pagebox, &rm);
1280 p->pagebox.x1 -= p->pagebox.x0;
1281 p->pagebox.y1 -= p->pagebox.y0;
1282 p->pagebox.x0 = 0;
1283 p->pagebox.y0 = 0;
1284 rect = p->pagebox;
1285 fz_transform_rect (&rect, &ctm);
1286 fz_round_rect (&p->bounds, &rect);
1287 p->ctm = ctm;
1289 fz_translate (&tm, 0, -p->mediabox.y1);
1290 fz_scale (&sm, zoom, -zoom);
1291 fz_concat (&ctm, &tm, &sm);
1292 fz_concat (&p->lctm, &ctm, &rm);
1294 p->tctmready = 0;
1297 do {
1298 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1299 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1300 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1301 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1302 int w = x1 - x0;
1303 int h = y1 - y0;
1305 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1306 } while (p-- != state.pagedims);
1309 static
1310 struct anchor { int n; int x; int y; int w; int h; }
1311 desttoanchor (fz_link_dest *dest)
1313 int i;
1314 struct anchor a;
1315 struct pagedim *pdim = state.pagedims;
1317 a.n = -1;
1318 a.x = 0;
1319 a.y = 0;
1320 for (i = 0; i < state.pagedimcount; ++i) {
1321 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1322 break;
1323 pdim = &state.pagedims[i];
1325 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1326 fz_point p;
1327 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1328 p.x = dest->ld.gotor.lt.x;
1329 else
1330 p.x = 0.0;
1331 p.y = dest->ld.gotor.lt.y;
1332 fz_transform_point (&p, &pdim->lctm);
1333 a.y = p.y;
1334 a.x = p.x;
1336 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1337 double x0, x1, y0, y1;
1339 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1340 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1341 a.w = x1 - x0;
1342 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1343 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1344 a.h = y1 - y0;
1345 a.n = dest->ld.gotor.page;
1347 return a;
1350 static void recurse_outline (fz_outline *outline, int level)
1352 while (outline) {
1353 switch (outline->dest.kind) {
1354 case FZ_LINK_GOTO:
1356 struct anchor a = desttoanchor (&outline->dest);
1358 if (a.n >= 0) {
1359 printd ("o %d %d %d %d %s",
1360 level, a.n, a.y, a.h, outline->title);
1363 break;
1365 case FZ_LINK_URI:
1366 printd ("ou %d %" FMT_s " %s %s", level,
1367 strlen (outline->title), outline->title,
1368 outline->dest.ld.uri.uri);
1369 break;
1371 case FZ_LINK_NONE:
1372 printd ("on %d %s", level, outline->title);
1373 break;
1375 default:
1376 printd ("emsg Unhandled outline kind %d for %s\n",
1377 outline->dest.kind, outline->title);
1378 break;
1380 if (outline->down) {
1381 recurse_outline (outline->down, level + 1);
1383 outline = outline->next;
1387 static void process_outline (void)
1389 fz_outline *outline;
1391 if (!state.needoutline) return;
1393 state.needoutline = 0;
1394 switch (state.type) {
1395 case DPDF:
1396 outline = pdf_load_outline (state.u.pdf);
1397 break;
1398 case DXPS:
1399 outline = xps_load_outline (state.u.xps);
1400 break;
1401 default:
1402 outline = NULL;
1403 break;
1405 if (outline) {
1406 recurse_outline (outline, 0);
1407 fz_free_outline (state.ctx, outline);
1411 static char *strofspan (fz_text_span *span)
1413 char *p;
1414 char utf8[10];
1415 fz_text_char *ch;
1416 size_t size = 0, cap = 80;
1418 p = malloc (cap + 1);
1419 if (!p) return NULL;
1421 for (ch = span->text; ch < span->text + span->len; ++ch) {
1422 int n = fz_runetochar (utf8, ch->c);
1423 if (size + n > cap) {
1424 cap *= 2;
1425 p = realloc (p, cap + 1);
1426 if (!p) return NULL;
1429 memcpy (p + size, utf8, n);
1430 size += n;
1432 p[size] = 0;
1433 return p;
1436 static int matchspan (regex_t *re, fz_text_page *page,
1437 fz_text_span *span, fz_matrix ctm,
1438 int stop, int pageno, double start)
1440 int ret;
1441 char *p;
1442 regmatch_t rm;
1443 int a, b, c;
1444 fz_rect sb, eb;
1445 fz_point p1, p2, p3, p4;
1447 p = strofspan (span);
1448 if (!p) return -1;
1450 ret = regexec (re, p, 1, &rm, 0);
1451 if (ret) {
1452 free (p);
1453 if (ret != REG_NOMATCH) {
1454 size_t size;
1455 char errbuf[80];
1456 size = regerror (ret, re, errbuf, sizeof (errbuf));
1457 printd ("msg regexec error `%.*s'",
1458 (int) size, errbuf);
1459 return -1;
1461 return 0;
1463 else {
1464 int l = span->len;
1466 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1467 c += fz_runelen (span->text[a].c);
1469 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1470 c += fz_runelen (span->text[b].c);
1473 if (fz_runelen (span->text[b].c) > 1) {
1474 b = MAX (0, b-1);
1477 fz_text_char_bbox (&sb, span, a);
1478 fz_text_char_bbox (&eb, span, b);
1480 p1.x = sb.x0;
1481 p1.y = sb.y0;
1482 p2.x = eb.x1;
1483 p2.y = sb.y0;
1484 p3.x = eb.x1;
1485 p3.y = eb.y1;
1486 p4.x = sb.x0;
1487 p4.y = eb.y1;
1489 if (!stop) {
1490 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1491 pageno, 1,
1492 p1.x, p1.y,
1493 p2.x, p2.y,
1494 p3.x, p3.y,
1495 p4.x, p4.y);
1497 printd ("progress 1 found at %d `%.*s' in %f sec",
1498 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1499 now () - start);
1501 else {
1502 printd ("match %d %d %f %f %f %f %f %f %f %f",
1503 pageno, 2,
1504 p1.x, p1.y,
1505 p2.x, p2.y,
1506 p3.x, p3.y,
1507 p4.x, p4.y);
1509 free (p);
1510 return 1;
1514 static int compareblocks (const void *l, const void *r)
1516 fz_text_block const *ls = l;
1517 fz_text_block const* rs = r;
1518 return ls->bbox.y0 - rs->bbox.y0;
1521 /* wishful thinking function */
1522 static void search (regex_t *re, int pageno, int y, int forward)
1524 int i, j;
1525 fz_matrix ctm;
1526 fz_device *tdev;
1527 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1528 fz_text_page *text;
1529 fz_text_sheet *sheet;
1530 struct pagedim *pdim, *pdimprev;
1531 int stop = 0, niters = 0;
1532 double start, end;
1534 if (!(state.type == DPDF || state.type == DXPS))
1535 return;
1537 start = now ();
1538 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1539 if (niters++ == 5) {
1540 niters = 0;
1541 if (hasdata ()) {
1542 printd ("progress 1 attention requested aborting search at %d",
1543 pageno);
1544 stop = 1;
1546 else {
1547 printd ("progress %f searching in page %d",
1548 (double) (pageno + 1) / state.pagecount,
1549 pageno);
1552 pdimprev = NULL;
1553 for (i = 0; i < state.pagedimcount; ++i) {
1554 pdim = &state.pagedims[i];
1555 if (pdim->pageno == pageno) {
1556 goto found;
1558 if (pdim->pageno > pageno) {
1559 pdim = pdimprev;
1560 goto found;
1562 pdimprev = pdim;
1564 pdim = pdimprev;
1565 found:
1567 sheet = fz_new_text_sheet (state.ctx);
1568 text = fz_new_text_page (state.ctx);
1569 tdev = fz_new_text_device (state.ctx, sheet, text);
1571 switch (state.type) {
1572 case DPDF:
1573 u.ptr = NULL;
1574 fz_try (state.ctx) {
1575 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1576 trimctm (u.pdfpage, pdim - state.pagedims);
1577 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1578 fz_begin_page (tdev, &fz_infinite_rect, &ctm);
1579 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1580 fz_end_page (tdev);
1582 fz_catch (state.ctx) {
1583 fz_free_device (tdev);
1584 u.ptr = NULL;
1585 goto nextiter;
1587 break;
1589 case DXPS:
1590 u.xpspage = xps_load_page (state.u.xps, pageno);
1591 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1592 break;
1594 default:
1595 ARSERT (0 && state.type);
1598 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1599 fz_free_device (tdev);
1601 for (j = 0; j < text->len; ++j) {
1602 int k;
1603 fz_page_block *pb;
1604 fz_text_block *block;
1606 pb = &text->blocks[forward ? j : text->len - 1 - j];
1607 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1608 block = pb->u.text;
1610 for (k = 0; k < block->len; ++k) {
1611 fz_text_line *line;
1612 fz_text_span *span;
1614 if (forward) {
1615 line = &block->lines[k];
1616 if (line->bbox.y0 < y + 1) continue;
1618 else {
1619 line = &block->lines[block->len - 1 - k];
1620 if (line->bbox.y0 > y - 1) continue;
1623 for (span = line->first_span; span; span = span->next) {
1624 switch (matchspan (re, text, span, ctm,
1625 stop, pageno, start)) {
1626 case 0: break;
1627 case 1: stop = 1; break;
1628 case -1: stop = 1; goto endloop;
1633 nextiter:
1634 if (forward) {
1635 pageno += 1;
1636 y = 0;
1638 else {
1639 pageno -= 1;
1640 y = INT_MAX;
1642 endloop:
1643 fz_free_text_page (state.ctx, text);
1644 fz_free_text_sheet (state.ctx, sheet);
1645 if (u.ptr) {
1646 state.freepage (u.ptr);
1649 end = now ();
1650 if (!stop) {
1651 printd ("progress 1 no matches %f sec", end - start);
1653 printd ("clearrects");
1656 static void set_tex_params (int colorspace)
1658 union {
1659 unsigned char b;
1660 unsigned int s;
1661 } endianness = {1};
1663 switch (colorspace) {
1664 case 0:
1665 state.texiform = GL_RGBA8;
1666 state.texform = GL_RGBA;
1667 state.texty = GL_UNSIGNED_BYTE;
1668 state.colorspace = fz_device_rgb (state.ctx);
1669 break;
1670 case 1:
1671 state.texiform = GL_RGBA8;
1672 state.texform = GL_BGRA;
1673 state.texty = endianness.s > 1
1674 ? GL_UNSIGNED_INT_8_8_8_8
1675 : GL_UNSIGNED_INT_8_8_8_8_REV;
1676 state.colorspace = fz_device_bgr (state.ctx);
1677 break;
1678 case 2:
1679 state.texiform = GL_LUMINANCE_ALPHA;
1680 state.texform = GL_LUMINANCE_ALPHA;
1681 state.texty = GL_UNSIGNED_BYTE;
1682 state.colorspace = fz_device_gray (state.ctx);
1683 break;
1684 default:
1685 errx (1, "invalid colorspce %d", colorspace);
1689 static void realloctexts (int texcount)
1691 size_t size;
1693 if (texcount == state.texcount) return;
1695 if (texcount < state.texcount) {
1696 glDeleteTextures (state.texcount - texcount,
1697 state.texids + texcount);
1700 size = texcount * sizeof (*state.texids);
1701 state.texids = realloc (state.texids, size);
1702 if (!state.texids) {
1703 err (1, "realloc texids %" FMT_s, size);
1706 size = texcount * sizeof (*state.texowners);
1707 state.texowners = realloc (state.texowners, size);
1708 if (!state.texowners) {
1709 err (1, "realloc texowners %" FMT_s, size);
1711 if (texcount > state.texcount) {
1712 int i;
1714 glGenTextures (texcount - state.texcount,
1715 state.texids + state.texcount);
1716 for (i = state.texcount; i < texcount; ++i) {
1717 state.texowners[i].w = -1;
1718 state.texowners[i].slice = NULL;
1721 state.texcount = texcount;
1722 state.texindex = 0;
1725 static char *mbtoutf8 (char *s)
1727 char *p, *r;
1728 wchar_t *tmp;
1729 size_t i, ret, len;
1731 len = mbstowcs (NULL, s, strlen (s));
1732 if (len == 0) {
1733 return s;
1735 else {
1736 if (len == (size_t) -1) {
1737 return s;
1741 tmp = malloc (len * sizeof (wchar_t));
1742 if (!tmp) {
1743 return s;
1746 ret = mbstowcs (tmp, s, len);
1747 if (ret == (size_t) -1) {
1748 free (tmp);
1749 return s;
1752 len = 0;
1753 for (i = 0; i < ret; ++i) {
1754 len += fz_runelen (tmp[i]);
1757 p = r = malloc (len + 1);
1758 if (!r) {
1759 free (tmp);
1760 return s;
1763 for (i = 0; i < ret; ++i) {
1764 p += fz_runetochar (p, tmp[i]);
1766 *p = 0;
1767 free (tmp);
1768 return r;
1771 CAMLprim value ml_mbtoutf8 (value s_v)
1773 CAMLparam1 (s_v);
1774 CAMLlocal1 (ret_v);
1775 char *s, *r;
1777 s = String_val (s_v);
1778 r = mbtoutf8 (s);
1779 if (r == s) {
1780 ret_v = s_v;
1782 else {
1783 ret_v = caml_copy_string (r);
1784 free (r);
1786 CAMLreturn (ret_v);
1789 static void * mainloop (void *unused)
1791 char *p = NULL;
1792 int len, ret, oldlen = 0;
1794 for (;;) {
1795 len = readlen ();
1796 if (len == 0) {
1797 errx (1, "readlen returned 0");
1800 if (oldlen < len + 1) {
1801 p = realloc (p, len + 1);
1802 if (!p) {
1803 err (1, "realloc %d failed", len + 1);
1805 oldlen = len + 1;
1807 readdata (p, len);
1808 p[len] = 0;
1810 if (!strncmp ("open", p, 4)) {
1811 int wthack, off;
1812 char *password;
1813 char *filename;
1814 char *utf8filename;
1815 size_t filenamelen;
1817 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1818 if (ret != 2) {
1819 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1822 filename = p + 5 + off;
1823 filenamelen = strlen (filename);
1824 password = filename + filenamelen + 1;
1826 lock ("open");
1827 openxref (filename, password);
1828 pdfinfo ();
1829 initpdims ();
1830 unlock ("open");
1832 if (!wthack) {
1833 utf8filename = mbtoutf8 (filename);
1834 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1835 if (utf8filename != filename) {
1836 free (utf8filename);
1839 state.needoutline = 1;
1841 else if (!strncmp ("cs", p, 2)) {
1842 int i, colorspace;
1844 ret = sscanf (p + 2, " %d", &colorspace);
1845 if (ret != 1) {
1846 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1848 lock ("cs");
1849 set_tex_params (colorspace);
1850 for (i = 0; i < state.texcount; ++i) {
1851 state.texowners[i].w = -1;
1852 state.texowners[i].slice = NULL;
1854 unlock ("cs");
1856 else if (!strncmp ("freepage", p, 8)) {
1857 void *ptr;
1859 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1860 if (ret != 1) {
1861 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1863 freepage (ptr);
1865 else if (!strncmp ("freetile", p, 8)) {
1866 void *ptr;
1868 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1869 if (ret != 1) {
1870 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1872 freetile (ptr);
1874 else if (!strncmp ("search", p, 6)) {
1875 int icase, pageno, y, ret, len2, forward;
1876 char *pattern;
1877 regex_t re;
1879 ret = sscanf (p + 6, " %d %d %d %d,%n",
1880 &icase, &pageno, &y, &forward, &len2);
1881 if (ret != 4) {
1882 errx (1, "malformed search `%s' ret=%d", p, ret);
1885 pattern = p + 6 + len2;
1886 ret = regcomp (&re, pattern,
1887 REG_EXTENDED | (icase ? REG_ICASE : 0));
1888 if (ret) {
1889 char errbuf[80];
1890 size_t size;
1892 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1893 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1895 else {
1896 search (&re, pageno, y, forward);
1897 regfree (&re);
1900 else if (!strncmp ("geometry", p, 8)) {
1901 int w, h, fitmodel;
1903 printd ("clear");
1904 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1905 if (ret != 3) {
1906 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1909 lock ("geometry");
1910 state.h = h;
1911 if (w != state.w) {
1912 int i;
1913 state.w = w;
1914 for (i = 0; i < state.texcount; ++i) {
1915 state.texowners[i].slice = NULL;
1918 state.fitmodel = fitmodel;
1919 layout ();
1920 process_outline ();
1922 state.gen++;
1923 unlock ("geometry");
1924 printd ("continue %d", state.pagecount);
1926 else if (!strncmp ("reqlayout", p, 9)) {
1927 char *nameddest;
1928 int rotate, fitmodel, off, h;
1930 printd ("clear");
1931 ret = sscanf (p + 9, " %d %d %d %n",
1932 &rotate, &fitmodel, &h, &off);
1933 if (ret != 3) {
1934 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1936 lock ("reqlayout");
1937 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1938 state.gen += 1;
1940 state.rotate = rotate;
1941 state.fitmodel = fitmodel;
1942 state.h = h;
1943 layout ();
1944 process_outline ();
1946 nameddest = p + 9 + off;
1947 if (state.type == DPDF && nameddest && *nameddest) {
1948 struct anchor a;
1949 fz_link_dest dest;
1950 pdf_obj *needle, *obj;
1952 needle = pdf_new_string (state.u.pdf, nameddest,
1953 strlen (nameddest));
1954 obj = pdf_lookup_dest (state.u.pdf, needle);
1955 if (obj) {
1956 dest = pdf_parse_link_dest (state.u.pdf, FZ_LINK_GOTO, obj);
1958 a = desttoanchor (&dest);
1959 if (a.n >= 0) {
1960 printd ("a %d %d %d", a.n, a.x, a.y);
1962 else {
1963 printd ("emsg failed to parse destination `%s'\n",
1964 nameddest);
1967 else {
1968 printd ("emsg destination `%s' not found\n",
1969 nameddest);
1971 pdf_drop_obj (needle);
1974 state.gen++;
1975 unlock ("reqlayout");
1976 printd ("continue %d", state.pagecount);
1978 else if (!strncmp ("page", p, 4)) {
1979 double a, b;
1980 struct page *page;
1981 int pageno, pindex, ret;
1983 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1984 if (ret != 2) {
1985 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1988 lock ("page");
1989 a = now ();
1990 page = loadpage (pageno, pindex);
1991 b = now ();
1992 unlock ("page");
1994 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1996 else if (!strncmp ("tile", p, 4)) {
1997 int x, y, w, h, ret;
1998 struct page *page;
1999 struct tile *tile;
2000 double a, b;
2001 void *data;
2003 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
2004 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
2005 if (ret != 6) {
2006 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
2009 lock ("tile");
2010 a = now ();
2011 tile = rendertile (page, x, y, w, h, data);
2012 b = now ();
2013 unlock ("tile");
2015 printd ("tile %d %d %" FMT_ptr " %u %f",
2016 x, y,
2017 FMT_ptr_cast2 (tile),
2018 tile->w * tile->h * tile->pixmap->n,
2019 b - a);
2021 else if (!strncmp ("settrim", p, 7)) {
2022 fz_irect fuzz;
2023 int trimmargins;
2025 ret = sscanf (p + 7, " %d %d %d %d %d",
2026 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
2027 if (ret != 5) {
2028 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
2030 printd ("clear");
2031 lock ("settrim");
2032 state.trimmargins = trimmargins;
2033 state.needoutline = 1;
2034 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
2035 state.trimanew = 1;
2036 state.trimfuzz = fuzz;
2038 state.pagedimcount = 0;
2039 free (state.pagedims);
2040 state.pagedims = NULL;
2041 initpdims ();
2042 layout ();
2043 process_outline ();
2044 unlock ("settrim");
2045 printd ("continue %d", state.pagecount);
2047 else if (!strncmp ("sliceh", p, 6)) {
2048 int h;
2050 ret = sscanf (p + 6, " %d", &h);
2051 if (ret != 1) {
2052 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
2054 if (h != state.sliceheight) {
2055 int i;
2057 state.sliceheight = h;
2058 for (i = 0; i < state.texcount; ++i) {
2059 state.texowners[i].w = -1;
2060 state.texowners[i].h = -1;
2061 state.texowners[i].slice = NULL;
2065 else if (!strncmp ("interrupt", p, 9)) {
2066 printd ("vmsg interrupted");
2068 else {
2069 errx (1, "unknown command %.*s", len, p);
2072 return 0;
2075 CAMLprim value ml_realloctexts (value texcount_v)
2077 CAMLparam1 (texcount_v);
2078 int ok;
2080 if (trylock ("ml_realloctexts")) {
2081 ok = 0;
2082 goto done;
2084 realloctexts (Int_val (texcount_v));
2085 ok = 1;
2086 unlock ("ml_realloctexts");
2088 done:
2089 CAMLreturn (Val_bool (ok));
2092 static void recti (int x0, int y0, int x1, int y1)
2094 GLfloat *v = state.vertices;
2096 glVertexPointer (2, GL_FLOAT, 0, v);
2097 v[0] = x0; v[1] = y0;
2098 v[2] = x1; v[3] = y0;
2099 v[4] = x0; v[5] = y1;
2100 v[6] = x1; v[7] = y1;
2101 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2104 static void showsel (struct page *page, int ox, int oy)
2106 int seen = 0;
2107 fz_irect bbox;
2108 fz_rect rect;
2109 fz_text_line *line;
2110 fz_page_block *pageb;
2111 fz_text_block *block;
2112 struct mark first, last;
2114 first = page->fmark;
2115 last = page->lmark;
2117 if (!first.span || !last.span) return;
2119 glEnable (GL_BLEND);
2120 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2121 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
2123 ox += state.pagedims[page->pdimno].bounds.x0;
2124 oy += state.pagedims[page->pdimno].bounds.y0;
2125 for (pageb = page->text->blocks;
2126 pageb < page->text->blocks + page->text->len;
2127 ++pageb) {
2128 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2129 block = pageb->u.text;
2131 for (line = block->lines;
2132 line < block->lines + block->len;
2133 ++line) {
2134 fz_text_span *span;
2135 rect = fz_empty_rect;
2137 for (span = line->first_span; span; span = span->next) {
2138 int i, j, k;
2139 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2141 j = 0;
2142 k = span->len - 1;
2144 if (span == page->fmark.span && span == page->lmark.span) {
2145 seen = 1;
2146 j = MIN (first.i, last.i);
2147 k = MAX (first.i, last.i);
2149 else if (span == first.span) {
2150 seen = 1;
2151 j = first.i;
2153 else if (span == last.span) {
2154 seen = 1;
2155 k = last.i;
2158 if (seen) {
2159 for (i = j; i <= k; ++i) {
2160 fz_rect bbox;
2161 fz_union_rect (&rect,
2162 fz_text_char_bbox (&bbox, span, i));
2164 fz_round_rect (&bbox, &rect);
2165 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2166 bbox.x0,
2167 bbox.y0,
2168 bbox.x1,
2169 bbox.y1,
2170 oy, ox);
2172 recti (bbox.x0 + ox, bbox.y0 + oy,
2173 bbox.x1 + ox, bbox.y1 + oy);
2174 if (span == last.span) {
2175 goto done;
2177 rect = fz_empty_rect;
2182 done:
2183 glDisable (GL_BLEND);
2186 #include "glfont.c"
2188 static void highlightlinks (struct page *page, int xoff, int yoff)
2190 fz_matrix ctm, tm, pm;
2191 fz_link *link, *links;
2192 GLfloat *texcoords = state.texcoords;
2193 GLfloat *vertices = state.vertices;
2195 switch (page->type) {
2196 case DPDF:
2197 links = page->u.pdfpage->links;
2198 break;
2200 case DXPS:
2201 links = page->u.xpspage->links;
2202 break;
2204 default:
2205 return;
2208 glEnable (GL_TEXTURE_1D);
2209 glEnable (GL_BLEND);
2210 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2211 glBindTexture (GL_TEXTURE_1D, state.stid);
2213 xoff -= state.pagedims[page->pdimno].bounds.x0;
2214 yoff -= state.pagedims[page->pdimno].bounds.y0;
2215 fz_translate (&tm, xoff, yoff);
2216 pm = pagectm (page);
2217 fz_concat (&ctm, &pm, &tm);
2219 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2220 glVertexPointer (2, GL_FLOAT, 0, vertices);
2222 for (link = links; link; link = link->next) {
2223 fz_point p1, p2, p3, p4;
2225 p1.x = link->rect.x0;
2226 p1.y = link->rect.y0;
2228 p2.x = link->rect.x1;
2229 p2.y = link->rect.y0;
2231 p3.x = link->rect.x1;
2232 p3.y = link->rect.y1;
2234 p4.x = link->rect.x0;
2235 p4.y = link->rect.y1;
2237 fz_transform_point (&p1, &ctm);
2238 fz_transform_point (&p2, &ctm);
2239 fz_transform_point (&p3, &ctm);
2240 fz_transform_point (&p4, &ctm);
2242 switch (link->dest.kind) {
2243 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2244 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2245 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2246 default: glColor3ub (0, 0, 0); break;
2250 float w, h, s, t;
2252 w = p2.x - p1.x;
2253 h = p2.y - p1.y;
2254 t = sqrtf (w*w + h*h) * .25f;
2256 w = p3.x - p2.x;
2257 h = p3.y - p2.y;
2258 s = sqrtf (w*w + h*h) * .25f;
2260 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
2261 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
2263 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
2264 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
2266 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
2267 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
2269 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
2270 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
2272 glDrawArrays (GL_LINES, 0, 8);
2275 glDisable (GL_BLEND);
2276 glDisable (GL_TEXTURE_1D);
2279 static int compareslinks (const void *l, const void *r)
2281 struct slink const *ls = l;
2282 struct slink const *rs = r;
2283 if (ls->bbox.y0 == rs->bbox.y0) {
2284 return rs->bbox.x0 - rs->bbox.x0;
2286 return ls->bbox.y0 - rs->bbox.y0;
2289 static void droptext (struct page *page)
2291 if (page->text) {
2292 fz_free_text_page (state.ctx, page->text);
2293 page->fmark.i = -1;
2294 page->lmark.i = -1;
2295 page->fmark.span = NULL;
2296 page->lmark.span = NULL;
2297 page->text = NULL;
2299 if (page->sheet) {
2300 fz_free_text_sheet (state.ctx, page->sheet);
2301 page->sheet = NULL;
2305 static void dropslinks (struct page *page)
2307 if (page->slinks) {
2308 free (page->slinks);
2309 page->slinks = NULL;
2310 page->slinkcount = 0;
2314 static void ensureslinks (struct page *page)
2316 fz_matrix ctm;
2317 int i, count = 0;
2318 size_t slinksize = sizeof (*page->slinks);
2319 fz_link *link, *links;
2321 if (state.gen != page->sgen) {
2322 dropslinks (page);
2323 page->sgen = state.gen;
2325 if (page->slinks) return;
2327 switch (page->type) {
2328 case DPDF:
2329 links = page->u.pdfpage->links;
2330 trimctm (page->u.pdfpage, page->pdimno);
2331 fz_concat (&ctm,
2332 &state.pagedims[page->pdimno].tctm,
2333 &state.pagedims[page->pdimno].ctm);
2334 break;
2336 case DXPS:
2337 links = page->u.xpspage->links;
2338 ctm = state.pagedims[page->pdimno].ctm;
2339 break;
2341 default:
2342 return;
2345 for (link = links; link; link = link->next) {
2346 count++;
2348 if (count > 0) {
2349 page->slinkcount = count;
2350 page->slinks = calloc (count, slinksize);
2351 if (!page->slinks) {
2352 err (1, "realloc slinks %d", count);
2355 for (i = 0, link = links; link; ++i, link = link->next) {
2356 fz_rect rect;
2358 rect = link->rect;
2359 fz_transform_rect (&rect, &ctm);
2360 page->slinks[i].link = link;
2361 fz_round_rect (&page->slinks[i].bbox, &rect);
2363 qsort (page->slinks, count, slinksize, compareslinks);
2367 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2368 static void fmt_linkn (char *s, unsigned int u)
2370 unsigned int len; unsigned int q;
2371 int zma = 'z' - 'a' + 1;
2372 len = 1; q = u;
2373 while (q > zma - 1) { ++len; q /= zma; }
2374 if (s) {
2375 s += len;
2376 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2377 /* handles u == 0 */
2379 s[len] = 0;
2382 static void highlightslinks (struct page *page, int xoff, int yoff,
2383 int noff, char *targ, int tlen, int hfsize)
2385 int i;
2386 char buf[40];
2387 struct slink *slink;
2388 double x0, y0, x1, y1, w;
2390 ensureslinks (page);
2391 glColor3ub (0xc3, 0xb0, 0x91);
2392 for (i = 0; i < page->slinkcount; ++i) {
2393 fmt_linkn (buf, i + noff);
2394 if (!tlen || !strncmp (targ, buf, tlen)) {
2395 slink = &page->slinks[i];
2397 x0 = slink->bbox.x0 + xoff - 5;
2398 y1 = slink->bbox.y0 + yoff - 5;
2399 y0 = y1 + 10 + hfsize;
2400 w = measure_string (state.face, hfsize, buf);
2401 x1 = x0 + w + 10;
2402 recti (x0, y0, x1, y1);
2406 glEnable (GL_BLEND);
2407 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2408 glEnable (GL_TEXTURE_2D);
2409 glColor3ub (0, 0, 0);
2410 for (i = 0; i < page->slinkcount; ++i) {
2411 fmt_linkn (buf, i + noff);
2412 if (!tlen || !strncmp (targ, buf, tlen)) {
2413 slink = &page->slinks[i];
2415 x0 = slink->bbox.x0 + xoff;
2416 y0 = slink->bbox.y0 + yoff + hfsize;
2417 draw_string (state.face, hfsize, x0, y0, buf);
2420 glDisable (GL_TEXTURE_2D);
2421 glDisable (GL_BLEND);
2425 static void uploadslice (struct tile *tile, struct slice *slice)
2427 int offset;
2428 struct slice *slice1;
2429 unsigned char *texdata;
2431 offset = 0;
2432 for (slice1 = tile->slices; slice != slice1; slice1++) {
2433 offset += slice1->h * tile->w * tile->pixmap->n;
2435 if (slice->texindex != -1 && slice->texindex < state.texcount
2436 && state.texowners[slice->texindex].slice == slice) {
2437 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2439 else {
2440 int subimage = 0;
2441 int texindex = state.texindex++ % state.texcount;
2443 if (state.texowners[texindex].w == tile->w) {
2444 if (state.texowners[texindex].h >= slice->h) {
2445 subimage = 1;
2447 else {
2448 state.texowners[texindex].h = slice->h;
2451 else {
2452 state.texowners[texindex].h = slice->h;
2455 state.texowners[texindex].w = tile->w;
2456 state.texowners[texindex].slice = slice;
2457 slice->texindex = texindex;
2459 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2460 if (tile->pbo) {
2461 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2462 texdata = 0;
2464 else {
2465 texdata = tile->pixmap->samples;
2467 if (subimage) {
2468 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2472 tile->w,
2473 slice->h,
2474 state.texform,
2475 state.texty,
2476 texdata+offset
2479 else {
2480 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2482 state.texiform,
2483 tile->w,
2484 slice->h,
2486 state.texform,
2487 state.texty,
2488 texdata+offset
2491 if (tile->pbo) {
2492 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2497 CAMLprim value ml_begintiles (value unit_v)
2499 CAMLparam1 (unit_v);
2500 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2501 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2502 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2503 CAMLreturn (unit_v);
2506 CAMLprim value ml_endtiles (value unit_v)
2508 CAMLparam1 (unit_v);
2509 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2510 CAMLreturn (unit_v);
2513 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2515 CAMLparam2 (args_v, ptr_v);
2516 int dispx = Int_val (Field (args_v, 0));
2517 int dispy = Int_val (Field (args_v, 1));
2518 int dispw = Int_val (Field (args_v, 2));
2519 int disph = Int_val (Field (args_v, 3));
2520 int tilex = Int_val (Field (args_v, 4));
2521 int tiley = Int_val (Field (args_v, 5));
2522 char *s = String_val (ptr_v);
2523 struct tile *tile = parse_pointer ("ml_drawtile", s);
2524 int slicey, firstslice;
2525 struct slice *slice;
2526 GLfloat *texcoords = state.texcoords;
2527 GLfloat *vertices = state.vertices;
2529 firstslice = tiley / tile->sliceheight;
2530 slice = &tile->slices[firstslice];
2531 slicey = tiley % tile->sliceheight;
2533 while (disph > 0) {
2534 int dh;
2536 dh = slice->h - slicey;
2537 dh = MIN (disph, dh);
2538 uploadslice (tile, slice);
2540 texcoords[0] = tilex; texcoords[1] = slicey;
2541 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2542 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2543 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2545 vertices[0] = dispx; vertices[1] = dispy;
2546 vertices[2] = dispx+dispw; vertices[3] = dispy;
2547 vertices[4] = dispx; vertices[5] = dispy+dh;
2548 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2550 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2551 dispy += dh;
2552 disph -= dh;
2553 slice++;
2554 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2555 slicey = 0;
2557 CAMLreturn (Val_unit);
2560 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2561 value xoff_v, value yoff_v,
2562 value li_v)
2564 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2565 int xoff = Int_val (xoff_v);
2566 int yoff = Int_val (yoff_v);
2567 int noff = Int_val (Field (li_v, 0));
2568 char *targ = String_val (Field (li_v, 1));
2569 int tlen = caml_string_length (Field (li_v, 1));
2570 int hfsize = Int_val (Field (li_v, 2));
2571 char *s = String_val (ptr_v);
2572 int hlmask = Int_val (hlinks_v);
2573 struct page *page = parse_pointer ("ml_postprocess", s);
2575 if (!page->u.ptr) {
2576 /* deal with loadpage failed pages */
2577 goto done;
2580 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2581 if (trylock ("ml_postprocess")) {
2582 noff = 0;
2583 goto done;
2585 if (hlmask & 2) {
2586 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2587 noff = page->slinkcount;
2589 if (page->tgen == state.gen) {
2590 showsel (page, xoff, yoff);
2592 unlock ("ml_postprocess");
2594 done:
2595 CAMLreturn (Val_int (noff));
2598 static fz_link *getlink (struct page *page, int x, int y)
2600 fz_point p;
2601 fz_matrix ctm;
2602 const fz_matrix *tctm;
2603 fz_link *link, *links;
2605 switch (page->type) {
2606 case DPDF:
2607 trimctm (page->u.pdfpage, page->pdimno);
2608 tctm = &state.pagedims[page->pdimno].tctm;
2609 links = page->u.pdfpage->links;
2610 break;
2612 case DXPS:
2613 tctm = &fz_identity;
2614 links = page->u.xpspage->links;
2615 break;
2617 default:
2618 return NULL;
2620 p.x = x;
2621 p.y = y;
2623 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2624 fz_invert_matrix (&ctm, &ctm);
2625 fz_transform_point (&p, &ctm);
2627 for (link = links; link; link = link->next) {
2628 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2629 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2630 return link;
2634 return NULL;
2637 static void ensuretext (struct page *page)
2639 if (state.gen != page->tgen) {
2640 droptext (page);
2641 page->tgen = state.gen;
2643 if (!page->text) {
2644 fz_matrix ctm;
2645 fz_device *tdev;
2647 page->text = fz_new_text_page (state.ctx);
2648 page->sheet = fz_new_text_sheet (state.ctx);
2649 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2650 ctm = pagectm (page);
2651 fz_begin_page (tdev, &fz_infinite_rect, &ctm);
2652 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2653 qsort (page->text->blocks, page->text->len,
2654 sizeof (*page->text->blocks), compareblocks);
2655 fz_end_page (tdev);
2656 fz_free_device (tdev);
2660 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2662 CAMLparam2 (start_page_v, dir_v);
2663 CAMLlocal1 (ret_v);
2664 int i, dir = Int_val (dir_v);
2665 int start_page = Int_val (start_page_v);
2666 int end_page = dir > 0 ? state.pagecount : -1;
2668 ret_v = Val_int (0);
2669 if (!(state.type == DPDF || state.type == DXPS)) {
2670 goto done;
2673 lock ("ml_findpage_with_links");
2674 for (i = start_page + dir; i != end_page; i += dir) {
2675 int found;
2677 switch (state.type) {
2678 case DPDF:
2680 pdf_page *page = NULL;
2682 fz_try (state.ctx) {
2683 page = pdf_load_page (state.u.pdf, i);
2684 found = !!page->links;
2686 fz_catch (state.ctx) {
2687 found = 0;
2689 if (page) {
2690 freepdfpage (page);
2693 break;
2694 case DXPS:
2696 xps_page *page = xps_load_page (state.u.xps, i);
2697 found = !!page->links;
2698 freexpspage (page);
2700 break;
2702 default:
2703 ARSERT (0 && "invalid document type");
2706 if (found) {
2707 ret_v = caml_alloc_small (1, 1);
2708 Field (ret_v, 0) = Val_int (i);
2709 goto unlock;
2712 unlock:
2713 unlock ("ml_findpage_with_links");
2715 done:
2716 CAMLreturn (ret_v);
2719 enum { dir_first, dir_last };
2720 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2722 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2724 CAMLparam2 (ptr_v, dir_v);
2725 CAMLlocal2 (ret_v, pos_v);
2726 struct page *page;
2727 int dirtag, i, slinkindex;
2728 struct slink *found = NULL ,*slink;
2729 char *s = String_val (ptr_v);
2731 page = parse_pointer ("ml_findlink", s);
2732 ret_v = Val_int (0);
2733 if (trylock ("ml_findlink")) {
2734 goto done;
2737 ensureslinks (page);
2739 if (Is_block (dir_v)) {
2740 dirtag = Tag_val (dir_v);
2741 switch (dirtag) {
2742 case dir_first_visible:
2744 int x0, y0, dir, first_index, last_index;
2746 pos_v = Field (dir_v, 0);
2747 x0 = Int_val (Field (pos_v, 0));
2748 y0 = Int_val (Field (pos_v, 1));
2749 dir = Int_val (Field (pos_v, 2));
2751 if (dir >= 0) {
2752 dir = 1;
2753 first_index = 0;
2754 last_index = page->slinkcount;
2756 else {
2757 first_index = page->slinkcount - 1;
2758 last_index = -1;
2761 for (i = first_index; i != last_index; i += dir) {
2762 slink = &page->slinks[i];
2763 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2764 found = slink;
2765 break;
2769 break;
2771 case dir_left:
2772 slinkindex = Int_val (Field (dir_v, 0));
2773 found = &page->slinks[slinkindex];
2774 for (i = slinkindex - 1; i >= 0; --i) {
2775 slink = &page->slinks[i];
2776 if (slink->bbox.x0 < found->bbox.x0) {
2777 found = slink;
2778 break;
2781 break;
2783 case dir_right:
2784 slinkindex = Int_val (Field (dir_v, 0));
2785 found = &page->slinks[slinkindex];
2786 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2787 slink = &page->slinks[i];
2788 if (slink->bbox.x0 > found->bbox.x0) {
2789 found = slink;
2790 break;
2793 break;
2795 case dir_down:
2796 slinkindex = Int_val (Field (dir_v, 0));
2797 found = &page->slinks[slinkindex];
2798 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2799 slink = &page->slinks[i];
2800 if (slink->bbox.y0 >= found->bbox.y0) {
2801 found = slink;
2802 break;
2805 break;
2807 case dir_up:
2808 slinkindex = Int_val (Field (dir_v, 0));
2809 found = &page->slinks[slinkindex];
2810 for (i = slinkindex - 1; i >= 0; --i) {
2811 slink = &page->slinks[i];
2812 if (slink->bbox.y0 <= found->bbox.y0) {
2813 found = slink;
2814 break;
2817 break;
2820 else {
2821 dirtag = Int_val (dir_v);
2822 switch (dirtag) {
2823 case dir_first:
2824 found = page->slinks;
2825 break;
2827 case dir_last:
2828 if (page->slinks) {
2829 found = page->slinks + (page->slinkcount - 1);
2831 break;
2834 if (found) {
2835 ret_v = caml_alloc_small (2, 1);
2836 Field (ret_v, 0) = Val_int (found - page->slinks);
2839 unlock ("ml_findlink");
2840 done:
2841 CAMLreturn (ret_v);
2844 enum { uuri, ugoto, utext, uunexpected,
2845 ulaunch, unamed, uremote, uremotedest };
2847 #define LINKTOVAL \
2849 int pageno; \
2851 switch (link->dest.kind) { \
2852 case FZ_LINK_GOTO: \
2854 fz_point p; \
2856 pageno = link->dest.ld.gotor.page; \
2857 p.x = 0; \
2858 p.y = 0; \
2860 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2861 p.y = link->dest.ld.gotor.lt.y; \
2862 fz_transform_point (&p, &pdim->lctm); \
2864 tup_v = caml_alloc_tuple (2); \
2865 ret_v = caml_alloc_small (1, ugoto); \
2866 Field (tup_v, 0) = Val_int (pageno); \
2867 Field (tup_v, 1) = Val_int (p.y); \
2868 Field (ret_v, 0) = tup_v; \
2870 break; \
2872 case FZ_LINK_URI: \
2873 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2874 ret_v = caml_alloc_small (1, uuri); \
2875 Field (ret_v, 0) = str_v; \
2876 break; \
2878 case FZ_LINK_LAUNCH: \
2879 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2880 ret_v = caml_alloc_small (1, ulaunch); \
2881 Field (ret_v, 0) = str_v; \
2882 break; \
2884 case FZ_LINK_NAMED: \
2885 str_v = caml_copy_string (link->dest.ld.named.named); \
2886 ret_v = caml_alloc_small (1, unamed); \
2887 Field (ret_v, 0) = str_v; \
2888 break; \
2890 case FZ_LINK_GOTOR: \
2892 int rty; \
2894 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2895 pageno = link->dest.ld.gotor.page; \
2896 if (pageno == -1) { \
2897 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2898 rty = uremotedest; \
2900 else { \
2901 gr_v = Val_int (pageno); \
2902 rty = uremote; \
2904 tup_v = caml_alloc_tuple (2); \
2905 ret_v = caml_alloc_small (1, rty); \
2906 Field (tup_v, 0) = str_v; \
2907 Field (tup_v, 1) = gr_v; \
2908 Field (ret_v, 0) = tup_v; \
2910 break; \
2912 default: \
2914 char buf[80]; \
2916 snprintf (buf, sizeof (buf), \
2917 "unhandled link kind %d", link->dest.kind); \
2918 str_v = caml_copy_string (buf); \
2919 ret_v = caml_alloc_small (1, uunexpected); \
2920 Field (ret_v, 0) = str_v; \
2922 break; \
2926 CAMLprim value ml_getlink (value ptr_v, value n_v)
2928 CAMLparam2 (ptr_v, n_v);
2929 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2930 fz_link *link;
2931 struct page *page;
2932 struct pagedim *pdim;
2933 char *s = String_val (ptr_v);
2935 ret_v = Val_int (0);
2936 if (trylock ("ml_getlink")) {
2937 goto done;
2940 page = parse_pointer ("ml_getlink", s);
2941 ensureslinks (page);
2942 pdim = &state.pagedims[page->pdimno];
2943 link = page->slinks[Int_val (n_v)].link;
2944 LINKTOVAL;
2946 unlock ("ml_getlink");
2947 done:
2948 CAMLreturn (ret_v);
2951 CAMLprim value ml_getlinkcount (value ptr_v)
2953 CAMLparam1 (ptr_v);
2954 struct page *page;
2955 char *s = String_val (ptr_v);
2957 page = parse_pointer ("ml_getlinkcount", s);
2958 CAMLreturn (Val_int (page->slinkcount));
2961 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2963 CAMLparam2 (ptr_v, n_v);
2964 CAMLlocal1 (ret_v);
2965 struct page *page;
2966 struct slink *slink;
2967 char *s = String_val (ptr_v);
2969 page = parse_pointer ("ml_getlinkrect", s);
2970 ret_v = caml_alloc_tuple (4);
2971 if (trylock ("ml_getlinkrect")) {
2972 Field (ret_v, 0) = Val_int (0);
2973 Field (ret_v, 1) = Val_int (0);
2974 Field (ret_v, 2) = Val_int (0);
2975 Field (ret_v, 3) = Val_int (0);
2976 goto done;
2978 ensureslinks (page);
2980 slink = &page->slinks[Int_val (n_v)];
2981 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2982 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2983 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2984 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2985 unlock ("ml_getlinkrect");
2987 done:
2988 CAMLreturn (ret_v);
2991 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2993 CAMLparam3 (ptr_v, x_v, y_v);
2994 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2995 fz_link *link;
2996 struct page *page;
2997 char *s = String_val (ptr_v);
2998 int x = Int_val (x_v), y = Int_val (y_v);
2999 struct pagedim *pdim;
3001 ret_v = Val_int (0);
3002 if (trylock ("ml_whatsunder")) {
3003 goto done;
3006 page = parse_pointer ("ml_whatsunder", s);
3007 pdim = &state.pagedims[page->pdimno];
3008 x += pdim->bounds.x0;
3009 y += pdim->bounds.y0;
3010 link = getlink (page, x, y);
3011 if (link) {
3012 LINKTOVAL;
3014 else {
3015 fz_rect *b;
3016 fz_page_block *pageb;
3017 fz_text_block *block;
3019 ensuretext (page);
3020 for (pageb = page->text->blocks;
3021 pageb < page->text->blocks + page->text->len;
3022 ++pageb) {
3023 fz_text_line *line;
3024 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3025 block = pageb->u.text;
3027 b = &block->bbox;
3028 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3029 continue;
3031 for (line = block->lines;
3032 line < block->lines + block->len;
3033 ++line) {
3034 fz_text_span *span;
3036 b = &line->bbox;
3037 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3038 continue;
3040 for (span = line->first_span; span; span = span->next) {
3041 int charnum;
3043 b = &span->bbox;
3044 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3045 continue;
3047 for (charnum = 0; charnum < span->len; ++charnum) {
3048 fz_rect bbox;
3049 fz_text_char_bbox (&bbox, span, charnum);
3050 b = &bbox;
3052 if (x >= b->x0 && x <= b->x1
3053 && y >= b->y0 && y <= b->y1) {
3054 fz_text_style *style = span->text->style;
3055 const char *n2 =
3056 style->font && style->font->name
3057 ? style->font->name
3058 : "Span has no font name"
3060 FT_FaceRec *face = style->font->ft_face;
3061 if (face && face->family_name) {
3062 char *s;
3063 char *n1 = face->family_name;
3064 size_t l1 = strlen (n1);
3065 size_t l2 = strlen (n2);
3067 if (l1 != l2 || memcmp (n1, n2, l1)) {
3068 s = malloc (l1 + l2 + 2);
3069 if (s) {
3070 memcpy (s, n2, l2);
3071 s[l2] = '=';
3072 memcpy (s + l2 + 1, n1, l1 + 1);
3073 str_v = caml_copy_string (s);
3074 free (s);
3078 if (str_v == 0) {
3079 str_v = caml_copy_string (n2);
3081 ret_v = caml_alloc_small (1, utext);
3082 Field (ret_v, 0) = str_v;
3083 goto unlock;
3090 unlock:
3091 unlock ("ml_whatsunder");
3093 done:
3094 CAMLreturn (ret_v);
3097 enum { mark_page, mark_block, mark_line, mark_word };
3099 static int uninteresting (int c)
3101 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3102 || ispunct (c);
3105 CAMLprim value ml_clearmark (value ptr_v)
3107 CAMLparam1 (ptr_v);
3108 char *s = String_val (ptr_v);
3109 struct page *page;
3111 if (trylock ("ml_clearmark")) {
3112 goto done;
3115 page = parse_pointer ("ml_clearmark", s);
3116 page->fmark.span = NULL;
3117 page->lmark.span = NULL;
3118 page->fmark.i = 0;
3119 page->lmark.i = 0;
3121 unlock ("ml_clearmark");
3122 done:
3123 CAMLreturn (Val_unit);
3126 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3128 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3129 CAMLlocal1 (ret_v);
3130 fz_rect *b;
3131 struct page *page;
3132 fz_text_line *line;
3133 fz_page_block *pageb;
3134 fz_text_block *block;
3135 struct pagedim *pdim;
3136 int mark = Int_val (mark_v);
3137 char *s = String_val (ptr_v);
3138 int x = Int_val (x_v), y = Int_val (y_v);
3140 ret_v = Val_bool (0);
3141 if (trylock ("ml_markunder")) {
3142 goto done;
3145 page = parse_pointer ("ml_markunder", s);
3146 pdim = &state.pagedims[page->pdimno];
3148 ensuretext (page);
3150 if (mark == mark_page) {
3151 int i;
3152 fz_page_block *pb1 = NULL, *pb2 = NULL;
3154 for (i = 0; i < page->text->len; ++i) {
3155 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3156 pb1 = &page->text->blocks[i];
3157 break;
3160 if (!pb1) goto unlock;
3162 for (i = page->text->len - 1; i >= 0; --i) {
3163 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3164 pb2 = &page->text->blocks[i];
3165 break;
3168 if (!pb2) goto unlock;
3170 block = pb1->u.text;
3172 page->fmark.i = 0;
3173 page->fmark.span = block->lines->first_span;
3175 block = pb2->u.text;
3176 line = &block->lines[block->len - 1];
3177 page->lmark.i = line->last_span->len - 1;
3178 page->lmark.span = line->last_span;
3179 ret_v = Val_bool (1);
3180 goto unlock;
3183 x += pdim->bounds.x0;
3184 y += pdim->bounds.y0;
3186 for (pageb = page->text->blocks;
3187 pageb < page->text->blocks + page->text->len;
3188 ++pageb) {
3189 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3190 block = pageb->u.text;
3192 b = &block->bbox;
3193 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3194 continue;
3196 if (mark == mark_block) {
3197 page->fmark.i = 0;
3198 page->fmark.span = block->lines->first_span;
3200 line = &block->lines[block->len - 1];
3201 page->lmark.i = line->last_span->len - 1;
3202 page->lmark.span = line->last_span;
3203 ret_v = Val_bool (1);
3204 goto unlock;
3207 for (line = block->lines;
3208 line < block->lines + block->len;
3209 ++line) {
3210 fz_text_span *span;
3212 b = &line->bbox;
3213 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3214 continue;
3216 if (mark == mark_line) {
3217 page->fmark.i = 0;
3218 page->fmark.span = line->first_span;
3220 page->lmark.i = line->last_span->len - 1;
3221 page->lmark.span = line->last_span;
3222 ret_v = Val_bool (1);
3223 goto unlock;
3226 for (span = line->first_span; span; span = span->next) {
3227 int charnum;
3229 b = &span->bbox;
3230 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3231 continue;
3233 for (charnum = 0; charnum < span->len; ++charnum) {
3234 fz_rect bbox;
3235 fz_text_char_bbox (&bbox, span, charnum);
3236 b = &bbox;
3238 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3239 /* unicode ftw */
3240 int charnum2, charnum3 = -1, charnum4 = -1;
3242 if (uninteresting (span->text[charnum].c)) goto unlock;
3244 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3245 if (uninteresting (span->text[charnum2].c)) {
3246 charnum3 = charnum2 + 1;
3247 break;
3250 if (charnum3 == -1) charnum3 = 0;
3252 for (charnum2 = charnum + 1;
3253 charnum2 < span->len;
3254 ++charnum2) {
3255 if (uninteresting (span->text[charnum2].c)) break;
3256 charnum4 = charnum2;
3258 if (charnum4 == -1) goto unlock;
3260 page->fmark.i = charnum3;
3261 page->fmark.span = span;
3263 page->lmark.i = charnum4;
3264 page->lmark.span = span;
3265 ret_v = Val_bool (1);
3266 goto unlock;
3272 unlock:
3273 if (!Bool_val (ret_v)) {
3274 page->fmark.span = NULL;
3275 page->lmark.span = NULL;
3276 page->fmark.i = 0;
3277 page->lmark.i = 0;
3279 unlock ("ml_markunder");
3281 done:
3282 CAMLreturn (ret_v);
3285 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3287 CAMLparam3 (ptr_v, x_v, y_v);
3288 CAMLlocal2 (ret_v, res_v);
3289 fz_rect *b = NULL;
3290 struct page *page;
3291 fz_page_block *pageb;
3292 struct pagedim *pdim;
3293 char *s = String_val (ptr_v);
3294 int x = Int_val (x_v), y = Int_val (y_v);
3296 ret_v = Val_int (0);
3297 if (trylock ("ml_rectofblock")) {
3298 goto done;
3301 page = parse_pointer ("ml_rectofblock", s);
3302 pdim = &state.pagedims[page->pdimno];
3303 x += pdim->bounds.x0;
3304 y += pdim->bounds.y0;
3306 ensuretext (page);
3308 for (pageb = page->text->blocks;
3309 pageb < page->text->blocks + page->text->len;
3310 ++pageb) {
3311 switch (pageb->type) {
3312 case FZ_PAGE_BLOCK_TEXT:
3313 b = &pageb->u.text->bbox;
3314 break;
3316 case FZ_PAGE_BLOCK_IMAGE:
3317 b = &pageb->u.image->bbox;
3318 break;
3320 default:
3321 continue;
3324 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3325 break;
3326 b = NULL;
3328 if (b) {
3329 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3330 ret_v = caml_alloc_small (1, 1);
3331 Store_double_field (res_v, 0, b->x0);
3332 Store_double_field (res_v, 1, b->x1);
3333 Store_double_field (res_v, 2, b->y0);
3334 Store_double_field (res_v, 3, b->y1);
3335 Field (ret_v, 0) = res_v;
3337 unlock ("ml_rectofblock");
3339 done:
3340 CAMLreturn (ret_v);
3343 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3345 CAMLparam2 (ptr_v, rect_v);
3346 fz_rect b;
3347 struct page *page;
3348 struct pagedim *pdim;
3349 char *s = String_val (ptr_v);
3350 int i, x0, x1, y0, y1, fi, li;
3351 fz_page_block *pageb;
3352 fz_text_block *block;
3353 fz_text_span *span, *fspan, *lspan;
3354 fz_text_line *line, *fline = NULL, *lline = NULL;
3356 if (trylock ("ml_seltext")) {
3357 goto done;
3360 page = parse_pointer ("ml_seltext", s);
3361 ensuretext (page);
3363 pdim = &state.pagedims[page->pdimno];
3364 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3365 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3366 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3367 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3369 if (y0 > y1) {
3370 int t = y0;
3371 y0 = y1;
3372 y1 = t;
3373 x0 = x1;
3374 x1 = t;
3377 if (0) {
3378 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3379 glColor3ub (128, 128, 128);
3380 recti (x0, y0, x1, y1);
3381 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3384 fi = page->fmark.i;
3385 fspan = page->fmark.span;
3387 li = page->lmark.i;
3388 lspan = page->lmark.span;
3390 for (pageb= page->text->blocks;
3391 pageb < page->text->blocks + page->text->len;
3392 ++pageb) {
3393 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3394 block = pageb->u.text;
3395 for (line = block->lines;
3396 line < block->lines + block->len;
3397 ++line) {
3398 fz_text_span *span;
3400 for (span = line->first_span; span; span = span->next) {
3401 for (i = 0; i < span->len; ++i) {
3402 int selected = 0;
3404 fz_text_char_bbox (&b, span, i);
3406 if (x0 >= b.x0 && x0 <= b.x1
3407 && y0 >= b.y0 && y0 <= b.y1) {
3408 fspan = span;
3409 fline = line;
3410 fi = i;
3411 selected = 1;
3413 if (x1 >= b.x0 && x1 <= b.x1
3414 && y1 >= b.y0 && y1 <= b.y1) {
3415 lspan = span;
3416 lline = line;
3417 li = i;
3418 selected = 1;
3420 if (0 && selected) {
3421 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3422 glColor3ub (128, 128, 128);
3423 recti (b.x0, b.y0, b.x1, b.y1);
3424 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3430 if (y1 < y0 || x1 < x0) {
3431 int swap = 0;
3433 if (fspan == lspan) {
3434 swap = 1;
3436 else {
3437 if (y1 < y0) {
3438 if (fline != lline) {
3439 swap = 1;
3444 if (swap) {
3445 i = fi;
3446 span = fspan;
3448 fi = li;
3449 fspan = lspan;
3451 li = i;
3452 lspan = span;
3456 page->fmark.i = fi;
3457 page->fmark.span = fspan;
3459 page->lmark.i = li;
3460 page->lmark.span = lspan;
3462 unlock ("ml_seltext");
3464 done:
3465 CAMLreturn (Val_unit);
3468 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3470 char buf[4];
3471 int i, len, ret;
3473 for (i = a; i <= b; ++i) {
3474 len = fz_runetochar (buf, span->text[i].c);
3475 ret = fwrite (buf, len, 1, f);
3477 if (ret != 1) {
3478 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3479 len, ret, strerror (errno));
3480 return -1;
3483 return 0;
3486 #ifdef __CYGWIN__
3487 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3489 caml_failwith ("ml_popen not implemented under Cygwin");
3491 #else
3492 CAMLprim value ml_popen (value command_v, value fds_v)
3494 CAMLparam2 (command_v, fds_v);
3495 CAMLlocal2 (l_v, tup_v);
3496 int ret;
3497 char *msg = NULL;
3498 value earg_v = Nothing;
3499 posix_spawnattr_t attr;
3500 posix_spawn_file_actions_t fa;
3501 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
3503 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3504 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3507 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3508 msg = "posix_spawnattr_init";
3509 goto fail1;
3512 #ifdef POSIX_SPAWN_USEVFORK
3513 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3514 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3515 goto fail;
3517 #endif
3519 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3520 int fd1, fd2;
3522 tup_v = Field (l_v, 0);
3523 fd1 = Int_val (Field (tup_v, 0));
3524 fd2 = Int_val (Field (tup_v, 1));
3525 if (fd2 < 0) {
3526 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3527 msg = "posix_spawn_file_actions_addclose";
3528 earg_v = tup_v;
3529 goto fail;
3532 else {
3533 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3534 msg = "posix_spawn_file_actions_adddup2";
3535 earg_v = tup_v;
3536 goto fail;
3541 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3542 msg = "posix_spawn";
3543 goto fail;
3546 fail:
3547 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3548 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3551 fail1:
3552 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3553 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3554 strerror (ret));
3557 if (msg)
3558 unix_error (ret, msg, earg_v);
3560 CAMLreturn (Val_unit);
3562 #endif
3564 CAMLprim value ml_copysel (value fd_v, value ptr_v, value clear_v)
3566 CAMLparam3 (fd_v, ptr_v, clear_v);
3567 FILE *f;
3568 int seen = 0;
3569 struct page *page;
3570 fz_text_line *line;
3571 fz_page_block *pageb;
3572 fz_text_block *block;
3573 int fd = Int_val (fd_v);
3574 char *s = String_val (ptr_v);
3575 int clear = Bool_val (clear_v);
3577 if (trylock ("ml_copysel")) {
3578 goto done;
3581 page = parse_pointer ("ml_sopysel", s);
3583 if (!page->fmark.span || !page->lmark.span) {
3584 fprintf (stderr, "nothing to copy\n");
3585 goto unlock;
3588 f = fdopen (fd, "w");
3589 if (!f) {
3590 fprintf (stderr, "failed to fopen sel pipe (from fd %d): %s\n",
3591 fd, strerror (errno));
3592 f = stdout;
3595 for (pageb = page->text->blocks;
3596 pageb < page->text->blocks + page->text->len;
3597 ++pageb) {
3598 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3599 block = pageb->u.text;
3600 for (line = block->lines;
3601 line < block->lines + block->len;
3602 ++line) {
3603 fz_text_span *span;
3605 for (span = line->first_span; span; span = span->next) {
3606 int a, b;
3608 seen |= span == page->fmark.span || span == page->lmark.span;
3609 a = span == page->fmark.span ? page->fmark.i : 0;
3610 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3612 if (seen) {
3613 if (pipespan (f, span, a, b)) {
3614 goto close;
3616 if (span == line->last_span) {
3617 if (putc ('\n', f) == EOF) {
3618 fprintf (stderr,
3619 "failed break line on sel pipe: %s\n",
3620 strerror (errno));
3621 goto close;
3624 if (span == page->lmark.span) {
3625 goto endloop;
3631 endloop:
3632 if (clear) {
3633 page->lmark.span = NULL;
3634 page->fmark.span = NULL;
3637 close:
3638 if (f != stdout) {
3639 int ret = fclose (f);
3640 fd = -1;
3641 if (ret == -1) {
3642 if (errno != ECHILD) {
3643 fprintf (stderr, "failed to close sel pipe: %s\n",
3644 strerror (errno));
3648 unlock:
3649 unlock ("ml_copysel");
3651 done:
3652 if (fd >= 0) {
3653 if (close (fd)) {
3654 fprintf (stderr, "failed to close sel pipe: %s\n",
3655 strerror (errno));
3658 CAMLreturn (Val_unit);
3661 CAMLprim value ml_getpdimrect (value pagedimno_v)
3663 CAMLparam1 (pagedimno_v);
3664 CAMLlocal1 (ret_v);
3665 int pagedimno = Int_val (pagedimno_v);
3666 fz_rect box;
3668 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3669 if (trylock ("ml_getpdimrect")) {
3670 box = fz_empty_rect;
3672 else {
3673 box = state.pagedims[pagedimno].mediabox;
3674 unlock ("ml_getpdimrect");
3677 Store_double_field (ret_v, 0, box.x0);
3678 Store_double_field (ret_v, 1, box.x1);
3679 Store_double_field (ret_v, 2, box.y0);
3680 Store_double_field (ret_v, 3, box.y1);
3682 CAMLreturn (ret_v);
3685 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3686 value dw_v, value cols_v)
3688 CAMLparam3 (winw_v, winh_v, dw_v);
3689 CAMLlocal1 (ret_v);
3690 int i;
3691 double zoom = -1.;
3692 double maxh = 0.0;
3693 struct pagedim *p;
3694 double winw = Int_val (winw_v);
3695 double winh = Int_val (winh_v);
3696 double dw = Int_val (dw_v);
3697 double cols = Int_val (cols_v);
3698 double pw = 1.0, ph = 1.0;
3700 if (trylock ("ml_zoom_for_height")) {
3701 goto done;
3704 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3705 double w = p->pagebox.x1 / cols;
3706 double h = p->pagebox.y1;
3707 if (h > maxh) {
3708 maxh = h;
3709 ph = h;
3710 if (state.fitmodel != FitProportional) pw = w;
3712 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3715 zoom = (((winh / ph) * pw) + dw) / winw;
3716 unlock ("ml_zoom_for_height");
3717 done:
3718 ret_v = caml_copy_double (zoom);
3719 CAMLreturn (ret_v);
3722 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3724 CAMLparam4 (pt_v, x_v, y_v, string_v);
3725 CAMLlocal1 (ret_v);
3726 int pt = Int_val(pt_v);
3727 int x = Int_val (x_v);
3728 int y = Int_val (y_v);
3729 double w;
3731 w = draw_string (state.face, pt, x, y, String_val (string_v));
3732 ret_v = caml_copy_double (w);
3733 CAMLreturn (ret_v);
3736 CAMLprim value ml_measure_string (value pt_v, value string_v)
3738 CAMLparam2 (pt_v, string_v);
3739 CAMLlocal1 (ret_v);
3740 int pt = Int_val (pt_v);
3741 double w;
3743 w = measure_string (state.face, pt, String_val (string_v));
3744 ret_v = caml_copy_double (w);
3745 CAMLreturn (ret_v);
3748 CAMLprim value ml_getpagebox (value opaque_v)
3750 CAMLparam1 (opaque_v);
3751 CAMLlocal1 (ret_v);
3752 fz_rect rect;
3753 fz_irect bbox;
3754 fz_matrix ctm;
3755 fz_device *dev;
3756 char *s = String_val (opaque_v);
3757 struct page *page = parse_pointer ("ml_getpagebox", s);
3759 ret_v = caml_alloc_tuple (4);
3760 dev = fz_new_bbox_device (state.ctx, &rect);
3761 dev->hints |= FZ_IGNORE_SHADE;
3763 switch (page->type) {
3764 case DPDF:
3765 ctm = pagectm (page);
3766 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3767 break;
3769 case DXPS:
3770 ctm = pagectm (page);
3771 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3772 break;
3774 default:
3775 rect = fz_infinite_rect;
3776 break;
3779 fz_free_device (dev);
3780 fz_round_rect (&bbox, &rect);
3781 Field (ret_v, 0) = Val_int (bbox.x0);
3782 Field (ret_v, 1) = Val_int (bbox.y0);
3783 Field (ret_v, 2) = Val_int (bbox.x1);
3784 Field (ret_v, 3) = Val_int (bbox.y1);
3786 CAMLreturn (ret_v);
3789 CAMLprim value ml_setaalevel (value level_v)
3791 CAMLparam1 (level_v);
3793 state.aalevel = Int_val (level_v);
3794 CAMLreturn (Val_unit);
3797 #undef pixel
3798 #include <X11/Xlib.h>
3799 #include <GL/glx.h>
3801 static struct {
3802 Display *dpy;
3803 GLXContext ctx;
3804 GLXDrawable drawable;
3805 } glx;
3807 #include "keysym2ucs.c"
3809 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3811 CAMLparam1 (keysym_v);
3812 CAMLlocal1 (str_v);
3813 KeySym keysym = Int_val (keysym_v);
3814 Rune rune;
3815 int len;
3816 char buf[5];
3818 rune = keysym2ucs (keysym);
3819 len = fz_runetochar (buf, rune);
3820 buf[len] = 0;
3821 str_v = caml_copy_string (buf);
3822 CAMLreturn (str_v);
3825 CAMLprim value ml_glx (value win_v)
3827 CAMLparam1 (win_v);
3828 XVisualInfo *visual;
3829 int screen, wid = Int_val (win_v);
3830 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3832 glx.dpy = XOpenDisplay (NULL);
3833 if (!glx.dpy) {
3834 caml_failwith ("XOpenDisplay");
3837 screen = DefaultScreen (glx.dpy);
3838 visual = glXChooseVisual (glx.dpy, screen, attributes);
3839 if (!visual) {
3840 XCloseDisplay (glx.dpy);
3841 glx.dpy = NULL;
3842 caml_failwith ("glXChooseVisual");
3845 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3846 XFree (visual);
3847 if (!glx.ctx) {
3848 XCloseDisplay (glx.dpy);
3849 glx.dpy = NULL;
3850 caml_failwith ("glXCreateContext");
3853 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3854 glXDestroyContext (glx.dpy, glx.ctx);
3855 XCloseDisplay (glx.dpy);
3856 glx.dpy = NULL;
3857 glx.ctx = NULL;
3858 caml_failwith ("glXMakeCurrent");
3860 glx.drawable = wid;
3861 CAMLreturn (Val_unit);
3864 CAMLprim value ml_swapb (value unit_v)
3866 CAMLparam1 (unit_v);
3867 glXSwapBuffers (glx.dpy, glx.drawable);
3868 CAMLreturn (Val_unit);
3871 CAMLprim value ml_glxsync (value unit_v)
3873 CAMLparam1 (unit_v);
3874 if (glx.dpy && glx.ctx) {
3875 glXWaitX ();
3876 glXWaitGL ();
3878 CAMLreturn (Val_unit);
3881 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3882 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3884 CAMLprim value ml_platform (value unit_v)
3886 CAMLparam1 (unit_v);
3887 int platid = piunknown;
3889 #if defined __linux__
3890 platid = pilinux;
3891 #elif defined __CYGWIN__
3892 platid = picygwin;
3893 #elif defined __DragonFly__
3894 platid = pidragonflybsd;
3895 #elif defined __FreeBSD__
3896 platid = pifreebsd;
3897 #elif defined __OpenBSD__
3898 platid = piopenbsd;
3899 #elif defined __NetBSD__
3900 platid = pinetbsd;
3901 #elif defined __sun__
3902 platid = pisun;
3903 #elif defined __APPLE__
3904 platid = piosx;
3905 #endif
3906 CAMLreturn (Val_int (platid));
3909 CAMLprim value ml_cloexec (value fd_v)
3911 CAMLparam1 (fd_v);
3912 int fd = Int_val (fd_v);
3914 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3915 uerror ("fcntl", Nothing);
3917 CAMLreturn (Val_unit);
3920 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3922 CAMLparam2 (w_v, h_v);
3923 CAMLlocal1 (ret_v);
3924 struct pbo *pbo;
3925 int w = Int_val (w_v);
3926 int h = Int_val (h_v);
3927 int cs = Int_val (cs_v);
3929 if (state.pbo_usable) {
3930 pbo = calloc (sizeof (*pbo), 1);
3931 if (!pbo) {
3932 err (1, "calloc pbo");
3935 switch (cs) {
3936 case 0:
3937 case 1:
3938 pbo->size = w*h*4;
3939 break;
3940 case 2:
3941 pbo->size = w*h*2;
3942 break;
3943 default:
3944 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3947 state.glGenBuffersARB (1, &pbo->id);
3948 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3949 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3950 NULL, GL_STREAM_DRAW);
3951 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3952 GL_READ_WRITE);
3953 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3954 if (!pbo->ptr) {
3955 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3956 state.glDeleteBuffersARB (1, &pbo->id);
3957 free (pbo);
3958 ret_v = caml_copy_string ("0");
3960 else {
3961 int res;
3962 char *s;
3964 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3965 if (res < 0) {
3966 err (1, "snprintf %" FMT_ptr " failed", pbo);
3968 s = malloc (res+1);
3969 if (!s) {
3970 err (1, "malloc %d bytes failed", res+1);
3972 res = sprintf (s, "%" FMT_ptr, pbo);
3973 if (res < 0) {
3974 err (1, "sprintf %" FMT_ptr " failed", pbo);
3976 ret_v = caml_copy_string (s);
3977 free (s);
3980 else {
3981 ret_v = caml_copy_string ("0");
3983 CAMLreturn (ret_v);
3986 CAMLprim value ml_freepbo (value s_v)
3988 CAMLparam1 (s_v);
3989 char *s = String_val (s_v);
3990 struct tile *tile = parse_pointer ("ml_freepbo", s);
3992 if (tile->pbo) {
3993 state.glDeleteBuffersARB (1, &tile->pbo->id);
3994 tile->pbo->id = -1;
3995 tile->pbo->ptr = NULL;
3996 tile->pbo->size = -1;
3998 CAMLreturn (Val_unit);
4001 CAMLprim value ml_unmappbo (value s_v)
4003 CAMLparam1 (s_v);
4004 char *s = String_val (s_v);
4005 struct tile *tile = parse_pointer ("ml_unmappbo", s);
4007 if (tile->pbo) {
4008 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4009 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4010 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4012 tile->pbo->ptr = NULL;
4013 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4015 CAMLreturn (Val_unit);
4018 static void setuppbo (void)
4020 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4021 state.pbo_usable = GGPA (glBindBufferARB)
4022 && GGPA (glUnmapBufferARB)
4023 && GGPA (glMapBufferARB)
4024 && GGPA (glBufferDataARB)
4025 && GGPA (glGenBuffersARB)
4026 && GGPA (glDeleteBuffersARB);
4027 #undef GGPA
4030 CAMLprim value ml_pbo_usable (value unit_v)
4032 CAMLparam1 (unit_v);
4033 CAMLreturn (Val_bool (state.pbo_usable));
4036 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4038 CAMLparam3 (ptr_v, x_v, y_v);
4039 CAMLlocal2 (ret_v, tup_v);
4040 struct page *page;
4041 char *s = String_val (ptr_v);
4042 int x = Int_val (x_v), y = Int_val (y_v);
4043 struct pagedim *pdim;
4044 fz_point p;
4045 fz_matrix ctm;
4047 page = parse_pointer ("ml_unproject", s);
4048 pdim = &state.pagedims[page->pdimno];
4050 ret_v = Val_int (0);
4051 if (trylock ("ml_unproject")) {
4052 goto done;
4055 switch (page->type) {
4056 case DPDF:
4057 trimctm (page->u.pdfpage, page->pdimno);
4058 break;
4060 default:
4061 break;
4063 p.x = x;
4064 p.y = y;
4066 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4067 fz_invert_matrix (&ctm, &ctm);
4068 fz_transform_point (&p, &ctm);
4070 tup_v = caml_alloc_tuple (2);
4071 ret_v = caml_alloc_small (1, 1);
4072 Field (tup_v, 0) = Val_int (p.x);
4073 Field (tup_v, 1) = Val_int (p.y);
4074 Field (ret_v, 0) = tup_v;
4076 unlock ("ml_unproject");
4077 done:
4078 CAMLreturn (ret_v);
4081 static void makestippletex (void)
4083 const char pixels[] = "\xff\xff\0\0";
4084 glGenTextures (1, &state.stid);
4085 glBindTexture (GL_TEXTURE_1D, state.stid);
4086 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4087 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4088 glTexImage1D (
4089 GL_TEXTURE_1D,
4091 GL_ALPHA,
4094 GL_ALPHA,
4095 GL_UNSIGNED_BYTE,
4096 pixels
4100 CAMLprim value ml_fz_version (value unit_v)
4102 return caml_copy_string (FZ_VERSION);
4105 CAMLprim value ml_init (value pipe_v, value params_v)
4107 CAMLparam2 (pipe_v, params_v);
4108 CAMLlocal2 (trim_v, fuzz_v);
4109 int ret;
4110 int texcount;
4111 char *fontpath;
4112 int colorspace;
4113 int mustoresize;
4114 int haspboext;
4115 struct sigaction sa;
4117 state.cr = Int_val (Field (pipe_v, 0));
4118 state.cw = Int_val (Field (pipe_v, 1));
4119 state.rotate = Int_val (Field (params_v, 0));
4120 state.fitmodel = Int_val (Field (params_v, 1));
4121 trim_v = Field (params_v, 2);
4122 texcount = Int_val (Field (params_v, 3));
4123 state.sliceheight = Int_val (Field (params_v, 4));
4124 mustoresize = Int_val (Field (params_v, 5));
4125 colorspace = Int_val (Field (params_v, 6));
4126 fontpath = String_val (Field (params_v, 7));
4128 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4129 if (!state.trimcachepath) {
4130 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4131 strerror (errno));
4133 haspboext = Bool_val (Field (params_v, 9));
4135 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4137 state.trimmargins = Bool_val (Field (trim_v, 0));
4138 fuzz_v = Field (trim_v, 1);
4139 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4140 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4141 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4142 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4144 set_tex_params (colorspace);
4146 if (*fontpath) {
4147 state.face = load_font (fontpath);
4149 else {
4150 unsigned int len;
4151 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
4153 state.face = load_builtin_font (base, len);
4155 if (!state.face) _exit (1);
4157 realloctexts (texcount);
4159 if (haspboext) {
4160 setuppbo ();
4163 makestippletex ();
4165 #ifdef __CYGWIN__
4166 sa.sa_handler = SIG_IGN;
4167 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4168 #else
4169 sa.sa_handler = SIG_DFL;
4170 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
4171 #endif
4172 if (sigemptyset (&sa.sa_mask)) {
4173 err (1, "sigemptyset");
4175 if (sigaction (SIGCHLD, &sa, NULL)) {
4176 err (1, "sigaction");
4179 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4180 if (ret) {
4181 errx (1, "pthread_create: %s", strerror (ret));
4184 CAMLreturn (Val_unit);