WShoops
[llpp/slowscroll.git] / link.c
blob2592d5173e15ae63f58c5613b4d0fdfd2abdbfef
1 /* lots of code c&p-ed directly from mupdf */
2 #define CAML_NAME_SPACE
3 #define FIXME 0
5 #include <errno.h>
6 #include <stdio.h>
7 #include <ctype.h>
8 #include <string.h>
9 #include <stdlib.h>
10 #include <signal.h>
11 #include <wchar.h>
13 #include <unistd.h>
14 #include <pthread.h>
15 #include <sys/uio.h>
16 #include <sys/time.h>
17 #include <sys/types.h>
18 #include <sys/ioctl.h>
19 #include <sys/utsname.h>
21 #ifdef __CYGWIN__
22 #include <cygwin/socket.h> /* FIONREAD */
23 #else
24 #include <spawn.h>
25 #endif
27 #include <regex.h>
28 #include <stdarg.h>
29 #include <limits.h>
30 #include <inttypes.h>
32 #ifdef __COCOA__
33 #include <CoreFoundation/CoreFoundation.h>
34 #endif
36 #ifdef __APPLE__
37 #include <OpenGL/gl.h>
38 #else
39 #include <GL/gl.h>
40 #endif
42 #include <caml/fail.h>
43 #include <caml/alloc.h>
44 #include <caml/memory.h>
45 #include <caml/unixsupport.h>
47 #if __GNUC__ < 5 && !defined __clang__
48 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
49 clobbered diagnostics */
50 #pragma GCC diagnostic ignored "-Wclobbered"
51 #endif
53 #include <mupdf/fitz.h>
54 #include <mupdf/pdf.h>
56 #include <ft2build.h>
57 #include FT_FREETYPE_H
59 #define PIGGYBACK
60 #define CACHE_PAGEREFS
62 #ifndef __USE_GNU
63 extern char **environ;
64 #endif
66 #if defined __GNUC__
67 #define NORETURN_ATTR __attribute__ ((noreturn))
68 #define UNUSED_ATTR __attribute__ ((unused))
69 #if !defined __clang__
70 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
71 #else
72 #define OPTIMIZE_ATTR(n)
73 #endif
74 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
75 #else
76 #define NORETURN_ATTR
77 #define UNUSED_ATTR
78 #define OPTIMIZE_ATTR(n)
79 #define GCC_FMT_ATTR(a, b)
80 #endif
82 #define FMT_s "zu"
84 #define FMT_ptr PRIxPTR
85 #define SCN_ptr SCNxPTR
86 #define FMT_ptr_cast(p) ((uintptr_t) (p))
87 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
89 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
90 err (int exitcode, const char *fmt, ...)
92 va_list ap;
93 int savederrno;
95 savederrno = errno;
96 va_start (ap, fmt);
97 vfprintf (stderr, fmt, ap);
98 va_end (ap);
99 fprintf (stderr, ": %s\n", strerror (savederrno));
100 fflush (stderr);
101 _exit (exitcode);
104 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
105 errx (int exitcode, const char *fmt, ...)
107 va_list ap;
109 va_start (ap, fmt);
110 vfprintf (stderr, fmt, ap);
111 va_end (ap);
112 fputc ('\n', stderr);
113 fflush (stderr);
114 _exit (exitcode);
117 #ifndef GL_TEXTURE_RECTANGLE_ARB
118 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
119 #endif
121 #ifdef USE_NPOT
122 #define TEXT_TYPE GL_TEXTURE_2D
123 #else
124 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
125 #endif
127 #ifndef GL_BGRA
128 #define GL_BGRA 0x80E1
129 #endif
131 #ifndef GL_UNSIGNED_INT_8_8_8_8
132 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
133 #endif
135 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
136 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
137 #endif
139 #if 0
140 #define lprintf printf
141 #else
142 #define lprintf(...)
143 #endif
145 #define ARSERT(cond) for (;;) { \
146 if (!(cond)) { \
147 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
149 break; \
152 struct slice {
153 int h;
154 int texindex;
157 struct tile {
158 int w, h;
159 int slicecount;
160 int sliceheight;
161 struct bo *pbo;
162 fz_pixmap *pixmap;
163 struct slice slices[1];
166 struct pagedim {
167 int pageno;
168 int rotate;
169 int left;
170 int tctmready;
171 fz_irect bounds;
172 fz_rect pagebox;
173 fz_rect mediabox;
174 fz_matrix ctm, zoomctm, tctm;
177 struct slink {
178 enum { SLINK, SANNOT } tag;
179 fz_irect bbox;
180 union {
181 fz_link *link;
182 fz_annot *annot;
183 } u;
186 struct annot {
187 fz_irect bbox;
188 fz_annot *annot;
191 struct page {
192 int tgen;
193 int sgen;
194 int agen;
195 int pageno;
196 int pdimno;
197 fz_stext_page *text;
198 fz_stext_sheet *sheet;
199 fz_page *fzpage;
200 fz_display_list *dlist;
201 int slinkcount;
202 struct slink *slinks;
203 int annotcount;
204 struct annot *annots;
205 struct mark {
206 int i;
207 fz_stext_span *span;
208 } fmark, lmark;
211 struct {
212 int sliceheight;
213 struct pagedim *pagedims;
214 int pagecount;
215 int pagedimcount;
216 fz_document *doc;
217 fz_context *ctx;
218 int w, h;
220 int texindex;
221 int texcount;
222 GLuint *texids;
224 GLenum texiform;
225 GLenum texform;
226 GLenum texty;
228 fz_colorspace *colorspace;
230 struct {
231 int w, h;
232 struct slice *slice;
233 } *texowners;
235 int rotate;
236 enum { FitWidth, FitProportional, FitPage } fitmodel;
237 int trimmargins;
238 int needoutline;
239 int gen;
240 int aalevel;
242 int trimanew;
243 fz_irect trimfuzz;
244 fz_pixmap *pig;
246 pthread_t thread;
247 int csock;
248 FT_Face face;
250 char *trimcachepath;
251 int cxack;
252 int dirty;
254 GLuint stid;
256 int bo_usable;
257 GLuint boid;
259 void (*glBindBufferARB) (GLenum, GLuint);
260 GLboolean (*glUnmapBufferARB) (GLenum);
261 void *(*glMapBufferARB) (GLenum, GLenum);
262 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
263 void (*glGenBuffersARB) (GLsizei, GLuint *);
264 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
266 GLfloat texcoords[8];
267 GLfloat vertices[16];
269 #ifdef CACHE_PAGEREFS
270 struct {
271 int idx;
272 int count;
273 pdf_obj **objs;
274 pdf_document *pdf;
275 } pdflut;
276 #endif
277 } state;
279 struct bo {
280 GLuint id;
281 void *ptr;
282 size_t size;
285 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
287 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
290 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
292 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
295 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
297 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
298 m.a, m.b, m.c, m.d, m.e, m.f);
301 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
303 static void lock (const char *cap)
305 int ret = pthread_mutex_lock (&mutex);
306 if (ret) {
307 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
311 static void unlock (const char *cap)
313 int ret = pthread_mutex_unlock (&mutex);
314 if (ret) {
315 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
319 static int trylock (const char *cap)
321 int ret = pthread_mutex_trylock (&mutex);
322 if (ret && ret != EBUSY) {
323 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
325 return ret == EBUSY;
328 static void *parse_pointer (const char *cap, const char *s)
330 int ret;
331 void *ptr;
333 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
334 if (ret != 1) {
335 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
337 return ptr;
340 static double now (void)
342 struct timeval tv;
344 if (gettimeofday (&tv, NULL)) {
345 err (1, "gettimeofday");
347 return tv.tv_sec + tv.tv_usec*1e-6;
350 static int hasdata (void)
352 int ret, avail;
353 ret = ioctl (state.csock, FIONREAD, &avail);
354 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
355 return avail > 0;
358 CAMLprim value ml_hasdata (value fd_v)
360 CAMLparam1 (fd_v);
361 int ret, avail;
363 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
364 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
365 CAMLreturn (Val_bool (avail > 0));
368 static void readdata (int fd, void *p, int size)
370 ssize_t n;
372 again:
373 n = read (fd, p, size);
374 if (n - size) {
375 if (n < 0 && errno == EINTR) goto again;
376 if (!n) errx (1, "EOF while reading");
377 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
381 static void writedata (int fd, char *p, int size)
383 ssize_t n;
384 uint32_t size4 = size;
385 struct iovec iov[2] = {
386 { .iov_base = &size4, .iov_len = 4 },
387 { .iov_base = p, .iov_len = size }
390 again:
391 n = writev (fd, iov, 2);
392 if (n < 0 && errno == EINTR) goto again;
393 if (n - size - 4) {
394 if (!n) errx (1, "EOF while writing data");
395 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
399 static int readlen (int fd)
401 /* Type punned unions here. Why? Less code (Adjusted by more comments).
402 https://en.wikipedia.org/wiki/Type_punning */
403 union { uint32_t len; char raw[4]; } buf;
404 readdata (fd, buf.raw, 4);
405 return buf.len;
408 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
410 CAMLparam3 (fd_v, bytes_v, len_v);
411 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
412 CAMLreturn0;
415 CAMLprim value ml_rcmd (value fd_v)
417 CAMLparam1 (fd_v);
418 CAMLlocal1 (strdata_v);
419 int fd = Int_val (fd_v);
420 int len = readlen (fd);
421 strdata_v = caml_alloc_string (len);
422 readdata (fd, String_val (strdata_v), len);
423 CAMLreturn (strdata_v);
426 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
428 int size = 64, len;
429 va_list ap;
430 char fbuf[size];
431 char *buf = fbuf;
433 for (;;) {
434 va_start (ap, fmt);
435 len = vsnprintf (buf, size, fmt, ap);
436 va_end (ap);
438 if (len > -1) {
439 if (len < size - 4) {
440 writedata (state.csock, buf, len);
441 break;
443 else size = len + 5;
445 else {
446 err (1, "vsnprintf for `%s' failed", fmt);
448 buf = realloc (buf == fbuf ? NULL : buf, size);
449 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
451 if (buf != fbuf) free (buf);
454 static void closedoc (void)
456 #ifdef CACHE_PAGEREFS
457 if (state.pdflut.objs) {
458 for (int i = 0; i < state.pdflut.count; ++i) {
459 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
461 free (state.pdflut.objs);
462 state.pdflut.objs = NULL;
463 state.pdflut.idx = 0;
465 #endif
466 if (state.doc) {
467 fz_drop_document (state.ctx, state.doc);
468 state.doc = NULL;
472 static int openxref (char *filename, char *password)
474 for (int i = 0; i < state.texcount; ++i) {
475 state.texowners[i].w = -1;
476 state.texowners[i].slice = NULL;
479 closedoc ();
481 state.dirty = 0;
482 if (state.pagedims) {
483 free (state.pagedims);
484 state.pagedims = NULL;
486 state.pagedimcount = 0;
488 fz_set_aa_level (state.ctx, state.aalevel);
489 state.doc = fz_open_document (state.ctx, filename);
490 if (fz_needs_password (state.ctx, state.doc)) {
491 if (password && !*password) {
492 printd ("pass");
493 return 0;
495 else {
496 int ok = fz_authenticate_password (state.ctx, state.doc, password);
497 if (!ok) {
498 printd ("pass fail");
499 return 0;
503 state.pagecount = fz_count_pages (state.ctx, state.doc);
504 return 1;
507 static void pdfinfo (void)
509 struct { char *tag; char *name; } metatbl[] = {
510 { FZ_META_INFO_TITLE, "Title" },
511 { FZ_META_INFO_AUTHOR, "Author" },
512 { FZ_META_FORMAT, "Format" },
513 { FZ_META_ENCRYPTION, "Encryption" },
514 { "info:Creator", "Creator" },
515 { "info:Producer", "Producer" },
516 { "info:CreationDate", "Creation date" },
518 int len = 0;
519 char *buf = NULL;
521 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
522 int need;
523 again:
524 need = fz_lookup_metadata (state.ctx, state.doc,
525 metatbl[i].tag, buf, len);
526 if (need > 0) {
527 if (need <= len) {
528 printd ("info %s\t%s", metatbl[i].name, buf);
530 else {
531 buf = realloc (buf, need + 1);
532 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
533 len = need + 1;
534 goto again;
538 free (buf);
540 printd ("infoend");
543 static void unlinktile (struct tile *tile)
545 for (int i = 0; i < tile->slicecount; ++i) {
546 struct slice *s = &tile->slices[i];
548 if (s->texindex != -1) {
549 if (state.texowners[s->texindex].slice == s) {
550 state.texowners[s->texindex].slice = NULL;
556 static void freepage (struct page *page)
558 if (!page) return;
559 if (page->text) {
560 fz_drop_stext_page (state.ctx, page->text);
562 if (page->sheet) {
563 fz_drop_stext_sheet (state.ctx, page->sheet);
565 if (page->slinks) {
566 free (page->slinks);
568 fz_drop_display_list (state.ctx, page->dlist);
569 fz_drop_page (state.ctx, page->fzpage);
570 free (page);
573 static void freetile (struct tile *tile)
575 unlinktile (tile);
576 if (!tile->pbo) {
577 #ifndef PIGGYBACK
578 fz_drop_pixmap (state.ctx, tile->pixmap);
579 #else
580 if (state.pig) {
581 fz_drop_pixmap (state.ctx, state.pig);
583 state.pig = tile->pixmap;
584 #endif
586 else {
587 free (tile->pbo);
588 fz_drop_pixmap (state.ctx, tile->pixmap);
590 free (tile);
593 #ifdef __ALTIVEC__
594 #include <stdint.h>
595 #include <altivec.h>
597 static int cacheline32bytes;
599 static void __attribute__ ((constructor)) clcheck (void)
601 char **envp = environ;
602 unsigned long *auxv;
604 while (*envp++);
606 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
607 if (*auxv == 19) {
608 cacheline32bytes = auxv[1] == 32;
609 return;
614 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
616 size_t size = pixmap->w * pixmap->h * pixmap->n;
617 if (cacheline32bytes && size > 32) {
618 intptr_t a1, a2, diff;
619 size_t sizea, i;
620 vector unsigned char v = vec_splat_u8 (-1);
621 vector unsigned char *p;
623 a1 = a2 = (intptr_t) pixmap->samples;
624 a2 = (a1 + 31) & ~31;
625 diff = a2 - a1;
626 sizea = size - diff;
627 p = (void *) a2;
629 while (a1 != a2) *(char *) a1++ = 0xff;
630 for (i = 0; i < (sizea & ~31); i += 32) {
631 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
632 vec_st (v, i, p);
633 vec_st (v, i + 16, p);
635 while (i < sizea) *((char *) a1 + i++) = 0xff;
637 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
639 #else
640 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
641 #endif
643 static void trimctm (pdf_page *page, int pindex)
645 fz_matrix ctm;
646 struct pagedim *pdim = &state.pagedims[pindex];
648 if (!page) return;
649 if (!pdim->tctmready) {
650 fz_rect realbox, mediabox;
651 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
653 fz_rotate (&rm, -pdim->rotate);
654 fz_scale (&sm, 1, -1);
655 fz_concat (&ctm, &rm, &sm);
656 realbox = pdim->mediabox;
657 fz_transform_rect (&realbox, &ctm);
658 fz_translate (&tm, -realbox.x0, -realbox.y0);
659 fz_concat (&ctm1, &ctm, &tm);
660 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
661 fz_invert_matrix (&im, &page_ctm);
662 fz_concat (&ctm, &im, &ctm1);
663 pdim->tctm = ctm;
664 pdim->tctmready = 1;
668 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
670 fz_matrix ctm, tm;
671 int pdimno = pdim - state.pagedims;
673 if (pdf_specifics (state.ctx, state.doc)) {
674 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
675 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
677 else {
678 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
679 fz_concat (&ctm, &tm, &pdim->ctm);
681 return ctm;
684 static fz_matrix pagectm (struct page *page)
686 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
689 static void *loadpage (int pageno, int pindex)
691 fz_device *dev;
692 struct page *page;
694 page = calloc (sizeof (struct page), 1);
695 if (!page) {
696 err (1, "calloc page %d", pageno);
699 page->dlist = fz_new_display_list (state.ctx, NULL);
700 dev = fz_new_list_device (state.ctx, page->dlist);
701 fz_try (state.ctx) {
702 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
703 fz_run_page (state.ctx, page->fzpage, dev,
704 &fz_identity, NULL);
706 fz_catch (state.ctx) {
707 page->fzpage = NULL;
709 fz_close_device (state.ctx, dev);
710 fz_drop_device (state.ctx, dev);
712 page->pdimno = pindex;
713 page->pageno = pageno;
714 page->sgen = state.gen;
715 page->agen = state.gen;
716 page->tgen = state.gen;
717 return page;
720 static struct tile *alloctile (int h)
722 int slicecount;
723 size_t tilesize;
724 struct tile *tile;
726 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
727 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
728 tile = calloc (tilesize, 1);
729 if (!tile) {
730 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
732 for (int i = 0; i < slicecount; ++i) {
733 int sh = fz_mini (h, state.sliceheight);
734 tile->slices[i].h = sh;
735 tile->slices[i].texindex = -1;
736 h -= sh;
738 tile->slicecount = slicecount;
739 tile->sliceheight = state.sliceheight;
740 return tile;
743 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
744 struct bo *pbo)
746 fz_rect rect;
747 fz_irect bbox;
748 fz_matrix ctm;
749 fz_device *dev;
750 struct tile *tile;
751 struct pagedim *pdim;
753 tile = alloctile (h);
754 pdim = &state.pagedims[page->pdimno];
756 bbox = pdim->bounds;
757 bbox.x0 += x;
758 bbox.y0 += y;
759 bbox.x1 = bbox.x0 + w;
760 bbox.y1 = bbox.y0 + h;
762 if (state.pig) {
763 if (state.pig->w == w
764 && state.pig->h == h
765 && state.pig->colorspace == state.colorspace) {
766 tile->pixmap = state.pig;
767 tile->pixmap->x = bbox.x0;
768 tile->pixmap->y = bbox.y0;
770 else {
771 fz_drop_pixmap (state.ctx, state.pig);
773 state.pig = NULL;
775 if (!tile->pixmap) {
776 if (pbo) {
777 tile->pixmap =
778 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
779 &bbox, 1, pbo->ptr);
780 tile->pbo = pbo;
782 else {
783 tile->pixmap =
784 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
788 tile->w = w;
789 tile->h = h;
790 clearpixmap (tile->pixmap);
792 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
793 ctm = pagectm (page);
794 fz_rect_from_irect (&rect, &bbox);
795 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
796 fz_close_device (state.ctx, dev);
797 fz_drop_device (state.ctx, dev);
799 return tile;
802 #ifdef CACHE_PAGEREFS
803 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
804 thanks to Robin Watts */
805 static void
806 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
808 fz_context *ctx = state.ctx; /* doc->ctx; */
809 pdf_obj *kids;
810 int len;
812 if (state.pdflut.idx == state.pagecount) return;
814 kids = pdf_dict_gets (ctx, node, "Kids");
815 len = pdf_array_len (ctx, kids);
817 if (len == 0)
818 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
820 if (pdf_mark_obj (ctx, node))
821 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
822 for (int i = 0; i < len; i++) {
823 pdf_obj *kid = pdf_array_get (ctx, kids, i);
824 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
825 if (*type
826 ? !strcmp (type, "Pages")
827 : pdf_dict_gets (ctx, kid, "Kids")
828 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
829 pdf_collect_pages (doc, kid);
831 else {
832 if (*type
833 ? strcmp (type, "Page") != 0
834 : !pdf_dict_gets (ctx, kid, "MediaBox"))
835 fz_warn (ctx, "non-page object in page tree (%s)", type);
836 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
839 pdf_unmark_obj (ctx, node);
842 static void
843 pdf_load_page_objs (pdf_document *doc)
845 pdf_obj *root = pdf_dict_gets (state.ctx,
846 pdf_trailer (state.ctx, doc), "Root");
847 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
849 if (!node)
850 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
852 state.pdflut.idx = 0;
853 pdf_collect_pages (doc, node);
855 #endif
857 static void initpdims (int wthack)
859 double start, end;
860 FILE *trimf = NULL;
861 fz_rect rootmediabox;
862 int pageno, trim, show;
863 int trimw = 0, cxcount;
864 fz_context *ctx = state.ctx;
865 pdf_document *pdf = pdf_specifics (ctx, state.doc);
867 fz_var (trimw);
868 fz_var (trimf);
869 fz_var (cxcount);
870 start = now ();
872 if (state.trimmargins && state.trimcachepath) {
873 trimf = fopen (state.trimcachepath, "rb");
874 if (!trimf) {
875 trimf = fopen (state.trimcachepath, "wb");
876 trimw = 1;
880 if (state.trimmargins || pdf || !state.cxack)
881 cxcount = state.pagecount;
882 else
883 cxcount = fz_mini (state.pagecount, 1);
885 if (pdf) {
886 pdf_obj *obj;
887 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
888 "Root/Pages/MediaBox");
889 pdf_to_rect (ctx, obj, &rootmediabox);
892 #ifdef CACHE_PAGEREFS
893 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
894 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
895 if (!state.pdflut.objs) {
896 err (1, "malloc pageobjs %zu %d %zu failed",
897 sizeof (*state.pdflut.objs), cxcount,
898 sizeof (*state.pdflut.objs) * cxcount);
900 state.pdflut.count = cxcount;
901 pdf_load_page_objs (pdf);
902 state.pdflut.pdf = pdf;
904 #endif
906 for (pageno = 0; pageno < cxcount; ++pageno) {
907 int rotate = 0;
908 struct pagedim *p;
909 fz_rect mediabox;
911 fz_var (rotate);
912 if (pdf) {
913 pdf_obj *pageref, *pageobj;
915 #ifdef CACHE_PAGEREFS
916 pageref = state.pdflut.objs[pageno];
917 #else
918 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
919 #endif
920 pageobj = pdf_resolve_indirect (ctx, pageref);
921 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
923 if (state.trimmargins) {
924 pdf_obj *obj;
925 pdf_page *page;
927 fz_try (ctx) {
928 page = pdf_load_page (ctx, pdf, pageno);
929 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
930 trim = state.trimanew || !obj;
931 if (trim) {
932 fz_rect rect;
933 fz_device *dev;
934 fz_matrix ctm, page_ctm;
936 dev = fz_new_bbox_device (ctx, &rect);
937 dev->hints |= FZ_IGNORE_SHADE;
938 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
939 fz_invert_matrix (&ctm, &page_ctm);
940 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
941 fz_close_device (ctx, dev);
942 fz_drop_device (ctx, dev);
944 rect.x0 += state.trimfuzz.x0;
945 rect.x1 += state.trimfuzz.x1;
946 rect.y0 += state.trimfuzz.y0;
947 rect.y1 += state.trimfuzz.y1;
948 fz_transform_rect (&rect, &ctm);
949 fz_intersect_rect (&rect, &mediabox);
951 if (!fz_is_empty_rect (&rect)) {
952 mediabox = rect;
955 obj = pdf_new_array (ctx, pdf, 4);
956 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
957 mediabox.x0));
958 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
959 mediabox.y0));
960 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
961 mediabox.x1));
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.y1));
964 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
966 else {
967 mediabox.x0 = pdf_to_real (ctx,
968 pdf_array_get (ctx, obj, 0));
969 mediabox.y0 = pdf_to_real (ctx,
970 pdf_array_get (ctx, obj, 1));
971 mediabox.x1 = pdf_to_real (ctx,
972 pdf_array_get (ctx, obj, 2));
973 mediabox.y1 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 3));
977 fz_drop_page (ctx, &page->super);
978 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
979 if (show) {
980 printd ("progress %f Trimming %d",
981 (double) (pageno + 1) / state.pagecount,
982 pageno + 1);
985 fz_catch (ctx) {
986 fprintf (stderr, "failed to load page %d\n", pageno+1);
989 else {
990 int empty = 0;
991 fz_rect cropbox;
993 pdf_to_rect (ctx,
994 pdf_dict_gets (ctx, pageobj, "MediaBox"),
995 &mediabox);
996 if (fz_is_empty_rect (&mediabox)) {
997 mediabox.x0 = 0;
998 mediabox.y0 = 0;
999 mediabox.x1 = 612;
1000 mediabox.y1 = 792;
1001 empty = 1;
1004 pdf_to_rect (ctx,
1005 pdf_dict_gets (ctx, pageobj, "CropBox"),
1006 &cropbox);
1007 if (!fz_is_empty_rect (&cropbox)) {
1008 if (empty) {
1009 mediabox = cropbox;
1011 else {
1012 fz_intersect_rect (&mediabox, &cropbox);
1015 else {
1016 if (empty) {
1017 if (fz_is_empty_rect (&rootmediabox)) {
1018 fprintf (stderr,
1019 "cannot find page size for page %d\n",
1020 pageno+1);
1022 else {
1023 mediabox = rootmediabox;
1029 else {
1030 if (state.trimmargins && trimw) {
1031 fz_page *page;
1033 fz_try (ctx) {
1034 page = fz_load_page (ctx, state.doc, pageno);
1035 fz_bound_page (ctx, page, &mediabox);
1036 if (state.trimmargins) {
1037 fz_rect rect;
1038 fz_device *dev;
1040 dev = fz_new_bbox_device (ctx, &rect);
1041 dev->hints |= FZ_IGNORE_SHADE;
1042 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1043 fz_close_device (ctx, dev);
1044 fz_drop_device (ctx, dev);
1046 rect.x0 += state.trimfuzz.x0;
1047 rect.x1 += state.trimfuzz.x1;
1048 rect.y0 += state.trimfuzz.y0;
1049 rect.y1 += state.trimfuzz.y1;
1050 fz_intersect_rect (&rect, &mediabox);
1052 if (!fz_is_empty_rect (&rect)) {
1053 mediabox = rect;
1056 fz_drop_page (ctx, page);
1057 if (!state.cxack) {
1058 printd ("progress %f loading %d",
1059 (double) (pageno + 1) / state.pagecount,
1060 pageno + 1);
1063 fz_catch (ctx) {
1065 if (trimf) {
1066 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1067 if (n - 1) {
1068 err (1, "fwrite trim mediabox");
1072 else {
1073 if (trimf) {
1074 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1075 if (n - 1) {
1076 err (1, "fread trim mediabox %d", pageno);
1079 else {
1080 fz_page *page;
1081 fz_try (ctx) {
1082 page = fz_load_page (ctx, state.doc, pageno);
1083 fz_bound_page (ctx, page, &mediabox);
1084 fz_drop_page (ctx, page);
1086 show = !state.trimmargins && pageno % 20 == 0;
1087 if (show) {
1088 printd ("progress %f Gathering dimensions %d",
1089 (double) (pageno) / state.pagecount,
1090 pageno);
1093 fz_catch (ctx) {
1094 fprintf (stderr, "failed to load page %d\n", pageno);
1100 if (state.pagedimcount == 0
1101 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1102 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1103 size_t size;
1105 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1106 state.pagedims = realloc (state.pagedims, size);
1107 if (!state.pagedims) {
1108 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1109 size, state.pagedimcount + 1);
1112 p = &state.pagedims[state.pagedimcount++];
1113 p->rotate = rotate;
1114 p->mediabox = mediabox;
1115 p->pageno = pageno;
1118 end = now ();
1119 if (!wthack) {
1120 printd ("progress 1 %s %d pages in %f seconds",
1121 state.trimmargins ? "Trimmed" : "Processed",
1122 state.pagecount, end - start);
1124 state.trimanew = 0;
1125 if (trimf) {
1126 if (fclose (trimf)) {
1127 err (1, "fclose");
1132 static void layout (void)
1134 int pindex;
1135 fz_rect box;
1136 fz_matrix ctm, rm;
1137 struct pagedim *p = p;
1138 double zw, w, maxw = 0.0, zoom = zoom;
1140 if (state.pagedimcount == 0) return;
1142 switch (state.fitmodel) {
1143 case FitProportional:
1144 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1145 double x0, x1;
1147 p = &state.pagedims[pindex];
1148 fz_rotate (&rm, p->rotate + state.rotate);
1149 box = p->mediabox;
1150 fz_transform_rect (&box, &rm);
1152 x0 = fz_min (box.x0, box.x1);
1153 x1 = fz_max (box.x0, box.x1);
1155 w = x1 - x0;
1156 maxw = fz_max (w, maxw);
1157 zoom = state.w / maxw;
1159 break;
1161 case FitPage:
1162 maxw = state.w;
1163 break;
1165 case FitWidth:
1166 break;
1168 default:
1169 ARSERT (0 && state.fitmodel);
1172 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1173 fz_rect rect;
1174 fz_matrix tm, sm;
1176 p = &state.pagedims[pindex];
1177 fz_rotate (&ctm, state.rotate);
1178 fz_rotate (&rm, p->rotate + state.rotate);
1179 box = p->mediabox;
1180 fz_transform_rect (&box, &rm);
1181 w = box.x1 - box.x0;
1182 switch (state.fitmodel) {
1183 case FitProportional:
1184 p->left = ((maxw - w) * zoom) / 2.0;
1185 break;
1186 case FitPage:
1188 double zh, h;
1189 zw = maxw / w;
1190 h = box.y1 - box.y0;
1191 zh = state.h / h;
1192 zoom = fz_min (zw, zh);
1193 p->left = (maxw - (w * zoom)) / 2.0;
1195 break;
1196 case FitWidth:
1197 p->left = 0;
1198 zoom = state.w / w;
1199 break;
1202 fz_scale (&p->zoomctm, zoom, zoom);
1203 fz_concat (&ctm, &p->zoomctm, &ctm);
1205 fz_rotate (&rm, p->rotate);
1206 p->pagebox = p->mediabox;
1207 fz_transform_rect (&p->pagebox, &rm);
1208 p->pagebox.x1 -= p->pagebox.x0;
1209 p->pagebox.y1 -= p->pagebox.y0;
1210 p->pagebox.x0 = 0;
1211 p->pagebox.y0 = 0;
1212 rect = p->pagebox;
1213 fz_transform_rect (&rect, &ctm);
1214 fz_round_rect (&p->bounds, &rect);
1215 p->ctm = ctm;
1217 fz_translate (&tm, 0, -p->mediabox.y1);
1218 fz_scale (&sm, zoom, -zoom);
1219 fz_concat (&ctm, &tm, &sm);
1221 p->tctmready = 0;
1224 do {
1225 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1226 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1227 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1228 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1229 int boundw = x1 - x0;
1230 int boundh = y1 - y0;
1232 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1233 } while (p-- != state.pagedims);
1236 struct pagedim *pdimofpageno (int pageno)
1238 struct pagedim *pdim = state.pagedims;
1240 for (int i = 0; i < state.pagedimcount; ++i) {
1241 if (state.pagedims[i].pageno > pageno)
1242 break;
1243 pdim = &state.pagedims[i];
1245 return pdim;
1248 static
1249 struct anchor { int n; int x; int y; int w; int h; }
1250 uritoanchor (const char *uri)
1252 fz_point p;
1253 struct anchor a;
1255 a.n = -1;
1256 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1257 if (a.n >= 0) {
1258 struct pagedim *pdim = pdimofpageno (a.n);
1259 fz_transform_point (&p, &pdim->ctm);
1260 a.x = p.x;
1261 a.y = p.y;
1262 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1264 return a;
1267 static void recurse_outline (fz_outline *outline, int level)
1269 while (outline) {
1270 struct anchor a = uritoanchor (outline->uri);
1271 if (a.n >= 0) {
1272 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1274 else {
1275 printd ("on %d %s", level, outline->title);
1277 if (outline->down) {
1278 recurse_outline (outline->down, level + 1);
1280 outline = outline->next;
1284 static void process_outline (void)
1286 fz_outline *outline;
1288 if (!state.needoutline || !state.pagedimcount) return;
1290 state.needoutline = 0;
1291 outline = fz_load_outline (state.ctx, state.doc);
1292 if (outline) {
1293 recurse_outline (outline, 0);
1294 fz_drop_outline (state.ctx, outline);
1298 static char *strofspan (fz_stext_span *span)
1300 char *p;
1301 char utf8[10];
1302 fz_stext_char *ch;
1303 size_t size = 0, cap = 80;
1305 p = malloc (cap + 1);
1306 if (!p) return NULL;
1308 for (ch = span->text; ch < span->text + span->len; ++ch) {
1309 int n = fz_runetochar (utf8, ch->c);
1310 if (size + n > cap) {
1311 cap *= 2;
1312 p = realloc (p, cap + 1);
1313 if (!p) return NULL;
1316 memcpy (p + size, utf8, n);
1317 size += n;
1319 p[size] = 0;
1320 return p;
1323 static int matchspan (regex_t *re, fz_stext_span *span,
1324 int stop, int pageno, double start)
1326 int ret;
1327 char *p;
1328 regmatch_t rm;
1329 int a, b, c;
1330 fz_rect sb, eb;
1331 fz_point p1, p2, p3, p4;
1333 p = strofspan (span);
1334 if (!p) return -1;
1336 ret = regexec (re, p, 1, &rm, 0);
1337 if (ret) {
1338 free (p);
1339 if (ret != REG_NOMATCH) {
1340 size_t size;
1341 char errbuf[80];
1342 size = regerror (ret, re, errbuf, sizeof (errbuf));
1343 printd ("msg regexec error `%.*s'",
1344 (int) size, errbuf);
1345 return -1;
1347 return 0;
1349 else {
1350 int l = span->len;
1352 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1353 c += fz_runelen (span->text[a].c);
1355 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1356 c += fz_runelen (span->text[b].c);
1359 if (fz_runelen (span->text[b].c) > 1) {
1360 b = fz_maxi (0, b-1);
1363 fz_stext_char_bbox (state.ctx, &sb, span, a);
1364 fz_stext_char_bbox (state.ctx, &eb, span, b);
1366 p1.x = sb.x0;
1367 p1.y = sb.y0;
1368 p2.x = eb.x1;
1369 p2.y = sb.y0;
1370 p3.x = eb.x1;
1371 p3.y = eb.y1;
1372 p4.x = sb.x0;
1373 p4.y = eb.y1;
1375 if (!stop) {
1376 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1377 pageno, 1,
1378 p1.x, p1.y,
1379 p2.x, p2.y,
1380 p3.x, p3.y,
1381 p4.x, p4.y);
1383 printd ("progress 1 found at %d `%.*s' in %f sec",
1384 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1385 now () - start);
1387 else {
1388 printd ("match %d %d %f %f %f %f %f %f %f %f",
1389 pageno, 2,
1390 p1.x, p1.y,
1391 p2.x, p2.y,
1392 p3.x, p3.y,
1393 p4.x, p4.y);
1395 free (p);
1396 return 1;
1400 static int compareblocks (const void *l, const void *r)
1402 fz_stext_block const *ls = l;
1403 fz_stext_block const *rs = r;
1404 return ls->bbox.y0 - rs->bbox.y0;
1407 /* wishful thinking function */
1408 static void search (regex_t *re, int pageno, int y, int forward)
1410 int j;
1411 fz_device *tdev;
1412 fz_stext_page *text;
1413 fz_stext_sheet *sheet;
1414 struct pagedim *pdim;
1415 int stop = 0, niters = 0;
1416 double start, end;
1417 fz_page *page;
1419 start = now ();
1420 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1421 if (niters++ == 5) {
1422 niters = 0;
1423 if (hasdata ()) {
1424 printd ("progress 1 attention requested aborting search at %d",
1425 pageno);
1426 stop = 1;
1428 else {
1429 printd ("progress %f searching in page %d",
1430 (double) (pageno + 1) / state.pagecount,
1431 pageno);
1434 pdim = pdimofpageno (pageno);
1435 sheet = fz_new_stext_sheet (state.ctx);
1436 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1437 tdev = fz_new_stext_device (state.ctx, sheet, text, 0);
1439 page = fz_load_page (state.ctx, state.doc, pageno);
1441 fz_matrix ctm = pagectm1 (page, pdim);
1442 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1445 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1446 fz_close_device (state.ctx, tdev);
1447 fz_drop_device (state.ctx, tdev);
1449 for (j = 0; j < text->len; ++j) {
1450 int k;
1451 fz_page_block *pb;
1452 fz_stext_block *block;
1454 pb = &text->blocks[forward ? j : text->len - 1 - j];
1455 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1456 block = pb->u.text;
1458 for (k = 0; k < block->len; ++k) {
1459 fz_stext_line *line;
1460 fz_stext_span *span;
1462 if (forward) {
1463 line = &block->lines[k];
1464 if (line->bbox.y0 < y + 1) continue;
1466 else {
1467 line = &block->lines[block->len - 1 - k];
1468 if (line->bbox.y0 > y - 1) continue;
1471 for (span = line->first_span; span; span = span->next) {
1472 switch (matchspan (re, span, stop, pageno, start)) {
1473 case 0: break;
1474 case 1: stop = 1; break;
1475 case -1: stop = 1; goto endloop;
1480 if (forward) {
1481 pageno += 1;
1482 y = 0;
1484 else {
1485 pageno -= 1;
1486 y = INT_MAX;
1488 endloop:
1489 fz_drop_stext_page (state.ctx, text);
1490 fz_drop_stext_sheet (state.ctx, sheet);
1491 fz_drop_page (state.ctx, page);
1493 end = now ();
1494 if (!stop) {
1495 printd ("progress 1 no matches %f sec", end - start);
1497 printd ("clearrects");
1500 static void set_tex_params (int colorspace)
1502 union {
1503 unsigned char b;
1504 unsigned int s;
1505 } endianness = {1};
1507 switch (colorspace) {
1508 case 0:
1509 state.texiform = GL_RGBA8;
1510 state.texform = GL_RGBA;
1511 state.texty = GL_UNSIGNED_BYTE;
1512 state.colorspace = fz_device_rgb (state.ctx);
1513 break;
1514 case 1:
1515 state.texiform = GL_RGBA8;
1516 state.texform = GL_BGRA;
1517 state.texty = endianness.s > 1
1518 ? GL_UNSIGNED_INT_8_8_8_8
1519 : GL_UNSIGNED_INT_8_8_8_8_REV;
1520 state.colorspace = fz_device_bgr (state.ctx);
1521 break;
1522 case 2:
1523 state.texiform = GL_LUMINANCE_ALPHA;
1524 state.texform = GL_LUMINANCE_ALPHA;
1525 state.texty = GL_UNSIGNED_BYTE;
1526 state.colorspace = fz_device_gray (state.ctx);
1527 break;
1528 default:
1529 errx (1, "invalid colorspce %d", colorspace);
1533 static void realloctexts (int texcount)
1535 size_t size;
1537 if (texcount == state.texcount) return;
1539 if (texcount < state.texcount) {
1540 glDeleteTextures (state.texcount - texcount,
1541 state.texids + texcount);
1544 size = texcount * sizeof (*state.texids);
1545 state.texids = realloc (state.texids, size);
1546 if (!state.texids) {
1547 err (1, "realloc texids %" FMT_s, size);
1550 size = texcount * sizeof (*state.texowners);
1551 state.texowners = realloc (state.texowners, size);
1552 if (!state.texowners) {
1553 err (1, "realloc texowners %" FMT_s, size);
1555 if (texcount > state.texcount) {
1556 glGenTextures (texcount - state.texcount,
1557 state.texids + state.texcount);
1558 for (int i = state.texcount; i < texcount; ++i) {
1559 state.texowners[i].w = -1;
1560 state.texowners[i].slice = NULL;
1563 state.texcount = texcount;
1564 state.texindex = 0;
1567 static char *mbtoutf8 (char *s)
1569 char *p, *r;
1570 wchar_t *tmp;
1571 size_t i, ret, len;
1573 len = mbstowcs (NULL, s, strlen (s));
1574 if (len == 0) {
1575 return s;
1577 else {
1578 if (len == (size_t) -1) {
1579 return s;
1583 tmp = malloc (len * sizeof (wchar_t));
1584 if (!tmp) {
1585 return s;
1588 ret = mbstowcs (tmp, s, len);
1589 if (ret == (size_t) -1) {
1590 free (tmp);
1591 return s;
1594 len = 0;
1595 for (i = 0; i < ret; ++i) {
1596 len += fz_runelen (tmp[i]);
1599 p = r = malloc (len + 1);
1600 if (!r) {
1601 free (tmp);
1602 return s;
1605 for (i = 0; i < ret; ++i) {
1606 p += fz_runetochar (p, tmp[i]);
1608 *p = 0;
1609 free (tmp);
1610 return r;
1613 CAMLprim value ml_mbtoutf8 (value s_v)
1615 CAMLparam1 (s_v);
1616 CAMLlocal1 (ret_v);
1617 char *s, *r;
1619 s = String_val (s_v);
1620 r = mbtoutf8 (s);
1621 if (r == s) {
1622 ret_v = s_v;
1624 else {
1625 ret_v = caml_copy_string (r);
1626 free (r);
1628 CAMLreturn (ret_v);
1631 static void * mainloop (void UNUSED_ATTR *unused)
1633 char *p = NULL;
1634 int len, ret, oldlen = 0;
1636 fz_var (p);
1637 fz_var (oldlen);
1638 for (;;) {
1639 len = readlen (state.csock);
1640 if (len == 0) {
1641 errx (1, "readlen returned 0");
1644 if (oldlen < len + 1) {
1645 p = realloc (p, len + 1);
1646 if (!p) {
1647 err (1, "realloc %d failed", len + 1);
1649 oldlen = len + 1;
1651 readdata (state.csock, p, len);
1652 p[len] = 0;
1654 if (!strncmp ("open", p, 4)) {
1655 int wthack, off, usedoccss, ok = 0;
1656 char *password;
1657 char *filename;
1658 char *utf8filename;
1659 size_t filenamelen;
1661 fz_var (ok);
1662 ret = sscanf (p + 5, " %d %d %d %n",
1663 &wthack, &state.cxack, &usedoccss, &off);
1664 if (ret != 3) {
1665 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1668 filename = p + 5 + off;
1669 filenamelen = strlen (filename);
1670 password = filename + filenamelen + 1;
1672 if (password[strlen (password) + 1]) {
1673 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1676 lock ("open");
1677 fz_set_use_document_css (state.ctx, usedoccss);
1678 fz_try (state.ctx) {
1679 ok = openxref (filename, password);
1681 fz_catch (state.ctx) {
1682 utf8filename = mbtoutf8 (filename);
1683 printd ("msg Could not open %s", utf8filename);
1685 if (ok) {
1686 pdfinfo ();
1687 initpdims (wthack);
1689 unlock ("open");
1691 if (ok) {
1692 if (!wthack) {
1693 utf8filename = mbtoutf8 (filename);
1694 printd ("msg Opened %s (press h/F1 to get help)",
1695 utf8filename);
1696 if (utf8filename != filename) {
1697 free (utf8filename);
1700 state.needoutline = 1;
1703 else if (!strncmp ("cs", p, 2)) {
1704 int i, colorspace;
1706 ret = sscanf (p + 2, " %d", &colorspace);
1707 if (ret != 1) {
1708 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1710 lock ("cs");
1711 set_tex_params (colorspace);
1712 for (i = 0; i < state.texcount; ++i) {
1713 state.texowners[i].w = -1;
1714 state.texowners[i].slice = NULL;
1716 unlock ("cs");
1718 else if (!strncmp ("freepage", p, 8)) {
1719 void *ptr;
1721 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1722 if (ret != 1) {
1723 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1725 freepage (ptr);
1727 else if (!strncmp ("freetile", p, 8)) {
1728 void *ptr;
1730 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1731 if (ret != 1) {
1732 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1734 freetile (ptr);
1736 else if (!strncmp ("search", p, 6)) {
1737 int icase, pageno, y, len2, forward;
1738 char *pattern;
1739 regex_t re;
1741 ret = sscanf (p + 6, " %d %d %d %d,%n",
1742 &icase, &pageno, &y, &forward, &len2);
1743 if (ret != 4) {
1744 errx (1, "malformed search `%s' ret=%d", p, ret);
1747 pattern = p + 6 + len2;
1748 ret = regcomp (&re, pattern,
1749 REG_EXTENDED | (icase ? REG_ICASE : 0));
1750 if (ret) {
1751 char errbuf[80];
1752 size_t size;
1754 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1755 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1757 else {
1758 search (&re, pageno, y, forward);
1759 regfree (&re);
1762 else if (!strncmp ("geometry", p, 8)) {
1763 int w, h, fitmodel;
1765 printd ("clear");
1766 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1767 if (ret != 3) {
1768 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1771 lock ("geometry");
1772 state.h = h;
1773 if (w != state.w) {
1774 state.w = w;
1775 for (int i = 0; i < state.texcount; ++i) {
1776 state.texowners[i].slice = NULL;
1779 state.fitmodel = fitmodel;
1780 layout ();
1781 process_outline ();
1783 state.gen++;
1784 unlock ("geometry");
1785 printd ("continue %d", state.pagecount);
1787 else if (!strncmp ("reqlayout", p, 9)) {
1788 char *nameddest;
1789 int rotate, off, h;
1790 unsigned int fitmodel;
1791 pdf_document *pdf;
1793 printd ("clear");
1794 ret = sscanf (p + 9, " %d %u %d %n",
1795 &rotate, &fitmodel, &h, &off);
1796 if (ret != 3) {
1797 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1799 lock ("reqlayout");
1800 pdf = pdf_specifics (state.ctx, state.doc);
1801 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1802 state.gen += 1;
1804 state.rotate = rotate;
1805 state.fitmodel = fitmodel;
1806 state.h = h;
1807 layout ();
1808 process_outline ();
1810 nameddest = p + 9 + off;
1811 if (pdf && nameddest && *nameddest) {
1812 fz_point xy;
1813 struct pagedim *pdim;
1814 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1815 &xy.x, &xy.y);
1816 pdim = pdimofpageno (pageno);
1817 fz_transform_point (&xy, &pdim->ctm);
1818 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1821 state.gen++;
1822 unlock ("reqlayout");
1823 printd ("continue %d", state.pagecount);
1825 else if (!strncmp ("page", p, 4)) {
1826 double a, b;
1827 struct page *page;
1828 int pageno, pindex;
1830 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1831 if (ret != 2) {
1832 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1835 lock ("page");
1836 a = now ();
1837 page = loadpage (pageno, pindex);
1838 b = now ();
1839 unlock ("page");
1841 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1843 else if (!strncmp ("tile", p, 4)) {
1844 int x, y, w, h;
1845 struct page *page;
1846 struct tile *tile;
1847 double a, b;
1848 void *data;
1850 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1851 SCN_ptr_cast (&page), &x, &y, &w, &h,
1852 SCN_ptr_cast (&data));
1853 if (ret != 6) {
1854 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1857 lock ("tile");
1858 a = now ();
1859 tile = rendertile (page, x, y, w, h, data);
1860 b = now ();
1861 unlock ("tile");
1863 printd ("tile %d %d %" FMT_ptr " %u %f",
1864 x, y,
1865 FMT_ptr_cast (tile),
1866 tile->w * tile->h * tile->pixmap->n,
1867 b - a);
1869 else if (!strncmp ("trimset", p, 7)) {
1870 fz_irect fuzz;
1871 int trimmargins;
1873 ret = sscanf (p + 7, " %d %d %d %d %d",
1874 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1875 if (ret != 5) {
1876 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1878 lock ("trimset");
1879 state.trimmargins = trimmargins;
1880 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1881 state.trimanew = 1;
1882 state.trimfuzz = fuzz;
1884 unlock ("trimset");
1886 else if (!strncmp ("settrim", p, 7)) {
1887 fz_irect fuzz;
1888 int trimmargins;
1890 ret = sscanf (p + 7, " %d %d %d %d %d",
1891 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1892 if (ret != 5) {
1893 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1895 printd ("clear");
1896 lock ("settrim");
1897 state.trimmargins = trimmargins;
1898 state.needoutline = 1;
1899 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1900 state.trimanew = 1;
1901 state.trimfuzz = fuzz;
1903 state.pagedimcount = 0;
1904 free (state.pagedims);
1905 state.pagedims = NULL;
1906 initpdims (0);
1907 layout ();
1908 process_outline ();
1909 unlock ("settrim");
1910 printd ("continue %d", state.pagecount);
1912 else if (!strncmp ("sliceh", p, 6)) {
1913 int h;
1915 ret = sscanf (p + 6, " %d", &h);
1916 if (ret != 1) {
1917 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1919 if (h != state.sliceheight) {
1920 state.sliceheight = h;
1921 for (int i = 0; i < state.texcount; ++i) {
1922 state.texowners[i].w = -1;
1923 state.texowners[i].h = -1;
1924 state.texowners[i].slice = NULL;
1928 else if (!strncmp ("interrupt", p, 9)) {
1929 printd ("vmsg interrupted");
1931 else {
1932 errx (1, "unknown command %.*s", len, p);
1935 return 0;
1938 CAMLprim value ml_isexternallink (value uri_v)
1940 CAMLparam1 (uri_v);
1941 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1942 CAMLreturn (Val_bool (ext));
1945 CAMLprim value ml_uritolocation (value uri_v)
1947 CAMLparam1 (uri_v);
1948 CAMLlocal1 (ret_v);
1949 int pageno;
1950 fz_point xy;
1951 struct pagedim *pdim;
1953 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1954 &xy.x, &xy.y);
1955 pdim = pdimofpageno (pageno);
1956 fz_transform_point (&xy, &pdim->ctm);
1957 ret_v = caml_alloc_tuple (3);
1958 Field (ret_v, 0) = Val_int (pageno);
1959 Field (ret_v, 1) = caml_copy_double (xy.x);
1960 Field (ret_v, 2) = caml_copy_double (xy.y);
1961 CAMLreturn (ret_v);
1964 CAMLprim value ml_realloctexts (value texcount_v)
1966 CAMLparam1 (texcount_v);
1967 int ok;
1969 if (trylock (__func__)) {
1970 ok = 0;
1971 goto done;
1973 realloctexts (Int_val (texcount_v));
1974 ok = 1;
1975 unlock (__func__);
1977 done:
1978 CAMLreturn (Val_bool (ok));
1981 static void recti (int x0, int y0, int x1, int y1)
1983 GLfloat *v = state.vertices;
1985 glVertexPointer (2, GL_FLOAT, 0, v);
1986 v[0] = x0; v[1] = y0;
1987 v[2] = x1; v[3] = y0;
1988 v[4] = x0; v[5] = y1;
1989 v[6] = x1; v[7] = y1;
1990 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1993 static void showsel (struct page *page, int ox, int oy)
1995 int seen = 0;
1996 fz_irect bbox;
1997 fz_rect rect;
1998 fz_stext_line *line;
1999 fz_page_block *pageb;
2000 fz_stext_block *block;
2001 struct mark first, last;
2002 unsigned char selcolor[] = {15,15,15,140};
2004 first = page->fmark;
2005 last = page->lmark;
2007 if (!first.span || !last.span) return;
2009 glEnable (GL_BLEND);
2010 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2011 glColor4ubv (selcolor);
2013 ox += state.pagedims[page->pdimno].bounds.x0;
2014 oy += state.pagedims[page->pdimno].bounds.y0;
2015 for (pageb = page->text->blocks;
2016 pageb < page->text->blocks + page->text->len;
2017 ++pageb) {
2018 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2019 block = pageb->u.text;
2021 for (line = block->lines;
2022 line < block->lines + block->len;
2023 ++line) {
2024 fz_stext_span *span;
2025 rect = fz_empty_rect;
2027 for (span = line->first_span; span; span = span->next) {
2028 int i, j, k;
2029 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2031 j = 0;
2032 k = span->len - 1;
2034 if (span == page->fmark.span && span == page->lmark.span) {
2035 seen = 1;
2036 j = fz_mini (first.i, last.i);
2037 k = fz_maxi (first.i, last.i);
2039 else {
2040 if (span == first.span) {
2041 seen = 1;
2042 j = first.i;
2044 else if (span == last.span) {
2045 seen = 1;
2046 k = last.i;
2050 if (seen) {
2051 for (i = j; i <= k; ++i) {
2052 fz_rect bbox1;
2053 fz_union_rect (&rect,
2054 fz_stext_char_bbox (state.ctx, &bbox1,
2055 span, i));
2057 fz_round_rect (&bbox, &rect);
2058 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2059 bbox.x0,
2060 bbox.y0,
2061 bbox.x1,
2062 bbox.y1,
2063 oy, ox);
2065 recti (bbox.x0 + ox, bbox.y0 + oy,
2066 bbox.x1 + ox, bbox.y1 + oy);
2067 if (span == last.span) {
2068 goto done;
2070 rect = fz_empty_rect;
2075 done:
2076 glDisable (GL_BLEND);
2079 #include "glfont.c"
2081 static void stipplerect (fz_matrix *m,
2082 fz_point *p1,
2083 fz_point *p2,
2084 fz_point *p3,
2085 fz_point *p4,
2086 GLfloat *texcoords,
2087 GLfloat *vertices)
2089 fz_transform_point (p1, m);
2090 fz_transform_point (p2, m);
2091 fz_transform_point (p3, m);
2092 fz_transform_point (p4, m);
2094 float w, h, s, t;
2096 w = p2->x - p1->x;
2097 h = p2->y - p1->y;
2098 t = hypotf (w, h) * .25f;
2100 w = p3->x - p2->x;
2101 h = p3->y - p2->y;
2102 s = hypotf (w, h) * .25f;
2104 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2105 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2107 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2108 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2110 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2111 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2113 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2114 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2116 glDrawArrays (GL_LINES, 0, 8);
2119 static void solidrect (fz_matrix *m,
2120 fz_point *p1,
2121 fz_point *p2,
2122 fz_point *p3,
2123 fz_point *p4,
2124 GLfloat *vertices)
2126 fz_transform_point (p1, m);
2127 fz_transform_point (p2, m);
2128 fz_transform_point (p3, m);
2129 fz_transform_point (p4, m);
2130 vertices[0] = p1->x; vertices[1] = p1->y;
2131 vertices[2] = p2->x; vertices[3] = p2->y;
2133 vertices[4] = p3->x; vertices[5] = p3->y;
2134 vertices[6] = p4->x; vertices[7] = p4->y;
2135 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2138 static void highlightlinks (struct page *page, int xoff, int yoff)
2140 fz_matrix ctm, tm, pm;
2141 fz_link *link, *links;
2142 GLfloat *texcoords = state.texcoords;
2143 GLfloat *vertices = state.vertices;
2145 links = fz_load_links (state.ctx, page->fzpage);
2147 glEnable (GL_TEXTURE_1D);
2148 glEnable (GL_BLEND);
2149 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2150 glBindTexture (GL_TEXTURE_1D, state.stid);
2152 xoff -= state.pagedims[page->pdimno].bounds.x0;
2153 yoff -= state.pagedims[page->pdimno].bounds.y0;
2154 fz_translate (&tm, xoff, yoff);
2155 pm = pagectm (page);
2156 fz_concat (&ctm, &pm, &tm);
2158 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2159 glVertexPointer (2, GL_FLOAT, 0, vertices);
2161 for (link = links; link; link = link->next) {
2162 fz_point p1, p2, p3, p4;
2164 p1.x = link->rect.x0;
2165 p1.y = link->rect.y0;
2167 p2.x = link->rect.x1;
2168 p2.y = link->rect.y0;
2170 p3.x = link->rect.x1;
2171 p3.y = link->rect.y1;
2173 p4.x = link->rect.x0;
2174 p4.y = link->rect.y1;
2176 /* TODO: different colours for different schemes */
2177 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2178 else glColor3ub (255, 0, 0);
2180 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2183 for (int i = 0; i < page->annotcount; ++i) {
2184 fz_point p1, p2, p3, p4;
2185 struct annot *annot = &page->annots[i];
2187 p1.x = annot->bbox.x0;
2188 p1.y = annot->bbox.y0;
2190 p2.x = annot->bbox.x1;
2191 p2.y = annot->bbox.y0;
2193 p3.x = annot->bbox.x1;
2194 p3.y = annot->bbox.y1;
2196 p4.x = annot->bbox.x0;
2197 p4.y = annot->bbox.y1;
2199 glColor3ub (0, 0, 128);
2200 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2203 glDisable (GL_BLEND);
2204 glDisable (GL_TEXTURE_1D);
2207 static int compareslinks (const void *l, const void *r)
2209 struct slink const *ls = l;
2210 struct slink const *rs = r;
2211 if (ls->bbox.y0 == rs->bbox.y0) {
2212 return rs->bbox.x0 - rs->bbox.x0;
2214 return ls->bbox.y0 - rs->bbox.y0;
2217 static void droptext (struct page *page)
2219 if (page->text) {
2220 fz_drop_stext_page (state.ctx, page->text);
2221 page->fmark.i = -1;
2222 page->lmark.i = -1;
2223 page->fmark.span = NULL;
2224 page->lmark.span = NULL;
2225 page->text = NULL;
2227 if (page->sheet) {
2228 fz_drop_stext_sheet (state.ctx, page->sheet);
2229 page->sheet = NULL;
2233 static void dropannots (struct page *page)
2235 if (page->annots) {
2236 free (page->annots);
2237 page->annots = NULL;
2238 page->annotcount = 0;
2242 static void ensureannots (struct page *page)
2244 int i, count = 0;
2245 size_t annotsize = sizeof (*page->annots);
2246 fz_annot *annot;
2248 if (state.gen != page->agen) {
2249 dropannots (page);
2250 page->agen = state.gen;
2252 if (page->annots) return;
2254 for (annot = fz_first_annot (state.ctx, page->fzpage);
2255 annot;
2256 annot = fz_next_annot (state.ctx, annot)) {
2257 count++;
2260 if (count > 0) {
2261 page->annotcount = count;
2262 page->annots = calloc (count, annotsize);
2263 if (!page->annots) {
2264 err (1, "calloc annots %d", count);
2267 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2268 annot;
2269 annot = fz_next_annot (state.ctx, annot), i++) {
2270 fz_rect rect;
2272 fz_bound_annot (state.ctx, annot, &rect);
2273 page->annots[i].annot = annot;
2274 fz_round_rect (&page->annots[i].bbox, &rect);
2279 static void dropslinks (struct page *page)
2281 if (page->slinks) {
2282 free (page->slinks);
2283 page->slinks = NULL;
2284 page->slinkcount = 0;
2288 static void ensureslinks (struct page *page)
2290 fz_matrix ctm;
2291 int i, count;
2292 size_t slinksize = sizeof (*page->slinks);
2293 fz_link *link, *links;
2295 ensureannots (page);
2296 if (state.gen != page->sgen) {
2297 dropslinks (page);
2298 page->sgen = state.gen;
2300 if (page->slinks) return;
2302 links = fz_load_links (state.ctx, page->fzpage);
2303 ctm = pagectm (page);
2305 count = page->annotcount;
2306 for (link = links; link; link = link->next) {
2307 count++;
2309 if (count > 0) {
2310 int j;
2312 page->slinkcount = count;
2313 page->slinks = calloc (count, slinksize);
2314 if (!page->slinks) {
2315 err (1, "calloc slinks %d", count);
2318 for (i = 0, link = links; link; ++i, link = link->next) {
2319 fz_rect rect;
2321 rect = link->rect;
2322 fz_transform_rect (&rect, &ctm);
2323 page->slinks[i].tag = SLINK;
2324 page->slinks[i].u.link = link;
2325 fz_round_rect (&page->slinks[i].bbox, &rect);
2327 for (j = 0; j < page->annotcount; ++j, ++i) {
2328 fz_rect rect;
2329 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2330 fz_transform_rect (&rect, &ctm);
2331 fz_round_rect (&page->slinks[i].bbox, &rect);
2333 page->slinks[i].tag = SANNOT;
2334 page->slinks[i].u.annot = page->annots[j].annot;
2336 qsort (page->slinks, count, slinksize, compareslinks);
2340 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2341 static void fmt_linkn (char *s, unsigned int u)
2343 unsigned int len; unsigned int q;
2344 unsigned int zma = 'z' - 'a' + 1;
2345 len = 1; q = u;
2346 while (q > zma - 1) { ++len; q /= zma; }
2347 if (s) {
2348 s += len;
2349 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2350 /* handles u == 0 */
2352 s[len] = 0;
2355 static void highlightslinks (struct page *page, int xoff, int yoff,
2356 int noff, char *targ, int tlen, int hfsize)
2358 char buf[40];
2359 struct slink *slink;
2360 double x0, y0, x1, y1, w;
2362 ensureslinks (page);
2363 glColor3ub (0xc3, 0xb0, 0x91);
2364 for (int i = 0; i < page->slinkcount; ++i) {
2365 fmt_linkn (buf, i + noff);
2366 if (!tlen || !strncmp (targ, buf, tlen)) {
2367 slink = &page->slinks[i];
2369 x0 = slink->bbox.x0 + xoff - 5;
2370 y1 = slink->bbox.y0 + yoff - 5;
2371 y0 = y1 + 10 + hfsize;
2372 w = measure_string (state.face, hfsize, buf);
2373 x1 = x0 + w + 10;
2374 recti (x0, y0, x1, y1);
2378 glEnable (GL_BLEND);
2379 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2380 glEnable (GL_TEXTURE_2D);
2381 glColor3ub (0, 0, 0);
2382 for (int i = 0; i < page->slinkcount; ++i) {
2383 fmt_linkn (buf, i + noff);
2384 if (!tlen || !strncmp (targ, buf, tlen)) {
2385 slink = &page->slinks[i];
2387 x0 = slink->bbox.x0 + xoff;
2388 y0 = slink->bbox.y0 + yoff + hfsize;
2389 draw_string (state.face, hfsize, x0, y0, buf);
2392 glDisable (GL_TEXTURE_2D);
2393 glDisable (GL_BLEND);
2396 static void uploadslice (struct tile *tile, struct slice *slice)
2398 int offset;
2399 struct slice *slice1;
2400 unsigned char *texdata;
2402 offset = 0;
2403 for (slice1 = tile->slices; slice != slice1; slice1++) {
2404 offset += slice1->h * tile->w * tile->pixmap->n;
2406 if (slice->texindex != -1 && slice->texindex < state.texcount
2407 && state.texowners[slice->texindex].slice == slice) {
2408 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2410 else {
2411 int subimage = 0;
2412 int texindex = state.texindex++ % state.texcount;
2414 if (state.texowners[texindex].w == tile->w) {
2415 if (state.texowners[texindex].h >= slice->h) {
2416 subimage = 1;
2418 else {
2419 state.texowners[texindex].h = slice->h;
2422 else {
2423 state.texowners[texindex].h = slice->h;
2426 state.texowners[texindex].w = tile->w;
2427 state.texowners[texindex].slice = slice;
2428 slice->texindex = texindex;
2430 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2431 #if TEXT_TYPE == GL_TEXTURE_2D
2432 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2433 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2434 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2435 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2436 #endif
2437 if (tile->pbo) {
2438 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2439 texdata = 0;
2441 else {
2442 texdata = tile->pixmap->samples;
2444 if (subimage) {
2445 glTexSubImage2D (TEXT_TYPE,
2449 tile->w,
2450 slice->h,
2451 state.texform,
2452 state.texty,
2453 texdata+offset
2456 else {
2457 glTexImage2D (TEXT_TYPE,
2459 state.texiform,
2460 tile->w,
2461 slice->h,
2463 state.texform,
2464 state.texty,
2465 texdata+offset
2468 if (tile->pbo) {
2469 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2474 CAMLprim value ml_begintiles (value unit_v)
2476 CAMLparam1 (unit_v);
2477 glEnable (TEXT_TYPE);
2478 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2479 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2480 CAMLreturn (unit_v);
2483 CAMLprim value ml_endtiles (value unit_v)
2485 CAMLparam1 (unit_v);
2486 glDisable (TEXT_TYPE);
2487 CAMLreturn (unit_v);
2490 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2492 CAMLparam2 (args_v, ptr_v);
2493 int dispx = Int_val (Field (args_v, 0));
2494 int dispy = Int_val (Field (args_v, 1));
2495 int dispw = Int_val (Field (args_v, 2));
2496 int disph = Int_val (Field (args_v, 3));
2497 int tilex = Int_val (Field (args_v, 4));
2498 int tiley = Int_val (Field (args_v, 5));
2499 char *s = String_val (ptr_v);
2500 struct tile *tile = parse_pointer (__func__, s);
2501 int slicey, firstslice;
2502 struct slice *slice;
2503 GLfloat *texcoords = state.texcoords;
2504 GLfloat *vertices = state.vertices;
2506 firstslice = tiley / tile->sliceheight;
2507 slice = &tile->slices[firstslice];
2508 slicey = tiley % tile->sliceheight;
2510 while (disph > 0) {
2511 int dh;
2513 dh = slice->h - slicey;
2514 dh = fz_mini (disph, dh);
2515 uploadslice (tile, slice);
2517 texcoords[0] = tilex; texcoords[1] = slicey;
2518 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2519 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2520 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2522 vertices[0] = dispx; vertices[1] = dispy;
2523 vertices[2] = dispx+dispw; vertices[3] = dispy;
2524 vertices[4] = dispx; vertices[5] = dispy+dh;
2525 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2527 #if TEXT_TYPE == GL_TEXTURE_2D
2528 for (int i = 0; i < 8; ++i) {
2529 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2531 #endif
2533 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2534 dispy += dh;
2535 disph -= dh;
2536 slice++;
2537 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2538 slicey = 0;
2540 CAMLreturn0;
2543 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2545 fz_matrix ctm, tm, pm;
2546 fz_point p1, p2, p3, p4;
2547 GLfloat *vertices = state.vertices;
2548 double *v = (double *) rects_v;
2550 xoff -= state.pagedims[page->pdimno].bounds.x0;
2551 yoff -= state.pagedims[page->pdimno].bounds.y0;
2552 fz_translate (&tm, xoff, yoff);
2553 pm = pagectm (page);
2554 fz_concat (&ctm, &pm, &tm);
2556 glEnable (GL_BLEND);
2557 glVertexPointer (2, GL_FLOAT, 0, vertices);
2559 glColor4dv (v);
2560 p1.x = v[4];
2561 p1.y = v[5];
2563 p2.x = v[6];
2564 p2.y = v[5];
2566 p3.x = v[6];
2567 p3.y = v[7];
2569 p4.x = v[4];
2570 p4.y = v[7];
2571 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2572 glDisable (GL_BLEND);
2575 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2576 value xoff_v, value yoff_v,
2577 value li_v)
2579 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2580 int xoff = Int_val (xoff_v);
2581 int yoff = Int_val (yoff_v);
2582 int noff = Int_val (Field (li_v, 0));
2583 char *targ = String_val (Field (li_v, 1));
2584 int tlen = caml_string_length (Field (li_v, 1));
2585 int hfsize = Int_val (Field (li_v, 2));
2586 char *s = String_val (ptr_v);
2587 int hlmask = Int_val (hlinks_v);
2588 struct page *page = parse_pointer (__func__, s);
2590 if (!page->fzpage) {
2591 /* deal with loadpage failed pages */
2592 goto done;
2595 if (trylock (__func__)) {
2596 noff = -1;
2597 goto done;
2600 ensureannots (page);
2601 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2602 if (hlmask & 2) {
2603 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2604 noff = page->slinkcount;
2606 if (page->tgen == state.gen) {
2607 showsel (page, xoff, yoff);
2609 unlock (__func__);
2611 done:
2612 CAMLreturn (Val_int (noff));
2615 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2616 value rects_v)
2618 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2619 int xoff = Int_val (xoff_v);
2620 int yoff = Int_val (yoff_v);
2621 char *s = String_val (ptr_v);
2622 struct page *page = parse_pointer (__func__, s);
2624 drawprect (page, xoff, yoff, rects_v);
2625 CAMLreturn0;
2628 static struct annot *getannot (struct page *page, int x, int y)
2630 fz_point p;
2631 fz_matrix ctm;
2632 const fz_matrix *tctm;
2633 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2635 if (!page->annots) return NULL;
2637 if (pdf) {
2638 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2639 tctm = &state.pagedims[page->pdimno].tctm;
2641 else {
2642 tctm = &fz_identity;
2645 p.x = x;
2646 p.y = y;
2648 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2649 fz_invert_matrix (&ctm, &ctm);
2650 fz_transform_point (&p, &ctm);
2652 if (pdf) {
2653 for (int i = 0; i < page->annotcount; ++i) {
2654 struct annot *a = &page->annots[i];
2655 fz_rect rect;
2657 fz_bound_annot (state.ctx, a->annot, &rect);
2658 if (p.x >= rect.x0 && p.x <= rect.x1) {
2659 if (p.y >= rect.y0 && p.y <= rect.y1)
2660 return a;
2664 return NULL;
2667 static fz_link *getlink (struct page *page, int x, int y)
2669 fz_point p;
2670 fz_matrix ctm;
2671 fz_link *link, *links;
2673 links = fz_load_links (state.ctx, page->fzpage);
2675 p.x = x;
2676 p.y = y;
2678 ctm = pagectm (page);
2679 fz_invert_matrix (&ctm, &ctm);
2680 fz_transform_point (&p, &ctm);
2682 for (link = links; link; link = link->next) {
2683 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2684 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2685 return link;
2689 return NULL;
2692 static void ensuretext (struct page *page)
2694 if (state.gen != page->tgen) {
2695 droptext (page);
2696 page->tgen = state.gen;
2698 if (!page->text) {
2699 fz_matrix ctm;
2700 fz_device *tdev;
2702 page->text = fz_new_stext_page (state.ctx,
2703 &state.pagedims[page->pdimno].mediabox);
2704 page->sheet = fz_new_stext_sheet (state.ctx);
2705 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2706 ctm = pagectm (page);
2707 fz_run_display_list (state.ctx, page->dlist,
2708 tdev, &ctm, &fz_infinite_rect, NULL);
2709 qsort (page->text->blocks, page->text->len,
2710 sizeof (*page->text->blocks), compareblocks);
2711 fz_close_device (state.ctx, tdev);
2712 fz_drop_device (state.ctx, tdev);
2716 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2718 CAMLparam2 (start_page_v, dir_v);
2719 CAMLlocal1 (ret_v);
2720 int i, dir = Int_val (dir_v);
2721 int start_page = Int_val (start_page_v);
2722 int end_page = dir > 0 ? state.pagecount : -1;
2723 pdf_document *pdf;
2725 fz_var (end_page);
2726 ret_v = Val_int (0);
2727 lock (__func__);
2728 pdf = pdf_specifics (state.ctx, state.doc);
2729 for (i = start_page + dir; i != end_page; i += dir) {
2730 int found;
2732 fz_var (found);
2733 if (pdf) {
2734 pdf_page *page = NULL;
2736 fz_var (page);
2737 fz_try (state.ctx) {
2738 page = pdf_load_page (state.ctx, pdf, i);
2739 found = !!page->links || !!page->annots;
2741 fz_catch (state.ctx) {
2742 found = 0;
2744 if (page) {
2745 fz_drop_page (state.ctx, &page->super);
2748 else {
2749 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2750 found = !!fz_load_links (state.ctx, page);
2751 fz_drop_page (state.ctx, page);
2754 if (found) {
2755 ret_v = caml_alloc_small (1, 1);
2756 Field (ret_v, 0) = Val_int (i);
2757 goto unlock;
2760 unlock:
2761 unlock (__func__);
2762 CAMLreturn (ret_v);
2765 enum { dir_first, dir_last };
2766 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2768 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2770 CAMLparam2 (ptr_v, dir_v);
2771 CAMLlocal2 (ret_v, pos_v);
2772 struct page *page;
2773 int dirtag, i, slinkindex;
2774 struct slink *found = NULL ,*slink;
2775 char *s = String_val (ptr_v);
2777 page = parse_pointer (__func__, s);
2778 ret_v = Val_int (0);
2779 lock (__func__);
2780 ensureslinks (page);
2782 if (Is_block (dir_v)) {
2783 dirtag = Tag_val (dir_v);
2784 switch (dirtag) {
2785 case dir_first_visible:
2787 int x0, y0, dir, first_index, last_index;
2789 pos_v = Field (dir_v, 0);
2790 x0 = Int_val (Field (pos_v, 0));
2791 y0 = Int_val (Field (pos_v, 1));
2792 dir = Int_val (Field (pos_v, 2));
2794 if (dir >= 0) {
2795 dir = 1;
2796 first_index = 0;
2797 last_index = page->slinkcount;
2799 else {
2800 first_index = page->slinkcount - 1;
2801 last_index = -1;
2804 for (i = first_index; i != last_index; i += dir) {
2805 slink = &page->slinks[i];
2806 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2807 found = slink;
2808 break;
2812 break;
2814 case dir_left:
2815 slinkindex = Int_val (Field (dir_v, 0));
2816 found = &page->slinks[slinkindex];
2817 for (i = slinkindex - 1; i >= 0; --i) {
2818 slink = &page->slinks[i];
2819 if (slink->bbox.x0 < found->bbox.x0) {
2820 found = slink;
2821 break;
2824 break;
2826 case dir_right:
2827 slinkindex = Int_val (Field (dir_v, 0));
2828 found = &page->slinks[slinkindex];
2829 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2830 slink = &page->slinks[i];
2831 if (slink->bbox.x0 > found->bbox.x0) {
2832 found = slink;
2833 break;
2836 break;
2838 case dir_down:
2839 slinkindex = Int_val (Field (dir_v, 0));
2840 found = &page->slinks[slinkindex];
2841 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2842 slink = &page->slinks[i];
2843 if (slink->bbox.y0 >= found->bbox.y0) {
2844 found = slink;
2845 break;
2848 break;
2850 case dir_up:
2851 slinkindex = Int_val (Field (dir_v, 0));
2852 found = &page->slinks[slinkindex];
2853 for (i = slinkindex - 1; i >= 0; --i) {
2854 slink = &page->slinks[i];
2855 if (slink->bbox.y0 <= found->bbox.y0) {
2856 found = slink;
2857 break;
2860 break;
2863 else {
2864 dirtag = Int_val (dir_v);
2865 switch (dirtag) {
2866 case dir_first:
2867 found = page->slinks;
2868 break;
2870 case dir_last:
2871 if (page->slinks) {
2872 found = page->slinks + (page->slinkcount - 1);
2874 break;
2877 if (found) {
2878 ret_v = caml_alloc_small (2, 1);
2879 Field (ret_v, 0) = Val_int (found - page->slinks);
2882 unlock (__func__);
2883 CAMLreturn (ret_v);
2886 enum { uuri, utext, uannot };
2888 CAMLprim value ml_getlink (value ptr_v, value n_v)
2890 CAMLparam2 (ptr_v, n_v);
2891 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2892 fz_link *link;
2893 struct page *page;
2894 char *s = String_val (ptr_v);
2895 struct slink *slink;
2897 ret_v = Val_int (0);
2898 page = parse_pointer (__func__, s);
2900 lock (__func__);
2901 ensureslinks (page);
2902 slink = &page->slinks[Int_val (n_v)];
2903 if (slink->tag == SLINK) {
2904 link = slink->u.link;
2905 str_v = caml_copy_string (link->uri);
2906 ret_v = caml_alloc_small (1, uuri);
2907 Field (ret_v, 0) = str_v;
2909 else {
2910 ret_v = caml_alloc_small (1, uannot);
2911 tup_v = caml_alloc_tuple (2);
2912 Field (ret_v, 0) = tup_v;
2913 Field (tup_v, 0) = ptr_v;
2914 Field (tup_v, 1) = n_v;
2916 unlock (__func__);
2918 CAMLreturn (ret_v);
2921 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2923 CAMLparam2 (ptr_v, n_v);
2924 pdf_document *pdf;
2925 const char *contents = "";
2927 lock (__func__);
2928 pdf = pdf_specifics (state.ctx, state.doc);
2929 if (pdf) {
2930 char *s = String_val (ptr_v);
2931 struct page *page;
2932 struct slink *slink;
2934 page = parse_pointer (__func__, s);
2935 slink = &page->slinks[Int_val (n_v)];
2936 contents = pdf_annot_contents (state.ctx,
2937 (pdf_annot *) slink->u.annot);
2939 unlock (__func__);
2940 CAMLreturn (caml_copy_string (contents));
2943 CAMLprim value ml_getlinkcount (value ptr_v)
2945 CAMLparam1 (ptr_v);
2946 struct page *page;
2947 char *s = String_val (ptr_v);
2949 page = parse_pointer (__func__, s);
2950 CAMLreturn (Val_int (page->slinkcount));
2953 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2955 CAMLparam2 (ptr_v, n_v);
2956 CAMLlocal1 (ret_v);
2957 struct page *page;
2958 struct slink *slink;
2959 char *s = String_val (ptr_v);
2961 page = parse_pointer (__func__, s);
2962 ret_v = caml_alloc_tuple (4);
2963 lock (__func__);
2964 ensureslinks (page);
2966 slink = &page->slinks[Int_val (n_v)];
2967 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2968 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2969 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2970 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2971 unlock (__func__);
2972 CAMLreturn (ret_v);
2975 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2977 CAMLparam3 (ptr_v, x_v, y_v);
2978 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2979 fz_link *link;
2980 struct annot *annot;
2981 struct page *page;
2982 char *ptr = String_val (ptr_v);
2983 int x = Int_val (x_v), y = Int_val (y_v);
2984 struct pagedim *pdim;
2986 ret_v = Val_int (0);
2987 if (trylock (__func__)) {
2988 goto done;
2991 page = parse_pointer (__func__, ptr);
2992 pdim = &state.pagedims[page->pdimno];
2993 x += pdim->bounds.x0;
2994 y += pdim->bounds.y0;
2997 annot = getannot (page, x, y);
2998 if (annot) {
2999 int i, n = -1;
3001 ensureslinks (page);
3002 for (i = 0; i < page->slinkcount; ++i) {
3003 if (page->slinks[i].tag == SANNOT
3004 && page->slinks[i].u.annot == annot->annot) {
3005 n = i;
3006 break;
3009 ret_v = caml_alloc_small (1, uannot);
3010 tup_v = caml_alloc_tuple (2);
3011 Field (ret_v, 0) = tup_v;
3012 Field (tup_v, 0) = ptr_v;
3013 Field (tup_v, 1) = Val_int (n);
3014 goto unlock;
3018 link = getlink (page, x, y);
3019 if (link) {
3020 str_v = caml_copy_string (link->uri);
3021 ret_v = caml_alloc_small (1, uuri);
3022 Field (ret_v, 0) = str_v;
3024 else {
3025 fz_rect *b;
3026 fz_page_block *pageb;
3027 fz_stext_block *block;
3029 ensuretext (page);
3030 for (pageb = page->text->blocks;
3031 pageb < page->text->blocks + page->text->len;
3032 ++pageb) {
3033 fz_stext_line *line;
3034 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3035 block = pageb->u.text;
3037 b = &block->bbox;
3038 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3039 continue;
3041 for (line = block->lines;
3042 line < block->lines + block->len;
3043 ++line) {
3044 fz_stext_span *span;
3046 b = &line->bbox;
3047 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3048 continue;
3050 for (span = line->first_span; span; span = span->next) {
3051 int charnum;
3053 b = &span->bbox;
3054 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3055 continue;
3057 for (charnum = 0; charnum < span->len; ++charnum) {
3058 fz_rect bbox;
3059 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3060 b = &bbox;
3062 if (x >= b->x0 && x <= b->x1
3063 && y >= b->y0 && y <= b->y1) {
3064 fz_stext_style *style = span->text->style;
3065 const char *n2 =
3066 style->font
3067 ? fz_font_name (state.ctx, style->font)
3068 : "Span has no font name"
3070 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3071 style->font);
3072 if (face && face->family_name) {
3073 char *s;
3074 char *n1 = face->family_name;
3075 size_t l1 = strlen (n1);
3076 size_t l2 = strlen (n2);
3078 if (l1 != l2 || memcmp (n1, n2, l1)) {
3079 s = malloc (l1 + l2 + 2);
3080 if (s) {
3081 memcpy (s, n2, l2);
3082 s[l2] = '=';
3083 memcpy (s + l2 + 1, n1, l1 + 1);
3084 str_v = caml_copy_string (s);
3085 free (s);
3089 if (str_v == Val_unit) {
3090 str_v = caml_copy_string (n2);
3092 ret_v = caml_alloc_small (1, utext);
3093 Field (ret_v, 0) = str_v;
3094 goto unlock;
3101 unlock:
3102 unlock (__func__);
3104 done:
3105 CAMLreturn (ret_v);
3108 enum { mark_page, mark_block, mark_line, mark_word };
3110 static int uninteresting (int c)
3112 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3113 || ispunct (c);
3116 CAMLprim void ml_clearmark (value ptr_v)
3118 CAMLparam1 (ptr_v);
3119 char *s = String_val (ptr_v);
3120 struct page *page;
3122 if (trylock (__func__)) {
3123 goto done;
3126 page = parse_pointer (__func__, s);
3127 page->fmark.span = NULL;
3128 page->lmark.span = NULL;
3129 page->fmark.i = 0;
3130 page->lmark.i = 0;
3132 unlock (__func__);
3133 done:
3134 CAMLreturn0;
3137 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3139 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3140 CAMLlocal1 (ret_v);
3141 fz_rect *b;
3142 struct page *page;
3143 fz_stext_line *line;
3144 fz_page_block *pageb;
3145 fz_stext_block *block;
3146 struct pagedim *pdim;
3147 int mark = Int_val (mark_v);
3148 char *s = String_val (ptr_v);
3149 int x = Int_val (x_v), y = Int_val (y_v);
3151 ret_v = Val_bool (0);
3152 if (trylock (__func__)) {
3153 goto done;
3156 page = parse_pointer (__func__, s);
3157 pdim = &state.pagedims[page->pdimno];
3159 ensuretext (page);
3161 if (mark == mark_page) {
3162 int i;
3163 fz_page_block *pb1 = NULL, *pb2 = NULL;
3165 for (i = 0; i < page->text->len; ++i) {
3166 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3167 pb1 = &page->text->blocks[i];
3168 break;
3171 if (!pb1) goto unlock;
3173 for (i = page->text->len - 1; i >= 0; --i) {
3174 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3175 pb2 = &page->text->blocks[i];
3176 break;
3179 if (!pb2) goto unlock;
3181 block = pb1->u.text;
3183 page->fmark.i = 0;
3184 page->fmark.span = block->lines->first_span;
3186 block = pb2->u.text;
3187 line = &block->lines[block->len - 1];
3188 page->lmark.i = line->last_span->len - 1;
3189 page->lmark.span = line->last_span;
3190 ret_v = Val_bool (1);
3191 goto unlock;
3194 x += pdim->bounds.x0;
3195 y += pdim->bounds.y0;
3197 for (pageb = page->text->blocks;
3198 pageb < page->text->blocks + page->text->len;
3199 ++pageb) {
3200 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3201 block = pageb->u.text;
3203 b = &block->bbox;
3204 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3205 continue;
3207 if (mark == mark_block) {
3208 page->fmark.i = 0;
3209 page->fmark.span = block->lines->first_span;
3211 line = &block->lines[block->len - 1];
3212 page->lmark.i = line->last_span->len - 1;
3213 page->lmark.span = line->last_span;
3214 ret_v = Val_bool (1);
3215 goto unlock;
3218 for (line = block->lines;
3219 line < block->lines + block->len;
3220 ++line) {
3221 fz_stext_span *span;
3223 b = &line->bbox;
3224 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3225 continue;
3227 if (mark == mark_line) {
3228 page->fmark.i = 0;
3229 page->fmark.span = line->first_span;
3231 page->lmark.i = line->last_span->len - 1;
3232 page->lmark.span = line->last_span;
3233 ret_v = Val_bool (1);
3234 goto unlock;
3237 for (span = line->first_span; span; span = span->next) {
3238 int charnum;
3240 b = &span->bbox;
3241 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3242 continue;
3244 for (charnum = 0; charnum < span->len; ++charnum) {
3245 fz_rect bbox;
3246 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3247 b = &bbox;
3249 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3250 /* unicode ftw */
3251 int charnum2, charnum3 = -1, charnum4 = -1;
3253 if (uninteresting (span->text[charnum].c)) goto unlock;
3255 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3256 if (uninteresting (span->text[charnum2].c)) {
3257 charnum3 = charnum2 + 1;
3258 break;
3261 if (charnum3 == -1) charnum3 = 0;
3263 charnum4 = charnum;
3264 for (charnum2 = charnum + 1;
3265 charnum2 < span->len;
3266 ++charnum2) {
3267 if (uninteresting (span->text[charnum2].c)) break;
3268 charnum4 = charnum2;
3271 page->fmark.i = charnum3;
3272 page->fmark.span = span;
3274 page->lmark.i = charnum4;
3275 page->lmark.span = span;
3276 ret_v = Val_bool (1);
3277 goto unlock;
3283 unlock:
3284 if (!Bool_val (ret_v)) {
3285 page->fmark.span = NULL;
3286 page->lmark.span = NULL;
3287 page->fmark.i = 0;
3288 page->lmark.i = 0;
3290 unlock (__func__);
3292 done:
3293 CAMLreturn (ret_v);
3296 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3298 CAMLparam3 (ptr_v, x_v, y_v);
3299 CAMLlocal2 (ret_v, res_v);
3300 fz_rect *b = NULL;
3301 struct page *page;
3302 fz_page_block *pageb;
3303 struct pagedim *pdim;
3304 char *s = String_val (ptr_v);
3305 int x = Int_val (x_v), y = Int_val (y_v);
3307 ret_v = Val_int (0);
3308 if (trylock (__func__)) {
3309 goto done;
3312 page = parse_pointer (__func__, s);
3313 pdim = &state.pagedims[page->pdimno];
3314 x += pdim->bounds.x0;
3315 y += pdim->bounds.y0;
3317 ensuretext (page);
3319 for (pageb = page->text->blocks;
3320 pageb < page->text->blocks + page->text->len;
3321 ++pageb) {
3322 switch (pageb->type) {
3323 case FZ_PAGE_BLOCK_TEXT:
3324 b = &pageb->u.text->bbox;
3325 break;
3327 case FZ_PAGE_BLOCK_IMAGE:
3328 b = &pageb->u.image->bbox;
3329 break;
3331 default:
3332 continue;
3335 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3336 break;
3337 b = NULL;
3339 if (b) {
3340 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3341 ret_v = caml_alloc_small (1, 1);
3342 Store_double_field (res_v, 0, b->x0);
3343 Store_double_field (res_v, 1, b->x1);
3344 Store_double_field (res_v, 2, b->y0);
3345 Store_double_field (res_v, 3, b->y1);
3346 Field (ret_v, 0) = res_v;
3348 unlock (__func__);
3350 done:
3351 CAMLreturn (ret_v);
3354 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3356 CAMLparam2 (ptr_v, rect_v);
3357 fz_rect b;
3358 struct page *page;
3359 struct pagedim *pdim;
3360 char *s = String_val (ptr_v);
3361 int i, x0, x1, y0, y1, fi, li;
3362 fz_stext_line *line;
3363 fz_page_block *pageb;
3364 fz_stext_block *block;
3365 fz_stext_span *span, *fspan, *lspan;
3367 if (trylock (__func__)) {
3368 goto done;
3371 page = parse_pointer (__func__, s);
3372 ensuretext (page);
3374 pdim = &state.pagedims[page->pdimno];
3375 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3376 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3377 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3378 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3380 if (y0 > y1) {
3381 int t = y0;
3382 y0 = y1;
3383 y1 = t;
3384 x0 = x1;
3385 x1 = t;
3388 fi = page->fmark.i;
3389 fspan = page->fmark.span;
3391 li = page->lmark.i;
3392 lspan = page->lmark.span;
3394 for (pageb = page->text->blocks;
3395 pageb < page->text->blocks + page->text->len;
3396 ++pageb) {
3397 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3398 block = pageb->u.text;
3399 for (line = block->lines;
3400 line < block->lines + block->len;
3401 ++line) {
3403 for (span = line->first_span; span; span = span->next) {
3404 for (i = 0; i < span->len; ++i) {
3405 fz_stext_char_bbox (state.ctx, &b, span, i);
3407 if (x0 >= b.x0 && x0 <= b.x1
3408 && y0 >= b.y0 && y0 <= b.y1) {
3409 fspan = span;
3410 fi = i;
3412 if (x1 >= b.x0 && x1 <= b.x1
3413 && y1 >= b.y0 && y1 <= b.y1) {
3414 lspan = span;
3415 li = i;
3421 if (x1 < x0 && fspan == lspan) {
3422 i = fi;
3423 span = fspan;
3425 fi = li;
3426 fspan = lspan;
3428 li = i;
3429 lspan = span;
3432 page->fmark.i = fi;
3433 page->fmark.span = fspan;
3435 page->lmark.i = li;
3436 page->lmark.span = lspan;
3438 unlock (__func__);
3440 done:
3441 CAMLreturn0;
3444 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3446 char buf[4];
3447 int i, len, ret;
3449 for (i = a; i <= b; ++i) {
3450 len = fz_runetochar (buf, span->text[i].c);
3451 ret = fwrite (buf, len, 1, f);
3453 if (ret != 1) {
3454 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3455 len, ret, strerror (errno));
3456 return -1;
3459 return 0;
3462 #ifdef __CYGWIN__
3463 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3465 caml_failwith ("ml_popen not implemented under Cygwin");
3467 #else
3468 CAMLprim value ml_spawn (value command_v, value fds_v)
3470 CAMLparam2 (command_v, fds_v);
3471 CAMLlocal2 (l_v, tup_v);
3472 int ret, ret1;
3473 pid_t pid;
3474 char *msg = NULL;
3475 value earg_v = Nothing;
3476 posix_spawnattr_t attr;
3477 posix_spawn_file_actions_t fa;
3478 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3480 argv[2] = String_val (command_v);
3482 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3483 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3486 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3487 msg = "posix_spawnattr_init";
3488 goto fail1;
3491 #ifdef POSIX_SPAWN_USEVFORK
3492 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3493 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3494 goto fail;
3496 #endif
3498 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3499 int fd1, fd2;
3501 tup_v = Field (l_v, 0);
3502 fd1 = Int_val (Field (tup_v, 0));
3503 fd2 = Int_val (Field (tup_v, 1));
3504 if (fd2 < 0) {
3505 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3506 msg = "posix_spawn_file_actions_addclose";
3507 earg_v = tup_v;
3508 goto fail;
3511 else {
3512 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3513 msg = "posix_spawn_file_actions_adddup2";
3514 earg_v = tup_v;
3515 goto fail;
3520 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3521 msg = "posix_spawn";
3522 goto fail;
3525 fail:
3526 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3527 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3530 fail1:
3531 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3532 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3533 strerror (ret1));
3536 if (msg)
3537 unix_error (ret, msg, earg_v);
3539 CAMLreturn (Val_int (pid));
3541 #endif
3543 CAMLprim value ml_hassel (value ptr_v)
3545 CAMLparam1 (ptr_v);
3546 CAMLlocal1 (ret_v);
3547 struct page *page;
3548 char *s = String_val (ptr_v);
3550 ret_v = Val_bool (0);
3551 if (trylock (__func__)) {
3552 goto done;
3555 page = parse_pointer (__func__, s);
3556 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3557 unlock (__func__);
3558 done:
3559 CAMLreturn (ret_v);
3562 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3564 CAMLparam2 (fd_v, ptr_v);
3565 FILE *f;
3566 int seen = 0;
3567 struct page *page;
3568 fz_stext_line *line;
3569 fz_page_block *pageb;
3570 fz_stext_block *block;
3571 int fd = Int_val (fd_v);
3572 char *s = String_val (ptr_v);
3574 if (trylock (__func__)) {
3575 goto done;
3578 page = parse_pointer (__func__, s);
3580 if (!page->fmark.span || !page->lmark.span) {
3581 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3582 goto unlock;
3585 f = fdopen (fd, "w");
3586 if (!f) {
3587 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3588 fd, strerror (errno));
3589 f = stdout;
3592 for (pageb = page->text->blocks;
3593 pageb < page->text->blocks + page->text->len;
3594 ++pageb) {
3595 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3596 block = pageb->u.text;
3597 for (line = block->lines;
3598 line < block->lines + block->len;
3599 ++line) {
3600 fz_stext_span *span;
3602 for (span = line->first_span; span; span = span->next) {
3603 int a, b;
3605 seen |= span == page->fmark.span || span == page->lmark.span;
3606 a = span == page->fmark.span ? page->fmark.i : 0;
3607 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3609 if (seen) {
3610 if (pipespan (f, span, a, b)) {
3611 goto close;
3613 if (span == page->lmark.span) {
3614 goto close;
3616 if (span == line->last_span) {
3617 if (putc ('\n', f) == EOF) {
3618 fprintf (stderr,
3619 "failed break line on sel pipe: %s\n",
3620 strerror (errno));
3621 goto close;
3628 close:
3629 if (f != stdout) {
3630 int ret = fclose (f);
3631 fd = -1;
3632 if (ret == -1) {
3633 if (errno != ECHILD) {
3634 fprintf (stderr, "failed to close sel pipe: %s\n",
3635 strerror (errno));
3639 unlock:
3640 unlock (__func__);
3642 done:
3643 if (fd >= 0) {
3644 if (close (fd)) {
3645 fprintf (stderr, "failed to close sel pipe: %s\n",
3646 strerror (errno));
3649 CAMLreturn0;
3652 CAMLprim value ml_getpdimrect (value pagedimno_v)
3654 CAMLparam1 (pagedimno_v);
3655 CAMLlocal1 (ret_v);
3656 int pagedimno = Int_val (pagedimno_v);
3657 fz_rect box;
3659 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3660 if (trylock (__func__)) {
3661 box = fz_empty_rect;
3663 else {
3664 box = state.pagedims[pagedimno].mediabox;
3665 unlock (__func__);
3668 Store_double_field (ret_v, 0, box.x0);
3669 Store_double_field (ret_v, 1, box.x1);
3670 Store_double_field (ret_v, 2, box.y0);
3671 Store_double_field (ret_v, 3, box.y1);
3673 CAMLreturn (ret_v);
3676 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3677 value dw_v, value cols_v)
3679 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3680 CAMLlocal1 (ret_v);
3681 int i;
3682 double zoom = -1.;
3683 double maxh = 0.0;
3684 struct pagedim *p;
3685 double winw = Int_val (winw_v);
3686 double winh = Int_val (winh_v);
3687 double dw = Int_val (dw_v);
3688 double cols = Int_val (cols_v);
3689 double pw = 1.0, ph = 1.0;
3691 if (trylock (__func__)) {
3692 goto done;
3695 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3696 double w = p->pagebox.x1 / cols;
3697 double h = p->pagebox.y1;
3698 if (h > maxh) {
3699 maxh = h;
3700 ph = h;
3701 if (state.fitmodel != FitProportional) pw = w;
3703 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3706 zoom = (((winh / ph) * pw) + dw) / winw;
3707 unlock (__func__);
3708 done:
3709 ret_v = caml_copy_double (zoom);
3710 CAMLreturn (ret_v);
3713 CAMLprim value ml_getmaxw (value unit_v)
3715 CAMLparam1 (unit_v);
3716 CAMLlocal1 (ret_v);
3717 int i;
3718 double maxw = -1.;
3719 struct pagedim *p;
3721 if (trylock (__func__)) {
3722 goto done;
3725 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3726 double w = p->pagebox.x1;
3727 maxw = fz_max (maxw, w);
3730 unlock (__func__);
3731 done:
3732 ret_v = caml_copy_double (maxw);
3733 CAMLreturn (ret_v);
3736 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3738 CAMLparam4 (pt_v, x_v, y_v, string_v);
3739 CAMLlocal1 (ret_v);
3740 int pt = Int_val(pt_v);
3741 int x = Int_val (x_v);
3742 int y = Int_val (y_v);
3743 double w;
3745 w = draw_string (state.face, pt, x, y, String_val (string_v));
3746 ret_v = caml_copy_double (w);
3747 CAMLreturn (ret_v);
3750 CAMLprim value ml_measure_string (value pt_v, value string_v)
3752 CAMLparam2 (pt_v, string_v);
3753 CAMLlocal1 (ret_v);
3754 int pt = Int_val (pt_v);
3755 double w;
3757 w = measure_string (state.face, pt, String_val (string_v));
3758 ret_v = caml_copy_double (w);
3759 CAMLreturn (ret_v);
3762 CAMLprim value ml_getpagebox (value opaque_v)
3764 CAMLparam1 (opaque_v);
3765 CAMLlocal1 (ret_v);
3766 fz_rect rect;
3767 fz_irect bbox;
3768 fz_matrix ctm;
3769 fz_device *dev;
3770 char *s = String_val (opaque_v);
3771 struct page *page = parse_pointer (__func__, s);
3773 ret_v = caml_alloc_tuple (4);
3774 dev = fz_new_bbox_device (state.ctx, &rect);
3775 dev->hints |= FZ_IGNORE_SHADE;
3777 ctm = pagectm (page);
3778 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3780 fz_close_device (state.ctx, dev);
3781 fz_drop_device (state.ctx, dev);
3782 fz_round_rect (&bbox, &rect);
3783 Field (ret_v, 0) = Val_int (bbox.x0);
3784 Field (ret_v, 1) = Val_int (bbox.y0);
3785 Field (ret_v, 2) = Val_int (bbox.x1);
3786 Field (ret_v, 3) = Val_int (bbox.y1);
3788 CAMLreturn (ret_v);
3791 CAMLprim void ml_setaalevel (value level_v)
3793 CAMLparam1 (level_v);
3795 state.aalevel = Int_val (level_v);
3796 CAMLreturn0;
3799 #pragma GCC diagnostic push
3800 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3802 #ifndef __COCOA__
3803 #include <X11/Xlib.h>
3804 #include <X11/cursorfont.h>
3805 #pragma GCC diagnostic pop
3807 #ifdef USE_EGL
3808 #include <EGL/egl.h>
3809 #else
3810 #include <GL/glx.h>
3811 #endif
3813 static const int shapes[] = {
3814 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3817 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3819 static struct {
3820 Window wid;
3821 Display *dpy;
3822 #ifdef USE_EGL
3823 EGLContext ctx;
3824 EGLConfig conf;
3825 EGLSurface win;
3826 EGLDisplay *edpy;
3827 #else
3828 GLXContext ctx;
3829 #endif
3830 XVisualInfo *visual;
3831 Cursor curs[CURS_COUNT];
3832 } glx;
3835 static void initcurs (void)
3837 for (size_t n = 0; n < CURS_COUNT; ++n) {
3838 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3842 CAMLprim void ml_setbgcol (value color_v)
3844 CAMLparam1 (color_v);
3845 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3846 CAMLreturn0;
3849 #ifdef USE_EGL
3850 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3852 CAMLparam3 (display_v, wid_v, screen_v);
3853 int major, minor;
3854 int num_conf;
3855 EGLint visid;
3856 EGLint attribs[] = {
3857 EGL_DEPTH_SIZE, 24,
3858 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3859 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3860 EGL_NONE
3862 EGLConfig conf;
3864 glx.dpy = XOpenDisplay (String_val (display_v));
3865 if (!glx.dpy) {
3866 caml_failwith ("XOpenDisplay");
3869 eglBindAPI (EGL_OPENGL_API);
3871 glx.edpy = eglGetDisplay (glx.dpy);
3872 if (glx.edpy == EGL_NO_DISPLAY) {
3873 caml_failwith ("eglGetDisplay");
3876 if (!eglInitialize (glx.edpy, &major, &minor)) {
3877 caml_failwith ("eglInitialize");
3880 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3881 !num_conf) {
3882 caml_failwith ("eglChooseConfig");
3885 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3886 caml_failwith ("eglGetConfigAttrib");
3889 glx.conf = conf;
3890 initcurs ();
3892 glx.wid = Int_val (wid_v);
3893 CAMLreturn (Val_int (visid));
3896 CAMLprim value ml_glxcompleteinit (value unit_v)
3898 CAMLparam1 (unit_v);
3900 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3901 if (!glx.ctx) {
3902 caml_failwith ("eglCreateContext");
3905 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3906 glx.wid, NULL);
3907 if (glx.win == EGL_NO_SURFACE) {
3908 caml_failwith ("eglCreateWindowSurface");
3911 XFree (glx.visual);
3912 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3913 glx.ctx = NULL;
3914 caml_failwith ("eglMakeCurrent");
3916 CAMLreturn (unit_v);
3918 #else
3919 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3921 CAMLparam3 (display_v, wid_v, screen_v);
3923 glx.dpy = XOpenDisplay (String_val (display_v));
3924 if (!glx.dpy) {
3925 caml_failwith ("XOpenDisplay");
3928 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3929 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3930 if (!glx.visual) {
3931 XCloseDisplay (glx.dpy);
3932 caml_failwith ("glXChooseVisual");
3935 initcurs ();
3937 glx.wid = Int_val (wid_v);
3938 CAMLreturn (Val_int (glx.visual->visualid));
3941 CAMLprim value ml_glxcompleteinit (value unit_v)
3943 CAMLparam1 (unit_v);
3945 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3946 if (!glx.ctx) {
3947 caml_failwith ("glXCreateContext");
3950 XFree (glx.visual);
3951 glx.visual = NULL;
3953 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3954 glXDestroyContext (glx.dpy, glx.ctx);
3955 glx.ctx = NULL;
3956 caml_failwith ("glXMakeCurrent");
3958 CAMLreturn (unit_v);
3960 #endif
3962 CAMLprim void ml_setcursor (value cursor_v)
3964 CAMLparam1 (cursor_v);
3965 size_t cursn = Int_val (cursor_v);
3967 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3968 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3969 XFlush (glx.dpy);
3970 CAMLreturn0;
3973 CAMLprim value ml_swapb (value unit_v)
3975 CAMLparam1 (unit_v);
3976 #ifdef USE_EGL
3977 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3978 caml_failwith ("eglSwapBuffers");
3980 #else
3981 glXSwapBuffers (glx.dpy, glx.wid);
3982 #endif
3983 CAMLreturn (unit_v);
3986 #include "keysym2ucs.c"
3988 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3990 CAMLparam1 (keysym_v);
3991 CAMLlocal1 (str_v);
3992 KeySym keysym = Int_val (keysym_v);
3993 Rune rune;
3994 int len;
3995 char buf[5];
3997 rune = keysym2ucs (keysym);
3998 len = fz_runetochar (buf, rune);
3999 buf[len] = 0;
4000 str_v = caml_copy_string (buf);
4001 CAMLreturn (str_v);
4003 #else
4004 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4006 CAMLparam1 (keysym_v);
4007 CAMLlocal1 (str_v);
4008 long ucs_v = Long_val (keysym_v);
4009 int len;
4010 char buf[5];
4012 len = fz_runetochar (buf, ucs_v);
4013 buf[len] = 0;
4014 str_v = caml_copy_string (buf);
4015 CAMLreturn (str_v);
4017 #endif
4019 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4021 CAMLprim value ml_platform (value unit_v)
4023 CAMLparam1 (unit_v);
4024 CAMLlocal2 (tup_v, arr_v);
4025 int platid = piunknown;
4026 struct utsname buf;
4028 #if defined __linux__
4029 platid = pilinux;
4030 #elif defined __CYGWIN__
4031 platid = picygwin;
4032 #elif defined __DragonFly__ || defined __FreeBSD__
4033 || defined __OpenBSD__ || defined __NetBSD__
4034 platid = pibsd;
4035 #elif defined __sun__
4036 platid = pisun;
4037 #elif defined __APPLE__
4038 platid = piosx;
4039 #endif
4040 if (uname (&buf)) err (1, "uname");
4042 tup_v = caml_alloc_tuple (2);
4044 char const *sar[] = {
4045 buf.sysname,
4046 buf.release,
4047 buf.version,
4048 buf.machine,
4049 NULL
4051 arr_v = caml_copy_string_array (sar);
4053 Field (tup_v, 0) = Val_int (platid);
4054 Field (tup_v, 1) = arr_v;
4055 CAMLreturn (tup_v);
4058 CAMLprim void ml_cloexec (value fd_v)
4060 CAMLparam1 (fd_v);
4061 int fd = Int_val (fd_v);
4063 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4064 uerror ("fcntl", Nothing);
4066 CAMLreturn0;
4069 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4071 CAMLparam2 (w_v, h_v);
4072 CAMLlocal1 (ret_v);
4073 struct bo *pbo;
4074 int w = Int_val (w_v);
4075 int h = Int_val (h_v);
4076 int cs = Int_val (cs_v);
4078 if (state.bo_usable) {
4079 pbo = calloc (sizeof (*pbo), 1);
4080 if (!pbo) {
4081 err (1, "calloc pbo");
4084 switch (cs) {
4085 case 0:
4086 case 1:
4087 pbo->size = w*h*4;
4088 break;
4089 case 2:
4090 pbo->size = w*h*2;
4091 break;
4092 default:
4093 errx (1, "%s: invalid colorspace %d", __func__, cs);
4096 state.glGenBuffersARB (1, &pbo->id);
4097 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4098 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4099 NULL, GL_STREAM_DRAW);
4100 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4101 GL_READ_WRITE);
4102 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4103 if (!pbo->ptr) {
4104 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4105 state.glDeleteBuffersARB (1, &pbo->id);
4106 free (pbo);
4107 ret_v = caml_copy_string ("0");
4109 else {
4110 int res;
4111 char *s;
4113 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4114 if (res < 0) {
4115 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4117 s = malloc (res+1);
4118 if (!s) {
4119 err (1, "malloc %d bytes failed", res+1);
4121 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4122 if (res < 0) {
4123 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4125 ret_v = caml_copy_string (s);
4126 free (s);
4129 else {
4130 ret_v = caml_copy_string ("0");
4132 CAMLreturn (ret_v);
4135 CAMLprim void ml_freepbo (value s_v)
4137 CAMLparam1 (s_v);
4138 char *s = String_val (s_v);
4139 struct tile *tile = parse_pointer (__func__, s);
4141 if (tile->pbo) {
4142 state.glDeleteBuffersARB (1, &tile->pbo->id);
4143 tile->pbo->id = -1;
4144 tile->pbo->ptr = NULL;
4145 tile->pbo->size = -1;
4147 CAMLreturn0;
4150 CAMLprim void ml_unmappbo (value s_v)
4152 CAMLparam1 (s_v);
4153 char *s = String_val (s_v);
4154 struct tile *tile = parse_pointer (__func__, s);
4156 if (tile->pbo) {
4157 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4158 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4159 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4161 tile->pbo->ptr = NULL;
4162 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4164 CAMLreturn0;
4167 static void setuppbo (void)
4169 #ifdef __COCOA__
4170 static CFBundleRef framework = NULL;
4171 if (framework == NULL)
4172 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
4173 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
4174 #else
4175 #ifdef USE_EGL
4176 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4177 #else
4178 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4179 #endif
4180 state.bo_usable = GGPA (glBindBufferARB)
4181 && GGPA (glUnmapBufferARB)
4182 && GGPA (glMapBufferARB)
4183 && GGPA (glBufferDataARB)
4184 && GGPA (glGenBuffersARB)
4185 && GGPA (glDeleteBuffersARB);
4186 #endif
4187 #undef GGPA
4190 CAMLprim value ml_bo_usable (value unit_v)
4192 CAMLparam1 (unit_v);
4193 CAMLreturn (Val_bool (state.bo_usable));
4196 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4198 CAMLparam3 (ptr_v, x_v, y_v);
4199 CAMLlocal2 (ret_v, tup_v);
4200 struct page *page;
4201 char *s = String_val (ptr_v);
4202 int x = Int_val (x_v), y = Int_val (y_v);
4203 struct pagedim *pdim;
4204 fz_point p;
4205 fz_matrix ctm;
4207 page = parse_pointer (__func__, s);
4208 pdim = &state.pagedims[page->pdimno];
4210 ret_v = Val_int (0);
4211 if (trylock (__func__)) {
4212 goto done;
4215 if (pdf_specifics (state.ctx, state.doc)) {
4216 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4217 ctm = state.pagedims[page->pdimno].tctm;
4219 else {
4220 ctm = fz_identity;
4222 p.x = x + pdim->bounds.x0;
4223 p.y = y + pdim->bounds.y0;
4225 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4226 fz_invert_matrix (&ctm, &ctm);
4227 fz_transform_point (&p, &ctm);
4229 tup_v = caml_alloc_tuple (2);
4230 ret_v = caml_alloc_small (1, 1);
4231 Field (tup_v, 0) = Val_int (p.x);
4232 Field (tup_v, 1) = Val_int (p.y);
4233 Field (ret_v, 0) = tup_v;
4235 unlock (__func__);
4236 done:
4237 CAMLreturn (ret_v);
4240 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4241 value x_v, value y_v)
4243 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4244 CAMLlocal1 (ret_v);
4245 struct page *page;
4246 char *s = String_val (ptr_v);
4247 int pageno = Int_val (pageno_v);
4248 int pdimno = Int_val (pdimno_v);
4249 double x = Double_val (x_v), y = Double_val (y_v);
4250 struct pagedim *pdim;
4251 fz_point p;
4252 fz_matrix ctm;
4254 ret_v = Val_int (0);
4255 lock (__func__);
4257 if (!*s) {
4258 page = loadpage (pageno, pdimno);
4260 else {
4261 page = parse_pointer (__func__, s);
4263 pdim = &state.pagedims[pdimno];
4265 if (pdf_specifics (state.ctx, state.doc)) {
4266 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4267 ctm = state.pagedims[page->pdimno].tctm;
4269 else {
4270 ctm = fz_identity;
4272 p.x = x + pdim->bounds.x0;
4273 p.y = y + pdim->bounds.y0;
4275 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4276 fz_transform_point (&p, &ctm);
4278 ret_v = caml_alloc_tuple (2);
4279 Field (ret_v, 0) = caml_copy_double (p.x);
4280 Field (ret_v, 1) = caml_copy_double (p.y);
4282 if (!*s) {
4283 freepage (page);
4285 unlock (__func__);
4286 CAMLreturn (ret_v);
4289 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4290 value contents_v)
4292 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4293 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4295 if (pdf) {
4296 pdf_annot *annot;
4297 struct page *page;
4298 fz_point p;
4299 char *s = String_val (ptr_v);
4301 page = parse_pointer (__func__, s);
4302 annot = pdf_create_annot (state.ctx,
4303 pdf_page_from_fz_page (state.ctx,
4304 page->fzpage),
4305 PDF_ANNOT_TEXT);
4306 p.x = Int_val (x_v);
4307 p.y = Int_val (y_v);
4308 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4309 pdf_set_text_annot_position (state.ctx, annot, p);
4310 state.dirty = 1;
4312 CAMLreturn0;
4315 CAMLprim void ml_delannot (value ptr_v, value n_v)
4317 CAMLparam2 (ptr_v, n_v);
4318 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4320 if (pdf) {
4321 struct page *page;
4322 char *s = String_val (ptr_v);
4323 struct slink *slink;
4325 page = parse_pointer (__func__, s);
4326 slink = &page->slinks[Int_val (n_v)];
4327 pdf_delete_annot (state.ctx,
4328 pdf_page_from_fz_page (state.ctx, page->fzpage),
4329 (pdf_annot *) slink->u.annot);
4330 state.dirty = 1;
4332 CAMLreturn0;
4335 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4337 CAMLparam3 (ptr_v, n_v, str_v);
4338 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4340 if (pdf) {
4341 struct page *page;
4342 char *s = String_val (ptr_v);
4343 struct slink *slink;
4345 page = parse_pointer (__func__, s);
4346 slink = &page->slinks[Int_val (n_v)];
4347 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4348 String_val (str_v));
4349 state.dirty = 1;
4351 CAMLreturn0;
4354 CAMLprim value ml_hasunsavedchanges (value unit_v)
4356 CAMLparam1 (unit_v);
4357 CAMLreturn (Val_bool (state.dirty));
4360 CAMLprim void ml_savedoc (value path_v)
4362 CAMLparam1 (path_v);
4363 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4365 if (pdf) {
4366 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4368 CAMLreturn0;
4371 static void makestippletex (void)
4373 const char pixels[] = "\xff\xff\0\0";
4374 glGenTextures (1, &state.stid);
4375 glBindTexture (GL_TEXTURE_1D, state.stid);
4376 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4377 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4378 glTexImage1D (
4379 GL_TEXTURE_1D,
4381 GL_ALPHA,
4384 GL_ALPHA,
4385 GL_UNSIGNED_BYTE,
4386 pixels
4390 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4392 return caml_copy_string (FZ_VERSION);
4395 CAMLprim void ml_init (value csock_v, value params_v)
4397 CAMLparam2 (csock_v, params_v);
4398 CAMLlocal2 (trim_v, fuzz_v);
4399 int ret;
4400 int texcount;
4401 char *fontpath;
4402 int colorspace;
4403 int mustoresize;
4404 int haspboext;
4406 state.csock = Int_val (csock_v);
4407 state.rotate = Int_val (Field (params_v, 0));
4408 state.fitmodel = Int_val (Field (params_v, 1));
4409 trim_v = Field (params_v, 2);
4410 texcount = Int_val (Field (params_v, 3));
4411 state.sliceheight = Int_val (Field (params_v, 4));
4412 mustoresize = Int_val (Field (params_v, 5));
4413 colorspace = Int_val (Field (params_v, 6));
4414 fontpath = String_val (Field (params_v, 7));
4416 if (caml_string_length (Field (params_v, 8)) > 0) {
4417 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4419 if (!state.trimcachepath) {
4420 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4421 strerror (errno));
4425 haspboext = Bool_val (Field (params_v, 9));
4427 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4428 fz_register_document_handlers (state.ctx);
4430 state.trimmargins = Bool_val (Field (trim_v, 0));
4431 fuzz_v = Field (trim_v, 1);
4432 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4433 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4434 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4435 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4437 set_tex_params (colorspace);
4439 if (*fontpath) {
4440 state.face = load_font (fontpath);
4442 else {
4443 int len;
4444 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4445 0, 0, &len);
4446 state.face = load_builtin_font (data, len);
4448 if (!state.face) _exit (1);
4450 realloctexts (texcount);
4452 if (haspboext) {
4453 setuppbo ();
4456 makestippletex ();
4458 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4459 if (ret) {
4460 errx (1, "pthread_create: %s", strerror (ret));
4463 CAMLreturn0;