Moved to snippets
[llpp.git] / link.c
bloba5e6790cd83699781985e8eccc502f0c813ac04c
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 "-Wmissing-prototypes"
11 #pragma GCC diagnostic ignored "-Wdouble-promotion"
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; \
93 struct slice {
94 int h;
95 int texindex;
98 struct tile {
99 int w, h;
100 int slicecount;
101 int sliceheight;
102 struct bo *pbo;
103 fz_pixmap *pixmap;
104 struct slice slices[1];
107 struct pagedim {
108 int pageno;
109 int rotate;
110 int left;
111 int tctmready;
112 fz_irect bounds;
113 fz_rect pagebox;
114 fz_rect mediabox;
115 fz_matrix ctm, zoomctm, tctm;
118 struct slink {
119 enum { SLINK, SANNOT } tag;
120 fz_irect bbox;
121 union {
122 fz_link *link;
123 fz_annot *annot;
124 } u;
127 struct annot {
128 fz_irect bbox;
129 fz_annot *annot;
132 struct page {
133 int tgen;
134 int sgen;
135 int agen;
136 int pageno;
137 int pdimno;
138 fz_stext_page *text;
139 fz_page *fzpage;
140 fz_display_list *dlist;
141 fz_link *links;
142 int slinkcount;
143 struct slink *slinks;
144 int annotcount;
145 struct annot *annots;
146 fz_stext_char *fmark, *lmark;
149 enum { FitWidth, FitProportional, FitPage };
151 static struct {
152 int sliceheight;
153 struct pagedim *pagedims;
154 int pagecount;
155 int pagedimcount;
156 fz_document *doc;
157 fz_context *ctx;
158 int w, h;
160 int texindex;
161 int texcount;
162 GLuint *texids;
164 GLenum texiform;
165 GLenum texform;
166 GLenum texty;
168 fz_colorspace *colorspace;
170 struct {
171 int w, h;
172 struct slice *slice;
173 } *texowners;
175 int rotate;
176 int fitmodel;
177 int trimmargins;
178 int needoutline;
179 int gen;
180 int aalevel;
182 int trimanew;
183 fz_irect trimfuzz;
184 fz_pixmap *pig;
186 pthread_t thread;
187 int csock;
188 FT_Face face;
190 char *trimcachepath;
191 int dirty;
193 GLuint stid;
195 int bo_usable;
196 GLuint boid;
198 void (*glBindBufferARB) (GLenum, GLuint);
199 GLboolean (*glUnmapBufferARB) (GLenum);
200 void *(*glMapBufferARB) (GLenum, GLenum);
201 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
202 void (*glGenBuffersARB) (GLsizei, GLuint *);
203 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
205 GLfloat texcoords[8];
206 GLfloat vertices[16];
208 #ifdef CACHE_PAGEREFS
209 struct {
210 int idx;
211 int count;
212 pdf_obj **objs;
213 pdf_document *pdf;
214 } pdflut;
215 #endif
216 int utf8cs;
217 } state;
219 struct bo {
220 GLuint id;
221 void *ptr;
222 size_t size;
225 static void UNUSED_ATTR debug_rect (const char *cap, fz_rect r)
227 printf ("%s(rect) %.2f,%.2f,%.2f,%.2f\n", cap, r.x0, r.y0, r.x1, r.y1);
230 static void UNUSED_ATTR debug_bbox (const char *cap, fz_irect r)
232 printf ("%s(bbox) %d,%d,%d,%d\n", cap, r.x0, r.y0, r.x1, r.y1);
235 static void UNUSED_ATTR debug_matrix (const char *cap, fz_matrix m)
237 printf ("%s(matrix) %.2f,%.2f,%.2f,%.2f %.2f %.2f\n", cap,
238 m.a, m.b, m.c, m.d, m.e, m.f);
241 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
243 static void lock (const char *cap)
245 int ret = pthread_mutex_lock (&mutex);
246 if (ret) {
247 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
251 static void unlock (const char *cap)
253 int ret = pthread_mutex_unlock (&mutex);
254 if (ret) {
255 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
259 static int trylock (const char *cap)
261 int ret = pthread_mutex_trylock (&mutex);
262 if (ret && ret != EBUSY) {
263 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
265 return ret == EBUSY;
268 static int hasdata (void)
270 int ret, avail;
271 ret = ioctl (state.csock, FIONREAD, &avail);
272 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
273 return avail > 0;
276 CAMLprim value ml_hasdata (value fd_v)
278 CAMLparam1 (fd_v);
279 int ret, avail;
281 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
282 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
283 CAMLreturn (Val_bool (avail > 0));
286 static void readdata (int fd, void *p, int size)
288 ssize_t n;
290 again:
291 n = read (fd, p, size);
292 if (n - size) {
293 if (n < 0 && errno == EINTR) goto again;
294 if (!n) errx (1, "EOF while reading");
295 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
299 static void writedata (int fd, char *p, int size)
301 ssize_t n;
302 uint32_t size4 = size;
303 struct iovec iov[2] = {
304 { .iov_base = &size4, .iov_len = 4 },
305 { .iov_base = p, .iov_len = size }
308 again:
309 n = writev (fd, iov, 2);
310 if (n < 0 && errno == EINTR) goto again;
311 if (n - size - 4) {
312 if (!n) errx (1, "EOF while writing data");
313 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
317 static int readlen (int fd)
319 uint32_t u;
320 readdata (fd, &u, 4);
321 return u;
324 CAMLprim void ml_wcmd (value fd_v, value bytes_v, value len_v)
326 CAMLparam3 (fd_v, bytes_v, len_v);
327 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
328 CAMLreturn0;
331 CAMLprim value ml_rcmd (value fd_v)
333 CAMLparam1 (fd_v);
334 CAMLlocal1 (strdata_v);
335 int fd = Int_val (fd_v);
336 int len = readlen (fd);
337 strdata_v = caml_alloc_string (len);
338 readdata (fd, String_val (strdata_v), len);
339 CAMLreturn (strdata_v);
342 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
344 char fbuf[64];
345 int size = sizeof (fbuf), len;
346 va_list ap;
347 char *buf = fbuf;
349 for (;;) {
350 va_start (ap, fmt);
351 len = vsnprintf (buf, size, fmt, ap);
352 va_end (ap);
354 if (len > -1) {
355 if (len < size - 4) {
356 writedata (state.csock, buf, len);
357 break;
359 else size = len + 5;
361 else {
362 err (1, "vsnprintf for `%s' failed", fmt);
364 buf = realloc (buf == fbuf ? NULL : buf, size);
365 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
367 if (buf != fbuf) free (buf);
370 static void closedoc (void)
372 #ifdef CACHE_PAGEREFS
373 if (state.pdflut.objs) {
374 for (int i = 0; i < state.pdflut.count; ++i) {
375 pdf_drop_obj (state.ctx, state.pdflut.objs[i]);
377 free (state.pdflut.objs);
378 state.pdflut.objs = NULL;
379 state.pdflut.idx = 0;
381 #endif
382 if (state.doc) {
383 fz_drop_document (state.ctx, state.doc);
384 state.doc = NULL;
388 static int openxref (char *filename, char *password, int layouth)
390 for (int i = 0; i < state.texcount; ++i) {
391 state.texowners[i].w = -1;
392 state.texowners[i].slice = NULL;
395 closedoc ();
397 state.dirty = 0;
398 if (state.pagedims) {
399 free (state.pagedims);
400 state.pagedims = NULL;
402 state.pagedimcount = 0;
404 fz_set_aa_level (state.ctx, state.aalevel);
405 state.doc = fz_open_document (state.ctx, filename);
406 if (fz_needs_password (state.ctx, state.doc)) {
407 if (password && !*password) {
408 printd ("pass");
409 return 0;
411 else {
412 int ok = fz_authenticate_password (state.ctx, state.doc, password);
413 if (!ok) {
414 printd ("pass fail");
415 return 0;
419 if (layouth >= 0)
420 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
421 state.pagecount = fz_count_pages (state.ctx, state.doc);
422 return 1;
425 static void docinfo (void)
427 struct { char *tag; char *name; } metatbl[] = {
428 { FZ_META_INFO_TITLE, "Title" },
429 { FZ_META_INFO_AUTHOR, "Author" },
430 { FZ_META_FORMAT, "Format" },
431 { FZ_META_ENCRYPTION, "Encryption" },
432 { "info:Creator", "Creator" },
433 { "info:Producer", "Producer" },
434 { "info:CreationDate", "Creation date" },
436 int len = 0;
437 char *buf = NULL;
439 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
440 int need;
441 again:
442 need = fz_lookup_metadata (state.ctx, state.doc,
443 metatbl[i].tag, buf, len);
444 if (need > 0) {
445 if (need <= len) {
446 printd ("info %s\t%s", metatbl[i].name, buf);
448 else {
449 buf = realloc (buf, need + 1);
450 if (!buf) err (1, "docinfo realloc %d", need + 1);
451 len = need + 1;
452 goto again;
456 free (buf);
458 printd ("infoend");
461 static void unlinktile (struct tile *tile)
463 for (int i = 0; i < tile->slicecount; ++i) {
464 struct slice *s = &tile->slices[i];
466 if (s->texindex != -1) {
467 if (state.texowners[s->texindex].slice == s) {
468 state.texowners[s->texindex].slice = NULL;
474 static void freepage (struct page *page)
476 if (!page) return;
477 if (page->text) {
478 fz_drop_stext_page (state.ctx, page->text);
480 if (page->slinks) {
481 free (page->slinks);
483 fz_drop_display_list (state.ctx, page->dlist);
484 fz_drop_page (state.ctx, page->fzpage);
485 free (page);
488 static void freetile (struct tile *tile)
490 unlinktile (tile);
491 if (!tile->pbo) {
492 #if 0
493 fz_drop_pixmap (state.ctx, tile->pixmap);
494 #else /* piggyback */
495 if (state.pig) {
496 fz_drop_pixmap (state.ctx, state.pig);
498 state.pig = tile->pixmap;
499 #endif
501 else {
502 free (tile->pbo);
503 fz_drop_pixmap (state.ctx, tile->pixmap);
505 free (tile);
508 static void trimctm (pdf_page *page, int pindex)
510 fz_matrix ctm;
511 struct pagedim *pdim = &state.pagedims[pindex];
513 if (!page) return;
514 if (!pdim->tctmready) {
515 fz_rect realbox, mediabox;
516 fz_matrix rm, sm, tm, im, ctm1, page_ctm;
518 fz_rotate (&rm, -pdim->rotate);
519 fz_scale (&sm, 1, -1);
520 fz_concat (&ctm, &rm, &sm);
521 realbox = pdim->mediabox;
522 fz_transform_rect (&realbox, &ctm);
523 fz_translate (&tm, -realbox.x0, -realbox.y0);
524 fz_concat (&ctm1, &ctm, &tm);
525 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
526 fz_invert_matrix (&im, &page_ctm);
527 fz_concat (&ctm, &im, &ctm1);
528 pdim->tctm = ctm;
529 pdim->tctmready = 1;
533 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
535 fz_matrix ctm, tm;
536 ptrdiff_t pdimno = pdim - state.pagedims;
538 ARSERT (pdim - state.pagedims < INT_MAX);
539 if (pdf_specifics (state.ctx, state.doc)) {
540 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
541 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
543 else {
544 fz_translate (&tm, -pdim->mediabox.x0, -pdim->mediabox.y0);
545 fz_concat (&ctm, &tm, &pdim->ctm);
547 return ctm;
550 static fz_matrix pagectm (struct page *page)
552 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
555 static void *loadpage (int pageno, int pindex)
557 fz_device *dev;
558 struct page *page;
560 page = calloc (sizeof (struct page), 1);
561 if (!page) {
562 err (1, "calloc page %d", pageno);
565 page->dlist = fz_new_display_list (state.ctx, NULL);
566 dev = fz_new_list_device (state.ctx, page->dlist);
567 fz_try (state.ctx) {
568 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
569 fz_run_page (state.ctx, page->fzpage, dev,
570 &fz_identity, NULL);
572 fz_catch (state.ctx) {
573 page->fzpage = NULL;
575 fz_close_device (state.ctx, dev);
576 fz_drop_device (state.ctx, dev);
578 page->pdimno = pindex;
579 page->pageno = pageno;
580 page->sgen = state.gen;
581 page->agen = state.gen;
582 page->tgen = state.gen;
583 return page;
586 static struct tile *alloctile (int h)
588 int slicecount;
589 size_t tilesize;
590 struct tile *tile;
592 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
593 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
594 tile = calloc (tilesize, 1);
595 if (!tile) {
596 err (1, "cannot allocate tile (%zu bytes)", tilesize);
598 for (int i = 0; i < slicecount; ++i) {
599 int sh = fz_mini (h, state.sliceheight);
600 tile->slices[i].h = sh;
601 tile->slices[i].texindex = -1;
602 h -= sh;
604 tile->slicecount = slicecount;
605 tile->sliceheight = state.sliceheight;
606 return tile;
609 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
610 struct bo *pbo)
612 fz_rect rect;
613 fz_irect bbox;
614 fz_matrix ctm;
615 fz_device *dev;
616 struct tile *tile;
617 struct pagedim *pdim;
619 tile = alloctile (h);
620 pdim = &state.pagedims[page->pdimno];
622 bbox = pdim->bounds;
623 bbox.x0 += x;
624 bbox.y0 += y;
625 bbox.x1 = bbox.x0 + w;
626 bbox.y1 = bbox.y0 + h;
628 if (state.pig) {
629 if (state.pig->w == w
630 && state.pig->h == h
631 && state.pig->colorspace == state.colorspace) {
632 tile->pixmap = state.pig;
633 tile->pixmap->x = bbox.x0;
634 tile->pixmap->y = bbox.y0;
636 else {
637 fz_drop_pixmap (state.ctx, state.pig);
639 state.pig = NULL;
641 if (!tile->pixmap) {
642 if (pbo) {
643 tile->pixmap =
644 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
645 &bbox, NULL, 1, pbo->ptr);
646 tile->pbo = pbo;
648 else {
649 tile->pixmap =
650 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, &bbox,
651 NULL, 1);
655 tile->w = w;
656 tile->h = h;
657 fz_clear_pixmap_with_value (state.ctx, tile->pixmap, 0xff);
659 dev = fz_new_draw_device (state.ctx, NULL, tile->pixmap);
660 ctm = pagectm (page);
661 fz_rect_from_irect (&rect, &bbox);
662 fz_run_display_list (state.ctx, page->dlist, dev, &ctm, &rect, NULL);
663 fz_close_device (state.ctx, dev);
664 fz_drop_device (state.ctx, dev);
666 return tile;
669 #ifdef CACHE_PAGEREFS
670 /* modified mupdf/source/pdf/pdf-page.c:pdf_lookup_page_loc_imp
671 thanks to Robin Watts */
672 static void
673 pdf_collect_pages(pdf_document *doc, pdf_obj *node)
675 fz_context *ctx = state.ctx; /* doc->ctx; */
676 pdf_obj *kids;
677 int len;
679 if (state.pdflut.idx == state.pagecount) return;
681 kids = pdf_dict_gets (ctx, node, "Kids");
682 len = pdf_array_len (ctx, kids);
684 if (len == 0)
685 fz_throw (ctx, FZ_ERROR_GENERIC, "malformed pages tree");
687 if (pdf_mark_obj (ctx, node))
688 fz_throw (ctx, FZ_ERROR_GENERIC, "cycle in page tree");
689 for (int i = 0; i < len; i++) {
690 pdf_obj *kid = pdf_array_get (ctx, kids, i);
691 const char *type = pdf_to_name (ctx, pdf_dict_gets (ctx, kid, "Type"));
692 if (*type
693 ? !strcmp (type, "Pages")
694 : pdf_dict_gets (ctx, kid, "Kids")
695 && !pdf_dict_gets (ctx, kid, "MediaBox")) {
696 pdf_collect_pages (doc, kid);
698 else {
699 if (*type
700 ? strcmp (type, "Page") != 0
701 : !pdf_dict_gets (ctx, kid, "MediaBox"))
702 fz_warn (ctx, "non-page object in page tree (%s)", type);
703 state.pdflut.objs[state.pdflut.idx++] = pdf_keep_obj (ctx, kid);
706 pdf_unmark_obj (ctx, node);
709 static void
710 pdf_load_page_objs (pdf_document *doc)
712 pdf_obj *root = pdf_dict_gets (state.ctx,
713 pdf_trailer (state.ctx, doc), "Root");
714 pdf_obj *node = pdf_dict_gets (state.ctx, root, "Pages");
716 if (!node)
717 fz_throw (state.ctx, FZ_ERROR_GENERIC, "cannot find page tree");
719 state.pdflut.idx = 0;
720 pdf_collect_pages (doc, node);
722 #endif
724 static void initpdims (void)
726 double start, end;
727 FILE *trimf = NULL;
728 fz_rect rootmediabox = fz_empty_rect;
729 int pageno, trim, show;
730 int trimw = 0, cxcount;
731 fz_context *ctx = state.ctx;
732 pdf_document *pdf = pdf_specifics (ctx, state.doc);
734 fz_var (trimw);
735 fz_var (trimf);
736 fz_var (cxcount);
737 start = now ();
739 if (state.trimmargins && state.trimcachepath) {
740 trimf = fopen (state.trimcachepath, "rb");
741 if (!trimf) {
742 trimf = fopen (state.trimcachepath, "wb");
743 trimw = 1;
747 if (state.trimmargins || pdf)
748 cxcount = state.pagecount;
749 else
750 cxcount = fz_mini (state.pagecount, 1);
752 if (pdf) {
753 pdf_obj *obj;
754 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
755 "Root/Pages/MediaBox");
756 pdf_to_rect (ctx, obj, &rootmediabox);
759 #ifdef CACHE_PAGEREFS
760 if (pdf && (!state.pdflut.objs || state.pdflut.pdf != pdf)) {
761 state.pdflut.objs = calloc (sizeof (*state.pdflut.objs), cxcount);
762 if (!state.pdflut.objs) {
763 err (1, "malloc pageobjs %zu %d %zu failed",
764 sizeof (*state.pdflut.objs), cxcount,
765 sizeof (*state.pdflut.objs) * cxcount);
767 state.pdflut.count = cxcount;
768 pdf_load_page_objs (pdf);
769 state.pdflut.pdf = pdf;
771 #endif
773 for (pageno = 0; pageno < cxcount; ++pageno) {
774 int rotate = 0;
775 struct pagedim *p;
776 fz_rect mediabox = fz_empty_rect;
778 fz_var (rotate);
779 if (pdf) {
780 pdf_obj *pageref, *pageobj;
782 #ifdef CACHE_PAGEREFS
783 pageref = state.pdflut.objs[pageno];
784 #else
785 pageref = pdf_lookup_page_obj (ctx, pdf, pageno);
786 #endif
787 pageobj = pdf_resolve_indirect (ctx, pageref);
788 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
790 if (state.trimmargins) {
791 pdf_obj *obj;
792 pdf_page *page;
794 fz_try (ctx) {
795 page = pdf_load_page (ctx, pdf, pageno);
796 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
797 trim = state.trimanew || !obj;
798 if (trim) {
799 fz_rect rect;
800 fz_device *dev;
801 fz_matrix ctm, page_ctm;
803 dev = fz_new_bbox_device (ctx, &rect);
804 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
805 fz_invert_matrix (&ctm, &page_ctm);
806 pdf_run_page (ctx, page, dev, &fz_identity, NULL);
807 fz_close_device (ctx, dev);
808 fz_drop_device (ctx, dev);
810 rect.x0 += state.trimfuzz.x0;
811 rect.x1 += state.trimfuzz.x1;
812 rect.y0 += state.trimfuzz.y0;
813 rect.y1 += state.trimfuzz.y1;
814 fz_transform_rect (&rect, &ctm);
815 fz_intersect_rect (&rect, &mediabox);
817 if (!fz_is_empty_rect (&rect)) {
818 mediabox = rect;
821 obj = pdf_new_array (ctx, pdf, 4);
822 pdf_array_push (ctx, obj,
823 pdf_new_real (ctx, mediabox.x0));
824 pdf_array_push (ctx, obj,
825 pdf_new_real (ctx, mediabox.y0));
826 pdf_array_push (ctx, obj,
827 pdf_new_real (ctx, mediabox.x1));
828 pdf_array_push (ctx, obj,
829 pdf_new_real (ctx, mediabox.y1));
830 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
832 else {
833 mediabox.x0 = pdf_to_real (ctx,
834 pdf_array_get (ctx, obj, 0));
835 mediabox.y0 = pdf_to_real (ctx,
836 pdf_array_get (ctx, obj, 1));
837 mediabox.x1 = pdf_to_real (ctx,
838 pdf_array_get (ctx, obj, 2));
839 mediabox.y1 = pdf_to_real (ctx,
840 pdf_array_get (ctx, obj, 3));
843 fz_drop_page (ctx, &page->super);
844 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
845 if (show) {
846 printd ("progress %f Trimming %d",
847 (double) (pageno + 1) / state.pagecount,
848 pageno + 1);
851 fz_catch (ctx) {
852 printd ("emsg failed to load page %d", pageno);
855 else {
856 int empty = 0;
857 fz_rect cropbox;
859 pdf_to_rect (ctx,
860 pdf_dict_gets (ctx, pageobj, "MediaBox"),
861 &mediabox);
862 if (fz_is_empty_rect (&mediabox)) {
863 mediabox.x0 = 0;
864 mediabox.y0 = 0;
865 mediabox.x1 = 612;
866 mediabox.y1 = 792;
867 empty = 1;
870 pdf_to_rect (ctx,
871 pdf_dict_gets (ctx, pageobj, "CropBox"),
872 &cropbox);
873 if (!fz_is_empty_rect (&cropbox)) {
874 if (empty) {
875 mediabox = cropbox;
877 else {
878 fz_intersect_rect (&mediabox, &cropbox);
881 else {
882 if (empty) {
883 if (fz_is_empty_rect (&rootmediabox)) {
884 printd ("emsg cannot find page size for page %d",
885 pageno);
887 else {
888 mediabox = rootmediabox;
894 else {
895 if (state.trimmargins && trimw) {
896 fz_page *page;
898 fz_try (ctx) {
899 page = fz_load_page (ctx, state.doc, pageno);
900 fz_bound_page (ctx, page, &mediabox);
901 if (state.trimmargins) {
902 fz_rect rect;
903 fz_device *dev;
905 dev = fz_new_bbox_device (ctx, &rect);
906 fz_run_page (ctx, page, dev, &fz_identity, NULL);
907 fz_close_device (ctx, dev);
908 fz_drop_device (ctx, dev);
910 rect.x0 += state.trimfuzz.x0;
911 rect.x1 += state.trimfuzz.x1;
912 rect.y0 += state.trimfuzz.y0;
913 rect.y1 += state.trimfuzz.y1;
914 fz_intersect_rect (&rect, &mediabox);
916 if (!fz_is_empty_rect (&rect)) {
917 mediabox = rect;
920 fz_drop_page (ctx, page);
922 fz_catch (ctx) {
924 if (trimf) {
925 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
926 if (n - 1) {
927 err (1, "fwrite trim mediabox");
931 else {
932 if (trimf) {
933 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
934 if (n - 1) {
935 err (1, "fread trim mediabox %d", pageno);
938 else {
939 fz_page *page;
940 fz_try (ctx) {
941 page = fz_load_page (ctx, state.doc, pageno);
942 fz_bound_page (ctx, page, &mediabox);
943 fz_drop_page (ctx, page);
945 show = !state.trimmargins && pageno % 20 == 0;
946 if (show) {
947 printd ("progress %f Gathering dimensions %d",
948 (double) (pageno) / state.pagecount,
949 pageno);
952 fz_catch (ctx) {
953 printd ("emsg failed to load page %d", pageno);
959 if (state.pagedimcount == 0
960 || ((void) (p = &state.pagedims[state.pagedimcount-1])
961 , p->rotate != rotate)
962 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
963 size_t size;
965 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
966 state.pagedims = realloc (state.pagedims, size);
967 if (!state.pagedims) {
968 err (1, "realloc pagedims to %zu (%d elems)",
969 size, state.pagedimcount + 1);
972 p = &state.pagedims[state.pagedimcount++];
973 p->rotate = rotate;
974 p->mediabox = mediabox;
975 p->pageno = pageno;
978 end = now ();
979 printd ("progress 1 %s %d pages in %f seconds",
980 state.trimmargins ? "Trimmed" : "Processed",
981 state.pagecount, end - start);
982 state.trimanew = 0;
983 if (trimf) {
984 if (fclose (trimf)) {
985 err (1, "fclose");
990 static void layout (void)
992 int pindex;
993 fz_rect box;
994 fz_matrix ctm, rm;
995 struct pagedim *p = NULL;
996 float zw, w, maxw = 0.0, zoom = 1.0;
998 if (state.pagedimcount == 0) return;
1000 switch (state.fitmodel) {
1001 case FitProportional:
1002 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1003 float x0, x1;
1005 p = &state.pagedims[pindex];
1006 fz_rotate (&rm, p->rotate + state.rotate);
1007 box = p->mediabox;
1008 fz_transform_rect (&box, &rm);
1010 x0 = fz_min (box.x0, box.x1);
1011 x1 = fz_max (box.x0, box.x1);
1013 w = x1 - x0;
1014 maxw = fz_max (w, maxw);
1015 zoom = state.w / maxw;
1017 break;
1019 case FitPage:
1020 maxw = state.w;
1021 break;
1023 case FitWidth:
1024 break;
1026 default:
1027 ARSERT (0 && state.fitmodel);
1030 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
1031 fz_rect rect;
1032 fz_matrix tm, sm;
1034 p = &state.pagedims[pindex];
1035 fz_rotate (&ctm, state.rotate);
1036 fz_rotate (&rm, p->rotate + state.rotate);
1037 box = p->mediabox;
1038 fz_transform_rect (&box, &rm);
1039 w = box.x1 - box.x0;
1040 switch (state.fitmodel) {
1041 case FitProportional:
1042 p->left = (int) (((maxw - w) * zoom) / 2.f);
1043 break;
1044 case FitPage:
1046 float zh, h;
1047 zw = maxw / w;
1048 h = box.y1 - box.y0;
1049 zh = state.h / h;
1050 zoom = fz_min (zw, zh);
1051 p->left = (int) ((maxw - (w * zoom)) / 2.f);
1053 break;
1054 case FitWidth:
1055 p->left = 0;
1056 zoom = state.w / w;
1057 break;
1060 fz_scale (&p->zoomctm, zoom, zoom);
1061 fz_concat (&ctm, &p->zoomctm, &ctm);
1063 fz_rotate (&rm, p->rotate);
1064 p->pagebox = p->mediabox;
1065 fz_transform_rect (&p->pagebox, &rm);
1066 p->pagebox.x1 -= p->pagebox.x0;
1067 p->pagebox.y1 -= p->pagebox.y0;
1068 p->pagebox.x0 = 0;
1069 p->pagebox.y0 = 0;
1070 rect = p->pagebox;
1071 fz_transform_rect (&rect, &ctm);
1072 fz_round_rect (&p->bounds, &rect);
1073 p->ctm = ctm;
1075 fz_translate (&tm, 0, -p->mediabox.y1);
1076 fz_scale (&sm, zoom, -zoom);
1077 fz_concat (&ctm, &tm, &sm);
1079 p->tctmready = 0;
1082 do {
1083 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
1084 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
1085 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
1086 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
1087 int boundw = x1 - x0;
1088 int boundh = y1 - y0;
1090 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
1091 } while (p-- != state.pagedims);
1094 struct pagedim *pdimofpageno (int pageno)
1096 struct pagedim *pdim = state.pagedims;
1098 for (int i = 0; i < state.pagedimcount; ++i) {
1099 if (state.pagedims[i].pageno > pageno)
1100 break;
1101 pdim = &state.pagedims[i];
1103 return pdim;
1106 static void recurse_outline (fz_outline *outline, int level)
1108 while (outline) {
1109 if (outline->page >= 0) {
1110 fz_point p = {.x = outline->x, .y = outline->y};
1111 struct pagedim *pdim = pdimofpageno (outline->page);
1112 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1113 fz_transform_point (&p, &pdim->ctm);
1114 printd ("o %d %d %d %d %s",
1115 level, outline->page, (int) p.y, h, outline->title);
1117 else {
1118 printd ("on %d %s", level, outline->title);
1120 if (outline->down) {
1121 recurse_outline (outline->down, level + 1);
1123 outline = outline->next;
1127 static void process_outline (void)
1129 fz_outline *outline;
1131 if (!state.needoutline || !state.pagedimcount) return;
1133 state.needoutline = 0;
1134 outline = fz_load_outline (state.ctx, state.doc);
1135 if (outline) {
1136 recurse_outline (outline, 0);
1137 fz_drop_outline (state.ctx, outline);
1141 static char *strofline (fz_stext_line *line)
1143 char *p;
1144 char utf8[10];
1145 fz_stext_char *ch;
1146 size_t size = 0, cap = 80;
1148 p = malloc (cap + 1);
1149 if (!p) return NULL;
1151 for (ch = line->first_char; ch; ch = ch->next) {
1152 int n = fz_runetochar (utf8, ch->c);
1153 if (size + n > cap) {
1154 cap *= 2;
1155 p = realloc (p, cap + 1);
1156 if (!p) return NULL;
1159 memcpy (p + size, utf8, n);
1160 size += n;
1162 p[size] = 0;
1163 return p;
1166 static int matchline (regex_t *re, fz_stext_line *line,
1167 int stop, int pageno, double start)
1169 int ret;
1170 char *p;
1171 regmatch_t rm;
1173 p = strofline (line);
1174 if (!p) return -1;
1176 ret = regexec (re, p, 1, &rm, 0);
1177 if (ret) {
1178 free (p);
1179 if (ret != REG_NOMATCH) {
1180 size_t size;
1181 char errbuf[80];
1182 size = regerror (ret, re, errbuf, sizeof (errbuf));
1183 printd ("msg regexec error `%.*s'",
1184 (int) size, errbuf);
1185 return -1;
1187 return 0;
1189 else {
1190 fz_quad s, e;
1191 fz_stext_char *ch;
1192 int o = 0;
1194 for (ch = line->first_char; ch; ch = ch->next) {
1195 o += fz_runelen (ch->c);
1196 if (o > rm.rm_so) {
1197 s = ch->quad;
1198 break;
1201 for (;ch; ch = ch->next) {
1202 o += fz_runelen (ch->c);
1203 if (o > rm.rm_eo) break;
1205 e = ch->quad;
1207 if (!stop) {
1208 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1209 pageno, 1,
1210 s.ul.x, s.ul.y,
1211 e.ur.x, s.ul.y,
1212 e.lr.x, e.lr.y,
1213 s.ul.x, e.lr.y);
1215 printd ("progress 1 found at %d `%.*s' in %f sec",
1216 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1217 now () - start);
1219 else {
1220 printd ("match %d %d %f %f %f %f %f %f %f %f",
1221 pageno, 2,
1222 s.ul.x, s.ul.y,
1223 e.ur.x, s.ul.y,
1224 e.lr.x, e.lr.y,
1225 s.ul.x, e.lr.y);
1227 free (p);
1228 return 1;
1232 /* wishful thinking function */
1233 static void search (regex_t *re, int pageno, int y, int forward)
1235 fz_device *tdev;
1236 fz_stext_page *text;
1237 struct pagedim *pdim;
1238 int stop = 0, niters = 0;
1239 double start, end;
1240 fz_page *page;
1241 fz_stext_block *block;
1243 start = now ();
1244 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1245 if (niters++ == 5) {
1246 niters = 0;
1247 if (hasdata ()) {
1248 printd ("progress 1 attention requested aborting search at %d",
1249 pageno);
1250 stop = 1;
1252 else {
1253 printd ("progress %f searching in page %d",
1254 (double) (pageno + 1) / state.pagecount,
1255 pageno);
1258 pdim = pdimofpageno (pageno);
1259 text = fz_new_stext_page (state.ctx, &pdim->mediabox);
1260 tdev = fz_new_stext_device (state.ctx, text, 0);
1262 page = fz_load_page (state.ctx, state.doc, pageno);
1264 fz_matrix ctm = pagectm1 (page, pdim);
1265 fz_run_page (state.ctx, page, tdev, &ctm, NULL);
1268 fz_close_device (state.ctx, tdev);
1269 fz_drop_device (state.ctx, tdev);
1271 if (forward) {
1272 for (block = text->first_block; block; block = block->next) {
1273 fz_stext_line *line;
1275 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1276 for (line = block->u.t.first_line; line; line = line->next) {
1277 if (line->bbox.y0 < y + 1) continue;
1279 switch (matchline (re, line, stop, pageno, start)) {
1280 case 0: break;
1281 case 1: stop = 1; break;
1282 case -1: stop = 1; goto endloop;
1287 else {
1288 for (block = text->last_block; block; block = block->prev) {
1289 fz_stext_line *line;
1291 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1292 for (line = block->u.t.last_line; line; line = line->prev) {
1293 if (line->bbox.y0 < y + 1) continue;
1295 switch (matchline (re, line, stop, pageno, start)) {
1296 case 0: break;
1297 case 1: stop = 1; break;
1298 case -1: stop = 1; goto endloop;
1304 if (forward) {
1305 pageno += 1;
1306 y = 0;
1308 else {
1309 pageno -= 1;
1310 y = INT_MAX;
1312 endloop:
1313 fz_drop_stext_page (state.ctx, text);
1314 fz_drop_page (state.ctx, page);
1316 end = now ();
1317 if (!stop) {
1318 printd ("progress 1 no matches %f sec", end - start);
1320 printd ("clearrects");
1323 static void set_tex_params (int colorspace)
1325 switch (colorspace) {
1326 case 0:
1327 state.texiform = GL_RGBA8;
1328 state.texform = GL_RGBA;
1329 state.texty = GL_UNSIGNED_BYTE;
1330 state.colorspace = fz_device_rgb (state.ctx);
1331 break;
1332 case 1:
1333 state.texiform = GL_LUMINANCE_ALPHA;
1334 state.texform = GL_LUMINANCE_ALPHA;
1335 state.texty = GL_UNSIGNED_BYTE;
1336 state.colorspace = fz_device_gray (state.ctx);
1337 break;
1338 default:
1339 errx (1, "invalid colorspce %d", colorspace);
1343 static void realloctexts (int texcount)
1345 size_t size;
1347 if (texcount == state.texcount) return;
1349 if (texcount < state.texcount) {
1350 glDeleteTextures (state.texcount - texcount,
1351 state.texids + texcount);
1354 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1355 state.texids = realloc (state.texids, size);
1356 if (!state.texids) {
1357 err (1, "realloc texs %zu", size);
1360 state.texowners = (void *) (state.texids + texcount);
1361 if (texcount > state.texcount) {
1362 glGenTextures (texcount - state.texcount,
1363 state.texids + state.texcount);
1364 for (int i = state.texcount; i < texcount; ++i) {
1365 state.texowners[i].w = -1;
1366 state.texowners[i].slice = NULL;
1369 state.texcount = texcount;
1370 state.texindex = 0;
1373 static char *mbtoutf8 (char *s)
1375 char *p, *r;
1376 wchar_t *tmp;
1377 size_t i, ret, len;
1379 if (state.utf8cs) {
1380 return s;
1383 len = mbstowcs (NULL, s, strlen (s));
1384 if (len == 0 || len == (size_t) -1) {
1385 if (len)
1386 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1387 return s;
1390 tmp = calloc (len, sizeof (wchar_t));
1391 if (!tmp) {
1392 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1393 len, sizeof (wchar_t), errno, strerror (errno));
1394 return s;
1397 ret = mbstowcs (tmp, s, len);
1398 if (ret == (size_t) -1) {
1399 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1400 len, errno, strerror (errno));
1401 free (tmp);
1402 return s;
1405 len = 0;
1406 for (i = 0; i < ret; ++i) {
1407 len += fz_runelen (tmp[i]);
1410 p = r = malloc (len + 1);
1411 if (!r) {
1412 printd ("emsg mbtoutf8: malloc(%zu)", len);
1413 free (tmp);
1414 return s;
1417 for (i = 0; i < ret; ++i) {
1418 p += fz_runetochar (p, tmp[i]);
1420 *p = 0;
1421 free (tmp);
1422 return r;
1425 CAMLprim value ml_mbtoutf8 (value s_v)
1427 CAMLparam1 (s_v);
1428 CAMLlocal1 (ret_v);
1429 char *s, *r;
1431 s = String_val (s_v);
1432 r = mbtoutf8 (s);
1433 if (r == s) {
1434 ret_v = s_v;
1436 else {
1437 ret_v = caml_copy_string (r);
1438 free (r);
1440 CAMLreturn (ret_v);
1443 static void * mainloop (void UNUSED_ATTR *unused)
1445 char *p = NULL;
1446 int len, ret, oldlen = 0;
1448 fz_var (p);
1449 fz_var (oldlen);
1450 for (;;) {
1451 len = readlen (state.csock);
1452 if (len == 0) {
1453 errx (1, "readlen returned 0");
1456 if (oldlen < len + 1) {
1457 p = realloc (p, len + 1);
1458 if (!p) {
1459 err (1, "realloc %d failed", len + 1);
1461 oldlen = len + 1;
1463 readdata (state.csock, p, len);
1464 p[len] = 0;
1466 if (!strncmp ("open", p, 4)) {
1467 int off, usedoccss, ok = 0, layouth;
1468 char *password;
1469 char *filename;
1470 char *utf8filename;
1471 size_t filenamelen;
1473 fz_var (ok);
1474 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1475 if (ret != 2) {
1476 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1479 filename = p + 5 + off;
1480 filenamelen = strlen (filename);
1481 password = filename + filenamelen + 1;
1483 if (password[strlen (password) + 1]) {
1484 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1487 lock ("open");
1488 fz_set_use_document_css (state.ctx, usedoccss);
1489 fz_try (state.ctx) {
1490 ok = openxref (filename, password, layouth);
1492 fz_catch (state.ctx) {
1493 utf8filename = mbtoutf8 (filename);
1494 printd ("msg Could not open %s", utf8filename);
1495 if (utf8filename != filename) {
1496 free (utf8filename);
1499 if (ok) {
1500 docinfo ();
1501 initpdims ();
1503 unlock ("open");
1505 if (ok) {
1506 utf8filename = mbtoutf8 (filename);
1507 printd ("msg Opened %s (press h/F1 to get help)", utf8filename);
1508 if (utf8filename != filename) {
1509 free (utf8filename);
1511 state.needoutline = 1;
1514 else if (!strncmp ("cs", p, 2)) {
1515 int i, colorspace;
1517 ret = sscanf (p + 2, " %d", &colorspace);
1518 if (ret != 1) {
1519 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1521 lock ("cs");
1522 set_tex_params (colorspace);
1523 for (i = 0; i < state.texcount; ++i) {
1524 state.texowners[i].w = -1;
1525 state.texowners[i].slice = NULL;
1527 unlock ("cs");
1529 else if (!strncmp ("freepage", p, 8)) {
1530 void *ptr;
1532 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1533 if (ret != 1) {
1534 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1536 lock ("freepage");
1537 freepage (ptr);
1538 unlock ("freepage");
1540 else if (!strncmp ("freetile", p, 8)) {
1541 void *ptr;
1543 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1544 if (ret != 1) {
1545 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1547 lock ("freetile");
1548 freetile (ptr);
1549 unlock ("freetile");
1551 else if (!strncmp ("search", p, 6)) {
1552 int icase, pageno, y, len2, forward;
1553 char *pattern;
1554 regex_t re;
1556 ret = sscanf (p + 6, " %d %d %d %d,%n",
1557 &icase, &pageno, &y, &forward, &len2);
1558 if (ret != 4) {
1559 errx (1, "malformed search `%s' ret=%d", p, ret);
1562 pattern = p + 6 + len2;
1563 ret = regcomp (&re, pattern,
1564 REG_EXTENDED | (icase ? REG_ICASE : 0));
1565 if (ret) {
1566 char errbuf[80];
1567 size_t size;
1569 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1570 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1572 else {
1573 search (&re, pageno, y, forward);
1574 regfree (&re);
1577 else if (!strncmp ("geometry", p, 8)) {
1578 int w, h, fitmodel;
1580 printd ("clear");
1581 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1582 if (ret != 3) {
1583 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1586 lock ("geometry");
1587 state.h = h;
1588 if (w != state.w) {
1589 state.w = w;
1590 for (int i = 0; i < state.texcount; ++i) {
1591 state.texowners[i].slice = NULL;
1594 state.fitmodel = fitmodel;
1595 layout ();
1596 process_outline ();
1598 state.gen++;
1599 unlock ("geometry");
1600 printd ("continue %d", state.pagecount);
1602 else if (!strncmp ("reqlayout", p, 9)) {
1603 char *nameddest;
1604 int rotate, off, h;
1605 int fitmodel;
1606 pdf_document *pdf;
1608 printd ("clear");
1609 ret = sscanf (p + 9, " %d %d %d %n",
1610 &rotate, &fitmodel, &h, &off);
1611 if (ret != 3) {
1612 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1614 lock ("reqlayout");
1615 pdf = pdf_specifics (state.ctx, state.doc);
1616 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1617 state.gen += 1;
1619 state.rotate = rotate;
1620 state.fitmodel = fitmodel;
1621 state.h = h;
1622 layout ();
1623 process_outline ();
1625 nameddest = p + 9 + off;
1626 if (pdf && nameddest && *nameddest) {
1627 fz_point xy;
1628 struct pagedim *pdim;
1629 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1630 &xy.x, &xy.y);
1631 pdim = pdimofpageno (pageno);
1632 fz_transform_point (&xy, &pdim->ctm);
1633 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1636 state.gen++;
1637 unlock ("reqlayout");
1638 printd ("continue %d", state.pagecount);
1640 else if (!strncmp ("page", p, 4)) {
1641 double a, b;
1642 struct page *page;
1643 int pageno, pindex;
1645 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1646 if (ret != 2) {
1647 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1650 lock ("page");
1651 a = now ();
1652 page = loadpage (pageno, pindex);
1653 b = now ();
1654 unlock ("page");
1656 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1658 else if (!strncmp ("tile", p, 4)) {
1659 int x, y, w, h;
1660 struct page *page;
1661 struct tile *tile;
1662 double a, b;
1663 void *data;
1665 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1666 (uintptr_t *) &page, &x, &y, &w, &h,
1667 (uintptr_t *) &data);
1668 if (ret != 6) {
1669 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1672 lock ("tile");
1673 a = now ();
1674 tile = rendertile (page, x, y, w, h, data);
1675 b = now ();
1676 unlock ("tile");
1678 printd ("tile %d %d %" PRIxPTR " %u %f",
1679 x, y, (uintptr_t) (tile),
1680 tile->w * tile->h * tile->pixmap->n,
1681 b - a);
1683 else if (!strncmp ("trimset", p, 7)) {
1684 fz_irect fuzz;
1685 int trimmargins;
1687 ret = sscanf (p + 7, " %d %d %d %d %d",
1688 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1689 if (ret != 5) {
1690 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1692 lock ("trimset");
1693 state.trimmargins = trimmargins;
1694 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1695 state.trimanew = 1;
1696 state.trimfuzz = fuzz;
1698 unlock ("trimset");
1700 else if (!strncmp ("settrim", p, 7)) {
1701 fz_irect fuzz;
1702 int trimmargins;
1704 ret = sscanf (p + 7, " %d %d %d %d %d",
1705 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1706 if (ret != 5) {
1707 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1709 printd ("clear");
1710 lock ("settrim");
1711 state.trimmargins = trimmargins;
1712 state.needoutline = 1;
1713 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1714 state.trimanew = 1;
1715 state.trimfuzz = fuzz;
1717 state.pagedimcount = 0;
1718 free (state.pagedims);
1719 state.pagedims = NULL;
1720 initpdims ();
1721 layout ();
1722 process_outline ();
1723 unlock ("settrim");
1724 printd ("continue %d", state.pagecount);
1726 else if (!strncmp ("sliceh", p, 6)) {
1727 int h;
1729 ret = sscanf (p + 6, " %d", &h);
1730 if (ret != 1) {
1731 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1733 if (h != state.sliceheight) {
1734 state.sliceheight = h;
1735 for (int i = 0; i < state.texcount; ++i) {
1736 state.texowners[i].w = -1;
1737 state.texowners[i].h = -1;
1738 state.texowners[i].slice = NULL;
1742 else if (!strncmp ("interrupt", p, 9)) {
1743 printd ("vmsg interrupted");
1745 else {
1746 errx (1, "unknown command %.*s", len, p);
1749 return 0;
1752 CAMLprim value ml_isexternallink (value uri_v)
1754 CAMLparam1 (uri_v);
1755 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1756 CAMLreturn (Val_bool (ext));
1759 CAMLprim value ml_uritolocation (value uri_v)
1761 CAMLparam1 (uri_v);
1762 CAMLlocal1 (ret_v);
1763 int pageno;
1764 fz_point xy;
1765 struct pagedim *pdim;
1767 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1768 &xy.x, &xy.y);
1769 pdim = pdimofpageno (pageno);
1770 fz_transform_point (&xy, &pdim->ctm);
1771 ret_v = caml_alloc_tuple (3);
1772 Field (ret_v, 0) = Val_int (pageno);
1773 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1774 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1775 CAMLreturn (ret_v);
1778 CAMLprim value ml_realloctexts (value texcount_v)
1780 CAMLparam1 (texcount_v);
1781 int ok;
1783 if (trylock (__func__)) {
1784 ok = 0;
1785 goto done;
1787 realloctexts (Int_val (texcount_v));
1788 ok = 1;
1789 unlock (__func__);
1791 done:
1792 CAMLreturn (Val_bool (ok));
1795 static void recti (int x0, int y0, int x1, int y1)
1797 GLfloat *v = state.vertices;
1799 glVertexPointer (2, GL_FLOAT, 0, v);
1800 v[0] = x0; v[1] = y0;
1801 v[2] = x1; v[3] = y0;
1802 v[4] = x0; v[5] = y1;
1803 v[6] = x1; v[7] = y1;
1804 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1807 static void showsel (struct page *page, int ox, int oy)
1809 fz_irect bbox;
1810 fz_rect rect;
1811 fz_stext_block *block;
1812 int seen = 0;
1813 unsigned char selcolor[] = {15,15,15,140};
1815 if (!page->fmark || !page->lmark) return;
1817 glEnable (GL_BLEND);
1818 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1819 glColor4ubv (selcolor);
1821 ox += state.pagedims[page->pdimno].bounds.x0;
1822 oy += state.pagedims[page->pdimno].bounds.y0;
1824 for (block = page->text->first_block; block; block = block->next) {
1825 fz_stext_line *line;
1827 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1828 for (line = block->u.t.first_line; line; line = line->next) {
1829 fz_stext_char *ch;
1831 rect = fz_empty_rect;
1832 for (ch = line->first_char; ch; ch = ch->next) {
1833 fz_rect r;
1834 if (ch == page->fmark) seen = 1;
1835 r = fz_rect_from_quad (ch->quad);
1836 if (seen) fz_union_rect (&rect, &r);
1837 if (ch == page->lmark) {
1838 fz_round_rect (&bbox, &rect);
1839 recti (bbox.x0 + ox, bbox.y0 + oy,
1840 bbox.x1 + ox, bbox.y1 + oy);
1841 goto done;
1844 fz_round_rect (&bbox, &rect);
1845 recti (bbox.x0 + ox, bbox.y0 + oy,
1846 bbox.x1 + ox, bbox.y1 + oy);
1849 done:
1850 glDisable (GL_BLEND);
1853 #pragma GCC diagnostic push
1854 #pragma GCC diagnostic ignored "-Wconversion"
1855 #include "glfont.c"
1856 #pragma GCC diagnostic pop
1858 static void stipplerect (fz_matrix *m,
1859 fz_point *p1,
1860 fz_point *p2,
1861 fz_point *p3,
1862 fz_point *p4,
1863 GLfloat *texcoords,
1864 GLfloat *vertices)
1866 fz_transform_point (p1, m);
1867 fz_transform_point (p2, m);
1868 fz_transform_point (p3, m);
1869 fz_transform_point (p4, m);
1871 float w, h, s, t;
1873 w = p2->x - p1->x;
1874 h = p2->y - p1->y;
1875 t = hypotf (w, h) * .25f;
1877 w = p3->x - p2->x;
1878 h = p3->y - p2->y;
1879 s = hypotf (w, h) * .25f;
1881 texcoords[0] = 0; vertices[0] = p1->x; vertices[1] = p1->y;
1882 texcoords[1] = t; vertices[2] = p2->x; vertices[3] = p2->y;
1884 texcoords[2] = 0; vertices[4] = p2->x; vertices[5] = p2->y;
1885 texcoords[3] = s; vertices[6] = p3->x; vertices[7] = p3->y;
1887 texcoords[4] = 0; vertices[8] = p3->x; vertices[9] = p3->y;
1888 texcoords[5] = t; vertices[10] = p4->x; vertices[11] = p4->y;
1890 texcoords[6] = 0; vertices[12] = p4->x; vertices[13] = p4->y;
1891 texcoords[7] = s; vertices[14] = p1->x; vertices[15] = p1->y;
1893 glDrawArrays (GL_LINES, 0, 8);
1896 static void solidrect (fz_matrix *m,
1897 fz_point *p1,
1898 fz_point *p2,
1899 fz_point *p3,
1900 fz_point *p4,
1901 GLfloat *vertices)
1903 fz_transform_point (p1, m);
1904 fz_transform_point (p2, m);
1905 fz_transform_point (p3, m);
1906 fz_transform_point (p4, m);
1907 vertices[0] = p1->x; vertices[1] = p1->y;
1908 vertices[2] = p2->x; vertices[3] = p2->y;
1910 vertices[4] = p3->x; vertices[5] = p3->y;
1911 vertices[6] = p4->x; vertices[7] = p4->y;
1912 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1915 static void ensurelinks (struct page *page)
1917 if (!page->links)
1918 page->links = fz_load_links (state.ctx, page->fzpage);
1921 static void highlightlinks (struct page *page, int xoff, int yoff)
1923 fz_matrix ctm, tm, pm;
1924 fz_link *link;
1925 GLfloat *texcoords = state.texcoords;
1926 GLfloat *vertices = state.vertices;
1928 ensurelinks (page);
1930 glEnable (GL_TEXTURE_1D);
1931 glEnable (GL_BLEND);
1932 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1933 glBindTexture (GL_TEXTURE_1D, state.stid);
1935 xoff -= state.pagedims[page->pdimno].bounds.x0;
1936 yoff -= state.pagedims[page->pdimno].bounds.y0;
1937 fz_translate (&tm, xoff, yoff);
1938 pm = pagectm (page);
1939 fz_concat (&ctm, &pm, &tm);
1941 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1942 glVertexPointer (2, GL_FLOAT, 0, vertices);
1944 for (link = page->links; link; link = link->next) {
1945 fz_point p1, p2, p3, p4;
1947 p1.x = link->rect.x0;
1948 p1.y = link->rect.y0;
1950 p2.x = link->rect.x1;
1951 p2.y = link->rect.y0;
1953 p3.x = link->rect.x1;
1954 p3.y = link->rect.y1;
1956 p4.x = link->rect.x0;
1957 p4.y = link->rect.y1;
1959 /* TODO: different colours for different schemes */
1960 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1961 else glColor3ub (255, 0, 0);
1963 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
1966 for (int i = 0; i < page->annotcount; ++i) {
1967 fz_point p1, p2, p3, p4;
1968 struct annot *annot = &page->annots[i];
1970 p1.x = annot->bbox.x0;
1971 p1.y = annot->bbox.y0;
1973 p2.x = annot->bbox.x1;
1974 p2.y = annot->bbox.y0;
1976 p3.x = annot->bbox.x1;
1977 p3.y = annot->bbox.y1;
1979 p4.x = annot->bbox.x0;
1980 p4.y = annot->bbox.y1;
1982 glColor3ub (0, 0, 128);
1983 stipplerect (&ctm, &p1, &p2, &p3, &p4, texcoords, vertices);
1986 glDisable (GL_BLEND);
1987 glDisable (GL_TEXTURE_1D);
1990 static int compareslinks (const void *l, const void *r)
1992 struct slink const *ls = l;
1993 struct slink const *rs = r;
1994 if (ls->bbox.y0 == rs->bbox.y0) {
1995 return rs->bbox.x0 - rs->bbox.x0;
1997 return ls->bbox.y0 - rs->bbox.y0;
2000 static void droptext (struct page *page)
2002 if (page->text) {
2003 fz_drop_stext_page (state.ctx, page->text);
2004 page->fmark = NULL;
2005 page->lmark = NULL;
2006 page->text = NULL;
2010 static void dropannots (struct page *page)
2012 if (page->annots) {
2013 free (page->annots);
2014 page->annots = NULL;
2015 page->annotcount = 0;
2019 static void ensureannots (struct page *page)
2021 int i, count = 0;
2022 size_t annotsize = sizeof (*page->annots);
2023 fz_annot *annot;
2025 if (state.gen != page->agen) {
2026 dropannots (page);
2027 page->agen = state.gen;
2029 if (page->annots) return;
2031 for (annot = fz_first_annot (state.ctx, page->fzpage);
2032 annot;
2033 annot = fz_next_annot (state.ctx, annot)) {
2034 count++;
2037 if (count > 0) {
2038 page->annotcount = count;
2039 page->annots = calloc (count, annotsize);
2040 if (!page->annots) {
2041 err (1, "calloc annots %d", count);
2044 for (annot = fz_first_annot (state.ctx, page->fzpage), i = 0;
2045 annot;
2046 annot = fz_next_annot (state.ctx, annot), i++) {
2047 fz_rect rect;
2049 fz_bound_annot (state.ctx, annot, &rect);
2050 page->annots[i].annot = annot;
2051 fz_round_rect (&page->annots[i].bbox, &rect);
2056 static void dropslinks (struct page *page)
2058 if (page->slinks) {
2059 free (page->slinks);
2060 page->slinks = NULL;
2061 page->slinkcount = 0;
2063 if (page->links) {
2064 fz_drop_link (state.ctx, page->links);
2065 page->links = NULL;
2069 static void ensureslinks (struct page *page)
2071 fz_matrix ctm;
2072 int i, count;
2073 size_t slinksize = sizeof (*page->slinks);
2074 fz_link *link;
2076 ensureannots (page);
2077 if (state.gen != page->sgen) {
2078 dropslinks (page);
2079 page->sgen = state.gen;
2081 if (page->slinks) return;
2083 ensurelinks (page);
2084 ctm = pagectm (page);
2086 count = page->annotcount;
2087 for (link = page->links; link; link = link->next) {
2088 count++;
2090 if (count > 0) {
2091 int j;
2093 page->slinkcount = count;
2094 page->slinks = calloc (count, slinksize);
2095 if (!page->slinks) {
2096 err (1, "calloc slinks %d", count);
2099 for (i = 0, link = page->links; link; ++i, link = link->next) {
2100 fz_rect rect;
2102 rect = link->rect;
2103 fz_transform_rect (&rect, &ctm);
2104 page->slinks[i].tag = SLINK;
2105 page->slinks[i].u.link = link;
2106 fz_round_rect (&page->slinks[i].bbox, &rect);
2108 for (j = 0; j < page->annotcount; ++j, ++i) {
2109 fz_rect rect;
2110 fz_bound_annot (state.ctx, page->annots[j].annot, &rect);
2111 fz_transform_rect (&rect, &ctm);
2112 fz_round_rect (&page->slinks[i].bbox, &rect);
2114 page->slinks[i].tag = SANNOT;
2115 page->slinks[i].u.annot = page->annots[j].annot;
2117 qsort (page->slinks, count, slinksize, compareslinks);
2121 static void highlightslinks (struct page *page, int xoff, int yoff,
2122 int noff, char *targ, mlsize_t tlen, int hfsize)
2124 char buf[40];
2125 struct slink *slink;
2126 float x0, y0, x1, y1, w;
2128 ensureslinks (page);
2129 glColor3ub (0xc3, 0xb0, 0x91);
2130 for (int i = 0; i < page->slinkcount; ++i) {
2131 fmt_linkn (buf, i + noff);
2132 if (!tlen || !strncmp (targ, buf, tlen)) {
2133 slink = &page->slinks[i];
2135 x0 = slink->bbox.x0 + xoff - 5;
2136 y1 = slink->bbox.y0 + yoff - 5;
2137 y0 = y1 + 10 + hfsize;
2138 w = measure_string (state.face, hfsize, buf);
2139 x1 = x0 + w + 10;
2140 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2144 glEnable (GL_BLEND);
2145 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2146 glEnable (GL_TEXTURE_2D);
2147 glColor3ub (0, 0, 0);
2148 for (int i = 0; i < page->slinkcount; ++i) {
2149 fmt_linkn (buf, i + noff);
2150 if (!tlen || !strncmp (targ, buf, tlen)) {
2151 slink = &page->slinks[i];
2153 x0 = slink->bbox.x0 + xoff;
2154 y0 = slink->bbox.y0 + yoff + hfsize;
2155 draw_string (state.face, hfsize, x0, y0, buf);
2158 glDisable (GL_TEXTURE_2D);
2159 glDisable (GL_BLEND);
2162 static void uploadslice (struct tile *tile, struct slice *slice)
2164 int offset;
2165 struct slice *slice1;
2166 unsigned char *texdata;
2168 offset = 0;
2169 for (slice1 = tile->slices; slice != slice1; slice1++) {
2170 offset += slice1->h * tile->w * tile->pixmap->n;
2172 if (slice->texindex != -1 && slice->texindex < state.texcount
2173 && state.texowners[slice->texindex].slice == slice) {
2174 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2176 else {
2177 int subimage = 0;
2178 int texindex = state.texindex++ % state.texcount;
2180 if (state.texowners[texindex].w == tile->w) {
2181 if (state.texowners[texindex].h >= slice->h) {
2182 subimage = 1;
2184 else {
2185 state.texowners[texindex].h = slice->h;
2188 else {
2189 state.texowners[texindex].h = slice->h;
2192 state.texowners[texindex].w = tile->w;
2193 state.texowners[texindex].slice = slice;
2194 slice->texindex = texindex;
2196 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2197 #if TEXT_TYPE == GL_TEXTURE_2D
2198 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2199 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2200 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2201 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2202 #endif
2203 if (tile->pbo) {
2204 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2205 texdata = 0;
2207 else {
2208 texdata = tile->pixmap->samples;
2210 if (subimage) {
2211 glTexSubImage2D (TEXT_TYPE,
2215 tile->w,
2216 slice->h,
2217 state.texform,
2218 state.texty,
2219 texdata+offset
2222 else {
2223 glTexImage2D (TEXT_TYPE,
2225 state.texiform,
2226 tile->w,
2227 slice->h,
2229 state.texform,
2230 state.texty,
2231 texdata+offset
2234 if (tile->pbo) {
2235 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2240 CAMLprim void ml_begintiles (void)
2242 glEnable (TEXT_TYPE);
2243 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2244 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2247 CAMLprim void ml_endtiles (void)
2249 glDisable (TEXT_TYPE);
2252 CAMLprim void ml_drawtile (value args_v, value ptr_v)
2254 CAMLparam2 (args_v, ptr_v);
2255 int dispx = Int_val (Field (args_v, 0));
2256 int dispy = Int_val (Field (args_v, 1));
2257 int dispw = Int_val (Field (args_v, 2));
2258 int disph = Int_val (Field (args_v, 3));
2259 int tilex = Int_val (Field (args_v, 4));
2260 int tiley = Int_val (Field (args_v, 5));
2261 char *s = String_val (ptr_v);
2262 struct tile *tile = parse_pointer (__func__, s);
2263 int slicey, firstslice;
2264 struct slice *slice;
2265 GLfloat *texcoords = state.texcoords;
2266 GLfloat *vertices = state.vertices;
2268 firstslice = tiley / tile->sliceheight;
2269 slice = &tile->slices[firstslice];
2270 slicey = tiley % tile->sliceheight;
2272 while (disph > 0) {
2273 int dh;
2275 dh = slice->h - slicey;
2276 dh = fz_mini (disph, dh);
2277 uploadslice (tile, slice);
2279 texcoords[0] = tilex; texcoords[1] = slicey;
2280 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2281 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2282 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2284 vertices[0] = dispx; vertices[1] = dispy;
2285 vertices[2] = dispx+dispw; vertices[3] = dispy;
2286 vertices[4] = dispx; vertices[5] = dispy+dh;
2287 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2289 #if TEXT_TYPE == GL_TEXTURE_2D
2290 for (int i = 0; i < 8; ++i) {
2291 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2293 #endif
2295 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2296 dispy += dh;
2297 disph -= dh;
2298 slice++;
2299 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2300 slicey = 0;
2302 CAMLreturn0;
2305 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2307 fz_matrix ctm, tm, pm;
2308 fz_point p1, p2, p3, p4;
2309 GLfloat *vertices = state.vertices;
2310 double *v = (double *) rects_v;
2312 xoff -= state.pagedims[page->pdimno].bounds.x0;
2313 yoff -= state.pagedims[page->pdimno].bounds.y0;
2314 fz_translate (&tm, xoff, yoff);
2315 pm = pagectm (page);
2316 fz_concat (&ctm, &pm, &tm);
2318 glEnable (GL_BLEND);
2319 glVertexPointer (2, GL_FLOAT, 0, vertices);
2321 glColor4dv (v);
2322 p1.x = (float) v[4];
2323 p1.y = (float) v[5];
2325 p2.x = (float) v[6];
2326 p2.y = (float) v[5];
2328 p3.x = (float) v[6];
2329 p3.y = (float) v[7];
2331 p4.x = (float) v[4];
2332 p4.y = (float) v[7];
2333 solidrect (&ctm, &p1, &p2, &p3, &p4, vertices);
2334 glDisable (GL_BLEND);
2337 CAMLprim value ml_postprocess (value ptr_v, value hlinks_v,
2338 value xoff_v, value yoff_v,
2339 value li_v)
2341 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2342 int xoff = Int_val (xoff_v);
2343 int yoff = Int_val (yoff_v);
2344 int noff = Int_val (Field (li_v, 0));
2345 char *targ = String_val (Field (li_v, 1));
2346 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2347 int hfsize = Int_val (Field (li_v, 2));
2348 char *s = String_val (ptr_v);
2349 int hlmask = Int_val (hlinks_v);
2350 struct page *page = parse_pointer (__func__, s);
2352 if (!page->fzpage) {
2353 /* deal with loadpage failed pages */
2354 goto done;
2357 if (trylock (__func__)) {
2358 noff = -1;
2359 goto done;
2362 ensureannots (page);
2363 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2364 if (hlmask & 2) {
2365 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2366 noff = page->slinkcount;
2368 if (page->tgen == state.gen) {
2369 showsel (page, xoff, yoff);
2371 unlock (__func__);
2373 done:
2374 CAMLreturn (Val_int (noff));
2377 CAMLprim void ml_drawprect (value ptr_v, value xoff_v, value yoff_v,
2378 value rects_v)
2380 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2381 int xoff = Int_val (xoff_v);
2382 int yoff = Int_val (yoff_v);
2383 char *s = String_val (ptr_v);
2384 struct page *page = parse_pointer (__func__, s);
2386 drawprect (page, xoff, yoff, rects_v);
2387 CAMLreturn0;
2390 static struct annot *getannot (struct page *page, int x, int y)
2392 fz_point p;
2393 fz_matrix ctm;
2394 const fz_matrix *tctm;
2395 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2397 if (!page->annots) return NULL;
2399 if (pdf) {
2400 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2401 tctm = &state.pagedims[page->pdimno].tctm;
2403 else {
2404 tctm = &fz_identity;
2407 p.x = x;
2408 p.y = y;
2410 fz_concat (&ctm, tctm, &state.pagedims[page->pdimno].ctm);
2411 fz_invert_matrix (&ctm, &ctm);
2412 fz_transform_point (&p, &ctm);
2414 if (pdf) {
2415 for (int i = 0; i < page->annotcount; ++i) {
2416 struct annot *a = &page->annots[i];
2417 fz_rect rect;
2419 fz_bound_annot (state.ctx, a->annot, &rect);
2420 if (p.x >= rect.x0 && p.x <= rect.x1) {
2421 if (p.y >= rect.y0 && p.y <= rect.y1)
2422 return a;
2426 return NULL;
2429 static fz_link *getlink (struct page *page, int x, int y)
2431 fz_point p;
2432 fz_matrix ctm;
2433 fz_link *link;
2435 ensureslinks (page);
2437 p.x = x;
2438 p.y = y;
2440 ctm = pagectm (page);
2441 fz_invert_matrix (&ctm, &ctm);
2442 fz_transform_point (&p, &ctm);
2444 for (link = page->links; link; link = link->next) {
2445 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2446 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2447 return link;
2451 return NULL;
2454 static void ensuretext (struct page *page)
2456 if (state.gen != page->tgen) {
2457 droptext (page);
2458 page->tgen = state.gen;
2460 if (!page->text) {
2461 fz_matrix ctm;
2462 fz_device *tdev;
2464 page->text = fz_new_stext_page (state.ctx,
2465 &state.pagedims[page->pdimno].mediabox);
2466 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2467 ctm = pagectm (page);
2468 fz_run_display_list (state.ctx, page->dlist,
2469 tdev, &ctm, &fz_infinite_rect, NULL);
2470 fz_close_device (state.ctx, tdev);
2471 fz_drop_device (state.ctx, tdev);
2475 CAMLprim value ml_find_page_with_links (value start_page_v, value dir_v)
2477 CAMLparam2 (start_page_v, dir_v);
2478 CAMLlocal1 (ret_v);
2479 int i, dir = Int_val (dir_v);
2480 int start_page = Int_val (start_page_v);
2481 int end_page = dir > 0 ? state.pagecount : -1;
2482 pdf_document *pdf;
2484 fz_var (end_page);
2485 ret_v = Val_int (0);
2486 lock (__func__);
2487 pdf = pdf_specifics (state.ctx, state.doc);
2488 for (i = start_page + dir; i != end_page; i += dir) {
2489 int found;
2491 fz_var (found);
2492 if (pdf) {
2493 pdf_page *page = NULL;
2495 fz_var (page);
2496 fz_try (state.ctx) {
2497 page = pdf_load_page (state.ctx, pdf, i);
2498 found = !!page->links || !!page->annots;
2500 fz_catch (state.ctx) {
2501 found = 0;
2503 if (page) {
2504 fz_drop_page (state.ctx, &page->super);
2507 else {
2508 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2509 fz_link *link = fz_load_links (state.ctx, page);
2510 found = !!link;
2511 fz_drop_link (state.ctx, link);
2512 fz_drop_page (state.ctx, page);
2515 if (found) {
2516 ret_v = caml_alloc_small (1, 1);
2517 Field (ret_v, 0) = Val_int (i);
2518 goto unlock;
2521 unlock:
2522 unlock (__func__);
2523 CAMLreturn (ret_v);
2526 enum { dir_first, dir_last };
2527 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2529 CAMLprim value ml_findlink (value ptr_v, value dir_v)
2531 CAMLparam2 (ptr_v, dir_v);
2532 CAMLlocal2 (ret_v, pos_v);
2533 struct page *page;
2534 int dirtag, i, slinkindex;
2535 struct slink *found = NULL ,*slink;
2536 char *s = String_val (ptr_v);
2538 page = parse_pointer (__func__, s);
2539 ret_v = Val_int (0);
2540 lock (__func__);
2541 ensureslinks (page);
2543 if (Is_block (dir_v)) {
2544 dirtag = Tag_val (dir_v);
2545 switch (dirtag) {
2546 case dir_first_visible:
2548 int x0, y0, dir, first_index, last_index;
2550 pos_v = Field (dir_v, 0);
2551 x0 = Int_val (Field (pos_v, 0));
2552 y0 = Int_val (Field (pos_v, 1));
2553 dir = Int_val (Field (pos_v, 2));
2555 if (dir >= 0) {
2556 dir = 1;
2557 first_index = 0;
2558 last_index = page->slinkcount;
2560 else {
2561 first_index = page->slinkcount - 1;
2562 last_index = -1;
2565 for (i = first_index; i != last_index; i += dir) {
2566 slink = &page->slinks[i];
2567 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2568 found = slink;
2569 break;
2573 break;
2575 case dir_left:
2576 slinkindex = Int_val (Field (dir_v, 0));
2577 found = &page->slinks[slinkindex];
2578 for (i = slinkindex - 1; i >= 0; --i) {
2579 slink = &page->slinks[i];
2580 if (slink->bbox.x0 < found->bbox.x0) {
2581 found = slink;
2582 break;
2585 break;
2587 case dir_right:
2588 slinkindex = Int_val (Field (dir_v, 0));
2589 found = &page->slinks[slinkindex];
2590 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2591 slink = &page->slinks[i];
2592 if (slink->bbox.x0 > found->bbox.x0) {
2593 found = slink;
2594 break;
2597 break;
2599 case dir_down:
2600 slinkindex = Int_val (Field (dir_v, 0));
2601 found = &page->slinks[slinkindex];
2602 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2603 slink = &page->slinks[i];
2604 if (slink->bbox.y0 >= found->bbox.y0) {
2605 found = slink;
2606 break;
2609 break;
2611 case dir_up:
2612 slinkindex = Int_val (Field (dir_v, 0));
2613 found = &page->slinks[slinkindex];
2614 for (i = slinkindex - 1; i >= 0; --i) {
2615 slink = &page->slinks[i];
2616 if (slink->bbox.y0 <= found->bbox.y0) {
2617 found = slink;
2618 break;
2621 break;
2624 else {
2625 dirtag = Int_val (dir_v);
2626 switch (dirtag) {
2627 case dir_first:
2628 found = page->slinks;
2629 break;
2631 case dir_last:
2632 if (page->slinks) {
2633 found = page->slinks + (page->slinkcount - 1);
2635 break;
2638 if (found) {
2639 ret_v = caml_alloc_small (2, 1);
2640 Field (ret_v, 0) = Val_int (found - page->slinks);
2643 unlock (__func__);
2644 CAMLreturn (ret_v);
2647 enum { uuri, utext, uannot };
2649 CAMLprim value ml_getlink (value ptr_v, value n_v)
2651 CAMLparam2 (ptr_v, n_v);
2652 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2653 fz_link *link;
2654 struct page *page;
2655 char *s = String_val (ptr_v);
2656 struct slink *slink;
2658 ret_v = Val_int (0);
2659 page = parse_pointer (__func__, s);
2661 lock (__func__);
2662 ensureslinks (page);
2663 slink = &page->slinks[Int_val (n_v)];
2664 if (slink->tag == SLINK) {
2665 link = slink->u.link;
2666 str_v = caml_copy_string (link->uri);
2667 ret_v = caml_alloc_small (1, uuri);
2668 Field (ret_v, 0) = str_v;
2670 else {
2671 ret_v = caml_alloc_small (1, uannot);
2672 tup_v = caml_alloc_tuple (2);
2673 Field (ret_v, 0) = tup_v;
2674 Field (tup_v, 0) = ptr_v;
2675 Field (tup_v, 1) = n_v;
2677 unlock (__func__);
2679 CAMLreturn (ret_v);
2682 CAMLprim value ml_getannotcontents (value ptr_v, value n_v)
2684 CAMLparam2 (ptr_v, n_v);
2685 CAMLlocal1 (ret_v);
2686 pdf_document *pdf;
2687 const char *contents = "";
2689 lock (__func__);
2690 pdf = pdf_specifics (state.ctx, state.doc);
2691 if (pdf) {
2692 char *s = String_val (ptr_v);
2693 struct page *page;
2694 struct slink *slink;
2696 page = parse_pointer (__func__, s);
2697 slink = &page->slinks[Int_val (n_v)];
2698 contents = pdf_get_annot_contents (state.ctx,
2699 (pdf_annot *) slink->u.annot);
2701 unlock (__func__);
2702 ret_v = caml_copy_string (contents);
2703 CAMLreturn (ret_v);
2706 CAMLprim value ml_getlinkcount (value ptr_v)
2708 CAMLparam1 (ptr_v);
2709 struct page *page;
2710 char *s = String_val (ptr_v);
2712 page = parse_pointer (__func__, s);
2713 CAMLreturn (Val_int (page->slinkcount));
2716 CAMLprim value ml_getlinkrect (value ptr_v, value n_v)
2718 CAMLparam2 (ptr_v, n_v);
2719 CAMLlocal1 (ret_v);
2720 struct page *page;
2721 struct slink *slink;
2722 char *s = String_val (ptr_v);
2724 page = parse_pointer (__func__, s);
2725 ret_v = caml_alloc_tuple (4);
2726 lock (__func__);
2727 ensureslinks (page);
2729 slink = &page->slinks[Int_val (n_v)];
2730 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2731 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2732 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2733 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2734 unlock (__func__);
2735 CAMLreturn (ret_v);
2738 CAMLprim value ml_whatsunder (value ptr_v, value x_v, value y_v)
2740 CAMLparam3 (ptr_v, x_v, y_v);
2741 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2742 fz_link *link;
2743 struct annot *annot;
2744 struct page *page;
2745 char *ptr = String_val (ptr_v);
2746 int x = Int_val (x_v), y = Int_val (y_v);
2747 struct pagedim *pdim;
2749 ret_v = Val_int (0);
2750 if (trylock (__func__)) {
2751 goto done;
2754 page = parse_pointer (__func__, ptr);
2755 pdim = &state.pagedims[page->pdimno];
2756 x += pdim->bounds.x0;
2757 y += pdim->bounds.y0;
2760 annot = getannot (page, x, y);
2761 if (annot) {
2762 int i, n = -1;
2764 ensureslinks (page);
2765 for (i = 0; i < page->slinkcount; ++i) {
2766 if (page->slinks[i].tag == SANNOT
2767 && page->slinks[i].u.annot == annot->annot) {
2768 n = i;
2769 break;
2772 ret_v = caml_alloc_small (1, uannot);
2773 tup_v = caml_alloc_tuple (2);
2774 Field (ret_v, 0) = tup_v;
2775 Field (tup_v, 0) = ptr_v;
2776 Field (tup_v, 1) = Val_int (n);
2777 goto unlock;
2781 link = getlink (page, x, y);
2782 if (link) {
2783 str_v = caml_copy_string (link->uri);
2784 ret_v = caml_alloc_small (1, uuri);
2785 Field (ret_v, 0) = str_v;
2787 else {
2788 fz_rect *b;
2789 fz_stext_block *block;
2791 ensuretext (page);
2793 for (block = page->text->first_block; block; block = block->next) {
2794 fz_stext_line *line;
2796 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2797 b = &block->bbox;
2798 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2799 continue;
2801 for (line = block->u.t.first_line; line; line = line->next) {
2802 fz_stext_char *ch;
2804 b = &line->bbox;
2805 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2806 continue;
2808 for (ch = line->first_char; ch; ch = ch->next) {
2809 fz_quad *q = &ch->quad;
2811 if (x >= q->ul.x && x <= q->ur.x
2812 && y >= q->ul.y && y <= q->ll.y) {
2813 const char *n2 = fz_font_name (state.ctx, ch->font);
2814 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2815 ch->font);
2817 if (!n2) n2 = "<unknown font>";
2819 if (face && face->family_name) {
2820 char *s;
2821 char *n1 = face->family_name;
2822 size_t l1 = strlen (n1);
2823 size_t l2 = strlen (n2);
2825 if (l1 != l2 || memcmp (n1, n2, l1)) {
2826 s = malloc (l1 + l2 + 2);
2827 if (s) {
2828 memcpy (s, n2, l2);
2829 s[l2] = '=';
2830 memcpy (s + l2 + 1, n1, l1 + 1);
2831 str_v = caml_copy_string (s);
2832 free (s);
2836 if (str_v == Val_unit) {
2837 str_v = caml_copy_string (n2);
2839 ret_v = caml_alloc_small (1, utext);
2840 Field (ret_v, 0) = str_v;
2841 goto unlock;
2847 unlock:
2848 unlock (__func__);
2850 done:
2851 CAMLreturn (ret_v);
2854 enum { mark_page, mark_block, mark_line, mark_word };
2856 CAMLprim void ml_clearmark (value ptr_v)
2858 CAMLparam1 (ptr_v);
2859 char *s = String_val (ptr_v);
2860 struct page *page;
2862 if (trylock (__func__)) {
2863 goto done;
2866 page = parse_pointer (__func__, s);
2867 page->fmark = NULL;
2868 page->lmark = NULL;
2870 unlock (__func__);
2871 done:
2872 CAMLreturn0;
2875 static int uninteresting (int c)
2877 return isspace (c) || ispunct (c);
2880 CAMLprim value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2882 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2883 CAMLlocal1 (ret_v);
2884 fz_rect *b;
2885 struct page *page;
2886 fz_stext_line *line;
2887 fz_stext_block *block;
2888 struct pagedim *pdim;
2889 int mark = Int_val (mark_v);
2890 char *s = String_val (ptr_v);
2891 int x = Int_val (x_v), y = Int_val (y_v);
2893 ret_v = Val_bool (0);
2894 if (trylock (__func__)) {
2895 goto done;
2898 page = parse_pointer (__func__, s);
2899 pdim = &state.pagedims[page->pdimno];
2901 ensuretext (page);
2903 if (mark == mark_page) {
2904 page->fmark = page->text->first_block->u.t.first_line->first_char;
2905 page->lmark = page->text->last_block->u.t.last_line->last_char;
2906 ret_v = Val_bool (1);
2907 goto unlock;
2910 x += pdim->bounds.x0;
2911 y += pdim->bounds.y0;
2913 for (block = page->text->first_block; block; block = block->next) {
2914 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2915 b = &block->bbox;
2916 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2917 continue;
2919 if (mark == mark_block) {
2920 page->fmark = block->u.t.first_line->first_char;
2921 page->lmark = block->u.t.last_line->last_char;
2922 ret_v = Val_bool (1);
2923 goto unlock;
2926 for (line = block->u.t.first_line; line; line = line->next) {
2927 fz_stext_char *ch;
2929 b = &line->bbox;
2930 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2931 continue;
2933 if (mark == mark_line) {
2934 page->fmark = line->first_char;
2935 page->lmark = line->last_char;
2936 ret_v = Val_bool (1);
2937 goto unlock;
2940 for (ch = line->first_char; ch; ch = ch->next) {
2941 fz_stext_char *ch2, *first = NULL, *last = NULL;
2942 fz_quad *q = &ch->quad;
2943 if (x >= q->ul.x && x <= q->ur.x
2944 && y >= q->ul.y && y <= q->ll.y) {
2945 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2946 if (uninteresting (ch2->c)) first = NULL;
2947 else if (!first) first = ch2;
2949 for (ch2 = ch; ch2; ch2 = ch2->next) {
2950 if (uninteresting (ch2->c)) break;
2951 last = ch2;
2954 page->fmark = first;
2955 page->lmark = last;
2956 ret_v = Val_bool (1);
2957 goto unlock;
2962 unlock:
2963 if (!Bool_val (ret_v)) {
2964 page->fmark = NULL;
2965 page->lmark = NULL;
2967 unlock (__func__);
2969 done:
2970 CAMLreturn (ret_v);
2973 CAMLprim value ml_rectofblock (value ptr_v, value x_v, value y_v)
2975 CAMLparam3 (ptr_v, x_v, y_v);
2976 CAMLlocal2 (ret_v, res_v);
2977 fz_rect *b = NULL;
2978 struct page *page;
2979 struct pagedim *pdim;
2980 fz_stext_block *block;
2981 char *s = String_val (ptr_v);
2982 int x = Int_val (x_v), y = Int_val (y_v);
2984 ret_v = Val_int (0);
2985 if (trylock (__func__)) {
2986 goto done;
2989 page = parse_pointer (__func__, s);
2990 pdim = &state.pagedims[page->pdimno];
2991 x += pdim->bounds.x0;
2992 y += pdim->bounds.y0;
2994 ensuretext (page);
2996 for (block = page->text->first_block; block; block = block->next) {
2997 switch (block->type) {
2998 case FZ_STEXT_BLOCK_TEXT:
2999 b = &block->bbox;
3000 break;
3002 case FZ_STEXT_BLOCK_IMAGE:
3003 b = &block->bbox;
3004 break;
3006 default:
3007 continue;
3010 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
3011 break;
3012 b = NULL;
3014 if (b) {
3015 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3016 ret_v = caml_alloc_small (1, 1);
3017 Store_double_field (res_v, 0, (double) b->x0);
3018 Store_double_field (res_v, 1, (double) b->x1);
3019 Store_double_field (res_v, 2, (double) b->y0);
3020 Store_double_field (res_v, 3, (double) b->y1);
3021 Field (ret_v, 0) = res_v;
3023 unlock (__func__);
3025 done:
3026 CAMLreturn (ret_v);
3029 CAMLprim void ml_seltext (value ptr_v, value rect_v)
3031 CAMLparam2 (ptr_v, rect_v);
3032 struct page *page;
3033 struct pagedim *pdim;
3034 char *s = String_val (ptr_v);
3035 int x0, x1, y0, y1;
3036 fz_stext_char *ch;
3037 fz_stext_line *line;
3038 fz_stext_block *block;
3039 fz_stext_char *fc, *lc;
3041 if (trylock (__func__)) {
3042 goto done;
3045 page = parse_pointer (__func__, s);
3046 ensuretext (page);
3048 pdim = &state.pagedims[page->pdimno];
3049 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
3050 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
3051 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
3052 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
3054 if (y0 > y1) {
3055 int t = y0;
3056 y0 = y1;
3057 y1 = t;
3058 x0 = x1;
3059 x1 = t;
3062 fc = page->fmark;
3063 lc = page->lmark;
3065 for (block = page->text->first_block; block; block = block->next) {
3066 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3067 for (line = block->u.t.first_line; line; line = line->next) {
3068 for (ch = line->first_char; ch; ch = ch->next) {
3069 fz_quad q = ch->quad;
3070 if (x0 >= q.ul.x && x0 <= q.ur.x
3071 && y0 >= q.ul.y && y0 <= q.ll.y) {
3072 fc = ch;
3074 if (x1 >= q.ul.x && x1 <= q.ur.x
3075 && y1 >= q.ul.y && y1 <= q.ll.y) {
3076 lc = ch;
3081 if (x1 < x0 && fc == lc) {
3082 fz_stext_char *t;
3084 t = fc;
3085 fc = lc;
3086 lc = t;
3089 page->fmark = fc;
3090 page->lmark = lc;
3092 unlock (__func__);
3094 done:
3095 CAMLreturn0;
3098 static int pipechar (FILE *f, fz_stext_char *ch)
3100 char buf[4];
3101 int len;
3102 size_t ret;
3104 len = fz_runetochar (buf, ch->c);
3105 ret = fwrite (buf, len, 1, f);
3106 if (ret != 1) {
3107 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3108 len, ret, errno, strerror (errno));
3109 return -1;
3111 return 0;
3114 CAMLprim value ml_spawn (value command_v, value fds_v)
3116 CAMLparam2 (command_v, fds_v);
3117 CAMLlocal2 (l_v, tup_v);
3118 int ret, ret1;
3119 pid_t pid = (pid_t) -1;
3120 char *msg = NULL;
3121 value earg_v = Nothing;
3122 posix_spawnattr_t attr;
3123 posix_spawn_file_actions_t fa;
3124 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3126 argv[2] = String_val (command_v);
3128 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3129 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3132 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3133 msg = "posix_spawnattr_init";
3134 goto fail1;
3137 #ifdef POSIX_SPAWN_USEVFORK
3138 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3139 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3140 goto fail;
3142 #endif
3144 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3145 int fd1, fd2;
3147 tup_v = Field (l_v, 0);
3148 fd1 = Int_val (Field (tup_v, 0));
3149 fd2 = Int_val (Field (tup_v, 1));
3150 if (fd2 < 0) {
3151 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3152 msg = "posix_spawn_file_actions_addclose";
3153 earg_v = tup_v;
3154 goto fail;
3157 else {
3158 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3159 msg = "posix_spawn_file_actions_adddup2";
3160 earg_v = tup_v;
3161 goto fail;
3166 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3167 msg = "posix_spawn";
3168 goto fail;
3171 fail:
3172 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3173 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3176 fail1:
3177 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3178 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3179 ret1, strerror (ret1));
3182 if (msg)
3183 unix_error (ret, msg, earg_v);
3185 CAMLreturn (Val_int (pid));
3188 CAMLprim value ml_hassel (value ptr_v)
3190 CAMLparam1 (ptr_v);
3191 CAMLlocal1 (ret_v);
3192 struct page *page;
3193 char *s = String_val (ptr_v);
3195 ret_v = Val_bool (0);
3196 if (trylock (__func__)) {
3197 goto done;
3200 page = parse_pointer (__func__, s);
3201 ret_v = Val_bool (page->fmark && page->lmark);
3202 unlock (__func__);
3203 done:
3204 CAMLreturn (ret_v);
3207 CAMLprim void ml_copysel (value fd_v, value ptr_v)
3209 CAMLparam2 (fd_v, ptr_v);
3210 FILE *f;
3211 int seen = 0;
3212 struct page *page;
3213 fz_stext_line *line;
3214 fz_stext_block *block;
3215 int fd = Int_val (fd_v);
3216 char *s = String_val (ptr_v);
3218 if (trylock (__func__)) {
3219 goto done;
3222 page = parse_pointer (__func__, s);
3224 if (!page->fmark || !page->lmark) {
3225 printd ("emsg nothing to copy on page %d", page->pageno);
3226 goto unlock;
3229 f = fdopen (fd, "w");
3230 if (!f) {
3231 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3232 fd, errno, strerror (errno));
3233 f = stdout;
3236 for (block = page->text->first_block; block; block = block->next) {
3237 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3238 for (line = block->u.t.first_line; line; line = line->next) {
3239 fz_stext_char *ch;
3240 for (ch = line->first_char; ch; ch = ch->next) {
3241 if (seen || ch == page->fmark) {
3242 do {
3243 pipechar (f, ch);
3244 if (ch == page->lmark) goto close;
3245 } while ((ch = ch->next));
3246 seen = 1;
3247 break;
3250 if (seen) fputc ('\n', f);
3253 close:
3254 if (f != stdout) {
3255 int ret = fclose (f);
3256 fd = -1;
3257 if (ret == -1) {
3258 if (errno != ECHILD) {
3259 printd ("emsg failed to close sel pipe: %d:%s",
3260 errno, strerror (errno));
3264 unlock:
3265 unlock (__func__);
3267 done:
3268 if (fd >= 0) {
3269 if (close (fd)) {
3270 printd ("emsg failed to close sel pipe: %d:%s",
3271 errno, strerror (errno));
3274 CAMLreturn0;
3277 CAMLprim value ml_getpdimrect (value pagedimno_v)
3279 CAMLparam1 (pagedimno_v);
3280 CAMLlocal1 (ret_v);
3281 int pagedimno = Int_val (pagedimno_v);
3282 fz_rect box;
3284 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3285 if (trylock (__func__)) {
3286 box = fz_empty_rect;
3288 else {
3289 box = state.pagedims[pagedimno].mediabox;
3290 unlock (__func__);
3293 Store_double_field (ret_v, 0, (double) box.x0);
3294 Store_double_field (ret_v, 1, (double) box.x1);
3295 Store_double_field (ret_v, 2, (double) box.y0);
3296 Store_double_field (ret_v, 3, (double) box.y1);
3298 CAMLreturn (ret_v);
3301 CAMLprim value ml_zoom_for_height (value winw_v, value winh_v,
3302 value dw_v, value cols_v)
3304 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3305 CAMLlocal1 (ret_v);
3306 int i;
3307 float zoom = -1.;
3308 float maxh = 0.0;
3309 struct pagedim *p;
3310 float winw = Int_val (winw_v);
3311 float winh = Int_val (winh_v);
3312 float dw = Int_val (dw_v);
3313 float cols = Int_val (cols_v);
3314 float pw = 1.0, ph = 1.0;
3316 if (trylock (__func__)) {
3317 goto done;
3320 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3321 float w = p->pagebox.x1 / cols;
3322 float h = p->pagebox.y1;
3323 if (h > maxh) {
3324 maxh = h;
3325 ph = h;
3326 if (state.fitmodel != FitProportional) pw = w;
3328 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3331 zoom = (((winh / ph) * pw) + dw) / winw;
3332 unlock (__func__);
3333 done:
3334 ret_v = caml_copy_double ((double) zoom);
3335 CAMLreturn (ret_v);
3338 CAMLprim value ml_getmaxw (value unit_v)
3340 CAMLparam1 (unit_v);
3341 CAMLlocal1 (ret_v);
3342 int i;
3343 float maxw = -1.;
3344 struct pagedim *p;
3346 if (trylock (__func__)) {
3347 goto done;
3350 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3351 float w = p->pagebox.x1;
3352 maxw = fz_max (maxw, w);
3355 unlock (__func__);
3356 done:
3357 ret_v = caml_copy_double ((double) maxw);
3358 CAMLreturn (ret_v);
3361 CAMLprim value ml_draw_string (value pt_v, value x_v, value y_v, value string_v)
3363 CAMLparam4 (pt_v, x_v, y_v, string_v);
3364 CAMLlocal1 (ret_v);
3365 int pt = Int_val(pt_v);
3366 int x = Int_val (x_v);
3367 int y = Int_val (y_v);
3368 double w;
3370 w = (double) draw_string (state.face, pt, x, y, String_val (string_v));
3371 ret_v = caml_copy_double (w);
3372 CAMLreturn (ret_v);
3375 CAMLprim value ml_measure_string (value pt_v, value string_v)
3377 CAMLparam2 (pt_v, string_v);
3378 CAMLlocal1 (ret_v);
3379 int pt = Int_val (pt_v);
3380 double w;
3382 w = (double) measure_string (state.face, pt, String_val (string_v));
3383 ret_v = caml_copy_double (w);
3384 CAMLreturn (ret_v);
3387 CAMLprim value ml_getpagebox (value opaque_v)
3389 CAMLparam1 (opaque_v);
3390 CAMLlocal1 (ret_v);
3391 fz_rect rect;
3392 fz_irect bbox;
3393 fz_matrix ctm;
3394 fz_device *dev;
3395 char *s = String_val (opaque_v);
3396 struct page *page = parse_pointer (__func__, s);
3398 ret_v = caml_alloc_tuple (4);
3399 dev = fz_new_bbox_device (state.ctx, &rect);
3401 ctm = pagectm (page);
3402 fz_run_page (state.ctx, page->fzpage, dev, &ctm, NULL);
3404 fz_close_device (state.ctx, dev);
3405 fz_drop_device (state.ctx, dev);
3406 fz_round_rect (&bbox, &rect);
3407 Field (ret_v, 0) = Val_int (bbox.x0);
3408 Field (ret_v, 1) = Val_int (bbox.y0);
3409 Field (ret_v, 2) = Val_int (bbox.x1);
3410 Field (ret_v, 3) = Val_int (bbox.y1);
3412 CAMLreturn (ret_v);
3415 CAMLprim void ml_setaalevel (value level_v)
3417 CAMLparam1 (level_v);
3419 state.aalevel = Int_val (level_v);
3420 CAMLreturn0;
3423 #ifndef CIDER
3424 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3426 CAMLparam1 (keysym_v);
3427 CAMLlocal1 (str_v);
3428 KeySym keysym = Int_val (keysym_v);
3429 Rune rune;
3430 extern long keysym2ucs (KeySym);
3431 int len;
3432 char buf[5];
3434 rune = (Rune) keysym2ucs (keysym);
3435 len = fz_runetochar (buf, rune);
3436 buf[len] = 0;
3437 str_v = caml_copy_string (buf);
3438 CAMLreturn (str_v);
3440 #else
3441 CAMLprim value ml_keysymtoutf8 (value keysym_v)
3443 CAMLparam1 (keysym_v);
3444 CAMLlocal1 (str_v);
3445 long ucs_v = Long_val (keysym_v);
3446 int len;
3447 char buf[5];
3449 len = fz_runetochar (buf, (int) ucs_v);
3450 buf[len] = 0;
3451 str_v = caml_copy_string (buf);
3452 CAMLreturn (str_v);
3454 #endif
3456 enum { piunknown, pilinux, pimacos, pibsd };
3458 CAMLprim value ml_platform (value unit_v)
3460 CAMLparam1 (unit_v);
3461 CAMLlocal2 (tup_v, arr_v);
3462 int platid = piunknown;
3463 struct utsname buf;
3465 #if defined __linux__
3466 platid = pilinux;
3467 #elif defined __DragonFly__ || defined __FreeBSD__
3468 || defined __OpenBSD__ || defined __NetBSD__
3469 platid = pibsd;
3470 #elif defined __APPLE__
3471 platid = pimacos;
3472 #endif
3473 if (uname (&buf)) err (1, "uname");
3475 tup_v = caml_alloc_tuple (2);
3477 char const *sar[] = {
3478 buf.sysname,
3479 buf.release,
3480 buf.version,
3481 buf.machine,
3482 NULL
3484 arr_v = caml_copy_string_array (sar);
3486 Field (tup_v, 0) = Val_int (platid);
3487 Field (tup_v, 1) = arr_v;
3488 CAMLreturn (tup_v);
3491 CAMLprim void ml_cloexec (value fd_v)
3493 CAMLparam1 (fd_v);
3494 int fd = Int_val (fd_v);
3496 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3497 uerror ("fcntl", Nothing);
3499 CAMLreturn0;
3502 CAMLprim value ml_getpbo (value w_v, value h_v, value cs_v)
3504 CAMLparam2 (w_v, h_v);
3505 CAMLlocal1 (ret_v);
3506 struct bo *pbo;
3507 int w = Int_val (w_v);
3508 int h = Int_val (h_v);
3509 int cs = Int_val (cs_v);
3511 if (state.bo_usable) {
3512 pbo = calloc (sizeof (*pbo), 1);
3513 if (!pbo) {
3514 err (1, "calloc pbo");
3517 switch (cs) {
3518 case 0:
3519 case 1:
3520 pbo->size = w*h*4;
3521 break;
3522 case 2:
3523 pbo->size = w*h*2;
3524 break;
3525 default:
3526 errx (1, "%s: invalid colorspace %d", __func__, cs);
3529 state.glGenBuffersARB (1, &pbo->id);
3530 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3531 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3532 NULL, GL_STREAM_DRAW);
3533 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3534 GL_READ_WRITE);
3535 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3536 if (!pbo->ptr) {
3537 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3538 state.glDeleteBuffersARB (1, &pbo->id);
3539 free (pbo);
3540 ret_v = caml_copy_string ("0");
3542 else {
3543 int res;
3544 char *s;
3546 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3547 if (res < 0) {
3548 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3550 s = malloc (res+1);
3551 if (!s) {
3552 err (1, "malloc %d bytes failed", res+1);
3554 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3555 if (res < 0) {
3556 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3558 ret_v = caml_copy_string (s);
3559 free (s);
3562 else {
3563 ret_v = caml_copy_string ("0");
3565 CAMLreturn (ret_v);
3568 CAMLprim void ml_freepbo (value s_v)
3570 CAMLparam1 (s_v);
3571 char *s = String_val (s_v);
3572 struct tile *tile = parse_pointer (__func__, s);
3574 if (tile->pbo) {
3575 state.glDeleteBuffersARB (1, &tile->pbo->id);
3576 tile->pbo->id = -1;
3577 tile->pbo->ptr = NULL;
3578 tile->pbo->size = -1;
3580 CAMLreturn0;
3583 CAMLprim void ml_unmappbo (value s_v)
3585 CAMLparam1 (s_v);
3586 char *s = String_val (s_v);
3587 struct tile *tile = parse_pointer (__func__, s);
3589 if (tile->pbo) {
3590 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3591 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3592 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3594 tile->pbo->ptr = NULL;
3595 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3597 CAMLreturn0;
3600 static void setuppbo (void)
3602 extern void (*wsigladdr (const char *name)) (void);
3603 #pragma GCC diagnostic push
3604 #ifdef __clang__
3605 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3606 #endif
3607 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3608 state.bo_usable = GPA (glBindBufferARB)
3609 && GPA (glUnmapBufferARB)
3610 && GPA (glMapBufferARB)
3611 && GPA (glBufferDataARB)
3612 && GPA (glGenBuffersARB)
3613 && GPA (glDeleteBuffersARB);
3614 #undef GPA
3615 #pragma GCC diagnostic pop
3618 CAMLprim value ml_bo_usable (void)
3620 return Val_bool (state.bo_usable);
3623 CAMLprim value ml_unproject (value ptr_v, value x_v, value y_v)
3625 CAMLparam3 (ptr_v, x_v, y_v);
3626 CAMLlocal2 (ret_v, tup_v);
3627 struct page *page;
3628 char *s = String_val (ptr_v);
3629 int x = Int_val (x_v), y = Int_val (y_v);
3630 struct pagedim *pdim;
3631 fz_point p;
3632 fz_matrix ctm;
3634 page = parse_pointer (__func__, s);
3635 pdim = &state.pagedims[page->pdimno];
3637 ret_v = Val_int (0);
3638 if (trylock (__func__)) {
3639 goto done;
3642 if (pdf_specifics (state.ctx, state.doc)) {
3643 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3644 ctm = state.pagedims[page->pdimno].tctm;
3646 else {
3647 ctm = fz_identity;
3649 p.x = x + pdim->bounds.x0;
3650 p.y = y + pdim->bounds.y0;
3652 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3653 fz_invert_matrix (&ctm, &ctm);
3654 fz_transform_point (&p, &ctm);
3656 tup_v = caml_alloc_tuple (2);
3657 ret_v = caml_alloc_small (1, 1);
3658 Field (tup_v, 0) = Val_int (p.x);
3659 Field (tup_v, 1) = Val_int (p.y);
3660 Field (ret_v, 0) = tup_v;
3662 unlock (__func__);
3663 done:
3664 CAMLreturn (ret_v);
3667 CAMLprim value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3668 value x_v, value y_v)
3670 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3671 CAMLlocal1 (ret_v);
3672 struct page *page;
3673 char *s = String_val (ptr_v);
3674 int pageno = Int_val (pageno_v);
3675 int pdimno = Int_val (pdimno_v);
3676 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3677 struct pagedim *pdim;
3678 fz_point p;
3679 fz_matrix ctm;
3681 ret_v = Val_int (0);
3682 lock (__func__);
3684 if (!*s) {
3685 page = loadpage (pageno, pdimno);
3687 else {
3688 page = parse_pointer (__func__, s);
3690 pdim = &state.pagedims[pdimno];
3692 if (pdf_specifics (state.ctx, state.doc)) {
3693 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3694 ctm = state.pagedims[page->pdimno].tctm;
3696 else {
3697 ctm = fz_identity;
3699 p.x = x + pdim->bounds.x0;
3700 p.y = y + pdim->bounds.y0;
3702 fz_concat (&ctm, &pdim->tctm, &pdim->ctm);
3703 fz_transform_point (&p, &ctm);
3705 ret_v = caml_alloc_tuple (2);
3706 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3707 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3709 if (!*s) {
3710 freepage (page);
3712 unlock (__func__);
3713 CAMLreturn (ret_v);
3716 CAMLprim void ml_addannot (value ptr_v, value x_v, value y_v,
3717 value contents_v)
3719 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3720 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3722 if (pdf) {
3723 pdf_annot *annot;
3724 struct page *page;
3725 fz_point p;
3726 char *s = String_val (ptr_v);
3728 page = parse_pointer (__func__, s);
3729 annot = pdf_create_annot (state.ctx,
3730 pdf_page_from_fz_page (state.ctx,
3731 page->fzpage),
3732 PDF_ANNOT_TEXT);
3733 p.x = Int_val (x_v);
3734 p.y = Int_val (y_v);
3735 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3736 pdf_set_text_annot_position (state.ctx, annot, p);
3737 state.dirty = 1;
3739 CAMLreturn0;
3742 CAMLprim void ml_delannot (value ptr_v, value n_v)
3744 CAMLparam2 (ptr_v, n_v);
3745 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3747 if (pdf) {
3748 struct page *page;
3749 char *s = String_val (ptr_v);
3750 struct slink *slink;
3752 page = parse_pointer (__func__, s);
3753 slink = &page->slinks[Int_val (n_v)];
3754 pdf_delete_annot (state.ctx,
3755 pdf_page_from_fz_page (state.ctx, page->fzpage),
3756 (pdf_annot *) slink->u.annot);
3757 state.dirty = 1;
3759 CAMLreturn0;
3762 CAMLprim void ml_modannot (value ptr_v, value n_v, value str_v)
3764 CAMLparam3 (ptr_v, n_v, str_v);
3765 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3767 if (pdf) {
3768 struct page *page;
3769 char *s = String_val (ptr_v);
3770 struct slink *slink;
3772 page = parse_pointer (__func__, s);
3773 slink = &page->slinks[Int_val (n_v)];
3774 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3775 String_val (str_v));
3776 state.dirty = 1;
3778 CAMLreturn0;
3781 CAMLprim value ml_hasunsavedchanges (void)
3783 return Val_bool (state.dirty);
3786 CAMLprim void ml_savedoc (value path_v)
3788 CAMLparam1 (path_v);
3789 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3791 if (pdf) {
3792 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3794 CAMLreturn0;
3797 static void makestippletex (void)
3799 const char pixels[] = "\xff\xff\0\0";
3800 glGenTextures (1, &state.stid);
3801 glBindTexture (GL_TEXTURE_1D, state.stid);
3802 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3803 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3804 glTexImage1D (
3805 GL_TEXTURE_1D,
3807 GL_ALPHA,
3810 GL_ALPHA,
3811 GL_UNSIGNED_BYTE,
3812 pixels
3816 CAMLprim value ml_fz_version (void)
3818 return caml_copy_string (FZ_VERSION);
3821 CAMLprim value ml_llpp_version (void)
3823 extern char llpp_version[];
3824 return caml_copy_string (llpp_version);
3827 CAMLprim void ml_init (value csock_v, value params_v)
3829 CAMLparam2 (csock_v, params_v);
3830 CAMLlocal2 (trim_v, fuzz_v);
3831 int ret;
3832 int texcount;
3833 char *fontpath;
3834 int colorspace;
3835 int mustoresize;
3837 state.csock = Int_val (csock_v);
3838 state.rotate = Int_val (Field (params_v, 0));
3839 state.fitmodel = Int_val (Field (params_v, 1));
3840 trim_v = Field (params_v, 2);
3841 texcount = Int_val (Field (params_v, 3));
3842 state.sliceheight = Int_val (Field (params_v, 4));
3843 mustoresize = Int_val (Field (params_v, 5));
3844 colorspace = Int_val (Field (params_v, 6));
3845 fontpath = String_val (Field (params_v, 7));
3847 #ifdef CIDER
3848 state.utf8cs = 1;
3849 #else
3850 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3851 if (setlocale (LC_CTYPE, "")) {
3852 const char *cset = nl_langinfo (CODESET);
3853 state.utf8cs = !strcmp (cset, "UTF-8");
3855 else {
3856 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3858 #endif
3860 if (caml_string_length (Field (params_v, 8)) > 0) {
3861 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3863 if (!state.trimcachepath) {
3864 printd ("emsg failed to strdup trimcachepath: %d:%s",
3865 errno, strerror (errno));
3869 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3870 fz_register_document_handlers (state.ctx);
3872 state.trimmargins = Bool_val (Field (trim_v, 0));
3873 fuzz_v = Field (trim_v, 1);
3874 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3875 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3876 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3877 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3879 set_tex_params (colorspace);
3881 if (*fontpath) {
3882 state.face = load_font (fontpath);
3884 else {
3885 int len;
3886 const unsigned char *data;
3888 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3889 state.face = load_builtin_font (data, len);
3891 if (!state.face) _exit (1);
3893 realloctexts (texcount);
3894 setuppbo ();
3895 makestippletex ();
3897 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3898 if (ret) {
3899 errx (1, "pthread_create: %s", strerror (ret));
3902 CAMLreturn0;
3905 #if FIXME || !FIXME
3906 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3907 #endif