Remove dysfunctional (for OCaml) automatic dependency generation
[llpp.git] / link.c
blobf1ce9ad19589416cad35a2138b40fb7040b2b57b
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(pdf_document *doc, pdf_obj **page_objs)
956 #error broken for now
959 static void
960 pdf_load_page_objs(pdf_document *doc, pdf_obj **page_objs)
962 pdf_obj *pages = pdf_dict_getp(pdf_trailer(doc), "Root/Pages");
963 int page_no = 1;
964 pdf_load_page_objs_rec(doc, pages, &page_no, page_objs);
966 #endif
968 static void initpdims (void)
970 double start, end;
971 FILE *trimf = NULL;
972 fz_rect rootmediabox;
973 int pageno, trim, show;
974 int trimw = 0, cxcount;
976 start = now ();
978 if (state.trimmargins && state.trimcachepath) {
979 trimf = fopen (state.trimcachepath, "rb");
980 if (!trimf) {
981 trimf = fopen (state.trimcachepath, "wb");
982 trimw = 1;
986 if (state.trimmargins || state.type == DPDF || !state.cxack)
987 cxcount = state.pagecount;
988 else
989 cxcount = MIN (state.pagecount, 1);
991 if (state.type == DPDF) {
992 pdf_obj *obj;
993 obj = pdf_dict_getp (pdf_trailer (state.u.pdf),
994 "Root/Pages/MediaBox");
995 pdf_to_rect (state.ctx, obj, &rootmediabox);
998 #ifdef SUMATRA_LOOKUP
999 if (state.type == DPDF
1000 && (!state.pdflut.objs || state.pdflut.pdf != state.u.pdf)) {
1001 state.pdflut.objs = malloc (sizeof (*state.pdflut.objs) * cxcount);
1002 if (!state.pdflut.objs) {
1003 err (1, "malloc pageobjs %zu %d %zu failed",
1004 sizeof (*state.pdflut.objs), cxcount,
1005 sizeof (*state.pdflut.objs) * cxcount);
1007 state.pdflut.count = cxcount;
1008 pdf_load_page_objs (state.u.pdf, state.pdflut.objs);
1009 state.pdflut.pdf = state.u.pdf;
1011 #endif
1013 for (pageno = 0; pageno < cxcount; ++pageno) {
1014 int rotate = 0;
1015 struct pagedim *p;
1016 fz_rect mediabox;
1018 switch (state.type) {
1019 case DPDF: {
1020 pdf_document *pdf = state.u.pdf;
1021 pdf_obj *pageref, *pageobj;
1023 #ifdef SUMATRA_LOOKUP
1024 pageref = state.pdflut.objs[pageno];
1025 #else
1026 pageref = pdf_lookup_page_obj (pdf, pageno);
1027 #endif
1028 pageobj = pdf_resolve_indirect (pageref);
1030 if (state.trimmargins) {
1031 pdf_obj *obj;
1032 pdf_page *page;
1034 fz_try (state.ctx) {
1035 page = pdf_load_page (pdf, pageno);
1036 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
1037 trim = state.trimanew || !obj;
1038 if (trim) {
1039 fz_rect rect;
1040 fz_matrix ctm;
1041 fz_device *dev;
1043 dev = fz_new_bbox_device (state.ctx, &rect);
1044 dev->hints |= FZ_IGNORE_SHADE;
1045 fz_invert_matrix (&ctm, &page->ctm);
1046 pdf_run_page (pdf, page, dev, &fz_identity, NULL);
1047 fz_free_device (dev);
1049 rect.x0 += state.trimfuzz.x0;
1050 rect.x1 += state.trimfuzz.x1;
1051 rect.y0 += state.trimfuzz.y0;
1052 rect.y1 += state.trimfuzz.y1;
1053 fz_transform_rect (&rect, &ctm);
1054 fz_intersect_rect (&rect, &page->mediabox);
1056 if (fz_is_empty_rect (&rect)) {
1057 mediabox = page->mediabox;
1059 else {
1060 mediabox = rect;
1063 obj = pdf_new_array (pdf, 4);
1064 pdf_array_push (obj, pdf_new_real (pdf, mediabox.x0));
1065 pdf_array_push (obj, pdf_new_real (pdf, mediabox.y0));
1066 pdf_array_push (obj, pdf_new_real (pdf, mediabox.x1));
1067 pdf_array_push (obj, pdf_new_real (pdf, mediabox.y1));
1068 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
1070 else {
1071 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
1072 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
1073 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
1074 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
1077 rotate = page->rotate;
1078 pdf_free_page (pdf, page);
1080 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
1081 if (show) {
1082 printd ("progress %f Trimming %d",
1083 (double) (pageno + 1) / state.pagecount,
1084 pageno + 1);
1087 fz_catch (state.ctx) {
1088 fprintf (stderr, "failed to load page %d\n", pageno+1);
1091 else {
1092 int empty = 0;
1093 fz_rect cropbox;
1095 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "MediaBox"),
1096 &mediabox);
1097 if (fz_is_empty_rect (&mediabox)) {
1098 mediabox.x0 = 0;
1099 mediabox.y0 = 0;
1100 mediabox.x1 = 612;
1101 mediabox.y1 = 792;
1102 empty = 1;
1105 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "CropBox"),
1106 &cropbox);
1107 if (!fz_is_empty_rect (&cropbox)) {
1108 if (empty) {
1109 mediabox = cropbox;
1111 else {
1112 fz_intersect_rect (&mediabox, &cropbox);
1115 else {
1116 if (empty) {
1117 if (fz_is_empty_rect (&rootmediabox)) {
1118 fprintf (stderr,
1119 "cannot find page size for page %d\n",
1120 pageno+1);
1122 else {
1123 mediabox = rootmediabox;
1127 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
1129 break;
1132 case DXPS:
1134 xps_page *page;
1136 fz_try (state.ctx) {
1137 page = xps_load_page (state.u.xps, pageno);
1138 xps_bound_page (state.u.xps, page, &mediabox);
1139 rotate = 0;
1140 if (state.trimmargins) {
1141 fz_rect rect;
1142 fz_device *dev;
1144 dev = fz_new_bbox_device (state.ctx, &rect);
1145 dev->hints |= FZ_IGNORE_SHADE;
1146 xps_run_page (state.u.xps, page, dev,
1147 &fz_identity, NULL);
1148 fz_free_device (dev);
1150 rect.x0 += state.trimfuzz.x0;
1151 rect.x1 += state.trimfuzz.x1;
1152 rect.y0 += state.trimfuzz.y0;
1153 rect.y1 += state.trimfuzz.y1;
1154 fz_intersect_rect (&rect, &mediabox);
1156 if (!fz_is_empty_rect (&rect)) {
1157 mediabox = rect;
1160 xps_free_page (state.u.xps, page);
1161 if (!state.cxack) {
1162 printd ("progress %f loading %d",
1163 (double) (pageno + 1) / state.pagecount,
1164 pageno + 1);
1167 fz_catch (state.ctx) {
1170 break;
1172 case DCBZ:
1174 rotate = 0;
1175 mediabox.x0 = 0;
1176 mediabox.y0 = 0;
1177 mediabox.x1 = 900;
1178 mediabox.y1 = 900;
1179 if (state.trimmargins && trimw) {
1180 cbz_page *page;
1182 fz_try (state.ctx) {
1183 page = cbz_load_page (state.u.cbz, pageno);
1184 cbz_bound_page (state.u.cbz, page, &mediabox);
1185 cbz_free_page (state.u.cbz, page);
1186 printd ("progress %f Trimming %d",
1187 (double) (pageno + 1) / state.pagecount,
1188 pageno + 1);
1190 fz_catch (state.ctx) {
1191 fprintf (stderr, "failed to load page %d\n", pageno+1);
1193 if (trimf) {
1194 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1195 if (n - 1) {
1196 err (1, "fwrite trim mediabox");
1200 else {
1201 if (trimf) {
1202 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1203 if (n - 1) {
1204 err (1, "fread trim mediabox");
1207 else {
1208 if (state.cxack) {
1209 cbz_page *page;
1210 fz_try (state.ctx) {
1211 page = cbz_load_page (state.u.cbz, pageno);
1212 cbz_bound_page (state.u.cbz, page, &mediabox);
1213 cbz_free_page (state.u.cbz, page);
1215 fz_catch (state.ctx) {
1216 fprintf (stderr, "failed to load cbz page\n");
1222 break;
1224 case DIMG:
1226 image_page *page;
1228 rotate = 0;
1229 mediabox.x0 = 0;
1230 mediabox.y0 = 0;
1231 mediabox.x1 = 900;
1232 mediabox.y1 = 900;
1234 fz_try (state.ctx) {
1235 page = image_load_page (state.u.img, pageno);
1236 image_bound_page (state.u.img, page, &mediabox);
1237 image_free_page (state.u.img, page);
1239 fz_catch (state.ctx) {
1240 fprintf (stderr, "failed to load page %d\n", pageno+1);
1243 break;
1245 default:
1246 ARSERT (0 && state.type);
1249 if (state.pagedimcount == 0
1250 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1251 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1252 size_t size;
1254 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1255 state.pagedims = realloc (state.pagedims, size);
1256 if (!state.pagedims) {
1257 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1258 size, state.pagedimcount + 1);
1261 p = &state.pagedims[state.pagedimcount++];
1262 p->rotate = rotate;
1263 p->mediabox = mediabox;
1264 p->pageno = pageno;
1267 end = now ();
1268 if (state.trimmargins) {
1269 printd ("progress 1 Trimmed %d pages in %f seconds",
1270 state.pagecount, end - start);
1272 else {
1273 printd ("vmsg Processed %d pages in %f seconds",
1274 state.pagecount, end - start);
1276 state.trimanew = 0;
1277 if (trimf) {
1278 if (fclose (trimf)) {
1279 err (1, "fclose");
1284 static void layout (void)
1286 int pindex;
1287 fz_rect box;
1288 fz_matrix ctm, rm;
1289 struct pagedim *p = p;
1290 double zw, w, maxw = 0.0, zoom = zoom;
1292 if (state.pagedimcount == 0) return;
1294 switch (state.fitmodel) {
1295 case FitProportional:
1296 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1297 double x0, x1;
1299 p = &state.pagedims[pindex];
1300 fz_rotate (&rm, p->rotate + state.rotate);
1301 box = p->mediabox;
1302 fz_transform_rect (&box, &rm);
1304 x0 = MIN (box.x0, box.x1);
1305 x1 = MAX (box.x0, box.x1);
1307 w = x1 - x0;
1308 maxw = MAX (w, maxw);
1309 zoom = state.w / maxw;
1311 break;
1313 case FitPage:
1314 maxw = state.w;
1315 break;
1317 case FitWidth:
1318 break;
1320 default:
1321 ARSERT (0 && state.fitmodel);
1324 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1325 fz_rect rect;
1326 fz_matrix tm, sm;
1328 p = &state.pagedims[pindex];
1329 fz_rotate (&ctm, state.rotate);
1330 fz_rotate (&rm, p->rotate + state.rotate);
1331 box = p->mediabox;
1332 fz_transform_rect (&box, &rm);
1333 w = box.x1 - box.x0;
1334 switch (state.fitmodel) {
1335 case FitProportional:
1336 p->left = ((maxw - w) * zoom) / 2.0;
1337 break;
1338 case FitPage:
1340 double zh, h;
1341 zw = maxw / w;
1342 h = box.y1 - box.y0;
1343 zh = state.h / h;
1344 zoom = MIN (zw, zh);
1345 p->left = (maxw - (w * zoom)) / 2.0;
1347 break;
1348 case FitWidth:
1349 p->left = 0;
1350 zoom = state.w / w;
1351 break;
1354 fz_scale (&p->zoomctm, zoom, zoom);
1355 fz_concat (&ctm, &p->zoomctm, &ctm);
1357 fz_rotate (&rm, p->rotate);
1358 p->pagebox = p->mediabox;
1359 fz_transform_rect (&p->pagebox, &rm);
1360 p->pagebox.x1 -= p->pagebox.x0;
1361 p->pagebox.y1 -= p->pagebox.y0;
1362 p->pagebox.x0 = 0;
1363 p->pagebox.y0 = 0;
1364 rect = p->pagebox;
1365 fz_transform_rect (&rect, &ctm);
1366 fz_round_rect (&p->bounds, &rect);
1367 p->ctm = ctm;
1369 fz_translate (&tm, 0, -p->mediabox.y1);
1370 fz_scale (&sm, zoom, -zoom);
1371 fz_concat (&ctm, &tm, &sm);
1372 fz_concat (&p->lctm, &ctm, &rm);
1374 p->tctmready = 0;
1377 do {
1378 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1379 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1380 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1381 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1382 int boundw = x1 - x0;
1383 int boundh = y1 - y0;
1385 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1386 } while (p-- != state.pagedims);
1389 static
1390 struct anchor { int n; int x; int y; int w; int h; }
1391 desttoanchor (fz_link_dest *dest)
1393 int i;
1394 struct anchor a;
1395 struct pagedim *pdim = state.pagedims;
1397 a.n = -1;
1398 a.x = 0;
1399 a.y = 0;
1400 for (i = 0; i < state.pagedimcount; ++i) {
1401 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1402 break;
1403 pdim = &state.pagedims[i];
1405 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1406 fz_point p;
1407 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1408 p.x = dest->ld.gotor.lt.x;
1409 else
1410 p.x = 0.0;
1411 p.y = dest->ld.gotor.lt.y;
1412 fz_transform_point (&p, &pdim->lctm);
1413 a.x = p.x;
1414 a.y = p.y;
1416 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1417 double x0, x1, y0, y1;
1419 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1420 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1421 a.w = x1 - x0;
1422 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1423 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1424 a.h = y1 - y0;
1425 a.n = dest->ld.gotor.page;
1427 return a;
1430 static void recurse_outline (fz_outline *outline, int level)
1432 while (outline) {
1433 switch (outline->dest.kind) {
1434 case FZ_LINK_GOTO:
1436 struct anchor a = desttoanchor (&outline->dest);
1438 if (a.n >= 0) {
1439 printd ("o %d %d %d %d %s",
1440 level, a.n, a.y, a.h, outline->title);
1443 break;
1445 case FZ_LINK_URI:
1446 printd ("ou %d %" FMT_s " %s %s", level,
1447 strlen (outline->title), outline->title,
1448 outline->dest.ld.uri.uri);
1449 break;
1451 case FZ_LINK_NONE:
1452 printd ("on %d %s", level, outline->title);
1453 break;
1455 default:
1456 printd ("emsg Unhandled outline kind %d for %s\n",
1457 outline->dest.kind, outline->title);
1458 break;
1460 if (outline->down) {
1461 recurse_outline (outline->down, level + 1);
1463 outline = outline->next;
1467 static void process_outline (void)
1469 fz_outline *outline;
1471 if (!state.needoutline) return;
1473 state.needoutline = 0;
1474 switch (state.type) {
1475 case DPDF:
1476 outline = pdf_load_outline (state.u.pdf);
1477 break;
1478 case DXPS:
1479 outline = xps_load_outline (state.u.xps);
1480 break;
1481 default:
1482 outline = NULL;
1483 break;
1485 if (outline) {
1486 recurse_outline (outline, 0);
1487 fz_free_outline (state.ctx, outline);
1491 static char *strofspan (fz_text_span *span)
1493 char *p;
1494 char utf8[10];
1495 fz_text_char *ch;
1496 size_t size = 0, cap = 80;
1498 p = malloc (cap + 1);
1499 if (!p) return NULL;
1501 for (ch = span->text; ch < span->text + span->len; ++ch) {
1502 int n = fz_runetochar (utf8, ch->c);
1503 if (size + n > cap) {
1504 cap *= 2;
1505 p = realloc (p, cap + 1);
1506 if (!p) return NULL;
1509 memcpy (p + size, utf8, n);
1510 size += n;
1512 p[size] = 0;
1513 return p;
1516 static int matchspan (regex_t *re, fz_text_page UNUSED_ATTR *page,
1517 fz_text_span *span, fz_matrix UNUSED_ATTR ctm,
1518 int stop, int pageno, double start)
1520 int ret;
1521 char *p;
1522 regmatch_t rm;
1523 int a, b, c;
1524 fz_rect sb, eb;
1525 fz_point p1, p2, p3, p4;
1527 p = strofspan (span);
1528 if (!p) return -1;
1530 ret = regexec (re, p, 1, &rm, 0);
1531 if (ret) {
1532 free (p);
1533 if (ret != REG_NOMATCH) {
1534 size_t size;
1535 char errbuf[80];
1536 size = regerror (ret, re, errbuf, sizeof (errbuf));
1537 printd ("msg regexec error `%.*s'",
1538 (int) size, errbuf);
1539 return -1;
1541 return 0;
1543 else {
1544 int l = span->len;
1546 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1547 c += fz_runelen (span->text[a].c);
1549 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1550 c += fz_runelen (span->text[b].c);
1553 if (fz_runelen (span->text[b].c) > 1) {
1554 b = MAX (0, b-1);
1557 fz_text_char_bbox (&sb, span, a);
1558 fz_text_char_bbox (&eb, span, b);
1560 p1.x = sb.x0;
1561 p1.y = sb.y0;
1562 p2.x = eb.x1;
1563 p2.y = sb.y0;
1564 p3.x = eb.x1;
1565 p3.y = eb.y1;
1566 p4.x = sb.x0;
1567 p4.y = eb.y1;
1569 if (!stop) {
1570 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1571 pageno, 1,
1572 p1.x, p1.y,
1573 p2.x, p2.y,
1574 p3.x, p3.y,
1575 p4.x, p4.y);
1577 printd ("progress 1 found at %d `%.*s' in %f sec",
1578 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1579 now () - start);
1581 else {
1582 printd ("match %d %d %f %f %f %f %f %f %f %f",
1583 pageno, 2,
1584 p1.x, p1.y,
1585 p2.x, p2.y,
1586 p3.x, p3.y,
1587 p4.x, p4.y);
1589 free (p);
1590 return 1;
1594 static int compareblocks (const void *l, const void *r)
1596 fz_text_block const *ls = l;
1597 fz_text_block const* rs = r;
1598 return ls->bbox.y0 - rs->bbox.y0;
1601 /* wishful thinking function */
1602 static void search (regex_t *re, int pageno, int y, int forward)
1604 int i, j;
1605 fz_matrix ctm;
1606 fz_device *tdev;
1607 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1608 fz_text_page *text;
1609 fz_text_sheet *sheet;
1610 struct pagedim *pdim, *pdimprev;
1611 int stop = 0, niters = 0;
1612 double start, end;
1614 if (!(state.type == DPDF || state.type == DXPS))
1615 return;
1617 start = now ();
1618 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1619 if (niters++ == 5) {
1620 niters = 0;
1621 if (hasdata ()) {
1622 printd ("progress 1 attention requested aborting search at %d",
1623 pageno);
1624 stop = 1;
1626 else {
1627 printd ("progress %f searching in page %d",
1628 (double) (pageno + 1) / state.pagecount,
1629 pageno);
1632 pdimprev = NULL;
1633 for (i = 0; i < state.pagedimcount; ++i) {
1634 pdim = &state.pagedims[i];
1635 if (pdim->pageno == pageno) {
1636 goto found;
1638 if (pdim->pageno > pageno) {
1639 pdim = pdimprev;
1640 goto found;
1642 pdimprev = pdim;
1644 pdim = pdimprev;
1645 found:
1647 sheet = fz_new_text_sheet (state.ctx);
1648 text = fz_new_text_page (state.ctx);
1649 tdev = fz_new_text_device (state.ctx, sheet, text);
1651 switch (state.type) {
1652 case DPDF:
1653 u.ptr = NULL;
1654 fz_try (state.ctx) {
1655 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1656 trimctm (u.pdfpage, pdim - state.pagedims);
1657 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1658 fz_begin_page (tdev, &fz_infinite_rect, &ctm);
1659 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1660 fz_end_page (tdev);
1662 fz_catch (state.ctx) {
1663 fz_free_device (tdev);
1664 u.ptr = NULL;
1665 goto nextiter;
1667 break;
1669 case DXPS:
1670 u.xpspage = xps_load_page (state.u.xps, pageno);
1671 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1672 break;
1674 default:
1675 ARSERT (0 && state.type);
1678 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1679 fz_free_device (tdev);
1681 for (j = 0; j < text->len; ++j) {
1682 int k;
1683 fz_page_block *pb;
1684 fz_text_block *block;
1686 pb = &text->blocks[forward ? j : text->len - 1 - j];
1687 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1688 block = pb->u.text;
1690 for (k = 0; k < block->len; ++k) {
1691 fz_text_line *line;
1692 fz_text_span *span;
1694 if (forward) {
1695 line = &block->lines[k];
1696 if (line->bbox.y0 < y + 1) continue;
1698 else {
1699 line = &block->lines[block->len - 1 - k];
1700 if (line->bbox.y0 > y - 1) continue;
1703 for (span = line->first_span; span; span = span->next) {
1704 switch (matchspan (re, text, span, ctm,
1705 stop, pageno, start)) {
1706 case 0: break;
1707 case 1: stop = 1; break;
1708 case -1: stop = 1; goto endloop;
1713 nextiter:
1714 if (forward) {
1715 pageno += 1;
1716 y = 0;
1718 else {
1719 pageno -= 1;
1720 y = INT_MAX;
1722 endloop:
1723 fz_free_text_page (state.ctx, text);
1724 fz_free_text_sheet (state.ctx, sheet);
1725 if (u.ptr) {
1726 state.freepage (u.ptr);
1729 end = now ();
1730 if (!stop) {
1731 printd ("progress 1 no matches %f sec", end - start);
1733 printd ("clearrects");
1736 static void set_tex_params (int colorspace)
1738 union {
1739 unsigned char b;
1740 unsigned int s;
1741 } endianness = {1};
1743 switch (colorspace) {
1744 case 0:
1745 state.texiform = GL_RGBA8;
1746 state.texform = GL_RGBA;
1747 state.texty = GL_UNSIGNED_BYTE;
1748 state.colorspace = fz_device_rgb (state.ctx);
1749 break;
1750 case 1:
1751 state.texiform = GL_RGBA8;
1752 state.texform = GL_BGRA;
1753 state.texty = endianness.s > 1
1754 ? GL_UNSIGNED_INT_8_8_8_8
1755 : GL_UNSIGNED_INT_8_8_8_8_REV;
1756 state.colorspace = fz_device_bgr (state.ctx);
1757 break;
1758 case 2:
1759 state.texiform = GL_LUMINANCE_ALPHA;
1760 state.texform = GL_LUMINANCE_ALPHA;
1761 state.texty = GL_UNSIGNED_BYTE;
1762 state.colorspace = fz_device_gray (state.ctx);
1763 break;
1764 default:
1765 errx (1, "invalid colorspce %d", colorspace);
1769 static void realloctexts (int texcount)
1771 size_t size;
1773 if (texcount == state.texcount) return;
1775 if (texcount < state.texcount) {
1776 glDeleteTextures (state.texcount - texcount,
1777 state.texids + texcount);
1780 size = texcount * sizeof (*state.texids);
1781 state.texids = realloc (state.texids, size);
1782 if (!state.texids) {
1783 err (1, "realloc texids %" FMT_s, size);
1786 size = texcount * sizeof (*state.texowners);
1787 state.texowners = realloc (state.texowners, size);
1788 if (!state.texowners) {
1789 err (1, "realloc texowners %" FMT_s, size);
1791 if (texcount > state.texcount) {
1792 int i;
1794 glGenTextures (texcount - state.texcount,
1795 state.texids + state.texcount);
1796 for (i = state.texcount; i < texcount; ++i) {
1797 state.texowners[i].w = -1;
1798 state.texowners[i].slice = NULL;
1801 state.texcount = texcount;
1802 state.texindex = 0;
1805 static char *mbtoutf8 (char *s)
1807 char *p, *r;
1808 wchar_t *tmp;
1809 size_t i, ret, len;
1811 len = mbstowcs (NULL, s, strlen (s));
1812 if (len == 0) {
1813 return s;
1815 else {
1816 if (len == (size_t) -1) {
1817 return s;
1821 tmp = malloc (len * sizeof (wchar_t));
1822 if (!tmp) {
1823 return s;
1826 ret = mbstowcs (tmp, s, len);
1827 if (ret == (size_t) -1) {
1828 free (tmp);
1829 return s;
1832 len = 0;
1833 for (i = 0; i < ret; ++i) {
1834 len += fz_runelen (tmp[i]);
1837 p = r = malloc (len + 1);
1838 if (!r) {
1839 free (tmp);
1840 return s;
1843 for (i = 0; i < ret; ++i) {
1844 p += fz_runetochar (p, tmp[i]);
1846 *p = 0;
1847 free (tmp);
1848 return r;
1851 CAMLprim value ml_mbtoutf8 (value s_v)
1853 CAMLparam1 (s_v);
1854 CAMLlocal1 (ret_v);
1855 char *s, *r;
1857 s = String_val (s_v);
1858 r = mbtoutf8 (s);
1859 if (r == s) {
1860 ret_v = s_v;
1862 else {
1863 ret_v = caml_copy_string (r);
1864 free (r);
1866 CAMLreturn (ret_v);
1869 static void * mainloop (void UNUSED_ATTR *unused)
1871 char *p = NULL;
1872 int len, ret, oldlen = 0;
1874 for (;;) {
1875 len = readlen ();
1876 if (len == 0) {
1877 errx (1, "readlen returned 0");
1880 if (oldlen < len + 1) {
1881 p = realloc (p, len + 1);
1882 if (!p) {
1883 err (1, "realloc %d failed", len + 1);
1885 oldlen = len + 1;
1887 readdata (p, len);
1888 p[len] = 0;
1890 if (!strncmp ("open", p, 4)) {
1891 int wthack, off, ok = 0;
1892 char *password;
1893 char *filename;
1894 char *utf8filename;
1895 size_t filenamelen;
1897 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1898 if (ret != 2) {
1899 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1902 filename = p + 5 + off;
1903 filenamelen = strlen (filename);
1904 password = filename + filenamelen + 1;
1906 lock ("open");
1907 fz_try (state.ctx) {
1908 openxref (filename, password);
1909 ok = 1;
1911 fz_catch (state.ctx) {
1912 utf8filename = mbtoutf8 (filename);
1913 printd ("msg Could not open %s", utf8filename);
1915 if (ok) {
1916 pdfinfo ();
1917 initpdims ();
1919 unlock ("open");
1921 if (ok) {
1922 if (!wthack) {
1923 utf8filename = mbtoutf8 (filename);
1924 printd ("msg Opened %s (press h/F1 to get help)",
1925 utf8filename);
1926 if (utf8filename != filename) {
1927 free (utf8filename);
1930 state.needoutline = 1;
1933 else if (!strncmp ("cs", p, 2)) {
1934 int i, colorspace;
1936 ret = sscanf (p + 2, " %d", &colorspace);
1937 if (ret != 1) {
1938 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1940 lock ("cs");
1941 set_tex_params (colorspace);
1942 for (i = 0; i < state.texcount; ++i) {
1943 state.texowners[i].w = -1;
1944 state.texowners[i].slice = NULL;
1946 unlock ("cs");
1948 else if (!strncmp ("freepage", p, 8)) {
1949 void *ptr;
1951 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1952 if (ret != 1) {
1953 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1955 freepage (ptr);
1957 else if (!strncmp ("freetile", p, 8)) {
1958 void *ptr;
1960 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1961 if (ret != 1) {
1962 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1964 freetile (ptr);
1966 else if (!strncmp ("search", p, 6)) {
1967 int icase, pageno, y, len2, forward;
1968 char *pattern;
1969 regex_t re;
1971 ret = sscanf (p + 6, " %d %d %d %d,%n",
1972 &icase, &pageno, &y, &forward, &len2);
1973 if (ret != 4) {
1974 errx (1, "malformed search `%s' ret=%d", p, ret);
1977 pattern = p + 6 + len2;
1978 ret = regcomp (&re, pattern,
1979 REG_EXTENDED | (icase ? REG_ICASE : 0));
1980 if (ret) {
1981 char errbuf[80];
1982 size_t size;
1984 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1985 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1987 else {
1988 search (&re, pageno, y, forward);
1989 regfree (&re);
1992 else if (!strncmp ("geometry", p, 8)) {
1993 int w, h, fitmodel;
1995 printd ("clear");
1996 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1997 if (ret != 3) {
1998 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
2001 lock ("geometry");
2002 state.h = h;
2003 if (w != state.w) {
2004 int i;
2005 state.w = w;
2006 for (i = 0; i < state.texcount; ++i) {
2007 state.texowners[i].slice = NULL;
2010 state.fitmodel = fitmodel;
2011 layout ();
2012 process_outline ();
2014 state.gen++;
2015 unlock ("geometry");
2016 printd ("continue %d", state.pagecount);
2018 else if (!strncmp ("reqlayout", p, 9)) {
2019 char *nameddest;
2020 int rotate, off, h;
2021 unsigned int fitmodel;
2023 printd ("clear");
2024 ret = sscanf (p + 9, " %d %u %d %n",
2025 &rotate, &fitmodel, &h, &off);
2026 if (ret != 3) {
2027 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
2029 lock ("reqlayout");
2030 if (state.rotate != rotate || state.fitmodel != fitmodel) {
2031 state.gen += 1;
2033 state.rotate = rotate;
2034 state.fitmodel = fitmodel;
2035 state.h = h;
2036 layout ();
2037 process_outline ();
2039 nameddest = p + 9 + off;
2040 if (state.type == DPDF && nameddest && *nameddest) {
2041 struct anchor a;
2042 fz_link_dest dest;
2043 pdf_obj *needle, *obj;
2045 needle = pdf_new_string (state.u.pdf, nameddest,
2046 strlen (nameddest));
2047 obj = pdf_lookup_dest (state.u.pdf, needle);
2048 if (obj) {
2049 dest = pdf_parse_link_dest (state.u.pdf, FZ_LINK_GOTO, obj);
2051 a = desttoanchor (&dest);
2052 if (a.n >= 0) {
2053 printd ("a %d %d %d", a.n, a.x, a.y);
2055 else {
2056 printd ("emsg failed to parse destination `%s'\n",
2057 nameddest);
2060 else {
2061 printd ("emsg destination `%s' not found\n",
2062 nameddest);
2064 pdf_drop_obj (needle);
2067 state.gen++;
2068 unlock ("reqlayout");
2069 printd ("continue %d", state.pagecount);
2071 else if (!strncmp ("page", p, 4)) {
2072 double a, b;
2073 struct page *page;
2074 int pageno, pindex;
2076 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
2077 if (ret != 2) {
2078 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
2081 lock ("page");
2082 a = now ();
2083 page = loadpage (pageno, pindex);
2084 b = now ();
2085 unlock ("page");
2087 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
2089 else if (!strncmp ("tile", p, 4)) {
2090 int x, y, w, h;
2091 struct page *page;
2092 struct tile *tile;
2093 double a, b;
2094 void *data;
2096 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
2097 SCN_ptr_cast (&page), &x, &y, &w, &h,
2098 SCN_ptr_cast (&data));
2099 if (ret != 6) {
2100 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
2103 lock ("tile");
2104 a = now ();
2105 tile = rendertile (page, x, y, w, h, data);
2106 b = now ();
2107 unlock ("tile");
2109 printd ("tile %d %d %" FMT_ptr " %u %f",
2110 x, y,
2111 FMT_ptr_cast (tile),
2112 tile->w * tile->h * tile->pixmap->n,
2113 b - a);
2115 else if (!strncmp ("settrim", p, 7)) {
2116 fz_irect fuzz;
2117 int trimmargins;
2119 ret = sscanf (p + 7, " %d %d %d %d %d",
2120 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
2121 if (ret != 5) {
2122 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
2124 printd ("clear");
2125 lock ("settrim");
2126 state.trimmargins = trimmargins;
2127 state.needoutline = 1;
2128 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
2129 state.trimanew = 1;
2130 state.trimfuzz = fuzz;
2132 state.pagedimcount = 0;
2133 free (state.pagedims);
2134 state.pagedims = NULL;
2135 initpdims ();
2136 layout ();
2137 process_outline ();
2138 unlock ("settrim");
2139 printd ("continue %d", state.pagecount);
2141 else if (!strncmp ("sliceh", p, 6)) {
2142 int h;
2144 ret = sscanf (p + 6, " %d", &h);
2145 if (ret != 1) {
2146 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
2148 if (h != state.sliceheight) {
2149 int i;
2151 state.sliceheight = h;
2152 for (i = 0; i < state.texcount; ++i) {
2153 state.texowners[i].w = -1;
2154 state.texowners[i].h = -1;
2155 state.texowners[i].slice = NULL;
2159 else if (!strncmp ("interrupt", p, 9)) {
2160 printd ("vmsg interrupted");
2162 else {
2163 errx (1, "unknown command %.*s", len, p);
2166 return 0;
2169 CAMLprim value ml_realloctexts (value texcount_v)
2171 CAMLparam1 (texcount_v);
2172 int ok;
2174 if (trylock ("ml_realloctexts")) {
2175 ok = 0;
2176 goto done;
2178 realloctexts (Int_val (texcount_v));
2179 ok = 1;
2180 unlock ("ml_realloctexts");
2182 done:
2183 CAMLreturn (Val_bool (ok));
2186 static void recti (int x0, int y0, int x1, int y1)
2188 GLfloat *v = state.vertices;
2190 glVertexPointer (2, GL_FLOAT, 0, v);
2191 v[0] = x0; v[1] = y0;
2192 v[2] = x1; v[3] = y0;
2193 v[4] = x0; v[5] = y1;
2194 v[6] = x1; v[7] = y1;
2195 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2198 static void showsel (struct page *page, int ox, int oy)
2200 int seen = 0;
2201 fz_irect bbox;
2202 fz_rect rect;
2203 fz_text_line *line;
2204 fz_page_block *pageb;
2205 fz_text_block *block;
2206 struct mark first, last;
2207 unsigned char selcolor[] = {15,15,15,140};
2209 first = page->fmark;
2210 last = page->lmark;
2212 if (!first.span || !last.span) return;
2214 glEnable (GL_BLEND);
2215 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2216 glColor4ubv (selcolor);
2218 ox += state.pagedims[page->pdimno].bounds.x0;
2219 oy += state.pagedims[page->pdimno].bounds.y0;
2220 for (pageb = page->text->blocks;
2221 pageb < page->text->blocks + page->text->len;
2222 ++pageb) {
2223 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2224 block = pageb->u.text;
2226 for (line = block->lines;
2227 line < block->lines + block->len;
2228 ++line) {
2229 fz_text_span *span;
2230 rect = fz_empty_rect;
2232 for (span = line->first_span; span; span = span->next) {
2233 int i, j, k;
2234 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2236 j = 0;
2237 k = span->len - 1;
2239 if (span == page->fmark.span && span == page->lmark.span) {
2240 seen = 1;
2241 j = MIN (first.i, last.i);
2242 k = MAX (first.i, last.i);
2244 else {
2245 if (span == first.span) {
2246 seen = 1;
2247 j = first.i;
2249 else if (span == last.span) {
2250 seen = 1;
2251 k = last.i;
2255 if (seen) {
2256 for (i = j; i <= k; ++i) {
2257 fz_rect bbox1;
2258 fz_union_rect (&rect,
2259 fz_text_char_bbox (&bbox1, span, i));
2261 fz_round_rect (&bbox, &rect);
2262 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2263 bbox.x0,
2264 bbox.y0,
2265 bbox.x1,
2266 bbox.y1,
2267 oy, ox);
2269 recti (bbox.x0 + ox, bbox.y0 + oy,
2270 bbox.x1 + ox, bbox.y1 + oy);
2271 if (span == last.span) {
2272 goto done;
2274 rect = fz_empty_rect;
2279 done:
2280 glDisable (GL_BLEND);
2283 #include "glfont.c"
2285 static void highlightlinks (struct page *page, int xoff, int yoff)
2287 fz_matrix ctm, tm, pm;
2288 fz_link *link, *links;
2289 GLfloat *texcoords = state.texcoords;
2290 GLfloat *vertices = state.vertices;
2292 switch (page->type) {
2293 case DPDF:
2294 links = page->u.pdfpage->links;
2295 break;
2297 case DXPS:
2298 links = page->u.xpspage->links;
2299 break;
2301 default:
2302 return;
2305 glEnable (GL_TEXTURE_1D);
2306 glEnable (GL_BLEND);
2307 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2308 glBindTexture (GL_TEXTURE_1D, state.stid);
2310 xoff -= state.pagedims[page->pdimno].bounds.x0;
2311 yoff -= state.pagedims[page->pdimno].bounds.y0;
2312 fz_translate (&tm, xoff, yoff);
2313 pm = pagectm (page);
2314 fz_concat (&ctm, &pm, &tm);
2316 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2317 glVertexPointer (2, GL_FLOAT, 0, vertices);
2319 for (link = links; link; link = link->next) {
2320 fz_point p1, p2, p3, p4;
2322 p1.x = link->rect.x0;
2323 p1.y = link->rect.y0;
2325 p2.x = link->rect.x1;
2326 p2.y = link->rect.y0;
2328 p3.x = link->rect.x1;
2329 p3.y = link->rect.y1;
2331 p4.x = link->rect.x0;
2332 p4.y = link->rect.y1;
2334 fz_transform_point (&p1, &ctm);
2335 fz_transform_point (&p2, &ctm);
2336 fz_transform_point (&p3, &ctm);
2337 fz_transform_point (&p4, &ctm);
2339 switch (link->dest.kind) {
2340 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2341 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2342 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2343 default: glColor3ub (0, 0, 0); break;
2347 float w, h, s, t;
2349 w = p2.x - p1.x;
2350 h = p2.y - p1.y;
2351 t = sqrtf (w*w + h*h) * .25f;
2353 w = p3.x - p2.x;
2354 h = p3.y - p2.y;
2355 s = sqrtf (w*w + h*h) * .25f;
2357 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
2358 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
2360 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
2361 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
2363 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
2364 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
2366 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
2367 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
2369 glDrawArrays (GL_LINES, 0, 8);
2372 glDisable (GL_BLEND);
2373 glDisable (GL_TEXTURE_1D);
2376 static int compareslinks (const void *l, const void *r)
2378 struct slink const *ls = l;
2379 struct slink const *rs = r;
2380 if (ls->bbox.y0 == rs->bbox.y0) {
2381 return rs->bbox.x0 - rs->bbox.x0;
2383 return ls->bbox.y0 - rs->bbox.y0;
2386 static void droptext (struct page *page)
2388 if (page->text) {
2389 fz_free_text_page (state.ctx, page->text);
2390 page->fmark.i = -1;
2391 page->lmark.i = -1;
2392 page->fmark.span = NULL;
2393 page->lmark.span = NULL;
2394 page->text = NULL;
2396 if (page->sheet) {
2397 fz_free_text_sheet (state.ctx, page->sheet);
2398 page->sheet = NULL;
2402 static void dropslinks (struct page *page)
2404 if (page->slinks) {
2405 free (page->slinks);
2406 page->slinks = NULL;
2407 page->slinkcount = 0;
2411 static void ensureslinks (struct page *page)
2413 fz_matrix ctm;
2414 int i, count = 0;
2415 size_t slinksize = sizeof (*page->slinks);
2416 fz_link *link, *links;
2418 if (state.gen != page->sgen) {
2419 dropslinks (page);
2420 page->sgen = state.gen;
2422 if (page->slinks) return;
2424 switch (page->type) {
2425 case DPDF:
2426 links = page->u.pdfpage->links;
2427 trimctm (page->u.pdfpage, page->pdimno);
2428 fz_concat (&ctm,
2429 &state.pagedims[page->pdimno].tctm,
2430 &state.pagedims[page->pdimno].ctm);
2431 break;
2433 case DXPS:
2434 links = page->u.xpspage->links;
2435 ctm = state.pagedims[page->pdimno].ctm;
2436 break;
2438 default:
2439 return;
2442 for (link = links; link; link = link->next) {
2443 count++;
2445 if (count > 0) {
2446 page->slinkcount = count;
2447 page->slinks = calloc (count, slinksize);
2448 if (!page->slinks) {
2449 err (1, "realloc slinks %d", count);
2452 for (i = 0, link = links; link; ++i, link = link->next) {
2453 fz_rect rect;
2455 rect = link->rect;
2456 fz_transform_rect (&rect, &ctm);
2457 page->slinks[i].link = link;
2458 fz_round_rect (&page->slinks[i].bbox, &rect);
2460 qsort (page->slinks, count, slinksize, compareslinks);
2464 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2465 static void fmt_linkn (char *s, unsigned int u)
2467 unsigned int len; unsigned int q;
2468 unsigned int zma = 'z' - 'a' + 1;
2469 len = 1; q = u;
2470 while (q > zma - 1) { ++len; q /= zma; }
2471 if (s) {
2472 s += len;
2473 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2474 /* handles u == 0 */
2476 s[len] = 0;
2479 static void highlightslinks (struct page *page, int xoff, int yoff,
2480 int noff, char *targ, int tlen, int hfsize)
2482 int i;
2483 char buf[40];
2484 struct slink *slink;
2485 double x0, y0, x1, y1, w;
2487 ensureslinks (page);
2488 glColor3ub (0xc3, 0xb0, 0x91);
2489 for (i = 0; i < page->slinkcount; ++i) {
2490 fmt_linkn (buf, i + noff);
2491 if (!tlen || !strncmp (targ, buf, tlen)) {
2492 slink = &page->slinks[i];
2494 x0 = slink->bbox.x0 + xoff - 5;
2495 y1 = slink->bbox.y0 + yoff - 5;
2496 y0 = y1 + 10 + hfsize;
2497 w = measure_string (state.face, hfsize, buf);
2498 x1 = x0 + w + 10;
2499 recti (x0, y0, x1, y1);
2503 glEnable (GL_BLEND);
2504 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2505 glEnable (GL_TEXTURE_2D);
2506 glColor3ub (0, 0, 0);
2507 for (i = 0; i < page->slinkcount; ++i) {
2508 fmt_linkn (buf, i + noff);
2509 if (!tlen || !strncmp (targ, buf, tlen)) {
2510 slink = &page->slinks[i];
2512 x0 = slink->bbox.x0 + xoff;
2513 y0 = slink->bbox.y0 + yoff + hfsize;
2514 draw_string (state.face, hfsize, x0, y0, buf);
2517 glDisable (GL_TEXTURE_2D);
2518 glDisable (GL_BLEND);
2521 static void uploadslice (struct tile *tile, struct slice *slice)
2523 int offset;
2524 struct slice *slice1;
2525 unsigned char *texdata;
2527 offset = 0;
2528 for (slice1 = tile->slices; slice != slice1; slice1++) {
2529 offset += slice1->h * tile->w * tile->pixmap->n;
2531 if (slice->texindex != -1 && slice->texindex < state.texcount
2532 && state.texowners[slice->texindex].slice == slice) {
2533 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2535 else {
2536 int subimage = 0;
2537 int texindex = state.texindex++ % state.texcount;
2539 if (state.texowners[texindex].w == tile->w) {
2540 if (state.texowners[texindex].h >= slice->h) {
2541 subimage = 1;
2543 else {
2544 state.texowners[texindex].h = slice->h;
2547 else {
2548 state.texowners[texindex].h = slice->h;
2551 state.texowners[texindex].w = tile->w;
2552 state.texowners[texindex].slice = slice;
2553 slice->texindex = texindex;
2555 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2556 if (tile->pbo) {
2557 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2558 texdata = 0;
2560 else {
2561 texdata = tile->pixmap->samples;
2563 if (subimage) {
2564 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2568 tile->w,
2569 slice->h,
2570 state.texform,
2571 state.texty,
2572 texdata+offset
2575 else {
2576 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2578 state.texiform,
2579 tile->w,
2580 slice->h,
2582 state.texform,
2583 state.texty,
2584 texdata+offset
2587 if (tile->pbo) {
2588 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2593 CAMLprim value ml_begintiles (value unit_v)
2595 CAMLparam1 (unit_v);
2596 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2597 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2598 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2599 CAMLreturn (unit_v);
2602 CAMLprim value ml_endtiles (value unit_v)
2604 CAMLparam1 (unit_v);
2605 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2606 CAMLreturn (unit_v);
2609 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2611 CAMLparam2 (args_v, ptr_v);
2612 int dispx = Int_val (Field (args_v, 0));
2613 int dispy = Int_val (Field (args_v, 1));
2614 int dispw = Int_val (Field (args_v, 2));
2615 int disph = Int_val (Field (args_v, 3));
2616 int tilex = Int_val (Field (args_v, 4));
2617 int tiley = Int_val (Field (args_v, 5));
2618 char *s = String_val (ptr_v);
2619 struct tile *tile = parse_pointer ("ml_drawtile", s);
2620 int slicey, firstslice;
2621 struct slice *slice;
2622 GLfloat *texcoords = state.texcoords;
2623 GLfloat *vertices = state.vertices;
2625 firstslice = tiley / tile->sliceheight;
2626 slice = &tile->slices[firstslice];
2627 slicey = tiley % tile->sliceheight;
2629 while (disph > 0) {
2630 int dh;
2632 dh = slice->h - slicey;
2633 dh = MIN (disph, dh);
2634 uploadslice (tile, slice);
2636 texcoords[0] = tilex; texcoords[1] = slicey;
2637 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2638 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2639 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2641 vertices[0] = dispx; vertices[1] = dispy;
2642 vertices[2] = dispx+dispw; vertices[3] = dispy;
2643 vertices[4] = dispx; vertices[5] = dispy+dh;
2644 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2646 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2647 dispy += dh;
2648 disph -= dh;
2649 slice++;
2650 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2651 slicey = 0;
2653 CAMLreturn (Val_unit);
2656 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2657 value xoff_v, value yoff_v,
2658 value li_v)
2660 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2661 int xoff = Int_val (xoff_v);
2662 int yoff = Int_val (yoff_v);
2663 int noff = Int_val (Field (li_v, 0));
2664 char *targ = String_val (Field (li_v, 1));
2665 int tlen = caml_string_length (Field (li_v, 1));
2666 int hfsize = Int_val (Field (li_v, 2));
2667 char *s = String_val (ptr_v);
2668 int hlmask = Int_val (hlinks_v);
2669 struct page *page = parse_pointer ("ml_postprocess", s);
2671 if (!page->u.ptr) {
2672 /* deal with loadpage failed pages */
2673 goto done;
2676 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2677 if (trylock ("ml_postprocess")) {
2678 noff = 0;
2679 goto done;
2681 if (hlmask & 2) {
2682 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2683 noff = page->slinkcount;
2685 if (page->tgen == state.gen) {
2686 showsel (page, xoff, yoff);
2688 unlock ("ml_postprocess");
2690 done:
2691 CAMLreturn (Val_int (noff));
2694 static fz_link *getlink (struct page *page, int x, int y)
2696 fz_point p;
2697 fz_matrix ctm;
2698 const fz_matrix *tctm;
2699 fz_link *link, *links;
2701 switch (page->type) {
2702 case DPDF:
2703 trimctm (page->u.pdfpage, page->pdimno);
2704 tctm = &state.pagedims[page->pdimno].tctm;
2705 links = page->u.pdfpage->links;
2706 break;
2708 case DXPS:
2709 tctm = &fz_identity;
2710 links = page->u.xpspage->links;
2711 break;
2713 default:
2714 return NULL;
2716 p.x = x;
2717 p.y = y;
2719 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2720 fz_invert_matrix (&ctm, &ctm);
2721 fz_transform_point (&p, &ctm);
2723 for (link = links; link; link = link->next) {
2724 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2725 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2726 return link;
2730 return NULL;
2733 static void ensuretext (struct page *page)
2735 if (state.gen != page->tgen) {
2736 droptext (page);
2737 page->tgen = state.gen;
2739 if (!page->text) {
2740 fz_matrix ctm;
2741 fz_device *tdev;
2743 page->text = fz_new_text_page (state.ctx);
2744 page->sheet = fz_new_text_sheet (state.ctx);
2745 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2746 ctm = pagectm (page);
2747 fz_begin_page (tdev, &fz_infinite_rect, &ctm);
2748 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2749 qsort (page->text->blocks, page->text->len,
2750 sizeof (*page->text->blocks), compareblocks);
2751 fz_end_page (tdev);
2752 fz_free_device (tdev);
2756 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2758 CAMLparam2 (start_page_v, dir_v);
2759 CAMLlocal1 (ret_v);
2760 int i, dir = Int_val (dir_v);
2761 int start_page = Int_val (start_page_v);
2762 int end_page = dir > 0 ? state.pagecount : -1;
2764 ret_v = Val_int (0);
2765 if (!(state.type == DPDF || state.type == DXPS)) {
2766 goto done;
2769 lock ("ml_findpage_with_links");
2770 for (i = start_page + dir; i != end_page; i += dir) {
2771 int found;
2773 switch (state.type) {
2774 case DPDF:
2776 pdf_page *page = NULL;
2778 fz_try (state.ctx) {
2779 page = pdf_load_page (state.u.pdf, i);
2780 found = !!page->links;
2782 fz_catch (state.ctx) {
2783 found = 0;
2785 if (page) {
2786 freepdfpage (page);
2789 break;
2790 case DXPS:
2792 xps_page *page = xps_load_page (state.u.xps, i);
2793 found = !!page->links;
2794 freexpspage (page);
2796 break;
2798 default:
2799 ARSERT (0 && "invalid document type");
2802 if (found) {
2803 ret_v = caml_alloc_small (1, 1);
2804 Field (ret_v, 0) = Val_int (i);
2805 goto unlock;
2808 unlock:
2809 unlock ("ml_findpage_with_links");
2811 done:
2812 CAMLreturn (ret_v);
2815 enum { dir_first, dir_last };
2816 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2818 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2820 CAMLparam2 (ptr_v, dir_v);
2821 CAMLlocal2 (ret_v, pos_v);
2822 struct page *page;
2823 int dirtag, i, slinkindex;
2824 struct slink *found = NULL ,*slink;
2825 char *s = String_val (ptr_v);
2827 page = parse_pointer ("ml_findlink", s);
2828 ret_v = Val_int (0);
2829 if (trylock ("ml_findlink")) {
2830 goto done;
2833 ensureslinks (page);
2835 if (Is_block (dir_v)) {
2836 dirtag = Tag_val (dir_v);
2837 switch (dirtag) {
2838 case dir_first_visible:
2840 int x0, y0, dir, first_index, last_index;
2842 pos_v = Field (dir_v, 0);
2843 x0 = Int_val (Field (pos_v, 0));
2844 y0 = Int_val (Field (pos_v, 1));
2845 dir = Int_val (Field (pos_v, 2));
2847 if (dir >= 0) {
2848 dir = 1;
2849 first_index = 0;
2850 last_index = page->slinkcount;
2852 else {
2853 first_index = page->slinkcount - 1;
2854 last_index = -1;
2857 for (i = first_index; i != last_index; i += dir) {
2858 slink = &page->slinks[i];
2859 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2860 found = slink;
2861 break;
2865 break;
2867 case dir_left:
2868 slinkindex = Int_val (Field (dir_v, 0));
2869 found = &page->slinks[slinkindex];
2870 for (i = slinkindex - 1; i >= 0; --i) {
2871 slink = &page->slinks[i];
2872 if (slink->bbox.x0 < found->bbox.x0) {
2873 found = slink;
2874 break;
2877 break;
2879 case dir_right:
2880 slinkindex = Int_val (Field (dir_v, 0));
2881 found = &page->slinks[slinkindex];
2882 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2883 slink = &page->slinks[i];
2884 if (slink->bbox.x0 > found->bbox.x0) {
2885 found = slink;
2886 break;
2889 break;
2891 case dir_down:
2892 slinkindex = Int_val (Field (dir_v, 0));
2893 found = &page->slinks[slinkindex];
2894 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2895 slink = &page->slinks[i];
2896 if (slink->bbox.y0 >= found->bbox.y0) {
2897 found = slink;
2898 break;
2901 break;
2903 case dir_up:
2904 slinkindex = Int_val (Field (dir_v, 0));
2905 found = &page->slinks[slinkindex];
2906 for (i = slinkindex - 1; i >= 0; --i) {
2907 slink = &page->slinks[i];
2908 if (slink->bbox.y0 <= found->bbox.y0) {
2909 found = slink;
2910 break;
2913 break;
2916 else {
2917 dirtag = Int_val (dir_v);
2918 switch (dirtag) {
2919 case dir_first:
2920 found = page->slinks;
2921 break;
2923 case dir_last:
2924 if (page->slinks) {
2925 found = page->slinks + (page->slinkcount - 1);
2927 break;
2930 if (found) {
2931 ret_v = caml_alloc_small (2, 1);
2932 Field (ret_v, 0) = Val_int (found - page->slinks);
2935 unlock ("ml_findlink");
2936 done:
2937 CAMLreturn (ret_v);
2940 enum { uuri, ugoto, utext, uunexpected,
2941 ulaunch, unamed, uremote, uremotedest };
2943 #define LINKTOVAL \
2945 int pageno; \
2947 switch (link->dest.kind) { \
2948 case FZ_LINK_GOTO: \
2950 fz_point p; \
2952 pageno = link->dest.ld.gotor.page; \
2953 p.x = 0; \
2954 p.y = 0; \
2956 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2957 p.y = link->dest.ld.gotor.lt.y; \
2958 fz_transform_point (&p, &pdim->lctm); \
2959 if (p.y < 0) p.y = 0; \
2961 tup_v = caml_alloc_tuple (2); \
2962 ret_v = caml_alloc_small (1, ugoto); \
2963 Field (tup_v, 0) = Val_int (pageno); \
2964 Field (tup_v, 1) = Val_int (p.y); \
2965 Field (ret_v, 0) = tup_v; \
2967 break; \
2969 case FZ_LINK_URI: \
2970 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2971 ret_v = caml_alloc_small (1, uuri); \
2972 Field (ret_v, 0) = str_v; \
2973 break; \
2975 case FZ_LINK_LAUNCH: \
2976 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2977 ret_v = caml_alloc_small (1, ulaunch); \
2978 Field (ret_v, 0) = str_v; \
2979 break; \
2981 case FZ_LINK_NAMED: \
2982 str_v = caml_copy_string (link->dest.ld.named.named); \
2983 ret_v = caml_alloc_small (1, unamed); \
2984 Field (ret_v, 0) = str_v; \
2985 break; \
2987 case FZ_LINK_GOTOR: \
2989 int rty; \
2991 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2992 pageno = link->dest.ld.gotor.page; \
2993 if (pageno == -1) { \
2994 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2995 rty = uremotedest; \
2997 else { \
2998 gr_v = Val_int (pageno); \
2999 rty = uremote; \
3001 tup_v = caml_alloc_tuple (2); \
3002 ret_v = caml_alloc_small (1, rty); \
3003 Field (tup_v, 0) = str_v; \
3004 Field (tup_v, 1) = gr_v; \
3005 Field (ret_v, 0) = tup_v; \
3007 break; \
3009 default: \
3011 char buf[80]; \
3013 snprintf (buf, sizeof (buf), \
3014 "unhandled link kind %d", link->dest.kind); \
3015 str_v = caml_copy_string (buf); \
3016 ret_v = caml_alloc_small (1, uunexpected); \
3017 Field (ret_v, 0) = str_v; \
3019 break; \
3023 CAMLprim value ml_getlink (value ptr_v, value n_v)
3025 CAMLparam2 (ptr_v, n_v);
3026 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3027 fz_link *link;
3028 struct page *page;
3029 struct pagedim *pdim;
3030 char *s = String_val (ptr_v);
3032 ret_v = Val_int (0);
3033 if (trylock ("ml_getlink")) {
3034 goto done;
3037 page = parse_pointer ("ml_getlink", s);
3038 ensureslinks (page);
3039 pdim = &state.pagedims[page->pdimno];
3040 link = page->slinks[Int_val (n_v)].link;
3041 LINKTOVAL;
3043 unlock ("ml_getlink");
3044 done:
3045 CAMLreturn (ret_v);
3048 CAMLprim value ml_getlinkcount (value ptr_v)
3050 CAMLparam1 (ptr_v);
3051 struct page *page;
3052 char *s = String_val (ptr_v);
3054 page = parse_pointer ("ml_getlinkcount", s);
3055 CAMLreturn (Val_int (page->slinkcount));
3058 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3060 CAMLparam2 (ptr_v, n_v);
3061 CAMLlocal1 (ret_v);
3062 struct page *page;
3063 struct slink *slink;
3064 char *s = String_val (ptr_v);
3066 page = parse_pointer ("ml_getlinkrect", s);
3067 ret_v = caml_alloc_tuple (4);
3068 if (trylock ("ml_getlinkrect")) {
3069 Field (ret_v, 0) = Val_int (0);
3070 Field (ret_v, 1) = Val_int (0);
3071 Field (ret_v, 2) = Val_int (0);
3072 Field (ret_v, 3) = Val_int (0);
3073 goto done;
3075 ensureslinks (page);
3077 slink = &page->slinks[Int_val (n_v)];
3078 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3079 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3080 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3081 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3082 unlock ("ml_getlinkrect");
3084 done:
3085 CAMLreturn (ret_v);
3088 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3090 CAMLparam3 (ptr_v, x_v, y_v);
3091 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3092 fz_link *link;
3093 struct page *page;
3094 char *ptr = String_val (ptr_v);
3095 int x = Int_val (x_v), y = Int_val (y_v);
3096 struct pagedim *pdim;
3098 ret_v = Val_int (0);
3099 if (trylock ("ml_whatsunder")) {
3100 goto done;
3103 page = parse_pointer ("ml_whatsunder", ptr);
3104 pdim = &state.pagedims[page->pdimno];
3105 x += pdim->bounds.x0;
3106 y += pdim->bounds.y0;
3107 link = getlink (page, x, y);
3108 if (link) {
3109 LINKTOVAL;
3111 else {
3112 fz_rect *b;
3113 fz_page_block *pageb;
3114 fz_text_block *block;
3116 ensuretext (page);
3117 for (pageb = page->text->blocks;
3118 pageb < page->text->blocks + page->text->len;
3119 ++pageb) {
3120 fz_text_line *line;
3121 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3122 block = pageb->u.text;
3124 b = &block->bbox;
3125 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3126 continue;
3128 for (line = block->lines;
3129 line < block->lines + block->len;
3130 ++line) {
3131 fz_text_span *span;
3133 b = &line->bbox;
3134 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3135 continue;
3137 for (span = line->first_span; span; span = span->next) {
3138 int charnum;
3140 b = &span->bbox;
3141 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3142 continue;
3144 for (charnum = 0; charnum < span->len; ++charnum) {
3145 fz_rect bbox;
3146 fz_text_char_bbox (&bbox, span, charnum);
3147 b = &bbox;
3149 if (x >= b->x0 && x <= b->x1
3150 && y >= b->y0 && y <= b->y1) {
3151 fz_text_style *style = span->text->style;
3152 const char *n2 =
3153 style->font && style->font->name
3154 ? style->font->name
3155 : "Span has no font name"
3157 FT_FaceRec *face = style->font->ft_face;
3158 if (face && face->family_name) {
3159 char *s;
3160 char *n1 = face->family_name;
3161 size_t l1 = strlen (n1);
3162 size_t l2 = strlen (n2);
3164 if (l1 != l2 || memcmp (n1, n2, l1)) {
3165 s = malloc (l1 + l2 + 2);
3166 if (s) {
3167 memcpy (s, n2, l2);
3168 s[l2] = '=';
3169 memcpy (s + l2 + 1, n1, l1 + 1);
3170 str_v = caml_copy_string (s);
3171 free (s);
3175 if (str_v == Val_unit) {
3176 str_v = caml_copy_string (n2);
3178 ret_v = caml_alloc_small (1, utext);
3179 Field (ret_v, 0) = str_v;
3180 goto unlock;
3187 unlock:
3188 unlock ("ml_whatsunder");
3190 done:
3191 CAMLreturn (ret_v);
3194 enum { mark_page, mark_block, mark_line, mark_word };
3196 static int uninteresting (int c)
3198 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3199 || ispunct (c);
3202 CAMLprim value ml_clearmark (value ptr_v)
3204 CAMLparam1 (ptr_v);
3205 char *s = String_val (ptr_v);
3206 struct page *page;
3208 if (trylock ("ml_clearmark")) {
3209 goto done;
3212 page = parse_pointer ("ml_clearmark", s);
3213 page->fmark.span = NULL;
3214 page->lmark.span = NULL;
3215 page->fmark.i = 0;
3216 page->lmark.i = 0;
3218 unlock ("ml_clearmark");
3219 done:
3220 CAMLreturn (Val_unit);
3223 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3225 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3226 CAMLlocal1 (ret_v);
3227 fz_rect *b;
3228 struct page *page;
3229 fz_text_line *line;
3230 fz_page_block *pageb;
3231 fz_text_block *block;
3232 struct pagedim *pdim;
3233 int mark = Int_val (mark_v);
3234 char *s = String_val (ptr_v);
3235 int x = Int_val (x_v), y = Int_val (y_v);
3237 ret_v = Val_bool (0);
3238 if (trylock ("ml_markunder")) {
3239 goto done;
3242 page = parse_pointer ("ml_markunder", s);
3243 pdim = &state.pagedims[page->pdimno];
3245 ensuretext (page);
3247 if (mark == mark_page) {
3248 int i;
3249 fz_page_block *pb1 = NULL, *pb2 = NULL;
3251 for (i = 0; i < page->text->len; ++i) {
3252 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3253 pb1 = &page->text->blocks[i];
3254 break;
3257 if (!pb1) goto unlock;
3259 for (i = page->text->len - 1; i >= 0; --i) {
3260 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3261 pb2 = &page->text->blocks[i];
3262 break;
3265 if (!pb2) goto unlock;
3267 block = pb1->u.text;
3269 page->fmark.i = 0;
3270 page->fmark.span = block->lines->first_span;
3272 block = pb2->u.text;
3273 line = &block->lines[block->len - 1];
3274 page->lmark.i = line->last_span->len - 1;
3275 page->lmark.span = line->last_span;
3276 ret_v = Val_bool (1);
3277 goto unlock;
3280 x += pdim->bounds.x0;
3281 y += pdim->bounds.y0;
3283 for (pageb = page->text->blocks;
3284 pageb < page->text->blocks + page->text->len;
3285 ++pageb) {
3286 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3287 block = pageb->u.text;
3289 b = &block->bbox;
3290 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3291 continue;
3293 if (mark == mark_block) {
3294 page->fmark.i = 0;
3295 page->fmark.span = block->lines->first_span;
3297 line = &block->lines[block->len - 1];
3298 page->lmark.i = line->last_span->len - 1;
3299 page->lmark.span = line->last_span;
3300 ret_v = Val_bool (1);
3301 goto unlock;
3304 for (line = block->lines;
3305 line < block->lines + block->len;
3306 ++line) {
3307 fz_text_span *span;
3309 b = &line->bbox;
3310 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3311 continue;
3313 if (mark == mark_line) {
3314 page->fmark.i = 0;
3315 page->fmark.span = line->first_span;
3317 page->lmark.i = line->last_span->len - 1;
3318 page->lmark.span = line->last_span;
3319 ret_v = Val_bool (1);
3320 goto unlock;
3323 for (span = line->first_span; span; span = span->next) {
3324 int charnum;
3326 b = &span->bbox;
3327 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3328 continue;
3330 for (charnum = 0; charnum < span->len; ++charnum) {
3331 fz_rect bbox;
3332 fz_text_char_bbox (&bbox, span, charnum);
3333 b = &bbox;
3335 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3336 /* unicode ftw */
3337 int charnum2, charnum3 = -1, charnum4 = -1;
3339 if (uninteresting (span->text[charnum].c)) goto unlock;
3341 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3342 if (uninteresting (span->text[charnum2].c)) {
3343 charnum3 = charnum2 + 1;
3344 break;
3347 if (charnum3 == -1) charnum3 = 0;
3349 for (charnum2 = charnum + 1;
3350 charnum2 < span->len;
3351 ++charnum2) {
3352 if (uninteresting (span->text[charnum2].c)) break;
3353 charnum4 = charnum2;
3355 if (charnum4 == -1) goto unlock;
3357 page->fmark.i = charnum3;
3358 page->fmark.span = span;
3360 page->lmark.i = charnum4;
3361 page->lmark.span = span;
3362 ret_v = Val_bool (1);
3363 goto unlock;
3369 unlock:
3370 if (!Bool_val (ret_v)) {
3371 page->fmark.span = NULL;
3372 page->lmark.span = NULL;
3373 page->fmark.i = 0;
3374 page->lmark.i = 0;
3376 unlock ("ml_markunder");
3378 done:
3379 CAMLreturn (ret_v);
3382 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3384 CAMLparam3 (ptr_v, x_v, y_v);
3385 CAMLlocal2 (ret_v, res_v);
3386 fz_rect *b = NULL;
3387 struct page *page;
3388 fz_page_block *pageb;
3389 struct pagedim *pdim;
3390 char *s = String_val (ptr_v);
3391 int x = Int_val (x_v), y = Int_val (y_v);
3393 ret_v = Val_int (0);
3394 if (trylock ("ml_rectofblock")) {
3395 goto done;
3398 page = parse_pointer ("ml_rectofblock", s);
3399 pdim = &state.pagedims[page->pdimno];
3400 x += pdim->bounds.x0;
3401 y += pdim->bounds.y0;
3403 ensuretext (page);
3405 for (pageb = page->text->blocks;
3406 pageb < page->text->blocks + page->text->len;
3407 ++pageb) {
3408 switch (pageb->type) {
3409 case FZ_PAGE_BLOCK_TEXT:
3410 b = &pageb->u.text->bbox;
3411 break;
3413 case FZ_PAGE_BLOCK_IMAGE:
3414 b = &pageb->u.image->bbox;
3415 break;
3417 default:
3418 continue;
3421 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3422 break;
3423 b = NULL;
3425 if (b) {
3426 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3427 ret_v = caml_alloc_small (1, 1);
3428 Store_double_field (res_v, 0, b->x0);
3429 Store_double_field (res_v, 1, b->x1);
3430 Store_double_field (res_v, 2, b->y0);
3431 Store_double_field (res_v, 3, b->y1);
3432 Field (ret_v, 0) = res_v;
3434 unlock ("ml_rectofblock");
3436 done:
3437 CAMLreturn (ret_v);
3440 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3442 CAMLparam2 (ptr_v, rect_v);
3443 fz_rect b;
3444 struct page *page;
3445 struct pagedim *pdim;
3446 char *s = String_val (ptr_v);
3447 int i, x0, x1, y0, y1, fi, li;
3448 fz_text_line *line;
3449 fz_page_block *pageb;
3450 fz_text_block *block;
3451 fz_text_span *span, *fspan, *lspan;
3453 if (trylock ("ml_seltext")) {
3454 goto done;
3457 page = parse_pointer ("ml_seltext", s);
3458 ensuretext (page);
3460 pdim = &state.pagedims[page->pdimno];
3461 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3462 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3463 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3464 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3466 if (y0 > y1) {
3467 int t = y0;
3468 y0 = y1;
3469 y1 = t;
3470 x0 = x1;
3471 x1 = t;
3474 if (0) {
3475 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3476 glColor3ub (128, 128, 128);
3477 recti (x0, y0, x1, y1);
3478 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3481 fi = page->fmark.i;
3482 fspan = page->fmark.span;
3484 li = page->lmark.i;
3485 lspan = page->lmark.span;
3487 for (pageb = page->text->blocks;
3488 pageb < page->text->blocks + page->text->len;
3489 ++pageb) {
3490 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3491 block = pageb->u.text;
3492 for (line = block->lines;
3493 line < block->lines + block->len;
3494 ++line) {
3496 for (span = line->first_span; span; span = span->next) {
3497 for (i = 0; i < span->len; ++i) {
3498 int selected = 0;
3500 fz_text_char_bbox (&b, span, i);
3502 if (x0 >= b.x0 && x0 <= b.x1
3503 && y0 >= b.y0 && y0 <= b.y1) {
3504 fspan = span;
3505 fi = i;
3506 selected = 1;
3508 if (x1 >= b.x0 && x1 <= b.x1
3509 && y1 >= b.y0 && y1 <= b.y1) {
3510 lspan = span;
3511 li = i;
3512 selected = 1;
3514 if (0 && selected) {
3515 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3516 glColor3ub (128, 128, 128);
3517 recti (b.x0, b.y0, b.x1, b.y1);
3518 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3524 if (x1 < x0 && fspan == lspan) {
3525 i = fi;
3526 span = fspan;
3528 fi = li;
3529 fspan = lspan;
3531 li = i;
3532 lspan = span;
3535 page->fmark.i = fi;
3536 page->fmark.span = fspan;
3538 page->lmark.i = li;
3539 page->lmark.span = lspan;
3541 unlock ("ml_seltext");
3543 done:
3544 CAMLreturn (Val_unit);
3547 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3549 char buf[4];
3550 int i, len, ret;
3552 for (i = a; i <= b; ++i) {
3553 len = fz_runetochar (buf, span->text[i].c);
3554 ret = fwrite (buf, len, 1, f);
3556 if (ret != 1) {
3557 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3558 len, ret, strerror (errno));
3559 return -1;
3562 return 0;
3565 #ifdef __CYGWIN__
3566 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3568 caml_failwith ("ml_popen not implemented under Cygwin");
3570 #else
3571 CAMLprim value ml_popen (value command_v, value fds_v)
3573 CAMLparam2 (command_v, fds_v);
3574 CAMLlocal2 (l_v, tup_v);
3575 int ret;
3576 char *msg = NULL;
3577 value earg_v = Nothing;
3578 posix_spawnattr_t attr;
3579 posix_spawn_file_actions_t fa;
3580 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3582 argv[2] = String_val (command_v);
3584 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3585 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3588 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3589 msg = "posix_spawnattr_init";
3590 goto fail1;
3593 #ifdef POSIX_SPAWN_USEVFORK
3594 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3595 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3596 goto fail;
3598 #endif
3600 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3601 int fd1, fd2;
3603 tup_v = Field (l_v, 0);
3604 fd1 = Int_val (Field (tup_v, 0));
3605 fd2 = Int_val (Field (tup_v, 1));
3606 if (fd2 < 0) {
3607 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3608 msg = "posix_spawn_file_actions_addclose";
3609 earg_v = tup_v;
3610 goto fail;
3613 else {
3614 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3615 msg = "posix_spawn_file_actions_adddup2";
3616 earg_v = tup_v;
3617 goto fail;
3622 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3623 msg = "posix_spawn";
3624 goto fail;
3627 fail:
3628 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3629 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3632 fail1:
3633 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3634 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3635 strerror (ret));
3638 if (msg)
3639 unix_error (ret, msg, earg_v);
3641 CAMLreturn (Val_unit);
3643 #endif
3645 CAMLprim value ml_hassel (value ptr_v)
3647 CAMLparam1 (ptr_v);
3648 CAMLlocal1 (ret_v);
3649 struct page *page;
3650 char *s = String_val (ptr_v);
3652 ret_v = Val_bool (0);
3653 if (trylock ("ml_hassel")) {
3654 goto done;
3657 page = parse_pointer ("ml_hassel", s);
3658 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3659 unlock ("ml_hassel");
3660 done:
3661 CAMLreturn (ret_v);
3664 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3666 CAMLparam2 (fd_v, ptr_v);
3667 FILE *f;
3668 int seen = 0;
3669 struct page *page;
3670 fz_text_line *line;
3671 fz_page_block *pageb;
3672 fz_text_block *block;
3673 int fd = Int_val (fd_v);
3674 char *s = String_val (ptr_v);
3676 if (trylock ("ml_copysel")) {
3677 goto done;
3680 page = parse_pointer ("ml_copysel", s);
3682 if (!page->fmark.span || !page->lmark.span) {
3683 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3684 goto unlock;
3687 f = fdopen (fd, "w");
3688 if (!f) {
3689 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3690 fd, strerror (errno));
3691 f = stdout;
3694 for (pageb = page->text->blocks;
3695 pageb < page->text->blocks + page->text->len;
3696 ++pageb) {
3697 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3698 block = pageb->u.text;
3699 for (line = block->lines;
3700 line < block->lines + block->len;
3701 ++line) {
3702 fz_text_span *span;
3704 for (span = line->first_span; span; span = span->next) {
3705 int a, b;
3707 seen |= span == page->fmark.span || span == page->lmark.span;
3708 a = span == page->fmark.span ? page->fmark.i : 0;
3709 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3711 if (seen) {
3712 if (pipespan (f, span, a, b)) {
3713 goto close;
3715 if (span == page->lmark.span) {
3716 goto close;
3718 if (span == line->last_span) {
3719 if (putc ('\n', f) == EOF) {
3720 fprintf (stderr,
3721 "failed break line on sel pipe: %s\n",
3722 strerror (errno));
3723 goto close;
3730 close:
3731 if (f != stdout) {
3732 int ret = fclose (f);
3733 fd = -1;
3734 if (ret == -1) {
3735 if (errno != ECHILD) {
3736 fprintf (stderr, "failed to close sel pipe: %s\n",
3737 strerror (errno));
3741 unlock:
3742 unlock ("ml_copysel");
3744 done:
3745 if (fd >= 0) {
3746 if (close (fd)) {
3747 fprintf (stderr, "failed to close sel pipe: %s\n",
3748 strerror (errno));
3751 CAMLreturn (Val_unit);
3754 CAMLprim value ml_getpdimrect (value pagedimno_v)
3756 CAMLparam1 (pagedimno_v);
3757 CAMLlocal1 (ret_v);
3758 int pagedimno = Int_val (pagedimno_v);
3759 fz_rect box;
3761 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3762 if (trylock ("ml_getpdimrect")) {
3763 box = fz_empty_rect;
3765 else {
3766 box = state.pagedims[pagedimno].mediabox;
3767 unlock ("ml_getpdimrect");
3770 Store_double_field (ret_v, 0, box.x0);
3771 Store_double_field (ret_v, 1, box.x1);
3772 Store_double_field (ret_v, 2, box.y0);
3773 Store_double_field (ret_v, 3, box.y1);
3775 CAMLreturn (ret_v);
3778 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3779 value dw_v, value cols_v)
3781 CAMLparam3 (winw_v, winh_v, dw_v);
3782 CAMLlocal1 (ret_v);
3783 int i;
3784 double zoom = -1.;
3785 double maxh = 0.0;
3786 struct pagedim *p;
3787 double winw = Int_val (winw_v);
3788 double winh = Int_val (winh_v);
3789 double dw = Int_val (dw_v);
3790 double cols = Int_val (cols_v);
3791 double pw = 1.0, ph = 1.0;
3793 if (trylock ("ml_zoom_for_height")) {
3794 goto done;
3797 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3798 double w = p->pagebox.x1 / cols;
3799 double h = p->pagebox.y1;
3800 if (h > maxh) {
3801 maxh = h;
3802 ph = h;
3803 if (state.fitmodel != FitProportional) pw = w;
3805 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3808 zoom = (((winh / ph) * pw) + dw) / winw;
3809 unlock ("ml_zoom_for_height");
3810 done:
3811 ret_v = caml_copy_double (zoom);
3812 CAMLreturn (ret_v);
3815 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3817 CAMLparam4 (pt_v, x_v, y_v, string_v);
3818 CAMLlocal1 (ret_v);
3819 int pt = Int_val(pt_v);
3820 int x = Int_val (x_v);
3821 int y = Int_val (y_v);
3822 double w;
3824 w = draw_string (state.face, pt, x, y, String_val (string_v));
3825 ret_v = caml_copy_double (w);
3826 CAMLreturn (ret_v);
3829 CAMLprim value ml_measure_string (value pt_v, value string_v)
3831 CAMLparam2 (pt_v, string_v);
3832 CAMLlocal1 (ret_v);
3833 int pt = Int_val (pt_v);
3834 double w;
3836 w = measure_string (state.face, pt, String_val (string_v));
3837 ret_v = caml_copy_double (w);
3838 CAMLreturn (ret_v);
3841 CAMLprim value ml_getpagebox (value opaque_v)
3843 CAMLparam1 (opaque_v);
3844 CAMLlocal1 (ret_v);
3845 fz_rect rect;
3846 fz_irect bbox;
3847 fz_matrix ctm;
3848 fz_device *dev;
3849 char *s = String_val (opaque_v);
3850 struct page *page = parse_pointer ("ml_getpagebox", s);
3852 ret_v = caml_alloc_tuple (4);
3853 dev = fz_new_bbox_device (state.ctx, &rect);
3854 dev->hints |= FZ_IGNORE_SHADE;
3856 switch (page->type) {
3857 case DPDF:
3858 ctm = pagectm (page);
3859 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3860 break;
3862 case DXPS:
3863 ctm = pagectm (page);
3864 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3865 break;
3867 default:
3868 rect = fz_infinite_rect;
3869 break;
3872 fz_free_device (dev);
3873 fz_round_rect (&bbox, &rect);
3874 Field (ret_v, 0) = Val_int (bbox.x0);
3875 Field (ret_v, 1) = Val_int (bbox.y0);
3876 Field (ret_v, 2) = Val_int (bbox.x1);
3877 Field (ret_v, 3) = Val_int (bbox.y1);
3879 CAMLreturn (ret_v);
3882 CAMLprim value ml_setaalevel (value level_v)
3884 CAMLparam1 (level_v);
3886 state.aalevel = Int_val (level_v);
3887 CAMLreturn (Val_unit);
3890 #pragma GCC diagnostic push
3891 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3892 #include <X11/Xlib.h>
3893 #pragma GCC diagnostic pop
3895 #include <GL/glx.h>
3897 static struct {
3898 Window wid;
3899 Display *dpy;
3900 GLXContext ctx;
3901 XVisualInfo *visual;
3902 } glx;
3904 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3906 CAMLparam3 (display_v, wid_v, screen_v);
3907 int attribs[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
3909 glx.dpy = XOpenDisplay (String_val (display_v));
3910 if (!glx.dpy) {
3911 caml_failwith ("XOpenDisplay");
3914 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3915 if (!glx.visual) {
3916 XCloseDisplay (glx.dpy);
3917 caml_failwith ("glXChooseVisual");
3920 glx.wid = Int_val (wid_v);
3921 CAMLreturn (Val_int (glx.visual->visualid));
3924 CAMLprim value ml_glxcompleteinit (value unit_v)
3926 CAMLparam1 (unit_v);
3928 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3929 if (!glx.ctx) {
3930 caml_failwith ("glXCreateContext");
3933 XFree (glx.visual);
3934 glx.visual = NULL;
3936 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3937 glXDestroyContext (glx.dpy, glx.ctx);
3938 glx.ctx = NULL;
3939 caml_failwith ("glXMakeCurrent");
3941 CAMLreturn (Val_unit);
3944 CAMLprim value ml_swapb (value unit_v)
3946 CAMLparam1 (unit_v);
3947 glXSwapBuffers (glx.dpy, glx.wid);
3948 CAMLreturn (Val_unit);
3951 #include "keysym2ucs.c"
3953 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3955 CAMLparam1 (keysym_v);
3956 CAMLlocal1 (str_v);
3957 KeySym keysym = Int_val (keysym_v);
3958 Rune rune;
3959 int len;
3960 char buf[5];
3962 rune = keysym2ucs (keysym);
3963 len = fz_runetochar (buf, rune);
3964 buf[len] = 0;
3965 str_v = caml_copy_string (buf);
3966 CAMLreturn (str_v);
3969 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3971 CAMLprim value ml_platform (value unit_v)
3973 CAMLparam1 (unit_v);
3974 CAMLlocal2 (tup_v, arr_v);
3975 int platid = piunknown;
3976 struct utsname buf;
3978 #if defined __linux__
3979 platid = pilinux;
3980 #elif defined __CYGWIN__
3981 platid = picygwin;
3982 #elif defined __DragonFly__ || defined __FreeBSD__
3983 || defined __OpenBSD__ || defined __NetBSD__
3984 platid = pibsd;
3985 #elif defined __sun__
3986 platid = pisun;
3987 #elif defined __APPLE__
3988 platid = piosx;
3989 #endif
3990 if (uname (&buf)) err (1, "uname");
3992 tup_v = caml_alloc_tuple (2);
3994 char const *sar[] = {
3995 buf.sysname,
3996 buf.release,
3997 buf.version,
3998 buf.machine,
3999 NULL
4001 arr_v = caml_copy_string_array (sar);
4003 Field (tup_v, 0) = Val_int (platid);
4004 Field (tup_v, 1) = arr_v;
4005 CAMLreturn (tup_v);
4008 CAMLprim value ml_cloexec (value fd_v)
4010 CAMLparam1 (fd_v);
4011 int fd = Int_val (fd_v);
4013 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4014 uerror ("fcntl", Nothing);
4016 CAMLreturn (Val_unit);
4019 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4021 CAMLparam2 (w_v, h_v);
4022 CAMLlocal1 (ret_v);
4023 struct pbo *pbo;
4024 int w = Int_val (w_v);
4025 int h = Int_val (h_v);
4026 int cs = Int_val (cs_v);
4028 if (state.pbo_usable) {
4029 pbo = calloc (sizeof (*pbo), 1);
4030 if (!pbo) {
4031 err (1, "calloc pbo");
4034 switch (cs) {
4035 case 0:
4036 case 1:
4037 pbo->size = w*h*4;
4038 break;
4039 case 2:
4040 pbo->size = w*h*2;
4041 break;
4042 default:
4043 errx (1, "ml_getpbo: invalid colorspace %d", cs);
4046 state.glGenBuffersARB (1, &pbo->id);
4047 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4048 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4049 NULL, GL_STREAM_DRAW);
4050 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4051 GL_READ_WRITE);
4052 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4053 if (!pbo->ptr) {
4054 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4055 state.glDeleteBuffersARB (1, &pbo->id);
4056 free (pbo);
4057 ret_v = caml_copy_string ("0");
4059 else {
4060 int res;
4061 char *s;
4063 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4064 if (res < 0) {
4065 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4067 s = malloc (res+1);
4068 if (!s) {
4069 err (1, "malloc %d bytes failed", res+1);
4071 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4072 if (res < 0) {
4073 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4075 ret_v = caml_copy_string (s);
4076 free (s);
4079 else {
4080 ret_v = caml_copy_string ("0");
4082 CAMLreturn (ret_v);
4085 CAMLprim value ml_freepbo (value s_v)
4087 CAMLparam1 (s_v);
4088 char *s = String_val (s_v);
4089 struct tile *tile = parse_pointer ("ml_freepbo", s);
4091 if (tile->pbo) {
4092 state.glDeleteBuffersARB (1, &tile->pbo->id);
4093 tile->pbo->id = -1;
4094 tile->pbo->ptr = NULL;
4095 tile->pbo->size = -1;
4097 CAMLreturn (Val_unit);
4100 CAMLprim value ml_unmappbo (value s_v)
4102 CAMLparam1 (s_v);
4103 char *s = String_val (s_v);
4104 struct tile *tile = parse_pointer ("ml_unmappbo", s);
4106 if (tile->pbo) {
4107 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4108 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4109 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4111 tile->pbo->ptr = NULL;
4112 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4114 CAMLreturn (Val_unit);
4117 static void setuppbo (void)
4119 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4120 state.pbo_usable = GGPA (glBindBufferARB)
4121 && GGPA (glUnmapBufferARB)
4122 && GGPA (glMapBufferARB)
4123 && GGPA (glBufferDataARB)
4124 && GGPA (glGenBuffersARB)
4125 && GGPA (glDeleteBuffersARB);
4126 #undef GGPA
4129 CAMLprim value ml_pbo_usable (value unit_v)
4131 CAMLparam1 (unit_v);
4132 CAMLreturn (Val_bool (state.pbo_usable));
4135 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4137 CAMLparam3 (ptr_v, x_v, y_v);
4138 CAMLlocal2 (ret_v, tup_v);
4139 struct page *page;
4140 char *s = String_val (ptr_v);
4141 int x = Int_val (x_v), y = Int_val (y_v);
4142 struct pagedim *pdim;
4143 fz_point p;
4144 fz_matrix ctm;
4146 page = parse_pointer ("ml_unproject", s);
4147 pdim = &state.pagedims[page->pdimno];
4149 ret_v = Val_int (0);
4150 if (trylock ("ml_unproject")) {
4151 goto done;
4154 switch (page->type) {
4155 case DPDF:
4156 trimctm (page->u.pdfpage, page->pdimno);
4157 break;
4159 default:
4160 break;
4162 p.x = x + pdim->bounds.x0;
4163 p.y = y + pdim->bounds.y0;
4165 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4166 fz_invert_matrix (&ctm, &ctm);
4167 fz_transform_point (&p, &ctm);
4169 tup_v = caml_alloc_tuple (2);
4170 ret_v = caml_alloc_small (1, 1);
4171 Field (tup_v, 0) = Val_int (p.x);
4172 Field (tup_v, 1) = Val_int (p.y);
4173 Field (ret_v, 0) = tup_v;
4175 unlock ("ml_unproject");
4176 done:
4177 CAMLreturn (ret_v);
4180 static void makestippletex (void)
4182 const char pixels[] = "\xff\xff\0\0";
4183 glGenTextures (1, &state.stid);
4184 glBindTexture (GL_TEXTURE_1D, state.stid);
4185 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4186 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4187 glTexImage1D (
4188 GL_TEXTURE_1D,
4190 GL_ALPHA,
4193 GL_ALPHA,
4194 GL_UNSIGNED_BYTE,
4195 pixels
4199 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4201 return caml_copy_string (FZ_VERSION);
4204 #ifdef USE_FONTCONFIG
4205 static struct {
4206 int inited;
4207 FcConfig *config;
4208 } fc;
4210 static fz_font *fc_load_system_font_func (fz_context *ctx,
4211 const char *name,
4212 int bold,
4213 int italic,
4214 int UNUSED_ATTR needs_exact_metrics)
4216 char *buf;
4217 size_t i, size;
4218 fz_font *font;
4219 FcChar8 *path;
4220 FcResult result;
4221 FcPattern *pat, *pat1;
4223 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4224 name, bold, italic, needs_exact_metrics);
4225 if (!fc.inited) {
4226 fc.inited = 1;
4227 fc.config = FcInitLoadConfigAndFonts ();
4228 if (!fc.config) {
4229 lprintf ("FcInitLoadConfigAndFonts failed\n");
4230 return NULL;
4233 if (!fc.config) return NULL;
4235 size = strlen (name);
4236 if (bold) size += sizeof (":bold") - 1;
4237 if (italic) size += sizeof (":italic") - 1;
4238 size += 1;
4240 buf = malloc (size);
4241 if (!buf) {
4242 err (1, "malloc %zu failed", size);
4245 strcpy (buf, name);
4246 if (bold && italic) {
4247 strcat (buf, ":bold:italic");
4249 else {
4250 if (bold) strcat (buf, ":bold");
4251 if (italic) strcat (buf, ":italic");
4253 for (i = 0; i < size; ++i) {
4254 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4257 lprintf ("fcbuf=%s\n", buf);
4258 pat = FcNameParse ((FcChar8 *) buf);
4259 if (!pat) {
4260 printd ("emsg FcNameParse failed\n");
4261 free (buf);
4262 return NULL;
4265 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4266 printd ("emsg FcConfigSubstitute failed\n");
4267 free (buf);
4268 return NULL;
4270 FcDefaultSubstitute (pat);
4272 pat1 = FcFontMatch (fc.config, pat, &result);
4273 if (!pat1) {
4274 printd ("emsg FcFontMatch failed\n");
4275 FcPatternDestroy (pat);
4276 free (buf);
4277 return NULL;
4280 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4281 printd ("emsg FcPatternGetString failed\n");
4282 FcPatternDestroy (pat);
4283 FcPatternDestroy (pat1);
4284 free (buf);
4285 return NULL;
4288 #if 0
4289 printd ("emsg name=%s path=%s\n", name, path);
4290 #endif
4291 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4292 FcPatternDestroy (pat);
4293 FcPatternDestroy (pat1);
4294 free (buf);
4295 return font;
4297 #endif
4299 CAMLprim value ml_init (value csock_v, value params_v)
4301 CAMLparam2 (csock_v, params_v);
4302 CAMLlocal2 (trim_v, fuzz_v);
4303 int ret;
4304 int texcount;
4305 char *fontpath;
4306 int colorspace;
4307 int mustoresize;
4308 int haspboext;
4309 struct sigaction sa;
4311 state.csock = Int_val (csock_v);
4312 state.rotate = Int_val (Field (params_v, 0));
4313 state.fitmodel = Int_val (Field (params_v, 1));
4314 trim_v = Field (params_v, 2);
4315 texcount = Int_val (Field (params_v, 3));
4316 state.sliceheight = Int_val (Field (params_v, 4));
4317 mustoresize = Int_val (Field (params_v, 5));
4318 colorspace = Int_val (Field (params_v, 6));
4319 fontpath = String_val (Field (params_v, 7));
4321 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4322 if (!state.trimcachepath) {
4323 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4324 strerror (errno));
4326 haspboext = Bool_val (Field (params_v, 9));
4328 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4330 #ifdef USE_FONTCONFIG
4331 if (Bool_val (Field (params_v, 10))) {
4332 fz_install_load_system_font_funcs (
4333 state.ctx, fc_load_system_font_func, NULL
4336 #endif
4338 state.trimmargins = Bool_val (Field (trim_v, 0));
4339 fuzz_v = Field (trim_v, 1);
4340 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4341 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4342 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4343 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4345 set_tex_params (colorspace);
4347 if (*fontpath) {
4348 #ifndef USE_FONTCONFIG
4349 state.face = load_font (fontpath);
4350 #else
4351 FcChar8 *path;
4352 FcResult result;
4353 char *buf = fontpath;
4354 FcPattern *pat, *pat1;
4356 fc.inited = 1;
4357 fc.config = FcInitLoadConfigAndFonts ();
4358 if (!fc.config) {
4359 errx (1, "FcInitLoadConfigAndFonts failed");
4362 pat = FcNameParse ((FcChar8 *) buf);
4363 if (!pat) {
4364 errx (1, "FcNameParse failed");
4367 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4368 errx (1, "FcConfigSubstitute failed");
4370 FcDefaultSubstitute (pat);
4372 pat1 = FcFontMatch (fc.config, pat, &result);
4373 if (!pat1) {
4374 errx (1, "FcFontMatch failed");
4377 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4378 errx (1, "FcPatternGetString failed");
4381 state.face = load_font ((char *) path);
4382 FcPatternDestroy (pat);
4383 FcPatternDestroy (pat1);
4384 #endif
4386 else {
4387 unsigned int len;
4388 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
4390 state.face = load_builtin_font (base, len);
4392 if (!state.face) _exit (1);
4394 realloctexts (texcount);
4396 if (haspboext) {
4397 setuppbo ();
4400 makestippletex ();
4402 #ifdef __CYGWIN__
4403 sa.sa_handler = SIG_IGN;
4404 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4405 #else
4406 sa.sa_handler = SIG_DFL;
4407 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
4408 #endif
4409 if (sigemptyset (&sa.sa_mask)) {
4410 err (1, "sigemptyset");
4412 if (sigaction (SIGCHLD, &sa, NULL)) {
4413 err (1, "sigaction");
4416 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4417 if (ret) {
4418 errx (1, "pthread_create: %s", strerror (ret));
4421 CAMLreturn (Val_unit);