Cosmetics
[llpp.git] / link.c
blob1601c4a5f0dd93307cc7ca23bcc7cbbbcd79d279
1 /* lots of code c&p-ed directly from mupdf */
2 #define FIXME 0
4 #ifdef __clang__
5 #pragma GCC diagnostic error "-Weverything"
6 #pragma GCC diagnostic ignored "-Wpadded"
7 #pragma GCC diagnostic ignored "-Wsign-conversion"
8 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
9 #pragma GCC diagnostic ignored "-Wdocumentation"
10 #pragma GCC diagnostic ignored "-Wdouble-promotion"
11 #pragma GCC diagnostic ignored "-Wimplicit-int-float-conversion"
12 #endif
14 extern char **environ;
16 #include <errno.h>
17 #include <stdio.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <signal.h>
23 #include <math.h>
24 #include <wchar.h>
25 #include <locale.h>
26 #include <langinfo.h>
28 #include <unistd.h>
29 #include <pthread.h>
30 #include <sys/uio.h>
31 #include <sys/time.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/utsname.h>
38 #include <spawn.h>
40 #include <regex.h>
41 #include <stdarg.h>
42 #include <limits.h>
43 #include <inttypes.h>
45 #ifdef CIDER
46 #include <OpenGL/gl.h>
47 #else
48 #include <GL/gl.h>
49 #endif
51 #pragma GCC diagnostic push
52 #ifdef __clang__
53 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
54 #endif
55 #pragma GCC diagnostic ignored "-Wpedantic"
56 #define CAML_NAME_SPACE
57 #include <caml/fail.h>
58 #include <caml/alloc.h>
59 #include <caml/memory.h>
60 #include <caml/unixsupport.h>
62 #pragma GCC diagnostic push
63 #pragma GCC diagnostic ignored "-Wfloat-equal"
64 #include <mupdf/fitz.h>
65 #include <mupdf/pdf.h>
66 #pragma GCC diagnostic pop
68 #include <ft2build.h>
69 #include FT_FREETYPE_H
70 #pragma GCC diagnostic pop
72 #include "cutils.h"
74 #ifdef USE_NPOT
75 #define TEXT_TYPE GL_TEXTURE_2D
76 #else
77 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
78 #endif
80 #if 0
81 #define lprintf printf
82 #else
83 #define lprintf(...)
84 #endif
86 #define ARSERT(cond) for (;;) { \
87 if (!(cond)) { \
88 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
89 } \
90 break; \
91 } (void) 0
93 #define ML(d) extern value ml_##d; value ml_##d
94 #define ML0(d) extern void ml_##d; void ml_##d
96 struct slice {
97 int h;
98 int texindex;
101 struct tile {
102 int w, h;
103 int slicecount;
104 int sliceheight;
105 struct bo *pbo;
106 fz_pixmap *pixmap;
107 struct slice slices[1];
110 struct pagedim {
111 int pageno;
112 int rotate;
113 int left;
114 int tctmready;
115 fz_irect bounds;
116 fz_rect pagebox;
117 fz_rect mediabox;
118 fz_matrix ctm, zoomctm, tctm;
121 struct slink {
122 enum { SLINK, SANNOT } tag;
123 fz_irect bbox;
124 union {
125 fz_link *link;
126 pdf_annot *annot;
127 } u;
130 struct annot {
131 fz_irect bbox;
132 pdf_annot *annot;
135 struct page {
136 int tgen;
137 int sgen;
138 int agen;
139 int pageno;
140 int pdimno;
141 fz_stext_page *text;
142 fz_page *fzpage;
143 fz_display_list *dlist;
144 fz_link *links;
145 int slinkcount;
146 struct slink *slinks;
147 int annotcount;
148 struct annot *annots;
149 fz_stext_char *fmark, *lmark;
152 enum { FitWidth, FitProportional, FitPage };
154 static struct {
155 int sliceheight;
156 struct pagedim *pagedims;
157 int pagecount;
158 int pagedimcount;
159 fz_document *doc;
160 fz_context *ctx;
161 int w, h;
163 struct {
164 int index, count;
165 GLuint *ids;
166 GLenum iform, form, ty;
167 struct {
168 int w, h;
169 struct slice *slice;
170 } *owners;
171 } tex;
173 fz_colorspace *colorspace;
174 float papercolor[4];
177 FT_Face face;
178 fz_pixmap *pig;
179 pthread_t thread;
180 fz_irect trimfuzz;
181 GLuint stid, boid;
182 int trimmargins, needoutline, gen, rotate, aalevel,
183 fitmodel, trimanew, csock, dirty, bo_usable, utf8cs;
185 void (*glBindBufferARB) (GLenum, GLuint);
186 GLboolean (*glUnmapBufferARB) (GLenum);
187 void *(*glMapBufferARB) (GLenum, GLenum);
188 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
189 void (*glGenBuffersARB) (GLsizei, GLuint *);
190 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
192 GLfloat texcoords[8], vertices[16];
193 } state;
195 struct bo {
196 GLuint id;
197 void *ptr;
198 size_t size;
201 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
203 static void lock (const char *cap)
205 int ret = pthread_mutex_lock (&mutex);
206 if (ret) {
207 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
211 static void unlock (const char *cap)
213 int ret = pthread_mutex_unlock (&mutex);
214 if (ret) {
215 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
219 static int trylock (const char *cap)
221 int ret = pthread_mutex_trylock (&mutex);
222 if (ret && ret != EBUSY) {
223 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
225 return ret == EBUSY;
228 static int hasdata (void)
230 int ret, avail;
231 ret = ioctl (state.csock, FIONREAD, &avail);
232 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
233 return avail > 0;
236 ML (hasdata (value fd_v))
238 CAMLparam1 (fd_v);
239 int ret, avail;
241 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
242 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
243 CAMLreturn (Val_bool (avail > 0));
246 static void readdata (int fd, void *p, int size)
248 ssize_t n;
250 again:
251 n = read (fd, p, size);
252 if (n - size) {
253 if (n < 0 && errno == EINTR) goto again;
254 if (!n) errx (1, "EOF while reading");
255 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
259 static void writedata (int fd, char *p, int size)
261 ssize_t n;
262 uint32_t size4 = size;
263 struct iovec iov[2] = {
264 { .iov_base = &size4, .iov_len = 4 },
265 { .iov_base = p, .iov_len = size }
268 again:
269 n = writev (fd, iov, 2);
270 if (n < 0 && errno == EINTR) goto again;
271 if (n - size - 4) {
272 if (!n) errx (1, "EOF while writing data");
273 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
277 static int readlen (int fd)
279 uint32_t u;
280 readdata (fd, &u, 4);
281 return u;
284 ML0 (wcmd (value fd_v, value bytes_v, value len_v))
286 CAMLparam3 (fd_v, bytes_v, len_v);
287 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
288 CAMLreturn0;
291 ML (rcmd (value fd_v))
293 CAMLparam1 (fd_v);
294 CAMLlocal1 (strdata_v);
295 int fd = Int_val (fd_v);
296 int len = readlen (fd);
297 strdata_v = caml_alloc_string (len);
298 readdata (fd, Bytes_val (strdata_v), len);
299 CAMLreturn (strdata_v);
302 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
304 char fbuf[64];
305 int size = sizeof (fbuf), len;
306 va_list ap;
307 char *buf = fbuf;
309 for (;;) {
310 va_start (ap, fmt);
311 len = vsnprintf (buf, size, fmt, ap);
312 va_end (ap);
314 if (len > -1) {
315 if (len < size - 4) {
316 writedata (state.csock, buf, len);
317 break;
319 else size = len + 5;
321 else {
322 err (1, "vsnprintf for `%s' failed", fmt);
324 buf = realloc (buf == fbuf ? NULL : buf, size);
325 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
327 if (buf != fbuf) free (buf);
330 static void closedoc (void)
332 if (state.doc) {
333 fz_drop_document (state.ctx, state.doc);
334 state.doc = NULL;
338 static int openxref (char *filename, char *password, int layouth)
340 for (int i = 0; i < state.tex.count; ++i) {
341 state.tex.owners[i].w = -1;
342 state.tex.owners[i].slice = NULL;
345 closedoc ();
347 state.dirty = 0;
348 if (state.pagedims) {
349 free (state.pagedims);
350 state.pagedims = NULL;
352 state.pagedimcount = 0;
354 fz_set_aa_level (state.ctx, state.aalevel);
355 state.doc = fz_open_document (state.ctx, filename);
356 if (fz_needs_password (state.ctx, state.doc)) {
357 if (password && !*password) {
358 printd ("pass");
359 return 0;
361 else {
362 int ok = fz_authenticate_password (state.ctx, state.doc, password);
363 if (!ok) {
364 printd ("pass fail");
365 return 0;
369 if (layouth >= 0)
370 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
371 state.pagecount = fz_count_pages (state.ctx, state.doc);
372 return 1;
375 static void docinfo (void)
377 struct { char *tag; char *name; } metatbl[] = {
378 { FZ_META_INFO_TITLE, "Title" },
379 { FZ_META_INFO_AUTHOR, "Author" },
380 { FZ_META_FORMAT, "Format" },
381 { FZ_META_ENCRYPTION, "Encryption" },
382 { FZ_META_INFO_CREATOR, "Creator" },
383 { FZ_META_INFO_PRODUCER, "Producer" },
384 { "info:CreationDate", "Creation date" },
386 int len = 0;
387 char *buf = NULL;
389 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
390 int need;
391 again:
392 need = fz_lookup_metadata (state.ctx, state.doc,
393 metatbl[i].tag, buf, len);
394 if (need > 0) {
395 if (need <= len) {
396 printd ("info %s\t%s", metatbl[i].name, buf);
398 else {
399 buf = realloc (buf, need + 1);
400 if (!buf) err (1, "docinfo realloc %d", need + 1);
401 len = need + 1;
402 goto again;
406 free (buf);
408 printd ("infoend");
411 static void unlinktile (struct tile *tile)
413 for (int i = 0; i < tile->slicecount; ++i) {
414 struct slice *s = &tile->slices[i];
416 if (s->texindex != -1) {
417 if (state.tex.owners[s->texindex].slice == s) {
418 state.tex.owners[s->texindex].slice = NULL;
424 static void freepage (struct page *page)
426 if (!page) return;
427 if (page->text) {
428 fz_drop_stext_page (state.ctx, page->text);
430 if (page->slinks) {
431 free (page->slinks);
433 fz_drop_display_list (state.ctx, page->dlist);
434 fz_drop_page (state.ctx, page->fzpage);
435 free (page);
438 static void freetile (struct tile *tile)
440 unlinktile (tile);
441 if (!tile->pbo) {
442 #if 0
443 fz_drop_pixmap (state.ctx, tile->pixmap);
444 #else /* piggyback */
445 if (state.pig) {
446 fz_drop_pixmap (state.ctx, state.pig);
448 state.pig = tile->pixmap;
449 #endif
451 else {
452 free (tile->pbo);
453 fz_drop_pixmap (state.ctx, tile->pixmap);
455 free (tile);
458 static void trimctm (pdf_page *page, int pindex)
460 struct pagedim *pdim = &state.pagedims[pindex];
462 if (!page) return;
463 if (!pdim->tctmready) {
464 fz_rect realbox, mediabox;
465 fz_matrix page_ctm, ctm;
467 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
468 realbox = fz_transform_rect (pdim->mediabox, ctm);
469 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
470 pdim->tctm = fz_concat (
471 fz_invert_matrix (page_ctm),
472 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
473 pdim->tctmready = 1;
477 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
479 fz_matrix ctm;
480 ptrdiff_t pdimno = pdim - state.pagedims;
482 ARSERT (pdim - state.pagedims < INT_MAX);
483 if (pdf_specifics (state.ctx, state.doc)) {
484 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
485 ctm = fz_concat (pdim->tctm, pdim->ctm);
487 else {
488 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
489 pdim->ctm);
491 return ctm;
494 static fz_matrix pagectm (struct page *page)
496 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
499 static void *loadpage (int pageno, int pindex)
501 fz_device *dev;
502 struct page *page;
504 page = calloc (sizeof (struct page), 1);
505 if (!page) {
506 err (1, "calloc page %d", pageno);
509 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
510 dev = fz_new_list_device (state.ctx, page->dlist);
511 fz_try (state.ctx) {
512 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
513 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
515 fz_catch (state.ctx) {
516 page->fzpage = NULL;
518 fz_close_device (state.ctx, dev);
519 fz_drop_device (state.ctx, dev);
521 page->pdimno = pindex;
522 page->pageno = pageno;
523 page->sgen = state.gen;
524 page->agen = state.gen;
525 page->tgen = state.gen;
526 return page;
529 static struct tile *alloctile (int h)
531 int slicecount;
532 size_t tilesize;
533 struct tile *tile;
535 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
536 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
537 tile = calloc (tilesize, 1);
538 if (!tile) {
539 err (1, "cannot allocate tile (%zu bytes)", tilesize);
541 for (int i = 0; i < slicecount; ++i) {
542 int sh = fz_mini (h, state.sliceheight);
543 tile->slices[i].h = sh;
544 tile->slices[i].texindex = -1;
545 h -= sh;
547 tile->slicecount = slicecount;
548 tile->sliceheight = state.sliceheight;
549 return tile;
552 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
553 struct bo *pbo)
555 fz_irect bbox;
556 fz_matrix ctm;
557 fz_device *dev;
558 struct tile *tile;
559 struct pagedim *pdim;
561 tile = alloctile (h);
562 pdim = &state.pagedims[page->pdimno];
564 bbox = pdim->bounds;
565 bbox.x0 += x;
566 bbox.y0 += y;
567 bbox.x1 = bbox.x0 + w;
568 bbox.y1 = bbox.y0 + h;
570 if (state.pig) {
571 if (state.pig->w == w
572 && state.pig->h == h
573 && state.pig->colorspace == state.colorspace) {
574 tile->pixmap = state.pig;
575 tile->pixmap->x = bbox.x0;
576 tile->pixmap->y = bbox.y0;
578 else {
579 fz_drop_pixmap (state.ctx, state.pig);
581 state.pig = NULL;
583 if (!tile->pixmap) {
584 if (pbo) {
585 tile->pixmap =
586 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
587 bbox, NULL, 1, pbo->ptr);
588 tile->pbo = pbo;
590 else {
591 tile->pixmap =
592 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
593 NULL, 1);
597 tile->w = w;
598 tile->h = h;
599 fz_fill_pixmap_with_color (state.ctx, tile->pixmap,
600 fz_device_rgb (state.ctx),
601 state.papercolor,
602 fz_default_color_params);
604 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
605 ctm = pagectm (page);
606 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
607 fz_rect_from_irect (bbox), NULL);
608 fz_close_device (state.ctx, dev);
609 fz_drop_device (state.ctx, dev);
611 return tile;
614 static void initpdims (void)
616 struct pagedim *p = NULL;
617 pdf_document *pdf = NULL;
618 fz_context *ctx = state.ctx;
619 int pageno, trim, show, cxcount;
620 fz_rect rootmediabox = fz_empty_rect;
622 fz_var (p);
623 fz_var (pdf);
624 fz_var (cxcount);
626 cxcount = state.pagecount;
627 if ((pdf = pdf_specifics (ctx, state.doc))) {
628 pdf_obj *obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
629 "Root/Pages/MediaBox");
630 rootmediabox = pdf_to_rect (ctx, obj);
631 pdf_load_page_tree (ctx, pdf);
634 for (pageno = 0; pageno < cxcount; ++pageno) {
635 int rotate = 0;
636 fz_rect mediabox = fz_empty_rect;
638 fz_var (rotate);
639 if (pdf) {
640 pdf_obj *pageobj = NULL;
642 fz_var (pageobj);
643 if (pdf->rev_page_map) {
644 for (int i = 0; i < pdf->rev_page_count; ++i) {
645 if (pdf->rev_page_map[i].page == pageno) {
646 pageobj = pdf_get_xref_entry (
647 ctx, pdf, pdf->rev_page_map[i].object
648 )->obj;
649 break;
653 if (!pageobj) {
654 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
657 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
659 if (state.trimmargins) {
660 pdf_obj *obj;
661 pdf_page *page;
663 fz_try (ctx) {
664 page = pdf_load_page (ctx, pdf, pageno);
665 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
666 trim = state.trimanew || !obj;
667 if (trim) {
668 fz_rect rect;
669 fz_device *dev;
670 fz_matrix ctm, page_ctm;
672 dev = fz_new_bbox_device (ctx, &rect);
673 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
674 ctm = fz_invert_matrix (page_ctm);
675 pdf_run_page (ctx, page, dev, fz_identity, NULL);
676 fz_close_device (ctx, dev);
677 fz_drop_device (ctx, dev);
679 rect.x0 += state.trimfuzz.x0;
680 rect.x1 += state.trimfuzz.x1;
681 rect.y0 += state.trimfuzz.y0;
682 rect.y1 += state.trimfuzz.y1;
683 rect = fz_transform_rect (rect, ctm);
684 rect = fz_intersect_rect (rect, mediabox);
686 if (!fz_is_empty_rect (rect)) {
687 mediabox = rect;
690 obj = pdf_new_array (ctx, pdf, 4);
691 pdf_array_push_real (ctx, obj, mediabox.x0);
692 pdf_array_push_real (ctx, obj, mediabox.y0);
693 pdf_array_push_real (ctx, obj, mediabox.x1);
694 pdf_array_push_real (ctx, obj, mediabox.y1);
695 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
697 else {
698 mediabox.x0 = pdf_array_get_real (ctx, obj, 0);
699 mediabox.y0 = pdf_array_get_real (ctx, obj, 1);
700 mediabox.x1 = pdf_array_get_real (ctx, obj, 2);
701 mediabox.y1 = pdf_array_get_real (ctx, obj, 3);
704 fz_drop_page (ctx, &page->super);
705 show = (pageno + 1 == state.pagecount)
706 || (trim ? pageno % 5 == 0 : pageno % 20 == 0);
707 if (show) {
708 printd ("progress %f Trimming %d",
709 (double) (pageno + 1) / state.pagecount,
710 pageno + 1);
713 fz_catch (ctx) {
714 printd ("emsg failed to load page %d", pageno);
717 else {
718 int empty = 0;
719 fz_rect cropbox;
721 mediabox =
722 pdf_to_rect (ctx,
723 pdf_dict_get_inheritable (
724 ctx,
725 pageobj,
726 PDF_NAME (MediaBox)
729 if (fz_is_empty_rect (mediabox)) {
730 mediabox.x0 = 0;
731 mediabox.y0 = 0;
732 mediabox.x1 = 612;
733 mediabox.y1 = 792;
734 empty = 1;
737 cropbox =
738 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
739 if (!fz_is_empty_rect (cropbox)) {
740 if (empty) {
741 mediabox = cropbox;
743 else {
744 mediabox = fz_intersect_rect (mediabox, cropbox);
747 else {
748 if (empty) {
749 if (fz_is_empty_rect (rootmediabox)) {
750 printd ("emsg cannot find page size for page %d",
751 pageno);
753 else {
754 mediabox = rootmediabox;
760 else {
761 if (state.trimmargins) {
762 fz_page *page;
764 fz_try (ctx) {
765 page = fz_load_page (ctx, state.doc, pageno);
766 mediabox = fz_bound_page (ctx, page);
767 if (state.trimmargins) {
768 fz_rect rect;
769 fz_device *dev;
771 dev = fz_new_bbox_device (ctx, &rect);
772 fz_run_page (ctx, page, dev, fz_identity, NULL);
773 fz_close_device (ctx, dev);
774 fz_drop_device (ctx, dev);
776 rect.x0 += state.trimfuzz.x0;
777 rect.x1 += state.trimfuzz.x1;
778 rect.y0 += state.trimfuzz.y0;
779 rect.y1 += state.trimfuzz.y1;
780 rect = fz_intersect_rect (rect, mediabox);
782 if (!fz_is_empty_rect (rect)) {
783 mediabox = rect;
786 fz_drop_page (ctx, page);
788 fz_catch (ctx) {
791 else {
792 fz_page *page;
793 fz_try (ctx) {
794 page = fz_load_page (ctx, state.doc, pageno);
795 mediabox = fz_bound_page (ctx, page);
796 fz_drop_page (ctx, page);
798 show = !state.trimmargins && pageno % 20 == 0;
799 if (show) {
800 printd ("progress %f Gathering dimensions %d",
801 (double) (pageno) / state.pagecount,
802 pageno);
805 fz_catch (ctx) {
806 printd ("emsg failed to load page %d", pageno);
811 if (!p || p->rotate != rotate
812 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
813 size_t size;
815 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
816 state.pagedims = realloc (state.pagedims, size);
817 if (!state.pagedims) {
818 err (1, "realloc pagedims to %zu (%d elems)",
819 size, state.pagedimcount + 1);
822 p = &state.pagedims[state.pagedimcount++];
823 p->rotate = rotate;
824 p->mediabox = mediabox;
825 p->pageno = pageno;
828 state.trimanew = 0;
831 static void layout (void)
833 int pindex;
834 fz_rect box;
835 fz_matrix ctm;
836 struct pagedim *p = NULL;
837 float zw, w, maxw = 0.0, zoom = 1.0;
839 if (state.pagedimcount == 0) return;
841 switch (state.fitmodel) {
842 case FitProportional:
843 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
844 float x0, x1;
846 p = &state.pagedims[pindex];
847 box = fz_transform_rect (p->mediabox,
848 fz_rotate (p->rotate + state.rotate));
850 x0 = fz_min (box.x0, box.x1);
851 x1 = fz_max (box.x0, box.x1);
853 w = x1 - x0;
854 maxw = fz_max (w, maxw);
855 zoom = state.w / maxw;
857 break;
859 case FitPage:
860 maxw = state.w;
861 break;
863 case FitWidth:
864 break;
866 default:
867 ARSERT (0 && state.fitmodel);
870 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
871 p = &state.pagedims[pindex];
872 ctm = fz_rotate (state.rotate);
873 box = fz_transform_rect (p->mediabox,
874 fz_rotate (p->rotate + state.rotate));
875 w = box.x1 - box.x0;
876 switch (state.fitmodel) {
877 case FitProportional:
878 p->left = (int) (((maxw - w) * zoom) / 2.f);
879 break;
880 case FitPage:
882 float zh, h;
883 zw = maxw / w;
884 h = box.y1 - box.y0;
885 zh = state.h / h;
886 zoom = fz_min (zw, zh);
887 p->left = (int) ((maxw - (w * zoom)) / 2.f);
889 break;
890 case FitWidth:
891 p->left = 0;
892 zoom = state.w / w;
893 break;
896 p->zoomctm = fz_scale (zoom, zoom);
897 ctm = fz_concat (p->zoomctm, ctm);
899 p->pagebox = p->mediabox;
900 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
901 p->pagebox.x1 -= p->pagebox.x0;
902 p->pagebox.y1 -= p->pagebox.y0;
903 p->pagebox.x0 = 0;
904 p->pagebox.y0 = 0;
905 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
906 p->ctm = ctm;
908 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
909 fz_scale (zoom, -zoom));
910 p->tctmready = 0;
913 do {
914 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
915 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
916 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
917 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
918 int boundw = x1 - x0;
919 int boundh = y1 - y0;
921 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
922 } while (p-- != state.pagedims);
925 static struct pagedim *pdimofpageno (int pageno)
927 struct pagedim *pdim = state.pagedims;
929 for (int i = 0; i < state.pagedimcount; ++i) {
930 if (state.pagedims[i].pageno > pageno)
931 break;
932 pdim = &state.pagedims[i];
934 return pdim;
937 static void recurse_outline (fz_outline *outline, int level)
939 while (outline) {
940 if (outline->page >= 0) {
941 fz_point p = {.x = outline->x, .y = outline->y};
942 struct pagedim *pdim = pdimofpageno (outline->page);
943 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
944 p = fz_transform_point (p, pdim->ctm);
945 printd ("o %d %d %d %d %s",
946 level, outline->page, (int) p.y, h, outline->title);
948 else {
949 printd ("on %d %s", level, outline->title);
951 if (outline->down) {
952 recurse_outline (outline->down, level + 1);
954 outline = outline->next;
958 static void process_outline (void)
960 fz_outline *outline;
962 if (!state.needoutline || !state.pagedimcount) return;
964 state.needoutline = 0;
965 outline = fz_load_outline (state.ctx, state.doc);
966 if (outline) {
967 recurse_outline (outline, 0);
968 fz_drop_outline (state.ctx, outline);
972 static char *strofline (fz_stext_line *line)
974 char *p;
975 char utf8[10];
976 fz_stext_char *ch;
977 size_t size = 0, cap = 80;
979 p = malloc (cap + 1);
980 if (!p) return NULL;
982 for (ch = line->first_char; ch; ch = ch->next) {
983 int n = fz_runetochar (utf8, ch->c);
984 if (size + n > cap) {
985 cap *= 2;
986 p = realloc (p, cap + 1);
987 if (!p) return NULL;
990 memcpy (p + size, utf8, n);
991 size += n;
993 p[size] = 0;
994 return p;
997 static int matchline (regex_t *re, fz_stext_line *line,
998 int stop, int pageno, double start)
1000 int ret;
1001 char *p;
1002 regmatch_t rm;
1004 p = strofline (line);
1005 if (!p) return -1;
1007 ret = regexec (re, p, 1, &rm, 0);
1008 if (ret) {
1009 free (p);
1010 if (ret != REG_NOMATCH) {
1011 size_t size;
1012 char errbuf[80];
1013 size = regerror (ret, re, errbuf, sizeof (errbuf));
1014 printd ("msg regexec error `%.*s'",
1015 (int) size, errbuf);
1016 return -1;
1018 return 0;
1020 else {
1021 fz_quad s, e;
1022 fz_stext_char *ch;
1023 int o = 0;
1025 for (ch = line->first_char; ch; ch = ch->next) {
1026 o += fz_runelen (ch->c);
1027 if (o > rm.rm_so) {
1028 s = ch->quad;
1029 break;
1032 for (;ch; ch = ch->next) {
1033 o += fz_runelen (ch->c);
1034 if (o > rm.rm_eo) break;
1036 e = ch->quad;
1038 if (!stop) {
1039 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1040 pageno, 1,
1041 s.ul.x, s.ul.y,
1042 e.ur.x, s.ul.y,
1043 e.lr.x, e.lr.y,
1044 s.ul.x, e.lr.y);
1046 printd ("progress 1 found at %d `%.*s' in %f sec",
1047 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1048 now () - start);
1050 else {
1051 printd ("match %d %d %f %f %f %f %f %f %f %f",
1052 pageno, 2,
1053 s.ul.x, s.ul.y,
1054 e.ur.x, s.ul.y,
1055 e.lr.x, e.lr.y,
1056 s.ul.x, e.lr.y);
1058 free (p);
1059 return 1;
1063 /* wishful thinking function */
1064 static void search (regex_t *re, int pageno, int y, int forward)
1066 fz_device *tdev;
1067 fz_stext_page *text;
1068 struct pagedim *pdim;
1069 int stop = 0, niters = 0;
1070 double start, end;
1071 fz_page *page;
1072 fz_stext_block *block;
1074 start = now ();
1075 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1076 if (niters++ == 5) {
1077 niters = 0;
1078 if (hasdata ()) {
1079 printd ("progress 1 attention requested aborting search at %d",
1080 pageno);
1081 stop = 1;
1083 else {
1084 printd ("progress %f searching in page %d",
1085 (double) (pageno + 1) / state.pagecount,
1086 pageno);
1089 pdim = pdimofpageno (pageno);
1090 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1091 tdev = fz_new_stext_device (state.ctx, text, 0);
1093 page = fz_load_page (state.ctx, state.doc, pageno);
1094 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1096 fz_close_device (state.ctx, tdev);
1097 fz_drop_device (state.ctx, tdev);
1099 if (forward) {
1100 for (block = text->first_block; block; block = block->next) {
1101 fz_stext_line *line;
1103 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1104 for (line = block->u.t.first_line; line; line = line->next) {
1105 if (line->bbox.y0 < y + 1) continue;
1107 switch (matchline (re, line, stop, pageno, start)) {
1108 case 0: break;
1109 case 1: stop = 1; break;
1110 case -1: stop = 1; goto endloop;
1115 else {
1116 for (block = text->last_block; block; block = block->prev) {
1117 fz_stext_line *line;
1119 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1120 for (line = block->u.t.last_line; line; line = line->prev) {
1121 if (line->bbox.y0 < y + 1) continue;
1123 switch (matchline (re, line, stop, pageno, start)) {
1124 case 0: break;
1125 case 1: stop = 1; break;
1126 case -1: stop = 1; goto endloop;
1132 if (forward) {
1133 pageno += 1;
1134 y = 0;
1136 else {
1137 pageno -= 1;
1138 y = INT_MAX;
1140 endloop:
1141 fz_drop_stext_page (state.ctx, text);
1142 fz_drop_page (state.ctx, page);
1144 end = now ();
1145 if (!stop) {
1146 printd ("progress 1 no matches %f sec", end - start);
1148 printd ("clearrects");
1151 static void set_tex_params (int colorspace)
1153 switch (colorspace) {
1154 case 0:
1155 state.tex.iform = GL_RGBA8;
1156 state.tex.form = GL_RGBA;
1157 state.tex.ty = GL_UNSIGNED_BYTE;
1158 state.colorspace = fz_device_rgb (state.ctx);
1159 break;
1160 case 1:
1161 state.tex.iform = GL_LUMINANCE_ALPHA;
1162 state.tex.form = GL_LUMINANCE_ALPHA;
1163 state.tex.ty = GL_UNSIGNED_BYTE;
1164 state.colorspace = fz_device_gray (state.ctx);
1165 break;
1166 default:
1167 errx (1, "invalid colorspce %d", colorspace);
1171 static void realloctexts (int texcount)
1173 size_t size;
1175 if (texcount == state.tex.count) return;
1177 if (texcount < state.tex.count) {
1178 glDeleteTextures (state.tex.count - texcount,
1179 state.tex.ids + texcount);
1182 size = texcount * (sizeof (*state.tex.ids) + sizeof (*state.tex.owners));
1183 state.tex.ids = realloc (state.tex.ids, size);
1184 if (!state.tex.ids) {
1185 err (1, "realloc texs %zu", size);
1188 state.tex.owners = (void *) (state.tex.ids + texcount);
1189 if (texcount > state.tex.count) {
1190 glGenTextures (texcount - state.tex.count,
1191 state.tex.ids + state.tex.count);
1192 for (int i = state.tex.count; i < texcount; ++i) {
1193 state.tex.owners[i].w = -1;
1194 state.tex.owners[i].slice = NULL;
1197 state.tex.count = texcount;
1198 state.tex.index = 0;
1201 static char *mbtoutf8 (char *s)
1203 char *p, *r;
1204 wchar_t *tmp;
1205 size_t i, ret, len;
1207 if (state.utf8cs) {
1208 return s;
1211 len = mbstowcs (NULL, s, strlen (s));
1212 if (len == 0 || len == (size_t) -1) {
1213 if (len)
1214 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1215 return s;
1218 tmp = calloc (len, sizeof (wchar_t));
1219 if (!tmp) {
1220 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1221 len, sizeof (wchar_t), errno, strerror (errno));
1222 return s;
1225 ret = mbstowcs (tmp, s, len);
1226 if (ret == (size_t) -1) {
1227 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1228 len, errno, strerror (errno));
1229 free (tmp);
1230 return s;
1233 len = 0;
1234 for (i = 0; i < ret; ++i) {
1235 len += fz_runelen (tmp[i]);
1238 p = r = malloc (len + 1);
1239 if (!r) {
1240 printd ("emsg mbtoutf8: malloc(%zu)", len);
1241 free (tmp);
1242 return s;
1245 for (i = 0; i < ret; ++i) {
1246 p += fz_runetochar (p, tmp[i]);
1248 *p = 0;
1249 free (tmp);
1250 return r;
1253 ML (mbtoutf8 (value s_v))
1255 CAMLparam1 (s_v);
1256 CAMLlocal1 (ret_v);
1257 char *s, *r;
1259 s = &Byte (s_v, 0);
1260 r = mbtoutf8 (s);
1261 if (r == s) {
1262 ret_v = s_v;
1264 else {
1265 ret_v = caml_copy_string (r);
1266 free (r);
1268 CAMLreturn (ret_v);
1271 static void * mainloop (void UNUSED_ATTR *unused)
1273 char *p = NULL;
1274 int len, ret, oldlen = 0;
1276 fz_var (p);
1277 fz_var (oldlen);
1278 for (;;) {
1279 len = readlen (state.csock);
1280 if (len == 0) {
1281 errx (1, "readlen returned 0");
1284 if (oldlen < len + 1) {
1285 p = realloc (p, len + 1);
1286 if (!p) {
1287 err (1, "realloc %d failed", len + 1);
1289 oldlen = len + 1;
1291 readdata (state.csock, p, len);
1292 p[len] = 0;
1294 if (!strncmp ("open", p, 4)) {
1295 int off, usedoccss, ok = 0, layouth;
1296 char *password;
1297 char *filename;
1298 char *utf8filename;
1299 size_t filenamelen;
1301 fz_var (ok);
1302 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1303 if (ret != 2) {
1304 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1307 filename = p + 5 + off;
1308 filenamelen = strlen (filename);
1309 password = filename + filenamelen + 1;
1311 if (password[strlen (password) + 1]) {
1312 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1315 lock ("open");
1316 fz_set_use_document_css (state.ctx, usedoccss);
1317 fz_try (state.ctx) {
1318 ok = openxref (filename, password, layouth);
1320 fz_catch (state.ctx) {
1321 utf8filename = mbtoutf8 (filename);
1322 printd ("emsg Error loading %s: %s",
1323 utf8filename, fz_caught_message (state.ctx));
1324 if (utf8filename != filename) {
1325 free (utf8filename);
1328 if (ok) {
1329 docinfo ();
1330 initpdims ();
1332 unlock ("open");
1333 state.needoutline = ok;
1335 else if (!strncmp ("cs", p, 2)) {
1336 int i, colorspace;
1338 ret = sscanf (p + 2, " %d", &colorspace);
1339 if (ret != 1) {
1340 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1342 lock ("cs");
1343 set_tex_params (colorspace);
1344 for (i = 0; i < state.tex.count; ++i) {
1345 state.tex.owners[i].w = -1;
1346 state.tex.owners[i].slice = NULL;
1348 unlock ("cs");
1350 else if (!strncmp ("freepage", p, 8)) {
1351 void *ptr;
1353 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1354 if (ret != 1) {
1355 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1357 lock ("freepage");
1358 freepage (ptr);
1359 unlock ("freepage");
1361 else if (!strncmp ("freetile", p, 8)) {
1362 void *ptr;
1364 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1365 if (ret != 1) {
1366 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1368 lock ("freetile");
1369 freetile (ptr);
1370 unlock ("freetile");
1372 else if (!strncmp ("search", p, 6)) {
1373 int icase, pageno, y, len2, forward;
1374 char *pattern;
1375 regex_t re;
1377 ret = sscanf (p + 6, " %d %d %d %d,%n",
1378 &icase, &pageno, &y, &forward, &len2);
1379 if (ret != 4) {
1380 errx (1, "malformed search `%s' ret=%d", p, ret);
1383 pattern = p + 6 + len2;
1384 ret = regcomp (&re, pattern,
1385 REG_EXTENDED | (icase ? REG_ICASE : 0));
1386 if (ret) {
1387 char errbuf[80];
1388 size_t size;
1390 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1391 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1393 else {
1394 lock ("search");
1395 search (&re, pageno, y, forward);
1396 unlock ("search");
1397 regfree (&re);
1400 else if (!strncmp ("geometry", p, 8)) {
1401 int w, h, fitmodel;
1403 printd ("clear");
1404 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1405 if (ret != 3) {
1406 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1409 lock ("geometry");
1410 state.h = h;
1411 if (w != state.w) {
1412 state.w = w;
1413 for (int i = 0; i < state.tex.count; ++i) {
1414 state.tex.owners[i].slice = NULL;
1417 state.fitmodel = fitmodel;
1418 layout ();
1419 process_outline ();
1421 state.gen++;
1422 unlock ("geometry");
1423 printd ("continue %d", state.pagecount);
1425 else if (!strncmp ("reqlayout", p, 9)) {
1426 char *nameddest;
1427 int rotate, off, h;
1428 int fitmodel;
1429 pdf_document *pdf;
1431 printd ("clear");
1432 ret = sscanf (p + 9, " %d %d %d %n",
1433 &rotate, &fitmodel, &h, &off);
1434 if (ret != 3) {
1435 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1437 lock ("reqlayout");
1438 pdf = pdf_specifics (state.ctx, state.doc);
1439 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1440 state.gen += 1;
1442 state.rotate = rotate;
1443 state.fitmodel = fitmodel;
1444 state.h = h;
1445 layout ();
1446 process_outline ();
1448 nameddest = p + 9 + off;
1449 if (pdf && nameddest && *nameddest) {
1450 fz_point xy;
1451 struct pagedim *pdim;
1452 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1453 &xy.x, &xy.y);
1454 pdim = pdimofpageno (pageno);
1455 xy = fz_transform_point (xy, pdim->ctm);
1456 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1459 state.gen++;
1460 unlock ("reqlayout");
1461 printd ("continue %d", state.pagecount);
1463 else if (!strncmp ("page", p, 4)) {
1464 double a, b;
1465 struct page *page;
1466 int pageno, pindex;
1468 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1469 if (ret != 2) {
1470 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1473 lock ("page");
1474 a = now ();
1475 page = loadpage (pageno, pindex);
1476 b = now ();
1477 unlock ("page");
1479 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1481 else if (!strncmp ("tile", p, 4)) {
1482 int x, y, w, h;
1483 struct page *page;
1484 struct tile *tile;
1485 double a, b;
1486 void *data;
1488 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1489 (uintptr_t *) &page, &x, &y, &w, &h,
1490 (uintptr_t *) &data);
1491 if (ret != 6) {
1492 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1495 lock ("tile");
1496 a = now ();
1497 tile = rendertile (page, x, y, w, h, data);
1498 b = now ();
1499 unlock ("tile");
1501 printd ("tile %d %d %" PRIxPTR " %u %f",
1502 x, y, (uintptr_t) (tile),
1503 tile->w * tile->h * tile->pixmap->n,
1504 b - a);
1506 else if (!strncmp ("trimset", p, 7)) {
1507 fz_irect fuzz;
1508 int trimmargins;
1510 ret = sscanf (p + 7, " %d %d %d %d %d",
1511 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1512 if (ret != 5) {
1513 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1515 lock ("trimset");
1516 state.trimmargins = trimmargins;
1517 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1518 state.trimanew = 1;
1519 state.trimfuzz = fuzz;
1521 unlock ("trimset");
1523 else if (!strncmp ("settrim", p, 7)) {
1524 fz_irect fuzz;
1525 int trimmargins;
1527 ret = sscanf (p + 7, " %d %d %d %d %d",
1528 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1529 if (ret != 5) {
1530 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1532 printd ("clear");
1533 lock ("settrim");
1534 state.trimmargins = trimmargins;
1535 state.needoutline = 1;
1536 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1537 state.trimanew = 1;
1538 state.trimfuzz = fuzz;
1540 state.pagedimcount = 0;
1541 free (state.pagedims);
1542 state.pagedims = NULL;
1543 initpdims ();
1544 layout ();
1545 process_outline ();
1546 unlock ("settrim");
1547 printd ("continue %d", state.pagecount);
1549 else if (!strncmp ("sliceh", p, 6)) {
1550 int h;
1552 ret = sscanf (p + 6, " %d", &h);
1553 if (ret != 1) {
1554 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1556 if (h != state.sliceheight) {
1557 state.sliceheight = h;
1558 for (int i = 0; i < state.tex.count; ++i) {
1559 state.tex.owners[i].w = -1;
1560 state.tex.owners[i].h = -1;
1561 state.tex.owners[i].slice = NULL;
1565 else if (!strncmp ("interrupt", p, 9)) {
1566 printd ("vmsg interrupted");
1568 else {
1569 errx (1, "unknown command %.*s", len, p);
1572 return 0;
1575 ML (isexternallink (value uri_v))
1577 CAMLparam1 (uri_v);
1578 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1579 CAMLreturn (Val_bool (ext));
1582 ML (uritolocation (value uri_v))
1584 CAMLparam1 (uri_v);
1585 CAMLlocal1 (ret_v);
1586 int pageno;
1587 fz_point xy;
1588 struct pagedim *pdim;
1590 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1591 &xy.x, &xy.y).page;
1592 pdim = pdimofpageno (pageno);
1593 xy = fz_transform_point (xy, pdim->ctm);
1594 ret_v = caml_alloc_tuple (3);
1595 Field (ret_v, 0) = Val_int (pageno);
1596 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1597 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1598 CAMLreturn (ret_v);
1601 ML (realloctexts (value texcount_v))
1603 CAMLparam1 (texcount_v);
1604 int ok;
1606 if (trylock (__func__)) {
1607 ok = 0;
1608 goto done;
1610 realloctexts (Int_val (texcount_v));
1611 ok = 1;
1612 unlock (__func__);
1614 done:
1615 CAMLreturn (Val_bool (ok));
1618 static void recti (int x0, int y0, int x1, int y1)
1620 GLfloat *v = state.vertices;
1622 glVertexPointer (2, GL_FLOAT, 0, v);
1623 v[0] = x0; v[1] = y0;
1624 v[2] = x1; v[3] = y0;
1625 v[4] = x0; v[5] = y1;
1626 v[6] = x1; v[7] = y1;
1627 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1630 static void showsel (struct page *page, int ox, int oy)
1632 fz_irect bbox;
1633 fz_rect rect;
1634 fz_stext_block *block;
1635 int seen = 0;
1636 unsigned char selcolor[] = {15,15,15,140};
1638 if (!page->fmark || !page->lmark) return;
1640 glEnable (GL_BLEND);
1641 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1642 glColor4ubv (selcolor);
1644 ox += state.pagedims[page->pdimno].bounds.x0;
1645 oy += state.pagedims[page->pdimno].bounds.y0;
1647 for (block = page->text->first_block; block; block = block->next) {
1648 fz_stext_line *line;
1650 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1651 for (line = block->u.t.first_line; line; line = line->next) {
1652 fz_stext_char *ch;
1654 rect = fz_empty_rect;
1655 for (ch = line->first_char; ch; ch = ch->next) {
1656 fz_rect r;
1657 if (ch == page->fmark) seen = 1;
1658 r = fz_rect_from_quad (ch->quad);
1659 if (seen) rect = fz_union_rect (rect, r);
1660 if (ch == page->lmark) {
1661 bbox = fz_round_rect (rect);
1662 recti (bbox.x0 + ox, bbox.y0 + oy,
1663 bbox.x1 + ox, bbox.y1 + oy);
1664 goto done;
1667 bbox = fz_round_rect (rect);
1668 recti (bbox.x0 + ox, bbox.y0 + oy,
1669 bbox.x1 + ox, bbox.y1 + oy);
1672 done:
1673 glDisable (GL_BLEND);
1676 #pragma GCC diagnostic push
1677 #pragma GCC diagnostic ignored "-Wconversion"
1678 #include "glfont.c"
1679 #pragma GCC diagnostic pop
1681 static void stipplerect (fz_matrix m,
1682 fz_point p1,
1683 fz_point p2,
1684 fz_point p3,
1685 fz_point p4,
1686 GLfloat *texcoords,
1687 GLfloat *vertices)
1689 p1 = fz_transform_point (p1, m);
1690 p2 = fz_transform_point (p2, m);
1691 p3 = fz_transform_point (p3, m);
1692 p4 = fz_transform_point (p4, m);
1694 float w, h, s, t;
1696 w = p2.x - p1.x;
1697 h = p2.y - p1.y;
1698 t = hypotf (w, h) * .25f;
1700 w = p3.x - p2.x;
1701 h = p3.y - p2.y;
1702 s = hypotf (w, h) * .25f;
1704 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1705 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1707 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1708 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1710 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1711 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1713 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1714 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1716 glDrawArrays (GL_LINES, 0, 8);
1719 static void solidrect (fz_matrix m,
1720 fz_point p1,
1721 fz_point p2,
1722 fz_point p3,
1723 fz_point p4,
1724 GLfloat *vertices)
1726 p1 = fz_transform_point (p1, m);
1727 p2 = fz_transform_point (p2, m);
1728 p3 = fz_transform_point (p3, m);
1729 p4 = fz_transform_point (p4, m);
1730 vertices[0] = p1.x; vertices[1] = p1.y;
1731 vertices[2] = p2.x; vertices[3] = p2.y;
1733 vertices[4] = p3.x; vertices[5] = p3.y;
1734 vertices[6] = p4.x; vertices[7] = p4.y;
1735 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1738 static void ensurelinks (struct page *page)
1740 if (!page->links)
1741 page->links = fz_load_links (state.ctx, page->fzpage);
1744 static void highlightlinks (struct page *page, int xoff, int yoff)
1746 fz_matrix ctm;
1747 fz_link *link;
1748 GLfloat *texcoords = state.texcoords;
1749 GLfloat *vertices = state.vertices;
1751 ensurelinks (page);
1753 glEnable (GL_TEXTURE_1D);
1754 glEnable (GL_BLEND);
1755 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1756 glBindTexture (GL_TEXTURE_1D, state.stid);
1758 xoff -= state.pagedims[page->pdimno].bounds.x0;
1759 yoff -= state.pagedims[page->pdimno].bounds.y0;
1760 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1762 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1763 glVertexPointer (2, GL_FLOAT, 0, vertices);
1765 for (link = page->links; link; link = link->next) {
1766 fz_point p1, p2, p3, p4;
1768 p1.x = link->rect.x0;
1769 p1.y = link->rect.y0;
1771 p2.x = link->rect.x1;
1772 p2.y = link->rect.y0;
1774 p3.x = link->rect.x1;
1775 p3.y = link->rect.y1;
1777 p4.x = link->rect.x0;
1778 p4.y = link->rect.y1;
1780 /* TODO: different colours for different schemes */
1781 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1782 else glColor3ub (255, 0, 0);
1784 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1787 for (int i = 0; i < page->annotcount; ++i) {
1788 fz_point p1, p2, p3, p4;
1789 struct annot *annot = &page->annots[i];
1791 p1.x = annot->bbox.x0;
1792 p1.y = annot->bbox.y0;
1794 p2.x = annot->bbox.x1;
1795 p2.y = annot->bbox.y0;
1797 p3.x = annot->bbox.x1;
1798 p3.y = annot->bbox.y1;
1800 p4.x = annot->bbox.x0;
1801 p4.y = annot->bbox.y1;
1803 glColor3ub (0, 0, 128);
1804 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1807 glDisable (GL_BLEND);
1808 glDisable (GL_TEXTURE_1D);
1811 static int compareslinks (const void *l, const void *r)
1813 struct slink const *ls = l;
1814 struct slink const *rs = r;
1815 if (ls->bbox.y0 == rs->bbox.y0) {
1816 return ls->bbox.x0 - rs->bbox.x0;
1818 return ls->bbox.y0 - rs->bbox.y0;
1821 static void droptext (struct page *page)
1823 if (page->text) {
1824 fz_drop_stext_page (state.ctx, page->text);
1825 page->fmark = NULL;
1826 page->lmark = NULL;
1827 page->text = NULL;
1831 static void dropannots (struct page *page)
1833 if (page->annots) {
1834 free (page->annots);
1835 page->annots = NULL;
1836 page->annotcount = 0;
1840 static void ensureannots (struct page *page)
1842 int i, count = 0;
1843 size_t annotsize = sizeof (*page->annots);
1844 pdf_annot *annot;
1845 pdf_document *pdf;
1846 pdf_page *pdfpage;
1848 pdf = pdf_specifics (state.ctx, state.doc);
1849 if (!pdf) return;
1851 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1852 if (state.gen != page->agen) {
1853 dropannots (page);
1854 page->agen = state.gen;
1856 if (page->annots) return;
1858 for (annot = pdf_first_annot (state.ctx, pdfpage);
1859 annot;
1860 annot = pdf_next_annot (state.ctx, annot)) {
1861 count++;
1864 if (count > 0) {
1865 page->annotcount = count;
1866 page->annots = calloc (count, annotsize);
1867 if (!page->annots) {
1868 err (1, "calloc annots %d", count);
1871 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1872 annot;
1873 annot = pdf_next_annot (state.ctx, annot), i++) {
1874 fz_rect rect;
1876 rect = pdf_bound_annot (state.ctx, annot);
1877 page->annots[i].annot = annot;
1878 page->annots[i].bbox = fz_round_rect (rect);
1883 static void dropslinks (struct page *page)
1885 if (page->slinks) {
1886 free (page->slinks);
1887 page->slinks = NULL;
1888 page->slinkcount = 0;
1890 if (page->links) {
1891 fz_drop_link (state.ctx, page->links);
1892 page->links = NULL;
1896 static void ensureslinks (struct page *page)
1898 fz_matrix ctm;
1899 int i, count;
1900 size_t slinksize = sizeof (*page->slinks);
1901 fz_link *link;
1903 ensureannots (page);
1904 if (state.gen != page->sgen) {
1905 dropslinks (page);
1906 page->sgen = state.gen;
1908 if (page->slinks) return;
1910 ensurelinks (page);
1911 ctm = pagectm (page);
1913 count = page->annotcount;
1914 for (link = page->links; link; link = link->next) {
1915 count++;
1917 if (count > 0) {
1918 int j;
1920 page->slinkcount = count;
1921 page->slinks = calloc (count, slinksize);
1922 if (!page->slinks) {
1923 err (1, "calloc slinks %d", count);
1926 for (i = 0, link = page->links; link; ++i, link = link->next) {
1927 fz_rect rect;
1929 rect = link->rect;
1930 rect = fz_transform_rect (rect, ctm);
1931 page->slinks[i].tag = SLINK;
1932 page->slinks[i].u.link = link;
1933 page->slinks[i].bbox = fz_round_rect (rect);
1935 for (j = 0; j < page->annotcount; ++j, ++i) {
1936 fz_rect rect;
1937 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1938 rect = fz_transform_rect (rect, ctm);
1939 page->slinks[i].bbox = fz_round_rect (rect);
1941 page->slinks[i].tag = SANNOT;
1942 page->slinks[i].u.annot = page->annots[j].annot;
1944 qsort (page->slinks, count, slinksize, compareslinks);
1948 static void highlightslinks (struct page *page, int xoff, int yoff,
1949 int noff, const char *targ,
1950 mlsize_t tlen, int hfsize)
1952 char buf[40];
1953 struct slink *slink;
1954 float x0, y0, x1, y1, w;
1956 ensureslinks (page);
1957 glColor3ub (0xc3, 0xb0, 0x91);
1958 for (int i = 0; i < page->slinkcount; ++i) {
1959 fmt_linkn (buf, i + noff);
1960 if (!tlen || !strncmp (targ, buf, tlen)) {
1961 slink = &page->slinks[i];
1963 x0 = slink->bbox.x0 + xoff - 5;
1964 y1 = slink->bbox.y0 + yoff - 5;
1965 y0 = y1 + 10 + hfsize;
1966 w = measure_string (state.face, hfsize, buf);
1967 x1 = x0 + w + 10;
1968 recti ((int) x0, (int) y0, (int) x1, (int) y1);
1972 glEnable (GL_BLEND);
1973 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1974 glEnable (GL_TEXTURE_2D);
1975 glColor3ub (0, 0, 0);
1976 for (int i = 0; i < page->slinkcount; ++i) {
1977 fmt_linkn (buf, i + noff);
1978 if (!tlen || !strncmp (targ, buf, tlen)) {
1979 slink = &page->slinks[i];
1981 x0 = slink->bbox.x0 + xoff;
1982 y0 = slink->bbox.y0 + yoff + hfsize;
1983 draw_string (state.face, hfsize, x0, y0, buf);
1986 glDisable (GL_TEXTURE_2D);
1987 glDisable (GL_BLEND);
1990 static void uploadslice (struct tile *tile, struct slice *slice)
1992 int offset;
1993 struct slice *slice1;
1994 unsigned char *texdata;
1996 offset = 0;
1997 for (slice1 = tile->slices; slice != slice1; slice1++) {
1998 offset += slice1->h * tile->w * tile->pixmap->n;
2000 if (slice->texindex != -1 && slice->texindex < state.tex.count
2001 && state.tex.owners[slice->texindex].slice == slice) {
2002 glBindTexture (TEXT_TYPE, state.tex.ids[slice->texindex]);
2004 else {
2005 int subimage = 0;
2006 int texindex = state.tex.index++ % state.tex.count;
2008 if (state.tex.owners[texindex].w == tile->w) {
2009 if (state.tex.owners[texindex].h >= slice->h) {
2010 subimage = 1;
2012 else {
2013 state.tex.owners[texindex].h = slice->h;
2016 else {
2017 state.tex.owners[texindex].h = slice->h;
2020 state.tex.owners[texindex].w = tile->w;
2021 state.tex.owners[texindex].slice = slice;
2022 slice->texindex = texindex;
2024 glBindTexture (TEXT_TYPE, state.tex.ids[texindex]);
2025 #if TEXT_TYPE == GL_TEXTURE_2D
2026 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2027 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2028 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2029 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2030 #endif
2031 if (tile->pbo) {
2032 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2033 texdata = 0;
2035 else {
2036 texdata = tile->pixmap->samples;
2038 if (subimage) {
2039 glTexSubImage2D (TEXT_TYPE,
2043 tile->w,
2044 slice->h,
2045 state.tex.form,
2046 state.tex.ty,
2047 texdata+offset
2050 else {
2051 glTexImage2D (TEXT_TYPE,
2053 state.tex.iform,
2054 tile->w,
2055 slice->h,
2057 state.tex.form,
2058 state.tex.ty,
2059 texdata+offset
2062 if (tile->pbo) {
2063 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2068 ML0 (begintiles (void))
2070 glEnable (TEXT_TYPE);
2071 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2072 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2075 ML0 (endtiles (void))
2077 glDisable (TEXT_TYPE);
2080 ML0 (drawtile (value args_v, value ptr_v))
2082 CAMLparam2 (args_v, ptr_v);
2083 int dispx = Int_val (Field (args_v, 0));
2084 int dispy = Int_val (Field (args_v, 1));
2085 int dispw = Int_val (Field (args_v, 2));
2086 int disph = Int_val (Field (args_v, 3));
2087 int tilex = Int_val (Field (args_v, 4));
2088 int tiley = Int_val (Field (args_v, 5));
2089 const char *s = String_val (ptr_v);
2090 struct tile *tile = parse_pointer (__func__, s);
2091 int slicey, firstslice;
2092 struct slice *slice;
2093 GLfloat *texcoords = state.texcoords;
2094 GLfloat *vertices = state.vertices;
2096 firstslice = tiley / tile->sliceheight;
2097 slice = &tile->slices[firstslice];
2098 slicey = tiley % tile->sliceheight;
2100 while (disph > 0) {
2101 int dh;
2103 dh = slice->h - slicey;
2104 dh = fz_mini (disph, dh);
2105 uploadslice (tile, slice);
2107 texcoords[0] = tilex; texcoords[1] = slicey;
2108 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2109 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2110 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2112 vertices[0] = dispx; vertices[1] = dispy;
2113 vertices[2] = dispx+dispw; vertices[3] = dispy;
2114 vertices[4] = dispx; vertices[5] = dispy+dh;
2115 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2117 #if TEXT_TYPE == GL_TEXTURE_2D
2118 for (int i = 0; i < 8; ++i) {
2119 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2121 #endif
2123 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2124 dispy += dh;
2125 disph -= dh;
2126 slice++;
2127 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2128 slicey = 0;
2130 CAMLreturn0;
2133 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2135 fz_matrix ctm;
2136 fz_point p1, p2, p3, p4;
2137 GLfloat *vertices = state.vertices;
2139 xoff -= state.pagedims[page->pdimno].bounds.x0;
2140 yoff -= state.pagedims[page->pdimno].bounds.y0;
2141 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2143 glEnable (GL_BLEND);
2144 glVertexPointer (2, GL_FLOAT, 0, vertices);
2146 glColor4d (
2147 Double_array_field (rects_v, 0),
2148 Double_array_field (rects_v, 1),
2149 Double_array_field (rects_v, 2),
2150 Double_array_field (rects_v, 3)
2152 p1.x = (float) Double_array_field (rects_v, 4);
2153 p1.y = (float) Double_array_field (rects_v, 5);
2155 p2.x = (float) Double_array_field (rects_v, 6);
2156 p2.y = p1.y;
2158 p3.x = p2.x;
2159 p3.y = (float) Double_array_field (rects_v, 7);
2161 p4.x = p1.x;
2162 p4.y = p3.y;
2163 solidrect (ctm, p1, p2, p3, p4, vertices);
2164 glDisable (GL_BLEND);
2167 ML (postprocess (value ptr_v, value hlinks_v,
2168 value xoff_v, value yoff_v,
2169 value li_v))
2171 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2172 int xoff = Int_val (xoff_v);
2173 int yoff = Int_val (yoff_v);
2174 int noff = Int_val (Field (li_v, 0));
2175 const char *targ = String_val (Field (li_v, 1));
2176 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2177 int hfsize = Int_val (Field (li_v, 2));
2178 const char *s = String_val (ptr_v);
2179 int hlmask = Int_val (hlinks_v);
2180 struct page *page = parse_pointer (__func__, s);
2182 if (!page->fzpage) {
2183 /* deal with loadpage failed pages */
2184 goto done;
2187 if (trylock (__func__)) {
2188 noff = -1;
2189 goto done;
2192 ensureannots (page);
2193 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2194 if (hlmask & 2) {
2195 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2196 noff = page->slinkcount;
2198 if (page->tgen == state.gen) {
2199 showsel (page, xoff, yoff);
2201 unlock (__func__);
2203 done:
2204 CAMLreturn (Val_int (noff));
2207 ML0 (drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v))
2209 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2210 int xoff = Int_val (xoff_v);
2211 int yoff = Int_val (yoff_v);
2212 const char *s = String_val (ptr_v);
2213 struct page *page = parse_pointer (__func__, s);
2215 drawprect (page, xoff, yoff, rects_v);
2216 CAMLreturn0;
2219 static struct annot *getannot (struct page *page, int x, int y)
2221 fz_point p;
2222 fz_matrix ctm;
2223 const fz_matrix *tctm;
2224 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2226 if (!page->annots) return NULL;
2228 if (pdf) {
2229 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2230 tctm = &state.pagedims[page->pdimno].tctm;
2232 else {
2233 tctm = &fz_identity;
2236 p.x = x;
2237 p.y = y;
2239 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2240 ctm = fz_invert_matrix (ctm);
2241 p = fz_transform_point (p, ctm);
2243 if (pdf) {
2244 for (int i = 0; i < page->annotcount; ++i) {
2245 struct annot *a = &page->annots[i];
2246 fz_rect rect;
2248 rect = pdf_bound_annot (state.ctx, a->annot);
2249 if (p.x >= rect.x0 && p.x <= rect.x1) {
2250 if (p.y >= rect.y0 && p.y <= rect.y1)
2251 return a;
2255 return NULL;
2258 static fz_link *getlink (struct page *page, int x, int y)
2260 fz_point p;
2261 fz_link *link;
2263 ensureslinks (page);
2265 p.x = x;
2266 p.y = y;
2268 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2270 for (link = page->links; link; link = link->next) {
2271 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2272 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2273 return link;
2277 return NULL;
2280 static void ensuretext (struct page *page)
2282 if (state.gen != page->tgen) {
2283 droptext (page);
2284 page->tgen = state.gen;
2286 if (!page->text) {
2287 fz_device *tdev;
2289 page->text = fz_new_stext_page (state.ctx,
2290 state.pagedims[page->pdimno].mediabox);
2291 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2292 fz_run_display_list (state.ctx, page->dlist,
2293 tdev, pagectm (page), fz_infinite_rect, NULL);
2294 fz_close_device (state.ctx, tdev);
2295 fz_drop_device (state.ctx, tdev);
2299 ML (find_page_with_links (value start_page_v, value dir_v))
2301 CAMLparam2 (start_page_v, dir_v);
2302 CAMLlocal1 (ret_v);
2303 int i, dir = Int_val (dir_v);
2304 int start_page = Int_val (start_page_v);
2305 int end_page = dir > 0 ? state.pagecount : -1;
2306 pdf_document *pdf;
2308 fz_var (end_page);
2309 ret_v = Val_int (0);
2310 lock (__func__);
2311 pdf = pdf_specifics (state.ctx, state.doc);
2312 for (i = start_page + dir; i != end_page; i += dir) {
2313 int found;
2315 fz_var (found);
2316 if (pdf) {
2317 pdf_page *page = NULL;
2319 fz_var (page);
2320 fz_try (state.ctx) {
2321 page = pdf_load_page (state.ctx, pdf, i);
2322 found = !!page->links || !!page->annots;
2324 fz_catch (state.ctx) {
2325 found = 0;
2327 if (page) {
2328 fz_drop_page (state.ctx, &page->super);
2331 else {
2332 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2333 fz_link *link = fz_load_links (state.ctx, page);
2334 found = !!link;
2335 fz_drop_link (state.ctx, link);
2336 fz_drop_page (state.ctx, page);
2339 if (found) {
2340 ret_v = caml_alloc_small (1, 1);
2341 Field (ret_v, 0) = Val_int (i);
2342 goto unlock;
2345 unlock:
2346 unlock (__func__);
2347 CAMLreturn (ret_v);
2350 enum { dir_first, dir_last };
2351 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2353 ML (findlink (value ptr_v, value dir_v))
2355 CAMLparam2 (ptr_v, dir_v);
2356 CAMLlocal2 (ret_v, pos_v);
2357 struct page *page;
2358 int dirtag, i, slinkindex;
2359 struct slink *found = NULL ,*slink;
2360 const char *s = String_val (ptr_v);
2362 page = parse_pointer (__func__, s);
2363 ret_v = Val_int (0);
2364 lock (__func__);
2365 ensureslinks (page);
2367 if (Is_block (dir_v)) {
2368 dirtag = Tag_val (dir_v);
2369 switch (dirtag) {
2370 case dir_first_visible:
2372 int x0, y0, dir, first_index, last_index;
2374 pos_v = Field (dir_v, 0);
2375 x0 = Int_val (Field (pos_v, 0));
2376 y0 = Int_val (Field (pos_v, 1));
2377 dir = Int_val (Field (pos_v, 2));
2379 if (dir >= 0) {
2380 dir = 1;
2381 first_index = 0;
2382 last_index = page->slinkcount;
2384 else {
2385 first_index = page->slinkcount - 1;
2386 last_index = -1;
2389 for (i = first_index; i != last_index; i += dir) {
2390 slink = &page->slinks[i];
2391 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2392 found = slink;
2393 break;
2397 break;
2399 case dir_left:
2400 slinkindex = Int_val (Field (dir_v, 0));
2401 found = &page->slinks[slinkindex];
2402 for (i = slinkindex - 1; i >= 0; --i) {
2403 slink = &page->slinks[i];
2404 if (slink->bbox.x0 < found->bbox.x0) {
2405 found = slink;
2406 break;
2409 break;
2411 case dir_right:
2412 slinkindex = Int_val (Field (dir_v, 0));
2413 found = &page->slinks[slinkindex];
2414 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2415 slink = &page->slinks[i];
2416 if (slink->bbox.x0 > found->bbox.x0) {
2417 found = slink;
2418 break;
2421 break;
2423 case dir_down:
2424 slinkindex = Int_val (Field (dir_v, 0));
2425 found = &page->slinks[slinkindex];
2426 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2427 slink = &page->slinks[i];
2428 if (slink->bbox.y0 >= found->bbox.y0) {
2429 found = slink;
2430 break;
2433 break;
2435 case dir_up:
2436 slinkindex = Int_val (Field (dir_v, 0));
2437 found = &page->slinks[slinkindex];
2438 for (i = slinkindex - 1; i >= 0; --i) {
2439 slink = &page->slinks[i];
2440 if (slink->bbox.y0 <= found->bbox.y0) {
2441 found = slink;
2442 break;
2445 break;
2448 else {
2449 dirtag = Int_val (dir_v);
2450 switch (dirtag) {
2451 case dir_first:
2452 found = page->slinks;
2453 break;
2455 case dir_last:
2456 if (page->slinks) {
2457 found = page->slinks + (page->slinkcount - 1);
2459 break;
2462 if (found) {
2463 ret_v = caml_alloc_small (2, 1);
2464 Field (ret_v, 0) = Val_int (found - page->slinks);
2467 unlock (__func__);
2468 CAMLreturn (ret_v);
2471 enum { uuri, utext, uannot };
2473 ML (getlink (value ptr_v, value n_v))
2475 CAMLparam2 (ptr_v, n_v);
2476 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2477 fz_link *link;
2478 struct page *page;
2479 const char *s = String_val (ptr_v);
2480 struct slink *slink;
2482 ret_v = Val_int (0);
2483 page = parse_pointer (__func__, s);
2485 lock (__func__);
2486 ensureslinks (page);
2487 slink = &page->slinks[Int_val (n_v)];
2488 if (slink->tag == SLINK) {
2489 link = slink->u.link;
2490 str_v = caml_copy_string (link->uri);
2491 ret_v = caml_alloc_small (1, uuri);
2492 Field (ret_v, 0) = str_v;
2494 else {
2495 ret_v = caml_alloc_small (1, uannot);
2496 tup_v = caml_alloc_tuple (2);
2497 Field (ret_v, 0) = tup_v;
2498 Field (tup_v, 0) = ptr_v;
2499 Field (tup_v, 1) = n_v;
2501 unlock (__func__);
2503 CAMLreturn (ret_v);
2506 ML (getannotcontents (value ptr_v, value n_v))
2508 CAMLparam2 (ptr_v, n_v);
2509 CAMLlocal1 (ret_v);
2510 pdf_document *pdf;
2511 const char *contents = "";
2513 lock (__func__);
2514 pdf = pdf_specifics (state.ctx, state.doc);
2515 if (pdf) {
2516 const char *s = String_val (ptr_v);
2517 struct page *page;
2518 struct slink *slink;
2520 page = parse_pointer (__func__, s);
2521 slink = &page->slinks[Int_val (n_v)];
2522 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2524 unlock (__func__);
2525 ret_v = caml_copy_string (contents);
2526 CAMLreturn (ret_v);
2529 ML (getlinkcount (value ptr_v))
2531 CAMLparam1 (ptr_v);
2532 struct page *page;
2533 const char *s = String_val (ptr_v);
2535 page = parse_pointer (__func__, s);
2536 CAMLreturn (Val_int (page->slinkcount));
2539 ML (getlinkrect (value ptr_v, value n_v))
2541 CAMLparam2 (ptr_v, n_v);
2542 CAMLlocal1 (ret_v);
2543 struct page *page;
2544 struct slink *slink;
2545 const char *s = String_val (ptr_v);
2547 page = parse_pointer (__func__, s);
2548 ret_v = caml_alloc_tuple (4);
2549 lock (__func__);
2550 ensureslinks (page);
2552 slink = &page->slinks[Int_val (n_v)];
2553 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2554 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2555 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2556 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2557 unlock (__func__);
2558 CAMLreturn (ret_v);
2561 ML (whatsunder (value ptr_v, value x_v, value y_v))
2563 CAMLparam3 (ptr_v, x_v, y_v);
2564 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2565 fz_link *link;
2566 struct annot *annot;
2567 struct page *page;
2568 const char *ptr = String_val (ptr_v);
2569 int x = Int_val (x_v), y = Int_val (y_v);
2570 struct pagedim *pdim;
2572 ret_v = Val_int (0);
2573 if (trylock (__func__)) {
2574 goto done;
2577 page = parse_pointer (__func__, ptr);
2578 pdim = &state.pagedims[page->pdimno];
2579 x += pdim->bounds.x0;
2580 y += pdim->bounds.y0;
2583 annot = getannot (page, x, y);
2584 if (annot) {
2585 int i, n = -1;
2587 ensureslinks (page);
2588 for (i = 0; i < page->slinkcount; ++i) {
2589 if (page->slinks[i].tag == SANNOT
2590 && page->slinks[i].u.annot == annot->annot) {
2591 n = i;
2592 break;
2595 ret_v = caml_alloc_small (1, uannot);
2596 tup_v = caml_alloc_tuple (2);
2597 Field (ret_v, 0) = tup_v;
2598 Field (tup_v, 0) = ptr_v;
2599 Field (tup_v, 1) = Val_int (n);
2600 goto unlock;
2604 link = getlink (page, x, y);
2605 if (link) {
2606 str_v = caml_copy_string (link->uri);
2607 ret_v = caml_alloc_small (1, uuri);
2608 Field (ret_v, 0) = str_v;
2610 else {
2611 fz_rect *b;
2612 fz_stext_block *block;
2614 ensuretext (page);
2616 for (block = page->text->first_block; block; block = block->next) {
2617 fz_stext_line *line;
2619 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2620 b = &block->bbox;
2621 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2622 continue;
2624 for (line = block->u.t.first_line; line; line = line->next) {
2625 fz_stext_char *ch;
2627 b = &line->bbox;
2628 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2629 continue;
2631 for (ch = line->first_char; ch; ch = ch->next) {
2632 fz_quad *q = &ch->quad;
2634 if (x >= q->ul.x && x <= q->ur.x
2635 && y >= q->ul.y && y <= q->ll.y) {
2636 const char *n2 = fz_font_name (state.ctx, ch->font);
2637 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2638 ch->font);
2640 if (!n2) n2 = "<unknown font>";
2642 if (face && face->family_name) {
2643 char *s;
2644 char *n1 = face->family_name;
2645 size_t l1 = strlen (n1);
2646 size_t l2 = strlen (n2);
2648 if (l1 != l2 || memcmp (n1, n2, l1)) {
2649 s = malloc (l1 + l2 + 2);
2650 if (s) {
2651 memcpy (s, n2, l2);
2652 s[l2] = '=';
2653 memcpy (s + l2 + 1, n1, l1 + 1);
2654 str_v = caml_copy_string (s);
2655 free (s);
2659 if (str_v == Val_unit) {
2660 str_v = caml_copy_string (n2);
2662 ret_v = caml_alloc_small (1, utext);
2663 Field (ret_v, 0) = str_v;
2664 goto unlock;
2670 unlock:
2671 unlock (__func__);
2673 done:
2674 CAMLreturn (ret_v);
2677 enum { mark_page, mark_block, mark_line, mark_word };
2679 ML0 (clearmark (value ptr_v))
2681 CAMLparam1 (ptr_v);
2682 const char *s = String_val (ptr_v);
2683 struct page *page;
2685 if (trylock (__func__)) {
2686 goto done;
2689 page = parse_pointer (__func__, s);
2690 page->fmark = NULL;
2691 page->lmark = NULL;
2693 unlock (__func__);
2694 done:
2695 CAMLreturn0;
2698 static int uninteresting (int c)
2700 return isspace (c) || ispunct (c);
2703 ML (markunder (value ptr_v, value x_v, value y_v, value mark_v))
2705 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2706 CAMLlocal1 (ret_v);
2707 fz_rect *b;
2708 struct page *page;
2709 fz_stext_line *line;
2710 fz_stext_block *block;
2711 struct pagedim *pdim;
2712 int mark = Int_val (mark_v);
2713 const char *s = String_val (ptr_v);
2714 int x = Int_val (x_v), y = Int_val (y_v);
2716 ret_v = Val_bool (0);
2717 if (trylock (__func__)) {
2718 goto done;
2721 page = parse_pointer (__func__, s);
2722 pdim = &state.pagedims[page->pdimno];
2724 ensuretext (page);
2726 if (mark == mark_page) {
2727 page->fmark = page->text->first_block->u.t.first_line->first_char;
2728 page->lmark = page->text->last_block->u.t.last_line->last_char;
2729 ret_v = Val_bool (1);
2730 goto unlock;
2733 x += pdim->bounds.x0;
2734 y += pdim->bounds.y0;
2736 for (block = page->text->first_block; block; block = block->next) {
2737 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2738 b = &block->bbox;
2739 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2740 continue;
2742 if (mark == mark_block) {
2743 page->fmark = block->u.t.first_line->first_char;
2744 page->lmark = block->u.t.last_line->last_char;
2745 ret_v = Val_bool (1);
2746 goto unlock;
2749 for (line = block->u.t.first_line; line; line = line->next) {
2750 fz_stext_char *ch;
2752 b = &line->bbox;
2753 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2754 continue;
2756 if (mark == mark_line) {
2757 page->fmark = line->first_char;
2758 page->lmark = line->last_char;
2759 ret_v = Val_bool (1);
2760 goto unlock;
2763 for (ch = line->first_char; ch; ch = ch->next) {
2764 fz_stext_char *ch2, *first = NULL, *last = NULL;
2765 fz_quad *q = &ch->quad;
2766 if (x >= q->ul.x && x <= q->ur.x
2767 && y >= q->ul.y && y <= q->ll.y) {
2768 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2769 if (uninteresting (ch2->c)) first = NULL;
2770 else if (!first) first = ch2;
2772 for (ch2 = ch; ch2; ch2 = ch2->next) {
2773 if (uninteresting (ch2->c)) break;
2774 last = ch2;
2777 page->fmark = first;
2778 page->lmark = last;
2779 ret_v = Val_bool (1);
2780 goto unlock;
2785 unlock:
2786 if (!Bool_val (ret_v)) {
2787 page->fmark = NULL;
2788 page->lmark = NULL;
2790 unlock (__func__);
2792 done:
2793 CAMLreturn (ret_v);
2796 ML (rectofblock (value ptr_v, value x_v, value y_v))
2798 CAMLparam3 (ptr_v, x_v, y_v);
2799 CAMLlocal2 (ret_v, res_v);
2800 fz_rect *b = NULL;
2801 struct page *page;
2802 struct pagedim *pdim;
2803 fz_stext_block *block;
2804 const char *s = String_val (ptr_v);
2805 int x = Int_val (x_v), y = Int_val (y_v);
2807 ret_v = Val_int (0);
2808 if (trylock (__func__)) {
2809 goto done;
2812 page = parse_pointer (__func__, s);
2813 pdim = &state.pagedims[page->pdimno];
2814 x += pdim->bounds.x0;
2815 y += pdim->bounds.y0;
2817 ensuretext (page);
2819 for (block = page->text->first_block; block; block = block->next) {
2820 switch (block->type) {
2821 case FZ_STEXT_BLOCK_TEXT:
2822 b = &block->bbox;
2823 break;
2825 case FZ_STEXT_BLOCK_IMAGE:
2826 b = &block->bbox;
2827 break;
2829 default:
2830 continue;
2833 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2834 break;
2835 b = NULL;
2837 if (b) {
2838 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2839 ret_v = caml_alloc_small (1, 1);
2840 Store_double_field (res_v, 0, (double) b->x0);
2841 Store_double_field (res_v, 1, (double) b->x1);
2842 Store_double_field (res_v, 2, (double) b->y0);
2843 Store_double_field (res_v, 3, (double) b->y1);
2844 Field (ret_v, 0) = res_v;
2846 unlock (__func__);
2848 done:
2849 CAMLreturn (ret_v);
2852 ML0 (seltext (value ptr_v, value rect_v))
2854 CAMLparam2 (ptr_v, rect_v);
2855 struct page *page;
2856 struct pagedim *pdim;
2857 const char *s = String_val (ptr_v);
2858 int x0, x1, y0, y1;
2859 fz_stext_char *ch;
2860 fz_stext_line *line;
2861 fz_stext_block *block;
2862 fz_stext_char *fc, *lc;
2864 if (trylock (__func__)) {
2865 goto done;
2868 page = parse_pointer (__func__, s);
2869 ensuretext (page);
2871 pdim = &state.pagedims[page->pdimno];
2872 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2873 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2874 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2875 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2877 if (y0 > y1) {
2878 int t = y0;
2879 y0 = y1;
2880 y1 = t;
2881 x0 = x1;
2882 x1 = t;
2885 fc = page->fmark;
2886 lc = page->lmark;
2888 for (block = page->text->first_block; block; block = block->next) {
2889 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2890 for (line = block->u.t.first_line; line; line = line->next) {
2891 for (ch = line->first_char; ch; ch = ch->next) {
2892 fz_quad q = ch->quad;
2893 if (x0 >= q.ul.x && x0 <= q.ur.x
2894 && y0 >= q.ul.y && y0 <= q.ll.y) {
2895 fc = ch;
2897 if (x1 >= q.ul.x && x1 <= q.ur.x
2898 && y1 >= q.ul.y && y1 <= q.ll.y) {
2899 lc = ch;
2904 if (x1 < x0 && fc == lc) {
2905 fz_stext_char *t;
2907 t = fc;
2908 fc = lc;
2909 lc = t;
2912 page->fmark = fc;
2913 page->lmark = lc;
2915 unlock (__func__);
2917 done:
2918 CAMLreturn0;
2921 static int pipechar (FILE *f, fz_stext_char *ch)
2923 char buf[4];
2924 int len;
2925 size_t ret;
2927 len = fz_runetochar (buf, ch->c);
2928 ret = fwrite (buf, len, 1, f);
2929 if (ret != 1) {
2930 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
2931 len, ret, errno, strerror (errno));
2932 return -1;
2934 return 0;
2937 ML (spawn (value command_v, value fds_v))
2939 CAMLparam2 (command_v, fds_v);
2940 CAMLlocal2 (l_v, tup_v);
2941 int ret, ret1;
2942 pid_t pid = (pid_t) -1;
2943 char *msg = NULL;
2944 value earg_v = Nothing;
2945 posix_spawnattr_t attr;
2946 posix_spawn_file_actions_t fa;
2947 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
2949 argv[2] = &Byte (command_v, 0);
2950 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
2951 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
2954 if ((ret = posix_spawnattr_init (&attr)) != 0) {
2955 msg = "posix_spawnattr_init";
2956 goto fail1;
2959 #ifdef POSIX_SPAWN_USEVFORK
2960 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
2961 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
2962 goto fail;
2964 #endif
2966 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
2967 int fd1, fd2;
2969 tup_v = Field (l_v, 0);
2970 fd1 = Int_val (Field (tup_v, 0));
2971 fd2 = Int_val (Field (tup_v, 1));
2972 if (fd2 < 0) {
2973 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
2974 msg = "posix_spawn_file_actions_addclose";
2975 earg_v = tup_v;
2976 goto fail;
2979 else {
2980 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
2981 msg = "posix_spawn_file_actions_adddup2";
2982 earg_v = tup_v;
2983 goto fail;
2988 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
2989 msg = "posix_spawn";
2990 goto fail;
2993 fail:
2994 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
2995 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
2998 fail1:
2999 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3000 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3001 ret1, strerror (ret1));
3004 if (msg)
3005 unix_error (ret, msg, earg_v);
3007 CAMLreturn (Val_int (pid));
3010 ML (hassel (value ptr_v))
3012 CAMLparam1 (ptr_v);
3013 CAMLlocal1 (ret_v);
3014 struct page *page;
3015 const char *s = String_val (ptr_v);
3017 ret_v = Val_bool (0);
3018 if (trylock (__func__)) {
3019 goto done;
3022 page = parse_pointer (__func__, s);
3023 ret_v = Val_bool (page->fmark && page->lmark);
3024 unlock (__func__);
3025 done:
3026 CAMLreturn (ret_v);
3029 ML0 (copysel (value fd_v, value ptr_v))
3031 CAMLparam2 (fd_v, ptr_v);
3032 FILE *f;
3033 int seen = 0;
3034 struct page *page;
3035 fz_stext_line *line;
3036 fz_stext_block *block;
3037 int fd = Int_val (fd_v);
3038 const char *s = String_val (ptr_v);
3040 if (trylock (__func__)) {
3041 goto done;
3044 page = parse_pointer (__func__, s);
3046 if (!page->fmark || !page->lmark) {
3047 printd ("emsg nothing to copy on page %d", page->pageno);
3048 goto unlock;
3051 f = fdopen (fd, "w");
3052 if (!f) {
3053 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3054 fd, errno, strerror (errno));
3055 f = stdout;
3058 for (block = page->text->first_block; block; block = block->next) {
3059 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3060 for (line = block->u.t.first_line; line; line = line->next) {
3061 fz_stext_char *ch;
3062 for (ch = line->first_char; ch; ch = ch->next) {
3063 if (seen || ch == page->fmark) {
3064 do {
3065 pipechar (f, ch);
3066 if (ch == page->lmark) goto close;
3067 } while ((ch = ch->next));
3068 seen = 1;
3069 break;
3072 if (seen) fputc ('\n', f);
3075 close:
3076 if (f != stdout) {
3077 int ret = fclose (f);
3078 fd = -1;
3079 if (ret == -1) {
3080 if (errno != ECHILD) {
3081 printd ("emsg failed to close sel pipe: %d:%s",
3082 errno, strerror (errno));
3086 unlock:
3087 unlock (__func__);
3089 done:
3090 if (fd >= 0) {
3091 if (close (fd)) {
3092 printd ("emsg failed to close sel pipe: %d:%s",
3093 errno, strerror (errno));
3096 CAMLreturn0;
3099 ML (getpdimrect (value pagedimno_v))
3101 CAMLparam1 (pagedimno_v);
3102 CAMLlocal1 (ret_v);
3103 int pagedimno = Int_val (pagedimno_v);
3104 fz_rect box;
3106 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3107 if (trylock (__func__)) {
3108 box = fz_empty_rect;
3110 else {
3111 box = state.pagedims[pagedimno].mediabox;
3112 unlock (__func__);
3115 Store_double_field (ret_v, 0, (double) box.x0);
3116 Store_double_field (ret_v, 1, (double) box.x1);
3117 Store_double_field (ret_v, 2, (double) box.y0);
3118 Store_double_field (ret_v, 3, (double) box.y1);
3120 CAMLreturn (ret_v);
3123 ML (zoom_for_height (value winw_v, value winh_v, value dw_v, value cols_v))
3125 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3126 CAMLlocal1 (ret_v);
3127 int i;
3128 float zoom = -1.;
3129 float maxh = 0.0;
3130 struct pagedim *p;
3131 float winw = Int_val (winw_v);
3132 float winh = Int_val (winh_v);
3133 float dw = Int_val (dw_v);
3134 float cols = Int_val (cols_v);
3135 float pw = 1.0, ph = 1.0;
3137 if (trylock (__func__)) {
3138 goto done;
3141 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3142 float w = p->pagebox.x1 / cols;
3143 float h = p->pagebox.y1;
3144 if (h > maxh) {
3145 maxh = h;
3146 ph = h;
3147 if (state.fitmodel != FitProportional) pw = w;
3149 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3152 zoom = (((winh / ph) * pw) + dw) / winw;
3153 unlock (__func__);
3154 done:
3155 ret_v = caml_copy_double ((double) zoom);
3156 CAMLreturn (ret_v);
3159 ML (getmaxw (value unit_v))
3161 CAMLparam1 (unit_v);
3162 CAMLlocal1 (ret_v);
3163 int i;
3164 float maxw = -1.;
3165 struct pagedim *p;
3167 if (trylock (__func__)) {
3168 goto done;
3171 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3172 float w = p->pagebox.x1;
3173 maxw = fz_max (maxw, w);
3176 unlock (__func__);
3177 done:
3178 ret_v = caml_copy_double ((double) maxw);
3179 CAMLreturn (ret_v);
3182 ML (draw_string (value pt_v, value x_v, value y_v, value string_v))
3184 CAMLparam4 (pt_v, x_v, y_v, string_v);
3185 CAMLlocal1 (ret_v);
3186 int pt = Int_val(pt_v);
3187 int x = Int_val (x_v);
3188 int y = Int_val (y_v);
3189 float w;
3191 w = draw_string (state.face, pt, x, y, String_val (string_v));
3192 ret_v = caml_copy_double (w);
3193 CAMLreturn (ret_v);
3196 ML (measure_string (value pt_v, value string_v))
3198 CAMLparam2 (pt_v, string_v);
3199 CAMLlocal1 (ret_v);
3200 int pt = Int_val (pt_v);
3201 double w;
3203 w = (double) measure_string (state.face, pt, String_val (string_v));
3204 ret_v = caml_copy_double (w);
3205 CAMLreturn (ret_v);
3208 ML (getpagebox (value opaque_v))
3210 CAMLparam1 (opaque_v);
3211 CAMLlocal1 (ret_v);
3212 fz_rect rect;
3213 fz_irect bbox;
3214 fz_device *dev;
3215 const char *s = String_val (opaque_v);
3216 struct page *page = parse_pointer (__func__, s);
3218 ret_v = caml_alloc_tuple (4);
3219 dev = fz_new_bbox_device (state.ctx, &rect);
3221 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3223 fz_close_device (state.ctx, dev);
3224 fz_drop_device (state.ctx, dev);
3225 bbox = fz_round_rect (rect);
3226 Field (ret_v, 0) = Val_int (bbox.x0);
3227 Field (ret_v, 1) = Val_int (bbox.y0);
3228 Field (ret_v, 2) = Val_int (bbox.x1);
3229 Field (ret_v, 3) = Val_int (bbox.y1);
3231 CAMLreturn (ret_v);
3234 ML0 (setaalevel (value level_v))
3236 CAMLparam1 (level_v);
3238 state.aalevel = Int_val (level_v);
3239 CAMLreturn0;
3242 ML0 (setpapercolor (value rgba_v))
3244 CAMLparam1 (rgba_v);
3246 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3247 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3248 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3249 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3250 CAMLreturn0;
3253 value ml_keysymtoutf8 (value keysym_v);
3254 #ifndef CIDER
3255 value ml_keysymtoutf8 (value keysym_v)
3257 CAMLparam1 (keysym_v);
3258 CAMLlocal1 (str_v);
3259 unsigned short keysym = (unsigned short) Int_val (keysym_v);
3260 Rune rune;
3261 extern long keysym2ucs (unsigned short);
3262 int len;
3263 char buf[5];
3265 rune = (Rune) keysym2ucs (keysym);
3266 len = fz_runetochar (buf, rune);
3267 buf[len] = 0;
3268 str_v = caml_copy_string (buf);
3269 CAMLreturn (str_v);
3271 #else
3272 value ml_keysymtoutf8 (value keysym_v)
3274 CAMLparam1 (keysym_v);
3275 CAMLlocal1 (str_v);
3276 long ucs = Long_val (keysym_v);
3277 int len;
3278 char buf[5];
3280 len = fz_runetochar (buf, (int) ucs);
3281 buf[len] = 0;
3282 str_v = caml_copy_string (buf);
3283 CAMLreturn (str_v);
3285 #endif
3287 enum { piunknown, pilinux, pimacos, pibsd };
3289 ML (platform (value unit_v))
3291 CAMLparam1 (unit_v);
3292 CAMLlocal2 (tup_v, arr_v);
3293 int platid = piunknown;
3294 struct utsname buf;
3296 #if defined __linux__
3297 platid = pilinux;
3298 #elif defined __DragonFly__ || defined __FreeBSD__
3299 || defined __OpenBSD__ || defined __NetBSD__
3300 platid = pibsd;
3301 #elif defined __APPLE__
3302 platid = pimacos;
3303 #endif
3304 if (uname (&buf)) err (1, "uname");
3306 tup_v = caml_alloc_tuple (2);
3308 char const *sar[] = {
3309 buf.sysname,
3310 buf.release,
3311 buf.version,
3312 buf.machine,
3313 NULL
3315 arr_v = caml_copy_string_array (sar);
3317 Field (tup_v, 0) = Val_int (platid);
3318 Field (tup_v, 1) = arr_v;
3319 CAMLreturn (tup_v);
3322 ML0 (cloexec (value fd_v))
3324 CAMLparam1 (fd_v);
3325 int fd = Int_val (fd_v);
3327 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3328 uerror ("fcntl", Nothing);
3330 CAMLreturn0;
3333 ML (getpbo (value w_v, value h_v, value cs_v))
3335 CAMLparam2 (w_v, h_v);
3336 CAMLlocal1 (ret_v);
3337 struct bo *pbo;
3338 int w = Int_val (w_v);
3339 int h = Int_val (h_v);
3340 int cs = Int_val (cs_v);
3342 if (state.bo_usable) {
3343 pbo = calloc (sizeof (*pbo), 1);
3344 if (!pbo) {
3345 err (1, "calloc pbo");
3348 switch (cs) {
3349 case 0:
3350 case 1:
3351 pbo->size = w*h*4;
3352 break;
3353 case 2:
3354 pbo->size = w*h*2;
3355 break;
3356 default:
3357 errx (1, "%s: invalid colorspace %d", __func__, cs);
3360 state.glGenBuffersARB (1, &pbo->id);
3361 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3362 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3363 NULL, GL_STREAM_DRAW);
3364 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3365 GL_READ_WRITE);
3366 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3367 if (!pbo->ptr) {
3368 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3369 state.glDeleteBuffersARB (1, &pbo->id);
3370 free (pbo);
3371 ret_v = caml_copy_string ("0");
3373 else {
3374 int res;
3375 char *s;
3377 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3378 if (res < 0) {
3379 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3381 s = malloc (res+1);
3382 if (!s) {
3383 err (1, "malloc %d bytes failed", res+1);
3385 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3386 if (res < 0) {
3387 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3389 ret_v = caml_copy_string (s);
3390 free (s);
3393 else {
3394 ret_v = caml_copy_string ("0");
3396 CAMLreturn (ret_v);
3399 ML0 (freepbo (value s_v))
3401 CAMLparam1 (s_v);
3402 const char *s = String_val (s_v);
3403 struct tile *tile = parse_pointer (__func__, s);
3405 if (tile->pbo) {
3406 state.glDeleteBuffersARB (1, &tile->pbo->id);
3407 tile->pbo->id = -1;
3408 tile->pbo->ptr = NULL;
3409 tile->pbo->size = -1;
3411 CAMLreturn0;
3414 ML0 (unmappbo (value s_v))
3416 CAMLparam1 (s_v);
3417 const char *s = String_val (s_v);
3418 struct tile *tile = parse_pointer (__func__, s);
3420 if (tile->pbo) {
3421 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3422 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3423 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3425 tile->pbo->ptr = NULL;
3426 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3428 CAMLreturn0;
3431 static void setuppbo (void)
3433 extern void (*wsigladdr (const char *name)) (void);
3434 #pragma GCC diagnostic push
3435 #ifdef __clang__
3436 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3437 #endif
3438 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3439 state.bo_usable = GPA (glBindBufferARB)
3440 && GPA (glUnmapBufferARB)
3441 && GPA (glMapBufferARB)
3442 && GPA (glBufferDataARB)
3443 && GPA (glGenBuffersARB)
3444 && GPA (glDeleteBuffersARB);
3445 #undef GPA
3446 #pragma GCC diagnostic pop
3449 ML (bo_usable (void))
3451 return Val_bool (state.bo_usable);
3454 ML (unproject (value ptr_v, value x_v, value y_v))
3456 CAMLparam3 (ptr_v, x_v, y_v);
3457 CAMLlocal2 (ret_v, tup_v);
3458 struct page *page;
3459 const char *s = String_val (ptr_v);
3460 int x = Int_val (x_v), y = Int_val (y_v);
3461 struct pagedim *pdim;
3462 fz_point p;
3464 page = parse_pointer (__func__, s);
3465 pdim = &state.pagedims[page->pdimno];
3467 ret_v = Val_int (0);
3468 if (trylock (__func__)) {
3469 goto done;
3472 p.x = x + pdim->bounds.x0;
3473 p.y = y + pdim->bounds.y0;
3475 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3476 pdim->ctm)));
3478 tup_v = caml_alloc_tuple (2);
3479 ret_v = caml_alloc_small (1, 1);
3480 Field (tup_v, 0) = Val_int (p.x);
3481 Field (tup_v, 1) = Val_int (p.y);
3482 Field (ret_v, 0) = tup_v;
3484 unlock (__func__);
3485 done:
3486 CAMLreturn (ret_v);
3489 ML (project (value ptr_v, value pageno_v, value pdimno_v, value x_v, value y_v))
3491 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3492 CAMLlocal1 (ret_v);
3493 struct page *page;
3494 const char *s = String_val (ptr_v);
3495 int pageno = Int_val (pageno_v);
3496 int pdimno = Int_val (pdimno_v);
3497 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3498 struct pagedim *pdim;
3499 fz_point p;
3500 fz_matrix ctm;
3502 ret_v = Val_int (0);
3503 lock (__func__);
3505 if (!*s) {
3506 page = loadpage (pageno, pdimno);
3508 else {
3509 page = parse_pointer (__func__, s);
3511 pdim = &state.pagedims[pdimno];
3513 if (pdf_specifics (state.ctx, state.doc)) {
3514 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3515 ctm = state.pagedims[page->pdimno].tctm;
3517 else {
3518 ctm = fz_identity;
3520 p.x = x + pdim->bounds.x0;
3521 p.y = y + pdim->bounds.y0;
3523 ctm = fz_concat (pdim->tctm, pdim->ctm);
3524 p = fz_transform_point (p, ctm);
3526 ret_v = caml_alloc_tuple (2);
3527 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3528 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3530 if (!*s) {
3531 freepage (page);
3533 unlock (__func__);
3534 CAMLreturn (ret_v);
3537 ML0 (addannot (value ptr_v, value x_v, value y_v, value contents_v))
3539 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3540 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3542 if (pdf) {
3543 pdf_annot *annot;
3544 struct page *page;
3545 fz_rect r;
3546 const char *s = String_val (ptr_v);
3548 page = parse_pointer (__func__, s);
3549 annot = pdf_create_annot (state.ctx,
3550 pdf_page_from_fz_page (state.ctx,
3551 page->fzpage),
3552 PDF_ANNOT_TEXT);
3553 r.x0 = Int_val (x_v) - 10;
3554 r.y0 = Int_val (y_v) - 10;
3555 r.x1 = r.x0 + 20;
3556 r.y1 = r.y0 + 20;
3557 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3558 pdf_set_annot_rect (state.ctx, annot, r);
3560 state.dirty = 1;
3562 CAMLreturn0;
3565 ML0 (delannot (value ptr_v, value n_v))
3567 CAMLparam2 (ptr_v, n_v);
3568 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3570 if (pdf) {
3571 struct page *page;
3572 const char *s = String_val (ptr_v);
3573 struct slink *slink;
3575 page = parse_pointer (__func__, s);
3576 slink = &page->slinks[Int_val (n_v)];
3577 pdf_delete_annot (state.ctx,
3578 pdf_page_from_fz_page (state.ctx, page->fzpage),
3579 (pdf_annot *) slink->u.annot);
3580 state.dirty = 1;
3582 CAMLreturn0;
3585 ML0 (modannot (value ptr_v, value n_v, value str_v))
3587 CAMLparam3 (ptr_v, n_v, str_v);
3588 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3590 if (pdf) {
3591 struct page *page;
3592 const char *s = String_val (ptr_v);
3593 struct slink *slink;
3595 page = parse_pointer (__func__, s);
3596 slink = &page->slinks[Int_val (n_v)];
3597 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3598 String_val (str_v));
3599 state.dirty = 1;
3601 CAMLreturn0;
3604 ML (hasunsavedchanges (void))
3606 return Val_bool (state.dirty);
3609 ML0 (savedoc (value path_v))
3611 CAMLparam1 (path_v);
3612 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3614 if (pdf) {
3615 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3617 CAMLreturn0;
3620 static void makestippletex (void)
3622 const char pixels[] = "\xff\xff\0\0";
3623 glGenTextures (1, &state.stid);
3624 glBindTexture (GL_TEXTURE_1D, state.stid);
3625 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3626 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3627 glTexImage1D (
3628 GL_TEXTURE_1D,
3630 GL_ALPHA,
3633 GL_ALPHA,
3634 GL_UNSIGNED_BYTE,
3635 pixels
3639 ML (fz_version (void))
3641 return caml_copy_string (FZ_VERSION);
3644 ML (llpp_version (void))
3646 extern char llpp_version[];
3647 return caml_copy_string (llpp_version);
3650 static void diag_callback (void *user, const char *message)
3652 printd ("emsg %s %s", (char *) user, message);
3655 static fz_font *lsff (fz_context *ctx,int UNUSED_ATTR script,
3656 int UNUSED_ATTR language, int UNUSED_ATTR serif,
3657 int UNUSED_ATTR bold, int UNUSED_ATTR italic)
3659 static fz_font *font;
3660 static int done;
3662 if (!done) {
3663 char *path = getenv ("LLPP_FALLBACK_FONT");
3664 if (path) font = fz_new_font_from_file (ctx, NULL, path, 0, 1);
3665 done = 1;
3667 return font;
3670 ML0 (init (value csock_v, value params_v))
3672 CAMLparam2 (csock_v, params_v);
3673 CAMLlocal2 (trim_v, fuzz_v);
3674 int ret;
3675 int texcount;
3676 const char *fontpath;
3677 int colorspace;
3678 int mustoresize;
3680 state.csock = Int_val (csock_v);
3681 state.rotate = Int_val (Field (params_v, 0));
3682 state.fitmodel = Int_val (Field (params_v, 1));
3683 trim_v = Field (params_v, 2);
3684 texcount = Int_val (Field (params_v, 3));
3685 state.sliceheight = Int_val (Field (params_v, 4));
3686 mustoresize = Int_val (Field (params_v, 5));
3687 colorspace = Int_val (Field (params_v, 6));
3688 fontpath = String_val (Field (params_v, 7));
3690 #ifdef CIDER
3691 state.utf8cs = 1;
3692 #else
3693 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3694 if (setlocale (LC_CTYPE, "")) {
3695 const char *cset = nl_langinfo (CODESET);
3696 state.utf8cs = !strcmp (cset, "UTF-8");
3698 else {
3699 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3701 #endif
3703 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3704 fz_register_document_handlers (state.ctx);
3705 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3706 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3707 fz_install_load_system_font_funcs (state.ctx, NULL, NULL, lsff);
3709 state.trimmargins = Bool_val (Field (trim_v, 0));
3710 fuzz_v = Field (trim_v, 1);
3711 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3712 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3713 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3714 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3716 set_tex_params (colorspace);
3718 if (*fontpath) {
3719 state.face = load_font (fontpath);
3721 else {
3722 int len;
3723 const unsigned char *data;
3725 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3726 state.face = load_builtin_font (data, len);
3728 if (!state.face) _exit (1);
3730 realloctexts (texcount);
3731 setuppbo ();
3732 makestippletex ();
3734 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3735 if (ret) {
3736 errx (1, "pthread_create: %s", strerror (ret));
3739 CAMLreturn0;
3742 #if FIXME || !FIXME
3743 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3744 #endif