Consistency
[llpp.git] / link.c
blob196ef94cce7c315253a8509a2f36b59f4b40d91d
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>
16 #ifdef __CYGWIN__
17 #include <cygwin/socket.h> /* FIONREAD */
18 #else
19 #include <spawn.h>
20 #endif
22 #include <regex.h>
23 #include <stdarg.h>
24 #include <limits.h>
26 #include <GL/gl.h>
28 #include <caml/fail.h>
29 #include <caml/alloc.h>
30 #include <caml/memory.h>
31 #include <caml/unixsupport.h>
33 #include <fitz.h>
34 #include <mupdf.h>
35 #include <mupdf-internal.h>
36 #include <muxps.h>
37 #include <muxps-internal.h>
38 #include <mucbz.h>
40 #include FT_FREETYPE_H
42 #define PIGGYBACK
44 #ifndef __USE_GNU
45 extern char **environ;
46 #endif
48 #define MIN(a,b) ((a) < (b) ? (a) : (b))
49 #define MAX(a,b) ((a) > (b) ? (a) : (b))
51 #if defined __GNUC__
52 #define NORETURN_ATTR __attribute__ ((noreturn))
53 #define UNUSED_ATTR __attribute__ ((unused))
54 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
55 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
56 #else
57 #define NORETURN_ATTR
58 #define UNUSED_ATTR
59 #define OPTIMIZE_ATTR(n)
60 #define GCC_FMT_ATTR(a, b)
61 #endif
63 #define FMT_s "zu"
65 #define FMT_ptr "p"
66 #define FMT_ptr_cast(p) (p)
67 #define FMT_ptr_cast2(p) (p)
69 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
70 err (int exitcode, const char *fmt, ...)
72 va_list ap;
73 int savederrno;
75 savederrno = errno;
76 va_start (ap, fmt);
77 vfprintf (stderr, fmt, ap);
78 va_end (ap);
79 fprintf (stderr, ": %s\n", strerror (savederrno));
80 fflush (stderr);
81 _exit (exitcode);
84 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
85 errx (int exitcode, const char *fmt, ...)
87 va_list ap;
89 va_start (ap, fmt);
90 vfprintf (stderr, fmt, ap);
91 va_end (ap);
92 fputc ('\n', stderr);
93 fflush (stderr);
94 _exit (exitcode);
97 #ifndef GL_TEXTURE_RECTANGLE_ARB
98 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
99 #endif
101 #ifndef GL_BGRA
102 #define GL_BGRA 0x80E1
103 #endif
105 #ifndef GL_UNSIGNED_INT_8_8_8_8
106 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
107 #endif
109 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
110 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
111 #endif
113 #if 0
114 #define lprintf printf
115 #else
116 #define lprintf(...)
117 #endif
119 #define ARSERT(cond) for (;;) { \
120 if (!(cond)) { \
121 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
123 break; \
126 struct slice {
127 int h;
128 int texindex;
131 struct tile {
132 int x, y, w, h;
133 int slicecount;
134 int sliceheight;
135 struct pbo *pbo;
136 fz_pixmap *pixmap;
137 struct slice slices[1];
140 struct pagedim {
141 int pageno;
142 int rotate;
143 int left;
144 int tctmready;
145 fz_irect bounds;
146 fz_rect pagebox;
147 fz_rect mediabox;
148 fz_matrix ctm, zoomctm, lctm, tctm;
151 struct slink {
152 fz_irect bbox;
153 fz_link *link;
156 enum { DPDF, DXPS, DCBZ };
158 struct page {
159 int tgen;
160 int sgen;
161 int type;
162 int pageno;
163 int pdimno;
164 fz_text_page *text;
165 fz_text_sheet *sheet;
166 union {
167 void *ptr;
168 pdf_page *pdfpage;
169 xps_page *xpspage;
170 cbz_page *cbzpage;
171 } u;
172 fz_display_list *dlist;
173 int slinkcount;
174 struct slink *slinks;
175 struct mark {
176 int i;
177 fz_text_span *span;
178 } fmark, lmark;
179 void (*freepage) (void *);
182 struct {
183 int type;
184 int sliceheight;
185 struct pagedim *pagedims;
186 int pagecount;
187 int pagedimcount;
188 union {
189 pdf_document *pdf;
190 xps_document *xps;
191 cbz_document *cbz;
192 } u;
193 fz_context *ctx;
194 int w, h;
196 int texindex;
197 int texcount;
198 GLuint *texids;
200 GLenum texiform;
201 GLenum texform;
202 GLenum texty;
204 fz_colorspace *colorspace;
206 struct {
207 int w, h;
208 struct slice *slice;
209 } *texowners;
211 int rotate;
212 enum { FitWidth, FitProportional, FitPage } fitmodel;
213 int trimmargins;
214 int needoutline;
215 int gen;
216 int aalevel;
218 int trimanew;
219 fz_irect trimfuzz;
220 fz_pixmap *pig;
222 pthread_t thread;
223 int cr, cw;
224 FT_Face face;
226 void (*closedoc) (void);
227 void (*freepage) (void *);
229 char *trimcachepath;
231 GLuint stid;
233 int pbo_usable;
234 void (*glBindBufferARB) (GLenum, GLuint);
235 GLboolean (*glUnmapBufferARB) (GLenum);
236 void *(*glMapBufferARB) (GLenum, GLenum);
237 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
238 void (*glGenBuffersARB) (GLsizei, GLuint *);
239 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
240 } state;
242 struct pbo {
243 GLuint id;
244 void *ptr;
245 size_t size;
248 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
250 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
253 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
255 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
258 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
260 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
261 m.a, m.b, m.c, m.d, m.e, m.f);
264 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
266 static void lock (const char *cap)
268 int ret = pthread_mutex_lock (&mutex);
269 if (ret) {
270 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
274 static void unlock (const char *cap)
276 int ret = pthread_mutex_unlock (&mutex);
277 if (ret) {
278 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
282 static int trylock (const char *cap)
284 int ret = pthread_mutex_trylock (&mutex);
285 if (ret && ret != EBUSY) {
286 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
288 return ret == EBUSY;
291 static void *parse_pointer (const char *cap, const char *s)
293 int ret;
294 void *ptr;
296 ret = sscanf (s, "%" FMT_ptr, FMT_ptr_cast (&ptr));
297 if (ret != 1) {
298 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
300 return ptr;
303 static double now (void)
305 struct timeval tv;
307 if (gettimeofday (&tv, NULL)) {
308 err (1, "gettimeofday");
310 return tv.tv_sec + tv.tv_usec*1e-6;
313 static int hasdata (void)
315 int ret, avail;
316 ret = ioctl (state.cr, FIONREAD, &avail);
317 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
318 return avail > 0;
321 CAMLprim value ml_hasdata (value fd_v)
323 CAMLparam1 (fd_v);
324 int ret, avail;
326 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
327 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
328 CAMLreturn (Val_bool (avail > 0));
331 static void readdata (void *p, int size)
333 ssize_t n;
335 again:
336 n = read (state.cr, p, size);
337 if (n < 0) {
338 if (errno == EINTR) goto again;
339 err (1, "read (req %d, ret %zd)", size, n);
341 if (n - size) {
342 if (!n) errx (1, "EOF while reading");
343 errx (1, "read (req %d, ret %zd)", size, n);
347 static void writedata (char *p, int size)
349 char buf[4];
350 ssize_t n;
352 buf[0] = (size >> 24) & 0xff;
353 buf[1] = (size >> 16) & 0xff;
354 buf[2] = (size >> 8) & 0xff;
355 buf[3] = (size >> 0) & 0xff;
357 n = write (state.cw, buf, 4);
358 if (n != 4) {
359 if (!n) errx (1, "EOF while writing length");
360 err (1, "write %zd", n);
363 n = write (state.cw, p, size);
364 if (n - size) {
365 if (!n) errx (1, "EOF while writing data");
366 err (1, "write (req %d, ret %zd)", size, n);
370 static int readlen (void)
372 unsigned char p[4];
374 readdata (p, 4);
375 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
378 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
380 int size = 200, len;
381 va_list ap;
382 char *buf;
384 buf = malloc (size);
385 for (;;) {
386 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
388 va_start (ap, fmt);
389 len = vsnprintf (buf, size, fmt, ap);
390 va_end (ap);
392 if (len > -1 && len < size) {
393 writedata (buf, len);
394 break;
397 if (len > -1) {
398 size = len + 1;
400 else {
401 size *= 2;
403 buf = realloc (buf, size);
405 free (buf);
408 static void closepdf (void)
410 if (state.u.pdf) {
411 pdf_close_document (state.u.pdf);
412 state.u.pdf = NULL;
416 static void closexps (void)
418 if (state.u.xps) {
419 xps_close_document (state.u.xps);
420 state.u.xps = NULL;
424 static void closecbz (void)
426 if (state.u.cbz) {
427 cbz_close_document (state.u.cbz);
428 state.u.cbz = NULL;
432 static void freepdfpage (void *ptr)
434 pdf_free_page (state.u.pdf, ptr);
437 static void freeemptyxxxpage (void *ptr)
439 (void) ptr;
442 static void freexpspage (void *ptr)
444 xps_free_page (state.u.xps, ptr);
447 static void freecbzpage (void *ptr)
449 cbz_free_page (state.u.cbz, ptr);
452 static void openxref (char *filename, char *password)
454 int i, len;
456 for (i = 0; i < state.texcount; ++i) {
457 state.texowners[i].w = -1;
458 state.texowners[i].slice = NULL;
461 if (state.closedoc) state.closedoc ();
463 len = strlen (filename);
465 state.type = DPDF;
466 if (len > 4) {
467 char ext[4];
469 ext[0] = tolower ((int) filename[len-3]);
470 ext[1] = tolower ((int) filename[len-2]);
471 ext[2] = tolower ((int) filename[len-1]);
473 /**/ if (ext[0] == 'x' && ext[1] == 'p' && ext[2] == 's') {
474 state.type = DXPS;
476 else if (ext[0] == 'c' && ext[1] == 'b' && ext[2] == 'z') {
477 state.type = DCBZ;
481 if (state.pagedims) {
482 free (state.pagedims);
483 state.pagedims = NULL;
485 state.pagedimcount = 0;
487 fz_set_aa_level (state.ctx, state.aalevel);
488 switch (state.type) {
489 case DPDF:
490 state.u.pdf = pdf_open_document (state.ctx, filename);
491 if (pdf_needs_password (state.u.pdf)) {
492 int okay = pdf_authenticate_password (state.u.pdf, password);
493 if (!okay) {
494 errx (1, "invalid password");
497 state.pagecount = pdf_count_pages (state.u.pdf);
498 state.closedoc = closepdf;
499 state.freepage = freepdfpage;
500 break;
502 case DXPS:
503 state.u.xps = xps_open_document (state.ctx, filename);
504 state.pagecount = xps_count_pages (state.u.xps);
505 state.closedoc = closexps;
506 state.freepage = freexpspage;
507 break;
509 case DCBZ:
510 state.u.cbz = cbz_open_document (state.ctx, filename);
511 state.pagecount = cbz_count_pages (state.u.cbz);
512 state.closedoc = closecbz;
513 state.freepage = freecbzpage;
514 break;
518 static void pdfinfo (void)
520 if (state.type == DPDF) {
521 pdf_obj *infoobj;
523 printd ("info PDF version\t%d.%d",
524 state.u.pdf->version / 10, state.u.pdf->version % 10);
526 infoobj = pdf_dict_gets (state.u.pdf->trailer, "Info");
527 if (infoobj) {
528 int i;
529 char *s;
530 char *items[] = { "Title", "Author", "Creator",
531 "Producer", "CreationDate" };
533 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
534 pdf_obj *obj = pdf_dict_gets (infoobj, items[i]);
535 s = pdf_to_utf8 (state.u.pdf, obj);
536 if (*s) {
537 if (i == 0) {
538 printd ("title %s", s);
540 printd ("info %s\t%s", items[i], s);
542 fz_free (state.ctx, s);
545 printd ("infoend");
549 static void unlinktile (struct tile *tile)
551 int i;
553 for (i = 0; i < tile->slicecount; ++i) {
554 struct slice *s = &tile->slices[i];
556 if (s->texindex != -1) {
557 if (state.texowners[s->texindex].slice == s) {
558 state.texowners[s->texindex].slice = NULL;
564 static void freepage (struct page *page)
566 if (page->text) {
567 fz_free_text_page (state.ctx, page->text);
569 if (page->sheet) {
570 fz_free_text_sheet (state.ctx, page->sheet);
572 if (page->slinks) {
573 free (page->slinks);
575 page->freepage (page->u.ptr);
576 fz_free_display_list (state.ctx, page->dlist);
577 free (page);
580 static void freetile (struct tile *tile)
582 unlinktile (tile);
583 if (!tile->pbo) {
584 #ifndef PIGGYBACK
585 fz_drop_pixmap (state.ctx, tile->pixmap);
586 #else
587 if (state.pig) {
588 fz_drop_pixmap (state.ctx, state.pig);
590 state.pig = tile->pixmap;
591 #endif
593 else {
594 free (tile->pbo);
595 fz_drop_pixmap (state.ctx, tile->pixmap);
597 free (tile);
600 #ifdef __ALTIVEC__
601 #include <stdint.h>
602 #include <altivec.h>
604 static int cacheline32bytes;
606 static void __attribute__ ((constructor)) clcheck (void)
608 char **envp = environ;
609 unsigned long *auxv;
611 while (*envp++);
613 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
614 if (*auxv == 19) {
615 cacheline32bytes = auxv[1] == 32;
616 return;
621 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
623 size_t size = pixmap->w * pixmap->h * pixmap->n;
624 if (cacheline32bytes && size > 32) {
625 intptr_t a1, a2, diff;
626 size_t sizea, i;
627 vector unsigned char v = vec_splat_u8 (-1);
628 vector unsigned char *p;
630 a1 = a2 = (intptr_t) pixmap->samples;
631 a2 = (a1 + 31) & ~31;
632 diff = a2 - a1;
633 sizea = size - diff;
634 p = (void *) a2;
636 while (a1 != a2) *(char *) a1++ = 0xff;
637 for (i = 0; i < (sizea & ~31); i += 32) {
638 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
639 vec_st (v, i, p);
640 vec_st (v, i + 16, p);
642 while (i < sizea) *((char *) a1 + i++) = 0xff;
644 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
646 #else
647 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
648 #endif
650 static void trimctm (pdf_page *page, int pindex)
652 fz_matrix ctm;
653 struct pagedim *pdim = &state.pagedims[pindex];
655 if (!pdim->tctmready) {
656 if (state.trimmargins) {
657 fz_rect realbox;
658 fz_matrix rm, sm, tm, im, ctm1;
660 fz_rotate (&rm, -pdim->rotate);
661 fz_scale (&sm, 1, -1);
662 fz_concat (&ctm, &rm, &sm);
663 realbox = pdim->mediabox;
664 fz_transform_rect (&realbox, &ctm);
665 fz_translate (&tm, -realbox.x0, -realbox.y0);
666 fz_concat (&ctm1, &ctm, &tm);
667 fz_invert_matrix (&im, &page->ctm);
668 fz_concat (&ctm, &im, &ctm1);
670 else {
671 ctm = fz_identity;
673 pdim->tctm = ctm;
674 pdim->tctmready = 1;
678 static fz_matrix pagectm (struct page *page)
680 fz_matrix ctm, tm;
682 if (page->type == DPDF) {
683 trimctm (page->u.pdfpage, page->pdimno);
684 fz_concat (&ctm,
685 &state.pagedims[page->pdimno].tctm,
686 &state.pagedims[page->pdimno].ctm);
688 else {
689 struct pagedim *pdim = &state.pagedims[page->pdimno];
691 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
692 fz_concat (&ctm, &tm, &state.pagedims[page->pdimno].ctm);
694 return ctm;
697 static void *loadpage (int pageno, int pindex)
699 fz_device *dev;
700 struct page *page = NULL;
702 page = calloc (sizeof (struct page), 1);
703 if (!page) {
704 err (1, "calloc page %d", pageno);
707 page->dlist = fz_new_display_list (state.ctx);
708 dev = fz_new_list_device (state.ctx, page->dlist);
709 fz_try (state.ctx) {
710 switch (state.type) {
711 case DPDF:
712 page->u.pdfpage = pdf_load_page (state.u.pdf, pageno);
713 pdf_run_page (state.u.pdf, page->u.pdfpage, dev,
714 &fz_identity, NULL);
715 page->freepage = freepdfpage;
716 break;
718 case DXPS:
719 page->u.xpspage = xps_load_page (state.u.xps, pageno);
720 xps_run_page (state.u.xps, page->u.xpspage, dev,
721 &fz_identity, NULL);
722 page->freepage = freexpspage;
723 break;
725 case DCBZ:
726 page->u.cbzpage = cbz_load_page (state.u.cbz, pageno);
727 cbz_run_page (state.u.cbz, page->u.cbzpage, dev,
728 &fz_identity, NULL);
729 page->freepage = freecbzpage;
730 break;
733 fz_catch (state.ctx) {
734 page->u.ptr = NULL;
735 page->freepage = freeemptyxxxpage;
737 fz_free_device (dev);
739 page->pdimno = pindex;
740 page->pageno = pageno;
741 page->sgen = state.gen;
742 page->tgen = state.gen;
743 page->type = state.type;
745 return page;
748 static struct tile *alloctile (int h)
750 int i;
751 int slicecount;
752 size_t tilesize;
753 struct tile *tile;
755 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
756 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
757 tile = calloc (tilesize, 1);
758 if (!tile) {
759 err (1, "can not allocate tile (%" FMT_s " bytes)", tilesize);
761 for (i = 0; i < slicecount; ++i) {
762 int sh = MIN (h, state.sliceheight);
763 tile->slices[i].h = sh;
764 tile->slices[i].texindex = -1;
765 h -= sh;
767 tile->slicecount = slicecount;
768 tile->sliceheight = state.sliceheight;
769 return tile;
772 #ifdef OBSCURED_OPT
773 struct obs {
774 int cured;
775 fz_irect b;
778 static void obs_fill_image (fz_device *dev, fz_image *image,
779 const fz_matrix *ctm, float alpha)
781 struct obs *obs = dev->user;
783 if (!obs->cured && fabs (1.0 - alpha) < 1e6) {
784 fz_irect b;
785 fz_rect rect = fz_unit_rect;
787 fz_transform_rect (&rect, ctm);
788 fz_round_rect (&b, &rect);
789 fz_intersect_irect (&b, &obs->b);
790 obs->cured = b.x0 == obs->b.x0
791 && b.x1 == obs->b.x1
792 && b.y0 == obs->b.y0
793 && b.y1 == obs->b.y1;
797 static int obscured (struct page *page, fz_irect bbox)
799 fz_rect rect;
800 fz_matrix ctm;
801 fz_device dev;
802 struct obs obs;
804 memset (&dev, 0, sizeof (dev));
805 memset (&obs, 0, sizeof (obs));
806 dev.hints = 0;
807 dev.flags = 0;
808 dev.user = &obs;
809 dev.ctx = state.ctx;
810 dev.fill_image = obs_fill_image;
811 obs.b = bbox;
812 fz_rect_from_irect (&rect, &bbox);
813 ctm = pagectm (page);
814 fz_run_display_list (page->dlist, &dev, &ctm, &rect, NULL);
815 return obs.cured;
817 #define OBSCURED obscured
818 #else
819 #define OBSCURED(a, b) 0
820 #endif
822 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
823 struct pbo *pbo)
825 fz_rect rect;
826 fz_irect bbox;
827 fz_matrix ctm;
828 fz_device *dev;
829 struct tile *tile;
830 struct pagedim *pdim;
832 tile = alloctile (h);
833 pdim = &state.pagedims[page->pdimno];
835 bbox = pdim->bounds;
836 bbox.x0 += x;
837 bbox.y0 += y;
838 bbox.x1 = bbox.x0 + w;
839 bbox.y1 = bbox.y0 + h;
841 if (state.pig) {
842 if (state.pig->w == w
843 && state.pig->h == h
844 && state.pig->colorspace == state.colorspace) {
845 tile->pixmap = state.pig;
846 tile->pixmap->x = bbox.x0;
847 tile->pixmap->y = bbox.y0;
849 else {
850 fz_drop_pixmap (state.ctx, state.pig);
852 state.pig = NULL;
854 if (!tile->pixmap) {
855 if (pbo) {
856 tile->pixmap =
857 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
858 &bbox, pbo->ptr);
859 tile->pbo = pbo;
861 else {
862 tile->pixmap =
863 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
867 tile->w = w;
868 tile->h = h;
869 if (!page->u.ptr || ((w < 128 && h < 128) || !OBSCURED (page, bbox))) {
870 clearpixmap (tile->pixmap);
872 dev = fz_new_draw_device (state.ctx, tile->pixmap);
873 ctm = pagectm (page);
874 fz_rect_from_irect (&rect, &bbox);
875 fz_run_display_list (page->dlist, dev, &ctm, &rect, NULL);
876 fz_free_device (dev);
878 return tile;
881 static void initpdims (void)
883 double start, end;
884 int pageno, trim, show;
885 FILE *trimf = NULL;
886 int trimw = 0;
888 start = now ();
890 if (state.trimmargins && state.trimcachepath) {
891 trimf = fopen (state.trimcachepath, "rb");
892 if (!trimf) {
893 trimf = fopen (state.trimcachepath, "wb");
894 trimw = 1;
897 for (pageno = 0; pageno < state.pagecount; ++pageno) {
898 int rotate = 0;
899 struct pagedim *p;
900 fz_rect mediabox;
902 switch (state.type) {
903 case DPDF: {
904 pdf_obj *pageobj = state.u.pdf->page_objs[pageno];
906 if (state.trimmargins) {
907 pdf_obj *obj;
908 pdf_page *page;
910 fz_try (state.ctx) {
911 page = pdf_load_page (state.u.pdf, pageno);
912 obj = pdf_dict_gets (pageobj, "llpp.TrimBox");
913 trim = state.trimanew || !obj;
914 if (trim) {
915 fz_rect rect;
916 fz_matrix ctm;
917 fz_device *dev;
919 dev = fz_new_bbox_device (state.ctx, &rect);
920 dev->hints |= FZ_IGNORE_SHADE;
921 fz_invert_matrix (&ctm, &page->ctm);
922 pdf_run_page (state.u.pdf, page, dev,
923 &fz_identity, NULL);
924 fz_free_device (dev);
926 rect.x0 += state.trimfuzz.x0;
927 rect.x1 += state.trimfuzz.x1;
928 rect.y0 += state.trimfuzz.y0;
929 rect.y1 += state.trimfuzz.y1;
930 fz_transform_rect (&rect, &ctm);
931 fz_intersect_rect (&rect, &page->mediabox);
933 if (fz_is_empty_rect (&rect)) {
934 mediabox = page->mediabox;
936 else {
937 mediabox = rect;
940 obj = pdf_new_array (state.ctx, 4);
941 pdf_array_push (obj,
942 pdf_new_real (state.ctx, mediabox.x0));
943 pdf_array_push (obj,
944 pdf_new_real (state.ctx, mediabox.y0));
945 pdf_array_push (obj,
946 pdf_new_real (state.ctx, mediabox.x1));
947 pdf_array_push (obj,
948 pdf_new_real (state.ctx, mediabox.y1));
949 pdf_dict_puts (pageobj, "llpp.TrimBox", obj);
951 else {
952 mediabox.x0 = pdf_to_real (pdf_array_get (obj, 0));
953 mediabox.y0 = pdf_to_real (pdf_array_get (obj, 1));
954 mediabox.x1 = pdf_to_real (pdf_array_get (obj, 2));
955 mediabox.y1 = pdf_to_real (pdf_array_get (obj, 3));
958 rotate = page->rotate;
959 pdf_free_page (state.u.pdf, page);
961 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
962 if (show) {
963 printd ("progress %f Trimming %d",
964 (double) (pageno + 1) / state.pagecount,
965 pageno + 1);
968 fz_catch (state.ctx) {
969 fprintf (stderr, "failed to load page %d\n", pageno+1);
972 else {
973 fz_rect cropbox;
975 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "MediaBox"),
976 &mediabox);
977 if (fz_is_empty_rect (&mediabox)) {
978 fprintf (stderr, "cannot find page size for page %d\n",
979 pageno+1);
980 mediabox.x0 = 0;
981 mediabox.y0 = 0;
982 mediabox.x1 = 612;
983 mediabox.y1 = 792;
986 pdf_to_rect (state.ctx, pdf_dict_gets (pageobj, "CropBox"),
987 &cropbox);
988 if (!fz_is_empty_rect (&cropbox)) {
989 fz_intersect_rect (&mediabox, &cropbox);
991 rotate = pdf_to_int (pdf_dict_gets (pageobj, "Rotate"));
993 break;
996 case DXPS:
998 xps_page *page;
1000 fz_try (state.ctx) {
1001 page = xps_load_page (state.u.xps, pageno);
1002 xps_bound_page (state.u.xps, page, &mediabox);
1003 rotate = 0;
1004 if (state.trimmargins) {
1005 fz_rect rect;
1006 fz_device *dev;
1008 dev = fz_new_bbox_device (state.ctx, &rect);
1009 dev->hints |= FZ_IGNORE_SHADE;
1010 xps_run_page (state.u.xps, page, dev,
1011 &fz_identity, NULL);
1012 fz_free_device (dev);
1014 rect.x0 += state.trimfuzz.x0;
1015 rect.x1 += state.trimfuzz.x1;
1016 rect.y0 += state.trimfuzz.y0;
1017 rect.y1 += state.trimfuzz.y1;
1018 fz_intersect_rect (&rect, &mediabox);
1020 if (!fz_is_empty_rect (&rect)) {
1021 mediabox = rect;
1024 xps_free_page (state.u.xps, page);
1025 printd ("progress %f loading %d",
1026 (double) (pageno + 1) / state.pagecount,
1027 pageno + 1);
1029 fz_catch (state.ctx) {
1032 break;
1034 case DCBZ:
1036 rotate = 0;
1037 if (state.trimmargins && trimw) {
1038 cbz_page *page;
1040 fz_try (state.ctx) {
1041 page = cbz_load_page (state.u.cbz, pageno);
1042 cbz_bound_page (state.u.cbz, page, &mediabox);
1043 cbz_free_page (state.u.cbz, page);
1044 printd ("progress %f Trimming %d",
1045 (double) (pageno + 1) / state.pagecount,
1046 pageno + 1);
1048 fz_catch (state.ctx) {
1049 fprintf (stderr, "failed to load page %d\n", pageno+1);
1050 mediabox.x0 = 0;
1051 mediabox.y0 = 0;
1052 mediabox.x1 = 900;
1053 mediabox.y1 = 900;
1055 if (trimf) {
1056 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1057 if (n - 1) {
1058 err (1, "fwrite trim mediabox");
1062 else {
1063 if (trimf) {
1064 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1065 if (n - 1) {
1066 err (1, "fread trim mediabox");
1069 else {
1070 mediabox.x0 = mediabox.y0 = 0;
1071 mediabox.x1 = 900;
1072 mediabox.y1 = 900;
1076 break;
1078 default:
1079 ARSERT (0 && state.type);
1082 if (state.pagedimcount == 0
1083 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1084 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1085 size_t size;
1087 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1088 state.pagedims = realloc (state.pagedims, size);
1089 if (!state.pagedims) {
1090 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1091 size, state.pagedimcount + 1);
1094 p = &state.pagedims[state.pagedimcount++];
1095 p->rotate = rotate;
1096 p->mediabox = mediabox;
1097 p->pageno = pageno;
1100 end = now ();
1101 if (state.trimmargins) {
1102 printd ("progress 1 Trimmed %d pages in %f seconds",
1103 state.pagecount, end - start);
1105 else {
1106 printd ("vmsg Processed %d pages in %f seconds",
1107 state.pagecount, end - start);
1109 state.trimanew = 0;
1110 if (trimf) {
1111 if (fclose (trimf)) {
1112 err (1, "fclose");
1117 static void layout (void)
1119 int pindex;
1120 fz_rect box;
1121 fz_matrix ctm, rm;
1122 struct pagedim *p = p;
1123 double zw, w, maxw = 0.0, zoom = zoom;
1125 if (state.pagedimcount == 0) return;
1127 switch (state.fitmodel) {
1128 case FitProportional:
1129 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1130 double x0, x1;
1132 p = &state.pagedims[pindex];
1133 fz_rotate (&rm, p->rotate + state.rotate);
1134 box = p->mediabox;
1135 fz_transform_rect (&box, &rm);
1137 x0 = MIN (box.x0, box.x1);
1138 x1 = MAX (box.x0, box.x1);
1140 w = x1 - x0;
1141 maxw = MAX (w, maxw);
1142 zoom = state.w / maxw;
1144 break;
1146 case FitPage:
1147 maxw = state.w;
1148 break;
1150 case FitWidth:
1151 break;
1153 default:
1154 ARSERT (0 && state.fitmodel);
1157 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1158 fz_rect rect;
1159 fz_matrix tm, sm;
1161 p = &state.pagedims[pindex];
1162 fz_rotate (&ctm, state.rotate);
1163 fz_rotate (&rm, p->rotate + state.rotate);
1164 box = p->mediabox;
1165 fz_transform_rect (&box, &rm);
1166 w = box.x1 - box.x0;
1167 switch (state.fitmodel) {
1168 case FitProportional:
1169 p->left = ((maxw - w) * zoom) / 2.0;
1170 break;
1171 case FitPage:
1173 double zh, h;
1174 zw = maxw / w;
1175 h = box.y1 - box.y0;
1176 zh = state.h / h;
1177 zoom = MIN (zw, zh);
1178 p->left = (maxw - (w * zoom)) / 2.0;
1180 break;
1181 case FitWidth:
1182 p->left = 0;
1183 zoom = state.w / w;
1184 break;
1187 fz_scale (&p->zoomctm, zoom, zoom);
1188 fz_concat (&ctm, &p->zoomctm, &ctm);
1190 fz_rotate (&rm, p->rotate);
1191 p->pagebox = p->mediabox;
1192 fz_transform_rect (&p->pagebox, &rm);
1193 p->pagebox.x1 -= p->pagebox.x0;
1194 p->pagebox.y1 -= p->pagebox.y0;
1195 p->pagebox.x0 = 0;
1196 p->pagebox.y0 = 0;
1197 rect = p->pagebox;
1198 fz_transform_rect (&rect, &ctm);
1199 fz_round_rect (&p->bounds, &rect);
1200 p->ctm = ctm;
1202 fz_translate (&tm, 0, -p->mediabox.y1);
1203 fz_scale (&sm, zoom, -zoom);
1204 fz_concat (&ctm, &tm, &sm);
1205 fz_concat (&p->lctm, &ctm, &rm);
1207 p->tctmready = 0;
1210 do {
1211 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1212 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1213 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1214 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1215 int w = x1 - x0;
1216 int h = y1 - y0;
1218 printd ("pdim %d %d %d %d", p->pageno, w, h, p->left);
1219 } while (p-- != state.pagedims);
1222 static
1223 struct anchor { int n; int x; int y; int w; int h; }
1224 desttoanchor (fz_link_dest *dest)
1226 int i;
1227 struct anchor a;
1228 struct pagedim *pdim = state.pagedims;
1230 a.n = -1;
1231 a.x = 0;
1232 a.y = 0;
1233 for (i = 0; i < state.pagedimcount; ++i) {
1234 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1235 break;
1236 pdim = &state.pagedims[i];
1238 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1239 fz_point p;
1240 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1241 p.x = dest->ld.gotor.lt.x;
1242 p.y = dest->ld.gotor.lt.y;
1243 fz_transform_point (&p, &pdim->lctm);
1244 a.y = p.y;
1245 a.x = p.x;
1247 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1248 double x0, x1, y0, y1;
1250 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1251 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1252 a.w = x1 - x0;
1253 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1254 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1255 a.h = y1 - y0;
1256 a.n = dest->ld.gotor.page;
1258 return a;
1261 static void recurse_outline (fz_outline *outline, int level)
1263 while (outline) {
1264 struct anchor a = desttoanchor (&outline->dest);
1266 if (a.n >= 0) {
1267 printd ("o %d %d %d %d %s",
1268 level, a.n, a.y, a.h, outline->title);
1270 if (outline->down) {
1271 recurse_outline (outline->down, level + 1);
1273 outline = outline->next;
1277 static void process_outline (void)
1279 fz_outline *outline;
1281 if (!state.needoutline) return;
1283 state.needoutline = 0;
1284 switch (state.type) {
1285 case DPDF:
1286 outline = pdf_load_outline (state.u.pdf);
1287 break;
1288 case DXPS:
1289 outline = xps_load_outline (state.u.xps);
1290 break;
1291 default:
1292 outline = NULL;
1293 break;
1295 if (outline) {
1296 recurse_outline (outline, 0);
1297 fz_free_outline (state.ctx, outline);
1301 static char *strofspan (fz_text_span *span)
1303 char *p;
1304 char utf8[10];
1305 fz_text_char *ch;
1306 size_t size = 0, cap = 80;
1308 p = malloc (cap + 1);
1309 if (!p) return NULL;
1311 for (ch = span->text; ch < span->text + span->len; ++ch) {
1312 int n = fz_runetochar (utf8, ch->c);
1313 if (size + n > cap) {
1314 cap *= 2;
1315 p = realloc (p, cap + 1);
1316 if (!p) return NULL;
1319 memcpy (p + size, utf8, n);
1320 size += n;
1322 p[size] = 0;
1323 return p;
1326 static int matchspan (regex_t *re, fz_text_page *page,
1327 fz_text_span *span, fz_matrix ctm,
1328 int stop, int pageno, double start)
1330 int ret;
1331 char *p;
1332 regmatch_t rm;
1333 int a, b, c;
1334 fz_rect sb, eb;
1335 fz_point p1, p2, p3, p4;
1337 p = strofspan (span);
1338 if (!p) return -1;
1340 ret = regexec (re, p, 1, &rm, 0);
1341 if (ret) {
1342 free (p);
1343 if (ret != REG_NOMATCH) {
1344 size_t size;
1345 char errbuf[80];
1346 size = regerror (ret, re, errbuf, sizeof (errbuf));
1347 printd ("msg regexec error `%.*s'",
1348 (int) size, errbuf);
1349 return -1;
1351 return 0;
1353 else {
1354 int l = span->len;
1356 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1357 c += fz_runelen (span->text[a].c);
1359 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1360 c += fz_runelen (span->text[b].c);
1363 if (fz_runelen (span->text[b].c) > 1) {
1364 b = MAX (0, b-1);
1367 fz_text_char_bbox (&sb, span, a);
1368 fz_text_char_bbox (&eb, span, b);
1370 p1.x = sb.x0;
1371 p1.y = sb.y0;
1372 p2.x = eb.x1;
1373 p2.y = sb.y0;
1374 p3.x = eb.x1;
1375 p3.y = eb.y1;
1376 p4.x = sb.x0;
1377 p4.y = eb.y1;
1379 if (!stop) {
1380 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1381 pageno, 1,
1382 p1.x, p1.y,
1383 p2.x, p2.y,
1384 p3.x, p3.y,
1385 p4.x, p4.y);
1387 printd ("progress 1 found at %d `%.*s' in %f sec",
1388 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1389 now () - start);
1391 else {
1392 printd ("match %d %d %f %f %f %f %f %f %f %f",
1393 pageno, 2,
1394 p1.x, p1.y,
1395 p2.x, p2.y,
1396 p3.x, p3.y,
1397 p4.x, p4.y);
1399 free (p);
1400 return 1;
1404 static int compareblocks (const void *l, const void *r)
1406 fz_text_block const *ls = l;
1407 fz_text_block const* rs = r;
1408 return ls->bbox.y0 - rs->bbox.y0;
1411 /* wishful thinking function */
1412 static void search (regex_t *re, int pageno, int y, int forward)
1414 int i, j;
1415 fz_matrix ctm;
1416 fz_device *tdev;
1417 union { void *ptr; pdf_page *pdfpage; xps_page *xpspage; } u;
1418 fz_text_page *text;
1419 fz_text_sheet *sheet;
1420 struct pagedim *pdim, *pdimprev;
1421 int stop = 0, niters = 0;
1422 double start, end;
1424 if (!(state.type == DPDF || state.type == DXPS))
1425 return;
1427 start = now ();
1428 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1429 if (niters++ == 5) {
1430 niters = 0;
1431 if (hasdata ()) {
1432 printd ("progress 1 attention requested aborting search at %d",
1433 pageno);
1434 stop = 1;
1436 else {
1437 printd ("progress %f searching in page %d",
1438 (double) (pageno + 1) / state.pagecount,
1439 pageno);
1442 pdimprev = NULL;
1443 for (i = 0; i < state.pagedimcount; ++i) {
1444 pdim = &state.pagedims[i];
1445 if (pdim->pageno == pageno) {
1446 goto found;
1448 if (pdim->pageno > pageno) {
1449 pdim = pdimprev;
1450 goto found;
1452 pdimprev = pdim;
1454 pdim = pdimprev;
1455 found:
1457 sheet = fz_new_text_sheet (state.ctx);
1458 text = fz_new_text_page (state.ctx, &fz_infinite_rect);
1459 tdev = fz_new_text_device (state.ctx, sheet, text);
1461 switch (state.type) {
1462 case DPDF:
1463 u.ptr = NULL;
1464 fz_try (state.ctx) {
1465 u.pdfpage = pdf_load_page (state.u.pdf, pageno);
1466 trimctm (u.pdfpage, pdim - state.pagedims);
1467 fz_concat (&ctm, &pdim->tctm, &pdim->zoomctm);
1468 pdf_run_page (state.u.pdf, u.pdfpage, tdev, &ctm, NULL);
1470 fz_catch (state.ctx) {
1471 fz_free_device (tdev);
1472 u.ptr = NULL;
1473 goto nextiter;
1475 break;
1477 case DXPS:
1478 u.xpspage = xps_load_page (state.u.xps, pageno);
1479 xps_run_page (state.u.xps, u.xpspage, tdev, &pdim->ctm, NULL);
1480 break;
1482 default:
1483 ARSERT (0 && state.type);
1486 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1487 fz_free_device (tdev);
1489 for (j = 0; j < text->len; ++j) {
1490 int k;
1491 fz_page_block *pb;
1492 fz_text_block *block;
1494 pb = &text->blocks[forward ? j : text->len - 1 - j];
1495 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1496 block = pb->u.text;
1498 for (k = 0; k < block->len; ++k) {
1499 fz_text_line *line;
1500 fz_text_span *span;
1502 if (forward) {
1503 line = &block->lines[k];
1504 if (line->bbox.y0 < y + 1) continue;
1506 else {
1507 line = &block->lines[block->len - 1 - k];
1508 if (line->bbox.y0 > y - 1) continue;
1511 for (span = line->first_span; span; span = span->next) {
1512 switch (matchspan (re, text, span, ctm,
1513 stop, pageno, start)) {
1514 case 0: break;
1515 case 1: stop = 1; break;
1516 case -1: stop = 1; goto endloop;
1521 nextiter:
1522 if (forward) {
1523 pageno += 1;
1524 y = 0;
1526 else {
1527 pageno -= 1;
1528 y = INT_MAX;
1530 endloop:
1531 fz_free_text_page (state.ctx, text);
1532 fz_free_text_sheet (state.ctx, sheet);
1533 if (u.ptr) {
1534 state.freepage (u.ptr);
1537 end = now ();
1538 if (!stop) {
1539 printd ("progress 1 no matches %f sec", end - start);
1541 printd ("clearrects");
1544 static void set_tex_params (int colorspace)
1546 union {
1547 unsigned char b;
1548 unsigned int s;
1549 } endianness = {1};
1551 switch (colorspace) {
1552 case 0:
1553 state.texiform = GL_RGBA8;
1554 state.texform = GL_RGBA;
1555 state.texty = GL_UNSIGNED_BYTE;
1556 state.colorspace = fz_device_rgb (state.ctx);
1557 break;
1558 case 1:
1559 state.texiform = GL_RGBA8;
1560 state.texform = GL_BGRA;
1561 state.texty = endianness.s > 1
1562 ? GL_UNSIGNED_INT_8_8_8_8
1563 : GL_UNSIGNED_INT_8_8_8_8_REV;
1564 state.colorspace = fz_device_bgr (state.ctx);
1565 break;
1566 case 2:
1567 state.texiform = GL_LUMINANCE_ALPHA;
1568 state.texform = GL_LUMINANCE_ALPHA;
1569 state.texty = GL_UNSIGNED_BYTE;
1570 state.colorspace = fz_device_gray (state.ctx);
1571 break;
1572 default:
1573 errx (1, "invalid colorspce %d", colorspace);
1577 static void realloctexts (int texcount)
1579 size_t size;
1581 if (texcount == state.texcount) return;
1583 if (texcount < state.texcount) {
1584 glDeleteTextures (state.texcount - texcount,
1585 state.texids + texcount);
1588 size = texcount * sizeof (*state.texids);
1589 state.texids = realloc (state.texids, size);
1590 if (!state.texids) {
1591 err (1, "realloc texids %" FMT_s, size);
1594 size = texcount * sizeof (*state.texowners);
1595 state.texowners = realloc (state.texowners, size);
1596 if (!state.texowners) {
1597 err (1, "realloc texowners %" FMT_s, size);
1599 if (texcount > state.texcount) {
1600 int i;
1602 glGenTextures (texcount - state.texcount,
1603 state.texids + state.texcount);
1604 for (i = state.texcount; i < texcount; ++i) {
1605 state.texowners[i].w = -1;
1606 state.texowners[i].slice = NULL;
1609 state.texcount = texcount;
1610 state.texindex = 0;
1613 static char *mbtoutf8 (char *s)
1615 char *p, *r;
1616 wchar_t *tmp;
1617 size_t i, ret, len;
1619 len = mbstowcs (NULL, s, strlen (s));
1620 if (len == 0) {
1621 return s;
1623 else {
1624 if (len == (size_t) -1) {
1625 return s;
1629 tmp = malloc (len * sizeof (wchar_t));
1630 if (!tmp) {
1631 return s;
1634 ret = mbstowcs (tmp, s, len);
1635 if (ret == (size_t) -1) {
1636 free (tmp);
1637 return s;
1640 len = 0;
1641 for (i = 0; i < ret; ++i) {
1642 len += fz_runelen (tmp[i]);
1645 p = r = malloc (len + 1);
1646 if (!r) {
1647 free (tmp);
1648 return s;
1651 for (i = 0; i < ret; ++i) {
1652 p += fz_runetochar (p, tmp[i]);
1654 *p = 0;
1655 free (tmp);
1656 return r;
1659 CAMLprim value ml_mbtoutf8 (value s_v)
1661 CAMLparam1 (s_v);
1662 CAMLlocal1 (ret_v);
1663 char *s, *r;
1665 s = String_val (s_v);
1666 r = mbtoutf8 (s);
1667 if (r == s) {
1668 ret_v = s_v;
1670 else {
1671 ret_v = caml_copy_string (r);
1672 free (r);
1674 CAMLreturn (ret_v);
1677 static void * mainloop (void *unused)
1679 char *p = NULL;
1680 int len, ret, oldlen = 0;
1682 for (;;) {
1683 len = readlen ();
1684 if (len == 0) {
1685 errx (1, "readlen returned 0");
1688 if (oldlen < len + 1) {
1689 p = realloc (p, len + 1);
1690 if (!p) {
1691 err (1, "realloc %d failed", len + 1);
1693 oldlen = len + 1;
1695 readdata (p, len);
1696 p[len] = 0;
1698 if (!strncmp ("open", p, 4)) {
1699 size_t filenamelen;
1700 int wthack, off;
1701 char *password;
1702 char *filename;
1703 char *utf8filename;
1705 ret = sscanf (p + 5, " %d %n", &wthack, &off);
1706 if (ret != 1) {
1707 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1710 filename = p + 5 + off;
1711 filenamelen = strlen (filename);
1712 password = filename + filenamelen + 1;
1714 lock ("open");
1715 openxref (filename, password);
1716 pdfinfo ();
1717 initpdims ();
1718 unlock ("open");
1720 if (!wthack) {
1721 utf8filename = mbtoutf8 (filename);
1722 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1723 if (utf8filename != filename) {
1724 free (utf8filename);
1727 state.needoutline = 1;
1729 else if (!strncmp ("cs", p, 2)) {
1730 int i, colorspace;
1732 ret = sscanf (p + 2, " %d", &colorspace);
1733 if (ret != 1) {
1734 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1736 lock ("cs");
1737 set_tex_params (colorspace);
1738 for (i = 0; i < state.texcount; ++i) {
1739 state.texowners[i].w = -1;
1740 state.texowners[i].slice = NULL;
1742 unlock ("cs");
1744 else if (!strncmp ("freepage", p, 8)) {
1745 void *ptr;
1747 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1748 if (ret != 1) {
1749 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1751 freepage (ptr);
1753 else if (!strncmp ("freetile", p, 8)) {
1754 void *ptr;
1756 ret = sscanf (p + 8, " %" FMT_ptr, FMT_ptr_cast (&ptr));
1757 if (ret != 1) {
1758 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1760 freetile (ptr);
1762 else if (!strncmp ("search", p, 6)) {
1763 int icase, pageno, y, ret, len2, forward;
1764 char *pattern;
1765 regex_t re;
1767 ret = sscanf (p + 6, " %d %d %d %d,%n",
1768 &icase, &pageno, &y, &forward, &len2);
1769 if (ret != 4) {
1770 errx (1, "malformed search `%s' ret=%d", p, ret);
1773 pattern = p + 6 + len2;
1774 ret = regcomp (&re, pattern,
1775 REG_EXTENDED | (icase ? REG_ICASE : 0));
1776 if (ret) {
1777 char errbuf[80];
1778 size_t size;
1780 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1781 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1783 else {
1784 search (&re, pageno, y, forward);
1785 regfree (&re);
1788 else if (!strncmp ("geometry", p, 8)) {
1789 int w, h, fitmodel;
1791 printd ("clear");
1792 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1793 if (ret != 3) {
1794 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1797 lock ("geometry");
1798 state.h = h;
1799 if (w != state.w) {
1800 int i;
1801 state.w = w;
1802 for (i = 0; i < state.texcount; ++i) {
1803 state.texowners[i].slice = NULL;
1806 state.fitmodel = fitmodel;
1807 layout ();
1808 process_outline ();
1810 state.gen++;
1811 unlock ("geometry");
1812 printd ("continue %d", state.pagecount);
1814 else if (!strncmp ("reqlayout", p, 9)) {
1815 char *nameddest;
1816 int rotate, fitmodel, off, h;
1818 printd ("clear");
1819 ret = sscanf (p + 9, " %d %d %d %n",
1820 &rotate, &fitmodel, &h, &off);
1821 if (ret != 3) {
1822 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1824 lock ("reqlayout");
1825 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1826 state.gen += 1;
1828 state.rotate = rotate;
1829 state.fitmodel = fitmodel;
1830 state.h = h;
1831 layout ();
1832 process_outline ();
1834 nameddest = p + 9 + off;
1835 if (state.type == DPDF && nameddest && *nameddest) {
1836 struct anchor a;
1837 fz_link_dest dest;
1838 pdf_obj *needle, *obj;
1840 needle = pdf_new_string (state.ctx, nameddest,
1841 strlen (nameddest));
1842 obj = pdf_lookup_dest (state.u.pdf, needle);
1843 if (obj) {
1844 dest = pdf_parse_link_dest (state.u.pdf, obj);
1846 a = desttoanchor (&dest);
1847 if (a.n >= 0) {
1848 printd ("a %d %d %d", a.n, a.x, a.y);
1850 else {
1851 printd ("emsg failed to parse destination `%s'\n",
1852 nameddest);
1855 else {
1856 printd ("emsg destination `%s' not found\n",
1857 nameddest);
1859 pdf_drop_obj (needle);
1862 state.gen++;
1863 unlock ("reqlayout");
1864 printd ("continue %d", state.pagecount);
1866 else if (!strncmp ("page", p, 4)) {
1867 double a, b;
1868 struct page *page;
1869 int pageno, pindex, ret;
1871 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1872 if (ret != 2) {
1873 errx (1, "bad render line `%.*s' ret=%d", len, p, ret);
1876 lock ("page");
1877 a = now ();
1878 page = loadpage (pageno, pindex);
1879 b = now ();
1880 unlock ("page");
1882 printd ("page %" FMT_ptr " %f", FMT_ptr_cast2 (page), b - a);
1884 else if (!strncmp ("tile", p, 4)) {
1885 int x, y, w, h, ret;
1886 struct page *page;
1887 struct tile *tile;
1888 double a, b;
1889 void *data;
1891 ret = sscanf (p + 4, " %" FMT_ptr " %d %d %d %d %" FMT_ptr,
1892 FMT_ptr_cast (&page), &x, &y, &w, &h, &data);
1893 if (ret != 6) {
1894 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1897 lock ("tile");
1898 a = now ();
1899 tile = rendertile (page, x, y, w, h, data);
1900 b = now ();
1901 unlock ("tile");
1903 printd ("tile %d %d %" FMT_ptr " %u %f",
1904 x, y,
1905 FMT_ptr_cast2 (tile),
1906 tile->w * tile->h * tile->pixmap->n,
1907 b - a);
1909 else if (!strncmp ("settrim", p, 7)) {
1910 fz_irect fuzz;
1911 int trimmargins;
1913 ret = sscanf (p + 7, " %d %d %d %d %d",
1914 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1915 if (ret != 5) {
1916 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1918 printd ("clear");
1919 lock ("settrim");
1920 state.trimmargins = trimmargins;
1921 state.needoutline = 1;
1922 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1923 state.trimanew = 1;
1924 state.trimfuzz = fuzz;
1926 state.pagedimcount = 0;
1927 free (state.pagedims);
1928 state.pagedims = NULL;
1929 initpdims ();
1930 layout ();
1931 process_outline ();
1932 unlock ("settrim");
1933 printd ("continue %d", state.pagecount);
1935 else if (!strncmp ("sliceh", p, 6)) {
1936 int h;
1938 ret = sscanf (p + 6, " %d", &h);
1939 if (ret != 1) {
1940 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1942 if (h != state.sliceheight) {
1943 int i;
1945 state.sliceheight = h;
1946 for (i = 0; i < state.texcount; ++i) {
1947 state.texowners[i].w = -1;
1948 state.texowners[i].h = -1;
1949 state.texowners[i].slice = NULL;
1953 else if (!strncmp ("interrupt", p, 9)) {
1954 printd ("vmsg interrupted");
1956 else {
1957 errx (1, "unknown command %.*s", len, p);
1960 return 0;
1963 CAMLprim value ml_realloctexts (value texcount_v)
1965 CAMLparam1 (texcount_v);
1966 int ok;
1968 if (trylock ("ml_realloctexts")) {
1969 ok = 0;
1970 goto done;
1972 realloctexts (Int_val (texcount_v));
1973 ok = 1;
1974 unlock ("ml_realloctexts");
1976 done:
1977 CAMLreturn (Val_bool (ok));
1980 static void showsel (struct page *page, int ox, int oy)
1982 int seen = 0;
1983 fz_irect bbox;
1984 fz_rect rect;
1985 fz_text_line *line;
1986 fz_page_block *pageb;
1987 fz_text_block *block;
1988 struct mark first, last;
1990 first = page->fmark;
1991 last = page->lmark;
1993 if (!first.span || !last.span) return;
1995 glEnable (GL_BLEND);
1996 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1997 glColor4f (0.5f, 0.5f, 0.0f, 0.6f);
1999 ox += state.pagedims[page->pdimno].bounds.x0;
2000 oy += state.pagedims[page->pdimno].bounds.y0;
2001 for (pageb = page->text->blocks;
2002 pageb < page->text->blocks + page->text->len;
2003 ++pageb) {
2004 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2005 block = pageb->u.text;
2007 for (line = block->lines;
2008 line < block->lines + block->len;
2009 ++line) {
2010 fz_text_span *span;
2011 rect = fz_empty_rect;
2013 for (span = line->first_span; span; span = span->next) {
2014 int i, j, k;
2015 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2017 j = 0;
2018 k = span->len - 1;
2020 if (span == page->fmark.span && span == page->lmark.span) {
2021 seen = 1;
2022 j = MIN (first.i, last.i);
2023 k = MAX (first.i, last.i);
2025 else if (span == first.span) {
2026 seen = 1;
2027 j = first.i;
2029 else if (span == last.span) {
2030 seen = 1;
2031 k = last.i;
2034 if (seen) {
2035 for (i = j; i <= k; ++i) {
2036 fz_rect bbox;
2037 fz_union_rect (&rect,
2038 fz_text_char_bbox (&bbox, span, i));
2040 fz_round_rect (&bbox, &rect);
2041 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2042 bbox.x0,
2043 bbox.y0,
2044 bbox.x1,
2045 bbox.y1,
2046 oy, ox);
2048 glRecti (bbox.x0 + ox, bbox.y0 + oy,
2049 bbox.x1 + ox, bbox.y1 + oy);
2050 if (span == last.span) {
2051 goto done;
2057 done:
2058 glDisable (GL_BLEND);
2061 #include "glfont.c"
2063 static void highlightlinks (struct page *page, int xoff, int yoff)
2065 fz_matrix ctm, tm, pm;
2066 fz_link *link, *links;
2068 switch (page->type) {
2069 case DPDF:
2070 links = page->u.pdfpage->links;
2071 break;
2073 case DXPS:
2074 links = page->u.xpspage->links;
2075 break;
2077 default:
2078 return;
2081 glEnable (GL_TEXTURE_1D);
2082 glEnable (GL_BLEND);
2083 glBindTexture (GL_TEXTURE_1D, state.stid);
2085 xoff -= state.pagedims[page->pdimno].bounds.x0;
2086 yoff -= state.pagedims[page->pdimno].bounds.y0;
2087 fz_translate (&tm, xoff, yoff);
2088 pm = pagectm (page);
2089 fz_concat (&ctm, &pm, &tm);
2091 glBegin (GL_LINES);
2092 for (link = links; link; link = link->next) {
2093 fz_point p1, p2, p3, p4;
2095 p1.x = link->rect.x0;
2096 p1.y = link->rect.y0;
2098 p2.x = link->rect.x1;
2099 p2.y = link->rect.y0;
2101 p3.x = link->rect.x1;
2102 p3.y = link->rect.y1;
2104 p4.x = link->rect.x0;
2105 p4.y = link->rect.y1;
2107 fz_transform_point (&p1, &ctm);
2108 fz_transform_point (&p2, &ctm);
2109 fz_transform_point (&p3, &ctm);
2110 fz_transform_point (&p4, &ctm);
2112 switch (link->dest.kind) {
2113 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2114 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2115 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2116 default: glColor3ub (0, 0, 0); break;
2120 float w, h, s, t;
2122 w = p2.x - p1.x;
2123 h = p2.y - p1.y;
2124 t = sqrtf (w*w + h*h) * .25f;
2126 w = p3.x - p2.x;
2127 h = p3.y - p2.y;
2128 s = sqrtf (w*w + h*h) * .25f;
2130 glTexCoord1i (0);
2131 glVertex2f (p1.x, p1.y);
2132 glTexCoord1f (t);
2133 glVertex2f (p2.x, p2.y);
2135 glTexCoord1i (0);
2136 glVertex2f (p2.x, p2.y);
2137 glTexCoord1f (s);
2138 glVertex2f (p3.x, p3.y);
2140 glTexCoord1i (0);
2141 glVertex2f (p3.x, p3.y);
2142 glTexCoord1f (t);
2143 glVertex2f (p4.x, p4.y);
2145 glTexCoord1i (0);
2146 glVertex2f (p4.x, p4.y);
2147 glTexCoord1f (s);
2148 glVertex2f (p1.x, p1.y);
2151 glEnd ();
2153 glDisable (GL_BLEND);
2154 glDisable (GL_TEXTURE_1D);
2157 static int compareslinks (const void *l, const void *r)
2159 struct slink const *ls = l;
2160 struct slink const *rs = r;
2161 if (ls->bbox.y0 == rs->bbox.y0) {
2162 return rs->bbox.x0 - rs->bbox.x0;
2164 return ls->bbox.y0 - rs->bbox.y0;
2167 static void droptext (struct page *page)
2169 if (page->text) {
2170 fz_free_text_page (state.ctx, page->text);
2171 page->fmark.i = -1;
2172 page->lmark.i = -1;
2173 page->fmark.span = NULL;
2174 page->lmark.span = NULL;
2175 page->text = NULL;
2177 if (page->sheet) {
2178 fz_free_text_sheet (state.ctx, page->sheet);
2182 static void dropslinks (struct page *page)
2184 if (page->slinks) {
2185 free (page->slinks);
2186 page->slinks = NULL;
2187 page->slinkcount = 0;
2191 static void ensureslinks (struct page *page)
2193 fz_matrix ctm;
2194 int i, count = 0;
2195 size_t slinksize = sizeof (*page->slinks);
2196 fz_link *link, *links;
2198 if (state.gen != page->sgen) {
2199 dropslinks (page);
2200 page->sgen = state.gen;
2202 if (page->slinks) return;
2204 switch (page->type) {
2205 case DPDF:
2206 links = page->u.pdfpage->links;
2207 trimctm (page->u.pdfpage, page->pdimno);
2208 fz_concat (&ctm,
2209 &state.pagedims[page->pdimno].tctm,
2210 &state.pagedims[page->pdimno].ctm);
2211 break;
2213 case DXPS:
2214 links = page->u.xpspage->links;
2215 ctm = state.pagedims[page->pdimno].ctm;
2216 break;
2218 default:
2219 return;
2222 for (link = links; link; link = link->next) {
2223 count++;
2225 if (count > 0) {
2226 page->slinkcount = count;
2227 page->slinks = calloc (count, slinksize);
2228 if (!page->slinks) {
2229 err (1, "realloc slinks %d", count);
2232 for (i = 0, link = links; link; ++i, link = link->next) {
2233 fz_rect rect;
2235 rect = link->rect;
2236 fz_transform_rect (&rect, &ctm);
2237 page->slinks[i].link = link;
2238 fz_round_rect (&page->slinks[i].bbox, &rect);
2240 qsort (page->slinks, count, slinksize, compareslinks);
2244 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2245 static void fmt_linkn (char *s, unsigned int u)
2247 unsigned int len; unsigned int q;
2248 int zma = 'z' - 'a' + 1;
2249 len = 1; q = u;
2250 while (q > zma - 1) { ++len; q /= zma; }
2251 if (s) {
2252 s += len;
2253 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2254 /* handles u == 0 */
2256 s[len] = 0;
2259 static void highlightslinks (struct page *page, int xoff, int yoff,
2260 int noff, char *targ, int tlen, int hfsize)
2262 int i;
2263 char buf[40];
2264 struct slink *slink;
2265 double x0, y0, x1, y1, w;
2267 ensureslinks (page);
2268 glColor3ub (0xc3, 0xb0, 0x91);
2269 for (i = 0; i < page->slinkcount; ++i) {
2270 fmt_linkn (buf, i + noff);
2271 if (!tlen || !strncmp (targ, buf, tlen)) {
2272 slink = &page->slinks[i];
2274 x0 = slink->bbox.x0 + xoff - 5;
2275 y1 = slink->bbox.y0 + yoff - 5;
2276 y0 = y1 + 10 + hfsize;
2277 w = measure_string (state.face, hfsize, buf);
2278 x1 = x0 + w + 10;
2279 glRectd (x0, y0, x1, y1);
2283 glEnable (GL_BLEND);
2284 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2285 glEnable (GL_TEXTURE_2D);
2286 glColor3ub (0, 0, 0);
2287 for (i = 0; i < page->slinkcount; ++i) {
2288 fmt_linkn (buf, i + noff);
2289 if (!tlen || !strncmp (targ, buf, tlen)) {
2290 slink = &page->slinks[i];
2292 x0 = slink->bbox.x0 + xoff;
2293 y0 = slink->bbox.y0 + yoff + hfsize;
2294 draw_string (state.face, hfsize, x0, y0, buf);
2297 glDisable (GL_TEXTURE_2D);
2298 glDisable (GL_BLEND);
2302 static void uploadslice (struct tile *tile, struct slice *slice)
2304 int offset;
2305 struct slice *slice1;
2306 unsigned char *texdata;
2308 offset = 0;
2309 for (slice1 = tile->slices; slice != slice1; slice1++) {
2310 offset += slice1->h * tile->w * tile->pixmap->n;
2312 if (slice->texindex != -1 && slice->texindex < state.texcount
2313 && state.texowners[slice->texindex].slice == slice) {
2314 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2316 else {
2317 int subimage = 0;
2318 int texindex = state.texindex++ % state.texcount;
2320 if (state.texowners[texindex].w == tile->w) {
2321 if (state.texowners[texindex].h >= slice->h) {
2322 subimage = 1;
2324 else {
2325 state.texowners[texindex].h = slice->h;
2328 else {
2329 state.texowners[texindex].h = slice->h;
2332 state.texowners[texindex].w = tile->w;
2333 state.texowners[texindex].slice = slice;
2334 slice->texindex = texindex;
2336 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2337 if (tile->pbo) {
2338 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2339 texdata = 0;
2341 else {
2342 texdata = tile->pixmap->samples;
2344 if (subimage) {
2345 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2349 tile->w,
2350 slice->h,
2351 state.texform,
2352 state.texty,
2353 texdata+offset
2356 else {
2357 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2359 state.texiform,
2360 tile->w,
2361 slice->h,
2363 state.texform,
2364 state.texty,
2365 texdata+offset
2368 if (tile->pbo) {
2369 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2374 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2376 CAMLparam2 (args_v, ptr_v);
2377 int dispx = Int_val (Field (args_v, 0));
2378 int dispy = Int_val (Field (args_v, 1));
2379 int dispw = Int_val (Field (args_v, 2));
2380 int disph = Int_val (Field (args_v, 3));
2381 int tilex = Int_val (Field (args_v, 4));
2382 int tiley = Int_val (Field (args_v, 5));
2383 char *s = String_val (ptr_v);
2384 struct tile *tile = parse_pointer ("ml_drawtile", s);
2386 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2388 int slicey, firstslice;
2389 struct slice *slice;
2391 firstslice = tiley / tile->sliceheight;
2392 slice = &tile->slices[firstslice];
2393 slicey = tiley % tile->sliceheight;
2395 while (disph > 0) {
2396 int dh;
2398 dh = slice->h - slicey;
2399 dh = MIN (disph, dh);
2400 uploadslice (tile, slice);
2402 glBegin (GL_QUADS);
2404 glTexCoord2i (tilex, slicey);
2405 glVertex2i (dispx, dispy);
2407 glTexCoord2i (tilex+dispw, slicey);
2408 glVertex2i (dispx+dispw, dispy);
2410 glTexCoord2i (tilex+dispw, slicey+dh);
2411 glVertex2i (dispx+dispw, dispy+dh);
2413 glTexCoord2i (tilex, slicey+dh);
2414 glVertex2i (dispx, dispy+dh);
2416 glEnd ();
2418 dispy += dh;
2419 disph -= dh;
2420 slice++;
2421 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2422 slicey = 0;
2425 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2426 CAMLreturn (Val_unit);
2429 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2430 value xoff_v, value yoff_v,
2431 value li_v)
2433 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2434 int xoff = Int_val (xoff_v);
2435 int yoff = Int_val (yoff_v);
2436 int noff = Int_val (Field (li_v, 0));
2437 char *targ = String_val (Field (li_v, 1));
2438 int tlen = caml_string_length (Field (li_v, 1));
2439 int hfsize = Int_val (Field (li_v, 2));
2440 char *s = String_val (ptr_v);
2441 int hlmask = Int_val (hlinks_v);
2442 struct page *page = parse_pointer ("ml_postprocess", s);
2444 if (!page->u.ptr) {
2445 /* deal with loadpage failed pages */
2446 goto done;
2449 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2450 if (trylock ("ml_postprocess")) {
2451 noff = 0;
2452 goto done;
2454 if (hlmask & 2) {
2455 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2456 noff = page->slinkcount;
2458 showsel (page, xoff, yoff);
2459 unlock ("ml_postprocess");
2461 done:
2462 CAMLreturn (Val_int (noff));
2465 static fz_link *getlink (struct page *page, int x, int y)
2467 fz_point p;
2468 fz_matrix ctm;
2469 const fz_matrix *tctm;
2470 fz_link *link, *links;
2472 switch (page->type) {
2473 case DPDF:
2474 trimctm (page->u.pdfpage, page->pdimno);
2475 tctm = &state.pagedims[page->pdimno].tctm;
2476 links = page->u.pdfpage->links;
2477 break;
2479 case DXPS:
2480 tctm = &fz_identity;
2481 links = page->u.xpspage->links;
2482 break;
2484 default:
2485 return NULL;
2487 p.x = x;
2488 p.y = y;
2490 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2491 fz_invert_matrix (&ctm, &ctm);
2492 fz_transform_point (&p, &ctm);
2494 for (link = links; link; link = link->next) {
2495 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2496 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2497 return link;
2501 return NULL;
2504 static void ensuretext (struct page *page)
2506 if (state.gen != page->tgen) {
2507 droptext (page);
2508 page->tgen = state.gen;
2510 if (!page->text) {
2511 fz_matrix ctm;
2512 fz_device *tdev;
2514 page->text = fz_new_text_page (state.ctx, &fz_infinite_rect);
2515 page->sheet = fz_new_text_sheet (state.ctx);
2516 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2517 ctm = pagectm (page);
2518 fz_run_display_list (page->dlist, tdev, &ctm, &fz_infinite_rect, NULL);
2519 qsort (page->text->blocks, page->text->len,
2520 sizeof (*page->text->blocks), compareblocks);
2521 fz_free_device (tdev);
2525 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2527 CAMLparam2 (start_page_v, dir_v);
2528 CAMLlocal1 (ret_v);
2529 int i, dir = Int_val (dir_v);
2530 int start_page = Int_val (start_page_v);
2531 int end_page = dir > 0 ? state.pagecount : -1;
2533 ret_v = Val_int (0);
2534 if (!(state.type == DPDF || state.type == DXPS)) {
2535 goto done;
2538 lock ("ml_findpage_with_links");
2539 for (i = start_page + dir; i != end_page; i += dir) {
2540 int found;
2542 switch (state.type) {
2543 case DPDF:
2545 pdf_page *page = NULL;
2547 fz_try (state.ctx) {
2548 page = pdf_load_page (state.u.pdf, i);
2549 found = !!page->links;
2551 fz_catch (state.ctx) {
2552 found = 0;
2554 if (page) {
2555 freepdfpage (page);
2558 break;
2559 case DXPS:
2561 xps_page *page = xps_load_page (state.u.xps, i);
2562 found = !!page->links;
2563 freexpspage (page);
2565 break;
2567 default:
2568 ARSERT (0 && "invalid document type");
2571 if (found) {
2572 ret_v = caml_alloc_small (1, 1);
2573 Field (ret_v, 0) = Val_int (i);
2574 goto unlock;
2577 unlock:
2578 unlock ("ml_findpage_with_links");
2580 done:
2581 CAMLreturn (ret_v);
2584 enum { dir_first, dir_last};
2585 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2587 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2589 CAMLparam2 (ptr_v, dir_v);
2590 CAMLlocal2 (ret_v, pos_v);
2591 struct page *page;
2592 int dirtag, i, slinkindex;
2593 struct slink *found = NULL ,*slink;
2594 char *s = String_val (ptr_v);
2596 page = parse_pointer ("ml_findlink", s);
2597 ret_v = Val_int (0);
2598 if (trylock ("ml_findlink")) {
2599 goto done;
2602 ensureslinks (page);
2604 if (Is_block (dir_v)) {
2605 dirtag = Tag_val (dir_v);
2606 switch (dirtag) {
2607 case dir_first_visible:
2609 int x0, y0, dir, first_index, last_index;
2611 pos_v = Field (dir_v, 0);
2612 x0 = Int_val (Field (pos_v, 0));
2613 y0 = Int_val (Field (pos_v, 1));
2614 dir = Int_val (Field (pos_v, 2));
2616 if (dir >= 0) {
2617 dir = 1;
2618 first_index = 0;
2619 last_index = page->slinkcount;
2621 else {
2622 first_index = page->slinkcount - 1;
2623 last_index = -1;
2626 for (i = first_index; i != last_index; i += dir) {
2627 slink = &page->slinks[i];
2628 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2629 found = slink;
2630 break;
2634 break;
2636 case dir_left:
2637 slinkindex = Int_val (Field (dir_v, 0));
2638 found = &page->slinks[slinkindex];
2639 for (i = slinkindex - 1; i >= 0; --i) {
2640 slink = &page->slinks[i];
2641 if (slink->bbox.x0 < found->bbox.x0) {
2642 found = slink;
2643 break;
2646 break;
2648 case dir_right:
2649 slinkindex = Int_val (Field (dir_v, 0));
2650 found = &page->slinks[slinkindex];
2651 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2652 slink = &page->slinks[i];
2653 if (slink->bbox.x0 > found->bbox.x0) {
2654 found = slink;
2655 break;
2658 break;
2660 case dir_down:
2661 slinkindex = Int_val (Field (dir_v, 0));
2662 found = &page->slinks[slinkindex];
2663 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2664 slink = &page->slinks[i];
2665 if (slink->bbox.y0 >= found->bbox.y0) {
2666 found = slink;
2667 break;
2670 break;
2672 case dir_up:
2673 slinkindex = Int_val (Field (dir_v, 0));
2674 found = &page->slinks[slinkindex];
2675 for (i = slinkindex - 1; i >= 0; --i) {
2676 slink = &page->slinks[i];
2677 if (slink->bbox.y0 <= found->bbox.y0) {
2678 found = slink;
2679 break;
2682 break;
2685 else {
2686 dirtag = Int_val (dir_v);
2687 switch (dirtag) {
2688 case dir_first:
2689 found = page->slinks;
2690 break;
2692 case dir_last:
2693 if (page->slinks) {
2694 found = page->slinks + (page->slinkcount - 1);
2696 break;
2699 if (found) {
2700 ret_v = caml_alloc_small (2, 1);
2701 Field (ret_v, 0) = Val_int (found - page->slinks);
2704 unlock ("ml_findlink");
2705 done:
2706 CAMLreturn (ret_v);
2709 enum { uuri, ugoto, utext, uunexpected, ulaunch, unamed, uremote };
2711 #define LINKTOVAL \
2713 int pageno; \
2715 switch (link->dest.kind) { \
2716 case FZ_LINK_GOTO: \
2718 fz_point p; \
2720 pageno = link->dest.ld.gotor.page; \
2721 p.x = 0; \
2722 p.y = 0; \
2724 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2725 p.y = link->dest.ld.gotor.lt.y; \
2726 fz_transform_point (&p, &pdim->lctm); \
2728 tup_v = caml_alloc_tuple (2); \
2729 ret_v = caml_alloc_small (1, ugoto); \
2730 Field (tup_v, 0) = Val_int (pageno); \
2731 Field (tup_v, 1) = Val_int (p.y); \
2732 Field (ret_v, 0) = tup_v; \
2734 break; \
2736 case FZ_LINK_URI: \
2737 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2738 ret_v = caml_alloc_small (1, uuri); \
2739 Field (ret_v, 0) = str_v; \
2740 break; \
2742 case FZ_LINK_LAUNCH: \
2743 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2744 ret_v = caml_alloc_small (1, ulaunch); \
2745 Field (ret_v, 0) = str_v; \
2746 break; \
2748 case FZ_LINK_NAMED: \
2749 str_v = caml_copy_string (link->dest.ld.named.named); \
2750 ret_v = caml_alloc_small (1, unamed); \
2751 Field (ret_v, 0) = str_v; \
2752 break; \
2754 case FZ_LINK_GOTOR: \
2755 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2756 pageno = link->dest.ld.gotor.page; \
2757 tup_v = caml_alloc_tuple (2); \
2758 ret_v = caml_alloc_small (1, uremote); \
2759 Field (tup_v, 0) = str_v; \
2760 Field (tup_v, 1) = Val_int (pageno); \
2761 Field (ret_v, 0) = tup_v; \
2762 break; \
2764 default: \
2766 char buf[80]; \
2768 snprintf (buf, sizeof (buf), \
2769 "unhandled link kind %d", link->dest.kind); \
2770 str_v = caml_copy_string (buf); \
2771 ret_v = caml_alloc_small (1, uunexpected); \
2772 Field (ret_v, 0) = str_v; \
2774 break; \
2778 CAMLprim value ml_getlink (value ptr_v, value n_v)
2780 CAMLparam2 (ptr_v, n_v);
2781 CAMLlocal3 (ret_v, tup_v, str_v);
2782 fz_link *link;
2783 struct page *page;
2784 struct pagedim *pdim;
2785 char *s = String_val (ptr_v);
2787 ret_v = Val_int (0);
2788 if (trylock ("ml_getlink")) {
2789 goto done;
2792 page = parse_pointer ("ml_getlink", s);
2793 ensureslinks (page);
2794 pdim = &state.pagedims[page->pdimno];
2795 link = page->slinks[Int_val (n_v)].link;
2796 LINKTOVAL;
2798 unlock ("ml_getlink");
2799 done:
2800 CAMLreturn (ret_v);
2803 CAMLprim value ml_getlinkcount (value ptr_v)
2805 CAMLparam1 (ptr_v);
2806 struct page *page;
2807 char *s = String_val (ptr_v);
2809 page = parse_pointer ("ml_getlinkcount", s);
2810 CAMLreturn (Val_int (page->slinkcount));
2813 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2815 CAMLparam2 (ptr_v, n_v);
2816 CAMLlocal1 (ret_v);
2817 struct page *page;
2818 struct slink *slink;
2819 char *s = String_val (ptr_v);
2821 page = parse_pointer ("ml_getlinkrect", s);
2822 ret_v = caml_alloc_tuple (4);
2823 if (trylock ("ml_getlinkrect")) {
2824 Field (ret_v, 0) = Val_int (0);
2825 Field (ret_v, 1) = Val_int (0);
2826 Field (ret_v, 2) = Val_int (0);
2827 Field (ret_v, 3) = Val_int (0);
2828 goto done;
2830 ensureslinks (page);
2832 slink = &page->slinks[Int_val (n_v)];
2833 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2834 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2835 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2836 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2837 unlock ("ml_getlinkrect");
2839 done:
2840 CAMLreturn (ret_v);
2843 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2845 CAMLparam3 (ptr_v, x_v, y_v);
2846 CAMLlocal3 (ret_v, tup_v, str_v);
2847 fz_link *link;
2848 struct page *page;
2849 char *s = String_val (ptr_v);
2850 int x = Int_val (x_v), y = Int_val (y_v);
2851 struct pagedim *pdim;
2853 ret_v = Val_int (0);
2854 if (trylock ("ml_whatsunder")) {
2855 goto done;
2858 page = parse_pointer ("ml_whatsunder", s);
2859 pdim = &state.pagedims[page->pdimno];
2860 x += pdim->bounds.x0;
2861 y += pdim->bounds.y0;
2862 link = getlink (page, x, y);
2863 if (link) {
2864 LINKTOVAL;
2866 else {
2867 fz_rect *b;
2868 fz_page_block *pageb;
2869 fz_text_block *block;
2871 ensuretext (page);
2872 for (pageb = page->text->blocks;
2873 pageb < page->text->blocks + page->text->len;
2874 ++pageb) {
2875 fz_text_line *line;
2876 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2877 block = pageb->u.text;
2879 b = &block->bbox;
2880 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2881 continue;
2883 for (line = block->lines;
2884 line < block->lines + block->len;
2885 ++line) {
2886 fz_text_span *span;
2888 b = &line->bbox;
2889 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2890 continue;
2892 for (span = line->first_span; span; span = span->next) {
2893 int charnum;
2895 b = &span->bbox;
2896 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2897 continue;
2899 for (charnum = 0; charnum < span->len; ++charnum) {
2900 fz_rect bbox;
2901 fz_text_char_bbox (&bbox, span, charnum);
2902 b = &bbox;
2904 if (x >= b->x0 && x <= b->x1
2905 && y >= b->y0 && y <= b->y1) {
2906 fz_text_style *style = span->text->style;
2907 const char *n2 =
2908 style->font && style->font->name
2909 ? style->font->name
2910 : "Span has no font name"
2912 FT_FaceRec *face = style->font->ft_face;
2913 if (face && face->family_name) {
2914 char *s;
2915 char *n1 = face->family_name;
2916 size_t l1 = strlen (n1);
2917 size_t l2 = strlen (n2);
2919 if (l1 != l2 || memcmp (n1, n2, l1)) {
2920 s = malloc (l1 + l2 + 2);
2921 if (s) {
2922 memcpy (s, n2, l2);
2923 s[l2] = '=';
2924 memcpy (s + l2 + 1, n1, l1 + 1);
2925 str_v = caml_copy_string (s);
2926 free (s);
2930 if (str_v == 0) {
2931 str_v = caml_copy_string (n2);
2933 ret_v = caml_alloc_small (1, utext);
2934 Field (ret_v, 0) = str_v;
2935 goto unlock;
2942 unlock:
2943 unlock ("ml_whatsunder");
2945 done:
2946 CAMLreturn (ret_v);
2949 enum { mark_page, mark_block, mark_line, mark_word };
2951 static int white (int c)
2953 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r';
2956 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2958 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2959 CAMLlocal3 (ret_v, tup_v, str_v);
2960 fz_rect *b;
2961 struct page *page;
2962 fz_text_line *line;
2963 fz_page_block *pageb;
2964 fz_text_block *block;
2965 struct pagedim *pdim;
2966 int mark = Int_val (mark_v);
2967 char *s = String_val (ptr_v);
2968 int x = Int_val (x_v), y = Int_val (y_v);
2970 ret_v = Val_bool (0);
2971 if (trylock ("ml_markunder")) {
2972 goto done;
2975 page = parse_pointer ("ml_markunder", s);
2976 pdim = &state.pagedims[page->pdimno];
2977 x += pdim->bounds.x0;
2978 y += pdim->bounds.y0;
2980 ensuretext (page);
2982 if (mark == mark_page) {
2983 int i;
2985 for (i = page->text->len - 1; i >= 0; --i) {
2986 pageb = &page->text->blocks[i];
2987 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2989 if (i < 0) goto unlock;
2991 block = pageb->u.text;
2993 page->fmark.i = 0;
2994 page->fmark.span = block->lines->first_span;
2996 line = &block->lines[block->len - 1];
2997 page->lmark.i = line->last_span->len - 1;
2998 page->lmark.span = line->last_span;
2999 ret_v = Val_bool (1);
3000 goto unlock;
3003 for (pageb = page->text->blocks;
3004 pageb < page->text->blocks + page->text->len;
3005 ++pageb) {
3006 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3007 block = pageb->u.text;
3009 b = &block->bbox;
3010 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3011 continue;
3013 if (mark == mark_block) {
3014 page->fmark.i = 0;
3015 page->fmark.span = block->lines->first_span;
3017 line = &block->lines[block->len - 1];
3018 page->lmark.i = line->last_span->len - 1;
3019 page->lmark.span = line->last_span;
3020 ret_v = Val_bool (1);
3021 goto unlock;
3024 for (line = block->lines;
3025 line < block->lines + block->len;
3026 ++line) {
3027 fz_text_span *span;
3029 b = &line->bbox;
3030 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3031 continue;
3033 if (mark == mark_line) {
3034 page->fmark.i = 0;
3035 page->fmark.span = line->first_span;
3037 page->lmark.i = line->last_span->len - 1;
3038 page->lmark.span = line->last_span;
3039 ret_v = Val_bool (1);
3040 goto unlock;
3043 for (span = line->first_span; span; span = span->next) {
3044 int charnum;
3046 b = &span->bbox;
3047 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3048 continue;
3050 for (charnum = 0; charnum < span->len; ++charnum) {
3051 fz_rect bbox;
3052 fz_text_char_bbox (&bbox, span, charnum);
3053 b = &bbox;
3055 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3056 /* unicode ftw */
3057 int charnum2, charnum3 = -1, charnum4 = -1;
3059 if (white (span->text[charnum].c)) goto unlock;
3061 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3062 if (white (span->text[charnum2].c)) {
3063 charnum3 = charnum2 + 1;
3064 break;
3067 if (charnum3 == -1) charnum3 = 0;
3069 for (charnum2 = charnum + 1;
3070 charnum2 < span->len;
3071 ++charnum2) {
3072 if (white (span->text[charnum2].c)) break;
3073 charnum4 = charnum2;
3075 if (charnum4 == -1) goto unlock;
3077 page->fmark.i = charnum3;
3078 page->fmark.span = span;
3080 page->lmark.i = charnum4;
3081 page->lmark.span = span;
3082 ret_v = Val_bool (1);
3083 goto unlock;
3089 unlock:
3090 if (!Bool_val (ret_v)) {
3091 page->fmark.span = NULL;
3092 page->lmark.span = NULL;
3093 page->fmark.i = 0;
3094 page->lmark.i = 0;
3096 unlock ("ml_markunder");
3098 done:
3099 CAMLreturn (ret_v);
3102 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3104 CAMLparam2 (ptr_v, rect_v);
3105 fz_rect b;
3106 struct page *page;
3107 struct pagedim *pdim;
3108 int i, x0, x1, y0, y1;
3109 char *s = String_val (ptr_v);
3110 int fi = 0, li = 0;
3111 fz_page_block *pageb;
3112 fz_text_block *block;
3113 fz_text_span *span, *fspan, *lspan;
3114 fz_text_line *line, *fline = NULL, *lline = NULL;
3116 if (trylock ("ml_seltext")) {
3117 goto done;
3120 page = parse_pointer ("ml_seltext", s);
3121 ensuretext (page);
3123 pdim = &state.pagedims[page->pdimno];
3124 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;;
3125 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3126 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3127 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3129 if (0) {
3130 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3131 glColor3ub (128, 128, 128);
3132 glRecti (x0, y0, x1, y1);
3133 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3136 fspan = lspan = NULL;
3138 for (pageb= page->text->blocks;
3139 pageb < page->text->blocks + page->text->len;
3140 ++pageb) {
3141 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3142 block = pageb->u.text;
3143 for (line = block->lines;
3144 line < block->lines + block->len;
3145 ++line) {
3146 fz_text_span *span;
3148 for (span = line->first_span; span; span = span->next) {
3149 for (i = 0; i < span->len; ++i) {
3150 int selected = 0;
3152 fz_text_char_bbox (&b, span, i);
3154 if (x0 >= b.x0 && x0 <= b.x1
3155 && y0 >= b.y0 && y0 <= b.y1) {
3156 fspan = span;
3157 fline = line;
3158 fi = i;
3159 selected = 1;
3161 if (x1 >= b.x0 && x1 <= b.x1
3162 && y1 >= b.y0 && y1 <= b.y1) {
3163 lspan = span;
3164 lline = line;
3165 li = i;
3166 selected = 1;
3168 if (0 && selected) {
3169 glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
3170 glColor3ub (128, 128, 128);
3171 glRecti (b.x0, b.y0, b.x1, b.y1);
3172 glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
3178 if (y1 < y0 || x1 < x0) {
3179 int swap = 0;
3181 if (fspan == lspan) {
3182 swap = 1;
3184 else {
3185 if (y1 < y0) {
3186 if (fline != lline) {
3187 swap = 1;
3192 if (swap) {
3193 i = fi;
3194 span = fspan;
3196 fi = li;
3197 fspan = lspan;
3199 li = i;
3200 lspan = span;
3204 page->fmark.i = fi;
3205 page->fmark.span = fspan;
3207 page->lmark.i = li;
3208 page->lmark.span = lspan;
3210 unlock ("ml_seltext");
3212 done:
3213 CAMLreturn (Val_unit);
3216 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3218 char buf[4];
3219 int i, len, ret;
3221 for (i = a; i <= b; ++i) {
3222 len = fz_runetochar (buf, span->text[i].c);
3223 ret = fwrite (buf, len, 1, f);
3225 if (ret != 1) {
3226 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3227 len, ret, strerror (errno));
3228 return -1;
3231 return 0;
3234 #ifdef __CYGWIN__
3235 value ml_popen (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3237 caml_failwith ("ml_popen not implemented under Cygwin");
3239 #else
3240 CAMLprim value ml_popen (value command_v, value fds_v)
3242 CAMLparam2 (command_v, fds_v);
3243 CAMLlocal2 (l_v, tup_v);
3244 int ret;
3245 char *msg = NULL;
3246 value earg_v = Nothing;
3247 posix_spawnattr_t attr;
3248 posix_spawn_file_actions_t fa;
3249 char *argv[] = { "/bin/sh", "-c", String_val (command_v), NULL };
3251 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3252 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3255 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3256 msg = "posix_spawnattr_init";
3257 goto fail1;
3260 #ifdef POSIX_SPAWN_USEVFORK
3261 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3262 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3263 goto fail;
3265 #endif
3267 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3268 int fd1, fd2;
3270 tup_v = Field (l_v, 0);
3271 fd1 = Int_val (Field (tup_v, 0));
3272 fd2 = Int_val (Field (tup_v, 1));
3273 if (fd2 < 0) {
3274 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3275 msg = "posix_spawn_file_actions_addclose";
3276 earg_v = tup_v;
3277 goto fail;
3280 else {
3281 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3282 msg = "posix_spawn_file_actions_adddup2";
3283 earg_v = tup_v;
3284 goto fail;
3289 if ((ret = posix_spawn (NULL, "/bin/sh", &fa, &attr, argv, environ))) {
3290 msg = "posix_spawn";
3291 goto fail;
3294 fail:
3295 if ((ret = posix_spawnattr_destroy (&attr)) != 0) {
3296 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret));
3299 fail1:
3300 if ((ret = posix_spawn_file_actions_destroy (&fa)) != 0) {
3301 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3302 strerror (ret));
3305 if (msg)
3306 unix_error (ret, msg, earg_v);
3308 CAMLreturn (Val_unit);
3310 #endif
3312 CAMLprim value ml_copysel (value fd_v, value ptr_v, value clear_v)
3314 CAMLparam3 (fd_v, ptr_v, clear_v);
3315 FILE *f;
3316 int seen = 0;
3317 struct page *page;
3318 fz_text_line *line;
3319 fz_page_block *pageb;
3320 fz_text_block *block;
3321 int fd = Int_val (fd_v);
3322 char *s = String_val (ptr_v);
3323 int clear = Bool_val (clear_v);
3325 if (trylock ("ml_copysel")) {
3326 goto done;
3329 page = parse_pointer ("ml_sopysel", s);
3331 if (!page->fmark.span || !page->lmark.span) {
3332 fprintf (stderr, "nothing to copy\n");
3333 goto unlock;
3336 f = fdopen (fd, "w");
3337 if (!f) {
3338 fprintf (stderr, "failed to fopen sel pipe: %s\n",
3339 strerror (errno));
3340 f = stdout;
3343 for (pageb = page->text->blocks;
3344 pageb < page->text->blocks + page->text->len;
3345 ++pageb) {
3346 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3347 block = pageb->u.text;
3348 for (line = block->lines;
3349 line < block->lines + block->len;
3350 ++line) {
3351 fz_text_span *span;
3353 for (span = line->first_span; span; span = span->next) {
3354 int a, b;
3356 seen |= span == page->fmark.span || span == page->lmark.span;
3357 a = span == page->fmark.span ? page->fmark.i : 0;
3358 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3360 if (seen) {
3361 if (pipespan (f, span, a, b)) {
3362 goto close;
3364 if (span == line->last_span) {
3365 if (putc ('\n', f) == EOF) {
3366 fprintf (stderr,
3367 "failed break line on sel pipe: %s\n",
3368 strerror (errno));
3369 goto close;
3372 if (span == page->lmark.span) {
3373 goto endloop;
3379 endloop:
3380 if (clear) {
3381 page->lmark.span = NULL;
3382 page->fmark.span = NULL;
3385 close:
3386 if (f != stdout) {
3387 int ret = fclose (f);
3388 fd = -1;
3389 if (ret == -1) {
3390 if (errno != ECHILD) {
3391 fprintf (stderr, "failed to close sel pipe: %s\n",
3392 strerror (errno));
3396 unlock:
3397 unlock ("ml_copysel");
3399 done:
3400 if (fd >= 0) {
3401 if (close (fd)) {
3402 fprintf (stderr, "failed to close sel pipe: %s\n",
3403 strerror (errno));
3406 CAMLreturn (Val_unit);
3409 CAMLprim value ml_getpdimrect (value pagedimno_v)
3411 CAMLparam1 (pagedimno_v);
3412 CAMLlocal1 (ret_v);
3413 int pagedimno = Int_val (pagedimno_v);
3414 fz_rect box;
3416 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3417 if (trylock ("ml_getpdimrect")) {
3418 box = fz_empty_rect;
3420 else {
3421 box = state.pagedims[pagedimno].mediabox;
3422 unlock ("ml_getpdimrect");
3425 Store_double_field (ret_v, 0, box.x0);
3426 Store_double_field (ret_v, 1, box.x1);
3427 Store_double_field (ret_v, 2, box.y0);
3428 Store_double_field (ret_v, 3, box.y1);
3430 CAMLreturn (ret_v);
3433 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3434 value dw_v, value cols_v)
3436 CAMLparam3 (winw_v, winh_v, dw_v);
3437 CAMLlocal1 (ret_v);
3438 int i;
3439 double zoom = -1.;
3440 double maxh = 0.0;
3441 struct pagedim *p;
3442 double winw = Int_val (winw_v);
3443 double winh = Int_val (winh_v);
3444 double dw = Int_val (dw_v);
3445 double cols = Int_val (cols_v);
3446 double pw = 1.0, ph = 1.0;
3448 if (trylock ("ml_zoom_for_height")) {
3449 goto done;
3452 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3453 double w = p->pagebox.x1 / cols;
3454 double h = p->pagebox.y1;
3455 if (h > maxh) {
3456 maxh = h;
3457 ph = h;
3458 if (state.fitmodel != FitProportional) pw = w;
3460 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3463 zoom = (((winh / ph) * pw) + dw) / winw;
3464 unlock ("ml_zoom_for_height");
3465 done:
3466 ret_v = caml_copy_double (zoom);
3467 CAMLreturn (ret_v);
3470 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3472 CAMLparam4 (pt_v, x_v, y_v, string_v);
3473 CAMLlocal1 (ret_v);
3474 int pt = Int_val(pt_v);
3475 int x = Int_val (x_v);
3476 int y = Int_val (y_v);
3477 double w;
3479 w = draw_string (state.face, pt, x, y, String_val (string_v));
3480 ret_v = caml_copy_double (w);
3481 CAMLreturn (ret_v);
3484 CAMLprim value ml_measure_string (value pt_v, value string_v)
3486 CAMLparam2 (pt_v, string_v);
3487 CAMLlocal1 (ret_v);
3488 int pt = Int_val (pt_v);
3489 double w;
3491 w = measure_string (state.face, pt, String_val (string_v));
3492 ret_v = caml_copy_double (w);
3493 CAMLreturn (ret_v);
3496 CAMLprim value ml_getpagebox (value opaque_v)
3498 CAMLparam1 (opaque_v);
3499 CAMLlocal1 (ret_v);
3500 fz_rect rect;
3501 fz_irect bbox;
3502 fz_matrix ctm;
3503 fz_device *dev;
3504 char *s = String_val (opaque_v);
3505 struct page *page = parse_pointer ("ml_getpagebox", s);
3507 ret_v = caml_alloc_tuple (4);
3508 dev = fz_new_bbox_device (state.ctx, &rect);
3509 dev->hints |= FZ_IGNORE_SHADE;
3511 switch (page->type) {
3512 case DPDF:
3513 ctm = pagectm (page);
3514 pdf_run_page (state.u.pdf, page->u.pdfpage, dev, &ctm, NULL);
3515 break;
3517 case DXPS:
3518 ctm = pagectm (page);
3519 xps_run_page (state.u.xps, page->u.xpspage, dev, &ctm, NULL);
3520 break;
3522 default:
3523 rect = fz_infinite_rect;
3524 break;
3527 fz_free_device (dev);
3528 fz_round_rect (&bbox, &rect);
3529 Field (ret_v, 0) = Val_int (bbox.x0);
3530 Field (ret_v, 1) = Val_int (bbox.y0);
3531 Field (ret_v, 2) = Val_int (bbox.x1);
3532 Field (ret_v, 3) = Val_int (bbox.y1);
3534 CAMLreturn (ret_v);
3537 CAMLprim value ml_setaalevel (value level_v)
3539 CAMLparam1 (level_v);
3541 state.aalevel = Int_val (level_v);
3542 CAMLreturn (Val_unit);
3545 #undef pixel
3546 #include <X11/Xlib.h>
3547 #include <GL/glx.h>
3549 static struct {
3550 Display *dpy;
3551 GLXContext ctx;
3552 GLXDrawable drawable;
3553 } glx;
3555 #include "keysym2ucs.c"
3557 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3559 CAMLparam1 (keysym_v);
3560 CAMLlocal1 (str_v);
3561 KeySym keysym = Int_val (keysym_v);
3562 Rune rune;
3563 int len;
3564 char buf[5];
3566 rune = keysym2ucs (keysym);
3567 len = fz_runetochar (buf, rune);
3568 buf[len] = 0;
3569 str_v = caml_copy_string (buf);
3570 CAMLreturn (str_v);
3573 CAMLprim value ml_glx (value win_v)
3575 CAMLparam1 (win_v);
3576 XVisualInfo *visual;
3577 int screen, wid = Int_val (win_v);
3578 int attributes[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3580 glx.dpy = XOpenDisplay (NULL);
3581 if (!glx.dpy) {
3582 caml_failwith ("XOpenDisplay");
3585 screen = DefaultScreen (glx.dpy);
3586 visual = glXChooseVisual (glx.dpy, screen, attributes);
3587 if (!visual) {
3588 XCloseDisplay (glx.dpy);
3589 glx.dpy = NULL;
3590 caml_failwith ("glXChooseVisual");
3593 glx.ctx = glXCreateContext (glx.dpy, visual, NULL, True);
3594 XFree (visual);
3595 if (!glx.ctx) {
3596 XCloseDisplay (glx.dpy);
3597 glx.dpy = NULL;
3598 caml_failwith ("glXCreateContext");
3601 if (!glXMakeCurrent (glx.dpy, wid, glx.ctx)) {
3602 glXDestroyContext (glx.dpy, glx.ctx);
3603 XCloseDisplay (glx.dpy);
3604 glx.dpy = NULL;
3605 glx.ctx = NULL;
3606 caml_failwith ("glXMakeCurrent");
3608 glx.drawable = wid;
3609 CAMLreturn (Val_unit);
3612 CAMLprim value ml_swapb (value unit_v)
3614 CAMLparam1 (unit_v);
3615 glXSwapBuffers (glx.dpy, glx.drawable);
3616 CAMLreturn (Val_unit);
3619 CAMLprim value ml_glxsync (value unit_v)
3621 CAMLparam1 (unit_v);
3622 if (glx.dpy && glx.ctx) {
3623 glXWaitX ();
3624 glXWaitGL ();
3626 CAMLreturn (Val_unit);
3629 enum { piunknown, pilinux, piosx, pisun, pifreebsd,
3630 pidragonflybsd, piopenbsd, pinetbsd, picygwin };
3632 CAMLprim value ml_platform (value unit_v)
3634 CAMLparam1 (unit_v);
3635 int platid = piunknown;
3637 #if defined __linux__
3638 platid = pilinux;
3639 #elif defined __CYGWIN__
3640 platid = picygwin;
3641 #elif defined __DragonFly__
3642 platid = pidragonflybsd;
3643 #elif defined __FreeBSD__
3644 platid = pifreebsd;
3645 #elif defined __OpenBSD__
3646 platid = piopenbsd;
3647 #elif defined __NetBSD__
3648 platid = pinetbsd;
3649 #elif defined __sun__
3650 platid = pisun;
3651 #elif defined __APPLE__
3652 platid = piosx;
3653 #endif
3654 CAMLreturn (Val_int (platid));
3657 CAMLprim value ml_cloexec (value fd_v)
3659 CAMLparam1 (fd_v);
3660 int fd = Int_val (fd_v);
3662 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3663 uerror ("fcntl", Nothing);
3665 CAMLreturn (Val_unit);
3668 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3670 CAMLparam2 (w_v, h_v);
3671 CAMLlocal1 (ret_v);
3672 struct pbo *pbo;
3673 int w = Int_val (w_v);
3674 int h = Int_val (h_v);
3675 int cs = Int_val (cs_v);
3677 if (state.pbo_usable) {
3678 pbo = calloc (sizeof (*pbo), 1);
3679 if (!pbo) {
3680 err (1, "calloc pbo");
3683 switch (cs) {
3684 case 0:
3685 case 1:
3686 pbo->size = w*h*4;
3687 break;
3688 case 2:
3689 pbo->size = w*h*2;
3690 break;
3691 default:
3692 errx (1, "ml_getpbo: invalid colorspace %d", cs);
3695 state.glGenBuffersARB (1, &pbo->id);
3696 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3697 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
3698 NULL, GL_STREAM_DRAW);
3699 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3700 GL_READ_WRITE);
3701 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3702 if (!pbo->ptr) {
3703 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
3704 state.glDeleteBuffersARB (1, &pbo->id);
3705 free (pbo);
3706 ret_v = caml_copy_string ("0");
3708 else {
3709 int res;
3710 char *s;
3712 res = snprintf (NULL, 0, "%" FMT_ptr, pbo);
3713 if (res < 0) {
3714 err (1, "snprintf %" FMT_ptr " failed", pbo);
3716 s = malloc (res+1);
3717 if (!s) {
3718 err (1, "malloc %d bytes failed", res+1);
3720 res = sprintf (s, "%" FMT_ptr, pbo);
3721 if (res < 0) {
3722 err (1, "sprintf %" FMT_ptr " failed", pbo);
3724 ret_v = caml_copy_string (s);
3725 free (s);
3728 else {
3729 ret_v = caml_copy_string ("0");
3731 CAMLreturn (ret_v);
3734 CAMLprim value ml_freepbo (value s_v)
3736 CAMLparam1 (s_v);
3737 char *s = String_val (s_v);
3738 struct tile *tile = parse_pointer ("ml_freepbo", s);
3740 if (tile->pbo) {
3741 state.glDeleteBuffersARB (1, &tile->pbo->id);
3742 tile->pbo->id = -1;
3743 tile->pbo->ptr = NULL;
3744 tile->pbo->size = -1;
3746 CAMLreturn (Val_unit);
3749 CAMLprim value ml_unmappbo (value s_v)
3751 CAMLparam1 (s_v);
3752 char *s = String_val (s_v);
3753 struct tile *tile = parse_pointer ("ml_unmappbo", s);
3755 if (tile->pbo) {
3756 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3757 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3758 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3760 tile->pbo->ptr = NULL;
3761 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3763 CAMLreturn (Val_unit);
3766 static void setuppbo (void)
3768 #define GGPA(n) *(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n)
3769 GGPA (glBindBufferARB);
3770 if (state.glBindBufferARB) {
3771 GGPA (glUnmapBufferARB);
3772 if (state.glUnmapBufferARB) {
3773 GGPA (glMapBufferARB);
3774 if (state.glMapBufferARB) {
3775 GGPA (glBufferDataARB);
3776 if (state.glBufferDataARB) {
3777 GGPA (glGenBuffersARB);
3778 if (state.glGenBuffersARB) {
3779 GGPA (glDeleteBuffersARB);
3780 if (state.glDeleteBuffersARB) {
3781 state.pbo_usable = 1;
3788 #undef GGPA
3791 CAMLprim value ml_pbo_usable (value unit_v)
3793 CAMLparam1 (unit_v);
3794 CAMLreturn (Val_bool (state.pbo_usable));
3797 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3799 CAMLparam3 (ptr_v, x_v, y_v);
3800 CAMLlocal2 (ret_v, tup_v);
3801 struct page *page;
3802 char *s = String_val (ptr_v);
3803 int x = Int_val (x_v), y = Int_val (y_v);
3804 struct pagedim *pdim;
3805 fz_point p;
3806 fz_matrix ctm;
3808 page = parse_pointer ("ml_unproject", s);
3809 pdim = &state.pagedims[page->pdimno];
3811 ret_v = Val_int (0);
3812 if (trylock ("ml_unproject")) {
3813 goto done;
3816 switch (page->type) {
3817 case DPDF:
3818 trimctm (page->u.pdfpage, page->pdimno);
3819 break;
3821 default:
3822 break;
3824 p.x = x;
3825 p.y = y;
3827 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3828 fz_invert_matrix (&ctm, &ctm);
3829 fz_transform_point (&p, &ctm);
3831 tup_v = caml_alloc_tuple (2);
3832 ret_v = caml_alloc_small (1, 1);
3833 Field (tup_v, 0) = Val_int (p.x);
3834 Field (tup_v, 1) = Val_int (p.y);
3835 Field (ret_v, 0) = tup_v;
3837 unlock ("ml_unproject");
3838 done:
3839 CAMLreturn (ret_v);
3842 static void makestippletex (void)
3844 const char pixels[] = "\xff\xff\0\0";
3845 glGenTextures (1, &state.stid);
3846 glBindTexture (GL_TEXTURE_1D, state.stid);
3847 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3848 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3849 glTexImage1D (
3850 GL_TEXTURE_1D,
3852 GL_ALPHA,
3855 GL_ALPHA,
3856 GL_UNSIGNED_BYTE,
3857 pixels
3861 CAMLprim value ml_init (value pipe_v, value params_v)
3863 CAMLparam2 (pipe_v, params_v);
3864 CAMLlocal2 (trim_v, fuzz_v);
3865 int ret;
3866 int texcount;
3867 char *fontpath;
3868 int colorspace;
3869 int mustoresize;
3870 int haspboext;
3871 struct sigaction sa;
3873 state.cr = Int_val (Field (pipe_v, 0));
3874 state.cw = Int_val (Field (pipe_v, 1));
3875 state.rotate = Int_val (Field (params_v, 0));
3876 state.fitmodel = Int_val (Field (params_v, 1));
3877 trim_v = Field (params_v, 2);
3878 texcount = Int_val (Field (params_v, 3));
3879 state.sliceheight = Int_val (Field (params_v, 4));
3880 mustoresize = Int_val (Field (params_v, 5));
3881 colorspace = Int_val (Field (params_v, 6));
3882 fontpath = String_val (Field (params_v, 7));
3883 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
3884 if (!state.trimcachepath) {
3885 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
3886 strerror (errno));
3888 haspboext = Bool_val (Field (params_v, 9));
3890 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3892 state.trimmargins = Bool_val (Field (trim_v, 0));
3893 fuzz_v = Field (trim_v, 1);
3894 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3895 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3896 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3897 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3899 set_tex_params (colorspace);
3901 if (*fontpath) {
3902 state.face = load_font (fontpath);
3904 else {
3905 unsigned int len;
3906 void *base = pdf_lookup_substitute_font (0, 0, 0, 0, &len);
3908 state.face = load_builtin_font (base, len);
3910 if (!state.face) _exit (1);
3912 realloctexts (texcount);
3914 if (haspboext) {
3915 setuppbo ();
3918 makestippletex ();
3919 #ifdef __CYGWIN__
3920 sa.sa_handler = SIG_IGN;
3921 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3922 #else
3923 sa.sa_handler = SIG_DFL;
3924 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP | SA_NOCLDWAIT;
3925 #endif
3926 if (sigemptyset (&sa.sa_mask)) {
3927 err (1, "sigemptyset");
3929 if (sigaction (SIGCHLD, &sa, NULL)) {
3930 err (1, "sigaction");
3933 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3934 if (ret) {
3935 errx (1, "pthread_create: %s", strerror (ret));
3938 CAMLreturn (Val_unit);