Unification
[llpp.git] / link.c
bloba405f2e30252b0ada8caa844c180db807cf8f6ae
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 #pragma GCC diagnostic push
38 #pragma GCC diagnostic ignored "-Wunused-parameter"
39 #include <mupdf/fitz.h>
40 #pragma GCC diagnostic pop
41 #include <mupdf/pdf.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 { DPDF, DANY };
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 fz_page *anypage;
193 pdf_page *pdfpage;
194 } u;
195 fz_display_list *dlist;
196 int slinkcount;
197 struct slink *slinks;
198 int annotcount;
199 struct annot *annots;
200 struct mark {
201 int i;
202 fz_text_span *span;
203 } fmark, lmark;
204 void (*freepage) (void *);
207 struct {
208 int type;
209 int sliceheight;
210 struct pagedim *pagedims;
211 int pagecount;
212 int pagedimcount;
213 union {
214 fz_document *doc;
215 pdf_document *pdf;
216 } u;
217 fz_context *ctx;
218 int w, h;
220 int texindex;
221 int texcount;
222 GLuint *texids;
224 GLenum texiform;
225 GLenum texform;
226 GLenum texty;
228 fz_colorspace *colorspace;
230 struct {
231 int w, h;
232 struct slice *slice;
233 } *texowners;
235 int rotate;
236 enum { FitWidth, FitProportional, FitPage } fitmodel;
237 int trimmargins;
238 int needoutline;
239 int gen;
240 int aalevel;
242 int trimanew;
243 fz_irect trimfuzz;
244 fz_pixmap *pig;
246 pthread_t thread;
247 int csock;
248 FT_Face face;
250 void (*closedoc) (void);
251 void (*freepage) (void *);
253 char *trimcachepath;
254 int cxack;
255 int dirty;
257 GLuint stid;
259 int pbo_usable;
260 void (*glBindBufferARB) (GLenum, GLuint);
261 GLboolean (*glUnmapBufferARB) (GLenum);
262 void *(*glMapBufferARB) (GLenum, GLenum);
263 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
264 void (*glGenBuffersARB) (GLsizei, GLuint *);
265 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
267 GLfloat texcoords[8];
268 GLfloat vertices[16];
270 #ifdef CACHE_PAGEREFS
271 struct {
272 int idx;
273 int count;
274 pdf_obj **objs;
275 pdf_document *pdf;
276 } pdflut;
277 #endif
278 } state;
280 struct pbo {
281 GLuint id;
282 void *ptr;
283 size_t size;
286 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
288 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
291 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
293 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
296 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
298 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
299 m.a, m.b, m.c, m.d, m.e, m.f);
302 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
304 static void lock (const char *cap)
306 int ret = pthread_mutex_lock (&mutex);
307 if (ret) {
308 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
312 static void unlock (const char *cap)
314 int ret = pthread_mutex_unlock (&mutex);
315 if (ret) {
316 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
320 static int trylock (const char *cap)
322 int ret = pthread_mutex_trylock (&mutex);
323 if (ret && ret != EBUSY) {
324 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
326 return ret == EBUSY;
329 static void *parse_pointer (const char *cap, const char *s)
331 int ret;
332 void *ptr;
334 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
335 if (ret != 1) {
336 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
338 return ptr;
341 static double now (void)
343 struct timeval tv;
345 if (gettimeofday (&tv, NULL)) {
346 err (1, "gettimeofday");
348 return tv.tv_sec + tv.tv_usec*1e-6;
351 static int hasdata (void)
353 int ret, avail;
354 ret = ioctl (state.csock, FIONREAD, &avail);
355 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
356 return avail > 0;
359 CAMLprim value ml_hasdata (value fd_v)
361 CAMLparam1 (fd_v);
362 int ret, avail;
364 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
365 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
366 CAMLreturn (Val_bool (avail > 0));
369 static void readdata (void *p, int size)
371 ssize_t n;
373 again:
374 n = read (state.csock, p, size);
375 if (n < 0) {
376 if (errno == EINTR) goto again;
377 err (1, "read (req %d, ret %zd)", size, n);
379 if (n - size) {
380 if (!n) errx (1, "EOF while reading");
381 errx (1, "read (req %d, ret %zd)", size, n);
385 static void writedata (char *p, int size)
387 ssize_t n;
389 p[0] = (size >> 24) & 0xff;
390 p[1] = (size >> 16) & 0xff;
391 p[2] = (size >> 8) & 0xff;
392 p[3] = (size >> 0) & 0xff;
394 n = write (state.csock, p, size + 4);
395 if (n - size - 4) {
396 if (!n) errx (1, "EOF while writing data");
397 err (1, "write (req %d, ret %zd)", size + 4, n);
401 static int readlen (void)
403 unsigned char p[4];
405 readdata (p, 4);
406 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
409 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
411 int size = 200, len;
412 va_list ap;
413 char *buf;
415 buf = malloc (size);
416 for (;;) {
417 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
419 va_start (ap, fmt);
420 len = vsnprintf (buf + 4, size - 4, fmt, ap);
421 va_end (ap);
423 if (len > -1) {
424 if (len < size - 4) {
425 writedata (buf, len);
426 break;
428 else size = len + 5;
430 else {
431 err (1, "vsnprintf for `%s' failed", fmt);
433 buf = realloc (buf, size);
435 free (buf);
438 static void closepdf (void)
440 #ifdef CACHE_PAGEREFS
441 if (state.pdflut.objs) {
442 int i;
444 for (i = 0; i < state.pdflut.count; ++i) {
445 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
447 free (state.pdflut.objs);
448 state.pdflut.objs = NULL;
449 state.pdflut.idx = 0;
451 #endif
453 if (state.u.pdf) {
454 pdf_close_document (state.ctx, state.u.pdf);
455 state.u.pdf = NULL;
459 static void closedoc (void)
461 if (state.u.doc) {
462 fz_drop_document (state.ctx, state.u.doc);
463 state.u.doc = NULL;
467 static void freepdfpage (void *ptr)
469 fz_drop_page (state.ctx, ptr);
472 static void freeemptyxxxpage (void *ptr)
474 (void) ptr;
477 static void freeanypage (void *ptr)
479 fz_drop_page (state.ctx, ptr);
482 static int openxref (char *filename, char *password)
484 int i, len;
486 for (i = 0; i < state.texcount; ++i) {
487 state.texowners[i].w = -1;
488 state.texowners[i].slice = NULL;
491 if (state.closedoc) state.closedoc ();
493 state.dirty = 0;
494 len = strlen (filename);
496 state.type = DANY;
498 size_t j;
499 struct {
500 char *ext;
501 int type;
502 } tbl[] = {
503 { "pdf", DPDF },
506 for (j = 0; j < sizeof (tbl) / sizeof (*tbl); ++j) {
507 const char *ext = tbl[j].ext;
508 int len2 = strlen (ext);
510 if (len2 < len && !strcasecmp (ext, filename + len - len2)) {
511 state.type = tbl[j].type;
512 break;
517 if (state.pagedims) {
518 free (state.pagedims);
519 state.pagedims = NULL;
521 state.pagedimcount = 0;
523 fz_set_aa_level (state.ctx, state.aalevel);
524 switch (state.type) {
525 case DPDF:
526 state.u.pdf = pdf_open_document (state.ctx, filename);
527 if (pdf_needs_password (state.ctx, state.u.pdf)) {
528 if (password && !*password) {
529 printd ("pass");
530 return 0;
532 else {
533 int ok = pdf_authenticate_password (state.ctx, state.u.pdf,
534 password);
535 if (!ok) {
536 printd ("pass fail");
537 return 0;
541 state.pagecount = pdf_count_pages (state.ctx, state.u.pdf);
542 state.closedoc = closepdf;
543 state.freepage = freepdfpage;
544 break;
546 case DANY:
547 state.u.doc = fz_open_document (state.ctx, filename);
548 state.pagecount = fz_count_pages (state.ctx, state.u.doc);
549 state.closedoc = closedoc;
550 state.freepage = freeanypage;
551 break;
553 return 1;
556 static void pdfinfo (void)
558 if (state.type == DPDF) {
559 pdf_obj *infoobj;
561 printd ("info PDF version\t%d.%d",
562 state.u.pdf->version / 10, state.u.pdf->version % 10);
564 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
565 state.u.pdf), "Info");
566 if (infoobj) {
567 unsigned int i;
568 char *s;
569 char *items[] = { "Title", "Author", "Creator",
570 "Producer", "CreationDate" };
572 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
573 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
574 s = pdf_to_utf8 (state.ctx, state.u.pdf, obj);
575 if (*s) printd ("info %s\t%s", items[i], s);
576 fz_free (state.ctx, s);
579 printd ("infoend");
583 static void unlinktile (struct tile *tile)
585 int i;
587 for (i = 0; i < tile->slicecount; ++i) {
588 struct slice *s = &tile->slices[i];
590 if (s->texindex != -1) {
591 if (state.texowners[s->texindex].slice == s) {
592 state.texowners[s->texindex].slice = NULL;
598 static void freepage (struct page *page)
600 if (page->text) {
601 fz_drop_text_page (state.ctx, page->text);
603 if (page->sheet) {
604 fz_drop_text_sheet (state.ctx, page->sheet);
606 if (page->slinks) {
607 free (page->slinks);
609 fz_drop_display_list (state.ctx, page->dlist);
610 page->freepage (page->u.ptr);
611 free (page);
614 static void freetile (struct tile *tile)
616 unlinktile (tile);
617 if (!tile->pbo) {
618 #ifndef PIGGYBACK
619 fz_drop_pixmap (state.ctx, tile->pixmap);
620 #else
621 if (state.pig) {
622 fz_drop_pixmap (state.ctx, state.pig);
624 state.pig = tile->pixmap;
625 #endif
627 else {
628 free (tile->pbo);
629 fz_drop_pixmap (state.ctx, tile->pixmap);
631 free (tile);
634 #ifdef __ALTIVEC__
635 #include <stdint.h>
636 #include <altivec.h>
638 static int cacheline32bytes;
640 static void __attribute__ ((constructor)) clcheck (void)
642 char **envp = environ;
643 unsigned long *auxv;
645 while (*envp++);
647 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
648 if (*auxv == 19) {
649 cacheline32bytes = auxv[1] == 32;
650 return;
655 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
657 size_t size = pixmap->w * pixmap->h * pixmap->n;
658 if (cacheline32bytes && size > 32) {
659 intptr_t a1, a2, diff;
660 size_t sizea, i;
661 vector unsigned char v = vec_splat_u8 (-1);
662 vector unsigned char *p;
664 a1 = a2 = (intptr_t) pixmap->samples;
665 a2 = (a1 + 31) & ~31;
666 diff = a2 - a1;
667 sizea = size - diff;
668 p = (void *) a2;
670 while (a1 != a2) *(char *) a1++ = 0xff;
671 for (i = 0; i < (sizea & ~31); i += 32) {
672 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
673 vec_st (v, i, p);
674 vec_st (v, i + 16, p);
676 while (i < sizea) *((char *) a1 + i++) = 0xff;
678 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
680 #else
681 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
682 #endif
684 static void trimctm (pdf_page *page, int pindex)
686 fz_matrix ctm;
687 struct pagedim *pdim = &state.pagedims[pindex];
689 if (!pdim->tctmready) {
690 if (state.trimmargins) {
691 fz_rect realbox;
692 fz_matrix rm, sm, tm, im, ctm1;
694 fz_rotate (&rm, -pdim->rotate);
695 fz_scale (&sm, 1, -1);
696 fz_concat (&ctm, &rm, &sm);
697 realbox = pdim->mediabox;
698 fz_transform_rect (&realbox, &ctm);
699 fz_translate (&tm, -realbox.x0, -realbox.y0);
700 fz_concat (&ctm1, &ctm, &tm);
701 fz_invert_matrix (&im, &page->ctm);
702 fz_concat (&ctm, &im, &ctm1);
704 else {
705 ctm = fz_identity;
707 pdim->tctm = ctm;
708 pdim->tctmready = 1;
712 static fz_matrix pagectm (struct page *page)
714 fz_matrix ctm, tm;
716 if (page->type == DPDF) {
717 trimctm (page->u.pdfpage, page->pdimno);
718 fz_concat (&ctm,
719 &state.pagedims[page->pdimno].tctm,
720 &state.pagedims[page->pdimno].ctm);
722 else {
723 struct pagedim *pdim = &state.pagedims[page->pdimno];
725 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
726 fz_concat (&ctm, &tm, &state.pagedims[page->pdimno].ctm);
728 return ctm;
731 static void *loadpage (int pageno, int pindex)
733 fz_device *dev;
734 struct page *page;
736 page = calloc (sizeof (struct page), 1);
737 if (!page) {
738 err (1, "calloc page %d", pageno);
741 page->dlist = fz_new_display_list (state.ctx);
742 dev = fz_new_list_device (state.ctx, page->dlist);
743 fz_try (state.ctx) {
744 switch (state.type) {
745 case DPDF:
746 page->u.pdfpage = pdf_load_page (state.ctx, state.u.pdf, pageno);
747 pdf_run_page (state.ctx, page->u.pdfpage, dev,
748 &fz_identity, NULL);
749 page->freepage = freepdfpage;
750 break;
752 case DANY:
753 page->u.anypage = fz_load_page (state.ctx, state.u.doc, pageno);
754 fz_run_page (state.ctx, page->u.anypage, dev,
755 &fz_identity, NULL);
756 page->freepage = freeanypage;
757 break;
760 fz_catch (state.ctx) {
761 page->u.ptr = NULL;
762 page->freepage = freeemptyxxxpage;
764 fz_drop_device (state.ctx, dev);
766 page->pdimno = pindex;
767 page->pageno = pageno;
768 page->sgen = state.gen;
769 page->agen = state.gen;
770 page->tgen = state.gen;
771 page->type = state.type;
773 return page;
776 static struct tile *alloctile (int h)
778 int i;
779 int slicecount;
780 size_t tilesize;
781 struct tile *tile;
783 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
784 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
785 tile = calloc (tilesize, 1);
786 if (!tile) {
787 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
789 for (i = 0; i < slicecount; ++i) {
790 int sh = MIN (h, state.sliceheight);
791 tile->slices[i].h = sh;
792 tile->slices[i].texindex = -1;
793 h -= sh;
795 tile->slicecount = slicecount;
796 tile->sliceheight = state.sliceheight;
797 return tile;
800 #ifdef OBSCURED_OPT
801 struct obs {
802 fz_device super;
803 int cured;
804 fz_irect b;
807 static void obs_fill_image (fz_context *ctx, fz_device *dev,
808 fz_image UNUSED_ATTR *image,
809 const fz_matrix *ctm, float alpha)
811 struct obs *obs = (struct obs *) dev;
812 (void) ctx;
814 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
815 fz_irect b;
816 fz_rect rect = fz_unit_rect;
818 fz_transform_rect (&rect, ctm);
819 fz_round_rect (&b, &rect);
820 fz_intersect_irect (&b, &obs->b);
821 obs->cured = b.x0 == obs->b.x0
822 && b.x1 == obs->b.x1
823 && b.y0 == obs->b.y0
824 && b.y1 == obs->b.y1;
828 static int obscured (struct page *page, fz_irect bbox)
830 fz_rect rect;
831 fz_matrix ctm;
832 struct obs obs;
834 memset (&obs, 0, sizeof (obs));
835 obs.super.hints = 0;
836 obs.super.flags = 0;
837 obs.super.fill_image = obs_fill_image;
838 obs.b = bbox;
839 fz_rect_from_irect (&rect, &bbox);
840 ctm = pagectm (page);
841 fz_run_display_list (state.ctx, page->dlist, &obs.super, &ctm, &rect, NULL);
842 return obs.cured;
844 #define OBSCURED obscured
845 #else
846 #define OBSCURED(a, b) 0
847 #endif
849 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
850 struct pbo *pbo)
852 fz_rect rect;
853 fz_irect bbox;
854 fz_matrix ctm;
855 fz_device *dev;
856 struct tile *tile;
857 struct pagedim *pdim;
859 tile = alloctile (h);
860 pdim = &state.pagedims[page->pdimno];
862 bbox = pdim->bounds;
863 bbox.x0 += x;
864 bbox.y0 += y;
865 bbox.x1 = bbox.x0 + w;
866 bbox.y1 = bbox.y0 + h;
868 if (state.pig) {
869 if (state.pig->w == w
870 && state.pig->h == h
871 && state.pig->colorspace == state.colorspace) {
872 tile->pixmap = state.pig;
873 tile->pixmap->x = bbox.x0;
874 tile->pixmap->y = bbox.y0;
876 else {
877 fz_drop_pixmap (state.ctx, state.pig);
879 state.pig = NULL;
881 if (!tile->pixmap) {
882 if (pbo) {
883 tile->pixmap =
884 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
885 &bbox, pbo->ptr);
886 tile->pbo = pbo;
888 else {
889 tile->pixmap =
890 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
894 tile->w = w;
895 tile->h = h;
896 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
897 clearpixmap (tile->pixmap);
899 dev = fz_new_draw_device (state.ctx, tile->pixmap);
900 ctm = pagectm (page);
901 fz_rect_from_irect (&rect, &bbox);
902 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
903 fz_drop_device (state.ctx, dev);
905 return tile;
908 #ifdef CACHE_PAGEREFS
909 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
910 thanks to Robin Watts */
911 static void
912 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
914 fz_context *ctx = state.ctx; /* doc->ctx; */
915 pdf_obj *kids;
916 int i, len;
918 if (state.pdflut.idx == state.pagecount) return;
920 kids = pdf_dict_gets (ctx, node, "Kids");
921 len = pdf_array_len (ctx, kids);
923 if (len == 0)
924 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
926 if (pdf_mark_obj (ctx, node))
927 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
928 for (i = 0; i < len; i++) {
929 pdf_obj *kid = pdf_array_get (ctx, kids, i);
930 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
931 if (*type
932 ? !strcmp (type, "Pages")
933 : pdf_dict_gets (ctx, kid, "Kids")
934 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
935 pdf_collect_pages (doc, kid);
937 else {
938 if (*type
939 ? strcmp (type, "Page") != 0
940 : !pdf_dict_gets (ctx, kid, "MediaBox"))
941 fz_warn (ctx, "non-page object in page tree (%s)", type);
942 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
945 pdf_unmark_obj (ctx, node);
948 static void
949 pdf_load_page_objs (pdf_document *doc)
951 pdf_obj *root = pdf_dict_gets (state.ctx,
952 pdf_trailer (state.ctx, doc), "Root");
953 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
955 if (!node)
956 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
958 state.pdflut.idx = 0;
959 pdf_collect_pages (doc, node);
961 #endif
963 static void initpdims (void)
965 double start, end;
966 FILE *trimf = NULL;
967 fz_rect rootmediabox;
968 int pageno, trim, show;
969 int trimw = 0, cxcount;
971 start = now ();
973 if (state.trimmargins && state.trimcachepath) {
974 trimf = fopen (state.trimcachepath, "rb");
975 if (!trimf) {
976 trimf = fopen (state.trimcachepath, "wb");
977 trimw = 1;
981 if (state.trimmargins || state.type == DPDF || !state.cxack)
982 cxcount = state.pagecount;
983 else
984 cxcount = MIN (state.pagecount, 1);
986 if (state.type == DPDF) {
987 pdf_obj *obj;
988 obj = pdf_dict_getp (state.ctx, pdf_trailer (state.ctx, state.u.pdf),
989 "Root/Pages/MediaBox");
990 pdf_to_rect (state.ctx, obj, &rootmediabox);
993 #ifdef CACHE_PAGEREFS
994 if (state.type == DPDF
995 && (!state.pdflut.objs || state.pdflut.pdf != state.u.pdf)) {
996 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
997 if (!state.pdflut.objs) {
998 err (1, "malloc pageobjs %zu %d %zu failed",
999 sizeof (*state.pdflut.objs), cxcount,
1000 sizeof (*state.pdflut.objs) * cxcount);
1002 state.pdflut.count = cxcount;
1003 pdf_load_page_objs (state.u.pdf);
1004 state.pdflut.pdf = state.u.pdf;
1006 #endif
1008 for (pageno = 0; pageno < cxcount; ++pageno) {
1009 int rotate = 0;
1010 struct pagedim *p;
1011 fz_rect mediabox;
1013 switch (state.type) {
1014 case DPDF: {
1015 pdf_document *pdf = state.u.pdf;
1016 pdf_obj *pageref, *pageobj;
1018 #ifdef CACHE_PAGEREFS
1019 pageref = state.pdflut.objs[pageno];
1020 #else
1021 pageref = pdf_lookup_page_obj (state.ctx, pdf, pageno);
1022 #endif
1023 pageobj = pdf_resolve_indirect (state.ctx, pageref);
1025 if (state.trimmargins) {
1026 fz_context *ctx = state.ctx;
1027 pdf_obj *obj;
1028 pdf_page *page;
1030 fz_try (state.ctx) {
1031 page = pdf_load_page (ctx, pdf, pageno);
1032 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
1033 trim = state.trimanew || !obj;
1034 if (trim) {
1035 fz_rect rect;
1036 fz_matrix ctm;
1037 fz_device *dev;
1039 dev = fz_new_bbox_device (ctx, &rect);
1040 dev->hints |= FZ_IGNORE_SHADE;
1041 fz_invert_matrix (&ctm, &page->ctm);
1042 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
1043 fz_drop_device (ctx, dev);
1045 rect.x0 += state.trimfuzz.x0;
1046 rect.x1 += state.trimfuzz.x1;
1047 rect.y0 += state.trimfuzz.y0;
1048 rect.y1 += state.trimfuzz.y1;
1049 fz_transform_rect (&rect, &ctm);
1050 fz_intersect_rect (&rect, &page->mediabox);
1052 if (fz_is_empty_rect (&rect)) {
1053 mediabox = page->mediabox;
1055 else {
1056 mediabox = rect;
1059 obj = pdf_new_array (ctx, pdf, 4);
1060 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
1061 mediabox.x0));
1062 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
1063 mediabox.y0));
1064 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
1065 mediabox.x1));
1066 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
1067 mediabox.y1));
1068 pdf_dict_puts (state.ctx, pageobj, "llpp.TrimBox", obj);
1070 else {
1071 mediabox.x0 = pdf_to_real (ctx,
1072 pdf_array_get (ctx, obj, 0));
1073 mediabox.y0 = pdf_to_real (ctx,
1074 pdf_array_get (ctx, obj, 1));
1075 mediabox.x1 = pdf_to_real (ctx,
1076 pdf_array_get (ctx, obj, 2));
1077 mediabox.y1 = pdf_to_real (ctx,
1078 pdf_array_get (ctx, obj, 3));
1081 rotate = page->rotate;
1082 fz_drop_page (ctx, &page->super);
1084 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
1085 if (show) {
1086 printd ("progress %f Trimming %d",
1087 (double) (pageno + 1) / state.pagecount,
1088 pageno + 1);
1091 fz_catch (state.ctx) {
1092 fprintf (stderr, "failed to load page %d\n", pageno+1);
1095 else {
1096 int empty = 0;
1097 fz_rect cropbox;
1099 pdf_to_rect (state.ctx,
1100 pdf_dict_gets (state.ctx, pageobj, "MediaBox"),
1101 &mediabox);
1102 if (fz_is_empty_rect (&mediabox)) {
1103 mediabox.x0 = 0;
1104 mediabox.y0 = 0;
1105 mediabox.x1 = 612;
1106 mediabox.y1 = 792;
1107 empty = 1;
1110 pdf_to_rect (state.ctx,
1111 pdf_dict_gets (state.ctx, pageobj, "CropBox"),
1112 &cropbox);
1113 if (!fz_is_empty_rect (&cropbox)) {
1114 if (empty) {
1115 mediabox = cropbox;
1117 else {
1118 fz_intersect_rect (&mediabox, &cropbox);
1121 else {
1122 if (empty) {
1123 if (fz_is_empty_rect (&rootmediabox)) {
1124 fprintf (stderr,
1125 "cannot find page size for page %d\n",
1126 pageno+1);
1128 else {
1129 mediabox = rootmediabox;
1133 rotate = pdf_to_int (state.ctx,
1134 pdf_dict_gets (state.ctx,
1135 pageobj, "Rotate"));
1137 break;
1140 case DANY:
1141 if (state.trimmargins && trimw) {
1142 fz_page *page;
1144 fz_try (state.ctx) {
1145 page = fz_load_page (state.ctx, state.u.doc, pageno);
1146 fz_bound_page (state.ctx, page, &mediabox);
1147 rotate = 0;
1148 if (state.trimmargins) {
1149 fz_rect rect;
1150 fz_device *dev;
1152 dev = fz_new_bbox_device (state.ctx, &rect);
1153 dev->hints |= FZ_IGNORE_SHADE;
1154 fz_run_page (state.ctx, page, dev,
1155 &fz_identity, NULL);
1156 fz_drop_device (state.ctx, dev);
1158 rect.x0 += state.trimfuzz.x0;
1159 rect.x1 += state.trimfuzz.x1;
1160 rect.y0 += state.trimfuzz.y0;
1161 rect.y1 += state.trimfuzz.y1;
1162 fz_intersect_rect (&rect, &mediabox);
1164 if (!fz_is_empty_rect (&rect)) {
1165 mediabox = rect;
1168 fz_drop_page (state.ctx, page);
1169 if (!state.cxack) {
1170 printd ("progress %f loading %d",
1171 (double) (pageno + 1) / state.pagecount,
1172 pageno + 1);
1175 fz_catch (state.ctx) {
1177 if (trimf) {
1178 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1179 if (n - 1) {
1180 err (1, "fwrite trim mediabox");
1184 else {
1185 if (trimf) {
1186 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1187 if (n - 1) {
1188 err (1, "fread trim mediabox %d", pageno);
1191 else {
1192 fz_page *page;
1193 fz_try (state.ctx) {
1194 page = fz_load_page (state.ctx,
1195 state.u.doc, pageno);
1196 fz_bound_page (state.ctx, page, &mediabox);
1197 fz_drop_page (state.ctx, page);
1199 show = !state.trimmargins && pageno % 20 == 0;
1200 if (show) {
1201 printd ("progress %f Gathering dimensions %d",
1202 (double) (pageno) / state.pagecount,
1203 pageno);
1206 fz_catch (state.ctx) {
1207 fprintf (stderr, "failed to load page %d\n", pageno);
1211 break;
1213 default:
1214 ARSERT (0 && state.type);
1217 if (state.pagedimcount == 0
1218 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1219 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1220 size_t size;
1222 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1223 state.pagedims = realloc (state.pagedims, size);
1224 if (!state.pagedims) {
1225 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1226 size, state.pagedimcount + 1);
1229 p = &state.pagedims[state.pagedimcount++];
1230 p->rotate = rotate;
1231 p->mediabox = mediabox;
1232 p->pageno = pageno;
1235 end = now ();
1236 if (state.trimmargins) {
1237 printd ("progress 1 Trimmed %d pages in %f seconds",
1238 state.pagecount, end - start);
1240 else {
1241 printd ("progress 1 Processed %d pages in %f seconds\n",
1242 state.pagecount, end - start);
1244 state.trimanew = 0;
1245 if (trimf) {
1246 if (fclose (trimf)) {
1247 err (1, "fclose");
1252 static void layout (void)
1254 int pindex;
1255 fz_rect box;
1256 fz_matrix ctm, rm;
1257 struct pagedim *p = p;
1258 double zw, w, maxw = 0.0, zoom = zoom;
1260 if (state.pagedimcount == 0) return;
1262 switch (state.fitmodel) {
1263 case FitProportional:
1264 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1265 double x0, x1;
1267 p = &state.pagedims[pindex];
1268 fz_rotate (&rm, p->rotate + state.rotate);
1269 box = p->mediabox;
1270 fz_transform_rect (&box, &rm);
1272 x0 = MIN (box.x0, box.x1);
1273 x1 = MAX (box.x0, box.x1);
1275 w = x1 - x0;
1276 maxw = MAX (w, maxw);
1277 zoom = state.w / maxw;
1279 break;
1281 case FitPage:
1282 maxw = state.w;
1283 break;
1285 case FitWidth:
1286 break;
1288 default:
1289 ARSERT (0 && state.fitmodel);
1292 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1293 fz_rect rect;
1294 fz_matrix tm, sm;
1296 p = &state.pagedims[pindex];
1297 fz_rotate (&ctm, state.rotate);
1298 fz_rotate (&rm, p->rotate + state.rotate);
1299 box = p->mediabox;
1300 fz_transform_rect (&box, &rm);
1301 w = box.x1 - box.x0;
1302 switch (state.fitmodel) {
1303 case FitProportional:
1304 p->left = ((maxw - w) * zoom) / 2.0;
1305 break;
1306 case FitPage:
1308 double zh, h;
1309 zw = maxw / w;
1310 h = box.y1 - box.y0;
1311 zh = state.h / h;
1312 zoom = MIN (zw, zh);
1313 p->left = (maxw - (w * zoom)) / 2.0;
1315 break;
1316 case FitWidth:
1317 p->left = 0;
1318 zoom = state.w / w;
1319 break;
1322 fz_scale (&p->zoomctm, zoom, zoom);
1323 fz_concat (&ctm, &p->zoomctm, &ctm);
1325 fz_rotate (&rm, p->rotate);
1326 p->pagebox = p->mediabox;
1327 fz_transform_rect (&p->pagebox, &rm);
1328 p->pagebox.x1 -= p->pagebox.x0;
1329 p->pagebox.y1 -= p->pagebox.y0;
1330 p->pagebox.x0 = 0;
1331 p->pagebox.y0 = 0;
1332 rect = p->pagebox;
1333 fz_transform_rect (&rect, &ctm);
1334 fz_round_rect (&p->bounds, &rect);
1335 p->ctm = ctm;
1337 fz_translate (&tm, 0, -p->mediabox.y1);
1338 fz_scale (&sm, zoom, -zoom);
1339 fz_concat (&ctm, &tm, &sm);
1340 fz_concat (&p->lctm, &ctm, &rm);
1342 p->tctmready = 0;
1345 do {
1346 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1347 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1348 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1349 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1350 int boundw = x1 - x0;
1351 int boundh = y1 - y0;
1353 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1354 } while (p-- != state.pagedims);
1357 static
1358 struct anchor { int n; int x; int y; int w; int h; }
1359 desttoanchor (fz_link_dest *dest)
1361 int i;
1362 struct anchor a;
1363 struct pagedim *pdim = state.pagedims;
1365 a.n = -1;
1366 a.x = 0;
1367 a.y = 0;
1368 for (i = 0; i < state.pagedimcount; ++i) {
1369 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1370 break;
1371 pdim = &state.pagedims[i];
1373 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1374 fz_point p;
1375 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1376 p.x = dest->ld.gotor.lt.x;
1377 else
1378 p.x = 0.0;
1379 p.y = dest->ld.gotor.lt.y;
1380 fz_transform_point (&p, &pdim->lctm);
1381 a.x = p.x;
1382 a.y = p.y;
1384 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1385 double x0, x1, y0, y1;
1387 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1388 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1389 a.w = x1 - x0;
1390 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1391 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1392 a.h = y1 - y0;
1393 a.n = dest->ld.gotor.page;
1395 return a;
1398 static void recurse_outline (fz_outline *outline, int level)
1400 while (outline) {
1401 switch (outline->dest.kind) {
1402 case FZ_LINK_GOTO:
1404 struct anchor a = desttoanchor (&outline->dest);
1406 if (a.n >= 0) {
1407 printd ("o %d %d %d %d %s",
1408 level, a.n, a.y, a.h, outline->title);
1411 break;
1413 case FZ_LINK_URI:
1414 printd ("ou %d %" FMT_s " %s %s", level,
1415 strlen (outline->title), outline->title,
1416 outline->dest.ld.uri.uri);
1417 break;
1419 case FZ_LINK_NONE:
1420 printd ("on %d %s", level, outline->title);
1421 break;
1423 default:
1424 printd ("emsg Unhandled outline kind %d for %s\n",
1425 outline->dest.kind, outline->title);
1426 break;
1428 if (outline->down) {
1429 recurse_outline (outline->down, level + 1);
1431 outline = outline->next;
1435 static void process_outline (void)
1437 fz_outline *outline;
1439 if (!state.needoutline || !state.pagedimcount) return;
1441 state.needoutline = 0;
1442 outline = fz_load_outline (state.ctx, state.u.doc);
1443 if (outline) {
1444 recurse_outline (outline, 0);
1445 fz_drop_outline (state.ctx, outline);
1449 static char *strofspan (fz_text_span *span)
1451 char *p;
1452 char utf8[10];
1453 fz_text_char *ch;
1454 size_t size = 0, cap = 80;
1456 p = malloc (cap + 1);
1457 if (!p) return NULL;
1459 for (ch = span->text; ch < span->text + span->len; ++ch) {
1460 int n = fz_runetochar (utf8, ch->c);
1461 if (size + n > cap) {
1462 cap *= 2;
1463 p = realloc (p, cap + 1);
1464 if (!p) return NULL;
1467 memcpy (p + size, utf8, n);
1468 size += n;
1470 p[size] = 0;
1471 return p;
1474 static int matchspan (regex_t *re, fz_text_span *span,
1475 int stop, int pageno, double start)
1477 int ret;
1478 char *p;
1479 regmatch_t rm;
1480 int a, b, c;
1481 fz_rect sb, eb;
1482 fz_point p1, p2, p3, p4;
1484 p = strofspan (span);
1485 if (!p) return -1;
1487 ret = regexec (re, p, 1, &rm, 0);
1488 if (ret) {
1489 free (p);
1490 if (ret != REG_NOMATCH) {
1491 size_t size;
1492 char errbuf[80];
1493 size = regerror (ret, re, errbuf, sizeof (errbuf));
1494 printd ("msg regexec error `%.*s'",
1495 (int) size, errbuf);
1496 return -1;
1498 return 0;
1500 else {
1501 int l = span->len;
1503 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1504 c += fz_runelen (span->text[a].c);
1506 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1507 c += fz_runelen (span->text[b].c);
1510 if (fz_runelen (span->text[b].c) > 1) {
1511 b = MAX (0, b-1);
1514 fz_text_char_bbox (state.ctx, &sb, span, a);
1515 fz_text_char_bbox (state.ctx, &eb, span, b);
1517 p1.x = sb.x0;
1518 p1.y = sb.y0;
1519 p2.x = eb.x1;
1520 p2.y = sb.y0;
1521 p3.x = eb.x1;
1522 p3.y = eb.y1;
1523 p4.x = sb.x0;
1524 p4.y = eb.y1;
1526 if (!stop) {
1527 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1528 pageno, 1,
1529 p1.x, p1.y,
1530 p2.x, p2.y,
1531 p3.x, p3.y,
1532 p4.x, p4.y);
1534 printd ("progress 1 found at %d `%.*s' in %f sec",
1535 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1536 now () - start);
1538 else {
1539 printd ("match %d %d %f %f %f %f %f %f %f %f",
1540 pageno, 2,
1541 p1.x, p1.y,
1542 p2.x, p2.y,
1543 p3.x, p3.y,
1544 p4.x, p4.y);
1546 free (p);
1547 return 1;
1551 static int compareblocks (const void *l, const void *r)
1553 fz_text_block const *ls = l;
1554 fz_text_block const* rs = r;
1555 return ls->bbox.y0 - rs->bbox.y0;
1558 /* wishful thinking function */
1559 static void search (regex_t *re, int pageno, int y, int forward)
1561 int i, j;
1562 fz_matrix ctm;
1563 fz_device *tdev;
1564 union {
1565 void *ptr;
1566 pdf_page *pdfpage;
1567 fz_page *anypage;
1568 } u;
1569 fz_text_page *text;
1570 fz_text_sheet *sheet;
1571 struct pagedim *pdim, *pdimprev;
1572 int stop = 0, niters = 0;
1573 double start, end;
1575 start = now ();
1576 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1577 if (niters++ == 5) {
1578 niters = 0;
1579 if (hasdata ()) {
1580 printd ("progress 1 attention requested aborting search at %d",
1581 pageno);
1582 stop = 1;
1584 else {
1585 printd ("progress %f searching in page %d",
1586 (double) (pageno + 1) / state.pagecount,
1587 pageno);
1590 pdimprev = NULL;
1591 for (i = 0; i < state.pagedimcount; ++i) {
1592 pdim = &state.pagedims[i];
1593 if (pdim->pageno == pageno) {
1594 goto found;
1596 if (pdim->pageno > pageno) {
1597 pdim = pdimprev;
1598 goto found;
1600 pdimprev = pdim;
1602 pdim = pdimprev;
1603 found:
1605 sheet = fz_new_text_sheet (state.ctx);
1606 text = fz_new_text_page (state.ctx);
1607 tdev = fz_new_text_device (state.ctx, sheet, text);
1609 switch (state.type) {
1610 case DPDF:
1611 u.ptr = NULL;
1612 fz_try (state.ctx) {
1613 u.pdfpage = pdf_load_page (state.ctx, state.u.pdf, pageno);
1614 trimctm (u.pdfpage, pdim - state.pagedims);
1615 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1616 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
1617 pdf_run_page (state.ctx, u.pdfpage, tdev, &ctm, NULL);
1618 fz_end_page (state.ctx, tdev);
1620 fz_catch (state.ctx) {
1621 fz_drop_device (state.ctx, tdev);
1622 u.ptr = NULL;
1623 goto nextiter;
1625 break;
1627 case DANY:
1628 u.anypage = fz_load_page (state.ctx, state.u.doc, pageno);
1629 fz_run_page (state.ctx, u.anypage, tdev, &pdim->ctm, NULL);
1630 break;
1632 default:
1633 ARSERT (0 && state.type);
1636 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1637 fz_drop_device (state.ctx, tdev);
1639 for (j = 0; j < text->len; ++j) {
1640 int k;
1641 fz_page_block *pb;
1642 fz_text_block *block;
1644 pb = &text->blocks[forward ? j : text->len - 1 - j];
1645 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1646 block = pb->u.text;
1648 for (k = 0; k < block->len; ++k) {
1649 fz_text_line *line;
1650 fz_text_span *span;
1652 if (forward) {
1653 line = &block->lines[k];
1654 if (line->bbox.y0 < y + 1) continue;
1656 else {
1657 line = &block->lines[block->len - 1 - k];
1658 if (line->bbox.y0 > y - 1) continue;
1661 for (span = line->first_span; span; span = span->next) {
1662 switch (matchspan (re, span, stop, pageno, start)) {
1663 case 0: break;
1664 case 1: stop = 1; break;
1665 case -1: stop = 1; goto endloop;
1670 nextiter:
1671 if (forward) {
1672 pageno += 1;
1673 y = 0;
1675 else {
1676 pageno -= 1;
1677 y = INT_MAX;
1679 endloop:
1680 fz_drop_text_page (state.ctx, text);
1681 fz_drop_text_sheet (state.ctx, sheet);
1682 if (u.ptr) {
1683 state.freepage (u.ptr);
1686 end = now ();
1687 if (!stop) {
1688 printd ("progress 1 no matches %f sec", end - start);
1690 printd ("clearrects");
1693 static void set_tex_params (int colorspace)
1695 union {
1696 unsigned char b;
1697 unsigned int s;
1698 } endianness = {1};
1700 switch (colorspace) {
1701 case 0:
1702 state.texiform = GL_RGBA8;
1703 state.texform = GL_RGBA;
1704 state.texty = GL_UNSIGNED_BYTE;
1705 state.colorspace = fz_device_rgb (state.ctx);
1706 break;
1707 case 1:
1708 state.texiform = GL_RGBA8;
1709 state.texform = GL_BGRA;
1710 state.texty = endianness.s > 1
1711 ? GL_UNSIGNED_INT_8_8_8_8
1712 : GL_UNSIGNED_INT_8_8_8_8_REV;
1713 state.colorspace = fz_device_bgr (state.ctx);
1714 break;
1715 case 2:
1716 state.texiform = GL_LUMINANCE_ALPHA;
1717 state.texform = GL_LUMINANCE_ALPHA;
1718 state.texty = GL_UNSIGNED_BYTE;
1719 state.colorspace = fz_device_gray (state.ctx);
1720 break;
1721 default:
1722 errx (1, "invalid colorspce %d", colorspace);
1726 static void realloctexts (int texcount)
1728 size_t size;
1730 if (texcount == state.texcount) return;
1732 if (texcount < state.texcount) {
1733 glDeleteTextures (state.texcount - texcount,
1734 state.texids + texcount);
1737 size = texcount * sizeof (*state.texids);
1738 state.texids = realloc (state.texids, size);
1739 if (!state.texids) {
1740 err (1, "realloc texids %" FMT_s, size);
1743 size = texcount * sizeof (*state.texowners);
1744 state.texowners = realloc (state.texowners, size);
1745 if (!state.texowners) {
1746 err (1, "realloc texowners %" FMT_s, size);
1748 if (texcount > state.texcount) {
1749 int i;
1751 glGenTextures (texcount - state.texcount,
1752 state.texids + state.texcount);
1753 for (i = state.texcount; i < texcount; ++i) {
1754 state.texowners[i].w = -1;
1755 state.texowners[i].slice = NULL;
1758 state.texcount = texcount;
1759 state.texindex = 0;
1762 static char *mbtoutf8 (char *s)
1764 char *p, *r;
1765 wchar_t *tmp;
1766 size_t i, ret, len;
1768 len = mbstowcs (NULL, s, strlen (s));
1769 if (len == 0) {
1770 return s;
1772 else {
1773 if (len == (size_t) -1) {
1774 return s;
1778 tmp = malloc (len * sizeof (wchar_t));
1779 if (!tmp) {
1780 return s;
1783 ret = mbstowcs (tmp, s, len);
1784 if (ret == (size_t) -1) {
1785 free (tmp);
1786 return s;
1789 len = 0;
1790 for (i = 0; i < ret; ++i) {
1791 len += fz_runelen (tmp[i]);
1794 p = r = malloc (len + 1);
1795 if (!r) {
1796 free (tmp);
1797 return s;
1800 for (i = 0; i < ret; ++i) {
1801 p += fz_runetochar (p, tmp[i]);
1803 *p = 0;
1804 free (tmp);
1805 return r;
1808 CAMLprim value ml_mbtoutf8 (value s_v)
1810 CAMLparam1 (s_v);
1811 CAMLlocal1 (ret_v);
1812 char *s, *r;
1814 s = String_val (s_v);
1815 r = mbtoutf8 (s);
1816 if (r == s) {
1817 ret_v = s_v;
1819 else {
1820 ret_v = caml_copy_string (r);
1821 free (r);
1823 CAMLreturn (ret_v);
1826 static void * mainloop (void UNUSED_ATTR *unused)
1828 char *p = NULL;
1829 int len, ret, oldlen = 0;
1831 for (;;) {
1832 len = readlen ();
1833 if (len == 0) {
1834 errx (1, "readlen returned 0");
1837 if (oldlen < len + 1) {
1838 p = realloc (p, len + 1);
1839 if (!p) {
1840 err (1, "realloc %d failed", len + 1);
1842 oldlen = len + 1;
1844 readdata (p, len);
1845 p[len] = 0;
1847 if (!strncmp ("open", p, 4)) {
1848 int wthack, off, ok = 0;
1849 char *password;
1850 char *filename;
1851 char *utf8filename;
1852 size_t filenamelen;
1854 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1855 if (ret != 2) {
1856 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1859 filename = p + 5 + off;
1860 filenamelen = strlen (filename);
1861 password = filename + filenamelen + 1;
1863 lock ("open");
1864 fz_try (state.ctx) {
1865 ok = openxref (filename, password);
1867 fz_catch (state.ctx) {
1868 utf8filename = mbtoutf8 (filename);
1869 printd ("msg Could not open %s", utf8filename);
1871 if (ok) {
1872 pdfinfo ();
1873 initpdims ();
1875 unlock ("open");
1877 if (ok) {
1878 if (!wthack) {
1879 utf8filename = mbtoutf8 (filename);
1880 printd ("msg Opened %s (press h/F1 to get help)",
1881 utf8filename);
1882 if (utf8filename != filename) {
1883 free (utf8filename);
1886 state.needoutline = 1;
1889 else if (!strncmp ("cs", p, 2)) {
1890 int i, colorspace;
1892 ret = sscanf (p + 2, " %d", &colorspace);
1893 if (ret != 1) {
1894 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1896 lock ("cs");
1897 set_tex_params (colorspace);
1898 for (i = 0; i < state.texcount; ++i) {
1899 state.texowners[i].w = -1;
1900 state.texowners[i].slice = NULL;
1902 unlock ("cs");
1904 else if (!strncmp ("freepage", p, 8)) {
1905 void *ptr;
1907 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1908 if (ret != 1) {
1909 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1911 freepage (ptr);
1913 else if (!strncmp ("freetile", p, 8)) {
1914 void *ptr;
1916 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1917 if (ret != 1) {
1918 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1920 freetile (ptr);
1922 else if (!strncmp ("search", p, 6)) {
1923 int icase, pageno, y, len2, forward;
1924 char *pattern;
1925 regex_t re;
1927 ret = sscanf (p + 6, " %d %d %d %d,%n",
1928 &icase, &pageno, &y, &forward, &len2);
1929 if (ret != 4) {
1930 errx (1, "malformed search `%s' ret=%d", p, ret);
1933 pattern = p + 6 + len2;
1934 ret = regcomp (&re, pattern,
1935 REG_EXTENDED | (icase ? REG_ICASE : 0));
1936 if (ret) {
1937 char errbuf[80];
1938 size_t size;
1940 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1941 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1943 else {
1944 search (&re, pageno, y, forward);
1945 regfree (&re);
1948 else if (!strncmp ("geometry", p, 8)) {
1949 int w, h, fitmodel;
1951 printd ("clear");
1952 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1953 if (ret != 3) {
1954 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1957 lock ("geometry");
1958 state.h = h;
1959 if (w != state.w) {
1960 int i;
1961 state.w = w;
1962 for (i = 0; i < state.texcount; ++i) {
1963 state.texowners[i].slice = NULL;
1966 state.fitmodel = fitmodel;
1967 layout ();
1968 process_outline ();
1970 state.gen++;
1971 unlock ("geometry");
1972 printd ("continue %d", state.pagecount);
1974 else if (!strncmp ("reqlayout", p, 9)) {
1975 char *nameddest;
1976 int rotate, off, h;
1977 unsigned int fitmodel;
1979 printd ("clear");
1980 ret = sscanf (p + 9, " %d %u %d %n",
1981 &rotate, &fitmodel, &h, &off);
1982 if (ret != 3) {
1983 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1985 lock ("reqlayout");
1986 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1987 state.gen += 1;
1989 state.rotate = rotate;
1990 state.fitmodel = fitmodel;
1991 state.h = h;
1992 layout ();
1993 process_outline ();
1995 nameddest = p + 9 + off;
1996 if (state.type == DPDF && nameddest && *nameddest) {
1997 struct anchor a;
1998 fz_link_dest dest;
1999 pdf_obj *needle, *obj;
2001 needle = pdf_new_string (state.ctx, state.u.pdf, nameddest,
2002 strlen (nameddest));
2003 obj = pdf_lookup_dest (state.ctx, state.u.pdf, needle);
2004 if (obj) {
2005 dest = pdf_parse_link_dest (state.ctx, state.u.pdf,
2006 FZ_LINK_GOTO, obj);
2008 a = desttoanchor (&dest);
2009 if (a.n >= 0) {
2010 printd ("a %d %d %d", a.n, a.x, a.y);
2012 else {
2013 printd ("emsg failed to parse destination `%s'\n",
2014 nameddest);
2017 else {
2018 printd ("emsg destination `%s' not found\n",
2019 nameddest);
2021 pdf_drop_obj (state.ctx, needle);
2024 state.gen++;
2025 unlock ("reqlayout");
2026 printd ("continue %d", state.pagecount);
2028 else if (!strncmp ("page", p, 4)) {
2029 double a, b;
2030 struct page *page;
2031 int pageno, pindex;
2033 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
2034 if (ret != 2) {
2035 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
2038 lock ("page");
2039 a = now ();
2040 page = loadpage (pageno, pindex);
2041 b = now ();
2042 unlock ("page");
2044 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
2046 else if (!strncmp ("tile", p, 4)) {
2047 int x, y, w, h;
2048 struct page *page;
2049 struct tile *tile;
2050 double a, b;
2051 void *data;
2053 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
2054 SCN_ptr_cast (&page), &x, &y, &w, &h,
2055 SCN_ptr_cast (&data));
2056 if (ret != 6) {
2057 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
2060 lock ("tile");
2061 a = now ();
2062 tile = rendertile (page, x, y, w, h, data);
2063 b = now ();
2064 unlock ("tile");
2066 printd ("tile %d %d %" FMT_ptr " %u %f",
2067 x, y,
2068 FMT_ptr_cast (tile),
2069 tile->w * tile->h * tile->pixmap->n,
2070 b - a);
2072 else if (!strncmp ("trimset", p, 7)) {
2073 fz_irect fuzz;
2074 int trimmargins;
2076 ret = sscanf (p + 7, " %d %d %d %d %d",
2077 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
2078 if (ret != 5) {
2079 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
2081 lock ("trimset");
2082 state.trimmargins = trimmargins;
2083 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
2084 state.trimanew = 1;
2085 state.trimfuzz = fuzz;
2087 unlock ("trimset");
2089 else if (!strncmp ("settrim", p, 7)) {
2090 fz_irect fuzz;
2091 int trimmargins;
2093 ret = sscanf (p + 7, " %d %d %d %d %d",
2094 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
2095 if (ret != 5) {
2096 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
2098 printd ("clear");
2099 lock ("settrim");
2100 state.trimmargins = trimmargins;
2101 state.needoutline = 1;
2102 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
2103 state.trimanew = 1;
2104 state.trimfuzz = fuzz;
2106 state.pagedimcount = 0;
2107 free (state.pagedims);
2108 state.pagedims = NULL;
2109 initpdims ();
2110 layout ();
2111 process_outline ();
2112 unlock ("settrim");
2113 printd ("continue %d", state.pagecount);
2115 else if (!strncmp ("sliceh", p, 6)) {
2116 int h;
2118 ret = sscanf (p + 6, " %d", &h);
2119 if (ret != 1) {
2120 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
2122 if (h != state.sliceheight) {
2123 int i;
2125 state.sliceheight = h;
2126 for (i = 0; i < state.texcount; ++i) {
2127 state.texowners[i].w = -1;
2128 state.texowners[i].h = -1;
2129 state.texowners[i].slice = NULL;
2133 else if (!strncmp ("interrupt", p, 9)) {
2134 printd ("vmsg interrupted");
2136 else {
2137 errx (1, "unknown command %.*s", len, p);
2140 return 0;
2143 CAMLprim value ml_realloctexts (value texcount_v)
2145 CAMLparam1 (texcount_v);
2146 int ok;
2148 if (trylock ("ml_realloctexts")) {
2149 ok = 0;
2150 goto done;
2152 realloctexts (Int_val (texcount_v));
2153 ok = 1;
2154 unlock ("ml_realloctexts");
2156 done:
2157 CAMLreturn (Val_bool (ok));
2160 static void recti (int x0, int y0, int x1, int y1)
2162 GLfloat *v = state.vertices;
2164 glVertexPointer (2, GL_FLOAT, 0, v);
2165 v[0] = x0; v[1] = y0;
2166 v[2] = x1; v[3] = y0;
2167 v[4] = x0; v[5] = y1;
2168 v[6] = x1; v[7] = y1;
2169 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2172 static void showsel (struct page *page, int ox, int oy)
2174 int seen = 0;
2175 fz_irect bbox;
2176 fz_rect rect;
2177 fz_text_line *line;
2178 fz_page_block *pageb;
2179 fz_text_block *block;
2180 struct mark first, last;
2181 unsigned char selcolor[] = {15,15,15,140};
2183 first = page->fmark;
2184 last = page->lmark;
2186 if (!first.span || !last.span) return;
2188 glEnable (GL_BLEND);
2189 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2190 glColor4ubv (selcolor);
2192 ox += state.pagedims[page->pdimno].bounds.x0;
2193 oy += state.pagedims[page->pdimno].bounds.y0;
2194 for (pageb = page->text->blocks;
2195 pageb < page->text->blocks + page->text->len;
2196 ++pageb) {
2197 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2198 block = pageb->u.text;
2200 for (line = block->lines;
2201 line < block->lines + block->len;
2202 ++line) {
2203 fz_text_span *span;
2204 rect = fz_empty_rect;
2206 for (span = line->first_span; span; span = span->next) {
2207 int i, j, k;
2208 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2210 j = 0;
2211 k = span->len - 1;
2213 if (span == page->fmark.span && span == page->lmark.span) {
2214 seen = 1;
2215 j = MIN (first.i, last.i);
2216 k = MAX (first.i, last.i);
2218 else {
2219 if (span == first.span) {
2220 seen = 1;
2221 j = first.i;
2223 else if (span == last.span) {
2224 seen = 1;
2225 k = last.i;
2229 if (seen) {
2230 for (i = j; i <= k; ++i) {
2231 fz_rect bbox1;
2232 fz_union_rect (&rect,
2233 fz_text_char_bbox (state.ctx, &bbox1,
2234 span, i));
2236 fz_round_rect (&bbox, &rect);
2237 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2238 bbox.x0,
2239 bbox.y0,
2240 bbox.x1,
2241 bbox.y1,
2242 oy, ox);
2244 recti (bbox.x0 + ox, bbox.y0 + oy,
2245 bbox.x1 + ox, bbox.y1 + oy);
2246 if (span == last.span) {
2247 goto done;
2249 rect = fz_empty_rect;
2254 done:
2255 glDisable (GL_BLEND);
2258 #include "glfont.c"
2260 static void stipplerect (fz_matrix *m,
2261 fz_point *p1,
2262 fz_point *p2,
2263 fz_point *p3,
2264 fz_point *p4,
2265 GLfloat *texcoords,
2266 GLfloat *vertices)
2268 fz_transform_point (p1, m);
2269 fz_transform_point (p2, m);
2270 fz_transform_point (p3, m);
2271 fz_transform_point (p4, m);
2273 float w, h, s, t;
2275 w = p2->x - p1->x;
2276 h = p2->y - p1->y;
2277 t = sqrtf (w*w + h*h) * .25f;
2279 w = p3->x - p2->x;
2280 h = p3->y - p2->y;
2281 s = sqrtf (w*w + h*h) * .25f;
2283 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2284 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2286 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2287 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2289 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2290 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2292 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2293 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2295 glDrawArrays (GL_LINES, 0, 8);
2298 static void highlightlinks (struct page *page, int xoff, int yoff)
2300 int i;
2301 fz_matrix ctm, tm, pm;
2302 fz_link *link, *links;
2303 GLfloat *texcoords = state.texcoords;
2304 GLfloat *vertices = state.vertices;
2306 links = fz_load_links (state.ctx, page->u.anypage);
2308 glEnable (GL_TEXTURE_1D);
2309 glEnable (GL_BLEND);
2310 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2311 glBindTexture (GL_TEXTURE_1D, state.stid);
2313 xoff -= state.pagedims[page->pdimno].bounds.x0;
2314 yoff -= state.pagedims[page->pdimno].bounds.y0;
2315 fz_translate (&tm, xoff, yoff);
2316 pm = pagectm (page);
2317 fz_concat (&ctm, &pm, &tm);
2319 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2320 glVertexPointer (2, GL_FLOAT, 0, vertices);
2322 for (link = links; link; link = link->next) {
2323 fz_point p1, p2, p3, p4;
2325 p1.x = link->rect.x0;
2326 p1.y = link->rect.y0;
2328 p2.x = link->rect.x1;
2329 p2.y = link->rect.y0;
2331 p3.x = link->rect.x1;
2332 p3.y = link->rect.y1;
2334 p4.x = link->rect.x0;
2335 p4.y = link->rect.y1;
2337 switch (link->dest.kind) {
2338 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2339 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2340 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2341 default: glColor3ub (0, 0, 0); break;
2343 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2346 for (i = 0; i < page->annotcount; ++i) {
2347 fz_point p1, p2, p3, p4;
2348 struct annot *annot = &page->annots[i];
2350 p1.x = annot->bbox.x0;
2351 p1.y = annot->bbox.y0;
2353 p2.x = annot->bbox.x1;
2354 p2.y = annot->bbox.y0;
2356 p3.x = annot->bbox.x1;
2357 p3.y = annot->bbox.y1;
2359 p4.x = annot->bbox.x0;
2360 p4.y = annot->bbox.y1;
2362 glColor3ub (0, 0, 128);
2363 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2366 glDisable (GL_BLEND);
2367 glDisable (GL_TEXTURE_1D);
2370 static int compareslinks (const void *l, const void *r)
2372 struct slink const *ls = l;
2373 struct slink const *rs = r;
2374 if (ls->bbox.y0 == rs->bbox.y0) {
2375 return rs->bbox.x0 - rs->bbox.x0;
2377 return ls->bbox.y0 - rs->bbox.y0;
2380 static void droptext (struct page *page)
2382 if (page->text) {
2383 fz_drop_text_page (state.ctx, page->text);
2384 page->fmark.i = -1;
2385 page->lmark.i = -1;
2386 page->fmark.span = NULL;
2387 page->lmark.span = NULL;
2388 page->text = NULL;
2390 if (page->sheet) {
2391 fz_drop_text_sheet (state.ctx, page->sheet);
2392 page->sheet = NULL;
2396 static void dropanots (struct page *page)
2398 if (page->annots) {
2399 free (page->annots);
2400 page->annots = NULL;
2401 page->annotcount = 0;
2405 static void ensureanots (struct page *page)
2407 fz_matrix ctm;
2408 int i, count = 0;
2409 size_t anotsize = sizeof (*page->annots);
2410 pdf_annot *annot;
2412 if (state.gen != page->agen) {
2413 dropanots (page);
2414 page->agen = state.gen;
2416 if (page->annots) return;
2418 switch (page->type) {
2419 case DPDF:
2420 trimctm (page->u.pdfpage, page->pdimno);
2421 fz_concat (&ctm,
2422 &state.pagedims[page->pdimno].tctm,
2423 &state.pagedims[page->pdimno].ctm);
2424 break;
2426 default:
2427 return;
2430 for (annot = pdf_first_annot (state.ctx, page->u.pdfpage);
2431 annot;
2432 annot = pdf_next_annot (state.ctx, page->u.pdfpage, annot)) {
2433 count++;
2436 if (count > 0) {
2437 page->annotcount = count;
2438 page->annots = calloc (count, anotsize);
2439 if (!page->annots) {
2440 err (1, "calloc annots %d", count);
2443 for (annot = pdf_first_annot (state.ctx, page->u.pdfpage), i = 0;
2444 annot;
2445 annot = pdf_next_annot (state.ctx, page->u.pdfpage, annot), i++) {
2446 fz_rect rect;
2448 pdf_bound_annot (state.ctx, page->u.pdfpage, annot, &rect);
2449 fz_transform_rect (&rect, &ctm);
2450 page->annots[i].annot = annot;
2451 fz_round_rect (&page->annots[i].bbox, &annot->pagerect);
2456 static void dropslinks (struct page *page)
2458 if (page->slinks) {
2459 free (page->slinks);
2460 page->slinks = NULL;
2461 page->slinkcount = 0;
2465 static void ensureslinks (struct page *page)
2467 fz_matrix ctm;
2468 int i, count;
2469 size_t slinksize = sizeof (*page->slinks);
2470 fz_link *link, *links;
2472 ensureanots (page);
2473 if (state.gen != page->sgen) {
2474 dropslinks (page);
2475 page->sgen = state.gen;
2477 if (page->slinks) return;
2479 switch (page->type) {
2480 case DPDF:
2481 links = page->u.pdfpage->links;
2482 trimctm (page->u.pdfpage, page->pdimno);
2483 fz_concat (&ctm,
2484 &state.pagedims[page->pdimno].tctm,
2485 &state.pagedims[page->pdimno].ctm);
2486 break;
2488 case DANY:
2489 links = fz_load_links (state.ctx, page->u.anypage);
2490 ctm = state.pagedims[page->pdimno].ctm;
2491 break;
2493 default:
2494 return;
2497 count = page->annotcount;
2498 for (link = links; link; link = link->next) {
2499 count++;
2501 if (count > 0) {
2502 int j;
2504 page->slinkcount = count;
2505 page->slinks = calloc (count, slinksize);
2506 if (!page->slinks) {
2507 err (1, "calloc slinks %d", count);
2510 for (i = 0, link = links; link; ++i, link = link->next) {
2511 fz_rect rect;
2513 rect = link->rect;
2514 fz_transform_rect (&rect, &ctm);
2515 page->slinks[i].tag = SLINK;
2516 page->slinks[i].u.link = link;
2517 fz_round_rect (&page->slinks[i].bbox, &rect);
2519 for (j = 0; j < page->annotcount; ++j, ++i) {
2520 fz_rect rect;
2522 rect = page->annots[j].annot->pagerect;
2523 fz_transform_rect (&rect, &ctm);
2524 fz_round_rect (&page->slinks[i].bbox, &rect);
2526 page->slinks[i].tag = SANNOT;
2527 page->slinks[i].u.annot = page->annots[j].annot;
2529 qsort (page->slinks, count, slinksize, compareslinks);
2533 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2534 static void fmt_linkn (char *s, unsigned int u)
2536 unsigned int len; unsigned int q;
2537 unsigned int zma = 'z' - 'a' + 1;
2538 len = 1; q = u;
2539 while (q > zma - 1) { ++len; q /= zma; }
2540 if (s) {
2541 s += len;
2542 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2543 /* handles u == 0 */
2545 s[len] = 0;
2548 static void highlightslinks (struct page *page, int xoff, int yoff,
2549 int noff, char *targ, int tlen, int hfsize)
2551 int i;
2552 char buf[40];
2553 struct slink *slink;
2554 double x0, y0, x1, y1, w;
2556 ensureslinks (page);
2557 glColor3ub (0xc3, 0xb0, 0x91);
2558 for (i = 0; i < page->slinkcount; ++i) {
2559 fmt_linkn (buf, i + noff);
2560 if (!tlen || !strncmp (targ, buf, tlen)) {
2561 slink = &page->slinks[i];
2563 x0 = slink->bbox.x0 + xoff - 5;
2564 y1 = slink->bbox.y0 + yoff - 5;
2565 y0 = y1 + 10 + hfsize;
2566 w = measure_string (state.face, hfsize, buf);
2567 x1 = x0 + w + 10;
2568 recti (x0, y0, x1, y1);
2572 glEnable (GL_BLEND);
2573 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2574 glEnable (GL_TEXTURE_2D);
2575 glColor3ub (0, 0, 0);
2576 for (i = 0; i < page->slinkcount; ++i) {
2577 fmt_linkn (buf, i + noff);
2578 if (!tlen || !strncmp (targ, buf, tlen)) {
2579 slink = &page->slinks[i];
2581 x0 = slink->bbox.x0 + xoff;
2582 y0 = slink->bbox.y0 + yoff + hfsize;
2583 draw_string (state.face, hfsize, x0, y0, buf);
2586 glDisable (GL_TEXTURE_2D);
2587 glDisable (GL_BLEND);
2590 static void uploadslice (struct tile *tile, struct slice *slice)
2592 int offset;
2593 struct slice *slice1;
2594 unsigned char *texdata;
2596 offset = 0;
2597 for (slice1 = tile->slices; slice != slice1; slice1++) {
2598 offset += slice1->h * tile->w * tile->pixmap->n;
2600 if (slice->texindex != -1 && slice->texindex < state.texcount
2601 && state.texowners[slice->texindex].slice == slice) {
2602 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2604 else {
2605 int subimage = 0;
2606 int texindex = state.texindex++ % state.texcount;
2608 if (state.texowners[texindex].w == tile->w) {
2609 if (state.texowners[texindex].h >= slice->h) {
2610 subimage = 1;
2612 else {
2613 state.texowners[texindex].h = slice->h;
2616 else {
2617 state.texowners[texindex].h = slice->h;
2620 state.texowners[texindex].w = tile->w;
2621 state.texowners[texindex].slice = slice;
2622 slice->texindex = texindex;
2624 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2625 if (tile->pbo) {
2626 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2627 texdata = 0;
2629 else {
2630 texdata = tile->pixmap->samples;
2632 if (subimage) {
2633 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2637 tile->w,
2638 slice->h,
2639 state.texform,
2640 state.texty,
2641 texdata+offset
2644 else {
2645 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2647 state.texiform,
2648 tile->w,
2649 slice->h,
2651 state.texform,
2652 state.texty,
2653 texdata+offset
2656 if (tile->pbo) {
2657 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2662 CAMLprim value ml_begintiles (value unit_v)
2664 CAMLparam1 (unit_v);
2665 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2666 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2667 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2668 CAMLreturn (unit_v);
2671 CAMLprim value ml_endtiles (value unit_v)
2673 CAMLparam1 (unit_v);
2674 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2675 CAMLreturn (unit_v);
2678 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2680 CAMLparam2 (args_v, ptr_v);
2681 int dispx = Int_val (Field (args_v, 0));
2682 int dispy = Int_val (Field (args_v, 1));
2683 int dispw = Int_val (Field (args_v, 2));
2684 int disph = Int_val (Field (args_v, 3));
2685 int tilex = Int_val (Field (args_v, 4));
2686 int tiley = Int_val (Field (args_v, 5));
2687 char *s = String_val (ptr_v);
2688 struct tile *tile = parse_pointer ("ml_drawtile", s);
2689 int slicey, firstslice;
2690 struct slice *slice;
2691 GLfloat *texcoords = state.texcoords;
2692 GLfloat *vertices = state.vertices;
2694 firstslice = tiley / tile->sliceheight;
2695 slice = &tile->slices[firstslice];
2696 slicey = tiley % tile->sliceheight;
2698 while (disph > 0) {
2699 int dh;
2701 dh = slice->h - slicey;
2702 dh = MIN (disph, dh);
2703 uploadslice (tile, slice);
2705 texcoords[0] = tilex; texcoords[1] = slicey;
2706 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2707 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2708 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2710 vertices[0] = dispx; vertices[1] = dispy;
2711 vertices[2] = dispx+dispw; vertices[3] = dispy;
2712 vertices[4] = dispx; vertices[5] = dispy+dh;
2713 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2715 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2716 dispy += dh;
2717 disph -= dh;
2718 slice++;
2719 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2720 slicey = 0;
2722 CAMLreturn (Val_unit);
2725 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2726 value xoff_v, value yoff_v,
2727 value li_v)
2729 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2730 int xoff = Int_val (xoff_v);
2731 int yoff = Int_val (yoff_v);
2732 int noff = Int_val (Field (li_v, 0));
2733 char *targ = String_val (Field (li_v, 1));
2734 int tlen = caml_string_length (Field (li_v, 1));
2735 int hfsize = Int_val (Field (li_v, 2));
2736 char *s = String_val (ptr_v);
2737 int hlmask = Int_val (hlinks_v);
2738 struct page *page = parse_pointer ("ml_postprocess", s);
2740 if (!page->u.ptr) {
2741 /* deal with loadpage failed pages */
2742 goto done;
2745 ensureanots (page);
2747 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2748 if (trylock ("ml_postprocess")) {
2749 noff = 0;
2750 goto done;
2752 if (hlmask & 2) {
2753 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2754 noff = page->slinkcount;
2756 if (page->tgen == state.gen) {
2757 showsel (page, xoff, yoff);
2759 unlock ("ml_postprocess");
2761 done:
2762 CAMLreturn (Val_int (noff));
2765 static struct annot *getannot (struct page *page, int x, int y)
2767 int i;
2768 fz_point p;
2769 fz_matrix ctm;
2770 const fz_matrix *tctm;
2772 if (!page->annots) return NULL;
2774 switch (page->type) {
2775 case DPDF:
2776 trimctm (page->u.pdfpage, page->pdimno);
2777 tctm = &state.pagedims[page->pdimno].tctm;
2778 break;
2780 case DANY:
2781 tctm = &fz_identity;
2782 break;
2784 default:
2785 return NULL;
2788 p.x = x;
2789 p.y = y;
2791 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2792 fz_invert_matrix (&ctm, &ctm);
2793 fz_transform_point (&p, &ctm);
2795 for (i = 0; i < page->annotcount; ++i) {
2796 struct annot *a = &page->annots[i];
2797 if (p.x >= a->annot->pagerect.x0 && p.x <= a->annot->pagerect.x1) {
2798 if (p.y >= a->annot->pagerect.y0 && p.y <= a->annot->pagerect.y1) {
2799 return a;
2803 return NULL;
2806 static fz_link *getlink (struct page *page, int x, int y)
2808 fz_point p;
2809 fz_matrix ctm;
2810 const fz_matrix *tctm;
2811 fz_link *link, *links;
2813 switch (page->type) {
2814 case DPDF + 10:
2815 trimctm (page->u.pdfpage, page->pdimno);
2816 tctm = &state.pagedims[page->pdimno].tctm;
2817 links = page->u.pdfpage->links;
2818 break;
2820 case DANY:
2821 tctm = &fz_identity;
2822 links = fz_load_links (state.ctx, page->u.anypage);
2823 break;
2825 default:
2826 return NULL;
2828 p.x = x;
2829 p.y = y;
2831 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2832 fz_invert_matrix (&ctm, &ctm);
2833 fz_transform_point (&p, &ctm);
2835 for (link = links; link; link = link->next) {
2836 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2837 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2838 return link;
2842 return NULL;
2845 static void ensuretext (struct page *page)
2847 if (state.gen != page->tgen) {
2848 droptext (page);
2849 page->tgen = state.gen;
2851 if (!page->text) {
2852 fz_matrix ctm;
2853 fz_device *tdev;
2855 page->text = fz_new_text_page (state.ctx);
2856 page->sheet = fz_new_text_sheet (state.ctx);
2857 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2858 ctm = pagectm (page);
2859 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2860 fz_run_display_list (state.ctx, page->dlist,
2861 tdev, &ctm, &fz_infinite_rect, NULL);
2862 qsort (page->text->blocks, page->text->len,
2863 sizeof (*page->text->blocks), compareblocks);
2864 fz_end_page (state.ctx, tdev);
2865 fz_drop_device (state.ctx, tdev);
2869 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2871 CAMLparam2 (start_page_v, dir_v);
2872 CAMLlocal1 (ret_v);
2873 int i, dir = Int_val (dir_v);
2874 int start_page = Int_val (start_page_v);
2875 int end_page = dir > 0 ? state.pagecount : -1;
2877 ret_v = Val_int (0);
2878 lock ("ml_findpage_with_links");
2879 for (i = start_page + dir; i != end_page; i += dir) {
2880 int found;
2882 switch (state.type) {
2883 case DPDF:
2885 pdf_page *page = NULL;
2887 fz_try (state.ctx) {
2888 page = pdf_load_page (state.ctx, state.u.pdf, i);
2889 found = !!page->links || !!page->annots;
2891 fz_catch (state.ctx) {
2892 found = 0;
2894 if (page) {
2895 freepdfpage (page);
2898 break;
2899 case DANY:
2901 fz_page *page = fz_load_page (state.ctx, state.u.doc, i);
2902 found = !!fz_load_links (state.ctx, page);
2903 fz_drop_page (state.ctx, page);
2905 break;
2907 default:
2908 ARSERT (0 && "invalid document type");
2911 if (found) {
2912 ret_v = caml_alloc_small (1, 1);
2913 Field (ret_v, 0) = Val_int (i);
2914 goto unlock;
2917 unlock:
2918 unlock ("ml_findpage_with_links");
2919 CAMLreturn (ret_v);
2922 enum { dir_first, dir_last };
2923 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2925 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2927 CAMLparam2 (ptr_v, dir_v);
2928 CAMLlocal2 (ret_v, pos_v);
2929 struct page *page;
2930 int dirtag, i, slinkindex;
2931 struct slink *found = NULL ,*slink;
2932 char *s = String_val (ptr_v);
2934 page = parse_pointer ("ml_findlink", s);
2935 ret_v = Val_int (0);
2936 /* This is scary we are not taking locks here ensureslinks does
2937 not modify state and given that we obtained the page it can not
2938 disappear under us either */
2939 lock ("ml_findlink");
2940 ensureslinks (page);
2942 if (Is_block (dir_v)) {
2943 dirtag = Tag_val (dir_v);
2944 switch (dirtag) {
2945 case dir_first_visible:
2947 int x0, y0, dir, first_index, last_index;
2949 pos_v = Field (dir_v, 0);
2950 x0 = Int_val (Field (pos_v, 0));
2951 y0 = Int_val (Field (pos_v, 1));
2952 dir = Int_val (Field (pos_v, 2));
2954 if (dir >= 0) {
2955 dir = 1;
2956 first_index = 0;
2957 last_index = page->slinkcount;
2959 else {
2960 first_index = page->slinkcount - 1;
2961 last_index = -1;
2964 for (i = first_index; i != last_index; i += dir) {
2965 slink = &page->slinks[i];
2966 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2967 found = slink;
2968 break;
2972 break;
2974 case dir_left:
2975 slinkindex = Int_val (Field (dir_v, 0));
2976 found = &page->slinks[slinkindex];
2977 for (i = slinkindex - 1; i >= 0; --i) {
2978 slink = &page->slinks[i];
2979 if (slink->bbox.x0 < found->bbox.x0) {
2980 found = slink;
2981 break;
2984 break;
2986 case dir_right:
2987 slinkindex = Int_val (Field (dir_v, 0));
2988 found = &page->slinks[slinkindex];
2989 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2990 slink = &page->slinks[i];
2991 if (slink->bbox.x0 > found->bbox.x0) {
2992 found = slink;
2993 break;
2996 break;
2998 case dir_down:
2999 slinkindex = Int_val (Field (dir_v, 0));
3000 found = &page->slinks[slinkindex];
3001 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
3002 slink = &page->slinks[i];
3003 if (slink->bbox.y0 >= found->bbox.y0) {
3004 found = slink;
3005 break;
3008 break;
3010 case dir_up:
3011 slinkindex = Int_val (Field (dir_v, 0));
3012 found = &page->slinks[slinkindex];
3013 for (i = slinkindex - 1; i >= 0; --i) {
3014 slink = &page->slinks[i];
3015 if (slink->bbox.y0 <= found->bbox.y0) {
3016 found = slink;
3017 break;
3020 break;
3023 else {
3024 dirtag = Int_val (dir_v);
3025 switch (dirtag) {
3026 case dir_first:
3027 found = page->slinks;
3028 break;
3030 case dir_last:
3031 if (page->slinks) {
3032 found = page->slinks + (page->slinkcount - 1);
3034 break;
3037 if (found) {
3038 ret_v = caml_alloc_small (2, 1);
3039 Field (ret_v, 0) = Val_int (found - page->slinks);
3042 unlock ("ml_findlink");
3043 CAMLreturn (ret_v);
3046 enum { uuri, ugoto, utext, uunexpected, ulaunch,
3047 unamed, uremote, uremotedest, uannot };
3049 #define LINKTOVAL \
3051 int pageno; \
3053 switch (link->dest.kind) { \
3054 case FZ_LINK_GOTO: \
3056 fz_point p; \
3058 pageno = link->dest.ld.gotor.page; \
3059 p.x = 0; \
3060 p.y = 0; \
3062 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
3063 p.y = link->dest.ld.gotor.lt.y; \
3064 fz_transform_point (&p, &pdim->lctm); \
3065 if (p.y < 0) p.y = 0; \
3067 tup_v = caml_alloc_tuple (2); \
3068 ret_v = caml_alloc_small (1, ugoto); \
3069 Field (tup_v, 0) = Val_int (pageno); \
3070 Field (tup_v, 1) = Val_int (p.y); \
3071 Field (ret_v, 0) = tup_v; \
3073 break; \
3075 case FZ_LINK_URI: \
3076 str_v = caml_copy_string (link->dest.ld.uri.uri); \
3077 ret_v = caml_alloc_small (1, uuri); \
3078 Field (ret_v, 0) = str_v; \
3079 break; \
3081 case FZ_LINK_LAUNCH: \
3082 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
3083 ret_v = caml_alloc_small (1, ulaunch); \
3084 Field (ret_v, 0) = str_v; \
3085 break; \
3087 case FZ_LINK_NAMED: \
3088 str_v = caml_copy_string (link->dest.ld.named.named); \
3089 ret_v = caml_alloc_small (1, unamed); \
3090 Field (ret_v, 0) = str_v; \
3091 break; \
3093 case FZ_LINK_GOTOR: \
3095 int rty; \
3097 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
3098 pageno = link->dest.ld.gotor.page; \
3099 if (pageno == -1) { \
3100 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
3101 rty = uremotedest; \
3103 else { \
3104 gr_v = Val_int (pageno); \
3105 rty = uremote; \
3107 tup_v = caml_alloc_tuple (2); \
3108 ret_v = caml_alloc_small (1, rty); \
3109 Field (tup_v, 0) = str_v; \
3110 Field (tup_v, 1) = gr_v; \
3111 Field (ret_v, 0) = tup_v; \
3113 break; \
3115 default: \
3117 char buf[80]; \
3119 snprintf (buf, sizeof (buf), \
3120 "unhandled link kind %d", link->dest.kind); \
3121 str_v = caml_copy_string (buf); \
3122 ret_v = caml_alloc_small (1, uunexpected); \
3123 Field (ret_v, 0) = str_v; \
3125 break; \
3129 CAMLprim value ml_getlink (value ptr_v, value n_v)
3131 CAMLparam2 (ptr_v, n_v);
3132 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3133 fz_link *link;
3134 struct page *page;
3135 struct pagedim *pdim;
3136 char *s = String_val (ptr_v);
3137 struct slink *slink;
3139 /* See ml_findlink for caveat */
3141 ret_v = Val_int (0);
3142 page = parse_pointer ("ml_getlink", s);
3143 ensureslinks (page);
3144 pdim = &state.pagedims[page->pdimno];
3145 slink = &page->slinks[Int_val (n_v)];
3146 if (slink->tag == SLINK) {
3147 link = slink->u.link;
3148 LINKTOVAL;
3150 else {
3151 ret_v = caml_alloc_small (1, uannot);
3152 tup_v = caml_alloc_tuple (2);
3153 Field (ret_v, 0) = tup_v;
3154 Field (tup_v, 0) = ptr_v;
3155 Field (tup_v, 1) = n_v;
3158 unlock ("ml_getlink");
3159 CAMLreturn (ret_v);
3162 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3164 CAMLparam2 (ptr_v, n_v);
3165 char *s = String_val (ptr_v);
3166 struct page *page;
3167 struct slink *slink;
3169 page = parse_pointer ("ml_getannotcontent", s);
3170 slink = &page->slinks[Int_val (n_v)];
3171 CAMLreturn (caml_copy_string (pdf_annot_contents (state.ctx, state.u.pdf,
3172 slink->u.annot)));
3175 CAMLprim value ml_getlinkcount (value ptr_v)
3177 CAMLparam1 (ptr_v);
3178 struct page *page;
3179 char *s = String_val (ptr_v);
3181 page = parse_pointer ("ml_getlinkcount", s);
3182 CAMLreturn (Val_int (page->slinkcount));
3185 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3187 CAMLparam2 (ptr_v, n_v);
3188 CAMLlocal1 (ret_v);
3189 struct page *page;
3190 struct slink *slink;
3191 char *s = String_val (ptr_v);
3192 /* See ml_findlink for caveat */
3194 page = parse_pointer ("ml_getlinkrect", s);
3195 ret_v = caml_alloc_tuple (4);
3196 ensureslinks (page);
3198 slink = &page->slinks[Int_val (n_v)];
3199 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3200 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3201 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3202 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3203 unlock ("ml_getlinkrect");
3204 CAMLreturn (ret_v);
3207 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3209 CAMLparam3 (ptr_v, x_v, y_v);
3210 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3211 fz_link *link;
3212 struct annot *annot;
3213 struct page *page;
3214 char *ptr = String_val (ptr_v);
3215 int x = Int_val (x_v), y = Int_val (y_v);
3216 struct pagedim *pdim;
3218 ret_v = Val_int (0);
3219 if (trylock ("ml_whatsunder")) {
3220 goto done;
3223 page = parse_pointer ("ml_whatsunder", ptr);
3224 pdim = &state.pagedims[page->pdimno];
3225 x += pdim->bounds.x0;
3226 y += pdim->bounds.y0;
3228 if (1 || state.type == DPDF) {
3229 annot = getannot (page, x, y);
3230 if (annot) {
3231 int i, n = -1;
3233 ensureslinks (page);
3234 for (i = 0; i < page->slinkcount; ++i) {
3235 if (page->slinks[i].tag == SANNOT
3236 && page->slinks[i].u.annot == annot->annot) {
3237 n = i;
3238 break;
3241 ret_v = caml_alloc_small (1, uannot);
3242 tup_v = caml_alloc_tuple (2);
3243 Field (ret_v, 0) = tup_v;
3244 Field (tup_v, 0) = ptr_v;
3245 Field (tup_v, 1) = Val_int (n);
3246 goto unlock;
3250 link = getlink (page, x, y);
3251 if (link) {
3252 LINKTOVAL;
3254 else {
3255 fz_rect *b;
3256 fz_page_block *pageb;
3257 fz_text_block *block;
3259 ensuretext (page);
3260 for (pageb = page->text->blocks;
3261 pageb < page->text->blocks + page->text->len;
3262 ++pageb) {
3263 fz_text_line *line;
3264 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3265 block = pageb->u.text;
3267 b = &block->bbox;
3268 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3269 continue;
3271 for (line = block->lines;
3272 line < block->lines + block->len;
3273 ++line) {
3274 fz_text_span *span;
3276 b = &line->bbox;
3277 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3278 continue;
3280 for (span = line->first_span; span; span = span->next) {
3281 int charnum;
3283 b = &span->bbox;
3284 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3285 continue;
3287 for (charnum = 0; charnum < span->len; ++charnum) {
3288 fz_rect bbox;
3289 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3290 b = &bbox;
3292 if (x >= b->x0 && x <= b->x1
3293 && y >= b->y0 && y <= b->y1) {
3294 fz_text_style *style = span->text->style;
3295 const char *n2 =
3296 style->font && style->font->name
3297 ? style->font->name
3298 : "Span has no font name"
3300 FT_FaceRec *face = style->font->ft_face;
3301 if (face && face->family_name) {
3302 char *s;
3303 char *n1 = face->family_name;
3304 size_t l1 = strlen (n1);
3305 size_t l2 = strlen (n2);
3307 if (l1 != l2 || memcmp (n1, n2, l1)) {
3308 s = malloc (l1 + l2 + 2);
3309 if (s) {
3310 memcpy (s, n2, l2);
3311 s[l2] = '=';
3312 memcpy (s + l2 + 1, n1, l1 + 1);
3313 str_v = caml_copy_string (s);
3314 free (s);
3318 if (str_v == Val_unit) {
3319 str_v = caml_copy_string (n2);
3321 ret_v = caml_alloc_small (1, utext);
3322 Field (ret_v, 0) = str_v;
3323 goto unlock;
3330 unlock:
3331 unlock ("ml_whatsunder");
3333 done:
3334 CAMLreturn (ret_v);
3337 enum { mark_page, mark_block, mark_line, mark_word };
3339 static int uninteresting (int c)
3341 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3342 || ispunct (c);
3345 CAMLprim value ml_clearmark (value ptr_v)
3347 CAMLparam1 (ptr_v);
3348 char *s = String_val (ptr_v);
3349 struct page *page;
3351 if (trylock ("ml_clearmark")) {
3352 goto done;
3355 page = parse_pointer ("ml_clearmark", s);
3356 page->fmark.span = NULL;
3357 page->lmark.span = NULL;
3358 page->fmark.i = 0;
3359 page->lmark.i = 0;
3361 unlock ("ml_clearmark");
3362 done:
3363 CAMLreturn (Val_unit);
3366 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3368 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3369 CAMLlocal1 (ret_v);
3370 fz_rect *b;
3371 struct page *page;
3372 fz_text_line *line;
3373 fz_page_block *pageb;
3374 fz_text_block *block;
3375 struct pagedim *pdim;
3376 int mark = Int_val (mark_v);
3377 char *s = String_val (ptr_v);
3378 int x = Int_val (x_v), y = Int_val (y_v);
3380 ret_v = Val_bool (0);
3381 if (trylock ("ml_markunder")) {
3382 goto done;
3385 page = parse_pointer ("ml_markunder", s);
3386 pdim = &state.pagedims[page->pdimno];
3388 ensuretext (page);
3390 if (mark == mark_page) {
3391 int i;
3392 fz_page_block *pb1 = NULL, *pb2 = NULL;
3394 for (i = 0; i < page->text->len; ++i) {
3395 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3396 pb1 = &page->text->blocks[i];
3397 break;
3400 if (!pb1) goto unlock;
3402 for (i = page->text->len - 1; i >= 0; --i) {
3403 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3404 pb2 = &page->text->blocks[i];
3405 break;
3408 if (!pb2) goto unlock;
3410 block = pb1->u.text;
3412 page->fmark.i = 0;
3413 page->fmark.span = block->lines->first_span;
3415 block = pb2->u.text;
3416 line = &block->lines[block->len - 1];
3417 page->lmark.i = line->last_span->len - 1;
3418 page->lmark.span = line->last_span;
3419 ret_v = Val_bool (1);
3420 goto unlock;
3423 x += pdim->bounds.x0;
3424 y += pdim->bounds.y0;
3426 for (pageb = page->text->blocks;
3427 pageb < page->text->blocks + page->text->len;
3428 ++pageb) {
3429 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3430 block = pageb->u.text;
3432 b = &block->bbox;
3433 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3434 continue;
3436 if (mark == mark_block) {
3437 page->fmark.i = 0;
3438 page->fmark.span = block->lines->first_span;
3440 line = &block->lines[block->len - 1];
3441 page->lmark.i = line->last_span->len - 1;
3442 page->lmark.span = line->last_span;
3443 ret_v = Val_bool (1);
3444 goto unlock;
3447 for (line = block->lines;
3448 line < block->lines + block->len;
3449 ++line) {
3450 fz_text_span *span;
3452 b = &line->bbox;
3453 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3454 continue;
3456 if (mark == mark_line) {
3457 page->fmark.i = 0;
3458 page->fmark.span = line->first_span;
3460 page->lmark.i = line->last_span->len - 1;
3461 page->lmark.span = line->last_span;
3462 ret_v = Val_bool (1);
3463 goto unlock;
3466 for (span = line->first_span; span; span = span->next) {
3467 int charnum;
3469 b = &span->bbox;
3470 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3471 continue;
3473 for (charnum = 0; charnum < span->len; ++charnum) {
3474 fz_rect bbox;
3475 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3476 b = &bbox;
3478 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3479 /* unicode ftw */
3480 int charnum2, charnum3 = -1, charnum4 = -1;
3482 if (uninteresting (span->text[charnum].c)) goto unlock;
3484 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3485 if (uninteresting (span->text[charnum2].c)) {
3486 charnum3 = charnum2 + 1;
3487 break;
3490 if (charnum3 == -1) charnum3 = 0;
3492 for (charnum2 = charnum + 1;
3493 charnum2 < span->len;
3494 ++charnum2) {
3495 if (uninteresting (span->text[charnum2].c)) break;
3496 charnum4 = charnum2;
3498 if (charnum4 == -1) goto unlock;
3500 page->fmark.i = charnum3;
3501 page->fmark.span = span;
3503 page->lmark.i = charnum4;
3504 page->lmark.span = span;
3505 ret_v = Val_bool (1);
3506 goto unlock;
3512 unlock:
3513 if (!Bool_val (ret_v)) {
3514 page->fmark.span = NULL;
3515 page->lmark.span = NULL;
3516 page->fmark.i = 0;
3517 page->lmark.i = 0;
3519 unlock ("ml_markunder");
3521 done:
3522 CAMLreturn (ret_v);
3525 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3527 CAMLparam3 (ptr_v, x_v, y_v);
3528 CAMLlocal2 (ret_v, res_v);
3529 fz_rect *b = NULL;
3530 struct page *page;
3531 fz_page_block *pageb;
3532 struct pagedim *pdim;
3533 char *s = String_val (ptr_v);
3534 int x = Int_val (x_v), y = Int_val (y_v);
3536 ret_v = Val_int (0);
3537 if (trylock ("ml_rectofblock")) {
3538 goto done;
3541 page = parse_pointer ("ml_rectofblock", s);
3542 pdim = &state.pagedims[page->pdimno];
3543 x += pdim->bounds.x0;
3544 y += pdim->bounds.y0;
3546 ensuretext (page);
3548 for (pageb = page->text->blocks;
3549 pageb < page->text->blocks + page->text->len;
3550 ++pageb) {
3551 switch (pageb->type) {
3552 case FZ_PAGE_BLOCK_TEXT:
3553 b = &pageb->u.text->bbox;
3554 break;
3556 case FZ_PAGE_BLOCK_IMAGE:
3557 b = &pageb->u.image->bbox;
3558 break;
3560 default:
3561 continue;
3564 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3565 break;
3566 b = NULL;
3568 if (b) {
3569 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3570 ret_v = caml_alloc_small (1, 1);
3571 Store_double_field (res_v, 0, b->x0);
3572 Store_double_field (res_v, 1, b->x1);
3573 Store_double_field (res_v, 2, b->y0);
3574 Store_double_field (res_v, 3, b->y1);
3575 Field (ret_v, 0) = res_v;
3577 unlock ("ml_rectofblock");
3579 done:
3580 CAMLreturn (ret_v);
3583 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3585 CAMLparam2 (ptr_v, rect_v);
3586 fz_rect b;
3587 struct page *page;
3588 struct pagedim *pdim;
3589 char *s = String_val (ptr_v);
3590 int i, x0, x1, y0, y1, fi, li;
3591 fz_text_line *line;
3592 fz_page_block *pageb;
3593 fz_text_block *block;
3594 fz_text_span *span, *fspan, *lspan;
3596 if (trylock ("ml_seltext")) {
3597 goto done;
3600 page = parse_pointer ("ml_seltext", s);
3601 ensuretext (page);
3603 pdim = &state.pagedims[page->pdimno];
3604 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3605 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3606 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3607 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3609 if (y0 > y1) {
3610 int t = y0;
3611 y0 = y1;
3612 y1 = t;
3613 x0 = x1;
3614 x1 = t;
3617 if (0) {
3618 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3619 glColor3ub (128, 128, 128);
3620 recti (x0, y0, x1, y1);
3621 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3624 fi = page->fmark.i;
3625 fspan = page->fmark.span;
3627 li = page->lmark.i;
3628 lspan = page->lmark.span;
3630 for (pageb = page->text->blocks;
3631 pageb < page->text->blocks + page->text->len;
3632 ++pageb) {
3633 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3634 block = pageb->u.text;
3635 for (line = block->lines;
3636 line < block->lines + block->len;
3637 ++line) {
3639 for (span = line->first_span; span; span = span->next) {
3640 for (i = 0; i < span->len; ++i) {
3641 int selected = 0;
3643 fz_text_char_bbox (state.ctx, &b, span, i);
3645 if (x0 >= b.x0 && x0 <= b.x1
3646 && y0 >= b.y0 && y0 <= b.y1) {
3647 fspan = span;
3648 fi = i;
3649 selected = 1;
3651 if (x1 >= b.x0 && x1 <= b.x1
3652 && y1 >= b.y0 && y1 <= b.y1) {
3653 lspan = span;
3654 li = i;
3655 selected = 1;
3657 if (0 && selected) {
3658 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3659 glColor3ub (128, 128, 128);
3660 recti (b.x0, b.y0, b.x1, b.y1);
3661 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3667 if (x1 < x0 && fspan == lspan) {
3668 i = fi;
3669 span = fspan;
3671 fi = li;
3672 fspan = lspan;
3674 li = i;
3675 lspan = span;
3678 page->fmark.i = fi;
3679 page->fmark.span = fspan;
3681 page->lmark.i = li;
3682 page->lmark.span = lspan;
3684 unlock ("ml_seltext");
3686 done:
3687 CAMLreturn (Val_unit);
3690 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3692 char buf[4];
3693 int i, len, ret;
3695 for (i = a; i <= b; ++i) {
3696 len = fz_runetochar (buf, span->text[i].c);
3697 ret = fwrite (buf, len, 1, f);
3699 if (ret != 1) {
3700 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3701 len, ret, strerror (errno));
3702 return -1;
3705 return 0;
3708 #ifdef __CYGWIN__
3709 CAMLprim value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3711 caml_failwith ("ml_popen not implemented under Cygwin");
3713 #else
3714 CAMLprim value ml_popen (value command_v, value fds_v)
3716 CAMLparam2 (command_v, fds_v);
3717 CAMLlocal2 (l_v, tup_v);
3718 int ret;
3719 pid_t pid;
3720 char *msg = NULL;
3721 value earg_v = Nothing;
3722 posix_spawnattr_t attr;
3723 posix_spawn_file_actions_t fa;
3724 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3726 argv[2] = String_val (command_v);
3728 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3729 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3732 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3733 msg = "posix_spawnattr_init";
3734 goto fail1;
3737 #ifdef POSIX_SPAWN_USEVFORK
3738 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3739 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3740 goto fail;
3742 #endif
3744 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3745 int fd1, fd2;
3747 tup_v = Field (l_v, 0);
3748 fd1 = Int_val (Field (tup_v, 0));
3749 fd2 = Int_val (Field (tup_v, 1));
3750 if (fd2 < 0) {
3751 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3752 msg = "posix_spawn_file_actions_addclose";
3753 earg_v = tup_v;
3754 goto fail;
3757 else {
3758 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3759 msg = "posix_spawn_file_actions_adddup2";
3760 earg_v = tup_v;
3761 goto fail;
3766 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3767 msg = "posix_spawn";
3768 goto fail;
3771 fail:
3772 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3773 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3776 fail1:
3777 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3778 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3779 strerror (ret));
3782 if (msg)
3783 unix_error (ret, msg, earg_v);
3785 CAMLreturn (Val_int (pid));
3787 #endif
3789 CAMLprim value ml_hassel (value ptr_v)
3791 CAMLparam1 (ptr_v);
3792 CAMLlocal1 (ret_v);
3793 struct page *page;
3794 char *s = String_val (ptr_v);
3796 ret_v = Val_bool (0);
3797 if (trylock ("ml_hassel")) {
3798 goto done;
3801 page = parse_pointer ("ml_hassel", s);
3802 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3803 unlock ("ml_hassel");
3804 done:
3805 CAMLreturn (ret_v);
3808 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3810 CAMLparam2 (fd_v, ptr_v);
3811 FILE *f;
3812 int seen = 0;
3813 struct page *page;
3814 fz_text_line *line;
3815 fz_page_block *pageb;
3816 fz_text_block *block;
3817 int fd = Int_val (fd_v);
3818 char *s = String_val (ptr_v);
3820 if (trylock ("ml_copysel")) {
3821 goto done;
3824 page = parse_pointer ("ml_copysel", s);
3826 if (!page->fmark.span || !page->lmark.span) {
3827 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3828 goto unlock;
3831 f = fdopen (fd, "w");
3832 if (!f) {
3833 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3834 fd, strerror (errno));
3835 f = stdout;
3838 for (pageb = page->text->blocks;
3839 pageb < page->text->blocks + page->text->len;
3840 ++pageb) {
3841 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3842 block = pageb->u.text;
3843 for (line = block->lines;
3844 line < block->lines + block->len;
3845 ++line) {
3846 fz_text_span *span;
3848 for (span = line->first_span; span; span = span->next) {
3849 int a, b;
3851 seen |= span == page->fmark.span || span == page->lmark.span;
3852 a = span == page->fmark.span ? page->fmark.i : 0;
3853 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3855 if (seen) {
3856 if (pipespan (f, span, a, b)) {
3857 goto close;
3859 if (span == page->lmark.span) {
3860 goto close;
3862 if (span == line->last_span) {
3863 if (putc ('\n', f) == EOF) {
3864 fprintf (stderr,
3865 "failed break line on sel pipe: %s\n",
3866 strerror (errno));
3867 goto close;
3874 close:
3875 if (f != stdout) {
3876 int ret = fclose (f);
3877 fd = -1;
3878 if (ret == -1) {
3879 if (errno != ECHILD) {
3880 fprintf (stderr, "failed to close sel pipe: %s\n",
3881 strerror (errno));
3885 unlock:
3886 unlock ("ml_copysel");
3888 done:
3889 if (fd >= 0) {
3890 if (close (fd)) {
3891 fprintf (stderr, "failed to close sel pipe: %s\n",
3892 strerror (errno));
3895 CAMLreturn (Val_unit);
3898 CAMLprim value ml_getpdimrect (value pagedimno_v)
3900 CAMLparam1 (pagedimno_v);
3901 CAMLlocal1 (ret_v);
3902 int pagedimno = Int_val (pagedimno_v);
3903 fz_rect box;
3905 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3906 if (trylock ("ml_getpdimrect")) {
3907 box = fz_empty_rect;
3909 else {
3910 box = state.pagedims[pagedimno].mediabox;
3911 unlock ("ml_getpdimrect");
3914 Store_double_field (ret_v, 0, box.x0);
3915 Store_double_field (ret_v, 1, box.x1);
3916 Store_double_field (ret_v, 2, box.y0);
3917 Store_double_field (ret_v, 3, box.y1);
3919 CAMLreturn (ret_v);
3922 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3923 value dw_v, value cols_v)
3925 CAMLparam3 (winw_v, winh_v, dw_v);
3926 CAMLlocal1 (ret_v);
3927 int i;
3928 double zoom = -1.;
3929 double maxh = 0.0;
3930 struct pagedim *p;
3931 double winw = Int_val (winw_v);
3932 double winh = Int_val (winh_v);
3933 double dw = Int_val (dw_v);
3934 double cols = Int_val (cols_v);
3935 double pw = 1.0, ph = 1.0;
3937 if (trylock ("ml_zoom_for_height")) {
3938 goto done;
3941 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3942 double w = p->pagebox.x1 / cols;
3943 double h = p->pagebox.y1;
3944 if (h > maxh) {
3945 maxh = h;
3946 ph = h;
3947 if (state.fitmodel != FitProportional) pw = w;
3949 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3952 zoom = (((winh / ph) * pw) + dw) / winw;
3953 unlock ("ml_zoom_for_height");
3954 done:
3955 ret_v = caml_copy_double (zoom);
3956 CAMLreturn (ret_v);
3959 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3961 CAMLparam4 (pt_v, x_v, y_v, string_v);
3962 CAMLlocal1 (ret_v);
3963 int pt = Int_val(pt_v);
3964 int x = Int_val (x_v);
3965 int y = Int_val (y_v);
3966 double w;
3968 w = draw_string (state.face, pt, x, y, String_val (string_v));
3969 ret_v = caml_copy_double (w);
3970 CAMLreturn (ret_v);
3973 CAMLprim value ml_measure_string (value pt_v, value string_v)
3975 CAMLparam2 (pt_v, string_v);
3976 CAMLlocal1 (ret_v);
3977 int pt = Int_val (pt_v);
3978 double w;
3980 w = measure_string (state.face, pt, String_val (string_v));
3981 ret_v = caml_copy_double (w);
3982 CAMLreturn (ret_v);
3985 CAMLprim value ml_getpagebox (value opaque_v)
3987 CAMLparam1 (opaque_v);
3988 CAMLlocal1 (ret_v);
3989 fz_rect rect;
3990 fz_irect bbox;
3991 fz_matrix ctm;
3992 fz_device *dev;
3993 char *s = String_val (opaque_v);
3994 struct page *page = parse_pointer ("ml_getpagebox", s);
3996 ret_v = caml_alloc_tuple (4);
3997 dev = fz_new_bbox_device (state.ctx, &rect);
3998 dev->hints |= FZ_IGNORE_SHADE;
4000 switch (page->type) {
4001 case DPDF:
4002 ctm = pagectm (page);
4003 pdf_run_page (state.ctx, page->u.pdfpage, dev, &ctm, NULL);
4004 break;
4006 case DANY:
4007 ctm = pagectm (page);
4008 fz_run_page (state.ctx, page->u.anypage, dev, &ctm, NULL);
4009 break;
4011 default:
4012 rect = fz_infinite_rect;
4013 break;
4016 fz_drop_device (state.ctx, dev);
4017 fz_round_rect (&bbox, &rect);
4018 Field (ret_v, 0) = Val_int (bbox.x0);
4019 Field (ret_v, 1) = Val_int (bbox.y0);
4020 Field (ret_v, 2) = Val_int (bbox.x1);
4021 Field (ret_v, 3) = Val_int (bbox.y1);
4023 CAMLreturn (ret_v);
4026 CAMLprim value ml_setaalevel (value level_v)
4028 CAMLparam1 (level_v);
4030 state.aalevel = Int_val (level_v);
4031 CAMLreturn (Val_unit);
4034 #pragma GCC diagnostic push
4035 #pragma GCC diagnostic ignored "-Wvariadic-macros"
4036 #include <X11/Xlib.h>
4037 #pragma GCC diagnostic pop
4039 #include <GL/glx.h>
4041 static struct {
4042 Window wid;
4043 Display *dpy;
4044 GLXContext ctx;
4045 XVisualInfo *visual;
4046 } glx;
4048 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4050 CAMLparam3 (display_v, wid_v, screen_v);
4051 int attribs[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
4053 glx.dpy = XOpenDisplay (String_val (display_v));
4054 if (!glx.dpy) {
4055 caml_failwith ("XOpenDisplay");
4058 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4059 if (!glx.visual) {
4060 XCloseDisplay (glx.dpy);
4061 caml_failwith ("glXChooseVisual");
4064 glx.wid = Int_val (wid_v);
4065 CAMLreturn (Val_int (glx.visual->visualid));
4068 CAMLprim value ml_glxcompleteinit (value unit_v)
4070 CAMLparam1 (unit_v);
4072 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4073 if (!glx.ctx) {
4074 caml_failwith ("glXCreateContext");
4077 XFree (glx.visual);
4078 glx.visual = NULL;
4080 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4081 glXDestroyContext (glx.dpy, glx.ctx);
4082 glx.ctx = NULL;
4083 caml_failwith ("glXMakeCurrent");
4085 CAMLreturn (Val_unit);
4088 CAMLprim value ml_swapb (value unit_v)
4090 CAMLparam1 (unit_v);
4091 glXSwapBuffers (glx.dpy, glx.wid);
4092 CAMLreturn (Val_unit);
4095 #include "keysym2ucs.c"
4097 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4099 CAMLparam1 (keysym_v);
4100 CAMLlocal1 (str_v);
4101 KeySym keysym = Int_val (keysym_v);
4102 Rune rune;
4103 int len;
4104 char buf[5];
4106 rune = keysym2ucs (keysym);
4107 len = fz_runetochar (buf, rune);
4108 buf[len] = 0;
4109 str_v = caml_copy_string (buf);
4110 CAMLreturn (str_v);
4113 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4115 CAMLprim value ml_platform (value unit_v)
4117 CAMLparam1 (unit_v);
4118 CAMLlocal2 (tup_v, arr_v);
4119 int platid = piunknown;
4120 struct utsname buf;
4122 #if defined __linux__
4123 platid = pilinux;
4124 #elif defined __CYGWIN__
4125 platid = picygwin;
4126 #elif defined __DragonFly__ || defined __FreeBSD__
4127 || defined __OpenBSD__ || defined __NetBSD__
4128 platid = pibsd;
4129 #elif defined __sun__
4130 platid = pisun;
4131 #elif defined __APPLE__
4132 platid = piosx;
4133 #endif
4134 if (uname (&buf)) err (1, "uname");
4136 tup_v = caml_alloc_tuple (2);
4138 char const *sar[] = {
4139 buf.sysname,
4140 buf.release,
4141 buf.version,
4142 buf.machine,
4143 NULL
4145 arr_v = caml_copy_string_array (sar);
4147 Field (tup_v, 0) = Val_int (platid);
4148 Field (tup_v, 1) = arr_v;
4149 CAMLreturn (tup_v);
4152 CAMLprim value ml_cloexec (value fd_v)
4154 CAMLparam1 (fd_v);
4155 int fd = Int_val (fd_v);
4157 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4158 uerror ("fcntl", Nothing);
4160 CAMLreturn (Val_unit);
4163 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4165 CAMLparam2 (w_v, h_v);
4166 CAMLlocal1 (ret_v);
4167 struct pbo *pbo;
4168 int w = Int_val (w_v);
4169 int h = Int_val (h_v);
4170 int cs = Int_val (cs_v);
4172 if (state.pbo_usable) {
4173 pbo = calloc (sizeof (*pbo), 1);
4174 if (!pbo) {
4175 err (1, "calloc pbo");
4178 switch (cs) {
4179 case 0:
4180 case 1:
4181 pbo->size = w*h*4;
4182 break;
4183 case 2:
4184 pbo->size = w*h*2;
4185 break;
4186 default:
4187 errx (1, "ml_getpbo: invalid colorspace %d", cs);
4190 state.glGenBuffersARB (1, &pbo->id);
4191 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4192 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4193 NULL, GL_STREAM_DRAW);
4194 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4195 GL_READ_WRITE);
4196 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4197 if (!pbo->ptr) {
4198 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4199 state.glDeleteBuffersARB (1, &pbo->id);
4200 free (pbo);
4201 ret_v = caml_copy_string ("0");
4203 else {
4204 int res;
4205 char *s;
4207 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4208 if (res < 0) {
4209 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4211 s = malloc (res+1);
4212 if (!s) {
4213 err (1, "malloc %d bytes failed", res+1);
4215 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4216 if (res < 0) {
4217 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4219 ret_v = caml_copy_string (s);
4220 free (s);
4223 else {
4224 ret_v = caml_copy_string ("0");
4226 CAMLreturn (ret_v);
4229 CAMLprim value ml_freepbo (value s_v)
4231 CAMLparam1 (s_v);
4232 char *s = String_val (s_v);
4233 struct tile *tile = parse_pointer ("ml_freepbo", s);
4235 if (tile->pbo) {
4236 state.glDeleteBuffersARB (1, &tile->pbo->id);
4237 tile->pbo->id = -1;
4238 tile->pbo->ptr = NULL;
4239 tile->pbo->size = -1;
4241 CAMLreturn (Val_unit);
4244 CAMLprim value ml_unmappbo (value s_v)
4246 CAMLparam1 (s_v);
4247 char *s = String_val (s_v);
4248 struct tile *tile = parse_pointer ("ml_unmappbo", s);
4250 if (tile->pbo) {
4251 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4252 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4253 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4255 tile->pbo->ptr = NULL;
4256 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4258 CAMLreturn (Val_unit);
4261 static void setuppbo (void)
4263 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4264 state.pbo_usable = GGPA (glBindBufferARB)
4265 && GGPA (glUnmapBufferARB)
4266 && GGPA (glMapBufferARB)
4267 && GGPA (glBufferDataARB)
4268 && GGPA (glGenBuffersARB)
4269 && GGPA (glDeleteBuffersARB);
4270 #undef GGPA
4273 CAMLprim value ml_pbo_usable (value unit_v)
4275 CAMLparam1 (unit_v);
4276 CAMLreturn (Val_bool (state.pbo_usable));
4279 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4281 CAMLparam3 (ptr_v, x_v, y_v);
4282 CAMLlocal2 (ret_v, tup_v);
4283 struct page *page;
4284 char *s = String_val (ptr_v);
4285 int x = Int_val (x_v), y = Int_val (y_v);
4286 struct pagedim *pdim;
4287 fz_point p;
4288 fz_matrix ctm;
4290 page = parse_pointer ("ml_unproject", s);
4291 pdim = &state.pagedims[page->pdimno];
4293 ret_v = Val_int (0);
4294 if (trylock ("ml_unproject")) {
4295 goto done;
4298 switch (page->type) {
4299 case DPDF:
4300 trimctm (page->u.pdfpage, page->pdimno);
4301 break;
4303 default:
4304 break;
4306 p.x = x + pdim->bounds.x0;
4307 p.y = y + pdim->bounds.y0;
4309 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4310 fz_invert_matrix (&ctm, &ctm);
4311 fz_transform_point (&p, &ctm);
4313 tup_v = caml_alloc_tuple (2);
4314 ret_v = caml_alloc_small (1, 1);
4315 Field (tup_v, 0) = Val_int (p.x);
4316 Field (tup_v, 1) = Val_int (p.y);
4317 Field (ret_v, 0) = tup_v;
4319 unlock ("ml_unproject");
4320 done:
4321 CAMLreturn (ret_v);
4324 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4325 value contents_v)
4327 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4329 if (state.type == DPDF) {
4330 pdf_document *pdf;
4331 pdf_annot *annot;
4332 struct page *page;
4333 fz_point p;
4334 char *s = String_val (ptr_v);
4336 pdf = state.u.pdf;
4337 page = parse_pointer ("ml_addannot", s);
4338 annot = pdf_create_annot (state.ctx, pdf,
4339 page->u.pdfpage, FZ_ANNOT_TEXT);
4340 p.x = Int_val (x_v);
4341 p.y = Int_val (y_v);
4342 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4343 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4344 state.dirty = 1;
4346 CAMLreturn (Val_unit);
4349 CAMLprim value ml_delannot (value ptr_v, value n_v)
4351 CAMLparam2 (ptr_v, n_v);
4353 if (state.type == DPDF) {
4354 struct page *page;
4355 char *s = String_val (ptr_v);
4356 struct slink *slink;
4358 page = parse_pointer ("ml_delannot", s);
4359 slink = &page->slinks[Int_val (n_v)];
4360 pdf_delete_annot (state.ctx, state.u.pdf,
4361 page->u.pdfpage, slink->u.annot);
4362 state.dirty = 1;
4364 CAMLreturn (Val_unit);
4367 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4369 CAMLparam3 (ptr_v, n_v, str_v);
4371 if (state.type == DPDF) {
4372 struct page *page;
4373 char *s = String_val (ptr_v);
4374 struct slink *slink;
4376 page = parse_pointer ("ml_modannot", s);
4377 slink = &page->slinks[Int_val (n_v)];
4378 pdf_set_annot_contents (state.ctx, state.u.pdf, slink->u.annot,
4379 String_val (str_v));
4380 state.dirty = 1;
4382 CAMLreturn (Val_unit);
4385 CAMLprim value ml_hasunsavedchanges (value unit_v)
4387 CAMLparam1 (unit_v);
4388 CAMLreturn (Val_bool (state.dirty));
4391 CAMLprim value ml_savedoc (value path_v)
4393 CAMLparam1 (path_v);
4395 if (state.type == DPDF) {
4396 pdf_write_document (state.ctx, state.u.pdf, String_val (path_v), NULL);
4398 CAMLreturn (Val_unit);
4401 static void makestippletex (void)
4403 const char pixels[] = "\xff\xff\0\0";
4404 glGenTextures (1, &state.stid);
4405 glBindTexture (GL_TEXTURE_1D, state.stid);
4406 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4407 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4408 glTexImage1D (
4409 GL_TEXTURE_1D,
4411 GL_ALPHA,
4414 GL_ALPHA,
4415 GL_UNSIGNED_BYTE,
4416 pixels
4420 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4422 return caml_copy_string (FZ_VERSION);
4425 #ifdef USE_FONTCONFIG
4426 static struct {
4427 int inited;
4428 FcConfig *config;
4429 } fc;
4431 static fz_font *fc_load_system_font_func (fz_context *ctx,
4432 const char *name,
4433 int bold,
4434 int italic,
4435 int UNUSED_ATTR needs_exact_metrics)
4437 char *buf;
4438 size_t i, size;
4439 fz_font *font;
4440 FcChar8 *path;
4441 FcResult result;
4442 FcPattern *pat, *pat1;
4444 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4445 name, bold, italic, needs_exact_metrics);
4446 if (!fc.inited) {
4447 fc.inited = 1;
4448 fc.config = FcInitLoadConfigAndFonts ();
4449 if (!fc.config) {
4450 lprintf ("FcInitLoadConfigAndFonts failed\n");
4451 return NULL;
4454 if (!fc.config) return NULL;
4456 size = strlen (name);
4457 if (bold) size += sizeof (":bold") - 1;
4458 if (italic) size += sizeof (":italic") - 1;
4459 size += 1;
4461 buf = malloc (size);
4462 if (!buf) {
4463 err (1, "malloc %zu failed", size);
4466 strcpy (buf, name);
4467 if (bold && italic) {
4468 strcat (buf, ":bold:italic");
4470 else {
4471 if (bold) strcat (buf, ":bold");
4472 if (italic) strcat (buf, ":italic");
4474 for (i = 0; i < size; ++i) {
4475 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4478 lprintf ("fcbuf=%s\n", buf);
4479 pat = FcNameParse ((FcChar8 *) buf);
4480 if (!pat) {
4481 printd ("emsg FcNameParse failed\n");
4482 free (buf);
4483 return NULL;
4486 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4487 printd ("emsg FcConfigSubstitute failed\n");
4488 free (buf);
4489 return NULL;
4491 FcDefaultSubstitute (pat);
4493 pat1 = FcFontMatch (fc.config, pat, &result);
4494 if (!pat1) {
4495 printd ("emsg FcFontMatch failed\n");
4496 FcPatternDestroy (pat);
4497 free (buf);
4498 return NULL;
4501 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4502 printd ("emsg FcPatternGetString failed\n");
4503 FcPatternDestroy (pat);
4504 FcPatternDestroy (pat1);
4505 free (buf);
4506 return NULL;
4509 #if 0
4510 printd ("emsg name=%s path=%s\n", name, path);
4511 #endif
4512 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4513 FcPatternDestroy (pat);
4514 FcPatternDestroy (pat1);
4515 free (buf);
4516 return font;
4518 #endif
4520 CAMLprim value ml_init (value csock_v, value params_v)
4522 CAMLparam2 (csock_v, params_v);
4523 CAMLlocal2 (trim_v, fuzz_v);
4524 int ret;
4525 int texcount;
4526 char *fontpath;
4527 int colorspace;
4528 int mustoresize;
4529 int haspboext;
4531 state.csock = Int_val (csock_v);
4532 state.rotate = Int_val (Field (params_v, 0));
4533 state.fitmodel = Int_val (Field (params_v, 1));
4534 trim_v = Field (params_v, 2);
4535 texcount = Int_val (Field (params_v, 3));
4536 state.sliceheight = Int_val (Field (params_v, 4));
4537 mustoresize = Int_val (Field (params_v, 5));
4538 colorspace = Int_val (Field (params_v, 6));
4539 fontpath = String_val (Field (params_v, 7));
4541 if (caml_string_length (Field (params_v, 8)) > 0) {
4542 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4544 if (!state.trimcachepath) {
4545 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4546 strerror (errno));
4549 haspboext = Bool_val (Field (params_v, 9));
4551 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4552 fz_register_document_handlers (state.ctx);
4554 #ifdef USE_FONTCONFIG
4555 if (Bool_val (Field (params_v, 10))) {
4556 fz_install_load_system_font_funcs (
4557 state.ctx, fc_load_system_font_func, NULL
4560 #endif
4562 state.trimmargins = Bool_val (Field (trim_v, 0));
4563 fuzz_v = Field (trim_v, 1);
4564 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4565 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4566 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4567 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4569 set_tex_params (colorspace);
4571 if (*fontpath) {
4572 #ifndef USE_FONTCONFIG
4573 state.face = load_font (fontpath);
4574 #else
4575 FcChar8 *path;
4576 FcResult result;
4577 char *buf = fontpath;
4578 FcPattern *pat, *pat1;
4580 fc.inited = 1;
4581 fc.config = FcInitLoadConfigAndFonts ();
4582 if (!fc.config) {
4583 errx (1, "FcInitLoadConfigAndFonts failed");
4586 pat = FcNameParse ((FcChar8 *) buf);
4587 if (!pat) {
4588 errx (1, "FcNameParse failed");
4591 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4592 errx (1, "FcConfigSubstitute failed");
4594 FcDefaultSubstitute (pat);
4596 pat1 = FcFontMatch (fc.config, pat, &result);
4597 if (!pat1) {
4598 errx (1, "FcFontMatch failed");
4601 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4602 errx (1, "FcPatternGetString failed");
4605 state.face = load_font ((char *) path);
4606 FcPatternDestroy (pat);
4607 FcPatternDestroy (pat1);
4608 #endif
4610 else {
4611 unsigned int len;
4612 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4614 state.face = load_builtin_font (base, len);
4616 if (!state.face) _exit (1);
4618 realloctexts (texcount);
4620 if (haspboext) {
4621 setuppbo ();
4624 makestippletex ();
4626 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4627 if (ret) {
4628 errx (1, "pthread_create: %s", strerror (ret));
4631 CAMLreturn (Val_unit);