More __func__ionization
[llpp.git] / link.c
blobd98294b033d953a475cafcc4a4c64880db1cab3d
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
4 #include <errno.h>
5 #include <stdio.h>
6 #include <ctype.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <signal.h>
10 #include <wchar.h>
12 #include <unistd.h>
13 #include <pthread.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/utsname.h>
19 #ifdef __CYGWIN__
20 #include <cygwin/socket.h> /* FIONREAD */
21 #else
22 #include <spawn.h>
23 #endif
25 #include <regex.h>
26 #include <stdarg.h>
27 #include <limits.h>
28 #include <inttypes.h>
30 #include <GL/gl.h>
32 #include <caml/fail.h>
33 #include <caml/alloc.h>
34 #include <caml/memory.h>
35 #include <caml/unixsupport.h>
37 #if __GNUC__ < 5
38 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
39 clobbered diagnostics */
40 #pragma GCC diagnostic ignored "-Wclobbered"
41 #endif
43 #pragma GCC diagnostic push
44 #pragma GCC diagnostic ignored "-Wunused-parameter"
45 #pragma GCC diagnostic ignored "-Wshadow"
46 #include <mupdf/fitz.h>
47 #pragma GCC diagnostic pop
48 #include <mupdf/pdf.h>
50 #include <ft2build.h>
51 #include FT_FREETYPE_H
53 #ifdef USE_FONTCONFIG
54 #include <fontconfig/fontconfig.h>
55 #endif
57 #define PIGGYBACK
58 #define CACHE_PAGEREFS
60 #ifndef __USE_GNU
61 extern char **environ;
62 #endif
64 #define MIN(a,b) ((a) < (b) ? (a) : (b))
65 #define MAX(a,b) ((a) > (b) ? (a) : (b))
67 #if defined __GNUC__
68 #define NORETURN_ATTR __attribute__ ((noreturn))
69 #define UNUSED_ATTR __attribute__ ((unused))
70 #if !defined __clang__
71 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
72 #else
73 #define OPTIMIZE_ATTR(n)
74 #endif
75 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
76 #else
77 #define NORETURN_ATTR
78 #define UNUSED_ATTR
79 #define OPTIMIZE_ATTR(n)
80 #define GCC_FMT_ATTR(a, b)
81 #endif
83 #define FMT_s "zu"
85 #define FMT_ptr PRIxPTR
86 #define SCN_ptr SCNxPTR
87 #define FMT_ptr_cast(p) ((uintptr_t) (p))
88 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
90 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
91 err (int exitcode, const char *fmt, ...)
93 va_list ap;
94 int savederrno;
96 savederrno = errno;
97 va_start (ap, fmt);
98 vfprintf (stderr, fmt, ap);
99 va_end (ap);
100 fprintf (stderr, ": %s\n", strerror (savederrno));
101 fflush (stderr);
102 _exit (exitcode);
105 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
106 errx (int exitcode, const char *fmt, ...)
108 va_list ap;
110 va_start (ap, fmt);
111 vfprintf (stderr, fmt, ap);
112 va_end (ap);
113 fputc ('\n', stderr);
114 fflush (stderr);
115 _exit (exitcode);
118 #ifndef GL_TEXTURE_RECTANGLE_ARB
119 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
120 #endif
122 #ifndef GL_BGRA
123 #define GL_BGRA 0x80E1
124 #endif
126 #ifndef GL_UNSIGNED_INT_8_8_8_8
127 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
128 #endif
130 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
131 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
132 #endif
134 #if 0
135 #define lprintf printf
136 #else
137 #define lprintf(...)
138 #endif
140 #define ARSERT(cond) for (;;) { \
141 if (!(cond)) { \
142 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
144 break; \
147 struct slice {
148 int h;
149 int texindex;
152 struct tile {
153 int w, h;
154 int slicecount;
155 int sliceheight;
156 struct pbo *pbo;
157 fz_pixmap *pixmap;
158 struct slice slices[1];
161 struct pagedim {
162 int pageno;
163 int rotate;
164 int left;
165 int tctmready;
166 fz_irect bounds;
167 fz_rect pagebox;
168 fz_rect mediabox;
169 fz_matrix ctm, zoomctm, lctm, tctm;
172 struct slink {
173 enum { SLINK, SANNOT } tag;
174 fz_irect bbox;
175 union {
176 fz_link *link;
177 fz_annot *annot;
178 } u;
181 struct annot {
182 fz_irect bbox;
183 fz_annot *annot;
186 struct page {
187 int tgen;
188 int sgen;
189 int agen;
190 int pageno;
191 int pdimno;
192 fz_text_page *text;
193 fz_text_sheet *sheet;
194 fz_page *fzpage;
195 fz_display_list *dlist;
196 int slinkcount;
197 struct slink *slinks;
198 int annotcount;
199 struct annot *annots;
200 struct mark {
201 int i;
202 fz_text_span *span;
203 } fmark, lmark;
206 struct {
207 int sliceheight;
208 struct pagedim *pagedims;
209 int pagecount;
210 int pagedimcount;
211 fz_document *doc;
212 fz_context *ctx;
213 int w, h;
215 int texindex;
216 int texcount;
217 GLuint *texids;
219 GLenum texiform;
220 GLenum texform;
221 GLenum texty;
223 fz_colorspace *colorspace;
225 struct {
226 int w, h;
227 struct slice *slice;
228 } *texowners;
230 int rotate;
231 enum { FitWidth, FitProportional, FitPage } fitmodel;
232 int trimmargins;
233 int needoutline;
234 int gen;
235 int aalevel;
237 int trimanew;
238 fz_irect trimfuzz;
239 fz_pixmap *pig;
241 pthread_t thread;
242 int csock;
243 FT_Face face;
245 char *trimcachepath;
246 int cxack;
247 int dirty;
249 GLuint stid;
251 int pbo_usable;
252 void (*glBindBufferARB) (GLenum, GLuint);
253 GLboolean (*glUnmapBufferARB) (GLenum);
254 void *(*glMapBufferARB) (GLenum, GLenum);
255 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
256 void (*glGenBuffersARB) (GLsizei, GLuint *);
257 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
259 GLfloat texcoords[8];
260 GLfloat vertices[16];
262 #ifdef CACHE_PAGEREFS
263 struct {
264 int idx;
265 int count;
266 pdf_obj **objs;
267 pdf_document *pdf;
268 } pdflut;
269 #endif
270 } state;
272 struct pbo {
273 GLuint id;
274 void *ptr;
275 size_t size;
278 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
280 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
283 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
285 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
288 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
290 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
291 m.a, m.b, m.c, m.d, m.e, m.f);
294 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
296 static void lock (const char *cap)
298 int ret = pthread_mutex_lock (&mutex);
299 if (ret) {
300 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
304 static void unlock (const char *cap)
306 int ret = pthread_mutex_unlock (&mutex);
307 if (ret) {
308 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
312 static int trylock (const char *cap)
314 int ret = pthread_mutex_trylock (&mutex);
315 if (ret && ret != EBUSY) {
316 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
318 return ret == EBUSY;
321 static void *parse_pointer (const char *cap, const char *s)
323 int ret;
324 void *ptr;
326 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
327 if (ret != 1) {
328 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
330 return ptr;
333 static double now (void)
335 struct timeval tv;
337 if (gettimeofday (&tv, NULL)) {
338 err (1, "gettimeofday");
340 return tv.tv_sec + tv.tv_usec*1e-6;
343 static int hasdata (void)
345 int ret, avail;
346 ret = ioctl (state.csock, FIONREAD, &avail);
347 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
348 return avail > 0;
351 CAMLprim value ml_hasdata (value fd_v)
353 CAMLparam1 (fd_v);
354 int ret, avail;
356 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
357 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
358 CAMLreturn (Val_bool (avail > 0));
361 static void readdata (void *p, int size)
363 ssize_t n;
365 again:
366 n = read (state.csock, p, size);
367 if (n < 0) {
368 if (errno == EINTR) goto again;
369 err (1, "read (req %d, ret %zd)", size, n);
371 if (n - size) {
372 if (!n) errx (1, "EOF while reading");
373 errx (1, "read (req %d, ret %zd)", size, n);
377 static void writedata (char *p, int size)
379 ssize_t n;
381 p[0] = (size >> 24) & 0xff;
382 p[1] = (size >> 16) & 0xff;
383 p[2] = (size >> 8) & 0xff;
384 p[3] = (size >> 0) & 0xff;
386 n = write (state.csock, p, size + 4);
387 if (n - size - 4) {
388 if (!n) errx (1, "EOF while writing data");
389 err (1, "write (req %d, ret %zd)", size + 4, n);
393 static int readlen (void)
395 unsigned char p[4];
397 readdata (p, 4);
398 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
401 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
403 int size = 200, len;
404 va_list ap;
405 char *buf;
407 buf = malloc (size);
408 for (;;) {
409 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
411 va_start (ap, fmt);
412 len = vsnprintf (buf + 4, size - 4, fmt, ap);
413 va_end (ap);
415 if (len > -1) {
416 if (len < size - 4) {
417 writedata (buf, len);
418 break;
420 else size = len + 5;
422 else {
423 err (1, "vsnprintf for `%s' failed", fmt);
425 buf = realloc (buf, size);
427 free (buf);
430 static void closedoc (void)
432 #ifdef CACHE_PAGEREFS
433 if (state.pdflut.objs) {
434 int i;
436 for (i = 0; i < state.pdflut.count; ++i) {
437 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
439 free (state.pdflut.objs);
440 state.pdflut.objs = NULL;
441 state.pdflut.idx = 0;
443 #endif
444 if (state.doc) {
445 fz_drop_document (state.ctx, state.doc);
446 state.doc = NULL;
450 static int openxref (char *filename, char *password)
452 int i;
454 for (i = 0; i < state.texcount; ++i) {
455 state.texowners[i].w = -1;
456 state.texowners[i].slice = NULL;
459 closedoc ();
461 state.dirty = 0;
462 if (state.pagedims) {
463 free (state.pagedims);
464 state.pagedims = NULL;
466 state.pagedimcount = 0;
468 fz_set_aa_level (state.ctx, state.aalevel);
469 state.doc = fz_open_document (state.ctx, filename);
470 if (fz_needs_password (state.ctx, state.doc)) {
471 if (password && !*password) {
472 printd ("pass");
473 return 0;
475 else {
476 int ok = fz_authenticate_password (state.ctx, state.doc, password);
477 if (!ok) {
478 printd ("pass fail");
479 return 0;
483 state.pagecount = fz_count_pages (state.ctx, state.doc);
484 return 1;
487 static void pdfinfo (void)
489 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
490 if (pdf) {
491 pdf_obj *infoobj;
493 printd ("info PDF version\t%d.%d",
494 pdf->version / 10, pdf->version % 10);
496 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
497 pdf), "Info");
498 if (infoobj) {
499 unsigned int i;
500 char *s;
501 char *items[] = { "Title", "Author", "Creator",
502 "Producer", "CreationDate" };
504 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
505 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
506 s = pdf_to_utf8 (state.ctx, pdf, obj);
507 if (*s) printd ("info %s\t%s", items[i], s);
508 fz_free (state.ctx, s);
511 printd ("infoend");
515 static void unlinktile (struct tile *tile)
517 int i;
519 for (i = 0; i < tile->slicecount; ++i) {
520 struct slice *s = &tile->slices[i];
522 if (s->texindex != -1) {
523 if (state.texowners[s->texindex].slice == s) {
524 state.texowners[s->texindex].slice = NULL;
530 static void freepage (struct page *page)
532 if (!page) return;
533 if (page->text) {
534 fz_drop_text_page (state.ctx, page->text);
536 if (page->sheet) {
537 fz_drop_text_sheet (state.ctx, page->sheet);
539 if (page->slinks) {
540 free (page->slinks);
542 fz_drop_display_list (state.ctx, page->dlist);
543 fz_drop_page (state.ctx, page->fzpage);
544 free (page);
547 static void freetile (struct tile *tile)
549 unlinktile (tile);
550 if (!tile->pbo) {
551 #ifndef PIGGYBACK
552 fz_drop_pixmap (state.ctx, tile->pixmap);
553 #else
554 if (state.pig) {
555 fz_drop_pixmap (state.ctx, state.pig);
557 state.pig = tile->pixmap;
558 #endif
560 else {
561 free (tile->pbo);
562 fz_drop_pixmap (state.ctx, tile->pixmap);
564 free (tile);
567 #ifdef __ALTIVEC__
568 #include <stdint.h>
569 #include <altivec.h>
571 static int cacheline32bytes;
573 static void __attribute__ ((constructor)) clcheck (void)
575 char **envp = environ;
576 unsigned long *auxv;
578 while (*envp++);
580 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
581 if (*auxv == 19) {
582 cacheline32bytes = auxv[1] == 32;
583 return;
588 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
590 size_t size = pixmap->w * pixmap->h * pixmap->n;
591 if (cacheline32bytes && size > 32) {
592 intptr_t a1, a2, diff;
593 size_t sizea, i;
594 vector unsigned char v = vec_splat_u8 (-1);
595 vector unsigned char *p;
597 a1 = a2 = (intptr_t) pixmap->samples;
598 a2 = (a1 + 31) & ~31;
599 diff = a2 - a1;
600 sizea = size - diff;
601 p = (void *) a2;
603 while (a1 != a2) *(char *) a1++ = 0xff;
604 for (i = 0; i < (sizea & ~31); i += 32) {
605 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
606 vec_st (v, i, p);
607 vec_st (v, i + 16, p);
609 while (i < sizea) *((char *) a1 + i++) = 0xff;
611 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
613 #else
614 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
615 #endif
617 static void trimctm (pdf_page *page, int pindex)
619 fz_matrix ctm;
620 struct pagedim *pdim = &state.pagedims[pindex];
622 if (!pdim->tctmready) {
623 if (state.trimmargins) {
624 fz_rect realbox;
625 fz_matrix rm, sm, tm, im, ctm1;
627 fz_rotate (&rm, -pdim->rotate);
628 fz_scale (&sm, 1, -1);
629 fz_concat (&ctm, &rm, &sm);
630 realbox = pdim->mediabox;
631 fz_transform_rect (&realbox, &ctm);
632 fz_translate (&tm, -realbox.x0, -realbox.y0);
633 fz_concat (&ctm1, &ctm, &tm);
634 fz_invert_matrix (&im, &page->ctm);
635 fz_concat (&ctm, &im, &ctm1);
637 else {
638 ctm = fz_identity;
640 pdim->tctm = ctm;
641 pdim->tctmready = 1;
645 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
647 fz_matrix ctm, tm;
648 int pdimno = pdim - state.pagedims;
650 if (pdf_specifics (state.ctx, state.doc)) {
651 trimctm ((pdf_page *) fzpage, pdimno);
652 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
654 else {
655 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
656 fz_concat (&ctm, &tm, &pdim->ctm);
658 return ctm;
661 static fz_matrix pagectm (struct page *page)
663 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
666 static void *loadpage (int pageno, int pindex)
668 fz_device *dev;
669 struct page *page;
671 page = calloc (sizeof (struct page), 1);
672 if (!page) {
673 err (1, "calloc page %d", pageno);
676 page->dlist = fz_new_display_list (state.ctx);
677 dev = fz_new_list_device (state.ctx, page->dlist);
678 fz_try (state.ctx) {
679 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
680 fz_run_page (state.ctx, page->fzpage, dev,
681 &fz_identity, NULL);
683 fz_catch (state.ctx) {
684 page->fzpage = NULL;
686 fz_drop_device (state.ctx, dev);
688 page->pdimno = pindex;
689 page->pageno = pageno;
690 page->sgen = state.gen;
691 page->agen = state.gen;
692 page->tgen = state.gen;
693 return page;
696 static struct tile *alloctile (int h)
698 int i;
699 int slicecount;
700 size_t tilesize;
701 struct tile *tile;
703 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
704 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
705 tile = calloc (tilesize, 1);
706 if (!tile) {
707 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
709 for (i = 0; i < slicecount; ++i) {
710 int sh = MIN (h, state.sliceheight);
711 tile->slices[i].h = sh;
712 tile->slices[i].texindex = -1;
713 h -= sh;
715 tile->slicecount = slicecount;
716 tile->sliceheight = state.sliceheight;
717 return tile;
720 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
721 struct pbo *pbo)
723 fz_rect rect;
724 fz_irect bbox;
725 fz_matrix ctm;
726 fz_device *dev;
727 struct tile *tile;
728 struct pagedim *pdim;
730 tile = alloctile (h);
731 pdim = &state.pagedims[page->pdimno];
733 bbox = pdim->bounds;
734 bbox.x0 += x;
735 bbox.y0 += y;
736 bbox.x1 = bbox.x0 + w;
737 bbox.y1 = bbox.y0 + h;
739 if (state.pig) {
740 if (state.pig->w == w
741 && state.pig->h == h
742 && state.pig->colorspace == state.colorspace) {
743 tile->pixmap = state.pig;
744 tile->pixmap->x = bbox.x0;
745 tile->pixmap->y = bbox.y0;
747 else {
748 fz_drop_pixmap (state.ctx, state.pig);
750 state.pig = NULL;
752 if (!tile->pixmap) {
753 if (pbo) {
754 tile->pixmap =
755 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
756 &bbox, pbo->ptr);
757 tile->pbo = pbo;
759 else {
760 tile->pixmap =
761 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
765 tile->w = w;
766 tile->h = h;
767 clearpixmap (tile->pixmap);
769 dev = fz_new_draw_device (state.ctx, tile->pixmap);
770 ctm = pagectm (page);
771 fz_rect_from_irect (&rect, &bbox);
772 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
773 fz_drop_device (state.ctx, dev);
775 return tile;
778 #ifdef CACHE_PAGEREFS
779 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
780 thanks to Robin Watts */
781 static void
782 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
784 fz_context *ctx = state.ctx; /* doc->ctx; */
785 pdf_obj *kids;
786 int i, len;
788 if (state.pdflut.idx == state.pagecount) return;
790 kids = pdf_dict_gets (ctx, node, "Kids");
791 len = pdf_array_len (ctx, kids);
793 if (len == 0)
794 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
796 if (pdf_mark_obj (ctx, node))
797 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
798 for (i = 0; i < len; i++) {
799 pdf_obj *kid = pdf_array_get (ctx, kids, i);
800 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
801 if (*type
802 ? !strcmp (type, "Pages")
803 : pdf_dict_gets (ctx, kid, "Kids")
804 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
805 pdf_collect_pages (doc, kid);
807 else {
808 if (*type
809 ? strcmp (type, "Page") != 0
810 : !pdf_dict_gets (ctx, kid, "MediaBox"))
811 fz_warn (ctx, "non-page object in page tree (%s)", type);
812 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
815 pdf_unmark_obj (ctx, node);
818 static void
819 pdf_load_page_objs (pdf_document *doc)
821 pdf_obj *root = pdf_dict_gets (state.ctx,
822 pdf_trailer (state.ctx, doc), "Root");
823 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
825 if (!node)
826 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
828 state.pdflut.idx = 0;
829 pdf_collect_pages (doc, node);
831 #endif
833 static void initpdims (int wthack)
835 double start, end;
836 FILE *trimf = NULL;
837 fz_rect rootmediabox;
838 int pageno, trim, show;
839 int trimw = 0, cxcount;
840 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
842 fz_var (trimw);
843 fz_var (cxcount);
844 start = now ();
846 if (state.trimmargins && state.trimcachepath) {
847 trimf = fopen (state.trimcachepath, "rb");
848 if (!trimf) {
849 trimf = fopen (state.trimcachepath, "wb");
850 trimw = 1;
854 if (state.trimmargins || pdf || !state.cxack)
855 cxcount = state.pagecount;
856 else
857 cxcount = MIN (state.pagecount, 1);
859 if (pdf) {
860 pdf_obj *obj;
861 obj = pdf_dict_getp (state.ctx, pdf_trailer (state.ctx, pdf),
862 "Root/Pages/MediaBox");
863 pdf_to_rect (state.ctx, obj, &rootmediabox);
866 #ifdef CACHE_PAGEREFS
867 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
868 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
869 if (!state.pdflut.objs) {
870 err (1, "malloc pageobjs %zu %d %zu failed",
871 sizeof (*state.pdflut.objs), cxcount,
872 sizeof (*state.pdflut.objs) * cxcount);
874 state.pdflut.count = cxcount;
875 pdf_load_page_objs (pdf);
876 state.pdflut.pdf = pdf;
878 #endif
880 for (pageno = 0; pageno < cxcount; ++pageno) {
881 int rotate = 0;
882 struct pagedim *p;
883 fz_rect mediabox;
885 if (pdf) {
886 pdf_obj *pageref, *pageobj;
888 #ifdef CACHE_PAGEREFS
889 pageref = state.pdflut.objs[pageno];
890 #else
891 pageref = pdf_lookup_page_obj (state.ctx, pdf, pageno);
892 #endif
893 pageobj = pdf_resolve_indirect (state.ctx, pageref);
895 if (state.trimmargins) {
896 fz_context *ctx = state.ctx;
897 pdf_obj *obj;
898 pdf_page *page;
900 fz_try (state.ctx) {
901 page = pdf_load_page (ctx, pdf, pageno);
902 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
903 trim = state.trimanew || !obj;
904 if (trim) {
905 fz_rect rect;
906 fz_matrix ctm;
907 fz_device *dev;
909 dev = fz_new_bbox_device (ctx, &rect);
910 dev->hints |= FZ_IGNORE_SHADE;
911 fz_invert_matrix (&ctm, &page->ctm);
912 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
913 fz_drop_device (ctx, dev);
915 rect.x0 += state.trimfuzz.x0;
916 rect.x1 += state.trimfuzz.x1;
917 rect.y0 += state.trimfuzz.y0;
918 rect.y1 += state.trimfuzz.y1;
919 fz_transform_rect (&rect, &ctm);
920 fz_intersect_rect (&rect, &page->mediabox);
922 if (fz_is_empty_rect (&rect)) {
923 mediabox = page->mediabox;
925 else {
926 mediabox = rect;
929 obj = pdf_new_array (ctx, pdf, 4);
930 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
931 mediabox.x0));
932 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
933 mediabox.y0));
934 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
935 mediabox.x1));
936 pdf_array_push (ctx, obj, pdf_new_real (state.ctx, pdf,
937 mediabox.y1));
938 pdf_dict_puts (state.ctx, pageobj, "llpp.TrimBox", obj);
940 else {
941 mediabox.x0 = pdf_to_real (ctx,
942 pdf_array_get (ctx, obj, 0));
943 mediabox.y0 = pdf_to_real (ctx,
944 pdf_array_get (ctx, obj, 1));
945 mediabox.x1 = pdf_to_real (ctx,
946 pdf_array_get (ctx, obj, 2));
947 mediabox.y1 = pdf_to_real (ctx,
948 pdf_array_get (ctx, obj, 3));
951 rotate = page->rotate;
952 fz_drop_page (ctx, &page->super);
954 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
955 if (show) {
956 printd ("progress %f Trimming %d",
957 (double) (pageno + 1) / state.pagecount,
958 pageno + 1);
961 fz_catch (state.ctx) {
962 fprintf (stderr, "failed to load page %d\n", pageno+1);
965 else {
966 int empty = 0;
967 fz_rect cropbox;
969 pdf_to_rect (state.ctx,
970 pdf_dict_gets (state.ctx, pageobj, "MediaBox"),
971 &mediabox);
972 if (fz_is_empty_rect (&mediabox)) {
973 mediabox.x0 = 0;
974 mediabox.y0 = 0;
975 mediabox.x1 = 612;
976 mediabox.y1 = 792;
977 empty = 1;
980 pdf_to_rect (state.ctx,
981 pdf_dict_gets (state.ctx, pageobj, "CropBox"),
982 &cropbox);
983 if (!fz_is_empty_rect (&cropbox)) {
984 if (empty) {
985 mediabox = cropbox;
987 else {
988 fz_intersect_rect (&mediabox, &cropbox);
991 else {
992 if (empty) {
993 if (fz_is_empty_rect (&rootmediabox)) {
994 fprintf (stderr,
995 "cannot find page size for page %d\n",
996 pageno+1);
998 else {
999 mediabox = rootmediabox;
1003 rotate = pdf_to_int (state.ctx,
1004 pdf_dict_gets (state.ctx,
1005 pageobj, "Rotate"));
1008 else {
1009 if (state.trimmargins && trimw) {
1010 fz_page *page;
1012 fz_try (state.ctx) {
1013 page = fz_load_page (state.ctx, state.doc, pageno);
1014 fz_bound_page (state.ctx, page, &mediabox);
1015 rotate = 0;
1016 if (state.trimmargins) {
1017 fz_rect rect;
1018 fz_device *dev;
1020 dev = fz_new_bbox_device (state.ctx, &rect);
1021 dev->hints |= FZ_IGNORE_SHADE;
1022 fz_run_page (state.ctx, page, dev,
1023 &fz_identity, NULL);
1024 fz_drop_device (state.ctx, dev);
1026 rect.x0 += state.trimfuzz.x0;
1027 rect.x1 += state.trimfuzz.x1;
1028 rect.y0 += state.trimfuzz.y0;
1029 rect.y1 += state.trimfuzz.y1;
1030 fz_intersect_rect (&rect, &mediabox);
1032 if (!fz_is_empty_rect (&rect)) {
1033 mediabox = rect;
1036 fz_drop_page (state.ctx, page);
1037 if (!state.cxack) {
1038 printd ("progress %f loading %d",
1039 (double) (pageno + 1) / state.pagecount,
1040 pageno + 1);
1043 fz_catch (state.ctx) {
1045 if (trimf) {
1046 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1047 if (n - 1) {
1048 err (1, "fwrite trim mediabox");
1052 else {
1053 if (trimf) {
1054 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1055 if (n - 1) {
1056 err (1, "fread trim mediabox %d", pageno);
1059 else {
1060 fz_page *page;
1061 fz_try (state.ctx) {
1062 page = fz_load_page (state.ctx,
1063 state.doc, pageno);
1064 fz_bound_page (state.ctx, page, &mediabox);
1065 fz_drop_page (state.ctx, page);
1067 show = !state.trimmargins && pageno % 20 == 0;
1068 if (show) {
1069 printd ("progress %f Gathering dimensions %d",
1070 (double) (pageno) / state.pagecount,
1071 pageno);
1074 fz_catch (state.ctx) {
1075 fprintf (stderr, "failed to load page %d\n", pageno);
1081 if (state.pagedimcount == 0
1082 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1083 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1084 size_t size;
1086 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1087 state.pagedims = realloc (state.pagedims, size);
1088 if (!state.pagedims) {
1089 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1090 size, state.pagedimcount + 1);
1093 p = &state.pagedims[state.pagedimcount++];
1094 p->rotate = rotate;
1095 p->mediabox = mediabox;
1096 p->pageno = pageno;
1099 end = now ();
1100 if (!wthack) {
1101 printd ("progress 1 %s %d pages in %f seconds",
1102 state.trimmargins ? "Trimmed" : "Processed",
1103 state.pagecount, end - start);
1105 state.trimanew = 0;
1106 if (trimf) {
1107 if (fclose (trimf)) {
1108 err (1, "fclose");
1113 static void layout (void)
1115 int pindex;
1116 fz_rect box;
1117 fz_matrix ctm, rm;
1118 struct pagedim *p = p;
1119 double zw, w, maxw = 0.0, zoom = zoom;
1121 if (state.pagedimcount == 0) return;
1123 switch (state.fitmodel) {
1124 case FitProportional:
1125 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1126 double x0, x1;
1128 p = &state.pagedims[pindex];
1129 fz_rotate (&rm, p->rotate + state.rotate);
1130 box = p->mediabox;
1131 fz_transform_rect (&box, &rm);
1133 x0 = MIN (box.x0, box.x1);
1134 x1 = MAX (box.x0, box.x1);
1136 w = x1 - x0;
1137 maxw = MAX (w, maxw);
1138 zoom = state.w / maxw;
1140 break;
1142 case FitPage:
1143 maxw = state.w;
1144 break;
1146 case FitWidth:
1147 break;
1149 default:
1150 ARSERT (0 && state.fitmodel);
1153 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1154 fz_rect rect;
1155 fz_matrix tm, sm;
1157 p = &state.pagedims[pindex];
1158 fz_rotate (&ctm, state.rotate);
1159 fz_rotate (&rm, p->rotate + state.rotate);
1160 box = p->mediabox;
1161 fz_transform_rect (&box, &rm);
1162 w = box.x1 - box.x0;
1163 switch (state.fitmodel) {
1164 case FitProportional:
1165 p->left = ((maxw - w) * zoom) / 2.0;
1166 break;
1167 case FitPage:
1169 double zh, h;
1170 zw = maxw / w;
1171 h = box.y1 - box.y0;
1172 zh = state.h / h;
1173 zoom = MIN (zw, zh);
1174 p->left = (maxw - (w * zoom)) / 2.0;
1176 break;
1177 case FitWidth:
1178 p->left = 0;
1179 zoom = state.w / w;
1180 break;
1183 fz_scale (&p->zoomctm, zoom, zoom);
1184 fz_concat (&ctm, &p->zoomctm, &ctm);
1186 fz_rotate (&rm, p->rotate);
1187 p->pagebox = p->mediabox;
1188 fz_transform_rect (&p->pagebox, &rm);
1189 p->pagebox.x1 -= p->pagebox.x0;
1190 p->pagebox.y1 -= p->pagebox.y0;
1191 p->pagebox.x0 = 0;
1192 p->pagebox.y0 = 0;
1193 rect = p->pagebox;
1194 fz_transform_rect (&rect, &ctm);
1195 fz_round_rect (&p->bounds, &rect);
1196 p->ctm = ctm;
1198 fz_translate (&tm, 0, -p->mediabox.y1);
1199 fz_scale (&sm, zoom, -zoom);
1200 fz_concat (&ctm, &tm, &sm);
1201 fz_concat (&p->lctm, &ctm, &rm);
1203 p->tctmready = 0;
1206 do {
1207 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1208 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1209 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1210 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1211 int boundw = x1 - x0;
1212 int boundh = y1 - y0;
1214 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1215 } while (p-- != state.pagedims);
1218 static
1219 struct anchor { int n; int x; int y; int w; int h; }
1220 desttoanchor (fz_link_dest *dest)
1222 int i;
1223 struct anchor a;
1224 struct pagedim *pdim = state.pagedims;
1226 a.n = -1;
1227 a.x = 0;
1228 a.y = 0;
1229 for (i = 0; i < state.pagedimcount; ++i) {
1230 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1231 break;
1232 pdim = &state.pagedims[i];
1234 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1235 fz_point p;
1236 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1237 p.x = dest->ld.gotor.lt.x;
1238 else
1239 p.x = 0.0;
1240 p.y = dest->ld.gotor.lt.y;
1241 fz_transform_point (&p, &pdim->lctm);
1242 a.x = p.x;
1243 a.y = p.y;
1245 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1246 double x0, x1, y0, y1;
1248 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1249 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1250 a.w = x1 - x0;
1251 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1252 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1253 a.h = y1 - y0;
1254 a.n = dest->ld.gotor.page;
1256 return a;
1259 static void recurse_outline (fz_outline *outline, int level)
1261 while (outline) {
1262 switch (outline->dest.kind) {
1263 case FZ_LINK_GOTO:
1265 struct anchor a = desttoanchor (&outline->dest);
1267 if (a.n >= 0) {
1268 printd ("o %d %d %d %d %s",
1269 level, a.n, a.y, a.h, outline->title);
1272 break;
1274 case FZ_LINK_URI:
1275 printd ("ou %d %" FMT_s " %s %s", level,
1276 strlen (outline->title), outline->title,
1277 outline->dest.ld.uri.uri);
1278 break;
1280 case FZ_LINK_NONE:
1281 printd ("on %d %s", level, outline->title);
1282 break;
1284 default:
1285 printd ("emsg Unhandled outline kind %d for %s\n",
1286 outline->dest.kind, outline->title);
1287 break;
1289 if (outline->down) {
1290 recurse_outline (outline->down, level + 1);
1292 outline = outline->next;
1296 static void process_outline (void)
1298 fz_outline *outline;
1300 if (!state.needoutline || !state.pagedimcount) return;
1302 state.needoutline = 0;
1303 outline = fz_load_outline (state.ctx, state.doc);
1304 if (outline) {
1305 recurse_outline (outline, 0);
1306 fz_drop_outline (state.ctx, outline);
1310 static char *strofspan (fz_text_span *span)
1312 char *p;
1313 char utf8[10];
1314 fz_text_char *ch;
1315 size_t size = 0, cap = 80;
1317 p = malloc (cap + 1);
1318 if (!p) return NULL;
1320 for (ch = span->text; ch < span->text + span->len; ++ch) {
1321 int n = fz_runetochar (utf8, ch->c);
1322 if (size + n > cap) {
1323 cap *= 2;
1324 p = realloc (p, cap + 1);
1325 if (!p) return NULL;
1328 memcpy (p + size, utf8, n);
1329 size += n;
1331 p[size] = 0;
1332 return p;
1335 static int matchspan (regex_t *re, fz_text_span *span,
1336 int stop, int pageno, double start)
1338 int ret;
1339 char *p;
1340 regmatch_t rm;
1341 int a, b, c;
1342 fz_rect sb, eb;
1343 fz_point p1, p2, p3, p4;
1345 p = strofspan (span);
1346 if (!p) return -1;
1348 ret = regexec (re, p, 1, &rm, 0);
1349 if (ret) {
1350 free (p);
1351 if (ret != REG_NOMATCH) {
1352 size_t size;
1353 char errbuf[80];
1354 size = regerror (ret, re, errbuf, sizeof (errbuf));
1355 printd ("msg regexec error `%.*s'",
1356 (int) size, errbuf);
1357 return -1;
1359 return 0;
1361 else {
1362 int l = span->len;
1364 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1365 c += fz_runelen (span->text[a].c);
1367 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1368 c += fz_runelen (span->text[b].c);
1371 if (fz_runelen (span->text[b].c) > 1) {
1372 b = MAX (0, b-1);
1375 fz_text_char_bbox (state.ctx, &sb, span, a);
1376 fz_text_char_bbox (state.ctx, &eb, span, b);
1378 p1.x = sb.x0;
1379 p1.y = sb.y0;
1380 p2.x = eb.x1;
1381 p2.y = sb.y0;
1382 p3.x = eb.x1;
1383 p3.y = eb.y1;
1384 p4.x = sb.x0;
1385 p4.y = eb.y1;
1387 if (!stop) {
1388 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1389 pageno, 1,
1390 p1.x, p1.y,
1391 p2.x, p2.y,
1392 p3.x, p3.y,
1393 p4.x, p4.y);
1395 printd ("progress 1 found at %d `%.*s' in %f sec",
1396 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1397 now () - start);
1399 else {
1400 printd ("match %d %d %f %f %f %f %f %f %f %f",
1401 pageno, 2,
1402 p1.x, p1.y,
1403 p2.x, p2.y,
1404 p3.x, p3.y,
1405 p4.x, p4.y);
1407 free (p);
1408 return 1;
1412 static int compareblocks (const void *l, const void *r)
1414 fz_text_block const *ls = l;
1415 fz_text_block const *rs = r;
1416 return ls->bbox.y0 - rs->bbox.y0;
1419 /* wishful thinking function */
1420 static void search (regex_t *re, int pageno, int y, int forward)
1422 int i, j;
1423 fz_device *tdev;
1424 fz_text_page *text;
1425 fz_text_sheet *sheet;
1426 struct pagedim *pdim, *pdimprev;
1427 int stop = 0, niters = 0;
1428 double start, end;
1429 fz_page *page;
1431 start = now ();
1432 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1433 if (niters++ == 5) {
1434 niters = 0;
1435 if (hasdata ()) {
1436 printd ("progress 1 attention requested aborting search at %d",
1437 pageno);
1438 stop = 1;
1440 else {
1441 printd ("progress %f searching in page %d",
1442 (double) (pageno + 1) / state.pagecount,
1443 pageno);
1446 pdimprev = NULL;
1447 for (i = 0; i < state.pagedimcount; ++i) {
1448 pdim = &state.pagedims[i];
1449 if (pdim->pageno == pageno) {
1450 goto found;
1452 if (pdim->pageno > pageno) {
1453 pdim = pdimprev;
1454 goto found;
1456 pdimprev = pdim;
1458 pdim = pdimprev;
1459 found:
1461 sheet = fz_new_text_sheet (state.ctx);
1462 text = fz_new_text_page (state.ctx);
1463 tdev = fz_new_text_device (state.ctx, sheet, text);
1465 page = fz_load_page (state.ctx, state.doc, pageno);
1467 fz_matrix ctm = pagectm1 (page, pdim);
1468 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1471 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1472 fz_drop_device (state.ctx, tdev);
1474 for (j = 0; j < text->len; ++j) {
1475 int k;
1476 fz_page_block *pb;
1477 fz_text_block *block;
1479 pb = &text->blocks[forward ? j : text->len - 1 - j];
1480 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1481 block = pb->u.text;
1483 for (k = 0; k < block->len; ++k) {
1484 fz_text_line *line;
1485 fz_text_span *span;
1487 if (forward) {
1488 line = &block->lines[k];
1489 if (line->bbox.y0 < y + 1) continue;
1491 else {
1492 line = &block->lines[block->len - 1 - k];
1493 if (line->bbox.y0 > y - 1) continue;
1496 for (span = line->first_span; span; span = span->next) {
1497 switch (matchspan (re, span, stop, pageno, start)) {
1498 case 0: break;
1499 case 1: stop = 1; break;
1500 case -1: stop = 1; goto endloop;
1505 if (forward) {
1506 pageno += 1;
1507 y = 0;
1509 else {
1510 pageno -= 1;
1511 y = INT_MAX;
1513 endloop:
1514 fz_drop_text_page (state.ctx, text);
1515 fz_drop_text_sheet (state.ctx, sheet);
1516 fz_drop_page (state.ctx, page);
1518 end = now ();
1519 if (!stop) {
1520 printd ("progress 1 no matches %f sec", end - start);
1522 printd ("clearrects");
1525 static void set_tex_params (int colorspace)
1527 union {
1528 unsigned char b;
1529 unsigned int s;
1530 } endianness = {1};
1532 switch (colorspace) {
1533 case 0:
1534 state.texiform = GL_RGBA8;
1535 state.texform = GL_RGBA;
1536 state.texty = GL_UNSIGNED_BYTE;
1537 state.colorspace = fz_device_rgb (state.ctx);
1538 break;
1539 case 1:
1540 state.texiform = GL_RGBA8;
1541 state.texform = GL_BGRA;
1542 state.texty = endianness.s > 1
1543 ? GL_UNSIGNED_INT_8_8_8_8
1544 : GL_UNSIGNED_INT_8_8_8_8_REV;
1545 state.colorspace = fz_device_bgr (state.ctx);
1546 break;
1547 case 2:
1548 state.texiform = GL_LUMINANCE_ALPHA;
1549 state.texform = GL_LUMINANCE_ALPHA;
1550 state.texty = GL_UNSIGNED_BYTE;
1551 state.colorspace = fz_device_gray (state.ctx);
1552 break;
1553 default:
1554 errx (1, "invalid colorspce %d", colorspace);
1558 static void realloctexts (int texcount)
1560 size_t size;
1562 if (texcount == state.texcount) return;
1564 if (texcount < state.texcount) {
1565 glDeleteTextures (state.texcount - texcount,
1566 state.texids + texcount);
1569 size = texcount * sizeof (*state.texids);
1570 state.texids = realloc (state.texids, size);
1571 if (!state.texids) {
1572 err (1, "realloc texids %" FMT_s, size);
1575 size = texcount * sizeof (*state.texowners);
1576 state.texowners = realloc (state.texowners, size);
1577 if (!state.texowners) {
1578 err (1, "realloc texowners %" FMT_s, size);
1580 if (texcount > state.texcount) {
1581 int i;
1583 glGenTextures (texcount - state.texcount,
1584 state.texids + state.texcount);
1585 for (i = state.texcount; i < texcount; ++i) {
1586 state.texowners[i].w = -1;
1587 state.texowners[i].slice = NULL;
1590 state.texcount = texcount;
1591 state.texindex = 0;
1594 static char *mbtoutf8 (char *s)
1596 char *p, *r;
1597 wchar_t *tmp;
1598 size_t i, ret, len;
1600 len = mbstowcs (NULL, s, strlen (s));
1601 if (len == 0) {
1602 return s;
1604 else {
1605 if (len == (size_t) -1) {
1606 return s;
1610 tmp = malloc (len * sizeof (wchar_t));
1611 if (!tmp) {
1612 return s;
1615 ret = mbstowcs (tmp, s, len);
1616 if (ret == (size_t) -1) {
1617 free (tmp);
1618 return s;
1621 len = 0;
1622 for (i = 0; i < ret; ++i) {
1623 len += fz_runelen (tmp[i]);
1626 p = r = malloc (len + 1);
1627 if (!r) {
1628 free (tmp);
1629 return s;
1632 for (i = 0; i < ret; ++i) {
1633 p += fz_runetochar (p, tmp[i]);
1635 *p = 0;
1636 free (tmp);
1637 return r;
1640 CAMLprim value ml_mbtoutf8 (value s_v)
1642 CAMLparam1 (s_v);
1643 CAMLlocal1 (ret_v);
1644 char *s, *r;
1646 s = String_val (s_v);
1647 r = mbtoutf8 (s);
1648 if (r == s) {
1649 ret_v = s_v;
1651 else {
1652 ret_v = caml_copy_string (r);
1653 free (r);
1655 CAMLreturn (ret_v);
1658 static void * mainloop (void UNUSED_ATTR *unused)
1660 char *p = NULL;
1661 int len, ret, oldlen = 0;
1663 fz_var (p);
1664 fz_var (oldlen);
1665 for (;;) {
1666 len = readlen ();
1667 if (len == 0) {
1668 errx (1, "readlen returned 0");
1671 if (oldlen < len + 1) {
1672 p = realloc (p, len + 1);
1673 if (!p) {
1674 err (1, "realloc %d failed", len + 1);
1676 oldlen = len + 1;
1678 readdata (p, len);
1679 p[len] = 0;
1681 if (!strncmp ("open", p, 4)) {
1682 int wthack, off, ok = 0;
1683 char *password;
1684 char *filename;
1685 char *utf8filename;
1686 size_t filenamelen;
1688 fz_var (ok);
1689 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1690 if (ret != 2) {
1691 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1694 filename = p + 5 + off;
1695 filenamelen = strlen (filename);
1696 password = filename + filenamelen + 1;
1698 lock ("open");
1699 fz_try (state.ctx) {
1700 ok = openxref (filename, password);
1702 fz_catch (state.ctx) {
1703 utf8filename = mbtoutf8 (filename);
1704 printd ("msg Could not open %s", utf8filename);
1706 if (ok) {
1707 pdfinfo ();
1708 initpdims (wthack);
1710 unlock ("open");
1712 if (ok) {
1713 if (!wthack) {
1714 utf8filename = mbtoutf8 (filename);
1715 printd ("msg Opened %s (press h/F1 to get help)",
1716 utf8filename);
1717 if (utf8filename != filename) {
1718 free (utf8filename);
1721 state.needoutline = 1;
1724 else if (!strncmp ("cs", p, 2)) {
1725 int i, colorspace;
1727 ret = sscanf (p + 2, " %d", &colorspace);
1728 if (ret != 1) {
1729 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1731 lock ("cs");
1732 set_tex_params (colorspace);
1733 for (i = 0; i < state.texcount; ++i) {
1734 state.texowners[i].w = -1;
1735 state.texowners[i].slice = NULL;
1737 unlock ("cs");
1739 else if (!strncmp ("freepage", p, 8)) {
1740 void *ptr;
1742 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1743 if (ret != 1) {
1744 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1746 freepage (ptr);
1748 else if (!strncmp ("freetile", p, 8)) {
1749 void *ptr;
1751 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1752 if (ret != 1) {
1753 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1755 freetile (ptr);
1757 else if (!strncmp ("search", p, 6)) {
1758 int icase, pageno, y, len2, forward;
1759 char *pattern;
1760 regex_t re;
1762 ret = sscanf (p + 6, " %d %d %d %d,%n",
1763 &icase, &pageno, &y, &forward, &len2);
1764 if (ret != 4) {
1765 errx (1, "malformed search `%s' ret=%d", p, ret);
1768 pattern = p + 6 + len2;
1769 ret = regcomp (&re, pattern,
1770 REG_EXTENDED | (icase ? REG_ICASE : 0));
1771 if (ret) {
1772 char errbuf[80];
1773 size_t size;
1775 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1776 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1778 else {
1779 search (&re, pageno, y, forward);
1780 regfree (&re);
1783 else if (!strncmp ("geometry", p, 8)) {
1784 int w, h, fitmodel;
1786 printd ("clear");
1787 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1788 if (ret != 3) {
1789 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1792 lock ("geometry");
1793 state.h = h;
1794 if (w != state.w) {
1795 int i;
1796 state.w = w;
1797 for (i = 0; i < state.texcount; ++i) {
1798 state.texowners[i].slice = NULL;
1801 state.fitmodel = fitmodel;
1802 layout ();
1803 process_outline ();
1805 state.gen++;
1806 unlock ("geometry");
1807 printd ("continue %d", state.pagecount);
1809 else if (!strncmp ("reqlayout", p, 9)) {
1810 char *nameddest;
1811 int rotate, off, h;
1812 unsigned int fitmodel;
1813 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1815 printd ("clear");
1816 ret = sscanf (p + 9, " %d %u %d %n",
1817 &rotate, &fitmodel, &h, &off);
1818 if (ret != 3) {
1819 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1821 lock ("reqlayout");
1822 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1823 state.gen += 1;
1825 state.rotate = rotate;
1826 state.fitmodel = fitmodel;
1827 state.h = h;
1828 layout ();
1829 process_outline ();
1831 nameddest = p + 9 + off;
1832 if (pdf && nameddest && *nameddest) {
1833 struct anchor a;
1834 fz_link_dest dest;
1835 pdf_obj *needle, *obj;
1837 needle = pdf_new_string (state.ctx, pdf, nameddest,
1838 strlen (nameddest));
1839 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1840 if (obj) {
1841 dest = pdf_parse_link_dest (state.ctx, pdf,
1842 FZ_LINK_GOTO, obj);
1844 a = desttoanchor (&dest);
1845 if (a.n >= 0) {
1846 printd ("a %d %d %d", a.n, a.x, a.y);
1848 else {
1849 printd ("emsg failed to parse destination `%s'\n",
1850 nameddest);
1853 else {
1854 printd ("emsg destination `%s' not found\n",
1855 nameddest);
1857 pdf_drop_obj (state.ctx, needle);
1860 state.gen++;
1861 unlock ("reqlayout");
1862 printd ("continue %d", state.pagecount);
1864 else if (!strncmp ("page", p, 4)) {
1865 double a, b;
1866 struct page *page;
1867 int pageno, pindex;
1869 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1870 if (ret != 2) {
1871 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1874 lock ("page");
1875 a = now ();
1876 page = loadpage (pageno, pindex);
1877 b = now ();
1878 unlock ("page");
1880 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1882 else if (!strncmp ("tile", p, 4)) {
1883 int x, y, w, h;
1884 struct page *page;
1885 struct tile *tile;
1886 double a, b;
1887 void *data;
1889 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1890 SCN_ptr_cast (&page), &x, &y, &w, &h,
1891 SCN_ptr_cast (&data));
1892 if (ret != 6) {
1893 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1896 lock ("tile");
1897 a = now ();
1898 tile = rendertile (page, x, y, w, h, data);
1899 b = now ();
1900 unlock ("tile");
1902 printd ("tile %d %d %" FMT_ptr " %u %f",
1903 x, y,
1904 FMT_ptr_cast (tile),
1905 tile->w * tile->h * tile->pixmap->n,
1906 b - a);
1908 else if (!strncmp ("trimset", p, 7)) {
1909 fz_irect fuzz;
1910 int trimmargins;
1912 ret = sscanf (p + 7, " %d %d %d %d %d",
1913 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1914 if (ret != 5) {
1915 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1917 lock ("trimset");
1918 state.trimmargins = trimmargins;
1919 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1920 state.trimanew = 1;
1921 state.trimfuzz = fuzz;
1923 unlock ("trimset");
1925 else if (!strncmp ("settrim", p, 7)) {
1926 fz_irect fuzz;
1927 int trimmargins;
1929 ret = sscanf (p + 7, " %d %d %d %d %d",
1930 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1931 if (ret != 5) {
1932 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1934 printd ("clear");
1935 lock ("settrim");
1936 state.trimmargins = trimmargins;
1937 state.needoutline = 1;
1938 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1939 state.trimanew = 1;
1940 state.trimfuzz = fuzz;
1942 state.pagedimcount = 0;
1943 free (state.pagedims);
1944 state.pagedims = NULL;
1945 initpdims (0);
1946 layout ();
1947 process_outline ();
1948 unlock ("settrim");
1949 printd ("continue %d", state.pagecount);
1951 else if (!strncmp ("sliceh", p, 6)) {
1952 int h;
1954 ret = sscanf (p + 6, " %d", &h);
1955 if (ret != 1) {
1956 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1958 if (h != state.sliceheight) {
1959 int i;
1961 state.sliceheight = h;
1962 for (i = 0; i < state.texcount; ++i) {
1963 state.texowners[i].w = -1;
1964 state.texowners[i].h = -1;
1965 state.texowners[i].slice = NULL;
1969 else if (!strncmp ("interrupt", p, 9)) {
1970 printd ("vmsg interrupted");
1972 else if (!strncmp ("pgoto", p, 5)) {
1973 printd ("pgoto %s", p + 6);
1975 else {
1976 errx (1, "unknown command %.*s", len, p);
1979 return 0;
1982 CAMLprim value ml_realloctexts (value texcount_v)
1984 CAMLparam1 (texcount_v);
1985 int ok;
1987 if (trylock (__func__)) {
1988 ok = 0;
1989 goto done;
1991 realloctexts (Int_val (texcount_v));
1992 ok = 1;
1993 unlock (__func__);
1995 done:
1996 CAMLreturn (Val_bool (ok));
1999 static void recti (int x0, int y0, int x1, int y1)
2001 GLfloat *v = state.vertices;
2003 glVertexPointer (2, GL_FLOAT, 0, v);
2004 v[0] = x0; v[1] = y0;
2005 v[2] = x1; v[3] = y0;
2006 v[4] = x0; v[5] = y1;
2007 v[6] = x1; v[7] = y1;
2008 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2011 static void showsel (struct page *page, int ox, int oy)
2013 int seen = 0;
2014 fz_irect bbox;
2015 fz_rect rect;
2016 fz_text_line *line;
2017 fz_page_block *pageb;
2018 fz_text_block *block;
2019 struct mark first, last;
2020 unsigned char selcolor[] = {15,15,15,140};
2022 first = page->fmark;
2023 last = page->lmark;
2025 if (!first.span || !last.span) return;
2027 glEnable (GL_BLEND);
2028 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2029 glColor4ubv (selcolor);
2031 ox += state.pagedims[page->pdimno].bounds.x0;
2032 oy += state.pagedims[page->pdimno].bounds.y0;
2033 for (pageb = page->text->blocks;
2034 pageb < page->text->blocks + page->text->len;
2035 ++pageb) {
2036 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2037 block = pageb->u.text;
2039 for (line = block->lines;
2040 line < block->lines + block->len;
2041 ++line) {
2042 fz_text_span *span;
2043 rect = fz_empty_rect;
2045 for (span = line->first_span; span; span = span->next) {
2046 int i, j, k;
2047 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2049 j = 0;
2050 k = span->len - 1;
2052 if (span == page->fmark.span && span == page->lmark.span) {
2053 seen = 1;
2054 j = MIN (first.i, last.i);
2055 k = MAX (first.i, last.i);
2057 else {
2058 if (span == first.span) {
2059 seen = 1;
2060 j = first.i;
2062 else if (span == last.span) {
2063 seen = 1;
2064 k = last.i;
2068 if (seen) {
2069 for (i = j; i <= k; ++i) {
2070 fz_rect bbox1;
2071 fz_union_rect (&rect,
2072 fz_text_char_bbox (state.ctx, &bbox1,
2073 span, i));
2075 fz_round_rect (&bbox, &rect);
2076 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2077 bbox.x0,
2078 bbox.y0,
2079 bbox.x1,
2080 bbox.y1,
2081 oy, ox);
2083 recti (bbox.x0 + ox, bbox.y0 + oy,
2084 bbox.x1 + ox, bbox.y1 + oy);
2085 if (span == last.span) {
2086 goto done;
2088 rect = fz_empty_rect;
2093 done:
2094 glDisable (GL_BLEND);
2097 #include "glfont.c"
2099 static void stipplerect (fz_matrix *m,
2100 fz_point *p1,
2101 fz_point *p2,
2102 fz_point *p3,
2103 fz_point *p4,
2104 GLfloat *texcoords,
2105 GLfloat *vertices)
2107 fz_transform_point (p1, m);
2108 fz_transform_point (p2, m);
2109 fz_transform_point (p3, m);
2110 fz_transform_point (p4, m);
2112 float w, h, s, t;
2114 w = p2->x - p1->x;
2115 h = p2->y - p1->y;
2116 t = sqrtf (w*w + h*h) * .25f;
2118 w = p3->x - p2->x;
2119 h = p3->y - p2->y;
2120 s = sqrtf (w*w + h*h) * .25f;
2122 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2123 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2125 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2126 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2128 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2129 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2131 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2132 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2134 glDrawArrays (GL_LINES, 0, 8);
2137 static void solidrect (fz_matrix *m,
2138 fz_point *p1,
2139 fz_point *p2,
2140 fz_point *p3,
2141 fz_point *p4,
2142 GLfloat *vertices)
2144 fz_transform_point (p1, m);
2145 fz_transform_point (p2, m);
2146 fz_transform_point (p3, m);
2147 fz_transform_point (p4, m);
2148 vertices[0] = p1->x; vertices[1] = p1->y;
2149 vertices[2] = p2->x; vertices[3] = p2->y;
2151 vertices[4] = p3->x; vertices[5] = p3->y;
2152 vertices[6] = p4->x; vertices[7] = p4->y;
2153 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2156 static void highlightlinks (struct page *page, int xoff, int yoff)
2158 int i;
2159 fz_matrix ctm, tm, pm;
2160 fz_link *link, *links;
2161 GLfloat *texcoords = state.texcoords;
2162 GLfloat *vertices = state.vertices;
2164 links = fz_load_links (state.ctx, page->fzpage);
2166 glEnable (GL_TEXTURE_1D);
2167 glEnable (GL_BLEND);
2168 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2169 glBindTexture (GL_TEXTURE_1D, state.stid);
2171 xoff -= state.pagedims[page->pdimno].bounds.x0;
2172 yoff -= state.pagedims[page->pdimno].bounds.y0;
2173 fz_translate (&tm, xoff, yoff);
2174 pm = pagectm (page);
2175 fz_concat (&ctm, &pm, &tm);
2177 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2178 glVertexPointer (2, GL_FLOAT, 0, vertices);
2180 for (link = links; link; link = link->next) {
2181 fz_point p1, p2, p3, p4;
2183 p1.x = link->rect.x0;
2184 p1.y = link->rect.y0;
2186 p2.x = link->rect.x1;
2187 p2.y = link->rect.y0;
2189 p3.x = link->rect.x1;
2190 p3.y = link->rect.y1;
2192 p4.x = link->rect.x0;
2193 p4.y = link->rect.y1;
2195 switch (link->dest.kind) {
2196 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2197 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2198 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2199 default: glColor3ub (0, 0, 0); break;
2201 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2204 for (i = 0; i < page->annotcount; ++i) {
2205 fz_point p1, p2, p3, p4;
2206 struct annot *annot = &page->annots[i];
2208 p1.x = annot->bbox.x0;
2209 p1.y = annot->bbox.y0;
2211 p2.x = annot->bbox.x1;
2212 p2.y = annot->bbox.y0;
2214 p3.x = annot->bbox.x1;
2215 p3.y = annot->bbox.y1;
2217 p4.x = annot->bbox.x0;
2218 p4.y = annot->bbox.y1;
2220 glColor3ub (0, 0, 128);
2221 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2224 glDisable (GL_BLEND);
2225 glDisable (GL_TEXTURE_1D);
2228 static int compareslinks (const void *l, const void *r)
2230 struct slink const *ls = l;
2231 struct slink const *rs = r;
2232 if (ls->bbox.y0 == rs->bbox.y0) {
2233 return rs->bbox.x0 - rs->bbox.x0;
2235 return ls->bbox.y0 - rs->bbox.y0;
2238 static void droptext (struct page *page)
2240 if (page->text) {
2241 fz_drop_text_page (state.ctx, page->text);
2242 page->fmark.i = -1;
2243 page->lmark.i = -1;
2244 page->fmark.span = NULL;
2245 page->lmark.span = NULL;
2246 page->text = NULL;
2248 if (page->sheet) {
2249 fz_drop_text_sheet (state.ctx, page->sheet);
2250 page->sheet = NULL;
2254 static void dropannots (struct page *page)
2256 if (page->annots) {
2257 free (page->annots);
2258 page->annots = NULL;
2259 page->annotcount = 0;
2263 static void ensureannots (struct page *page)
2265 int i, count = 0;
2266 size_t annotsize = sizeof (*page->annots);
2267 fz_annot *annot;
2269 if (state.gen != page->agen) {
2270 dropannots (page);
2271 page->agen = state.gen;
2273 if (page->annots) return;
2275 for (annot = fz_first_annot (state.ctx, page->fzpage);
2276 annot;
2277 annot = fz_next_annot (state.ctx, page->fzpage, annot)) {
2278 count++;
2281 if (count > 0) {
2282 page->annotcount = count;
2283 page->annots = calloc (count, annotsize);
2284 if (!page->annots) {
2285 err (1, "calloc annots %d", count);
2288 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2289 annot;
2290 annot = fz_next_annot (state.ctx, page->fzpage, annot), i++) {
2291 fz_rect rect;
2293 fz_bound_annot (state.ctx, page->fzpage, annot, &rect);
2294 page->annots[i].annot = annot;
2295 fz_round_rect (&page->annots[i].bbox, &rect);
2300 static void dropslinks (struct page *page)
2302 if (page->slinks) {
2303 free (page->slinks);
2304 page->slinks = NULL;
2305 page->slinkcount = 0;
2309 static void ensureslinks (struct page *page)
2311 fz_matrix ctm;
2312 int i, count;
2313 size_t slinksize = sizeof (*page->slinks);
2314 fz_link *link, *links;
2316 ensureannots (page);
2317 if (state.gen != page->sgen) {
2318 dropslinks (page);
2319 page->sgen = state.gen;
2321 if (page->slinks) return;
2323 links = fz_load_links (state.ctx, page->fzpage);
2324 ctm = state.pagedims[page->pdimno].ctm;
2326 count = page->annotcount;
2327 for (link = links; link; link = link->next) {
2328 count++;
2330 if (count > 0) {
2331 int j;
2333 page->slinkcount = count;
2334 page->slinks = calloc (count, slinksize);
2335 if (!page->slinks) {
2336 err (1, "calloc slinks %d", count);
2339 for (i = 0, link = links; link; ++i, link = link->next) {
2340 fz_rect rect;
2342 rect = link->rect;
2343 fz_transform_rect (&rect, &ctm);
2344 page->slinks[i].tag = SLINK;
2345 page->slinks[i].u.link = link;
2346 fz_round_rect (&page->slinks[i].bbox, &rect);
2348 for (j = 0; j < page->annotcount; ++j, ++i) {
2349 fz_rect rect;
2350 fz_bound_annot (state.ctx,
2351 page->fzpage,
2352 page->annots[j].annot,
2353 &rect);
2354 fz_transform_rect (&rect, &ctm);
2355 fz_round_rect (&page->slinks[i].bbox, &rect);
2357 page->slinks[i].tag = SANNOT;
2358 page->slinks[i].u.annot = page->annots[j].annot;
2360 qsort (page->slinks, count, slinksize, compareslinks);
2364 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2365 static void fmt_linkn (char *s, unsigned int u)
2367 unsigned int len; unsigned int q;
2368 unsigned int zma = 'z' - 'a' + 1;
2369 len = 1; q = u;
2370 while (q > zma - 1) { ++len; q /= zma; }
2371 if (s) {
2372 s += len;
2373 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2374 /* handles u == 0 */
2376 s[len] = 0;
2379 static void highlightslinks (struct page *page, int xoff, int yoff,
2380 int noff, char *targ, int tlen, int hfsize)
2382 int i;
2383 char buf[40];
2384 struct slink *slink;
2385 double x0, y0, x1, y1, w;
2387 ensureslinks (page);
2388 glColor3ub (0xc3, 0xb0, 0x91);
2389 for (i = 0; i < page->slinkcount; ++i) {
2390 fmt_linkn (buf, i + noff);
2391 if (!tlen || !strncmp (targ, buf, tlen)) {
2392 slink = &page->slinks[i];
2394 x0 = slink->bbox.x0 + xoff - 5;
2395 y1 = slink->bbox.y0 + yoff - 5;
2396 y0 = y1 + 10 + hfsize;
2397 w = measure_string (state.face, hfsize, buf);
2398 x1 = x0 + w + 10;
2399 recti (x0, y0, x1, y1);
2403 glEnable (GL_BLEND);
2404 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2405 glEnable (GL_TEXTURE_2D);
2406 glColor3ub (0, 0, 0);
2407 for (i = 0; i < page->slinkcount; ++i) {
2408 fmt_linkn (buf, i + noff);
2409 if (!tlen || !strncmp (targ, buf, tlen)) {
2410 slink = &page->slinks[i];
2412 x0 = slink->bbox.x0 + xoff;
2413 y0 = slink->bbox.y0 + yoff + hfsize;
2414 draw_string (state.face, hfsize, x0, y0, buf);
2417 glDisable (GL_TEXTURE_2D);
2418 glDisable (GL_BLEND);
2421 static void uploadslice (struct tile *tile, struct slice *slice)
2423 int offset;
2424 struct slice *slice1;
2425 unsigned char *texdata;
2427 offset = 0;
2428 for (slice1 = tile->slices; slice != slice1; slice1++) {
2429 offset += slice1->h * tile->w * tile->pixmap->n;
2431 if (slice->texindex != -1 && slice->texindex < state.texcount
2432 && state.texowners[slice->texindex].slice == slice) {
2433 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[slice->texindex]);
2435 else {
2436 int subimage = 0;
2437 int texindex = state.texindex++ % state.texcount;
2439 if (state.texowners[texindex].w == tile->w) {
2440 if (state.texowners[texindex].h >= slice->h) {
2441 subimage = 1;
2443 else {
2444 state.texowners[texindex].h = slice->h;
2447 else {
2448 state.texowners[texindex].h = slice->h;
2451 state.texowners[texindex].w = tile->w;
2452 state.texowners[texindex].slice = slice;
2453 slice->texindex = texindex;
2455 glBindTexture (GL_TEXTURE_RECTANGLE_ARB, state.texids[texindex]);
2456 if (tile->pbo) {
2457 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2458 texdata = 0;
2460 else {
2461 texdata = tile->pixmap->samples;
2463 if (subimage) {
2464 glTexSubImage2D (GL_TEXTURE_RECTANGLE_ARB,
2468 tile->w,
2469 slice->h,
2470 state.texform,
2471 state.texty,
2472 texdata+offset
2475 else {
2476 glTexImage2D (GL_TEXTURE_RECTANGLE_ARB,
2478 state.texiform,
2479 tile->w,
2480 slice->h,
2482 state.texform,
2483 state.texty,
2484 texdata+offset
2487 if (tile->pbo) {
2488 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2493 CAMLprim value ml_begintiles (value unit_v)
2495 CAMLparam1 (unit_v);
2496 glEnable (GL_TEXTURE_RECTANGLE_ARB);
2497 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2498 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2499 CAMLreturn (unit_v);
2502 CAMLprim value ml_endtiles (value unit_v)
2504 CAMLparam1 (unit_v);
2505 glDisable (GL_TEXTURE_RECTANGLE_ARB);
2506 CAMLreturn (unit_v);
2509 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2511 CAMLparam2 (args_v, ptr_v);
2512 int dispx = Int_val (Field (args_v, 0));
2513 int dispy = Int_val (Field (args_v, 1));
2514 int dispw = Int_val (Field (args_v, 2));
2515 int disph = Int_val (Field (args_v, 3));
2516 int tilex = Int_val (Field (args_v, 4));
2517 int tiley = Int_val (Field (args_v, 5));
2518 char *s = String_val (ptr_v);
2519 struct tile *tile = parse_pointer (__func__, s);
2520 int slicey, firstslice;
2521 struct slice *slice;
2522 GLfloat *texcoords = state.texcoords;
2523 GLfloat *vertices = state.vertices;
2525 firstslice = tiley / tile->sliceheight;
2526 slice = &tile->slices[firstslice];
2527 slicey = tiley % tile->sliceheight;
2529 while (disph > 0) {
2530 int dh;
2532 dh = slice->h - slicey;
2533 dh = MIN (disph, dh);
2534 uploadslice (tile, slice);
2536 texcoords[0] = tilex; texcoords[1] = slicey;
2537 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2538 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2539 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2541 vertices[0] = dispx; vertices[1] = dispy;
2542 vertices[2] = dispx+dispw; vertices[3] = dispy;
2543 vertices[4] = dispx; vertices[5] = dispy+dh;
2544 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2546 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2547 dispy += dh;
2548 disph -= dh;
2549 slice++;
2550 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2551 slicey = 0;
2553 CAMLreturn (Val_unit);
2556 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2558 fz_matrix ctm, tm, pm;
2559 fz_point p1, p2, p3, p4;
2560 GLfloat *vertices = state.vertices;
2561 double *v = (double *) rects_v;
2563 xoff -= state.pagedims[page->pdimno].bounds.x0;
2564 yoff -= state.pagedims[page->pdimno].bounds.y0;
2565 fz_translate (&tm, xoff, yoff);
2566 pm = pagectm (page);
2567 fz_concat (&ctm, &pm, &tm);
2569 glEnable (GL_BLEND);
2570 glVertexPointer (2, GL_FLOAT, 0, vertices);
2572 glColor4dv (v);
2573 p1.x = v[4];
2574 p1.y = v[5];
2576 p2.x = v[6];
2577 p2.y = v[5];
2579 p3.x = v[6];
2580 p3.y = v[7];
2582 p4.x = v[4];
2583 p4.y = v[7];
2584 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2585 glDisable (GL_BLEND);
2588 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2589 value xoff_v, value yoff_v,
2590 value li_v)
2592 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2593 int xoff = Int_val (xoff_v);
2594 int yoff = Int_val (yoff_v);
2595 int noff = Int_val (Field (li_v, 0));
2596 char *targ = String_val (Field (li_v, 1));
2597 int tlen = caml_string_length (Field (li_v, 1));
2598 int hfsize = Int_val (Field (li_v, 2));
2599 char *s = String_val (ptr_v);
2600 int hlmask = Int_val (hlinks_v);
2601 struct page *page = parse_pointer (__func__, s);
2603 if (!page->fzpage) {
2604 /* deal with loadpage failed pages */
2605 goto done;
2608 ensureannots (page);
2610 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2611 if (trylock (__func__)) {
2612 noff = 0;
2613 goto done;
2615 if (hlmask & 2) {
2616 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2617 noff = page->slinkcount;
2619 if (page->tgen == state.gen) {
2620 showsel (page, xoff, yoff);
2622 unlock (__func__);
2624 done:
2625 CAMLreturn (Val_int (noff));
2628 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2629 value rects_v)
2631 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2632 int xoff = Int_val (xoff_v);
2633 int yoff = Int_val (yoff_v);
2634 char *s = String_val (ptr_v);
2635 struct page *page = parse_pointer (__func__, s);
2637 drawprect (page, xoff, yoff, rects_v);
2638 CAMLreturn (Val_unit);
2641 static struct annot *getannot (struct page *page, int x, int y)
2643 int i;
2644 fz_point p;
2645 fz_matrix ctm;
2646 const fz_matrix *tctm;
2647 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2649 if (!page->annots) return NULL;
2651 if (pdf) {
2652 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2653 tctm = &state.pagedims[page->pdimno].tctm;
2655 else {
2656 tctm = &fz_identity;
2659 p.x = x;
2660 p.y = y;
2662 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2663 fz_invert_matrix (&ctm, &ctm);
2664 fz_transform_point (&p, &ctm);
2666 if (pdf) {
2667 for (i = 0; i < page->annotcount; ++i) {
2668 struct annot *a = &page->annots[i];
2669 pdf_annot *annot = (pdf_annot *) a->annot;
2670 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2671 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2672 return a;
2677 return NULL;
2680 static fz_link *getlink (struct page *page, int x, int y)
2682 fz_point p;
2683 fz_matrix ctm;
2684 const fz_matrix *tctm;
2685 fz_link *link, *links;
2687 tctm = &fz_identity;
2688 links = fz_load_links (state.ctx, page->fzpage);
2690 p.x = x;
2691 p.y = y;
2693 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2694 fz_invert_matrix (&ctm, &ctm);
2695 fz_transform_point (&p, &ctm);
2697 for (link = links; link; link = link->next) {
2698 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2699 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2700 return link;
2704 return NULL;
2707 static void ensuretext (struct page *page)
2709 if (state.gen != page->tgen) {
2710 droptext (page);
2711 page->tgen = state.gen;
2713 if (!page->text) {
2714 fz_matrix ctm;
2715 fz_device *tdev;
2717 page->text = fz_new_text_page (state.ctx);
2718 page->sheet = fz_new_text_sheet (state.ctx);
2719 tdev = fz_new_text_device (state.ctx, page->sheet, page->text);
2720 ctm = pagectm (page);
2721 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2722 fz_run_display_list (state.ctx, page->dlist,
2723 tdev, &ctm, &fz_infinite_rect, NULL);
2724 qsort (page->text->blocks, page->text->len,
2725 sizeof (*page->text->blocks), compareblocks);
2726 fz_end_page (state.ctx, tdev);
2727 fz_drop_device (state.ctx, tdev);
2731 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2733 CAMLparam2 (start_page_v, dir_v);
2734 CAMLlocal1 (ret_v);
2735 int i, dir = Int_val (dir_v);
2736 int start_page = Int_val (start_page_v);
2737 int end_page = dir > 0 ? state.pagecount : -1;
2738 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2740 fz_var (end_page);
2741 ret_v = Val_int (0);
2742 lock (__func__);
2743 for (i = start_page + dir; i != end_page; i += dir) {
2744 int found;
2746 fz_var (found);
2747 if (pdf) {
2748 pdf_page *page = NULL;
2750 fz_try (state.ctx) {
2751 page = pdf_load_page (state.ctx, pdf, i);
2752 found = !!page->links || !!page->annots;
2754 fz_catch (state.ctx) {
2755 found = 0;
2757 if (page) {
2758 fz_drop_page (state.ctx, &page->super);
2761 else {
2762 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2763 found = !!fz_load_links (state.ctx, page);
2764 fz_drop_page (state.ctx, page);
2767 if (found) {
2768 ret_v = caml_alloc_small (1, 1);
2769 Field (ret_v, 0) = Val_int (i);
2770 goto unlock;
2773 unlock:
2774 unlock (__func__);
2775 CAMLreturn (ret_v);
2778 enum { dir_first, dir_last };
2779 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2781 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2783 CAMLparam2 (ptr_v, dir_v);
2784 CAMLlocal2 (ret_v, pos_v);
2785 struct page *page;
2786 int dirtag, i, slinkindex;
2787 struct slink *found = NULL ,*slink;
2788 char *s = String_val (ptr_v);
2790 page = parse_pointer (__func__, s);
2791 ret_v = Val_int (0);
2792 /* This is scary we are not taking locks here ensureslinks does
2793 not modify state and given that we obtained the page it can not
2794 disappear under us either */
2795 lock (__func__);
2796 ensureslinks (page);
2798 if (Is_block (dir_v)) {
2799 dirtag = Tag_val (dir_v);
2800 switch (dirtag) {
2801 case dir_first_visible:
2803 int x0, y0, dir, first_index, last_index;
2805 pos_v = Field (dir_v, 0);
2806 x0 = Int_val (Field (pos_v, 0));
2807 y0 = Int_val (Field (pos_v, 1));
2808 dir = Int_val (Field (pos_v, 2));
2810 if (dir >= 0) {
2811 dir = 1;
2812 first_index = 0;
2813 last_index = page->slinkcount;
2815 else {
2816 first_index = page->slinkcount - 1;
2817 last_index = -1;
2820 for (i = first_index; i != last_index; i += dir) {
2821 slink = &page->slinks[i];
2822 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2823 found = slink;
2824 break;
2828 break;
2830 case dir_left:
2831 slinkindex = Int_val (Field (dir_v, 0));
2832 found = &page->slinks[slinkindex];
2833 for (i = slinkindex - 1; i >= 0; --i) {
2834 slink = &page->slinks[i];
2835 if (slink->bbox.x0 < found->bbox.x0) {
2836 found = slink;
2837 break;
2840 break;
2842 case dir_right:
2843 slinkindex = Int_val (Field (dir_v, 0));
2844 found = &page->slinks[slinkindex];
2845 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2846 slink = &page->slinks[i];
2847 if (slink->bbox.x0 > found->bbox.x0) {
2848 found = slink;
2849 break;
2852 break;
2854 case dir_down:
2855 slinkindex = Int_val (Field (dir_v, 0));
2856 found = &page->slinks[slinkindex];
2857 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2858 slink = &page->slinks[i];
2859 if (slink->bbox.y0 >= found->bbox.y0) {
2860 found = slink;
2861 break;
2864 break;
2866 case dir_up:
2867 slinkindex = Int_val (Field (dir_v, 0));
2868 found = &page->slinks[slinkindex];
2869 for (i = slinkindex - 1; i >= 0; --i) {
2870 slink = &page->slinks[i];
2871 if (slink->bbox.y0 <= found->bbox.y0) {
2872 found = slink;
2873 break;
2876 break;
2879 else {
2880 dirtag = Int_val (dir_v);
2881 switch (dirtag) {
2882 case dir_first:
2883 found = page->slinks;
2884 break;
2886 case dir_last:
2887 if (page->slinks) {
2888 found = page->slinks + (page->slinkcount - 1);
2890 break;
2893 if (found) {
2894 ret_v = caml_alloc_small (2, 1);
2895 Field (ret_v, 0) = Val_int (found - page->slinks);
2898 unlock (__func__);
2899 CAMLreturn (ret_v);
2902 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2903 unamed, uremote, uremotedest, uannot };
2905 #define LINKTOVAL \
2907 int pageno; \
2909 switch (link->dest.kind) { \
2910 case FZ_LINK_GOTO: \
2912 fz_point p; \
2914 pageno = link->dest.ld.gotor.page; \
2915 p.x = 0; \
2916 p.y = 0; \
2918 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2919 p.y = link->dest.ld.gotor.lt.y; \
2920 fz_transform_point (&p, &pdim->lctm); \
2921 if (p.y < 0) p.y = 0; \
2923 tup_v = caml_alloc_tuple (2); \
2924 ret_v = caml_alloc_small (1, ugoto); \
2925 Field (tup_v, 0) = Val_int (pageno); \
2926 Field (tup_v, 1) = Val_int (p.y); \
2927 Field (ret_v, 0) = tup_v; \
2929 break; \
2931 case FZ_LINK_URI: \
2932 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2933 ret_v = caml_alloc_small (1, uuri); \
2934 Field (ret_v, 0) = str_v; \
2935 break; \
2937 case FZ_LINK_LAUNCH: \
2938 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2939 ret_v = caml_alloc_small (1, ulaunch); \
2940 Field (ret_v, 0) = str_v; \
2941 break; \
2943 case FZ_LINK_NAMED: \
2944 str_v = caml_copy_string (link->dest.ld.named.named); \
2945 ret_v = caml_alloc_small (1, unamed); \
2946 Field (ret_v, 0) = str_v; \
2947 break; \
2949 case FZ_LINK_GOTOR: \
2951 int rty; \
2953 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2954 pageno = link->dest.ld.gotor.page; \
2955 if (pageno == -1) { \
2956 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2957 rty = uremotedest; \
2959 else { \
2960 gr_v = Val_int (pageno); \
2961 rty = uremote; \
2963 tup_v = caml_alloc_tuple (2); \
2964 ret_v = caml_alloc_small (1, rty); \
2965 Field (tup_v, 0) = str_v; \
2966 Field (tup_v, 1) = gr_v; \
2967 Field (ret_v, 0) = tup_v; \
2969 break; \
2971 default: \
2973 char buf[80]; \
2975 snprintf (buf, sizeof (buf), \
2976 "unhandled link kind %d", link->dest.kind); \
2977 str_v = caml_copy_string (buf); \
2978 ret_v = caml_alloc_small (1, uunexpected); \
2979 Field (ret_v, 0) = str_v; \
2981 break; \
2985 CAMLprim value ml_getlink (value ptr_v, value n_v)
2987 CAMLparam2 (ptr_v, n_v);
2988 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2989 fz_link *link;
2990 struct page *page;
2991 struct pagedim *pdim;
2992 char *s = String_val (ptr_v);
2993 struct slink *slink;
2995 /* See ml_findlink for caveat */
2997 ret_v = Val_int (0);
2998 page = parse_pointer (__func__, s);
2999 ensureslinks (page);
3000 pdim = &state.pagedims[page->pdimno];
3001 slink = &page->slinks[Int_val (n_v)];
3002 if (slink->tag == SLINK) {
3003 link = slink->u.link;
3004 LINKTOVAL;
3006 else {
3007 ret_v = caml_alloc_small (1, uannot);
3008 tup_v = caml_alloc_tuple (2);
3009 Field (ret_v, 0) = tup_v;
3010 Field (tup_v, 0) = ptr_v;
3011 Field (tup_v, 1) = n_v;
3014 CAMLreturn (ret_v);
3017 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3019 CAMLparam2 (ptr_v, n_v);
3020 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3021 if (pdf) {
3022 char *s = String_val (ptr_v);
3023 struct page *page;
3024 struct slink *slink;
3026 page = parse_pointer (__func__, s);
3027 slink = &page->slinks[Int_val (n_v)];
3028 CAMLreturn (caml_copy_string (
3029 pdf_annot_contents (state.ctx, pdf,
3030 (pdf_annot *) slink->u.annot)));
3032 else {
3033 CAMLreturn (caml_copy_string (""));
3037 CAMLprim value ml_getlinkcount (value ptr_v)
3039 CAMLparam1 (ptr_v);
3040 struct page *page;
3041 char *s = String_val (ptr_v);
3043 page = parse_pointer (__func__, s);
3044 CAMLreturn (Val_int (page->slinkcount));
3047 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3049 CAMLparam2 (ptr_v, n_v);
3050 CAMLlocal1 (ret_v);
3051 struct page *page;
3052 struct slink *slink;
3053 char *s = String_val (ptr_v);
3054 /* See ml_findlink for caveat */
3056 page = parse_pointer (__func__, s);
3057 ret_v = caml_alloc_tuple (4);
3058 ensureslinks (page);
3060 slink = &page->slinks[Int_val (n_v)];
3061 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3062 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3063 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3064 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3065 unlock ("ml_getlinkrect");
3066 CAMLreturn (ret_v);
3069 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3071 CAMLparam3 (ptr_v, x_v, y_v);
3072 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3073 fz_link *link;
3074 struct annot *annot;
3075 struct page *page;
3076 char *ptr = String_val (ptr_v);
3077 int x = Int_val (x_v), y = Int_val (y_v);
3078 struct pagedim *pdim;
3080 ret_v = Val_int (0);
3081 if (trylock (__func__)) {
3082 goto done;
3085 page = parse_pointer (__func__, ptr);
3086 pdim = &state.pagedims[page->pdimno];
3087 x += pdim->bounds.x0;
3088 y += pdim->bounds.y0;
3091 annot = getannot (page, x, y);
3092 if (annot) {
3093 int i, n = -1;
3095 ensureslinks (page);
3096 for (i = 0; i < page->slinkcount; ++i) {
3097 if (page->slinks[i].tag == SANNOT
3098 && page->slinks[i].u.annot == annot->annot) {
3099 n = i;
3100 break;
3103 ret_v = caml_alloc_small (1, uannot);
3104 tup_v = caml_alloc_tuple (2);
3105 Field (ret_v, 0) = tup_v;
3106 Field (tup_v, 0) = ptr_v;
3107 Field (tup_v, 1) = Val_int (n);
3108 goto unlock;
3112 link = getlink (page, x, y);
3113 if (link) {
3114 LINKTOVAL;
3116 else {
3117 fz_rect *b;
3118 fz_page_block *pageb;
3119 fz_text_block *block;
3121 ensuretext (page);
3122 for (pageb = page->text->blocks;
3123 pageb < page->text->blocks + page->text->len;
3124 ++pageb) {
3125 fz_text_line *line;
3126 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3127 block = pageb->u.text;
3129 b = &block->bbox;
3130 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3131 continue;
3133 for (line = block->lines;
3134 line < block->lines + block->len;
3135 ++line) {
3136 fz_text_span *span;
3138 b = &line->bbox;
3139 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3140 continue;
3142 for (span = line->first_span; span; span = span->next) {
3143 int charnum;
3145 b = &span->bbox;
3146 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3147 continue;
3149 for (charnum = 0; charnum < span->len; ++charnum) {
3150 fz_rect bbox;
3151 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3152 b = &bbox;
3154 if (x >= b->x0 && x <= b->x1
3155 && y >= b->y0 && y <= b->y1) {
3156 fz_text_style *style = span->text->style;
3157 const char *n2 =
3158 style->font
3159 ? style->font->name
3160 : "Span has no font name"
3162 FT_FaceRec *face = style->font->ft_face;
3163 if (face && face->family_name) {
3164 char *s;
3165 char *n1 = face->family_name;
3166 size_t l1 = strlen (n1);
3167 size_t l2 = strlen (n2);
3169 if (l1 != l2 || memcmp (n1, n2, l1)) {
3170 s = malloc (l1 + l2 + 2);
3171 if (s) {
3172 memcpy (s, n2, l2);
3173 s[l2] = '=';
3174 memcpy (s + l2 + 1, n1, l1 + 1);
3175 str_v = caml_copy_string (s);
3176 free (s);
3180 if (str_v == Val_unit) {
3181 str_v = caml_copy_string (n2);
3183 ret_v = caml_alloc_small (1, utext);
3184 Field (ret_v, 0) = str_v;
3185 goto unlock;
3192 unlock:
3193 unlock (__func__);
3195 done:
3196 CAMLreturn (ret_v);
3199 enum { mark_page, mark_block, mark_line, mark_word };
3201 static int uninteresting (int c)
3203 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3204 || ispunct (c);
3207 CAMLprim value ml_clearmark (value ptr_v)
3209 CAMLparam1 (ptr_v);
3210 char *s = String_val (ptr_v);
3211 struct page *page;
3213 if (trylock (__func__)) {
3214 goto done;
3217 page = parse_pointer (__func__, s);
3218 page->fmark.span = NULL;
3219 page->lmark.span = NULL;
3220 page->fmark.i = 0;
3221 page->lmark.i = 0;
3223 unlock (__func__);
3224 done:
3225 CAMLreturn (Val_unit);
3228 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3230 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3231 CAMLlocal1 (ret_v);
3232 fz_rect *b;
3233 struct page *page;
3234 fz_text_line *line;
3235 fz_page_block *pageb;
3236 fz_text_block *block;
3237 struct pagedim *pdim;
3238 int mark = Int_val (mark_v);
3239 char *s = String_val (ptr_v);
3240 int x = Int_val (x_v), y = Int_val (y_v);
3242 ret_v = Val_bool (0);
3243 if (trylock (__func__)) {
3244 goto done;
3247 page = parse_pointer (__func__, s);
3248 pdim = &state.pagedims[page->pdimno];
3250 ensuretext (page);
3252 if (mark == mark_page) {
3253 int i;
3254 fz_page_block *pb1 = NULL, *pb2 = NULL;
3256 for (i = 0; i < page->text->len; ++i) {
3257 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3258 pb1 = &page->text->blocks[i];
3259 break;
3262 if (!pb1) goto unlock;
3264 for (i = page->text->len - 1; i >= 0; --i) {
3265 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3266 pb2 = &page->text->blocks[i];
3267 break;
3270 if (!pb2) goto unlock;
3272 block = pb1->u.text;
3274 page->fmark.i = 0;
3275 page->fmark.span = block->lines->first_span;
3277 block = pb2->u.text;
3278 line = &block->lines[block->len - 1];
3279 page->lmark.i = line->last_span->len - 1;
3280 page->lmark.span = line->last_span;
3281 ret_v = Val_bool (1);
3282 goto unlock;
3285 x += pdim->bounds.x0;
3286 y += pdim->bounds.y0;
3288 for (pageb = page->text->blocks;
3289 pageb < page->text->blocks + page->text->len;
3290 ++pageb) {
3291 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3292 block = pageb->u.text;
3294 b = &block->bbox;
3295 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3296 continue;
3298 if (mark == mark_block) {
3299 page->fmark.i = 0;
3300 page->fmark.span = block->lines->first_span;
3302 line = &block->lines[block->len - 1];
3303 page->lmark.i = line->last_span->len - 1;
3304 page->lmark.span = line->last_span;
3305 ret_v = Val_bool (1);
3306 goto unlock;
3309 for (line = block->lines;
3310 line < block->lines + block->len;
3311 ++line) {
3312 fz_text_span *span;
3314 b = &line->bbox;
3315 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3316 continue;
3318 if (mark == mark_line) {
3319 page->fmark.i = 0;
3320 page->fmark.span = line->first_span;
3322 page->lmark.i = line->last_span->len - 1;
3323 page->lmark.span = line->last_span;
3324 ret_v = Val_bool (1);
3325 goto unlock;
3328 for (span = line->first_span; span; span = span->next) {
3329 int charnum;
3331 b = &span->bbox;
3332 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3333 continue;
3335 for (charnum = 0; charnum < span->len; ++charnum) {
3336 fz_rect bbox;
3337 fz_text_char_bbox (state.ctx, &bbox, span, charnum);
3338 b = &bbox;
3340 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3341 /* unicode ftw */
3342 int charnum2, charnum3 = -1, charnum4 = -1;
3344 if (uninteresting (span->text[charnum].c)) goto unlock;
3346 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3347 if (uninteresting (span->text[charnum2].c)) {
3348 charnum3 = charnum2 + 1;
3349 break;
3352 if (charnum3 == -1) charnum3 = 0;
3354 for (charnum2 = charnum + 1;
3355 charnum2 < span->len;
3356 ++charnum2) {
3357 if (uninteresting (span->text[charnum2].c)) break;
3358 charnum4 = charnum2;
3360 if (charnum4 == -1) goto unlock;
3362 page->fmark.i = charnum3;
3363 page->fmark.span = span;
3365 page->lmark.i = charnum4;
3366 page->lmark.span = span;
3367 ret_v = Val_bool (1);
3368 goto unlock;
3374 unlock:
3375 if (!Bool_val (ret_v)) {
3376 page->fmark.span = NULL;
3377 page->lmark.span = NULL;
3378 page->fmark.i = 0;
3379 page->lmark.i = 0;
3381 unlock (__func__);
3383 done:
3384 CAMLreturn (ret_v);
3387 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3389 CAMLparam3 (ptr_v, x_v, y_v);
3390 CAMLlocal2 (ret_v, res_v);
3391 fz_rect *b = NULL;
3392 struct page *page;
3393 fz_page_block *pageb;
3394 struct pagedim *pdim;
3395 char *s = String_val (ptr_v);
3396 int x = Int_val (x_v), y = Int_val (y_v);
3398 ret_v = Val_int (0);
3399 if (trylock (__func__)) {
3400 goto done;
3403 page = parse_pointer (__func__, s);
3404 pdim = &state.pagedims[page->pdimno];
3405 x += pdim->bounds.x0;
3406 y += pdim->bounds.y0;
3408 ensuretext (page);
3410 for (pageb = page->text->blocks;
3411 pageb < page->text->blocks + page->text->len;
3412 ++pageb) {
3413 switch (pageb->type) {
3414 case FZ_PAGE_BLOCK_TEXT:
3415 b = &pageb->u.text->bbox;
3416 break;
3418 case FZ_PAGE_BLOCK_IMAGE:
3419 b = &pageb->u.image->bbox;
3420 break;
3422 default:
3423 continue;
3426 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3427 break;
3428 b = NULL;
3430 if (b) {
3431 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3432 ret_v = caml_alloc_small (1, 1);
3433 Store_double_field (res_v, 0, b->x0);
3434 Store_double_field (res_v, 1, b->x1);
3435 Store_double_field (res_v, 2, b->y0);
3436 Store_double_field (res_v, 3, b->y1);
3437 Field (ret_v, 0) = res_v;
3439 unlock (__func__);
3441 done:
3442 CAMLreturn (ret_v);
3445 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3447 CAMLparam2 (ptr_v, rect_v);
3448 fz_rect b;
3449 struct page *page;
3450 struct pagedim *pdim;
3451 char *s = String_val (ptr_v);
3452 int i, x0, x1, y0, y1, fi, li;
3453 fz_text_line *line;
3454 fz_page_block *pageb;
3455 fz_text_block *block;
3456 fz_text_span *span, *fspan, *lspan;
3458 if (trylock (__func__)) {
3459 goto done;
3462 page = parse_pointer (__func__, s);
3463 ensuretext (page);
3465 pdim = &state.pagedims[page->pdimno];
3466 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3467 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3468 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3469 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3471 if (y0 > y1) {
3472 int t = y0;
3473 y0 = y1;
3474 y1 = t;
3475 x0 = x1;
3476 x1 = t;
3479 fi = page->fmark.i;
3480 fspan = page->fmark.span;
3482 li = page->lmark.i;
3483 lspan = page->lmark.span;
3485 for (pageb = page->text->blocks;
3486 pageb < page->text->blocks + page->text->len;
3487 ++pageb) {
3488 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3489 block = pageb->u.text;
3490 for (line = block->lines;
3491 line < block->lines + block->len;
3492 ++line) {
3494 for (span = line->first_span; span; span = span->next) {
3495 for (i = 0; i < span->len; ++i) {
3496 fz_text_char_bbox (state.ctx, &b, span, i);
3498 if (x0 >= b.x0 && x0 <= b.x1
3499 && y0 >= b.y0 && y0 <= b.y1) {
3500 fspan = span;
3501 fi = i;
3503 if (x1 >= b.x0 && x1 <= b.x1
3504 && y1 >= b.y0 && y1 <= b.y1) {
3505 lspan = span;
3506 li = i;
3512 if (x1 < x0 && fspan == lspan) {
3513 i = fi;
3514 span = fspan;
3516 fi = li;
3517 fspan = lspan;
3519 li = i;
3520 lspan = span;
3523 page->fmark.i = fi;
3524 page->fmark.span = fspan;
3526 page->lmark.i = li;
3527 page->lmark.span = lspan;
3529 unlock (__func__);
3531 done:
3532 CAMLreturn (Val_unit);
3535 static int UNUSED_ATTR pipespan (FILE *f, fz_text_span *span, int a, int b)
3537 char buf[4];
3538 int i, len, ret;
3540 for (i = a; i <= b; ++i) {
3541 len = fz_runetochar (buf, span->text[i].c);
3542 ret = fwrite (buf, len, 1, f);
3544 if (ret != 1) {
3545 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3546 len, ret, strerror (errno));
3547 return -1;
3550 return 0;
3553 #ifdef __CYGWIN__
3554 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3556 caml_failwith ("ml_popen not implemented under Cygwin");
3558 #else
3559 CAMLprim value ml_spawn (value command_v, value fds_v)
3561 CAMLparam2 (command_v, fds_v);
3562 CAMLlocal2 (l_v, tup_v);
3563 int ret, ret1;
3564 pid_t pid;
3565 char *msg = NULL;
3566 value earg_v = Nothing;
3567 posix_spawnattr_t attr;
3568 posix_spawn_file_actions_t fa;
3569 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3571 argv[2] = String_val (command_v);
3573 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3574 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3577 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3578 msg = "posix_spawnattr_init";
3579 goto fail1;
3582 #ifdef POSIX_SPAWN_USEVFORK
3583 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3584 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3585 goto fail;
3587 #endif
3589 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3590 int fd1, fd2;
3592 tup_v = Field (l_v, 0);
3593 fd1 = Int_val (Field (tup_v, 0));
3594 fd2 = Int_val (Field (tup_v, 1));
3595 if (fd2 < 0) {
3596 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3597 msg = "posix_spawn_file_actions_addclose";
3598 earg_v = tup_v;
3599 goto fail;
3602 else {
3603 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3604 msg = "posix_spawn_file_actions_adddup2";
3605 earg_v = tup_v;
3606 goto fail;
3611 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3612 msg = "posix_spawn";
3613 goto fail;
3616 fail:
3617 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3618 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3621 fail1:
3622 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3623 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3624 strerror (ret1));
3627 if (msg)
3628 unix_error (ret, msg, earg_v);
3630 CAMLreturn (Val_int (pid));
3632 #endif
3634 CAMLprim value ml_hassel (value ptr_v)
3636 CAMLparam1 (ptr_v);
3637 CAMLlocal1 (ret_v);
3638 struct page *page;
3639 char *s = String_val (ptr_v);
3641 ret_v = Val_bool (0);
3642 if (trylock (__func__)) {
3643 goto done;
3646 page = parse_pointer (__func__, s);
3647 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3648 unlock (__func__);
3649 done:
3650 CAMLreturn (ret_v);
3653 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3655 CAMLparam2 (fd_v, ptr_v);
3656 FILE *f;
3657 int seen = 0;
3658 struct page *page;
3659 fz_text_line *line;
3660 fz_page_block *pageb;
3661 fz_text_block *block;
3662 int fd = Int_val (fd_v);
3663 char *s = String_val (ptr_v);
3665 if (trylock (__func__)) {
3666 goto done;
3669 page = parse_pointer (__func__, s);
3671 if (!page->fmark.span || !page->lmark.span) {
3672 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3673 goto unlock;
3676 f = fdopen (fd, "w");
3677 if (!f) {
3678 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3679 fd, strerror (errno));
3680 f = stdout;
3683 for (pageb = page->text->blocks;
3684 pageb < page->text->blocks + page->text->len;
3685 ++pageb) {
3686 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3687 block = pageb->u.text;
3688 for (line = block->lines;
3689 line < block->lines + block->len;
3690 ++line) {
3691 fz_text_span *span;
3693 for (span = line->first_span; span; span = span->next) {
3694 int a, b;
3696 seen |= span == page->fmark.span || span == page->lmark.span;
3697 a = span == page->fmark.span ? page->fmark.i : 0;
3698 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3700 if (seen) {
3701 if (pipespan (f, span, a, b)) {
3702 goto close;
3704 if (span == page->lmark.span) {
3705 goto close;
3707 if (span == line->last_span) {
3708 if (putc ('\n', f) == EOF) {
3709 fprintf (stderr,
3710 "failed break line on sel pipe: %s\n",
3711 strerror (errno));
3712 goto close;
3719 close:
3720 if (f != stdout) {
3721 int ret = fclose (f);
3722 fd = -1;
3723 if (ret == -1) {
3724 if (errno != ECHILD) {
3725 fprintf (stderr, "failed to close sel pipe: %s\n",
3726 strerror (errno));
3730 unlock:
3731 unlock (__func__);
3733 done:
3734 if (fd >= 0) {
3735 if (close (fd)) {
3736 fprintf (stderr, "failed to close sel pipe: %s\n",
3737 strerror (errno));
3740 CAMLreturn (Val_unit);
3743 CAMLprim value ml_getpdimrect (value pagedimno_v)
3745 CAMLparam1 (pagedimno_v);
3746 CAMLlocal1 (ret_v);
3747 int pagedimno = Int_val (pagedimno_v);
3748 fz_rect box;
3750 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3751 if (trylock (__func__)) {
3752 box = fz_empty_rect;
3754 else {
3755 box = state.pagedims[pagedimno].mediabox;
3756 unlock (__func__);
3759 Store_double_field (ret_v, 0, box.x0);
3760 Store_double_field (ret_v, 1, box.x1);
3761 Store_double_field (ret_v, 2, box.y0);
3762 Store_double_field (ret_v, 3, box.y1);
3764 CAMLreturn (ret_v);
3767 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3768 value dw_v, value cols_v)
3770 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3771 CAMLlocal1 (ret_v);
3772 int i;
3773 double zoom = -1.;
3774 double maxh = 0.0;
3775 struct pagedim *p;
3776 double winw = Int_val (winw_v);
3777 double winh = Int_val (winh_v);
3778 double dw = Int_val (dw_v);
3779 double cols = Int_val (cols_v);
3780 double pw = 1.0, ph = 1.0;
3782 if (trylock (__func__)) {
3783 goto done;
3786 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3787 double w = p->pagebox.x1 / cols;
3788 double h = p->pagebox.y1;
3789 if (h > maxh) {
3790 maxh = h;
3791 ph = h;
3792 if (state.fitmodel != FitProportional) pw = w;
3794 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3797 zoom = (((winh / ph) * pw) + dw) / winw;
3798 unlock (__func__);
3799 done:
3800 ret_v = caml_copy_double (zoom);
3801 CAMLreturn (ret_v);
3804 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3806 CAMLparam4 (pt_v, x_v, y_v, string_v);
3807 CAMLlocal1 (ret_v);
3808 int pt = Int_val(pt_v);
3809 int x = Int_val (x_v);
3810 int y = Int_val (y_v);
3811 double w;
3813 w = draw_string (state.face, pt, x, y, String_val (string_v));
3814 ret_v = caml_copy_double (w);
3815 CAMLreturn (ret_v);
3818 CAMLprim value ml_measure_string (value pt_v, value string_v)
3820 CAMLparam2 (pt_v, string_v);
3821 CAMLlocal1 (ret_v);
3822 int pt = Int_val (pt_v);
3823 double w;
3825 w = measure_string (state.face, pt, String_val (string_v));
3826 ret_v = caml_copy_double (w);
3827 CAMLreturn (ret_v);
3830 CAMLprim value ml_getpagebox (value opaque_v)
3832 CAMLparam1 (opaque_v);
3833 CAMLlocal1 (ret_v);
3834 fz_rect rect;
3835 fz_irect bbox;
3836 fz_matrix ctm;
3837 fz_device *dev;
3838 char *s = String_val (opaque_v);
3839 struct page *page = parse_pointer (__func__, s);
3841 ret_v = caml_alloc_tuple (4);
3842 dev = fz_new_bbox_device (state.ctx, &rect);
3843 dev->hints |= FZ_IGNORE_SHADE;
3845 ctm = pagectm (page);
3846 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3848 fz_drop_device (state.ctx, dev);
3849 fz_round_rect (&bbox, &rect);
3850 Field (ret_v, 0) = Val_int (bbox.x0);
3851 Field (ret_v, 1) = Val_int (bbox.y0);
3852 Field (ret_v, 2) = Val_int (bbox.x1);
3853 Field (ret_v, 3) = Val_int (bbox.y1);
3855 CAMLreturn (ret_v);
3858 CAMLprim value ml_setaalevel (value level_v)
3860 CAMLparam1 (level_v);
3862 state.aalevel = Int_val (level_v);
3863 CAMLreturn (Val_unit);
3866 #pragma GCC diagnostic push
3867 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3868 #include <X11/Xlib.h>
3869 #include <X11/cursorfont.h>
3870 #pragma GCC diagnostic pop
3872 #include <GL/glx.h>
3874 static const int shapes[] = {
3875 XC_arrow, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3878 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3880 static struct {
3881 Window wid;
3882 Display *dpy;
3883 GLXContext ctx;
3884 XVisualInfo *visual;
3885 Cursor curs[CURS_COUNT];
3886 } glx;
3888 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3890 CAMLparam3 (display_v, wid_v, screen_v);
3891 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3893 glx.dpy = XOpenDisplay (String_val (display_v));
3894 if (!glx.dpy) {
3895 caml_failwith ("XOpenDisplay");
3898 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3899 if (!glx.visual) {
3900 XCloseDisplay (glx.dpy);
3901 caml_failwith ("glXChooseVisual");
3904 for (size_t n = 0; n < CURS_COUNT; ++n) {
3905 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3908 glx.wid = Int_val (wid_v);
3909 CAMLreturn (Val_int (glx.visual->visualid));
3912 CAMLprim value ml_glxcompleteinit (value unit_v)
3914 CAMLparam1 (unit_v);
3916 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3917 if (!glx.ctx) {
3918 caml_failwith ("glXCreateContext");
3921 XFree (glx.visual);
3922 glx.visual = NULL;
3924 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3925 glXDestroyContext (glx.dpy, glx.ctx);
3926 glx.ctx = NULL;
3927 caml_failwith ("glXMakeCurrent");
3929 CAMLreturn (Val_unit);
3932 CAMLprim value ml_setcursor (value cursor_v)
3934 CAMLparam1 (cursor_v);
3935 size_t cursn = Int_val (cursor_v);
3936 XSetWindowAttributes wa;
3938 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3939 wa.cursor = glx.curs[cursn];
3940 XChangeWindowAttributes (glx.dpy, glx.wid, CWCursor, &wa);
3941 XFlush (glx.dpy);
3942 CAMLreturn (Val_unit);
3945 CAMLprim value ml_swapb (value unit_v)
3947 CAMLparam1 (unit_v);
3948 glXSwapBuffers (glx.dpy, glx.wid);
3949 CAMLreturn (Val_unit);
3952 #include "keysym2ucs.c"
3954 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3956 CAMLparam1 (keysym_v);
3957 CAMLlocal1 (str_v);
3958 KeySym keysym = Int_val (keysym_v);
3959 Rune rune;
3960 int len;
3961 char buf[5];
3963 rune = keysym2ucs (keysym);
3964 len = fz_runetochar (buf, rune);
3965 buf[len] = 0;
3966 str_v = caml_copy_string (buf);
3967 CAMLreturn (str_v);
3970 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
3972 CAMLprim value ml_platform (value unit_v)
3974 CAMLparam1 (unit_v);
3975 CAMLlocal2 (tup_v, arr_v);
3976 int platid = piunknown;
3977 struct utsname buf;
3979 #if defined __linux__
3980 platid = pilinux;
3981 #elif defined __CYGWIN__
3982 platid = picygwin;
3983 #elif defined __DragonFly__ || defined __FreeBSD__
3984 || defined __OpenBSD__ || defined __NetBSD__
3985 platid = pibsd;
3986 #elif defined __sun__
3987 platid = pisun;
3988 #elif defined __APPLE__
3989 platid = piosx;
3990 #endif
3991 if (uname (&buf)) err (1, "uname");
3993 tup_v = caml_alloc_tuple (2);
3995 char const *sar[] = {
3996 buf.sysname,
3997 buf.release,
3998 buf.version,
3999 buf.machine,
4000 NULL
4002 arr_v = caml_copy_string_array (sar);
4004 Field (tup_v, 0) = Val_int (platid);
4005 Field (tup_v, 1) = arr_v;
4006 CAMLreturn (tup_v);
4009 CAMLprim value ml_cloexec (value fd_v)
4011 CAMLparam1 (fd_v);
4012 int fd = Int_val (fd_v);
4014 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4015 uerror ("fcntl", Nothing);
4017 CAMLreturn (Val_unit);
4020 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4022 CAMLparam2 (w_v, h_v);
4023 CAMLlocal1 (ret_v);
4024 struct pbo *pbo;
4025 int w = Int_val (w_v);
4026 int h = Int_val (h_v);
4027 int cs = Int_val (cs_v);
4029 if (state.pbo_usable) {
4030 pbo = calloc (sizeof (*pbo), 1);
4031 if (!pbo) {
4032 err (1, "calloc pbo");
4035 switch (cs) {
4036 case 0:
4037 case 1:
4038 pbo->size = w*h*4;
4039 break;
4040 case 2:
4041 pbo->size = w*h*2;
4042 break;
4043 default:
4044 errx (1, "ml_getpbo: invalid colorspace %d", cs);
4047 state.glGenBuffersARB (1, &pbo->id);
4048 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4049 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4050 NULL, GL_STREAM_DRAW);
4051 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4052 GL_READ_WRITE);
4053 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4054 if (!pbo->ptr) {
4055 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4056 state.glDeleteBuffersARB (1, &pbo->id);
4057 free (pbo);
4058 ret_v = caml_copy_string ("0");
4060 else {
4061 int res;
4062 char *s;
4064 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4065 if (res < 0) {
4066 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4068 s = malloc (res+1);
4069 if (!s) {
4070 err (1, "malloc %d bytes failed", res+1);
4072 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4073 if (res < 0) {
4074 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4076 ret_v = caml_copy_string (s);
4077 free (s);
4080 else {
4081 ret_v = caml_copy_string ("0");
4083 CAMLreturn (ret_v);
4086 CAMLprim value ml_freepbo (value s_v)
4088 CAMLparam1 (s_v);
4089 char *s = String_val (s_v);
4090 struct tile *tile = parse_pointer (__func__, s);
4092 if (tile->pbo) {
4093 state.glDeleteBuffersARB (1, &tile->pbo->id);
4094 tile->pbo->id = -1;
4095 tile->pbo->ptr = NULL;
4096 tile->pbo->size = -1;
4098 CAMLreturn (Val_unit);
4101 CAMLprim value ml_unmappbo (value s_v)
4103 CAMLparam1 (s_v);
4104 char *s = String_val (s_v);
4105 struct tile *tile = parse_pointer (__func__, s);
4107 if (tile->pbo) {
4108 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4109 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4110 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4112 tile->pbo->ptr = NULL;
4113 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4115 CAMLreturn (Val_unit);
4118 static void setuppbo (void)
4120 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4121 state.pbo_usable = GGPA (glBindBufferARB)
4122 && GGPA (glUnmapBufferARB)
4123 && GGPA (glMapBufferARB)
4124 && GGPA (glBufferDataARB)
4125 && GGPA (glGenBuffersARB)
4126 && GGPA (glDeleteBuffersARB);
4127 #undef GGPA
4130 CAMLprim value ml_pbo_usable (value unit_v)
4132 CAMLparam1 (unit_v);
4133 CAMLreturn (Val_bool (state.pbo_usable));
4136 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4138 CAMLparam3 (ptr_v, x_v, y_v);
4139 CAMLlocal2 (ret_v, tup_v);
4140 struct page *page;
4141 char *s = String_val (ptr_v);
4142 int x = Int_val (x_v), y = Int_val (y_v);
4143 struct pagedim *pdim;
4144 fz_point p;
4145 fz_matrix ctm;
4147 page = parse_pointer (__func__, s);
4148 pdim = &state.pagedims[page->pdimno];
4150 ret_v = Val_int (0);
4151 if (trylock (__func__)) {
4152 goto done;
4155 if (pdf_specifics (state.ctx, state.doc)) {
4156 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4157 ctm = state.pagedims[page->pdimno].tctm;
4159 else {
4160 ctm = fz_identity;
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 (__func__);
4176 done:
4177 CAMLreturn (ret_v);
4180 CAMLprim value ml_project (value ptr_v, value x_v, value y_v)
4182 CAMLparam3 (ptr_v, x_v, y_v);
4183 CAMLlocal1 (ret_v);
4184 struct page *page;
4185 char *s = String_val (ptr_v);
4186 double x = Double_val (x_v), y = Double_val (y_v);
4187 struct pagedim *pdim;
4188 fz_point p;
4189 fz_matrix ctm;
4191 page = parse_pointer (__func__, s);
4192 pdim = &state.pagedims[page->pdimno];
4194 ret_v = Val_int (0);
4195 lock (__func__);
4197 if (pdf_specifics (state.ctx, state.doc)) {
4198 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4199 ctm = state.pagedims[page->pdimno].tctm;
4201 else {
4202 ctm = fz_identity;
4204 p.x = x + pdim->bounds.x0;
4205 p.y = y + pdim->bounds.y0;
4207 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4208 fz_transform_point (&p, &ctm);
4210 ret_v = caml_alloc_tuple (2);
4211 Field (ret_v, 0) = caml_copy_double (p.x);
4212 Field (ret_v, 1) = caml_copy_double (p.y);
4214 unlock (__func__);
4215 CAMLreturn (ret_v);
4218 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4219 value contents_v)
4221 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4222 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4224 if (pdf) {
4225 pdf_annot *annot;
4226 struct page *page;
4227 fz_point p;
4228 char *s = String_val (ptr_v);
4230 page = parse_pointer (__func__, s);
4231 annot = pdf_create_annot (state.ctx, pdf,
4232 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4233 p.x = Int_val (x_v);
4234 p.y = Int_val (y_v);
4235 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4236 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4237 state.dirty = 1;
4239 CAMLreturn (Val_unit);
4242 CAMLprim value ml_delannot (value ptr_v, value n_v)
4244 CAMLparam2 (ptr_v, n_v);
4245 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4247 if (pdf) {
4248 struct page *page;
4249 char *s = String_val (ptr_v);
4250 struct slink *slink;
4252 page = parse_pointer (__func__, s);
4253 slink = &page->slinks[Int_val (n_v)];
4254 pdf_delete_annot (state.ctx, pdf,
4255 (pdf_page *) page->fzpage,
4256 (pdf_annot *) slink->u.annot);
4257 state.dirty = 1;
4259 CAMLreturn (Val_unit);
4262 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4264 CAMLparam3 (ptr_v, n_v, str_v);
4265 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4267 if (pdf) {
4268 struct page *page;
4269 char *s = String_val (ptr_v);
4270 struct slink *slink;
4272 page = parse_pointer (__func__, s);
4273 slink = &page->slinks[Int_val (n_v)];
4274 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4275 String_val (str_v));
4276 state.dirty = 1;
4278 CAMLreturn (Val_unit);
4281 CAMLprim value ml_hasunsavedchanges (value unit_v)
4283 CAMLparam1 (unit_v);
4284 CAMLreturn (Val_bool (state.dirty));
4287 CAMLprim value ml_savedoc (value path_v)
4289 CAMLparam1 (path_v);
4290 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4292 if (pdf) {
4293 pdf_write_document (state.ctx, pdf, String_val (path_v), NULL);
4295 CAMLreturn (Val_unit);
4298 static void makestippletex (void)
4300 const char pixels[] = "\xff\xff\0\0";
4301 glGenTextures (1, &state.stid);
4302 glBindTexture (GL_TEXTURE_1D, state.stid);
4303 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4304 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4305 glTexImage1D (
4306 GL_TEXTURE_1D,
4308 GL_ALPHA,
4311 GL_ALPHA,
4312 GL_UNSIGNED_BYTE,
4313 pixels
4317 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4319 return caml_copy_string (FZ_VERSION);
4322 #ifdef USE_FONTCONFIG
4323 static struct {
4324 int inited;
4325 FcConfig *config;
4326 } fc;
4328 static fz_font *fc_load_system_font_func (fz_context *ctx,
4329 const char *name,
4330 int bold,
4331 int italic,
4332 int UNUSED_ATTR needs_exact_metrics)
4334 char *buf;
4335 size_t i, size;
4336 fz_font *font;
4337 FcChar8 *path;
4338 FcResult result;
4339 FcPattern *pat, *pat1;
4341 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4342 name, bold, italic, needs_exact_metrics);
4343 if (!fc.inited) {
4344 fc.inited = 1;
4345 fc.config = FcInitLoadConfigAndFonts ();
4346 if (!fc.config) {
4347 lprintf ("FcInitLoadConfigAndFonts failed\n");
4348 return NULL;
4351 if (!fc.config) return NULL;
4353 size = strlen (name);
4354 if (bold) size += sizeof (":bold") - 1;
4355 if (italic) size += sizeof (":italic") - 1;
4356 size += 1;
4358 buf = malloc (size);
4359 if (!buf) {
4360 err (1, "malloc %zu failed", size);
4363 strcpy (buf, name);
4364 if (bold && italic) {
4365 strcat (buf, ":bold:italic");
4367 else {
4368 if (bold) strcat (buf, ":bold");
4369 if (italic) strcat (buf, ":italic");
4371 for (i = 0; i < size; ++i) {
4372 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4375 lprintf ("fcbuf=%s\n", buf);
4376 pat = FcNameParse ((FcChar8 *) buf);
4377 if (!pat) {
4378 printd ("emsg FcNameParse failed\n");
4379 free (buf);
4380 return NULL;
4383 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4384 printd ("emsg FcConfigSubstitute failed\n");
4385 free (buf);
4386 return NULL;
4388 FcDefaultSubstitute (pat);
4390 pat1 = FcFontMatch (fc.config, pat, &result);
4391 if (!pat1) {
4392 printd ("emsg FcFontMatch failed\n");
4393 FcPatternDestroy (pat);
4394 free (buf);
4395 return NULL;
4398 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4399 printd ("emsg FcPatternGetString failed\n");
4400 FcPatternDestroy (pat);
4401 FcPatternDestroy (pat1);
4402 free (buf);
4403 return NULL;
4406 #if 0
4407 printd ("emsg name=%s path=%s\n", name, path);
4408 #endif
4409 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4410 FcPatternDestroy (pat);
4411 FcPatternDestroy (pat1);
4412 free (buf);
4413 return font;
4415 #endif
4417 CAMLprim value ml_init (value csock_v, value params_v)
4419 CAMLparam2 (csock_v, params_v);
4420 CAMLlocal2 (trim_v, fuzz_v);
4421 int ret;
4422 int texcount;
4423 char *fontpath;
4424 int colorspace;
4425 int mustoresize;
4426 int haspboext;
4428 state.csock = Int_val (csock_v);
4429 state.rotate = Int_val (Field (params_v, 0));
4430 state.fitmodel = Int_val (Field (params_v, 1));
4431 trim_v = Field (params_v, 2);
4432 texcount = Int_val (Field (params_v, 3));
4433 state.sliceheight = Int_val (Field (params_v, 4));
4434 mustoresize = Int_val (Field (params_v, 5));
4435 colorspace = Int_val (Field (params_v, 6));
4436 fontpath = String_val (Field (params_v, 7));
4438 if (caml_string_length (Field (params_v, 8)) > 0) {
4439 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4441 if (!state.trimcachepath) {
4442 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4443 strerror (errno));
4446 haspboext = Bool_val (Field (params_v, 9));
4448 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4449 fz_register_document_handlers (state.ctx);
4451 #ifdef USE_FONTCONFIG
4452 if (Bool_val (Field (params_v, 10))) {
4453 fz_install_load_system_font_funcs (
4454 state.ctx, fc_load_system_font_func, NULL
4457 #endif
4459 state.trimmargins = Bool_val (Field (trim_v, 0));
4460 fuzz_v = Field (trim_v, 1);
4461 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4462 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4463 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4464 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4466 set_tex_params (colorspace);
4468 if (*fontpath) {
4469 #ifndef USE_FONTCONFIG
4470 state.face = load_font (fontpath);
4471 #else
4472 FcChar8 *path;
4473 FcResult result;
4474 char *buf = fontpath;
4475 FcPattern *pat, *pat1;
4477 fc.inited = 1;
4478 fc.config = FcInitLoadConfigAndFonts ();
4479 if (!fc.config) {
4480 errx (1, "FcInitLoadConfigAndFonts failed");
4483 pat = FcNameParse ((FcChar8 *) buf);
4484 if (!pat) {
4485 errx (1, "FcNameParse failed");
4488 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4489 errx (1, "FcConfigSubstitute failed");
4491 FcDefaultSubstitute (pat);
4493 pat1 = FcFontMatch (fc.config, pat, &result);
4494 if (!pat1) {
4495 errx (1, "FcFontMatch failed");
4498 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4499 errx (1, "FcPatternGetString failed");
4502 state.face = load_font ((char *) path);
4503 FcPatternDestroy (pat);
4504 FcPatternDestroy (pat1);
4505 #endif
4507 else {
4508 unsigned int len;
4509 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4511 state.face = load_builtin_font (base, len);
4513 if (!state.face) _exit (1);
4515 realloctexts (texcount);
4517 if (haspboext) {
4518 setuppbo ();
4521 makestippletex ();
4523 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4524 if (ret) {
4525 errx (1, "pthread_create: %s", strerror (ret));
4528 CAMLreturn (Val_unit);