Fix subtle build.bash issue
[llpp.git] / link.c
blob0e87e54396344a3707d18f70c341ef097fa15441
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; } tab[] = {
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, need;
387 char *buf = NULL;
389 for (size_t i = 0; i < sizeof (tab) / sizeof (*tab); ++i) {
390 again:
391 need = fz_lookup_metadata (state.ctx, state.doc, tab[i].tag, buf, len);
392 if (need > 0) {
393 if (need <= len) {
394 printd ("info %s\t%s", tab[i].name, buf);
396 else {
397 buf = realloc (buf, need + 1);
398 if (!buf) err (1, "docinfo realloc %d", need + 1);
399 len = need + 1;
400 goto again;
404 free (buf);
406 printd ("infoend");
409 static void unlinktile (struct tile *tile)
411 for (int i = 0; i < tile->slicecount; ++i) {
412 struct slice *s = &tile->slices[i];
414 if (s->texindex != -1) {
415 if (state.tex.owners[s->texindex].slice == s) {
416 state.tex.owners[s->texindex].slice = NULL;
422 static void freepage (struct page *page)
424 if (!page) return;
425 if (page->text) {
426 fz_drop_stext_page (state.ctx, page->text);
428 if (page->slinks) {
429 free (page->slinks);
431 fz_drop_display_list (state.ctx, page->dlist);
432 fz_drop_page (state.ctx, page->fzpage);
433 free (page);
436 static void freetile (struct tile *tile)
438 unlinktile (tile);
439 if (!tile->pbo) {
440 #if 0
441 fz_drop_pixmap (state.ctx, tile->pixmap);
442 #else /* piggyback */
443 if (state.pig) {
444 fz_drop_pixmap (state.ctx, state.pig);
446 state.pig = tile->pixmap;
447 #endif
449 else {
450 free (tile->pbo);
451 fz_drop_pixmap (state.ctx, tile->pixmap);
453 free (tile);
456 static void trimctm (pdf_page *page, int pindex)
458 struct pagedim *pdim = &state.pagedims[pindex];
460 if (!page) return;
461 if (!pdim->tctmready) {
462 fz_rect realbox, mediabox;
463 fz_matrix page_ctm, ctm;
465 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
466 realbox = fz_transform_rect (pdim->mediabox, ctm);
467 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
468 pdim->tctm = fz_concat (
469 fz_invert_matrix (page_ctm),
470 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
471 pdim->tctmready = 1;
475 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
477 fz_matrix ctm;
478 ptrdiff_t pdimno = pdim - state.pagedims;
480 ARSERT (pdim - state.pagedims < INT_MAX);
481 if (pdf_specifics (state.ctx, state.doc)) {
482 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
483 ctm = fz_concat (pdim->tctm, pdim->ctm);
485 else {
486 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
487 pdim->ctm);
489 return ctm;
492 static fz_matrix pagectm (struct page *page)
494 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
497 static void *loadpage (int pageno, int pindex)
499 fz_device *dev;
500 struct page *page;
502 page = calloc (sizeof (struct page), 1);
503 if (!page) {
504 err (1, "calloc page %d", pageno);
507 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
508 dev = fz_new_list_device (state.ctx, page->dlist);
509 fz_try (state.ctx) {
510 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
511 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
513 fz_catch (state.ctx) {
514 page->fzpage = NULL;
516 fz_close_device (state.ctx, dev);
517 fz_drop_device (state.ctx, dev);
519 page->pdimno = pindex;
520 page->pageno = pageno;
521 page->sgen = state.gen;
522 page->agen = state.gen;
523 page->tgen = state.gen;
524 return page;
527 static struct tile *alloctile (int h)
529 int slicecount;
530 size_t tilesize;
531 struct tile *tile;
533 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
534 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
535 tile = calloc (tilesize, 1);
536 if (!tile) {
537 err (1, "cannot allocate tile (%zu bytes)", tilesize);
539 for (int i = 0; i < slicecount; ++i) {
540 int sh = fz_mini (h, state.sliceheight);
541 tile->slices[i].h = sh;
542 tile->slices[i].texindex = -1;
543 h -= sh;
545 tile->slicecount = slicecount;
546 tile->sliceheight = state.sliceheight;
547 return tile;
550 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
551 struct bo *pbo)
553 fz_irect bbox;
554 fz_matrix ctm;
555 fz_device *dev;
556 struct tile *tile;
557 struct pagedim *pdim;
559 tile = alloctile (h);
560 pdim = &state.pagedims[page->pdimno];
562 bbox = pdim->bounds;
563 bbox.x0 += x;
564 bbox.y0 += y;
565 bbox.x1 = bbox.x0 + w;
566 bbox.y1 = bbox.y0 + h;
568 if (state.pig) {
569 if (state.pig->w == w
570 && state.pig->h == h
571 && state.pig->colorspace == state.colorspace) {
572 tile->pixmap = state.pig;
573 tile->pixmap->x = bbox.x0;
574 tile->pixmap->y = bbox.y0;
576 else {
577 fz_drop_pixmap (state.ctx, state.pig);
579 state.pig = NULL;
581 if (!tile->pixmap) {
582 if (pbo) {
583 tile->pixmap =
584 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
585 bbox, NULL, 1, pbo->ptr);
586 tile->pbo = pbo;
588 else {
589 tile->pixmap =
590 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
591 NULL, 1);
595 tile->w = w;
596 tile->h = h;
597 fz_fill_pixmap_with_color (state.ctx, tile->pixmap,
598 fz_device_rgb (state.ctx),
599 state.papercolor,
600 fz_default_color_params);
602 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
603 ctm = pagectm (page);
604 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
605 fz_rect_from_irect (bbox), NULL);
606 fz_close_device (state.ctx, dev);
607 fz_drop_device (state.ctx, dev);
609 return tile;
612 static void initpdims1 (void)
614 struct pagedim *p;
615 pdf_document *pdf;
616 fz_context *ctx = state.ctx;
617 int pageno, trim, show, cxcount;
618 fz_rect rootmediabox = fz_empty_rect;
620 fz_var (p);
621 fz_var (pdf);
622 fz_var (cxcount);
624 cxcount = state.pagecount;
625 if ((pdf = pdf_specifics (ctx, state.doc))) {
626 pdf_obj *obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
627 "Root/Pages/MediaBox");
628 rootmediabox = pdf_to_rect (ctx, obj);
629 pdf_load_page_tree (ctx, pdf);
632 for (pageno = 0; pageno < cxcount; ++pageno) {
633 int rotate = 0;
634 fz_rect mediabox = fz_empty_rect;
636 fz_var (rotate);
637 if (pdf) {
638 pdf_obj *pageobj = NULL;
640 fz_var (pageobj);
641 if (pdf->rev_page_map) {
642 for (int i = 0; i < pdf->rev_page_count; ++i) {
643 if (pdf->rev_page_map[i].page == pageno) {
644 pageobj = pdf_get_xref_entry (
645 ctx, pdf, pdf->rev_page_map[i].object
646 )->obj;
647 break;
651 if (!pageobj) {
652 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
655 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
657 if (state.trimmargins) {
658 pdf_obj *obj;
659 pdf_page *page;
661 fz_try (ctx) {
662 page = pdf_load_page (ctx, pdf, pageno);
663 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
664 trim = state.trimanew || !obj;
665 if (trim) {
666 fz_rect rect;
667 fz_device *dev;
668 fz_matrix ctm, page_ctm;
670 dev = fz_new_bbox_device (ctx, &rect);
671 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
672 ctm = fz_invert_matrix (page_ctm);
673 pdf_run_page (ctx, page, dev, fz_identity, NULL);
674 fz_close_device (ctx, dev);
675 fz_drop_device (ctx, dev);
677 rect.x0 += state.trimfuzz.x0;
678 rect.x1 += state.trimfuzz.x1;
679 rect.y0 += state.trimfuzz.y0;
680 rect.y1 += state.trimfuzz.y1;
681 rect = fz_transform_rect (rect, ctm);
682 rect = fz_intersect_rect (rect, mediabox);
684 if (!fz_is_empty_rect (rect)) {
685 mediabox = rect;
688 obj = pdf_new_array (ctx, pdf, 4);
689 pdf_array_push_real (ctx, obj, mediabox.x0);
690 pdf_array_push_real (ctx, obj, mediabox.y0);
691 pdf_array_push_real (ctx, obj, mediabox.x1);
692 pdf_array_push_real (ctx, obj, mediabox.y1);
693 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
695 else {
696 mediabox.x0 = pdf_array_get_real (ctx, obj, 0);
697 mediabox.y0 = pdf_array_get_real (ctx, obj, 1);
698 mediabox.x1 = pdf_array_get_real (ctx, obj, 2);
699 mediabox.y1 = pdf_array_get_real (ctx, obj, 3);
702 fz_drop_page (ctx, &page->super);
703 show = (pageno + 1 == state.pagecount)
704 || (trim ? pageno % 5 == 0 : pageno % 20 == 0);
705 if (show) {
706 printd ("progress %f Trimming %d",
707 (double) (pageno + 1) / state.pagecount,
708 pageno + 1);
711 fz_catch (ctx) {
712 printd ("emsg failed to load page %d", pageno);
715 else {
716 int empty = 0;
717 fz_rect cropbox;
719 mediabox =
720 pdf_to_rect (ctx,
721 pdf_dict_get_inheritable (
722 ctx,
723 pageobj,
724 PDF_NAME (MediaBox)
727 if (fz_is_empty_rect (mediabox)) {
728 mediabox.x0 = 0;
729 mediabox.y0 = 0;
730 mediabox.x1 = 612;
731 mediabox.y1 = 792;
732 empty = 1;
735 cropbox =
736 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
737 if (!fz_is_empty_rect (cropbox)) {
738 if (empty) {
739 mediabox = cropbox;
741 else {
742 mediabox = fz_intersect_rect (mediabox, cropbox);
745 else {
746 if (empty) {
747 if (fz_is_empty_rect (rootmediabox)) {
748 printd ("emsg cannot find page size for page %d",
749 pageno);
751 else {
752 mediabox = rootmediabox;
758 else {
759 if (state.trimmargins) {
760 fz_page *page;
762 fz_try (ctx) {
763 page = fz_load_page (ctx, state.doc, pageno);
764 mediabox = fz_bound_page (ctx, page);
765 if (state.trimmargins) {
766 fz_rect rect;
767 fz_device *dev;
769 dev = fz_new_bbox_device (ctx, &rect);
770 fz_run_page (ctx, page, dev, fz_identity, NULL);
771 fz_close_device (ctx, dev);
772 fz_drop_device (ctx, dev);
774 rect.x0 += state.trimfuzz.x0;
775 rect.x1 += state.trimfuzz.x1;
776 rect.y0 += state.trimfuzz.y0;
777 rect.y1 += state.trimfuzz.y1;
778 rect = fz_intersect_rect (rect, mediabox);
780 if (!fz_is_empty_rect (rect)) {
781 mediabox = rect;
784 fz_drop_page (ctx, page);
786 fz_catch (ctx) {
789 else {
790 fz_page *page;
791 fz_try (ctx) {
792 page = fz_load_page (ctx, state.doc, pageno);
793 mediabox = fz_bound_page (ctx, page);
794 fz_drop_page (ctx, page);
796 show = !state.trimmargins && pageno % 20 == 0;
797 if (show) {
798 printd ("progress %f Gathering dimensions %d",
799 (double) (pageno) / state.pagecount,
800 pageno);
803 fz_catch (ctx) {
804 printd ("emsg failed to load page %d", pageno);
808 if (state.pagedimcount == 0
809 || ((void) (p = &state.pagedims[state.pagedimcount-1])
810 , p->rotate != rotate)
811 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
812 size_t size;
814 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
815 state.pagedims = realloc (state.pagedims, size);
816 if (!state.pagedims) {
817 err (1, "realloc pagedims to %zu (%d elems)",
818 size, state.pagedimcount + 1);
821 p = &state.pagedims[state.pagedimcount++];
822 p->rotate = rotate;
823 p->mediabox = mediabox;
824 p->pageno = pageno;
827 state.trimanew = 0;
830 static void initpdims (void)
832 FILE *f = state.dcf ? fopen (state.dcf, "rb") : NULL;
833 if (f) {
834 size_t nread;
836 nread = fread (&state.pagedimcount, sizeof (state.pagedimcount),
837 1, f);
838 if (nread - 1) {
839 err (1, "fread pagedim %zu", sizeof (state.pagedimcount));
841 size_t size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
842 state.pagedims = realloc (state.pagedims, size);
843 if (!state.pagedims) {
844 err (1, "realloc pagedims to %zu (%d elems)",
845 size, state.pagedimcount + 1);
847 if (fread (state.pagedims,
848 sizeof (*state.pagedims),
849 state.pagedimcount+1,
850 f) - (state.pagedimcount+1)) {
851 err (1, "fread pagedim data %zu %d",
852 sizeof (*state.pagedims), state.pagedimcount+1);
854 fclose (f);
857 if (!state.pagedims) {
858 initpdims1 ();
859 if (state.dcf) {
860 f = fopen (state.dcf, "wb");
861 if (!f) {
862 err (1, "fopen %s for writing", state.dcf);
864 if (fwrite (&state.pagedimcount,
865 sizeof (state.pagedimcount), 1, f) - 1) {
866 err (1, "fwrite pagedimcunt %zu", sizeof (state.pagedimcount));
868 if (fwrite (state.pagedims, sizeof (*state.pagedims),
869 state.pagedimcount + 1, f)
870 - (state.pagedimcount + 1)) {
871 err (1, "fwrite pagedim data %zu %u",
872 sizeof (*state.pagedims), state.pagedimcount+1);
873 } fclose (f);
878 static void layout (void)
880 int pindex;
881 fz_rect box;
882 fz_matrix ctm;
883 struct pagedim *p = NULL;
884 float zw, w, maxw = 0.0, zoom = 1.0;
886 if (state.pagedimcount == 0) return;
888 switch (state.fitmodel) {
889 case FitProportional:
890 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
891 float x0, x1;
893 p = &state.pagedims[pindex];
894 box = fz_transform_rect (p->mediabox,
895 fz_rotate (p->rotate + state.rotate));
897 x0 = fz_min (box.x0, box.x1);
898 x1 = fz_max (box.x0, box.x1);
900 w = x1 - x0;
901 maxw = fz_max (w, maxw);
902 zoom = state.w / maxw;
904 break;
906 case FitPage:
907 maxw = state.w;
908 break;
910 case FitWidth:
911 break;
913 default:
914 ARSERT (0 && state.fitmodel);
917 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
918 p = &state.pagedims[pindex];
919 ctm = fz_rotate (state.rotate);
920 box = fz_transform_rect (p->mediabox,
921 fz_rotate (p->rotate + state.rotate));
922 w = box.x1 - box.x0;
923 switch (state.fitmodel) {
924 case FitProportional:
925 p->left = (int) (((maxw - w) * zoom) / 2.f);
926 break;
927 case FitPage:
929 float zh, h;
930 zw = maxw / w;
931 h = box.y1 - box.y0;
932 zh = state.h / h;
933 zoom = fz_min (zw, zh);
934 p->left = (int) ((maxw - (w * zoom)) / 2.f);
936 break;
937 case FitWidth:
938 p->left = 0;
939 zoom = state.w / w;
940 break;
943 p->zoomctm = fz_scale (zoom, zoom);
944 ctm = fz_concat (p->zoomctm, ctm);
946 p->pagebox = p->mediabox;
947 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
948 p->pagebox.x1 -= p->pagebox.x0;
949 p->pagebox.y1 -= p->pagebox.y0;
950 p->pagebox.x0 = 0;
951 p->pagebox.y0 = 0;
952 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
953 p->ctm = ctm;
955 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
956 fz_scale (zoom, -zoom));
957 p->tctmready = 0;
960 do {
961 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
962 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
963 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
964 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
965 int boundw = x1 - x0;
966 int boundh = y1 - y0;
968 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
969 } while (p-- != state.pagedims);
972 static struct pagedim *pdimofpageno (int pageno)
974 struct pagedim *pdim = state.pagedims;
976 for (int i = 0; i < state.pagedimcount; ++i) {
977 if (state.pagedims[i].pageno > pageno)
978 break;
979 pdim = &state.pagedims[i];
981 return pdim;
984 static void recurse_outline (fz_outline *outline, int level)
986 while (outline) {
987 if (outline->page >= 0) {
988 fz_point p = {.x = outline->x, .y = outline->y};
989 struct pagedim *pdim = pdimofpageno (outline->page);
990 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
991 p = fz_transform_point (p, pdim->ctm);
992 printd ("o %d %d %d %d %s",
993 level, outline->page, (int) p.y, h, outline->title);
995 else {
996 printd ("on %d %s", level, outline->title);
998 if (outline->down) {
999 recurse_outline (outline->down, level + 1);
1001 outline = outline->next;
1005 static void process_outline (void)
1007 fz_outline *outline;
1009 if (!state.needoutline || !state.pagedimcount) return;
1011 state.needoutline = 0;
1012 outline = fz_load_outline (state.ctx, state.doc);
1013 if (outline) {
1014 recurse_outline (outline, 0);
1015 fz_drop_outline (state.ctx, outline);
1019 static char *strofline (fz_stext_line *line)
1021 char *p;
1022 char utf8[10];
1023 fz_stext_char *ch;
1024 size_t size = 0, cap = 80;
1026 p = malloc (cap + 1);
1027 if (!p) return NULL;
1029 for (ch = line->first_char; ch; ch = ch->next) {
1030 int n = fz_runetochar (utf8, ch->c);
1031 if (size + n > cap) {
1032 cap *= 2;
1033 p = realloc (p, cap + 1);
1034 if (!p) return NULL;
1037 memcpy (p + size, utf8, n);
1038 size += n;
1040 p[size] = 0;
1041 return p;
1044 static int matchline (regex_t *re, fz_stext_line *line,
1045 int stop, int pageno, double start)
1047 int ret;
1048 char *p;
1049 regmatch_t rm;
1051 p = strofline (line);
1052 if (!p) return -1;
1054 ret = regexec (re, p, 1, &rm, 0);
1055 if (ret) {
1056 free (p);
1057 if (ret != REG_NOMATCH) {
1058 size_t size;
1059 char errbuf[80];
1060 size = regerror (ret, re, errbuf, sizeof (errbuf));
1061 printd ("msg regexec error `%.*s'",
1062 (int) size, errbuf);
1063 return -1;
1065 return 0;
1067 else {
1068 fz_quad s, e;
1069 fz_stext_char *ch;
1070 int o = 0;
1072 for (ch = line->first_char; ch; ch = ch->next) {
1073 o += fz_runelen (ch->c);
1074 if (o > rm.rm_so) {
1075 s = ch->quad;
1076 break;
1079 for (;ch; ch = ch->next) {
1080 o += fz_runelen (ch->c);
1081 if (o > rm.rm_eo) break;
1083 e = ch->quad;
1085 if (!stop) {
1086 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1087 pageno, 1,
1088 s.ul.x, s.ul.y,
1089 e.ur.x, s.ul.y,
1090 e.lr.x, e.lr.y,
1091 s.ul.x, e.lr.y);
1093 printd ("progress 1 found at %d `%.*s' in %f sec",
1094 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1095 now () - start);
1097 else {
1098 printd ("match %d %d %f %f %f %f %f %f %f %f",
1099 pageno, 2,
1100 s.ul.x, s.ul.y,
1101 e.ur.x, s.ul.y,
1102 e.lr.x, e.lr.y,
1103 s.ul.x, e.lr.y);
1105 free (p);
1106 return 1;
1110 /* wishful thinking function */
1111 static void search (regex_t *re, int pageno, int y, int forward)
1113 fz_device *tdev;
1114 fz_stext_page *text;
1115 struct pagedim *pdim;
1116 int stop = 0, niters = 0;
1117 double start, end;
1118 fz_page *page;
1119 fz_stext_block *block;
1121 start = now ();
1122 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1123 if (niters++ == 5) {
1124 niters = 0;
1125 if (hasdata ()) {
1126 printd ("progress 1 attention requested aborting search at %d",
1127 pageno);
1128 stop = 1;
1130 else {
1131 printd ("progress %f searching in page %d",
1132 (double) (pageno + 1) / state.pagecount,
1133 pageno);
1136 pdim = pdimofpageno (pageno);
1137 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1138 tdev = fz_new_stext_device (state.ctx, text, 0);
1140 page = fz_load_page (state.ctx, state.doc, pageno);
1141 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1143 fz_close_device (state.ctx, tdev);
1144 fz_drop_device (state.ctx, tdev);
1146 if (forward) {
1147 for (block = text->first_block; block; block = block->next) {
1148 fz_stext_line *line;
1150 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1151 for (line = block->u.t.first_line; line; line = line->next) {
1152 if (line->bbox.y0 < y + 1) continue;
1154 switch (matchline (re, line, stop, pageno, start)) {
1155 case 0: break;
1156 case 1: stop = 1; break;
1157 case -1: stop = 1; goto endloop;
1162 else {
1163 for (block = text->last_block; block; block = block->prev) {
1164 fz_stext_line *line;
1166 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1167 for (line = block->u.t.last_line; line; line = line->prev) {
1168 if (line->bbox.y0 < y + 1) continue;
1170 switch (matchline (re, line, stop, pageno, start)) {
1171 case 0: break;
1172 case 1: stop = 1; break;
1173 case -1: stop = 1; goto endloop;
1179 if (forward) {
1180 pageno += 1;
1181 y = 0;
1183 else {
1184 pageno -= 1;
1185 y = INT_MAX;
1187 endloop:
1188 fz_drop_stext_page (state.ctx, text);
1189 fz_drop_page (state.ctx, page);
1191 end = now ();
1192 if (!stop) {
1193 printd ("progress 1 no matches %f sec", end - start);
1195 printd ("clearrects");
1198 static void set_tex_params (int colorspace)
1200 switch (colorspace) {
1201 case 0:
1202 state.tex.iform = GL_RGBA8;
1203 state.tex.form = GL_RGBA;
1204 state.tex.ty = GL_UNSIGNED_BYTE;
1205 state.colorspace = fz_device_rgb (state.ctx);
1206 break;
1207 case 1:
1208 state.tex.iform = GL_LUMINANCE_ALPHA;
1209 state.tex.form = GL_LUMINANCE_ALPHA;
1210 state.tex.ty = GL_UNSIGNED_BYTE;
1211 state.colorspace = fz_device_gray (state.ctx);
1212 break;
1213 default:
1214 errx (1, "invalid colorspce %d", colorspace);
1218 static void realloctexts (int texcount)
1220 size_t size;
1222 if (texcount == state.tex.count) return;
1224 if (texcount < state.tex.count) {
1225 glDeleteTextures (state.tex.count - texcount,
1226 state.tex.ids + texcount);
1229 size = texcount * (sizeof (*state.tex.ids) + sizeof (*state.tex.owners));
1230 state.tex.ids = realloc (state.tex.ids, size);
1231 if (!state.tex.ids) {
1232 err (1, "realloc texs %zu", size);
1235 state.tex.owners = (void *) (state.tex.ids + texcount);
1236 if (texcount > state.tex.count) {
1237 glGenTextures (texcount - state.tex.count,
1238 state.tex.ids + state.tex.count);
1239 for (int i = state.tex.count; i < texcount; ++i) {
1240 state.tex.owners[i].w = -1;
1241 state.tex.owners[i].slice = NULL;
1244 state.tex.count = texcount;
1245 state.tex.index = 0;
1248 static char *mbtoutf8 (char *s)
1250 char *p, *r;
1251 wchar_t *tmp;
1252 size_t i, ret, len;
1254 if (state.utf8cs) {
1255 return s;
1258 len = mbstowcs (NULL, s, strlen (s));
1259 if (len == 0 || len == (size_t) -1) {
1260 if (len)
1261 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1262 return s;
1265 tmp = calloc (len, sizeof (wchar_t));
1266 if (!tmp) {
1267 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1268 len, sizeof (wchar_t), errno, strerror (errno));
1269 return s;
1272 ret = mbstowcs (tmp, s, len);
1273 if (ret == (size_t) -1) {
1274 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1275 len, errno, strerror (errno));
1276 free (tmp);
1277 return s;
1280 len = 0;
1281 for (i = 0; i < ret; ++i) {
1282 len += fz_runelen (tmp[i]);
1285 p = r = malloc (len + 1);
1286 if (!r) {
1287 printd ("emsg mbtoutf8: malloc(%zu)", len);
1288 free (tmp);
1289 return s;
1292 for (i = 0; i < ret; ++i) {
1293 p += fz_runetochar (p, tmp[i]);
1295 *p = 0;
1296 free (tmp);
1297 return r;
1300 ML (mbtoutf8 (value s_v))
1302 CAMLparam1 (s_v);
1303 CAMLlocal1 (ret_v);
1304 char *s, *r;
1306 s = &Byte (s_v, 0);
1307 r = mbtoutf8 (s);
1308 if (r == s) {
1309 ret_v = s_v;
1311 else {
1312 ret_v = caml_copy_string (r);
1313 free (r);
1315 CAMLreturn (ret_v);
1318 static void * mainloop (void UNUSED_ATTR *unused)
1320 char *p = NULL;
1321 int len, ret, oldlen = 0;
1323 fz_var (p);
1324 fz_var (oldlen);
1325 for (;;) {
1326 len = readlen (state.csock);
1327 if (len == 0) {
1328 errx (1, "readlen returned 0");
1331 if (oldlen < len + 1) {
1332 p = realloc (p, len + 1);
1333 if (!p) {
1334 err (1, "realloc %d failed", len + 1);
1336 oldlen = len + 1;
1338 readdata (state.csock, p, len);
1339 p[len] = 0;
1341 if (!strncmp ("open", p, 4)) {
1342 int off, usedoccss, ok = 0, layouth;
1343 char *password;
1344 char *filename;
1345 char *utf8filename;
1346 size_t filenamelen;
1348 fz_var (ok);
1349 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1350 if (ret != 2) {
1351 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1354 filename = p + 5 + off;
1355 filenamelen = strlen (filename);
1356 password = filename + filenamelen + 1;
1358 if (password[strlen (password) + 1]) {
1359 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1362 lock ("open");
1363 fz_set_use_document_css (state.ctx, usedoccss);
1364 fz_try (state.ctx) {
1365 ok = openxref (filename, password, layouth);
1367 fz_catch (state.ctx) {
1368 utf8filename = mbtoutf8 (filename);
1369 printd ("emsg Error loading %s: %s",
1370 utf8filename, fz_caught_message (state.ctx));
1371 if (utf8filename != filename) {
1372 free (utf8filename);
1375 if (ok) {
1376 docinfo ();
1377 initpdims ();
1379 unlock ("open");
1380 state.needoutline = ok;
1382 else if (!strncmp ("cs", p, 2)) {
1383 int i, colorspace;
1385 ret = sscanf (p + 2, " %d", &colorspace);
1386 if (ret != 1) {
1387 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1389 lock ("cs");
1390 set_tex_params (colorspace);
1391 for (i = 0; i < state.tex.count; ++i) {
1392 state.tex.owners[i].w = -1;
1393 state.tex.owners[i].slice = NULL;
1395 unlock ("cs");
1397 else if (!strncmp ("freepage", p, 8)) {
1398 void *ptr;
1400 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1401 if (ret != 1) {
1402 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1404 lock ("freepage");
1405 freepage (ptr);
1406 unlock ("freepage");
1408 else if (!strncmp ("freetile", p, 8)) {
1409 void *ptr;
1411 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1412 if (ret != 1) {
1413 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1415 lock ("freetile");
1416 freetile (ptr);
1417 unlock ("freetile");
1419 else if (!strncmp ("search", p, 6)) {
1420 int icase, pageno, y, len2, forward;
1421 char *pattern;
1422 regex_t re;
1424 ret = sscanf (p + 6, " %d %d %d %d,%n",
1425 &icase, &pageno, &y, &forward, &len2);
1426 if (ret != 4) {
1427 errx (1, "malformed search `%s' ret=%d", p, ret);
1430 pattern = p + 6 + len2;
1431 ret = regcomp (&re, pattern,
1432 REG_EXTENDED | (icase ? REG_ICASE : 0));
1433 if (ret) {
1434 char errbuf[80];
1435 size_t size;
1437 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1438 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1440 else {
1441 lock ("search");
1442 search (&re, pageno, y, forward);
1443 unlock ("search");
1444 regfree (&re);
1447 else if (!strncmp ("geometry", p, 8)) {
1448 int w, h, fitmodel;
1450 printd ("clear");
1451 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1452 if (ret != 3) {
1453 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1456 lock ("geometry");
1457 state.h = h;
1458 if (w != state.w) {
1459 state.w = w;
1460 for (int i = 0; i < state.tex.count; ++i) {
1461 state.tex.owners[i].slice = NULL;
1464 state.fitmodel = fitmodel;
1465 layout ();
1466 process_outline ();
1468 state.gen++;
1469 unlock ("geometry");
1470 printd ("continue %d", state.pagecount);
1472 else if (!strncmp ("reqlayout", p, 9)) {
1473 char *nameddest;
1474 int rotate, off, h;
1475 int fitmodel;
1476 pdf_document *pdf;
1478 printd ("clear");
1479 ret = sscanf (p + 9, " %d %d %d %n",
1480 &rotate, &fitmodel, &h, &off);
1481 if (ret != 3) {
1482 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1484 lock ("reqlayout");
1485 pdf = pdf_specifics (state.ctx, state.doc);
1486 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1487 state.gen += 1;
1489 state.rotate = rotate;
1490 state.fitmodel = fitmodel;
1491 state.h = h;
1492 layout ();
1493 process_outline ();
1495 nameddest = p + 9 + off;
1496 if (pdf && nameddest && *nameddest) {
1497 fz_point xy;
1498 struct pagedim *pdim;
1499 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1500 &xy.x, &xy.y);
1501 pdim = pdimofpageno (pageno);
1502 xy = fz_transform_point (xy, pdim->ctm);
1503 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1506 state.gen++;
1507 unlock ("reqlayout");
1508 printd ("continue %d", state.pagecount);
1510 else if (!strncmp ("page", p, 4)) {
1511 double a, b;
1512 struct page *page;
1513 int pageno, pindex;
1515 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1516 if (ret != 2) {
1517 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1520 lock ("page");
1521 a = now ();
1522 page = loadpage (pageno, pindex);
1523 b = now ();
1524 unlock ("page");
1526 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1528 else if (!strncmp ("tile", p, 4)) {
1529 int x, y, w, h;
1530 struct page *page;
1531 struct tile *tile;
1532 double a, b;
1533 void *data;
1535 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1536 (uintptr_t *) &page, &x, &y, &w, &h,
1537 (uintptr_t *) &data);
1538 if (ret != 6) {
1539 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1542 lock ("tile");
1543 a = now ();
1544 tile = rendertile (page, x, y, w, h, data);
1545 b = now ();
1546 unlock ("tile");
1548 printd ("tile %d %d %" PRIxPTR " %u %f",
1549 x, y, (uintptr_t) (tile),
1550 tile->w * tile->h * tile->pixmap->n,
1551 b - a);
1553 else if (!strncmp ("trimset", p, 7)) {
1554 fz_irect fuzz;
1555 int trimmargins;
1557 ret = sscanf (p + 7, " %d %d %d %d %d",
1558 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1559 if (ret != 5) {
1560 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1562 lock ("trimset");
1563 state.trimmargins = trimmargins;
1564 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1565 state.trimanew = 1;
1566 state.trimfuzz = fuzz;
1568 unlock ("trimset");
1570 else if (!strncmp ("settrim", p, 7)) {
1571 fz_irect fuzz;
1572 int trimmargins;
1574 ret = sscanf (p + 7, " %d %d %d %d %d",
1575 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1576 if (ret != 5) {
1577 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1579 printd ("clear");
1580 lock ("settrim");
1581 state.trimmargins = trimmargins;
1582 state.needoutline = 1;
1583 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1584 state.trimanew = 1;
1585 state.trimfuzz = fuzz;
1587 state.pagedimcount = 0;
1588 free (state.pagedims);
1589 state.pagedims = NULL;
1590 initpdims ();
1591 layout ();
1592 process_outline ();
1593 unlock ("settrim");
1594 printd ("continue %d", state.pagecount);
1596 else if (!strncmp ("sliceh", p, 6)) {
1597 int h;
1599 ret = sscanf (p + 6, " %d", &h);
1600 if (ret != 1) {
1601 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1603 if (h != state.sliceheight) {
1604 state.sliceheight = h;
1605 for (int i = 0; i < state.tex.count; ++i) {
1606 state.tex.owners[i].w = -1;
1607 state.tex.owners[i].h = -1;
1608 state.tex.owners[i].slice = NULL;
1612 else if (!strncmp ("interrupt", p, 9)) {
1613 printd ("vmsg interrupted");
1615 else {
1616 errx (1, "unknown command %.*s", len, p);
1619 return 0;
1622 ML (isexternallink (value uri_v))
1624 CAMLparam1 (uri_v);
1625 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1626 CAMLreturn (Val_bool (ext));
1629 ML (uritolocation (value uri_v))
1631 CAMLparam1 (uri_v);
1632 CAMLlocal1 (ret_v);
1633 int pageno;
1634 fz_point xy;
1635 struct pagedim *pdim;
1637 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1638 &xy.x, &xy.y).page;
1639 pdim = pdimofpageno (pageno);
1640 xy = fz_transform_point (xy, pdim->ctm);
1641 ret_v = caml_alloc_tuple (3);
1642 Field (ret_v, 0) = Val_int (pageno);
1643 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1644 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1645 CAMLreturn (ret_v);
1648 ML (realloctexts (value texcount_v))
1650 CAMLparam1 (texcount_v);
1651 int ok;
1653 if (trylock (__func__)) {
1654 ok = 0;
1655 goto done;
1657 realloctexts (Int_val (texcount_v));
1658 ok = 1;
1659 unlock (__func__);
1661 done:
1662 CAMLreturn (Val_bool (ok));
1665 static void recti (int x0, int y0, int x1, int y1)
1667 GLfloat *v = state.vertices;
1669 glVertexPointer (2, GL_FLOAT, 0, v);
1670 v[0] = x0; v[1] = y0;
1671 v[2] = x1; v[3] = y0;
1672 v[4] = x0; v[5] = y1;
1673 v[6] = x1; v[7] = y1;
1674 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1677 static void showsel (struct page *page, int ox, int oy)
1679 fz_irect bbox;
1680 fz_rect rect;
1681 fz_stext_block *block;
1682 int seen = 0;
1683 unsigned char selcolor[] = {15,15,15,140};
1685 if (!page->fmark || !page->lmark) return;
1687 glEnable (GL_BLEND);
1688 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1689 glColor4ubv (selcolor);
1691 ox += state.pagedims[page->pdimno].bounds.x0;
1692 oy += state.pagedims[page->pdimno].bounds.y0;
1694 for (block = page->text->first_block; block; block = block->next) {
1695 fz_stext_line *line;
1697 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1698 for (line = block->u.t.first_line; line; line = line->next) {
1699 fz_stext_char *ch;
1701 rect = fz_empty_rect;
1702 for (ch = line->first_char; ch; ch = ch->next) {
1703 fz_rect r;
1704 if (ch == page->fmark) seen = 1;
1705 r = fz_rect_from_quad (ch->quad);
1706 if (seen) rect = fz_union_rect (rect, r);
1707 if (ch == page->lmark) {
1708 bbox = fz_round_rect (rect);
1709 recti (bbox.x0 + ox, bbox.y0 + oy,
1710 bbox.x1 + ox, bbox.y1 + oy);
1711 goto done;
1714 bbox = fz_round_rect (rect);
1715 recti (bbox.x0 + ox, bbox.y0 + oy,
1716 bbox.x1 + ox, bbox.y1 + oy);
1719 done:
1720 glDisable (GL_BLEND);
1723 #pragma GCC diagnostic push
1724 #pragma GCC diagnostic ignored "-Wconversion"
1725 #include "glfont.c"
1726 #pragma GCC diagnostic pop
1728 static void stipplerect (fz_matrix m,
1729 fz_point p1,
1730 fz_point p2,
1731 fz_point p3,
1732 fz_point p4,
1733 GLfloat *texcoords,
1734 GLfloat *vertices)
1736 p1 = fz_transform_point (p1, m);
1737 p2 = fz_transform_point (p2, m);
1738 p3 = fz_transform_point (p3, m);
1739 p4 = fz_transform_point (p4, m);
1741 float w, h, s, t;
1743 w = p2.x - p1.x;
1744 h = p2.y - p1.y;
1745 t = hypotf (w, h) * .25f;
1747 w = p3.x - p2.x;
1748 h = p3.y - p2.y;
1749 s = hypotf (w, h) * .25f;
1751 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1752 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1754 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1755 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1757 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1758 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1760 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1761 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1763 glDrawArrays (GL_LINES, 0, 8);
1766 static void solidrect (fz_matrix m,
1767 fz_point p1,
1768 fz_point p2,
1769 fz_point p3,
1770 fz_point p4,
1771 GLfloat *vertices)
1773 p1 = fz_transform_point (p1, m);
1774 p2 = fz_transform_point (p2, m);
1775 p3 = fz_transform_point (p3, m);
1776 p4 = fz_transform_point (p4, m);
1777 vertices[0] = p1.x; vertices[1] = p1.y;
1778 vertices[2] = p2.x; vertices[3] = p2.y;
1780 vertices[4] = p3.x; vertices[5] = p3.y;
1781 vertices[6] = p4.x; vertices[7] = p4.y;
1782 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1785 static void ensurelinks (struct page *page)
1787 if (!page->links)
1788 page->links = fz_load_links (state.ctx, page->fzpage);
1791 static void highlightlinks (struct page *page, int xoff, int yoff)
1793 fz_matrix ctm;
1794 fz_link *link;
1795 GLfloat *texcoords = state.texcoords;
1796 GLfloat *vertices = state.vertices;
1798 ensurelinks (page);
1800 glEnable (GL_TEXTURE_1D);
1801 glEnable (GL_BLEND);
1802 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1803 glBindTexture (GL_TEXTURE_1D, state.stid);
1805 xoff -= state.pagedims[page->pdimno].bounds.x0;
1806 yoff -= state.pagedims[page->pdimno].bounds.y0;
1807 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1809 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1810 glVertexPointer (2, GL_FLOAT, 0, vertices);
1812 for (link = page->links; link; link = link->next) {
1813 fz_point p1, p2, p3, p4;
1815 p1.x = link->rect.x0;
1816 p1.y = link->rect.y0;
1818 p2.x = link->rect.x1;
1819 p2.y = link->rect.y0;
1821 p3.x = link->rect.x1;
1822 p3.y = link->rect.y1;
1824 p4.x = link->rect.x0;
1825 p4.y = link->rect.y1;
1827 /* TODO: different colours for different schemes */
1828 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1829 else glColor3ub (255, 0, 0);
1831 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1834 for (int i = 0; i < page->annotcount; ++i) {
1835 fz_point p1, p2, p3, p4;
1836 struct annot *annot = &page->annots[i];
1838 p1.x = annot->bbox.x0;
1839 p1.y = annot->bbox.y0;
1841 p2.x = annot->bbox.x1;
1842 p2.y = annot->bbox.y0;
1844 p3.x = annot->bbox.x1;
1845 p3.y = annot->bbox.y1;
1847 p4.x = annot->bbox.x0;
1848 p4.y = annot->bbox.y1;
1850 glColor3ub (0, 0, 128);
1851 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1854 glDisable (GL_BLEND);
1855 glDisable (GL_TEXTURE_1D);
1858 static int compareslinks (const void *l, const void *r)
1860 struct slink const *ls = l;
1861 struct slink const *rs = r;
1862 if (ls->bbox.y0 == rs->bbox.y0) {
1863 return ls->bbox.x0 - rs->bbox.x0;
1865 return ls->bbox.y0 - rs->bbox.y0;
1868 static void droptext (struct page *page)
1870 if (page->text) {
1871 fz_drop_stext_page (state.ctx, page->text);
1872 page->fmark = NULL;
1873 page->lmark = NULL;
1874 page->text = NULL;
1878 static void dropannots (struct page *page)
1880 if (page->annots) {
1881 free (page->annots);
1882 page->annots = NULL;
1883 page->annotcount = 0;
1887 static void ensureannots (struct page *page)
1889 int i, count = 0;
1890 size_t annotsize = sizeof (*page->annots);
1891 pdf_annot *annot;
1892 pdf_document *pdf;
1893 pdf_page *pdfpage;
1895 pdf = pdf_specifics (state.ctx, state.doc);
1896 if (!pdf) return;
1898 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1899 if (state.gen != page->agen) {
1900 dropannots (page);
1901 page->agen = state.gen;
1903 if (page->annots) return;
1905 for (annot = pdf_first_annot (state.ctx, pdfpage);
1906 annot;
1907 annot = pdf_next_annot (state.ctx, annot)) {
1908 count++;
1911 if (count > 0) {
1912 page->annotcount = count;
1913 page->annots = calloc (count, annotsize);
1914 if (!page->annots) {
1915 err (1, "calloc annots %d", count);
1918 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1919 annot;
1920 annot = pdf_next_annot (state.ctx, annot), i++) {
1921 fz_rect rect;
1923 rect = pdf_bound_annot (state.ctx, annot);
1924 page->annots[i].annot = annot;
1925 page->annots[i].bbox = fz_round_rect (rect);
1930 static void dropslinks (struct page *page)
1932 if (page->slinks) {
1933 free (page->slinks);
1934 page->slinks = NULL;
1935 page->slinkcount = 0;
1937 if (page->links) {
1938 fz_drop_link (state.ctx, page->links);
1939 page->links = NULL;
1943 static void ensureslinks (struct page *page)
1945 fz_matrix ctm;
1946 int i, count;
1947 size_t slinksize = sizeof (*page->slinks);
1948 fz_link *link;
1950 ensureannots (page);
1951 if (state.gen != page->sgen) {
1952 dropslinks (page);
1953 page->sgen = state.gen;
1955 if (page->slinks) return;
1957 ensurelinks (page);
1958 ctm = pagectm (page);
1960 count = page->annotcount;
1961 for (link = page->links; link; link = link->next) {
1962 count++;
1964 if (count > 0) {
1965 int j;
1967 page->slinkcount = count;
1968 page->slinks = calloc (count, slinksize);
1969 if (!page->slinks) {
1970 err (1, "calloc slinks %d", count);
1973 for (i = 0, link = page->links; link; ++i, link = link->next) {
1974 fz_rect rect;
1976 rect = link->rect;
1977 rect = fz_transform_rect (rect, ctm);
1978 page->slinks[i].tag = SLINK;
1979 page->slinks[i].u.link = link;
1980 page->slinks[i].bbox = fz_round_rect (rect);
1982 for (j = 0; j < page->annotcount; ++j, ++i) {
1983 fz_rect rect;
1984 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1985 rect = fz_transform_rect (rect, ctm);
1986 page->slinks[i].bbox = fz_round_rect (rect);
1988 page->slinks[i].tag = SANNOT;
1989 page->slinks[i].u.annot = page->annots[j].annot;
1991 qsort (page->slinks, count, slinksize, compareslinks);
1995 static void highlightslinks (struct page *page, int xoff, int yoff,
1996 int noff, const char *targ,
1997 mlsize_t tlen, int hfsize)
1999 char buf[40];
2000 struct slink *slink;
2001 float x0, y0, x1, y1, w;
2003 ensureslinks (page);
2004 glColor3ub (0xc3, 0xb0, 0x91);
2005 for (int i = 0; i < page->slinkcount; ++i) {
2006 fmt_linkn (buf, i + noff);
2007 if (!tlen || !strncmp (targ, buf, tlen)) {
2008 slink = &page->slinks[i];
2010 x0 = slink->bbox.x0 + xoff - 5;
2011 y1 = slink->bbox.y0 + yoff - 5;
2012 y0 = y1 + 10 + hfsize;
2013 w = measure_string (state.face, hfsize, buf);
2014 x1 = x0 + w + 10;
2015 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2019 glEnable (GL_BLEND);
2020 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2021 glEnable (GL_TEXTURE_2D);
2022 glColor3ub (0, 0, 0);
2023 for (int i = 0; i < page->slinkcount; ++i) {
2024 fmt_linkn (buf, i + noff);
2025 if (!tlen || !strncmp (targ, buf, tlen)) {
2026 slink = &page->slinks[i];
2028 x0 = slink->bbox.x0 + xoff;
2029 y0 = slink->bbox.y0 + yoff + hfsize;
2030 draw_string (state.face, hfsize, x0, y0, buf);
2033 glDisable (GL_TEXTURE_2D);
2034 glDisable (GL_BLEND);
2037 static void uploadslice (struct tile *tile, struct slice *slice)
2039 int offset;
2040 struct slice *slice1;
2041 unsigned char *texdata;
2043 offset = 0;
2044 for (slice1 = tile->slices; slice != slice1; slice1++) {
2045 offset += slice1->h * tile->w * tile->pixmap->n;
2047 if (slice->texindex != -1 && slice->texindex < state.tex.count
2048 && state.tex.owners[slice->texindex].slice == slice) {
2049 glBindTexture (TEXT_TYPE, state.tex.ids[slice->texindex]);
2051 else {
2052 int subimage = 0;
2053 int texindex = state.tex.index++ % state.tex.count;
2055 if (state.tex.owners[texindex].w == tile->w) {
2056 if (state.tex.owners[texindex].h >= slice->h) {
2057 subimage = 1;
2059 else {
2060 state.tex.owners[texindex].h = slice->h;
2063 else {
2064 state.tex.owners[texindex].h = slice->h;
2067 state.tex.owners[texindex].w = tile->w;
2068 state.tex.owners[texindex].slice = slice;
2069 slice->texindex = texindex;
2071 glBindTexture (TEXT_TYPE, state.tex.ids[texindex]);
2072 #if TEXT_TYPE == GL_TEXTURE_2D
2073 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2074 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2075 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2076 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2077 #endif
2078 if (tile->pbo) {
2079 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2080 texdata = 0;
2082 else {
2083 texdata = tile->pixmap->samples;
2085 if (subimage) {
2086 glTexSubImage2D (TEXT_TYPE,
2090 tile->w,
2091 slice->h,
2092 state.tex.form,
2093 state.tex.ty,
2094 texdata+offset
2097 else {
2098 glTexImage2D (TEXT_TYPE,
2100 state.tex.iform,
2101 tile->w,
2102 slice->h,
2104 state.tex.form,
2105 state.tex.ty,
2106 texdata+offset
2109 if (tile->pbo) {
2110 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2115 ML0 (begintiles (void))
2117 glEnable (TEXT_TYPE);
2118 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2119 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2122 ML0 (endtiles (void))
2124 glDisable (TEXT_TYPE);
2127 ML0 (drawtile (value args_v, value ptr_v))
2129 CAMLparam2 (args_v, ptr_v);
2130 int dispx = Int_val (Field (args_v, 0));
2131 int dispy = Int_val (Field (args_v, 1));
2132 int dispw = Int_val (Field (args_v, 2));
2133 int disph = Int_val (Field (args_v, 3));
2134 int tilex = Int_val (Field (args_v, 4));
2135 int tiley = Int_val (Field (args_v, 5));
2136 const char *s = String_val (ptr_v);
2137 struct tile *tile = parse_pointer (__func__, s);
2138 int slicey, firstslice;
2139 struct slice *slice;
2140 GLfloat *texcoords = state.texcoords;
2141 GLfloat *vertices = state.vertices;
2143 firstslice = tiley / tile->sliceheight;
2144 slice = &tile->slices[firstslice];
2145 slicey = tiley % tile->sliceheight;
2147 while (disph > 0) {
2148 int dh;
2150 dh = slice->h - slicey;
2151 dh = fz_mini (disph, dh);
2152 uploadslice (tile, slice);
2154 texcoords[0] = tilex; texcoords[1] = slicey;
2155 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2156 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2157 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2159 vertices[0] = dispx; vertices[1] = dispy;
2160 vertices[2] = dispx+dispw; vertices[3] = dispy;
2161 vertices[4] = dispx; vertices[5] = dispy+dh;
2162 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2164 #if TEXT_TYPE == GL_TEXTURE_2D
2165 for (int i = 0; i < 8; ++i) {
2166 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2168 #endif
2170 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2171 dispy += dh;
2172 disph -= dh;
2173 slice++;
2174 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2175 slicey = 0;
2177 CAMLreturn0;
2180 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2182 fz_matrix ctm;
2183 fz_point p1, p2, p3, p4;
2184 GLfloat *vertices = state.vertices;
2186 xoff -= state.pagedims[page->pdimno].bounds.x0;
2187 yoff -= state.pagedims[page->pdimno].bounds.y0;
2188 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2190 glEnable (GL_BLEND);
2191 glVertexPointer (2, GL_FLOAT, 0, vertices);
2193 glColor4d (
2194 Double_array_field (rects_v, 0),
2195 Double_array_field (rects_v, 1),
2196 Double_array_field (rects_v, 2),
2197 Double_array_field (rects_v, 3)
2199 p1.x = (float) Double_array_field (rects_v, 4);
2200 p1.y = (float) Double_array_field (rects_v, 5);
2202 p2.x = (float) Double_array_field (rects_v, 6);
2203 p2.y = p1.y;
2205 p3.x = p2.x;
2206 p3.y = (float) Double_array_field (rects_v, 7);
2208 p4.x = p1.x;
2209 p4.y = p3.y;
2210 solidrect (ctm, p1, p2, p3, p4, vertices);
2211 glDisable (GL_BLEND);
2214 ML (postprocess (value ptr_v, value hlinks_v,
2215 value xoff_v, value yoff_v,
2216 value li_v))
2218 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2219 int xoff = Int_val (xoff_v);
2220 int yoff = Int_val (yoff_v);
2221 int noff = Int_val (Field (li_v, 0));
2222 const char *targ = String_val (Field (li_v, 1));
2223 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2224 int hfsize = Int_val (Field (li_v, 2));
2225 const char *s = String_val (ptr_v);
2226 int hlmask = Int_val (hlinks_v);
2227 struct page *page = parse_pointer (__func__, s);
2229 if (!page->fzpage) {
2230 /* deal with loadpage failed pages */
2231 goto done;
2234 if (trylock (__func__)) {
2235 noff = -1;
2236 goto done;
2239 ensureannots (page);
2240 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2241 if (hlmask & 2) {
2242 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2243 noff = page->slinkcount;
2245 if (page->tgen == state.gen) {
2246 showsel (page, xoff, yoff);
2248 unlock (__func__);
2250 done:
2251 CAMLreturn (Val_int (noff));
2254 ML0 (drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v))
2256 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2257 int xoff = Int_val (xoff_v);
2258 int yoff = Int_val (yoff_v);
2259 const char *s = String_val (ptr_v);
2260 struct page *page = parse_pointer (__func__, s);
2262 drawprect (page, xoff, yoff, rects_v);
2263 CAMLreturn0;
2266 static struct annot *getannot (struct page *page, int x, int y)
2268 fz_point p;
2269 fz_matrix ctm;
2270 const fz_matrix *tctm;
2271 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2273 if (!page->annots) return NULL;
2275 if (pdf) {
2276 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2277 tctm = &state.pagedims[page->pdimno].tctm;
2279 else {
2280 tctm = &fz_identity;
2283 p.x = x;
2284 p.y = y;
2286 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2287 ctm = fz_invert_matrix (ctm);
2288 p = fz_transform_point (p, ctm);
2290 if (pdf) {
2291 for (int i = 0; i < page->annotcount; ++i) {
2292 struct annot *a = &page->annots[i];
2293 fz_rect rect;
2295 rect = pdf_bound_annot (state.ctx, a->annot);
2296 if (p.x >= rect.x0 && p.x <= rect.x1) {
2297 if (p.y >= rect.y0 && p.y <= rect.y1)
2298 return a;
2302 return NULL;
2305 static fz_link *getlink (struct page *page, int x, int y)
2307 fz_point p;
2308 fz_link *link;
2310 ensureslinks (page);
2312 p.x = x;
2313 p.y = y;
2315 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2317 for (link = page->links; link; link = link->next) {
2318 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2319 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2320 return link;
2324 return NULL;
2327 static void ensuretext (struct page *page)
2329 if (state.gen != page->tgen) {
2330 droptext (page);
2331 page->tgen = state.gen;
2333 if (!page->text) {
2334 fz_device *tdev;
2336 page->text = fz_new_stext_page (state.ctx,
2337 state.pagedims[page->pdimno].mediabox);
2338 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2339 fz_run_display_list (state.ctx, page->dlist,
2340 tdev, pagectm (page), fz_infinite_rect, NULL);
2341 fz_close_device (state.ctx, tdev);
2342 fz_drop_device (state.ctx, tdev);
2346 ML (find_page_with_links (value start_page_v, value dir_v))
2348 CAMLparam2 (start_page_v, dir_v);
2349 CAMLlocal1 (ret_v);
2350 int i, dir = Int_val (dir_v);
2351 int start_page = Int_val (start_page_v);
2352 int end_page = dir > 0 ? state.pagecount : -1;
2353 pdf_document *pdf;
2355 fz_var (end_page);
2356 ret_v = Val_int (0);
2357 lock (__func__);
2358 pdf = pdf_specifics (state.ctx, state.doc);
2359 for (i = start_page + dir; i != end_page; i += dir) {
2360 int found;
2362 fz_var (found);
2363 if (pdf) {
2364 pdf_page *page = NULL;
2366 fz_var (page);
2367 fz_try (state.ctx) {
2368 page = pdf_load_page (state.ctx, pdf, i);
2369 found = !!page->links || !!page->annots;
2371 fz_catch (state.ctx) {
2372 found = 0;
2374 if (page) {
2375 fz_drop_page (state.ctx, &page->super);
2378 else {
2379 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2380 fz_link *link = fz_load_links (state.ctx, page);
2381 found = !!link;
2382 fz_drop_link (state.ctx, link);
2383 fz_drop_page (state.ctx, page);
2386 if (found) {
2387 ret_v = caml_alloc_small (1, 1);
2388 Field (ret_v, 0) = Val_int (i);
2389 goto unlock;
2392 unlock:
2393 unlock (__func__);
2394 CAMLreturn (ret_v);
2397 enum { dir_first, dir_last };
2398 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2400 ML (findlink (value ptr_v, value dir_v))
2402 CAMLparam2 (ptr_v, dir_v);
2403 CAMLlocal2 (ret_v, pos_v);
2404 struct page *page;
2405 int dirtag, i, slinkindex;
2406 struct slink *found = NULL ,*slink;
2407 const char *s = String_val (ptr_v);
2409 page = parse_pointer (__func__, s);
2410 ret_v = Val_int (0);
2411 lock (__func__);
2412 ensureslinks (page);
2414 if (Is_block (dir_v)) {
2415 dirtag = Tag_val (dir_v);
2416 switch (dirtag) {
2417 case dir_first_visible:
2419 int x0, y0, dir, first_index, last_index;
2421 pos_v = Field (dir_v, 0);
2422 x0 = Int_val (Field (pos_v, 0));
2423 y0 = Int_val (Field (pos_v, 1));
2424 dir = Int_val (Field (pos_v, 2));
2426 if (dir >= 0) {
2427 dir = 1;
2428 first_index = 0;
2429 last_index = page->slinkcount;
2431 else {
2432 first_index = page->slinkcount - 1;
2433 last_index = -1;
2436 for (i = first_index; i != last_index; i += dir) {
2437 slink = &page->slinks[i];
2438 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2439 found = slink;
2440 break;
2444 break;
2446 case dir_left:
2447 slinkindex = Int_val (Field (dir_v, 0));
2448 found = &page->slinks[slinkindex];
2449 for (i = slinkindex - 1; i >= 0; --i) {
2450 slink = &page->slinks[i];
2451 if (slink->bbox.x0 < found->bbox.x0) {
2452 found = slink;
2453 break;
2456 break;
2458 case dir_right:
2459 slinkindex = Int_val (Field (dir_v, 0));
2460 found = &page->slinks[slinkindex];
2461 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2462 slink = &page->slinks[i];
2463 if (slink->bbox.x0 > found->bbox.x0) {
2464 found = slink;
2465 break;
2468 break;
2470 case dir_down:
2471 slinkindex = Int_val (Field (dir_v, 0));
2472 found = &page->slinks[slinkindex];
2473 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2474 slink = &page->slinks[i];
2475 if (slink->bbox.y0 >= found->bbox.y0) {
2476 found = slink;
2477 break;
2480 break;
2482 case dir_up:
2483 slinkindex = Int_val (Field (dir_v, 0));
2484 found = &page->slinks[slinkindex];
2485 for (i = slinkindex - 1; i >= 0; --i) {
2486 slink = &page->slinks[i];
2487 if (slink->bbox.y0 <= found->bbox.y0) {
2488 found = slink;
2489 break;
2492 break;
2495 else {
2496 dirtag = Int_val (dir_v);
2497 switch (dirtag) {
2498 case dir_first:
2499 found = page->slinks;
2500 break;
2502 case dir_last:
2503 if (page->slinks) {
2504 found = page->slinks + (page->slinkcount - 1);
2506 break;
2509 if (found) {
2510 ret_v = caml_alloc_small (2, 1);
2511 Field (ret_v, 0) = Val_int (found - page->slinks);
2514 unlock (__func__);
2515 CAMLreturn (ret_v);
2518 enum { uuri, utext, uannot };
2520 ML (getlink (value ptr_v, value n_v))
2522 CAMLparam2 (ptr_v, n_v);
2523 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2524 fz_link *link;
2525 struct page *page;
2526 const char *s = String_val (ptr_v);
2527 struct slink *slink;
2529 ret_v = Val_int (0);
2530 page = parse_pointer (__func__, s);
2532 lock (__func__);
2533 ensureslinks (page);
2534 slink = &page->slinks[Int_val (n_v)];
2535 if (slink->tag == SLINK) {
2536 link = slink->u.link;
2537 str_v = caml_copy_string (link->uri);
2538 ret_v = caml_alloc_small (1, uuri);
2539 Field (ret_v, 0) = str_v;
2541 else {
2542 ret_v = caml_alloc_small (1, uannot);
2543 tup_v = caml_alloc_tuple (2);
2544 Field (ret_v, 0) = tup_v;
2545 Field (tup_v, 0) = ptr_v;
2546 Field (tup_v, 1) = n_v;
2548 unlock (__func__);
2550 CAMLreturn (ret_v);
2553 ML (getannotcontents (value ptr_v, value n_v))
2555 CAMLparam2 (ptr_v, n_v);
2556 CAMLlocal1 (ret_v);
2557 pdf_document *pdf;
2558 const char *contents = "";
2560 lock (__func__);
2561 pdf = pdf_specifics (state.ctx, state.doc);
2562 if (pdf) {
2563 const char *s = String_val (ptr_v);
2564 struct page *page;
2565 struct slink *slink;
2567 page = parse_pointer (__func__, s);
2568 slink = &page->slinks[Int_val (n_v)];
2569 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2571 unlock (__func__);
2572 ret_v = caml_copy_string (contents);
2573 CAMLreturn (ret_v);
2576 ML (getlinkcount (value ptr_v))
2578 CAMLparam1 (ptr_v);
2579 struct page *page;
2580 const char *s = String_val (ptr_v);
2582 page = parse_pointer (__func__, s);
2583 CAMLreturn (Val_int (page->slinkcount));
2586 ML (getlinkrect (value ptr_v, value n_v))
2588 CAMLparam2 (ptr_v, n_v);
2589 CAMLlocal1 (ret_v);
2590 struct page *page;
2591 struct slink *slink;
2592 const char *s = String_val (ptr_v);
2594 page = parse_pointer (__func__, s);
2595 ret_v = caml_alloc_tuple (4);
2596 lock (__func__);
2597 ensureslinks (page);
2599 slink = &page->slinks[Int_val (n_v)];
2600 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2601 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2602 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2603 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2604 unlock (__func__);
2605 CAMLreturn (ret_v);
2608 ML (whatsunder (value ptr_v, value x_v, value y_v))
2610 CAMLparam3 (ptr_v, x_v, y_v);
2611 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2612 fz_link *link;
2613 struct annot *annot;
2614 struct page *page;
2615 const char *ptr = String_val (ptr_v);
2616 int x = Int_val (x_v), y = Int_val (y_v);
2617 struct pagedim *pdim;
2619 ret_v = Val_int (0);
2620 if (trylock (__func__)) {
2621 goto done;
2624 page = parse_pointer (__func__, ptr);
2625 pdim = &state.pagedims[page->pdimno];
2626 x += pdim->bounds.x0;
2627 y += pdim->bounds.y0;
2630 annot = getannot (page, x, y);
2631 if (annot) {
2632 int i, n = -1;
2634 ensureslinks (page);
2635 for (i = 0; i < page->slinkcount; ++i) {
2636 if (page->slinks[i].tag == SANNOT
2637 && page->slinks[i].u.annot == annot->annot) {
2638 n = i;
2639 break;
2642 ret_v = caml_alloc_small (1, uannot);
2643 tup_v = caml_alloc_tuple (2);
2644 Field (ret_v, 0) = tup_v;
2645 Field (tup_v, 0) = ptr_v;
2646 Field (tup_v, 1) = Val_int (n);
2647 goto unlock;
2651 link = getlink (page, x, y);
2652 if (link) {
2653 str_v = caml_copy_string (link->uri);
2654 ret_v = caml_alloc_small (1, uuri);
2655 Field (ret_v, 0) = str_v;
2657 else {
2658 fz_rect *b;
2659 fz_stext_block *block;
2661 ensuretext (page);
2663 for (block = page->text->first_block; block; block = block->next) {
2664 fz_stext_line *line;
2666 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2667 b = &block->bbox;
2668 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2669 continue;
2671 for (line = block->u.t.first_line; line; line = line->next) {
2672 fz_stext_char *ch;
2674 b = &line->bbox;
2675 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2676 continue;
2678 for (ch = line->first_char; ch; ch = ch->next) {
2679 fz_quad *q = &ch->quad;
2681 if (x >= q->ul.x && x <= q->ur.x
2682 && y >= q->ul.y && y <= q->ll.y) {
2683 const char *n2 = fz_font_name (state.ctx, ch->font);
2684 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2685 ch->font);
2687 if (!n2) n2 = "<unknown font>";
2689 if (face && face->family_name) {
2690 char *s;
2691 char *n1 = face->family_name;
2692 size_t l1 = strlen (n1);
2693 size_t l2 = strlen (n2);
2695 if (l1 != l2 || memcmp (n1, n2, l1)) {
2696 s = malloc (l1 + l2 + 2);
2697 if (s) {
2698 memcpy (s, n2, l2);
2699 s[l2] = '=';
2700 memcpy (s + l2 + 1, n1, l1 + 1);
2701 str_v = caml_copy_string (s);
2702 free (s);
2706 if (str_v == Val_unit) {
2707 str_v = caml_copy_string (n2);
2709 ret_v = caml_alloc_small (1, utext);
2710 Field (ret_v, 0) = str_v;
2711 goto unlock;
2717 unlock:
2718 unlock (__func__);
2720 done:
2721 CAMLreturn (ret_v);
2724 enum { mark_page, mark_block, mark_line, mark_word };
2726 ML0 (clearmark (value ptr_v))
2728 CAMLparam1 (ptr_v);
2729 const char *s = String_val (ptr_v);
2730 struct page *page;
2732 if (trylock (__func__)) {
2733 goto done;
2736 page = parse_pointer (__func__, s);
2737 page->fmark = NULL;
2738 page->lmark = NULL;
2740 unlock (__func__);
2741 done:
2742 CAMLreturn0;
2745 static int uninteresting (int c)
2747 return isspace (c) || ispunct (c);
2750 ML (markunder (value ptr_v, value x_v, value y_v, value mark_v))
2752 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2753 CAMLlocal1 (ret_v);
2754 fz_rect *b;
2755 struct page *page;
2756 fz_stext_line *line;
2757 fz_stext_block *block;
2758 struct pagedim *pdim;
2759 int mark = Int_val (mark_v);
2760 const char *s = String_val (ptr_v);
2761 int x = Int_val (x_v), y = Int_val (y_v);
2763 ret_v = Val_bool (0);
2764 if (trylock (__func__)) {
2765 goto done;
2768 page = parse_pointer (__func__, s);
2769 pdim = &state.pagedims[page->pdimno];
2771 ensuretext (page);
2773 if (mark == mark_page) {
2774 page->fmark = page->text->first_block->u.t.first_line->first_char;
2775 page->lmark = page->text->last_block->u.t.last_line->last_char;
2776 ret_v = Val_bool (1);
2777 goto unlock;
2780 x += pdim->bounds.x0;
2781 y += pdim->bounds.y0;
2783 for (block = page->text->first_block; block; block = block->next) {
2784 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2785 b = &block->bbox;
2786 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2787 continue;
2789 if (mark == mark_block) {
2790 page->fmark = block->u.t.first_line->first_char;
2791 page->lmark = block->u.t.last_line->last_char;
2792 ret_v = Val_bool (1);
2793 goto unlock;
2796 for (line = block->u.t.first_line; line; line = line->next) {
2797 fz_stext_char *ch;
2799 b = &line->bbox;
2800 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2801 continue;
2803 if (mark == mark_line) {
2804 page->fmark = line->first_char;
2805 page->lmark = line->last_char;
2806 ret_v = Val_bool (1);
2807 goto unlock;
2810 for (ch = line->first_char; ch; ch = ch->next) {
2811 fz_stext_char *ch2, *first = NULL, *last = NULL;
2812 fz_quad *q = &ch->quad;
2813 if (x >= q->ul.x && x <= q->ur.x
2814 && y >= q->ul.y && y <= q->ll.y) {
2815 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2816 if (uninteresting (ch2->c)) first = NULL;
2817 else if (!first) first = ch2;
2819 for (ch2 = ch; ch2; ch2 = ch2->next) {
2820 if (uninteresting (ch2->c)) break;
2821 last = ch2;
2824 page->fmark = first;
2825 page->lmark = last;
2826 ret_v = Val_bool (1);
2827 goto unlock;
2832 unlock:
2833 if (!Bool_val (ret_v)) {
2834 page->fmark = NULL;
2835 page->lmark = NULL;
2837 unlock (__func__);
2839 done:
2840 CAMLreturn (ret_v);
2843 ML (rectofblock (value ptr_v, value x_v, value y_v))
2845 CAMLparam3 (ptr_v, x_v, y_v);
2846 CAMLlocal2 (ret_v, res_v);
2847 fz_rect *b = NULL;
2848 struct page *page;
2849 struct pagedim *pdim;
2850 fz_stext_block *block;
2851 const char *s = String_val (ptr_v);
2852 int x = Int_val (x_v), y = Int_val (y_v);
2854 ret_v = Val_int (0);
2855 if (trylock (__func__)) {
2856 goto done;
2859 page = parse_pointer (__func__, s);
2860 pdim = &state.pagedims[page->pdimno];
2861 x += pdim->bounds.x0;
2862 y += pdim->bounds.y0;
2864 ensuretext (page);
2866 for (block = page->text->first_block; block; block = block->next) {
2867 switch (block->type) {
2868 case FZ_STEXT_BLOCK_TEXT:
2869 b = &block->bbox;
2870 break;
2872 case FZ_STEXT_BLOCK_IMAGE:
2873 b = &block->bbox;
2874 break;
2876 default:
2877 continue;
2880 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2881 break;
2882 b = NULL;
2884 if (b) {
2885 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2886 ret_v = caml_alloc_small (1, 1);
2887 Store_double_field (res_v, 0, (double) b->x0);
2888 Store_double_field (res_v, 1, (double) b->x1);
2889 Store_double_field (res_v, 2, (double) b->y0);
2890 Store_double_field (res_v, 3, (double) b->y1);
2891 Field (ret_v, 0) = res_v;
2893 unlock (__func__);
2895 done:
2896 CAMLreturn (ret_v);
2899 ML0 (seltext (value ptr_v, value rect_v))
2901 CAMLparam2 (ptr_v, rect_v);
2902 struct page *page;
2903 struct pagedim *pdim;
2904 const char *s = String_val (ptr_v);
2905 int x0, x1, y0, y1;
2906 fz_stext_char *ch;
2907 fz_stext_line *line;
2908 fz_stext_block *block;
2909 fz_stext_char *fc, *lc;
2911 if (trylock (__func__)) {
2912 goto done;
2915 page = parse_pointer (__func__, s);
2916 ensuretext (page);
2918 pdim = &state.pagedims[page->pdimno];
2919 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2920 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2921 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2922 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2924 if (y0 > y1) {
2925 int t = y0;
2926 y0 = y1;
2927 y1 = t;
2928 x0 = x1;
2929 x1 = t;
2932 fc = page->fmark;
2933 lc = page->lmark;
2935 for (block = page->text->first_block; block; block = block->next) {
2936 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2937 for (line = block->u.t.first_line; line; line = line->next) {
2938 for (ch = line->first_char; ch; ch = ch->next) {
2939 fz_quad q = ch->quad;
2940 if (x0 >= q.ul.x && x0 <= q.ur.x
2941 && y0 >= q.ul.y && y0 <= q.ll.y) {
2942 fc = ch;
2944 if (x1 >= q.ul.x && x1 <= q.ur.x
2945 && y1 >= q.ul.y && y1 <= q.ll.y) {
2946 lc = ch;
2951 if (x1 < x0 && fc == lc) {
2952 fz_stext_char *t;
2954 t = fc;
2955 fc = lc;
2956 lc = t;
2959 page->fmark = fc;
2960 page->lmark = lc;
2962 unlock (__func__);
2964 done:
2965 CAMLreturn0;
2968 static int pipechar (FILE *f, fz_stext_char *ch)
2970 char buf[4];
2971 int len;
2972 size_t ret;
2974 len = fz_runetochar (buf, ch->c);
2975 ret = fwrite (buf, len, 1, f);
2976 if (ret != 1) {
2977 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
2978 len, ret, errno, strerror (errno));
2979 return -1;
2981 return 0;
2984 ML (spawn (value command_v, value fds_v))
2986 CAMLparam2 (command_v, fds_v);
2987 CAMLlocal2 (l_v, tup_v);
2988 int ret, ret1;
2989 pid_t pid = (pid_t) -1;
2990 char *msg = NULL;
2991 value earg_v = Nothing;
2992 posix_spawnattr_t attr;
2993 posix_spawn_file_actions_t fa;
2994 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
2996 argv[2] = &Byte (command_v, 0);
2997 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
2998 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3001 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3002 msg = "posix_spawnattr_init";
3003 goto fail1;
3006 #ifdef POSIX_SPAWN_USEVFORK
3007 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3008 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3009 goto fail;
3011 #endif
3013 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3014 int fd1, fd2;
3016 tup_v = Field (l_v, 0);
3017 fd1 = Int_val (Field (tup_v, 0));
3018 fd2 = Int_val (Field (tup_v, 1));
3019 if (fd2 < 0) {
3020 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3021 msg = "posix_spawn_file_actions_addclose";
3022 earg_v = tup_v;
3023 goto fail;
3026 else {
3027 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3028 msg = "posix_spawn_file_actions_adddup2";
3029 earg_v = tup_v;
3030 goto fail;
3035 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3036 msg = "posix_spawn";
3037 goto fail;
3040 fail:
3041 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3042 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3045 fail1:
3046 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3047 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3048 ret1, strerror (ret1));
3051 if (msg)
3052 unix_error (ret, msg, earg_v);
3054 CAMLreturn (Val_int (pid));
3057 ML (hassel (value ptr_v))
3059 CAMLparam1 (ptr_v);
3060 CAMLlocal1 (ret_v);
3061 struct page *page;
3062 const char *s = String_val (ptr_v);
3064 ret_v = Val_bool (0);
3065 if (trylock (__func__)) {
3066 goto done;
3069 page = parse_pointer (__func__, s);
3070 ret_v = Val_bool (page->fmark && page->lmark);
3071 unlock (__func__);
3072 done:
3073 CAMLreturn (ret_v);
3076 ML0 (copysel (value fd_v, value ptr_v))
3078 CAMLparam2 (fd_v, ptr_v);
3079 FILE *f;
3080 int seen = 0;
3081 struct page *page;
3082 fz_stext_line *line;
3083 fz_stext_block *block;
3084 int fd = Int_val (fd_v);
3085 const char *s = String_val (ptr_v);
3087 if (trylock (__func__)) {
3088 goto done;
3091 page = parse_pointer (__func__, s);
3093 if (!page->fmark || !page->lmark) {
3094 printd ("emsg nothing to copy on page %d", page->pageno);
3095 goto unlock;
3098 f = fdopen (fd, "w");
3099 if (!f) {
3100 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3101 fd, errno, strerror (errno));
3102 f = stdout;
3105 for (block = page->text->first_block; block; block = block->next) {
3106 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3107 for (line = block->u.t.first_line; line; line = line->next) {
3108 fz_stext_char *ch;
3109 for (ch = line->first_char; ch; ch = ch->next) {
3110 if (seen || ch == page->fmark) {
3111 do {
3112 pipechar (f, ch);
3113 if (ch == page->lmark) goto close;
3114 } while ((ch = ch->next));
3115 seen = 1;
3116 break;
3119 if (seen) fputc ('\n', f);
3122 close:
3123 if (f != stdout) {
3124 int ret = fclose (f);
3125 fd = -1;
3126 if (ret == -1) {
3127 if (errno != ECHILD) {
3128 printd ("emsg failed to close sel pipe: %d:%s",
3129 errno, strerror (errno));
3133 unlock:
3134 unlock (__func__);
3136 done:
3137 if (fd >= 0) {
3138 if (close (fd)) {
3139 printd ("emsg failed to close sel pipe: %d:%s",
3140 errno, strerror (errno));
3143 CAMLreturn0;
3146 ML (getpdimrect (value pagedimno_v))
3148 CAMLparam1 (pagedimno_v);
3149 CAMLlocal1 (ret_v);
3150 int pagedimno = Int_val (pagedimno_v);
3151 fz_rect box;
3153 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3154 if (trylock (__func__)) {
3155 box = fz_empty_rect;
3157 else {
3158 box = state.pagedims[pagedimno].mediabox;
3159 unlock (__func__);
3162 Store_double_field (ret_v, 0, (double) box.x0);
3163 Store_double_field (ret_v, 1, (double) box.x1);
3164 Store_double_field (ret_v, 2, (double) box.y0);
3165 Store_double_field (ret_v, 3, (double) box.y1);
3167 CAMLreturn (ret_v);
3170 ML (zoom_for_height (value winw_v, value winh_v, value dw_v, value cols_v))
3172 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3173 CAMLlocal1 (ret_v);
3174 int i;
3175 float zoom = -1.;
3176 float maxh = 0.0;
3177 struct pagedim *p;
3178 float winw = Int_val (winw_v);
3179 float winh = Int_val (winh_v);
3180 float dw = Int_val (dw_v);
3181 float cols = Int_val (cols_v);
3182 float pw = 1.0, ph = 1.0;
3184 if (trylock (__func__)) {
3185 goto done;
3188 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3189 float w = p->pagebox.x1 / cols;
3190 float h = p->pagebox.y1;
3191 if (h > maxh) {
3192 maxh = h;
3193 ph = h;
3194 if (state.fitmodel != FitProportional) pw = w;
3196 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3199 zoom = (((winh / ph) * pw) + dw) / winw;
3200 unlock (__func__);
3201 done:
3202 ret_v = caml_copy_double ((double) zoom);
3203 CAMLreturn (ret_v);
3206 ML (getmaxw (value unit_v))
3208 CAMLparam1 (unit_v);
3209 CAMLlocal1 (ret_v);
3210 int i;
3211 float maxw = -1.;
3212 struct pagedim *p;
3214 if (trylock (__func__)) {
3215 goto done;
3218 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3219 float w = p->pagebox.x1;
3220 maxw = fz_max (maxw, w);
3223 unlock (__func__);
3224 done:
3225 ret_v = caml_copy_double ((double) maxw);
3226 CAMLreturn (ret_v);
3229 ML (draw_string (value pt_v, value x_v, value y_v, value string_v))
3231 CAMLparam4 (pt_v, x_v, y_v, string_v);
3232 CAMLlocal1 (ret_v);
3233 int pt = Int_val(pt_v);
3234 int x = Int_val (x_v);
3235 int y = Int_val (y_v);
3236 float w;
3238 w = draw_string (state.face, pt, x, y, String_val (string_v));
3239 ret_v = caml_copy_double (w);
3240 CAMLreturn (ret_v);
3243 ML (measure_string (value pt_v, value string_v))
3245 CAMLparam2 (pt_v, string_v);
3246 CAMLlocal1 (ret_v);
3247 int pt = Int_val (pt_v);
3248 double w;
3250 w = (double) measure_string (state.face, pt, String_val (string_v));
3251 ret_v = caml_copy_double (w);
3252 CAMLreturn (ret_v);
3255 ML (getpagebox (value opaque_v))
3257 CAMLparam1 (opaque_v);
3258 CAMLlocal1 (ret_v);
3259 fz_rect rect;
3260 fz_irect bbox;
3261 fz_device *dev;
3262 const char *s = String_val (opaque_v);
3263 struct page *page = parse_pointer (__func__, s);
3265 ret_v = caml_alloc_tuple (4);
3266 dev = fz_new_bbox_device (state.ctx, &rect);
3268 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3270 fz_close_device (state.ctx, dev);
3271 fz_drop_device (state.ctx, dev);
3272 bbox = fz_round_rect (rect);
3273 Field (ret_v, 0) = Val_int (bbox.x0);
3274 Field (ret_v, 1) = Val_int (bbox.y0);
3275 Field (ret_v, 2) = Val_int (bbox.x1);
3276 Field (ret_v, 3) = Val_int (bbox.y1);
3278 CAMLreturn (ret_v);
3281 ML0 (setaalevel (value level_v))
3283 CAMLparam1 (level_v);
3285 state.aalevel = Int_val (level_v);
3286 CAMLreturn0;
3289 ML0 (setpapercolor (value rgba_v))
3291 CAMLparam1 (rgba_v);
3293 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3294 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3295 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3296 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3297 CAMLreturn0;
3300 value ml_keysymtoutf8 (value keysym_v);
3301 #ifndef CIDER
3302 value ml_keysymtoutf8 (value keysym_v)
3304 CAMLparam1 (keysym_v);
3305 CAMLlocal1 (str_v);
3306 unsigned short keysym = (unsigned short) Int_val (keysym_v);
3307 Rune rune;
3308 extern long keysym2ucs (unsigned short);
3309 int len;
3310 char buf[5];
3312 rune = (Rune) keysym2ucs (keysym);
3313 len = fz_runetochar (buf, rune);
3314 buf[len] = 0;
3315 str_v = caml_copy_string (buf);
3316 CAMLreturn (str_v);
3318 #else
3319 value ml_keysymtoutf8 (value keysym_v)
3321 CAMLparam1 (keysym_v);
3322 CAMLlocal1 (str_v);
3323 long ucs = Long_val (keysym_v);
3324 int len;
3325 char buf[5];
3327 len = fz_runetochar (buf, (int) ucs);
3328 buf[len] = 0;
3329 str_v = caml_copy_string (buf);
3330 CAMLreturn (str_v);
3332 #endif
3334 enum { piunknown, pilinux, pimacos, pibsd };
3336 ML (platform (value unit_v))
3338 CAMLparam1 (unit_v);
3339 CAMLlocal2 (tup_v, arr_v);
3340 int platid = piunknown;
3341 struct utsname buf;
3343 #if defined __linux__
3344 platid = pilinux;
3345 #elif defined __DragonFly__ || defined __FreeBSD__
3346 || defined __OpenBSD__ || defined __NetBSD__
3347 platid = pibsd;
3348 #elif defined __APPLE__
3349 platid = pimacos;
3350 #endif
3351 if (uname (&buf)) err (1, "uname");
3353 tup_v = caml_alloc_tuple (2);
3355 char const *sar[] = {
3356 buf.sysname,
3357 buf.release,
3358 buf.version,
3359 buf.machine,
3360 NULL
3362 arr_v = caml_copy_string_array (sar);
3364 Field (tup_v, 0) = Val_int (platid);
3365 Field (tup_v, 1) = arr_v;
3366 CAMLreturn (tup_v);
3369 ML0 (cloexec (value fd_v))
3371 CAMLparam1 (fd_v);
3372 int fd = Int_val (fd_v);
3374 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3375 uerror ("fcntl", Nothing);
3377 CAMLreturn0;
3380 ML (getpbo (value w_v, value h_v, value cs_v))
3382 CAMLparam2 (w_v, h_v);
3383 CAMLlocal1 (ret_v);
3384 struct bo *pbo;
3385 int w = Int_val (w_v);
3386 int h = Int_val (h_v);
3387 int cs = Int_val (cs_v);
3389 if (state.bo_usable) {
3390 pbo = calloc (sizeof (*pbo), 1);
3391 if (!pbo) {
3392 err (1, "calloc pbo");
3395 switch (cs) {
3396 case 0:
3397 case 1:
3398 pbo->size = w*h*4;
3399 break;
3400 case 2:
3401 pbo->size = w*h*2;
3402 break;
3403 default:
3404 errx (1, "%s: invalid colorspace %d", __func__, cs);
3407 state.glGenBuffersARB (1, &pbo->id);
3408 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3409 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3410 NULL, GL_STREAM_DRAW);
3411 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3412 GL_READ_WRITE);
3413 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3414 if (!pbo->ptr) {
3415 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3416 state.glDeleteBuffersARB (1, &pbo->id);
3417 free (pbo);
3418 ret_v = caml_copy_string ("0");
3420 else {
3421 int res;
3422 char *s;
3424 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3425 if (res < 0) {
3426 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3428 s = malloc (res+1);
3429 if (!s) {
3430 err (1, "malloc %d bytes failed", res+1);
3432 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3433 if (res < 0) {
3434 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3436 ret_v = caml_copy_string (s);
3437 free (s);
3440 else {
3441 ret_v = caml_copy_string ("0");
3443 CAMLreturn (ret_v);
3446 ML0 (freepbo (value s_v))
3448 CAMLparam1 (s_v);
3449 const char *s = String_val (s_v);
3450 struct tile *tile = parse_pointer (__func__, s);
3452 if (tile->pbo) {
3453 state.glDeleteBuffersARB (1, &tile->pbo->id);
3454 tile->pbo->id = -1;
3455 tile->pbo->ptr = NULL;
3456 tile->pbo->size = -1;
3458 CAMLreturn0;
3461 ML0 (unmappbo (value s_v))
3463 CAMLparam1 (s_v);
3464 const char *s = String_val (s_v);
3465 struct tile *tile = parse_pointer (__func__, s);
3467 if (tile->pbo) {
3468 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3469 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3470 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3472 tile->pbo->ptr = NULL;
3473 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3475 CAMLreturn0;
3478 static void setuppbo (void)
3480 extern void (*wsigladdr (const char *name)) (void);
3481 #pragma GCC diagnostic push
3482 #ifdef __clang__
3483 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3484 #endif
3485 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3486 state.bo_usable = GPA (glBindBufferARB)
3487 && GPA (glUnmapBufferARB)
3488 && GPA (glMapBufferARB)
3489 && GPA (glBufferDataARB)
3490 && GPA (glGenBuffersARB)
3491 && GPA (glDeleteBuffersARB);
3492 #undef GPA
3493 #pragma GCC diagnostic pop
3496 ML (bo_usable (void))
3498 return Val_bool (state.bo_usable);
3501 ML (unproject (value ptr_v, value x_v, value y_v))
3503 CAMLparam3 (ptr_v, x_v, y_v);
3504 CAMLlocal2 (ret_v, tup_v);
3505 struct page *page;
3506 const char *s = String_val (ptr_v);
3507 int x = Int_val (x_v), y = Int_val (y_v);
3508 struct pagedim *pdim;
3509 fz_point p;
3511 page = parse_pointer (__func__, s);
3512 pdim = &state.pagedims[page->pdimno];
3514 ret_v = Val_int (0);
3515 if (trylock (__func__)) {
3516 goto done;
3519 p.x = x + pdim->bounds.x0;
3520 p.y = y + pdim->bounds.y0;
3522 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3523 pdim->ctm)));
3525 tup_v = caml_alloc_tuple (2);
3526 ret_v = caml_alloc_small (1, 1);
3527 Field (tup_v, 0) = Val_int (p.x);
3528 Field (tup_v, 1) = Val_int (p.y);
3529 Field (ret_v, 0) = tup_v;
3531 unlock (__func__);
3532 done:
3533 CAMLreturn (ret_v);
3536 ML (project (value ptr_v, value pageno_v, value pdimno_v, value x_v, value y_v))
3538 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3539 CAMLlocal1 (ret_v);
3540 struct page *page;
3541 const char *s = String_val (ptr_v);
3542 int pageno = Int_val (pageno_v);
3543 int pdimno = Int_val (pdimno_v);
3544 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3545 struct pagedim *pdim;
3546 fz_point p;
3547 fz_matrix ctm;
3549 ret_v = Val_int (0);
3550 lock (__func__);
3552 if (!*s) {
3553 page = loadpage (pageno, pdimno);
3555 else {
3556 page = parse_pointer (__func__, s);
3558 pdim = &state.pagedims[pdimno];
3560 if (pdf_specifics (state.ctx, state.doc)) {
3561 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3562 ctm = state.pagedims[page->pdimno].tctm;
3564 else {
3565 ctm = fz_identity;
3567 p.x = x + pdim->bounds.x0;
3568 p.y = y + pdim->bounds.y0;
3570 ctm = fz_concat (pdim->tctm, pdim->ctm);
3571 p = fz_transform_point (p, ctm);
3573 ret_v = caml_alloc_tuple (2);
3574 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3575 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3577 if (!*s) {
3578 freepage (page);
3580 unlock (__func__);
3581 CAMLreturn (ret_v);
3584 ML0 (addannot (value ptr_v, value x_v, value y_v, value contents_v))
3586 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3587 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3589 if (pdf) {
3590 pdf_annot *annot;
3591 struct page *page;
3592 fz_rect r;
3593 const char *s = String_val (ptr_v);
3595 page = parse_pointer (__func__, s);
3596 annot = pdf_create_annot (state.ctx,
3597 pdf_page_from_fz_page (state.ctx,
3598 page->fzpage),
3599 PDF_ANNOT_TEXT);
3600 r.x0 = Int_val (x_v) - 10;
3601 r.y0 = Int_val (y_v) - 10;
3602 r.x1 = r.x0 + 20;
3603 r.y1 = r.y0 + 20;
3604 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3605 pdf_set_annot_rect (state.ctx, annot, r);
3607 state.dirty = 1;
3609 CAMLreturn0;
3612 ML0 (delannot (value ptr_v, value n_v))
3614 CAMLparam2 (ptr_v, n_v);
3615 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3617 if (pdf) {
3618 struct page *page;
3619 const char *s = String_val (ptr_v);
3620 struct slink *slink;
3622 page = parse_pointer (__func__, s);
3623 slink = &page->slinks[Int_val (n_v)];
3624 pdf_delete_annot (state.ctx,
3625 pdf_page_from_fz_page (state.ctx, page->fzpage),
3626 (pdf_annot *) slink->u.annot);
3627 state.dirty = 1;
3629 CAMLreturn0;
3632 ML0 (modannot (value ptr_v, value n_v, value str_v))
3634 CAMLparam3 (ptr_v, n_v, str_v);
3635 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3637 if (pdf) {
3638 struct page *page;
3639 const char *s = String_val (ptr_v);
3640 struct slink *slink;
3642 page = parse_pointer (__func__, s);
3643 slink = &page->slinks[Int_val (n_v)];
3644 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3645 String_val (str_v));
3646 state.dirty = 1;
3648 CAMLreturn0;
3651 ML (hasunsavedchanges (void))
3653 return Val_bool (state.dirty);
3656 ML0 (savedoc (value path_v))
3658 CAMLparam1 (path_v);
3659 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3661 if (pdf) {
3662 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3664 CAMLreturn0;
3667 static void makestippletex (void)
3669 const char pixels[] = "\xff\xff\0\0";
3670 glGenTextures (1, &state.stid);
3671 glBindTexture (GL_TEXTURE_1D, state.stid);
3672 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3673 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3674 glTexImage1D (
3675 GL_TEXTURE_1D,
3677 GL_ALPHA,
3680 GL_ALPHA,
3681 GL_UNSIGNED_BYTE,
3682 pixels
3686 ML (fz_version (void))
3688 return caml_copy_string (FZ_VERSION);
3691 ML (llpp_version (void))
3693 extern char llpp_version[];
3694 return caml_copy_string (llpp_version);
3697 static void diag_callback (void *user, const char *message)
3699 printd ("emsg %s %s", (char *) user, message);
3702 static fz_font *lsff (fz_context *ctx,int UNUSED_ATTR script,
3703 int UNUSED_ATTR language, int UNUSED_ATTR serif,
3704 int UNUSED_ATTR bold, int UNUSED_ATTR italic)
3706 static fz_font *font;
3707 static int done;
3709 if (!done) {
3710 char *path = getenv ("LLPP_FALLBACK_FONT");
3711 if (path) font = fz_new_font_from_file (ctx, NULL, path, 0, 1);
3712 done = 1;
3714 return font;
3717 ML0 (setdcf (value path_v))
3719 free (state.dcf);
3720 state.dcf = NULL;
3721 const char *p = String_val (path_v);
3722 size_t len = caml_string_length (path_v);
3723 if (*p) {
3724 state.dcf = malloc (len + 1);
3725 if (!state.dcf) {
3726 err (1, "malloc dimpath %zu", len + 1);
3728 memcpy (state.dcf, p, len);
3729 state.dcf[len] = 0;
3733 ML0 (init (value csock_v, value params_v))
3735 CAMLparam2 (csock_v, params_v);
3736 CAMLlocal2 (trim_v, fuzz_v);
3737 int ret;
3738 int texcount;
3739 const char *fontpath;
3740 int colorspace;
3741 int mustoresize;
3743 state.csock = Int_val (csock_v);
3744 state.rotate = Int_val (Field (params_v, 0));
3745 state.fitmodel = Int_val (Field (params_v, 1));
3746 trim_v = Field (params_v, 2);
3747 texcount = Int_val (Field (params_v, 3));
3748 state.sliceheight = Int_val (Field (params_v, 4));
3749 mustoresize = Int_val (Field (params_v, 5));
3750 colorspace = Int_val (Field (params_v, 6));
3751 fontpath = String_val (Field (params_v, 7));
3753 #ifdef CIDER
3754 state.utf8cs = 1;
3755 #else
3756 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3757 if (setlocale (LC_CTYPE, "")) {
3758 const char *cset = nl_langinfo (CODESET);
3759 state.utf8cs = !strcmp (cset, "UTF-8");
3761 else {
3762 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3764 #endif
3766 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3767 fz_register_document_handlers (state.ctx);
3768 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3769 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3770 fz_install_load_system_font_funcs (state.ctx, NULL, NULL, lsff);
3772 state.trimmargins = Bool_val (Field (trim_v, 0));
3773 fuzz_v = Field (trim_v, 1);
3774 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3775 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3776 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3777 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3779 set_tex_params (colorspace);
3781 if (*fontpath) {
3782 state.face = load_font (fontpath);
3784 else {
3785 int len;
3786 const unsigned char *data;
3788 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3789 state.face = load_builtin_font (data, len);
3791 if (!state.face) _exit (1);
3793 realloctexts (texcount);
3794 setuppbo ();
3795 makestippletex ();
3797 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3798 if (ret) {
3799 errx (1, "pthread_create: %s", strerror (ret));
3802 CAMLreturn0;
3805 #if FIXME || !FIXME
3806 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3807 #endif