Fix the condition and error reporting
[llpp.git] / link.c
bloba35475923762fba227e4f4a9dac914f9f2808b9d
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>
12 #include <wchar.h>
13 #include <locale.h>
14 #include <langinfo.h>
16 #include <unistd.h>
17 #include <pthread.h>
18 #include <sys/uio.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/ioctl.h>
22 #include <sys/utsname.h>
24 #ifdef __CYGWIN__
25 #include <cygwin/socket.h> /* FIONREAD */
26 #else
27 #include <spawn.h>
28 #endif
30 #include <regex.h>
31 #include <stdarg.h>
32 #include <limits.h>
33 #include <inttypes.h>
35 #ifdef __COCOA__
36 #include <CoreFoundation/CoreFoundation.h>
37 #endif
39 #ifdef __APPLE__
40 #include <OpenGL/gl.h>
41 #else
42 #include <GL/gl.h>
43 #endif
45 #include <caml/fail.h>
46 #include <caml/alloc.h>
47 #include <caml/memory.h>
48 #include <caml/unixsupport.h>
50 #if __GNUC__ < 5 && !defined __clang__
51 /* At least gcc (Gentoo 4.9.3 p1.0, pie-0.6.2) 4.9.3 emits erroneous
52 clobbered diagnostics */
53 #pragma GCC diagnostic ignored "-Wclobbered"
54 #endif
56 #include <mupdf/fitz.h>
57 #include <mupdf/pdf.h>
59 #include <ft2build.h>
60 #include FT_FREETYPE_H
62 #define PIGGYBACK
63 #define CACHE_PAGEREFS
65 #ifndef __USE_GNU
66 extern char **environ;
67 #endif
69 #if defined __GNUC__
70 #define NORETURN_ATTR __attribute__ ((noreturn))
71 #define UNUSED_ATTR __attribute__ ((unused))
72 #if !defined __clang__
73 #define OPTIMIZE_ATTR(n) __attribute__ ((optimize ("O"#n)))
74 #else
75 #define OPTIMIZE_ATTR(n)
76 #endif
77 #define GCC_FMT_ATTR(a, b) __attribute__ ((format (printf, a, b)))
78 #else
79 #define NORETURN_ATTR
80 #define UNUSED_ATTR
81 #define OPTIMIZE_ATTR(n)
82 #define GCC_FMT_ATTR(a, b)
83 #endif
85 #define FMT_s "zu"
87 #define FMT_ptr PRIxPTR
88 #define SCN_ptr SCNxPTR
89 #define FMT_ptr_cast(p) ((uintptr_t) (p))
90 #define SCN_ptr_cast(p) ((uintptr_t *) (p))
92 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
93 err (int exitcode, const char *fmt, ...)
95 va_list ap;
96 int savederrno;
98 savederrno = errno;
99 va_start (ap, fmt);
100 vfprintf (stderr, fmt, ap);
101 va_end (ap);
102 fprintf (stderr, ": %s\n", strerror (savederrno));
103 fflush (stderr);
104 _exit (exitcode);
107 static void NORETURN_ATTR GCC_FMT_ATTR (2, 3)
108 errx (int exitcode, const char *fmt, ...)
110 va_list ap;
112 va_start (ap, fmt);
113 vfprintf (stderr, fmt, ap);
114 va_end (ap);
115 fputc ('\n', stderr);
116 fflush (stderr);
117 _exit (exitcode);
120 #ifndef GL_TEXTURE_RECTANGLE_ARB
121 #define GL_TEXTURE_RECTANGLE_ARB 0x84F5
122 #endif
124 #ifdef USE_NPOT
125 #define TEXT_TYPE GL_TEXTURE_2D
126 #else
127 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
128 #endif
130 #ifndef GL_BGRA
131 #define GL_BGRA 0x80E1
132 #endif
134 #ifndef GL_UNSIGNED_INT_8_8_8_8
135 #define GL_UNSIGNED_INT_8_8_8_8 0x8035
136 #endif
138 #ifndef GL_UNSIGNED_INT_8_8_8_8_REV
139 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
140 #endif
142 #if 0
143 #define lprintf printf
144 #else
145 #define lprintf(...)
146 #endif
148 #define ARSERT(cond) for (;;) { \
149 if (!(cond)) { \
150 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
152 break; \
155 struct slice {
156 int h;
157 int texindex;
160 struct tile {
161 int w, h;
162 int slicecount;
163 int sliceheight;
164 struct bo *pbo;
165 fz_pixmap *pixmap;
166 struct slice slices[1];
169 struct pagedim {
170 int pageno;
171 int rotate;
172 int left;
173 int tctmready;
174 fz_irect bounds;
175 fz_rect pagebox;
176 fz_rect mediabox;
177 fz_matrix ctm, zoomctm, tctm;
180 struct slink {
181 enum { SLINK, SANNOT } tag;
182 fz_irect bbox;
183 union {
184 fz_link *link;
185 fz_annot *annot;
186 } u;
189 struct annot {
190 fz_irect bbox;
191 fz_annot *annot;
194 struct page {
195 int tgen;
196 int sgen;
197 int agen;
198 int pageno;
199 int pdimno;
200 fz_stext_page *text;
201 fz_stext_sheet *sheet;
202 fz_page *fzpage;
203 fz_display_list *dlist;
204 int slinkcount;
205 struct slink *slinks;
206 int annotcount;
207 struct annot *annots;
208 struct mark {
209 int i;
210 fz_stext_span *span;
211 } fmark, lmark;
214 struct {
215 int sliceheight;
216 struct pagedim *pagedims;
217 int pagecount;
218 int pagedimcount;
219 fz_document *doc;
220 fz_context *ctx;
221 int w, h;
223 int texindex;
224 int texcount;
225 GLuint *texids;
227 GLenum texiform;
228 GLenum texform;
229 GLenum texty;
231 fz_colorspace *colorspace;
233 struct {
234 int w, h;
235 struct slice *slice;
236 } *texowners;
238 int rotate;
239 enum { FitWidth, FitProportional, FitPage } fitmodel;
240 int trimmargins;
241 int needoutline;
242 int gen;
243 int aalevel;
245 int trimanew;
246 fz_irect trimfuzz;
247 fz_pixmap *pig;
249 pthread_t thread;
250 int csock;
251 FT_Face face;
253 char *trimcachepath;
254 int cxack;
255 int dirty;
257 GLuint stid;
259 int bo_usable;
260 GLuint boid;
262 void (*glBindBufferARB) (GLenum, GLuint);
263 GLboolean (*glUnmapBufferARB) (GLenum);
264 void *(*glMapBufferARB) (GLenum, GLenum);
265 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
266 void (*glGenBuffersARB) (GLsizei, GLuint *);
267 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
269 GLfloat texcoords[8];
270 GLfloat vertices[16];
272 #ifdef CACHE_PAGEREFS
273 struct {
274 int idx;
275 int count;
276 pdf_obj **objs;
277 pdf_document *pdf;
278 } pdflut;
279 #endif
280 int utf8cs;
281 } state;
283 struct bo {
284 GLuint id;
285 void *ptr;
286 size_t size;
289 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
291 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
294 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
296 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
299 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
301 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
302 m.a, m.b, m.c, m.d, m.e, m.f);
305 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
307 static void lock (const char *cap)
309 int ret = pthread_mutex_lock (&mutex);
310 if (ret) {
311 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
315 static void unlock (const char *cap)
317 int ret = pthread_mutex_unlock (&mutex);
318 if (ret) {
319 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
323 static int trylock (const char *cap)
325 int ret = pthread_mutex_trylock (&mutex);
326 if (ret && ret != EBUSY) {
327 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
329 return ret == EBUSY;
332 static void *parse_pointer (const char *cap, const char *s)
334 int ret;
335 void *ptr;
337 ret = sscanf (s, "%" SCN_ptr, SCN_ptr_cast (&ptr));
338 if (ret != 1) {
339 errx (1, "%s: cannot parse pointer in `%s'", cap, s);
341 return ptr;
344 static double now (void)
346 struct timeval tv;
348 if (gettimeofday (&tv, NULL)) {
349 err (1, "gettimeofday");
351 return tv.tv_sec + tv.tv_usec*1e-6;
354 static int hasdata (void)
356 int ret, avail;
357 ret = ioctl (state.csock, FIONREAD, &avail);
358 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
359 return avail > 0;
362 CAMLprim value ml_hasdata (value fd_v)
364 CAMLparam1 (fd_v);
365 int ret, avail;
367 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
368 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
369 CAMLreturn (Val_bool (avail > 0));
372 static void readdata (int fd, void *p, int size)
374 ssize_t n;
376 again:
377 n = read (fd, p, size);
378 if (n - size) {
379 if (n < 0 && errno == EINTR) goto again;
380 if (!n) errx (1, "EOF while reading");
381 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
385 static void writedata (int fd, char *p, int size)
387 ssize_t n;
388 uint32_t size4 = size;
389 struct iovec iov[2] = {
390 { .iov_base = &size4, .iov_len = 4 },
391 { .iov_base = p, .iov_len = size }
394 again:
395 n = writev (fd, iov, 2);
396 if (n < 0 && errno == EINTR) goto again;
397 if (n - size - 4) {
398 if (!n) errx (1, "EOF while writing data");
399 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
403 static int readlen (int fd)
405 /* Type punned unions here. Why? Less code (Adjusted by more comments).
406 https://en.wikipedia.org/wiki/Type_punning */
407 union { uint32_t len; char raw[4]; } buf;
408 readdata (fd, buf.raw, 4);
409 return buf.len;
412 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
414 CAMLparam3 (fd_v, bytes_v, len_v);
415 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
416 CAMLreturn0;
419 CAMLprim value ml_rcmd (value fd_v)
421 CAMLparam1 (fd_v);
422 CAMLlocal1 (strdata_v);
423 int fd = Int_val (fd_v);
424 int len = readlen (fd);
425 strdata_v = caml_alloc_string (len);
426 readdata (fd, String_val (strdata_v), len);
427 CAMLreturn (strdata_v);
430 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
432 int size = 64, len;
433 va_list ap;
434 char fbuf[size];
435 char *buf = fbuf;
437 for (;;) {
438 va_start (ap, fmt);
439 len = vsnprintf (buf, size, fmt, ap);
440 va_end (ap);
442 if (len > -1) {
443 if (len < size - 4) {
444 writedata (state.csock, buf, len);
445 break;
447 else size = len + 5;
449 else {
450 err (1, "vsnprintf for `%s' failed", fmt);
452 buf = realloc (buf == fbuf ? NULL : buf, size);
453 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
455 if (buf != fbuf) free (buf);
458 static void closedoc (void)
460 #ifdef CACHE_PAGEREFS
461 if (state.pdflut.objs) {
462 for (int i = 0; i < state.pdflut.count; ++i) {
463 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
465 free (state.pdflut.objs);
466 state.pdflut.objs = NULL;
467 state.pdflut.idx = 0;
469 #endif
470 if (state.doc) {
471 fz_drop_document (state.ctx, state.doc);
472 state.doc = NULL;
476 static int openxref (char *filename, char *password)
478 for (int i = 0; i < state.texcount; ++i) {
479 state.texowners[i].w = -1;
480 state.texowners[i].slice = NULL;
483 closedoc ();
485 state.dirty = 0;
486 if (state.pagedims) {
487 free (state.pagedims);
488 state.pagedims = NULL;
490 state.pagedimcount = 0;
492 fz_set_aa_level (state.ctx, state.aalevel);
493 state.doc = fz_open_document (state.ctx, filename);
494 if (fz_needs_password (state.ctx, state.doc)) {
495 if (password && !*password) {
496 printd ("pass");
497 return 0;
499 else {
500 int ok = fz_authenticate_password (state.ctx, state.doc, password);
501 if (!ok) {
502 printd ("pass fail");
503 return 0;
507 state.pagecount = fz_count_pages (state.ctx, state.doc);
508 return 1;
511 static void pdfinfo (void)
513 struct { char *tag; char *name; } metatbl[] = {
514 { FZ_META_INFO_TITLE, "Title" },
515 { FZ_META_INFO_AUTHOR, "Author" },
516 { FZ_META_FORMAT, "Format" },
517 { FZ_META_ENCRYPTION, "Encryption" },
518 { "info:Creator", "Creator" },
519 { "info:Producer", "Producer" },
520 { "info:CreationDate", "Creation date" },
522 int len = 0;
523 char *buf = NULL;
525 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
526 int need;
527 again:
528 need = fz_lookup_metadata (state.ctx, state.doc,
529 metatbl[i].tag, buf, len);
530 if (need > 0) {
531 if (need <= len) {
532 printd ("info %s\t%s", metatbl[i].name, buf);
534 else {
535 buf = realloc (buf, need + 1);
536 if (!buf) err (1, "pdfinfo realloc %d", need + 1);
537 len = need + 1;
538 goto again;
542 free (buf);
544 printd ("infoend");
547 static void unlinktile (struct tile *tile)
549 for (int i = 0; i < tile->slicecount; ++i) {
550 struct slice *s = &tile->slices[i];
552 if (s->texindex != -1) {
553 if (state.texowners[s->texindex].slice == s) {
554 state.texowners[s->texindex].slice = NULL;
560 static void freepage (struct page *page)
562 if (!page) return;
563 if (page->text) {
564 fz_drop_stext_page (state.ctx, page->text);
566 if (page->sheet) {
567 fz_drop_stext_sheet (state.ctx, page->sheet);
569 if (page->slinks) {
570 free (page->slinks);
572 fz_drop_display_list (state.ctx, page->dlist);
573 fz_drop_page (state.ctx, page->fzpage);
574 free (page);
577 static void freetile (struct tile *tile)
579 unlinktile (tile);
580 if (!tile->pbo) {
581 #ifndef PIGGYBACK
582 fz_drop_pixmap (state.ctx, tile->pixmap);
583 #else
584 if (state.pig) {
585 fz_drop_pixmap (state.ctx, state.pig);
587 state.pig = tile->pixmap;
588 #endif
590 else {
591 free (tile->pbo);
592 fz_drop_pixmap (state.ctx, tile->pixmap);
594 free (tile);
597 #ifdef __ALTIVEC__
598 #include <stdint.h>
599 #include <altivec.h>
601 static int cacheline32bytes;
603 static void __attribute__ ((constructor)) clcheck (void)
605 char **envp = environ;
606 unsigned long *auxv;
608 while (*envp++);
610 for (auxv = (unsigned long *) envp; *auxv != 0; auxv += 2) {
611 if (*auxv == 19) {
612 cacheline32bytes = auxv[1] == 32;
613 return;
618 static void OPTIMIZE_ATTR (3) clearpixmap (fz_pixmap *pixmap)
620 size_t size = pixmap->w * pixmap->h * pixmap->n;
621 if (cacheline32bytes && size > 32) {
622 intptr_t a1, a2, diff;
623 size_t sizea, i;
624 vector unsigned char v = vec_splat_u8 (-1);
625 vector unsigned char *p;
627 a1 = a2 = (intptr_t) pixmap->samples;
628 a2 = (a1 + 31) & ~31;
629 diff = a2 - a1;
630 sizea = size - diff;
631 p = (void *) a2;
633 while (a1 != a2) *(char *) a1++ = 0xff;
634 for (i = 0; i < (sizea & ~31); i += 32) {
635 __asm volatile ("dcbz %0, %1"::"b"(a2),"r"(i));
636 vec_st (v, i, p);
637 vec_st (v, i + 16, p);
639 while (i < sizea) *((char *) a1 + i++) = 0xff;
641 else fz_clear_pixmap_with_value (state.ctx, pixmap, 0xff);
643 #else
644 #define clearpixmap(p) fz_clear_pixmap_with_value (state.ctx, p, 0xff)
645 #endif
647 static void trimctm (pdf_page *page, int pindex)
649 fz_matrix ctm;
650 struct pagedim *pdim = &state.pagedims[pindex];
652 if (!page) return;
653 if (!pdim->tctmready) {
654 fz_rect realbox, mediabox;
655 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
657 fz_rotate (&rm, -pdim->rotate);
658 fz_scale (&sm, 1, -1);
659 fz_concat (&ctm, &rm, &sm);
660 realbox = pdim->mediabox;
661 fz_transform_rect (&realbox, &ctm);
662 fz_translate (&tm, -realbox.x0, -realbox.y0);
663 fz_concat (&ctm1, &ctm, &tm);
664 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
665 fz_invert_matrix (&im, &page_ctm);
666 fz_concat (&ctm, &im, &ctm1);
667 pdim->tctm = ctm;
668 pdim->tctmready = 1;
672 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
674 fz_matrix ctm, tm;
675 int pdimno = pdim - state.pagedims;
677 if (pdf_specifics (state.ctx, state.doc)) {
678 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), pdimno);
679 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
681 else {
682 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
683 fz_concat (&ctm, &tm, &pdim->ctm);
685 return ctm;
688 static fz_matrix pagectm (struct page *page)
690 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
693 static void *loadpage (int pageno, int pindex)
695 fz_device *dev;
696 struct page *page;
698 page = calloc (sizeof (struct page), 1);
699 if (!page) {
700 err (1, "calloc page %d", pageno);
703 page->dlist = fz_new_display_list (state.ctx, NULL);
704 dev = fz_new_list_device (state.ctx, page->dlist);
705 fz_try (state.ctx) {
706 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
707 fz_run_page (state.ctx, page->fzpage, dev,
708 &fz_identity, NULL);
710 fz_catch (state.ctx) {
711 page->fzpage = NULL;
713 fz_close_device (state.ctx, dev);
714 fz_drop_device (state.ctx, dev);
716 page->pdimno = pindex;
717 page->pageno = pageno;
718 page->sgen = state.gen;
719 page->agen = state.gen;
720 page->tgen = state.gen;
721 return page;
724 static struct tile *alloctile (int h)
726 int slicecount;
727 size_t tilesize;
728 struct tile *tile;
730 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
731 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
732 tile = calloc (tilesize, 1);
733 if (!tile) {
734 err (1, "cannot allocate tile (%" FMT_s " bytes)", tilesize);
736 for (int i = 0; i < slicecount; ++i) {
737 int sh = fz_mini (h, state.sliceheight);
738 tile->slices[i].h = sh;
739 tile->slices[i].texindex = -1;
740 h -= sh;
742 tile->slicecount = slicecount;
743 tile->sliceheight = state.sliceheight;
744 return tile;
747 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
748 struct bo *pbo)
750 fz_rect rect;
751 fz_irect bbox;
752 fz_matrix ctm;
753 fz_device *dev;
754 struct tile *tile;
755 struct pagedim *pdim;
757 tile = alloctile (h);
758 pdim = &state.pagedims[page->pdimno];
760 bbox = pdim->bounds;
761 bbox.x0 += x;
762 bbox.y0 += y;
763 bbox.x1 = bbox.x0 + w;
764 bbox.y1 = bbox.y0 + h;
766 if (state.pig) {
767 if (state.pig->w == w
768 && state.pig->h == h
769 && state.pig->colorspace == state.colorspace) {
770 tile->pixmap = state.pig;
771 tile->pixmap->x = bbox.x0;
772 tile->pixmap->y = bbox.y0;
774 else {
775 fz_drop_pixmap (state.ctx, state.pig);
777 state.pig = NULL;
779 if (!tile->pixmap) {
780 if (pbo) {
781 tile->pixmap =
782 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
783 &bbox, 1, pbo->ptr);
784 tile->pbo = pbo;
786 else {
787 tile->pixmap =
788 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox, 1);
792 tile->w = w;
793 tile->h = h;
794 clearpixmap (tile->pixmap);
796 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
797 ctm = pagectm (page);
798 fz_rect_from_irect (&rect, &bbox);
799 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
800 fz_close_device (state.ctx, dev);
801 fz_drop_device (state.ctx, dev);
803 return tile;
806 #ifdef CACHE_PAGEREFS
807 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
808 thanks to Robin Watts */
809 static void
810 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
812 fz_context *ctx = state.ctx; /* doc->ctx; */
813 pdf_obj *kids;
814 int len;
816 if (state.pdflut.idx == state.pagecount) return;
818 kids = pdf_dict_gets (ctx, node, "Kids");
819 len = pdf_array_len (ctx, kids);
821 if (len == 0)
822 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
824 if (pdf_mark_obj (ctx, node))
825 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
826 for (int i = 0; i < len; i++) {
827 pdf_obj *kid = pdf_array_get (ctx, kids, i);
828 char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
829 if (*type
830 ? !strcmp (type, "Pages")
831 : pdf_dict_gets (ctx, kid, "Kids")
832 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
833 pdf_collect_pages (doc, kid);
835 else {
836 if (*type
837 ? strcmp (type, "Page") != 0
838 : !pdf_dict_gets (ctx, kid, "MediaBox"))
839 fz_warn (ctx, "non-page object in page tree (%s)", type);
840 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
843 pdf_unmark_obj (ctx, node);
846 static void
847 pdf_load_page_objs (pdf_document *doc)
849 pdf_obj *root = pdf_dict_gets (state.ctx,
850 pdf_trailer (state.ctx, doc), "Root");
851 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
853 if (!node)
854 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
856 state.pdflut.idx = 0;
857 pdf_collect_pages (doc, node);
859 #endif
861 static void initpdims (int wthack)
863 double start, end;
864 FILE *trimf = NULL;
865 fz_rect rootmediabox;
866 int pageno, trim, show;
867 int trimw = 0, cxcount;
868 fz_context *ctx = state.ctx;
869 pdf_document *pdf = pdf_specifics (ctx, state.doc);
871 fz_var (trimw);
872 fz_var (trimf);
873 fz_var (cxcount);
874 start = now ();
876 if (state.trimmargins && state.trimcachepath) {
877 trimf = fopen (state.trimcachepath, "rb");
878 if (!trimf) {
879 trimf = fopen (state.trimcachepath, "wb");
880 trimw = 1;
884 if (state.trimmargins || pdf || !state.cxack)
885 cxcount = state.pagecount;
886 else
887 cxcount = fz_mini (state.pagecount, 1);
889 if (pdf) {
890 pdf_obj *obj;
891 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
892 "Root/Pages/MediaBox");
893 pdf_to_rect (ctx, obj, &rootmediabox);
896 #ifdef CACHE_PAGEREFS
897 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
898 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
899 if (!state.pdflut.objs) {
900 err (1, "malloc pageobjs %zu %d %zu failed",
901 sizeof (*state.pdflut.objs), cxcount,
902 sizeof (*state.pdflut.objs) * cxcount);
904 state.pdflut.count = cxcount;
905 pdf_load_page_objs (pdf);
906 state.pdflut.pdf = pdf;
908 #endif
910 for (pageno = 0; pageno < cxcount; ++pageno) {
911 int rotate = 0;
912 struct pagedim *p;
913 fz_rect mediabox;
915 fz_var (rotate);
916 if (pdf) {
917 pdf_obj *pageref, *pageobj;
919 #ifdef CACHE_PAGEREFS
920 pageref = state.pdflut.objs[pageno];
921 #else
922 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
923 #endif
924 pageobj = pdf_resolve_indirect (ctx, pageref);
925 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
927 if (state.trimmargins) {
928 pdf_obj *obj;
929 pdf_page *page;
931 fz_try (ctx) {
932 page = pdf_load_page (ctx, pdf, pageno);
933 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
934 trim = state.trimanew || !obj;
935 if (trim) {
936 fz_rect rect;
937 fz_device *dev;
938 fz_matrix ctm, page_ctm;
940 dev = fz_new_bbox_device (ctx, &rect);
941 dev->hints |= FZ_IGNORE_SHADE;
942 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
943 fz_invert_matrix (&ctm, &page_ctm);
944 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
945 fz_close_device (ctx, dev);
946 fz_drop_device (ctx, dev);
948 rect.x0 += state.trimfuzz.x0;
949 rect.x1 += state.trimfuzz.x1;
950 rect.y0 += state.trimfuzz.y0;
951 rect.y1 += state.trimfuzz.y1;
952 fz_transform_rect (&rect, &ctm);
953 fz_intersect_rect (&rect, &mediabox);
955 if (!fz_is_empty_rect (&rect)) {
956 mediabox = rect;
959 obj = pdf_new_array (ctx, pdf, 4);
960 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
961 mediabox.x0));
962 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
963 mediabox.y0));
964 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
965 mediabox.x1));
966 pdf_array_push (ctx, obj, pdf_new_real (ctx, pdf,
967 mediabox.y1));
968 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
970 else {
971 mediabox.x0 = pdf_to_real (ctx,
972 pdf_array_get (ctx, obj, 0));
973 mediabox.y0 = pdf_to_real (ctx,
974 pdf_array_get (ctx, obj, 1));
975 mediabox.x1 = pdf_to_real (ctx,
976 pdf_array_get (ctx, obj, 2));
977 mediabox.y1 = pdf_to_real (ctx,
978 pdf_array_get (ctx, obj, 3));
981 fz_drop_page (ctx, &page->super);
982 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
983 if (show) {
984 printd ("progress %f Trimming %d",
985 (double) (pageno + 1) / state.pagecount,
986 pageno + 1);
989 fz_catch (ctx) {
990 fprintf (stderr, "failed to load page %d\n", pageno+1);
993 else {
994 int empty = 0;
995 fz_rect cropbox;
997 pdf_to_rect (ctx,
998 pdf_dict_gets (ctx, pageobj, "MediaBox"),
999 &mediabox);
1000 if (fz_is_empty_rect (&mediabox)) {
1001 mediabox.x0 = 0;
1002 mediabox.y0 = 0;
1003 mediabox.x1 = 612;
1004 mediabox.y1 = 792;
1005 empty = 1;
1008 pdf_to_rect (ctx,
1009 pdf_dict_gets (ctx, pageobj, "CropBox"),
1010 &cropbox);
1011 if (!fz_is_empty_rect (&cropbox)) {
1012 if (empty) {
1013 mediabox = cropbox;
1015 else {
1016 fz_intersect_rect (&mediabox, &cropbox);
1019 else {
1020 if (empty) {
1021 if (fz_is_empty_rect (&rootmediabox)) {
1022 fprintf (stderr,
1023 "cannot find page size for page %d\n",
1024 pageno+1);
1026 else {
1027 mediabox = rootmediabox;
1033 else {
1034 if (state.trimmargins && trimw) {
1035 fz_page *page;
1037 fz_try (ctx) {
1038 page = fz_load_page (ctx, state.doc, pageno);
1039 fz_bound_page (ctx, page, &mediabox);
1040 if (state.trimmargins) {
1041 fz_rect rect;
1042 fz_device *dev;
1044 dev = fz_new_bbox_device (ctx, &rect);
1045 dev->hints |= FZ_IGNORE_SHADE;
1046 fz_run_page (ctx, page, dev, &fz_identity, NULL);
1047 fz_close_device (ctx, dev);
1048 fz_drop_device (ctx, dev);
1050 rect.x0 += state.trimfuzz.x0;
1051 rect.x1 += state.trimfuzz.x1;
1052 rect.y0 += state.trimfuzz.y0;
1053 rect.y1 += state.trimfuzz.y1;
1054 fz_intersect_rect (&rect, &mediabox);
1056 if (!fz_is_empty_rect (&rect)) {
1057 mediabox = rect;
1060 fz_drop_page (ctx, page);
1061 if (!state.cxack) {
1062 printd ("progress %f loading %d",
1063 (double) (pageno + 1) / state.pagecount,
1064 pageno + 1);
1067 fz_catch (ctx) {
1069 if (trimf) {
1070 int n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
1071 if (n - 1) {
1072 err (1, "fwrite trim mediabox");
1076 else {
1077 if (trimf) {
1078 int n = fread (&mediabox, sizeof (mediabox), 1, trimf);
1079 if (n - 1) {
1080 err (1, "fread trim mediabox %d", pageno);
1083 else {
1084 fz_page *page;
1085 fz_try (ctx) {
1086 page = fz_load_page (ctx, state.doc, pageno);
1087 fz_bound_page (ctx, page, &mediabox);
1088 fz_drop_page (ctx, page);
1090 show = !state.trimmargins && pageno % 20 == 0;
1091 if (show) {
1092 printd ("progress %f Gathering dimensions %d",
1093 (double) (pageno) / state.pagecount,
1094 pageno);
1097 fz_catch (ctx) {
1098 fprintf (stderr, "failed to load page %d\n", pageno);
1104 if (state.pagedimcount == 0
1105 || (p = &state.pagedims[state.pagedimcount-1], p->rotate != rotate)
1106 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
1107 size_t size;
1109 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
1110 state.pagedims = realloc (state.pagedims, size);
1111 if (!state.pagedims) {
1112 err (1, "realloc pagedims to %" FMT_s " (%d elems)",
1113 size, state.pagedimcount + 1);
1116 p = &state.pagedims[state.pagedimcount++];
1117 p->rotate = rotate;
1118 p->mediabox = mediabox;
1119 p->pageno = pageno;
1122 end = now ();
1123 if (!wthack) {
1124 printd ("progress 1 %s %d pages in %f seconds",
1125 state.trimmargins ? "Trimmed" : "Processed",
1126 state.pagecount, end - start);
1128 state.trimanew = 0;
1129 if (trimf) {
1130 if (fclose (trimf)) {
1131 err (1, "fclose");
1136 static void layout (void)
1138 int pindex;
1139 fz_rect box;
1140 fz_matrix ctm, rm;
1141 struct pagedim *p = p;
1142 double zw, w, maxw = 0.0, zoom = zoom;
1144 if (state.pagedimcount == 0) return;
1146 switch (state.fitmodel) {
1147 case FitProportional:
1148 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1149 double x0, x1;
1151 p = &state.pagedims[pindex];
1152 fz_rotate (&rm, p->rotate + state.rotate);
1153 box = p->mediabox;
1154 fz_transform_rect (&box, &rm);
1156 x0 = fz_min (box.x0, box.x1);
1157 x1 = fz_max (box.x0, box.x1);
1159 w = x1 - x0;
1160 maxw = fz_max (w, maxw);
1161 zoom = state.w / maxw;
1163 break;
1165 case FitPage:
1166 maxw = state.w;
1167 break;
1169 case FitWidth:
1170 break;
1172 default:
1173 ARSERT (0 && state.fitmodel);
1176 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1177 fz_rect rect;
1178 fz_matrix tm, sm;
1180 p = &state.pagedims[pindex];
1181 fz_rotate (&ctm, state.rotate);
1182 fz_rotate (&rm, p->rotate + state.rotate);
1183 box = p->mediabox;
1184 fz_transform_rect (&box, &rm);
1185 w = box.x1 - box.x0;
1186 switch (state.fitmodel) {
1187 case FitProportional:
1188 p->left = ((maxw - w) * zoom) / 2.0;
1189 break;
1190 case FitPage:
1192 double zh, h;
1193 zw = maxw / w;
1194 h = box.y1 - box.y0;
1195 zh = state.h / h;
1196 zoom = fz_min (zw, zh);
1197 p->left = (maxw - (w * zoom)) / 2.0;
1199 break;
1200 case FitWidth:
1201 p->left = 0;
1202 zoom = state.w / w;
1203 break;
1206 fz_scale (&p->zoomctm, zoom, zoom);
1207 fz_concat (&ctm, &p->zoomctm, &ctm);
1209 fz_rotate (&rm, p->rotate);
1210 p->pagebox = p->mediabox;
1211 fz_transform_rect (&p->pagebox, &rm);
1212 p->pagebox.x1 -= p->pagebox.x0;
1213 p->pagebox.y1 -= p->pagebox.y0;
1214 p->pagebox.x0 = 0;
1215 p->pagebox.y0 = 0;
1216 rect = p->pagebox;
1217 fz_transform_rect (&rect, &ctm);
1218 fz_round_rect (&p->bounds, &rect);
1219 p->ctm = ctm;
1221 fz_translate (&tm, 0, -p->mediabox.y1);
1222 fz_scale (&sm, zoom, -zoom);
1223 fz_concat (&ctm, &tm, &sm);
1225 p->tctmready = 0;
1228 do {
1229 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1230 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1231 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1232 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1233 int boundw = x1 - x0;
1234 int boundh = y1 - y0;
1236 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1237 } while (p-- != state.pagedims);
1240 struct pagedim *pdimofpageno (int pageno)
1242 struct pagedim *pdim = state.pagedims;
1244 for (int i = 0; i < state.pagedimcount; ++i) {
1245 if (state.pagedims[i].pageno > pageno)
1246 break;
1247 pdim = &state.pagedims[i];
1249 return pdim;
1252 static
1253 struct anchor { int n; int x; int y; int w; int h; }
1254 uritoanchor (const char *uri)
1256 fz_point p;
1257 struct anchor a;
1259 a.n = -1;
1260 a.n = fz_resolve_link (state.ctx, state.doc, uri, &p.x, &p.y);
1261 if (a.n >= 0) {
1262 struct pagedim *pdim = pdimofpageno (a.n);
1263 fz_transform_point (&p, &pdim->ctm);
1264 a.x = p.x;
1265 a.y = p.y;
1266 a.h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1268 return a;
1271 static void recurse_outline (fz_outline *outline, int level)
1273 while (outline) {
1274 struct anchor a = uritoanchor (outline->uri);
1275 if (a.n >= 0) {
1276 printd ("o %d %d %d %d %s", level, a.n, a.y, a.h, outline->title);
1278 else {
1279 printd ("on %d %s", level, outline->title);
1281 if (outline->down) {
1282 recurse_outline (outline->down, level + 1);
1284 outline = outline->next;
1288 static void process_outline (void)
1290 fz_outline *outline;
1292 if (!state.needoutline || !state.pagedimcount) return;
1294 state.needoutline = 0;
1295 outline = fz_load_outline (state.ctx, state.doc);
1296 if (outline) {
1297 recurse_outline (outline, 0);
1298 fz_drop_outline (state.ctx, outline);
1302 static char *strofspan (fz_stext_span *span)
1304 char *p;
1305 char utf8[10];
1306 fz_stext_char *ch;
1307 size_t size = 0, cap = 80;
1309 p = malloc (cap + 1);
1310 if (!p) return NULL;
1312 for (ch = span->text; ch < span->text + span->len; ++ch) {
1313 int n = fz_runetochar (utf8, ch->c);
1314 if (size + n > cap) {
1315 cap *= 2;
1316 p = realloc (p, cap + 1);
1317 if (!p) return NULL;
1320 memcpy (p + size, utf8, n);
1321 size += n;
1323 p[size] = 0;
1324 return p;
1327 static int matchspan (regex_t *re, fz_stext_span *span,
1328 int stop, int pageno, double start)
1330 int ret;
1331 char *p;
1332 regmatch_t rm;
1333 int a, b, c;
1334 fz_rect sb, eb;
1335 fz_point p1, p2, p3, p4;
1337 p = strofspan (span);
1338 if (!p) return -1;
1340 ret = regexec (re, p, 1, &rm, 0);
1341 if (ret) {
1342 free (p);
1343 if (ret != REG_NOMATCH) {
1344 size_t size;
1345 char errbuf[80];
1346 size = regerror (ret, re, errbuf, sizeof (errbuf));
1347 printd ("msg regexec error `%.*s'",
1348 (int) size, errbuf);
1349 return -1;
1351 return 0;
1353 else {
1354 int l = span->len;
1356 for (a = 0, c = 0; c < rm.rm_so && a < l; a++) {
1357 c += fz_runelen (span->text[a].c);
1359 for (b = a; c < rm.rm_eo - 1 && b < l; b++) {
1360 c += fz_runelen (span->text[b].c);
1363 if (fz_runelen (span->text[b].c) > 1) {
1364 b = fz_maxi (0, b-1);
1367 fz_stext_char_bbox (state.ctx, &sb, span, a);
1368 fz_stext_char_bbox (state.ctx, &eb, span, b);
1370 p1.x = sb.x0;
1371 p1.y = sb.y0;
1372 p2.x = eb.x1;
1373 p2.y = sb.y0;
1374 p3.x = eb.x1;
1375 p3.y = eb.y1;
1376 p4.x = sb.x0;
1377 p4.y = eb.y1;
1379 if (!stop) {
1380 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1381 pageno, 1,
1382 p1.x, p1.y,
1383 p2.x, p2.y,
1384 p3.x, p3.y,
1385 p4.x, p4.y);
1387 printd ("progress 1 found at %d `%.*s' in %f sec",
1388 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1389 now () - start);
1391 else {
1392 printd ("match %d %d %f %f %f %f %f %f %f %f",
1393 pageno, 2,
1394 p1.x, p1.y,
1395 p2.x, p2.y,
1396 p3.x, p3.y,
1397 p4.x, p4.y);
1399 free (p);
1400 return 1;
1404 static int compareblocks (const void *l, const void *r)
1406 fz_stext_block const *ls = l;
1407 fz_stext_block const *rs = r;
1408 return ls->bbox.y0 - rs->bbox.y0;
1411 /* wishful thinking function */
1412 static void search (regex_t *re, int pageno, int y, int forward)
1414 int j;
1415 fz_device *tdev;
1416 fz_stext_page *text;
1417 fz_stext_sheet *sheet;
1418 struct pagedim *pdim;
1419 int stop = 0, niters = 0;
1420 double start, end;
1421 fz_page *page;
1423 start = now ();
1424 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1425 if (niters++ == 5) {
1426 niters = 0;
1427 if (hasdata ()) {
1428 printd ("progress 1 attention requested aborting search at %d",
1429 pageno);
1430 stop = 1;
1432 else {
1433 printd ("progress %f searching in page %d",
1434 (double) (pageno + 1) / state.pagecount,
1435 pageno);
1438 pdim = pdimofpageno (pageno);
1439 sheet = fz_new_stext_sheet (state.ctx);
1440 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1441 tdev = fz_new_stext_device (state.ctx, sheet, text, 0);
1443 page = fz_load_page (state.ctx, state.doc, pageno);
1445 fz_matrix ctm = pagectm1 (page, pdim);
1446 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1449 qsort (text->blocks, text->len, sizeof (*text->blocks), compareblocks);
1450 fz_close_device (state.ctx, tdev);
1451 fz_drop_device (state.ctx, tdev);
1453 for (j = 0; j < text->len; ++j) {
1454 int k;
1455 fz_page_block *pb;
1456 fz_stext_block *block;
1458 pb = &text->blocks[forward ? j : text->len - 1 - j];
1459 if (pb->type != FZ_PAGE_BLOCK_TEXT) continue;
1460 block = pb->u.text;
1462 for (k = 0; k < block->len; ++k) {
1463 fz_stext_line *line;
1464 fz_stext_span *span;
1466 if (forward) {
1467 line = &block->lines[k];
1468 if (line->bbox.y0 < y + 1) continue;
1470 else {
1471 line = &block->lines[block->len - 1 - k];
1472 if (line->bbox.y0 > y - 1) continue;
1475 for (span = line->first_span; span; span = span->next) {
1476 switch (matchspan (re, span, stop, pageno, start)) {
1477 case 0: break;
1478 case 1: stop = 1; break;
1479 case -1: stop = 1; goto endloop;
1484 if (forward) {
1485 pageno += 1;
1486 y = 0;
1488 else {
1489 pageno -= 1;
1490 y = INT_MAX;
1492 endloop:
1493 fz_drop_stext_page (state.ctx, text);
1494 fz_drop_stext_sheet (state.ctx, sheet);
1495 fz_drop_page (state.ctx, page);
1497 end = now ();
1498 if (!stop) {
1499 printd ("progress 1 no matches %f sec", end - start);
1501 printd ("clearrects");
1504 static void set_tex_params (int colorspace)
1506 union {
1507 unsigned char b;
1508 unsigned int s;
1509 } endianness = {1};
1511 switch (colorspace) {
1512 case 0:
1513 state.texiform = GL_RGBA8;
1514 state.texform = GL_RGBA;
1515 state.texty = GL_UNSIGNED_BYTE;
1516 state.colorspace = fz_device_rgb (state.ctx);
1517 break;
1518 case 1:
1519 state.texiform = GL_RGBA8;
1520 state.texform = GL_BGRA;
1521 state.texty = endianness.s > 1
1522 ? GL_UNSIGNED_INT_8_8_8_8
1523 : GL_UNSIGNED_INT_8_8_8_8_REV;
1524 state.colorspace = fz_device_bgr (state.ctx);
1525 break;
1526 case 2:
1527 state.texiform = GL_LUMINANCE_ALPHA;
1528 state.texform = GL_LUMINANCE_ALPHA;
1529 state.texty = GL_UNSIGNED_BYTE;
1530 state.colorspace = fz_device_gray (state.ctx);
1531 break;
1532 default:
1533 errx (1, "invalid colorspce %d", colorspace);
1537 static void realloctexts (int texcount)
1539 size_t size;
1541 if (texcount == state.texcount) return;
1543 if (texcount < state.texcount) {
1544 glDeleteTextures (state.texcount - texcount,
1545 state.texids + texcount);
1548 size = texcount * sizeof (*state.texids);
1549 state.texids = realloc (state.texids, size);
1550 if (!state.texids) {
1551 err (1, "realloc texids %" FMT_s, size);
1554 size = texcount * sizeof (*state.texowners);
1555 state.texowners = realloc (state.texowners, size);
1556 if (!state.texowners) {
1557 err (1, "realloc texowners %" FMT_s, size);
1559 if (texcount > state.texcount) {
1560 glGenTextures (texcount - state.texcount,
1561 state.texids + state.texcount);
1562 for (int i = state.texcount; i < texcount; ++i) {
1563 state.texowners[i].w = -1;
1564 state.texowners[i].slice = NULL;
1567 state.texcount = texcount;
1568 state.texindex = 0;
1571 static char *mbtoutf8 (char *s)
1573 char *p, *r;
1574 wchar_t *tmp;
1575 size_t i, ret, len;
1577 if (state.utf8cs) {
1578 return s;
1581 len = mbstowcs (NULL, s, strlen (s));
1582 if (len == 0) {
1583 return s;
1585 else {
1586 if (len == (size_t) -1) {
1587 printd ("emsg mbstowcs %d:%s\n", errno, strerror (errno));
1588 return s;
1592 tmp = malloc (len * sizeof (wchar_t));
1593 if (!tmp) {
1594 return s;
1597 ret = mbstowcs (tmp, s, len);
1598 if (ret == (size_t) -1) {
1599 free (tmp);
1600 return s;
1603 len = 0;
1604 for (i = 0; i < ret; ++i) {
1605 len += fz_runelen (tmp[i]);
1608 p = r = malloc (len + 1);
1609 if (!r) {
1610 free (tmp);
1611 return s;
1614 for (i = 0; i < ret; ++i) {
1615 p += fz_runetochar (p, tmp[i]);
1617 *p = 0;
1618 free (tmp);
1619 return r;
1622 CAMLprim value ml_mbtoutf8 (value s_v)
1624 CAMLparam1 (s_v);
1625 CAMLlocal1 (ret_v);
1626 char *s, *r;
1628 s = String_val (s_v);
1629 r = mbtoutf8 (s);
1630 if (r == s) {
1631 ret_v = s_v;
1633 else {
1634 ret_v = caml_copy_string (r);
1635 free (r);
1637 CAMLreturn (ret_v);
1640 static void * mainloop (void UNUSED_ATTR *unused)
1642 char *p = NULL;
1643 int len, ret, oldlen = 0;
1645 fz_var (p);
1646 fz_var (oldlen);
1647 for (;;) {
1648 len = readlen (state.csock);
1649 if (len == 0) {
1650 errx (1, "readlen returned 0");
1653 if (oldlen < len + 1) {
1654 p = realloc (p, len + 1);
1655 if (!p) {
1656 err (1, "realloc %d failed", len + 1);
1658 oldlen = len + 1;
1660 readdata (state.csock, p, len);
1661 p[len] = 0;
1663 if (!strncmp ("open", p, 4)) {
1664 int wthack, off, usedoccss, ok = 0;
1665 char *password;
1666 char *filename;
1667 char *utf8filename;
1668 size_t filenamelen;
1670 fz_var (ok);
1671 ret = sscanf (p + 5, " %d %d %d %n",
1672 &wthack, &state.cxack, &usedoccss, &off);
1673 if (ret != 3) {
1674 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1677 filename = p + 5 + off;
1678 filenamelen = strlen (filename);
1679 password = filename + filenamelen + 1;
1681 if (password[strlen (password) + 1]) {
1682 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1685 lock ("open");
1686 fz_set_use_document_css (state.ctx, usedoccss);
1687 fz_try (state.ctx) {
1688 ok = openxref (filename, password);
1690 fz_catch (state.ctx) {
1691 utf8filename = mbtoutf8 (filename);
1692 printd ("msg Could not open %s", utf8filename);
1694 if (ok) {
1695 pdfinfo ();
1696 initpdims (wthack);
1698 unlock ("open");
1700 if (ok) {
1701 if (!wthack) {
1702 utf8filename = mbtoutf8 (filename);
1703 printd ("msg Opened %s (press h/F1 to get help)",
1704 utf8filename);
1705 if (utf8filename != filename) {
1706 free (utf8filename);
1709 state.needoutline = 1;
1712 else if (!strncmp ("cs", p, 2)) {
1713 int i, colorspace;
1715 ret = sscanf (p + 2, " %d", &colorspace);
1716 if (ret != 1) {
1717 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1719 lock ("cs");
1720 set_tex_params (colorspace);
1721 for (i = 0; i < state.texcount; ++i) {
1722 state.texowners[i].w = -1;
1723 state.texowners[i].slice = NULL;
1725 unlock ("cs");
1727 else if (!strncmp ("freepage", p, 8)) {
1728 void *ptr;
1730 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1731 if (ret != 1) {
1732 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1734 freepage (ptr);
1736 else if (!strncmp ("freetile", p, 8)) {
1737 void *ptr;
1739 ret = sscanf (p + 8, " %" SCN_ptr, SCN_ptr_cast (&ptr));
1740 if (ret != 1) {
1741 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1743 freetile (ptr);
1745 else if (!strncmp ("search", p, 6)) {
1746 int icase, pageno, y, len2, forward;
1747 char *pattern;
1748 regex_t re;
1750 ret = sscanf (p + 6, " %d %d %d %d,%n",
1751 &icase, &pageno, &y, &forward, &len2);
1752 if (ret != 4) {
1753 errx (1, "malformed search `%s' ret=%d", p, ret);
1756 pattern = p + 6 + len2;
1757 ret = regcomp (&re, pattern,
1758 REG_EXTENDED | (icase ? REG_ICASE : 0));
1759 if (ret) {
1760 char errbuf[80];
1761 size_t size;
1763 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1764 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1766 else {
1767 search (&re, pageno, y, forward);
1768 regfree (&re);
1771 else if (!strncmp ("geometry", p, 8)) {
1772 int w, h, fitmodel;
1774 printd ("clear");
1775 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1776 if (ret != 3) {
1777 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1780 lock ("geometry");
1781 state.h = h;
1782 if (w != state.w) {
1783 state.w = w;
1784 for (int i = 0; i < state.texcount; ++i) {
1785 state.texowners[i].slice = NULL;
1788 state.fitmodel = fitmodel;
1789 layout ();
1790 process_outline ();
1792 state.gen++;
1793 unlock ("geometry");
1794 printd ("continue %d", state.pagecount);
1796 else if (!strncmp ("reqlayout", p, 9)) {
1797 char *nameddest;
1798 int rotate, off, h;
1799 unsigned int fitmodel;
1800 pdf_document *pdf;
1802 printd ("clear");
1803 ret = sscanf (p + 9, " %d %u %d %n",
1804 &rotate, &fitmodel, &h, &off);
1805 if (ret != 3) {
1806 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1808 lock ("reqlayout");
1809 pdf = pdf_specifics (state.ctx, state.doc);
1810 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1811 state.gen += 1;
1813 state.rotate = rotate;
1814 state.fitmodel = fitmodel;
1815 state.h = h;
1816 layout ();
1817 process_outline ();
1819 nameddest = p + 9 + off;
1820 if (pdf && nameddest && *nameddest) {
1821 fz_point xy;
1822 struct pagedim *pdim;
1823 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1824 &xy.x, &xy.y);
1825 pdim = pdimofpageno (pageno);
1826 fz_transform_point (&xy, &pdim->ctm);
1827 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1830 state.gen++;
1831 unlock ("reqlayout");
1832 printd ("continue %d", state.pagecount);
1834 else if (!strncmp ("page", p, 4)) {
1835 double a, b;
1836 struct page *page;
1837 int pageno, pindex;
1839 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1840 if (ret != 2) {
1841 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1844 lock ("page");
1845 a = now ();
1846 page = loadpage (pageno, pindex);
1847 b = now ();
1848 unlock ("page");
1850 printd ("page %" FMT_ptr " %f", FMT_ptr_cast (page), b - a);
1852 else if (!strncmp ("tile", p, 4)) {
1853 int x, y, w, h;
1854 struct page *page;
1855 struct tile *tile;
1856 double a, b;
1857 void *data;
1859 ret = sscanf (p + 4, " %" SCN_ptr " %d %d %d %d %" SCN_ptr,
1860 SCN_ptr_cast (&page), &x, &y, &w, &h,
1861 SCN_ptr_cast (&data));
1862 if (ret != 6) {
1863 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1866 lock ("tile");
1867 a = now ();
1868 tile = rendertile (page, x, y, w, h, data);
1869 b = now ();
1870 unlock ("tile");
1872 printd ("tile %d %d %" FMT_ptr " %u %f",
1873 x, y,
1874 FMT_ptr_cast (tile),
1875 tile->w * tile->h * tile->pixmap->n,
1876 b - a);
1878 else if (!strncmp ("trimset", p, 7)) {
1879 fz_irect fuzz;
1880 int trimmargins;
1882 ret = sscanf (p + 7, " %d %d %d %d %d",
1883 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1884 if (ret != 5) {
1885 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1887 lock ("trimset");
1888 state.trimmargins = trimmargins;
1889 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1890 state.trimanew = 1;
1891 state.trimfuzz = fuzz;
1893 unlock ("trimset");
1895 else if (!strncmp ("settrim", p, 7)) {
1896 fz_irect fuzz;
1897 int trimmargins;
1899 ret = sscanf (p + 7, " %d %d %d %d %d",
1900 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1901 if (ret != 5) {
1902 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1904 printd ("clear");
1905 lock ("settrim");
1906 state.trimmargins = trimmargins;
1907 state.needoutline = 1;
1908 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1909 state.trimanew = 1;
1910 state.trimfuzz = fuzz;
1912 state.pagedimcount = 0;
1913 free (state.pagedims);
1914 state.pagedims = NULL;
1915 initpdims (0);
1916 layout ();
1917 process_outline ();
1918 unlock ("settrim");
1919 printd ("continue %d", state.pagecount);
1921 else if (!strncmp ("sliceh", p, 6)) {
1922 int h;
1924 ret = sscanf (p + 6, " %d", &h);
1925 if (ret != 1) {
1926 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1928 if (h != state.sliceheight) {
1929 state.sliceheight = h;
1930 for (int i = 0; i < state.texcount; ++i) {
1931 state.texowners[i].w = -1;
1932 state.texowners[i].h = -1;
1933 state.texowners[i].slice = NULL;
1937 else if (!strncmp ("interrupt", p, 9)) {
1938 printd ("vmsg interrupted");
1940 else {
1941 errx (1, "unknown command %.*s", len, p);
1944 return 0;
1947 CAMLprim value ml_isexternallink (value uri_v)
1949 CAMLparam1 (uri_v);
1950 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1951 CAMLreturn (Val_bool (ext));
1954 CAMLprim value ml_uritolocation (value uri_v)
1956 CAMLparam1 (uri_v);
1957 CAMLlocal1 (ret_v);
1958 int pageno;
1959 fz_point xy;
1960 struct pagedim *pdim;
1962 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1963 &xy.x, &xy.y);
1964 pdim = pdimofpageno (pageno);
1965 fz_transform_point (&xy, &pdim->ctm);
1966 ret_v = caml_alloc_tuple (3);
1967 Field (ret_v, 0) = Val_int (pageno);
1968 Field (ret_v, 1) = caml_copy_double (xy.x);
1969 Field (ret_v, 2) = caml_copy_double (xy.y);
1970 CAMLreturn (ret_v);
1973 CAMLprim value ml_realloctexts (value texcount_v)
1975 CAMLparam1 (texcount_v);
1976 int ok;
1978 if (trylock (__func__)) {
1979 ok = 0;
1980 goto done;
1982 realloctexts (Int_val (texcount_v));
1983 ok = 1;
1984 unlock (__func__);
1986 done:
1987 CAMLreturn (Val_bool (ok));
1990 static void recti (int x0, int y0, int x1, int y1)
1992 GLfloat *v = state.vertices;
1994 glVertexPointer (2, GL_FLOAT, 0, v);
1995 v[0] = x0; v[1] = y0;
1996 v[2] = x1; v[3] = y0;
1997 v[4] = x0; v[5] = y1;
1998 v[6] = x1; v[7] = y1;
1999 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2002 static void showsel (struct page *page, int ox, int oy)
2004 int seen = 0;
2005 fz_irect bbox;
2006 fz_rect rect;
2007 fz_stext_line *line;
2008 fz_page_block *pageb;
2009 fz_stext_block *block;
2010 struct mark first, last;
2011 unsigned char selcolor[] = {15,15,15,140};
2013 first = page->fmark;
2014 last = page->lmark;
2016 if (!first.span || !last.span) return;
2018 glEnable (GL_BLEND);
2019 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
2020 glColor4ubv (selcolor);
2022 ox += state.pagedims[page->pdimno].bounds.x0;
2023 oy += state.pagedims[page->pdimno].bounds.y0;
2024 for (pageb = page->text->blocks;
2025 pageb < page->text->blocks + page->text->len;
2026 ++pageb) {
2027 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
2028 block = pageb->u.text;
2030 for (line = block->lines;
2031 line < block->lines + block->len;
2032 ++line) {
2033 fz_stext_span *span;
2034 rect = fz_empty_rect;
2036 for (span = line->first_span; span; span = span->next) {
2037 int i, j, k;
2038 bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0;
2040 j = 0;
2041 k = span->len - 1;
2043 if (span == page->fmark.span && span == page->lmark.span) {
2044 seen = 1;
2045 j = fz_mini (first.i, last.i);
2046 k = fz_maxi (first.i, last.i);
2048 else {
2049 if (span == first.span) {
2050 seen = 1;
2051 j = first.i;
2053 else if (span == last.span) {
2054 seen = 1;
2055 k = last.i;
2059 if (seen) {
2060 for (i = j; i <= k; ++i) {
2061 fz_rect bbox1;
2062 fz_union_rect (&rect,
2063 fz_stext_char_bbox (state.ctx, &bbox1,
2064 span, i));
2066 fz_round_rect (&bbox, &rect);
2067 lprintf ("%d %d %d %d oy=%d ox=%d\n",
2068 bbox.x0,
2069 bbox.y0,
2070 bbox.x1,
2071 bbox.y1,
2072 oy, ox);
2074 recti (bbox.x0 + ox, bbox.y0 + oy,
2075 bbox.x1 + ox, bbox.y1 + oy);
2076 if (span == last.span) {
2077 goto done;
2079 rect = fz_empty_rect;
2084 done:
2085 glDisable (GL_BLEND);
2088 #include "glfont.c"
2090 static void stipplerect (fz_matrix *m,
2091 fz_point *p1,
2092 fz_point *p2,
2093 fz_point *p3,
2094 fz_point *p4,
2095 GLfloat *texcoords,
2096 GLfloat *vertices)
2098 fz_transform_point (p1, m);
2099 fz_transform_point (p2, m);
2100 fz_transform_point (p3, m);
2101 fz_transform_point (p4, m);
2103 float w, h, s, t;
2105 w = p2->x - p1->x;
2106 h = p2->y - p1->y;
2107 t = hypotf (w, h) * .25f;
2109 w = p3->x - p2->x;
2110 h = p3->y - p2->y;
2111 s = hypotf (w, h) * .25f;
2113 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
2114 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
2116 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
2117 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
2119 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
2120 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
2122 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
2123 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
2125 glDrawArrays (GL_LINES, 0, 8);
2128 static void solidrect (fz_matrix *m,
2129 fz_point *p1,
2130 fz_point *p2,
2131 fz_point *p3,
2132 fz_point *p4,
2133 GLfloat *vertices)
2135 fz_transform_point (p1, m);
2136 fz_transform_point (p2, m);
2137 fz_transform_point (p3, m);
2138 fz_transform_point (p4, m);
2139 vertices[0] = p1->x; vertices[1] = p1->y;
2140 vertices[2] = p2->x; vertices[3] = p2->y;
2142 vertices[4] = p3->x; vertices[5] = p3->y;
2143 vertices[6] = p4->x; vertices[7] = p4->y;
2144 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
2147 static void highlightlinks (struct page *page, int xoff, int yoff)
2149 fz_matrix ctm, tm, pm;
2150 fz_link *link, *links;
2151 GLfloat *texcoords = state.texcoords;
2152 GLfloat *vertices = state.vertices;
2154 links = fz_load_links (state.ctx, page->fzpage);
2156 glEnable (GL_TEXTURE_1D);
2157 glEnable (GL_BLEND);
2158 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2159 glBindTexture (GL_TEXTURE_1D, state.stid);
2161 xoff -= state.pagedims[page->pdimno].bounds.x0;
2162 yoff -= state.pagedims[page->pdimno].bounds.y0;
2163 fz_translate (&tm, xoff, yoff);
2164 pm = pagectm (page);
2165 fz_concat (&ctm, &pm, &tm);
2167 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
2168 glVertexPointer (2, GL_FLOAT, 0, vertices);
2170 for (link = links; link; link = link->next) {
2171 fz_point p1, p2, p3, p4;
2173 p1.x = link->rect.x0;
2174 p1.y = link->rect.y0;
2176 p2.x = link->rect.x1;
2177 p2.y = link->rect.y0;
2179 p3.x = link->rect.x1;
2180 p3.y = link->rect.y1;
2182 p4.x = link->rect.x0;
2183 p4.y = link->rect.y1;
2185 /* TODO: different colours for different schemes */
2186 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
2187 else glColor3ub (255, 0, 0);
2189 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2192 for (int i = 0; i < page->annotcount; ++i) {
2193 fz_point p1, p2, p3, p4;
2194 struct annot *annot = &page->annots[i];
2196 p1.x = annot->bbox.x0;
2197 p1.y = annot->bbox.y0;
2199 p2.x = annot->bbox.x1;
2200 p2.y = annot->bbox.y0;
2202 p3.x = annot->bbox.x1;
2203 p3.y = annot->bbox.y1;
2205 p4.x = annot->bbox.x0;
2206 p4.y = annot->bbox.y1;
2208 glColor3ub (0, 0, 128);
2209 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
2212 glDisable (GL_BLEND);
2213 glDisable (GL_TEXTURE_1D);
2216 static int compareslinks (const void *l, const void *r)
2218 struct slink const *ls = l;
2219 struct slink const *rs = r;
2220 if (ls->bbox.y0 == rs->bbox.y0) {
2221 return rs->bbox.x0 - rs->bbox.x0;
2223 return ls->bbox.y0 - rs->bbox.y0;
2226 static void droptext (struct page *page)
2228 if (page->text) {
2229 fz_drop_stext_page (state.ctx, page->text);
2230 page->fmark.i = -1;
2231 page->lmark.i = -1;
2232 page->fmark.span = NULL;
2233 page->lmark.span = NULL;
2234 page->text = NULL;
2236 if (page->sheet) {
2237 fz_drop_stext_sheet (state.ctx, page->sheet);
2238 page->sheet = NULL;
2242 static void dropannots (struct page *page)
2244 if (page->annots) {
2245 free (page->annots);
2246 page->annots = NULL;
2247 page->annotcount = 0;
2251 static void ensureannots (struct page *page)
2253 int i, count = 0;
2254 size_t annotsize = sizeof (*page->annots);
2255 fz_annot *annot;
2257 if (state.gen != page->agen) {
2258 dropannots (page);
2259 page->agen = state.gen;
2261 if (page->annots) return;
2263 for (annot = fz_first_annot (state.ctx, page->fzpage);
2264 annot;
2265 annot = fz_next_annot (state.ctx, annot)) {
2266 count++;
2269 if (count > 0) {
2270 page->annotcount = count;
2271 page->annots = calloc (count, annotsize);
2272 if (!page->annots) {
2273 err (1, "calloc annots %d", count);
2276 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2277 annot;
2278 annot = fz_next_annot (state.ctx, annot), i++) {
2279 fz_rect rect;
2281 fz_bound_annot (state.ctx, annot, &rect);
2282 page->annots[i].annot = annot;
2283 fz_round_rect (&page->annots[i].bbox, &rect);
2288 static void dropslinks (struct page *page)
2290 if (page->slinks) {
2291 free (page->slinks);
2292 page->slinks = NULL;
2293 page->slinkcount = 0;
2297 static void ensureslinks (struct page *page)
2299 fz_matrix ctm;
2300 int i, count;
2301 size_t slinksize = sizeof (*page->slinks);
2302 fz_link *link, *links;
2304 ensureannots (page);
2305 if (state.gen != page->sgen) {
2306 dropslinks (page);
2307 page->sgen = state.gen;
2309 if (page->slinks) return;
2311 links = fz_load_links (state.ctx, page->fzpage);
2312 ctm = pagectm (page);
2314 count = page->annotcount;
2315 for (link = links; link; link = link->next) {
2316 count++;
2318 if (count > 0) {
2319 int j;
2321 page->slinkcount = count;
2322 page->slinks = calloc (count, slinksize);
2323 if (!page->slinks) {
2324 err (1, "calloc slinks %d", count);
2327 for (i = 0, link = links; link; ++i, link = link->next) {
2328 fz_rect rect;
2330 rect = link->rect;
2331 fz_transform_rect (&rect, &ctm);
2332 page->slinks[i].tag = SLINK;
2333 page->slinks[i].u.link = link;
2334 fz_round_rect (&page->slinks[i].bbox, &rect);
2336 for (j = 0; j < page->annotcount; ++j, ++i) {
2337 fz_rect rect;
2338 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2339 fz_transform_rect (&rect, &ctm);
2340 fz_round_rect (&page->slinks[i].bbox, &rect);
2342 page->slinks[i].tag = SANNOT;
2343 page->slinks[i].u.annot = page->annots[j].annot;
2345 qsort (page->slinks, count, slinksize, compareslinks);
2349 /* slightly tweaked fmt_ulong by D.J. Bernstein */
2350 static void fmt_linkn (char *s, unsigned int u)
2352 unsigned int len; unsigned int q;
2353 unsigned int zma = 'z' - 'a' + 1;
2354 len = 1; q = u;
2355 while (q > zma - 1) { ++len; q /= zma; }
2356 if (s) {
2357 s += len;
2358 do { *--s = 'a' + (u % zma) - (u < zma && len > 1); u /= zma; } while(u);
2359 /* handles u == 0 */
2361 s[len] = 0;
2364 static void highlightslinks (struct page *page, int xoff, int yoff,
2365 int noff, char *targ, int tlen, int hfsize)
2367 char buf[40];
2368 struct slink *slink;
2369 double x0, y0, x1, y1, w;
2371 ensureslinks (page);
2372 glColor3ub (0xc3, 0xb0, 0x91);
2373 for (int i = 0; i < page->slinkcount; ++i) {
2374 fmt_linkn (buf, i + noff);
2375 if (!tlen || !strncmp (targ, buf, tlen)) {
2376 slink = &page->slinks[i];
2378 x0 = slink->bbox.x0 + xoff - 5;
2379 y1 = slink->bbox.y0 + yoff - 5;
2380 y0 = y1 + 10 + hfsize;
2381 w = measure_string (state.face, hfsize, buf);
2382 x1 = x0 + w + 10;
2383 recti (x0, y0, x1, y1);
2387 glEnable (GL_BLEND);
2388 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2389 glEnable (GL_TEXTURE_2D);
2390 glColor3ub (0, 0, 0);
2391 for (int i = 0; i < page->slinkcount; ++i) {
2392 fmt_linkn (buf, i + noff);
2393 if (!tlen || !strncmp (targ, buf, tlen)) {
2394 slink = &page->slinks[i];
2396 x0 = slink->bbox.x0 + xoff;
2397 y0 = slink->bbox.y0 + yoff + hfsize;
2398 draw_string (state.face, hfsize, x0, y0, buf);
2401 glDisable (GL_TEXTURE_2D);
2402 glDisable (GL_BLEND);
2405 static void uploadslice (struct tile *tile, struct slice *slice)
2407 int offset;
2408 struct slice *slice1;
2409 unsigned char *texdata;
2411 offset = 0;
2412 for (slice1 = tile->slices; slice != slice1; slice1++) {
2413 offset += slice1->h * tile->w * tile->pixmap->n;
2415 if (slice->texindex != -1 && slice->texindex < state.texcount
2416 && state.texowners[slice->texindex].slice == slice) {
2417 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2419 else {
2420 int subimage = 0;
2421 int texindex = state.texindex++ % state.texcount;
2423 if (state.texowners[texindex].w == tile->w) {
2424 if (state.texowners[texindex].h >= slice->h) {
2425 subimage = 1;
2427 else {
2428 state.texowners[texindex].h = slice->h;
2431 else {
2432 state.texowners[texindex].h = slice->h;
2435 state.texowners[texindex].w = tile->w;
2436 state.texowners[texindex].slice = slice;
2437 slice->texindex = texindex;
2439 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2440 #if TEXT_TYPE == GL_TEXTURE_2D
2441 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2442 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2443 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2444 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2445 #endif
2446 if (tile->pbo) {
2447 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2448 texdata = 0;
2450 else {
2451 texdata = tile->pixmap->samples;
2453 if (subimage) {
2454 glTexSubImage2D (TEXT_TYPE,
2458 tile->w,
2459 slice->h,
2460 state.texform,
2461 state.texty,
2462 texdata+offset
2465 else {
2466 glTexImage2D (TEXT_TYPE,
2468 state.texiform,
2469 tile->w,
2470 slice->h,
2472 state.texform,
2473 state.texty,
2474 texdata+offset
2477 if (tile->pbo) {
2478 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2483 CAMLprim value ml_begintiles (value unit_v)
2485 CAMLparam1 (unit_v);
2486 glEnable (TEXT_TYPE);
2487 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2488 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2489 CAMLreturn (unit_v);
2492 CAMLprim value ml_endtiles (value unit_v)
2494 CAMLparam1 (unit_v);
2495 glDisable (TEXT_TYPE);
2496 CAMLreturn (unit_v);
2499 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2501 CAMLparam2 (args_v, ptr_v);
2502 int dispx = Int_val (Field (args_v, 0));
2503 int dispy = Int_val (Field (args_v, 1));
2504 int dispw = Int_val (Field (args_v, 2));
2505 int disph = Int_val (Field (args_v, 3));
2506 int tilex = Int_val (Field (args_v, 4));
2507 int tiley = Int_val (Field (args_v, 5));
2508 char *s = String_val (ptr_v);
2509 struct tile *tile = parse_pointer (__func__, s);
2510 int slicey, firstslice;
2511 struct slice *slice;
2512 GLfloat *texcoords = state.texcoords;
2513 GLfloat *vertices = state.vertices;
2515 firstslice = tiley / tile->sliceheight;
2516 slice = &tile->slices[firstslice];
2517 slicey = tiley % tile->sliceheight;
2519 while (disph > 0) {
2520 int dh;
2522 dh = slice->h - slicey;
2523 dh = fz_mini (disph, dh);
2524 uploadslice (tile, slice);
2526 texcoords[0] = tilex; texcoords[1] = slicey;
2527 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2528 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2529 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2531 vertices[0] = dispx; vertices[1] = dispy;
2532 vertices[2] = dispx+dispw; vertices[3] = dispy;
2533 vertices[4] = dispx; vertices[5] = dispy+dh;
2534 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2536 #if TEXT_TYPE == GL_TEXTURE_2D
2537 for (int i = 0; i < 8; ++i) {
2538 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2540 #endif
2542 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2543 dispy += dh;
2544 disph -= dh;
2545 slice++;
2546 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2547 slicey = 0;
2549 CAMLreturn0;
2552 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2554 fz_matrix ctm, tm, pm;
2555 fz_point p1, p2, p3, p4;
2556 GLfloat *vertices = state.vertices;
2557 double *v = (double *) rects_v;
2559 xoff -= state.pagedims[page->pdimno].bounds.x0;
2560 yoff -= state.pagedims[page->pdimno].bounds.y0;
2561 fz_translate (&tm, xoff, yoff);
2562 pm = pagectm (page);
2563 fz_concat (&ctm, &pm, &tm);
2565 glEnable (GL_BLEND);
2566 glVertexPointer (2, GL_FLOAT, 0, vertices);
2568 glColor4dv (v);
2569 p1.x = v[4];
2570 p1.y = v[5];
2572 p2.x = v[6];
2573 p2.y = v[5];
2575 p3.x = v[6];
2576 p3.y = v[7];
2578 p4.x = v[4];
2579 p4.y = v[7];
2580 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2581 glDisable (GL_BLEND);
2584 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2585 value xoff_v, value yoff_v,
2586 value li_v)
2588 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2589 int xoff = Int_val (xoff_v);
2590 int yoff = Int_val (yoff_v);
2591 int noff = Int_val (Field (li_v, 0));
2592 char *targ = String_val (Field (li_v, 1));
2593 int tlen = caml_string_length (Field (li_v, 1));
2594 int hfsize = Int_val (Field (li_v, 2));
2595 char *s = String_val (ptr_v);
2596 int hlmask = Int_val (hlinks_v);
2597 struct page *page = parse_pointer (__func__, s);
2599 if (!page->fzpage) {
2600 /* deal with loadpage failed pages */
2601 goto done;
2604 if (trylock (__func__)) {
2605 noff = -1;
2606 goto done;
2609 ensureannots (page);
2610 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2611 if (hlmask & 2) {
2612 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2613 noff = page->slinkcount;
2615 if (page->tgen == state.gen) {
2616 showsel (page, xoff, yoff);
2618 unlock (__func__);
2620 done:
2621 CAMLreturn (Val_int (noff));
2624 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2625 value rects_v)
2627 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2628 int xoff = Int_val (xoff_v);
2629 int yoff = Int_val (yoff_v);
2630 char *s = String_val (ptr_v);
2631 struct page *page = parse_pointer (__func__, s);
2633 drawprect (page, xoff, yoff, rects_v);
2634 CAMLreturn0;
2637 static struct annot *getannot (struct page *page, int x, int y)
2639 fz_point p;
2640 fz_matrix ctm;
2641 const fz_matrix *tctm;
2642 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2644 if (!page->annots) return NULL;
2646 if (pdf) {
2647 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2648 tctm = &state.pagedims[page->pdimno].tctm;
2650 else {
2651 tctm = &fz_identity;
2654 p.x = x;
2655 p.y = y;
2657 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2658 fz_invert_matrix (&ctm, &ctm);
2659 fz_transform_point (&p, &ctm);
2661 if (pdf) {
2662 for (int i = 0; i < page->annotcount; ++i) {
2663 struct annot *a = &page->annots[i];
2664 fz_rect rect;
2666 fz_bound_annot (state.ctx, a->annot, &rect);
2667 if (p.x >= rect.x0 && p.x <= rect.x1) {
2668 if (p.y >= rect.y0 && p.y <= rect.y1)
2669 return a;
2673 return NULL;
2676 static fz_link *getlink (struct page *page, int x, int y)
2678 fz_point p;
2679 fz_matrix ctm;
2680 fz_link *link, *links;
2682 links = fz_load_links (state.ctx, page->fzpage);
2684 p.x = x;
2685 p.y = y;
2687 ctm = pagectm (page);
2688 fz_invert_matrix (&ctm, &ctm);
2689 fz_transform_point (&p, &ctm);
2691 for (link = links; link; link = link->next) {
2692 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2693 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2694 return link;
2698 return NULL;
2701 static void ensuretext (struct page *page)
2703 if (state.gen != page->tgen) {
2704 droptext (page);
2705 page->tgen = state.gen;
2707 if (!page->text) {
2708 fz_matrix ctm;
2709 fz_device *tdev;
2711 page->text = fz_new_stext_page (state.ctx,
2712 &state.pagedims[page->pdimno].mediabox);
2713 page->sheet = fz_new_stext_sheet (state.ctx);
2714 tdev = fz_new_stext_device (state.ctx, page->sheet, page->text, 0);
2715 ctm = pagectm (page);
2716 fz_run_display_list (state.ctx, page->dlist,
2717 tdev, &ctm, &fz_infinite_rect, NULL);
2718 qsort (page->text->blocks, page->text->len,
2719 sizeof (*page->text->blocks), compareblocks);
2720 fz_close_device (state.ctx, tdev);
2721 fz_drop_device (state.ctx, tdev);
2725 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2727 CAMLparam2 (start_page_v, dir_v);
2728 CAMLlocal1 (ret_v);
2729 int i, dir = Int_val (dir_v);
2730 int start_page = Int_val (start_page_v);
2731 int end_page = dir > 0 ? state.pagecount : -1;
2732 pdf_document *pdf;
2734 fz_var (end_page);
2735 ret_v = Val_int (0);
2736 lock (__func__);
2737 pdf = pdf_specifics (state.ctx, state.doc);
2738 for (i = start_page + dir; i != end_page; i += dir) {
2739 int found;
2741 fz_var (found);
2742 if (pdf) {
2743 pdf_page *page = NULL;
2745 fz_var (page);
2746 fz_try (state.ctx) {
2747 page = pdf_load_page (state.ctx, pdf, i);
2748 found = !!page->links || !!page->annots;
2750 fz_catch (state.ctx) {
2751 found = 0;
2753 if (page) {
2754 fz_drop_page (state.ctx, &page->super);
2757 else {
2758 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2759 found = !!fz_load_links (state.ctx, page);
2760 fz_drop_page (state.ctx, page);
2763 if (found) {
2764 ret_v = caml_alloc_small (1, 1);
2765 Field (ret_v, 0) = Val_int (i);
2766 goto unlock;
2769 unlock:
2770 unlock (__func__);
2771 CAMLreturn (ret_v);
2774 enum { dir_first, dir_last };
2775 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2777 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2779 CAMLparam2 (ptr_v, dir_v);
2780 CAMLlocal2 (ret_v, pos_v);
2781 struct page *page;
2782 int dirtag, i, slinkindex;
2783 struct slink *found = NULL ,*slink;
2784 char *s = String_val (ptr_v);
2786 page = parse_pointer (__func__, s);
2787 ret_v = Val_int (0);
2788 lock (__func__);
2789 ensureslinks (page);
2791 if (Is_block (dir_v)) {
2792 dirtag = Tag_val (dir_v);
2793 switch (dirtag) {
2794 case dir_first_visible:
2796 int x0, y0, dir, first_index, last_index;
2798 pos_v = Field (dir_v, 0);
2799 x0 = Int_val (Field (pos_v, 0));
2800 y0 = Int_val (Field (pos_v, 1));
2801 dir = Int_val (Field (pos_v, 2));
2803 if (dir >= 0) {
2804 dir = 1;
2805 first_index = 0;
2806 last_index = page->slinkcount;
2808 else {
2809 first_index = page->slinkcount - 1;
2810 last_index = -1;
2813 for (i = first_index; i != last_index; i += dir) {
2814 slink = &page->slinks[i];
2815 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2816 found = slink;
2817 break;
2821 break;
2823 case dir_left:
2824 slinkindex = Int_val (Field (dir_v, 0));
2825 found = &page->slinks[slinkindex];
2826 for (i = slinkindex - 1; i >= 0; --i) {
2827 slink = &page->slinks[i];
2828 if (slink->bbox.x0 < found->bbox.x0) {
2829 found = slink;
2830 break;
2833 break;
2835 case dir_right:
2836 slinkindex = Int_val (Field (dir_v, 0));
2837 found = &page->slinks[slinkindex];
2838 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2839 slink = &page->slinks[i];
2840 if (slink->bbox.x0 > found->bbox.x0) {
2841 found = slink;
2842 break;
2845 break;
2847 case dir_down:
2848 slinkindex = Int_val (Field (dir_v, 0));
2849 found = &page->slinks[slinkindex];
2850 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2851 slink = &page->slinks[i];
2852 if (slink->bbox.y0 >= found->bbox.y0) {
2853 found = slink;
2854 break;
2857 break;
2859 case dir_up:
2860 slinkindex = Int_val (Field (dir_v, 0));
2861 found = &page->slinks[slinkindex];
2862 for (i = slinkindex - 1; i >= 0; --i) {
2863 slink = &page->slinks[i];
2864 if (slink->bbox.y0 <= found->bbox.y0) {
2865 found = slink;
2866 break;
2869 break;
2872 else {
2873 dirtag = Int_val (dir_v);
2874 switch (dirtag) {
2875 case dir_first:
2876 found = page->slinks;
2877 break;
2879 case dir_last:
2880 if (page->slinks) {
2881 found = page->slinks + (page->slinkcount - 1);
2883 break;
2886 if (found) {
2887 ret_v = caml_alloc_small (2, 1);
2888 Field (ret_v, 0) = Val_int (found - page->slinks);
2891 unlock (__func__);
2892 CAMLreturn (ret_v);
2895 enum { uuri, utext, uannot };
2897 CAMLprim value ml_getlink (value ptr_v, value n_v)
2899 CAMLparam2 (ptr_v, n_v);
2900 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2901 fz_link *link;
2902 struct page *page;
2903 char *s = String_val (ptr_v);
2904 struct slink *slink;
2906 ret_v = Val_int (0);
2907 page = parse_pointer (__func__, s);
2909 lock (__func__);
2910 ensureslinks (page);
2911 slink = &page->slinks[Int_val (n_v)];
2912 if (slink->tag == SLINK) {
2913 link = slink->u.link;
2914 str_v = caml_copy_string (link->uri);
2915 ret_v = caml_alloc_small (1, uuri);
2916 Field (ret_v, 0) = str_v;
2918 else {
2919 ret_v = caml_alloc_small (1, uannot);
2920 tup_v = caml_alloc_tuple (2);
2921 Field (ret_v, 0) = tup_v;
2922 Field (tup_v, 0) = ptr_v;
2923 Field (tup_v, 1) = n_v;
2925 unlock (__func__);
2927 CAMLreturn (ret_v);
2930 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2932 CAMLparam2 (ptr_v, n_v);
2933 pdf_document *pdf;
2934 const char *contents = "";
2936 lock (__func__);
2937 pdf = pdf_specifics (state.ctx, state.doc);
2938 if (pdf) {
2939 char *s = String_val (ptr_v);
2940 struct page *page;
2941 struct slink *slink;
2943 page = parse_pointer (__func__, s);
2944 slink = &page->slinks[Int_val (n_v)];
2945 contents = pdf_annot_contents (state.ctx,
2946 (pdf_annot *) slink->u.annot);
2948 unlock (__func__);
2949 CAMLreturn (caml_copy_string (contents));
2952 CAMLprim value ml_getlinkcount (value ptr_v)
2954 CAMLparam1 (ptr_v);
2955 struct page *page;
2956 char *s = String_val (ptr_v);
2958 page = parse_pointer (__func__, s);
2959 CAMLreturn (Val_int (page->slinkcount));
2962 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2964 CAMLparam2 (ptr_v, n_v);
2965 CAMLlocal1 (ret_v);
2966 struct page *page;
2967 struct slink *slink;
2968 char *s = String_val (ptr_v);
2970 page = parse_pointer (__func__, s);
2971 ret_v = caml_alloc_tuple (4);
2972 lock (__func__);
2973 ensureslinks (page);
2975 slink = &page->slinks[Int_val (n_v)];
2976 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2977 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2978 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2979 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2980 unlock (__func__);
2981 CAMLreturn (ret_v);
2984 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2986 CAMLparam3 (ptr_v, x_v, y_v);
2987 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2988 fz_link *link;
2989 struct annot *annot;
2990 struct page *page;
2991 char *ptr = String_val (ptr_v);
2992 int x = Int_val (x_v), y = Int_val (y_v);
2993 struct pagedim *pdim;
2995 ret_v = Val_int (0);
2996 if (trylock (__func__)) {
2997 goto done;
3000 page = parse_pointer (__func__, ptr);
3001 pdim = &state.pagedims[page->pdimno];
3002 x += pdim->bounds.x0;
3003 y += pdim->bounds.y0;
3006 annot = getannot (page, x, y);
3007 if (annot) {
3008 int i, n = -1;
3010 ensureslinks (page);
3011 for (i = 0; i < page->slinkcount; ++i) {
3012 if (page->slinks[i].tag == SANNOT
3013 && page->slinks[i].u.annot == annot->annot) {
3014 n = i;
3015 break;
3018 ret_v = caml_alloc_small (1, uannot);
3019 tup_v = caml_alloc_tuple (2);
3020 Field (ret_v, 0) = tup_v;
3021 Field (tup_v, 0) = ptr_v;
3022 Field (tup_v, 1) = Val_int (n);
3023 goto unlock;
3027 link = getlink (page, x, y);
3028 if (link) {
3029 str_v = caml_copy_string (link->uri);
3030 ret_v = caml_alloc_small (1, uuri);
3031 Field (ret_v, 0) = str_v;
3033 else {
3034 fz_rect *b;
3035 fz_page_block *pageb;
3036 fz_stext_block *block;
3038 ensuretext (page);
3039 for (pageb = page->text->blocks;
3040 pageb < page->text->blocks + page->text->len;
3041 ++pageb) {
3042 fz_stext_line *line;
3043 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3044 block = pageb->u.text;
3046 b = &block->bbox;
3047 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3048 continue;
3050 for (line = block->lines;
3051 line < block->lines + block->len;
3052 ++line) {
3053 fz_stext_span *span;
3055 b = &line->bbox;
3056 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3057 continue;
3059 for (span = line->first_span; span; span = span->next) {
3060 int charnum;
3062 b = &span->bbox;
3063 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3064 continue;
3066 for (charnum = 0; charnum < span->len; ++charnum) {
3067 fz_rect bbox;
3068 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3069 b = &bbox;
3071 if (x >= b->x0 && x <= b->x1
3072 && y >= b->y0 && y <= b->y1) {
3073 fz_stext_style *style = span->text->style;
3074 const char *n2 =
3075 style->font
3076 ? fz_font_name (state.ctx, style->font)
3077 : "Span has no font name"
3079 FT_FaceRec *face = fz_font_ft_face (state.ctx,
3080 style->font);
3081 if (face && face->family_name) {
3082 char *s;
3083 char *n1 = face->family_name;
3084 size_t l1 = strlen (n1);
3085 size_t l2 = strlen (n2);
3087 if (l1 != l2 || memcmp (n1, n2, l1)) {
3088 s = malloc (l1 + l2 + 2);
3089 if (s) {
3090 memcpy (s, n2, l2);
3091 s[l2] = '=';
3092 memcpy (s + l2 + 1, n1, l1 + 1);
3093 str_v = caml_copy_string (s);
3094 free (s);
3098 if (str_v == Val_unit) {
3099 str_v = caml_copy_string (n2);
3101 ret_v = caml_alloc_small (1, utext);
3102 Field (ret_v, 0) = str_v;
3103 goto unlock;
3110 unlock:
3111 unlock (__func__);
3113 done:
3114 CAMLreturn (ret_v);
3117 enum { mark_page, mark_block, mark_line, mark_word };
3119 static int uninteresting (int c)
3121 return c == ' ' || c == '\n' || c == '\t' || c == '\n' || c == '\r'
3122 || ispunct (c);
3125 CAMLprim void ml_clearmark (value ptr_v)
3127 CAMLparam1 (ptr_v);
3128 char *s = String_val (ptr_v);
3129 struct page *page;
3131 if (trylock (__func__)) {
3132 goto done;
3135 page = parse_pointer (__func__, s);
3136 page->fmark.span = NULL;
3137 page->lmark.span = NULL;
3138 page->fmark.i = 0;
3139 page->lmark.i = 0;
3141 unlock (__func__);
3142 done:
3143 CAMLreturn0;
3146 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
3148 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
3149 CAMLlocal1 (ret_v);
3150 fz_rect *b;
3151 struct page *page;
3152 fz_stext_line *line;
3153 fz_page_block *pageb;
3154 fz_stext_block *block;
3155 struct pagedim *pdim;
3156 int mark = Int_val (mark_v);
3157 char *s = String_val (ptr_v);
3158 int x = Int_val (x_v), y = Int_val (y_v);
3160 ret_v = Val_bool (0);
3161 if (trylock (__func__)) {
3162 goto done;
3165 page = parse_pointer (__func__, s);
3166 pdim = &state.pagedims[page->pdimno];
3168 ensuretext (page);
3170 if (mark == mark_page) {
3171 int i;
3172 fz_page_block *pb1 = NULL, *pb2 = NULL;
3174 for (i = 0; i < page->text->len; ++i) {
3175 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3176 pb1 = &page->text->blocks[i];
3177 break;
3180 if (!pb1) goto unlock;
3182 for (i = page->text->len - 1; i >= 0; --i) {
3183 if (page->text->blocks[i].type == FZ_PAGE_BLOCK_TEXT) {
3184 pb2 = &page->text->blocks[i];
3185 break;
3188 if (!pb2) goto unlock;
3190 block = pb1->u.text;
3192 page->fmark.i = 0;
3193 page->fmark.span = block->lines->first_span;
3195 block = pb2->u.text;
3196 line = &block->lines[block->len - 1];
3197 page->lmark.i = line->last_span->len - 1;
3198 page->lmark.span = line->last_span;
3199 ret_v = Val_bool (1);
3200 goto unlock;
3203 x += pdim->bounds.x0;
3204 y += pdim->bounds.y0;
3206 for (pageb = page->text->blocks;
3207 pageb < page->text->blocks + page->text->len;
3208 ++pageb) {
3209 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3210 block = pageb->u.text;
3212 b = &block->bbox;
3213 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3214 continue;
3216 if (mark == mark_block) {
3217 page->fmark.i = 0;
3218 page->fmark.span = block->lines->first_span;
3220 line = &block->lines[block->len - 1];
3221 page->lmark.i = line->last_span->len - 1;
3222 page->lmark.span = line->last_span;
3223 ret_v = Val_bool (1);
3224 goto unlock;
3227 for (line = block->lines;
3228 line < block->lines + block->len;
3229 ++line) {
3230 fz_stext_span *span;
3232 b = &line->bbox;
3233 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3234 continue;
3236 if (mark == mark_line) {
3237 page->fmark.i = 0;
3238 page->fmark.span = line->first_span;
3240 page->lmark.i = line->last_span->len - 1;
3241 page->lmark.span = line->last_span;
3242 ret_v = Val_bool (1);
3243 goto unlock;
3246 for (span = line->first_span; span; span = span->next) {
3247 int charnum;
3249 b = &span->bbox;
3250 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
3251 continue;
3253 for (charnum = 0; charnum < span->len; ++charnum) {
3254 fz_rect bbox;
3255 fz_stext_char_bbox (state.ctx, &bbox, span, charnum);
3256 b = &bbox;
3258 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1) {
3259 /* unicode ftw */
3260 int charnum2, charnum3 = -1, charnum4 = -1;
3262 if (uninteresting (span->text[charnum].c)) goto unlock;
3264 for (charnum2 = charnum; charnum2 >= 0; --charnum2) {
3265 if (uninteresting (span->text[charnum2].c)) {
3266 charnum3 = charnum2 + 1;
3267 break;
3270 if (charnum3 == -1) charnum3 = 0;
3272 charnum4 = charnum;
3273 for (charnum2 = charnum + 1;
3274 charnum2 < span->len;
3275 ++charnum2) {
3276 if (uninteresting (span->text[charnum2].c)) break;
3277 charnum4 = charnum2;
3280 page->fmark.i = charnum3;
3281 page->fmark.span = span;
3283 page->lmark.i = charnum4;
3284 page->lmark.span = span;
3285 ret_v = Val_bool (1);
3286 goto unlock;
3292 unlock:
3293 if (!Bool_val (ret_v)) {
3294 page->fmark.span = NULL;
3295 page->lmark.span = NULL;
3296 page->fmark.i = 0;
3297 page->lmark.i = 0;
3299 unlock (__func__);
3301 done:
3302 CAMLreturn (ret_v);
3305 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
3307 CAMLparam3 (ptr_v, x_v, y_v);
3308 CAMLlocal2 (ret_v, res_v);
3309 fz_rect *b = NULL;
3310 struct page *page;
3311 fz_page_block *pageb;
3312 struct pagedim *pdim;
3313 char *s = String_val (ptr_v);
3314 int x = Int_val (x_v), y = Int_val (y_v);
3316 ret_v = Val_int (0);
3317 if (trylock (__func__)) {
3318 goto done;
3321 page = parse_pointer (__func__, s);
3322 pdim = &state.pagedims[page->pdimno];
3323 x += pdim->bounds.x0;
3324 y += pdim->bounds.y0;
3326 ensuretext (page);
3328 for (pageb = page->text->blocks;
3329 pageb < page->text->blocks + page->text->len;
3330 ++pageb) {
3331 switch (pageb->type) {
3332 case FZ_PAGE_BLOCK_TEXT:
3333 b = &pageb->u.text->bbox;
3334 break;
3336 case FZ_PAGE_BLOCK_IMAGE:
3337 b = &pageb->u.image->bbox;
3338 break;
3340 default:
3341 continue;
3344 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3345 break;
3346 b = NULL;
3348 if (b) {
3349 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3350 ret_v = caml_alloc_small (1, 1);
3351 Store_double_field (res_v, 0, b->x0);
3352 Store_double_field (res_v, 1, b->x1);
3353 Store_double_field (res_v, 2, b->y0);
3354 Store_double_field (res_v, 3, b->y1);
3355 Field (ret_v, 0) = res_v;
3357 unlock (__func__);
3359 done:
3360 CAMLreturn (ret_v);
3363 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3365 CAMLparam2 (ptr_v, rect_v);
3366 fz_rect b;
3367 struct page *page;
3368 struct pagedim *pdim;
3369 char *s = String_val (ptr_v);
3370 int i, x0, x1, y0, y1, fi, li;
3371 fz_stext_line *line;
3372 fz_page_block *pageb;
3373 fz_stext_block *block;
3374 fz_stext_span *span, *fspan, *lspan;
3376 if (trylock (__func__)) {
3377 goto done;
3380 page = parse_pointer (__func__, s);
3381 ensuretext (page);
3383 pdim = &state.pagedims[page->pdimno];
3384 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3385 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3386 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3387 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3389 if (y0 > y1) {
3390 int t = y0;
3391 y0 = y1;
3392 y1 = t;
3393 x0 = x1;
3394 x1 = t;
3397 fi = page->fmark.i;
3398 fspan = page->fmark.span;
3400 li = page->lmark.i;
3401 lspan = page->lmark.span;
3403 for (pageb = page->text->blocks;
3404 pageb < page->text->blocks + page->text->len;
3405 ++pageb) {
3406 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3407 block = pageb->u.text;
3408 for (line = block->lines;
3409 line < block->lines + block->len;
3410 ++line) {
3412 for (span = line->first_span; span; span = span->next) {
3413 for (i = 0; i < span->len; ++i) {
3414 fz_stext_char_bbox (state.ctx, &b, span, i);
3416 if (x0 >= b.x0 && x0 <= b.x1
3417 && y0 >= b.y0 && y0 <= b.y1) {
3418 fspan = span;
3419 fi = i;
3421 if (x1 >= b.x0 && x1 <= b.x1
3422 && y1 >= b.y0 && y1 <= b.y1) {
3423 lspan = span;
3424 li = i;
3430 if (x1 < x0 && fspan == lspan) {
3431 i = fi;
3432 span = fspan;
3434 fi = li;
3435 fspan = lspan;
3437 li = i;
3438 lspan = span;
3441 page->fmark.i = fi;
3442 page->fmark.span = fspan;
3444 page->lmark.i = li;
3445 page->lmark.span = lspan;
3447 unlock (__func__);
3449 done:
3450 CAMLreturn0;
3453 static int UNUSED_ATTR pipespan (FILE *f, fz_stext_span *span, int a, int b)
3455 char buf[4];
3456 int i, len, ret;
3458 for (i = a; i <= b; ++i) {
3459 len = fz_runetochar (buf, span->text[i].c);
3460 ret = fwrite (buf, len, 1, f);
3462 if (ret != 1) {
3463 fprintf (stderr, "failed to write %d bytes ret=%d: %s\n",
3464 len, ret, strerror (errno));
3465 return -1;
3468 return 0;
3471 #ifdef __CYGWIN__
3472 CAMLprim value ml_spawn (value UNUSED_ATTR u1, value UNUSED_ATTR u2)
3474 caml_failwith ("ml_popen not implemented under Cygwin");
3476 #else
3477 CAMLprim value ml_spawn (value command_v, value fds_v)
3479 CAMLparam2 (command_v, fds_v);
3480 CAMLlocal2 (l_v, tup_v);
3481 int ret, ret1;
3482 pid_t pid;
3483 char *msg = NULL;
3484 value earg_v = Nothing;
3485 posix_spawnattr_t attr;
3486 posix_spawn_file_actions_t fa;
3487 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3489 argv[2] = String_val (command_v);
3491 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3492 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3495 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3496 msg = "posix_spawnattr_init";
3497 goto fail1;
3500 #ifdef POSIX_SPAWN_USEVFORK
3501 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3502 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3503 goto fail;
3505 #endif
3507 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3508 int fd1, fd2;
3510 tup_v = Field (l_v, 0);
3511 fd1 = Int_val (Field (tup_v, 0));
3512 fd2 = Int_val (Field (tup_v, 1));
3513 if (fd2 < 0) {
3514 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3515 msg = "posix_spawn_file_actions_addclose";
3516 earg_v = tup_v;
3517 goto fail;
3520 else {
3521 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3522 msg = "posix_spawn_file_actions_adddup2";
3523 earg_v = tup_v;
3524 goto fail;
3529 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3530 msg = "posix_spawn";
3531 goto fail;
3534 fail:
3535 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3536 fprintf (stderr, "posix_spawnattr_destroy: %s\n", strerror (ret1));
3539 fail1:
3540 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3541 fprintf (stderr, "posix_spawn_file_actions_destroy: %s\n",
3542 strerror (ret1));
3545 if (msg)
3546 unix_error (ret, msg, earg_v);
3548 CAMLreturn (Val_int (pid));
3550 #endif
3552 CAMLprim value ml_hassel (value ptr_v)
3554 CAMLparam1 (ptr_v);
3555 CAMLlocal1 (ret_v);
3556 struct page *page;
3557 char *s = String_val (ptr_v);
3559 ret_v = Val_bool (0);
3560 if (trylock (__func__)) {
3561 goto done;
3564 page = parse_pointer (__func__, s);
3565 ret_v = Val_bool (page->fmark.span && page->lmark.span);
3566 unlock (__func__);
3567 done:
3568 CAMLreturn (ret_v);
3571 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3573 CAMLparam2 (fd_v, ptr_v);
3574 FILE *f;
3575 int seen = 0;
3576 struct page *page;
3577 fz_stext_line *line;
3578 fz_page_block *pageb;
3579 fz_stext_block *block;
3580 int fd = Int_val (fd_v);
3581 char *s = String_val (ptr_v);
3583 if (trylock (__func__)) {
3584 goto done;
3587 page = parse_pointer (__func__, s);
3589 if (!page->fmark.span || !page->lmark.span) {
3590 fprintf (stderr, "nothing to copy on page %d\n", page->pageno);
3591 goto unlock;
3594 f = fdopen (fd, "w");
3595 if (!f) {
3596 fprintf (stderr, "failed to fdopen sel pipe (from fd %d): %s\n",
3597 fd, strerror (errno));
3598 f = stdout;
3601 for (pageb = page->text->blocks;
3602 pageb < page->text->blocks + page->text->len;
3603 ++pageb) {
3604 if (pageb->type != FZ_PAGE_BLOCK_TEXT) continue;
3605 block = pageb->u.text;
3606 for (line = block->lines;
3607 line < block->lines + block->len;
3608 ++line) {
3609 fz_stext_span *span;
3611 for (span = line->first_span; span; span = span->next) {
3612 int a, b;
3614 seen |= span == page->fmark.span || span == page->lmark.span;
3615 a = span == page->fmark.span ? page->fmark.i : 0;
3616 b = span == page->lmark.span ? page->lmark.i : span->len - 1;
3618 if (seen) {
3619 if (pipespan (f, span, a, b)) {
3620 goto close;
3622 if (span == page->lmark.span) {
3623 goto close;
3625 if (span == line->last_span) {
3626 if (putc ('\n', f) == EOF) {
3627 fprintf (stderr,
3628 "failed break line on sel pipe: %s\n",
3629 strerror (errno));
3630 goto close;
3637 close:
3638 if (f != stdout) {
3639 int ret = fclose (f);
3640 fd = -1;
3641 if (ret == -1) {
3642 if (errno != ECHILD) {
3643 fprintf (stderr, "failed to close sel pipe: %s\n",
3644 strerror (errno));
3648 unlock:
3649 unlock (__func__);
3651 done:
3652 if (fd >= 0) {
3653 if (close (fd)) {
3654 fprintf (stderr, "failed to close sel pipe: %s\n",
3655 strerror (errno));
3658 CAMLreturn0;
3661 CAMLprim value ml_getpdimrect (value pagedimno_v)
3663 CAMLparam1 (pagedimno_v);
3664 CAMLlocal1 (ret_v);
3665 int pagedimno = Int_val (pagedimno_v);
3666 fz_rect box;
3668 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3669 if (trylock (__func__)) {
3670 box = fz_empty_rect;
3672 else {
3673 box = state.pagedims[pagedimno].mediabox;
3674 unlock (__func__);
3677 Store_double_field (ret_v, 0, box.x0);
3678 Store_double_field (ret_v, 1, box.x1);
3679 Store_double_field (ret_v, 2, box.y0);
3680 Store_double_field (ret_v, 3, box.y1);
3682 CAMLreturn (ret_v);
3685 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3686 value dw_v, value cols_v)
3688 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3689 CAMLlocal1 (ret_v);
3690 int i;
3691 double zoom = -1.;
3692 double maxh = 0.0;
3693 struct pagedim *p;
3694 double winw = Int_val (winw_v);
3695 double winh = Int_val (winh_v);
3696 double dw = Int_val (dw_v);
3697 double cols = Int_val (cols_v);
3698 double pw = 1.0, ph = 1.0;
3700 if (trylock (__func__)) {
3701 goto done;
3704 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3705 double w = p->pagebox.x1 / cols;
3706 double h = p->pagebox.y1;
3707 if (h > maxh) {
3708 maxh = h;
3709 ph = h;
3710 if (state.fitmodel != FitProportional) pw = w;
3712 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3715 zoom = (((winh / ph) * pw) + dw) / winw;
3716 unlock (__func__);
3717 done:
3718 ret_v = caml_copy_double (zoom);
3719 CAMLreturn (ret_v);
3722 CAMLprim value ml_getmaxw (value unit_v)
3724 CAMLparam1 (unit_v);
3725 CAMLlocal1 (ret_v);
3726 int i;
3727 double maxw = -1.;
3728 struct pagedim *p;
3730 if (trylock (__func__)) {
3731 goto done;
3734 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3735 double w = p->pagebox.x1;
3736 maxw = fz_max (maxw, w);
3739 unlock (__func__);
3740 done:
3741 ret_v = caml_copy_double (maxw);
3742 CAMLreturn (ret_v);
3745 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3747 CAMLparam4 (pt_v, x_v, y_v, string_v);
3748 CAMLlocal1 (ret_v);
3749 int pt = Int_val(pt_v);
3750 int x = Int_val (x_v);
3751 int y = Int_val (y_v);
3752 double w;
3754 w = draw_string (state.face, pt, x, y, String_val (string_v));
3755 ret_v = caml_copy_double (w);
3756 CAMLreturn (ret_v);
3759 CAMLprim value ml_measure_string (value pt_v, value string_v)
3761 CAMLparam2 (pt_v, string_v);
3762 CAMLlocal1 (ret_v);
3763 int pt = Int_val (pt_v);
3764 double w;
3766 w = measure_string (state.face, pt, String_val (string_v));
3767 ret_v = caml_copy_double (w);
3768 CAMLreturn (ret_v);
3771 CAMLprim value ml_getpagebox (value opaque_v)
3773 CAMLparam1 (opaque_v);
3774 CAMLlocal1 (ret_v);
3775 fz_rect rect;
3776 fz_irect bbox;
3777 fz_matrix ctm;
3778 fz_device *dev;
3779 char *s = String_val (opaque_v);
3780 struct page *page = parse_pointer (__func__, s);
3782 ret_v = caml_alloc_tuple (4);
3783 dev = fz_new_bbox_device (state.ctx, &rect);
3784 dev->hints |= FZ_IGNORE_SHADE;
3786 ctm = pagectm (page);
3787 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3789 fz_close_device (state.ctx, dev);
3790 fz_drop_device (state.ctx, dev);
3791 fz_round_rect (&bbox, &rect);
3792 Field (ret_v, 0) = Val_int (bbox.x0);
3793 Field (ret_v, 1) = Val_int (bbox.y0);
3794 Field (ret_v, 2) = Val_int (bbox.x1);
3795 Field (ret_v, 3) = Val_int (bbox.y1);
3797 CAMLreturn (ret_v);
3800 CAMLprim void ml_setaalevel (value level_v)
3802 CAMLparam1 (level_v);
3804 state.aalevel = Int_val (level_v);
3805 CAMLreturn0;
3808 #pragma GCC diagnostic push
3809 #pragma GCC diagnostic ignored "-Wvariadic-macros"
3811 #ifndef __COCOA__
3812 #include <X11/Xlib.h>
3813 #include <X11/cursorfont.h>
3814 #pragma GCC diagnostic pop
3816 #ifdef USE_EGL
3817 #include <EGL/egl.h>
3818 #else
3819 #include <GL/glx.h>
3820 #endif
3822 static const int shapes[] = {
3823 XC_left_ptr, XC_hand2, XC_exchange, XC_fleur, XC_xterm
3826 #define CURS_COUNT (sizeof (shapes) / sizeof (shapes[0]))
3828 static struct {
3829 Window wid;
3830 Display *dpy;
3831 #ifdef USE_EGL
3832 EGLContext ctx;
3833 EGLConfig conf;
3834 EGLSurface win;
3835 EGLDisplay *edpy;
3836 #else
3837 GLXContext ctx;
3838 #endif
3839 XVisualInfo *visual;
3840 Cursor curs[CURS_COUNT];
3841 } glx;
3844 static void initcurs (void)
3846 for (size_t n = 0; n < CURS_COUNT; ++n) {
3847 glx.curs[n] = XCreateFontCursor (glx.dpy, shapes[n]);
3851 CAMLprim void ml_setbgcol (value color_v)
3853 CAMLparam1 (color_v);
3854 XSetWindowBackground (glx.dpy, glx.wid, Int_val (color_v));
3855 CAMLreturn0;
3858 #ifdef USE_EGL
3859 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3861 CAMLparam3 (display_v, wid_v, screen_v);
3862 int major, minor;
3863 int num_conf;
3864 EGLint visid;
3865 EGLint attribs[] = {
3866 EGL_DEPTH_SIZE, 24,
3867 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
3868 EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
3869 EGL_NONE
3871 EGLConfig conf;
3873 glx.dpy = XOpenDisplay (String_val (display_v));
3874 if (!glx.dpy) {
3875 caml_failwith ("XOpenDisplay");
3878 eglBindAPI (EGL_OPENGL_API);
3880 glx.edpy = eglGetDisplay (glx.dpy);
3881 if (glx.edpy == EGL_NO_DISPLAY) {
3882 caml_failwith ("eglGetDisplay");
3885 if (!eglInitialize (glx.edpy, &major, &minor)) {
3886 caml_failwith ("eglInitialize");
3889 if (!eglChooseConfig (glx.edpy, attribs, &conf, 1, &num_conf) ||
3890 !num_conf) {
3891 caml_failwith ("eglChooseConfig");
3894 if (!eglGetConfigAttrib (glx.edpy, conf, EGL_NATIVE_VISUAL_ID, &visid)) {
3895 caml_failwith ("eglGetConfigAttrib");
3898 glx.conf = conf;
3899 initcurs ();
3901 glx.wid = Int_val (wid_v);
3902 CAMLreturn (Val_int (visid));
3905 CAMLprim value ml_glxcompleteinit (value unit_v)
3907 CAMLparam1 (unit_v);
3909 glx.ctx = eglCreateContext (glx.edpy, glx.conf, EGL_NO_CONTEXT, NULL);
3910 if (!glx.ctx) {
3911 caml_failwith ("eglCreateContext");
3914 glx.win = eglCreateWindowSurface (glx.edpy, glx.conf,
3915 glx.wid, NULL);
3916 if (glx.win == EGL_NO_SURFACE) {
3917 caml_failwith ("eglCreateWindowSurface");
3920 XFree (glx.visual);
3921 if (!eglMakeCurrent (glx.edpy, glx.win, glx.win, glx.ctx)) {
3922 glx.ctx = NULL;
3923 caml_failwith ("eglMakeCurrent");
3925 CAMLreturn (unit_v);
3927 #else
3928 CAMLprim value ml_glxinit (value display_v, value wid_v, value screen_v)
3930 CAMLparam3 (display_v, wid_v, screen_v);
3932 glx.dpy = XOpenDisplay (String_val (display_v));
3933 if (!glx.dpy) {
3934 caml_failwith ("XOpenDisplay");
3937 int attribs[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None };
3938 glx.visual = glXChooseVisual (glx.dpy, Int_val (screen_v), attribs);
3939 if (!glx.visual) {
3940 XCloseDisplay (glx.dpy);
3941 caml_failwith ("glXChooseVisual");
3944 initcurs ();
3946 glx.wid = Int_val (wid_v);
3947 CAMLreturn (Val_int (glx.visual->visualid));
3950 CAMLprim value ml_glxcompleteinit (value unit_v)
3952 CAMLparam1 (unit_v);
3954 glx.ctx = glXCreateContext (glx.dpy, glx.visual, NULL, True);
3955 if (!glx.ctx) {
3956 caml_failwith ("glXCreateContext");
3959 XFree (glx.visual);
3960 glx.visual = NULL;
3962 if (!glXMakeCurrent (glx.dpy, glx.wid, glx.ctx)) {
3963 glXDestroyContext (glx.dpy, glx.ctx);
3964 glx.ctx = NULL;
3965 caml_failwith ("glXMakeCurrent");
3967 CAMLreturn (unit_v);
3969 #endif
3971 CAMLprim void ml_setcursor (value cursor_v)
3973 CAMLparam1 (cursor_v);
3974 size_t cursn = Int_val (cursor_v);
3976 if (cursn >= CURS_COUNT) caml_failwith ("cursor index out of range");
3977 XDefineCursor (glx.dpy, glx.wid, glx.curs[cursn]);
3978 XFlush (glx.dpy);
3979 CAMLreturn0;
3982 CAMLprim value ml_swapb (value unit_v)
3984 CAMLparam1 (unit_v);
3985 #ifdef USE_EGL
3986 if (!eglSwapBuffers (glx.edpy, glx.win)) {
3987 caml_failwith ("eglSwapBuffers");
3989 #else
3990 glXSwapBuffers (glx.dpy, glx.wid);
3991 #endif
3992 CAMLreturn (unit_v);
3995 #include "keysym2ucs.c"
3997 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3999 CAMLparam1 (keysym_v);
4000 CAMLlocal1 (str_v);
4001 KeySym keysym = Int_val (keysym_v);
4002 Rune rune;
4003 int len;
4004 char buf[5];
4006 rune = keysym2ucs (keysym);
4007 len = fz_runetochar (buf, rune);
4008 buf[len] = 0;
4009 str_v = caml_copy_string (buf);
4010 CAMLreturn (str_v);
4012 #else
4013 CAMLprim value ml_keysymtoutf8 (value keysym_v)
4015 CAMLparam1 (keysym_v);
4016 CAMLlocal1 (str_v);
4017 long ucs_v = Long_val (keysym_v);
4018 int len;
4019 char buf[5];
4021 len = fz_runetochar (buf, ucs_v);
4022 buf[len] = 0;
4023 str_v = caml_copy_string (buf);
4024 CAMLreturn (str_v);
4026 #endif
4028 enum { piunknown, pilinux, piosx, pisun, pibsd, picygwin };
4030 CAMLprim value ml_platform (value unit_v)
4032 CAMLparam1 (unit_v);
4033 CAMLlocal2 (tup_v, arr_v);
4034 int platid = piunknown;
4035 struct utsname buf;
4037 #if defined __linux__
4038 platid = pilinux;
4039 #elif defined __CYGWIN__
4040 platid = picygwin;
4041 #elif defined __DragonFly__ || defined __FreeBSD__
4042 || defined __OpenBSD__ || defined __NetBSD__
4043 platid = pibsd;
4044 #elif defined __sun__
4045 platid = pisun;
4046 #elif defined __APPLE__
4047 platid = piosx;
4048 #endif
4049 if (uname (&buf)) err (1, "uname");
4051 tup_v = caml_alloc_tuple (2);
4053 char const *sar[] = {
4054 buf.sysname,
4055 buf.release,
4056 buf.version,
4057 buf.machine,
4058 NULL
4060 arr_v = caml_copy_string_array (sar);
4062 Field (tup_v, 0) = Val_int (platid);
4063 Field (tup_v, 1) = arr_v;
4064 CAMLreturn (tup_v);
4067 CAMLprim void ml_cloexec (value fd_v)
4069 CAMLparam1 (fd_v);
4070 int fd = Int_val (fd_v);
4072 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
4073 uerror ("fcntl", Nothing);
4075 CAMLreturn0;
4078 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
4080 CAMLparam2 (w_v, h_v);
4081 CAMLlocal1 (ret_v);
4082 struct bo *pbo;
4083 int w = Int_val (w_v);
4084 int h = Int_val (h_v);
4085 int cs = Int_val (cs_v);
4087 if (state.bo_usable) {
4088 pbo = calloc (sizeof (*pbo), 1);
4089 if (!pbo) {
4090 err (1, "calloc pbo");
4093 switch (cs) {
4094 case 0:
4095 case 1:
4096 pbo->size = w*h*4;
4097 break;
4098 case 2:
4099 pbo->size = w*h*2;
4100 break;
4101 default:
4102 errx (1, "%s: invalid colorspace %d", __func__, cs);
4105 state.glGenBuffersARB (1, &pbo->id);
4106 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
4107 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->size,
4108 NULL, GL_STREAM_DRAW);
4109 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
4110 GL_READ_WRITE);
4111 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4112 if (!pbo->ptr) {
4113 fprintf (stderr, "glMapBufferARB failed: %#x\n", glGetError ());
4114 state.glDeleteBuffersARB (1, &pbo->id);
4115 free (pbo);
4116 ret_v = caml_copy_string ("0");
4118 else {
4119 int res;
4120 char *s;
4122 res = snprintf (NULL, 0, "%" FMT_ptr, FMT_ptr_cast (pbo));
4123 if (res < 0) {
4124 err (1, "snprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4126 s = malloc (res+1);
4127 if (!s) {
4128 err (1, "malloc %d bytes failed", res+1);
4130 res = sprintf (s, "%" FMT_ptr, FMT_ptr_cast (pbo));
4131 if (res < 0) {
4132 err (1, "sprintf %" FMT_ptr " failed", FMT_ptr_cast (pbo));
4134 ret_v = caml_copy_string (s);
4135 free (s);
4138 else {
4139 ret_v = caml_copy_string ("0");
4141 CAMLreturn (ret_v);
4144 CAMLprim void ml_freepbo (value s_v)
4146 CAMLparam1 (s_v);
4147 char *s = String_val (s_v);
4148 struct tile *tile = parse_pointer (__func__, s);
4150 if (tile->pbo) {
4151 state.glDeleteBuffersARB (1, &tile->pbo->id);
4152 tile->pbo->id = -1;
4153 tile->pbo->ptr = NULL;
4154 tile->pbo->size = -1;
4156 CAMLreturn0;
4159 CAMLprim void ml_unmappbo (value s_v)
4161 CAMLparam1 (s_v);
4162 char *s = String_val (s_v);
4163 struct tile *tile = parse_pointer (__func__, s);
4165 if (tile->pbo) {
4166 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
4167 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
4168 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
4170 tile->pbo->ptr = NULL;
4171 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
4173 CAMLreturn0;
4176 static void setuppbo (void)
4178 #ifdef __COCOA__
4179 static CFBundleRef framework = NULL;
4180 if (framework == NULL)
4181 framework = CFBundleGetBundleWithIdentifier (CFSTR ("com.apple.opengl"));
4182 #define GGPA(n) (&state.n = CFBundleGetFunctionPointerForName (framework, CFSTR (#n)))
4183 #else
4184 #ifdef USE_EGL
4185 #define GGPA(n) (*(void (**) ()) &state.n = eglGetProcAddress (#n))
4186 #else
4187 #define GGPA(n) (*(void (**) ()) &state.n = glXGetProcAddress ((GLubyte *) #n))
4188 #endif
4189 state.bo_usable = GGPA (glBindBufferARB)
4190 && GGPA (glUnmapBufferARB)
4191 && GGPA (glMapBufferARB)
4192 && GGPA (glBufferDataARB)
4193 && GGPA (glGenBuffersARB)
4194 && GGPA (glDeleteBuffersARB);
4195 #endif
4196 #undef GGPA
4199 CAMLprim value ml_bo_usable (value unit_v)
4201 CAMLparam1 (unit_v);
4202 CAMLreturn (Val_bool (state.bo_usable));
4205 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
4207 CAMLparam3 (ptr_v, x_v, y_v);
4208 CAMLlocal2 (ret_v, tup_v);
4209 struct page *page;
4210 char *s = String_val (ptr_v);
4211 int x = Int_val (x_v), y = Int_val (y_v);
4212 struct pagedim *pdim;
4213 fz_point p;
4214 fz_matrix ctm;
4216 page = parse_pointer (__func__, s);
4217 pdim = &state.pagedims[page->pdimno];
4219 ret_v = Val_int (0);
4220 if (trylock (__func__)) {
4221 goto done;
4224 if (pdf_specifics (state.ctx, state.doc)) {
4225 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4226 ctm = state.pagedims[page->pdimno].tctm;
4228 else {
4229 ctm = fz_identity;
4231 p.x = x + pdim->bounds.x0;
4232 p.y = y + pdim->bounds.y0;
4234 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4235 fz_invert_matrix (&ctm, &ctm);
4236 fz_transform_point (&p, &ctm);
4238 tup_v = caml_alloc_tuple (2);
4239 ret_v = caml_alloc_small (1, 1);
4240 Field (tup_v, 0) = Val_int (p.x);
4241 Field (tup_v, 1) = Val_int (p.y);
4242 Field (ret_v, 0) = tup_v;
4244 unlock (__func__);
4245 done:
4246 CAMLreturn (ret_v);
4249 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
4250 value x_v, value y_v)
4252 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
4253 CAMLlocal1 (ret_v);
4254 struct page *page;
4255 char *s = String_val (ptr_v);
4256 int pageno = Int_val (pageno_v);
4257 int pdimno = Int_val (pdimno_v);
4258 double x = Double_val (x_v), y = Double_val (y_v);
4259 struct pagedim *pdim;
4260 fz_point p;
4261 fz_matrix ctm;
4263 ret_v = Val_int (0);
4264 lock (__func__);
4266 if (!*s) {
4267 page = loadpage (pageno, pdimno);
4269 else {
4270 page = parse_pointer (__func__, s);
4272 pdim = &state.pagedims[pdimno];
4274 if (pdf_specifics (state.ctx, state.doc)) {
4275 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
4276 ctm = state.pagedims[page->pdimno].tctm;
4278 else {
4279 ctm = fz_identity;
4281 p.x = x + pdim->bounds.x0;
4282 p.y = y + pdim->bounds.y0;
4284 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
4285 fz_transform_point (&p, &ctm);
4287 ret_v = caml_alloc_tuple (2);
4288 Field (ret_v, 0) = caml_copy_double (p.x);
4289 Field (ret_v, 1) = caml_copy_double (p.y);
4291 if (!*s) {
4292 freepage (page);
4294 unlock (__func__);
4295 CAMLreturn (ret_v);
4298 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
4299 value contents_v)
4301 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
4302 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4304 if (pdf) {
4305 pdf_annot *annot;
4306 struct page *page;
4307 fz_point p;
4308 char *s = String_val (ptr_v);
4310 page = parse_pointer (__func__, s);
4311 annot = pdf_create_annot (state.ctx,
4312 pdf_page_from_fz_page (state.ctx,
4313 page->fzpage),
4314 PDF_ANNOT_TEXT);
4315 p.x = Int_val (x_v);
4316 p.y = Int_val (y_v);
4317 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
4318 pdf_set_text_annot_position (state.ctx, annot, p);
4319 state.dirty = 1;
4321 CAMLreturn0;
4324 CAMLprim void ml_delannot (value ptr_v, value n_v)
4326 CAMLparam2 (ptr_v, n_v);
4327 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4329 if (pdf) {
4330 struct page *page;
4331 char *s = String_val (ptr_v);
4332 struct slink *slink;
4334 page = parse_pointer (__func__, s);
4335 slink = &page->slinks[Int_val (n_v)];
4336 pdf_delete_annot (state.ctx,
4337 pdf_page_from_fz_page (state.ctx, page->fzpage),
4338 (pdf_annot *) slink->u.annot);
4339 state.dirty = 1;
4341 CAMLreturn0;
4344 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
4346 CAMLparam3 (ptr_v, n_v, str_v);
4347 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4349 if (pdf) {
4350 struct page *page;
4351 char *s = String_val (ptr_v);
4352 struct slink *slink;
4354 page = parse_pointer (__func__, s);
4355 slink = &page->slinks[Int_val (n_v)];
4356 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
4357 String_val (str_v));
4358 state.dirty = 1;
4360 CAMLreturn0;
4363 CAMLprim value ml_hasunsavedchanges (value unit_v)
4365 CAMLparam1 (unit_v);
4366 CAMLreturn (Val_bool (state.dirty));
4369 CAMLprim void ml_savedoc (value path_v)
4371 CAMLparam1 (path_v);
4372 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
4374 if (pdf) {
4375 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
4377 CAMLreturn0;
4380 static void makestippletex (void)
4382 const char pixels[] = "\xff\xff\0\0";
4383 glGenTextures (1, &state.stid);
4384 glBindTexture (GL_TEXTURE_1D, state.stid);
4385 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
4386 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
4387 glTexImage1D (
4388 GL_TEXTURE_1D,
4390 GL_ALPHA,
4393 GL_ALPHA,
4394 GL_UNSIGNED_BYTE,
4395 pixels
4399 CAMLprim value ml_fz_version (value UNUSED_ATTR unit_v)
4401 return caml_copy_string (FZ_VERSION);
4404 CAMLprim void ml_init (value csock_v, value params_v)
4406 CAMLparam2 (csock_v, params_v);
4407 CAMLlocal2 (trim_v, fuzz_v);
4408 int ret;
4409 int texcount;
4410 char *fontpath;
4411 int colorspace;
4412 int mustoresize;
4413 int haspboext;
4415 /* Without following(dummy) call to setlocale mbstowcs fails for,
4416 at least, strings containing chinese symbols (δΈ­ for instance)
4417 (with glibc citing EILSEQ="Invalid or incomplete multibyte or
4418 wide character" as the reason of failure and with macOS
4419 producing bogus output) */
4420 if (setlocale (LC_CTYPE, "")) {
4421 /* Following two lines were taken from dvtm/vt.c */
4422 const char *cset = nl_langinfo (CODESET);
4423 state.utf8cs = !strcmp (cset, "UTF-8");
4425 else {
4426 fprintf (stderr, "setlocale failed\n");
4429 state.csock = Int_val (csock_v);
4430 state.rotate = Int_val (Field (params_v, 0));
4431 state.fitmodel = Int_val (Field (params_v, 1));
4432 trim_v = Field (params_v, 2);
4433 texcount = Int_val (Field (params_v, 3));
4434 state.sliceheight = Int_val (Field (params_v, 4));
4435 mustoresize = Int_val (Field (params_v, 5));
4436 colorspace = Int_val (Field (params_v, 6));
4437 fontpath = String_val (Field (params_v, 7));
4439 if (caml_string_length (Field (params_v, 8)) > 0) {
4440 state.trimcachepath = strdup (String_val (Field (params_v, 8)));
4442 if (!state.trimcachepath) {
4443 fprintf (stderr, "failed to strdup trimcachepath: %s\n",
4444 strerror (errno));
4448 haspboext = Bool_val (Field (params_v, 9));
4450 state.ctx = fz_new_context (NULL, NULL, mustoresize);
4451 fz_register_document_handlers (state.ctx);
4453 state.trimmargins = Bool_val (Field (trim_v, 0));
4454 fuzz_v = Field (trim_v, 1);
4455 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
4456 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
4457 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
4458 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
4460 set_tex_params (colorspace);
4462 if (*fontpath) {
4463 state.face = load_font (fontpath);
4465 else {
4466 int len;
4467 const char *data = pdf_lookup_substitute_font (state.ctx, 0, 0,
4468 0, 0, &len);
4469 state.face = load_builtin_font (data, len);
4471 if (!state.face) _exit (1);
4473 realloctexts (texcount);
4475 if (haspboext) {
4476 setuppbo ();
4479 makestippletex ();
4481 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
4482 if (ret) {
4483 errx (1, "pthread_create: %s", strerror (ret));
4486 CAMLreturn0;