Optionally ignore precise positioning in presentation mode
[llpp.git] / link.c
blob24383d2266ed3dc7ffb790be9e878fc008f9ad2f
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 #ifdef USE_NPOT
123 #define TEXT_TYPE GL_TEXTURE_2D
124 #else
125 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
126 #endif
128 #ifndef GL_BGRA
129 #define GL_BGRA 0x80E1
130 #endif
132 #ifndef GL_UNSIGNED_INT_8_8_8_8
133 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
134 #endif
136 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
137 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
138 #endif
140 #if 0
141 #define lprintf printf
142 #else
143 #define lprintf(...)
144 #endif
146 #define ARSERT(cond) for (;;) { \
147 if (!(cond)) { \
148 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
150 break; \
153 struct slice {
154 int h;
155 int texindex;
158 struct tile {
159 int w, h;
160 int slicecount;
161 int sliceheight;
162 struct bo *pbo;
163 fz_pixmap *pixmap;
164 struct slice slices[1];
167 struct pagedim {
168 int pageno;
169 int rotate;
170 int left;
171 int tctmready;
172 fz_irect bounds;
173 fz_rect pagebox;
174 fz_rect mediabox;
175 fz_matrix ctm, zoomctm, lctm, tctm;
178 struct slink {
179 enum { SLINK, SANNOT } tag;
180 fz_irect bbox;
181 union {
182 fz_link *link;
183 fz_annot *annot;
184 } u;
187 struct annot {
188 fz_irect bbox;
189 fz_annot *annot;
192 struct page {
193 int tgen;
194 int sgen;
195 int agen;
196 int pageno;
197 int pdimno;
198 fz_stext_page *text;
199 fz_stext_sheet *sheet;
200 fz_page *fzpage;
201 fz_display_list *dlist;
202 int slinkcount;
203 struct slink *slinks;
204 int annotcount;
205 struct annot *annots;
206 struct mark {
207 int i;
208 fz_stext_span *span;
209 } fmark, lmark;
212 struct {
213 int sliceheight;
214 struct pagedim *pagedims;
215 int pagecount;
216 int pagedimcount;
217 fz_document *doc;
218 fz_context *ctx;
219 int w, h;
221 int texindex;
222 int texcount;
223 GLuint *texids;
225 GLenum texiform;
226 GLenum texform;
227 GLenum texty;
229 fz_colorspace *colorspace;
231 struct {
232 int w, h;
233 struct slice *slice;
234 } *texowners;
236 int rotate;
237 enum { FitWidth, FitProportional, FitPage } fitmodel;
238 int trimmargins;
239 int needoutline;
240 int gen;
241 int aalevel;
243 int trimanew;
244 fz_irect trimfuzz;
245 fz_pixmap *pig;
247 pthread_t thread;
248 int csock;
249 FT_Face face;
251 char *trimcachepath;
252 int cxack;
253 int dirty;
255 GLuint stid;
257 int bo_usable;
258 GLuint boid;
260 void (*glBindBufferARB) (GLenum, GLuint);
261 GLboolean (*glUnmapBufferARB) (GLenum);
262 void *(*glMapBufferARB) (GLenum, GLenum);
263 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
264 void (*glGenBuffersARB) (GLsizei, GLuint *);
265 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
267 GLfloat texcoords[8];
268 GLfloat vertices[16];
270 #ifdef CACHE_PAGEREFS
271 struct {
272 int idx;
273 int count;
274 pdf_obj **objs;
275 pdf_document *pdf;
276 } pdflut;
277 #endif
278 } state;
280 struct bo {
281 GLuint id;
282 void *ptr;
283 size_t size;
286 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
288 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
291 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
293 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
296 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
298 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
299 m.a, m.b, m.c, m.d, m.e, m.f);
302 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
304 static void lock (const char *cap)
306 int ret = pthread_mutex_lock (&mutex);
307 if (ret) {
308 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
312 static void unlock (const char *cap)
314 int ret = pthread_mutex_unlock (&mutex);
315 if (ret) {
316 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
320 static int trylock (const char *cap)
322 int ret = pthread_mutex_trylock (&mutex);
323 if (ret && ret != EBUSY) {
324 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
326 return ret == EBUSY;
329 static void *parse_pointer (const char *cap, const char *s)
331 int ret;
332 void *ptr;
334 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
335 if (ret != 1) {
336 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
338 return ptr;
341 static double now (void)
343 struct timeval tv;
345 if (gettimeofday (&tv, NULL)) {
346 err (1, "gettimeofday");
348 return tv.tv_sec + tv.tv_usec*1e-6;
351 static int hasdata (void)
353 int ret, avail;
354 ret = ioctl (state.csock, FIONREAD, &avail);
355 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
356 return avail > 0;
359 CAMLprim value ml_hasdata (value fd_v)
361 CAMLparam1 (fd_v);
362 int ret, avail;
364 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
365 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
366 CAMLreturn (Val_bool (avail > 0));
369 static void readdata (void *p, int size)
371 ssize_t n;
373 again:
374 n = read (state.csock, p, size);
375 if (n < 0) {
376 if (errno == EINTR) goto again;
377 err (1, "read (req %d, ret %zd)", size, n);
379 if (n - size) {
380 if (!n) errx (1, "EOF while reading");
381 errx (1, "read (req %d, ret %zd)", size, n);
385 static void writedata (char *p, int size)
387 ssize_t n;
389 p[0] = (size >> 24) & 0xff;
390 p[1] = (size >> 16) & 0xff;
391 p[2] = (size >> 8) & 0xff;
392 p[3] = (size >> 0) & 0xff;
394 n = write (state.csock, p, size + 4);
395 if (n - size - 4) {
396 if (!n) errx (1, "EOF while writing data");
397 err (1, "write (req %d, ret %zd)", size + 4, n);
401 static int readlen (void)
403 unsigned char p[4];
405 readdata (p, 4);
406 return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
409 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
411 int size = 200, len;
412 va_list ap;
413 char *buf;
415 buf = malloc (size);
416 for (;;) {
417 if (!buf) err (1, "malloc for temp buf (%d bytes) failed", size);
419 va_start (ap, fmt);
420 len = vsnprintf (buf + 4, size - 4, fmt, ap);
421 va_end (ap);
423 if (len > -1) {
424 if (len < size - 4) {
425 writedata (buf, len);
426 break;
428 else size = len + 5;
430 else {
431 err (1, "vsnprintf for `%s' failed", fmt);
433 buf = realloc (buf, size);
435 free (buf);
438 static void closedoc (void)
440 #ifdef CACHE_PAGEREFS
441 if (state.pdflut.objs) {
442 int i;
444 for (i = 0; i < state.pdflut.count; ++i) {
445 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
447 free (state.pdflut.objs);
448 state.pdflut.objs = NULL;
449 state.pdflut.idx = 0;
451 #endif
452 if (state.doc) {
453 fz_drop_document (state.ctx, state.doc);
454 state.doc = NULL;
458 static int openxref (char *filename, char *password)
460 int i;
462 for (i = 0; i < state.texcount; ++i) {
463 state.texowners[i].w = -1;
464 state.texowners[i].slice = NULL;
467 closedoc ();
469 state.dirty = 0;
470 if (state.pagedims) {
471 free (state.pagedims);
472 state.pagedims = NULL;
474 state.pagedimcount = 0;
476 fz_set_aa_level (state.ctx, state.aalevel);
477 state.doc = fz_open_document (state.ctx, filename);
478 if (fz_needs_password (state.ctx, state.doc)) {
479 if (password && !*password) {
480 printd ("pass");
481 return 0;
483 else {
484 int ok = fz_authenticate_password (state.ctx, state.doc, password);
485 if (!ok) {
486 printd ("pass fail");
487 return 0;
491 state.pagecount = fz_count_pages (state.ctx, state.doc);
492 return 1;
495 static void pdfinfo (void)
497 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
498 if (pdf) {
499 pdf_obj *infoobj;
501 printd ("info PDF version\t%d.%d",
502 pdf->version / 10, pdf->version % 10);
504 infoobj = pdf_dict_gets (state.ctx, pdf_trailer (state.ctx,
505 pdf), "Info");
506 if (infoobj) {
507 unsigned int i;
508 char *s;
509 char *items[] = { "Title", "Author", "Creator",
510 "Producer", "CreationDate" };
512 for (i = 0; i < sizeof (items) / sizeof (*items); ++i) {
513 pdf_obj *obj = pdf_dict_gets (state.ctx, infoobj, items[i]);
514 s = pdf_to_utf8 (state.ctx, pdf, obj);
515 if (*s) printd ("info %s\t%s", items[i], s);
516 fz_free (state.ctx, s);
519 printd ("infoend");
523 static void unlinktile (struct tile *tile)
525 int i;
527 for (i = 0; i < tile->slicecount; ++i) {
528 struct slice *s = &tile->slices[i];
530 if (s->texindex != -1) {
531 if (state.texowners[s->texindex].slice == s) {
532 state.texowners[s->texindex].slice = NULL;
538 static void freepage (struct page *page)
540 if (!page) return;
541 if (page->text) {
542 fz_drop_stext_page (state.ctx, page->text);
544 if (page->sheet) {
545 fz_drop_stext_sheet (state.ctx, page->sheet);
547 if (page->slinks) {
548 free (page->slinks);
550 fz_drop_display_list (state.ctx, page->dlist);
551 fz_drop_page (state.ctx, page->fzpage);
552 free (page);
555 static void freetile (struct tile *tile)
557 unlinktile (tile);
558 if (!tile->pbo) {
559 #ifndef PIGGYBACK
560 fz_drop_pixmap (state.ctx, tile->pixmap);
561 #else
562 if (state.pig) {
563 fz_drop_pixmap (state.ctx, state.pig);
565 state.pig = tile->pixmap;
566 #endif
568 else {
569 free (tile->pbo);
570 fz_drop_pixmap (state.ctx, tile->pixmap);
572 free (tile);
575 #ifdef __ALTIVEC__
576 #include <stdint.h>
577 #include <altivec.h>
579 static int cacheline32bytes;
581 static void __attribute__ ((constructor)) clcheck (void)
583 char **envp = environ;
584 unsigned long *auxv;
586 while (*envp++);
588 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
589 if (*auxv == 19) {
590 cacheline32bytes = auxv[1] == 32;
591 return;
596 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
598 size_t size = pixmap->w * pixmap->h * pixmap->n;
599 if (cacheline32bytes && size > 32) {
600 intptr_t a1, a2, diff;
601 size_t sizea, i;
602 vector unsigned char v = vec_splat_u8 (-1);
603 vector unsigned char *p;
605 a1 = a2 = (intptr_t) pixmap->samples;
606 a2 = (a1 + 31) & ~31;
607 diff = a2 - a1;
608 sizea = size - diff;
609 p = (void *) a2;
611 while (a1 != a2) *(char *) a1++ = 0xff;
612 for (i = 0; i < (sizea & ~31); i += 32) {
613 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
614 vec_st (v, i, p);
615 vec_st (v, i + 16, p);
617 while (i < sizea) *((char *) a1 + i++) = 0xff;
619 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
621 #else
622 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
623 #endif
625 static void trimctm (pdf_page *page, int pindex)
627 fz_matrix ctm;
628 struct pagedim *pdim = &state.pagedims[pindex];
630 if (!pdim->tctmready) {
631 if (state.trimmargins) {
632 fz_rect realbox;
633 fz_matrix rm, sm, tm, im, ctm1;
635 fz_rotate (&rm, -pdim->rotate);
636 fz_scale (&sm, 1, -1);
637 fz_concat (&ctm, &rm, &sm);
638 realbox = pdim->mediabox;
639 fz_transform_rect (&realbox, &ctm);
640 fz_translate (&tm, -realbox.x0, -realbox.y0);
641 fz_concat (&ctm1, &ctm, &tm);
642 fz_invert_matrix (&im, &page->ctm);
643 fz_concat (&ctm, &im, &ctm1);
645 else {
646 ctm = fz_identity;
648 pdim->tctm = ctm;
649 pdim->tctmready = 1;
653 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
655 fz_matrix ctm, tm;
656 int pdimno = pdim - state.pagedims;
658 if (pdf_specifics (state.ctx, state.doc)) {
659 trimctm ((pdf_page *) fzpage, pdimno);
660 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
662 else {
663 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
664 fz_concat (&ctm, &tm, &pdim->ctm);
666 return ctm;
669 static fz_matrix pagectm (struct page *page)
671 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
674 static void *loadpage (int pageno, int pindex)
676 fz_device *dev;
677 struct page *page;
679 page = calloc (sizeof (struct page), 1);
680 if (!page) {
681 err (1, "calloc page %d", pageno);
684 page->dlist = fz_new_display_list (state.ctx);
685 dev = fz_new_list_device (state.ctx, page->dlist);
686 fz_try (state.ctx) {
687 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
688 fz_run_page (state.ctx, page->fzpage, dev,
689 &fz_identity, NULL);
691 fz_catch (state.ctx) {
692 page->fzpage = NULL;
694 fz_drop_device (state.ctx, dev);
696 page->pdimno = pindex;
697 page->pageno = pageno;
698 page->sgen = state.gen;
699 page->agen = state.gen;
700 page->tgen = state.gen;
701 return page;
704 static struct tile *alloctile (int h)
706 int i;
707 int slicecount;
708 size_t tilesize;
709 struct tile *tile;
711 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
712 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
713 tile = calloc (tilesize, 1);
714 if (!tile) {
715 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
717 for (i = 0; i < slicecount; ++i) {
718 int sh = MIN (h, state.sliceheight);
719 tile->slices[i].h = sh;
720 tile->slices[i].texindex = -1;
721 h -= sh;
723 tile->slicecount = slicecount;
724 tile->sliceheight = state.sliceheight;
725 return tile;
728 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
729 struct bo *pbo)
731 fz_rect rect;
732 fz_irect bbox;
733 fz_matrix ctm;
734 fz_device *dev;
735 struct tile *tile;
736 struct pagedim *pdim;
738 tile = alloctile (h);
739 pdim = &state.pagedims[page->pdimno];
741 bbox = pdim->bounds;
742 bbox.x0 += x;
743 bbox.y0 += y;
744 bbox.x1 = bbox.x0 + w;
745 bbox.y1 = bbox.y0 + h;
747 if (state.pig) {
748 if (state.pig->w == w
749 && state.pig->h == h
750 && state.pig->colorspace == state.colorspace) {
751 tile->pixmap = state.pig;
752 tile->pixmap->x = bbox.x0;
753 tile->pixmap->y = bbox.y0;
755 else {
756 fz_drop_pixmap (state.ctx, state.pig);
758 state.pig = NULL;
760 if (!tile->pixmap) {
761 if (pbo) {
762 tile->pixmap =
763 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
764 &bbox, pbo->ptr);
765 tile->pbo = pbo;
767 else {
768 tile->pixmap =
769 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox);
773 tile->w = w;
774 tile->h = h;
775 clearpixmap (tile->pixmap);
777 dev = fz_new_draw_device (state.ctx, tile->pixmap);
778 ctm = pagectm (page);
779 fz_rect_from_irect (&rect, &bbox);
780 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
781 fz_drop_device (state.ctx, dev);
783 return tile;
786 #ifdef CACHE_PAGEREFS
787 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
788 thanks to Robin Watts */
789 static void
790 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
792 fz_context *ctx = state.ctx; /* doc->ctx; */
793 pdf_obj *kids;
794 int i, len;
796 if (state.pdflut.idx == state.pagecount) return;
798 kids = pdf_dict_gets (ctx, node, "Kids");
799 len = pdf_array_len (ctx, kids);
801 if (len == 0)
802 fz_throw (ctx, FZ_ERROR_GENERIC, "Malformed pages tree");
804 if (pdf_mark_obj (ctx, node))
805 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
806 for (i = 0; i < len; i++) {
807 pdf_obj *kid = pdf_array_get (ctx, kids, i);
808 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
809 if (*type
810 ? !strcmp (type, "Pages")
811 : pdf_dict_gets (ctx, kid, "Kids")
812 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
813 pdf_collect_pages (doc, kid);
815 else {
816 if (*type
817 ? strcmp (type, "Page") != 0
818 : !pdf_dict_gets (ctx, kid, "MediaBox"))
819 fz_warn (ctx, "non-page object in page tree (%s)", type);
820 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
823 pdf_unmark_obj (ctx, node);
826 static void
827 pdf_load_page_objs (pdf_document *doc)
829 pdf_obj *root = pdf_dict_gets (state.ctx,
830 pdf_trailer (state.ctx, doc), "Root");
831 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
833 if (!node)
834 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
836 state.pdflut.idx = 0;
837 pdf_collect_pages (doc, node);
839 #endif
841 static void initpdims (int wthack)
843 double start, end;
844 FILE *trimf = NULL;
845 fz_rect rootmediabox;
846 int pageno, trim, show;
847 int trimw = 0, cxcount;
848 fz_context *ctx = state.ctx;
849 pdf_document *pdf = pdf_specifics (ctx, state.doc);
851 fz_var (trimw);
852 fz_var (cxcount);
853 start = now ();
855 if (state.trimmargins && state.trimcachepath) {
856 trimf = fopen (state.trimcachepath, "rb");
857 if (!trimf) {
858 trimf = fopen (state.trimcachepath, "wb");
859 trimw = 1;
863 if (state.trimmargins || pdf || !state.cxack)
864 cxcount = state.pagecount;
865 else
866 cxcount = MIN (state.pagecount, 1);
868 if (pdf) {
869 pdf_obj *obj;
870 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
871 "Root/Pages/MediaBox");
872 pdf_to_rect (ctx, obj, &rootmediabox);
875 #ifdef CACHE_PAGEREFS
876 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
877 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
878 if (!state.pdflut.objs) {
879 err (1, "malloc pageobjs %zu %d %zu failed",
880 sizeof (*state.pdflut.objs), cxcount,
881 sizeof (*state.pdflut.objs) * cxcount);
883 state.pdflut.count = cxcount;
884 pdf_load_page_objs (pdf);
885 state.pdflut.pdf = pdf;
887 #endif
889 for (pageno = 0; pageno < cxcount; ++pageno) {
890 int rotate = 0;
891 struct pagedim *p;
892 fz_rect mediabox;
894 if (pdf) {
895 pdf_obj *pageref, *pageobj;
897 #ifdef CACHE_PAGEREFS
898 pageref = state.pdflut.objs[pageno];
899 #else
900 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
901 #endif
902 pageobj = pdf_resolve_indirect (ctx, pageref);
904 if (state.trimmargins) {
905 pdf_obj *obj;
906 pdf_page *page;
908 fz_try (ctx) {
909 page = pdf_load_page (ctx, pdf, pageno);
910 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
911 trim = state.trimanew || !obj;
912 if (trim) {
913 fz_rect rect;
914 fz_matrix ctm;
915 fz_device *dev;
917 dev = fz_new_bbox_device (ctx, &rect);
918 dev->hints |= FZ_IGNORE_SHADE;
919 fz_invert_matrix (&ctm, &page->ctm);
920 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
921 fz_drop_device (ctx, dev);
923 rect.x0 += state.trimfuzz.x0;
924 rect.x1 += state.trimfuzz.x1;
925 rect.y0 += state.trimfuzz.y0;
926 rect.y1 += state.trimfuzz.y1;
927 fz_transform_rect (&rect, &ctm);
928 fz_intersect_rect (&rect, &page->mediabox);
930 if (fz_is_empty_rect (&rect)) {
931 mediabox = page->mediabox;
933 else {
934 mediabox = rect;
937 obj = pdf_new_array (ctx, pdf, 4);
938 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
939 mediabox.x0));
940 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
941 mediabox.y0));
942 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
943 mediabox.x1));
944 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
945 mediabox.y1));
946 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
948 else {
949 mediabox.x0 = pdf_to_real (ctx,
950 pdf_array_get (ctx, obj, 0));
951 mediabox.y0 = pdf_to_real (ctx,
952 pdf_array_get (ctx, obj, 1));
953 mediabox.x1 = pdf_to_real (ctx,
954 pdf_array_get (ctx, obj, 2));
955 mediabox.y1 = pdf_to_real (ctx,
956 pdf_array_get (ctx, obj, 3));
959 rotate = page->rotate;
960 fz_drop_page (ctx, &page->super);
962 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
963 if (show) {
964 printd ("progress %f Trimming %d",
965 (double) (pageno + 1) / state.pagecount,
966 pageno + 1);
969 fz_catch (ctx) {
970 fprintf (stderr, "failed to load page %d\n", pageno+1);
973 else {
974 int empty = 0;
975 fz_rect cropbox;
977 pdf_to_rect (ctx,
978 pdf_dict_gets (ctx, pageobj, "MediaBox"),
979 &mediabox);
980 if (fz_is_empty_rect (&mediabox)) {
981 mediabox.x0 = 0;
982 mediabox.y0 = 0;
983 mediabox.x1 = 612;
984 mediabox.y1 = 792;
985 empty = 1;
988 pdf_to_rect (ctx,
989 pdf_dict_gets (ctx, pageobj, "CropBox"),
990 &cropbox);
991 if (!fz_is_empty_rect (&cropbox)) {
992 if (empty) {
993 mediabox = cropbox;
995 else {
996 fz_intersect_rect (&mediabox, &cropbox);
999 else {
1000 if (empty) {
1001 if (fz_is_empty_rect (&rootmediabox)) {
1002 fprintf (stderr,
1003 "cannot find page size for page %d\n",
1004 pageno+1);
1006 else {
1007 mediabox = rootmediabox;
1011 rotate = pdf_to_int (ctx,
1012 pdf_dict_gets (ctx, pageobj, "Rotate"));
1015 else {
1016 if (state.trimmargins && trimw) {
1017 fz_page *page;
1019 fz_try (ctx) {
1020 page = fz_load_page (ctx, state.doc, pageno);
1021 fz_bound_page (ctx, page, &mediabox);
1022 rotate = 0;
1023 if (state.trimmargins) {
1024 fz_rect rect;
1025 fz_device *dev;
1027 dev = fz_new_bbox_device (ctx, &rect);
1028 dev->hints |= FZ_IGNORE_SHADE;
1029 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1030 fz_drop_device (ctx, dev);
1032 rect.x0 += state.trimfuzz.x0;
1033 rect.x1 += state.trimfuzz.x1;
1034 rect.y0 += state.trimfuzz.y0;
1035 rect.y1 += state.trimfuzz.y1;
1036 fz_intersect_rect (&rect, &mediabox);
1038 if (!fz_is_empty_rect (&rect)) {
1039 mediabox = rect;
1042 fz_drop_page (ctx, page);
1043 if (!state.cxack) {
1044 printd ("progress %f loading %d",
1045 (double) (pageno + 1) / state.pagecount,
1046 pageno + 1);
1049 fz_catch (ctx) {
1051 if (trimf) {
1052 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1053 if (n - 1) {
1054 err (1, "fwrite trim mediabox");
1058 else {
1059 if (trimf) {
1060 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1061 if (n - 1) {
1062 err (1, "fread trim mediabox %d", pageno);
1065 else {
1066 fz_page *page;
1067 fz_try (ctx) {
1068 page = fz_load_page (ctx, state.doc, pageno);
1069 fz_bound_page (ctx, page, &mediabox);
1070 fz_drop_page (ctx, page);
1072 show = !state.trimmargins && pageno % 20 == 0;
1073 if (show) {
1074 printd ("progress %f Gathering dimensions %d",
1075 (double) (pageno) / state.pagecount,
1076 pageno);
1079 fz_catch (ctx) {
1080 fprintf (stderr, "failed to load page %d\n", pageno);
1086 if (state.pagedimcount == 0
1087 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1088 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1089 size_t size;
1091 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1092 state.pagedims = realloc (state.pagedims, size);
1093 if (!state.pagedims) {
1094 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1095 size, state.pagedimcount + 1);
1098 p = &state.pagedims[state.pagedimcount++];
1099 p->rotate = rotate;
1100 p->mediabox = mediabox;
1101 p->pageno = pageno;
1104 end = now ();
1105 if (!wthack) {
1106 printd ("progress 1 %s %d pages in %f seconds",
1107 state.trimmargins ? "Trimmed" : "Processed",
1108 state.pagecount, end - start);
1110 state.trimanew = 0;
1111 if (trimf) {
1112 if (fclose (trimf)) {
1113 err (1, "fclose");
1118 static void layout (void)
1120 int pindex;
1121 fz_rect box;
1122 fz_matrix ctm, rm;
1123 struct pagedim *p = p;
1124 double zw, w, maxw = 0.0, zoom = zoom;
1126 if (state.pagedimcount == 0) return;
1128 switch (state.fitmodel) {
1129 case FitProportional:
1130 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1131 double x0, x1;
1133 p = &state.pagedims[pindex];
1134 fz_rotate (&rm, p->rotate + state.rotate);
1135 box = p->mediabox;
1136 fz_transform_rect (&box, &rm);
1138 x0 = MIN (box.x0, box.x1);
1139 x1 = MAX (box.x0, box.x1);
1141 w = x1 - x0;
1142 maxw = MAX (w, maxw);
1143 zoom = state.w / maxw;
1145 break;
1147 case FitPage:
1148 maxw = state.w;
1149 break;
1151 case FitWidth:
1152 break;
1154 default:
1155 ARSERT (0 && state.fitmodel);
1158 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1159 fz_rect rect;
1160 fz_matrix tm, sm;
1162 p = &state.pagedims[pindex];
1163 fz_rotate (&ctm, state.rotate);
1164 fz_rotate (&rm, p->rotate + state.rotate);
1165 box = p->mediabox;
1166 fz_transform_rect (&box, &rm);
1167 w = box.x1 - box.x0;
1168 switch (state.fitmodel) {
1169 case FitProportional:
1170 p->left = ((maxw - w) * zoom) / 2.0;
1171 break;
1172 case FitPage:
1174 double zh, h;
1175 zw = maxw / w;
1176 h = box.y1 - box.y0;
1177 zh = state.h / h;
1178 zoom = MIN (zw, zh);
1179 p->left = (maxw - (w * zoom)) / 2.0;
1181 break;
1182 case FitWidth:
1183 p->left = 0;
1184 zoom = state.w / w;
1185 break;
1188 fz_scale (&p->zoomctm, zoom, zoom);
1189 fz_concat (&ctm, &p->zoomctm, &ctm);
1191 fz_rotate (&rm, p->rotate);
1192 p->pagebox = p->mediabox;
1193 fz_transform_rect (&p->pagebox, &rm);
1194 p->pagebox.x1 -= p->pagebox.x0;
1195 p->pagebox.y1 -= p->pagebox.y0;
1196 p->pagebox.x0 = 0;
1197 p->pagebox.y0 = 0;
1198 rect = p->pagebox;
1199 fz_transform_rect (&rect, &ctm);
1200 fz_round_rect (&p->bounds, &rect);
1201 p->ctm = ctm;
1203 fz_translate (&tm, 0, -p->mediabox.y1);
1204 fz_scale (&sm, zoom, -zoom);
1205 fz_concat (&ctm, &tm, &sm);
1206 fz_concat (&p->lctm, &ctm, &rm);
1208 p->tctmready = 0;
1211 do {
1212 int x0 = MIN (p->bounds.x0, p->bounds.x1);
1213 int y0 = MIN (p->bounds.y0, p->bounds.y1);
1214 int x1 = MAX (p->bounds.x0, p->bounds.x1);
1215 int y1 = MAX (p->bounds.y0, p->bounds.y1);
1216 int boundw = x1 - x0;
1217 int boundh = y1 - y0;
1219 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1220 } while (p-- != state.pagedims);
1223 static
1224 struct anchor { int n; int x; int y; int w; int h; }
1225 desttoanchor (fz_link_dest *dest)
1227 int i;
1228 struct anchor a;
1229 struct pagedim *pdim = state.pagedims;
1231 a.n = -1;
1232 a.x = 0;
1233 a.y = 0;
1234 for (i = 0; i < state.pagedimcount; ++i) {
1235 if (state.pagedims[i].pageno > dest->ld.gotor.page)
1236 break;
1237 pdim = &state.pagedims[i];
1239 if (dest->ld.gotor.flags & fz_link_flag_t_valid) {
1240 fz_point p;
1241 if (dest->ld.gotor.flags & fz_link_flag_l_valid)
1242 p.x = dest->ld.gotor.lt.x;
1243 else
1244 p.x = 0.0;
1245 p.y = dest->ld.gotor.lt.y;
1246 fz_transform_point (&p, &pdim->lctm);
1247 a.x = p.x;
1248 a.y = p.y;
1250 if (dest->ld.gotor.page >= 0 && dest->ld.gotor.page < 1<<30) {
1251 double x0, x1, y0, y1;
1253 x0 = MIN (pdim->bounds.x0, pdim->bounds.x1);
1254 x1 = MAX (pdim->bounds.x0, pdim->bounds.x1);
1255 a.w = x1 - x0;
1256 y0 = MIN (pdim->bounds.y0, pdim->bounds.y1);
1257 y1 = MAX (pdim->bounds.y0, pdim->bounds.y1);
1258 a.h = y1 - y0;
1259 a.n = dest->ld.gotor.page;
1261 return a;
1264 static void recurse_outline (fz_outline *outline, int level)
1266 while (outline) {
1267 switch (outline->dest.kind) {
1268 case FZ_LINK_GOTO:
1270 struct anchor a = desttoanchor (&outline->dest);
1272 if (a.n >= 0) {
1273 printd ("o %d %d %d %d %s",
1274 level, a.n, a.y, a.h, outline->title);
1277 break;
1279 case FZ_LINK_URI:
1280 printd ("ou %d %" FMT_s " %s %s", level,
1281 strlen (outline->title), outline->title,
1282 outline->dest.ld.uri.uri);
1283 break;
1285 case FZ_LINK_NONE:
1286 printd ("on %d %s", level, outline->title);
1287 break;
1289 default:
1290 printd ("emsg Unhandled outline kind %d for %s\n",
1291 outline->dest.kind, outline->title);
1292 break;
1294 if (outline->down) {
1295 recurse_outline (outline->down, level + 1);
1297 outline = outline->next;
1301 static void process_outline (void)
1303 fz_outline *outline;
1305 if (!state.needoutline || !state.pagedimcount) return;
1307 state.needoutline = 0;
1308 outline = fz_load_outline (state.ctx, state.doc);
1309 if (outline) {
1310 recurse_outline (outline, 0);
1311 fz_drop_outline (state.ctx, outline);
1315 static char *strofspan (fz_stext_span *span)
1317 char *p;
1318 char utf8[10];
1319 fz_stext_char *ch;
1320 size_t size = 0, cap = 80;
1322 p = malloc (cap + 1);
1323 if (!p) return NULL;
1325 for (ch = span->text; ch < span->text + span->len; ++ch) {
1326 int n = fz_runetochar (utf8, ch->c);
1327 if (size + n > cap) {
1328 cap *= 2;
1329 p = realloc (p, cap + 1);
1330 if (!p) return NULL;
1333 memcpy (p + size, utf8, n);
1334 size += n;
1336 p[size] = 0;
1337 return p;
1340 static int matchspan (regex_t *re, fz_stext_span *span,
1341 int stop, int pageno, double start)
1343 int ret;
1344 char *p;
1345 regmatch_t rm;
1346 int a, b, c;
1347 fz_rect sb, eb;
1348 fz_point p1, p2, p3, p4;
1350 p = strofspan (span);
1351 if (!p) return -1;
1353 ret = regexec (re, p, 1, &rm, 0);
1354 if (ret) {
1355 free (p);
1356 if (ret != REG_NOMATCH) {
1357 size_t size;
1358 char errbuf[80];
1359 size = regerror (ret, re, errbuf, sizeof (errbuf));
1360 printd ("msg regexec error `%.*s'",
1361 (int) size, errbuf);
1362 return -1;
1364 return 0;
1366 else {
1367 int l = span->len;
1369 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1370 c += fz_runelen (span->text[a].c);
1372 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1373 c += fz_runelen (span->text[b].c);
1376 if (fz_runelen (span->text[b].c) > 1) {
1377 b = MAX (0, b-1);
1380 fz_stext_char_bbox (state.ctx, &sb, span, a);
1381 fz_stext_char_bbox (state.ctx, &eb, span, b);
1383 p1.x = sb.x0;
1384 p1.y = sb.y0;
1385 p2.x = eb.x1;
1386 p2.y = sb.y0;
1387 p3.x = eb.x1;
1388 p3.y = eb.y1;
1389 p4.x = sb.x0;
1390 p4.y = eb.y1;
1392 if (!stop) {
1393 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1394 pageno, 1,
1395 p1.x, p1.y,
1396 p2.x, p2.y,
1397 p3.x, p3.y,
1398 p4.x, p4.y);
1400 printd ("progress 1 found at %d `%.*s' in %f sec",
1401 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1402 now () - start);
1404 else {
1405 printd ("match %d %d %f %f %f %f %f %f %f %f",
1406 pageno, 2,
1407 p1.x, p1.y,
1408 p2.x, p2.y,
1409 p3.x, p3.y,
1410 p4.x, p4.y);
1412 free (p);
1413 return 1;
1417 static int compareblocks (const void *l, const void *r)
1419 fz_stext_block const *ls = l;
1420 fz_stext_block const *rs = r;
1421 return ls->bbox.y0 - rs->bbox.y0;
1424 /* wishful thinking function */
1425 static void search (regex_t *re, int pageno, int y, int forward)
1427 int i, j;
1428 fz_device *tdev;
1429 fz_stext_page *text;
1430 fz_stext_sheet *sheet;
1431 struct pagedim *pdim, *pdimprev;
1432 int stop = 0, niters = 0;
1433 double start, end;
1434 fz_page *page;
1436 start = now ();
1437 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1438 if (niters++ == 5) {
1439 niters = 0;
1440 if (hasdata ()) {
1441 printd ("progress 1 attention requested aborting search at %d",
1442 pageno);
1443 stop = 1;
1445 else {
1446 printd ("progress %f searching in page %d",
1447 (double) (pageno + 1) / state.pagecount,
1448 pageno);
1451 pdimprev = NULL;
1452 for (i = 0; i < state.pagedimcount; ++i) {
1453 pdim = &state.pagedims[i];
1454 if (pdim->pageno == pageno) {
1455 goto found;
1457 if (pdim->pageno > pageno) {
1458 pdim = pdimprev;
1459 goto found;
1461 pdimprev = pdim;
1463 pdim = pdimprev;
1464 found:
1466 sheet = fz_new_stext_sheet (state.ctx);
1467 text = fz_new_stext_page (state.ctx);
1468 tdev = fz_new_stext_device (state.ctx, sheet, text);
1470 page = fz_load_page (state.ctx, state.doc, pageno);
1472 fz_matrix ctm = pagectm1 (page, pdim);
1473 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1476 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1477 fz_drop_device (state.ctx, tdev);
1479 for (j = 0; j < text->len; ++j) {
1480 int k;
1481 fz_page_block *pb;
1482 fz_stext_block *block;
1484 pb = &text->blocks[forward ? j : text->len - 1 - j];
1485 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1486 block = pb->u.text;
1488 for (k = 0; k < block->len; ++k) {
1489 fz_stext_line *line;
1490 fz_stext_span *span;
1492 if (forward) {
1493 line = &block->lines[k];
1494 if (line->bbox.y0 < y + 1) continue;
1496 else {
1497 line = &block->lines[block->len - 1 - k];
1498 if (line->bbox.y0 > y - 1) continue;
1501 for (span = line->first_span; span; span = span->next) {
1502 switch (matchspan (re, span, stop, pageno, start)) {
1503 case 0: break;
1504 case 1: stop = 1; break;
1505 case -1: stop = 1; goto endloop;
1510 if (forward) {
1511 pageno += 1;
1512 y = 0;
1514 else {
1515 pageno -= 1;
1516 y = INT_MAX;
1518 endloop:
1519 fz_drop_stext_page (state.ctx, text);
1520 fz_drop_stext_sheet (state.ctx, sheet);
1521 fz_drop_page (state.ctx, page);
1523 end = now ();
1524 if (!stop) {
1525 printd ("progress 1 no matches %f sec", end - start);
1527 printd ("clearrects");
1530 static void set_tex_params (int colorspace)
1532 union {
1533 unsigned char b;
1534 unsigned int s;
1535 } endianness = {1};
1537 switch (colorspace) {
1538 case 0:
1539 state.texiform = GL_RGBA8;
1540 state.texform = GL_RGBA;
1541 state.texty = GL_UNSIGNED_BYTE;
1542 state.colorspace = fz_device_rgb (state.ctx);
1543 break;
1544 case 1:
1545 state.texiform = GL_RGBA8;
1546 state.texform = GL_BGRA;
1547 state.texty = endianness.s > 1
1548 ? GL_UNSIGNED_INT_8_8_8_8
1549 : GL_UNSIGNED_INT_8_8_8_8_REV;
1550 state.colorspace = fz_device_bgr (state.ctx);
1551 break;
1552 case 2:
1553 state.texiform = GL_LUMINANCE_ALPHA;
1554 state.texform = GL_LUMINANCE_ALPHA;
1555 state.texty = GL_UNSIGNED_BYTE;
1556 state.colorspace = fz_device_gray (state.ctx);
1557 break;
1558 default:
1559 errx (1, "invalid colorspce %d", colorspace);
1563 static void realloctexts (int texcount)
1565 size_t size;
1567 if (texcount == state.texcount) return;
1569 if (texcount < state.texcount) {
1570 glDeleteTextures (state.texcount - texcount,
1571 state.texids + texcount);
1574 size = texcount * sizeof (*state.texids);
1575 state.texids = realloc (state.texids, size);
1576 if (!state.texids) {
1577 err (1, "realloc texids %" FMT_s, size);
1580 size = texcount * sizeof (*state.texowners);
1581 state.texowners = realloc (state.texowners, size);
1582 if (!state.texowners) {
1583 err (1, "realloc texowners %" FMT_s, size);
1585 if (texcount > state.texcount) {
1586 int i;
1588 glGenTextures (texcount - state.texcount,
1589 state.texids + state.texcount);
1590 for (i = state.texcount; i < texcount; ++i) {
1591 state.texowners[i].w = -1;
1592 state.texowners[i].slice = NULL;
1595 state.texcount = texcount;
1596 state.texindex = 0;
1599 static char *mbtoutf8 (char *s)
1601 char *p, *r;
1602 wchar_t *tmp;
1603 size_t i, ret, len;
1605 len = mbstowcs (NULL, s, strlen (s));
1606 if (len == 0) {
1607 return s;
1609 else {
1610 if (len == (size_t) -1) {
1611 return s;
1615 tmp = malloc (len * sizeof (wchar_t));
1616 if (!tmp) {
1617 return s;
1620 ret = mbstowcs (tmp, s, len);
1621 if (ret == (size_t) -1) {
1622 free (tmp);
1623 return s;
1626 len = 0;
1627 for (i = 0; i < ret; ++i) {
1628 len += fz_runelen (tmp[i]);
1631 p = r = malloc (len + 1);
1632 if (!r) {
1633 free (tmp);
1634 return s;
1637 for (i = 0; i < ret; ++i) {
1638 p += fz_runetochar (p, tmp[i]);
1640 *p = 0;
1641 free (tmp);
1642 return r;
1645 CAMLprim value ml_mbtoutf8 (value s_v)
1647 CAMLparam1 (s_v);
1648 CAMLlocal1 (ret_v);
1649 char *s, *r;
1651 s = String_val (s_v);
1652 r = mbtoutf8 (s);
1653 if (r == s) {
1654 ret_v = s_v;
1656 else {
1657 ret_v = caml_copy_string (r);
1658 free (r);
1660 CAMLreturn (ret_v);
1663 static void * mainloop (void UNUSED_ATTR *unused)
1665 char *p = NULL;
1666 int len, ret, oldlen = 0;
1668 fz_var (p);
1669 fz_var (oldlen);
1670 for (;;) {
1671 len = readlen ();
1672 if (len == 0) {
1673 errx (1, "readlen returned 0");
1676 if (oldlen < len + 1) {
1677 p = realloc (p, len + 1);
1678 if (!p) {
1679 err (1, "realloc %d failed", len + 1);
1681 oldlen = len + 1;
1683 readdata (p, len);
1684 p[len] = 0;
1686 if (!strncmp ("open", p, 4)) {
1687 int wthack, off, ok = 0;
1688 char *password;
1689 char *filename;
1690 char *utf8filename;
1691 size_t filenamelen;
1693 fz_var (ok);
1694 ret = sscanf (p + 5, " %d %d %n", &wthack, &state.cxack, &off);
1695 if (ret != 2) {
1696 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1699 filename = p + 5 + off;
1700 filenamelen = strlen (filename);
1701 password = filename + filenamelen + 1;
1703 lock ("open");
1704 fz_try (state.ctx) {
1705 ok = openxref (filename, password);
1707 fz_catch (state.ctx) {
1708 utf8filename = mbtoutf8 (filename);
1709 printd ("msg Could not open %s", utf8filename);
1711 if (ok) {
1712 pdfinfo ();
1713 initpdims (wthack);
1715 unlock ("open");
1717 if (ok) {
1718 if (!wthack) {
1719 utf8filename = mbtoutf8 (filename);
1720 printd ("msg Opened %s (press h/F1 to get help)",
1721 utf8filename);
1722 if (utf8filename != filename) {
1723 free (utf8filename);
1726 state.needoutline = 1;
1729 else if (!strncmp ("cs", p, 2)) {
1730 int i, colorspace;
1732 ret = sscanf (p + 2, " %d", &colorspace);
1733 if (ret != 1) {
1734 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1736 lock ("cs");
1737 set_tex_params (colorspace);
1738 for (i = 0; i < state.texcount; ++i) {
1739 state.texowners[i].w = -1;
1740 state.texowners[i].slice = NULL;
1742 unlock ("cs");
1744 else if (!strncmp ("freepage", p, 8)) {
1745 void *ptr;
1747 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1748 if (ret != 1) {
1749 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1751 freepage (ptr);
1753 else if (!strncmp ("freetile", p, 8)) {
1754 void *ptr;
1756 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1757 if (ret != 1) {
1758 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1760 freetile (ptr);
1762 else if (!strncmp ("search", p, 6)) {
1763 int icase, pageno, y, len2, forward;
1764 char *pattern;
1765 regex_t re;
1767 ret = sscanf (p + 6, " %d %d %d %d,%n",
1768 &icase, &pageno, &y, &forward, &len2);
1769 if (ret != 4) {
1770 errx (1, "malformed search `%s' ret=%d", p, ret);
1773 pattern = p + 6 + len2;
1774 ret = regcomp (&re, pattern,
1775 REG_EXTENDED | (icase ? REG_ICASE : 0));
1776 if (ret) {
1777 char errbuf[80];
1778 size_t size;
1780 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1781 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1783 else {
1784 search (&re, pageno, y, forward);
1785 regfree (&re);
1788 else if (!strncmp ("geometry", p, 8)) {
1789 int w, h, fitmodel;
1791 printd ("clear");
1792 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1793 if (ret != 3) {
1794 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1797 lock ("geometry");
1798 state.h = h;
1799 if (w != state.w) {
1800 int i;
1801 state.w = w;
1802 for (i = 0; i < state.texcount; ++i) {
1803 state.texowners[i].slice = NULL;
1806 state.fitmodel = fitmodel;
1807 layout ();
1808 process_outline ();
1810 state.gen++;
1811 unlock ("geometry");
1812 printd ("continue %d", state.pagecount);
1814 else if (!strncmp ("reqlayout", p, 9)) {
1815 char *nameddest;
1816 int rotate, off, h;
1817 unsigned int fitmodel;
1818 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
1820 printd ("clear");
1821 ret = sscanf (p + 9, " %d %u %d %n",
1822 &rotate, &fitmodel, &h, &off);
1823 if (ret != 3) {
1824 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1826 lock ("reqlayout");
1827 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1828 state.gen += 1;
1830 state.rotate = rotate;
1831 state.fitmodel = fitmodel;
1832 state.h = h;
1833 layout ();
1834 process_outline ();
1836 nameddest = p + 9 + off;
1837 if (pdf && nameddest && *nameddest) {
1838 struct anchor a;
1839 fz_link_dest dest;
1840 pdf_obj *needle, *obj;
1842 needle = pdf_new_string (state.ctx, pdf, nameddest,
1843 strlen (nameddest));
1844 obj = pdf_lookup_dest (state.ctx, pdf, needle);
1845 if (obj) {
1846 dest = pdf_parse_link_dest (state.ctx, pdf,
1847 FZ_LINK_GOTO, obj);
1849 a = desttoanchor (&dest);
1850 if (a.n >= 0) {
1851 printd ("a %d %d %d", a.n, a.x, a.y);
1853 else {
1854 printd ("emsg failed to parse destination `%s'\n",
1855 nameddest);
1858 else {
1859 printd ("emsg destination `%s' not found\n",
1860 nameddest);
1862 pdf_drop_obj (state.ctx, needle);
1865 state.gen++;
1866 unlock ("reqlayout");
1867 printd ("continue %d", state.pagecount);
1869 else if (!strncmp ("page", p, 4)) {
1870 double a, b;
1871 struct page *page;
1872 int pageno, pindex;
1874 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1875 if (ret != 2) {
1876 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1879 lock ("page");
1880 a = now ();
1881 page = loadpage (pageno, pindex);
1882 b = now ();
1883 unlock ("page");
1885 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1887 else if (!strncmp ("tile", p, 4)) {
1888 int x, y, w, h;
1889 struct page *page;
1890 struct tile *tile;
1891 double a, b;
1892 void *data;
1894 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1895 SCN_ptr_cast (&page), &x, &y, &w, &h,
1896 SCN_ptr_cast (&data));
1897 if (ret != 6) {
1898 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1901 lock ("tile");
1902 a = now ();
1903 tile = rendertile (page, x, y, w, h, data);
1904 b = now ();
1905 unlock ("tile");
1907 printd ("tile %d %d %" FMT_ptr " %u %f",
1908 x, y,
1909 FMT_ptr_cast (tile),
1910 tile->w * tile->h * tile->pixmap->n,
1911 b - a);
1913 else if (!strncmp ("trimset", p, 7)) {
1914 fz_irect fuzz;
1915 int trimmargins;
1917 ret = sscanf (p + 7, " %d %d %d %d %d",
1918 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1919 if (ret != 5) {
1920 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1922 lock ("trimset");
1923 state.trimmargins = trimmargins;
1924 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1925 state.trimanew = 1;
1926 state.trimfuzz = fuzz;
1928 unlock ("trimset");
1930 else if (!strncmp ("settrim", p, 7)) {
1931 fz_irect fuzz;
1932 int trimmargins;
1934 ret = sscanf (p + 7, " %d %d %d %d %d",
1935 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1936 if (ret != 5) {
1937 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1939 printd ("clear");
1940 lock ("settrim");
1941 state.trimmargins = trimmargins;
1942 state.needoutline = 1;
1943 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1944 state.trimanew = 1;
1945 state.trimfuzz = fuzz;
1947 state.pagedimcount = 0;
1948 free (state.pagedims);
1949 state.pagedims = NULL;
1950 initpdims (0);
1951 layout ();
1952 process_outline ();
1953 unlock ("settrim");
1954 printd ("continue %d", state.pagecount);
1956 else if (!strncmp ("sliceh", p, 6)) {
1957 int h;
1959 ret = sscanf (p + 6, " %d", &h);
1960 if (ret != 1) {
1961 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1963 if (h != state.sliceheight) {
1964 int i;
1966 state.sliceheight = h;
1967 for (i = 0; i < state.texcount; ++i) {
1968 state.texowners[i].w = -1;
1969 state.texowners[i].h = -1;
1970 state.texowners[i].slice = NULL;
1974 else if (!strncmp ("interrupt", p, 9)) {
1975 printd ("vmsg interrupted");
1977 else {
1978 errx (1, "unknown command %.*s", len, p);
1981 return 0;
1984 CAMLprim value ml_realloctexts (value texcount_v)
1986 CAMLparam1 (texcount_v);
1987 int ok;
1989 if (trylock (__func__)) {
1990 ok = 0;
1991 goto done;
1993 realloctexts (Int_val (texcount_v));
1994 ok = 1;
1995 unlock (__func__);
1997 done:
1998 CAMLreturn (Val_bool (ok));
2001 static void recti (int x0, int y0, int x1, int y1)
2003 GLfloat *v = state.vertices;
2005 glVertexPointer (2, GL_FLOAT, 0, v);
2006 v[0] = x0; v[1] = y0;
2007 v[2] = x1; v[3] = y0;
2008 v[4] = x0; v[5] = y1;
2009 v[6] = x1; v[7] = y1;
2010 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2013 static void showsel (struct page *page, int ox, int oy)
2015 int seen = 0;
2016 fz_irect bbox;
2017 fz_rect rect;
2018 fz_stext_line *line;
2019 fz_page_block *pageb;
2020 fz_stext_block *block;
2021 struct mark first, last;
2022 unsigned char selcolor[] = {15,15,15,140};
2024 first = page->fmark;
2025 last = page->lmark;
2027 if (!first.span || !last.span) return;
2029 glEnable (GL_BLEND);
2030 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2031 glColor4ubv (selcolor);
2033 ox += state.pagedims[page->pdimno].bounds.x0;
2034 oy += state.pagedims[page->pdimno].bounds.y0;
2035 for (pageb = page->text->blocks;
2036 pageb < page->text->blocks + page->text->len;
2037 ++pageb) {
2038 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2039 block = pageb->u.text;
2041 for (line = block->lines;
2042 line < block->lines + block->len;
2043 ++line) {
2044 fz_stext_span *span;
2045 rect = fz_empty_rect;
2047 for (span = line->first_span; span; span = span->next) {
2048 int i, j, k;
2049 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2051 j = 0;
2052 k = span->len - 1;
2054 if (span == page->fmark.span && span == page->lmark.span) {
2055 seen = 1;
2056 j = MIN (first.i, last.i);
2057 k = MAX (first.i, last.i);
2059 else {
2060 if (span == first.span) {
2061 seen = 1;
2062 j = first.i;
2064 else if (span == last.span) {
2065 seen = 1;
2066 k = last.i;
2070 if (seen) {
2071 for (i = j; i <= k; ++i) {
2072 fz_rect bbox1;
2073 fz_union_rect (&rect,
2074 fz_stext_char_bbox (state.ctx, &bbox1,
2075 span, i));
2077 fz_round_rect (&bbox, &rect);
2078 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2079 bbox.x0,
2080 bbox.y0,
2081 bbox.x1,
2082 bbox.y1,
2083 oy, ox);
2085 recti (bbox.x0 + ox, bbox.y0 + oy,
2086 bbox.x1 + ox, bbox.y1 + oy);
2087 if (span == last.span) {
2088 goto done;
2090 rect = fz_empty_rect;
2095 done:
2096 glDisable (GL_BLEND);
2099 #include "glfont.c"
2101 static void stipplerect (fz_matrix *m,
2102 fz_point *p1,
2103 fz_point *p2,
2104 fz_point *p3,
2105 fz_point *p4,
2106 GLfloat *texcoords,
2107 GLfloat *vertices)
2109 fz_transform_point (p1, m);
2110 fz_transform_point (p2, m);
2111 fz_transform_point (p3, m);
2112 fz_transform_point (p4, m);
2114 float w, h, s, t;
2116 w = p2->x - p1->x;
2117 h = p2->y - p1->y;
2118 t = sqrtf (w*w + h*h) * .25f;
2120 w = p3->x - p2->x;
2121 h = p3->y - p2->y;
2122 s = sqrtf (w*w + h*h) * .25f;
2124 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2125 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2127 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2128 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2130 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2131 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2133 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2134 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2136 glDrawArrays (GL_LINES, 0, 8);
2139 static void solidrect (fz_matrix *m,
2140 fz_point *p1,
2141 fz_point *p2,
2142 fz_point *p3,
2143 fz_point *p4,
2144 GLfloat *vertices)
2146 fz_transform_point (p1, m);
2147 fz_transform_point (p2, m);
2148 fz_transform_point (p3, m);
2149 fz_transform_point (p4, m);
2150 vertices[0] = p1->x; vertices[1] = p1->y;
2151 vertices[2] = p2->x; vertices[3] = p2->y;
2153 vertices[4] = p3->x; vertices[5] = p3->y;
2154 vertices[6] = p4->x; vertices[7] = p4->y;
2155 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2158 static void highlightlinks (struct page *page, int xoff, int yoff)
2160 int i;
2161 fz_matrix ctm, tm, pm;
2162 fz_link *link, *links;
2163 GLfloat *texcoords = state.texcoords;
2164 GLfloat *vertices = state.vertices;
2166 links = fz_load_links (state.ctx, page->fzpage);
2168 glEnable (GL_TEXTURE_1D);
2169 glEnable (GL_BLEND);
2170 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2171 glBindTexture (GL_TEXTURE_1D, state.stid);
2173 xoff -= state.pagedims[page->pdimno].bounds.x0;
2174 yoff -= state.pagedims[page->pdimno].bounds.y0;
2175 fz_translate (&tm, xoff, yoff);
2176 pm = pagectm (page);
2177 fz_concat (&ctm, &pm, &tm);
2179 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2180 glVertexPointer (2, GL_FLOAT, 0, vertices);
2182 for (link = links; link; link = link->next) {
2183 fz_point p1, p2, p3, p4;
2185 p1.x = link->rect.x0;
2186 p1.y = link->rect.y0;
2188 p2.x = link->rect.x1;
2189 p2.y = link->rect.y0;
2191 p3.x = link->rect.x1;
2192 p3.y = link->rect.y1;
2194 p4.x = link->rect.x0;
2195 p4.y = link->rect.y1;
2197 switch (link->dest.kind) {
2198 case FZ_LINK_GOTO: glColor3ub (255, 0, 0); break;
2199 case FZ_LINK_URI: glColor3ub (0, 0, 255); break;
2200 case FZ_LINK_LAUNCH: glColor3ub (0, 255, 0); break;
2201 default: glColor3ub (0, 0, 0); break;
2203 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2206 for (i = 0; i < page->annotcount; ++i) {
2207 fz_point p1, p2, p3, p4;
2208 struct annot *annot = &page->annots[i];
2210 p1.x = annot->bbox.x0;
2211 p1.y = annot->bbox.y0;
2213 p2.x = annot->bbox.x1;
2214 p2.y = annot->bbox.y0;
2216 p3.x = annot->bbox.x1;
2217 p3.y = annot->bbox.y1;
2219 p4.x = annot->bbox.x0;
2220 p4.y = annot->bbox.y1;
2222 glColor3ub (0, 0, 128);
2223 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2226 glDisable (GL_BLEND);
2227 glDisable (GL_TEXTURE_1D);
2230 static int compareslinks (const void *l, const void *r)
2232 struct slink const *ls = l;
2233 struct slink const *rs = r;
2234 if (ls->bbox.y0 == rs->bbox.y0) {
2235 return rs->bbox.x0 - rs->bbox.x0;
2237 return ls->bbox.y0 - rs->bbox.y0;
2240 static void droptext (struct page *page)
2242 if (page->text) {
2243 fz_drop_stext_page (state.ctx, page->text);
2244 page->fmark.i = -1;
2245 page->lmark.i = -1;
2246 page->fmark.span = NULL;
2247 page->lmark.span = NULL;
2248 page->text = NULL;
2250 if (page->sheet) {
2251 fz_drop_stext_sheet (state.ctx, page->sheet);
2252 page->sheet = NULL;
2256 static void dropannots (struct page *page)
2258 if (page->annots) {
2259 free (page->annots);
2260 page->annots = NULL;
2261 page->annotcount = 0;
2265 static void ensureannots (struct page *page)
2267 int i, count = 0;
2268 size_t annotsize = sizeof (*page->annots);
2269 fz_annot *annot;
2271 if (state.gen != page->agen) {
2272 dropannots (page);
2273 page->agen = state.gen;
2275 if (page->annots) return;
2277 for (annot = fz_first_annot (state.ctx, page->fzpage);
2278 annot;
2279 annot = fz_next_annot (state.ctx, annot)) {
2280 count++;
2283 if (count > 0) {
2284 page->annotcount = count;
2285 page->annots = calloc (count, annotsize);
2286 if (!page->annots) {
2287 err (1, "calloc annots %d", count);
2290 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2291 annot;
2292 annot = fz_next_annot (state.ctx, annot), i++) {
2293 fz_rect rect;
2295 fz_bound_annot (state.ctx, annot, &rect);
2296 page->annots[i].annot = annot;
2297 fz_round_rect (&page->annots[i].bbox, &rect);
2302 static void dropslinks (struct page *page)
2304 if (page->slinks) {
2305 free (page->slinks);
2306 page->slinks = NULL;
2307 page->slinkcount = 0;
2311 static void ensureslinks (struct page *page)
2313 fz_matrix ctm;
2314 int i, count;
2315 size_t slinksize = sizeof (*page->slinks);
2316 fz_link *link, *links;
2318 ensureannots (page);
2319 if (state.gen != page->sgen) {
2320 dropslinks (page);
2321 page->sgen = state.gen;
2323 if (page->slinks) return;
2325 links = fz_load_links (state.ctx, page->fzpage);
2326 ctm = pagectm (page);
2328 count = page->annotcount;
2329 for (link = links; link; link = link->next) {
2330 count++;
2332 if (count > 0) {
2333 int j;
2335 page->slinkcount = count;
2336 page->slinks = calloc (count, slinksize);
2337 if (!page->slinks) {
2338 err (1, "calloc slinks %d", count);
2341 for (i = 0, link = links; link; ++i, link = link->next) {
2342 fz_rect rect;
2344 rect = link->rect;
2345 fz_transform_rect (&rect, &ctm);
2346 page->slinks[i].tag = SLINK;
2347 page->slinks[i].u.link = link;
2348 fz_round_rect (&page->slinks[i].bbox, &rect);
2350 for (j = 0; j < page->annotcount; ++j, ++i) {
2351 fz_rect rect;
2352 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2353 fz_transform_rect (&rect, &ctm);
2354 fz_round_rect (&page->slinks[i].bbox, &rect);
2356 page->slinks[i].tag = SANNOT;
2357 page->slinks[i].u.annot = page->annots[j].annot;
2359 qsort (page->slinks, count, slinksize, compareslinks);
2363 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2364 static void fmt_linkn (char *s, unsigned int u)
2366 unsigned int len; unsigned int q;
2367 unsigned int zma = 'z' - 'a' + 1;
2368 len = 1; q = u;
2369 while (q > zma - 1) { ++len; q /= zma; }
2370 if (s) {
2371 s += len;
2372 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2373 /* handles u == 0 */
2375 s[len] = 0;
2378 static void highlightslinks (struct page *page, int xoff, int yoff,
2379 int noff, char *targ, int tlen, int hfsize)
2381 int i;
2382 char buf[40];
2383 struct slink *slink;
2384 double x0, y0, x1, y1, w;
2386 ensureslinks (page);
2387 glColor3ub (0xc3, 0xb0, 0x91);
2388 for (i = 0; i < page->slinkcount; ++i) {
2389 fmt_linkn (buf, i + noff);
2390 if (!tlen || !strncmp (targ, buf, tlen)) {
2391 slink = &page->slinks[i];
2393 x0 = slink->bbox.x0 + xoff - 5;
2394 y1 = slink->bbox.y0 + yoff - 5;
2395 y0 = y1 + 10 + hfsize;
2396 w = measure_string (state.face, hfsize, buf);
2397 x1 = x0 + w + 10;
2398 recti (x0, y0, x1, y1);
2402 glEnable (GL_BLEND);
2403 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2404 glEnable (GL_TEXTURE_2D);
2405 glColor3ub (0, 0, 0);
2406 for (i = 0; i < page->slinkcount; ++i) {
2407 fmt_linkn (buf, i + noff);
2408 if (!tlen || !strncmp (targ, buf, tlen)) {
2409 slink = &page->slinks[i];
2411 x0 = slink->bbox.x0 + xoff;
2412 y0 = slink->bbox.y0 + yoff + hfsize;
2413 draw_string (state.face, hfsize, x0, y0, buf);
2416 glDisable (GL_TEXTURE_2D);
2417 glDisable (GL_BLEND);
2420 static void uploadslice (struct tile *tile, struct slice *slice)
2422 int offset;
2423 struct slice *slice1;
2424 unsigned char *texdata;
2426 offset = 0;
2427 for (slice1 = tile->slices; slice != slice1; slice1++) {
2428 offset += slice1->h * tile->w * tile->pixmap->n;
2430 if (slice->texindex != -1 && slice->texindex < state.texcount
2431 && state.texowners[slice->texindex].slice == slice) {
2432 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2434 else {
2435 int subimage = 0;
2436 int texindex = state.texindex++ % state.texcount;
2438 if (state.texowners[texindex].w == tile->w) {
2439 if (state.texowners[texindex].h >= slice->h) {
2440 subimage = 1;
2442 else {
2443 state.texowners[texindex].h = slice->h;
2446 else {
2447 state.texowners[texindex].h = slice->h;
2450 state.texowners[texindex].w = tile->w;
2451 state.texowners[texindex].slice = slice;
2452 slice->texindex = texindex;
2454 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2455 #if TEXT_TYPE == GL_TEXTURE_2D
2456 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2457 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2458 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2459 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2460 #endif
2461 if (tile->pbo) {
2462 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2463 texdata = 0;
2465 else {
2466 texdata = tile->pixmap->samples;
2468 if (subimage) {
2469 glTexSubImage2D (TEXT_TYPE,
2473 tile->w,
2474 slice->h,
2475 state.texform,
2476 state.texty,
2477 texdata+offset
2480 else {
2481 glTexImage2D (TEXT_TYPE,
2483 state.texiform,
2484 tile->w,
2485 slice->h,
2487 state.texform,
2488 state.texty,
2489 texdata+offset
2492 if (tile->pbo) {
2493 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2498 CAMLprim value ml_begintiles (value unit_v)
2500 CAMLparam1 (unit_v);
2501 glEnable (TEXT_TYPE);
2502 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2503 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2504 CAMLreturn (unit_v);
2507 CAMLprim value ml_endtiles (value unit_v)
2509 CAMLparam1 (unit_v);
2510 glDisable (TEXT_TYPE);
2511 CAMLreturn (unit_v);
2514 CAMLprim value ml_drawtile (value args_v, value ptr_v)
2516 CAMLparam2 (args_v, ptr_v);
2517 int dispx = Int_val (Field (args_v, 0));
2518 int dispy = Int_val (Field (args_v, 1));
2519 int dispw = Int_val (Field (args_v, 2));
2520 int disph = Int_val (Field (args_v, 3));
2521 int tilex = Int_val (Field (args_v, 4));
2522 int tiley = Int_val (Field (args_v, 5));
2523 char *s = String_val (ptr_v);
2524 struct tile *tile = parse_pointer (__func__, s);
2525 int slicey, firstslice;
2526 struct slice *slice;
2527 GLfloat *texcoords = state.texcoords;
2528 GLfloat *vertices = state.vertices;
2530 firstslice = tiley / tile->sliceheight;
2531 slice = &tile->slices[firstslice];
2532 slicey = tiley % tile->sliceheight;
2534 while (disph > 0) {
2535 int dh;
2537 dh = slice->h - slicey;
2538 dh = MIN (disph, dh);
2539 uploadslice (tile, slice);
2541 texcoords[0] = tilex; texcoords[1] = slicey;
2542 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2543 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2544 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2546 vertices[0] = dispx; vertices[1] = dispy;
2547 vertices[2] = dispx+dispw; vertices[3] = dispy;
2548 vertices[4] = dispx; vertices[5] = dispy+dh;
2549 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2551 #if TEXT_TYPE == GL_TEXTURE_2D
2552 for (int i = 0; i < 8; ++i) {
2553 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2555 #endif
2557 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2558 dispy += dh;
2559 disph -= dh;
2560 slice++;
2561 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2562 slicey = 0;
2564 CAMLreturn (Val_unit);
2567 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2569 fz_matrix ctm, tm, pm;
2570 fz_point p1, p2, p3, p4;
2571 GLfloat *vertices = state.vertices;
2572 double *v = (double *) rects_v;
2574 xoff -= state.pagedims[page->pdimno].bounds.x0;
2575 yoff -= state.pagedims[page->pdimno].bounds.y0;
2576 fz_translate (&tm, xoff, yoff);
2577 pm = pagectm (page);
2578 fz_concat (&ctm, &pm, &tm);
2580 glEnable (GL_BLEND);
2581 glVertexPointer (2, GL_FLOAT, 0, vertices);
2583 glColor4dv (v);
2584 p1.x = v[4];
2585 p1.y = v[5];
2587 p2.x = v[6];
2588 p2.y = v[5];
2590 p3.x = v[6];
2591 p3.y = v[7];
2593 p4.x = v[4];
2594 p4.y = v[7];
2595 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2596 glDisable (GL_BLEND);
2599 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2600 value xoff_v, value yoff_v,
2601 value li_v)
2603 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2604 int xoff = Int_val (xoff_v);
2605 int yoff = Int_val (yoff_v);
2606 int noff = Int_val (Field (li_v, 0));
2607 char *targ = String_val (Field (li_v, 1));
2608 int tlen = caml_string_length (Field (li_v, 1));
2609 int hfsize = Int_val (Field (li_v, 2));
2610 char *s = String_val (ptr_v);
2611 int hlmask = Int_val (hlinks_v);
2612 struct page *page = parse_pointer (__func__, s);
2614 if (!page->fzpage) {
2615 /* deal with loadpage failed pages */
2616 goto done;
2619 ensureannots (page);
2621 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2622 if (trylock (__func__)) {
2623 noff = 0;
2624 goto done;
2626 if (hlmask & 2) {
2627 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2628 noff = page->slinkcount;
2630 if (page->tgen == state.gen) {
2631 showsel (page, xoff, yoff);
2633 unlock (__func__);
2635 done:
2636 CAMLreturn (Val_int (noff));
2639 CAMLprim value ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2640 value rects_v)
2642 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2643 int xoff = Int_val (xoff_v);
2644 int yoff = Int_val (yoff_v);
2645 char *s = String_val (ptr_v);
2646 struct page *page = parse_pointer (__func__, s);
2648 drawprect (page, xoff, yoff, rects_v);
2649 CAMLreturn (Val_unit);
2652 static struct annot *getannot (struct page *page, int x, int y)
2654 int i;
2655 fz_point p;
2656 fz_matrix ctm;
2657 const fz_matrix *tctm;
2658 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2660 if (!page->annots) return NULL;
2662 if (pdf) {
2663 trimctm ((pdf_page *) page->fzpage, page->pdimno);
2664 tctm = &state.pagedims[page->pdimno].tctm;
2666 else {
2667 tctm = &fz_identity;
2670 p.x = x;
2671 p.y = y;
2673 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2674 fz_invert_matrix (&ctm, &ctm);
2675 fz_transform_point (&p, &ctm);
2677 if (pdf) {
2678 for (i = 0; i < page->annotcount; ++i) {
2679 struct annot *a = &page->annots[i];
2680 pdf_annot *annot = (pdf_annot *) a->annot;
2681 if (p.x >= annot->pagerect.x0 && p.x <= annot->pagerect.x1) {
2682 if (p.y >= annot->pagerect.y0 && p.y <= annot->pagerect.y1) {
2683 return a;
2688 return NULL;
2691 static fz_link *getlink (struct page *page, int x, int y)
2693 fz_point p;
2694 fz_matrix ctm;
2695 const fz_matrix *tctm;
2696 fz_link *link, *links;
2698 tctm = &fz_identity;
2699 links = fz_load_links (state.ctx, page->fzpage);
2701 p.x = x;
2702 p.y = y;
2704 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2705 fz_invert_matrix (&ctm, &ctm);
2706 fz_transform_point (&p, &ctm);
2708 for (link = links; link; link = link->next) {
2709 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2710 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2711 return link;
2715 return NULL;
2718 static void ensuretext (struct page *page)
2720 if (state.gen != page->tgen) {
2721 droptext (page);
2722 page->tgen = state.gen;
2724 if (!page->text) {
2725 fz_matrix ctm;
2726 fz_device *tdev;
2728 page->text = fz_new_stext_page (state.ctx);
2729 page->sheet = fz_new_stext_sheet (state.ctx);
2730 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text);
2731 ctm = pagectm (page);
2732 fz_begin_page (state.ctx, tdev, &fz_infinite_rect, &ctm);
2733 fz_run_display_list (state.ctx, page->dlist,
2734 tdev, &ctm, &fz_infinite_rect, NULL);
2735 qsort (page->text->blocks, page->text->len,
2736 sizeof (*page->text->blocks), compareblocks);
2737 fz_end_page (state.ctx, tdev);
2738 fz_drop_device (state.ctx, tdev);
2742 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2744 CAMLparam2 (start_page_v, dir_v);
2745 CAMLlocal1 (ret_v);
2746 int i, dir = Int_val (dir_v);
2747 int start_page = Int_val (start_page_v);
2748 int end_page = dir > 0 ? state.pagecount : -1;
2749 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2751 fz_var (end_page);
2752 ret_v = Val_int (0);
2753 lock (__func__);
2754 for (i = start_page + dir; i != end_page; i += dir) {
2755 int found;
2757 fz_var (found);
2758 if (pdf) {
2759 pdf_page *page = NULL;
2761 fz_try (state.ctx) {
2762 page = pdf_load_page (state.ctx, pdf, i);
2763 found = !!page->links || !!page->annots;
2765 fz_catch (state.ctx) {
2766 found = 0;
2768 if (page) {
2769 fz_drop_page (state.ctx, &page->super);
2772 else {
2773 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2774 found = !!fz_load_links (state.ctx, page);
2775 fz_drop_page (state.ctx, page);
2778 if (found) {
2779 ret_v = caml_alloc_small (1, 1);
2780 Field (ret_v, 0) = Val_int (i);
2781 goto unlock;
2784 unlock:
2785 unlock (__func__);
2786 CAMLreturn (ret_v);
2789 enum { dir_first, dir_last };
2790 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2792 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2794 CAMLparam2 (ptr_v, dir_v);
2795 CAMLlocal2 (ret_v, pos_v);
2796 struct page *page;
2797 int dirtag, i, slinkindex;
2798 struct slink *found = NULL ,*slink;
2799 char *s = String_val (ptr_v);
2801 page = parse_pointer (__func__, s);
2802 ret_v = Val_int (0);
2803 /* This is scary we are not taking locks here ensureslinks does
2804 not modify state and given that we obtained the page it can not
2805 disappear under us either */
2806 lock (__func__);
2807 ensureslinks (page);
2809 if (Is_block (dir_v)) {
2810 dirtag = Tag_val (dir_v);
2811 switch (dirtag) {
2812 case dir_first_visible:
2814 int x0, y0, dir, first_index, last_index;
2816 pos_v = Field (dir_v, 0);
2817 x0 = Int_val (Field (pos_v, 0));
2818 y0 = Int_val (Field (pos_v, 1));
2819 dir = Int_val (Field (pos_v, 2));
2821 if (dir >= 0) {
2822 dir = 1;
2823 first_index = 0;
2824 last_index = page->slinkcount;
2826 else {
2827 first_index = page->slinkcount - 1;
2828 last_index = -1;
2831 for (i = first_index; i != last_index; i += dir) {
2832 slink = &page->slinks[i];
2833 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2834 found = slink;
2835 break;
2839 break;
2841 case dir_left:
2842 slinkindex = Int_val (Field (dir_v, 0));
2843 found = &page->slinks[slinkindex];
2844 for (i = slinkindex - 1; i >= 0; --i) {
2845 slink = &page->slinks[i];
2846 if (slink->bbox.x0 < found->bbox.x0) {
2847 found = slink;
2848 break;
2851 break;
2853 case dir_right:
2854 slinkindex = Int_val (Field (dir_v, 0));
2855 found = &page->slinks[slinkindex];
2856 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2857 slink = &page->slinks[i];
2858 if (slink->bbox.x0 > found->bbox.x0) {
2859 found = slink;
2860 break;
2863 break;
2865 case dir_down:
2866 slinkindex = Int_val (Field (dir_v, 0));
2867 found = &page->slinks[slinkindex];
2868 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2869 slink = &page->slinks[i];
2870 if (slink->bbox.y0 >= found->bbox.y0) {
2871 found = slink;
2872 break;
2875 break;
2877 case dir_up:
2878 slinkindex = Int_val (Field (dir_v, 0));
2879 found = &page->slinks[slinkindex];
2880 for (i = slinkindex - 1; i >= 0; --i) {
2881 slink = &page->slinks[i];
2882 if (slink->bbox.y0 <= found->bbox.y0) {
2883 found = slink;
2884 break;
2887 break;
2890 else {
2891 dirtag = Int_val (dir_v);
2892 switch (dirtag) {
2893 case dir_first:
2894 found = page->slinks;
2895 break;
2897 case dir_last:
2898 if (page->slinks) {
2899 found = page->slinks + (page->slinkcount - 1);
2901 break;
2904 if (found) {
2905 ret_v = caml_alloc_small (2, 1);
2906 Field (ret_v, 0) = Val_int (found - page->slinks);
2909 unlock (__func__);
2910 CAMLreturn (ret_v);
2913 enum { uuri, ugoto, utext, uunexpected, ulaunch,
2914 unamed, uremote, uremotedest, uannot };
2916 #define LINKTOVAL \
2918 int pageno; \
2920 switch (link->dest.kind) { \
2921 case FZ_LINK_GOTO: \
2923 fz_point p; \
2925 pageno = link->dest.ld.gotor.page; \
2926 p.x = 0; \
2927 p.y = 0; \
2929 if (link->dest.ld.gotor.flags & fz_link_flag_t_valid) { \
2930 p.y = link->dest.ld.gotor.lt.y; \
2931 fz_transform_point (&p, &pdim->lctm); \
2932 if (p.y < 0) p.y = 0; \
2934 tup_v = caml_alloc_tuple (2); \
2935 ret_v = caml_alloc_small (1, ugoto); \
2936 Field (tup_v, 0) = Val_int (pageno); \
2937 Field (tup_v, 1) = Val_int (p.y); \
2938 Field (ret_v, 0) = tup_v; \
2940 break; \
2942 case FZ_LINK_URI: \
2943 str_v = caml_copy_string (link->dest.ld.uri.uri); \
2944 ret_v = caml_alloc_small (1, uuri); \
2945 Field (ret_v, 0) = str_v; \
2946 break; \
2948 case FZ_LINK_LAUNCH: \
2949 str_v = caml_copy_string (link->dest.ld.launch.file_spec); \
2950 ret_v = caml_alloc_small (1, ulaunch); \
2951 Field (ret_v, 0) = str_v; \
2952 break; \
2954 case FZ_LINK_NAMED: \
2955 str_v = caml_copy_string (link->dest.ld.named.named); \
2956 ret_v = caml_alloc_small (1, unamed); \
2957 Field (ret_v, 0) = str_v; \
2958 break; \
2960 case FZ_LINK_GOTOR: \
2962 int rty; \
2964 str_v = caml_copy_string (link->dest.ld.gotor.file_spec); \
2965 pageno = link->dest.ld.gotor.page; \
2966 if (pageno == -1) { \
2967 gr_v = caml_copy_string (link->dest.ld.gotor.dest); \
2968 rty = uremotedest; \
2970 else { \
2971 gr_v = Val_int (pageno); \
2972 rty = uremote; \
2974 tup_v = caml_alloc_tuple (2); \
2975 ret_v = caml_alloc_small (1, rty); \
2976 Field (tup_v, 0) = str_v; \
2977 Field (tup_v, 1) = gr_v; \
2978 Field (ret_v, 0) = tup_v; \
2980 break; \
2982 default: \
2984 char buf[80]; \
2986 snprintf (buf, sizeof (buf), \
2987 "unhandled link kind %d", link->dest.kind); \
2988 str_v = caml_copy_string (buf); \
2989 ret_v = caml_alloc_small (1, uunexpected); \
2990 Field (ret_v, 0) = str_v; \
2992 break; \
2996 CAMLprim value ml_getlink (value ptr_v, value n_v)
2998 CAMLparam2 (ptr_v, n_v);
2999 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3000 fz_link *link;
3001 struct page *page;
3002 struct pagedim *pdim;
3003 char *s = String_val (ptr_v);
3004 struct slink *slink;
3006 /* See ml_findlink for caveat */
3008 ret_v = Val_int (0);
3009 page = parse_pointer (__func__, s);
3010 ensureslinks (page);
3011 pdim = &state.pagedims[page->pdimno];
3012 slink = &page->slinks[Int_val (n_v)];
3013 if (slink->tag == SLINK) {
3014 link = slink->u.link;
3015 LINKTOVAL;
3017 else {
3018 ret_v = caml_alloc_small (1, uannot);
3019 tup_v = caml_alloc_tuple (2);
3020 Field (ret_v, 0) = tup_v;
3021 Field (tup_v, 0) = ptr_v;
3022 Field (tup_v, 1) = n_v;
3025 CAMLreturn (ret_v);
3028 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
3030 CAMLparam2 (ptr_v, n_v);
3031 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3032 if (pdf) {
3033 char *s = String_val (ptr_v);
3034 struct page *page;
3035 struct slink *slink;
3037 page = parse_pointer (__func__, s);
3038 slink = &page->slinks[Int_val (n_v)];
3039 CAMLreturn (caml_copy_string (
3040 pdf_annot_contents (state.ctx, pdf,
3041 (pdf_annot *) slink->u.annot)));
3043 else {
3044 CAMLreturn (caml_copy_string (""));
3048 CAMLprim value ml_getlinkcount (value ptr_v)
3050 CAMLparam1 (ptr_v);
3051 struct page *page;
3052 char *s = String_val (ptr_v);
3054 page = parse_pointer (__func__, s);
3055 CAMLreturn (Val_int (page->slinkcount));
3058 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
3060 CAMLparam2 (ptr_v, n_v);
3061 CAMLlocal1 (ret_v);
3062 struct page *page;
3063 struct slink *slink;
3064 char *s = String_val (ptr_v);
3065 /* See ml_findlink for caveat */
3067 page = parse_pointer (__func__, s);
3068 ret_v = caml_alloc_tuple (4);
3069 ensureslinks (page);
3071 slink = &page->slinks[Int_val (n_v)];
3072 Field (ret_v, 0) = Val_int (slink->bbox.x0);
3073 Field (ret_v, 1) = Val_int (slink->bbox.y0);
3074 Field (ret_v, 2) = Val_int (slink->bbox.x1);
3075 Field (ret_v, 3) = Val_int (slink->bbox.y1);
3076 unlock (__func__);
3077 CAMLreturn (ret_v);
3080 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
3082 CAMLparam3 (ptr_v, x_v, y_v);
3083 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
3084 fz_link *link;
3085 struct annot *annot;
3086 struct page *page;
3087 char *ptr = String_val (ptr_v);
3088 int x = Int_val (x_v), y = Int_val (y_v);
3089 struct pagedim *pdim;
3091 ret_v = Val_int (0);
3092 if (trylock (__func__)) {
3093 goto done;
3096 page = parse_pointer (__func__, ptr);
3097 pdim = &state.pagedims[page->pdimno];
3098 x += pdim->bounds.x0;
3099 y += pdim->bounds.y0;
3102 annot = getannot (page, x, y);
3103 if (annot) {
3104 int i, n = -1;
3106 ensureslinks (page);
3107 for (i = 0; i < page->slinkcount; ++i) {
3108 if (page->slinks[i].tag == SANNOT
3109 && page->slinks[i].u.annot == annot->annot) {
3110 n = i;
3111 break;
3114 ret_v = caml_alloc_small (1, uannot);
3115 tup_v = caml_alloc_tuple (2);
3116 Field (ret_v, 0) = tup_v;
3117 Field (tup_v, 0) = ptr_v;
3118 Field (tup_v, 1) = Val_int (n);
3119 goto unlock;
3123 link = getlink (page, x, y);
3124 if (link) {
3125 LINKTOVAL;
3127 else {
3128 fz_rect *b;
3129 fz_page_block *pageb;
3130 fz_stext_block *block;
3132 ensuretext (page);
3133 for (pageb = page->text->blocks;
3134 pageb < page->text->blocks + page->text->len;
3135 ++pageb) {
3136 fz_stext_line *line;
3137 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3138 block = pageb->u.text;
3140 b = &block->bbox;
3141 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3142 continue;
3144 for (line = block->lines;
3145 line < block->lines + block->len;
3146 ++line) {
3147 fz_stext_span *span;
3149 b = &line->bbox;
3150 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3151 continue;
3153 for (span = line->first_span; span; span = span->next) {
3154 int charnum;
3156 b = &span->bbox;
3157 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3158 continue;
3160 for (charnum = 0; charnum < span->len; ++charnum) {
3161 fz_rect bbox;
3162 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3163 b = &bbox;
3165 if (x >= b->x0 && x <= b->x1
3166 && y >= b->y0 && y <= b->y1) {
3167 fz_stext_style *style = span->text->style;
3168 const char *n2 =
3169 style->font
3170 ? style->font->name
3171 : "Span has no font name"
3173 FT_FaceRec *face = style->font->ft_face;
3174 if (face && face->family_name) {
3175 char *s;
3176 char *n1 = face->family_name;
3177 size_t l1 = strlen (n1);
3178 size_t l2 = strlen (n2);
3180 if (l1 != l2 || memcmp (n1, n2, l1)) {
3181 s = malloc (l1 + l2 + 2);
3182 if (s) {
3183 memcpy (s, n2, l2);
3184 s[l2] = '=';
3185 memcpy (s + l2 + 1, n1, l1 + 1);
3186 str_v = caml_copy_string (s);
3187 free (s);
3191 if (str_v == Val_unit) {
3192 str_v = caml_copy_string (n2);
3194 ret_v = caml_alloc_small (1, utext);
3195 Field (ret_v, 0) = str_v;
3196 goto unlock;
3203 unlock:
3204 unlock (__func__);
3206 done:
3207 CAMLreturn (ret_v);
3210 enum { mark_page, mark_block, mark_line, mark_word };
3212 static int uninteresting (int c)
3214 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3215 || ispunct (c);
3218 CAMLprim value ml_clearmark (value ptr_v)
3220 CAMLparam1 (ptr_v);
3221 char *s = String_val (ptr_v);
3222 struct page *page;
3224 if (trylock (__func__)) {
3225 goto done;
3228 page = parse_pointer (__func__, s);
3229 page->fmark.span = NULL;
3230 page->lmark.span = NULL;
3231 page->fmark.i = 0;
3232 page->lmark.i = 0;
3234 unlock (__func__);
3235 done:
3236 CAMLreturn (Val_unit);
3239 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3241 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3242 CAMLlocal1 (ret_v);
3243 fz_rect *b;
3244 struct page *page;
3245 fz_stext_line *line;
3246 fz_page_block *pageb;
3247 fz_stext_block *block;
3248 struct pagedim *pdim;
3249 int mark = Int_val (mark_v);
3250 char *s = String_val (ptr_v);
3251 int x = Int_val (x_v), y = Int_val (y_v);
3253 ret_v = Val_bool (0);
3254 if (trylock (__func__)) {
3255 goto done;
3258 page = parse_pointer (__func__, s);
3259 pdim = &state.pagedims[page->pdimno];
3261 ensuretext (page);
3263 if (mark == mark_page) {
3264 int i;
3265 fz_page_block *pb1 = NULL, *pb2 = NULL;
3267 for (i = 0; i < page->text->len; ++i) {
3268 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3269 pb1 = &page->text->blocks[i];
3270 break;
3273 if (!pb1) goto unlock;
3275 for (i = page->text->len - 1; i >= 0; --i) {
3276 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3277 pb2 = &page->text->blocks[i];
3278 break;
3281 if (!pb2) goto unlock;
3283 block = pb1->u.text;
3285 page->fmark.i = 0;
3286 page->fmark.span = block->lines->first_span;
3288 block = pb2->u.text;
3289 line = &block->lines[block->len - 1];
3290 page->lmark.i = line->last_span->len - 1;
3291 page->lmark.span = line->last_span;
3292 ret_v = Val_bool (1);
3293 goto unlock;
3296 x += pdim->bounds.x0;
3297 y += pdim->bounds.y0;
3299 for (pageb = page->text->blocks;
3300 pageb < page->text->blocks + page->text->len;
3301 ++pageb) {
3302 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3303 block = pageb->u.text;
3305 b = &block->bbox;
3306 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3307 continue;
3309 if (mark == mark_block) {
3310 page->fmark.i = 0;
3311 page->fmark.span = block->lines->first_span;
3313 line = &block->lines[block->len - 1];
3314 page->lmark.i = line->last_span->len - 1;
3315 page->lmark.span = line->last_span;
3316 ret_v = Val_bool (1);
3317 goto unlock;
3320 for (line = block->lines;
3321 line < block->lines + block->len;
3322 ++line) {
3323 fz_stext_span *span;
3325 b = &line->bbox;
3326 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3327 continue;
3329 if (mark == mark_line) {
3330 page->fmark.i = 0;
3331 page->fmark.span = line->first_span;
3333 page->lmark.i = line->last_span->len - 1;
3334 page->lmark.span = line->last_span;
3335 ret_v = Val_bool (1);
3336 goto unlock;
3339 for (span = line->first_span; span; span = span->next) {
3340 int charnum;
3342 b = &span->bbox;
3343 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3344 continue;
3346 for (charnum = 0; charnum < span->len; ++charnum) {
3347 fz_rect bbox;
3348 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3349 b = &bbox;
3351 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3352 /* unicode ftw */
3353 int charnum2, charnum3 = -1, charnum4 = -1;
3355 if (uninteresting (span->text[charnum].c)) goto unlock;
3357 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3358 if (uninteresting (span->text[charnum2].c)) {
3359 charnum3 = charnum2 + 1;
3360 break;
3363 if (charnum3 == -1) charnum3 = 0;
3365 for (charnum2 = charnum + 1;
3366 charnum2 < span->len;
3367 ++charnum2) {
3368 if (uninteresting (span->text[charnum2].c)) break;
3369 charnum4 = charnum2;
3371 if (charnum4 == -1) goto unlock;
3373 page->fmark.i = charnum3;
3374 page->fmark.span = span;
3376 page->lmark.i = charnum4;
3377 page->lmark.span = span;
3378 ret_v = Val_bool (1);
3379 goto unlock;
3385 unlock:
3386 if (!Bool_val (ret_v)) {
3387 page->fmark.span = NULL;
3388 page->lmark.span = NULL;
3389 page->fmark.i = 0;
3390 page->lmark.i = 0;
3392 unlock (__func__);
3394 done:
3395 CAMLreturn (ret_v);
3398 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3400 CAMLparam3 (ptr_v, x_v, y_v);
3401 CAMLlocal2 (ret_v, res_v);
3402 fz_rect *b = NULL;
3403 struct page *page;
3404 fz_page_block *pageb;
3405 struct pagedim *pdim;
3406 char *s = String_val (ptr_v);
3407 int x = Int_val (x_v), y = Int_val (y_v);
3409 ret_v = Val_int (0);
3410 if (trylock (__func__)) {
3411 goto done;
3414 page = parse_pointer (__func__, s);
3415 pdim = &state.pagedims[page->pdimno];
3416 x += pdim->bounds.x0;
3417 y += pdim->bounds.y0;
3419 ensuretext (page);
3421 for (pageb = page->text->blocks;
3422 pageb < page->text->blocks + page->text->len;
3423 ++pageb) {
3424 switch (pageb->type) {
3425 case FZ_PAGE_BLOCK_TEXT:
3426 b = &pageb->u.text->bbox;
3427 break;
3429 case FZ_PAGE_BLOCK_IMAGE:
3430 b = &pageb->u.image->bbox;
3431 break;
3433 default:
3434 continue;
3437 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3438 break;
3439 b = NULL;
3441 if (b) {
3442 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3443 ret_v = caml_alloc_small (1, 1);
3444 Store_double_field (res_v, 0, b->x0);
3445 Store_double_field (res_v, 1, b->x1);
3446 Store_double_field (res_v, 2, b->y0);
3447 Store_double_field (res_v, 3, b->y1);
3448 Field (ret_v, 0) = res_v;
3450 unlock (__func__);
3452 done:
3453 CAMLreturn (ret_v);
3456 CAMLprim value ml_seltext (value ptr_v, value rect_v)
3458 CAMLparam2 (ptr_v, rect_v);
3459 fz_rect b;
3460 struct page *page;
3461 struct pagedim *pdim;
3462 char *s = String_val (ptr_v);
3463 int i, x0, x1, y0, y1, fi, li;
3464 fz_stext_line *line;
3465 fz_page_block *pageb;
3466 fz_stext_block *block;
3467 fz_stext_span *span, *fspan, *lspan;
3469 if (trylock (__func__)) {
3470 goto done;
3473 page = parse_pointer (__func__, s);
3474 ensuretext (page);
3476 pdim = &state.pagedims[page->pdimno];
3477 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3478 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3479 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3480 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3482 if (y0 > y1) {
3483 int t = y0;
3484 y0 = y1;
3485 y1 = t;
3486 x0 = x1;
3487 x1 = t;
3490 fi = page->fmark.i;
3491 fspan = page->fmark.span;
3493 li = page->lmark.i;
3494 lspan = page->lmark.span;
3496 for (pageb = page->text->blocks;
3497 pageb < page->text->blocks + page->text->len;
3498 ++pageb) {
3499 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3500 block = pageb->u.text;
3501 for (line = block->lines;
3502 line < block->lines + block->len;
3503 ++line) {
3505 for (span = line->first_span; span; span = span->next) {
3506 for (i = 0; i < span->len; ++i) {
3507 fz_stext_char_bbox (state.ctx, &b, span, i);
3509 if (x0 >= b.x0 && x0 <= b.x1
3510 && y0 >= b.y0 && y0 <= b.y1) {
3511 fspan = span;
3512 fi = i;
3514 if (x1 >= b.x0 && x1 <= b.x1
3515 && y1 >= b.y0 && y1 <= b.y1) {
3516 lspan = span;
3517 li = i;
3523 if (x1 < x0 && fspan == lspan) {
3524 i = fi;
3525 span = fspan;
3527 fi = li;
3528 fspan = lspan;
3530 li = i;
3531 lspan = span;
3534 page->fmark.i = fi;
3535 page->fmark.span = fspan;
3537 page->lmark.i = li;
3538 page->lmark.span = lspan;
3540 unlock (__func__);
3542 done:
3543 CAMLreturn (Val_unit);
3546 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3548 char buf[4];
3549 int i, len, ret;
3551 for (i = a; i <= b; ++i) {
3552 len = fz_runetochar (buf, span->text[i].c);
3553 ret = fwrite (buf, len, 1, f);
3555 if (ret != 1) {
3556 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3557 len, ret, strerror (errno));
3558 return -1;
3561 return 0;
3564 #ifdef __CYGWIN__
3565 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3567 caml_failwith ("ml_popen not implemented under Cygwin");
3569 #else
3570 CAMLprim value ml_spawn (value command_v, value fds_v)
3572 CAMLparam2 (command_v, fds_v);
3573 CAMLlocal2 (l_v, tup_v);
3574 int ret, ret1;
3575 pid_t pid;
3576 char *msg = NULL;
3577 value earg_v = Nothing;
3578 posix_spawnattr_t attr;
3579 posix_spawn_file_actions_t fa;
3580 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3582 argv[2] = String_val (command_v);
3584 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3585 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3588 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3589 msg = "posix_spawnattr_init";
3590 goto fail1;
3593 #ifdef POSIX_SPAWN_USEVFORK
3594 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3595 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3596 goto fail;
3598 #endif
3600 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3601 int fd1, fd2;
3603 tup_v = Field (l_v, 0);
3604 fd1 = Int_val (Field (tup_v, 0));
3605 fd2 = Int_val (Field (tup_v, 1));
3606 if (fd2 < 0) {
3607 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3608 msg = "posix_spawn_file_actions_addclose";
3609 earg_v = tup_v;
3610 goto fail;
3613 else {
3614 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3615 msg = "posix_spawn_file_actions_adddup2";
3616 earg_v = tup_v;
3617 goto fail;
3622 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3623 msg = "posix_spawn";
3624 goto fail;
3627 fail:
3628 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3629 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3632 fail1:
3633 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3634 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3635 strerror (ret1));
3638 if (msg)
3639 unix_error (ret, msg, earg_v);
3641 CAMLreturn (Val_int (pid));
3643 #endif
3645 CAMLprim value ml_hassel (value ptr_v)
3647 CAMLparam1 (ptr_v);
3648 CAMLlocal1 (ret_v);
3649 struct page *page;
3650 char *s = String_val (ptr_v);
3652 ret_v = Val_bool (0);
3653 if (trylock (__func__)) {
3654 goto done;
3657 page = parse_pointer (__func__, s);
3658 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3659 unlock (__func__);
3660 done:
3661 CAMLreturn (ret_v);
3664 CAMLprim value ml_copysel (value fd_v, value ptr_v)
3666 CAMLparam2 (fd_v, ptr_v);
3667 FILE *f;
3668 int seen = 0;
3669 struct page *page;
3670 fz_stext_line *line;
3671 fz_page_block *pageb;
3672 fz_stext_block *block;
3673 int fd = Int_val (fd_v);
3674 char *s = String_val (ptr_v);
3676 if (trylock (__func__)) {
3677 goto done;
3680 page = parse_pointer (__func__, s);
3682 if (!page->fmark.span || !page->lmark.span) {
3683 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3684 goto unlock;
3687 f = fdopen (fd, "w");
3688 if (!f) {
3689 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3690 fd, strerror (errno));
3691 f = stdout;
3694 for (pageb = page->text->blocks;
3695 pageb < page->text->blocks + page->text->len;
3696 ++pageb) {
3697 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3698 block = pageb->u.text;
3699 for (line = block->lines;
3700 line < block->lines + block->len;
3701 ++line) {
3702 fz_stext_span *span;
3704 for (span = line->first_span; span; span = span->next) {
3705 int a, b;
3707 seen |= span == page->fmark.span || span == page->lmark.span;
3708 a = span == page->fmark.span ? page->fmark.i : 0;
3709 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3711 if (seen) {
3712 if (pipespan (f, span, a, b)) {
3713 goto close;
3715 if (span == page->lmark.span) {
3716 goto close;
3718 if (span == line->last_span) {
3719 if (putc ('\n', f) == EOF) {
3720 fprintf (stderr,
3721 "failed break line on sel pipe: %s\n",
3722 strerror (errno));
3723 goto close;
3730 close:
3731 if (f != stdout) {
3732 int ret = fclose (f);
3733 fd = -1;
3734 if (ret == -1) {
3735 if (errno != ECHILD) {
3736 fprintf (stderr, "failed to close sel pipe: %s\n",
3737 strerror (errno));
3741 unlock:
3742 unlock (__func__);
3744 done:
3745 if (fd >= 0) {
3746 if (close (fd)) {
3747 fprintf (stderr, "failed to close sel pipe: %s\n",
3748 strerror (errno));
3751 CAMLreturn (Val_unit);
3754 CAMLprim value ml_getpdimrect (value pagedimno_v)
3756 CAMLparam1 (pagedimno_v);
3757 CAMLlocal1 (ret_v);
3758 int pagedimno = Int_val (pagedimno_v);
3759 fz_rect box;
3761 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3762 if (trylock (__func__)) {
3763 box = fz_empty_rect;
3765 else {
3766 box = state.pagedims[pagedimno].mediabox;
3767 unlock (__func__);
3770 Store_double_field (ret_v, 0, box.x0);
3771 Store_double_field (ret_v, 1, box.x1);
3772 Store_double_field (ret_v, 2, box.y0);
3773 Store_double_field (ret_v, 3, box.y1);
3775 CAMLreturn (ret_v);
3778 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3779 value dw_v, value cols_v)
3781 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3782 CAMLlocal1 (ret_v);
3783 int i;
3784 double zoom = -1.;
3785 double maxh = 0.0;
3786 struct pagedim *p;
3787 double winw = Int_val (winw_v);
3788 double winh = Int_val (winh_v);
3789 double dw = Int_val (dw_v);
3790 double cols = Int_val (cols_v);
3791 double pw = 1.0, ph = 1.0;
3793 if (trylock (__func__)) {
3794 goto done;
3797 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3798 double w = p->pagebox.x1 / cols;
3799 double h = p->pagebox.y1;
3800 if (h > maxh) {
3801 maxh = h;
3802 ph = h;
3803 if (state.fitmodel != FitProportional) pw = w;
3805 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3808 zoom = (((winh / ph) * pw) + dw) / winw;
3809 unlock (__func__);
3810 done:
3811 ret_v = caml_copy_double (zoom);
3812 CAMLreturn (ret_v);
3815 CAMLprim value ml_getmaxw (value unit_v)
3817 CAMLparam1 (unit_v);
3818 CAMLlocal1 (ret_v);
3819 int i;
3820 double maxw = -1.;
3821 struct pagedim *p;
3823 if (trylock (__func__)) {
3824 goto done;
3827 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3828 double w = p->pagebox.x1;
3829 maxw = MAX (maxw, w);
3832 unlock (__func__);
3833 done:
3834 ret_v = caml_copy_double (maxw);
3835 CAMLreturn (ret_v);
3838 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3840 CAMLparam4 (pt_v, x_v, y_v, string_v);
3841 CAMLlocal1 (ret_v);
3842 int pt = Int_val(pt_v);
3843 int x = Int_val (x_v);
3844 int y = Int_val (y_v);
3845 double w;
3847 w = draw_string (state.face, pt, x, y, String_val (string_v));
3848 ret_v = caml_copy_double (w);
3849 CAMLreturn (ret_v);
3852 CAMLprim value ml_measure_string (value pt_v, value string_v)
3854 CAMLparam2 (pt_v, string_v);
3855 CAMLlocal1 (ret_v);
3856 int pt = Int_val (pt_v);
3857 double w;
3859 w = measure_string (state.face, pt, String_val (string_v));
3860 ret_v = caml_copy_double (w);
3861 CAMLreturn (ret_v);
3864 CAMLprim value ml_getpagebox (value opaque_v)
3866 CAMLparam1 (opaque_v);
3867 CAMLlocal1 (ret_v);
3868 fz_rect rect;
3869 fz_irect bbox;
3870 fz_matrix ctm;
3871 fz_device *dev;
3872 char *s = String_val (opaque_v);
3873 struct page *page = parse_pointer (__func__, s);
3875 ret_v = caml_alloc_tuple (4);
3876 dev = fz_new_bbox_device (state.ctx, &rect);
3877 dev->hints |= FZ_IGNORE_SHADE;
3879 ctm = pagectm (page);
3880 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3882 fz_drop_device (state.ctx, dev);
3883 fz_round_rect (&bbox, &rect);
3884 Field (ret_v, 0) = Val_int (bbox.x0);
3885 Field (ret_v, 1) = Val_int (bbox.y0);
3886 Field (ret_v, 2) = Val_int (bbox.x1);
3887 Field (ret_v, 3) = Val_int (bbox.y1);
3889 CAMLreturn (ret_v);
3892 CAMLprim value ml_setaalevel (value level_v)
3894 CAMLparam1 (level_v);
3896 state.aalevel = Int_val (level_v);
3897 CAMLreturn (Val_unit);
3900 #pragma GCC diagnostic push
3901 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3902 #include <X11/Xlib.h>
3903 #include <X11/cursorfont.h>
3904 #pragma GCC diagnostic pop
3906 #ifdef USE_EGL
3907 #include <EGL/egl.h>
3908 #else
3909 #include <GL/glx.h>
3910 #endif
3912 static const int shapes[] = {
3913 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3916 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3918 static struct {
3919 Window wid;
3920 Display *dpy;
3921 #ifdef USE_EGL
3922 EGLContext ctx;
3923 EGLConfig conf;
3924 EGLSurface win;
3925 EGLDisplay *edpy;
3926 #else
3927 GLXContext ctx;
3928 #endif
3929 XVisualInfo *visual;
3930 Cursor curs[CURS_COUNT];
3931 } glx;
3933 #ifdef VISAVIS
3934 static VisualID initvisual (void)
3936 /* On this system with: `Haswell-ULT Integrated Graphics
3937 Controller' and Mesa 11.0.6; perf stat reports [1] that when
3938 using glX chosen visual and auto scrolling some document in
3939 fullscreen the power/energy-gpu is more than 1 joule bigger
3940 than when using hand picked visual that stands alone in glxinfo
3941 output: it's dead last in the list and it's the only one with
3942 `visual dep' (sic) of 32
3944 No clue what's going on here...
3946 [1] perf stat -a -I 1200 -e "power/energy-gpu/"
3948 XVisualInfo info;
3949 int ret = 1;
3951 info.depth = 32;
3952 info.class = TrueColor;
3953 glx.visual = XGetVisualInfo (glx.dpy, VisualDepthMask | VisualClassMask,
3954 &info, &ret);
3955 if (!ret || !glx.visual) {
3956 XCloseDisplay (glx.dpy);
3957 caml_failwith ("XGetVisualInfo");
3959 return glx.visual->visualid;
3961 #endif
3963 static void initcurs (void)
3965 for (size_t n = 0; n < CURS_COUNT; ++n) {
3966 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3970 CAMLprim void ml_setbgcol (value color_v)
3972 CAMLparam1 (color_v);
3973 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3974 CAMLreturn0;
3977 #ifdef USE_EGL
3978 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3980 CAMLparam3 (display_v, wid_v, screen_v);
3981 int major, minor;
3982 int num_conf;
3983 EGLint visid;
3984 EGLint attribs[] = {
3985 #ifdef VISAVIS
3986 EGL_NATIVE_VISUAL_ID, 0,
3987 #else
3988 EGL_DEPTH_SIZE, 24,
3989 #endif
3990 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3991 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3992 EGL_NONE
3994 EGLConfig conf;
3996 glx.dpy = XOpenDisplay (String_val (display_v));
3997 if (!glx.dpy) {
3998 caml_failwith ("XOpenDisplay");
4001 eglBindAPI (EGL_OPENGL_API);
4003 glx.edpy = eglGetDisplay (glx.dpy);
4004 if (glx.dpy == EGL_NO_DISPLAY) {
4005 caml_failwith ("eglGetDisplay");
4008 if (!eglInitialize (glx.edpy, &major, &minor)) {
4009 caml_failwith ("eglInitialize");
4012 #ifdef VISAVIS
4013 attribs[1] = visid = initvisual ();
4014 #endif
4016 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
4017 !num_conf) {
4018 caml_failwith ("eglChooseConfig");
4021 glx.conf = conf;
4022 #ifndef VISAVIS
4023 if (!eglGetConfigAttrib (glx.edpy, glx.conf,
4024 EGL_NATIVE_VISUAL_ID, &visid)) {
4025 caml_failwith ("eglGetConfigAttrib");
4027 #endif
4028 initcurs ();
4030 glx.wid = Int_val (wid_v);
4031 CAMLreturn (Val_int (visid));
4034 CAMLprim value ml_glxcompleteinit (value unit_v)
4036 CAMLparam1 (unit_v);
4038 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
4039 if (!glx.ctx) {
4040 caml_failwith ("eglCreateContext");
4043 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
4044 glx.wid, NULL);
4045 if (glx.win == EGL_NO_SURFACE) {
4046 caml_failwith ("eglCreateWindowSurface");
4049 XFree (glx.visual);
4050 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
4051 glx.ctx = NULL;
4052 caml_failwith ("eglMakeCurrent");
4054 CAMLreturn (Val_unit);
4056 #else
4057 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
4059 CAMLparam3 (display_v, wid_v, screen_v);
4061 glx.dpy = XOpenDisplay (String_val (display_v));
4062 if (!glx.dpy) {
4063 caml_failwith ("XOpenDisplay");
4066 #ifdef VISAVIS
4067 initvisual ();
4068 #else
4069 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
4070 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
4071 if (!glx.visual) {
4072 XCloseDisplay (glx.dpy);
4073 caml_failwith ("glXChooseVisual");
4075 #endif
4076 initcurs ();
4078 glx.wid = Int_val (wid_v);
4079 CAMLreturn (Val_int (glx.visual->visualid));
4082 CAMLprim value ml_glxcompleteinit (value unit_v)
4084 CAMLparam1 (unit_v);
4086 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
4087 if (!glx.ctx) {
4088 caml_failwith ("glXCreateContext");
4091 XFree (glx.visual);
4092 glx.visual = NULL;
4094 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
4095 glXDestroyContext (glx.dpy, glx.ctx);
4096 glx.ctx = NULL;
4097 caml_failwith ("glXMakeCurrent");
4099 CAMLreturn (Val_unit);
4101 #endif
4103 CAMLprim value ml_setcursor (value cursor_v)
4105 CAMLparam1 (cursor_v);
4106 size_t cursn = Int_val (cursor_v);
4108 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
4109 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
4110 XFlush (glx.dpy);
4111 CAMLreturn (Val_unit);
4114 CAMLprim value ml_swapb (value unit_v)
4116 CAMLparam1 (unit_v);
4117 #ifdef USE_EGL
4118 if (!eglSwapBuffers (glx.edpy, glx.win)) {
4119 caml_failwith ("eglSwapBuffers");
4121 #else
4122 glXSwapBuffers (glx.dpy, glx.wid);
4123 #endif
4124 CAMLreturn (Val_unit);
4127 #include "keysym2ucs.c"
4129 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4131 CAMLparam1 (keysym_v);
4132 CAMLlocal1 (str_v);
4133 KeySym keysym = Int_val (keysym_v);
4134 Rune rune;
4135 int len;
4136 char buf[5];
4138 rune = keysym2ucs (keysym);
4139 len = fz_runetochar (buf, rune);
4140 buf[len] = 0;
4141 str_v = caml_copy_string (buf);
4142 CAMLreturn (str_v);
4145 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4147 CAMLprim value ml_platform (value unit_v)
4149 CAMLparam1 (unit_v);
4150 CAMLlocal2 (tup_v, arr_v);
4151 int platid = piunknown;
4152 struct utsname buf;
4154 #if defined __linux__
4155 platid = pilinux;
4156 #elif defined __CYGWIN__
4157 platid = picygwin;
4158 #elif defined __DragonFly__ || defined __FreeBSD__
4159 || defined __OpenBSD__ || defined __NetBSD__
4160 platid = pibsd;
4161 #elif defined __sun__
4162 platid = pisun;
4163 #elif defined __APPLE__
4164 platid = piosx;
4165 #endif
4166 if (uname (&buf)) err (1, "uname");
4168 tup_v = caml_alloc_tuple (2);
4170 char const *sar[] = {
4171 buf.sysname,
4172 buf.release,
4173 buf.version,
4174 buf.machine,
4175 NULL
4177 arr_v = caml_copy_string_array (sar);
4179 Field (tup_v, 0) = Val_int (platid);
4180 Field (tup_v, 1) = arr_v;
4181 CAMLreturn (tup_v);
4184 CAMLprim value ml_cloexec (value fd_v)
4186 CAMLparam1 (fd_v);
4187 int fd = Int_val (fd_v);
4189 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4190 uerror ("fcntl", Nothing);
4192 CAMLreturn (Val_unit);
4195 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4197 CAMLparam2 (w_v, h_v);
4198 CAMLlocal1 (ret_v);
4199 struct bo *pbo;
4200 int w = Int_val (w_v);
4201 int h = Int_val (h_v);
4202 int cs = Int_val (cs_v);
4204 if (state.bo_usable) {
4205 pbo = calloc (sizeof (*pbo), 1);
4206 if (!pbo) {
4207 err (1, "calloc pbo");
4210 switch (cs) {
4211 case 0:
4212 case 1:
4213 pbo->size = w*h*4;
4214 break;
4215 case 2:
4216 pbo->size = w*h*2;
4217 break;
4218 default:
4219 errx (1, "%s: invalid colorspace %d", __func__, cs);
4222 state.glGenBuffersARB (1, &pbo->id);
4223 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4224 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4225 NULL, GL_STREAM_DRAW);
4226 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4227 GL_READ_WRITE);
4228 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4229 if (!pbo->ptr) {
4230 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4231 state.glDeleteBuffersARB (1, &pbo->id);
4232 free (pbo);
4233 ret_v = caml_copy_string ("0");
4235 else {
4236 int res;
4237 char *s;
4239 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4240 if (res < 0) {
4241 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4243 s = malloc (res+1);
4244 if (!s) {
4245 err (1, "malloc %d bytes failed", res+1);
4247 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4248 if (res < 0) {
4249 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4251 ret_v = caml_copy_string (s);
4252 free (s);
4255 else {
4256 ret_v = caml_copy_string ("0");
4258 CAMLreturn (ret_v);
4261 CAMLprim value ml_freepbo (value s_v)
4263 CAMLparam1 (s_v);
4264 char *s = String_val (s_v);
4265 struct tile *tile = parse_pointer (__func__, s);
4267 if (tile->pbo) {
4268 state.glDeleteBuffersARB (1, &tile->pbo->id);
4269 tile->pbo->id = -1;
4270 tile->pbo->ptr = NULL;
4271 tile->pbo->size = -1;
4273 CAMLreturn (Val_unit);
4276 CAMLprim value ml_unmappbo (value s_v)
4278 CAMLparam1 (s_v);
4279 char *s = String_val (s_v);
4280 struct tile *tile = parse_pointer (__func__, s);
4282 if (tile->pbo) {
4283 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4284 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4285 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4287 tile->pbo->ptr = NULL;
4288 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4290 CAMLreturn (Val_unit);
4293 static void setuppbo (void)
4295 #ifdef USE_EGL
4296 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4297 #else
4298 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4299 #endif
4300 state.bo_usable = GGPA (glBindBufferARB)
4301 && GGPA (glUnmapBufferARB)
4302 && GGPA (glMapBufferARB)
4303 && GGPA (glBufferDataARB)
4304 && GGPA (glGenBuffersARB)
4305 && GGPA (glDeleteBuffersARB);
4306 #undef GGPA
4309 CAMLprim value ml_bo_usable (value unit_v)
4311 CAMLparam1 (unit_v);
4312 CAMLreturn (Val_bool (state.bo_usable));
4315 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4317 CAMLparam3 (ptr_v, x_v, y_v);
4318 CAMLlocal2 (ret_v, tup_v);
4319 struct page *page;
4320 char *s = String_val (ptr_v);
4321 int x = Int_val (x_v), y = Int_val (y_v);
4322 struct pagedim *pdim;
4323 fz_point p;
4324 fz_matrix ctm;
4326 page = parse_pointer (__func__, s);
4327 pdim = &state.pagedims[page->pdimno];
4329 ret_v = Val_int (0);
4330 if (trylock (__func__)) {
4331 goto done;
4334 if (pdf_specifics (state.ctx, state.doc)) {
4335 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4336 ctm = state.pagedims[page->pdimno].tctm;
4338 else {
4339 ctm = fz_identity;
4341 p.x = x + pdim->bounds.x0;
4342 p.y = y + pdim->bounds.y0;
4344 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4345 fz_invert_matrix (&ctm, &ctm);
4346 fz_transform_point (&p, &ctm);
4348 tup_v = caml_alloc_tuple (2);
4349 ret_v = caml_alloc_small (1, 1);
4350 Field (tup_v, 0) = Val_int (p.x);
4351 Field (tup_v, 1) = Val_int (p.y);
4352 Field (ret_v, 0) = tup_v;
4354 unlock (__func__);
4355 done:
4356 CAMLreturn (ret_v);
4359 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4360 value x_v, value y_v)
4362 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4363 CAMLlocal1 (ret_v);
4364 struct page *page;
4365 char *s = String_val (ptr_v);
4366 int pageno = Int_val (pageno_v);
4367 int pdimno = Int_val (pdimno_v);
4368 double x = Double_val (x_v), y = Double_val (y_v);
4369 struct pagedim *pdim;
4370 fz_point p;
4371 fz_matrix ctm;
4373 ret_v = Val_int (0);
4374 lock (__func__);
4376 if (!*s) {
4377 page = loadpage (pageno, pdimno);
4379 else {
4380 page = parse_pointer (__func__, s);
4382 pdim = &state.pagedims[pdimno];
4384 if (pdf_specifics (state.ctx, state.doc)) {
4385 trimctm ((pdf_page *) page->fzpage, page->pdimno);
4386 ctm = state.pagedims[page->pdimno].tctm;
4388 else {
4389 ctm = fz_identity;
4391 p.x = x + pdim->bounds.x0;
4392 p.y = y + pdim->bounds.y0;
4394 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4395 fz_transform_point (&p, &ctm);
4397 ret_v = caml_alloc_tuple (2);
4398 Field (ret_v, 0) = caml_copy_double (p.x);
4399 Field (ret_v, 1) = caml_copy_double (p.y);
4401 if (!*s) {
4402 freepage (page);
4404 unlock (__func__);
4405 CAMLreturn (ret_v);
4408 CAMLprim value ml_addannot (value ptr_v, value x_v, value y_v,
4409 value contents_v)
4411 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4412 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4414 if (pdf) {
4415 pdf_annot *annot;
4416 struct page *page;
4417 fz_point p;
4418 char *s = String_val (ptr_v);
4420 page = parse_pointer (__func__, s);
4421 annot = pdf_create_annot (state.ctx, pdf,
4422 (pdf_page *) page->fzpage, FZ_ANNOT_TEXT);
4423 p.x = Int_val (x_v);
4424 p.y = Int_val (y_v);
4425 pdf_set_annot_contents (state.ctx, pdf, annot, String_val (contents_v));
4426 pdf_set_text_annot_position (state.ctx, pdf, annot, p);
4427 state.dirty = 1;
4429 CAMLreturn (Val_unit);
4432 CAMLprim value ml_delannot (value ptr_v, value n_v)
4434 CAMLparam2 (ptr_v, n_v);
4435 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4437 if (pdf) {
4438 struct page *page;
4439 char *s = String_val (ptr_v);
4440 struct slink *slink;
4442 page = parse_pointer (__func__, s);
4443 slink = &page->slinks[Int_val (n_v)];
4444 pdf_delete_annot (state.ctx, pdf,
4445 (pdf_page *) page->fzpage,
4446 (pdf_annot *) slink->u.annot);
4447 state.dirty = 1;
4449 CAMLreturn (Val_unit);
4452 CAMLprim value ml_modannot (value ptr_v, value n_v, value str_v)
4454 CAMLparam3 (ptr_v, n_v, str_v);
4455 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4457 if (pdf) {
4458 struct page *page;
4459 char *s = String_val (ptr_v);
4460 struct slink *slink;
4462 page = parse_pointer (__func__, s);
4463 slink = &page->slinks[Int_val (n_v)];
4464 pdf_set_annot_contents (state.ctx, pdf, (pdf_annot *) slink->u.annot,
4465 String_val (str_v));
4466 state.dirty = 1;
4468 CAMLreturn (Val_unit);
4471 CAMLprim value ml_hasunsavedchanges (value unit_v)
4473 CAMLparam1 (unit_v);
4474 CAMLreturn (Val_bool (state.dirty));
4477 CAMLprim value ml_savedoc (value path_v)
4479 CAMLparam1 (path_v);
4480 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4482 if (pdf) {
4483 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4485 CAMLreturn (Val_unit);
4488 static void makestippletex (void)
4490 const char pixels[] = "\xff\xff\0\0";
4491 glGenTextures (1, &state.stid);
4492 glBindTexture (GL_TEXTURE_1D, state.stid);
4493 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4494 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4495 glTexImage1D (
4496 GL_TEXTURE_1D,
4498 GL_ALPHA,
4501 GL_ALPHA,
4502 GL_UNSIGNED_BYTE,
4503 pixels
4507 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4509 return caml_copy_string (FZ_VERSION);
4512 #ifdef USE_FONTCONFIG
4513 static struct {
4514 int inited;
4515 FcConfig *config;
4516 } fc;
4518 static fz_font *fc_load_system_font_func (fz_context *ctx,
4519 const char *name,
4520 int bold,
4521 int italic,
4522 int UNUSED_ATTR needs_exact_metrics)
4524 char *buf;
4525 size_t i, size;
4526 fz_font *font;
4527 FcChar8 *path;
4528 FcResult result;
4529 FcPattern *pat, *pat1;
4531 lprintf ("looking up %s bold:%d italic:%d needs_exact_metrics:%d\n",
4532 name, bold, italic, needs_exact_metrics);
4533 if (!fc.inited) {
4534 fc.inited = 1;
4535 fc.config = FcInitLoadConfigAndFonts ();
4536 if (!fc.config) {
4537 lprintf ("FcInitLoadConfigAndFonts failed\n");
4538 return NULL;
4541 if (!fc.config) return NULL;
4543 size = strlen (name);
4544 if (bold) size += sizeof (":bold") - 1;
4545 if (italic) size += sizeof (":italic") - 1;
4546 size += 1;
4548 buf = malloc (size);
4549 if (!buf) {
4550 err (1, "malloc %zu failed", size);
4553 strcpy (buf, name);
4554 if (bold && italic) {
4555 strcat (buf, ":bold:italic");
4557 else {
4558 if (bold) strcat (buf, ":bold");
4559 if (italic) strcat (buf, ":italic");
4561 for (i = 0; i < size; ++i) {
4562 if (buf[i] == ',' || buf[i] == '-') buf[i] = ':';
4565 lprintf ("fcbuf=%s\n", buf);
4566 pat = FcNameParse ((FcChar8 *) buf);
4567 if (!pat) {
4568 printd ("emsg FcNameParse failed\n");
4569 free (buf);
4570 return NULL;
4573 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4574 printd ("emsg FcConfigSubstitute failed\n");
4575 free (buf);
4576 return NULL;
4578 FcDefaultSubstitute (pat);
4580 pat1 = FcFontMatch (fc.config, pat, &result);
4581 if (!pat1) {
4582 printd ("emsg FcFontMatch failed\n");
4583 FcPatternDestroy (pat);
4584 free (buf);
4585 return NULL;
4588 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4589 printd ("emsg FcPatternGetString failed\n");
4590 FcPatternDestroy (pat);
4591 FcPatternDestroy (pat1);
4592 free (buf);
4593 return NULL;
4596 #if 0
4597 printd ("emsg name=%s path=%s\n", name, path);
4598 #endif
4599 font = fz_new_font_from_file (ctx, name, (char *) path, 0, 0);
4600 FcPatternDestroy (pat);
4601 FcPatternDestroy (pat1);
4602 free (buf);
4603 return font;
4605 #endif
4607 CAMLprim value ml_init (value csock_v, value params_v)
4609 CAMLparam2 (csock_v, params_v);
4610 CAMLlocal2 (trim_v, fuzz_v);
4611 int ret;
4612 int texcount;
4613 char *fontpath;
4614 int colorspace;
4615 int mustoresize;
4616 int haspboext;
4618 state.csock = Int_val (csock_v);
4619 state.rotate = Int_val (Field (params_v, 0));
4620 state.fitmodel = Int_val (Field (params_v, 1));
4621 trim_v = Field (params_v, 2);
4622 texcount = Int_val (Field (params_v, 3));
4623 state.sliceheight = Int_val (Field (params_v, 4));
4624 mustoresize = Int_val (Field (params_v, 5));
4625 colorspace = Int_val (Field (params_v, 6));
4626 fontpath = String_val (Field (params_v, 7));
4628 if (caml_string_length (Field (params_v, 8)) > 0) {
4629 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4631 if (!state.trimcachepath) {
4632 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4633 strerror (errno));
4636 haspboext = Bool_val (Field (params_v, 9));
4638 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4639 fz_register_document_handlers (state.ctx);
4641 #ifdef USE_FONTCONFIG
4642 if (Bool_val (Field (params_v, 10))) {
4643 fz_install_load_system_font_funcs (
4644 state.ctx, fc_load_system_font_func, NULL
4647 #endif
4649 state.trimmargins = Bool_val (Field (trim_v, 0));
4650 fuzz_v = Field (trim_v, 1);
4651 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4652 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4653 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4654 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4656 set_tex_params (colorspace);
4658 if (*fontpath) {
4659 #ifndef USE_FONTCONFIG
4660 state.face = load_font (fontpath);
4661 #else
4662 FcChar8 *path;
4663 FcResult result;
4664 char *buf = fontpath;
4665 FcPattern *pat, *pat1;
4667 fc.inited = 1;
4668 fc.config = FcInitLoadConfigAndFonts ();
4669 if (!fc.config) {
4670 errx (1, "FcInitLoadConfigAndFonts failed");
4673 pat = FcNameParse ((FcChar8 *) buf);
4674 if (!pat) {
4675 errx (1, "FcNameParse failed");
4678 if (!FcConfigSubstitute (fc.config, pat, FcMatchPattern)) {
4679 errx (1, "FcConfigSubstitute failed");
4681 FcDefaultSubstitute (pat);
4683 pat1 = FcFontMatch (fc.config, pat, &result);
4684 if (!pat1) {
4685 errx (1, "FcFontMatch failed");
4688 if (FcPatternGetString (pat1, FC_FILE, 0, &path) != FcResultMatch) {
4689 errx (1, "FcPatternGetString failed");
4692 state.face = load_font ((char *) path);
4693 FcPatternDestroy (pat);
4694 FcPatternDestroy (pat1);
4695 #endif
4697 else {
4698 unsigned int len;
4699 void *base = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
4701 state.face = load_builtin_font (base, len);
4703 if (!state.face) _exit (1);
4705 realloctexts (texcount);
4707 if (haspboext) {
4708 setuppbo ();
4711 makestippletex ();
4713 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4714 if (ret) {
4715 errx (1, "pthread_create: %s", strerror (ret));
4718 CAMLreturn (Val_unit);