%F is apparently not without issues
[llpp.git] / link.c
blobb287a11ed3e183fb24415cc61c9584fe9a1da5ab
1 /* lots of code c&p-ed directly from mupdf */
2 #include <errno.h>
3 #include <stdio.h>
4 #include <ctype.h>
5 #include <string.h>
6 #include <stdlib.h>
7 #include <signal.h>
8 #include <wchar.h>
10 #include <unistd.h>
11 #include <pthread.h>
12 #include <sys/time.h>
13 #include <sys/types.h>
14 #include <sys/ioctl.h>
15 #include <sys/utsname.h>
17 #ifdef __CYGWIN__
18 #include <cygwin/socket.h> /* FIONREAD */
19 #else
20 #include <spawn.h>
21 #endif
23 #include <regex.h>
24 #include <stdarg.h>
25 #include <limits.h>
26 #include <inttypes.h>
28 #include <GL/gl.h>
30 #include <caml/fail.h>
31 #include <caml/alloc.h>
32 #include <caml/memory.h>
33 #include <caml/unixsupport.h>
35 #include <mupdf/fitz.h>
36 #include <mupdf/cbz.h>
37 #include <mupdf/pdf.h>
38 #include <mupdf/xps.h>
39 #include <mupdf/img.h>
41 #include <ft2build.h>
42 #include FT_FREETYPE_H
44 #ifdef USE_FONTCONFIG
45 #include <fontconfig/fontconfig.h>
46 #endif
48 #define PIGGYBACK
49 #define SUMATRA_LOOKUP
51 #ifndef __USE_GNU
52 extern char **environ;
53 #endif
55 #define MIN(a,b) ((a) < (b) ? (a) : (b))
56 #define MAX(a,b) ((a) > (b) ? (a) : (b))
58 #if defined __GNUC__
59 #define NORETURN_ATTR __attribute__ ((noreturn))
60 #define UNUSED_ATTR __attribute__ ((unused))
61 #if !defined __clang__
62 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
63 #else
64 #define OPTIMIZE_ATTR(n)
65 #endif
66 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
67 #else
68 #define NORETURN_ATTR
69 #define UNUSED_ATTR
70 #define OPTIMIZE_ATTR(n)
71 #define GCC_FMT_ATTR(a, b)
72 #endif
74 #define FMT_s "zu"
76 #define FMT_ptr PRIxPTR
77 #define SCN_ptr SCNxPTR
78 #define FMT_ptr_cast(p) ((uintptr_t) (p))
79 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
81 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
82 err (int exitcode, const char *fmt, ...)
84 va_list ap;
85 int savederrno;
87 savederrno = errno;
88 va_start (ap, fmt);
89 vfprintf (stderr, fmt, ap);
90 va_end (ap);
91 fprintf (stderr, ": %s\n", strerror (savederrno));
92 fflush (stderr);
93 _exit (exitcode);
96 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
97 errx (int exitcode, const char *fmt, ...)
99 va_list ap;
101 va_start (ap, fmt);
102 vfprintf (stderr, fmt, ap);
103 va_end (ap);
104 fputc ('\n', stderr);
105 fflush (stderr);
106 _exit (exitcode);
109 #ifndef GL_TEXTURE_RECTANGLE_ARB
110 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
111 #endif
113 #ifndef GL_BGRA
114 #define GL_BGRA 0x80E1
115 #endif
117 #ifndef GL_UNSIGNED_INT_8_8_8_8
118 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
119 #endif
121 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
122 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
123 #endif
125 #if 0
126 #define lprintf printf
127 #else
128 #define lprintf(...)
129 #endif
131 #define ARSERT(cond) for (;;) { \
132 if (!(cond)) { \
133 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
135 break; \
138 struct slice {
139 int h;
140 int texindex;
143 struct tile {
144 int w, h;
145 int slicecount;
146 int sliceheight;
147 struct pbo *pbo;
148 fz_pixmap *pixmap;
149 struct slice slices[1];
152 struct pagedim {
153 int pageno;
154 int rotate;
155 int left;
156 int tctmready;
157 fz_irect bounds;
158 fz_rect pagebox;
159 fz_rect mediabox;
160 fz_matrix ctm, zoomctm, lctm, tctm;
163 struct slink {
164 fz_irect bbox;
165 fz_link *link;
168 enum { DNONE, DPDF, DXPS, DCBZ, DIMG };
170 struct page {
171 int tgen;
172 int sgen;
173 int type;
174 int pageno;
175 int pdimno;
176 fz_text_page *text;
177 fz_text_sheet *sheet;
178 union {
179 void *ptr;
180 pdf_page *pdfpage;
181 xps_page *xpspage;
182 cbz_page *cbzpage;
183 image_page *imgpage;
184 } u;
185 fz_display_list *dlist;
186 int slinkcount;
187 struct slink *slinks;
188 struct mark {
189 int i;
190 fz_text_span *span;
191 } fmark, lmark;
192 void (*freepage) (void *);
195 struct {
196 int type;
197 int sliceheight;
198 struct pagedim *pagedims;
199 int pagecount;
200 int pagedimcount;
201 union {
202 pdf_document *pdf;
203 xps_document *xps;
204 cbz_document *cbz;
205 image_document *img;
206 } u;
207 fz_context *ctx;
208 int w, h;
210 int texindex;
211 int texcount;
212 GLuint *texids;
214 GLenum texiform;
215 GLenum texform;
216 GLenum texty;
218 fz_colorspace *colorspace;
220 struct {
221 int w, h;
222 struct slice *slice;
223 } *texowners;
225 int rotate;
226 enum { FitWidth, FitProportional, FitPage } fitmodel;
227 int trimmargins;
228 int needoutline;
229 int gen;
230 int aalevel;
232 int trimanew;
233 fz_irect trimfuzz;
234 fz_pixmap *pig;
236 pthread_t thread;
237 int csock;
238 FT_Face face;
240 void (*closedoc) (void);
241 void (*freepage) (void *);
243 char *trimcachepath;
244 int cxack;
246 GLuint stid;
248 int pbo_usable;
249 void (*glBindBufferARB) (GLenum, GLuint);
250 GLboolean (*glUnmapBufferARB) (GLenum);
251 void *(*glMapBufferARB) (GLenum, GLenum);
252 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
253 void (*glGenBuffersARB) (GLsizei, GLuint *);
254 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
256 GLfloat texcoords[8];
257 GLfloat vertices[16];
259 #ifdef SUMATRA_LOOKUP
260 struct {
261 int count;
262 pdf_obj **objs;
263 pdf_document *pdf;
264 } pdflut;
265 #endif
266 } state;
268 struct pbo {
269 GLuint id;
270 void *ptr;
271 size_t size;
274 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
276 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
279 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
281 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
284 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
286 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
287 m.a, m.b, m.c, m.d, m.e, m.f);
290 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
292 static void lock (const char *cap)
294 int ret = pthread_mutex_lock (&mutex);
295 if (ret) {
296 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
300 static void unlock (const char *cap)
302 int ret = pthread_mutex_unlock (&mutex);
303 if (ret) {
304 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
308 static int trylock (const char *cap)
310 int ret = pthread_mutex_trylock (&mutex);
311 if (ret && ret != EBUSY) {
312 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
314 return ret == EBUSY;
317 static void *parse_pointer (const char *cap, const char *s)
319 int ret;
320 void *ptr;
322 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
323 if (ret != 1) {
324 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
326 return ptr;
329 static double now (void)
331 struct timeval tv;
333 if (gettimeofday (&tv, NULL)) {
334 err (1, "gettimeofday");
336 return tv.tv_sec + tv.tv_usec*1e-6;
339 static int hasdata (void)
341 int ret, avail;
342 ret = ioctl (state.csock, FIONREAD, &avail);
343 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
344 return avail > 0;
347 CAMLprim value ml_hasdata (value fd_v)
349 CAMLparam1 (fd_v);
350 int ret, avail;
352 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
353 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
354 CAMLreturn (Val_bool (avail > 0));
357 static void readdata (void *p, int size)
359 ssize_t n;
361 again:
362 n = read (state.csock, p, size);
363 if (n < 0) {
364 if (errno == EINTR) goto again;
365 err (1, "read (req %d, ret %zd)", size, n);
367 if (n - size) {
368 if (!n) errx (1, "EOF while reading");
369 errx (1, "read (req %d, ret %zd)", size, n);
373 static void writedata (char *p, int size)
375 ssize_t n;
377 p[0] = (size >> 24) & 0xff;
378 p[1] = (size >> 16) & 0xff;
379 p[2] = (size >> 8) & 0xff;
380 p[3] = (size >> 0) & 0xff;
382 n = write (state.csock, p, size + 4);
383 if (n - size - 4) {
384 if (!n) errx (1, "EOF while writing data");
385 err (1, "write (req %d, ret %zd)", size + 4, n);
389 static int readlen (void)
391 unsigned char p[4];
393 readdata (p, 4);
394 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
397 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
399 int size = 200, len;
400 va_list ap;
401 char *buf;
403 buf = malloc (size);
404 for (;;) {
405 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
407 va_start (ap, fmt);
408 len = vsnprintf (buf + 4, size - 4, fmt, ap);
409 va_end (ap);
411 if (len > -1) {
412 if (len < size - 4) {
413 writedata (buf, len);
414 break;
416 else size = len + 5;
418 else {
419 err (1, "vsnprintf for `%s' failed", fmt);
421 buf = realloc (buf, size);
423 free (buf);
426 static void closepdf (void)
428 #ifdef SUMATRA_LOOKUP
429 if (state.pdflut.objs) {
430 int i;
432 for (i = 0; i < state.pdflut.count; ++i) {
433 pdf_drop_obj (state.pdflut.objs[i]);
435 free (state.pdflut.objs);
436 state.pdflut.objs = NULL;
438 #endif
440 if (state.u.pdf) {
441 pdf_close_document (state.u.pdf);
442 state.u.pdf = NULL;
446 static void closexps (void)
448 if (state.u.xps) {
449 xps_close_document (state.u.xps);
450 state.u.xps = NULL;
454 static void closecbz (void)
456 if (state.u.cbz) {
457 cbz_close_document (state.u.cbz);
458 state.u.cbz = NULL;
462 static void closeimg (void)
464 if (state.u.img) {
465 image_close_document (state.u.img);
466 state.u.img = NULL;
470 static void freepdfpage (void *ptr)
472 pdf_free_page (state.u.pdf, ptr);
475 static void freeemptyxxxpage (void *ptr)
477 (void) ptr;
480 static void freexpspage (void *ptr)
482 xps_free_page (state.u.xps, ptr);
485 static void freecbzpage (void *ptr)
487 cbz_free_page (state.u.cbz, ptr);
490 static void freeimgpage (void *ptr)
492 image_free_page (state.u.img, ptr);
495 static void openxref (char *filename, char *password)
497 int i, len;
499 for (i = 0; i < state.texcount; ++i) {
500 state.texowners[i].w = -1;
501 state.texowners[i].slice = NULL;
504 if (state.closedoc) state.closedoc ();
506 len = strlen (filename);
508 state.type = DPDF;
510 size_t j;
511 struct {
512 char *ext;
513 int type;
514 } tbl[] = {
515 { "pdf", DPDF },
516 { "xps", DXPS },
517 { "zip", DCBZ },
518 { "cbz", DCBZ },
519 { "jpg", DIMG },
520 { "jpeg", DIMG },
521 { "png", DIMG }
524 for (j = 0; j < sizeof (tbl) / sizeof (*tbl); ++j) {
525 const char *ext = tbl[j].ext;
526 int len2 = strlen (ext);
528 if (len2 < len && !strcasecmp (ext, filename + len - len2)) {
529 state.type = tbl[j].type;
530 break;
535 if (state.pagedims) {
536 free (state.pagedims);
537 state.pagedims = NULL;
539 state.pagedimcount = 0;
541 fz_set_aa_level (state.ctx, state.aalevel);
542 switch (state.type) {
543 case DPDF:
544 state.u.pdf = pdf_open_document (state.ctx, filename);
545 if (pdf_needs_password (state.u.pdf)) {
546 int okay = pdf_authenticate_password (state.u.pdf, password);
547 if (!okay) {
548 errx (1, "invalid password");
551 state.pagecount = pdf_count_pages (state.u.pdf);
552 state.closedoc = closepdf;
553 state.freepage = freepdfpage;
554 break;
556 case DXPS:
557 state.u.xps = xps_open_document (state.ctx, filename);
558 state.pagecount = xps_count_pages (state.u.xps);
559 state.closedoc = closexps;
560 state.freepage = freexpspage;
561 break;
563 case DCBZ:
564 state.u.cbz = cbz_open_document (state.ctx, filename);
565 state.pagecount = cbz_count_pages (state.u.cbz);
566 state.closedoc = closecbz;
567 state.freepage = freecbzpage;
568 break;
570 case DIMG:
571 state.u.img = image_open_document (state.ctx, filename);
572 state.pagecount = 1;
573 state.closedoc = closeimg;
574 state.freepage = freeimgpage;
575 break;
579 static void pdfinfo (void)
581 if (state.type == DPDF) {
582 pdf_obj *infoobj;
584 printd ("info PDF version\t%d.%d",
585 state.u.pdf->version / 10, state.u.pdf->version % 10);
587 infoobj = pdf_dict_gets (pdf_trailer (state.u.pdf), "Info");
588 if (infoobj) {
589 unsigned int i;
590 char *s;
591 char *items[] = { "Title", "Author", "Creator",
592 "Producer", "CreationDate" };
594 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
595 pdf_obj *obj = pdf_dict_gets (infoobj, items[i]);
596 s = pdf_to_utf8 (state.u.pdf, obj);
597 if (*s) {
598 if (i == 0) {
599 printd ("title %s", s);
601 printd ("info %s\t%s", items[i], s);
603 fz_free (state.ctx, s);
606 printd ("infoend");
610 static void unlinktile (struct tile *tile)
612 int i;
614 for (i = 0; i < tile->slicecount; ++i) {
615 struct slice *s = &tile->slices[i];
617 if (s->texindex != -1) {
618 if (state.texowners[s->texindex].slice == s) {
619 state.texowners[s->texindex].slice = NULL;
625 static void freepage (struct page *page)
627 if (page->text) {
628 fz_free_text_page (state.ctx, page->text);
630 if (page->sheet) {
631 fz_free_text_sheet (state.ctx, page->sheet);
633 if (page->slinks) {
634 free (page->slinks);
636 fz_drop_display_list (state.ctx, page->dlist);
637 page->freepage (page->u.ptr);
638 free (page);
641 static void freetile (struct tile *tile)
643 unlinktile (tile);
644 if (!tile->pbo) {
645 #ifndef PIGGYBACK
646 fz_drop_pixmap (state.ctx, tile->pixmap);
647 #else
648 if (state.pig) {
649 fz_drop_pixmap (state.ctx, state.pig);
651 state.pig = tile->pixmap;
652 #endif
654 else {
655 free (tile->pbo);
656 fz_drop_pixmap (state.ctx, tile->pixmap);
658 free (tile);
661 #ifdef __ALTIVEC__
662 #include <stdint.h>
663 #include <altivec.h>
665 static int cacheline32bytes;
667 static void __attribute__ ((constructor)) clcheck (void)
669 char **envp = environ;
670 unsigned long *auxv;
672 while (*envp++);
674 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
675 if (*auxv == 19) {
676 cacheline32bytes = auxv[1] == 32;
677 return;
682 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
684 size_t size = pixmap->w * pixmap->h * pixmap->n;
685 if (cacheline32bytes && size > 32) {
686 intptr_t a1, a2, diff;
687 size_t sizea, i;
688 vector unsigned char v = vec_splat_u8 (-1);
689 vector unsigned char *p;
691 a1 = a2 = (intptr_t) pixmap->samples;
692 a2 = (a1 + 31) & ~31;
693 diff = a2 - a1;
694 sizea = size - diff;
695 p = (void *) a2;
697 while (a1 != a2) *(char *) a1++ = 0xff;
698 for (i = 0; i < (sizea & ~31); i += 32) {
699 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
700 vec_st (v, i, p);
701 vec_st (v, i + 16, p);
703 while (i < sizea) *((char *) a1 + i++) = 0xff;
705 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
707 #else
708 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
709 #endif
711 static void trimctm (pdf_page *page, int pindex)
713 fz_matrix ctm;
714 struct pagedim *pdim = &state.pagedims[pindex];
716 if (!pdim->tctmready) {
717 if (state.trimmargins) {
718 fz_rect realbox;
719 fz_matrix rm, sm, tm, im, ctm1;
721 fz_rotate (&rm, -pdim->rotate);
722 fz_scale (&sm, 1, -1);
723 fz_concat (&ctm, &rm, &sm);
724 realbox = pdim->mediabox;
725 fz_transform_rect (&realbox, &ctm);
726 fz_translate (&tm, -realbox.x0, -realbox.y0);
727 fz_concat (&ctm1, &ctm, &tm);
728 fz_invert_matrix (&im, &page->ctm);
729 fz_concat (&ctm, &im, &ctm1);
731 else {
732 ctm = fz_identity;
734 pdim->tctm = ctm;
735 pdim->tctmready = 1;
739 static fz_matrix pagectm (struct page *page)
741 fz_matrix ctm, tm;
743 if (page->type == DPDF) {
744 trimctm (page->u.pdfpage, page->pdimno);
745 fz_concat (&ctm,
746 &state.pagedims[page->pdimno].tctm,
747 &state.pagedims[page->pdimno].ctm);
749 else {
750 struct pagedim *pdim = &state.pagedims[page->pdimno];
752 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
753 fz_concat (&ctm, &tm, &state.pagedims[page->pdimno].ctm);
755 return ctm;
758 static void *loadpage (int pageno, int pindex)
760 fz_device *dev;
761 struct page *page;
763 page = calloc (sizeof (struct page), 1);
764 if (!page) {
765 err (1, "calloc page %d", pageno);
768 page->dlist = fz_new_display_list (state.ctx);
769 dev = fz_new_list_device (state.ctx, page->dlist);
770 fz_try (state.ctx) {
771 switch (state.type) {
772 case DPDF:
773 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
774 pdf_run_page (state.u.pdf, page->u.pdfpage, dev,
775 &fz_identity, NULL);
776 page->freepage = freepdfpage;
777 break;
779 case DXPS:
780 page->u.xpspage = xps_load_page (state.u.xps, pageno);
781 xps_run_page (state.u.xps, page->u.xpspage, dev,
782 &fz_identity, NULL);
783 page->freepage = freexpspage;
784 break;
786 case DCBZ:
787 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
788 cbz_run_page (state.u.cbz, page->u.cbzpage, dev,
789 &fz_identity, NULL);
790 page->freepage = freecbzpage;
791 break;
793 case DIMG:
794 page->u.imgpage = image_load_page (state.u.img, pageno);
795 image_run_page (state.u.img, page->u.imgpage, dev,
796 &fz_identity, NULL);
797 page->freepage = freeimgpage;
798 break;
801 fz_catch (state.ctx) {
802 page->u.ptr = NULL;
803 page->freepage = freeemptyxxxpage;
805 fz_free_device (dev);
807 page->pdimno = pindex;
808 page->pageno = pageno;
809 page->sgen = state.gen;
810 page->tgen = state.gen;
811 page->type = state.type;
813 return page;
816 static struct tile *alloctile (int h)
818 int i;
819 int slicecount;
820 size_t tilesize;
821 struct tile *tile;
823 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
824 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
825 tile = calloc (tilesize, 1);
826 if (!tile) {
827 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
829 for (i = 0; i < slicecount; ++i) {
830 int sh = MIN (h, state.sliceheight);
831 tile->slices[i].h = sh;
832 tile->slices[i].texindex = -1;
833 h -= sh;
835 tile->slicecount = slicecount;
836 tile->sliceheight = state.sliceheight;
837 return tile;
840 #ifdef OBSCURED_OPT
841 struct obs {
842 int cured;
843 fz_irect b;
846 static void obs_fill_image (fz_device *dev, fz_image UNUSED_ATTR *image,
847 const fz_matrix *ctm, float alpha)
849 struct obs *obs = dev->user;
851 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
852 fz_irect b;
853 fz_rect rect = fz_unit_rect;
855 fz_transform_rect (&rect, ctm);
856 fz_round_rect (&b, &rect);
857 fz_intersect_irect (&b, &obs->b);
858 obs->cured = b.x0 == obs->b.x0
859 && b.x1 == obs->b.x1
860 && b.y0 == obs->b.y0
861 && b.y1 == obs->b.y1;
865 static int obscured (struct page *page, fz_irect bbox)
867 fz_rect rect;
868 fz_matrix ctm;
869 fz_device dev;
870 struct obs obs;
872 memset (&dev, 0, sizeof (dev));
873 memset (&obs, 0, sizeof (obs));
874 dev.hints = 0;
875 dev.flags = 0;
876 dev.user = &obs;
877 dev.ctx = state.ctx;
878 dev.fill_image = obs_fill_image;
879 obs.b = bbox;
880 fz_rect_from_irect (&rect, &bbox);
881 ctm = pagectm (page);
882 fz_run_display_list (page->dlist, &dev, &ctm, &rect, NULL);
883 return obs.cured;
885 #define OBSCURED obscured
886 #else
887 #define OBSCURED(a, b) 0
888 #endif
890 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
891 struct pbo *pbo)
893 fz_rect rect;
894 fz_irect bbox;
895 fz_matrix ctm;
896 fz_device *dev;
897 struct tile *tile;
898 struct pagedim *pdim;
900 tile = alloctile (h);
901 pdim = &state.pagedims[page->pdimno];
903 bbox = pdim->bounds;
904 bbox.x0 += x;
905 bbox.y0 += y;
906 bbox.x1 = bbox.x0 + w;
907 bbox.y1 = bbox.y0 + h;
909 if (state.pig) {
910 if (state.pig->w == w
911 && state.pig->h == h
912 && state.pig->colorspace == state.colorspace) {
913 tile->pixmap = state.pig;
914 tile->pixmap->x = bbox.x0;
915 tile->pixmap->y = bbox.y0;
917 else {
918 fz_drop_pixmap (state.ctx, state.pig);
920 state.pig = NULL;
922 if (!tile->pixmap) {
923 if (pbo) {
924 tile->pixmap =
925 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
926 &bbox, pbo->ptr);
927 tile->pbo = pbo;
929 else {
930 tile->pixmap =
931 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
935 tile->w = w;
936 tile->h = h;
937 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
938 clearpixmap (tile->pixmap);
940 dev = fz_new_draw_device (state.ctx, tile->pixmap);
941 ctm = pagectm (page);
942 fz_rect_from_irect (&rect, &bbox);
943 fz_run_display_list (page->dlist, dev, &ctm, &rect, NULL);
944 fz_free_device (dev);
946 return tile;
949 #ifdef SUMATRA_LOOKUP
950 /* Following two functions are taken (almost) verbatim from SumatraPDF
951 PdfEngine.cpp
953 static void
954 pdf_load_page_objs_rec(pdf_document *doc, pdf_obj *node, int *page_no, pdf_obj **page_objs)
956 fz_context *ctx = doc->ctx;
958 if (pdf_mark_obj(node))
959 fz_throw(ctx, FZ_ERROR_GENERIC, "cycle in page tree");
961 fz_try(ctx) {
962 pdf_obj *kids = pdf_dict_gets(node, "Kids");
963 int len = pdf_array_len(kids), i;
964 for (i = 0; i < len; i++) {
965 pdf_obj *kid = pdf_array_get(kids, i);
966 char *type = pdf_to_name(pdf_dict_gets(kid, "Type"));
967 if (!strcmp(type, "Page")) {
968 if (*page_no > pdf_count_pages(doc))
969 fz_throw(ctx, FZ_ERROR_GENERIC, "found more /Page objects than anticipated");
970 page_objs[*page_no - 1] = pdf_keep_obj(kid);
971 (*page_no)++;
973 else if (!strcmp(type, "Pages")) {
974 int count = pdf_to_int(pdf_dict_gets(kid, "Count"));
975 if (count > 0)
976 pdf_load_page_objs_rec(doc, kid, page_no, page_objs);
978 else {
979 fz_warn(ctx, "non-page object in page tree (%s)", type);
983 fz_always(ctx) {
984 pdf_unmark_obj(node);
986 fz_catch(ctx) {
987 fz_rethrow(ctx);
991 static void
992 pdf_load_page_objs(pdf_document *doc, pdf_obj **page_objs)
994 pdf_obj *pages = pdf_dict_getp(pdf_trailer(doc), "Root/Pages");
995 int page_no = 1;
996 pdf_load_page_objs_rec(doc, pages, &page_no, page_objs);
998 #endif
1000 static void initpdims (void)
1002 double start, end;
1003 FILE *trimf = NULL;
1004 fz_rect rootmediabox;
1005 int pageno, trim, show;
1006 int trimw = 0, cxcount;
1008 start = now ();
1010 if (state.trimmargins && state.trimcachepath) {
1011 trimf = fopen (state.trimcachepath, "rb");
1012 if (!trimf) {
1013 trimf = fopen (state.trimcachepath, "wb");
1014 trimw = 1;
1018 if (state.trimmargins || state.type == DPDF || !state.cxack)
1019 cxcount = state.pagecount;
1020 else
1021 cxcount = MIN (state.pagecount, 1);
1023 if (state.type == DPDF) {
1024 pdf_obj *obj;
1025 obj = pdf_dict_getp (pdf_trailer (state.u.pdf),
1026 "Root/Pages/MediaBox");
1027 pdf_to_rect (state.ctx, obj, &rootmediabox);
1030 #ifdef SUMATRA_LOOKUP
1031 if (state.type == DPDF
1032 && (!state.pdflut.objs || state.pdflut.pdf != state.u.pdf)) {
1033 state.pdflut.objs = malloc (sizeof (*state.pdflut.objs) * cxcount);
1034 if (!state.pdflut.objs) {
1035 err (1, "malloc pageobjs %zu %d %zu failed",
1036 sizeof (*state.pdflut.objs), cxcount,
1037 sizeof (*state.pdflut.objs) * cxcount);
1039 state.pdflut.count = cxcount;
1040 pdf_load_page_objs (state.u.pdf, state.pdflut.objs);
1041 state.pdflut.pdf = state.u.pdf;
1043 #endif
1045 for (pageno = 0; pageno < cxcount; ++pageno) {
1046 int rotate = 0;
1047 struct pagedim *p;
1048 fz_rect mediabox;
1050 switch (state.type) {
1051 case DPDF: {
1052 pdf_document *pdf = state.u.pdf;
1053 pdf_obj *pageref, *pageobj;
1055 #ifdef SUMATRA_LOOKUP
1056 pageref = state.pdflut.objs[pageno];
1057 #else
1058 pageref = pdf_lookup_page_obj (pdf, pageno);
1059 #endif
1060 pageobj = pdf_resolve_indirect (pageref);
1062 if (state.trimmargins) {
1063 pdf_obj *obj;
1064 pdf_page *page;
1066 fz_try (state.ctx) {
1067 page = pdf_load_page (pdf, pageno);
1068 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
1069 trim = state.trimanew || !obj;
1070 if (trim) {
1071 fz_rect rect;
1072 fz_matrix ctm;
1073 fz_device *dev;
1075 dev = fz_new_bbox_device (state.ctx, &rect);
1076 dev->hints |= FZ_IGNORE_SHADE;
1077 fz_invert_matrix (&ctm, &page->ctm);
1078 pdf_run_page (pdf, page, dev, &fz_identity, NULL);
1079 fz_free_device (dev);
1081 rect.x0 += state.trimfuzz.x0;
1082 rect.x1 += state.trimfuzz.x1;
1083 rect.y0 += state.trimfuzz.y0;
1084 rect.y1 += state.trimfuzz.y1;
1085 fz_transform_rect (&rect, &ctm);
1086 fz_intersect_rect (&rect, &page->mediabox);
1088 if (fz_is_empty_rect (&rect)) {
1089 mediabox = page->mediabox;
1091 else {
1092 mediabox = rect;
1095 obj = pdf_new_array (pdf, 4);
1096 pdf_array_push (obj, pdf_new_real (pdf, mediabox.x0));
1097 pdf_array_push (obj, pdf_new_real (pdf, mediabox.y0));
1098 pdf_array_push (obj, pdf_new_real (pdf, mediabox.x1));
1099 pdf_array_push (obj, pdf_new_real (pdf, mediabox.y1));
1100 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
1102 else {
1103 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
1104 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
1105 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
1106 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
1109 rotate = page->rotate;
1110 pdf_free_page (pdf, page);
1112 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
1113 if (show) {
1114 printd ("progress %f Trimming %d",
1115 (double) (pageno + 1) / state.pagecount,
1116 pageno + 1);
1119 fz_catch (state.ctx) {
1120 fprintf (stderr, "failed to load page %d\n", pageno+1);
1123 else {
1124 int empty = 0;
1125 fz_rect cropbox;
1127 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "MediaBox"),
1128 &mediabox);
1129 if (fz_is_empty_rect (&mediabox)) {
1130 mediabox.x0 = 0;
1131 mediabox.y0 = 0;
1132 mediabox.x1 = 612;
1133 mediabox.y1 = 792;
1134 empty = 1;
1137 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "CropBox"),
1138 &cropbox);
1139 if (!fz_is_empty_rect (&cropbox)) {
1140 if (empty) {
1141 mediabox = cropbox;
1143 else {
1144 fz_intersect_rect (&mediabox, &cropbox);
1147 else {
1148 if (empty) {
1149 if (fz_is_empty_rect (&rootmediabox)) {
1150 fprintf (stderr,
1151 "cannot find page size for page %d\n",
1152 pageno+1);
1154 else {
1155 mediabox = rootmediabox;
1159 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
1161 break;
1164 case DXPS:
1166 xps_page *page;
1168 fz_try (state.ctx) {
1169 page = xps_load_page (state.u.xps, pageno);
1170 xps_bound_page (state.u.xps, page, &mediabox);
1171 rotate = 0;
1172 if (state.trimmargins) {
1173 fz_rect rect;
1174 fz_device *dev;
1176 dev = fz_new_bbox_device (state.ctx, &rect);
1177 dev->hints |= FZ_IGNORE_SHADE;
1178 xps_run_page (state.u.xps, page, dev,
1179 &fz_identity, NULL);
1180 fz_free_device (dev);
1182 rect.x0 += state.trimfuzz.x0;
1183 rect.x1 += state.trimfuzz.x1;
1184 rect.y0 += state.trimfuzz.y0;
1185 rect.y1 += state.trimfuzz.y1;
1186 fz_intersect_rect (&rect, &mediabox);
1188 if (!fz_is_empty_rect (&rect)) {
1189 mediabox = rect;
1192 xps_free_page (state.u.xps, page);
1193 if (!state.cxack) {
1194 printd ("progress %f loading %d",
1195 (double) (pageno + 1) / state.pagecount,
1196 pageno + 1);
1199 fz_catch (state.ctx) {
1202 break;
1204 case DCBZ:
1206 rotate = 0;
1207 mediabox.x0 = 0;
1208 mediabox.y0 = 0;
1209 mediabox.x1 = 900;
1210 mediabox.y1 = 900;
1211 if (state.trimmargins && trimw) {
1212 cbz_page *page;
1214 fz_try (state.ctx) {
1215 page = cbz_load_page (state.u.cbz, pageno);
1216 cbz_bound_page (state.u.cbz, page, &mediabox);
1217 cbz_free_page (state.u.cbz, page);
1218 printd ("progress %f Trimming %d",
1219 (double) (pageno + 1) / state.pagecount,
1220 pageno + 1);
1222 fz_catch (state.ctx) {
1223 fprintf (stderr, "failed to load page %d\n", pageno+1);
1225 if (trimf) {
1226 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1227 if (n - 1) {
1228 err (1, "fwrite trim mediabox");
1232 else {
1233 if (trimf) {
1234 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1235 if (n - 1) {
1236 err (1, "fread trim mediabox");
1239 else {
1240 if (state.cxack) {
1241 cbz_page *page;
1242 fz_try (state.ctx) {
1243 page = cbz_load_page (state.u.cbz, pageno);
1244 cbz_bound_page (state.u.cbz, page, &mediabox);
1245 cbz_free_page (state.u.cbz, page);
1247 fz_catch (state.ctx) {
1248 fprintf (stderr, "failed to load cbz page\n");
1254 break;
1256 case DIMG:
1258 image_page *page;
1260 rotate = 0;
1261 mediabox.x0 = 0;
1262 mediabox.y0 = 0;
1263 mediabox.x1 = 900;
1264 mediabox.y1 = 900;
1266 fz_try (state.ctx) {
1267 page = image_load_page (state.u.img, pageno);
1268 image_bound_page (state.u.img, page, &mediabox);
1269 image_free_page (state.u.img, page);
1271 fz_catch (state.ctx) {
1272 fprintf (stderr, "failed to load page %d\n", pageno+1);
1275 break;
1277 default:
1278 ARSERT (0 && state.type);
1281 if (state.pagedimcount == 0
1282 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1283 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1284 size_t size;
1286 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1287 state.pagedims = realloc (state.pagedims, size);
1288 if (!state.pagedims) {
1289 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1290 size, state.pagedimcount + 1);
1293 p = &state.pagedims[state.pagedimcount++];
1294 p->rotate = rotate;
1295 p->mediabox = mediabox;
1296 p->pageno = pageno;
1299 end = now ();
1300 if (state.trimmargins) {
1301 printd ("progress 1 Trimmed %d pages in %f seconds",
1302 state.pagecount, end - start);
1304 else {
1305 printd ("vmsg Processed %d pages in %f seconds",
1306 state.pagecount, end - start);
1308 state.trimanew = 0;
1309 if (trimf) {
1310 if (fclose (trimf)) {
1311 err (1, "fclose");
1316 static void layout (void)
1318 int pindex;
1319 fz_rect box;
1320 fz_matrix ctm, rm;
1321 struct pagedim *p = p;
1322 double zw, w, maxw = 0.0, zoom = zoom;
1324 if (state.pagedimcount == 0) return;
1326 switch (state.fitmodel) {
1327 case FitProportional:
1328 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1329 double x0, x1;
1331 p = &state.pagedims[pindex];
1332 fz_rotate (&rm, p->rotate + state.rotate);
1333 box = p->mediabox;
1334 fz_transform_rect (&box, &rm);
1336 x0 = MIN (box.x0, box.x1);
1337 x1 = MAX (box.x0, box.x1);
1339 w = x1 - x0;
1340 maxw = MAX (w, maxw);
1341 zoom = state.w / maxw;
1343 break;
1345 case FitPage:
1346 maxw = state.w;
1347 break;
1349 case FitWidth:
1350 break;
1352 default:
1353 ARSERT (0 && state.fitmodel);
1356 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1357 fz_rect rect;
1358 fz_matrix tm, sm;
1360 p = &state.pagedims[pindex];
1361 fz_rotate (&ctm, state.rotate);
1362 fz_rotate (&rm, p->rotate + state.rotate);
1363 box = p->mediabox;
1364 fz_transform_rect (&box, &rm);
1365 w = box.x1 - box.x0;
1366 switch (state.fitmodel) {
1367 case FitProportional:
1368 p->left = ((maxw - w) * zoom) / 2.0;
1369 break;
1370 case FitPage:
1372 double zh, h;
1373 zw = maxw / w;
1374 h = box.y1 - box.y0;
1375 zh = state.h / h;
1376 zoom = MIN (zw, zh);
1377 p->left = (maxw - (w * zoom)) / 2.0;
1379 break;
1380 case FitWidth:
1381 p->left = 0;
1382 zoom = state.w / w;
1383 break;
1386 fz_scale (&p->zoomctm, zoom, zoom);
1387 fz_concat (&ctm, &p->zoomctm, &ctm);
1389 fz_rotate (&rm, p->rotate);
1390 p->pagebox = p->mediabox;
1391 fz_transform_rect (&p->pagebox, &rm);
1392 p->pagebox.x1 -= p->pagebox.x0;
1393 p->pagebox.y1 -= p->pagebox.y0;
1394 p->pagebox.x0 = 0;
1395 p->pagebox.y0 = 0;
1396 rect = p->pagebox;
1397 fz_transform_rect (&rect, &ctm);
1398 fz_round_rect (&p->bounds, &rect);
1399 p->ctm = ctm;
1401 fz_translate (&tm, 0, -p->mediabox.y1);
1402 fz_scale (&sm, zoom, -zoom);
1403 fz_concat (&ctm, &tm, &sm);
1404 fz_concat (&p->lctm, &ctm, &rm);
1406 p->tctmready = 0;
1409 do {
1410 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1411 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1412 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1413 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1414 int boundw = x1 - x0;
1415 int boundh = y1 - y0;
1417 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1418 } while (p-- != state.pagedims);
1421 static
1422 struct anchor { int n; int x; int y; int w; int h; }
1423 desttoanchor (fz_link_dest *dest)
1425 int i;
1426 struct anchor a;
1427 struct pagedim *pdim = state.pagedims;
1429 a.n = -1;
1430 a.x = 0;
1431 a.y = 0;
1432 for (i = 0; i < state.pagedimcount; ++i) {
1433 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1434 break;
1435 pdim = &state.pagedims[i];
1437 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1438 fz_point p;
1439 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1440 p.x = dest->ld.gotor.lt.x;
1441 else
1442 p.x = 0.0;
1443 p.y = dest->ld.gotor.lt.y;
1444 fz_transform_point (&p, &pdim->lctm);
1445 a.x = p.x;
1446 a.y = p.y;
1448 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1449 double x0, x1, y0, y1;
1451 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1452 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1453 a.w = x1 - x0;
1454 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1455 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1456 a.h = y1 - y0;
1457 a.n = dest->ld.gotor.page;
1459 return a;
1462 static void recurse_outline (fz_outline *outline, int level)
1464 while (outline) {
1465 switch (outline->dest.kind) {
1466 case FZ_LINK_GOTO:
1468 struct anchor a = desttoanchor (&outline->dest);
1470 if (a.n >= 0) {
1471 printd ("o %d %d %d %d %s",
1472 level, a.n, a.y, a.h, outline->title);
1475 break;
1477 case FZ_LINK_URI:
1478 printd ("ou %d %" FMT_s " %s %s", level,
1479 strlen (outline->title), outline->title,
1480 outline->dest.ld.uri.uri);
1481 break;
1483 case FZ_LINK_NONE:
1484 printd ("on %d %s", level, outline->title);
1485 break;
1487 default:
1488 printd ("emsg Unhandled outline kind %d for %s\n",
1489 outline->dest.kind, outline->title);
1490 break;
1492 if (outline->down) {
1493 recurse_outline (outline->down, level + 1);
1495 outline = outline->next;
1499 static void process_outline (void)
1501 fz_outline *outline;
1503 if (!state.needoutline) return;
1505 state.needoutline = 0;
1506 switch (state.type) {
1507 case DPDF:
1508 outline = pdf_load_outline (state.u.pdf);
1509 break;
1510 case DXPS:
1511 outline = xps_load_outline (state.u.xps);
1512 break;
1513 default:
1514 outline = NULL;
1515 break;
1517 if (outline) {
1518 recurse_outline (outline, 0);
1519 fz_free_outline (state.ctx, outline);
1523 static char *strofspan (fz_text_span *span)
1525 char *p;
1526 char utf8[10];
1527 fz_text_char *ch;
1528 size_t size = 0, cap = 80;
1530 p = malloc (cap + 1);
1531 if (!p) return NULL;
1533 for (ch = span->text; ch < span->text + span->len; ++ch) {
1534 int n = fz_runetochar (utf8, ch->c);
1535 if (size + n > cap) {
1536 cap *= 2;
1537 p = realloc (p, cap + 1);
1538 if (!p) return NULL;
1541 memcpy (p + size, utf8, n);
1542 size += n;
1544 p[size] = 0;
1545 return p;
1548 static int matchspan (regex_t *re, fz_text_page UNUSED_ATTR *page,
1549 fz_text_span *span, fz_matrix UNUSED_ATTR ctm,
1550 int stop, int pageno, double start)
1552 int ret;
1553 char *p;
1554 regmatch_t rm;
1555 int a, b, c;
1556 fz_rect sb, eb;
1557 fz_point p1, p2, p3, p4;
1559 p = strofspan (span);
1560 if (!p) return -1;
1562 ret = regexec (re, p, 1, &rm, 0);
1563 if (ret) {
1564 free (p);
1565 if (ret != REG_NOMATCH) {
1566 size_t size;
1567 char errbuf[80];
1568 size = regerror (ret, re, errbuf, sizeof (errbuf));
1569 printd ("msg regexec error `%.*s'",
1570 (int) size, errbuf);
1571 return -1;
1573 return 0;
1575 else {
1576 int l = span->len;
1578 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1579 c += fz_runelen (span->text[a].c);
1581 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1582 c += fz_runelen (span->text[b].c);
1585 if (fz_runelen (span->text[b].c) > 1) {
1586 b = MAX (0, b-1);
1589 fz_text_char_bbox (&sb, span, a);
1590 fz_text_char_bbox (&eb, span, b);
1592 p1.x = sb.x0;
1593 p1.y = sb.y0;
1594 p2.x = eb.x1;
1595 p2.y = sb.y0;
1596 p3.x = eb.x1;
1597 p3.y = eb.y1;
1598 p4.x = sb.x0;
1599 p4.y = eb.y1;
1601 if (!stop) {
1602 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1603 pageno, 1,
1604 p1.x, p1.y,
1605 p2.x, p2.y,
1606 p3.x, p3.y,
1607 p4.x, p4.y);
1609 printd ("progress 1 found at %d `%.*s' in %f sec",
1610 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1611 now () - start);
1613 else {
1614 printd ("match %d %d %f %f %f %f %f %f %f %f",
1615 pageno, 2,
1616 p1.x, p1.y,
1617 p2.x, p2.y,
1618 p3.x, p3.y,
1619 p4.x, p4.y);
1621 free (p);
1622 return 1;
1626 static int compareblocks (const void *l, const void *r)
1628 fz_text_block const *ls = l;
1629 fz_text_block const* rs = r;
1630 return ls->bbox.y0 - rs->bbox.y0;
1633 /* wishful thinking function */
1634 static void search (regex_t *re, int pageno, int y, int forward)
1636 int i, j;
1637 fz_matrix ctm;
1638 fz_device *tdev;
1639 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1640 fz_text_page *text;
1641 fz_text_sheet *sheet;
1642 struct pagedim *pdim, *pdimprev;
1643 int stop = 0, niters = 0;
1644 double start, end;
1646 if (!(state.type == DPDF || state.type == DXPS))
1647 return;
1649 start = now ();
1650 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1651 if (niters++ == 5) {
1652 niters = 0;
1653 if (hasdata ()) {
1654 printd ("progress 1 attention requested aborting search at %d",
1655 pageno);
1656 stop = 1;
1658 else {
1659 printd ("progress %f searching in page %d",
1660 (double) (pageno + 1) / state.pagecount,
1661 pageno);
1664 pdimprev = NULL;
1665 for (i = 0; i < state.pagedimcount; ++i) {
1666 pdim = &state.pagedims[i];
1667 if (pdim->pageno == pageno) {
1668 goto found;
1670 if (pdim->pageno > pageno) {
1671 pdim = pdimprev;
1672 goto found;
1674 pdimprev = pdim;
1676 pdim = pdimprev;
1677 found:
1679 sheet = fz_new_text_sheet (state.ctx);
1680 text = fz_new_text_page (state.ctx);
1681 tdev = fz_new_text_device (state.ctx, sheet, text);
1683 switch (state.type) {
1684 case DPDF:
1685 u.ptr = NULL;
1686 fz_try (state.ctx) {
1687 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1688 trimctm (u.pdfpage, pdim - state.pagedims);
1689 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1690 fz_begin_page (tdev, &fz_infinite_rect, &ctm);
1691 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1692 fz_end_page (tdev);
1694 fz_catch (state.ctx) {
1695 fz_free_device (tdev);
1696 u.ptr = NULL;
1697 goto nextiter;
1699 break;
1701 case DXPS:
1702 u.xpspage = xps_load_page (state.u.xps, pageno);
1703 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1704 break;
1706 default:
1707 ARSERT (0 && state.type);
1710 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1711 fz_free_device (tdev);
1713 for (j = 0; j < text->len; ++j) {
1714 int k;
1715 fz_page_block *pb;
1716 fz_text_block *block;
1718 pb = &text->blocks[forward ? j : text->len - 1 - j];
1719 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1720 block = pb->u.text;
1722 for (k = 0; k < block->len; ++k) {
1723 fz_text_line *line;
1724 fz_text_span *span;
1726 if (forward) {
1727 line = &block->lines[k];
1728 if (line->bbox.y0 < y + 1) continue;
1730 else {
1731 line = &block->lines[block->len - 1 - k];
1732 if (line->bbox.y0 > y - 1) continue;
1735 for (span = line->first_span; span; span = span->next) {
1736 switch (matchspan (re, text, span, ctm,
1737 stop, pageno, start)) {
1738 case 0: break;
1739 case 1: stop = 1; break;
1740 case -1: stop = 1; goto endloop;
1745 nextiter:
1746 if (forward) {
1747 pageno += 1;
1748 y = 0;
1750 else {
1751 pageno -= 1;
1752 y = INT_MAX;
1754 endloop:
1755 fz_free_text_page (state.ctx, text);
1756 fz_free_text_sheet (state.ctx, sheet);
1757 if (u.ptr) {
1758 state.freepage (u.ptr);
1761 end = now ();
1762 if (!stop) {
1763 printd ("progress 1 no matches %f sec", end - start);
1765 printd ("clearrects");
1768 static void set_tex_params (int colorspace)
1770 union {
1771 unsigned char b;
1772 unsigned int s;
1773 } endianness = {1};
1775 switch (colorspace) {
1776 case 0:
1777 state.texiform = GL_RGBA8;
1778 state.texform = GL_RGBA;
1779 state.texty = GL_UNSIGNED_BYTE;
1780 state.colorspace = fz_device_rgb (state.ctx);
1781 break;
1782 case 1:
1783 state.texiform = GL_RGBA8;
1784 state.texform = GL_BGRA;
1785 state.texty = endianness.s > 1
1786 ? GL_UNSIGNED_INT_8_8_8_8
1787 : GL_UNSIGNED_INT_8_8_8_8_REV;
1788 state.colorspace = fz_device_bgr (state.ctx);
1789 break;
1790 case 2:
1791 state.texiform = GL_LUMINANCE_ALPHA;
1792 state.texform = GL_LUMINANCE_ALPHA;
1793 state.texty = GL_UNSIGNED_BYTE;
1794 state.colorspace = fz_device_gray (state.ctx);
1795 break;
1796 default:
1797 errx (1, "invalid colorspce %d", colorspace);
1801 static void realloctexts (int texcount)
1803 size_t size;
1805 if (texcount == state.texcount) return;
1807 if (texcount < state.texcount) {
1808 glDeleteTextures (state.texcount - texcount,
1809 state.texids + texcount);
1812 size = texcount * sizeof (*state.texids);
1813 state.texids = realloc (state.texids, size);
1814 if (!state.texids) {
1815 err (1, "realloc texids %" FMT_s, size);
1818 size = texcount * sizeof (*state.texowners);
1819 state.texowners = realloc (state.texowners, size);
1820 if (!state.texowners) {
1821 err (1, "realloc texowners %" FMT_s, size);
1823 if (texcount > state.texcount) {
1824 int i;
1826 glGenTextures (texcount - state.texcount,
1827 state.texids + state.texcount);
1828 for (i = state.texcount; i < texcount; ++i) {
1829 state.texowners[i].w = -1;
1830 state.texowners[i].slice = NULL;
1833 state.texcount = texcount;
1834 state.texindex = 0;
1837 static char *mbtoutf8 (char *s)
1839 char *p, *r;
1840 wchar_t *tmp;
1841 size_t i, ret, len;
1843 len = mbstowcs (NULL, s, strlen (s));
1844 if (len == 0) {
1845 return s;
1847 else {
1848 if (len == (size_t) -1) {
1849 return s;
1853 tmp = malloc (len * sizeof (wchar_t));
1854 if (!tmp) {
1855 return s;
1858 ret = mbstowcs (tmp, s, len);
1859 if (ret == (size_t) -1) {
1860 free (tmp);
1861 return s;
1864 len = 0;
1865 for (i = 0; i < ret; ++i) {
1866 len += fz_runelen (tmp[i]);
1869 p = r = malloc (len + 1);
1870 if (!r) {
1871 free (tmp);
1872 return s;
1875 for (i = 0; i < ret; ++i) {
1876 p += fz_runetochar (p, tmp[i]);
1878 *p = 0;
1879 free (tmp);
1880 return r;
1883 CAMLprim value ml_mbtoutf8 (value s_v)
1885 CAMLparam1 (s_v);
1886 CAMLlocal1 (ret_v);
1887 char *s, *r;
1889 s = String_val (s_v);
1890 r = mbtoutf8 (s);
1891 if (r == s) {
1892 ret_v = s_v;
1894 else {
1895 ret_v = caml_copy_string (r);
1896 free (r);
1898 CAMLreturn (ret_v);
1901 static void * mainloop (void UNUSED_ATTR *unused)
1903 char *p = NULL;
1904 int len, ret, oldlen = 0;
1906 for (;;) {
1907 len = readlen ();
1908 if (len == 0) {
1909 errx (1, "readlen returned 0");
1912 if (oldlen < len + 1) {
1913 p = realloc (p, len + 1);
1914 if (!p) {
1915 err (1, "realloc %d failed", len + 1);
1917 oldlen = len + 1;
1919 readdata (p, len);
1920 p[len] = 0;
1922 if (!strncmp ("open", p, 4)) {
1923 int wthack, off, ok = 0;
1924 char *password;
1925 char *filename;
1926 char *utf8filename;
1927 size_t filenamelen;
1929 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1930 if (ret != 2) {
1931 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1934 filename = p + 5 + off;
1935 filenamelen = strlen (filename);
1936 password = filename + filenamelen + 1;
1938 lock ("open");
1939 fz_try (state.ctx) {
1940 openxref (filename, password);
1941 ok = 1;
1943 fz_catch (state.ctx) {
1944 utf8filename = mbtoutf8 (filename);
1945 printd ("msg Could not open %s", utf8filename);
1947 if (ok) {
1948 pdfinfo ();
1949 initpdims ();
1951 unlock ("open");
1953 if (ok) {
1954 if (!wthack) {
1955 utf8filename = mbtoutf8 (filename);
1956 printd ("msg Opened %s (press h/F1 to get help)",
1957 utf8filename);
1958 if (utf8filename != filename) {
1959 free (utf8filename);
1962 state.needoutline = 1;
1965 else if (!strncmp ("cs", p, 2)) {
1966 int i, colorspace;
1968 ret = sscanf (p + 2, " %d", &colorspace);
1969 if (ret != 1) {
1970 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1972 lock ("cs");
1973 set_tex_params (colorspace);
1974 for (i = 0; i < state.texcount; ++i) {
1975 state.texowners[i].w = -1;
1976 state.texowners[i].slice = NULL;
1978 unlock ("cs");
1980 else if (!strncmp ("freepage", p, 8)) {
1981 void *ptr;
1983 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1984 if (ret != 1) {
1985 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1987 freepage (ptr);
1989 else if (!strncmp ("freetile", p, 8)) {
1990 void *ptr;
1992 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1993 if (ret != 1) {
1994 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1996 freetile (ptr);
1998 else if (!strncmp ("search", p, 6)) {
1999 int icase, pageno, y, len2, forward;
2000 char *pattern;
2001 regex_t re;
2003 ret = sscanf (p + 6, " %d %d %d %d,%n",
2004 &icase, &pageno, &y, &forward, &len2);
2005 if (ret != 4) {
2006 errx (1, "malformed search `%s' ret=%d", p, ret);
2009 pattern = p + 6 + len2;
2010 ret = regcomp (&re, pattern,
2011 REG_EXTENDED | (icase ? REG_ICASE : 0));
2012 if (ret) {
2013 char errbuf[80];
2014 size_t size;
2016 size = regerror (ret, &re, errbuf, sizeof (errbuf));
2017 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
2019 else {
2020 search (&re, pageno, y, forward);
2021 regfree (&re);
2024 else if (!strncmp ("geometry", p, 8)) {
2025 int w, h, fitmodel;
2027 printd ("clear");
2028 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
2029 if (ret != 3) {
2030 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
2033 lock ("geometry");
2034 state.h = h;
2035 if (w != state.w) {
2036 int i;
2037 state.w = w;
2038 for (i = 0; i < state.texcount; ++i) {
2039 state.texowners[i].slice = NULL;
2042 state.fitmodel = fitmodel;
2043 layout ();
2044 process_outline ();
2046 state.gen++;
2047 unlock ("geometry");
2048 printd ("continue %d", state.pagecount);
2050 else if (!strncmp ("reqlayout", p, 9)) {
2051 char *nameddest;
2052 int rotate, off, h;
2053 unsigned int fitmodel;
2055 printd ("clear");
2056 ret = sscanf (p + 9, " %d %u %d %n",
2057 &rotate, &fitmodel, &h, &off);
2058 if (ret != 3) {
2059 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
2061 lock ("reqlayout");
2062 if (state.rotate != rotate || state.fitmodel != fitmodel) {
2063 state.gen += 1;
2065 state.rotate = rotate;
2066 state.fitmodel = fitmodel;
2067 state.h = h;
2068 layout ();
2069 process_outline ();
2071 nameddest = p + 9 + off;
2072 if (state.type == DPDF && nameddest && *nameddest) {
2073 struct anchor a;
2074 fz_link_dest dest;
2075 pdf_obj *needle, *obj;
2077 needle = pdf_new_string (state.u.pdf, nameddest,
2078 strlen (nameddest));
2079 obj = pdf_lookup_dest (state.u.pdf, needle);
2080 if (obj) {
2081 dest = pdf_parse_link_dest (state.u.pdf, FZ_LINK_GOTO, obj);
2083 a = desttoanchor (&dest);
2084 if (a.n >= 0) {
2085 printd ("a %d %d %d", a.n, a.x, a.y);
2087 else {
2088 printd ("emsg failed to parse destination `%s'\n",
2089 nameddest);
2092 else {
2093 printd ("emsg destination `%s' not found\n",
2094 nameddest);
2096 pdf_drop_obj (needle);
2099 state.gen++;
2100 unlock ("reqlayout");
2101 printd ("continue %d", state.pagecount);
2103 else if (!strncmp ("page", p, 4)) {
2104 double a, b;
2105 struct page *page;
2106 int pageno, pindex;
2108 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
2109 if (ret != 2) {
2110 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
2113 lock ("page");
2114 a = now ();
2115 page = loadpage (pageno, pindex);
2116 b = now ();
2117 unlock ("page");
2119 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
2121 else if (!strncmp ("tile", p, 4)) {
2122 int x, y, w, h;
2123 struct page *page;
2124 struct tile *tile;
2125 double a, b;
2126 void *data;
2128 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
2129 SCN_ptr_cast (&page), &x, &y, &w, &h,
2130 SCN_ptr_cast (&data));
2131 if (ret != 6) {
2132 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
2135 lock ("tile");
2136 a = now ();
2137 tile = rendertile (page, x, y, w, h, data);
2138 b = now ();
2139 unlock ("tile");
2141 printd ("tile %d %d %" FMT_ptr " %u %f",
2142 x, y,
2143 FMT_ptr_cast (tile),
2144 tile->w * tile->h * tile->pixmap->n,
2145 b - a);
2147 else if (!strncmp ("settrim", p, 7)) {
2148 fz_irect fuzz;
2149 int trimmargins;
2151 ret = sscanf (p + 7, " %d %d %d %d %d",
2152 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
2153 if (ret != 5) {
2154 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
2156 printd ("clear");
2157 lock ("settrim");
2158 state.trimmargins = trimmargins;
2159 state.needoutline = 1;
2160 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
2161 state.trimanew = 1;
2162 state.trimfuzz = fuzz;
2164 state.pagedimcount = 0;
2165 free (state.pagedims);
2166 state.pagedims = NULL;
2167 initpdims ();
2168 layout ();
2169 process_outline ();
2170 unlock ("settrim");
2171 printd ("continue %d", state.pagecount);
2173 else if (!strncmp ("sliceh", p, 6)) {
2174 int h;
2176 ret = sscanf (p + 6, " %d", &h);
2177 if (ret != 1) {
2178 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
2180 if (h != state.sliceheight) {
2181 int i;
2183 state.sliceheight = h;
2184 for (i = 0; i < state.texcount; ++i) {
2185 state.texowners[i].w = -1;
2186 state.texowners[i].h = -1;
2187 state.texowners[i].slice = NULL;
2191 else if (!strncmp ("interrupt", p, 9)) {
2192 printd ("vmsg interrupted");
2194 else {
2195 errx (1, "unknown command %.*s", len, p);
2198 return 0;
2201 CAMLprim value ml_realloctexts (value texcount_v)
2203 CAMLparam1 (texcount_v);
2204 int ok;
2206 if (trylock ("ml_realloctexts")) {
2207 ok = 0;
2208 goto done;
2210 realloctexts (Int_val (texcount_v));
2211 ok = 1;
2212 unlock ("ml_realloctexts");
2214 done:
2215 CAMLreturn (Val_bool (ok));
2218 static void recti (int x0, int y0, int x1, int y1)
2220 GLfloat *v = state.vertices;
2222 glVertexPointer (2, GL_FLOAT, 0, v);
2223 v[0] = x0; v[1] = y0;
2224 v[2] = x1; v[3] = y0;
2225 v[4] = x0; v[5] = y1;
2226 v[6] = x1; v[7] = y1;
2227 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2230 static void showsel (struct page *page, int ox, int oy)
2232 int seen = 0;
2233 fz_irect bbox;
2234 fz_rect rect;
2235 fz_text_line *line;
2236 fz_page_block *pageb;
2237 fz_text_block *block;
2238 struct mark first, last;
2239 unsigned char selcolor[] = {15,15,15,140};
2241 first = page->fmark;
2242 last = page->lmark;
2244 if (!first.span || !last.span) return;
2246 glEnable (GL_BLEND);
2247 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2248 glColor4ubv (selcolor);
2250 ox += state.pagedims[page->pdimno].bounds.x0;
2251 oy += state.pagedims[page->pdimno].bounds.y0;
2252 for (pageb = page->text->blocks;
2253 pageb < page->text->blocks + page->text->len;
2254 ++pageb) {
2255 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2256 block = pageb->u.text;
2258 for (line = block->lines;
2259 line < block->lines + block->len;
2260 ++line) {
2261 fz_text_span *span;
2262 rect = fz_empty_rect;
2264 for (span = line->first_span; span; span = span->next) {
2265 int i, j, k;
2266 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2268 j = 0;
2269 k = span->len - 1;
2271 if (span == page->fmark.span && span == page->lmark.span) {
2272 seen = 1;
2273 j = MIN (first.i, last.i);
2274 k = MAX (first.i, last.i);
2276 else {
2277 if (span == first.span) {
2278 seen = 1;
2279 j = first.i;
2281 else if (span == last.span) {
2282 seen = 1;
2283 k = last.i;
2287 if (seen) {
2288 for (i = j; i <= k; ++i) {
2289 fz_rect bbox1;
2290 fz_union_rect (&rect,
2291 fz_text_char_bbox (&bbox1, span, i));
2293 fz_round_rect (&bbox, &rect);
2294 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2295 bbox.x0,
2296 bbox.y0,
2297 bbox.x1,
2298 bbox.y1,
2299 oy, ox);
2301 recti (bbox.x0 + ox, bbox.y0 + oy,
2302 bbox.x1 + ox, bbox.y1 + oy);
2303 if (span == last.span) {
2304 goto done;
2306 rect = fz_empty_rect;
2311 done:
2312 glDisable (GL_BLEND);
2315 #include "glfont.c"
2317 static void highlightlinks (struct page *page, int xoff, int yoff)
2319 fz_matrix ctm, tm, pm;
2320 fz_link *link, *links;
2321 GLfloat *texcoords = state.texcoords;
2322 GLfloat *vertices = state.vertices;
2324 switch (page->type) {
2325 case DPDF:
2326 links = page->u.pdfpage->links;
2327 break;
2329 case DXPS:
2330 links = page->u.xpspage->links;
2331 break;
2333 default:
2334 return;
2337 glEnable (GL_TEXTURE_1D);
2338 glEnable (GL_BLEND);
2339 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2340 glBindTexture (GL_TEXTURE_1D, state.stid);
2342 xoff -= state.pagedims[page->pdimno].bounds.x0;
2343 yoff -= state.pagedims[page->pdimno].bounds.y0;
2344 fz_translate (&tm, xoff, yoff);
2345 pm = pagectm (page);
2346 fz_concat (&ctm, &pm, &tm);
2348 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2349 glVertexPointer (2, GL_FLOAT, 0, vertices);
2351 for (link = links; link; link = link->next) {
2352 fz_point p1, p2, p3, p4;
2354 p1.x = link->rect.x0;
2355 p1.y = link->rect.y0;
2357 p2.x = link->rect.x1;
2358 p2.y = link->rect.y0;
2360 p3.x = link->rect.x1;
2361 p3.y = link->rect.y1;
2363 p4.x = link->rect.x0;
2364 p4.y = link->rect.y1;
2366 fz_transform_point (&p1, &ctm);
2367 fz_transform_point (&p2, &ctm);
2368 fz_transform_point (&p3, &ctm);
2369 fz_transform_point (&p4, &ctm);
2371 switch (link->dest.kind) {
2372 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2373 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2374 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2375 default: glColor3ub (0, 0, 0); break;
2379 float w, h, s, t;
2381 w = p2.x - p1.x;
2382 h = p2.y - p1.y;
2383 t = sqrtf (w*w + h*h) * .25f;
2385 w = p3.x - p2.x;
2386 h = p3.y - p2.y;
2387 s = sqrtf (w*w + h*h) * .25f;
2389 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
2390 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
2392 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
2393 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
2395 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
2396 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
2398 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
2399 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
2401 glDrawArrays (GL_LINES, 0, 8);
2404 glDisable (GL_BLEND);
2405 glDisable (GL_TEXTURE_1D);
2408 static int compareslinks (const void *l, const void *r)
2410 struct slink const *ls = l;
2411 struct slink const *rs = r;
2412 if (ls->bbox.y0 == rs->bbox.y0) {
2413 return rs->bbox.x0 - rs->bbox.x0;
2415 return ls->bbox.y0 - rs->bbox.y0;
2418 static void droptext (struct page *page)
2420 if (page->text) {
2421 fz_free_text_page (state.ctx, page->text);
2422 page->fmark.i = -1;
2423 page->lmark.i = -1;
2424 page->fmark.span = NULL;
2425 page->lmark.span = NULL;
2426 page->text = NULL;
2428 if (page->sheet) {
2429 fz_free_text_sheet (state.ctx, page->sheet);
2430 page->sheet = NULL;
2434 static void dropslinks (struct page *page)
2436 if (page->slinks) {
2437 free (page->slinks);
2438 page->slinks = NULL;
2439 page->slinkcount = 0;
2443 static void ensureslinks (struct page *page)
2445 fz_matrix ctm;
2446 int i, count = 0;
2447 size_t slinksize = sizeof (*page->slinks);
2448 fz_link *link, *links;
2450 if (state.gen != page->sgen) {
2451 dropslinks (page);
2452 page->sgen = state.gen;
2454 if (page->slinks) return;
2456 switch (page->type) {
2457 case DPDF:
2458 links = page->u.pdfpage->links;
2459 trimctm (page->u.pdfpage, page->pdimno);
2460 fz_concat (&ctm,
2461 &state.pagedims[page->pdimno].tctm,
2462 &state.pagedims[page->pdimno].ctm);
2463 break;
2465 case DXPS:
2466 links = page->u.xpspage->links;
2467 ctm = state.pagedims[page->pdimno].ctm;
2468 break;
2470 default:
2471 return;
2474 for (link = links; link; link = link->next) {
2475 count++;
2477 if (count > 0) {
2478 page->slinkcount = count;
2479 page->slinks = calloc (count, slinksize);
2480 if (!page->slinks) {
2481 err (1, "realloc slinks %d", count);
2484 for (i = 0, link = links; link; ++i, link = link->next) {
2485 fz_rect rect;
2487 rect = link->rect;
2488 fz_transform_rect (&rect, &ctm);
2489 page->slinks[i].link = link;
2490 fz_round_rect (&page->slinks[i].bbox, &rect);
2492 qsort (page->slinks, count, slinksize, compareslinks);
2496 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2497 static void fmt_linkn (char *s, unsigned int u)
2499 unsigned int len; unsigned int q;
2500 unsigned int zma = 'z' - 'a' + 1;
2501 len = 1; q = u;
2502 while (q > zma - 1) { ++len; q /= zma; }
2503 if (s) {
2504 s += len;
2505 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2506 /* handles u == 0 */
2508 s[len] = 0;
2511 static void highlightslinks (struct page *page, int xoff, int yoff,
2512 int noff, char *targ, int tlen, int hfsize)
2514 int i;
2515 char buf[40];
2516 struct slink *slink;
2517 double x0, y0, x1, y1, w;
2519 ensureslinks (page);
2520 glColor3ub (0xc3, 0xb0, 0x91);
2521 for (i = 0; i < page->slinkcount; ++i) {
2522 fmt_linkn (buf, i + noff);
2523 if (!tlen || !strncmp (targ, buf, tlen)) {
2524 slink = &page->slinks[i];
2526 x0 = slink->bbox.x0 + xoff - 5;
2527 y1 = slink->bbox.y0 + yoff - 5;
2528 y0 = y1 + 10 + hfsize;
2529 w = measure_string (state.face, hfsize, buf);
2530 x1 = x0 + w + 10;
2531 recti (x0, y0, x1, y1);
2535 glEnable (GL_BLEND);
2536 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2537 glEnable (GL_TEXTURE_2D);
2538 glColor3ub (0, 0, 0);
2539 for (i = 0; i < page->slinkcount; ++i) {
2540 fmt_linkn (buf, i + noff);
2541 if (!tlen || !strncmp (targ, buf, tlen)) {
2542 slink = &page->slinks[i];
2544 x0 = slink->bbox.x0 + xoff;
2545 y0 = slink->bbox.y0 + yoff + hfsize;
2546 draw_string (state.face, hfsize, x0, y0, buf);
2549 glDisable (GL_TEXTURE_2D);
2550 glDisable (GL_BLEND);
2553 static void uploadslice (struct tile *tile, struct slice *slice)
2555 int offset;
2556 struct slice *slice1;
2557 unsigned char *texdata;
2559 offset = 0;
2560 for (slice1 = tile->slices; slice != slice1; slice1++) {
2561 offset += slice1->h * tile->w * tile->pixmap->n;
2563 if (slice->texindex != -1 && slice->texindex < state.texcount
2564 && state.texowners[slice->texindex].slice == slice) {
2565 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2567 else {
2568 int subimage = 0;
2569 int texindex = state.texindex++ % state.texcount;
2571 if (state.texowners[texindex].w == tile->w) {
2572 if (state.texowners[texindex].h >= slice->h) {
2573 subimage = 1;
2575 else {
2576 state.texowners[texindex].h = slice->h;
2579 else {
2580 state.texowners[texindex].h = slice->h;
2583 state.texowners[texindex].w = tile->w;
2584 state.texowners[texindex].slice = slice;
2585 slice->texindex = texindex;
2587 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2588 if (tile->pbo) {
2589 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2590 texdata = 0;
2592 else {
2593 texdata = tile->pixmap->samples;
2595 if (subimage) {
2596 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2600 tile->w,
2601 slice->h,
2602 state.texform,
2603 state.texty,
2604 texdata+offset
2607 else {
2608 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2610 state.texiform,
2611 tile->w,
2612 slice->h,
2614 state.texform,
2615 state.texty,
2616 texdata+offset
2619 if (tile->pbo) {
2620 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2625 CAMLprim value ml_begintiles (value unit_v)
2627 CAMLparam1 (unit_v);
2628 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2629 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2630 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2631 CAMLreturn (unit_v);
2634 CAMLprim value ml_endtiles (value unit_v)
2636 CAMLparam1 (unit_v);
2637 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2638 CAMLreturn (unit_v);
2641 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2643 CAMLparam2 (args_v, ptr_v);
2644 int dispx = Int_val (Field (args_v, 0));
2645 int dispy = Int_val (Field (args_v, 1));
2646 int dispw = Int_val (Field (args_v, 2));
2647 int disph = Int_val (Field (args_v, 3));
2648 int tilex = Int_val (Field (args_v, 4));
2649 int tiley = Int_val (Field (args_v, 5));
2650 char *s = String_val (ptr_v);
2651 struct tile *tile = parse_pointer ("ml_drawtile", s);
2652 int slicey, firstslice;
2653 struct slice *slice;
2654 GLfloat *texcoords = state.texcoords;
2655 GLfloat *vertices = state.vertices;
2657 firstslice = tiley / tile->sliceheight;
2658 slice = &tile->slices[firstslice];
2659 slicey = tiley % tile->sliceheight;
2661 while (disph > 0) {
2662 int dh;
2664 dh = slice->h - slicey;
2665 dh = MIN (disph, dh);
2666 uploadslice (tile, slice);
2668 texcoords[0] = tilex; texcoords[1] = slicey;
2669 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2670 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2671 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2673 vertices[0] = dispx; vertices[1] = dispy;
2674 vertices[2] = dispx+dispw; vertices[3] = dispy;
2675 vertices[4] = dispx; vertices[5] = dispy+dh;
2676 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2678 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2679 dispy += dh;
2680 disph -= dh;
2681 slice++;
2682 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2683 slicey = 0;
2685 CAMLreturn (Val_unit);
2688 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2689 value xoff_v, value yoff_v,
2690 value li_v)
2692 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2693 int xoff = Int_val (xoff_v);
2694 int yoff = Int_val (yoff_v);
2695 int noff = Int_val (Field (li_v, 0));
2696 char *targ = String_val (Field (li_v, 1));
2697 int tlen = caml_string_length (Field (li_v, 1));
2698 int hfsize = Int_val (Field (li_v, 2));
2699 char *s = String_val (ptr_v);
2700 int hlmask = Int_val (hlinks_v);
2701 struct page *page = parse_pointer ("ml_postprocess", s);
2703 if (!page->u.ptr) {
2704 /* deal with loadpage failed pages */
2705 goto done;
2708 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2709 if (trylock ("ml_postprocess")) {
2710 noff = 0;
2711 goto done;
2713 if (hlmask & 2) {
2714 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2715 noff = page->slinkcount;
2717 if (page->tgen == state.gen) {
2718 showsel (page, xoff, yoff);
2720 unlock ("ml_postprocess");
2722 done:
2723 CAMLreturn (Val_int (noff));
2726 static fz_link *getlink (struct page *page, int x, int y)
2728 fz_point p;
2729 fz_matrix ctm;
2730 const fz_matrix *tctm;
2731 fz_link *link, *links;
2733 switch (page->type) {
2734 case DPDF:
2735 trimctm (page->u.pdfpage, page->pdimno);
2736 tctm = &state.pagedims[page->pdimno].tctm;
2737 links = page->u.pdfpage->links;
2738 break;
2740 case DXPS:
2741 tctm = &fz_identity;
2742 links = page->u.xpspage->links;
2743 break;
2745 default:
2746 return NULL;
2748 p.x = x;
2749 p.y = y;
2751 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2752 fz_invert_matrix (&ctm, &ctm);
2753 fz_transform_point (&p, &ctm);
2755 for (link = links; link; link = link->next) {
2756 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2757 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2758 return link;
2762 return NULL;
2765 static void ensuretext (struct page *page)
2767 if (state.gen != page->tgen) {
2768 droptext (page);
2769 page->tgen = state.gen;
2771 if (!page->text) {
2772 fz_matrix ctm;
2773 fz_device *tdev;
2775 page->text = fz_new_text_page (state.ctx);
2776 page->sheet = fz_new_text_sheet (state.ctx);
2777 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2778 ctm = pagectm (page);
2779 fz_begin_page (tdev, &fz_infinite_rect, &ctm);
2780 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2781 qsort (page->text->blocks, page->text->len,
2782 sizeof (*page->text->blocks), compareblocks);
2783 fz_end_page (tdev);
2784 fz_free_device (tdev);
2788 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2790 CAMLparam2 (start_page_v, dir_v);
2791 CAMLlocal1 (ret_v);
2792 int i, dir = Int_val (dir_v);
2793 int start_page = Int_val (start_page_v);
2794 int end_page = dir > 0 ? state.pagecount : -1;
2796 ret_v = Val_int (0);
2797 if (!(state.type == DPDF || state.type == DXPS)) {
2798 goto done;
2801 lock ("ml_findpage_with_links");
2802 for (i = start_page + dir; i != end_page; i += dir) {
2803 int found;
2805 switch (state.type) {
2806 case DPDF:
2808 pdf_page *page = NULL;
2810 fz_try (state.ctx) {
2811 page = pdf_load_page (state.u.pdf, i);
2812 found = !!page->links;
2814 fz_catch (state.ctx) {
2815 found = 0;
2817 if (page) {
2818 freepdfpage (page);
2821 break;
2822 case DXPS:
2824 xps_page *page = xps_load_page (state.u.xps, i);
2825 found = !!page->links;
2826 freexpspage (page);
2828 break;
2830 default:
2831 ARSERT (0 && "invalid document type");
2834 if (found) {
2835 ret_v = caml_alloc_small (1, 1);
2836 Field (ret_v, 0) = Val_int (i);
2837 goto unlock;
2840 unlock:
2841 unlock ("ml_findpage_with_links");
2843 done:
2844 CAMLreturn (ret_v);
2847 enum { dir_first, dir_last };
2848 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2850 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2852 CAMLparam2 (ptr_v, dir_v);
2853 CAMLlocal2 (ret_v, pos_v);
2854 struct page *page;
2855 int dirtag, i, slinkindex;
2856 struct slink *found = NULL ,*slink;
2857 char *s = String_val (ptr_v);
2859 page = parse_pointer ("ml_findlink", s);
2860 ret_v = Val_int (0);
2861 if (trylock ("ml_findlink")) {
2862 goto done;
2865 ensureslinks (page);
2867 if (Is_block (dir_v)) {
2868 dirtag = Tag_val (dir_v);
2869 switch (dirtag) {
2870 case dir_first_visible:
2872 int x0, y0, dir, first_index, last_index;
2874 pos_v = Field (dir_v, 0);
2875 x0 = Int_val (Field (pos_v, 0));
2876 y0 = Int_val (Field (pos_v, 1));
2877 dir = Int_val (Field (pos_v, 2));
2879 if (dir >= 0) {
2880 dir = 1;
2881 first_index = 0;
2882 last_index = page->slinkcount;
2884 else {
2885 first_index = page->slinkcount - 1;
2886 last_index = -1;
2889 for (i = first_index; i != last_index; i += dir) {
2890 slink = &page->slinks[i];
2891 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2892 found = slink;
2893 break;
2897 break;
2899 case dir_left:
2900 slinkindex = Int_val (Field (dir_v, 0));
2901 found = &page->slinks[slinkindex];
2902 for (i = slinkindex - 1; i >= 0; --i) {
2903 slink = &page->slinks[i];
2904 if (slink->bbox.x0 < found->bbox.x0) {
2905 found = slink;
2906 break;
2909 break;
2911 case dir_right:
2912 slinkindex = Int_val (Field (dir_v, 0));
2913 found = &page->slinks[slinkindex];
2914 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2915 slink = &page->slinks[i];
2916 if (slink->bbox.x0 > found->bbox.x0) {
2917 found = slink;
2918 break;
2921 break;
2923 case dir_down:
2924 slinkindex = Int_val (Field (dir_v, 0));
2925 found = &page->slinks[slinkindex];
2926 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2927 slink = &page->slinks[i];
2928 if (slink->bbox.y0 >= found->bbox.y0) {
2929 found = slink;
2930 break;
2933 break;
2935 case dir_up:
2936 slinkindex = Int_val (Field (dir_v, 0));
2937 found = &page->slinks[slinkindex];
2938 for (i = slinkindex - 1; i >= 0; --i) {
2939 slink = &page->slinks[i];
2940 if (slink->bbox.y0 <= found->bbox.y0) {
2941 found = slink;
2942 break;
2945 break;
2948 else {
2949 dirtag = Int_val (dir_v);
2950 switch (dirtag) {
2951 case dir_first:
2952 found = page->slinks;
2953 break;
2955 case dir_last:
2956 if (page->slinks) {
2957 found = page->slinks + (page->slinkcount - 1);
2959 break;
2962 if (found) {
2963 ret_v = caml_alloc_small (2, 1);
2964 Field (ret_v, 0) = Val_int (found - page->slinks);
2967 unlock ("ml_findlink");
2968 done:
2969 CAMLreturn (ret_v);
2972 enum { uuri, ugoto, utext, uunexpected,
2973 ulaunch, unamed, uremote, uremotedest };
2975 #define LINKTOVAL \
2977 int pageno; \
2979 switch (link->dest.kind) { \
2980 case FZ_LINK_GOTO: \
2982 fz_point p; \
2984 pageno = link->dest.ld.gotor.page; \
2985 p.x = 0; \
2986 p.y = 0; \
2988 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2989 p.y = link->dest.ld.gotor.lt.y; \
2990 fz_transform_point (&p, &pdim->lctm); \
2991 if (p.y < 0) p.y = 0; \
2993 tup_v = caml_alloc_tuple (2); \
2994 ret_v = caml_alloc_small (1, ugoto); \
2995 Field (tup_v, 0) = Val_int (pageno); \
2996 Field (tup_v, 1) = Val_int (p.y); \
2997 Field (ret_v, 0) = tup_v; \
2999 break; \
3001 case FZ_LINK_URI: \
3002 str_v = caml_copy_string (link->dest.ld.uri.uri); \
3003 ret_v = caml_alloc_small (1, uuri); \
3004 Field (ret_v, 0) = str_v; \
3005 break; \
3007 case FZ_LINK_LAUNCH: \
3008 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
3009 ret_v = caml_alloc_small (1, ulaunch); \
3010 Field (ret_v, 0) = str_v; \
3011 break; \
3013 case FZ_LINK_NAMED: \
3014 str_v = caml_copy_string (link->dest.ld.named.named); \
3015 ret_v = caml_alloc_small (1, unamed); \
3016 Field (ret_v, 0) = str_v; \
3017 break; \
3019 case FZ_LINK_GOTOR: \
3021 int rty; \
3023 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
3024 pageno = link->dest.ld.gotor.page; \
3025 if (pageno == -1) { \
3026 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
3027 rty = uremotedest; \
3029 else { \
3030 gr_v = Val_int (pageno); \
3031 rty = uremote; \
3033 tup_v = caml_alloc_tuple (2); \
3034 ret_v = caml_alloc_small (1, rty); \
3035 Field (tup_v, 0) = str_v; \
3036 Field (tup_v, 1) = gr_v; \
3037 Field (ret_v, 0) = tup_v; \
3039 break; \
3041 default: \
3043 char buf[80]; \
3045 snprintf (buf, sizeof (buf), \
3046 "unhandled link kind %d", link->dest.kind); \
3047 str_v = caml_copy_string (buf); \
3048 ret_v = caml_alloc_small (1, uunexpected); \
3049 Field (ret_v, 0) = str_v; \
3051 break; \
3055 CAMLprim value ml_getlink (value ptr_v, value n_v)
3057 CAMLparam2 (ptr_v, n_v);
3058 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3059 fz_link *link;
3060 struct page *page;
3061 struct pagedim *pdim;
3062 char *s = String_val (ptr_v);
3064 ret_v = Val_int (0);
3065 if (trylock ("ml_getlink")) {
3066 goto done;
3069 page = parse_pointer ("ml_getlink", s);
3070 ensureslinks (page);
3071 pdim = &state.pagedims[page->pdimno];
3072 link = page->slinks[Int_val (n_v)].link;
3073 LINKTOVAL;
3075 unlock ("ml_getlink");
3076 done:
3077 CAMLreturn (ret_v);
3080 CAMLprim value ml_getlinkcount (value ptr_v)
3082 CAMLparam1 (ptr_v);
3083 struct page *page;
3084 char *s = String_val (ptr_v);
3086 page = parse_pointer ("ml_getlinkcount", s);
3087 CAMLreturn (Val_int (page->slinkcount));
3090 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3092 CAMLparam2 (ptr_v, n_v);
3093 CAMLlocal1 (ret_v);
3094 struct page *page;
3095 struct slink *slink;
3096 char *s = String_val (ptr_v);
3098 page = parse_pointer ("ml_getlinkrect", s);
3099 ret_v = caml_alloc_tuple (4);
3100 if (trylock ("ml_getlinkrect")) {
3101 Field (ret_v, 0) = Val_int (0);
3102 Field (ret_v, 1) = Val_int (0);
3103 Field (ret_v, 2) = Val_int (0);
3104 Field (ret_v, 3) = Val_int (0);
3105 goto done;
3107 ensureslinks (page);
3109 slink = &page->slinks[Int_val (n_v)];
3110 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3111 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3112 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3113 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3114 unlock ("ml_getlinkrect");
3116 done:
3117 CAMLreturn (ret_v);
3120 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3122 CAMLparam3 (ptr_v, x_v, y_v);
3123 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3124 fz_link *link;
3125 struct page *page;
3126 char *ptr = String_val (ptr_v);
3127 int x = Int_val (x_v), y = Int_val (y_v);
3128 struct pagedim *pdim;
3130 ret_v = Val_int (0);
3131 if (trylock ("ml_whatsunder")) {
3132 goto done;
3135 page = parse_pointer ("ml_whatsunder", ptr);
3136 pdim = &state.pagedims[page->pdimno];
3137 x += pdim->bounds.x0;
3138 y += pdim->bounds.y0;
3139 link = getlink (page, x, y);
3140 if (link) {
3141 LINKTOVAL;
3143 else {
3144 fz_rect *b;
3145 fz_page_block *pageb;
3146 fz_text_block *block;
3148 ensuretext (page);
3149 for (pageb = page->text->blocks;
3150 pageb < page->text->blocks + page->text->len;
3151 ++pageb) {
3152 fz_text_line *line;
3153 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3154 block = pageb->u.text;
3156 b = &block->bbox;
3157 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3158 continue;
3160 for (line = block->lines;
3161 line < block->lines + block->len;
3162 ++line) {
3163 fz_text_span *span;
3165 b = &line->bbox;
3166 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3167 continue;
3169 for (span = line->first_span; span; span = span->next) {
3170 int charnum;
3172 b = &span->bbox;
3173 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3174 continue;
3176 for (charnum = 0; charnum < span->len; ++charnum) {
3177 fz_rect bbox;
3178 fz_text_char_bbox (&bbox, span, charnum);
3179 b = &bbox;
3181 if (x >= b->x0 && x <= b->x1
3182 && y >= b->y0 && y <= b->y1) {
3183 fz_text_style *style = span->text->style;
3184 const char *n2 =
3185 style->font && style->font->name
3186 ? style->font->name
3187 : "Span has no font name"
3189 FT_FaceRec *face = style->font->ft_face;
3190 if (face && face->family_name) {
3191 char *s;
3192 char *n1 = face->family_name;
3193 size_t l1 = strlen (n1);
3194 size_t l2 = strlen (n2);
3196 if (l1 != l2 || memcmp (n1, n2, l1)) {
3197 s = malloc (l1 + l2 + 2);
3198 if (s) {
3199 memcpy (s, n2, l2);
3200 s[l2] = '=';
3201 memcpy (s + l2 + 1, n1, l1 + 1);
3202 str_v = caml_copy_string (s);
3203 free (s);
3207 if (str_v == Val_unit) {
3208 str_v = caml_copy_string (n2);
3210 ret_v = caml_alloc_small (1, utext);
3211 Field (ret_v, 0) = str_v;
3212 goto unlock;
3219 unlock:
3220 unlock ("ml_whatsunder");
3222 done:
3223 CAMLreturn (ret_v);
3226 enum { mark_page, mark_block, mark_line, mark_word };
3228 static int uninteresting (int c)
3230 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3231 || ispunct (c);
3234 CAMLprim value ml_clearmark (value ptr_v)
3236 CAMLparam1 (ptr_v);
3237 char *s = String_val (ptr_v);
3238 struct page *page;
3240 if (trylock ("ml_clearmark")) {
3241 goto done;
3244 page = parse_pointer ("ml_clearmark", s);
3245 page->fmark.span = NULL;
3246 page->lmark.span = NULL;
3247 page->fmark.i = 0;
3248 page->lmark.i = 0;
3250 unlock ("ml_clearmark");
3251 done:
3252 CAMLreturn (Val_unit);
3255 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3257 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3258 CAMLlocal1 (ret_v);
3259 fz_rect *b;
3260 struct page *page;
3261 fz_text_line *line;
3262 fz_page_block *pageb;
3263 fz_text_block *block;
3264 struct pagedim *pdim;
3265 int mark = Int_val (mark_v);
3266 char *s = String_val (ptr_v);
3267 int x = Int_val (x_v), y = Int_val (y_v);
3269 ret_v = Val_bool (0);
3270 if (trylock ("ml_markunder")) {
3271 goto done;
3274 page = parse_pointer ("ml_markunder", s);
3275 pdim = &state.pagedims[page->pdimno];
3277 ensuretext (page);
3279 if (mark == mark_page) {
3280 int i;
3281 fz_page_block *pb1 = NULL, *pb2 = NULL;
3283 for (i = 0; i < page->text->len; ++i) {
3284 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3285 pb1 = &page->text->blocks[i];
3286 break;
3289 if (!pb1) goto unlock;
3291 for (i = page->text->len - 1; i >= 0; --i) {
3292 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3293 pb2 = &page->text->blocks[i];
3294 break;
3297 if (!pb2) goto unlock;
3299 block = pb1->u.text;
3301 page->fmark.i = 0;
3302 page->fmark.span = block->lines->first_span;
3304 block = pb2->u.text;
3305 line = &block->lines[block->len - 1];
3306 page->lmark.i = line->last_span->len - 1;
3307 page->lmark.span = line->last_span;
3308 ret_v = Val_bool (1);
3309 goto unlock;
3312 x += pdim->bounds.x0;
3313 y += pdim->bounds.y0;
3315 for (pageb = page->text->blocks;
3316 pageb < page->text->blocks + page->text->len;
3317 ++pageb) {
3318 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3319 block = pageb->u.text;
3321 b = &block->bbox;
3322 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3323 continue;
3325 if (mark == mark_block) {
3326 page->fmark.i = 0;
3327 page->fmark.span = block->lines->first_span;
3329 line = &block->lines[block->len - 1];
3330 page->lmark.i = line->last_span->len - 1;
3331 page->lmark.span = line->last_span;
3332 ret_v = Val_bool (1);
3333 goto unlock;
3336 for (line = block->lines;
3337 line < block->lines + block->len;
3338 ++line) {
3339 fz_text_span *span;
3341 b = &line->bbox;
3342 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3343 continue;
3345 if (mark == mark_line) {
3346 page->fmark.i = 0;
3347 page->fmark.span = line->first_span;
3349 page->lmark.i = line->last_span->len - 1;
3350 page->lmark.span = line->last_span;
3351 ret_v = Val_bool (1);
3352 goto unlock;
3355 for (span = line->first_span; span; span = span->next) {
3356 int charnum;
3358 b = &span->bbox;
3359 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3360 continue;
3362 for (charnum = 0; charnum < span->len; ++charnum) {
3363 fz_rect bbox;
3364 fz_text_char_bbox (&bbox, span, charnum);
3365 b = &bbox;
3367 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3368 /* unicode ftw */
3369 int charnum2, charnum3 = -1, charnum4 = -1;
3371 if (uninteresting (span->text[charnum].c)) goto unlock;
3373 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3374 if (uninteresting (span->text[charnum2].c)) {
3375 charnum3 = charnum2 + 1;
3376 break;
3379 if (charnum3 == -1) charnum3 = 0;
3381 for (charnum2 = charnum + 1;
3382 charnum2 < span->len;
3383 ++charnum2) {
3384 if (uninteresting (span->text[charnum2].c)) break;
3385 charnum4 = charnum2;
3387 if (charnum4 == -1) goto unlock;
3389 page->fmark.i = charnum3;
3390 page->fmark.span = span;
3392 page->lmark.i = charnum4;
3393 page->lmark.span = span;
3394 ret_v = Val_bool (1);
3395 goto unlock;
3401 unlock:
3402 if (!Bool_val (ret_v)) {
3403 page->fmark.span = NULL;
3404 page->lmark.span = NULL;
3405 page->fmark.i = 0;
3406 page->lmark.i = 0;
3408 unlock ("ml_markunder");
3410 done:
3411 CAMLreturn (ret_v);
3414 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3416 CAMLparam3 (ptr_v, x_v, y_v);
3417 CAMLlocal2 (ret_v, res_v);
3418 fz_rect *b = NULL;
3419 struct page *page;
3420 fz_page_block *pageb;
3421 struct pagedim *pdim;
3422 char *s = String_val (ptr_v);
3423 int x = Int_val (x_v), y = Int_val (y_v);
3425 ret_v = Val_int (0);
3426 if (trylock ("ml_rectofblock")) {
3427 goto done;
3430 page = parse_pointer ("ml_rectofblock", s);
3431 pdim = &state.pagedims[page->pdimno];
3432 x += pdim->bounds.x0;
3433 y += pdim->bounds.y0;
3435 ensuretext (page);
3437 for (pageb = page->text->blocks;
3438 pageb < page->text->blocks + page->text->len;
3439 ++pageb) {
3440 switch (pageb->type) {
3441 case FZ_PAGE_BLOCK_TEXT:
3442 b = &pageb->u.text->bbox;
3443 break;
3445 case FZ_PAGE_BLOCK_IMAGE:
3446 b = &pageb->u.image->bbox;
3447 break;
3449 default:
3450 continue;
3453 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3454 break;
3455 b = NULL;
3457 if (b) {
3458 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3459 ret_v = caml_alloc_small (1, 1);
3460 Store_double_field (res_v, 0, b->x0);
3461 Store_double_field (res_v, 1, b->x1);
3462 Store_double_field (res_v, 2, b->y0);
3463 Store_double_field (res_v, 3, b->y1);
3464 Field (ret_v, 0) = res_v;
3466 unlock ("ml_rectofblock");
3468 done:
3469 CAMLreturn (ret_v);
3472 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3474 CAMLparam2 (ptr_v, rect_v);
3475 fz_rect b;
3476 struct page *page;
3477 struct pagedim *pdim;
3478 char *s = String_val (ptr_v);
3479 int i, x0, x1, y0, y1, fi, li;
3480 fz_text_line *line;
3481 fz_page_block *pageb;
3482 fz_text_block *block;
3483 fz_text_span *span, *fspan, *lspan;
3485 if (trylock ("ml_seltext")) {
3486 goto done;
3489 page = parse_pointer ("ml_seltext", s);
3490 ensuretext (page);
3492 pdim = &state.pagedims[page->pdimno];
3493 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3494 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3495 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3496 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3498 if (y0 > y1) {
3499 int t = y0;
3500 y0 = y1;
3501 y1 = t;
3502 x0 = x1;
3503 x1 = t;
3506 if (0) {
3507 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3508 glColor3ub (128, 128, 128);
3509 recti (x0, y0, x1, y1);
3510 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3513 fi = page->fmark.i;
3514 fspan = page->fmark.span;
3516 li = page->lmark.i;
3517 lspan = page->lmark.span;
3519 for (pageb = page->text->blocks;
3520 pageb < page->text->blocks + page->text->len;
3521 ++pageb) {
3522 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3523 block = pageb->u.text;
3524 for (line = block->lines;
3525 line < block->lines + block->len;
3526 ++line) {
3528 for (span = line->first_span; span; span = span->next) {
3529 for (i = 0; i < span->len; ++i) {
3530 int selected = 0;
3532 fz_text_char_bbox (&b, span, i);
3534 if (x0 >= b.x0 && x0 <= b.x1
3535 && y0 >= b.y0 && y0 <= b.y1) {
3536 fspan = span;
3537 fi = i;
3538 selected = 1;
3540 if (x1 >= b.x0 && x1 <= b.x1
3541 && y1 >= b.y0 && y1 <= b.y1) {
3542 lspan = span;
3543 li = i;
3544 selected = 1;
3546 if (0 && selected) {
3547 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3548 glColor3ub (128, 128, 128);
3549 recti (b.x0, b.y0, b.x1, b.y1);
3550 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3556 if (x1 < x0 && fspan == lspan) {
3557 i = fi;
3558 span = fspan;
3560 fi = li;
3561 fspan = lspan;
3563 li = i;
3564 lspan = span;
3567 page->fmark.i = fi;
3568 page->fmark.span = fspan;
3570 page->lmark.i = li;
3571 page->lmark.span = lspan;
3573 unlock ("ml_seltext");
3575 done:
3576 CAMLreturn (Val_unit);
3579 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3581 char buf[4];
3582 int i, len, ret;
3584 for (i = a; i <= b; ++i) {
3585 len = fz_runetochar (buf, span->text[i].c);
3586 ret = fwrite (buf, len, 1, f);
3588 if (ret != 1) {
3589 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3590 len, ret, strerror (errno));
3591 return -1;
3594 return 0;
3597 #ifdef __CYGWIN__
3598 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3600 caml_failwith ("ml_popen not implemented under Cygwin");
3602 #else
3603 CAMLprim value ml_popen (value command_v, value fds_v)
3605 CAMLparam2 (command_v, fds_v);
3606 CAMLlocal2 (l_v, tup_v);
3607 int ret;
3608 char *msg = NULL;
3609 value earg_v = Nothing;
3610 posix_spawnattr_t attr;
3611 posix_spawn_file_actions_t fa;
3612 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3614 argv[2] = String_val (command_v);
3616 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3617 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3620 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3621 msg = "posix_spawnattr_init";
3622 goto fail1;
3625 #ifdef POSIX_SPAWN_USEVFORK
3626 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3627 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3628 goto fail;
3630 #endif
3632 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3633 int fd1, fd2;
3635 tup_v = Field (l_v, 0);
3636 fd1 = Int_val (Field (tup_v, 0));
3637 fd2 = Int_val (Field (tup_v, 1));
3638 if (fd2 < 0) {
3639 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3640 msg = "posix_spawn_file_actions_addclose";
3641 earg_v = tup_v;
3642 goto fail;
3645 else {
3646 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3647 msg = "posix_spawn_file_actions_adddup2";
3648 earg_v = tup_v;
3649 goto fail;
3654 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3655 msg = "posix_spawn";
3656 goto fail;
3659 fail:
3660 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3661 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3664 fail1:
3665 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3666 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3667 strerror (ret));
3670 if (msg)
3671 unix_error (ret, msg, earg_v);
3673 CAMLreturn (Val_unit);
3675 #endif
3677 CAMLprim value ml_hassel (value ptr_v)
3679 CAMLparam1 (ptr_v);
3680 CAMLlocal1 (ret_v);
3681 struct page *page;
3682 char *s = String_val (ptr_v);
3684 ret_v = Val_bool (0);
3685 if (trylock ("ml_hassel")) {
3686 goto done;
3689 page = parse_pointer ("ml_hassel", s);
3690 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3691 unlock ("ml_hassel");
3692 done:
3693 CAMLreturn (ret_v);
3696 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3698 CAMLparam2 (fd_v, ptr_v);
3699 FILE *f;
3700 int seen = 0;
3701 struct page *page;
3702 fz_text_line *line;
3703 fz_page_block *pageb;
3704 fz_text_block *block;
3705 int fd = Int_val (fd_v);
3706 char *s = String_val (ptr_v);
3708 if (trylock ("ml_copysel")) {
3709 goto done;
3712 page = parse_pointer ("ml_copysel", s);
3714 if (!page->fmark.span || !page->lmark.span) {
3715 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3716 goto unlock;
3719 f = fdopen (fd, "w");
3720 if (!f) {
3721 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3722 fd, strerror (errno));
3723 f = stdout;
3726 for (pageb = page->text->blocks;
3727 pageb < page->text->blocks + page->text->len;
3728 ++pageb) {
3729 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3730 block = pageb->u.text;
3731 for (line = block->lines;
3732 line < block->lines + block->len;
3733 ++line) {
3734 fz_text_span *span;
3736 for (span = line->first_span; span; span = span->next) {
3737 int a, b;
3739 seen |= span == page->fmark.span || span == page->lmark.span;
3740 a = span == page->fmark.span ? page->fmark.i : 0;
3741 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3743 if (seen) {
3744 if (pipespan (f, span, a, b)) {
3745 goto close;
3747 if (span == page->lmark.span) {
3748 goto close;
3750 if (span == line->last_span) {
3751 if (putc ('\n', f) == EOF) {
3752 fprintf (stderr,
3753 "failed break line on sel pipe: %s\n",
3754 strerror (errno));
3755 goto close;
3762 close:
3763 if (f != stdout) {
3764 int ret = fclose (f);
3765 fd = -1;
3766 if (ret == -1) {
3767 if (errno != ECHILD) {
3768 fprintf (stderr, "failed to close sel pipe: %s\n",
3769 strerror (errno));
3773 unlock:
3774 unlock ("ml_copysel");
3776 done:
3777 if (fd >= 0) {
3778 if (close (fd)) {
3779 fprintf (stderr, "failed to close sel pipe: %s\n",
3780 strerror (errno));
3783 CAMLreturn (Val_unit);
3786 CAMLprim value ml_getpdimrect (value pagedimno_v)
3788 CAMLparam1 (pagedimno_v);
3789 CAMLlocal1 (ret_v);
3790 int pagedimno = Int_val (pagedimno_v);
3791 fz_rect box;
3793 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3794 if (trylock ("ml_getpdimrect")) {
3795 box = fz_empty_rect;
3797 else {
3798 box = state.pagedims[pagedimno].mediabox;
3799 unlock ("ml_getpdimrect");
3802 Store_double_field (ret_v, 0, box.x0);
3803 Store_double_field (ret_v, 1, box.x1);
3804 Store_double_field (ret_v, 2, box.y0);
3805 Store_double_field (ret_v, 3, box.y1);
3807 CAMLreturn (ret_v);
3810 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3811 value dw_v, value cols_v)
3813 CAMLparam3 (winw_v, winh_v, dw_v);
3814 CAMLlocal1 (ret_v);
3815 int i;
3816 double zoom = -1.;
3817 double maxh = 0.0;
3818 struct pagedim *p;
3819 double winw = Int_val (winw_v);
3820 double winh = Int_val (winh_v);
3821 double dw = Int_val (dw_v);
3822 double cols = Int_val (cols_v);
3823 double pw = 1.0, ph = 1.0;
3825 if (trylock ("ml_zoom_for_height")) {
3826 goto done;
3829 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3830 double w = p->pagebox.x1 / cols;
3831 double h = p->pagebox.y1;
3832 if (h > maxh) {
3833 maxh = h;
3834 ph = h;
3835 if (state.fitmodel != FitProportional) pw = w;
3837 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3840 zoom = (((winh / ph) * pw) + dw) / winw;
3841 unlock ("ml_zoom_for_height");
3842 done:
3843 ret_v = caml_copy_double (zoom);
3844 CAMLreturn (ret_v);
3847 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3849 CAMLparam4 (pt_v, x_v, y_v, string_v);
3850 CAMLlocal1 (ret_v);
3851 int pt = Int_val(pt_v);
3852 int x = Int_val (x_v);
3853 int y = Int_val (y_v);
3854 double w;
3856 w = draw_string (state.face, pt, x, y, String_val (string_v));
3857 ret_v = caml_copy_double (w);
3858 CAMLreturn (ret_v);
3861 CAMLprim value ml_measure_string (value pt_v, value string_v)
3863 CAMLparam2 (pt_v, string_v);
3864 CAMLlocal1 (ret_v);
3865 int pt = Int_val (pt_v);
3866 double w;
3868 w = measure_string (state.face, pt, String_val (string_v));
3869 ret_v = caml_copy_double (w);
3870 CAMLreturn (ret_v);
3873 CAMLprim value ml_getpagebox (value opaque_v)
3875 CAMLparam1 (opaque_v);
3876 CAMLlocal1 (ret_v);
3877 fz_rect rect;
3878 fz_irect bbox;
3879 fz_matrix ctm;
3880 fz_device *dev;
3881 char *s = String_val (opaque_v);
3882 struct page *page = parse_pointer ("ml_getpagebox", s);
3884 ret_v = caml_alloc_tuple (4);
3885 dev = fz_new_bbox_device (state.ctx, &rect);
3886 dev->hints |= FZ_IGNORE_SHADE;
3888 switch (page->type) {
3889 case DPDF:
3890 ctm = pagectm (page);
3891 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3892 break;
3894 case DXPS:
3895 ctm = pagectm (page);
3896 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3897 break;
3899 default:
3900 rect = fz_infinite_rect;
3901 break;
3904 fz_free_device (dev);
3905 fz_round_rect (&bbox, &rect);
3906 Field (ret_v, 0) = Val_int (bbox.x0);
3907 Field (ret_v, 1) = Val_int (bbox.y0);
3908 Field (ret_v, 2) = Val_int (bbox.x1);
3909 Field (ret_v, 3) = Val_int (bbox.y1);
3911 CAMLreturn (ret_v);
3914 CAMLprim value ml_setaalevel (value level_v)
3916 CAMLparam1 (level_v);
3918 state.aalevel = Int_val (level_v);
3919 CAMLreturn (Val_unit);
3922 #pragma GCC diagnostic push
3923 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3924 #include <X11/Xlib.h>
3925 #pragma GCC diagnostic pop
3927 #include <GL/glx.h>
3929 static struct {
3930 Window wid;
3931 Display *dpy;
3932 GLXContext ctx;
3933 XVisualInfo *visual;
3934 } glx;
3936 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3938 CAMLparam3 (display_v, wid_v, screen_v);
3939 int attribs[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
3941 glx.dpy = XOpenDisplay (String_val (display_v));
3942 if (!glx.dpy) {
3943 caml_failwith ("XOpenDisplay");
3946 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3947 if (!glx.visual) {
3948 XCloseDisplay (glx.dpy);
3949 caml_failwith ("glXChooseVisual");
3952 glx.wid = Int_val (wid_v);
3953 CAMLreturn (Val_int (glx.visual->visualid));
3956 CAMLprim value ml_glxcompleteinit (value unit_v)
3958 CAMLparam1 (unit_v);
3960 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3961 if (!glx.ctx) {
3962 caml_failwith ("glXCreateContext");
3965 XFree (glx.visual);
3966 glx.visual = NULL;
3968 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3969 glXDestroyContext (glx.dpy, glx.ctx);
3970 glx.ctx = NULL;
3971 caml_failwith ("glXMakeCurrent");
3973 CAMLreturn (Val_unit);
3976 CAMLprim value ml_swapb (value unit_v)
3978 CAMLparam1 (unit_v);
3979 glXSwapBuffers (glx.dpy, glx.wid);
3980 CAMLreturn (Val_unit);
3983 #include "keysym2ucs.c"
3985 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3987 CAMLparam1 (keysym_v);
3988 CAMLlocal1 (str_v);
3989 KeySym keysym = Int_val (keysym_v);
3990 Rune rune;
3991 int len;
3992 char buf[5];
3994 rune = keysym2ucs (keysym);
3995 len = fz_runetochar (buf, rune);
3996 buf[len] = 0;
3997 str_v = caml_copy_string (buf);
3998 CAMLreturn (str_v);
4001 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4003 CAMLprim value ml_platform (value unit_v)
4005 CAMLparam1 (unit_v);
4006 CAMLlocal2 (tup_v, arr_v);
4007 int platid = piunknown;
4008 struct utsname buf;
4010 #if defined __linux__
4011 platid = pilinux;
4012 #elif defined __CYGWIN__
4013 platid = picygwin;
4014 #elif defined __DragonFly__ || defined __FreeBSD__
4015 || defined __OpenBSD__ || defined __NetBSD__
4016 platid = pibsd;
4017 #elif defined __sun__
4018 platid = pisun;
4019 #elif defined __APPLE__
4020 platid = piosx;
4021 #endif
4022 if (uname (&buf)) err (1, "uname");
4024 tup_v = caml_alloc_tuple (2);
4026 char const *sar[] = {
4027 buf.sysname,
4028 buf.release,
4029 buf.version,
4030 buf.machine,
4031 NULL
4033 arr_v = caml_copy_string_array (sar);
4035 Field (tup_v, 0) = Val_int (platid);
4036 Field (tup_v, 1) = arr_v;
4037 CAMLreturn (tup_v);
4040 CAMLprim value ml_cloexec (value fd_v)
4042 CAMLparam1 (fd_v);
4043 int fd = Int_val (fd_v);
4045 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4046 uerror ("fcntl", Nothing);
4048 CAMLreturn (Val_unit);
4051 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4053 CAMLparam2 (w_v, h_v);
4054 CAMLlocal1 (ret_v);
4055 struct pbo *pbo;
4056 int w = Int_val (w_v);
4057 int h = Int_val (h_v);
4058 int cs = Int_val (cs_v);
4060 if (state.pbo_usable) {
4061 pbo = calloc (sizeof (*pbo), 1);
4062 if (!pbo) {
4063 err (1, "calloc pbo");
4066 switch (cs) {
4067 case 0:
4068 case 1:
4069 pbo->size = w*h*4;
4070 break;
4071 case 2:
4072 pbo->size = w*h*2;
4073 break;
4074 default:
4075 errx (1, "ml_getpbo: invalid colorspace %d", cs);
4078 state.glGenBuffersARB (1, &pbo->id);
4079 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4080 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4081 NULL, GL_STREAM_DRAW);
4082 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4083 GL_READ_WRITE);
4084 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4085 if (!pbo->ptr) {
4086 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4087 state.glDeleteBuffersARB (1, &pbo->id);
4088 free (pbo);
4089 ret_v = caml_copy_string ("0");
4091 else {
4092 int res;
4093 char *s;
4095 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4096 if (res < 0) {
4097 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4099 s = malloc (res+1);
4100 if (!s) {
4101 err (1, "malloc %d bytes failed", res+1);
4103 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4104 if (res < 0) {
4105 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4107 ret_v = caml_copy_string (s);
4108 free (s);
4111 else {
4112 ret_v = caml_copy_string ("0");
4114 CAMLreturn (ret_v);
4117 CAMLprim value ml_freepbo (value s_v)
4119 CAMLparam1 (s_v);
4120 char *s = String_val (s_v);
4121 struct tile *tile = parse_pointer ("ml_freepbo", s);
4123 if (tile->pbo) {
4124 state.glDeleteBuffersARB (1, &tile->pbo->id);
4125 tile->pbo->id = -1;
4126 tile->pbo->ptr = NULL;
4127 tile->pbo->size = -1;
4129 CAMLreturn (Val_unit);
4132 CAMLprim value ml_unmappbo (value s_v)
4134 CAMLparam1 (s_v);
4135 char *s = String_val (s_v);
4136 struct tile *tile = parse_pointer ("ml_unmappbo", s);
4138 if (tile->pbo) {
4139 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4140 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4141 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4143 tile->pbo->ptr = NULL;
4144 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4146 CAMLreturn (Val_unit);
4149 static void setuppbo (void)
4151 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4152 state.pbo_usable = GGPA (glBindBufferARB)
4153 && GGPA (glUnmapBufferARB)
4154 && GGPA (glMapBufferARB)
4155 && GGPA (glBufferDataARB)
4156 && GGPA (glGenBuffersARB)
4157 && GGPA (glDeleteBuffersARB);
4158 #undef GGPA
4161 CAMLprim value ml_pbo_usable (value unit_v)
4163 CAMLparam1 (unit_v);
4164 CAMLreturn (Val_bool (state.pbo_usable));
4167 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4169 CAMLparam3 (ptr_v, x_v, y_v);
4170 CAMLlocal2 (ret_v, tup_v);
4171 struct page *page;
4172 char *s = String_val (ptr_v);
4173 int x = Int_val (x_v), y = Int_val (y_v);
4174 struct pagedim *pdim;
4175 fz_point p;
4176 fz_matrix ctm;
4178 page = parse_pointer ("ml_unproject", s);
4179 pdim = &state.pagedims[page->pdimno];
4181 ret_v = Val_int (0);
4182 if (trylock ("ml_unproject")) {
4183 goto done;
4186 switch (page->type) {
4187 case DPDF:
4188 trimctm (page->u.pdfpage, page->pdimno);
4189 break;
4191 default:
4192 break;
4194 p.x = x + pdim->bounds.x0;
4195 p.y = y + pdim->bounds.y0;
4197 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4198 fz_invert_matrix (&ctm, &ctm);
4199 fz_transform_point (&p, &ctm);
4201 tup_v = caml_alloc_tuple (2);
4202 ret_v = caml_alloc_small (1, 1);
4203 Field (tup_v, 0) = Val_int (p.x);
4204 Field (tup_v, 1) = Val_int (p.y);
4205 Field (ret_v, 0) = tup_v;
4207 unlock ("ml_unproject");
4208 done:
4209 CAMLreturn (ret_v);
4212 static void makestippletex (void)
4214 const char pixels[] = "\xff\xff\0\0";
4215 glGenTextures (1, &state.stid);
4216 glBindTexture (GL_TEXTURE_1D, state.stid);
4217 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4218 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4219 glTexImage1D (
4220 GL_TEXTURE_1D,
4222 GL_ALPHA,
4225 GL_ALPHA,
4226 GL_UNSIGNED_BYTE,
4227 pixels
4231 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4233 return caml_copy_string (FZ_VERSION);
4236 #ifdef USE_FONTCONFIG
4237 static struct {
4238 int inited;
4239 FcConfig *config;
4240 } fc;
4242 static fz_font *fc_load_system_font_func (fz_context *ctx,
4243 const char *name,
4244 int bold,
4245 int italic,
4246 int UNUSED_ATTR needs_exact_metrics)
4248 char *buf;
4249 size_t i, size;
4250 fz_font *font;
4251 FcChar8 *path;
4252 FcResult result;
4253 FcPattern *pat, *pat1;
4255 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4256 name, bold, italic, needs_exact_metrics);
4257 if (!fc.inited) {
4258 fc.inited = 1;
4259 fc.config = FcInitLoadConfigAndFonts ();
4260 if (!fc.config) {
4261 lprintf ("FcInitLoadConfigAndFonts failed\n");
4262 return NULL;
4265 if (!fc.config) return NULL;
4267 size = strlen (name);
4268 if (bold) size += sizeof (":bold") - 1;
4269 if (italic) size += sizeof (":italic") - 1;
4270 size += 1;
4272 buf = malloc (size);
4273 if (!buf) {
4274 err (1, "malloc %zu failed", size);
4277 strcpy (buf, name);
4278 if (bold && italic) {
4279 strcat (buf, ":bold:italic");
4281 else {
4282 if (bold) strcat (buf, ":bold");
4283 if (italic) strcat (buf, ":italic");
4285 for (i = 0; i < size; ++i) {
4286 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4289 lprintf ("fcbuf=%s\n", buf);
4290 pat = FcNameParse ((FcChar8 *) buf);
4291 if (!pat) {
4292 printd ("emsg FcNameParse failed\n");
4293 free (buf);
4294 return NULL;
4297 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4298 printd ("emsg FcConfigSubstitute failed\n");
4299 free (buf);
4300 return NULL;
4302 FcDefaultSubstitute (pat);
4304 pat1 = FcFontMatch (fc.config, pat, &result);
4305 if (!pat1) {
4306 printd ("emsg FcFontMatch failed\n");
4307 FcPatternDestroy (pat);
4308 free (buf);
4309 return NULL;
4312 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4313 printd ("emsg FcPatternGetString failed\n");
4314 FcPatternDestroy (pat);
4315 FcPatternDestroy (pat1);
4316 free (buf);
4317 return NULL;
4320 #if 0
4321 printd ("emsg name=%s path=%s\n", name, path);
4322 #endif
4323 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4324 FcPatternDestroy (pat);
4325 FcPatternDestroy (pat1);
4326 free (buf);
4327 return font;
4329 #endif
4331 CAMLprim value ml_init (value csock_v, value params_v)
4333 CAMLparam2 (csock_v, params_v);
4334 CAMLlocal2 (trim_v, fuzz_v);
4335 int ret;
4336 int texcount;
4337 char *fontpath;
4338 int colorspace;
4339 int mustoresize;
4340 int haspboext;
4341 struct sigaction sa;
4343 state.csock = Int_val (csock_v);
4344 state.rotate = Int_val (Field (params_v, 0));
4345 state.fitmodel = Int_val (Field (params_v, 1));
4346 trim_v = Field (params_v, 2);
4347 texcount = Int_val (Field (params_v, 3));
4348 state.sliceheight = Int_val (Field (params_v, 4));
4349 mustoresize = Int_val (Field (params_v, 5));
4350 colorspace = Int_val (Field (params_v, 6));
4351 fontpath = String_val (Field (params_v, 7));
4353 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4354 if (!state.trimcachepath) {
4355 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4356 strerror (errno));
4358 haspboext = Bool_val (Field (params_v, 9));
4360 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4362 #ifdef USE_FONTCONFIG
4363 fz_install_load_system_font_funcs (
4364 state.ctx, fc_load_system_font_func, NULL
4366 #endif
4368 state.trimmargins = Bool_val (Field (trim_v, 0));
4369 fuzz_v = Field (trim_v, 1);
4370 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4371 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4372 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4373 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4375 set_tex_params (colorspace);
4377 if (*fontpath) {
4378 #ifndef USE_FONTCONFIG
4379 state.face = load_font (fontpath);
4380 #else
4381 FcChar8 *path;
4382 FcResult result;
4383 char *buf = fontpath;
4384 FcPattern *pat, *pat1;
4386 fc.inited = 1;
4387 fc.config = FcInitLoadConfigAndFonts ();
4388 if (!fc.config) {
4389 errx (1, "FcInitLoadConfigAndFonts failed");
4392 pat = FcNameParse ((FcChar8 *) buf);
4393 if (!pat) {
4394 errx (1, "FcNameParse failed");
4397 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4398 errx (1, "FcConfigSubstitute failed");
4400 FcDefaultSubstitute (pat);
4402 pat1 = FcFontMatch (fc.config, pat, &result);
4403 if (!pat1) {
4404 errx (1, "FcFontMatch failed");
4407 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4408 errx (1, "FcPatternGetString failed");
4411 state.face = load_font ((char *) path);
4412 FcPatternDestroy (pat);
4413 FcPatternDestroy (pat1);
4414 #endif
4416 else {
4417 unsigned int len;
4418 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
4420 state.face = load_builtin_font (base, len);
4422 if (!state.face) _exit (1);
4424 realloctexts (texcount);
4426 if (haspboext) {
4427 setuppbo ();
4430 makestippletex ();
4432 #ifdef __CYGWIN__
4433 sa.sa_handler = SIG_IGN;
4434 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4435 #else
4436 sa.sa_handler = SIG_DFL;
4437 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
4438 #endif
4439 if (sigemptyset (&sa.sa_mask)) {
4440 err (1, "sigemptyset");
4442 if (sigaction (SIGCHLD, &sa, NULL)) {
4443 err (1, "sigaction");
4446 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4447 if (ret) {
4448 errx (1, "pthread_create: %s", strerror (ret));
4451 CAMLreturn (Val_unit);