Cosmetics
[llpp.git] / link.c
blob439e9e7308af8a73285ee41bdf73e5910752ce7b
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 (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 if (state.type == DPDF)
1242 printd ("progress 1 Processed %d pages in %f seconds",
1243 state.pagecount, end - start);
1244 else
1245 printd ("vmsg Processed %d pages in %f seconds",
1246 state.pagecount, end - start);
1248 state.trimanew = 0;
1249 if (trimf) {
1250 if (fclose (trimf)) {
1251 err (1, "fclose");
1256 static void layout (void)
1258 int pindex;
1259 fz_rect box;
1260 fz_matrix ctm, rm;
1261 struct pagedim *p = p;
1262 double zw, w, maxw = 0.0, zoom = zoom;
1264 if (state.pagedimcount == 0) return;
1266 switch (state.fitmodel) {
1267 case FitProportional:
1268 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1269 double x0, x1;
1271 p = &state.pagedims[pindex];
1272 fz_rotate (&rm, p->rotate + state.rotate);
1273 box = p->mediabox;
1274 fz_transform_rect (&box, &rm);
1276 x0 = MIN (box.x0, box.x1);
1277 x1 = MAX (box.x0, box.x1);
1279 w = x1 - x0;
1280 maxw = MAX (w, maxw);
1281 zoom = state.w / maxw;
1283 break;
1285 case FitPage:
1286 maxw = state.w;
1287 break;
1289 case FitWidth:
1290 break;
1292 default:
1293 ARSERT (0 && state.fitmodel);
1296 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1297 fz_rect rect;
1298 fz_matrix tm, sm;
1300 p = &state.pagedims[pindex];
1301 fz_rotate (&ctm, state.rotate);
1302 fz_rotate (&rm, p->rotate + state.rotate);
1303 box = p->mediabox;
1304 fz_transform_rect (&box, &rm);
1305 w = box.x1 - box.x0;
1306 switch (state.fitmodel) {
1307 case FitProportional:
1308 p->left = ((maxw - w) * zoom) / 2.0;
1309 break;
1310 case FitPage:
1312 double zh, h;
1313 zw = maxw / w;
1314 h = box.y1 - box.y0;
1315 zh = state.h / h;
1316 zoom = MIN (zw, zh);
1317 p->left = (maxw - (w * zoom)) / 2.0;
1319 break;
1320 case FitWidth:
1321 p->left = 0;
1322 zoom = state.w / w;
1323 break;
1326 fz_scale (&p->zoomctm, zoom, zoom);
1327 fz_concat (&ctm, &p->zoomctm, &ctm);
1329 fz_rotate (&rm, p->rotate);
1330 p->pagebox = p->mediabox;
1331 fz_transform_rect (&p->pagebox, &rm);
1332 p->pagebox.x1 -= p->pagebox.x0;
1333 p->pagebox.y1 -= p->pagebox.y0;
1334 p->pagebox.x0 = 0;
1335 p->pagebox.y0 = 0;
1336 rect = p->pagebox;
1337 fz_transform_rect (&rect, &ctm);
1338 fz_round_rect (&p->bounds, &rect);
1339 p->ctm = ctm;
1341 fz_translate (&tm, 0, -p->mediabox.y1);
1342 fz_scale (&sm, zoom, -zoom);
1343 fz_concat (&ctm, &tm, &sm);
1344 fz_concat (&p->lctm, &ctm, &rm);
1346 p->tctmready = 0;
1349 do {
1350 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1351 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1352 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1353 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1354 int boundw = x1 - x0;
1355 int boundh = y1 - y0;
1357 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1358 } while (p-- != state.pagedims);
1361 static
1362 struct anchor { int n; int x; int y; int w; int h; }
1363 desttoanchor (fz_link_dest *dest)
1365 int i;
1366 struct anchor a;
1367 struct pagedim *pdim = state.pagedims;
1369 a.n = -1;
1370 a.x = 0;
1371 a.y = 0;
1372 for (i = 0; i < state.pagedimcount; ++i) {
1373 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1374 break;
1375 pdim = &state.pagedims[i];
1377 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1378 fz_point p;
1379 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1380 p.x = dest->ld.gotor.lt.x;
1381 else
1382 p.x = 0.0;
1383 p.y = dest->ld.gotor.lt.y;
1384 fz_transform_point (&p, &pdim->lctm);
1385 a.x = p.x;
1386 a.y = p.y;
1388 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1389 double x0, x1, y0, y1;
1391 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1392 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1393 a.w = x1 - x0;
1394 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1395 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1396 a.h = y1 - y0;
1397 a.n = dest->ld.gotor.page;
1399 return a;
1402 static void recurse_outline (fz_outline *outline, int level)
1404 while (outline) {
1405 switch (outline->dest.kind) {
1406 case FZ_LINK_GOTO:
1408 struct anchor a = desttoanchor (&outline->dest);
1410 if (a.n >= 0) {
1411 printd ("o %d %d %d %d %s",
1412 level, a.n, a.y, a.h, outline->title);
1415 break;
1417 case FZ_LINK_URI:
1418 printd ("ou %d %" FMT_s " %s %s", level,
1419 strlen (outline->title), outline->title,
1420 outline->dest.ld.uri.uri);
1421 break;
1423 case FZ_LINK_NONE:
1424 printd ("on %d %s", level, outline->title);
1425 break;
1427 default:
1428 printd ("emsg Unhandled outline kind %d for %s\n",
1429 outline->dest.kind, outline->title);
1430 break;
1432 if (outline->down) {
1433 recurse_outline (outline->down, level + 1);
1435 outline = outline->next;
1439 static void process_outline (void)
1441 fz_outline *outline;
1443 if (!state.needoutline || !state.pagedimcount) return;
1445 state.needoutline = 0;
1446 outline = fz_load_outline (state.ctx, state.u.doc);
1447 if (outline) {
1448 recurse_outline (outline, 0);
1449 fz_drop_outline (state.ctx, outline);
1453 static char *strofspan (fz_text_span *span)
1455 char *p;
1456 char utf8[10];
1457 fz_text_char *ch;
1458 size_t size = 0, cap = 80;
1460 p = malloc (cap + 1);
1461 if (!p) return NULL;
1463 for (ch = span->text; ch < span->text + span->len; ++ch) {
1464 int n = fz_runetochar (utf8, ch->c);
1465 if (size + n > cap) {
1466 cap *= 2;
1467 p = realloc (p, cap + 1);
1468 if (!p) return NULL;
1471 memcpy (p + size, utf8, n);
1472 size += n;
1474 p[size] = 0;
1475 return p;
1478 static int matchspan (regex_t *re, fz_text_span *span,
1479 int stop, int pageno, double start)
1481 int ret;
1482 char *p;
1483 regmatch_t rm;
1484 int a, b, c;
1485 fz_rect sb, eb;
1486 fz_point p1, p2, p3, p4;
1488 p = strofspan (span);
1489 if (!p) return -1;
1491 ret = regexec (re, p, 1, &rm, 0);
1492 if (ret) {
1493 free (p);
1494 if (ret != REG_NOMATCH) {
1495 size_t size;
1496 char errbuf[80];
1497 size = regerror (ret, re, errbuf, sizeof (errbuf));
1498 printd ("msg regexec error `%.*s'",
1499 (int) size, errbuf);
1500 return -1;
1502 return 0;
1504 else {
1505 int l = span->len;
1507 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1508 c += fz_runelen (span->text[a].c);
1510 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1511 c += fz_runelen (span->text[b].c);
1514 if (fz_runelen (span->text[b].c) > 1) {
1515 b = MAX (0, b-1);
1518 fz_text_char_bbox (state.ctx, &sb, span, a);
1519 fz_text_char_bbox (state.ctx, &eb, span, b);
1521 p1.x = sb.x0;
1522 p1.y = sb.y0;
1523 p2.x = eb.x1;
1524 p2.y = sb.y0;
1525 p3.x = eb.x1;
1526 p3.y = eb.y1;
1527 p4.x = sb.x0;
1528 p4.y = eb.y1;
1530 if (!stop) {
1531 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1532 pageno, 1,
1533 p1.x, p1.y,
1534 p2.x, p2.y,
1535 p3.x, p3.y,
1536 p4.x, p4.y);
1538 printd ("progress 1 found at %d `%.*s' in %f sec",
1539 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1540 now () - start);
1542 else {
1543 printd ("match %d %d %f %f %f %f %f %f %f %f",
1544 pageno, 2,
1545 p1.x, p1.y,
1546 p2.x, p2.y,
1547 p3.x, p3.y,
1548 p4.x, p4.y);
1550 free (p);
1551 return 1;
1555 static int compareblocks (const void *l, const void *r)
1557 fz_text_block const *ls = l;
1558 fz_text_block const* rs = r;
1559 return ls->bbox.y0 - rs->bbox.y0;
1562 /* wishful thinking function */
1563 static void search (regex_t *re, int pageno, int y, int forward)
1565 int i, j;
1566 fz_matrix ctm;
1567 fz_device *tdev;
1568 union {
1569 void *ptr;
1570 pdf_page *pdfpage;
1571 fz_page *anypage;
1572 } u;
1573 fz_text_page *text;
1574 fz_text_sheet *sheet;
1575 struct pagedim *pdim, *pdimprev;
1576 int stop = 0, niters = 0;
1577 double start, end;
1579 start = now ();
1580 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1581 if (niters++ == 5) {
1582 niters = 0;
1583 if (hasdata ()) {
1584 printd ("progress 1 attention requested aborting search at %d",
1585 pageno);
1586 stop = 1;
1588 else {
1589 printd ("progress %f searching in page %d",
1590 (double) (pageno + 1) / state.pagecount,
1591 pageno);
1594 pdimprev = NULL;
1595 for (i = 0; i < state.pagedimcount; ++i) {
1596 pdim = &state.pagedims[i];
1597 if (pdim->pageno == pageno) {
1598 goto found;
1600 if (pdim->pageno > pageno) {
1601 pdim = pdimprev;
1602 goto found;
1604 pdimprev = pdim;
1606 pdim = pdimprev;
1607 found:
1609 sheet = fz_new_text_sheet (state.ctx);
1610 text = fz_new_text_page (state.ctx);
1611 tdev = fz_new_text_device (state.ctx, sheet, text);
1613 switch (state.type) {
1614 case DPDF:
1615 u.ptr = NULL;
1616 fz_try (state.ctx) {
1617 u.pdfpage = pdf_load_page (state.ctx, state.u.pdf, pageno);
1618 trimctm (u.pdfpage, pdim - state.pagedims);
1619 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1620 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
1621 pdf_run_page (state.ctx, u.pdfpage, tdev, &ctm, NULL);
1622 fz_end_page (state.ctx, tdev);
1624 fz_catch (state.ctx) {
1625 fz_drop_device (state.ctx, tdev);
1626 u.ptr = NULL;
1627 goto nextiter;
1629 break;
1631 case DANY:
1632 u.anypage = fz_load_page (state.ctx, state.u.doc, pageno);
1633 fz_run_page (state.ctx, u.anypage, tdev, &pdim->ctm, NULL);
1634 break;
1636 default:
1637 ARSERT (0 && state.type);
1640 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1641 fz_drop_device (state.ctx, tdev);
1643 for (j = 0; j < text->len; ++j) {
1644 int k;
1645 fz_page_block *pb;
1646 fz_text_block *block;
1648 pb = &text->blocks[forward ? j : text->len - 1 - j];
1649 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1650 block = pb->u.text;
1652 for (k = 0; k < block->len; ++k) {
1653 fz_text_line *line;
1654 fz_text_span *span;
1656 if (forward) {
1657 line = &block->lines[k];
1658 if (line->bbox.y0 < y + 1) continue;
1660 else {
1661 line = &block->lines[block->len - 1 - k];
1662 if (line->bbox.y0 > y - 1) continue;
1665 for (span = line->first_span; span; span = span->next) {
1666 switch (matchspan (re, span, stop, pageno, start)) {
1667 case 0: break;
1668 case 1: stop = 1; break;
1669 case -1: stop = 1; goto endloop;
1674 nextiter:
1675 if (forward) {
1676 pageno += 1;
1677 y = 0;
1679 else {
1680 pageno -= 1;
1681 y = INT_MAX;
1683 endloop:
1684 fz_drop_text_page (state.ctx, text);
1685 fz_drop_text_sheet (state.ctx, sheet);
1686 if (u.ptr) {
1687 state.freepage (u.ptr);
1690 end = now ();
1691 if (!stop) {
1692 printd ("progress 1 no matches %f sec", end - start);
1694 printd ("clearrects");
1697 static void set_tex_params (int colorspace)
1699 union {
1700 unsigned char b;
1701 unsigned int s;
1702 } endianness = {1};
1704 switch (colorspace) {
1705 case 0:
1706 state.texiform = GL_RGBA8;
1707 state.texform = GL_RGBA;
1708 state.texty = GL_UNSIGNED_BYTE;
1709 state.colorspace = fz_device_rgb (state.ctx);
1710 break;
1711 case 1:
1712 state.texiform = GL_RGBA8;
1713 state.texform = GL_BGRA;
1714 state.texty = endianness.s > 1
1715 ? GL_UNSIGNED_INT_8_8_8_8
1716 : GL_UNSIGNED_INT_8_8_8_8_REV;
1717 state.colorspace = fz_device_bgr (state.ctx);
1718 break;
1719 case 2:
1720 state.texiform = GL_LUMINANCE_ALPHA;
1721 state.texform = GL_LUMINANCE_ALPHA;
1722 state.texty = GL_UNSIGNED_BYTE;
1723 state.colorspace = fz_device_gray (state.ctx);
1724 break;
1725 default:
1726 errx (1, "invalid colorspce %d", colorspace);
1730 static void realloctexts (int texcount)
1732 size_t size;
1734 if (texcount == state.texcount) return;
1736 if (texcount < state.texcount) {
1737 glDeleteTextures (state.texcount - texcount,
1738 state.texids + texcount);
1741 size = texcount * sizeof (*state.texids);
1742 state.texids = realloc (state.texids, size);
1743 if (!state.texids) {
1744 err (1, "realloc texids %" FMT_s, size);
1747 size = texcount * sizeof (*state.texowners);
1748 state.texowners = realloc (state.texowners, size);
1749 if (!state.texowners) {
1750 err (1, "realloc texowners %" FMT_s, size);
1752 if (texcount > state.texcount) {
1753 int i;
1755 glGenTextures (texcount - state.texcount,
1756 state.texids + state.texcount);
1757 for (i = state.texcount; i < texcount; ++i) {
1758 state.texowners[i].w = -1;
1759 state.texowners[i].slice = NULL;
1762 state.texcount = texcount;
1763 state.texindex = 0;
1766 static char *mbtoutf8 (char *s)
1768 char *p, *r;
1769 wchar_t *tmp;
1770 size_t i, ret, len;
1772 len = mbstowcs (NULL, s, strlen (s));
1773 if (len == 0) {
1774 return s;
1776 else {
1777 if (len == (size_t) -1) {
1778 return s;
1782 tmp = malloc (len * sizeof (wchar_t));
1783 if (!tmp) {
1784 return s;
1787 ret = mbstowcs (tmp, s, len);
1788 if (ret == (size_t) -1) {
1789 free (tmp);
1790 return s;
1793 len = 0;
1794 for (i = 0; i < ret; ++i) {
1795 len += fz_runelen (tmp[i]);
1798 p = r = malloc (len + 1);
1799 if (!r) {
1800 free (tmp);
1801 return s;
1804 for (i = 0; i < ret; ++i) {
1805 p += fz_runetochar (p, tmp[i]);
1807 *p = 0;
1808 free (tmp);
1809 return r;
1812 CAMLprim value ml_mbtoutf8 (value s_v)
1814 CAMLparam1 (s_v);
1815 CAMLlocal1 (ret_v);
1816 char *s, *r;
1818 s = String_val (s_v);
1819 r = mbtoutf8 (s);
1820 if (r == s) {
1821 ret_v = s_v;
1823 else {
1824 ret_v = caml_copy_string (r);
1825 free (r);
1827 CAMLreturn (ret_v);
1830 static void * mainloop (void UNUSED_ATTR *unused)
1832 char *p = NULL;
1833 int len, ret, oldlen = 0;
1835 for (;;) {
1836 len = readlen ();
1837 if (len == 0) {
1838 errx (1, "readlen returned 0");
1841 if (oldlen < len + 1) {
1842 p = realloc (p, len + 1);
1843 if (!p) {
1844 err (1, "realloc %d failed", len + 1);
1846 oldlen = len + 1;
1848 readdata (p, len);
1849 p[len] = 0;
1851 if (!strncmp ("open", p, 4)) {
1852 int wthack, off, ok = 0;
1853 char *password;
1854 char *filename;
1855 char *utf8filename;
1856 size_t filenamelen;
1858 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1859 if (ret != 2) {
1860 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1863 filename = p + 5 + off;
1864 filenamelen = strlen (filename);
1865 password = filename + filenamelen + 1;
1867 lock ("open");
1868 fz_try (state.ctx) {
1869 ok = openxref (filename, password);
1871 fz_catch (state.ctx) {
1872 utf8filename = mbtoutf8 (filename);
1873 printd ("msg Could not open %s", utf8filename);
1875 if (ok) {
1876 pdfinfo ();
1877 initpdims ();
1879 unlock ("open");
1881 if (ok) {
1882 if (!wthack) {
1883 utf8filename = mbtoutf8 (filename);
1884 printd ("msg Opened %s (press h/F1 to get help)",
1885 utf8filename);
1886 if (utf8filename != filename) {
1887 free (utf8filename);
1890 state.needoutline = 1;
1893 else if (!strncmp ("cs", p, 2)) {
1894 int i, colorspace;
1896 ret = sscanf (p + 2, " %d", &colorspace);
1897 if (ret != 1) {
1898 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1900 lock ("cs");
1901 set_tex_params (colorspace);
1902 for (i = 0; i < state.texcount; ++i) {
1903 state.texowners[i].w = -1;
1904 state.texowners[i].slice = NULL;
1906 unlock ("cs");
1908 else if (!strncmp ("freepage", p, 8)) {
1909 void *ptr;
1911 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1912 if (ret != 1) {
1913 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1915 freepage (ptr);
1917 else if (!strncmp ("freetile", p, 8)) {
1918 void *ptr;
1920 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1921 if (ret != 1) {
1922 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1924 freetile (ptr);
1926 else if (!strncmp ("search", p, 6)) {
1927 int icase, pageno, y, len2, forward;
1928 char *pattern;
1929 regex_t re;
1931 ret = sscanf (p + 6, " %d %d %d %d,%n",
1932 &icase, &pageno, &y, &forward, &len2);
1933 if (ret != 4) {
1934 errx (1, "malformed search `%s' ret=%d", p, ret);
1937 pattern = p + 6 + len2;
1938 ret = regcomp (&re, pattern,
1939 REG_EXTENDED | (icase ? REG_ICASE : 0));
1940 if (ret) {
1941 char errbuf[80];
1942 size_t size;
1944 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1945 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1947 else {
1948 search (&re, pageno, y, forward);
1949 regfree (&re);
1952 else if (!strncmp ("geometry", p, 8)) {
1953 int w, h, fitmodel;
1955 printd ("clear");
1956 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1957 if (ret != 3) {
1958 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1961 lock ("geometry");
1962 state.h = h;
1963 if (w != state.w) {
1964 int i;
1965 state.w = w;
1966 for (i = 0; i < state.texcount; ++i) {
1967 state.texowners[i].slice = NULL;
1970 state.fitmodel = fitmodel;
1971 layout ();
1972 process_outline ();
1974 state.gen++;
1975 unlock ("geometry");
1976 printd ("continue %d", state.pagecount);
1978 else if (!strncmp ("reqlayout", p, 9)) {
1979 char *nameddest;
1980 int rotate, off, h;
1981 unsigned int fitmodel;
1983 printd ("clear");
1984 ret = sscanf (p + 9, " %d %u %d %n",
1985 &rotate, &fitmodel, &h, &off);
1986 if (ret != 3) {
1987 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1989 lock ("reqlayout");
1990 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1991 state.gen += 1;
1993 state.rotate = rotate;
1994 state.fitmodel = fitmodel;
1995 state.h = h;
1996 layout ();
1997 process_outline ();
1999 nameddest = p + 9 + off;
2000 if (state.type == DPDF && nameddest && *nameddest) {
2001 struct anchor a;
2002 fz_link_dest dest;
2003 pdf_obj *needle, *obj;
2005 needle = pdf_new_string (state.ctx, state.u.pdf, nameddest,
2006 strlen (nameddest));
2007 obj = pdf_lookup_dest (state.ctx, state.u.pdf, needle);
2008 if (obj) {
2009 dest = pdf_parse_link_dest (state.ctx, state.u.pdf,
2010 FZ_LINK_GOTO, obj);
2012 a = desttoanchor (&dest);
2013 if (a.n >= 0) {
2014 printd ("a %d %d %d", a.n, a.x, a.y);
2016 else {
2017 printd ("emsg failed to parse destination `%s'\n",
2018 nameddest);
2021 else {
2022 printd ("emsg destination `%s' not found\n",
2023 nameddest);
2025 pdf_drop_obj (state.ctx, needle);
2028 state.gen++;
2029 unlock ("reqlayout");
2030 printd ("continue %d", state.pagecount);
2032 else if (!strncmp ("page", p, 4)) {
2033 double a, b;
2034 struct page *page;
2035 int pageno, pindex;
2037 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
2038 if (ret != 2) {
2039 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
2042 lock ("page");
2043 a = now ();
2044 page = loadpage (pageno, pindex);
2045 b = now ();
2046 unlock ("page");
2048 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
2050 else if (!strncmp ("tile", p, 4)) {
2051 int x, y, w, h;
2052 struct page *page;
2053 struct tile *tile;
2054 double a, b;
2055 void *data;
2057 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
2058 SCN_ptr_cast (&page), &x, &y, &w, &h,
2059 SCN_ptr_cast (&data));
2060 if (ret != 6) {
2061 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
2064 lock ("tile");
2065 a = now ();
2066 tile = rendertile (page, x, y, w, h, data);
2067 b = now ();
2068 unlock ("tile");
2070 printd ("tile %d %d %" FMT_ptr " %u %f",
2071 x, y,
2072 FMT_ptr_cast (tile),
2073 tile->w * tile->h * tile->pixmap->n,
2074 b - a);
2076 else if (!strncmp ("trimset", p, 7)) {
2077 fz_irect fuzz;
2078 int trimmargins;
2080 ret = sscanf (p + 7, " %d %d %d %d %d",
2081 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
2082 if (ret != 5) {
2083 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
2085 lock ("trimset");
2086 state.trimmargins = trimmargins;
2087 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
2088 state.trimanew = 1;
2089 state.trimfuzz = fuzz;
2091 unlock ("trimset");
2093 else if (!strncmp ("settrim", p, 7)) {
2094 fz_irect fuzz;
2095 int trimmargins;
2097 ret = sscanf (p + 7, " %d %d %d %d %d",
2098 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
2099 if (ret != 5) {
2100 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
2102 printd ("clear");
2103 lock ("settrim");
2104 state.trimmargins = trimmargins;
2105 state.needoutline = 1;
2106 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
2107 state.trimanew = 1;
2108 state.trimfuzz = fuzz;
2110 state.pagedimcount = 0;
2111 free (state.pagedims);
2112 state.pagedims = NULL;
2113 initpdims ();
2114 layout ();
2115 process_outline ();
2116 unlock ("settrim");
2117 printd ("continue %d", state.pagecount);
2119 else if (!strncmp ("sliceh", p, 6)) {
2120 int h;
2122 ret = sscanf (p + 6, " %d", &h);
2123 if (ret != 1) {
2124 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
2126 if (h != state.sliceheight) {
2127 int i;
2129 state.sliceheight = h;
2130 for (i = 0; i < state.texcount; ++i) {
2131 state.texowners[i].w = -1;
2132 state.texowners[i].h = -1;
2133 state.texowners[i].slice = NULL;
2137 else if (!strncmp ("interrupt", p, 9)) {
2138 printd ("vmsg interrupted");
2140 else {
2141 errx (1, "unknown command %.*s", len, p);
2144 return 0;
2147 CAMLprim value ml_realloctexts (value texcount_v)
2149 CAMLparam1 (texcount_v);
2150 int ok;
2152 if (trylock ("ml_realloctexts")) {
2153 ok = 0;
2154 goto done;
2156 realloctexts (Int_val (texcount_v));
2157 ok = 1;
2158 unlock ("ml_realloctexts");
2160 done:
2161 CAMLreturn (Val_bool (ok));
2164 static void recti (int x0, int y0, int x1, int y1)
2166 GLfloat *v = state.vertices;
2168 glVertexPointer (2, GL_FLOAT, 0, v);
2169 v[0] = x0; v[1] = y0;
2170 v[2] = x1; v[3] = y0;
2171 v[4] = x0; v[5] = y1;
2172 v[6] = x1; v[7] = y1;
2173 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2176 static void showsel (struct page *page, int ox, int oy)
2178 int seen = 0;
2179 fz_irect bbox;
2180 fz_rect rect;
2181 fz_text_line *line;
2182 fz_page_block *pageb;
2183 fz_text_block *block;
2184 struct mark first, last;
2185 unsigned char selcolor[] = {15,15,15,140};
2187 first = page->fmark;
2188 last = page->lmark;
2190 if (!first.span || !last.span) return;
2192 glEnable (GL_BLEND);
2193 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2194 glColor4ubv (selcolor);
2196 ox += state.pagedims[page->pdimno].bounds.x0;
2197 oy += state.pagedims[page->pdimno].bounds.y0;
2198 for (pageb = page->text->blocks;
2199 pageb < page->text->blocks + page->text->len;
2200 ++pageb) {
2201 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2202 block = pageb->u.text;
2204 for (line = block->lines;
2205 line < block->lines + block->len;
2206 ++line) {
2207 fz_text_span *span;
2208 rect = fz_empty_rect;
2210 for (span = line->first_span; span; span = span->next) {
2211 int i, j, k;
2212 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2214 j = 0;
2215 k = span->len - 1;
2217 if (span == page->fmark.span && span == page->lmark.span) {
2218 seen = 1;
2219 j = MIN (first.i, last.i);
2220 k = MAX (first.i, last.i);
2222 else {
2223 if (span == first.span) {
2224 seen = 1;
2225 j = first.i;
2227 else if (span == last.span) {
2228 seen = 1;
2229 k = last.i;
2233 if (seen) {
2234 for (i = j; i <= k; ++i) {
2235 fz_rect bbox1;
2236 fz_union_rect (&rect,
2237 fz_text_char_bbox (state.ctx, &bbox1,
2238 span, i));
2240 fz_round_rect (&bbox, &rect);
2241 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2242 bbox.x0,
2243 bbox.y0,
2244 bbox.x1,
2245 bbox.y1,
2246 oy, ox);
2248 recti (bbox.x0 + ox, bbox.y0 + oy,
2249 bbox.x1 + ox, bbox.y1 + oy);
2250 if (span == last.span) {
2251 goto done;
2253 rect = fz_empty_rect;
2258 done:
2259 glDisable (GL_BLEND);
2262 #include "glfont.c"
2264 static void stipplerect (fz_matrix *m,
2265 fz_point *p1,
2266 fz_point *p2,
2267 fz_point *p3,
2268 fz_point *p4,
2269 GLfloat *texcoords,
2270 GLfloat *vertices)
2272 fz_transform_point (p1, m);
2273 fz_transform_point (p2, m);
2274 fz_transform_point (p3, m);
2275 fz_transform_point (p4, m);
2277 float w, h, s, t;
2279 w = p2->x - p1->x;
2280 h = p2->y - p1->y;
2281 t = sqrtf (w*w + h*h) * .25f;
2283 w = p3->x - p2->x;
2284 h = p3->y - p2->y;
2285 s = sqrtf (w*w + h*h) * .25f;
2287 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2288 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2290 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2291 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2293 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2294 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2296 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2297 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2299 glDrawArrays (GL_LINES, 0, 8);
2302 static void highlightlinks (struct page *page, int xoff, int yoff)
2304 int i;
2305 fz_matrix ctm, tm, pm;
2306 fz_link *link, *links;
2307 GLfloat *texcoords = state.texcoords;
2308 GLfloat *vertices = state.vertices;
2310 links = fz_load_links (state.ctx, page->u.anypage);
2312 glEnable (GL_TEXTURE_1D);
2313 glEnable (GL_BLEND);
2314 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2315 glBindTexture (GL_TEXTURE_1D, state.stid);
2317 xoff -= state.pagedims[page->pdimno].bounds.x0;
2318 yoff -= state.pagedims[page->pdimno].bounds.y0;
2319 fz_translate (&tm, xoff, yoff);
2320 pm = pagectm (page);
2321 fz_concat (&ctm, &pm, &tm);
2323 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2324 glVertexPointer (2, GL_FLOAT, 0, vertices);
2326 for (link = links; link; link = link->next) {
2327 fz_point p1, p2, p3, p4;
2329 p1.x = link->rect.x0;
2330 p1.y = link->rect.y0;
2332 p2.x = link->rect.x1;
2333 p2.y = link->rect.y0;
2335 p3.x = link->rect.x1;
2336 p3.y = link->rect.y1;
2338 p4.x = link->rect.x0;
2339 p4.y = link->rect.y1;
2341 switch (link->dest.kind) {
2342 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2343 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2344 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2345 default: glColor3ub (0, 0, 0); break;
2347 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2350 for (i = 0; i < page->annotcount; ++i) {
2351 fz_point p1, p2, p3, p4;
2352 struct annot *annot = &page->annots[i];
2354 p1.x = annot->bbox.x0;
2355 p1.y = annot->bbox.y0;
2357 p2.x = annot->bbox.x1;
2358 p2.y = annot->bbox.y0;
2360 p3.x = annot->bbox.x1;
2361 p3.y = annot->bbox.y1;
2363 p4.x = annot->bbox.x0;
2364 p4.y = annot->bbox.y1;
2366 glColor3ub (0, 0, 128);
2367 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2370 glDisable (GL_BLEND);
2371 glDisable (GL_TEXTURE_1D);
2374 static int compareslinks (const void *l, const void *r)
2376 struct slink const *ls = l;
2377 struct slink const *rs = r;
2378 if (ls->bbox.y0 == rs->bbox.y0) {
2379 return rs->bbox.x0 - rs->bbox.x0;
2381 return ls->bbox.y0 - rs->bbox.y0;
2384 static void droptext (struct page *page)
2386 if (page->text) {
2387 fz_drop_text_page (state.ctx, page->text);
2388 page->fmark.i = -1;
2389 page->lmark.i = -1;
2390 page->fmark.span = NULL;
2391 page->lmark.span = NULL;
2392 page->text = NULL;
2394 if (page->sheet) {
2395 fz_drop_text_sheet (state.ctx, page->sheet);
2396 page->sheet = NULL;
2400 static void dropanots (struct page *page)
2402 if (page->annots) {
2403 free (page->annots);
2404 page->annots = NULL;
2405 page->annotcount = 0;
2409 static void ensureanots (struct page *page)
2411 fz_matrix ctm;
2412 int i, count = 0;
2413 size_t anotsize = sizeof (*page->annots);
2414 pdf_annot *annot;
2416 if (state.gen != page->agen) {
2417 dropanots (page);
2418 page->agen = state.gen;
2420 if (page->annots) return;
2422 switch (page->type) {
2423 case DPDF:
2424 trimctm (page->u.pdfpage, page->pdimno);
2425 fz_concat (&ctm,
2426 &state.pagedims[page->pdimno].tctm,
2427 &state.pagedims[page->pdimno].ctm);
2428 break;
2430 default:
2431 return;
2434 for (annot = pdf_first_annot (state.ctx, page->u.pdfpage);
2435 annot;
2436 annot = pdf_next_annot (state.ctx, page->u.pdfpage, annot)) {
2437 count++;
2440 if (count > 0) {
2441 page->annotcount = count;
2442 page->annots = calloc (count, anotsize);
2443 if (!page->annots) {
2444 err (1, "calloc annots %d", count);
2447 for (annot = pdf_first_annot (state.ctx, page->u.pdfpage), i = 0;
2448 annot;
2449 annot = pdf_next_annot (state.ctx, page->u.pdfpage, annot), i++) {
2450 fz_rect rect;
2452 pdf_bound_annot (state.ctx, page->u.pdfpage, annot, &rect);
2453 fz_transform_rect (&rect, &ctm);
2454 page->annots[i].annot = annot;
2455 fz_round_rect (&page->annots[i].bbox, &annot->pagerect);
2460 static void dropslinks (struct page *page)
2462 if (page->slinks) {
2463 free (page->slinks);
2464 page->slinks = NULL;
2465 page->slinkcount = 0;
2469 static void ensureslinks (struct page *page)
2471 fz_matrix ctm;
2472 int i, count;
2473 size_t slinksize = sizeof (*page->slinks);
2474 fz_link *link, *links;
2476 ensureanots (page);
2477 if (state.gen != page->sgen) {
2478 dropslinks (page);
2479 page->sgen = state.gen;
2481 if (page->slinks) return;
2483 switch (page->type) {
2484 case DPDF:
2485 links = page->u.pdfpage->links;
2486 trimctm (page->u.pdfpage, page->pdimno);
2487 fz_concat (&ctm,
2488 &state.pagedims[page->pdimno].tctm,
2489 &state.pagedims[page->pdimno].ctm);
2490 break;
2492 case DANY:
2493 links = fz_load_links (state.ctx, page->u.anypage);
2494 ctm = state.pagedims[page->pdimno].ctm;
2495 break;
2497 default:
2498 return;
2501 count = page->annotcount;
2502 for (link = links; link; link = link->next) {
2503 count++;
2505 if (count > 0) {
2506 int j;
2508 page->slinkcount = count;
2509 page->slinks = calloc (count, slinksize);
2510 if (!page->slinks) {
2511 err (1, "calloc slinks %d", count);
2514 for (i = 0, link = links; link; ++i, link = link->next) {
2515 fz_rect rect;
2517 rect = link->rect;
2518 fz_transform_rect (&rect, &ctm);
2519 page->slinks[i].tag = SLINK;
2520 page->slinks[i].u.link = link;
2521 fz_round_rect (&page->slinks[i].bbox, &rect);
2523 for (j = 0; j < page->annotcount; ++j, ++i) {
2524 fz_rect rect;
2526 rect = page->annots[j].annot->pagerect;
2527 fz_transform_rect (&rect, &ctm);
2528 fz_round_rect (&page->slinks[i].bbox, &rect);
2530 page->slinks[i].tag = SANNOT;
2531 page->slinks[i].u.annot = page->annots[j].annot;
2533 qsort (page->slinks, count, slinksize, compareslinks);
2537 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2538 static void fmt_linkn (char *s, unsigned int u)
2540 unsigned int len; unsigned int q;
2541 unsigned int zma = 'z' - 'a' + 1;
2542 len = 1; q = u;
2543 while (q > zma - 1) { ++len; q /= zma; }
2544 if (s) {
2545 s += len;
2546 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2547 /* handles u == 0 */
2549 s[len] = 0;
2552 static void highlightslinks (struct page *page, int xoff, int yoff,
2553 int noff, char *targ, int tlen, int hfsize)
2555 int i;
2556 char buf[40];
2557 struct slink *slink;
2558 double x0, y0, x1, y1, w;
2560 ensureslinks (page);
2561 glColor3ub (0xc3, 0xb0, 0x91);
2562 for (i = 0; i < page->slinkcount; ++i) {
2563 fmt_linkn (buf, i + noff);
2564 if (!tlen || !strncmp (targ, buf, tlen)) {
2565 slink = &page->slinks[i];
2567 x0 = slink->bbox.x0 + xoff - 5;
2568 y1 = slink->bbox.y0 + yoff - 5;
2569 y0 = y1 + 10 + hfsize;
2570 w = measure_string (state.face, hfsize, buf);
2571 x1 = x0 + w + 10;
2572 recti (x0, y0, x1, y1);
2576 glEnable (GL_BLEND);
2577 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2578 glEnable (GL_TEXTURE_2D);
2579 glColor3ub (0, 0, 0);
2580 for (i = 0; i < page->slinkcount; ++i) {
2581 fmt_linkn (buf, i + noff);
2582 if (!tlen || !strncmp (targ, buf, tlen)) {
2583 slink = &page->slinks[i];
2585 x0 = slink->bbox.x0 + xoff;
2586 y0 = slink->bbox.y0 + yoff + hfsize;
2587 draw_string (state.face, hfsize, x0, y0, buf);
2590 glDisable (GL_TEXTURE_2D);
2591 glDisable (GL_BLEND);
2594 static void uploadslice (struct tile *tile, struct slice *slice)
2596 int offset;
2597 struct slice *slice1;
2598 unsigned char *texdata;
2600 offset = 0;
2601 for (slice1 = tile->slices; slice != slice1; slice1++) {
2602 offset += slice1->h * tile->w * tile->pixmap->n;
2604 if (slice->texindex != -1 && slice->texindex < state.texcount
2605 && state.texowners[slice->texindex].slice == slice) {
2606 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2608 else {
2609 int subimage = 0;
2610 int texindex = state.texindex++ % state.texcount;
2612 if (state.texowners[texindex].w == tile->w) {
2613 if (state.texowners[texindex].h >= slice->h) {
2614 subimage = 1;
2616 else {
2617 state.texowners[texindex].h = slice->h;
2620 else {
2621 state.texowners[texindex].h = slice->h;
2624 state.texowners[texindex].w = tile->w;
2625 state.texowners[texindex].slice = slice;
2626 slice->texindex = texindex;
2628 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2629 if (tile->pbo) {
2630 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2631 texdata = 0;
2633 else {
2634 texdata = tile->pixmap->samples;
2636 if (subimage) {
2637 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2641 tile->w,
2642 slice->h,
2643 state.texform,
2644 state.texty,
2645 texdata+offset
2648 else {
2649 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2651 state.texiform,
2652 tile->w,
2653 slice->h,
2655 state.texform,
2656 state.texty,
2657 texdata+offset
2660 if (tile->pbo) {
2661 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2666 CAMLprim value ml_begintiles (value unit_v)
2668 CAMLparam1 (unit_v);
2669 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2670 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2671 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2672 CAMLreturn (unit_v);
2675 CAMLprim value ml_endtiles (value unit_v)
2677 CAMLparam1 (unit_v);
2678 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2679 CAMLreturn (unit_v);
2682 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2684 CAMLparam2 (args_v, ptr_v);
2685 int dispx = Int_val (Field (args_v, 0));
2686 int dispy = Int_val (Field (args_v, 1));
2687 int dispw = Int_val (Field (args_v, 2));
2688 int disph = Int_val (Field (args_v, 3));
2689 int tilex = Int_val (Field (args_v, 4));
2690 int tiley = Int_val (Field (args_v, 5));
2691 char *s = String_val (ptr_v);
2692 struct tile *tile = parse_pointer ("ml_drawtile", s);
2693 int slicey, firstslice;
2694 struct slice *slice;
2695 GLfloat *texcoords = state.texcoords;
2696 GLfloat *vertices = state.vertices;
2698 firstslice = tiley / tile->sliceheight;
2699 slice = &tile->slices[firstslice];
2700 slicey = tiley % tile->sliceheight;
2702 while (disph > 0) {
2703 int dh;
2705 dh = slice->h - slicey;
2706 dh = MIN (disph, dh);
2707 uploadslice (tile, slice);
2709 texcoords[0] = tilex; texcoords[1] = slicey;
2710 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2711 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2712 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2714 vertices[0] = dispx; vertices[1] = dispy;
2715 vertices[2] = dispx+dispw; vertices[3] = dispy;
2716 vertices[4] = dispx; vertices[5] = dispy+dh;
2717 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2719 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2720 dispy += dh;
2721 disph -= dh;
2722 slice++;
2723 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2724 slicey = 0;
2726 CAMLreturn (Val_unit);
2729 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2730 value xoff_v, value yoff_v,
2731 value li_v)
2733 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2734 int xoff = Int_val (xoff_v);
2735 int yoff = Int_val (yoff_v);
2736 int noff = Int_val (Field (li_v, 0));
2737 char *targ = String_val (Field (li_v, 1));
2738 int tlen = caml_string_length (Field (li_v, 1));
2739 int hfsize = Int_val (Field (li_v, 2));
2740 char *s = String_val (ptr_v);
2741 int hlmask = Int_val (hlinks_v);
2742 struct page *page = parse_pointer ("ml_postprocess", s);
2744 if (!page->u.ptr) {
2745 /* deal with loadpage failed pages */
2746 goto done;
2749 ensureanots (page);
2751 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2752 if (trylock ("ml_postprocess")) {
2753 noff = 0;
2754 goto done;
2756 if (hlmask & 2) {
2757 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2758 noff = page->slinkcount;
2760 if (page->tgen == state.gen) {
2761 showsel (page, xoff, yoff);
2763 unlock ("ml_postprocess");
2765 done:
2766 CAMLreturn (Val_int (noff));
2769 static struct annot *getannot (struct page *page, int x, int y)
2771 int i;
2772 fz_point p;
2773 fz_matrix ctm;
2774 const fz_matrix *tctm;
2776 if (!page->annots) return NULL;
2778 switch (page->type) {
2779 case DPDF:
2780 trimctm (page->u.pdfpage, page->pdimno);
2781 tctm = &state.pagedims[page->pdimno].tctm;
2782 break;
2784 case DANY:
2785 tctm = &fz_identity;
2786 break;
2788 default:
2789 return NULL;
2792 p.x = x;
2793 p.y = y;
2795 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2796 fz_invert_matrix (&ctm, &ctm);
2797 fz_transform_point (&p, &ctm);
2799 for (i = 0; i < page->annotcount; ++i) {
2800 struct annot *a = &page->annots[i];
2801 if (p.x >= a->annot->pagerect.x0 && p.x <= a->annot->pagerect.x1) {
2802 if (p.y >= a->annot->pagerect.y0 && p.y <= a->annot->pagerect.y1) {
2803 return a;
2807 return NULL;
2810 static fz_link *getlink (struct page *page, int x, int y)
2812 fz_point p;
2813 fz_matrix ctm;
2814 const fz_matrix *tctm;
2815 fz_link *link, *links;
2817 switch (page->type) {
2818 case DPDF + 10:
2819 trimctm (page->u.pdfpage, page->pdimno);
2820 tctm = &state.pagedims[page->pdimno].tctm;
2821 links = page->u.pdfpage->links;
2822 break;
2824 case DANY:
2825 tctm = &fz_identity;
2826 links = fz_load_links (state.ctx, page->u.anypage);
2827 break;
2829 default:
2830 return NULL;
2832 p.x = x;
2833 p.y = y;
2835 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2836 fz_invert_matrix (&ctm, &ctm);
2837 fz_transform_point (&p, &ctm);
2839 for (link = links; link; link = link->next) {
2840 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2841 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2842 return link;
2846 return NULL;
2849 static void ensuretext (struct page *page)
2851 if (state.gen != page->tgen) {
2852 droptext (page);
2853 page->tgen = state.gen;
2855 if (!page->text) {
2856 fz_matrix ctm;
2857 fz_device *tdev;
2859 page->text = fz_new_text_page (state.ctx);
2860 page->sheet = fz_new_text_sheet (state.ctx);
2861 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2862 ctm = pagectm (page);
2863 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2864 fz_run_display_list (state.ctx, page->dlist,
2865 tdev, &ctm, &fz_infinite_rect, NULL);
2866 qsort (page->text->blocks, page->text->len,
2867 sizeof (*page->text->blocks), compareblocks);
2868 fz_end_page (state.ctx, tdev);
2869 fz_drop_device (state.ctx, tdev);
2873 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2875 CAMLparam2 (start_page_v, dir_v);
2876 CAMLlocal1 (ret_v);
2877 int i, dir = Int_val (dir_v);
2878 int start_page = Int_val (start_page_v);
2879 int end_page = dir > 0 ? state.pagecount : -1;
2881 ret_v = Val_int (0);
2882 lock ("ml_findpage_with_links");
2883 for (i = start_page + dir; i != end_page; i += dir) {
2884 int found;
2886 switch (state.type) {
2887 case DPDF:
2889 pdf_page *page = NULL;
2891 fz_try (state.ctx) {
2892 page = pdf_load_page (state.ctx, state.u.pdf, i);
2893 found = !!page->links || !!page->annots;
2895 fz_catch (state.ctx) {
2896 found = 0;
2898 if (page) {
2899 freepdfpage (page);
2902 break;
2903 case DANY:
2905 fz_page *page = fz_load_page (state.ctx, state.u.doc, i);
2906 found = !!fz_load_links (state.ctx, page);
2907 fz_drop_page (state.ctx, page);
2909 break;
2911 default:
2912 ARSERT (0 && "invalid document type");
2915 if (found) {
2916 ret_v = caml_alloc_small (1, 1);
2917 Field (ret_v, 0) = Val_int (i);
2918 goto unlock;
2921 unlock:
2922 unlock ("ml_findpage_with_links");
2923 CAMLreturn (ret_v);
2926 enum { dir_first, dir_last };
2927 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2929 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2931 CAMLparam2 (ptr_v, dir_v);
2932 CAMLlocal2 (ret_v, pos_v);
2933 struct page *page;
2934 int dirtag, i, slinkindex;
2935 struct slink *found = NULL ,*slink;
2936 char *s = String_val (ptr_v);
2938 page = parse_pointer ("ml_findlink", s);
2939 ret_v = Val_int (0);
2940 /* This is scary we are not taking locks here ensureslinks does
2941 not modify state and given that we obtained the page it can not
2942 disappear under us either */
2943 lock ("ml_findlink");
2944 ensureslinks (page);
2946 if (Is_block (dir_v)) {
2947 dirtag = Tag_val (dir_v);
2948 switch (dirtag) {
2949 case dir_first_visible:
2951 int x0, y0, dir, first_index, last_index;
2953 pos_v = Field (dir_v, 0);
2954 x0 = Int_val (Field (pos_v, 0));
2955 y0 = Int_val (Field (pos_v, 1));
2956 dir = Int_val (Field (pos_v, 2));
2958 if (dir >= 0) {
2959 dir = 1;
2960 first_index = 0;
2961 last_index = page->slinkcount;
2963 else {
2964 first_index = page->slinkcount - 1;
2965 last_index = -1;
2968 for (i = first_index; i != last_index; i += dir) {
2969 slink = &page->slinks[i];
2970 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2971 found = slink;
2972 break;
2976 break;
2978 case dir_left:
2979 slinkindex = Int_val (Field (dir_v, 0));
2980 found = &page->slinks[slinkindex];
2981 for (i = slinkindex - 1; i >= 0; --i) {
2982 slink = &page->slinks[i];
2983 if (slink->bbox.x0 < found->bbox.x0) {
2984 found = slink;
2985 break;
2988 break;
2990 case dir_right:
2991 slinkindex = Int_val (Field (dir_v, 0));
2992 found = &page->slinks[slinkindex];
2993 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2994 slink = &page->slinks[i];
2995 if (slink->bbox.x0 > found->bbox.x0) {
2996 found = slink;
2997 break;
3000 break;
3002 case dir_down:
3003 slinkindex = Int_val (Field (dir_v, 0));
3004 found = &page->slinks[slinkindex];
3005 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
3006 slink = &page->slinks[i];
3007 if (slink->bbox.y0 >= found->bbox.y0) {
3008 found = slink;
3009 break;
3012 break;
3014 case dir_up:
3015 slinkindex = Int_val (Field (dir_v, 0));
3016 found = &page->slinks[slinkindex];
3017 for (i = slinkindex - 1; i >= 0; --i) {
3018 slink = &page->slinks[i];
3019 if (slink->bbox.y0 <= found->bbox.y0) {
3020 found = slink;
3021 break;
3024 break;
3027 else {
3028 dirtag = Int_val (dir_v);
3029 switch (dirtag) {
3030 case dir_first:
3031 found = page->slinks;
3032 break;
3034 case dir_last:
3035 if (page->slinks) {
3036 found = page->slinks + (page->slinkcount - 1);
3038 break;
3041 if (found) {
3042 ret_v = caml_alloc_small (2, 1);
3043 Field (ret_v, 0) = Val_int (found - page->slinks);
3046 unlock ("ml_findlink");
3047 CAMLreturn (ret_v);
3050 enum { uuri, ugoto, utext, uunexpected, ulaunch,
3051 unamed, uremote, uremotedest, uannot };
3053 #define LINKTOVAL \
3055 int pageno; \
3057 switch (link->dest.kind) { \
3058 case FZ_LINK_GOTO: \
3060 fz_point p; \
3062 pageno = link->dest.ld.gotor.page; \
3063 p.x = 0; \
3064 p.y = 0; \
3066 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
3067 p.y = link->dest.ld.gotor.lt.y; \
3068 fz_transform_point (&p, &pdim->lctm); \
3069 if (p.y < 0) p.y = 0; \
3071 tup_v = caml_alloc_tuple (2); \
3072 ret_v = caml_alloc_small (1, ugoto); \
3073 Field (tup_v, 0) = Val_int (pageno); \
3074 Field (tup_v, 1) = Val_int (p.y); \
3075 Field (ret_v, 0) = tup_v; \
3077 break; \
3079 case FZ_LINK_URI: \
3080 str_v = caml_copy_string (link->dest.ld.uri.uri); \
3081 ret_v = caml_alloc_small (1, uuri); \
3082 Field (ret_v, 0) = str_v; \
3083 break; \
3085 case FZ_LINK_LAUNCH: \
3086 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
3087 ret_v = caml_alloc_small (1, ulaunch); \
3088 Field (ret_v, 0) = str_v; \
3089 break; \
3091 case FZ_LINK_NAMED: \
3092 str_v = caml_copy_string (link->dest.ld.named.named); \
3093 ret_v = caml_alloc_small (1, unamed); \
3094 Field (ret_v, 0) = str_v; \
3095 break; \
3097 case FZ_LINK_GOTOR: \
3099 int rty; \
3101 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
3102 pageno = link->dest.ld.gotor.page; \
3103 if (pageno == -1) { \
3104 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
3105 rty = uremotedest; \
3107 else { \
3108 gr_v = Val_int (pageno); \
3109 rty = uremote; \
3111 tup_v = caml_alloc_tuple (2); \
3112 ret_v = caml_alloc_small (1, rty); \
3113 Field (tup_v, 0) = str_v; \
3114 Field (tup_v, 1) = gr_v; \
3115 Field (ret_v, 0) = tup_v; \
3117 break; \
3119 default: \
3121 char buf[80]; \
3123 snprintf (buf, sizeof (buf), \
3124 "unhandled link kind %d", link->dest.kind); \
3125 str_v = caml_copy_string (buf); \
3126 ret_v = caml_alloc_small (1, uunexpected); \
3127 Field (ret_v, 0) = str_v; \
3129 break; \
3133 CAMLprim value ml_getlink (value ptr_v, value n_v)
3135 CAMLparam2 (ptr_v, n_v);
3136 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3137 fz_link *link;
3138 struct page *page;
3139 struct pagedim *pdim;
3140 char *s = String_val (ptr_v);
3141 struct slink *slink;
3143 /* See ml_findlink for caveat */
3145 ret_v = Val_int (0);
3146 page = parse_pointer ("ml_getlink", s);
3147 ensureslinks (page);
3148 pdim = &state.pagedims[page->pdimno];
3149 slink = &page->slinks[Int_val (n_v)];
3150 if (slink->tag == SLINK) {
3151 link = slink->u.link;
3152 LINKTOVAL;
3154 else {
3155 ret_v = caml_alloc_small (1, uannot);
3156 tup_v = caml_alloc_tuple (2);
3157 Field (ret_v, 0) = tup_v;
3158 Field (tup_v, 0) = ptr_v;
3159 Field (tup_v, 1) = n_v;
3162 unlock ("ml_getlink");
3163 CAMLreturn (ret_v);
3166 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3168 CAMLparam2 (ptr_v, n_v);
3169 char *s = String_val (ptr_v);
3170 struct page *page;
3171 struct slink *slink;
3173 page = parse_pointer ("ml_getannotcontent", s);
3174 slink = &page->slinks[Int_val (n_v)];
3175 CAMLreturn (caml_copy_string (pdf_annot_contents (state.ctx, state.u.pdf,
3176 slink->u.annot)));
3179 CAMLprim value ml_getlinkcount (value ptr_v)
3181 CAMLparam1 (ptr_v);
3182 struct page *page;
3183 char *s = String_val (ptr_v);
3185 page = parse_pointer ("ml_getlinkcount", s);
3186 CAMLreturn (Val_int (page->slinkcount));
3189 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3191 CAMLparam2 (ptr_v, n_v);
3192 CAMLlocal1 (ret_v);
3193 struct page *page;
3194 struct slink *slink;
3195 char *s = String_val (ptr_v);
3196 /* See ml_findlink for caveat */
3198 page = parse_pointer ("ml_getlinkrect", s);
3199 ret_v = caml_alloc_tuple (4);
3200 ensureslinks (page);
3202 slink = &page->slinks[Int_val (n_v)];
3203 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3204 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3205 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3206 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3207 unlock ("ml_getlinkrect");
3208 CAMLreturn (ret_v);
3211 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3213 CAMLparam3 (ptr_v, x_v, y_v);
3214 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3215 fz_link *link;
3216 struct annot *annot;
3217 struct page *page;
3218 char *ptr = String_val (ptr_v);
3219 int x = Int_val (x_v), y = Int_val (y_v);
3220 struct pagedim *pdim;
3222 ret_v = Val_int (0);
3223 if (trylock ("ml_whatsunder")) {
3224 goto done;
3227 page = parse_pointer ("ml_whatsunder", ptr);
3228 pdim = &state.pagedims[page->pdimno];
3229 x += pdim->bounds.x0;
3230 y += pdim->bounds.y0;
3232 if (1 || state.type == DPDF) {
3233 annot = getannot (page, x, y);
3234 if (annot) {
3235 int i, n = -1;
3237 ensureslinks (page);
3238 for (i = 0; i < page->slinkcount; ++i) {
3239 if (page->slinks[i].tag == SANNOT
3240 && page->slinks[i].u.annot == annot->annot) {
3241 n = i;
3242 break;
3245 ret_v = caml_alloc_small (1, uannot);
3246 tup_v = caml_alloc_tuple (2);
3247 Field (ret_v, 0) = tup_v;
3248 Field (tup_v, 0) = ptr_v;
3249 Field (tup_v, 1) = Val_int (n);
3250 goto unlock;
3254 link = getlink (page, x, y);
3255 if (link) {
3256 LINKTOVAL;
3258 else {
3259 fz_rect *b;
3260 fz_page_block *pageb;
3261 fz_text_block *block;
3263 ensuretext (page);
3264 for (pageb = page->text->blocks;
3265 pageb < page->text->blocks + page->text->len;
3266 ++pageb) {
3267 fz_text_line *line;
3268 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3269 block = pageb->u.text;
3271 b = &block->bbox;
3272 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3273 continue;
3275 for (line = block->lines;
3276 line < block->lines + block->len;
3277 ++line) {
3278 fz_text_span *span;
3280 b = &line->bbox;
3281 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3282 continue;
3284 for (span = line->first_span; span; span = span->next) {
3285 int charnum;
3287 b = &span->bbox;
3288 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3289 continue;
3291 for (charnum = 0; charnum < span->len; ++charnum) {
3292 fz_rect bbox;
3293 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3294 b = &bbox;
3296 if (x >= b->x0 && x <= b->x1
3297 && y >= b->y0 && y <= b->y1) {
3298 fz_text_style *style = span->text->style;
3299 const char *n2 =
3300 style->font && style->font->name
3301 ? style->font->name
3302 : "Span has no font name"
3304 FT_FaceRec *face = style->font->ft_face;
3305 if (face && face->family_name) {
3306 char *s;
3307 char *n1 = face->family_name;
3308 size_t l1 = strlen (n1);
3309 size_t l2 = strlen (n2);
3311 if (l1 != l2 || memcmp (n1, n2, l1)) {
3312 s = malloc (l1 + l2 + 2);
3313 if (s) {
3314 memcpy (s, n2, l2);
3315 s[l2] = '=';
3316 memcpy (s + l2 + 1, n1, l1 + 1);
3317 str_v = caml_copy_string (s);
3318 free (s);
3322 if (str_v == Val_unit) {
3323 str_v = caml_copy_string (n2);
3325 ret_v = caml_alloc_small (1, utext);
3326 Field (ret_v, 0) = str_v;
3327 goto unlock;
3334 unlock:
3335 unlock ("ml_whatsunder");
3337 done:
3338 CAMLreturn (ret_v);
3341 enum { mark_page, mark_block, mark_line, mark_word };
3343 static int uninteresting (int c)
3345 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3346 || ispunct (c);
3349 CAMLprim value ml_clearmark (value ptr_v)
3351 CAMLparam1 (ptr_v);
3352 char *s = String_val (ptr_v);
3353 struct page *page;
3355 if (trylock ("ml_clearmark")) {
3356 goto done;
3359 page = parse_pointer ("ml_clearmark", s);
3360 page->fmark.span = NULL;
3361 page->lmark.span = NULL;
3362 page->fmark.i = 0;
3363 page->lmark.i = 0;
3365 unlock ("ml_clearmark");
3366 done:
3367 CAMLreturn (Val_unit);
3370 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3372 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3373 CAMLlocal1 (ret_v);
3374 fz_rect *b;
3375 struct page *page;
3376 fz_text_line *line;
3377 fz_page_block *pageb;
3378 fz_text_block *block;
3379 struct pagedim *pdim;
3380 int mark = Int_val (mark_v);
3381 char *s = String_val (ptr_v);
3382 int x = Int_val (x_v), y = Int_val (y_v);
3384 ret_v = Val_bool (0);
3385 if (trylock ("ml_markunder")) {
3386 goto done;
3389 page = parse_pointer ("ml_markunder", s);
3390 pdim = &state.pagedims[page->pdimno];
3392 ensuretext (page);
3394 if (mark == mark_page) {
3395 int i;
3396 fz_page_block *pb1 = NULL, *pb2 = NULL;
3398 for (i = 0; i < page->text->len; ++i) {
3399 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3400 pb1 = &page->text->blocks[i];
3401 break;
3404 if (!pb1) goto unlock;
3406 for (i = page->text->len - 1; i >= 0; --i) {
3407 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3408 pb2 = &page->text->blocks[i];
3409 break;
3412 if (!pb2) goto unlock;
3414 block = pb1->u.text;
3416 page->fmark.i = 0;
3417 page->fmark.span = block->lines->first_span;
3419 block = pb2->u.text;
3420 line = &block->lines[block->len - 1];
3421 page->lmark.i = line->last_span->len - 1;
3422 page->lmark.span = line->last_span;
3423 ret_v = Val_bool (1);
3424 goto unlock;
3427 x += pdim->bounds.x0;
3428 y += pdim->bounds.y0;
3430 for (pageb = page->text->blocks;
3431 pageb < page->text->blocks + page->text->len;
3432 ++pageb) {
3433 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3434 block = pageb->u.text;
3436 b = &block->bbox;
3437 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3438 continue;
3440 if (mark == mark_block) {
3441 page->fmark.i = 0;
3442 page->fmark.span = block->lines->first_span;
3444 line = &block->lines[block->len - 1];
3445 page->lmark.i = line->last_span->len - 1;
3446 page->lmark.span = line->last_span;
3447 ret_v = Val_bool (1);
3448 goto unlock;
3451 for (line = block->lines;
3452 line < block->lines + block->len;
3453 ++line) {
3454 fz_text_span *span;
3456 b = &line->bbox;
3457 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3458 continue;
3460 if (mark == mark_line) {
3461 page->fmark.i = 0;
3462 page->fmark.span = line->first_span;
3464 page->lmark.i = line->last_span->len - 1;
3465 page->lmark.span = line->last_span;
3466 ret_v = Val_bool (1);
3467 goto unlock;
3470 for (span = line->first_span; span; span = span->next) {
3471 int charnum;
3473 b = &span->bbox;
3474 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3475 continue;
3477 for (charnum = 0; charnum < span->len; ++charnum) {
3478 fz_rect bbox;
3479 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3480 b = &bbox;
3482 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3483 /* unicode ftw */
3484 int charnum2, charnum3 = -1, charnum4 = -1;
3486 if (uninteresting (span->text[charnum].c)) goto unlock;
3488 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3489 if (uninteresting (span->text[charnum2].c)) {
3490 charnum3 = charnum2 + 1;
3491 break;
3494 if (charnum3 == -1) charnum3 = 0;
3496 for (charnum2 = charnum + 1;
3497 charnum2 < span->len;
3498 ++charnum2) {
3499 if (uninteresting (span->text[charnum2].c)) break;
3500 charnum4 = charnum2;
3502 if (charnum4 == -1) goto unlock;
3504 page->fmark.i = charnum3;
3505 page->fmark.span = span;
3507 page->lmark.i = charnum4;
3508 page->lmark.span = span;
3509 ret_v = Val_bool (1);
3510 goto unlock;
3516 unlock:
3517 if (!Bool_val (ret_v)) {
3518 page->fmark.span = NULL;
3519 page->lmark.span = NULL;
3520 page->fmark.i = 0;
3521 page->lmark.i = 0;
3523 unlock ("ml_markunder");
3525 done:
3526 CAMLreturn (ret_v);
3529 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3531 CAMLparam3 (ptr_v, x_v, y_v);
3532 CAMLlocal2 (ret_v, res_v);
3533 fz_rect *b = NULL;
3534 struct page *page;
3535 fz_page_block *pageb;
3536 struct pagedim *pdim;
3537 char *s = String_val (ptr_v);
3538 int x = Int_val (x_v), y = Int_val (y_v);
3540 ret_v = Val_int (0);
3541 if (trylock ("ml_rectofblock")) {
3542 goto done;
3545 page = parse_pointer ("ml_rectofblock", s);
3546 pdim = &state.pagedims[page->pdimno];
3547 x += pdim->bounds.x0;
3548 y += pdim->bounds.y0;
3550 ensuretext (page);
3552 for (pageb = page->text->blocks;
3553 pageb < page->text->blocks + page->text->len;
3554 ++pageb) {
3555 switch (pageb->type) {
3556 case FZ_PAGE_BLOCK_TEXT:
3557 b = &pageb->u.text->bbox;
3558 break;
3560 case FZ_PAGE_BLOCK_IMAGE:
3561 b = &pageb->u.image->bbox;
3562 break;
3564 default:
3565 continue;
3568 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3569 break;
3570 b = NULL;
3572 if (b) {
3573 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3574 ret_v = caml_alloc_small (1, 1);
3575 Store_double_field (res_v, 0, b->x0);
3576 Store_double_field (res_v, 1, b->x1);
3577 Store_double_field (res_v, 2, b->y0);
3578 Store_double_field (res_v, 3, b->y1);
3579 Field (ret_v, 0) = res_v;
3581 unlock ("ml_rectofblock");
3583 done:
3584 CAMLreturn (ret_v);
3587 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3589 CAMLparam2 (ptr_v, rect_v);
3590 fz_rect b;
3591 struct page *page;
3592 struct pagedim *pdim;
3593 char *s = String_val (ptr_v);
3594 int i, x0, x1, y0, y1, fi, li;
3595 fz_text_line *line;
3596 fz_page_block *pageb;
3597 fz_text_block *block;
3598 fz_text_span *span, *fspan, *lspan;
3600 if (trylock ("ml_seltext")) {
3601 goto done;
3604 page = parse_pointer ("ml_seltext", s);
3605 ensuretext (page);
3607 pdim = &state.pagedims[page->pdimno];
3608 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3609 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3610 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3611 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3613 if (y0 > y1) {
3614 int t = y0;
3615 y0 = y1;
3616 y1 = t;
3617 x0 = x1;
3618 x1 = t;
3621 if (0) {
3622 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3623 glColor3ub (128, 128, 128);
3624 recti (x0, y0, x1, y1);
3625 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3628 fi = page->fmark.i;
3629 fspan = page->fmark.span;
3631 li = page->lmark.i;
3632 lspan = page->lmark.span;
3634 for (pageb = page->text->blocks;
3635 pageb < page->text->blocks + page->text->len;
3636 ++pageb) {
3637 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3638 block = pageb->u.text;
3639 for (line = block->lines;
3640 line < block->lines + block->len;
3641 ++line) {
3643 for (span = line->first_span; span; span = span->next) {
3644 for (i = 0; i < span->len; ++i) {
3645 int selected = 0;
3647 fz_text_char_bbox (state.ctx, &b, span, i);
3649 if (x0 >= b.x0 && x0 <= b.x1
3650 && y0 >= b.y0 && y0 <= b.y1) {
3651 fspan = span;
3652 fi = i;
3653 selected = 1;
3655 if (x1 >= b.x0 && x1 <= b.x1
3656 && y1 >= b.y0 && y1 <= b.y1) {
3657 lspan = span;
3658 li = i;
3659 selected = 1;
3661 if (0 && selected) {
3662 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3663 glColor3ub (128, 128, 128);
3664 recti (b.x0, b.y0, b.x1, b.y1);
3665 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3671 if (x1 < x0 && fspan == lspan) {
3672 i = fi;
3673 span = fspan;
3675 fi = li;
3676 fspan = lspan;
3678 li = i;
3679 lspan = span;
3682 page->fmark.i = fi;
3683 page->fmark.span = fspan;
3685 page->lmark.i = li;
3686 page->lmark.span = lspan;
3688 unlock ("ml_seltext");
3690 done:
3691 CAMLreturn (Val_unit);
3694 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3696 char buf[4];
3697 int i, len, ret;
3699 for (i = a; i <= b; ++i) {
3700 len = fz_runetochar (buf, span->text[i].c);
3701 ret = fwrite (buf, len, 1, f);
3703 if (ret != 1) {
3704 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3705 len, ret, strerror (errno));
3706 return -1;
3709 return 0;
3712 #ifdef __CYGWIN__
3713 CAMLprim value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3715 caml_failwith ("ml_popen not implemented under Cygwin");
3717 #else
3718 CAMLprim value ml_popen (value command_v, value fds_v)
3720 CAMLparam2 (command_v, fds_v);
3721 CAMLlocal2 (l_v, tup_v);
3722 int ret;
3723 pid_t pid;
3724 char *msg = NULL;
3725 value earg_v = Nothing;
3726 posix_spawnattr_t attr;
3727 posix_spawn_file_actions_t fa;
3728 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3730 argv[2] = String_val (command_v);
3732 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3733 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3736 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3737 msg = "posix_spawnattr_init";
3738 goto fail1;
3741 #ifdef POSIX_SPAWN_USEVFORK
3742 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3743 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3744 goto fail;
3746 #endif
3748 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3749 int fd1, fd2;
3751 tup_v = Field (l_v, 0);
3752 fd1 = Int_val (Field (tup_v, 0));
3753 fd2 = Int_val (Field (tup_v, 1));
3754 if (fd2 < 0) {
3755 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3756 msg = "posix_spawn_file_actions_addclose";
3757 earg_v = tup_v;
3758 goto fail;
3761 else {
3762 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3763 msg = "posix_spawn_file_actions_adddup2";
3764 earg_v = tup_v;
3765 goto fail;
3770 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3771 msg = "posix_spawn";
3772 goto fail;
3775 fail:
3776 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3777 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3780 fail1:
3781 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3782 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3783 strerror (ret));
3786 if (msg)
3787 unix_error (ret, msg, earg_v);
3789 CAMLreturn (Val_int (pid));
3791 #endif
3793 CAMLprim value ml_hassel (value ptr_v)
3795 CAMLparam1 (ptr_v);
3796 CAMLlocal1 (ret_v);
3797 struct page *page;
3798 char *s = String_val (ptr_v);
3800 ret_v = Val_bool (0);
3801 if (trylock ("ml_hassel")) {
3802 goto done;
3805 page = parse_pointer ("ml_hassel", s);
3806 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3807 unlock ("ml_hassel");
3808 done:
3809 CAMLreturn (ret_v);
3812 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3814 CAMLparam2 (fd_v, ptr_v);
3815 FILE *f;
3816 int seen = 0;
3817 struct page *page;
3818 fz_text_line *line;
3819 fz_page_block *pageb;
3820 fz_text_block *block;
3821 int fd = Int_val (fd_v);
3822 char *s = String_val (ptr_v);
3824 if (trylock ("ml_copysel")) {
3825 goto done;
3828 page = parse_pointer ("ml_copysel", s);
3830 if (!page->fmark.span || !page->lmark.span) {
3831 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3832 goto unlock;
3835 f = fdopen (fd, "w");
3836 if (!f) {
3837 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3838 fd, strerror (errno));
3839 f = stdout;
3842 for (pageb = page->text->blocks;
3843 pageb < page->text->blocks + page->text->len;
3844 ++pageb) {
3845 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3846 block = pageb->u.text;
3847 for (line = block->lines;
3848 line < block->lines + block->len;
3849 ++line) {
3850 fz_text_span *span;
3852 for (span = line->first_span; span; span = span->next) {
3853 int a, b;
3855 seen |= span == page->fmark.span || span == page->lmark.span;
3856 a = span == page->fmark.span ? page->fmark.i : 0;
3857 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3859 if (seen) {
3860 if (pipespan (f, span, a, b)) {
3861 goto close;
3863 if (span == page->lmark.span) {
3864 goto close;
3866 if (span == line->last_span) {
3867 if (putc ('\n', f) == EOF) {
3868 fprintf (stderr,
3869 "failed break line on sel pipe: %s\n",
3870 strerror (errno));
3871 goto close;
3878 close:
3879 if (f != stdout) {
3880 int ret = fclose (f);
3881 fd = -1;
3882 if (ret == -1) {
3883 if (errno != ECHILD) {
3884 fprintf (stderr, "failed to close sel pipe: %s\n",
3885 strerror (errno));
3889 unlock:
3890 unlock ("ml_copysel");
3892 done:
3893 if (fd >= 0) {
3894 if (close (fd)) {
3895 fprintf (stderr, "failed to close sel pipe: %s\n",
3896 strerror (errno));
3899 CAMLreturn (Val_unit);
3902 CAMLprim value ml_getpdimrect (value pagedimno_v)
3904 CAMLparam1 (pagedimno_v);
3905 CAMLlocal1 (ret_v);
3906 int pagedimno = Int_val (pagedimno_v);
3907 fz_rect box;
3909 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3910 if (trylock ("ml_getpdimrect")) {
3911 box = fz_empty_rect;
3913 else {
3914 box = state.pagedims[pagedimno].mediabox;
3915 unlock ("ml_getpdimrect");
3918 Store_double_field (ret_v, 0, box.x0);
3919 Store_double_field (ret_v, 1, box.x1);
3920 Store_double_field (ret_v, 2, box.y0);
3921 Store_double_field (ret_v, 3, box.y1);
3923 CAMLreturn (ret_v);
3926 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3927 value dw_v, value cols_v)
3929 CAMLparam3 (winw_v, winh_v, dw_v);
3930 CAMLlocal1 (ret_v);
3931 int i;
3932 double zoom = -1.;
3933 double maxh = 0.0;
3934 struct pagedim *p;
3935 double winw = Int_val (winw_v);
3936 double winh = Int_val (winh_v);
3937 double dw = Int_val (dw_v);
3938 double cols = Int_val (cols_v);
3939 double pw = 1.0, ph = 1.0;
3941 if (trylock ("ml_zoom_for_height")) {
3942 goto done;
3945 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3946 double w = p->pagebox.x1 / cols;
3947 double h = p->pagebox.y1;
3948 if (h > maxh) {
3949 maxh = h;
3950 ph = h;
3951 if (state.fitmodel != FitProportional) pw = w;
3953 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3956 zoom = (((winh / ph) * pw) + dw) / winw;
3957 unlock ("ml_zoom_for_height");
3958 done:
3959 ret_v = caml_copy_double (zoom);
3960 CAMLreturn (ret_v);
3963 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3965 CAMLparam4 (pt_v, x_v, y_v, string_v);
3966 CAMLlocal1 (ret_v);
3967 int pt = Int_val(pt_v);
3968 int x = Int_val (x_v);
3969 int y = Int_val (y_v);
3970 double w;
3972 w = draw_string (state.face, pt, x, y, String_val (string_v));
3973 ret_v = caml_copy_double (w);
3974 CAMLreturn (ret_v);
3977 CAMLprim value ml_measure_string (value pt_v, value string_v)
3979 CAMLparam2 (pt_v, string_v);
3980 CAMLlocal1 (ret_v);
3981 int pt = Int_val (pt_v);
3982 double w;
3984 w = measure_string (state.face, pt, String_val (string_v));
3985 ret_v = caml_copy_double (w);
3986 CAMLreturn (ret_v);
3989 CAMLprim value ml_getpagebox (value opaque_v)
3991 CAMLparam1 (opaque_v);
3992 CAMLlocal1 (ret_v);
3993 fz_rect rect;
3994 fz_irect bbox;
3995 fz_matrix ctm;
3996 fz_device *dev;
3997 char *s = String_val (opaque_v);
3998 struct page *page = parse_pointer ("ml_getpagebox", s);
4000 ret_v = caml_alloc_tuple (4);
4001 dev = fz_new_bbox_device (state.ctx, &rect);
4002 dev->hints |= FZ_IGNORE_SHADE;
4004 switch (page->type) {
4005 case DPDF:
4006 ctm = pagectm (page);
4007 pdf_run_page (state.ctx, page->u.pdfpage, dev, &ctm, NULL);
4008 break;
4010 case DANY:
4011 ctm = pagectm (page);
4012 fz_run_page (state.ctx, page->u.anypage, dev, &ctm, NULL);
4013 break;
4015 default:
4016 rect = fz_infinite_rect;
4017 break;
4020 fz_drop_device (state.ctx, dev);
4021 fz_round_rect (&bbox, &rect);
4022 Field (ret_v, 0) = Val_int (bbox.x0);
4023 Field (ret_v, 1) = Val_int (bbox.y0);
4024 Field (ret_v, 2) = Val_int (bbox.x1);
4025 Field (ret_v, 3) = Val_int (bbox.y1);
4027 CAMLreturn (ret_v);
4030 CAMLprim value ml_setaalevel (value level_v)
4032 CAMLparam1 (level_v);
4034 state.aalevel = Int_val (level_v);
4035 CAMLreturn (Val_unit);
4038 #pragma GCC diagnostic push
4039 #pragma GCC diagnostic ignored "-Wvariadic-macros"
4040 #include <X11/Xlib.h>
4041 #pragma GCC diagnostic pop
4043 #include <GL/glx.h>
4045 static struct {
4046 Window wid;
4047 Display *dpy;
4048 GLXContext ctx;
4049 XVisualInfo *visual;
4050 } glx;
4052 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4054 CAMLparam3 (display_v, wid_v, screen_v);
4055 int attribs[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
4057 glx.dpy = XOpenDisplay (String_val (display_v));
4058 if (!glx.dpy) {
4059 caml_failwith ("XOpenDisplay");
4062 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4063 if (!glx.visual) {
4064 XCloseDisplay (glx.dpy);
4065 caml_failwith ("glXChooseVisual");
4068 glx.wid = Int_val (wid_v);
4069 CAMLreturn (Val_int (glx.visual->visualid));
4072 CAMLprim value ml_glxcompleteinit (value unit_v)
4074 CAMLparam1 (unit_v);
4076 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4077 if (!glx.ctx) {
4078 caml_failwith ("glXCreateContext");
4081 XFree (glx.visual);
4082 glx.visual = NULL;
4084 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4085 glXDestroyContext (glx.dpy, glx.ctx);
4086 glx.ctx = NULL;
4087 caml_failwith ("glXMakeCurrent");
4089 CAMLreturn (Val_unit);
4092 CAMLprim value ml_swapb (value unit_v)
4094 CAMLparam1 (unit_v);
4095 glXSwapBuffers (glx.dpy, glx.wid);
4096 CAMLreturn (Val_unit);
4099 #include "keysym2ucs.c"
4101 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4103 CAMLparam1 (keysym_v);
4104 CAMLlocal1 (str_v);
4105 KeySym keysym = Int_val (keysym_v);
4106 Rune rune;
4107 int len;
4108 char buf[5];
4110 rune = keysym2ucs (keysym);
4111 len = fz_runetochar (buf, rune);
4112 buf[len] = 0;
4113 str_v = caml_copy_string (buf);
4114 CAMLreturn (str_v);
4117 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4119 CAMLprim value ml_platform (value unit_v)
4121 CAMLparam1 (unit_v);
4122 CAMLlocal2 (tup_v, arr_v);
4123 int platid = piunknown;
4124 struct utsname buf;
4126 #if defined __linux__
4127 platid = pilinux;
4128 #elif defined __CYGWIN__
4129 platid = picygwin;
4130 #elif defined __DragonFly__ || defined __FreeBSD__
4131 || defined __OpenBSD__ || defined __NetBSD__
4132 platid = pibsd;
4133 #elif defined __sun__
4134 platid = pisun;
4135 #elif defined __APPLE__
4136 platid = piosx;
4137 #endif
4138 if (uname (&buf)) err (1, "uname");
4140 tup_v = caml_alloc_tuple (2);
4142 char const *sar[] = {
4143 buf.sysname,
4144 buf.release,
4145 buf.version,
4146 buf.machine,
4147 NULL
4149 arr_v = caml_copy_string_array (sar);
4151 Field (tup_v, 0) = Val_int (platid);
4152 Field (tup_v, 1) = arr_v;
4153 CAMLreturn (tup_v);
4156 CAMLprim value ml_cloexec (value fd_v)
4158 CAMLparam1 (fd_v);
4159 int fd = Int_val (fd_v);
4161 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4162 uerror ("fcntl", Nothing);
4164 CAMLreturn (Val_unit);
4167 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4169 CAMLparam2 (w_v, h_v);
4170 CAMLlocal1 (ret_v);
4171 struct pbo *pbo;
4172 int w = Int_val (w_v);
4173 int h = Int_val (h_v);
4174 int cs = Int_val (cs_v);
4176 if (state.pbo_usable) {
4177 pbo = calloc (sizeof (*pbo), 1);
4178 if (!pbo) {
4179 err (1, "calloc pbo");
4182 switch (cs) {
4183 case 0:
4184 case 1:
4185 pbo->size = w*h*4;
4186 break;
4187 case 2:
4188 pbo->size = w*h*2;
4189 break;
4190 default:
4191 errx (1, "ml_getpbo: invalid colorspace %d", cs);
4194 state.glGenBuffersARB (1, &pbo->id);
4195 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4196 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4197 NULL, GL_STREAM_DRAW);
4198 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4199 GL_READ_WRITE);
4200 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4201 if (!pbo->ptr) {
4202 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4203 state.glDeleteBuffersARB (1, &pbo->id);
4204 free (pbo);
4205 ret_v = caml_copy_string ("0");
4207 else {
4208 int res;
4209 char *s;
4211 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4212 if (res < 0) {
4213 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4215 s = malloc (res+1);
4216 if (!s) {
4217 err (1, "malloc %d bytes failed", res+1);
4219 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4220 if (res < 0) {
4221 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4223 ret_v = caml_copy_string (s);
4224 free (s);
4227 else {
4228 ret_v = caml_copy_string ("0");
4230 CAMLreturn (ret_v);
4233 CAMLprim value ml_freepbo (value s_v)
4235 CAMLparam1 (s_v);
4236 char *s = String_val (s_v);
4237 struct tile *tile = parse_pointer ("ml_freepbo", s);
4239 if (tile->pbo) {
4240 state.glDeleteBuffersARB (1, &tile->pbo->id);
4241 tile->pbo->id = -1;
4242 tile->pbo->ptr = NULL;
4243 tile->pbo->size = -1;
4245 CAMLreturn (Val_unit);
4248 CAMLprim value ml_unmappbo (value s_v)
4250 CAMLparam1 (s_v);
4251 char *s = String_val (s_v);
4252 struct tile *tile = parse_pointer ("ml_unmappbo", s);
4254 if (tile->pbo) {
4255 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4256 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4257 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4259 tile->pbo->ptr = NULL;
4260 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4262 CAMLreturn (Val_unit);
4265 static void setuppbo (void)
4267 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4268 state.pbo_usable = GGPA (glBindBufferARB)
4269 && GGPA (glUnmapBufferARB)
4270 && GGPA (glMapBufferARB)
4271 && GGPA (glBufferDataARB)
4272 && GGPA (glGenBuffersARB)
4273 && GGPA (glDeleteBuffersARB);
4274 #undef GGPA
4277 CAMLprim value ml_pbo_usable (value unit_v)
4279 CAMLparam1 (unit_v);
4280 CAMLreturn (Val_bool (state.pbo_usable));
4283 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4285 CAMLparam3 (ptr_v, x_v, y_v);
4286 CAMLlocal2 (ret_v, tup_v);
4287 struct page *page;
4288 char *s = String_val (ptr_v);
4289 int x = Int_val (x_v), y = Int_val (y_v);
4290 struct pagedim *pdim;
4291 fz_point p;
4292 fz_matrix ctm;
4294 page = parse_pointer ("ml_unproject", s);
4295 pdim = &state.pagedims[page->pdimno];
4297 ret_v = Val_int (0);
4298 if (trylock ("ml_unproject")) {
4299 goto done;
4302 switch (page->type) {
4303 case DPDF:
4304 trimctm (page->u.pdfpage, page->pdimno);
4305 break;
4307 default:
4308 break;
4310 p.x = x + pdim->bounds.x0;
4311 p.y = y + pdim->bounds.y0;
4313 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4314 fz_invert_matrix (&ctm, &ctm);
4315 fz_transform_point (&p, &ctm);
4317 tup_v = caml_alloc_tuple (2);
4318 ret_v = caml_alloc_small (1, 1);
4319 Field (tup_v, 0) = Val_int (p.x);
4320 Field (tup_v, 1) = Val_int (p.y);
4321 Field (ret_v, 0) = tup_v;
4323 unlock ("ml_unproject");
4324 done:
4325 CAMLreturn (ret_v);
4328 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4329 value contents_v)
4331 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4333 if (state.type == DPDF) {
4334 pdf_document *pdf;
4335 pdf_annot *annot;
4336 struct page *page;
4337 fz_point p;
4338 char *s = String_val (ptr_v);
4340 pdf = state.u.pdf;
4341 page = parse_pointer ("ml_addannot", s);
4342 annot = pdf_create_annot (state.ctx, pdf,
4343 page->u.pdfpage, FZ_ANNOT_TEXT);
4344 p.x = Int_val (x_v);
4345 p.y = Int_val (y_v);
4346 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4347 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4348 state.dirty = 1;
4350 CAMLreturn (Val_unit);
4353 CAMLprim value ml_delannot (value ptr_v, value n_v)
4355 CAMLparam2 (ptr_v, n_v);
4357 if (state.type == DPDF) {
4358 struct page *page;
4359 char *s = String_val (ptr_v);
4360 struct slink *slink;
4362 page = parse_pointer ("ml_delannot", s);
4363 slink = &page->slinks[Int_val (n_v)];
4364 pdf_delete_annot (state.ctx, state.u.pdf,
4365 page->u.pdfpage, slink->u.annot);
4366 state.dirty = 1;
4368 CAMLreturn (Val_unit);
4371 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4373 CAMLparam3 (ptr_v, n_v, str_v);
4375 if (state.type == DPDF) {
4376 struct page *page;
4377 char *s = String_val (ptr_v);
4378 struct slink *slink;
4380 page = parse_pointer ("ml_modannot", s);
4381 slink = &page->slinks[Int_val (n_v)];
4382 pdf_set_annot_contents (state.ctx, state.u.pdf, slink->u.annot,
4383 String_val (str_v));
4384 state.dirty = 1;
4386 CAMLreturn (Val_unit);
4389 CAMLprim value ml_hasunsavedchanges (value unit_v)
4391 CAMLparam1 (unit_v);
4392 CAMLreturn (Val_bool (state.dirty));
4395 CAMLprim value ml_savedoc (value path_v)
4397 CAMLparam1 (path_v);
4399 if (state.type == DPDF) {
4400 pdf_write_document (state.ctx, state.u.pdf, String_val (path_v), NULL);
4402 CAMLreturn (Val_unit);
4405 static void makestippletex (void)
4407 const char pixels[] = "\xff\xff\0\0";
4408 glGenTextures (1, &state.stid);
4409 glBindTexture (GL_TEXTURE_1D, state.stid);
4410 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4411 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4412 glTexImage1D (
4413 GL_TEXTURE_1D,
4415 GL_ALPHA,
4418 GL_ALPHA,
4419 GL_UNSIGNED_BYTE,
4420 pixels
4424 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4426 return caml_copy_string (FZ_VERSION);
4429 #ifdef USE_FONTCONFIG
4430 static struct {
4431 int inited;
4432 FcConfig *config;
4433 } fc;
4435 static fz_font *fc_load_system_font_func (fz_context *ctx,
4436 const char *name,
4437 int bold,
4438 int italic,
4439 int UNUSED_ATTR needs_exact_metrics)
4441 char *buf;
4442 size_t i, size;
4443 fz_font *font;
4444 FcChar8 *path;
4445 FcResult result;
4446 FcPattern *pat, *pat1;
4448 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4449 name, bold, italic, needs_exact_metrics);
4450 if (!fc.inited) {
4451 fc.inited = 1;
4452 fc.config = FcInitLoadConfigAndFonts ();
4453 if (!fc.config) {
4454 lprintf ("FcInitLoadConfigAndFonts failed\n");
4455 return NULL;
4458 if (!fc.config) return NULL;
4460 size = strlen (name);
4461 if (bold) size += sizeof (":bold") - 1;
4462 if (italic) size += sizeof (":italic") - 1;
4463 size += 1;
4465 buf = malloc (size);
4466 if (!buf) {
4467 err (1, "malloc %zu failed", size);
4470 strcpy (buf, name);
4471 if (bold && italic) {
4472 strcat (buf, ":bold:italic");
4474 else {
4475 if (bold) strcat (buf, ":bold");
4476 if (italic) strcat (buf, ":italic");
4478 for (i = 0; i < size; ++i) {
4479 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4482 lprintf ("fcbuf=%s\n", buf);
4483 pat = FcNameParse ((FcChar8 *) buf);
4484 if (!pat) {
4485 printd ("emsg FcNameParse failed\n");
4486 free (buf);
4487 return NULL;
4490 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4491 printd ("emsg FcConfigSubstitute failed\n");
4492 free (buf);
4493 return NULL;
4495 FcDefaultSubstitute (pat);
4497 pat1 = FcFontMatch (fc.config, pat, &result);
4498 if (!pat1) {
4499 printd ("emsg FcFontMatch failed\n");
4500 FcPatternDestroy (pat);
4501 free (buf);
4502 return NULL;
4505 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4506 printd ("emsg FcPatternGetString failed\n");
4507 FcPatternDestroy (pat);
4508 FcPatternDestroy (pat1);
4509 free (buf);
4510 return NULL;
4513 #if 0
4514 printd ("emsg name=%s path=%s\n", name, path);
4515 #endif
4516 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4517 FcPatternDestroy (pat);
4518 FcPatternDestroy (pat1);
4519 free (buf);
4520 return font;
4522 #endif
4524 CAMLprim value ml_init (value csock_v, value params_v)
4526 CAMLparam2 (csock_v, params_v);
4527 CAMLlocal2 (trim_v, fuzz_v);
4528 int ret;
4529 int texcount;
4530 char *fontpath;
4531 int colorspace;
4532 int mustoresize;
4533 int haspboext;
4535 state.csock = Int_val (csock_v);
4536 state.rotate = Int_val (Field (params_v, 0));
4537 state.fitmodel = Int_val (Field (params_v, 1));
4538 trim_v = Field (params_v, 2);
4539 texcount = Int_val (Field (params_v, 3));
4540 state.sliceheight = Int_val (Field (params_v, 4));
4541 mustoresize = Int_val (Field (params_v, 5));
4542 colorspace = Int_val (Field (params_v, 6));
4543 fontpath = String_val (Field (params_v, 7));
4545 if (caml_string_length (Field (params_v, 8)) > 0) {
4546 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4548 if (!state.trimcachepath) {
4549 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4550 strerror (errno));
4553 haspboext = Bool_val (Field (params_v, 9));
4555 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4556 fz_register_document_handlers (state.ctx);
4558 #ifdef USE_FONTCONFIG
4559 if (Bool_val (Field (params_v, 10))) {
4560 fz_install_load_system_font_funcs (
4561 state.ctx, fc_load_system_font_func, NULL
4564 #endif
4566 state.trimmargins = Bool_val (Field (trim_v, 0));
4567 fuzz_v = Field (trim_v, 1);
4568 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4569 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4570 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4571 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4573 set_tex_params (colorspace);
4575 if (*fontpath) {
4576 #ifndef USE_FONTCONFIG
4577 state.face = load_font (fontpath);
4578 #else
4579 FcChar8 *path;
4580 FcResult result;
4581 char *buf = fontpath;
4582 FcPattern *pat, *pat1;
4584 fc.inited = 1;
4585 fc.config = FcInitLoadConfigAndFonts ();
4586 if (!fc.config) {
4587 errx (1, "FcInitLoadConfigAndFonts failed");
4590 pat = FcNameParse ((FcChar8 *) buf);
4591 if (!pat) {
4592 errx (1, "FcNameParse failed");
4595 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4596 errx (1, "FcConfigSubstitute failed");
4598 FcDefaultSubstitute (pat);
4600 pat1 = FcFontMatch (fc.config, pat, &result);
4601 if (!pat1) {
4602 errx (1, "FcFontMatch failed");
4605 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4606 errx (1, "FcPatternGetString failed");
4609 state.face = load_font ((char *) path);
4610 FcPatternDestroy (pat);
4611 FcPatternDestroy (pat1);
4612 #endif
4614 else {
4615 unsigned int len;
4616 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4618 state.face = load_builtin_font (base, len);
4620 if (!state.face) _exit (1);
4622 realloctexts (texcount);
4624 if (haspboext) {
4625 setuppbo ();
4628 makestippletex ();
4630 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4631 if (ret) {
4632 errx (1, "pthread_create: %s", strerror (ret));
4635 CAMLreturn (Val_unit);