Persistent dcf
[llpp.git] / link.c
blob4318625252111e779b689c0c5885170a3d3801ce
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;
162 char *dcf;
164 struct {
165 int index, count;
166 GLuint *ids;
167 GLenum iform, form, ty;
168 struct {
169 int w, h;
170 struct slice *slice;
171 } *owners;
172 } tex;
174 fz_colorspace *colorspace;
175 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 initpdims1 (void)
616 struct pagedim *p;
617 pdf_document *pdf;
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 initpdims (void)
833 FILE *f = state.dcf ? fopen (state.dcf, "rb") : NULL;
834 if (f) {
835 size_t nread;
837 nread = fread (&state.pagedimcount, sizeof (state.pagedimcount),
838 1, f);
839 if (nread - 1) {
840 err (1, "fread pagedim %zu", sizeof (state.pagedimcount));
842 size_t size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
843 state.pagedims = realloc (state.pagedims, size);
844 if (!state.pagedims) {
845 err (1, "realloc pagedims to %zu (%d elems)",
846 size, state.pagedimcount + 1);
848 if (fread (state.pagedims,
849 sizeof (*state.pagedims),
850 state.pagedimcount+1,
851 f) - (state.pagedimcount+1)) {
852 err (1, "fread pagedim data %zu %d",
853 sizeof (*state.pagedims), state.pagedimcount+1);
855 fclose (f);
857 if (!state.pagedims) {
858 initpdims1 ();
859 if (state.dcf) {
860 f = fopen (state.dcf, "wb");
861 if (fwrite (&state.pagedimcount,
862 sizeof (state.pagedimcount), 1, f) - 1) {
863 err (1, "fwrite pagedimcunt %zu", sizeof (state.pagedimcount));
865 if (fwrite (state.pagedims, sizeof (*state.pagedims),
866 state.pagedimcount + 1, f)
867 - (state.pagedimcount + 1)) {
868 err (1, "fwrite pagedim data %zu %u",
869 sizeof (*state.pagedims), state.pagedimcount+1);
870 } fclose (f);
875 static void layout (void)
877 int pindex;
878 fz_rect box;
879 fz_matrix ctm;
880 struct pagedim *p = NULL;
881 float zw, w, maxw = 0.0, zoom = 1.0;
883 if (state.pagedimcount == 0) return;
885 switch (state.fitmodel) {
886 case FitProportional:
887 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
888 float x0, x1;
890 p = &state.pagedims[pindex];
891 box = fz_transform_rect (p->mediabox,
892 fz_rotate (p->rotate + state.rotate));
894 x0 = fz_min (box.x0, box.x1);
895 x1 = fz_max (box.x0, box.x1);
897 w = x1 - x0;
898 maxw = fz_max (w, maxw);
899 zoom = state.w / maxw;
901 break;
903 case FitPage:
904 maxw = state.w;
905 break;
907 case FitWidth:
908 break;
910 default:
911 ARSERT (0 && state.fitmodel);
914 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
915 p = &state.pagedims[pindex];
916 ctm = fz_rotate (state.rotate);
917 box = fz_transform_rect (p->mediabox,
918 fz_rotate (p->rotate + state.rotate));
919 w = box.x1 - box.x0;
920 switch (state.fitmodel) {
921 case FitProportional:
922 p->left = (int) (((maxw - w) * zoom) / 2.f);
923 break;
924 case FitPage:
926 float zh, h;
927 zw = maxw / w;
928 h = box.y1 - box.y0;
929 zh = state.h / h;
930 zoom = fz_min (zw, zh);
931 p->left = (int) ((maxw - (w * zoom)) / 2.f);
933 break;
934 case FitWidth:
935 p->left = 0;
936 zoom = state.w / w;
937 break;
940 p->zoomctm = fz_scale (zoom, zoom);
941 ctm = fz_concat (p->zoomctm, ctm);
943 p->pagebox = p->mediabox;
944 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
945 p->pagebox.x1 -= p->pagebox.x0;
946 p->pagebox.y1 -= p->pagebox.y0;
947 p->pagebox.x0 = 0;
948 p->pagebox.y0 = 0;
949 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
950 p->ctm = ctm;
952 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
953 fz_scale (zoom, -zoom));
954 p->tctmready = 0;
957 do {
958 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
959 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
960 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
961 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
962 int boundw = x1 - x0;
963 int boundh = y1 - y0;
965 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
966 } while (p-- != state.pagedims);
969 static struct pagedim *pdimofpageno (int pageno)
971 struct pagedim *pdim = state.pagedims;
973 for (int i = 0; i < state.pagedimcount; ++i) {
974 if (state.pagedims[i].pageno > pageno)
975 break;
976 pdim = &state.pagedims[i];
978 return pdim;
981 static void recurse_outline (fz_outline *outline, int level)
983 while (outline) {
984 if (outline->page >= 0) {
985 fz_point p = {.x = outline->x, .y = outline->y};
986 struct pagedim *pdim = pdimofpageno (outline->page);
987 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
988 p = fz_transform_point (p, pdim->ctm);
989 printd ("o %d %d %d %d %s",
990 level, outline->page, (int) p.y, h, outline->title);
992 else {
993 printd ("on %d %s", level, outline->title);
995 if (outline->down) {
996 recurse_outline (outline->down, level + 1);
998 outline = outline->next;
1002 static void process_outline (void)
1004 fz_outline *outline;
1006 if (!state.needoutline || !state.pagedimcount) return;
1008 state.needoutline = 0;
1009 outline = fz_load_outline (state.ctx, state.doc);
1010 if (outline) {
1011 recurse_outline (outline, 0);
1012 fz_drop_outline (state.ctx, outline);
1016 static char *strofline (fz_stext_line *line)
1018 char *p;
1019 char utf8[10];
1020 fz_stext_char *ch;
1021 size_t size = 0, cap = 80;
1023 p = malloc (cap + 1);
1024 if (!p) return NULL;
1026 for (ch = line->first_char; ch; ch = ch->next) {
1027 int n = fz_runetochar (utf8, ch->c);
1028 if (size + n > cap) {
1029 cap *= 2;
1030 p = realloc (p, cap + 1);
1031 if (!p) return NULL;
1034 memcpy (p + size, utf8, n);
1035 size += n;
1037 p[size] = 0;
1038 return p;
1041 static int matchline (regex_t *re, fz_stext_line *line,
1042 int stop, int pageno, double start)
1044 int ret;
1045 char *p;
1046 regmatch_t rm;
1048 p = strofline (line);
1049 if (!p) return -1;
1051 ret = regexec (re, p, 1, &rm, 0);
1052 if (ret) {
1053 free (p);
1054 if (ret != REG_NOMATCH) {
1055 size_t size;
1056 char errbuf[80];
1057 size = regerror (ret, re, errbuf, sizeof (errbuf));
1058 printd ("msg regexec error `%.*s'",
1059 (int) size, errbuf);
1060 return -1;
1062 return 0;
1064 else {
1065 fz_quad s, e;
1066 fz_stext_char *ch;
1067 int o = 0;
1069 for (ch = line->first_char; ch; ch = ch->next) {
1070 o += fz_runelen (ch->c);
1071 if (o > rm.rm_so) {
1072 s = ch->quad;
1073 break;
1076 for (;ch; ch = ch->next) {
1077 o += fz_runelen (ch->c);
1078 if (o > rm.rm_eo) break;
1080 e = ch->quad;
1082 if (!stop) {
1083 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1084 pageno, 1,
1085 s.ul.x, s.ul.y,
1086 e.ur.x, s.ul.y,
1087 e.lr.x, e.lr.y,
1088 s.ul.x, e.lr.y);
1090 printd ("progress 1 found at %d `%.*s' in %f sec",
1091 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1092 now () - start);
1094 else {
1095 printd ("match %d %d %f %f %f %f %f %f %f %f",
1096 pageno, 2,
1097 s.ul.x, s.ul.y,
1098 e.ur.x, s.ul.y,
1099 e.lr.x, e.lr.y,
1100 s.ul.x, e.lr.y);
1102 free (p);
1103 return 1;
1107 /* wishful thinking function */
1108 static void search (regex_t *re, int pageno, int y, int forward)
1110 fz_device *tdev;
1111 fz_stext_page *text;
1112 struct pagedim *pdim;
1113 int stop = 0, niters = 0;
1114 double start, end;
1115 fz_page *page;
1116 fz_stext_block *block;
1118 start = now ();
1119 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1120 if (niters++ == 5) {
1121 niters = 0;
1122 if (hasdata ()) {
1123 printd ("progress 1 attention requested aborting search at %d",
1124 pageno);
1125 stop = 1;
1127 else {
1128 printd ("progress %f searching in page %d",
1129 (double) (pageno + 1) / state.pagecount,
1130 pageno);
1133 pdim = pdimofpageno (pageno);
1134 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1135 tdev = fz_new_stext_device (state.ctx, text, 0);
1137 page = fz_load_page (state.ctx, state.doc, pageno);
1138 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1140 fz_close_device (state.ctx, tdev);
1141 fz_drop_device (state.ctx, tdev);
1143 if (forward) {
1144 for (block = text->first_block; block; block = block->next) {
1145 fz_stext_line *line;
1147 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1148 for (line = block->u.t.first_line; line; line = line->next) {
1149 if (line->bbox.y0 < y + 1) continue;
1151 switch (matchline (re, line, stop, pageno, start)) {
1152 case 0: break;
1153 case 1: stop = 1; break;
1154 case -1: stop = 1; goto endloop;
1159 else {
1160 for (block = text->last_block; block; block = block->prev) {
1161 fz_stext_line *line;
1163 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1164 for (line = block->u.t.last_line; line; line = line->prev) {
1165 if (line->bbox.y0 < y + 1) continue;
1167 switch (matchline (re, line, stop, pageno, start)) {
1168 case 0: break;
1169 case 1: stop = 1; break;
1170 case -1: stop = 1; goto endloop;
1176 if (forward) {
1177 pageno += 1;
1178 y = 0;
1180 else {
1181 pageno -= 1;
1182 y = INT_MAX;
1184 endloop:
1185 fz_drop_stext_page (state.ctx, text);
1186 fz_drop_page (state.ctx, page);
1188 end = now ();
1189 if (!stop) {
1190 printd ("progress 1 no matches %f sec", end - start);
1192 printd ("clearrects");
1195 static void set_tex_params (int colorspace)
1197 switch (colorspace) {
1198 case 0:
1199 state.tex.iform = GL_RGBA8;
1200 state.tex.form = GL_RGBA;
1201 state.tex.ty = GL_UNSIGNED_BYTE;
1202 state.colorspace = fz_device_rgb (state.ctx);
1203 break;
1204 case 1:
1205 state.tex.iform = GL_LUMINANCE_ALPHA;
1206 state.tex.form = GL_LUMINANCE_ALPHA;
1207 state.tex.ty = GL_UNSIGNED_BYTE;
1208 state.colorspace = fz_device_gray (state.ctx);
1209 break;
1210 default:
1211 errx (1, "invalid colorspce %d", colorspace);
1215 static void realloctexts (int texcount)
1217 size_t size;
1219 if (texcount == state.tex.count) return;
1221 if (texcount < state.tex.count) {
1222 glDeleteTextures (state.tex.count - texcount,
1223 state.tex.ids + texcount);
1226 size = texcount * (sizeof (*state.tex.ids) + sizeof (*state.tex.owners));
1227 state.tex.ids = realloc (state.tex.ids, size);
1228 if (!state.tex.ids) {
1229 err (1, "realloc texs %zu", size);
1232 state.tex.owners = (void *) (state.tex.ids + texcount);
1233 if (texcount > state.tex.count) {
1234 glGenTextures (texcount - state.tex.count,
1235 state.tex.ids + state.tex.count);
1236 for (int i = state.tex.count; i < texcount; ++i) {
1237 state.tex.owners[i].w = -1;
1238 state.tex.owners[i].slice = NULL;
1241 state.tex.count = texcount;
1242 state.tex.index = 0;
1245 static char *mbtoutf8 (char *s)
1247 char *p, *r;
1248 wchar_t *tmp;
1249 size_t i, ret, len;
1251 if (state.utf8cs) {
1252 return s;
1255 len = mbstowcs (NULL, s, strlen (s));
1256 if (len == 0 || len == (size_t) -1) {
1257 if (len)
1258 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1259 return s;
1262 tmp = calloc (len, sizeof (wchar_t));
1263 if (!tmp) {
1264 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1265 len, sizeof (wchar_t), errno, strerror (errno));
1266 return s;
1269 ret = mbstowcs (tmp, s, len);
1270 if (ret == (size_t) -1) {
1271 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1272 len, errno, strerror (errno));
1273 free (tmp);
1274 return s;
1277 len = 0;
1278 for (i = 0; i < ret; ++i) {
1279 len += fz_runelen (tmp[i]);
1282 p = r = malloc (len + 1);
1283 if (!r) {
1284 printd ("emsg mbtoutf8: malloc(%zu)", len);
1285 free (tmp);
1286 return s;
1289 for (i = 0; i < ret; ++i) {
1290 p += fz_runetochar (p, tmp[i]);
1292 *p = 0;
1293 free (tmp);
1294 return r;
1297 ML (mbtoutf8 (value s_v))
1299 CAMLparam1 (s_v);
1300 CAMLlocal1 (ret_v);
1301 char *s, *r;
1303 s = &Byte (s_v, 0);
1304 r = mbtoutf8 (s);
1305 if (r == s) {
1306 ret_v = s_v;
1308 else {
1309 ret_v = caml_copy_string (r);
1310 free (r);
1312 CAMLreturn (ret_v);
1315 static void * mainloop (void UNUSED_ATTR *unused)
1317 char *p = NULL;
1318 int len, ret, oldlen = 0;
1320 fz_var (p);
1321 fz_var (oldlen);
1322 for (;;) {
1323 len = readlen (state.csock);
1324 if (len == 0) {
1325 errx (1, "readlen returned 0");
1328 if (oldlen < len + 1) {
1329 p = realloc (p, len + 1);
1330 if (!p) {
1331 err (1, "realloc %d failed", len + 1);
1333 oldlen = len + 1;
1335 readdata (state.csock, p, len);
1336 p[len] = 0;
1338 if (!strncmp ("open", p, 4)) {
1339 int off, usedoccss, ok = 0, layouth;
1340 char *password;
1341 char *filename;
1342 char *utf8filename;
1343 size_t filenamelen;
1345 fz_var (ok);
1346 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1347 if (ret != 2) {
1348 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1351 filename = p + 5 + off;
1352 filenamelen = strlen (filename);
1353 password = filename + filenamelen + 1;
1355 if (password[strlen (password) + 1]) {
1356 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1359 lock ("open");
1360 fz_set_use_document_css (state.ctx, usedoccss);
1361 fz_try (state.ctx) {
1362 ok = openxref (filename, password, layouth);
1364 fz_catch (state.ctx) {
1365 utf8filename = mbtoutf8 (filename);
1366 printd ("emsg Error loading %s: %s",
1367 utf8filename, fz_caught_message (state.ctx));
1368 if (utf8filename != filename) {
1369 free (utf8filename);
1372 if (ok) {
1373 docinfo ();
1374 initpdims ();
1376 unlock ("open");
1377 state.needoutline = ok;
1379 else if (!strncmp ("cs", p, 2)) {
1380 int i, colorspace;
1382 ret = sscanf (p + 2, " %d", &colorspace);
1383 if (ret != 1) {
1384 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1386 lock ("cs");
1387 set_tex_params (colorspace);
1388 for (i = 0; i < state.tex.count; ++i) {
1389 state.tex.owners[i].w = -1;
1390 state.tex.owners[i].slice = NULL;
1392 unlock ("cs");
1394 else if (!strncmp ("freepage", p, 8)) {
1395 void *ptr;
1397 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1398 if (ret != 1) {
1399 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1401 lock ("freepage");
1402 freepage (ptr);
1403 unlock ("freepage");
1405 else if (!strncmp ("freetile", p, 8)) {
1406 void *ptr;
1408 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1409 if (ret != 1) {
1410 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1412 lock ("freetile");
1413 freetile (ptr);
1414 unlock ("freetile");
1416 else if (!strncmp ("search", p, 6)) {
1417 int icase, pageno, y, len2, forward;
1418 char *pattern;
1419 regex_t re;
1421 ret = sscanf (p + 6, " %d %d %d %d,%n",
1422 &icase, &pageno, &y, &forward, &len2);
1423 if (ret != 4) {
1424 errx (1, "malformed search `%s' ret=%d", p, ret);
1427 pattern = p + 6 + len2;
1428 ret = regcomp (&re, pattern,
1429 REG_EXTENDED | (icase ? REG_ICASE : 0));
1430 if (ret) {
1431 char errbuf[80];
1432 size_t size;
1434 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1435 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1437 else {
1438 lock ("search");
1439 search (&re, pageno, y, forward);
1440 unlock ("search");
1441 regfree (&re);
1444 else if (!strncmp ("geometry", p, 8)) {
1445 int w, h, fitmodel;
1447 printd ("clear");
1448 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1449 if (ret != 3) {
1450 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1453 lock ("geometry");
1454 state.h = h;
1455 if (w != state.w) {
1456 state.w = w;
1457 for (int i = 0; i < state.tex.count; ++i) {
1458 state.tex.owners[i].slice = NULL;
1461 state.fitmodel = fitmodel;
1462 layout ();
1463 process_outline ();
1465 state.gen++;
1466 unlock ("geometry");
1467 printd ("continue %d", state.pagecount);
1469 else if (!strncmp ("reqlayout", p, 9)) {
1470 char *nameddest;
1471 int rotate, off, h;
1472 int fitmodel;
1473 pdf_document *pdf;
1475 printd ("clear");
1476 ret = sscanf (p + 9, " %d %d %d %n",
1477 &rotate, &fitmodel, &h, &off);
1478 if (ret != 3) {
1479 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1481 lock ("reqlayout");
1482 pdf = pdf_specifics (state.ctx, state.doc);
1483 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1484 state.gen += 1;
1486 state.rotate = rotate;
1487 state.fitmodel = fitmodel;
1488 state.h = h;
1489 layout ();
1490 process_outline ();
1492 nameddest = p + 9 + off;
1493 if (pdf && nameddest && *nameddest) {
1494 fz_point xy;
1495 struct pagedim *pdim;
1496 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1497 &xy.x, &xy.y);
1498 pdim = pdimofpageno (pageno);
1499 xy = fz_transform_point (xy, pdim->ctm);
1500 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1503 state.gen++;
1504 unlock ("reqlayout");
1505 printd ("continue %d", state.pagecount);
1507 else if (!strncmp ("page", p, 4)) {
1508 double a, b;
1509 struct page *page;
1510 int pageno, pindex;
1512 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1513 if (ret != 2) {
1514 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1517 lock ("page");
1518 a = now ();
1519 page = loadpage (pageno, pindex);
1520 b = now ();
1521 unlock ("page");
1523 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1525 else if (!strncmp ("tile", p, 4)) {
1526 int x, y, w, h;
1527 struct page *page;
1528 struct tile *tile;
1529 double a, b;
1530 void *data;
1532 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1533 (uintptr_t *) &page, &x, &y, &w, &h,
1534 (uintptr_t *) &data);
1535 if (ret != 6) {
1536 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1539 lock ("tile");
1540 a = now ();
1541 tile = rendertile (page, x, y, w, h, data);
1542 b = now ();
1543 unlock ("tile");
1545 printd ("tile %d %d %" PRIxPTR " %u %f",
1546 x, y, (uintptr_t) (tile),
1547 tile->w * tile->h * tile->pixmap->n,
1548 b - a);
1550 else if (!strncmp ("trimset", p, 7)) {
1551 fz_irect fuzz;
1552 int trimmargins;
1554 ret = sscanf (p + 7, " %d %d %d %d %d",
1555 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1556 if (ret != 5) {
1557 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1559 lock ("trimset");
1560 state.trimmargins = trimmargins;
1561 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1562 state.trimanew = 1;
1563 state.trimfuzz = fuzz;
1565 unlock ("trimset");
1567 else if (!strncmp ("settrim", p, 7)) {
1568 fz_irect fuzz;
1569 int trimmargins;
1571 ret = sscanf (p + 7, " %d %d %d %d %d",
1572 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1573 if (ret != 5) {
1574 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1576 printd ("clear");
1577 lock ("settrim");
1578 state.trimmargins = trimmargins;
1579 state.needoutline = 1;
1580 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1581 state.trimanew = 1;
1582 state.trimfuzz = fuzz;
1584 state.pagedimcount = 0;
1585 free (state.pagedims);
1586 state.pagedims = NULL;
1587 initpdims ();
1588 layout ();
1589 process_outline ();
1590 unlock ("settrim");
1591 printd ("continue %d", state.pagecount);
1593 else if (!strncmp ("sliceh", p, 6)) {
1594 int h;
1596 ret = sscanf (p + 6, " %d", &h);
1597 if (ret != 1) {
1598 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1600 if (h != state.sliceheight) {
1601 state.sliceheight = h;
1602 for (int i = 0; i < state.tex.count; ++i) {
1603 state.tex.owners[i].w = -1;
1604 state.tex.owners[i].h = -1;
1605 state.tex.owners[i].slice = NULL;
1609 else if (!strncmp ("interrupt", p, 9)) {
1610 printd ("vmsg interrupted");
1612 else {
1613 errx (1, "unknown command %.*s", len, p);
1616 return 0;
1619 ML (isexternallink (value uri_v))
1621 CAMLparam1 (uri_v);
1622 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1623 CAMLreturn (Val_bool (ext));
1626 ML (uritolocation (value uri_v))
1628 CAMLparam1 (uri_v);
1629 CAMLlocal1 (ret_v);
1630 int pageno;
1631 fz_point xy;
1632 struct pagedim *pdim;
1634 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1635 &xy.x, &xy.y).page;
1636 pdim = pdimofpageno (pageno);
1637 xy = fz_transform_point (xy, pdim->ctm);
1638 ret_v = caml_alloc_tuple (3);
1639 Field (ret_v, 0) = Val_int (pageno);
1640 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1641 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1642 CAMLreturn (ret_v);
1645 ML (realloctexts (value texcount_v))
1647 CAMLparam1 (texcount_v);
1648 int ok;
1650 if (trylock (__func__)) {
1651 ok = 0;
1652 goto done;
1654 realloctexts (Int_val (texcount_v));
1655 ok = 1;
1656 unlock (__func__);
1658 done:
1659 CAMLreturn (Val_bool (ok));
1662 static void recti (int x0, int y0, int x1, int y1)
1664 GLfloat *v = state.vertices;
1666 glVertexPointer (2, GL_FLOAT, 0, v);
1667 v[0] = x0; v[1] = y0;
1668 v[2] = x1; v[3] = y0;
1669 v[4] = x0; v[5] = y1;
1670 v[6] = x1; v[7] = y1;
1671 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1674 static void showsel (struct page *page, int ox, int oy)
1676 fz_irect bbox;
1677 fz_rect rect;
1678 fz_stext_block *block;
1679 int seen = 0;
1680 unsigned char selcolor[] = {15,15,15,140};
1682 if (!page->fmark || !page->lmark) return;
1684 glEnable (GL_BLEND);
1685 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1686 glColor4ubv (selcolor);
1688 ox += state.pagedims[page->pdimno].bounds.x0;
1689 oy += state.pagedims[page->pdimno].bounds.y0;
1691 for (block = page->text->first_block; block; block = block->next) {
1692 fz_stext_line *line;
1694 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1695 for (line = block->u.t.first_line; line; line = line->next) {
1696 fz_stext_char *ch;
1698 rect = fz_empty_rect;
1699 for (ch = line->first_char; ch; ch = ch->next) {
1700 fz_rect r;
1701 if (ch == page->fmark) seen = 1;
1702 r = fz_rect_from_quad (ch->quad);
1703 if (seen) rect = fz_union_rect (rect, r);
1704 if (ch == page->lmark) {
1705 bbox = fz_round_rect (rect);
1706 recti (bbox.x0 + ox, bbox.y0 + oy,
1707 bbox.x1 + ox, bbox.y1 + oy);
1708 goto done;
1711 bbox = fz_round_rect (rect);
1712 recti (bbox.x0 + ox, bbox.y0 + oy,
1713 bbox.x1 + ox, bbox.y1 + oy);
1716 done:
1717 glDisable (GL_BLEND);
1720 #pragma GCC diagnostic push
1721 #pragma GCC diagnostic ignored "-Wconversion"
1722 #include "glfont.c"
1723 #pragma GCC diagnostic pop
1725 static void stipplerect (fz_matrix m,
1726 fz_point p1,
1727 fz_point p2,
1728 fz_point p3,
1729 fz_point p4,
1730 GLfloat *texcoords,
1731 GLfloat *vertices)
1733 p1 = fz_transform_point (p1, m);
1734 p2 = fz_transform_point (p2, m);
1735 p3 = fz_transform_point (p3, m);
1736 p4 = fz_transform_point (p4, m);
1738 float w, h, s, t;
1740 w = p2.x - p1.x;
1741 h = p2.y - p1.y;
1742 t = hypotf (w, h) * .25f;
1744 w = p3.x - p2.x;
1745 h = p3.y - p2.y;
1746 s = hypotf (w, h) * .25f;
1748 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1749 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1751 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1752 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1754 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1755 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1757 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1758 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1760 glDrawArrays (GL_LINES, 0, 8);
1763 static void solidrect (fz_matrix m,
1764 fz_point p1,
1765 fz_point p2,
1766 fz_point p3,
1767 fz_point p4,
1768 GLfloat *vertices)
1770 p1 = fz_transform_point (p1, m);
1771 p2 = fz_transform_point (p2, m);
1772 p3 = fz_transform_point (p3, m);
1773 p4 = fz_transform_point (p4, m);
1774 vertices[0] = p1.x; vertices[1] = p1.y;
1775 vertices[2] = p2.x; vertices[3] = p2.y;
1777 vertices[4] = p3.x; vertices[5] = p3.y;
1778 vertices[6] = p4.x; vertices[7] = p4.y;
1779 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1782 static void ensurelinks (struct page *page)
1784 if (!page->links)
1785 page->links = fz_load_links (state.ctx, page->fzpage);
1788 static void highlightlinks (struct page *page, int xoff, int yoff)
1790 fz_matrix ctm;
1791 fz_link *link;
1792 GLfloat *texcoords = state.texcoords;
1793 GLfloat *vertices = state.vertices;
1795 ensurelinks (page);
1797 glEnable (GL_TEXTURE_1D);
1798 glEnable (GL_BLEND);
1799 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1800 glBindTexture (GL_TEXTURE_1D, state.stid);
1802 xoff -= state.pagedims[page->pdimno].bounds.x0;
1803 yoff -= state.pagedims[page->pdimno].bounds.y0;
1804 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1806 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1807 glVertexPointer (2, GL_FLOAT, 0, vertices);
1809 for (link = page->links; link; link = link->next) {
1810 fz_point p1, p2, p3, p4;
1812 p1.x = link->rect.x0;
1813 p1.y = link->rect.y0;
1815 p2.x = link->rect.x1;
1816 p2.y = link->rect.y0;
1818 p3.x = link->rect.x1;
1819 p3.y = link->rect.y1;
1821 p4.x = link->rect.x0;
1822 p4.y = link->rect.y1;
1824 /* TODO: different colours for different schemes */
1825 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1826 else glColor3ub (255, 0, 0);
1828 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1831 for (int i = 0; i < page->annotcount; ++i) {
1832 fz_point p1, p2, p3, p4;
1833 struct annot *annot = &page->annots[i];
1835 p1.x = annot->bbox.x0;
1836 p1.y = annot->bbox.y0;
1838 p2.x = annot->bbox.x1;
1839 p2.y = annot->bbox.y0;
1841 p3.x = annot->bbox.x1;
1842 p3.y = annot->bbox.y1;
1844 p4.x = annot->bbox.x0;
1845 p4.y = annot->bbox.y1;
1847 glColor3ub (0, 0, 128);
1848 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1851 glDisable (GL_BLEND);
1852 glDisable (GL_TEXTURE_1D);
1855 static int compareslinks (const void *l, const void *r)
1857 struct slink const *ls = l;
1858 struct slink const *rs = r;
1859 if (ls->bbox.y0 == rs->bbox.y0) {
1860 return ls->bbox.x0 - rs->bbox.x0;
1862 return ls->bbox.y0 - rs->bbox.y0;
1865 static void droptext (struct page *page)
1867 if (page->text) {
1868 fz_drop_stext_page (state.ctx, page->text);
1869 page->fmark = NULL;
1870 page->lmark = NULL;
1871 page->text = NULL;
1875 static void dropannots (struct page *page)
1877 if (page->annots) {
1878 free (page->annots);
1879 page->annots = NULL;
1880 page->annotcount = 0;
1884 static void ensureannots (struct page *page)
1886 int i, count = 0;
1887 size_t annotsize = sizeof (*page->annots);
1888 pdf_annot *annot;
1889 pdf_document *pdf;
1890 pdf_page *pdfpage;
1892 pdf = pdf_specifics (state.ctx, state.doc);
1893 if (!pdf) return;
1895 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1896 if (state.gen != page->agen) {
1897 dropannots (page);
1898 page->agen = state.gen;
1900 if (page->annots) return;
1902 for (annot = pdf_first_annot (state.ctx, pdfpage);
1903 annot;
1904 annot = pdf_next_annot (state.ctx, annot)) {
1905 count++;
1908 if (count > 0) {
1909 page->annotcount = count;
1910 page->annots = calloc (count, annotsize);
1911 if (!page->annots) {
1912 err (1, "calloc annots %d", count);
1915 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1916 annot;
1917 annot = pdf_next_annot (state.ctx, annot), i++) {
1918 fz_rect rect;
1920 rect = pdf_bound_annot (state.ctx, annot);
1921 page->annots[i].annot = annot;
1922 page->annots[i].bbox = fz_round_rect (rect);
1927 static void dropslinks (struct page *page)
1929 if (page->slinks) {
1930 free (page->slinks);
1931 page->slinks = NULL;
1932 page->slinkcount = 0;
1934 if (page->links) {
1935 fz_drop_link (state.ctx, page->links);
1936 page->links = NULL;
1940 static void ensureslinks (struct page *page)
1942 fz_matrix ctm;
1943 int i, count;
1944 size_t slinksize = sizeof (*page->slinks);
1945 fz_link *link;
1947 ensureannots (page);
1948 if (state.gen != page->sgen) {
1949 dropslinks (page);
1950 page->sgen = state.gen;
1952 if (page->slinks) return;
1954 ensurelinks (page);
1955 ctm = pagectm (page);
1957 count = page->annotcount;
1958 for (link = page->links; link; link = link->next) {
1959 count++;
1961 if (count > 0) {
1962 int j;
1964 page->slinkcount = count;
1965 page->slinks = calloc (count, slinksize);
1966 if (!page->slinks) {
1967 err (1, "calloc slinks %d", count);
1970 for (i = 0, link = page->links; link; ++i, link = link->next) {
1971 fz_rect rect;
1973 rect = link->rect;
1974 rect = fz_transform_rect (rect, ctm);
1975 page->slinks[i].tag = SLINK;
1976 page->slinks[i].u.link = link;
1977 page->slinks[i].bbox = fz_round_rect (rect);
1979 for (j = 0; j < page->annotcount; ++j, ++i) {
1980 fz_rect rect;
1981 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1982 rect = fz_transform_rect (rect, ctm);
1983 page->slinks[i].bbox = fz_round_rect (rect);
1985 page->slinks[i].tag = SANNOT;
1986 page->slinks[i].u.annot = page->annots[j].annot;
1988 qsort (page->slinks, count, slinksize, compareslinks);
1992 static void highlightslinks (struct page *page, int xoff, int yoff,
1993 int noff, const char *targ,
1994 mlsize_t tlen, int hfsize)
1996 char buf[40];
1997 struct slink *slink;
1998 float x0, y0, x1, y1, w;
2000 ensureslinks (page);
2001 glColor3ub (0xc3, 0xb0, 0x91);
2002 for (int i = 0; i < page->slinkcount; ++i) {
2003 fmt_linkn (buf, i + noff);
2004 if (!tlen || !strncmp (targ, buf, tlen)) {
2005 slink = &page->slinks[i];
2007 x0 = slink->bbox.x0 + xoff - 5;
2008 y1 = slink->bbox.y0 + yoff - 5;
2009 y0 = y1 + 10 + hfsize;
2010 w = measure_string (state.face, hfsize, buf);
2011 x1 = x0 + w + 10;
2012 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2016 glEnable (GL_BLEND);
2017 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2018 glEnable (GL_TEXTURE_2D);
2019 glColor3ub (0, 0, 0);
2020 for (int i = 0; i < page->slinkcount; ++i) {
2021 fmt_linkn (buf, i + noff);
2022 if (!tlen || !strncmp (targ, buf, tlen)) {
2023 slink = &page->slinks[i];
2025 x0 = slink->bbox.x0 + xoff;
2026 y0 = slink->bbox.y0 + yoff + hfsize;
2027 draw_string (state.face, hfsize, x0, y0, buf);
2030 glDisable (GL_TEXTURE_2D);
2031 glDisable (GL_BLEND);
2034 static void uploadslice (struct tile *tile, struct slice *slice)
2036 int offset;
2037 struct slice *slice1;
2038 unsigned char *texdata;
2040 offset = 0;
2041 for (slice1 = tile->slices; slice != slice1; slice1++) {
2042 offset += slice1->h * tile->w * tile->pixmap->n;
2044 if (slice->texindex != -1 && slice->texindex < state.tex.count
2045 && state.tex.owners[slice->texindex].slice == slice) {
2046 glBindTexture (TEXT_TYPE, state.tex.ids[slice->texindex]);
2048 else {
2049 int subimage = 0;
2050 int texindex = state.tex.index++ % state.tex.count;
2052 if (state.tex.owners[texindex].w == tile->w) {
2053 if (state.tex.owners[texindex].h >= slice->h) {
2054 subimage = 1;
2056 else {
2057 state.tex.owners[texindex].h = slice->h;
2060 else {
2061 state.tex.owners[texindex].h = slice->h;
2064 state.tex.owners[texindex].w = tile->w;
2065 state.tex.owners[texindex].slice = slice;
2066 slice->texindex = texindex;
2068 glBindTexture (TEXT_TYPE, state.tex.ids[texindex]);
2069 #if TEXT_TYPE == GL_TEXTURE_2D
2070 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2071 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2072 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2073 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2074 #endif
2075 if (tile->pbo) {
2076 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2077 texdata = 0;
2079 else {
2080 texdata = tile->pixmap->samples;
2082 if (subimage) {
2083 glTexSubImage2D (TEXT_TYPE,
2087 tile->w,
2088 slice->h,
2089 state.tex.form,
2090 state.tex.ty,
2091 texdata+offset
2094 else {
2095 glTexImage2D (TEXT_TYPE,
2097 state.tex.iform,
2098 tile->w,
2099 slice->h,
2101 state.tex.form,
2102 state.tex.ty,
2103 texdata+offset
2106 if (tile->pbo) {
2107 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2112 ML0 (begintiles (void))
2114 glEnable (TEXT_TYPE);
2115 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2116 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2119 ML0 (endtiles (void))
2121 glDisable (TEXT_TYPE);
2124 ML0 (drawtile (value args_v, value ptr_v))
2126 CAMLparam2 (args_v, ptr_v);
2127 int dispx = Int_val (Field (args_v, 0));
2128 int dispy = Int_val (Field (args_v, 1));
2129 int dispw = Int_val (Field (args_v, 2));
2130 int disph = Int_val (Field (args_v, 3));
2131 int tilex = Int_val (Field (args_v, 4));
2132 int tiley = Int_val (Field (args_v, 5));
2133 const char *s = String_val (ptr_v);
2134 struct tile *tile = parse_pointer (__func__, s);
2135 int slicey, firstslice;
2136 struct slice *slice;
2137 GLfloat *texcoords = state.texcoords;
2138 GLfloat *vertices = state.vertices;
2140 firstslice = tiley / tile->sliceheight;
2141 slice = &tile->slices[firstslice];
2142 slicey = tiley % tile->sliceheight;
2144 while (disph > 0) {
2145 int dh;
2147 dh = slice->h - slicey;
2148 dh = fz_mini (disph, dh);
2149 uploadslice (tile, slice);
2151 texcoords[0] = tilex; texcoords[1] = slicey;
2152 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2153 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2154 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2156 vertices[0] = dispx; vertices[1] = dispy;
2157 vertices[2] = dispx+dispw; vertices[3] = dispy;
2158 vertices[4] = dispx; vertices[5] = dispy+dh;
2159 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2161 #if TEXT_TYPE == GL_TEXTURE_2D
2162 for (int i = 0; i < 8; ++i) {
2163 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2165 #endif
2167 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2168 dispy += dh;
2169 disph -= dh;
2170 slice++;
2171 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2172 slicey = 0;
2174 CAMLreturn0;
2177 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2179 fz_matrix ctm;
2180 fz_point p1, p2, p3, p4;
2181 GLfloat *vertices = state.vertices;
2183 xoff -= state.pagedims[page->pdimno].bounds.x0;
2184 yoff -= state.pagedims[page->pdimno].bounds.y0;
2185 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2187 glEnable (GL_BLEND);
2188 glVertexPointer (2, GL_FLOAT, 0, vertices);
2190 glColor4d (
2191 Double_array_field (rects_v, 0),
2192 Double_array_field (rects_v, 1),
2193 Double_array_field (rects_v, 2),
2194 Double_array_field (rects_v, 3)
2196 p1.x = (float) Double_array_field (rects_v, 4);
2197 p1.y = (float) Double_array_field (rects_v, 5);
2199 p2.x = (float) Double_array_field (rects_v, 6);
2200 p2.y = p1.y;
2202 p3.x = p2.x;
2203 p3.y = (float) Double_array_field (rects_v, 7);
2205 p4.x = p1.x;
2206 p4.y = p3.y;
2207 solidrect (ctm, p1, p2, p3, p4, vertices);
2208 glDisable (GL_BLEND);
2211 ML (postprocess (value ptr_v, value hlinks_v,
2212 value xoff_v, value yoff_v,
2213 value li_v))
2215 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2216 int xoff = Int_val (xoff_v);
2217 int yoff = Int_val (yoff_v);
2218 int noff = Int_val (Field (li_v, 0));
2219 const char *targ = String_val (Field (li_v, 1));
2220 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2221 int hfsize = Int_val (Field (li_v, 2));
2222 const char *s = String_val (ptr_v);
2223 int hlmask = Int_val (hlinks_v);
2224 struct page *page = parse_pointer (__func__, s);
2226 if (!page->fzpage) {
2227 /* deal with loadpage failed pages */
2228 goto done;
2231 if (trylock (__func__)) {
2232 noff = -1;
2233 goto done;
2236 ensureannots (page);
2237 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2238 if (hlmask & 2) {
2239 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2240 noff = page->slinkcount;
2242 if (page->tgen == state.gen) {
2243 showsel (page, xoff, yoff);
2245 unlock (__func__);
2247 done:
2248 CAMLreturn (Val_int (noff));
2251 ML0 (drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v))
2253 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2254 int xoff = Int_val (xoff_v);
2255 int yoff = Int_val (yoff_v);
2256 const char *s = String_val (ptr_v);
2257 struct page *page = parse_pointer (__func__, s);
2259 drawprect (page, xoff, yoff, rects_v);
2260 CAMLreturn0;
2263 static struct annot *getannot (struct page *page, int x, int y)
2265 fz_point p;
2266 fz_matrix ctm;
2267 const fz_matrix *tctm;
2268 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2270 if (!page->annots) return NULL;
2272 if (pdf) {
2273 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2274 tctm = &state.pagedims[page->pdimno].tctm;
2276 else {
2277 tctm = &fz_identity;
2280 p.x = x;
2281 p.y = y;
2283 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2284 ctm = fz_invert_matrix (ctm);
2285 p = fz_transform_point (p, ctm);
2287 if (pdf) {
2288 for (int i = 0; i < page->annotcount; ++i) {
2289 struct annot *a = &page->annots[i];
2290 fz_rect rect;
2292 rect = pdf_bound_annot (state.ctx, a->annot);
2293 if (p.x >= rect.x0 && p.x <= rect.x1) {
2294 if (p.y >= rect.y0 && p.y <= rect.y1)
2295 return a;
2299 return NULL;
2302 static fz_link *getlink (struct page *page, int x, int y)
2304 fz_point p;
2305 fz_link *link;
2307 ensureslinks (page);
2309 p.x = x;
2310 p.y = y;
2312 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2314 for (link = page->links; link; link = link->next) {
2315 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2316 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2317 return link;
2321 return NULL;
2324 static void ensuretext (struct page *page)
2326 if (state.gen != page->tgen) {
2327 droptext (page);
2328 page->tgen = state.gen;
2330 if (!page->text) {
2331 fz_device *tdev;
2333 page->text = fz_new_stext_page (state.ctx,
2334 state.pagedims[page->pdimno].mediabox);
2335 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2336 fz_run_display_list (state.ctx, page->dlist,
2337 tdev, pagectm (page), fz_infinite_rect, NULL);
2338 fz_close_device (state.ctx, tdev);
2339 fz_drop_device (state.ctx, tdev);
2343 ML (find_page_with_links (value start_page_v, value dir_v))
2345 CAMLparam2 (start_page_v, dir_v);
2346 CAMLlocal1 (ret_v);
2347 int i, dir = Int_val (dir_v);
2348 int start_page = Int_val (start_page_v);
2349 int end_page = dir > 0 ? state.pagecount : -1;
2350 pdf_document *pdf;
2352 fz_var (end_page);
2353 ret_v = Val_int (0);
2354 lock (__func__);
2355 pdf = pdf_specifics (state.ctx, state.doc);
2356 for (i = start_page + dir; i != end_page; i += dir) {
2357 int found;
2359 fz_var (found);
2360 if (pdf) {
2361 pdf_page *page = NULL;
2363 fz_var (page);
2364 fz_try (state.ctx) {
2365 page = pdf_load_page (state.ctx, pdf, i);
2366 found = !!page->links || !!page->annots;
2368 fz_catch (state.ctx) {
2369 found = 0;
2371 if (page) {
2372 fz_drop_page (state.ctx, &page->super);
2375 else {
2376 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2377 fz_link *link = fz_load_links (state.ctx, page);
2378 found = !!link;
2379 fz_drop_link (state.ctx, link);
2380 fz_drop_page (state.ctx, page);
2383 if (found) {
2384 ret_v = caml_alloc_small (1, 1);
2385 Field (ret_v, 0) = Val_int (i);
2386 goto unlock;
2389 unlock:
2390 unlock (__func__);
2391 CAMLreturn (ret_v);
2394 enum { dir_first, dir_last };
2395 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2397 ML (findlink (value ptr_v, value dir_v))
2399 CAMLparam2 (ptr_v, dir_v);
2400 CAMLlocal2 (ret_v, pos_v);
2401 struct page *page;
2402 int dirtag, i, slinkindex;
2403 struct slink *found = NULL ,*slink;
2404 const char *s = String_val (ptr_v);
2406 page = parse_pointer (__func__, s);
2407 ret_v = Val_int (0);
2408 lock (__func__);
2409 ensureslinks (page);
2411 if (Is_block (dir_v)) {
2412 dirtag = Tag_val (dir_v);
2413 switch (dirtag) {
2414 case dir_first_visible:
2416 int x0, y0, dir, first_index, last_index;
2418 pos_v = Field (dir_v, 0);
2419 x0 = Int_val (Field (pos_v, 0));
2420 y0 = Int_val (Field (pos_v, 1));
2421 dir = Int_val (Field (pos_v, 2));
2423 if (dir >= 0) {
2424 dir = 1;
2425 first_index = 0;
2426 last_index = page->slinkcount;
2428 else {
2429 first_index = page->slinkcount - 1;
2430 last_index = -1;
2433 for (i = first_index; i != last_index; i += dir) {
2434 slink = &page->slinks[i];
2435 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2436 found = slink;
2437 break;
2441 break;
2443 case dir_left:
2444 slinkindex = Int_val (Field (dir_v, 0));
2445 found = &page->slinks[slinkindex];
2446 for (i = slinkindex - 1; i >= 0; --i) {
2447 slink = &page->slinks[i];
2448 if (slink->bbox.x0 < found->bbox.x0) {
2449 found = slink;
2450 break;
2453 break;
2455 case dir_right:
2456 slinkindex = Int_val (Field (dir_v, 0));
2457 found = &page->slinks[slinkindex];
2458 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2459 slink = &page->slinks[i];
2460 if (slink->bbox.x0 > found->bbox.x0) {
2461 found = slink;
2462 break;
2465 break;
2467 case dir_down:
2468 slinkindex = Int_val (Field (dir_v, 0));
2469 found = &page->slinks[slinkindex];
2470 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2471 slink = &page->slinks[i];
2472 if (slink->bbox.y0 >= found->bbox.y0) {
2473 found = slink;
2474 break;
2477 break;
2479 case dir_up:
2480 slinkindex = Int_val (Field (dir_v, 0));
2481 found = &page->slinks[slinkindex];
2482 for (i = slinkindex - 1; i >= 0; --i) {
2483 slink = &page->slinks[i];
2484 if (slink->bbox.y0 <= found->bbox.y0) {
2485 found = slink;
2486 break;
2489 break;
2492 else {
2493 dirtag = Int_val (dir_v);
2494 switch (dirtag) {
2495 case dir_first:
2496 found = page->slinks;
2497 break;
2499 case dir_last:
2500 if (page->slinks) {
2501 found = page->slinks + (page->slinkcount - 1);
2503 break;
2506 if (found) {
2507 ret_v = caml_alloc_small (2, 1);
2508 Field (ret_v, 0) = Val_int (found - page->slinks);
2511 unlock (__func__);
2512 CAMLreturn (ret_v);
2515 enum { uuri, utext, uannot };
2517 ML (getlink (value ptr_v, value n_v))
2519 CAMLparam2 (ptr_v, n_v);
2520 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2521 fz_link *link;
2522 struct page *page;
2523 const char *s = String_val (ptr_v);
2524 struct slink *slink;
2526 ret_v = Val_int (0);
2527 page = parse_pointer (__func__, s);
2529 lock (__func__);
2530 ensureslinks (page);
2531 slink = &page->slinks[Int_val (n_v)];
2532 if (slink->tag == SLINK) {
2533 link = slink->u.link;
2534 str_v = caml_copy_string (link->uri);
2535 ret_v = caml_alloc_small (1, uuri);
2536 Field (ret_v, 0) = str_v;
2538 else {
2539 ret_v = caml_alloc_small (1, uannot);
2540 tup_v = caml_alloc_tuple (2);
2541 Field (ret_v, 0) = tup_v;
2542 Field (tup_v, 0) = ptr_v;
2543 Field (tup_v, 1) = n_v;
2545 unlock (__func__);
2547 CAMLreturn (ret_v);
2550 ML (getannotcontents (value ptr_v, value n_v))
2552 CAMLparam2 (ptr_v, n_v);
2553 CAMLlocal1 (ret_v);
2554 pdf_document *pdf;
2555 const char *contents = "";
2557 lock (__func__);
2558 pdf = pdf_specifics (state.ctx, state.doc);
2559 if (pdf) {
2560 const char *s = String_val (ptr_v);
2561 struct page *page;
2562 struct slink *slink;
2564 page = parse_pointer (__func__, s);
2565 slink = &page->slinks[Int_val (n_v)];
2566 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2568 unlock (__func__);
2569 ret_v = caml_copy_string (contents);
2570 CAMLreturn (ret_v);
2573 ML (getlinkcount (value ptr_v))
2575 CAMLparam1 (ptr_v);
2576 struct page *page;
2577 const char *s = String_val (ptr_v);
2579 page = parse_pointer (__func__, s);
2580 CAMLreturn (Val_int (page->slinkcount));
2583 ML (getlinkrect (value ptr_v, value n_v))
2585 CAMLparam2 (ptr_v, n_v);
2586 CAMLlocal1 (ret_v);
2587 struct page *page;
2588 struct slink *slink;
2589 const char *s = String_val (ptr_v);
2591 page = parse_pointer (__func__, s);
2592 ret_v = caml_alloc_tuple (4);
2593 lock (__func__);
2594 ensureslinks (page);
2596 slink = &page->slinks[Int_val (n_v)];
2597 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2598 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2599 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2600 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2601 unlock (__func__);
2602 CAMLreturn (ret_v);
2605 ML (whatsunder (value ptr_v, value x_v, value y_v))
2607 CAMLparam3 (ptr_v, x_v, y_v);
2608 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2609 fz_link *link;
2610 struct annot *annot;
2611 struct page *page;
2612 const char *ptr = String_val (ptr_v);
2613 int x = Int_val (x_v), y = Int_val (y_v);
2614 struct pagedim *pdim;
2616 ret_v = Val_int (0);
2617 if (trylock (__func__)) {
2618 goto done;
2621 page = parse_pointer (__func__, ptr);
2622 pdim = &state.pagedims[page->pdimno];
2623 x += pdim->bounds.x0;
2624 y += pdim->bounds.y0;
2627 annot = getannot (page, x, y);
2628 if (annot) {
2629 int i, n = -1;
2631 ensureslinks (page);
2632 for (i = 0; i < page->slinkcount; ++i) {
2633 if (page->slinks[i].tag == SANNOT
2634 && page->slinks[i].u.annot == annot->annot) {
2635 n = i;
2636 break;
2639 ret_v = caml_alloc_small (1, uannot);
2640 tup_v = caml_alloc_tuple (2);
2641 Field (ret_v, 0) = tup_v;
2642 Field (tup_v, 0) = ptr_v;
2643 Field (tup_v, 1) = Val_int (n);
2644 goto unlock;
2648 link = getlink (page, x, y);
2649 if (link) {
2650 str_v = caml_copy_string (link->uri);
2651 ret_v = caml_alloc_small (1, uuri);
2652 Field (ret_v, 0) = str_v;
2654 else {
2655 fz_rect *b;
2656 fz_stext_block *block;
2658 ensuretext (page);
2660 for (block = page->text->first_block; block; block = block->next) {
2661 fz_stext_line *line;
2663 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2664 b = &block->bbox;
2665 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2666 continue;
2668 for (line = block->u.t.first_line; line; line = line->next) {
2669 fz_stext_char *ch;
2671 b = &line->bbox;
2672 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2673 continue;
2675 for (ch = line->first_char; ch; ch = ch->next) {
2676 fz_quad *q = &ch->quad;
2678 if (x >= q->ul.x && x <= q->ur.x
2679 && y >= q->ul.y && y <= q->ll.y) {
2680 const char *n2 = fz_font_name (state.ctx, ch->font);
2681 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2682 ch->font);
2684 if (!n2) n2 = "<unknown font>";
2686 if (face && face->family_name) {
2687 char *s;
2688 char *n1 = face->family_name;
2689 size_t l1 = strlen (n1);
2690 size_t l2 = strlen (n2);
2692 if (l1 != l2 || memcmp (n1, n2, l1)) {
2693 s = malloc (l1 + l2 + 2);
2694 if (s) {
2695 memcpy (s, n2, l2);
2696 s[l2] = '=';
2697 memcpy (s + l2 + 1, n1, l1 + 1);
2698 str_v = caml_copy_string (s);
2699 free (s);
2703 if (str_v == Val_unit) {
2704 str_v = caml_copy_string (n2);
2706 ret_v = caml_alloc_small (1, utext);
2707 Field (ret_v, 0) = str_v;
2708 goto unlock;
2714 unlock:
2715 unlock (__func__);
2717 done:
2718 CAMLreturn (ret_v);
2721 enum { mark_page, mark_block, mark_line, mark_word };
2723 ML0 (clearmark (value ptr_v))
2725 CAMLparam1 (ptr_v);
2726 const char *s = String_val (ptr_v);
2727 struct page *page;
2729 if (trylock (__func__)) {
2730 goto done;
2733 page = parse_pointer (__func__, s);
2734 page->fmark = NULL;
2735 page->lmark = NULL;
2737 unlock (__func__);
2738 done:
2739 CAMLreturn0;
2742 static int uninteresting (int c)
2744 return isspace (c) || ispunct (c);
2747 ML (markunder (value ptr_v, value x_v, value y_v, value mark_v))
2749 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2750 CAMLlocal1 (ret_v);
2751 fz_rect *b;
2752 struct page *page;
2753 fz_stext_line *line;
2754 fz_stext_block *block;
2755 struct pagedim *pdim;
2756 int mark = Int_val (mark_v);
2757 const char *s = String_val (ptr_v);
2758 int x = Int_val (x_v), y = Int_val (y_v);
2760 ret_v = Val_bool (0);
2761 if (trylock (__func__)) {
2762 goto done;
2765 page = parse_pointer (__func__, s);
2766 pdim = &state.pagedims[page->pdimno];
2768 ensuretext (page);
2770 if (mark == mark_page) {
2771 page->fmark = page->text->first_block->u.t.first_line->first_char;
2772 page->lmark = page->text->last_block->u.t.last_line->last_char;
2773 ret_v = Val_bool (1);
2774 goto unlock;
2777 x += pdim->bounds.x0;
2778 y += pdim->bounds.y0;
2780 for (block = page->text->first_block; block; block = block->next) {
2781 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2782 b = &block->bbox;
2783 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2784 continue;
2786 if (mark == mark_block) {
2787 page->fmark = block->u.t.first_line->first_char;
2788 page->lmark = block->u.t.last_line->last_char;
2789 ret_v = Val_bool (1);
2790 goto unlock;
2793 for (line = block->u.t.first_line; line; line = line->next) {
2794 fz_stext_char *ch;
2796 b = &line->bbox;
2797 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2798 continue;
2800 if (mark == mark_line) {
2801 page->fmark = line->first_char;
2802 page->lmark = line->last_char;
2803 ret_v = Val_bool (1);
2804 goto unlock;
2807 for (ch = line->first_char; ch; ch = ch->next) {
2808 fz_stext_char *ch2, *first = NULL, *last = NULL;
2809 fz_quad *q = &ch->quad;
2810 if (x >= q->ul.x && x <= q->ur.x
2811 && y >= q->ul.y && y <= q->ll.y) {
2812 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2813 if (uninteresting (ch2->c)) first = NULL;
2814 else if (!first) first = ch2;
2816 for (ch2 = ch; ch2; ch2 = ch2->next) {
2817 if (uninteresting (ch2->c)) break;
2818 last = ch2;
2821 page->fmark = first;
2822 page->lmark = last;
2823 ret_v = Val_bool (1);
2824 goto unlock;
2829 unlock:
2830 if (!Bool_val (ret_v)) {
2831 page->fmark = NULL;
2832 page->lmark = NULL;
2834 unlock (__func__);
2836 done:
2837 CAMLreturn (ret_v);
2840 ML (rectofblock (value ptr_v, value x_v, value y_v))
2842 CAMLparam3 (ptr_v, x_v, y_v);
2843 CAMLlocal2 (ret_v, res_v);
2844 fz_rect *b = NULL;
2845 struct page *page;
2846 struct pagedim *pdim;
2847 fz_stext_block *block;
2848 const char *s = String_val (ptr_v);
2849 int x = Int_val (x_v), y = Int_val (y_v);
2851 ret_v = Val_int (0);
2852 if (trylock (__func__)) {
2853 goto done;
2856 page = parse_pointer (__func__, s);
2857 pdim = &state.pagedims[page->pdimno];
2858 x += pdim->bounds.x0;
2859 y += pdim->bounds.y0;
2861 ensuretext (page);
2863 for (block = page->text->first_block; block; block = block->next) {
2864 switch (block->type) {
2865 case FZ_STEXT_BLOCK_TEXT:
2866 b = &block->bbox;
2867 break;
2869 case FZ_STEXT_BLOCK_IMAGE:
2870 b = &block->bbox;
2871 break;
2873 default:
2874 continue;
2877 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2878 break;
2879 b = NULL;
2881 if (b) {
2882 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2883 ret_v = caml_alloc_small (1, 1);
2884 Store_double_field (res_v, 0, (double) b->x0);
2885 Store_double_field (res_v, 1, (double) b->x1);
2886 Store_double_field (res_v, 2, (double) b->y0);
2887 Store_double_field (res_v, 3, (double) b->y1);
2888 Field (ret_v, 0) = res_v;
2890 unlock (__func__);
2892 done:
2893 CAMLreturn (ret_v);
2896 ML0 (seltext (value ptr_v, value rect_v))
2898 CAMLparam2 (ptr_v, rect_v);
2899 struct page *page;
2900 struct pagedim *pdim;
2901 const char *s = String_val (ptr_v);
2902 int x0, x1, y0, y1;
2903 fz_stext_char *ch;
2904 fz_stext_line *line;
2905 fz_stext_block *block;
2906 fz_stext_char *fc, *lc;
2908 if (trylock (__func__)) {
2909 goto done;
2912 page = parse_pointer (__func__, s);
2913 ensuretext (page);
2915 pdim = &state.pagedims[page->pdimno];
2916 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2917 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2918 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2919 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2921 if (y0 > y1) {
2922 int t = y0;
2923 y0 = y1;
2924 y1 = t;
2925 x0 = x1;
2926 x1 = t;
2929 fc = page->fmark;
2930 lc = page->lmark;
2932 for (block = page->text->first_block; block; block = block->next) {
2933 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2934 for (line = block->u.t.first_line; line; line = line->next) {
2935 for (ch = line->first_char; ch; ch = ch->next) {
2936 fz_quad q = ch->quad;
2937 if (x0 >= q.ul.x && x0 <= q.ur.x
2938 && y0 >= q.ul.y && y0 <= q.ll.y) {
2939 fc = ch;
2941 if (x1 >= q.ul.x && x1 <= q.ur.x
2942 && y1 >= q.ul.y && y1 <= q.ll.y) {
2943 lc = ch;
2948 if (x1 < x0 && fc == lc) {
2949 fz_stext_char *t;
2951 t = fc;
2952 fc = lc;
2953 lc = t;
2956 page->fmark = fc;
2957 page->lmark = lc;
2959 unlock (__func__);
2961 done:
2962 CAMLreturn0;
2965 static int pipechar (FILE *f, fz_stext_char *ch)
2967 char buf[4];
2968 int len;
2969 size_t ret;
2971 len = fz_runetochar (buf, ch->c);
2972 ret = fwrite (buf, len, 1, f);
2973 if (ret != 1) {
2974 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
2975 len, ret, errno, strerror (errno));
2976 return -1;
2978 return 0;
2981 ML (spawn (value command_v, value fds_v))
2983 CAMLparam2 (command_v, fds_v);
2984 CAMLlocal2 (l_v, tup_v);
2985 int ret, ret1;
2986 pid_t pid = (pid_t) -1;
2987 char *msg = NULL;
2988 value earg_v = Nothing;
2989 posix_spawnattr_t attr;
2990 posix_spawn_file_actions_t fa;
2991 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
2993 argv[2] = &Byte (command_v, 0);
2994 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
2995 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
2998 if ((ret = posix_spawnattr_init (&attr)) != 0) {
2999 msg = "posix_spawnattr_init";
3000 goto fail1;
3003 #ifdef POSIX_SPAWN_USEVFORK
3004 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3005 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3006 goto fail;
3008 #endif
3010 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3011 int fd1, fd2;
3013 tup_v = Field (l_v, 0);
3014 fd1 = Int_val (Field (tup_v, 0));
3015 fd2 = Int_val (Field (tup_v, 1));
3016 if (fd2 < 0) {
3017 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3018 msg = "posix_spawn_file_actions_addclose";
3019 earg_v = tup_v;
3020 goto fail;
3023 else {
3024 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3025 msg = "posix_spawn_file_actions_adddup2";
3026 earg_v = tup_v;
3027 goto fail;
3032 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3033 msg = "posix_spawn";
3034 goto fail;
3037 fail:
3038 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3039 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3042 fail1:
3043 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3044 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3045 ret1, strerror (ret1));
3048 if (msg)
3049 unix_error (ret, msg, earg_v);
3051 CAMLreturn (Val_int (pid));
3054 ML (hassel (value ptr_v))
3056 CAMLparam1 (ptr_v);
3057 CAMLlocal1 (ret_v);
3058 struct page *page;
3059 const char *s = String_val (ptr_v);
3061 ret_v = Val_bool (0);
3062 if (trylock (__func__)) {
3063 goto done;
3066 page = parse_pointer (__func__, s);
3067 ret_v = Val_bool (page->fmark && page->lmark);
3068 unlock (__func__);
3069 done:
3070 CAMLreturn (ret_v);
3073 ML0 (copysel (value fd_v, value ptr_v))
3075 CAMLparam2 (fd_v, ptr_v);
3076 FILE *f;
3077 int seen = 0;
3078 struct page *page;
3079 fz_stext_line *line;
3080 fz_stext_block *block;
3081 int fd = Int_val (fd_v);
3082 const char *s = String_val (ptr_v);
3084 if (trylock (__func__)) {
3085 goto done;
3088 page = parse_pointer (__func__, s);
3090 if (!page->fmark || !page->lmark) {
3091 printd ("emsg nothing to copy on page %d", page->pageno);
3092 goto unlock;
3095 f = fdopen (fd, "w");
3096 if (!f) {
3097 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3098 fd, errno, strerror (errno));
3099 f = stdout;
3102 for (block = page->text->first_block; block; block = block->next) {
3103 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3104 for (line = block->u.t.first_line; line; line = line->next) {
3105 fz_stext_char *ch;
3106 for (ch = line->first_char; ch; ch = ch->next) {
3107 if (seen || ch == page->fmark) {
3108 do {
3109 pipechar (f, ch);
3110 if (ch == page->lmark) goto close;
3111 } while ((ch = ch->next));
3112 seen = 1;
3113 break;
3116 if (seen) fputc ('\n', f);
3119 close:
3120 if (f != stdout) {
3121 int ret = fclose (f);
3122 fd = -1;
3123 if (ret == -1) {
3124 if (errno != ECHILD) {
3125 printd ("emsg failed to close sel pipe: %d:%s",
3126 errno, strerror (errno));
3130 unlock:
3131 unlock (__func__);
3133 done:
3134 if (fd >= 0) {
3135 if (close (fd)) {
3136 printd ("emsg failed to close sel pipe: %d:%s",
3137 errno, strerror (errno));
3140 CAMLreturn0;
3143 ML (getpdimrect (value pagedimno_v))
3145 CAMLparam1 (pagedimno_v);
3146 CAMLlocal1 (ret_v);
3147 int pagedimno = Int_val (pagedimno_v);
3148 fz_rect box;
3150 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3151 if (trylock (__func__)) {
3152 box = fz_empty_rect;
3154 else {
3155 box = state.pagedims[pagedimno].mediabox;
3156 unlock (__func__);
3159 Store_double_field (ret_v, 0, (double) box.x0);
3160 Store_double_field (ret_v, 1, (double) box.x1);
3161 Store_double_field (ret_v, 2, (double) box.y0);
3162 Store_double_field (ret_v, 3, (double) box.y1);
3164 CAMLreturn (ret_v);
3167 ML (zoom_for_height (value winw_v, value winh_v, value dw_v, value cols_v))
3169 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3170 CAMLlocal1 (ret_v);
3171 int i;
3172 float zoom = -1.;
3173 float maxh = 0.0;
3174 struct pagedim *p;
3175 float winw = Int_val (winw_v);
3176 float winh = Int_val (winh_v);
3177 float dw = Int_val (dw_v);
3178 float cols = Int_val (cols_v);
3179 float pw = 1.0, ph = 1.0;
3181 if (trylock (__func__)) {
3182 goto done;
3185 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3186 float w = p->pagebox.x1 / cols;
3187 float h = p->pagebox.y1;
3188 if (h > maxh) {
3189 maxh = h;
3190 ph = h;
3191 if (state.fitmodel != FitProportional) pw = w;
3193 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3196 zoom = (((winh / ph) * pw) + dw) / winw;
3197 unlock (__func__);
3198 done:
3199 ret_v = caml_copy_double ((double) zoom);
3200 CAMLreturn (ret_v);
3203 ML (getmaxw (value unit_v))
3205 CAMLparam1 (unit_v);
3206 CAMLlocal1 (ret_v);
3207 int i;
3208 float maxw = -1.;
3209 struct pagedim *p;
3211 if (trylock (__func__)) {
3212 goto done;
3215 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3216 float w = p->pagebox.x1;
3217 maxw = fz_max (maxw, w);
3220 unlock (__func__);
3221 done:
3222 ret_v = caml_copy_double ((double) maxw);
3223 CAMLreturn (ret_v);
3226 ML (draw_string (value pt_v, value x_v, value y_v, value string_v))
3228 CAMLparam4 (pt_v, x_v, y_v, string_v);
3229 CAMLlocal1 (ret_v);
3230 int pt = Int_val(pt_v);
3231 int x = Int_val (x_v);
3232 int y = Int_val (y_v);
3233 float w;
3235 w = draw_string (state.face, pt, x, y, String_val (string_v));
3236 ret_v = caml_copy_double (w);
3237 CAMLreturn (ret_v);
3240 ML (measure_string (value pt_v, value string_v))
3242 CAMLparam2 (pt_v, string_v);
3243 CAMLlocal1 (ret_v);
3244 int pt = Int_val (pt_v);
3245 double w;
3247 w = (double) measure_string (state.face, pt, String_val (string_v));
3248 ret_v = caml_copy_double (w);
3249 CAMLreturn (ret_v);
3252 ML (getpagebox (value opaque_v))
3254 CAMLparam1 (opaque_v);
3255 CAMLlocal1 (ret_v);
3256 fz_rect rect;
3257 fz_irect bbox;
3258 fz_device *dev;
3259 const char *s = String_val (opaque_v);
3260 struct page *page = parse_pointer (__func__, s);
3262 ret_v = caml_alloc_tuple (4);
3263 dev = fz_new_bbox_device (state.ctx, &rect);
3265 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3267 fz_close_device (state.ctx, dev);
3268 fz_drop_device (state.ctx, dev);
3269 bbox = fz_round_rect (rect);
3270 Field (ret_v, 0) = Val_int (bbox.x0);
3271 Field (ret_v, 1) = Val_int (bbox.y0);
3272 Field (ret_v, 2) = Val_int (bbox.x1);
3273 Field (ret_v, 3) = Val_int (bbox.y1);
3275 CAMLreturn (ret_v);
3278 ML0 (setaalevel (value level_v))
3280 CAMLparam1 (level_v);
3282 state.aalevel = Int_val (level_v);
3283 CAMLreturn0;
3286 ML0 (setpapercolor (value rgba_v))
3288 CAMLparam1 (rgba_v);
3290 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3291 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3292 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3293 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3294 CAMLreturn0;
3297 value ml_keysymtoutf8 (value keysym_v);
3298 #ifndef CIDER
3299 value ml_keysymtoutf8 (value keysym_v)
3301 CAMLparam1 (keysym_v);
3302 CAMLlocal1 (str_v);
3303 unsigned short keysym = (unsigned short) Int_val (keysym_v);
3304 Rune rune;
3305 extern long keysym2ucs (unsigned short);
3306 int len;
3307 char buf[5];
3309 rune = (Rune) keysym2ucs (keysym);
3310 len = fz_runetochar (buf, rune);
3311 buf[len] = 0;
3312 str_v = caml_copy_string (buf);
3313 CAMLreturn (str_v);
3315 #else
3316 value ml_keysymtoutf8 (value keysym_v)
3318 CAMLparam1 (keysym_v);
3319 CAMLlocal1 (str_v);
3320 long ucs = Long_val (keysym_v);
3321 int len;
3322 char buf[5];
3324 len = fz_runetochar (buf, (int) ucs);
3325 buf[len] = 0;
3326 str_v = caml_copy_string (buf);
3327 CAMLreturn (str_v);
3329 #endif
3331 enum { piunknown, pilinux, pimacos, pibsd };
3333 ML (platform (value unit_v))
3335 CAMLparam1 (unit_v);
3336 CAMLlocal2 (tup_v, arr_v);
3337 int platid = piunknown;
3338 struct utsname buf;
3340 #if defined __linux__
3341 platid = pilinux;
3342 #elif defined __DragonFly__ || defined __FreeBSD__
3343 || defined __OpenBSD__ || defined __NetBSD__
3344 platid = pibsd;
3345 #elif defined __APPLE__
3346 platid = pimacos;
3347 #endif
3348 if (uname (&buf)) err (1, "uname");
3350 tup_v = caml_alloc_tuple (2);
3352 char const *sar[] = {
3353 buf.sysname,
3354 buf.release,
3355 buf.version,
3356 buf.machine,
3357 NULL
3359 arr_v = caml_copy_string_array (sar);
3361 Field (tup_v, 0) = Val_int (platid);
3362 Field (tup_v, 1) = arr_v;
3363 CAMLreturn (tup_v);
3366 ML0 (cloexec (value fd_v))
3368 CAMLparam1 (fd_v);
3369 int fd = Int_val (fd_v);
3371 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3372 uerror ("fcntl", Nothing);
3374 CAMLreturn0;
3377 ML (getpbo (value w_v, value h_v, value cs_v))
3379 CAMLparam2 (w_v, h_v);
3380 CAMLlocal1 (ret_v);
3381 struct bo *pbo;
3382 int w = Int_val (w_v);
3383 int h = Int_val (h_v);
3384 int cs = Int_val (cs_v);
3386 if (state.bo_usable) {
3387 pbo = calloc (sizeof (*pbo), 1);
3388 if (!pbo) {
3389 err (1, "calloc pbo");
3392 switch (cs) {
3393 case 0:
3394 case 1:
3395 pbo->size = w*h*4;
3396 break;
3397 case 2:
3398 pbo->size = w*h*2;
3399 break;
3400 default:
3401 errx (1, "%s: invalid colorspace %d", __func__, cs);
3404 state.glGenBuffersARB (1, &pbo->id);
3405 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3406 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3407 NULL, GL_STREAM_DRAW);
3408 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3409 GL_READ_WRITE);
3410 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3411 if (!pbo->ptr) {
3412 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3413 state.glDeleteBuffersARB (1, &pbo->id);
3414 free (pbo);
3415 ret_v = caml_copy_string ("0");
3417 else {
3418 int res;
3419 char *s;
3421 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3422 if (res < 0) {
3423 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3425 s = malloc (res+1);
3426 if (!s) {
3427 err (1, "malloc %d bytes failed", res+1);
3429 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3430 if (res < 0) {
3431 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3433 ret_v = caml_copy_string (s);
3434 free (s);
3437 else {
3438 ret_v = caml_copy_string ("0");
3440 CAMLreturn (ret_v);
3443 ML0 (freepbo (value s_v))
3445 CAMLparam1 (s_v);
3446 const char *s = String_val (s_v);
3447 struct tile *tile = parse_pointer (__func__, s);
3449 if (tile->pbo) {
3450 state.glDeleteBuffersARB (1, &tile->pbo->id);
3451 tile->pbo->id = -1;
3452 tile->pbo->ptr = NULL;
3453 tile->pbo->size = -1;
3455 CAMLreturn0;
3458 ML0 (unmappbo (value s_v))
3460 CAMLparam1 (s_v);
3461 const char *s = String_val (s_v);
3462 struct tile *tile = parse_pointer (__func__, s);
3464 if (tile->pbo) {
3465 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3466 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3467 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3469 tile->pbo->ptr = NULL;
3470 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3472 CAMLreturn0;
3475 static void setuppbo (void)
3477 extern void (*wsigladdr (const char *name)) (void);
3478 #pragma GCC diagnostic push
3479 #ifdef __clang__
3480 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3481 #endif
3482 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3483 state.bo_usable = GPA (glBindBufferARB)
3484 && GPA (glUnmapBufferARB)
3485 && GPA (glMapBufferARB)
3486 && GPA (glBufferDataARB)
3487 && GPA (glGenBuffersARB)
3488 && GPA (glDeleteBuffersARB);
3489 #undef GPA
3490 #pragma GCC diagnostic pop
3493 ML (bo_usable (void))
3495 return Val_bool (state.bo_usable);
3498 ML (unproject (value ptr_v, value x_v, value y_v))
3500 CAMLparam3 (ptr_v, x_v, y_v);
3501 CAMLlocal2 (ret_v, tup_v);
3502 struct page *page;
3503 const char *s = String_val (ptr_v);
3504 int x = Int_val (x_v), y = Int_val (y_v);
3505 struct pagedim *pdim;
3506 fz_point p;
3508 page = parse_pointer (__func__, s);
3509 pdim = &state.pagedims[page->pdimno];
3511 ret_v = Val_int (0);
3512 if (trylock (__func__)) {
3513 goto done;
3516 p.x = x + pdim->bounds.x0;
3517 p.y = y + pdim->bounds.y0;
3519 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3520 pdim->ctm)));
3522 tup_v = caml_alloc_tuple (2);
3523 ret_v = caml_alloc_small (1, 1);
3524 Field (tup_v, 0) = Val_int (p.x);
3525 Field (tup_v, 1) = Val_int (p.y);
3526 Field (ret_v, 0) = tup_v;
3528 unlock (__func__);
3529 done:
3530 CAMLreturn (ret_v);
3533 ML (project (value ptr_v, value pageno_v, value pdimno_v, value x_v, value y_v))
3535 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3536 CAMLlocal1 (ret_v);
3537 struct page *page;
3538 const char *s = String_val (ptr_v);
3539 int pageno = Int_val (pageno_v);
3540 int pdimno = Int_val (pdimno_v);
3541 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3542 struct pagedim *pdim;
3543 fz_point p;
3544 fz_matrix ctm;
3546 ret_v = Val_int (0);
3547 lock (__func__);
3549 if (!*s) {
3550 page = loadpage (pageno, pdimno);
3552 else {
3553 page = parse_pointer (__func__, s);
3555 pdim = &state.pagedims[pdimno];
3557 if (pdf_specifics (state.ctx, state.doc)) {
3558 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3559 ctm = state.pagedims[page->pdimno].tctm;
3561 else {
3562 ctm = fz_identity;
3564 p.x = x + pdim->bounds.x0;
3565 p.y = y + pdim->bounds.y0;
3567 ctm = fz_concat (pdim->tctm, pdim->ctm);
3568 p = fz_transform_point (p, ctm);
3570 ret_v = caml_alloc_tuple (2);
3571 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3572 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3574 if (!*s) {
3575 freepage (page);
3577 unlock (__func__);
3578 CAMLreturn (ret_v);
3581 ML0 (addannot (value ptr_v, value x_v, value y_v, value contents_v))
3583 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3584 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3586 if (pdf) {
3587 pdf_annot *annot;
3588 struct page *page;
3589 fz_rect r;
3590 const char *s = String_val (ptr_v);
3592 page = parse_pointer (__func__, s);
3593 annot = pdf_create_annot (state.ctx,
3594 pdf_page_from_fz_page (state.ctx,
3595 page->fzpage),
3596 PDF_ANNOT_TEXT);
3597 r.x0 = Int_val (x_v) - 10;
3598 r.y0 = Int_val (y_v) - 10;
3599 r.x1 = r.x0 + 20;
3600 r.y1 = r.y0 + 20;
3601 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3602 pdf_set_annot_rect (state.ctx, annot, r);
3604 state.dirty = 1;
3606 CAMLreturn0;
3609 ML0 (delannot (value ptr_v, value n_v))
3611 CAMLparam2 (ptr_v, n_v);
3612 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3614 if (pdf) {
3615 struct page *page;
3616 const char *s = String_val (ptr_v);
3617 struct slink *slink;
3619 page = parse_pointer (__func__, s);
3620 slink = &page->slinks[Int_val (n_v)];
3621 pdf_delete_annot (state.ctx,
3622 pdf_page_from_fz_page (state.ctx, page->fzpage),
3623 (pdf_annot *) slink->u.annot);
3624 state.dirty = 1;
3626 CAMLreturn0;
3629 ML0 (modannot (value ptr_v, value n_v, value str_v))
3631 CAMLparam3 (ptr_v, n_v, str_v);
3632 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3634 if (pdf) {
3635 struct page *page;
3636 const char *s = String_val (ptr_v);
3637 struct slink *slink;
3639 page = parse_pointer (__func__, s);
3640 slink = &page->slinks[Int_val (n_v)];
3641 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3642 String_val (str_v));
3643 state.dirty = 1;
3645 CAMLreturn0;
3648 ML (hasunsavedchanges (void))
3650 return Val_bool (state.dirty);
3653 ML0 (savedoc (value path_v))
3655 CAMLparam1 (path_v);
3656 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3658 if (pdf) {
3659 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3661 CAMLreturn0;
3664 static void makestippletex (void)
3666 const char pixels[] = "\xff\xff\0\0";
3667 glGenTextures (1, &state.stid);
3668 glBindTexture (GL_TEXTURE_1D, state.stid);
3669 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3670 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3671 glTexImage1D (
3672 GL_TEXTURE_1D,
3674 GL_ALPHA,
3677 GL_ALPHA,
3678 GL_UNSIGNED_BYTE,
3679 pixels
3683 ML (fz_version (void))
3685 return caml_copy_string (FZ_VERSION);
3688 ML (llpp_version (void))
3690 extern char llpp_version[];
3691 return caml_copy_string (llpp_version);
3694 static void diag_callback (void *user, const char *message)
3696 printd ("emsg %s %s", (char *) user, message);
3699 static fz_font *lsff (fz_context *ctx,int UNUSED_ATTR script,
3700 int UNUSED_ATTR language, int UNUSED_ATTR serif,
3701 int UNUSED_ATTR bold, int UNUSED_ATTR italic)
3703 static fz_font *font;
3704 static int done;
3706 if (!done) {
3707 char *path = getenv ("LLPP_FALLBACK_FONT");
3708 if (path) font = fz_new_font_from_file (ctx, NULL, path, 0, 1);
3709 done = 1;
3711 return font;
3714 ML0 (setdcf (value path_v))
3716 free (state.dcf);
3717 state.dcf = NULL;
3718 const char *p = String_val (path_v);
3719 size_t len = strlen (p);
3720 if (*p) {
3721 state.dcf = malloc (len + 1);
3722 if (!state.dcf) {
3723 err (1, "malloc dimpath %zu", len + 1);
3725 memcpy (state.dcf, p, len + 1);
3729 ML0 (init (value csock_v, value params_v))
3731 CAMLparam2 (csock_v, params_v);
3732 CAMLlocal2 (trim_v, fuzz_v);
3733 int ret;
3734 int texcount;
3735 const char *fontpath;
3736 int colorspace;
3737 int mustoresize;
3739 state.csock = Int_val (csock_v);
3740 state.rotate = Int_val (Field (params_v, 0));
3741 state.fitmodel = Int_val (Field (params_v, 1));
3742 trim_v = Field (params_v, 2);
3743 texcount = Int_val (Field (params_v, 3));
3744 state.sliceheight = Int_val (Field (params_v, 4));
3745 mustoresize = Int_val (Field (params_v, 5));
3746 colorspace = Int_val (Field (params_v, 6));
3747 fontpath = String_val (Field (params_v, 7));
3749 #ifdef CIDER
3750 state.utf8cs = 1;
3751 #else
3752 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3753 if (setlocale (LC_CTYPE, "")) {
3754 const char *cset = nl_langinfo (CODESET);
3755 state.utf8cs = !strcmp (cset, "UTF-8");
3757 else {
3758 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3760 #endif
3762 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3763 fz_register_document_handlers (state.ctx);
3764 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3765 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3766 fz_install_load_system_font_funcs (state.ctx, NULL, NULL, lsff);
3768 state.trimmargins = Bool_val (Field (trim_v, 0));
3769 fuzz_v = Field (trim_v, 1);
3770 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3771 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3772 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3773 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3775 set_tex_params (colorspace);
3777 if (*fontpath) {
3778 state.face = load_font (fontpath);
3780 else {
3781 int len;
3782 const unsigned char *data;
3784 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3785 state.face = load_builtin_font (data, len);
3787 if (!state.face) _exit (1);
3789 realloctexts (texcount);
3790 setuppbo ();
3791 makestippletex ();
3793 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3794 if (ret) {
3795 errx (1, "pthread_create: %s", strerror (ret));
3798 CAMLreturn0;
3801 #if FIXME || !FIXME
3802 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3803 #endif