Add a knob contolling the way annoations are created/edited
[llpp.git] / link.c
blobfc4d2a314fb61d5f3a0a46f8d452c4145bba4e3d
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
4 #include <errno.h>
5 #include <stdio.h>
6 #include <ctype.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <signal.h>
10 #include <wchar.h>
12 #include <unistd.h>
13 #include <pthread.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/utsname.h>
19 #ifdef __CYGWIN__
20 #include <cygwin/socket.h> /* FIONREAD */
21 #else
22 #include <spawn.h>
23 #endif
25 #include <regex.h>
26 #include <stdarg.h>
27 #include <limits.h>
28 #include <inttypes.h>
30 #include <GL/gl.h>
32 #include <caml/fail.h>
33 #include <caml/alloc.h>
34 #include <caml/memory.h>
35 #include <caml/unixsupport.h>
37 #include <mupdf/fitz.h>
38 #include <mupdf/cbz.h>
39 #include <mupdf/pdf.h>
40 #include <mupdf/xps.h>
41 #include <mupdf/img.h>
43 #include <ft2build.h>
44 #include FT_FREETYPE_H
46 #ifdef USE_FONTCONFIG
47 #include <fontconfig/fontconfig.h>
48 #endif
50 #define PIGGYBACK
51 #define CACHE_PAGEREFS
53 #ifndef __USE_GNU
54 extern char **environ;
55 #endif
57 #define MIN(a,b) ((a) < (b) ? (a) : (b))
58 #define MAX(a,b) ((a) > (b) ? (a) : (b))
60 #if defined __GNUC__
61 #define NORETURN_ATTR __attribute__ ((noreturn))
62 #define UNUSED_ATTR __attribute__ ((unused))
63 #if !defined __clang__
64 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
65 #else
66 #define OPTIMIZE_ATTR(n)
67 #endif
68 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
69 #else
70 #define NORETURN_ATTR
71 #define UNUSED_ATTR
72 #define OPTIMIZE_ATTR(n)
73 #define GCC_FMT_ATTR(a, b)
74 #endif
76 #define FMT_s "zu"
78 #define FMT_ptr PRIxPTR
79 #define SCN_ptr SCNxPTR
80 #define FMT_ptr_cast(p) ((uintptr_t) (p))
81 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
83 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
84 err (int exitcode, const char *fmt, ...)
86 va_list ap;
87 int savederrno;
89 savederrno = errno;
90 va_start (ap, fmt);
91 vfprintf (stderr, fmt, ap);
92 va_end (ap);
93 fprintf (stderr, ": %s\n", strerror (savederrno));
94 fflush (stderr);
95 _exit (exitcode);
98 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
99 errx (int exitcode, const char *fmt, ...)
101 va_list ap;
103 va_start (ap, fmt);
104 vfprintf (stderr, fmt, ap);
105 va_end (ap);
106 fputc ('\n', stderr);
107 fflush (stderr);
108 _exit (exitcode);
111 #ifndef GL_TEXTURE_RECTANGLE_ARB
112 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
113 #endif
115 #ifndef GL_BGRA
116 #define GL_BGRA 0x80E1
117 #endif
119 #ifndef GL_UNSIGNED_INT_8_8_8_8
120 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
121 #endif
123 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
124 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
125 #endif
127 #if 0
128 #define lprintf printf
129 #else
130 #define lprintf(...)
131 #endif
133 #define ARSERT(cond) for (;;) { \
134 if (!(cond)) { \
135 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
137 break; \
140 struct slice {
141 int h;
142 int texindex;
145 struct tile {
146 int w, h;
147 int slicecount;
148 int sliceheight;
149 struct pbo *pbo;
150 fz_pixmap *pixmap;
151 struct slice slices[1];
154 struct pagedim {
155 int pageno;
156 int rotate;
157 int left;
158 int tctmready;
159 fz_irect bounds;
160 fz_rect pagebox;
161 fz_rect mediabox;
162 fz_matrix ctm, zoomctm, lctm, tctm;
165 struct slink {
166 enum { SLINK, SANNOT } tag;
167 fz_irect bbox;
168 union {
169 fz_link *link;
170 pdf_annot *annot;
171 } u;
174 struct annot {
175 fz_irect bbox;
176 pdf_annot *annot;
179 enum { DNONE, DPDF, DXPS, DCBZ, DIMG };
181 struct page {
182 int tgen;
183 int sgen;
184 int agen;
185 int type;
186 int pageno;
187 int pdimno;
188 fz_text_page *text;
189 fz_text_sheet *sheet;
190 union {
191 void *ptr;
192 pdf_page *pdfpage;
193 xps_page *xpspage;
194 cbz_page *cbzpage;
195 image_page *imgpage;
196 } u;
197 fz_display_list *dlist;
198 int slinkcount;
199 struct slink *slinks;
200 int annotcount;
201 struct annot *annots;
202 struct mark {
203 int i;
204 fz_text_span *span;
205 } fmark, lmark;
206 void (*freepage) (void *);
209 struct {
210 int type;
211 int sliceheight;
212 struct pagedim *pagedims;
213 int pagecount;
214 int pagedimcount;
215 union {
216 pdf_document *pdf;
217 xps_document *xps;
218 cbz_document *cbz;
219 image_document *img;
220 } u;
221 fz_context *ctx;
222 int w, h;
224 int texindex;
225 int texcount;
226 GLuint *texids;
228 GLenum texiform;
229 GLenum texform;
230 GLenum texty;
232 fz_colorspace *colorspace;
234 struct {
235 int w, h;
236 struct slice *slice;
237 } *texowners;
239 int rotate;
240 enum { FitWidth, FitProportional, FitPage } fitmodel;
241 int trimmargins;
242 int needoutline;
243 int gen;
244 int aalevel;
246 int trimanew;
247 fz_irect trimfuzz;
248 fz_pixmap *pig;
250 pthread_t thread;
251 int csock;
252 FT_Face face;
254 void (*closedoc) (void);
255 void (*freepage) (void *);
257 char *trimcachepath;
258 int cxack;
259 int dirty;
261 GLuint stid;
263 int pbo_usable;
264 void (*glBindBufferARB) (GLenum, GLuint);
265 GLboolean (*glUnmapBufferARB) (GLenum);
266 void *(*glMapBufferARB) (GLenum, GLenum);
267 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
268 void (*glGenBuffersARB) (GLsizei, GLuint *);
269 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
271 GLfloat texcoords[8];
272 GLfloat vertices[16];
274 #ifdef CACHE_PAGEREFS
275 struct {
276 int idx;
277 int count;
278 pdf_obj **objs;
279 pdf_document *pdf;
280 } pdflut;
281 #endif
282 } state;
284 struct pbo {
285 GLuint id;
286 void *ptr;
287 size_t size;
290 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
292 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
295 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
297 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
300 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
302 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
303 m.a, m.b, m.c, m.d, m.e, m.f);
306 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
308 static void lock (const char *cap)
310 int ret = pthread_mutex_lock (&mutex);
311 if (ret) {
312 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
316 static void unlock (const char *cap)
318 int ret = pthread_mutex_unlock (&mutex);
319 if (ret) {
320 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
324 static int trylock (const char *cap)
326 int ret = pthread_mutex_trylock (&mutex);
327 if (ret && ret != EBUSY) {
328 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
330 return ret == EBUSY;
333 static void *parse_pointer (const char *cap, const char *s)
335 int ret;
336 void *ptr;
338 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
339 if (ret != 1) {
340 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
342 return ptr;
345 static double now (void)
347 struct timeval tv;
349 if (gettimeofday (&tv, NULL)) {
350 err (1, "gettimeofday");
352 return tv.tv_sec + tv.tv_usec*1e-6;
355 static int hasdata (void)
357 int ret, avail;
358 ret = ioctl (state.csock, FIONREAD, &avail);
359 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
360 return avail > 0;
363 CAMLprim value ml_hasdata (value fd_v)
365 CAMLparam1 (fd_v);
366 int ret, avail;
368 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
369 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
370 CAMLreturn (Val_bool (avail > 0));
373 static void readdata (void *p, int size)
375 ssize_t n;
377 again:
378 n = read (state.csock, p, size);
379 if (n < 0) {
380 if (errno == EINTR) goto again;
381 err (1, "read (req %d, ret %zd)", size, n);
383 if (n - size) {
384 if (!n) errx (1, "EOF while reading");
385 errx (1, "read (req %d, ret %zd)", size, n);
389 static void writedata (char *p, int size)
391 ssize_t n;
393 p[0] = (size >> 24) & 0xff;
394 p[1] = (size >> 16) & 0xff;
395 p[2] = (size >> 8) & 0xff;
396 p[3] = (size >> 0) & 0xff;
398 n = write (state.csock, p, size + 4);
399 if (n - size - 4) {
400 if (!n) errx (1, "EOF while writing data");
401 err (1, "write (req %d, ret %zd)", size + 4, n);
405 static int readlen (void)
407 unsigned char p[4];
409 readdata (p, 4);
410 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
413 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
415 int size = 200, len;
416 va_list ap;
417 char *buf;
419 buf = malloc (size);
420 for (;;) {
421 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
423 va_start (ap, fmt);
424 len = vsnprintf (buf + 4, size - 4, fmt, ap);
425 va_end (ap);
427 if (len > -1) {
428 if (len < size - 4) {
429 writedata (buf, len);
430 break;
432 else size = len + 5;
434 else {
435 err (1, "vsnprintf for `%s' failed", fmt);
437 buf = realloc (buf, size);
439 free (buf);
442 static void closepdf (void)
444 #ifdef CACHE_PAGEREFS
445 if (state.pdflut.objs) {
446 int i;
448 for (i = 0; i < state.pdflut.count; ++i) {
449 pdf_drop_obj (state.pdflut.objs[i]);
451 free (state.pdflut.objs);
452 state.pdflut.objs = NULL;
453 state.pdflut.idx = 0;
455 #endif
457 if (state.u.pdf) {
458 pdf_close_document (state.u.pdf);
459 state.u.pdf = NULL;
463 static void closexps (void)
465 if (state.u.xps) {
466 xps_close_document (state.u.xps);
467 state.u.xps = NULL;
471 static void closecbz (void)
473 if (state.u.cbz) {
474 cbz_close_document (state.u.cbz);
475 state.u.cbz = NULL;
479 static void closeimg (void)
481 if (state.u.img) {
482 image_close_document (state.u.img);
483 state.u.img = NULL;
487 static void freepdfpage (void *ptr)
489 pdf_free_page (state.u.pdf, ptr);
492 static void freeemptyxxxpage (void *ptr)
494 (void) ptr;
497 static void freexpspage (void *ptr)
499 xps_free_page (state.u.xps, ptr);
502 static void freecbzpage (void *ptr)
504 cbz_free_page (state.u.cbz, ptr);
507 static void freeimgpage (void *ptr)
509 image_free_page (state.u.img, ptr);
512 static int openxref (char *filename, char *password)
514 int i, len;
516 for (i = 0; i < state.texcount; ++i) {
517 state.texowners[i].w = -1;
518 state.texowners[i].slice = NULL;
521 if (state.closedoc) state.closedoc ();
523 state.dirty = 0;
524 len = strlen (filename);
526 state.type = DPDF;
528 size_t j;
529 struct {
530 char *ext;
531 int type;
532 } tbl[] = {
533 { "pdf", DPDF },
534 { "xps", DXPS },
535 { "zip", DCBZ },
536 { "cbz", DCBZ },
537 { "jpg", DIMG },
538 { "jpeg", DIMG },
539 { "png", DIMG }
542 for (j = 0; j < sizeof (tbl) / sizeof (*tbl); ++j) {
543 const char *ext = tbl[j].ext;
544 int len2 = strlen (ext);
546 if (len2 < len && !strcasecmp (ext, filename + len - len2)) {
547 state.type = tbl[j].type;
548 break;
553 if (state.pagedims) {
554 free (state.pagedims);
555 state.pagedims = NULL;
557 state.pagedimcount = 0;
559 fz_set_aa_level (state.ctx, state.aalevel);
560 switch (state.type) {
561 case DPDF:
562 state.u.pdf = pdf_open_document (state.ctx, filename);
563 if (pdf_needs_password (state.u.pdf)) {
564 if (password && !*password) {
565 printd ("pass");
566 return 0;
568 else {
569 int ok = pdf_authenticate_password (state.u.pdf, password);
570 if (!ok) {
571 printd ("pass fail");
572 return 0;
576 state.pagecount = pdf_count_pages (state.u.pdf);
577 state.closedoc = closepdf;
578 state.freepage = freepdfpage;
579 break;
581 case DXPS:
582 state.u.xps = xps_open_document (state.ctx, filename);
583 state.pagecount = xps_count_pages (state.u.xps);
584 state.closedoc = closexps;
585 state.freepage = freexpspage;
586 break;
588 case DCBZ:
589 state.u.cbz = cbz_open_document (state.ctx, filename);
590 state.pagecount = cbz_count_pages (state.u.cbz);
591 state.closedoc = closecbz;
592 state.freepage = freecbzpage;
593 break;
595 case DIMG:
596 state.u.img = image_open_document (state.ctx, filename);
597 state.pagecount = 1;
598 state.closedoc = closeimg;
599 state.freepage = freeimgpage;
600 break;
602 return 1;
605 static void pdfinfo (void)
607 if (state.type == DPDF) {
608 pdf_obj *infoobj;
610 printd ("info PDF version\t%d.%d",
611 state.u.pdf->version / 10, state.u.pdf->version % 10);
613 infoobj = pdf_dict_gets (pdf_trailer (state.u.pdf), "Info");
614 if (infoobj) {
615 unsigned int i;
616 char *s;
617 char *items[] = { "Title", "Author", "Creator",
618 "Producer", "CreationDate" };
620 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
621 pdf_obj *obj = pdf_dict_gets (infoobj, items[i]);
622 s = pdf_to_utf8 (state.u.pdf, obj);
623 if (*s) printd ("info %s\t%s", items[i], s);
624 fz_free (state.ctx, s);
627 printd ("infoend");
631 static void unlinktile (struct tile *tile)
633 int i;
635 for (i = 0; i < tile->slicecount; ++i) {
636 struct slice *s = &tile->slices[i];
638 if (s->texindex != -1) {
639 if (state.texowners[s->texindex].slice == s) {
640 state.texowners[s->texindex].slice = NULL;
646 static void freepage (struct page *page)
648 if (page->text) {
649 fz_free_text_page (state.ctx, page->text);
651 if (page->sheet) {
652 fz_free_text_sheet (state.ctx, page->sheet);
654 if (page->slinks) {
655 free (page->slinks);
657 fz_drop_display_list (state.ctx, page->dlist);
658 page->freepage (page->u.ptr);
659 free (page);
662 static void freetile (struct tile *tile)
664 unlinktile (tile);
665 if (!tile->pbo) {
666 #ifndef PIGGYBACK
667 fz_drop_pixmap (state.ctx, tile->pixmap);
668 #else
669 if (state.pig) {
670 fz_drop_pixmap (state.ctx, state.pig);
672 state.pig = tile->pixmap;
673 #endif
675 else {
676 free (tile->pbo);
677 fz_drop_pixmap (state.ctx, tile->pixmap);
679 free (tile);
682 #ifdef __ALTIVEC__
683 #include <stdint.h>
684 #include <altivec.h>
686 static int cacheline32bytes;
688 static void __attribute__ ((constructor)) clcheck (void)
690 char **envp = environ;
691 unsigned long *auxv;
693 while (*envp++);
695 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
696 if (*auxv == 19) {
697 cacheline32bytes = auxv[1] == 32;
698 return;
703 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
705 size_t size = pixmap->w * pixmap->h * pixmap->n;
706 if (cacheline32bytes && size > 32) {
707 intptr_t a1, a2, diff;
708 size_t sizea, i;
709 vector unsigned char v = vec_splat_u8 (-1);
710 vector unsigned char *p;
712 a1 = a2 = (intptr_t) pixmap->samples;
713 a2 = (a1 + 31) & ~31;
714 diff = a2 - a1;
715 sizea = size - diff;
716 p = (void *) a2;
718 while (a1 != a2) *(char *) a1++ = 0xff;
719 for (i = 0; i < (sizea & ~31); i += 32) {
720 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
721 vec_st (v, i, p);
722 vec_st (v, i + 16, p);
724 while (i < sizea) *((char *) a1 + i++) = 0xff;
726 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
728 #else
729 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
730 #endif
732 static void trimctm (pdf_page *page, int pindex)
734 fz_matrix ctm;
735 struct pagedim *pdim = &state.pagedims[pindex];
737 if (!pdim->tctmready) {
738 if (state.trimmargins) {
739 fz_rect realbox;
740 fz_matrix rm, sm, tm, im, ctm1;
742 fz_rotate (&rm, -pdim->rotate);
743 fz_scale (&sm, 1, -1);
744 fz_concat (&ctm, &rm, &sm);
745 realbox = pdim->mediabox;
746 fz_transform_rect (&realbox, &ctm);
747 fz_translate (&tm, -realbox.x0, -realbox.y0);
748 fz_concat (&ctm1, &ctm, &tm);
749 fz_invert_matrix (&im, &page->ctm);
750 fz_concat (&ctm, &im, &ctm1);
752 else {
753 ctm = fz_identity;
755 pdim->tctm = ctm;
756 pdim->tctmready = 1;
760 static fz_matrix pagectm (struct page *page)
762 fz_matrix ctm, tm;
764 if (page->type == DPDF) {
765 trimctm (page->u.pdfpage, page->pdimno);
766 fz_concat (&ctm,
767 &state.pagedims[page->pdimno].tctm,
768 &state.pagedims[page->pdimno].ctm);
770 else {
771 struct pagedim *pdim = &state.pagedims[page->pdimno];
773 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
774 fz_concat (&ctm, &tm, &state.pagedims[page->pdimno].ctm);
776 return ctm;
779 static void *loadpage (int pageno, int pindex)
781 fz_device *dev;
782 struct page *page;
784 page = calloc (sizeof (struct page), 1);
785 if (!page) {
786 err (1, "calloc page %d", pageno);
789 page->dlist = fz_new_display_list (state.ctx);
790 dev = fz_new_list_device (state.ctx, page->dlist);
791 fz_try (state.ctx) {
792 switch (state.type) {
793 case DPDF:
794 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
795 pdf_run_page (state.u.pdf, page->u.pdfpage, dev,
796 &fz_identity, NULL);
797 page->freepage = freepdfpage;
798 break;
800 case DXPS:
801 page->u.xpspage = xps_load_page (state.u.xps, pageno);
802 xps_run_page (state.u.xps, page->u.xpspage, dev,
803 &fz_identity, NULL);
804 page->freepage = freexpspage;
805 break;
807 case DCBZ:
808 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
809 cbz_run_page (state.u.cbz, page->u.cbzpage, dev,
810 &fz_identity, NULL);
811 page->freepage = freecbzpage;
812 break;
814 case DIMG:
815 page->u.imgpage = image_load_page (state.u.img, pageno);
816 image_run_page (state.u.img, page->u.imgpage, dev,
817 &fz_identity, NULL);
818 page->freepage = freeimgpage;
819 break;
822 fz_catch (state.ctx) {
823 page->u.ptr = NULL;
824 page->freepage = freeemptyxxxpage;
826 fz_free_device (dev);
828 page->pdimno = pindex;
829 page->pageno = pageno;
830 page->sgen = state.gen;
831 page->agen = state.gen;
832 page->tgen = state.gen;
833 page->type = state.type;
835 return page;
838 static struct tile *alloctile (int h)
840 int i;
841 int slicecount;
842 size_t tilesize;
843 struct tile *tile;
845 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
846 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
847 tile = calloc (tilesize, 1);
848 if (!tile) {
849 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
851 for (i = 0; i < slicecount; ++i) {
852 int sh = MIN (h, state.sliceheight);
853 tile->slices[i].h = sh;
854 tile->slices[i].texindex = -1;
855 h -= sh;
857 tile->slicecount = slicecount;
858 tile->sliceheight = state.sliceheight;
859 return tile;
862 #ifdef OBSCURED_OPT
863 struct obs {
864 int cured;
865 fz_irect b;
868 static void obs_fill_image (fz_device *dev, fz_image UNUSED_ATTR *image,
869 const fz_matrix *ctm, float alpha)
871 struct obs *obs = dev->user;
873 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
874 fz_irect b;
875 fz_rect rect = fz_unit_rect;
877 fz_transform_rect (&rect, ctm);
878 fz_round_rect (&b, &rect);
879 fz_intersect_irect (&b, &obs->b);
880 obs->cured = b.x0 == obs->b.x0
881 && b.x1 == obs->b.x1
882 && b.y0 == obs->b.y0
883 && b.y1 == obs->b.y1;
887 static int obscured (struct page *page, fz_irect bbox)
889 fz_rect rect;
890 fz_matrix ctm;
891 fz_device dev;
892 struct obs obs;
894 memset (&dev, 0, sizeof (dev));
895 memset (&obs, 0, sizeof (obs));
896 dev.hints = 0;
897 dev.flags = 0;
898 dev.user = &obs;
899 dev.ctx = state.ctx;
900 dev.fill_image = obs_fill_image;
901 obs.b = bbox;
902 fz_rect_from_irect (&rect, &bbox);
903 ctm = pagectm (page);
904 fz_run_display_list (page->dlist, &dev, &ctm, &rect, NULL);
905 return obs.cured;
907 #define OBSCURED obscured
908 #else
909 #define OBSCURED(a, b) 0
910 #endif
912 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
913 struct pbo *pbo)
915 fz_rect rect;
916 fz_irect bbox;
917 fz_matrix ctm;
918 fz_device *dev;
919 struct tile *tile;
920 struct pagedim *pdim;
922 tile = alloctile (h);
923 pdim = &state.pagedims[page->pdimno];
925 bbox = pdim->bounds;
926 bbox.x0 += x;
927 bbox.y0 += y;
928 bbox.x1 = bbox.x0 + w;
929 bbox.y1 = bbox.y0 + h;
931 if (state.pig) {
932 if (state.pig->w == w
933 && state.pig->h == h
934 && state.pig->colorspace == state.colorspace) {
935 tile->pixmap = state.pig;
936 tile->pixmap->x = bbox.x0;
937 tile->pixmap->y = bbox.y0;
939 else {
940 fz_drop_pixmap (state.ctx, state.pig);
942 state.pig = NULL;
944 if (!tile->pixmap) {
945 if (pbo) {
946 tile->pixmap =
947 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
948 &bbox, pbo->ptr);
949 tile->pbo = pbo;
951 else {
952 tile->pixmap =
953 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
957 tile->w = w;
958 tile->h = h;
959 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
960 clearpixmap (tile->pixmap);
962 dev = fz_new_draw_device (state.ctx, tile->pixmap);
963 ctm = pagectm (page);
964 fz_rect_from_irect (&rect, &bbox);
965 fz_run_display_list (page->dlist, dev, &ctm, &rect, NULL);
966 fz_free_device (dev);
968 return tile;
971 #ifdef CACHE_PAGEREFS
972 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
973 thanks to Robin Watts */
974 static void
975 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
977 fz_context *ctx = doc->ctx;
978 pdf_obj *kids;
979 int i, len;
981 if (state.pdflut.idx == state.pagecount) return;
983 kids = pdf_dict_gets (node, "Kids");
984 len = pdf_array_len (kids);
986 if (len == 0)
987 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
989 if (pdf_mark_obj (node))
990 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
991 for (i = 0; i < len; i++) {
992 pdf_obj *kid = pdf_array_get (kids, i);
993 char *type = pdf_to_name (pdf_dict_gets (kid, "Type"));
994 if (*type
995 ? !strcmp (type, "Pages")
996 : pdf_dict_gets (kid, "Kids")
997 && !pdf_dict_gets (kid, "MediaBox")) {
998 pdf_collect_pages (doc, kid);
1000 else {
1001 if (*type
1002 ? strcmp (type, "Page") != 0
1003 : !pdf_dict_gets (kid, "MediaBox"))
1004 fz_warn (ctx, "non-page object in page tree (%s)", type);
1005 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (kid);
1008 pdf_unmark_obj (node);
1011 static void
1012 pdf_load_page_objs (pdf_document *doc)
1014 pdf_obj *root = pdf_dict_gets (pdf_trailer (doc), "Root");
1015 pdf_obj *node = pdf_dict_gets (root, "Pages");
1017 if (!node)
1018 fz_throw (doc->ctx, FZ_ERROR_GENERIC, "cannot find page tree");
1020 state.pdflut.idx = 0;
1021 pdf_collect_pages (doc, node);
1023 #endif
1025 static void initpdims (void)
1027 double start, end;
1028 FILE *trimf = NULL;
1029 fz_rect rootmediabox;
1030 int pageno, trim, show;
1031 int trimw = 0, cxcount;
1033 start = now ();
1035 if (state.trimmargins && state.trimcachepath) {
1036 trimf = fopen (state.trimcachepath, "rb");
1037 if (!trimf) {
1038 trimf = fopen (state.trimcachepath, "wb");
1039 trimw = 1;
1043 if (state.trimmargins || state.type == DPDF || !state.cxack)
1044 cxcount = state.pagecount;
1045 else
1046 cxcount = MIN (state.pagecount, 1);
1048 if (state.type == DPDF) {
1049 pdf_obj *obj;
1050 obj = pdf_dict_getp (pdf_trailer (state.u.pdf),
1051 "Root/Pages/MediaBox");
1052 pdf_to_rect (state.ctx, obj, &rootmediabox);
1055 #ifdef CACHE_PAGEREFS
1056 if (state.type == DPDF
1057 && (!state.pdflut.objs || state.pdflut.pdf != state.u.pdf)) {
1058 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
1059 if (!state.pdflut.objs) {
1060 err (1, "malloc pageobjs %zu %d %zu failed",
1061 sizeof (*state.pdflut.objs), cxcount,
1062 sizeof (*state.pdflut.objs) * cxcount);
1064 state.pdflut.count = cxcount;
1065 pdf_load_page_objs (state.u.pdf);
1066 state.pdflut.pdf = state.u.pdf;
1068 #endif
1070 for (pageno = 0; pageno < cxcount; ++pageno) {
1071 int rotate = 0;
1072 struct pagedim *p;
1073 fz_rect mediabox;
1075 switch (state.type) {
1076 case DPDF: {
1077 pdf_document *pdf = state.u.pdf;
1078 pdf_obj *pageref, *pageobj;
1080 #ifdef CACHE_PAGEREFS
1081 pageref = state.pdflut.objs[pageno];
1082 #else
1083 pageref = pdf_lookup_page_obj (pdf, pageno);
1084 show = !state.trimmargins && pageno % 20 == 0;
1085 if (show) {
1086 printd ("progress %f Gathering dimensions %d",
1087 (double) (pageno) / state.pagecount,
1088 pageno);
1090 #endif
1091 pageobj = pdf_resolve_indirect (pageref);
1093 if (state.trimmargins) {
1094 pdf_obj *obj;
1095 pdf_page *page;
1097 fz_try (state.ctx) {
1098 page = pdf_load_page (pdf, pageno);
1099 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
1100 trim = state.trimanew || !obj;
1101 if (trim) {
1102 fz_rect rect;
1103 fz_matrix ctm;
1104 fz_device *dev;
1106 dev = fz_new_bbox_device (state.ctx, &rect);
1107 dev->hints |= FZ_IGNORE_SHADE;
1108 fz_invert_matrix (&ctm, &page->ctm);
1109 pdf_run_page (pdf, page, dev, &fz_identity, NULL);
1110 fz_free_device (dev);
1112 rect.x0 += state.trimfuzz.x0;
1113 rect.x1 += state.trimfuzz.x1;
1114 rect.y0 += state.trimfuzz.y0;
1115 rect.y1 += state.trimfuzz.y1;
1116 fz_transform_rect (&rect, &ctm);
1117 fz_intersect_rect (&rect, &page->mediabox);
1119 if (fz_is_empty_rect (&rect)) {
1120 mediabox = page->mediabox;
1122 else {
1123 mediabox = rect;
1126 obj = pdf_new_array (pdf, 4);
1127 pdf_array_push (obj, pdf_new_real (pdf, mediabox.x0));
1128 pdf_array_push (obj, pdf_new_real (pdf, mediabox.y0));
1129 pdf_array_push (obj, pdf_new_real (pdf, mediabox.x1));
1130 pdf_array_push (obj, pdf_new_real (pdf, mediabox.y1));
1131 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
1133 else {
1134 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
1135 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
1136 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
1137 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
1140 rotate = page->rotate;
1141 pdf_free_page (pdf, page);
1143 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
1144 if (show) {
1145 printd ("progress %f Trimming %d",
1146 (double) (pageno + 1) / state.pagecount,
1147 pageno + 1);
1150 fz_catch (state.ctx) {
1151 fprintf (stderr, "failed to load page %d\n", pageno+1);
1154 else {
1155 int empty = 0;
1156 fz_rect cropbox;
1158 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "MediaBox"),
1159 &mediabox);
1160 if (fz_is_empty_rect (&mediabox)) {
1161 mediabox.x0 = 0;
1162 mediabox.y0 = 0;
1163 mediabox.x1 = 612;
1164 mediabox.y1 = 792;
1165 empty = 1;
1168 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "CropBox"),
1169 &cropbox);
1170 if (!fz_is_empty_rect (&cropbox)) {
1171 if (empty) {
1172 mediabox = cropbox;
1174 else {
1175 fz_intersect_rect (&mediabox, &cropbox);
1178 else {
1179 if (empty) {
1180 if (fz_is_empty_rect (&rootmediabox)) {
1181 fprintf (stderr,
1182 "cannot find page size for page %d\n",
1183 pageno+1);
1185 else {
1186 mediabox = rootmediabox;
1190 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
1192 break;
1195 case DXPS:
1197 xps_page *page;
1199 fz_try (state.ctx) {
1200 page = xps_load_page (state.u.xps, pageno);
1201 xps_bound_page (state.u.xps, page, &mediabox);
1202 rotate = 0;
1203 if (state.trimmargins) {
1204 fz_rect rect;
1205 fz_device *dev;
1207 dev = fz_new_bbox_device (state.ctx, &rect);
1208 dev->hints |= FZ_IGNORE_SHADE;
1209 xps_run_page (state.u.xps, page, dev,
1210 &fz_identity, NULL);
1211 fz_free_device (dev);
1213 rect.x0 += state.trimfuzz.x0;
1214 rect.x1 += state.trimfuzz.x1;
1215 rect.y0 += state.trimfuzz.y0;
1216 rect.y1 += state.trimfuzz.y1;
1217 fz_intersect_rect (&rect, &mediabox);
1219 if (!fz_is_empty_rect (&rect)) {
1220 mediabox = rect;
1223 xps_free_page (state.u.xps, page);
1224 if (!state.cxack) {
1225 printd ("progress %f loading %d",
1226 (double) (pageno + 1) / state.pagecount,
1227 pageno + 1);
1230 fz_catch (state.ctx) {
1233 break;
1235 case DCBZ:
1237 rotate = 0;
1238 mediabox.x0 = 0;
1239 mediabox.y0 = 0;
1240 mediabox.x1 = 900;
1241 mediabox.y1 = 900;
1242 if (state.trimmargins && trimw) {
1243 cbz_page *page;
1245 fz_try (state.ctx) {
1246 page = cbz_load_page (state.u.cbz, pageno);
1247 cbz_bound_page (state.u.cbz, page, &mediabox);
1248 cbz_free_page (state.u.cbz, page);
1249 printd ("progress %f Trimming %d",
1250 (double) (pageno + 1) / state.pagecount,
1251 pageno + 1);
1253 fz_catch (state.ctx) {
1254 fprintf (stderr, "failed to load page %d\n", pageno+1);
1256 if (trimf) {
1257 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1258 if (n - 1) {
1259 err (1, "fwrite trim mediabox");
1263 else {
1264 if (trimf) {
1265 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1266 if (n - 1) {
1267 err (1, "fread trim mediabox");
1270 else {
1271 if (state.cxack) {
1272 cbz_page *page;
1273 fz_try (state.ctx) {
1274 page = cbz_load_page (state.u.cbz, pageno);
1275 cbz_bound_page (state.u.cbz, page, &mediabox);
1276 cbz_free_page (state.u.cbz, page);
1278 fz_catch (state.ctx) {
1279 fprintf (stderr, "failed to load cbz page\n");
1285 break;
1287 case DIMG:
1289 image_page *page;
1291 rotate = 0;
1292 mediabox.x0 = 0;
1293 mediabox.y0 = 0;
1294 mediabox.x1 = 900;
1295 mediabox.y1 = 900;
1297 fz_try (state.ctx) {
1298 page = image_load_page (state.u.img, pageno);
1299 image_bound_page (state.u.img, page, &mediabox);
1300 image_free_page (state.u.img, page);
1302 fz_catch (state.ctx) {
1303 fprintf (stderr, "failed to load page %d\n", pageno+1);
1306 break;
1308 default:
1309 ARSERT (0 && state.type);
1312 if (state.pagedimcount == 0
1313 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1314 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1315 size_t size;
1317 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1318 state.pagedims = realloc (state.pagedims, size);
1319 if (!state.pagedims) {
1320 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1321 size, state.pagedimcount + 1);
1324 p = &state.pagedims[state.pagedimcount++];
1325 p->rotate = rotate;
1326 p->mediabox = mediabox;
1327 p->pageno = pageno;
1330 end = now ();
1331 if (state.trimmargins) {
1332 printd ("progress 1 Trimmed %d pages in %f seconds",
1333 state.pagecount, end - start);
1335 else {
1336 if (state.type == DPDF)
1337 printd ("progress 1 Processed %d pages in %f seconds",
1338 state.pagecount, end - start);
1339 else
1340 printd ("vmsg Processed %d pages in %f seconds",
1341 state.pagecount, end - start);
1343 state.trimanew = 0;
1344 if (trimf) {
1345 if (fclose (trimf)) {
1346 err (1, "fclose");
1351 static void layout (void)
1353 int pindex;
1354 fz_rect box;
1355 fz_matrix ctm, rm;
1356 struct pagedim *p = p;
1357 double zw, w, maxw = 0.0, zoom = zoom;
1359 if (state.pagedimcount == 0) return;
1361 switch (state.fitmodel) {
1362 case FitProportional:
1363 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1364 double x0, x1;
1366 p = &state.pagedims[pindex];
1367 fz_rotate (&rm, p->rotate + state.rotate);
1368 box = p->mediabox;
1369 fz_transform_rect (&box, &rm);
1371 x0 = MIN (box.x0, box.x1);
1372 x1 = MAX (box.x0, box.x1);
1374 w = x1 - x0;
1375 maxw = MAX (w, maxw);
1376 zoom = state.w / maxw;
1378 break;
1380 case FitPage:
1381 maxw = state.w;
1382 break;
1384 case FitWidth:
1385 break;
1387 default:
1388 ARSERT (0 && state.fitmodel);
1391 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1392 fz_rect rect;
1393 fz_matrix tm, sm;
1395 p = &state.pagedims[pindex];
1396 fz_rotate (&ctm, state.rotate);
1397 fz_rotate (&rm, p->rotate + state.rotate);
1398 box = p->mediabox;
1399 fz_transform_rect (&box, &rm);
1400 w = box.x1 - box.x0;
1401 switch (state.fitmodel) {
1402 case FitProportional:
1403 p->left = ((maxw - w) * zoom) / 2.0;
1404 break;
1405 case FitPage:
1407 double zh, h;
1408 zw = maxw / w;
1409 h = box.y1 - box.y0;
1410 zh = state.h / h;
1411 zoom = MIN (zw, zh);
1412 p->left = (maxw - (w * zoom)) / 2.0;
1414 break;
1415 case FitWidth:
1416 p->left = 0;
1417 zoom = state.w / w;
1418 break;
1421 fz_scale (&p->zoomctm, zoom, zoom);
1422 fz_concat (&ctm, &p->zoomctm, &ctm);
1424 fz_rotate (&rm, p->rotate);
1425 p->pagebox = p->mediabox;
1426 fz_transform_rect (&p->pagebox, &rm);
1427 p->pagebox.x1 -= p->pagebox.x0;
1428 p->pagebox.y1 -= p->pagebox.y0;
1429 p->pagebox.x0 = 0;
1430 p->pagebox.y0 = 0;
1431 rect = p->pagebox;
1432 fz_transform_rect (&rect, &ctm);
1433 fz_round_rect (&p->bounds, &rect);
1434 p->ctm = ctm;
1436 fz_translate (&tm, 0, -p->mediabox.y1);
1437 fz_scale (&sm, zoom, -zoom);
1438 fz_concat (&ctm, &tm, &sm);
1439 fz_concat (&p->lctm, &ctm, &rm);
1441 p->tctmready = 0;
1444 do {
1445 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1446 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1447 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1448 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1449 int boundw = x1 - x0;
1450 int boundh = y1 - y0;
1452 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1453 } while (p-- != state.pagedims);
1456 static
1457 struct anchor { int n; int x; int y; int w; int h; }
1458 desttoanchor (fz_link_dest *dest)
1460 int i;
1461 struct anchor a;
1462 struct pagedim *pdim = state.pagedims;
1464 a.n = -1;
1465 a.x = 0;
1466 a.y = 0;
1467 for (i = 0; i < state.pagedimcount; ++i) {
1468 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1469 break;
1470 pdim = &state.pagedims[i];
1472 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1473 fz_point p;
1474 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1475 p.x = dest->ld.gotor.lt.x;
1476 else
1477 p.x = 0.0;
1478 p.y = dest->ld.gotor.lt.y;
1479 fz_transform_point (&p, &pdim->lctm);
1480 a.x = p.x;
1481 a.y = p.y;
1483 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1484 double x0, x1, y0, y1;
1486 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1487 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1488 a.w = x1 - x0;
1489 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1490 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1491 a.h = y1 - y0;
1492 a.n = dest->ld.gotor.page;
1494 return a;
1497 static void recurse_outline (fz_outline *outline, int level)
1499 while (outline) {
1500 switch (outline->dest.kind) {
1501 case FZ_LINK_GOTO:
1503 struct anchor a = desttoanchor (&outline->dest);
1505 if (a.n >= 0) {
1506 printd ("o %d %d %d %d %s",
1507 level, a.n, a.y, a.h, outline->title);
1510 break;
1512 case FZ_LINK_URI:
1513 printd ("ou %d %" FMT_s " %s %s", level,
1514 strlen (outline->title), outline->title,
1515 outline->dest.ld.uri.uri);
1516 break;
1518 case FZ_LINK_NONE:
1519 printd ("on %d %s", level, outline->title);
1520 break;
1522 default:
1523 printd ("emsg Unhandled outline kind %d for %s\n",
1524 outline->dest.kind, outline->title);
1525 break;
1527 if (outline->down) {
1528 recurse_outline (outline->down, level + 1);
1530 outline = outline->next;
1534 static void process_outline (void)
1536 fz_outline *outline;
1538 if (!state.needoutline || !state.pagedimcount) return;
1540 state.needoutline = 0;
1541 switch (state.type) {
1542 case DPDF:
1543 outline = pdf_load_outline (state.u.pdf);
1544 break;
1545 case DXPS:
1546 outline = xps_load_outline (state.u.xps);
1547 break;
1548 default:
1549 outline = NULL;
1550 break;
1552 if (outline) {
1553 recurse_outline (outline, 0);
1554 fz_free_outline (state.ctx, outline);
1558 static char *strofspan (fz_text_span *span)
1560 char *p;
1561 char utf8[10];
1562 fz_text_char *ch;
1563 size_t size = 0, cap = 80;
1565 p = malloc (cap + 1);
1566 if (!p) return NULL;
1568 for (ch = span->text; ch < span->text + span->len; ++ch) {
1569 int n = fz_runetochar (utf8, ch->c);
1570 if (size + n > cap) {
1571 cap *= 2;
1572 p = realloc (p, cap + 1);
1573 if (!p) return NULL;
1576 memcpy (p + size, utf8, n);
1577 size += n;
1579 p[size] = 0;
1580 return p;
1583 static int matchspan (regex_t *re, fz_text_span *span,
1584 int stop, int pageno, double start)
1586 int ret;
1587 char *p;
1588 regmatch_t rm;
1589 int a, b, c;
1590 fz_rect sb, eb;
1591 fz_point p1, p2, p3, p4;
1593 p = strofspan (span);
1594 if (!p) return -1;
1596 ret = regexec (re, p, 1, &rm, 0);
1597 if (ret) {
1598 free (p);
1599 if (ret != REG_NOMATCH) {
1600 size_t size;
1601 char errbuf[80];
1602 size = regerror (ret, re, errbuf, sizeof (errbuf));
1603 printd ("msg regexec error `%.*s'",
1604 (int) size, errbuf);
1605 return -1;
1607 return 0;
1609 else {
1610 int l = span->len;
1612 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1613 c += fz_runelen (span->text[a].c);
1615 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1616 c += fz_runelen (span->text[b].c);
1619 if (fz_runelen (span->text[b].c) > 1) {
1620 b = MAX (0, b-1);
1623 fz_text_char_bbox (&sb, span, a);
1624 fz_text_char_bbox (&eb, span, b);
1626 p1.x = sb.x0;
1627 p1.y = sb.y0;
1628 p2.x = eb.x1;
1629 p2.y = sb.y0;
1630 p3.x = eb.x1;
1631 p3.y = eb.y1;
1632 p4.x = sb.x0;
1633 p4.y = eb.y1;
1635 if (!stop) {
1636 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1637 pageno, 1,
1638 p1.x, p1.y,
1639 p2.x, p2.y,
1640 p3.x, p3.y,
1641 p4.x, p4.y);
1643 printd ("progress 1 found at %d `%.*s' in %f sec",
1644 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1645 now () - start);
1647 else {
1648 printd ("match %d %d %f %f %f %f %f %f %f %f",
1649 pageno, 2,
1650 p1.x, p1.y,
1651 p2.x, p2.y,
1652 p3.x, p3.y,
1653 p4.x, p4.y);
1655 free (p);
1656 return 1;
1660 static int compareblocks (const void *l, const void *r)
1662 fz_text_block const *ls = l;
1663 fz_text_block const* rs = r;
1664 return ls->bbox.y0 - rs->bbox.y0;
1667 /* wishful thinking function */
1668 static void search (regex_t *re, int pageno, int y, int forward)
1670 int i, j;
1671 fz_matrix ctm;
1672 fz_device *tdev;
1673 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1674 fz_text_page *text;
1675 fz_text_sheet *sheet;
1676 struct pagedim *pdim, *pdimprev;
1677 int stop = 0, niters = 0;
1678 double start, end;
1680 if (!(state.type == DPDF || state.type == DXPS))
1681 return;
1683 start = now ();
1684 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1685 if (niters++ == 5) {
1686 niters = 0;
1687 if (hasdata ()) {
1688 printd ("progress 1 attention requested aborting search at %d",
1689 pageno);
1690 stop = 1;
1692 else {
1693 printd ("progress %f searching in page %d",
1694 (double) (pageno + 1) / state.pagecount,
1695 pageno);
1698 pdimprev = NULL;
1699 for (i = 0; i < state.pagedimcount; ++i) {
1700 pdim = &state.pagedims[i];
1701 if (pdim->pageno == pageno) {
1702 goto found;
1704 if (pdim->pageno > pageno) {
1705 pdim = pdimprev;
1706 goto found;
1708 pdimprev = pdim;
1710 pdim = pdimprev;
1711 found:
1713 sheet = fz_new_text_sheet (state.ctx);
1714 text = fz_new_text_page (state.ctx);
1715 tdev = fz_new_text_device (state.ctx, sheet, text);
1717 switch (state.type) {
1718 case DPDF:
1719 u.ptr = NULL;
1720 fz_try (state.ctx) {
1721 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1722 trimctm (u.pdfpage, pdim - state.pagedims);
1723 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1724 fz_begin_page (tdev, &fz_infinite_rect, &ctm);
1725 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1726 fz_end_page (tdev);
1728 fz_catch (state.ctx) {
1729 fz_free_device (tdev);
1730 u.ptr = NULL;
1731 goto nextiter;
1733 break;
1735 case DXPS:
1736 u.xpspage = xps_load_page (state.u.xps, pageno);
1737 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1738 break;
1740 default:
1741 ARSERT (0 && state.type);
1744 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1745 fz_free_device (tdev);
1747 for (j = 0; j < text->len; ++j) {
1748 int k;
1749 fz_page_block *pb;
1750 fz_text_block *block;
1752 pb = &text->blocks[forward ? j : text->len - 1 - j];
1753 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1754 block = pb->u.text;
1756 for (k = 0; k < block->len; ++k) {
1757 fz_text_line *line;
1758 fz_text_span *span;
1760 if (forward) {
1761 line = &block->lines[k];
1762 if (line->bbox.y0 < y + 1) continue;
1764 else {
1765 line = &block->lines[block->len - 1 - k];
1766 if (line->bbox.y0 > y - 1) continue;
1769 for (span = line->first_span; span; span = span->next) {
1770 switch (matchspan (re, span, stop, pageno, start)) {
1771 case 0: break;
1772 case 1: stop = 1; break;
1773 case -1: stop = 1; goto endloop;
1778 nextiter:
1779 if (forward) {
1780 pageno += 1;
1781 y = 0;
1783 else {
1784 pageno -= 1;
1785 y = INT_MAX;
1787 endloop:
1788 fz_free_text_page (state.ctx, text);
1789 fz_free_text_sheet (state.ctx, sheet);
1790 if (u.ptr) {
1791 state.freepage (u.ptr);
1794 end = now ();
1795 if (!stop) {
1796 printd ("progress 1 no matches %f sec", end - start);
1798 printd ("clearrects");
1801 static void set_tex_params (int colorspace)
1803 union {
1804 unsigned char b;
1805 unsigned int s;
1806 } endianness = {1};
1808 switch (colorspace) {
1809 case 0:
1810 state.texiform = GL_RGBA8;
1811 state.texform = GL_RGBA;
1812 state.texty = GL_UNSIGNED_BYTE;
1813 state.colorspace = fz_device_rgb (state.ctx);
1814 break;
1815 case 1:
1816 state.texiform = GL_RGBA8;
1817 state.texform = GL_BGRA;
1818 state.texty = endianness.s > 1
1819 ? GL_UNSIGNED_INT_8_8_8_8
1820 : GL_UNSIGNED_INT_8_8_8_8_REV;
1821 state.colorspace = fz_device_bgr (state.ctx);
1822 break;
1823 case 2:
1824 state.texiform = GL_LUMINANCE_ALPHA;
1825 state.texform = GL_LUMINANCE_ALPHA;
1826 state.texty = GL_UNSIGNED_BYTE;
1827 state.colorspace = fz_device_gray (state.ctx);
1828 break;
1829 default:
1830 errx (1, "invalid colorspce %d", colorspace);
1834 static void realloctexts (int texcount)
1836 size_t size;
1838 if (texcount == state.texcount) return;
1840 if (texcount < state.texcount) {
1841 glDeleteTextures (state.texcount - texcount,
1842 state.texids + texcount);
1845 size = texcount * sizeof (*state.texids);
1846 state.texids = realloc (state.texids, size);
1847 if (!state.texids) {
1848 err (1, "realloc texids %" FMT_s, size);
1851 size = texcount * sizeof (*state.texowners);
1852 state.texowners = realloc (state.texowners, size);
1853 if (!state.texowners) {
1854 err (1, "realloc texowners %" FMT_s, size);
1856 if (texcount > state.texcount) {
1857 int i;
1859 glGenTextures (texcount - state.texcount,
1860 state.texids + state.texcount);
1861 for (i = state.texcount; i < texcount; ++i) {
1862 state.texowners[i].w = -1;
1863 state.texowners[i].slice = NULL;
1866 state.texcount = texcount;
1867 state.texindex = 0;
1870 static char *mbtoutf8 (char *s)
1872 char *p, *r;
1873 wchar_t *tmp;
1874 size_t i, ret, len;
1876 len = mbstowcs (NULL, s, strlen (s));
1877 if (len == 0) {
1878 return s;
1880 else {
1881 if (len == (size_t) -1) {
1882 return s;
1886 tmp = malloc (len * sizeof (wchar_t));
1887 if (!tmp) {
1888 return s;
1891 ret = mbstowcs (tmp, s, len);
1892 if (ret == (size_t) -1) {
1893 free (tmp);
1894 return s;
1897 len = 0;
1898 for (i = 0; i < ret; ++i) {
1899 len += fz_runelen (tmp[i]);
1902 p = r = malloc (len + 1);
1903 if (!r) {
1904 free (tmp);
1905 return s;
1908 for (i = 0; i < ret; ++i) {
1909 p += fz_runetochar (p, tmp[i]);
1911 *p = 0;
1912 free (tmp);
1913 return r;
1916 CAMLprim value ml_mbtoutf8 (value s_v)
1918 CAMLparam1 (s_v);
1919 CAMLlocal1 (ret_v);
1920 char *s, *r;
1922 s = String_val (s_v);
1923 r = mbtoutf8 (s);
1924 if (r == s) {
1925 ret_v = s_v;
1927 else {
1928 ret_v = caml_copy_string (r);
1929 free (r);
1931 CAMLreturn (ret_v);
1934 static void * mainloop (void UNUSED_ATTR *unused)
1936 char *p = NULL;
1937 int len, ret, oldlen = 0;
1939 for (;;) {
1940 len = readlen ();
1941 if (len == 0) {
1942 errx (1, "readlen returned 0");
1945 if (oldlen < len + 1) {
1946 p = realloc (p, len + 1);
1947 if (!p) {
1948 err (1, "realloc %d failed", len + 1);
1950 oldlen = len + 1;
1952 readdata (p, len);
1953 p[len] = 0;
1955 if (!strncmp ("open", p, 4)) {
1956 int wthack, off, ok = 0;
1957 char *password;
1958 char *filename;
1959 char *utf8filename;
1960 size_t filenamelen;
1962 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1963 if (ret != 2) {
1964 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1967 filename = p + 5 + off;
1968 filenamelen = strlen (filename);
1969 password = filename + filenamelen + 1;
1971 lock ("open");
1972 fz_try (state.ctx) {
1973 ok = openxref (filename, password);
1975 fz_catch (state.ctx) {
1976 utf8filename = mbtoutf8 (filename);
1977 printd ("msg Could not open %s", utf8filename);
1979 if (ok) {
1980 pdfinfo ();
1981 initpdims ();
1983 unlock ("open");
1985 if (ok) {
1986 if (!wthack) {
1987 utf8filename = mbtoutf8 (filename);
1988 printd ("msg Opened %s (press h/F1 to get help)",
1989 utf8filename);
1990 if (utf8filename != filename) {
1991 free (utf8filename);
1994 state.needoutline = 1;
1997 else if (!strncmp ("cs", p, 2)) {
1998 int i, colorspace;
2000 ret = sscanf (p + 2, " %d", &colorspace);
2001 if (ret != 1) {
2002 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
2004 lock ("cs");
2005 set_tex_params (colorspace);
2006 for (i = 0; i < state.texcount; ++i) {
2007 state.texowners[i].w = -1;
2008 state.texowners[i].slice = NULL;
2010 unlock ("cs");
2012 else if (!strncmp ("freepage", p, 8)) {
2013 void *ptr;
2015 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
2016 if (ret != 1) {
2017 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
2019 freepage (ptr);
2021 else if (!strncmp ("freetile", p, 8)) {
2022 void *ptr;
2024 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
2025 if (ret != 1) {
2026 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
2028 freetile (ptr);
2030 else if (!strncmp ("search", p, 6)) {
2031 int icase, pageno, y, len2, forward;
2032 char *pattern;
2033 regex_t re;
2035 ret = sscanf (p + 6, " %d %d %d %d,%n",
2036 &icase, &pageno, &y, &forward, &len2);
2037 if (ret != 4) {
2038 errx (1, "malformed search `%s' ret=%d", p, ret);
2041 pattern = p + 6 + len2;
2042 ret = regcomp (&re, pattern,
2043 REG_EXTENDED | (icase ? REG_ICASE : 0));
2044 if (ret) {
2045 char errbuf[80];
2046 size_t size;
2048 size = regerror (ret, &re, errbuf, sizeof (errbuf));
2049 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
2051 else {
2052 search (&re, pageno, y, forward);
2053 regfree (&re);
2056 else if (!strncmp ("geometry", p, 8)) {
2057 int w, h, fitmodel;
2059 printd ("clear");
2060 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
2061 if (ret != 3) {
2062 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
2065 lock ("geometry");
2066 state.h = h;
2067 if (w != state.w) {
2068 int i;
2069 state.w = w;
2070 for (i = 0; i < state.texcount; ++i) {
2071 state.texowners[i].slice = NULL;
2074 state.fitmodel = fitmodel;
2075 layout ();
2076 process_outline ();
2078 state.gen++;
2079 unlock ("geometry");
2080 printd ("continue %d", state.pagecount);
2082 else if (!strncmp ("reqlayout", p, 9)) {
2083 char *nameddest;
2084 int rotate, off, h;
2085 unsigned int fitmodel;
2087 printd ("clear");
2088 ret = sscanf (p + 9, " %d %u %d %n",
2089 &rotate, &fitmodel, &h, &off);
2090 if (ret != 3) {
2091 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
2093 lock ("reqlayout");
2094 if (state.rotate != rotate || state.fitmodel != fitmodel) {
2095 state.gen += 1;
2097 state.rotate = rotate;
2098 state.fitmodel = fitmodel;
2099 state.h = h;
2100 layout ();
2101 process_outline ();
2103 nameddest = p + 9 + off;
2104 if (state.type == DPDF && nameddest && *nameddest) {
2105 struct anchor a;
2106 fz_link_dest dest;
2107 pdf_obj *needle, *obj;
2109 needle = pdf_new_string (state.u.pdf, nameddest,
2110 strlen (nameddest));
2111 obj = pdf_lookup_dest (state.u.pdf, needle);
2112 if (obj) {
2113 dest = pdf_parse_link_dest (state.u.pdf, FZ_LINK_GOTO, obj);
2115 a = desttoanchor (&dest);
2116 if (a.n >= 0) {
2117 printd ("a %d %d %d", a.n, a.x, a.y);
2119 else {
2120 printd ("emsg failed to parse destination `%s'\n",
2121 nameddest);
2124 else {
2125 printd ("emsg destination `%s' not found\n",
2126 nameddest);
2128 pdf_drop_obj (needle);
2131 state.gen++;
2132 unlock ("reqlayout");
2133 printd ("continue %d", state.pagecount);
2135 else if (!strncmp ("page", p, 4)) {
2136 double a, b;
2137 struct page *page;
2138 int pageno, pindex;
2140 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
2141 if (ret != 2) {
2142 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
2145 lock ("page");
2146 a = now ();
2147 page = loadpage (pageno, pindex);
2148 b = now ();
2149 unlock ("page");
2151 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
2153 else if (!strncmp ("tile", p, 4)) {
2154 int x, y, w, h;
2155 struct page *page;
2156 struct tile *tile;
2157 double a, b;
2158 void *data;
2160 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
2161 SCN_ptr_cast (&page), &x, &y, &w, &h,
2162 SCN_ptr_cast (&data));
2163 if (ret != 6) {
2164 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
2167 lock ("tile");
2168 a = now ();
2169 tile = rendertile (page, x, y, w, h, data);
2170 b = now ();
2171 unlock ("tile");
2173 printd ("tile %d %d %" FMT_ptr " %u %f",
2174 x, y,
2175 FMT_ptr_cast (tile),
2176 tile->w * tile->h * tile->pixmap->n,
2177 b - a);
2179 else if (!strncmp ("trimset", p, 7)) {
2180 fz_irect fuzz;
2181 int trimmargins;
2183 ret = sscanf (p + 7, " %d %d %d %d %d",
2184 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
2185 if (ret != 5) {
2186 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
2188 lock ("trimset");
2189 state.trimmargins = trimmargins;
2190 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
2191 state.trimanew = 1;
2192 state.trimfuzz = fuzz;
2194 unlock ("trimset");
2196 else if (!strncmp ("settrim", p, 7)) {
2197 fz_irect fuzz;
2198 int trimmargins;
2200 ret = sscanf (p + 7, " %d %d %d %d %d",
2201 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
2202 if (ret != 5) {
2203 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
2205 printd ("clear");
2206 lock ("settrim");
2207 state.trimmargins = trimmargins;
2208 state.needoutline = 1;
2209 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
2210 state.trimanew = 1;
2211 state.trimfuzz = fuzz;
2213 state.pagedimcount = 0;
2214 free (state.pagedims);
2215 state.pagedims = NULL;
2216 initpdims ();
2217 layout ();
2218 process_outline ();
2219 unlock ("settrim");
2220 printd ("continue %d", state.pagecount);
2222 else if (!strncmp ("sliceh", p, 6)) {
2223 int h;
2225 ret = sscanf (p + 6, " %d", &h);
2226 if (ret != 1) {
2227 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
2229 if (h != state.sliceheight) {
2230 int i;
2232 state.sliceheight = h;
2233 for (i = 0; i < state.texcount; ++i) {
2234 state.texowners[i].w = -1;
2235 state.texowners[i].h = -1;
2236 state.texowners[i].slice = NULL;
2240 else if (!strncmp ("interrupt", p, 9)) {
2241 printd ("vmsg interrupted");
2243 else {
2244 errx (1, "unknown command %.*s", len, p);
2247 return 0;
2250 CAMLprim value ml_realloctexts (value texcount_v)
2252 CAMLparam1 (texcount_v);
2253 int ok;
2255 if (trylock ("ml_realloctexts")) {
2256 ok = 0;
2257 goto done;
2259 realloctexts (Int_val (texcount_v));
2260 ok = 1;
2261 unlock ("ml_realloctexts");
2263 done:
2264 CAMLreturn (Val_bool (ok));
2267 static void recti (int x0, int y0, int x1, int y1)
2269 GLfloat *v = state.vertices;
2271 glVertexPointer (2, GL_FLOAT, 0, v);
2272 v[0] = x0; v[1] = y0;
2273 v[2] = x1; v[3] = y0;
2274 v[4] = x0; v[5] = y1;
2275 v[6] = x1; v[7] = y1;
2276 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2279 static void showsel (struct page *page, int ox, int oy)
2281 int seen = 0;
2282 fz_irect bbox;
2283 fz_rect rect;
2284 fz_text_line *line;
2285 fz_page_block *pageb;
2286 fz_text_block *block;
2287 struct mark first, last;
2288 unsigned char selcolor[] = {15,15,15,140};
2290 first = page->fmark;
2291 last = page->lmark;
2293 if (!first.span || !last.span) return;
2295 glEnable (GL_BLEND);
2296 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2297 glColor4ubv (selcolor);
2299 ox += state.pagedims[page->pdimno].bounds.x0;
2300 oy += state.pagedims[page->pdimno].bounds.y0;
2301 for (pageb = page->text->blocks;
2302 pageb < page->text->blocks + page->text->len;
2303 ++pageb) {
2304 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2305 block = pageb->u.text;
2307 for (line = block->lines;
2308 line < block->lines + block->len;
2309 ++line) {
2310 fz_text_span *span;
2311 rect = fz_empty_rect;
2313 for (span = line->first_span; span; span = span->next) {
2314 int i, j, k;
2315 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2317 j = 0;
2318 k = span->len - 1;
2320 if (span == page->fmark.span && span == page->lmark.span) {
2321 seen = 1;
2322 j = MIN (first.i, last.i);
2323 k = MAX (first.i, last.i);
2325 else {
2326 if (span == first.span) {
2327 seen = 1;
2328 j = first.i;
2330 else if (span == last.span) {
2331 seen = 1;
2332 k = last.i;
2336 if (seen) {
2337 for (i = j; i <= k; ++i) {
2338 fz_rect bbox1;
2339 fz_union_rect (&rect,
2340 fz_text_char_bbox (&bbox1, span, i));
2342 fz_round_rect (&bbox, &rect);
2343 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2344 bbox.x0,
2345 bbox.y0,
2346 bbox.x1,
2347 bbox.y1,
2348 oy, ox);
2350 recti (bbox.x0 + ox, bbox.y0 + oy,
2351 bbox.x1 + ox, bbox.y1 + oy);
2352 if (span == last.span) {
2353 goto done;
2355 rect = fz_empty_rect;
2360 done:
2361 glDisable (GL_BLEND);
2364 #include "glfont.c"
2366 static void stipplerect (fz_matrix *m,
2367 fz_point *p1,
2368 fz_point *p2,
2369 fz_point *p3,
2370 fz_point *p4,
2371 GLfloat *texcoords,
2372 GLfloat *vertices)
2374 fz_transform_point (p1, m);
2375 fz_transform_point (p2, m);
2376 fz_transform_point (p3, m);
2377 fz_transform_point (p4, m);
2379 float w, h, s, t;
2381 w = p2->x - p1->x;
2382 h = p2->y - p1->y;
2383 t = sqrtf (w*w + h*h) * .25f;
2385 w = p3->x - p2->x;
2386 h = p3->y - p2->y;
2387 s = sqrtf (w*w + h*h) * .25f;
2389 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2390 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2392 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2393 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2395 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2396 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2398 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2399 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2401 glDrawArrays (GL_LINES, 0, 8);
2404 static void highlightlinks (struct page *page, int xoff, int yoff)
2406 int i;
2407 fz_matrix ctm, tm, pm;
2408 fz_link *link, *links;
2409 GLfloat *texcoords = state.texcoords;
2410 GLfloat *vertices = state.vertices;
2412 switch (page->type) {
2413 case DPDF:
2414 links = page->u.pdfpage->links;
2415 break;
2417 case DXPS:
2418 links = page->u.xpspage->links;
2419 break;
2421 default:
2422 return;
2425 glEnable (GL_TEXTURE_1D);
2426 glEnable (GL_BLEND);
2427 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2428 glBindTexture (GL_TEXTURE_1D, state.stid);
2430 xoff -= state.pagedims[page->pdimno].bounds.x0;
2431 yoff -= state.pagedims[page->pdimno].bounds.y0;
2432 fz_translate (&tm, xoff, yoff);
2433 pm = pagectm (page);
2434 fz_concat (&ctm, &pm, &tm);
2436 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2437 glVertexPointer (2, GL_FLOAT, 0, vertices);
2439 for (link = links; link; link = link->next) {
2440 fz_point p1, p2, p3, p4;
2442 p1.x = link->rect.x0;
2443 p1.y = link->rect.y0;
2445 p2.x = link->rect.x1;
2446 p2.y = link->rect.y0;
2448 p3.x = link->rect.x1;
2449 p3.y = link->rect.y1;
2451 p4.x = link->rect.x0;
2452 p4.y = link->rect.y1;
2454 switch (link->dest.kind) {
2455 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2456 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2457 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2458 default: glColor3ub (0, 0, 0); break;
2460 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2463 for (i = 0; i < page->annotcount; ++i) {
2464 fz_point p1, p2, p3, p4;
2465 struct annot *annot = &page->annots[i];
2467 p1.x = annot->bbox.x0;
2468 p1.y = annot->bbox.y0;
2470 p2.x = annot->bbox.x1;
2471 p2.y = annot->bbox.y0;
2473 p3.x = annot->bbox.x1;
2474 p3.y = annot->bbox.y1;
2476 p4.x = annot->bbox.x0;
2477 p4.y = annot->bbox.y1;
2479 glColor3ub (0, 0, 128);
2480 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2483 glDisable (GL_BLEND);
2484 glDisable (GL_TEXTURE_1D);
2487 static int compareslinks (const void *l, const void *r)
2489 struct slink const *ls = l;
2490 struct slink const *rs = r;
2491 if (ls->bbox.y0 == rs->bbox.y0) {
2492 return rs->bbox.x0 - rs->bbox.x0;
2494 return ls->bbox.y0 - rs->bbox.y0;
2497 static void droptext (struct page *page)
2499 if (page->text) {
2500 fz_free_text_page (state.ctx, page->text);
2501 page->fmark.i = -1;
2502 page->lmark.i = -1;
2503 page->fmark.span = NULL;
2504 page->lmark.span = NULL;
2505 page->text = NULL;
2507 if (page->sheet) {
2508 fz_free_text_sheet (state.ctx, page->sheet);
2509 page->sheet = NULL;
2513 static void dropanots (struct page *page)
2515 if (page->annots) {
2516 free (page->annots);
2517 page->annots = NULL;
2518 page->annotcount = 0;
2522 static void ensureanots (struct page *page)
2524 fz_matrix ctm;
2525 int i, count = 0;
2526 size_t anotsize = sizeof (*page->annots);
2527 pdf_annot *annot;
2529 if (state.gen != page->agen) {
2530 dropanots (page);
2531 page->agen = state.gen;
2533 if (page->annots) return;
2535 switch (page->type) {
2536 case DPDF:
2537 trimctm (page->u.pdfpage, page->pdimno);
2538 fz_concat (&ctm,
2539 &state.pagedims[page->pdimno].tctm,
2540 &state.pagedims[page->pdimno].ctm);
2541 break;
2543 default:
2544 return;
2547 for (annot = pdf_first_annot (state.u.pdf, page->u.pdfpage);
2548 annot;
2549 annot = pdf_next_annot (state.u.pdf, annot)) {
2550 count++;
2553 if (count > 0) {
2554 page->annotcount = count;
2555 page->annots = calloc (count, anotsize);
2556 if (!page->annots) {
2557 err (1, "calloc annots %d", count);
2560 for (annot = pdf_first_annot (state.u.pdf, page->u.pdfpage), i = 0;
2561 annot;
2562 annot = pdf_next_annot (state.u.pdf, annot), i++) {
2563 fz_rect rect;
2565 pdf_bound_annot (state.u.pdf, annot, &rect);
2566 fz_transform_rect (&rect, &ctm);
2567 page->annots[i].annot = annot;
2568 fz_round_rect (&page->annots[i].bbox, &annot->pagerect);
2573 static void dropslinks (struct page *page)
2575 if (page->slinks) {
2576 free (page->slinks);
2577 page->slinks = NULL;
2578 page->slinkcount = 0;
2582 static void ensureslinks (struct page *page)
2584 fz_matrix ctm;
2585 int i, count;
2586 size_t slinksize = sizeof (*page->slinks);
2587 fz_link *link, *links;
2589 ensureanots (page);
2590 if (state.gen != page->sgen) {
2591 dropslinks (page);
2592 page->sgen = state.gen;
2594 if (page->slinks) return;
2596 switch (page->type) {
2597 case DPDF:
2598 links = page->u.pdfpage->links;
2599 trimctm (page->u.pdfpage, page->pdimno);
2600 fz_concat (&ctm,
2601 &state.pagedims[page->pdimno].tctm,
2602 &state.pagedims[page->pdimno].ctm);
2603 break;
2605 case DXPS:
2606 links = page->u.xpspage->links;
2607 ctm = state.pagedims[page->pdimno].ctm;
2608 break;
2610 default:
2611 return;
2614 count = page->annotcount;
2615 for (link = links; link; link = link->next) {
2616 count++;
2618 if (count > 0) {
2619 int j;
2621 page->slinkcount = count;
2622 page->slinks = calloc (count, slinksize);
2623 if (!page->slinks) {
2624 err (1, "calloc slinks %d", count);
2627 for (i = 0, link = links; link; ++i, link = link->next) {
2628 fz_rect rect;
2630 rect = link->rect;
2631 fz_transform_rect (&rect, &ctm);
2632 page->slinks[i].tag = SLINK;
2633 page->slinks[i].u.link = link;
2634 fz_round_rect (&page->slinks[i].bbox, &rect);
2636 for (j = 0; j < page->annotcount; ++j, ++i) {
2637 fz_rect rect;
2639 rect = page->annots[j].annot->pagerect;
2640 fz_transform_rect (&rect, &ctm);
2641 fz_round_rect (&page->slinks[i].bbox, &rect);
2643 page->slinks[i].tag = SANNOT;
2644 page->slinks[i].u.annot = page->annots[j].annot;
2646 qsort (page->slinks, count, slinksize, compareslinks);
2650 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2651 static void fmt_linkn (char *s, unsigned int u)
2653 unsigned int len; unsigned int q;
2654 unsigned int zma = 'z' - 'a' + 1;
2655 len = 1; q = u;
2656 while (q > zma - 1) { ++len; q /= zma; }
2657 if (s) {
2658 s += len;
2659 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2660 /* handles u == 0 */
2662 s[len] = 0;
2665 static void highlightslinks (struct page *page, int xoff, int yoff,
2666 int noff, char *targ, int tlen, int hfsize)
2668 int i;
2669 char buf[40];
2670 struct slink *slink;
2671 double x0, y0, x1, y1, w;
2673 ensureslinks (page);
2674 glColor3ub (0xc3, 0xb0, 0x91);
2675 for (i = 0; i < page->slinkcount; ++i) {
2676 fmt_linkn (buf, i + noff);
2677 if (!tlen || !strncmp (targ, buf, tlen)) {
2678 slink = &page->slinks[i];
2680 x0 = slink->bbox.x0 + xoff - 5;
2681 y1 = slink->bbox.y0 + yoff - 5;
2682 y0 = y1 + 10 + hfsize;
2683 w = measure_string (state.face, hfsize, buf);
2684 x1 = x0 + w + 10;
2685 recti (x0, y0, x1, y1);
2689 glEnable (GL_BLEND);
2690 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2691 glEnable (GL_TEXTURE_2D);
2692 glColor3ub (0, 0, 0);
2693 for (i = 0; i < page->slinkcount; ++i) {
2694 fmt_linkn (buf, i + noff);
2695 if (!tlen || !strncmp (targ, buf, tlen)) {
2696 slink = &page->slinks[i];
2698 x0 = slink->bbox.x0 + xoff;
2699 y0 = slink->bbox.y0 + yoff + hfsize;
2700 draw_string (state.face, hfsize, x0, y0, buf);
2703 glDisable (GL_TEXTURE_2D);
2704 glDisable (GL_BLEND);
2707 static void uploadslice (struct tile *tile, struct slice *slice)
2709 int offset;
2710 struct slice *slice1;
2711 unsigned char *texdata;
2713 offset = 0;
2714 for (slice1 = tile->slices; slice != slice1; slice1++) {
2715 offset += slice1->h * tile->w * tile->pixmap->n;
2717 if (slice->texindex != -1 && slice->texindex < state.texcount
2718 && state.texowners[slice->texindex].slice == slice) {
2719 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2721 else {
2722 int subimage = 0;
2723 int texindex = state.texindex++ % state.texcount;
2725 if (state.texowners[texindex].w == tile->w) {
2726 if (state.texowners[texindex].h >= slice->h) {
2727 subimage = 1;
2729 else {
2730 state.texowners[texindex].h = slice->h;
2733 else {
2734 state.texowners[texindex].h = slice->h;
2737 state.texowners[texindex].w = tile->w;
2738 state.texowners[texindex].slice = slice;
2739 slice->texindex = texindex;
2741 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2742 if (tile->pbo) {
2743 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2744 texdata = 0;
2746 else {
2747 texdata = tile->pixmap->samples;
2749 if (subimage) {
2750 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2754 tile->w,
2755 slice->h,
2756 state.texform,
2757 state.texty,
2758 texdata+offset
2761 else {
2762 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2764 state.texiform,
2765 tile->w,
2766 slice->h,
2768 state.texform,
2769 state.texty,
2770 texdata+offset
2773 if (tile->pbo) {
2774 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2779 CAMLprim value ml_begintiles (value unit_v)
2781 CAMLparam1 (unit_v);
2782 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2783 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2784 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2785 CAMLreturn (unit_v);
2788 CAMLprim value ml_endtiles (value unit_v)
2790 CAMLparam1 (unit_v);
2791 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2792 CAMLreturn (unit_v);
2795 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2797 CAMLparam2 (args_v, ptr_v);
2798 int dispx = Int_val (Field (args_v, 0));
2799 int dispy = Int_val (Field (args_v, 1));
2800 int dispw = Int_val (Field (args_v, 2));
2801 int disph = Int_val (Field (args_v, 3));
2802 int tilex = Int_val (Field (args_v, 4));
2803 int tiley = Int_val (Field (args_v, 5));
2804 char *s = String_val (ptr_v);
2805 struct tile *tile = parse_pointer ("ml_drawtile", s);
2806 int slicey, firstslice;
2807 struct slice *slice;
2808 GLfloat *texcoords = state.texcoords;
2809 GLfloat *vertices = state.vertices;
2811 firstslice = tiley / tile->sliceheight;
2812 slice = &tile->slices[firstslice];
2813 slicey = tiley % tile->sliceheight;
2815 while (disph > 0) {
2816 int dh;
2818 dh = slice->h - slicey;
2819 dh = MIN (disph, dh);
2820 uploadslice (tile, slice);
2822 texcoords[0] = tilex; texcoords[1] = slicey;
2823 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2824 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2825 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2827 vertices[0] = dispx; vertices[1] = dispy;
2828 vertices[2] = dispx+dispw; vertices[3] = dispy;
2829 vertices[4] = dispx; vertices[5] = dispy+dh;
2830 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2832 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2833 dispy += dh;
2834 disph -= dh;
2835 slice++;
2836 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2837 slicey = 0;
2839 CAMLreturn (Val_unit);
2842 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2843 value xoff_v, value yoff_v,
2844 value li_v)
2846 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2847 int xoff = Int_val (xoff_v);
2848 int yoff = Int_val (yoff_v);
2849 int noff = Int_val (Field (li_v, 0));
2850 char *targ = String_val (Field (li_v, 1));
2851 int tlen = caml_string_length (Field (li_v, 1));
2852 int hfsize = Int_val (Field (li_v, 2));
2853 char *s = String_val (ptr_v);
2854 int hlmask = Int_val (hlinks_v);
2855 struct page *page = parse_pointer ("ml_postprocess", s);
2857 if (!page->u.ptr) {
2858 /* deal with loadpage failed pages */
2859 goto done;
2862 ensureanots (page);
2864 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2865 if (trylock ("ml_postprocess")) {
2866 noff = 0;
2867 goto done;
2869 if (hlmask & 2) {
2870 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2871 noff = page->slinkcount;
2873 if (page->tgen == state.gen) {
2874 showsel (page, xoff, yoff);
2876 unlock ("ml_postprocess");
2878 done:
2879 CAMLreturn (Val_int (noff));
2882 static struct annot *getannot (struct page *page, int x, int y)
2884 int i;
2885 fz_point p;
2886 fz_matrix ctm;
2887 const fz_matrix *tctm;
2889 if (!page->annots) return NULL;
2891 switch (page->type) {
2892 case DPDF:
2893 trimctm (page->u.pdfpage, page->pdimno);
2894 tctm = &state.pagedims[page->pdimno].tctm;
2895 break;
2897 case DXPS:
2898 tctm = &fz_identity;
2899 break;
2901 default:
2902 return NULL;
2905 p.x = x;
2906 p.y = y;
2908 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2909 fz_invert_matrix (&ctm, &ctm);
2910 fz_transform_point (&p, &ctm);
2912 for (i = 0; i < page->annotcount; ++i) {
2913 struct annot *a = &page->annots[i];
2914 if (p.x >= a->annot->pagerect.x0 && p.x <= a->annot->pagerect.x1) {
2915 if (p.y >= a->annot->pagerect.y0 && p.y <= a->annot->pagerect.y1) {
2916 return a;
2920 return NULL;
2923 static fz_link *getlink (struct page *page, int x, int y)
2925 fz_point p;
2926 fz_matrix ctm;
2927 const fz_matrix *tctm;
2928 fz_link *link, *links;
2930 switch (page->type) {
2931 case DPDF:
2932 trimctm (page->u.pdfpage, page->pdimno);
2933 tctm = &state.pagedims[page->pdimno].tctm;
2934 links = page->u.pdfpage->links;
2935 break;
2937 case DXPS:
2938 tctm = &fz_identity;
2939 links = page->u.xpspage->links;
2940 break;
2942 default:
2943 return NULL;
2945 p.x = x;
2946 p.y = y;
2948 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2949 fz_invert_matrix (&ctm, &ctm);
2950 fz_transform_point (&p, &ctm);
2952 for (link = links; link; link = link->next) {
2953 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2954 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2955 return link;
2959 return NULL;
2962 static void ensuretext (struct page *page)
2964 if (state.gen != page->tgen) {
2965 droptext (page);
2966 page->tgen = state.gen;
2968 if (!page->text) {
2969 fz_matrix ctm;
2970 fz_device *tdev;
2972 page->text = fz_new_text_page (state.ctx);
2973 page->sheet = fz_new_text_sheet (state.ctx);
2974 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2975 ctm = pagectm (page);
2976 fz_begin_page (tdev, &fz_infinite_rect, &ctm);
2977 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2978 qsort (page->text->blocks, page->text->len,
2979 sizeof (*page->text->blocks), compareblocks);
2980 fz_end_page (tdev);
2981 fz_free_device (tdev);
2985 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2987 CAMLparam2 (start_page_v, dir_v);
2988 CAMLlocal1 (ret_v);
2989 int i, dir = Int_val (dir_v);
2990 int start_page = Int_val (start_page_v);
2991 int end_page = dir > 0 ? state.pagecount : -1;
2993 ret_v = Val_int (0);
2994 if (!(state.type == DPDF || state.type == DXPS)) {
2995 goto done;
2998 lock ("ml_findpage_with_links");
2999 for (i = start_page + dir; i != end_page; i += dir) {
3000 int found;
3002 switch (state.type) {
3003 case DPDF:
3005 pdf_page *page = NULL;
3007 fz_try (state.ctx) {
3008 page = pdf_load_page (state.u.pdf, i);
3009 found = !!page->links || !!page->annots;
3011 fz_catch (state.ctx) {
3012 found = 0;
3014 if (page) {
3015 freepdfpage (page);
3018 break;
3019 case DXPS:
3021 xps_page *page = xps_load_page (state.u.xps, i);
3022 found = !!page->links;
3023 freexpspage (page);
3025 break;
3027 default:
3028 ARSERT (0 && "invalid document type");
3031 if (found) {
3032 ret_v = caml_alloc_small (1, 1);
3033 Field (ret_v, 0) = Val_int (i);
3034 goto unlock;
3037 unlock:
3038 unlock ("ml_findpage_with_links");
3040 done:
3041 CAMLreturn (ret_v);
3044 enum { dir_first, dir_last };
3045 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
3047 CAMLprim value ml_findlink (value ptr_v, value dir_v)
3049 CAMLparam2 (ptr_v, dir_v);
3050 CAMLlocal2 (ret_v, pos_v);
3051 struct page *page;
3052 int dirtag, i, slinkindex;
3053 struct slink *found = NULL ,*slink;
3054 char *s = String_val (ptr_v);
3056 page = parse_pointer ("ml_findlink", s);
3057 ret_v = Val_int (0);
3058 /* This is scary we are not taking locks here ensureslinks does
3059 not modify state and given that we obtained the page it can not
3060 disappear under us either */
3061 lock ("ml_findlink");
3062 ensureslinks (page);
3064 if (Is_block (dir_v)) {
3065 dirtag = Tag_val (dir_v);
3066 switch (dirtag) {
3067 case dir_first_visible:
3069 int x0, y0, dir, first_index, last_index;
3071 pos_v = Field (dir_v, 0);
3072 x0 = Int_val (Field (pos_v, 0));
3073 y0 = Int_val (Field (pos_v, 1));
3074 dir = Int_val (Field (pos_v, 2));
3076 if (dir >= 0) {
3077 dir = 1;
3078 first_index = 0;
3079 last_index = page->slinkcount;
3081 else {
3082 first_index = page->slinkcount - 1;
3083 last_index = -1;
3086 for (i = first_index; i != last_index; i += dir) {
3087 slink = &page->slinks[i];
3088 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
3089 found = slink;
3090 break;
3094 break;
3096 case dir_left:
3097 slinkindex = Int_val (Field (dir_v, 0));
3098 found = &page->slinks[slinkindex];
3099 for (i = slinkindex - 1; i >= 0; --i) {
3100 slink = &page->slinks[i];
3101 if (slink->bbox.x0 < found->bbox.x0) {
3102 found = slink;
3103 break;
3106 break;
3108 case dir_right:
3109 slinkindex = Int_val (Field (dir_v, 0));
3110 found = &page->slinks[slinkindex];
3111 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
3112 slink = &page->slinks[i];
3113 if (slink->bbox.x0 > found->bbox.x0) {
3114 found = slink;
3115 break;
3118 break;
3120 case dir_down:
3121 slinkindex = Int_val (Field (dir_v, 0));
3122 found = &page->slinks[slinkindex];
3123 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
3124 slink = &page->slinks[i];
3125 if (slink->bbox.y0 >= found->bbox.y0) {
3126 found = slink;
3127 break;
3130 break;
3132 case dir_up:
3133 slinkindex = Int_val (Field (dir_v, 0));
3134 found = &page->slinks[slinkindex];
3135 for (i = slinkindex - 1; i >= 0; --i) {
3136 slink = &page->slinks[i];
3137 if (slink->bbox.y0 <= found->bbox.y0) {
3138 found = slink;
3139 break;
3142 break;
3145 else {
3146 dirtag = Int_val (dir_v);
3147 switch (dirtag) {
3148 case dir_first:
3149 found = page->slinks;
3150 break;
3152 case dir_last:
3153 if (page->slinks) {
3154 found = page->slinks + (page->slinkcount - 1);
3156 break;
3159 if (found) {
3160 ret_v = caml_alloc_small (2, 1);
3161 Field (ret_v, 0) = Val_int (found - page->slinks);
3164 unlock ("ml_findlink");
3165 CAMLreturn (ret_v);
3168 enum { uuri, ugoto, utext, uunexpected, ulaunch,
3169 unamed, uremote, uremotedest, uannot };
3171 #define LINKTOVAL \
3173 int pageno; \
3175 switch (link->dest.kind) { \
3176 case FZ_LINK_GOTO: \
3178 fz_point p; \
3180 pageno = link->dest.ld.gotor.page; \
3181 p.x = 0; \
3182 p.y = 0; \
3184 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
3185 p.y = link->dest.ld.gotor.lt.y; \
3186 fz_transform_point (&p, &pdim->lctm); \
3187 if (p.y < 0) p.y = 0; \
3189 tup_v = caml_alloc_tuple (2); \
3190 ret_v = caml_alloc_small (1, ugoto); \
3191 Field (tup_v, 0) = Val_int (pageno); \
3192 Field (tup_v, 1) = Val_int (p.y); \
3193 Field (ret_v, 0) = tup_v; \
3195 break; \
3197 case FZ_LINK_URI: \
3198 str_v = caml_copy_string (link->dest.ld.uri.uri); \
3199 ret_v = caml_alloc_small (1, uuri); \
3200 Field (ret_v, 0) = str_v; \
3201 break; \
3203 case FZ_LINK_LAUNCH: \
3204 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
3205 ret_v = caml_alloc_small (1, ulaunch); \
3206 Field (ret_v, 0) = str_v; \
3207 break; \
3209 case FZ_LINK_NAMED: \
3210 str_v = caml_copy_string (link->dest.ld.named.named); \
3211 ret_v = caml_alloc_small (1, unamed); \
3212 Field (ret_v, 0) = str_v; \
3213 break; \
3215 case FZ_LINK_GOTOR: \
3217 int rty; \
3219 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
3220 pageno = link->dest.ld.gotor.page; \
3221 if (pageno == -1) { \
3222 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
3223 rty = uremotedest; \
3225 else { \
3226 gr_v = Val_int (pageno); \
3227 rty = uremote; \
3229 tup_v = caml_alloc_tuple (2); \
3230 ret_v = caml_alloc_small (1, rty); \
3231 Field (tup_v, 0) = str_v; \
3232 Field (tup_v, 1) = gr_v; \
3233 Field (ret_v, 0) = tup_v; \
3235 break; \
3237 default: \
3239 char buf[80]; \
3241 snprintf (buf, sizeof (buf), \
3242 "unhandled link kind %d", link->dest.kind); \
3243 str_v = caml_copy_string (buf); \
3244 ret_v = caml_alloc_small (1, uunexpected); \
3245 Field (ret_v, 0) = str_v; \
3247 break; \
3251 CAMLprim value ml_getlink (value ptr_v, value n_v)
3253 CAMLparam2 (ptr_v, n_v);
3254 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3255 fz_link *link;
3256 struct page *page;
3257 struct pagedim *pdim;
3258 char *s = String_val (ptr_v);
3259 struct slink *slink;
3261 /* See ml_findlink for caveat */
3263 ret_v = Val_int (0);
3264 page = parse_pointer ("ml_getlink", s);
3265 ensureslinks (page);
3266 pdim = &state.pagedims[page->pdimno];
3267 slink = &page->slinks[Int_val (n_v)];
3268 if (slink->tag == SLINK) {
3269 link = slink->u.link;
3270 LINKTOVAL;
3272 else {
3273 ret_v = caml_alloc_small (1, uannot);
3274 tup_v = caml_alloc_tuple (2);
3275 Field (ret_v, 0) = tup_v;
3276 Field (tup_v, 0) = ptr_v;
3277 Field (tup_v, 1) = n_v;
3280 unlock ("ml_getlink");
3281 CAMLreturn (ret_v);
3284 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3286 CAMLparam2 (ptr_v, n_v);
3287 char *s = String_val (ptr_v);
3288 struct page *page;
3289 struct slink *slink;
3291 page = parse_pointer ("ml_getannotcontent", s);
3292 slink = &page->slinks[Int_val (n_v)];
3293 CAMLreturn (caml_copy_string (pdf_annot_contents (state.u.pdf,
3294 slink->u.annot)));
3297 CAMLprim value ml_getlinkcount (value ptr_v)
3299 CAMLparam1 (ptr_v);
3300 struct page *page;
3301 char *s = String_val (ptr_v);
3303 page = parse_pointer ("ml_getlinkcount", s);
3304 CAMLreturn (Val_int (page->slinkcount));
3307 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3309 CAMLparam2 (ptr_v, n_v);
3310 CAMLlocal1 (ret_v);
3311 struct page *page;
3312 struct slink *slink;
3313 char *s = String_val (ptr_v);
3314 /* See ml_findlink for caveat */
3316 page = parse_pointer ("ml_getlinkrect", s);
3317 ret_v = caml_alloc_tuple (4);
3318 ensureslinks (page);
3320 slink = &page->slinks[Int_val (n_v)];
3321 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3322 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3323 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3324 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3325 unlock ("ml_getlinkrect");
3326 CAMLreturn (ret_v);
3329 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3331 CAMLparam3 (ptr_v, x_v, y_v);
3332 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3333 fz_link *link;
3334 struct annot *annot;
3335 struct page *page;
3336 char *ptr = String_val (ptr_v);
3337 int x = Int_val (x_v), y = Int_val (y_v);
3338 struct pagedim *pdim;
3340 ret_v = Val_int (0);
3341 if (trylock ("ml_whatsunder")) {
3342 goto done;
3345 page = parse_pointer ("ml_whatsunder", ptr);
3346 pdim = &state.pagedims[page->pdimno];
3347 x += pdim->bounds.x0;
3348 y += pdim->bounds.y0;
3350 if (state.type == DPDF) {
3351 annot = getannot (page, x, y);
3352 if (annot) {
3353 int i, n = -1;
3355 ensureslinks (page);
3356 for (i = 0; i < page->slinkcount; ++i) {
3357 if (page->slinks[i].tag == SANNOT
3358 && page->slinks[i].u.annot == annot->annot) {
3359 n = i;
3360 break;
3363 ret_v = caml_alloc_small (1, uannot);
3364 tup_v = caml_alloc_tuple (2);
3365 Field (ret_v, 0) = tup_v;
3366 Field (tup_v, 0) = ptr_v;
3367 Field (tup_v, 1) = Val_int (n);
3368 goto unlock;
3372 link = getlink (page, x, y);
3373 if (link) {
3374 LINKTOVAL;
3376 else {
3377 fz_rect *b;
3378 fz_page_block *pageb;
3379 fz_text_block *block;
3381 ensuretext (page);
3382 for (pageb = page->text->blocks;
3383 pageb < page->text->blocks + page->text->len;
3384 ++pageb) {
3385 fz_text_line *line;
3386 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3387 block = pageb->u.text;
3389 b = &block->bbox;
3390 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3391 continue;
3393 for (line = block->lines;
3394 line < block->lines + block->len;
3395 ++line) {
3396 fz_text_span *span;
3398 b = &line->bbox;
3399 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3400 continue;
3402 for (span = line->first_span; span; span = span->next) {
3403 int charnum;
3405 b = &span->bbox;
3406 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3407 continue;
3409 for (charnum = 0; charnum < span->len; ++charnum) {
3410 fz_rect bbox;
3411 fz_text_char_bbox (&bbox, span, charnum);
3412 b = &bbox;
3414 if (x >= b->x0 && x <= b->x1
3415 && y >= b->y0 && y <= b->y1) {
3416 fz_text_style *style = span->text->style;
3417 const char *n2 =
3418 style->font && style->font->name
3419 ? style->font->name
3420 : "Span has no font name"
3422 FT_FaceRec *face = style->font->ft_face;
3423 if (face && face->family_name) {
3424 char *s;
3425 char *n1 = face->family_name;
3426 size_t l1 = strlen (n1);
3427 size_t l2 = strlen (n2);
3429 if (l1 != l2 || memcmp (n1, n2, l1)) {
3430 s = malloc (l1 + l2 + 2);
3431 if (s) {
3432 memcpy (s, n2, l2);
3433 s[l2] = '=';
3434 memcpy (s + l2 + 1, n1, l1 + 1);
3435 str_v = caml_copy_string (s);
3436 free (s);
3440 if (str_v == Val_unit) {
3441 str_v = caml_copy_string (n2);
3443 ret_v = caml_alloc_small (1, utext);
3444 Field (ret_v, 0) = str_v;
3445 goto unlock;
3452 unlock:
3453 unlock ("ml_whatsunder");
3455 done:
3456 CAMLreturn (ret_v);
3459 enum { mark_page, mark_block, mark_line, mark_word };
3461 static int uninteresting (int c)
3463 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3464 || ispunct (c);
3467 CAMLprim value ml_clearmark (value ptr_v)
3469 CAMLparam1 (ptr_v);
3470 char *s = String_val (ptr_v);
3471 struct page *page;
3473 if (trylock ("ml_clearmark")) {
3474 goto done;
3477 page = parse_pointer ("ml_clearmark", s);
3478 page->fmark.span = NULL;
3479 page->lmark.span = NULL;
3480 page->fmark.i = 0;
3481 page->lmark.i = 0;
3483 unlock ("ml_clearmark");
3484 done:
3485 CAMLreturn (Val_unit);
3488 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3490 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3491 CAMLlocal1 (ret_v);
3492 fz_rect *b;
3493 struct page *page;
3494 fz_text_line *line;
3495 fz_page_block *pageb;
3496 fz_text_block *block;
3497 struct pagedim *pdim;
3498 int mark = Int_val (mark_v);
3499 char *s = String_val (ptr_v);
3500 int x = Int_val (x_v), y = Int_val (y_v);
3502 ret_v = Val_bool (0);
3503 if (trylock ("ml_markunder")) {
3504 goto done;
3507 page = parse_pointer ("ml_markunder", s);
3508 pdim = &state.pagedims[page->pdimno];
3510 ensuretext (page);
3512 if (mark == mark_page) {
3513 int i;
3514 fz_page_block *pb1 = NULL, *pb2 = NULL;
3516 for (i = 0; i < page->text->len; ++i) {
3517 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3518 pb1 = &page->text->blocks[i];
3519 break;
3522 if (!pb1) goto unlock;
3524 for (i = page->text->len - 1; i >= 0; --i) {
3525 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3526 pb2 = &page->text->blocks[i];
3527 break;
3530 if (!pb2) goto unlock;
3532 block = pb1->u.text;
3534 page->fmark.i = 0;
3535 page->fmark.span = block->lines->first_span;
3537 block = pb2->u.text;
3538 line = &block->lines[block->len - 1];
3539 page->lmark.i = line->last_span->len - 1;
3540 page->lmark.span = line->last_span;
3541 ret_v = Val_bool (1);
3542 goto unlock;
3545 x += pdim->bounds.x0;
3546 y += pdim->bounds.y0;
3548 for (pageb = page->text->blocks;
3549 pageb < page->text->blocks + page->text->len;
3550 ++pageb) {
3551 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3552 block = pageb->u.text;
3554 b = &block->bbox;
3555 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3556 continue;
3558 if (mark == mark_block) {
3559 page->fmark.i = 0;
3560 page->fmark.span = block->lines->first_span;
3562 line = &block->lines[block->len - 1];
3563 page->lmark.i = line->last_span->len - 1;
3564 page->lmark.span = line->last_span;
3565 ret_v = Val_bool (1);
3566 goto unlock;
3569 for (line = block->lines;
3570 line < block->lines + block->len;
3571 ++line) {
3572 fz_text_span *span;
3574 b = &line->bbox;
3575 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3576 continue;
3578 if (mark == mark_line) {
3579 page->fmark.i = 0;
3580 page->fmark.span = line->first_span;
3582 page->lmark.i = line->last_span->len - 1;
3583 page->lmark.span = line->last_span;
3584 ret_v = Val_bool (1);
3585 goto unlock;
3588 for (span = line->first_span; span; span = span->next) {
3589 int charnum;
3591 b = &span->bbox;
3592 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3593 continue;
3595 for (charnum = 0; charnum < span->len; ++charnum) {
3596 fz_rect bbox;
3597 fz_text_char_bbox (&bbox, span, charnum);
3598 b = &bbox;
3600 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3601 /* unicode ftw */
3602 int charnum2, charnum3 = -1, charnum4 = -1;
3604 if (uninteresting (span->text[charnum].c)) goto unlock;
3606 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3607 if (uninteresting (span->text[charnum2].c)) {
3608 charnum3 = charnum2 + 1;
3609 break;
3612 if (charnum3 == -1) charnum3 = 0;
3614 for (charnum2 = charnum + 1;
3615 charnum2 < span->len;
3616 ++charnum2) {
3617 if (uninteresting (span->text[charnum2].c)) break;
3618 charnum4 = charnum2;
3620 if (charnum4 == -1) goto unlock;
3622 page->fmark.i = charnum3;
3623 page->fmark.span = span;
3625 page->lmark.i = charnum4;
3626 page->lmark.span = span;
3627 ret_v = Val_bool (1);
3628 goto unlock;
3634 unlock:
3635 if (!Bool_val (ret_v)) {
3636 page->fmark.span = NULL;
3637 page->lmark.span = NULL;
3638 page->fmark.i = 0;
3639 page->lmark.i = 0;
3641 unlock ("ml_markunder");
3643 done:
3644 CAMLreturn (ret_v);
3647 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3649 CAMLparam3 (ptr_v, x_v, y_v);
3650 CAMLlocal2 (ret_v, res_v);
3651 fz_rect *b = NULL;
3652 struct page *page;
3653 fz_page_block *pageb;
3654 struct pagedim *pdim;
3655 char *s = String_val (ptr_v);
3656 int x = Int_val (x_v), y = Int_val (y_v);
3658 ret_v = Val_int (0);
3659 if (trylock ("ml_rectofblock")) {
3660 goto done;
3663 page = parse_pointer ("ml_rectofblock", s);
3664 pdim = &state.pagedims[page->pdimno];
3665 x += pdim->bounds.x0;
3666 y += pdim->bounds.y0;
3668 ensuretext (page);
3670 for (pageb = page->text->blocks;
3671 pageb < page->text->blocks + page->text->len;
3672 ++pageb) {
3673 switch (pageb->type) {
3674 case FZ_PAGE_BLOCK_TEXT:
3675 b = &pageb->u.text->bbox;
3676 break;
3678 case FZ_PAGE_BLOCK_IMAGE:
3679 b = &pageb->u.image->bbox;
3680 break;
3682 default:
3683 continue;
3686 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3687 break;
3688 b = NULL;
3690 if (b) {
3691 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3692 ret_v = caml_alloc_small (1, 1);
3693 Store_double_field (res_v, 0, b->x0);
3694 Store_double_field (res_v, 1, b->x1);
3695 Store_double_field (res_v, 2, b->y0);
3696 Store_double_field (res_v, 3, b->y1);
3697 Field (ret_v, 0) = res_v;
3699 unlock ("ml_rectofblock");
3701 done:
3702 CAMLreturn (ret_v);
3705 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3707 CAMLparam2 (ptr_v, rect_v);
3708 fz_rect b;
3709 struct page *page;
3710 struct pagedim *pdim;
3711 char *s = String_val (ptr_v);
3712 int i, x0, x1, y0, y1, fi, li;
3713 fz_text_line *line;
3714 fz_page_block *pageb;
3715 fz_text_block *block;
3716 fz_text_span *span, *fspan, *lspan;
3718 if (trylock ("ml_seltext")) {
3719 goto done;
3722 page = parse_pointer ("ml_seltext", s);
3723 ensuretext (page);
3725 pdim = &state.pagedims[page->pdimno];
3726 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3727 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3728 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3729 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3731 if (y0 > y1) {
3732 int t = y0;
3733 y0 = y1;
3734 y1 = t;
3735 x0 = x1;
3736 x1 = t;
3739 if (0) {
3740 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3741 glColor3ub (128, 128, 128);
3742 recti (x0, y0, x1, y1);
3743 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3746 fi = page->fmark.i;
3747 fspan = page->fmark.span;
3749 li = page->lmark.i;
3750 lspan = page->lmark.span;
3752 for (pageb = page->text->blocks;
3753 pageb < page->text->blocks + page->text->len;
3754 ++pageb) {
3755 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3756 block = pageb->u.text;
3757 for (line = block->lines;
3758 line < block->lines + block->len;
3759 ++line) {
3761 for (span = line->first_span; span; span = span->next) {
3762 for (i = 0; i < span->len; ++i) {
3763 int selected = 0;
3765 fz_text_char_bbox (&b, span, i);
3767 if (x0 >= b.x0 && x0 <= b.x1
3768 && y0 >= b.y0 && y0 <= b.y1) {
3769 fspan = span;
3770 fi = i;
3771 selected = 1;
3773 if (x1 >= b.x0 && x1 <= b.x1
3774 && y1 >= b.y0 && y1 <= b.y1) {
3775 lspan = span;
3776 li = i;
3777 selected = 1;
3779 if (0 && selected) {
3780 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3781 glColor3ub (128, 128, 128);
3782 recti (b.x0, b.y0, b.x1, b.y1);
3783 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3789 if (x1 < x0 && fspan == lspan) {
3790 i = fi;
3791 span = fspan;
3793 fi = li;
3794 fspan = lspan;
3796 li = i;
3797 lspan = span;
3800 page->fmark.i = fi;
3801 page->fmark.span = fspan;
3803 page->lmark.i = li;
3804 page->lmark.span = lspan;
3806 unlock ("ml_seltext");
3808 done:
3809 CAMLreturn (Val_unit);
3812 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3814 char buf[4];
3815 int i, len, ret;
3817 for (i = a; i <= b; ++i) {
3818 len = fz_runetochar (buf, span->text[i].c);
3819 ret = fwrite (buf, len, 1, f);
3821 if (ret != 1) {
3822 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3823 len, ret, strerror (errno));
3824 return -1;
3827 return 0;
3830 #ifdef __CYGWIN__
3831 CAMLprim value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3833 caml_failwith ("ml_popen not implemented under Cygwin");
3835 #else
3836 CAMLprim value ml_popen (value command_v, value fds_v)
3838 CAMLparam2 (command_v, fds_v);
3839 CAMLlocal2 (l_v, tup_v);
3840 int ret;
3841 pid_t pid;
3842 char *msg = NULL;
3843 value earg_v = Nothing;
3844 posix_spawnattr_t attr;
3845 posix_spawn_file_actions_t fa;
3846 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3848 argv[2] = String_val (command_v);
3850 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3851 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3854 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3855 msg = "posix_spawnattr_init";
3856 goto fail1;
3859 #ifdef POSIX_SPAWN_USEVFORK
3860 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3861 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3862 goto fail;
3864 #endif
3866 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3867 int fd1, fd2;
3869 tup_v = Field (l_v, 0);
3870 fd1 = Int_val (Field (tup_v, 0));
3871 fd2 = Int_val (Field (tup_v, 1));
3872 if (fd2 < 0) {
3873 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3874 msg = "posix_spawn_file_actions_addclose";
3875 earg_v = tup_v;
3876 goto fail;
3879 else {
3880 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3881 msg = "posix_spawn_file_actions_adddup2";
3882 earg_v = tup_v;
3883 goto fail;
3888 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3889 msg = "posix_spawn";
3890 goto fail;
3893 fail:
3894 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3895 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3898 fail1:
3899 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3900 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3901 strerror (ret));
3904 if (msg)
3905 unix_error (ret, msg, earg_v);
3907 CAMLreturn (Val_int (pid));
3909 #endif
3911 CAMLprim value ml_hassel (value ptr_v)
3913 CAMLparam1 (ptr_v);
3914 CAMLlocal1 (ret_v);
3915 struct page *page;
3916 char *s = String_val (ptr_v);
3918 ret_v = Val_bool (0);
3919 if (trylock ("ml_hassel")) {
3920 goto done;
3923 page = parse_pointer ("ml_hassel", s);
3924 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3925 unlock ("ml_hassel");
3926 done:
3927 CAMLreturn (ret_v);
3930 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3932 CAMLparam2 (fd_v, ptr_v);
3933 FILE *f;
3934 int seen = 0;
3935 struct page *page;
3936 fz_text_line *line;
3937 fz_page_block *pageb;
3938 fz_text_block *block;
3939 int fd = Int_val (fd_v);
3940 char *s = String_val (ptr_v);
3942 if (trylock ("ml_copysel")) {
3943 goto done;
3946 page = parse_pointer ("ml_copysel", s);
3948 if (!page->fmark.span || !page->lmark.span) {
3949 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3950 goto unlock;
3953 f = fdopen (fd, "w");
3954 if (!f) {
3955 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3956 fd, strerror (errno));
3957 f = stdout;
3960 for (pageb = page->text->blocks;
3961 pageb < page->text->blocks + page->text->len;
3962 ++pageb) {
3963 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3964 block = pageb->u.text;
3965 for (line = block->lines;
3966 line < block->lines + block->len;
3967 ++line) {
3968 fz_text_span *span;
3970 for (span = line->first_span; span; span = span->next) {
3971 int a, b;
3973 seen |= span == page->fmark.span || span == page->lmark.span;
3974 a = span == page->fmark.span ? page->fmark.i : 0;
3975 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3977 if (seen) {
3978 if (pipespan (f, span, a, b)) {
3979 goto close;
3981 if (span == page->lmark.span) {
3982 goto close;
3984 if (span == line->last_span) {
3985 if (putc ('\n', f) == EOF) {
3986 fprintf (stderr,
3987 "failed break line on sel pipe: %s\n",
3988 strerror (errno));
3989 goto close;
3996 close:
3997 if (f != stdout) {
3998 int ret = fclose (f);
3999 fd = -1;
4000 if (ret == -1) {
4001 if (errno != ECHILD) {
4002 fprintf (stderr, "failed to close sel pipe: %s\n",
4003 strerror (errno));
4007 unlock:
4008 unlock ("ml_copysel");
4010 done:
4011 if (fd >= 0) {
4012 if (close (fd)) {
4013 fprintf (stderr, "failed to close sel pipe: %s\n",
4014 strerror (errno));
4017 CAMLreturn (Val_unit);
4020 CAMLprim value ml_getpdimrect (value pagedimno_v)
4022 CAMLparam1 (pagedimno_v);
4023 CAMLlocal1 (ret_v);
4024 int pagedimno = Int_val (pagedimno_v);
4025 fz_rect box;
4027 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
4028 if (trylock ("ml_getpdimrect")) {
4029 box = fz_empty_rect;
4031 else {
4032 box = state.pagedims[pagedimno].mediabox;
4033 unlock ("ml_getpdimrect");
4036 Store_double_field (ret_v, 0, box.x0);
4037 Store_double_field (ret_v, 1, box.x1);
4038 Store_double_field (ret_v, 2, box.y0);
4039 Store_double_field (ret_v, 3, box.y1);
4041 CAMLreturn (ret_v);
4044 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
4045 value dw_v, value cols_v)
4047 CAMLparam3 (winw_v, winh_v, dw_v);
4048 CAMLlocal1 (ret_v);
4049 int i;
4050 double zoom = -1.;
4051 double maxh = 0.0;
4052 struct pagedim *p;
4053 double winw = Int_val (winw_v);
4054 double winh = Int_val (winh_v);
4055 double dw = Int_val (dw_v);
4056 double cols = Int_val (cols_v);
4057 double pw = 1.0, ph = 1.0;
4059 if (trylock ("ml_zoom_for_height")) {
4060 goto done;
4063 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
4064 double w = p->pagebox.x1 / cols;
4065 double h = p->pagebox.y1;
4066 if (h > maxh) {
4067 maxh = h;
4068 ph = h;
4069 if (state.fitmodel != FitProportional) pw = w;
4071 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
4074 zoom = (((winh / ph) * pw) + dw) / winw;
4075 unlock ("ml_zoom_for_height");
4076 done:
4077 ret_v = caml_copy_double (zoom);
4078 CAMLreturn (ret_v);
4081 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
4083 CAMLparam4 (pt_v, x_v, y_v, string_v);
4084 CAMLlocal1 (ret_v);
4085 int pt = Int_val(pt_v);
4086 int x = Int_val (x_v);
4087 int y = Int_val (y_v);
4088 double w;
4090 w = draw_string (state.face, pt, x, y, String_val (string_v));
4091 ret_v = caml_copy_double (w);
4092 CAMLreturn (ret_v);
4095 CAMLprim value ml_measure_string (value pt_v, value string_v)
4097 CAMLparam2 (pt_v, string_v);
4098 CAMLlocal1 (ret_v);
4099 int pt = Int_val (pt_v);
4100 double w;
4102 w = measure_string (state.face, pt, String_val (string_v));
4103 ret_v = caml_copy_double (w);
4104 CAMLreturn (ret_v);
4107 CAMLprim value ml_getpagebox (value opaque_v)
4109 CAMLparam1 (opaque_v);
4110 CAMLlocal1 (ret_v);
4111 fz_rect rect;
4112 fz_irect bbox;
4113 fz_matrix ctm;
4114 fz_device *dev;
4115 char *s = String_val (opaque_v);
4116 struct page *page = parse_pointer ("ml_getpagebox", s);
4118 ret_v = caml_alloc_tuple (4);
4119 dev = fz_new_bbox_device (state.ctx, &rect);
4120 dev->hints |= FZ_IGNORE_SHADE;
4122 switch (page->type) {
4123 case DPDF:
4124 ctm = pagectm (page);
4125 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
4126 break;
4128 case DXPS:
4129 ctm = pagectm (page);
4130 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
4131 break;
4133 default:
4134 rect = fz_infinite_rect;
4135 break;
4138 fz_free_device (dev);
4139 fz_round_rect (&bbox, &rect);
4140 Field (ret_v, 0) = Val_int (bbox.x0);
4141 Field (ret_v, 1) = Val_int (bbox.y0);
4142 Field (ret_v, 2) = Val_int (bbox.x1);
4143 Field (ret_v, 3) = Val_int (bbox.y1);
4145 CAMLreturn (ret_v);
4148 CAMLprim value ml_setaalevel (value level_v)
4150 CAMLparam1 (level_v);
4152 state.aalevel = Int_val (level_v);
4153 CAMLreturn (Val_unit);
4156 #pragma GCC diagnostic push
4157 #pragma GCC diagnostic ignored "-Wvariadic-macros"
4158 #include <X11/Xlib.h>
4159 #pragma GCC diagnostic pop
4161 #include <GL/glx.h>
4163 static struct {
4164 Window wid;
4165 Display *dpy;
4166 GLXContext ctx;
4167 XVisualInfo *visual;
4168 } glx;
4170 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4172 CAMLparam3 (display_v, wid_v, screen_v);
4173 int attribs[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
4175 glx.dpy = XOpenDisplay (String_val (display_v));
4176 if (!glx.dpy) {
4177 caml_failwith ("XOpenDisplay");
4180 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4181 if (!glx.visual) {
4182 XCloseDisplay (glx.dpy);
4183 caml_failwith ("glXChooseVisual");
4186 glx.wid = Int_val (wid_v);
4187 CAMLreturn (Val_int (glx.visual->visualid));
4190 CAMLprim value ml_glxcompleteinit (value unit_v)
4192 CAMLparam1 (unit_v);
4194 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4195 if (!glx.ctx) {
4196 caml_failwith ("glXCreateContext");
4199 XFree (glx.visual);
4200 glx.visual = NULL;
4202 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4203 glXDestroyContext (glx.dpy, glx.ctx);
4204 glx.ctx = NULL;
4205 caml_failwith ("glXMakeCurrent");
4207 CAMLreturn (Val_unit);
4210 CAMLprim value ml_swapb (value unit_v)
4212 CAMLparam1 (unit_v);
4213 glXSwapBuffers (glx.dpy, glx.wid);
4214 CAMLreturn (Val_unit);
4217 #include "keysym2ucs.c"
4219 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4221 CAMLparam1 (keysym_v);
4222 CAMLlocal1 (str_v);
4223 KeySym keysym = Int_val (keysym_v);
4224 Rune rune;
4225 int len;
4226 char buf[5];
4228 rune = keysym2ucs (keysym);
4229 len = fz_runetochar (buf, rune);
4230 buf[len] = 0;
4231 str_v = caml_copy_string (buf);
4232 CAMLreturn (str_v);
4235 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4237 CAMLprim value ml_platform (value unit_v)
4239 CAMLparam1 (unit_v);
4240 CAMLlocal2 (tup_v, arr_v);
4241 int platid = piunknown;
4242 struct utsname buf;
4244 #if defined __linux__
4245 platid = pilinux;
4246 #elif defined __CYGWIN__
4247 platid = picygwin;
4248 #elif defined __DragonFly__ || defined __FreeBSD__
4249 || defined __OpenBSD__ || defined __NetBSD__
4250 platid = pibsd;
4251 #elif defined __sun__
4252 platid = pisun;
4253 #elif defined __APPLE__
4254 platid = piosx;
4255 #endif
4256 if (uname (&buf)) err (1, "uname");
4258 tup_v = caml_alloc_tuple (2);
4260 char const *sar[] = {
4261 buf.sysname,
4262 buf.release,
4263 buf.version,
4264 buf.machine,
4265 NULL
4267 arr_v = caml_copy_string_array (sar);
4269 Field (tup_v, 0) = Val_int (platid);
4270 Field (tup_v, 1) = arr_v;
4271 CAMLreturn (tup_v);
4274 CAMLprim value ml_cloexec (value fd_v)
4276 CAMLparam1 (fd_v);
4277 int fd = Int_val (fd_v);
4279 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4280 uerror ("fcntl", Nothing);
4282 CAMLreturn (Val_unit);
4285 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4287 CAMLparam2 (w_v, h_v);
4288 CAMLlocal1 (ret_v);
4289 struct pbo *pbo;
4290 int w = Int_val (w_v);
4291 int h = Int_val (h_v);
4292 int cs = Int_val (cs_v);
4294 if (state.pbo_usable) {
4295 pbo = calloc (sizeof (*pbo), 1);
4296 if (!pbo) {
4297 err (1, "calloc pbo");
4300 switch (cs) {
4301 case 0:
4302 case 1:
4303 pbo->size = w*h*4;
4304 break;
4305 case 2:
4306 pbo->size = w*h*2;
4307 break;
4308 default:
4309 errx (1, "ml_getpbo: invalid colorspace %d", cs);
4312 state.glGenBuffersARB (1, &pbo->id);
4313 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4314 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4315 NULL, GL_STREAM_DRAW);
4316 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4317 GL_READ_WRITE);
4318 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4319 if (!pbo->ptr) {
4320 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4321 state.glDeleteBuffersARB (1, &pbo->id);
4322 free (pbo);
4323 ret_v = caml_copy_string ("0");
4325 else {
4326 int res;
4327 char *s;
4329 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4330 if (res < 0) {
4331 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4333 s = malloc (res+1);
4334 if (!s) {
4335 err (1, "malloc %d bytes failed", res+1);
4337 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4338 if (res < 0) {
4339 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4341 ret_v = caml_copy_string (s);
4342 free (s);
4345 else {
4346 ret_v = caml_copy_string ("0");
4348 CAMLreturn (ret_v);
4351 CAMLprim value ml_freepbo (value s_v)
4353 CAMLparam1 (s_v);
4354 char *s = String_val (s_v);
4355 struct tile *tile = parse_pointer ("ml_freepbo", s);
4357 if (tile->pbo) {
4358 state.glDeleteBuffersARB (1, &tile->pbo->id);
4359 tile->pbo->id = -1;
4360 tile->pbo->ptr = NULL;
4361 tile->pbo->size = -1;
4363 CAMLreturn (Val_unit);
4366 CAMLprim value ml_unmappbo (value s_v)
4368 CAMLparam1 (s_v);
4369 char *s = String_val (s_v);
4370 struct tile *tile = parse_pointer ("ml_unmappbo", s);
4372 if (tile->pbo) {
4373 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4374 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4375 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4377 tile->pbo->ptr = NULL;
4378 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4380 CAMLreturn (Val_unit);
4383 static void setuppbo (void)
4385 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4386 state.pbo_usable = GGPA (glBindBufferARB)
4387 && GGPA (glUnmapBufferARB)
4388 && GGPA (glMapBufferARB)
4389 && GGPA (glBufferDataARB)
4390 && GGPA (glGenBuffersARB)
4391 && GGPA (glDeleteBuffersARB);
4392 #undef GGPA
4395 CAMLprim value ml_pbo_usable (value unit_v)
4397 CAMLparam1 (unit_v);
4398 CAMLreturn (Val_bool (state.pbo_usable));
4401 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4403 CAMLparam3 (ptr_v, x_v, y_v);
4404 CAMLlocal2 (ret_v, tup_v);
4405 struct page *page;
4406 char *s = String_val (ptr_v);
4407 int x = Int_val (x_v), y = Int_val (y_v);
4408 struct pagedim *pdim;
4409 fz_point p;
4410 fz_matrix ctm;
4412 page = parse_pointer ("ml_unproject", s);
4413 pdim = &state.pagedims[page->pdimno];
4415 ret_v = Val_int (0);
4416 if (trylock ("ml_unproject")) {
4417 goto done;
4420 switch (page->type) {
4421 case DPDF:
4422 trimctm (page->u.pdfpage, page->pdimno);
4423 break;
4425 default:
4426 break;
4428 p.x = x + pdim->bounds.x0;
4429 p.y = y + pdim->bounds.y0;
4431 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4432 fz_invert_matrix (&ctm, &ctm);
4433 fz_transform_point (&p, &ctm);
4435 tup_v = caml_alloc_tuple (2);
4436 ret_v = caml_alloc_small (1, 1);
4437 Field (tup_v, 0) = Val_int (p.x);
4438 Field (tup_v, 1) = Val_int (p.y);
4439 Field (ret_v, 0) = tup_v;
4441 unlock ("ml_unproject");
4442 done:
4443 CAMLreturn (ret_v);
4446 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4447 value contents_v)
4449 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4451 if (state.type == DPDF) {
4452 pdf_document *pdf;
4453 pdf_annot *annot;
4454 struct page *page;
4455 fz_point p;
4456 char *s = String_val (ptr_v);
4458 pdf = state.u.pdf;
4459 page = parse_pointer ("ml_addannot", s);
4460 annot = pdf_create_annot (pdf, page->u.pdfpage, FZ_ANNOT_TEXT);
4461 p.x = Int_val (x_v);
4462 p.y = Int_val (y_v);
4463 pdf_set_annot_contents (pdf, annot, String_val (contents_v));
4464 pdf_set_text_annot_position (pdf, annot, p);
4465 state.dirty = 1;
4467 CAMLreturn (Val_unit);
4470 CAMLprim value ml_delannot (value ptr_v, value n_v)
4472 CAMLparam2 (ptr_v, n_v);
4474 if (state.type == DPDF) {
4475 struct page *page;
4476 char *s = String_val (ptr_v);
4477 struct slink *slink;
4479 page = parse_pointer ("ml_delannot", s);
4480 slink = &page->slinks[Int_val (n_v)];
4481 pdf_delete_annot (state.u.pdf, page->u.pdfpage, slink->u.annot);
4482 state.dirty = 1;
4484 CAMLreturn (Val_unit);
4487 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4489 CAMLparam3 (ptr_v, n_v, str_v);
4491 if (state.type == DPDF) {
4492 struct page *page;
4493 char *s = String_val (ptr_v);
4494 struct slink *slink;
4496 page = parse_pointer ("ml_modannot", s);
4497 slink = &page->slinks[Int_val (n_v)];
4498 pdf_set_annot_contents (state.u.pdf, slink->u.annot,
4499 String_val (str_v));
4500 state.dirty = 1;
4502 CAMLreturn (Val_unit);
4505 CAMLprim value ml_hasunsavedchanges (value unit_v)
4507 CAMLparam1 (unit_v);
4508 CAMLreturn (Val_bool (state.dirty));
4511 CAMLprim value ml_savedoc (value path_v)
4513 CAMLparam1 (path_v);
4515 if (state.type == DPDF) {
4516 pdf_write_document (state.u.pdf, String_val (path_v), NULL);
4518 CAMLreturn (Val_unit);
4521 static void makestippletex (void)
4523 const char pixels[] = "\xff\xff\0\0";
4524 glGenTextures (1, &state.stid);
4525 glBindTexture (GL_TEXTURE_1D, state.stid);
4526 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4527 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4528 glTexImage1D (
4529 GL_TEXTURE_1D,
4531 GL_ALPHA,
4534 GL_ALPHA,
4535 GL_UNSIGNED_BYTE,
4536 pixels
4540 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4542 return caml_copy_string (FZ_VERSION);
4545 #ifdef USE_FONTCONFIG
4546 static struct {
4547 int inited;
4548 FcConfig *config;
4549 } fc;
4551 static fz_font *fc_load_system_font_func (fz_context *ctx,
4552 const char *name,
4553 int bold,
4554 int italic,
4555 int UNUSED_ATTR needs_exact_metrics)
4557 char *buf;
4558 size_t i, size;
4559 fz_font *font;
4560 FcChar8 *path;
4561 FcResult result;
4562 FcPattern *pat, *pat1;
4564 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4565 name, bold, italic, needs_exact_metrics);
4566 if (!fc.inited) {
4567 fc.inited = 1;
4568 fc.config = FcInitLoadConfigAndFonts ();
4569 if (!fc.config) {
4570 lprintf ("FcInitLoadConfigAndFonts failed\n");
4571 return NULL;
4574 if (!fc.config) return NULL;
4576 size = strlen (name);
4577 if (bold) size += sizeof (":bold") - 1;
4578 if (italic) size += sizeof (":italic") - 1;
4579 size += 1;
4581 buf = malloc (size);
4582 if (!buf) {
4583 err (1, "malloc %zu failed", size);
4586 strcpy (buf, name);
4587 if (bold && italic) {
4588 strcat (buf, ":bold:italic");
4590 else {
4591 if (bold) strcat (buf, ":bold");
4592 if (italic) strcat (buf, ":italic");
4594 for (i = 0; i < size; ++i) {
4595 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4598 lprintf ("fcbuf=%s\n", buf);
4599 pat = FcNameParse ((FcChar8 *) buf);
4600 if (!pat) {
4601 printd ("emsg FcNameParse failed\n");
4602 free (buf);
4603 return NULL;
4606 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4607 printd ("emsg FcConfigSubstitute failed\n");
4608 free (buf);
4609 return NULL;
4611 FcDefaultSubstitute (pat);
4613 pat1 = FcFontMatch (fc.config, pat, &result);
4614 if (!pat1) {
4615 printd ("emsg FcFontMatch failed\n");
4616 FcPatternDestroy (pat);
4617 free (buf);
4618 return NULL;
4621 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4622 printd ("emsg FcPatternGetString failed\n");
4623 FcPatternDestroy (pat);
4624 FcPatternDestroy (pat1);
4625 free (buf);
4626 return NULL;
4629 #if 0
4630 printd ("emsg name=%s path=%s\n", name, path);
4631 #endif
4632 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4633 FcPatternDestroy (pat);
4634 FcPatternDestroy (pat1);
4635 free (buf);
4636 return font;
4638 #endif
4640 CAMLprim value ml_init (value csock_v, value params_v)
4642 CAMLparam2 (csock_v, params_v);
4643 CAMLlocal2 (trim_v, fuzz_v);
4644 int ret;
4645 int texcount;
4646 char *fontpath;
4647 int colorspace;
4648 int mustoresize;
4649 int haspboext;
4651 state.csock = Int_val (csock_v);
4652 state.rotate = Int_val (Field (params_v, 0));
4653 state.fitmodel = Int_val (Field (params_v, 1));
4654 trim_v = Field (params_v, 2);
4655 texcount = Int_val (Field (params_v, 3));
4656 state.sliceheight = Int_val (Field (params_v, 4));
4657 mustoresize = Int_val (Field (params_v, 5));
4658 colorspace = Int_val (Field (params_v, 6));
4659 fontpath = String_val (Field (params_v, 7));
4661 if (caml_string_length (Field (params_v, 8)) > 0) {
4662 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4664 if (!state.trimcachepath) {
4665 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4666 strerror (errno));
4669 haspboext = Bool_val (Field (params_v, 9));
4671 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4673 #ifdef USE_FONTCONFIG
4674 if (Bool_val (Field (params_v, 10))) {
4675 fz_install_load_system_font_funcs (
4676 state.ctx, fc_load_system_font_func, NULL
4679 #endif
4681 state.trimmargins = Bool_val (Field (trim_v, 0));
4682 fuzz_v = Field (trim_v, 1);
4683 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4684 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4685 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4686 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4688 set_tex_params (colorspace);
4690 if (*fontpath) {
4691 #ifndef USE_FONTCONFIG
4692 state.face = load_font (fontpath);
4693 #else
4694 FcChar8 *path;
4695 FcResult result;
4696 char *buf = fontpath;
4697 FcPattern *pat, *pat1;
4699 fc.inited = 1;
4700 fc.config = FcInitLoadConfigAndFonts ();
4701 if (!fc.config) {
4702 errx (1, "FcInitLoadConfigAndFonts failed");
4705 pat = FcNameParse ((FcChar8 *) buf);
4706 if (!pat) {
4707 errx (1, "FcNameParse failed");
4710 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4711 errx (1, "FcConfigSubstitute failed");
4713 FcDefaultSubstitute (pat);
4715 pat1 = FcFontMatch (fc.config, pat, &result);
4716 if (!pat1) {
4717 errx (1, "FcFontMatch failed");
4720 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4721 errx (1, "FcPatternGetString failed");
4724 state.face = load_font ((char *) path);
4725 FcPatternDestroy (pat);
4726 FcPatternDestroy (pat1);
4727 #endif
4729 else {
4730 unsigned int len;
4731 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
4733 state.face = load_builtin_font (base, len);
4735 if (!state.face) _exit (1);
4737 realloctexts (texcount);
4739 if (haspboext) {
4740 setuppbo ();
4743 makestippletex ();
4745 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4746 if (ret) {
4747 errx (1, "pthread_create: %s", strerror (ret));
4750 CAMLreturn (Val_unit);