Whoops
[llpp.git] / link.c
blob66681c8a04663e86bcd521980bd2cedfccdb6aeb
1 /* lots of code c&p-ed directly from mupdf */
2 #define FIXME 0
4 #ifdef __clang__
5 #pragma GCC diagnostic error "-Weverything"
6 #pragma GCC diagnostic ignored "-Wpadded"
7 #pragma GCC diagnostic ignored "-Wsign-conversion"
8 #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
9 #pragma GCC diagnostic ignored "-Wdocumentation"
10 #pragma GCC diagnostic ignored "-Wdouble-promotion"
11 #endif
13 extern char **environ;
15 #include <errno.h>
16 #include <stdio.h>
17 #include <ctype.h>
18 #include <string.h>
19 #include <stdlib.h>
20 #include <signal.h>
22 #include <math.h>
23 #include <wchar.h>
24 #include <locale.h>
25 #include <langinfo.h>
27 #include <unistd.h>
28 #include <pthread.h>
29 #include <sys/uio.h>
30 #include <sys/time.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/utsname.h>
37 #include <spawn.h>
39 #include <regex.h>
40 #include <stdarg.h>
41 #include <limits.h>
42 #include <inttypes.h>
44 #ifdef CIDER
45 #include <OpenGL/gl.h>
46 #else
47 #include <GL/gl.h>
48 #endif
50 #pragma GCC diagnostic push
51 #ifdef __clang__
52 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
53 #endif
54 #pragma GCC diagnostic ignored "-Wpedantic"
55 #define CAML_NAME_SPACE
56 #include <caml/fail.h>
57 #include <caml/alloc.h>
58 #include <caml/memory.h>
59 #include <caml/unixsupport.h>
61 #pragma GCC diagnostic push
62 #pragma GCC diagnostic ignored "-Wfloat-equal"
63 #include <mupdf/fitz.h>
64 #include <mupdf/pdf.h>
65 #pragma GCC diagnostic pop
67 #include <ft2build.h>
68 #include FT_FREETYPE_H
69 #pragma GCC diagnostic pop
71 #include "cutils.h"
73 #ifdef USE_NPOT
74 #define TEXT_TYPE GL_TEXTURE_2D
75 #else
76 #define TEXT_TYPE GL_TEXTURE_RECTANGLE_ARB
77 #endif
79 #if 0
80 #define lprintf printf
81 #else
82 #define lprintf(...)
83 #endif
85 #define ARSERT(cond) for (;;) { \
86 if (!(cond)) { \
87 errx (1, "%s:%d " #cond, __FILE__, __LINE__); \
88 } \
89 break; \
90 } (void) 0
92 #define ML(d) extern value ml_##d; value ml_##d
93 #define ML0(d) extern void ml_##d; void ml_##d
95 struct slice {
96 int h;
97 int texindex;
100 struct tile {
101 int w, h;
102 int slicecount;
103 int sliceheight;
104 struct bo *pbo;
105 fz_pixmap *pixmap;
106 struct slice slices[1];
109 struct pagedim {
110 int pageno;
111 int rotate;
112 int left;
113 int tctmready;
114 fz_irect bounds;
115 fz_rect pagebox;
116 fz_rect mediabox;
117 fz_matrix ctm, zoomctm, tctm;
120 struct slink {
121 enum { SLINK, SANNOT } tag;
122 fz_irect bbox;
123 union {
124 fz_link *link;
125 pdf_annot *annot;
126 } u;
129 struct annot {
130 fz_irect bbox;
131 pdf_annot *annot;
134 struct page {
135 int tgen;
136 int sgen;
137 int agen;
138 int pageno;
139 int pdimno;
140 fz_stext_page *text;
141 fz_page *fzpage;
142 fz_display_list *dlist;
143 fz_link *links;
144 int slinkcount;
145 struct slink *slinks;
146 int annotcount;
147 struct annot *annots;
148 fz_stext_char *fmark, *lmark;
151 enum { FitWidth, FitProportional, FitPage };
153 static struct {
154 int sliceheight;
155 struct pagedim *pagedims;
156 int pagecount;
157 int pagedimcount;
158 fz_document *doc;
159 fz_context *ctx;
160 int w, h;
162 int texindex;
163 int texcount;
164 GLuint *texids;
166 GLenum texiform;
167 GLenum texform;
168 GLenum texty;
170 fz_colorspace *colorspace;
171 float papercolor[4];
173 struct {
174 int w, h;
175 struct slice *slice;
176 } *texowners;
178 int rotate;
179 int fitmodel;
180 int trimmargins;
181 int needoutline;
182 int gen;
183 int aalevel;
185 int trimanew;
186 fz_irect trimfuzz;
187 fz_pixmap *pig;
189 pthread_t thread;
190 int csock;
191 FT_Face face;
193 char *trimcachepath;
194 int dirty;
196 GLuint stid;
198 int bo_usable;
199 GLuint boid;
201 void (*glBindBufferARB) (GLenum, GLuint);
202 GLboolean (*glUnmapBufferARB) (GLenum);
203 void *(*glMapBufferARB) (GLenum, GLenum);
204 void (*glBufferDataARB) (GLenum, GLsizei, void *, GLenum);
205 void (*glGenBuffersARB) (GLsizei, GLuint *);
206 void (*glDeleteBuffersARB) (GLsizei, GLuint *);
208 GLfloat texcoords[8];
209 GLfloat vertices[16];
211 int utf8cs;
212 } state;
214 struct bo {
215 GLuint id;
216 void *ptr;
217 size_t size;
220 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
222 static void lock (const char *cap)
224 int ret = pthread_mutex_lock (&mutex);
225 if (ret) {
226 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
230 static void unlock (const char *cap)
232 int ret = pthread_mutex_unlock (&mutex);
233 if (ret) {
234 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
238 static int trylock (const char *cap)
240 int ret = pthread_mutex_trylock (&mutex);
241 if (ret && ret != EBUSY) {
242 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
244 return ret == EBUSY;
247 static int hasdata (void)
249 int ret, avail;
250 ret = ioctl (state.csock, FIONREAD, &avail);
251 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
252 return avail > 0;
255 ML (hasdata (value fd_v))
257 CAMLparam1 (fd_v);
258 int ret, avail;
260 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
261 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
262 CAMLreturn (Val_bool (avail > 0));
265 static void readdata (int fd, void *p, int size)
267 ssize_t n;
269 again:
270 n = read (fd, p, size);
271 if (n - size) {
272 if (n < 0 && errno == EINTR) goto again;
273 if (!n) errx (1, "EOF while reading");
274 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
278 static void writedata (int fd, char *p, int size)
280 ssize_t n;
281 uint32_t size4 = size;
282 struct iovec iov[2] = {
283 { .iov_base = &size4, .iov_len = 4 },
284 { .iov_base = p, .iov_len = size }
287 again:
288 n = writev (fd, iov, 2);
289 if (n < 0 && errno == EINTR) goto again;
290 if (n - size - 4) {
291 if (!n) errx (1, "EOF while writing data");
292 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
296 static int readlen (int fd)
298 uint32_t u;
299 readdata (fd, &u, 4);
300 return u;
303 ML0 (wcmd (value fd_v, value bytes_v, value len_v))
305 CAMLparam3 (fd_v, bytes_v, len_v);
306 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
307 CAMLreturn0;
310 ML (rcmd (value fd_v))
312 CAMLparam1 (fd_v);
313 CAMLlocal1 (strdata_v);
314 int fd = Int_val (fd_v);
315 int len = readlen (fd);
316 strdata_v = caml_alloc_string (len);
317 readdata (fd, String_val (strdata_v), len);
318 CAMLreturn (strdata_v);
321 static void GCC_FMT_ATTR (1, 2) printd (const char *fmt, ...)
323 char fbuf[64];
324 int size = sizeof (fbuf), len;
325 va_list ap;
326 char *buf = fbuf;
328 for (;;) {
329 va_start (ap, fmt);
330 len = vsnprintf (buf, size, fmt, ap);
331 va_end (ap);
333 if (len > -1) {
334 if (len < size - 4) {
335 writedata (state.csock, buf, len);
336 break;
338 else size = len + 5;
340 else {
341 err (1, "vsnprintf for `%s' failed", fmt);
343 buf = realloc (buf == fbuf ? NULL : buf, size);
344 if (!buf) err (1, "realloc for temp buf (%d bytes) failed", size);
346 if (buf != fbuf) free (buf);
349 static void closedoc (void)
351 if (state.doc) {
352 fz_drop_document (state.ctx, state.doc);
353 state.doc = NULL;
357 static int openxref (char *filename, char *password, int layouth)
359 for (int i = 0; i < state.texcount; ++i) {
360 state.texowners[i].w = -1;
361 state.texowners[i].slice = NULL;
364 closedoc ();
366 state.dirty = 0;
367 if (state.pagedims) {
368 free (state.pagedims);
369 state.pagedims = NULL;
371 state.pagedimcount = 0;
373 fz_set_aa_level (state.ctx, state.aalevel);
374 state.doc = fz_open_document (state.ctx, filename);
375 if (fz_needs_password (state.ctx, state.doc)) {
376 if (password && !*password) {
377 printd ("pass");
378 return 0;
380 else {
381 int ok = fz_authenticate_password (state.ctx, state.doc, password);
382 if (!ok) {
383 printd ("pass fail");
384 return 0;
388 if (layouth >= 0)
389 fz_layout_document (state.ctx, state.doc, 460, layouth, 12);
390 state.pagecount = fz_count_pages (state.ctx, state.doc);
391 return 1;
394 static void docinfo (void)
396 struct { char *tag; char *name; } metatbl[] = {
397 { FZ_META_INFO_TITLE, "Title" },
398 { FZ_META_INFO_AUTHOR, "Author" },
399 { FZ_META_FORMAT, "Format" },
400 { FZ_META_ENCRYPTION, "Encryption" },
401 { "info:Creator", "Creator" },
402 { "info:Producer", "Producer" },
403 { "info:CreationDate", "Creation date" },
405 int len = 0;
406 char *buf = NULL;
408 for (size_t i = 0; i < sizeof (metatbl) / sizeof (metatbl[1]); ++i) {
409 int need;
410 again:
411 need = fz_lookup_metadata (state.ctx, state.doc,
412 metatbl[i].tag, buf, len);
413 if (need > 0) {
414 if (need <= len) {
415 printd ("info %s\t%s", metatbl[i].name, buf);
417 else {
418 buf = realloc (buf, need + 1);
419 if (!buf) err (1, "docinfo realloc %d", need + 1);
420 len = need + 1;
421 goto again;
425 free (buf);
427 printd ("infoend");
430 static void unlinktile (struct tile *tile)
432 for (int i = 0; i < tile->slicecount; ++i) {
433 struct slice *s = &tile->slices[i];
435 if (s->texindex != -1) {
436 if (state.texowners[s->texindex].slice == s) {
437 state.texowners[s->texindex].slice = NULL;
443 static void freepage (struct page *page)
445 if (!page) return;
446 if (page->text) {
447 fz_drop_stext_page (state.ctx, page->text);
449 if (page->slinks) {
450 free (page->slinks);
452 fz_drop_display_list (state.ctx, page->dlist);
453 fz_drop_page (state.ctx, page->fzpage);
454 free (page);
457 static void freetile (struct tile *tile)
459 unlinktile (tile);
460 if (!tile->pbo) {
461 #if 0
462 fz_drop_pixmap (state.ctx, tile->pixmap);
463 #else /* piggyback */
464 if (state.pig) {
465 fz_drop_pixmap (state.ctx, state.pig);
467 state.pig = tile->pixmap;
468 #endif
470 else {
471 free (tile->pbo);
472 fz_drop_pixmap (state.ctx, tile->pixmap);
474 free (tile);
477 static void trimctm (pdf_page *page, int pindex)
479 struct pagedim *pdim = &state.pagedims[pindex];
481 if (!page) return;
482 if (!pdim->tctmready) {
483 fz_rect realbox, mediabox;
484 fz_matrix page_ctm, ctm;
486 ctm = fz_concat (fz_rotate (-pdim->rotate), fz_scale (1, -1));
487 realbox = fz_transform_rect (pdim->mediabox, ctm);
488 pdf_page_transform (state.ctx, page, &mediabox, &page_ctm);
489 pdim->tctm = fz_concat (
490 fz_invert_matrix (page_ctm),
491 fz_concat (ctm, fz_translate (-realbox.x0, -realbox.y0)));
492 pdim->tctmready = 1;
496 static fz_matrix pagectm1 (fz_page *fzpage, struct pagedim *pdim)
498 fz_matrix ctm;
499 ptrdiff_t pdimno = pdim - state.pagedims;
501 ARSERT (pdim - state.pagedims < INT_MAX);
502 if (pdf_specifics (state.ctx, state.doc)) {
503 trimctm (pdf_page_from_fz_page (state.ctx, fzpage), (int) pdimno);
504 ctm = fz_concat (pdim->tctm, pdim->ctm);
506 else {
507 ctm = fz_concat (fz_translate (-pdim->mediabox.x0, -pdim->mediabox.y0),
508 pdim->ctm);
510 return ctm;
513 static fz_matrix pagectm (struct page *page)
515 return pagectm1 (page->fzpage, &state.pagedims[page->pdimno]);
518 static void *loadpage (int pageno, int pindex)
520 fz_device *dev;
521 struct page *page;
523 page = calloc (sizeof (struct page), 1);
524 if (!page) {
525 err (1, "calloc page %d", pageno);
528 page->dlist = fz_new_display_list (state.ctx, fz_infinite_rect);
529 dev = fz_new_list_device (state.ctx, page->dlist);
530 fz_try (state.ctx) {
531 page->fzpage = fz_load_page (state.ctx, state.doc, pageno);
532 fz_run_page (state.ctx, page->fzpage, dev, fz_identity, NULL);
534 fz_catch (state.ctx) {
535 page->fzpage = NULL;
537 fz_close_device (state.ctx, dev);
538 fz_drop_device (state.ctx, dev);
540 page->pdimno = pindex;
541 page->pageno = pageno;
542 page->sgen = state.gen;
543 page->agen = state.gen;
544 page->tgen = state.gen;
545 return page;
548 static struct tile *alloctile (int h)
550 int slicecount;
551 size_t tilesize;
552 struct tile *tile;
554 slicecount = (h + state.sliceheight - 1) / state.sliceheight;
555 tilesize = sizeof (*tile) + ((slicecount - 1) * sizeof (struct slice));
556 tile = calloc (tilesize, 1);
557 if (!tile) {
558 err (1, "cannot allocate tile (%zu bytes)", tilesize);
560 for (int i = 0; i < slicecount; ++i) {
561 int sh = fz_mini (h, state.sliceheight);
562 tile->slices[i].h = sh;
563 tile->slices[i].texindex = -1;
564 h -= sh;
566 tile->slicecount = slicecount;
567 tile->sliceheight = state.sliceheight;
568 return tile;
571 static struct tile *rendertile (struct page *page, int x, int y, int w, int h,
572 struct bo *pbo)
574 fz_irect bbox;
575 fz_matrix ctm;
576 fz_device *dev;
577 struct tile *tile;
578 struct pagedim *pdim;
580 tile = alloctile (h);
581 pdim = &state.pagedims[page->pdimno];
583 bbox = pdim->bounds;
584 bbox.x0 += x;
585 bbox.y0 += y;
586 bbox.x1 = bbox.x0 + w;
587 bbox.y1 = bbox.y0 + h;
589 if (state.pig) {
590 if (state.pig->w == w
591 && state.pig->h == h
592 && state.pig->colorspace == state.colorspace) {
593 tile->pixmap = state.pig;
594 tile->pixmap->x = bbox.x0;
595 tile->pixmap->y = bbox.y0;
597 else {
598 fz_drop_pixmap (state.ctx, state.pig);
600 state.pig = NULL;
602 if (!tile->pixmap) {
603 if (pbo) {
604 tile->pixmap =
605 fz_new_pixmap_with_bbox_and_data (state.ctx, state.colorspace,
606 bbox, NULL, 1, pbo->ptr);
607 tile->pbo = pbo;
609 else {
610 tile->pixmap =
611 fz_new_pixmap_with_bbox (state.ctx, state.colorspace, bbox,
612 NULL, 1);
616 tile->w = w;
617 tile->h = h;
618 fz_fill_pixmap_with_color (state.ctx, tile->pixmap,
619 fz_device_rgb (state.ctx),
620 state.papercolor,
621 fz_default_color_params);
623 dev = fz_new_draw_device (state.ctx, fz_identity, tile->pixmap);
624 ctm = pagectm (page);
625 fz_run_display_list (state.ctx, page->dlist, dev, ctm,
626 fz_rect_from_irect (bbox), NULL);
627 fz_close_device (state.ctx, dev);
628 fz_drop_device (state.ctx, dev);
630 return tile;
633 static void initpdims (void)
635 FILE *trimf = NULL;
636 int pageno, trim, show;
637 int trimw = 0, cxcount;
638 struct pagedim *p = NULL;
639 fz_context *ctx = state.ctx;
640 fz_rect rootmediabox = fz_empty_rect;
641 pdf_document *pdf = pdf_specifics (ctx, state.doc);
643 fz_var (p);
644 fz_var (trimw);
645 fz_var (trimf);
646 fz_var (cxcount);
648 if (state.trimmargins && state.trimcachepath) {
649 trimf = fopen (state.trimcachepath, "rb");
650 if (!trimf) {
651 trimf = fopen (state.trimcachepath, "wb");
652 trimw = 1;
656 cxcount = state.pagecount;
657 if (pdf) {
658 pdf_obj *obj;
659 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
660 "Root/Pages/MediaBox");
661 rootmediabox = pdf_to_rect (ctx, obj);
662 pdf_load_page_tree (ctx, pdf);
665 for (pageno = 0; pageno < cxcount; ++pageno) {
666 int rotate = 0;
667 fz_rect mediabox = fz_empty_rect;
669 fz_var (rotate);
670 if (pdf) {
671 pdf_obj *pageobj = NULL;
673 fz_var (pageobj);
674 if (pdf->rev_page_map) {
675 for (int i = 0; i < pdf->rev_page_count; ++i) {
676 if (pdf->rev_page_map[i].page == pageno) {
677 pageobj = pdf_get_xref_entry (
678 ctx, pdf, pdf->rev_page_map[i].object
679 )->obj;
680 break;
684 if (!pageobj) {
685 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
688 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
690 if (state.trimmargins) {
691 pdf_obj *obj;
692 pdf_page *page;
694 fz_try (ctx) {
695 page = pdf_load_page (ctx, pdf, pageno);
696 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
697 trim = state.trimanew || !obj;
698 if (trim) {
699 fz_rect rect;
700 fz_device *dev;
701 fz_matrix ctm, page_ctm;
703 dev = fz_new_bbox_device (ctx, &rect);
704 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
705 ctm = fz_invert_matrix (page_ctm);
706 pdf_run_page (ctx, page, dev, fz_identity, NULL);
707 fz_close_device (ctx, dev);
708 fz_drop_device (ctx, dev);
710 rect.x0 += state.trimfuzz.x0;
711 rect.x1 += state.trimfuzz.x1;
712 rect.y0 += state.trimfuzz.y0;
713 rect.y1 += state.trimfuzz.y1;
714 rect = fz_transform_rect (rect, ctm);
715 rect = fz_intersect_rect (rect, mediabox);
717 if (!fz_is_empty_rect (rect)) {
718 mediabox = rect;
721 obj = pdf_new_array (ctx, pdf, 4);
722 pdf_array_push (ctx, obj,
723 pdf_new_real (ctx, mediabox.x0));
724 pdf_array_push (ctx, obj,
725 pdf_new_real (ctx, mediabox.y0));
726 pdf_array_push (ctx, obj,
727 pdf_new_real (ctx, mediabox.x1));
728 pdf_array_push (ctx, obj,
729 pdf_new_real (ctx, mediabox.y1));
730 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
732 else {
733 mediabox.x0 = pdf_to_real (ctx,
734 pdf_array_get (ctx, obj, 0));
735 mediabox.y0 = pdf_to_real (ctx,
736 pdf_array_get (ctx, obj, 1));
737 mediabox.x1 = pdf_to_real (ctx,
738 pdf_array_get (ctx, obj, 2));
739 mediabox.y1 = pdf_to_real (ctx,
740 pdf_array_get (ctx, obj, 3));
743 fz_drop_page (ctx, &page->super);
744 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
745 if (show) {
746 printd ("progress %f Trimming %d",
747 (double) (pageno + 1) / state.pagecount,
748 pageno + 1);
751 fz_catch (ctx) {
752 printd ("emsg failed to load page %d", pageno);
755 else {
756 int empty = 0;
757 fz_rect cropbox;
759 mediabox =
760 pdf_to_rect (ctx, pdf_dict_get_inheritable (
761 ctx,
762 pageobj,
763 PDF_NAME (MediaBox)
766 if (fz_is_empty_rect (mediabox)) {
767 mediabox.x0 = 0;
768 mediabox.y0 = 0;
769 mediabox.x1 = 612;
770 mediabox.y1 = 792;
771 empty = 1;
774 cropbox =
775 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
776 if (!fz_is_empty_rect (cropbox)) {
777 if (empty) {
778 mediabox = cropbox;
780 else {
781 mediabox = fz_intersect_rect (mediabox, cropbox);
784 else {
785 if (empty) {
786 if (fz_is_empty_rect (rootmediabox)) {
787 printd ("emsg cannot find page size for page %d",
788 pageno);
790 else {
791 mediabox = rootmediabox;
797 else {
798 if (state.trimmargins && trimw) {
799 fz_page *page;
801 fz_try (ctx) {
802 page = fz_load_page (ctx, state.doc, pageno);
803 mediabox = fz_bound_page (ctx, page);
804 if (state.trimmargins) {
805 fz_rect rect;
806 fz_device *dev;
808 dev = fz_new_bbox_device (ctx, &rect);
809 fz_run_page (ctx, page, dev, fz_identity, NULL);
810 fz_close_device (ctx, dev);
811 fz_drop_device (ctx, dev);
813 rect.x0 += state.trimfuzz.x0;
814 rect.x1 += state.trimfuzz.x1;
815 rect.y0 += state.trimfuzz.y0;
816 rect.y1 += state.trimfuzz.y1;
817 rect = fz_intersect_rect (rect, mediabox);
819 if (!fz_is_empty_rect (rect)) {
820 mediabox = rect;
823 fz_drop_page (ctx, page);
825 fz_catch (ctx) {
827 if (trimf) {
828 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
829 if (n - 1) {
830 err (1, "fwrite trim mediabox");
834 else {
835 if (trimf) {
836 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
837 if (n - 1) {
838 err (1, "fread trim mediabox %d", pageno);
841 else {
842 fz_page *page;
843 fz_try (ctx) {
844 page = fz_load_page (ctx, state.doc, pageno);
845 mediabox = fz_bound_page (ctx, page);
846 fz_drop_page (ctx, page);
848 show = !state.trimmargins && pageno % 20 == 0;
849 if (show) {
850 printd ("progress %f Gathering dimensions %d",
851 (double) (pageno) / state.pagecount,
852 pageno);
855 fz_catch (ctx) {
856 printd ("emsg failed to load page %d", pageno);
862 if (!p || p->rotate != rotate
863 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
864 size_t size;
866 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
867 state.pagedims = realloc (state.pagedims, size);
868 if (!state.pagedims) {
869 err (1, "realloc pagedims to %zu (%d elems)",
870 size, state.pagedimcount + 1);
873 p = &state.pagedims[state.pagedimcount++];
874 p->rotate = rotate;
875 p->mediabox = mediabox;
876 p->pageno = pageno;
879 state.trimanew = 0;
880 if (trimf) {
881 if (fclose (trimf)) {
882 err (1, "fclose");
887 static void layout (void)
889 int pindex;
890 fz_rect box;
891 fz_matrix ctm;
892 struct pagedim *p = NULL;
893 float zw, w, maxw = 0.0, zoom = 1.0;
895 if (state.pagedimcount == 0) return;
897 switch (state.fitmodel) {
898 case FitProportional:
899 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
900 float x0, x1;
902 p = &state.pagedims[pindex];
903 box = fz_transform_rect (p->mediabox,
904 fz_rotate (p->rotate + state.rotate));
906 x0 = fz_min (box.x0, box.x1);
907 x1 = fz_max (box.x0, box.x1);
909 w = x1 - x0;
910 maxw = fz_max (w, maxw);
911 zoom = state.w / maxw;
913 break;
915 case FitPage:
916 maxw = state.w;
917 break;
919 case FitWidth:
920 break;
922 default:
923 ARSERT (0 && state.fitmodel);
926 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
927 p = &state.pagedims[pindex];
928 ctm = fz_rotate (state.rotate);
929 box = fz_transform_rect (p->mediabox,
930 fz_rotate (p->rotate + state.rotate));
931 w = box.x1 - box.x0;
932 switch (state.fitmodel) {
933 case FitProportional:
934 p->left = (int) (((maxw - w) * zoom) / 2.f);
935 break;
936 case FitPage:
938 float zh, h;
939 zw = maxw / w;
940 h = box.y1 - box.y0;
941 zh = state.h / h;
942 zoom = fz_min (zw, zh);
943 p->left = (int) ((maxw - (w * zoom)) / 2.f);
945 break;
946 case FitWidth:
947 p->left = 0;
948 zoom = state.w / w;
949 break;
952 p->zoomctm = fz_scale (zoom, zoom);
953 ctm = fz_concat (p->zoomctm, ctm);
955 p->pagebox = p->mediabox;
956 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
957 p->pagebox.x1 -= p->pagebox.x0;
958 p->pagebox.y1 -= p->pagebox.y0;
959 p->pagebox.x0 = 0;
960 p->pagebox.y0 = 0;
961 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
962 p->ctm = ctm;
964 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
965 fz_scale (zoom, -zoom));
966 p->tctmready = 0;
969 do {
970 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
971 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
972 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
973 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
974 int boundw = x1 - x0;
975 int boundh = y1 - y0;
977 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
978 } while (p-- != state.pagedims);
981 static struct pagedim *pdimofpageno (int pageno)
983 struct pagedim *pdim = state.pagedims;
985 for (int i = 0; i < state.pagedimcount; ++i) {
986 if (state.pagedims[i].pageno > pageno)
987 break;
988 pdim = &state.pagedims[i];
990 return pdim;
993 static void recurse_outline (fz_outline *outline, int level)
995 while (outline) {
996 if (outline->page >= 0) {
997 fz_point p = {.x = outline->x, .y = outline->y};
998 struct pagedim *pdim = pdimofpageno (outline->page);
999 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
1000 p = fz_transform_point (p, pdim->ctm);
1001 printd ("o %d %d %d %d %s",
1002 level, outline->page, (int) p.y, h, outline->title);
1004 else {
1005 printd ("on %d %s", level, outline->title);
1007 if (outline->down) {
1008 recurse_outline (outline->down, level + 1);
1010 outline = outline->next;
1014 static void process_outline (void)
1016 fz_outline *outline;
1018 if (!state.needoutline || !state.pagedimcount) return;
1020 state.needoutline = 0;
1021 outline = fz_load_outline (state.ctx, state.doc);
1022 if (outline) {
1023 recurse_outline (outline, 0);
1024 fz_drop_outline (state.ctx, outline);
1028 static char *strofline (fz_stext_line *line)
1030 char *p;
1031 char utf8[10];
1032 fz_stext_char *ch;
1033 size_t size = 0, cap = 80;
1035 p = malloc (cap + 1);
1036 if (!p) return NULL;
1038 for (ch = line->first_char; ch; ch = ch->next) {
1039 int n = fz_runetochar (utf8, ch->c);
1040 if (size + n > cap) {
1041 cap *= 2;
1042 p = realloc (p, cap + 1);
1043 if (!p) return NULL;
1046 memcpy (p + size, utf8, n);
1047 size += n;
1049 p[size] = 0;
1050 return p;
1053 static int matchline (regex_t *re, fz_stext_line *line,
1054 int stop, int pageno, double start)
1056 int ret;
1057 char *p;
1058 regmatch_t rm;
1060 p = strofline (line);
1061 if (!p) return -1;
1063 ret = regexec (re, p, 1, &rm, 0);
1064 if (ret) {
1065 free (p);
1066 if (ret != REG_NOMATCH) {
1067 size_t size;
1068 char errbuf[80];
1069 size = regerror (ret, re, errbuf, sizeof (errbuf));
1070 printd ("msg regexec error `%.*s'",
1071 (int) size, errbuf);
1072 return -1;
1074 return 0;
1076 else {
1077 fz_quad s, e;
1078 fz_stext_char *ch;
1079 int o = 0;
1081 for (ch = line->first_char; ch; ch = ch->next) {
1082 o += fz_runelen (ch->c);
1083 if (o > rm.rm_so) {
1084 s = ch->quad;
1085 break;
1088 for (;ch; ch = ch->next) {
1089 o += fz_runelen (ch->c);
1090 if (o > rm.rm_eo) break;
1092 e = ch->quad;
1094 if (!stop) {
1095 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1096 pageno, 1,
1097 s.ul.x, s.ul.y,
1098 e.ur.x, s.ul.y,
1099 e.lr.x, e.lr.y,
1100 s.ul.x, e.lr.y);
1102 printd ("progress 1 found at %d `%.*s' in %f sec",
1103 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1104 now () - start);
1106 else {
1107 printd ("match %d %d %f %f %f %f %f %f %f %f",
1108 pageno, 2,
1109 s.ul.x, s.ul.y,
1110 e.ur.x, s.ul.y,
1111 e.lr.x, e.lr.y,
1112 s.ul.x, e.lr.y);
1114 free (p);
1115 return 1;
1119 /* wishful thinking function */
1120 static void search (regex_t *re, int pageno, int y, int forward)
1122 fz_device *tdev;
1123 fz_stext_page *text;
1124 struct pagedim *pdim;
1125 int stop = 0, niters = 0;
1126 double start, end;
1127 fz_page *page;
1128 fz_stext_block *block;
1130 start = now ();
1131 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1132 if (niters++ == 5) {
1133 niters = 0;
1134 if (hasdata ()) {
1135 printd ("progress 1 attention requested aborting search at %d",
1136 pageno);
1137 stop = 1;
1139 else {
1140 printd ("progress %f searching in page %d",
1141 (double) (pageno + 1) / state.pagecount,
1142 pageno);
1145 pdim = pdimofpageno (pageno);
1146 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1147 tdev = fz_new_stext_device (state.ctx, text, 0);
1149 page = fz_load_page (state.ctx, state.doc, pageno);
1150 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1152 fz_close_device (state.ctx, tdev);
1153 fz_drop_device (state.ctx, tdev);
1155 if (forward) {
1156 for (block = text->first_block; block; block = block->next) {
1157 fz_stext_line *line;
1159 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1160 for (line = block->u.t.first_line; line; line = line->next) {
1161 if (line->bbox.y0 < y + 1) continue;
1163 switch (matchline (re, line, stop, pageno, start)) {
1164 case 0: break;
1165 case 1: stop = 1; break;
1166 case -1: stop = 1; goto endloop;
1171 else {
1172 for (block = text->last_block; block; block = block->prev) {
1173 fz_stext_line *line;
1175 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1176 for (line = block->u.t.last_line; line; line = line->prev) {
1177 if (line->bbox.y0 < y + 1) continue;
1179 switch (matchline (re, line, stop, pageno, start)) {
1180 case 0: break;
1181 case 1: stop = 1; break;
1182 case -1: stop = 1; goto endloop;
1188 if (forward) {
1189 pageno += 1;
1190 y = 0;
1192 else {
1193 pageno -= 1;
1194 y = INT_MAX;
1196 endloop:
1197 fz_drop_stext_page (state.ctx, text);
1198 fz_drop_page (state.ctx, page);
1200 end = now ();
1201 if (!stop) {
1202 printd ("progress 1 no matches %f sec", end - start);
1204 printd ("clearrects");
1207 static void set_tex_params (int colorspace)
1209 switch (colorspace) {
1210 case 0:
1211 state.texiform = GL_RGBA8;
1212 state.texform = GL_RGBA;
1213 state.texty = GL_UNSIGNED_BYTE;
1214 state.colorspace = fz_device_rgb (state.ctx);
1215 break;
1216 case 1:
1217 state.texiform = GL_LUMINANCE_ALPHA;
1218 state.texform = GL_LUMINANCE_ALPHA;
1219 state.texty = GL_UNSIGNED_BYTE;
1220 state.colorspace = fz_device_gray (state.ctx);
1221 break;
1222 default:
1223 errx (1, "invalid colorspce %d", colorspace);
1227 static void realloctexts (int texcount)
1229 size_t size;
1231 if (texcount == state.texcount) return;
1233 if (texcount < state.texcount) {
1234 glDeleteTextures (state.texcount - texcount,
1235 state.texids + texcount);
1238 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1239 state.texids = realloc (state.texids, size);
1240 if (!state.texids) {
1241 err (1, "realloc texs %zu", size);
1244 state.texowners = (void *) (state.texids + texcount);
1245 if (texcount > state.texcount) {
1246 glGenTextures (texcount - state.texcount,
1247 state.texids + state.texcount);
1248 for (int i = state.texcount; i < texcount; ++i) {
1249 state.texowners[i].w = -1;
1250 state.texowners[i].slice = NULL;
1253 state.texcount = texcount;
1254 state.texindex = 0;
1257 static char *mbtoutf8 (char *s)
1259 char *p, *r;
1260 wchar_t *tmp;
1261 size_t i, ret, len;
1263 if (state.utf8cs) {
1264 return s;
1267 len = mbstowcs (NULL, s, strlen (s));
1268 if (len == 0 || len == (size_t) -1) {
1269 if (len)
1270 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1271 return s;
1274 tmp = calloc (len, sizeof (wchar_t));
1275 if (!tmp) {
1276 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1277 len, sizeof (wchar_t), errno, strerror (errno));
1278 return s;
1281 ret = mbstowcs (tmp, s, len);
1282 if (ret == (size_t) -1) {
1283 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1284 len, errno, strerror (errno));
1285 free (tmp);
1286 return s;
1289 len = 0;
1290 for (i = 0; i < ret; ++i) {
1291 len += fz_runelen (tmp[i]);
1294 p = r = malloc (len + 1);
1295 if (!r) {
1296 printd ("emsg mbtoutf8: malloc(%zu)", len);
1297 free (tmp);
1298 return s;
1301 for (i = 0; i < ret; ++i) {
1302 p += fz_runetochar (p, tmp[i]);
1304 *p = 0;
1305 free (tmp);
1306 return r;
1309 ML (mbtoutf8 (value s_v))
1311 CAMLparam1 (s_v);
1312 CAMLlocal1 (ret_v);
1313 char *s, *r;
1315 s = String_val (s_v);
1316 r = mbtoutf8 (s);
1317 if (r == s) {
1318 ret_v = s_v;
1320 else {
1321 ret_v = caml_copy_string (r);
1322 free (r);
1324 CAMLreturn (ret_v);
1327 static void * mainloop (void UNUSED_ATTR *unused)
1329 char *p = NULL;
1330 int len, ret, oldlen = 0;
1332 fz_var (p);
1333 fz_var (oldlen);
1334 for (;;) {
1335 len = readlen (state.csock);
1336 if (len == 0) {
1337 errx (1, "readlen returned 0");
1340 if (oldlen < len + 1) {
1341 p = realloc (p, len + 1);
1342 if (!p) {
1343 err (1, "realloc %d failed", len + 1);
1345 oldlen = len + 1;
1347 readdata (state.csock, p, len);
1348 p[len] = 0;
1350 if (!strncmp ("open", p, 4)) {
1351 int off, usedoccss, ok = 0, layouth;
1352 char *password;
1353 char *filename;
1354 char *utf8filename;
1355 size_t filenamelen;
1357 fz_var (ok);
1358 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1359 if (ret != 2) {
1360 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1363 filename = p + 5 + off;
1364 filenamelen = strlen (filename);
1365 password = filename + filenamelen + 1;
1367 if (password[strlen (password) + 1]) {
1368 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1371 lock ("open");
1372 fz_set_use_document_css (state.ctx, usedoccss);
1373 fz_try (state.ctx) {
1374 ok = openxref (filename, password, layouth);
1376 fz_catch (state.ctx) {
1377 utf8filename = mbtoutf8 (filename);
1378 printd ("emsg Error loading %s: %s",
1379 utf8filename, fz_caught_message (state.ctx));
1380 if (utf8filename != filename) {
1381 free (utf8filename);
1384 if (ok) {
1385 docinfo ();
1386 initpdims ();
1388 unlock ("open");
1389 state.needoutline = ok;
1391 else if (!strncmp ("cs", p, 2)) {
1392 int i, colorspace;
1394 ret = sscanf (p + 2, " %d", &colorspace);
1395 if (ret != 1) {
1396 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1398 lock ("cs");
1399 set_tex_params (colorspace);
1400 for (i = 0; i < state.texcount; ++i) {
1401 state.texowners[i].w = -1;
1402 state.texowners[i].slice = NULL;
1404 unlock ("cs");
1406 else if (!strncmp ("freepage", p, 8)) {
1407 void *ptr;
1409 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1410 if (ret != 1) {
1411 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1413 lock ("freepage");
1414 freepage (ptr);
1415 unlock ("freepage");
1417 else if (!strncmp ("freetile", p, 8)) {
1418 void *ptr;
1420 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1421 if (ret != 1) {
1422 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1424 lock ("freetile");
1425 freetile (ptr);
1426 unlock ("freetile");
1428 else if (!strncmp ("search", p, 6)) {
1429 int icase, pageno, y, len2, forward;
1430 char *pattern;
1431 regex_t re;
1433 ret = sscanf (p + 6, " %d %d %d %d,%n",
1434 &icase, &pageno, &y, &forward, &len2);
1435 if (ret != 4) {
1436 errx (1, "malformed search `%s' ret=%d", p, ret);
1439 pattern = p + 6 + len2;
1440 ret = regcomp (&re, pattern,
1441 REG_EXTENDED | (icase ? REG_ICASE : 0));
1442 if (ret) {
1443 char errbuf[80];
1444 size_t size;
1446 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1447 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1449 else {
1450 lock ("search");
1451 search (&re, pageno, y, forward);
1452 unlock ("search");
1453 regfree (&re);
1456 else if (!strncmp ("geometry", p, 8)) {
1457 int w, h, fitmodel;
1459 printd ("clear");
1460 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1461 if (ret != 3) {
1462 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1465 lock ("geometry");
1466 state.h = h;
1467 if (w != state.w) {
1468 state.w = w;
1469 for (int i = 0; i < state.texcount; ++i) {
1470 state.texowners[i].slice = NULL;
1473 state.fitmodel = fitmodel;
1474 layout ();
1475 process_outline ();
1477 state.gen++;
1478 unlock ("geometry");
1479 printd ("continue %d", state.pagecount);
1481 else if (!strncmp ("reqlayout", p, 9)) {
1482 char *nameddest;
1483 int rotate, off, h;
1484 int fitmodel;
1485 pdf_document *pdf;
1487 printd ("clear");
1488 ret = sscanf (p + 9, " %d %d %d %n",
1489 &rotate, &fitmodel, &h, &off);
1490 if (ret != 3) {
1491 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1493 lock ("reqlayout");
1494 pdf = pdf_specifics (state.ctx, state.doc);
1495 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1496 state.gen += 1;
1498 state.rotate = rotate;
1499 state.fitmodel = fitmodel;
1500 state.h = h;
1501 layout ();
1502 process_outline ();
1504 nameddest = p + 9 + off;
1505 if (pdf && nameddest && *nameddest) {
1506 fz_point xy;
1507 struct pagedim *pdim;
1508 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1509 &xy.x, &xy.y);
1510 pdim = pdimofpageno (pageno);
1511 xy = fz_transform_point (xy, pdim->ctm);
1512 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1515 state.gen++;
1516 unlock ("reqlayout");
1517 printd ("continue %d", state.pagecount);
1519 else if (!strncmp ("page", p, 4)) {
1520 double a, b;
1521 struct page *page;
1522 int pageno, pindex;
1524 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1525 if (ret != 2) {
1526 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1529 lock ("page");
1530 a = now ();
1531 page = loadpage (pageno, pindex);
1532 b = now ();
1533 unlock ("page");
1535 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1537 else if (!strncmp ("tile", p, 4)) {
1538 int x, y, w, h;
1539 struct page *page;
1540 struct tile *tile;
1541 double a, b;
1542 void *data;
1544 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1545 (uintptr_t *) &page, &x, &y, &w, &h,
1546 (uintptr_t *) &data);
1547 if (ret != 6) {
1548 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1551 lock ("tile");
1552 a = now ();
1553 tile = rendertile (page, x, y, w, h, data);
1554 b = now ();
1555 unlock ("tile");
1557 printd ("tile %d %d %" PRIxPTR " %u %f",
1558 x, y, (uintptr_t) (tile),
1559 tile->w * tile->h * tile->pixmap->n,
1560 b - a);
1562 else if (!strncmp ("trimset", p, 7)) {
1563 fz_irect fuzz;
1564 int trimmargins;
1566 ret = sscanf (p + 7, " %d %d %d %d %d",
1567 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1568 if (ret != 5) {
1569 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1571 lock ("trimset");
1572 state.trimmargins = trimmargins;
1573 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1574 state.trimanew = 1;
1575 state.trimfuzz = fuzz;
1577 unlock ("trimset");
1579 else if (!strncmp ("settrim", p, 7)) {
1580 fz_irect fuzz;
1581 int trimmargins;
1583 ret = sscanf (p + 7, " %d %d %d %d %d",
1584 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1585 if (ret != 5) {
1586 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1588 printd ("clear");
1589 lock ("settrim");
1590 state.trimmargins = trimmargins;
1591 state.needoutline = 1;
1592 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1593 state.trimanew = 1;
1594 state.trimfuzz = fuzz;
1596 state.pagedimcount = 0;
1597 free (state.pagedims);
1598 state.pagedims = NULL;
1599 initpdims ();
1600 layout ();
1601 process_outline ();
1602 unlock ("settrim");
1603 printd ("continue %d", state.pagecount);
1605 else if (!strncmp ("sliceh", p, 6)) {
1606 int h;
1608 ret = sscanf (p + 6, " %d", &h);
1609 if (ret != 1) {
1610 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1612 if (h != state.sliceheight) {
1613 state.sliceheight = h;
1614 for (int i = 0; i < state.texcount; ++i) {
1615 state.texowners[i].w = -1;
1616 state.texowners[i].h = -1;
1617 state.texowners[i].slice = NULL;
1621 else if (!strncmp ("interrupt", p, 9)) {
1622 printd ("vmsg interrupted");
1624 else {
1625 errx (1, "unknown command %.*s", len, p);
1628 return 0;
1631 ML (isexternallink (value uri_v))
1633 CAMLparam1 (uri_v);
1634 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1635 CAMLreturn (Val_bool (ext));
1638 ML (uritolocation (value uri_v))
1640 CAMLparam1 (uri_v);
1641 CAMLlocal1 (ret_v);
1642 int pageno;
1643 fz_point xy;
1644 struct pagedim *pdim;
1646 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1647 &xy.x, &xy.y).page;
1648 pdim = pdimofpageno (pageno);
1649 xy = fz_transform_point (xy, pdim->ctm);
1650 ret_v = caml_alloc_tuple (3);
1651 Field (ret_v, 0) = Val_int (pageno);
1652 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1653 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1654 CAMLreturn (ret_v);
1657 ML (realloctexts (value texcount_v))
1659 CAMLparam1 (texcount_v);
1660 int ok;
1662 if (trylock (__func__)) {
1663 ok = 0;
1664 goto done;
1666 realloctexts (Int_val (texcount_v));
1667 ok = 1;
1668 unlock (__func__);
1670 done:
1671 CAMLreturn (Val_bool (ok));
1674 static void recti (int x0, int y0, int x1, int y1)
1676 GLfloat *v = state.vertices;
1678 glVertexPointer (2, GL_FLOAT, 0, v);
1679 v[0] = x0; v[1] = y0;
1680 v[2] = x1; v[3] = y0;
1681 v[4] = x0; v[5] = y1;
1682 v[6] = x1; v[7] = y1;
1683 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1686 static void showsel (struct page *page, int ox, int oy)
1688 fz_irect bbox;
1689 fz_rect rect;
1690 fz_stext_block *block;
1691 int seen = 0;
1692 unsigned char selcolor[] = {15,15,15,140};
1694 if (!page->fmark || !page->lmark) return;
1696 glEnable (GL_BLEND);
1697 glBlendFunc (GL_SRC_ALPHA, GL_SRC_ALPHA);
1698 glColor4ubv (selcolor);
1700 ox += state.pagedims[page->pdimno].bounds.x0;
1701 oy += state.pagedims[page->pdimno].bounds.y0;
1703 for (block = page->text->first_block; block; block = block->next) {
1704 fz_stext_line *line;
1706 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1707 for (line = block->u.t.first_line; line; line = line->next) {
1708 fz_stext_char *ch;
1710 rect = fz_empty_rect;
1711 for (ch = line->first_char; ch; ch = ch->next) {
1712 fz_rect r;
1713 if (ch == page->fmark) seen = 1;
1714 r = fz_rect_from_quad (ch->quad);
1715 if (seen) rect = fz_union_rect (rect, r);
1716 if (ch == page->lmark) {
1717 bbox = fz_round_rect (rect);
1718 recti (bbox.x0 + ox, bbox.y0 + oy,
1719 bbox.x1 + ox, bbox.y1 + oy);
1720 goto done;
1723 bbox = fz_round_rect (rect);
1724 recti (bbox.x0 + ox, bbox.y0 + oy,
1725 bbox.x1 + ox, bbox.y1 + oy);
1728 done:
1729 glDisable (GL_BLEND);
1732 #pragma GCC diagnostic push
1733 #pragma GCC diagnostic ignored "-Wconversion"
1734 #include "glfont.c"
1735 #pragma GCC diagnostic pop
1737 static void stipplerect (fz_matrix m,
1738 fz_point p1,
1739 fz_point p2,
1740 fz_point p3,
1741 fz_point p4,
1742 GLfloat *texcoords,
1743 GLfloat *vertices)
1745 p1 = fz_transform_point (p1, m);
1746 p2 = fz_transform_point (p2, m);
1747 p3 = fz_transform_point (p3, m);
1748 p4 = fz_transform_point (p4, m);
1750 float w, h, s, t;
1752 w = p2.x - p1.x;
1753 h = p2.y - p1.y;
1754 t = hypotf (w, h) * .25f;
1756 w = p3.x - p2.x;
1757 h = p3.y - p2.y;
1758 s = hypotf (w, h) * .25f;
1760 texcoords[0] = 0; vertices[0] = p1.x; vertices[1] = p1.y;
1761 texcoords[1] = t; vertices[2] = p2.x; vertices[3] = p2.y;
1763 texcoords[2] = 0; vertices[4] = p2.x; vertices[5] = p2.y;
1764 texcoords[3] = s; vertices[6] = p3.x; vertices[7] = p3.y;
1766 texcoords[4] = 0; vertices[8] = p3.x; vertices[9] = p3.y;
1767 texcoords[5] = t; vertices[10] = p4.x; vertices[11] = p4.y;
1769 texcoords[6] = 0; vertices[12] = p4.x; vertices[13] = p4.y;
1770 texcoords[7] = s; vertices[14] = p1.x; vertices[15] = p1.y;
1772 glDrawArrays (GL_LINES, 0, 8);
1775 static void solidrect (fz_matrix m,
1776 fz_point p1,
1777 fz_point p2,
1778 fz_point p3,
1779 fz_point p4,
1780 GLfloat *vertices)
1782 p1 = fz_transform_point (p1, m);
1783 p2 = fz_transform_point (p2, m);
1784 p3 = fz_transform_point (p3, m);
1785 p4 = fz_transform_point (p4, m);
1786 vertices[0] = p1.x; vertices[1] = p1.y;
1787 vertices[2] = p2.x; vertices[3] = p2.y;
1789 vertices[4] = p3.x; vertices[5] = p3.y;
1790 vertices[6] = p4.x; vertices[7] = p4.y;
1791 glDrawArrays (GL_TRIANGLE_FAN, 0, 4);
1794 static void ensurelinks (struct page *page)
1796 if (!page->links)
1797 page->links = fz_load_links (state.ctx, page->fzpage);
1800 static void highlightlinks (struct page *page, int xoff, int yoff)
1802 fz_matrix ctm;
1803 fz_link *link;
1804 GLfloat *texcoords = state.texcoords;
1805 GLfloat *vertices = state.vertices;
1807 ensurelinks (page);
1809 glEnable (GL_TEXTURE_1D);
1810 glEnable (GL_BLEND);
1811 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1812 glBindTexture (GL_TEXTURE_1D, state.stid);
1814 xoff -= state.pagedims[page->pdimno].bounds.x0;
1815 yoff -= state.pagedims[page->pdimno].bounds.y0;
1816 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
1818 glTexCoordPointer (1, GL_FLOAT, 0, texcoords);
1819 glVertexPointer (2, GL_FLOAT, 0, vertices);
1821 for (link = page->links; link; link = link->next) {
1822 fz_point p1, p2, p3, p4;
1824 p1.x = link->rect.x0;
1825 p1.y = link->rect.y0;
1827 p2.x = link->rect.x1;
1828 p2.y = link->rect.y0;
1830 p3.x = link->rect.x1;
1831 p3.y = link->rect.y1;
1833 p4.x = link->rect.x0;
1834 p4.y = link->rect.y1;
1836 /* TODO: different colours for different schemes */
1837 if (fz_is_external_link (state.ctx, link->uri)) glColor3ub (0, 0, 255);
1838 else glColor3ub (255, 0, 0);
1840 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1843 for (int i = 0; i < page->annotcount; ++i) {
1844 fz_point p1, p2, p3, p4;
1845 struct annot *annot = &page->annots[i];
1847 p1.x = annot->bbox.x0;
1848 p1.y = annot->bbox.y0;
1850 p2.x = annot->bbox.x1;
1851 p2.y = annot->bbox.y0;
1853 p3.x = annot->bbox.x1;
1854 p3.y = annot->bbox.y1;
1856 p4.x = annot->bbox.x0;
1857 p4.y = annot->bbox.y1;
1859 glColor3ub (0, 0, 128);
1860 stipplerect (ctm, p1, p2, p3, p4, texcoords, vertices);
1863 glDisable (GL_BLEND);
1864 glDisable (GL_TEXTURE_1D);
1867 static int compareslinks (const void *l, const void *r)
1869 struct slink const *ls = l;
1870 struct slink const *rs = r;
1871 if (ls->bbox.y0 == rs->bbox.y0) {
1872 return ls->bbox.x0 - rs->bbox.x0;
1874 return ls->bbox.y0 - rs->bbox.y0;
1877 static void droptext (struct page *page)
1879 if (page->text) {
1880 fz_drop_stext_page (state.ctx, page->text);
1881 page->fmark = NULL;
1882 page->lmark = NULL;
1883 page->text = NULL;
1887 static void dropannots (struct page *page)
1889 if (page->annots) {
1890 free (page->annots);
1891 page->annots = NULL;
1892 page->annotcount = 0;
1896 static void ensureannots (struct page *page)
1898 int i, count = 0;
1899 size_t annotsize = sizeof (*page->annots);
1900 pdf_annot *annot;
1901 pdf_document *pdf;
1902 pdf_page *pdfpage;
1904 pdf = pdf_specifics (state.ctx, state.doc);
1905 if (!pdf) return;
1907 pdfpage = pdf_page_from_fz_page (state.ctx, page->fzpage);
1908 if (state.gen != page->agen) {
1909 dropannots (page);
1910 page->agen = state.gen;
1912 if (page->annots) return;
1914 for (annot = pdf_first_annot (state.ctx, pdfpage);
1915 annot;
1916 annot = pdf_next_annot (state.ctx, annot)) {
1917 count++;
1920 if (count > 0) {
1921 page->annotcount = count;
1922 page->annots = calloc (count, annotsize);
1923 if (!page->annots) {
1924 err (1, "calloc annots %d", count);
1927 for (annot = pdf_first_annot (state.ctx, pdfpage), i = 0;
1928 annot;
1929 annot = pdf_next_annot (state.ctx, annot), i++) {
1930 fz_rect rect;
1932 rect = pdf_bound_annot (state.ctx, annot);
1933 page->annots[i].annot = annot;
1934 page->annots[i].bbox = fz_round_rect (rect);
1939 static void dropslinks (struct page *page)
1941 if (page->slinks) {
1942 free (page->slinks);
1943 page->slinks = NULL;
1944 page->slinkcount = 0;
1946 if (page->links) {
1947 fz_drop_link (state.ctx, page->links);
1948 page->links = NULL;
1952 static void ensureslinks (struct page *page)
1954 fz_matrix ctm;
1955 int i, count;
1956 size_t slinksize = sizeof (*page->slinks);
1957 fz_link *link;
1959 ensureannots (page);
1960 if (state.gen != page->sgen) {
1961 dropslinks (page);
1962 page->sgen = state.gen;
1964 if (page->slinks) return;
1966 ensurelinks (page);
1967 ctm = pagectm (page);
1969 count = page->annotcount;
1970 for (link = page->links; link; link = link->next) {
1971 count++;
1973 if (count > 0) {
1974 int j;
1976 page->slinkcount = count;
1977 page->slinks = calloc (count, slinksize);
1978 if (!page->slinks) {
1979 err (1, "calloc slinks %d", count);
1982 for (i = 0, link = page->links; link; ++i, link = link->next) {
1983 fz_rect rect;
1985 rect = link->rect;
1986 rect = fz_transform_rect (rect, ctm);
1987 page->slinks[i].tag = SLINK;
1988 page->slinks[i].u.link = link;
1989 page->slinks[i].bbox = fz_round_rect (rect);
1991 for (j = 0; j < page->annotcount; ++j, ++i) {
1992 fz_rect rect;
1993 rect = pdf_bound_annot (state.ctx, page->annots[j].annot);
1994 rect = fz_transform_rect (rect, ctm);
1995 page->slinks[i].bbox = fz_round_rect (rect);
1997 page->slinks[i].tag = SANNOT;
1998 page->slinks[i].u.annot = page->annots[j].annot;
2000 qsort (page->slinks, count, slinksize, compareslinks);
2004 static void highlightslinks (struct page *page, int xoff, int yoff,
2005 int noff, char *targ, mlsize_t tlen, int hfsize)
2007 char buf[40];
2008 struct slink *slink;
2009 float x0, y0, x1, y1, w;
2011 ensureslinks (page);
2012 glColor3ub (0xc3, 0xb0, 0x91);
2013 for (int i = 0; i < page->slinkcount; ++i) {
2014 fmt_linkn (buf, i + noff);
2015 if (!tlen || !strncmp (targ, buf, tlen)) {
2016 slink = &page->slinks[i];
2018 x0 = slink->bbox.x0 + xoff - 5;
2019 y1 = slink->bbox.y0 + yoff - 5;
2020 y0 = y1 + 10 + hfsize;
2021 w = measure_string (state.face, hfsize, buf);
2022 x1 = x0 + w + 10;
2023 recti ((int) x0, (int) y0, (int) x1, (int) y1);
2027 glEnable (GL_BLEND);
2028 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2029 glEnable (GL_TEXTURE_2D);
2030 glColor3ub (0, 0, 0);
2031 for (int i = 0; i < page->slinkcount; ++i) {
2032 fmt_linkn (buf, i + noff);
2033 if (!tlen || !strncmp (targ, buf, tlen)) {
2034 slink = &page->slinks[i];
2036 x0 = slink->bbox.x0 + xoff;
2037 y0 = slink->bbox.y0 + yoff + hfsize;
2038 draw_string (state.face, hfsize, x0, y0, buf);
2041 glDisable (GL_TEXTURE_2D);
2042 glDisable (GL_BLEND);
2045 static void uploadslice (struct tile *tile, struct slice *slice)
2047 int offset;
2048 struct slice *slice1;
2049 unsigned char *texdata;
2051 offset = 0;
2052 for (slice1 = tile->slices; slice != slice1; slice1++) {
2053 offset += slice1->h * tile->w * tile->pixmap->n;
2055 if (slice->texindex != -1 && slice->texindex < state.texcount
2056 && state.texowners[slice->texindex].slice == slice) {
2057 glBindTexture (TEXT_TYPE, state.texids[slice->texindex]);
2059 else {
2060 int subimage = 0;
2061 int texindex = state.texindex++ % state.texcount;
2063 if (state.texowners[texindex].w == tile->w) {
2064 if (state.texowners[texindex].h >= slice->h) {
2065 subimage = 1;
2067 else {
2068 state.texowners[texindex].h = slice->h;
2071 else {
2072 state.texowners[texindex].h = slice->h;
2075 state.texowners[texindex].w = tile->w;
2076 state.texowners[texindex].slice = slice;
2077 slice->texindex = texindex;
2079 glBindTexture (TEXT_TYPE, state.texids[texindex]);
2080 #if TEXT_TYPE == GL_TEXTURE_2D
2081 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2082 glTexParameteri (TEXT_TYPE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2083 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2084 glTexParameteri (TEXT_TYPE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2085 #endif
2086 if (tile->pbo) {
2087 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
2088 texdata = 0;
2090 else {
2091 texdata = tile->pixmap->samples;
2093 if (subimage) {
2094 glTexSubImage2D (TEXT_TYPE,
2098 tile->w,
2099 slice->h,
2100 state.texform,
2101 state.texty,
2102 texdata+offset
2105 else {
2106 glTexImage2D (TEXT_TYPE,
2108 state.texiform,
2109 tile->w,
2110 slice->h,
2112 state.texform,
2113 state.texty,
2114 texdata+offset
2117 if (tile->pbo) {
2118 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
2123 ML0 (begintiles (void))
2125 glEnable (TEXT_TYPE);
2126 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2127 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2130 ML0 (endtiles (void))
2132 glDisable (TEXT_TYPE);
2135 ML0 (drawtile (value args_v, value ptr_v))
2137 CAMLparam2 (args_v, ptr_v);
2138 int dispx = Int_val (Field (args_v, 0));
2139 int dispy = Int_val (Field (args_v, 1));
2140 int dispw = Int_val (Field (args_v, 2));
2141 int disph = Int_val (Field (args_v, 3));
2142 int tilex = Int_val (Field (args_v, 4));
2143 int tiley = Int_val (Field (args_v, 5));
2144 char *s = String_val (ptr_v);
2145 struct tile *tile = parse_pointer (__func__, s);
2146 int slicey, firstslice;
2147 struct slice *slice;
2148 GLfloat *texcoords = state.texcoords;
2149 GLfloat *vertices = state.vertices;
2151 firstslice = tiley / tile->sliceheight;
2152 slice = &tile->slices[firstslice];
2153 slicey = tiley % tile->sliceheight;
2155 while (disph > 0) {
2156 int dh;
2158 dh = slice->h - slicey;
2159 dh = fz_mini (disph, dh);
2160 uploadslice (tile, slice);
2162 texcoords[0] = tilex; texcoords[1] = slicey;
2163 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2164 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2165 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2167 vertices[0] = dispx; vertices[1] = dispy;
2168 vertices[2] = dispx+dispw; vertices[3] = dispy;
2169 vertices[4] = dispx; vertices[5] = dispy+dh;
2170 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2172 #if TEXT_TYPE == GL_TEXTURE_2D
2173 for (int i = 0; i < 8; ++i) {
2174 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2176 #endif
2178 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2179 dispy += dh;
2180 disph -= dh;
2181 slice++;
2182 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2183 slicey = 0;
2185 CAMLreturn0;
2188 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2190 fz_matrix ctm;
2191 fz_point p1, p2, p3, p4;
2192 GLfloat *vertices = state.vertices;
2194 xoff -= state.pagedims[page->pdimno].bounds.x0;
2195 yoff -= state.pagedims[page->pdimno].bounds.y0;
2196 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2198 glEnable (GL_BLEND);
2199 glVertexPointer (2, GL_FLOAT, 0, vertices);
2201 glColor4d (
2202 Double_array_field (rects_v, 0),
2203 Double_array_field (rects_v, 1),
2204 Double_array_field (rects_v, 2),
2205 Double_array_field (rects_v, 3)
2207 p1.x = (float) Double_array_field (rects_v, 4);
2208 p1.y = (float) Double_array_field (rects_v, 5);
2210 p2.x = (float) Double_array_field (rects_v, 6);
2211 p2.y = p1.y;
2213 p3.x = p2.x;
2214 p3.y = (float) Double_array_field (rects_v, 7);
2216 p4.x = p1.x;
2217 p4.y = p3.y;
2218 solidrect (ctm, p1, p2, p3, p4, vertices);
2219 glDisable (GL_BLEND);
2222 ML (postprocess (value ptr_v, value hlinks_v,
2223 value xoff_v, value yoff_v,
2224 value li_v))
2226 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2227 int xoff = Int_val (xoff_v);
2228 int yoff = Int_val (yoff_v);
2229 int noff = Int_val (Field (li_v, 0));
2230 char *targ = String_val (Field (li_v, 1));
2231 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2232 int hfsize = Int_val (Field (li_v, 2));
2233 char *s = String_val (ptr_v);
2234 int hlmask = Int_val (hlinks_v);
2235 struct page *page = parse_pointer (__func__, s);
2237 if (!page->fzpage) {
2238 /* deal with loadpage failed pages */
2239 goto done;
2242 if (trylock (__func__)) {
2243 noff = -1;
2244 goto done;
2247 ensureannots (page);
2248 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2249 if (hlmask & 2) {
2250 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2251 noff = page->slinkcount;
2253 if (page->tgen == state.gen) {
2254 showsel (page, xoff, yoff);
2256 unlock (__func__);
2258 done:
2259 CAMLreturn (Val_int (noff));
2262 ML0 (drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v))
2264 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2265 int xoff = Int_val (xoff_v);
2266 int yoff = Int_val (yoff_v);
2267 char *s = String_val (ptr_v);
2268 struct page *page = parse_pointer (__func__, s);
2270 drawprect (page, xoff, yoff, rects_v);
2271 CAMLreturn0;
2274 static struct annot *getannot (struct page *page, int x, int y)
2276 fz_point p;
2277 fz_matrix ctm;
2278 const fz_matrix *tctm;
2279 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2281 if (!page->annots) return NULL;
2283 if (pdf) {
2284 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2285 tctm = &state.pagedims[page->pdimno].tctm;
2287 else {
2288 tctm = &fz_identity;
2291 p.x = x;
2292 p.y = y;
2294 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2295 ctm = fz_invert_matrix (ctm);
2296 p = fz_transform_point (p, ctm);
2298 if (pdf) {
2299 for (int i = 0; i < page->annotcount; ++i) {
2300 struct annot *a = &page->annots[i];
2301 fz_rect rect;
2303 rect = pdf_bound_annot (state.ctx, a->annot);
2304 if (p.x >= rect.x0 && p.x <= rect.x1) {
2305 if (p.y >= rect.y0 && p.y <= rect.y1)
2306 return a;
2310 return NULL;
2313 static fz_link *getlink (struct page *page, int x, int y)
2315 fz_point p;
2316 fz_link *link;
2318 ensureslinks (page);
2320 p.x = x;
2321 p.y = y;
2323 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2325 for (link = page->links; link; link = link->next) {
2326 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2327 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2328 return link;
2332 return NULL;
2335 static void ensuretext (struct page *page)
2337 if (state.gen != page->tgen) {
2338 droptext (page);
2339 page->tgen = state.gen;
2341 if (!page->text) {
2342 fz_device *tdev;
2344 page->text = fz_new_stext_page (state.ctx,
2345 state.pagedims[page->pdimno].mediabox);
2346 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2347 fz_run_display_list (state.ctx, page->dlist,
2348 tdev, pagectm (page), fz_infinite_rect, NULL);
2349 fz_close_device (state.ctx, tdev);
2350 fz_drop_device (state.ctx, tdev);
2354 ML (find_page_with_links (value start_page_v, value dir_v))
2356 CAMLparam2 (start_page_v, dir_v);
2357 CAMLlocal1 (ret_v);
2358 int i, dir = Int_val (dir_v);
2359 int start_page = Int_val (start_page_v);
2360 int end_page = dir > 0 ? state.pagecount : -1;
2361 pdf_document *pdf;
2363 fz_var (end_page);
2364 ret_v = Val_int (0);
2365 lock (__func__);
2366 pdf = pdf_specifics (state.ctx, state.doc);
2367 for (i = start_page + dir; i != end_page; i += dir) {
2368 int found;
2370 fz_var (found);
2371 if (pdf) {
2372 pdf_page *page = NULL;
2374 fz_var (page);
2375 fz_try (state.ctx) {
2376 page = pdf_load_page (state.ctx, pdf, i);
2377 found = !!page->links || !!page->annots;
2379 fz_catch (state.ctx) {
2380 found = 0;
2382 if (page) {
2383 fz_drop_page (state.ctx, &page->super);
2386 else {
2387 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2388 fz_link *link = fz_load_links (state.ctx, page);
2389 found = !!link;
2390 fz_drop_link (state.ctx, link);
2391 fz_drop_page (state.ctx, page);
2394 if (found) {
2395 ret_v = caml_alloc_small (1, 1);
2396 Field (ret_v, 0) = Val_int (i);
2397 goto unlock;
2400 unlock:
2401 unlock (__func__);
2402 CAMLreturn (ret_v);
2405 enum { dir_first, dir_last };
2406 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2408 ML (findlink (value ptr_v, value dir_v))
2410 CAMLparam2 (ptr_v, dir_v);
2411 CAMLlocal2 (ret_v, pos_v);
2412 struct page *page;
2413 int dirtag, i, slinkindex;
2414 struct slink *found = NULL ,*slink;
2415 char *s = String_val (ptr_v);
2417 page = parse_pointer (__func__, s);
2418 ret_v = Val_int (0);
2419 lock (__func__);
2420 ensureslinks (page);
2422 if (Is_block (dir_v)) {
2423 dirtag = Tag_val (dir_v);
2424 switch (dirtag) {
2425 case dir_first_visible:
2427 int x0, y0, dir, first_index, last_index;
2429 pos_v = Field (dir_v, 0);
2430 x0 = Int_val (Field (pos_v, 0));
2431 y0 = Int_val (Field (pos_v, 1));
2432 dir = Int_val (Field (pos_v, 2));
2434 if (dir >= 0) {
2435 dir = 1;
2436 first_index = 0;
2437 last_index = page->slinkcount;
2439 else {
2440 first_index = page->slinkcount - 1;
2441 last_index = -1;
2444 for (i = first_index; i != last_index; i += dir) {
2445 slink = &page->slinks[i];
2446 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2447 found = slink;
2448 break;
2452 break;
2454 case dir_left:
2455 slinkindex = Int_val (Field (dir_v, 0));
2456 found = &page->slinks[slinkindex];
2457 for (i = slinkindex - 1; i >= 0; --i) {
2458 slink = &page->slinks[i];
2459 if (slink->bbox.x0 < found->bbox.x0) {
2460 found = slink;
2461 break;
2464 break;
2466 case dir_right:
2467 slinkindex = Int_val (Field (dir_v, 0));
2468 found = &page->slinks[slinkindex];
2469 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2470 slink = &page->slinks[i];
2471 if (slink->bbox.x0 > found->bbox.x0) {
2472 found = slink;
2473 break;
2476 break;
2478 case dir_down:
2479 slinkindex = Int_val (Field (dir_v, 0));
2480 found = &page->slinks[slinkindex];
2481 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2482 slink = &page->slinks[i];
2483 if (slink->bbox.y0 >= found->bbox.y0) {
2484 found = slink;
2485 break;
2488 break;
2490 case dir_up:
2491 slinkindex = Int_val (Field (dir_v, 0));
2492 found = &page->slinks[slinkindex];
2493 for (i = slinkindex - 1; i >= 0; --i) {
2494 slink = &page->slinks[i];
2495 if (slink->bbox.y0 <= found->bbox.y0) {
2496 found = slink;
2497 break;
2500 break;
2503 else {
2504 dirtag = Int_val (dir_v);
2505 switch (dirtag) {
2506 case dir_first:
2507 found = page->slinks;
2508 break;
2510 case dir_last:
2511 if (page->slinks) {
2512 found = page->slinks + (page->slinkcount - 1);
2514 break;
2517 if (found) {
2518 ret_v = caml_alloc_small (2, 1);
2519 Field (ret_v, 0) = Val_int (found - page->slinks);
2522 unlock (__func__);
2523 CAMLreturn (ret_v);
2526 enum { uuri, utext, uannot };
2528 ML (getlink (value ptr_v, value n_v))
2530 CAMLparam2 (ptr_v, n_v);
2531 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2532 fz_link *link;
2533 struct page *page;
2534 char *s = String_val (ptr_v);
2535 struct slink *slink;
2537 ret_v = Val_int (0);
2538 page = parse_pointer (__func__, s);
2540 lock (__func__);
2541 ensureslinks (page);
2542 slink = &page->slinks[Int_val (n_v)];
2543 if (slink->tag == SLINK) {
2544 link = slink->u.link;
2545 str_v = caml_copy_string (link->uri);
2546 ret_v = caml_alloc_small (1, uuri);
2547 Field (ret_v, 0) = str_v;
2549 else {
2550 ret_v = caml_alloc_small (1, uannot);
2551 tup_v = caml_alloc_tuple (2);
2552 Field (ret_v, 0) = tup_v;
2553 Field (tup_v, 0) = ptr_v;
2554 Field (tup_v, 1) = n_v;
2556 unlock (__func__);
2558 CAMLreturn (ret_v);
2561 ML (getannotcontents (value ptr_v, value n_v))
2563 CAMLparam2 (ptr_v, n_v);
2564 CAMLlocal1 (ret_v);
2565 pdf_document *pdf;
2566 const char *contents = "";
2568 lock (__func__);
2569 pdf = pdf_specifics (state.ctx, state.doc);
2570 if (pdf) {
2571 char *s = String_val (ptr_v);
2572 struct page *page;
2573 struct slink *slink;
2575 page = parse_pointer (__func__, s);
2576 slink = &page->slinks[Int_val (n_v)];
2577 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2579 unlock (__func__);
2580 ret_v = caml_copy_string (contents);
2581 CAMLreturn (ret_v);
2584 ML (getlinkcount (value ptr_v))
2586 CAMLparam1 (ptr_v);
2587 struct page *page;
2588 char *s = String_val (ptr_v);
2590 page = parse_pointer (__func__, s);
2591 CAMLreturn (Val_int (page->slinkcount));
2594 ML (getlinkrect (value ptr_v, value n_v))
2596 CAMLparam2 (ptr_v, n_v);
2597 CAMLlocal1 (ret_v);
2598 struct page *page;
2599 struct slink *slink;
2600 char *s = String_val (ptr_v);
2602 page = parse_pointer (__func__, s);
2603 ret_v = caml_alloc_tuple (4);
2604 lock (__func__);
2605 ensureslinks (page);
2607 slink = &page->slinks[Int_val (n_v)];
2608 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2609 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2610 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2611 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2612 unlock (__func__);
2613 CAMLreturn (ret_v);
2616 ML (whatsunder (value ptr_v, value x_v, value y_v))
2618 CAMLparam3 (ptr_v, x_v, y_v);
2619 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2620 fz_link *link;
2621 struct annot *annot;
2622 struct page *page;
2623 char *ptr = String_val (ptr_v);
2624 int x = Int_val (x_v), y = Int_val (y_v);
2625 struct pagedim *pdim;
2627 ret_v = Val_int (0);
2628 if (trylock (__func__)) {
2629 goto done;
2632 page = parse_pointer (__func__, ptr);
2633 pdim = &state.pagedims[page->pdimno];
2634 x += pdim->bounds.x0;
2635 y += pdim->bounds.y0;
2638 annot = getannot (page, x, y);
2639 if (annot) {
2640 int i, n = -1;
2642 ensureslinks (page);
2643 for (i = 0; i < page->slinkcount; ++i) {
2644 if (page->slinks[i].tag == SANNOT
2645 && page->slinks[i].u.annot == annot->annot) {
2646 n = i;
2647 break;
2650 ret_v = caml_alloc_small (1, uannot);
2651 tup_v = caml_alloc_tuple (2);
2652 Field (ret_v, 0) = tup_v;
2653 Field (tup_v, 0) = ptr_v;
2654 Field (tup_v, 1) = Val_int (n);
2655 goto unlock;
2659 link = getlink (page, x, y);
2660 if (link) {
2661 str_v = caml_copy_string (link->uri);
2662 ret_v = caml_alloc_small (1, uuri);
2663 Field (ret_v, 0) = str_v;
2665 else {
2666 fz_rect *b;
2667 fz_stext_block *block;
2669 ensuretext (page);
2671 for (block = page->text->first_block; block; block = block->next) {
2672 fz_stext_line *line;
2674 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2675 b = &block->bbox;
2676 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2677 continue;
2679 for (line = block->u.t.first_line; line; line = line->next) {
2680 fz_stext_char *ch;
2682 b = &line->bbox;
2683 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2684 continue;
2686 for (ch = line->first_char; ch; ch = ch->next) {
2687 fz_quad *q = &ch->quad;
2689 if (x >= q->ul.x && x <= q->ur.x
2690 && y >= q->ul.y && y <= q->ll.y) {
2691 const char *n2 = fz_font_name (state.ctx, ch->font);
2692 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2693 ch->font);
2695 if (!n2) n2 = "<unknown font>";
2697 if (face && face->family_name) {
2698 char *s;
2699 char *n1 = face->family_name;
2700 size_t l1 = strlen (n1);
2701 size_t l2 = strlen (n2);
2703 if (l1 != l2 || memcmp (n1, n2, l1)) {
2704 s = malloc (l1 + l2 + 2);
2705 if (s) {
2706 memcpy (s, n2, l2);
2707 s[l2] = '=';
2708 memcpy (s + l2 + 1, n1, l1 + 1);
2709 str_v = caml_copy_string (s);
2710 free (s);
2714 if (str_v == Val_unit) {
2715 str_v = caml_copy_string (n2);
2717 ret_v = caml_alloc_small (1, utext);
2718 Field (ret_v, 0) = str_v;
2719 goto unlock;
2725 unlock:
2726 unlock (__func__);
2728 done:
2729 CAMLreturn (ret_v);
2732 enum { mark_page, mark_block, mark_line, mark_word };
2734 ML0 (clearmark (value ptr_v))
2736 CAMLparam1 (ptr_v);
2737 char *s = String_val (ptr_v);
2738 struct page *page;
2740 if (trylock (__func__)) {
2741 goto done;
2744 page = parse_pointer (__func__, s);
2745 page->fmark = NULL;
2746 page->lmark = NULL;
2748 unlock (__func__);
2749 done:
2750 CAMLreturn0;
2753 static int uninteresting (int c)
2755 return isspace (c) || ispunct (c);
2758 ML (markunder (value ptr_v, value x_v, value y_v, value mark_v))
2760 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2761 CAMLlocal1 (ret_v);
2762 fz_rect *b;
2763 struct page *page;
2764 fz_stext_line *line;
2765 fz_stext_block *block;
2766 struct pagedim *pdim;
2767 int mark = Int_val (mark_v);
2768 char *s = String_val (ptr_v);
2769 int x = Int_val (x_v), y = Int_val (y_v);
2771 ret_v = Val_bool (0);
2772 if (trylock (__func__)) {
2773 goto done;
2776 page = parse_pointer (__func__, s);
2777 pdim = &state.pagedims[page->pdimno];
2779 ensuretext (page);
2781 if (mark == mark_page) {
2782 page->fmark = page->text->first_block->u.t.first_line->first_char;
2783 page->lmark = page->text->last_block->u.t.last_line->last_char;
2784 ret_v = Val_bool (1);
2785 goto unlock;
2788 x += pdim->bounds.x0;
2789 y += pdim->bounds.y0;
2791 for (block = page->text->first_block; block; block = block->next) {
2792 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2793 b = &block->bbox;
2794 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2795 continue;
2797 if (mark == mark_block) {
2798 page->fmark = block->u.t.first_line->first_char;
2799 page->lmark = block->u.t.last_line->last_char;
2800 ret_v = Val_bool (1);
2801 goto unlock;
2804 for (line = block->u.t.first_line; line; line = line->next) {
2805 fz_stext_char *ch;
2807 b = &line->bbox;
2808 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2809 continue;
2811 if (mark == mark_line) {
2812 page->fmark = line->first_char;
2813 page->lmark = line->last_char;
2814 ret_v = Val_bool (1);
2815 goto unlock;
2818 for (ch = line->first_char; ch; ch = ch->next) {
2819 fz_stext_char *ch2, *first = NULL, *last = NULL;
2820 fz_quad *q = &ch->quad;
2821 if (x >= q->ul.x && x <= q->ur.x
2822 && y >= q->ul.y && y <= q->ll.y) {
2823 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2824 if (uninteresting (ch2->c)) first = NULL;
2825 else if (!first) first = ch2;
2827 for (ch2 = ch; ch2; ch2 = ch2->next) {
2828 if (uninteresting (ch2->c)) break;
2829 last = ch2;
2832 page->fmark = first;
2833 page->lmark = last;
2834 ret_v = Val_bool (1);
2835 goto unlock;
2840 unlock:
2841 if (!Bool_val (ret_v)) {
2842 page->fmark = NULL;
2843 page->lmark = NULL;
2845 unlock (__func__);
2847 done:
2848 CAMLreturn (ret_v);
2851 ML (rectofblock (value ptr_v, value x_v, value y_v))
2853 CAMLparam3 (ptr_v, x_v, y_v);
2854 CAMLlocal2 (ret_v, res_v);
2855 fz_rect *b = NULL;
2856 struct page *page;
2857 struct pagedim *pdim;
2858 fz_stext_block *block;
2859 char *s = String_val (ptr_v);
2860 int x = Int_val (x_v), y = Int_val (y_v);
2862 ret_v = Val_int (0);
2863 if (trylock (__func__)) {
2864 goto done;
2867 page = parse_pointer (__func__, s);
2868 pdim = &state.pagedims[page->pdimno];
2869 x += pdim->bounds.x0;
2870 y += pdim->bounds.y0;
2872 ensuretext (page);
2874 for (block = page->text->first_block; block; block = block->next) {
2875 switch (block->type) {
2876 case FZ_STEXT_BLOCK_TEXT:
2877 b = &block->bbox;
2878 break;
2880 case FZ_STEXT_BLOCK_IMAGE:
2881 b = &block->bbox;
2882 break;
2884 default:
2885 continue;
2888 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2889 break;
2890 b = NULL;
2892 if (b) {
2893 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2894 ret_v = caml_alloc_small (1, 1);
2895 Store_double_field (res_v, 0, (double) b->x0);
2896 Store_double_field (res_v, 1, (double) b->x1);
2897 Store_double_field (res_v, 2, (double) b->y0);
2898 Store_double_field (res_v, 3, (double) b->y1);
2899 Field (ret_v, 0) = res_v;
2901 unlock (__func__);
2903 done:
2904 CAMLreturn (ret_v);
2907 ML0 (seltext (value ptr_v, value rect_v))
2909 CAMLparam2 (ptr_v, rect_v);
2910 struct page *page;
2911 struct pagedim *pdim;
2912 char *s = String_val (ptr_v);
2913 int x0, x1, y0, y1;
2914 fz_stext_char *ch;
2915 fz_stext_line *line;
2916 fz_stext_block *block;
2917 fz_stext_char *fc, *lc;
2919 if (trylock (__func__)) {
2920 goto done;
2923 page = parse_pointer (__func__, s);
2924 ensuretext (page);
2926 pdim = &state.pagedims[page->pdimno];
2927 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2928 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2929 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2930 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2932 if (y0 > y1) {
2933 int t = y0;
2934 y0 = y1;
2935 y1 = t;
2936 x0 = x1;
2937 x1 = t;
2940 fc = page->fmark;
2941 lc = page->lmark;
2943 for (block = page->text->first_block; block; block = block->next) {
2944 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2945 for (line = block->u.t.first_line; line; line = line->next) {
2946 for (ch = line->first_char; ch; ch = ch->next) {
2947 fz_quad q = ch->quad;
2948 if (x0 >= q.ul.x && x0 <= q.ur.x
2949 && y0 >= q.ul.y && y0 <= q.ll.y) {
2950 fc = ch;
2952 if (x1 >= q.ul.x && x1 <= q.ur.x
2953 && y1 >= q.ul.y && y1 <= q.ll.y) {
2954 lc = ch;
2959 if (x1 < x0 && fc == lc) {
2960 fz_stext_char *t;
2962 t = fc;
2963 fc = lc;
2964 lc = t;
2967 page->fmark = fc;
2968 page->lmark = lc;
2970 unlock (__func__);
2972 done:
2973 CAMLreturn0;
2976 static int pipechar (FILE *f, fz_stext_char *ch)
2978 char buf[4];
2979 int len;
2980 size_t ret;
2982 len = fz_runetochar (buf, ch->c);
2983 ret = fwrite (buf, len, 1, f);
2984 if (ret != 1) {
2985 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
2986 len, ret, errno, strerror (errno));
2987 return -1;
2989 return 0;
2992 ML (spawn (value command_v, value fds_v))
2994 CAMLparam2 (command_v, fds_v);
2995 CAMLlocal2 (l_v, tup_v);
2996 int ret, ret1;
2997 pid_t pid = (pid_t) -1;
2998 char *msg = NULL;
2999 value earg_v = Nothing;
3000 posix_spawnattr_t attr;
3001 posix_spawn_file_actions_t fa;
3002 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3004 argv[2] = String_val (command_v);
3006 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3007 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3010 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3011 msg = "posix_spawnattr_init";
3012 goto fail1;
3015 #ifdef POSIX_SPAWN_USEVFORK
3016 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3017 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3018 goto fail;
3020 #endif
3022 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3023 int fd1, fd2;
3025 tup_v = Field (l_v, 0);
3026 fd1 = Int_val (Field (tup_v, 0));
3027 fd2 = Int_val (Field (tup_v, 1));
3028 if (fd2 < 0) {
3029 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3030 msg = "posix_spawn_file_actions_addclose";
3031 earg_v = tup_v;
3032 goto fail;
3035 else {
3036 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3037 msg = "posix_spawn_file_actions_adddup2";
3038 earg_v = tup_v;
3039 goto fail;
3044 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3045 msg = "posix_spawn";
3046 goto fail;
3049 fail:
3050 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3051 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3054 fail1:
3055 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3056 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3057 ret1, strerror (ret1));
3060 if (msg)
3061 unix_error (ret, msg, earg_v);
3063 CAMLreturn (Val_int (pid));
3066 ML (hassel (value ptr_v))
3068 CAMLparam1 (ptr_v);
3069 CAMLlocal1 (ret_v);
3070 struct page *page;
3071 char *s = String_val (ptr_v);
3073 ret_v = Val_bool (0);
3074 if (trylock (__func__)) {
3075 goto done;
3078 page = parse_pointer (__func__, s);
3079 ret_v = Val_bool (page->fmark && page->lmark);
3080 unlock (__func__);
3081 done:
3082 CAMLreturn (ret_v);
3085 ML0 (copysel (value fd_v, value ptr_v))
3087 CAMLparam2 (fd_v, ptr_v);
3088 FILE *f;
3089 int seen = 0;
3090 struct page *page;
3091 fz_stext_line *line;
3092 fz_stext_block *block;
3093 int fd = Int_val (fd_v);
3094 char *s = String_val (ptr_v);
3096 if (trylock (__func__)) {
3097 goto done;
3100 page = parse_pointer (__func__, s);
3102 if (!page->fmark || !page->lmark) {
3103 printd ("emsg nothing to copy on page %d", page->pageno);
3104 goto unlock;
3107 f = fdopen (fd, "w");
3108 if (!f) {
3109 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3110 fd, errno, strerror (errno));
3111 f = stdout;
3114 for (block = page->text->first_block; block; block = block->next) {
3115 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3116 for (line = block->u.t.first_line; line; line = line->next) {
3117 fz_stext_char *ch;
3118 for (ch = line->first_char; ch; ch = ch->next) {
3119 if (seen || ch == page->fmark) {
3120 do {
3121 pipechar (f, ch);
3122 if (ch == page->lmark) goto close;
3123 } while ((ch = ch->next));
3124 seen = 1;
3125 break;
3128 if (seen) fputc ('\n', f);
3131 close:
3132 if (f != stdout) {
3133 int ret = fclose (f);
3134 fd = -1;
3135 if (ret == -1) {
3136 if (errno != ECHILD) {
3137 printd ("emsg failed to close sel pipe: %d:%s",
3138 errno, strerror (errno));
3142 unlock:
3143 unlock (__func__);
3145 done:
3146 if (fd >= 0) {
3147 if (close (fd)) {
3148 printd ("emsg failed to close sel pipe: %d:%s",
3149 errno, strerror (errno));
3152 CAMLreturn0;
3155 ML (getpdimrect (value pagedimno_v))
3157 CAMLparam1 (pagedimno_v);
3158 CAMLlocal1 (ret_v);
3159 int pagedimno = Int_val (pagedimno_v);
3160 fz_rect box;
3162 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3163 if (trylock (__func__)) {
3164 box = fz_empty_rect;
3166 else {
3167 box = state.pagedims[pagedimno].mediabox;
3168 unlock (__func__);
3171 Store_double_field (ret_v, 0, (double) box.x0);
3172 Store_double_field (ret_v, 1, (double) box.x1);
3173 Store_double_field (ret_v, 2, (double) box.y0);
3174 Store_double_field (ret_v, 3, (double) box.y1);
3176 CAMLreturn (ret_v);
3179 ML (zoom_for_height (value winw_v, value winh_v, value dw_v, value cols_v))
3181 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3182 CAMLlocal1 (ret_v);
3183 int i;
3184 float zoom = -1.;
3185 float maxh = 0.0;
3186 struct pagedim *p;
3187 float winw = Int_val (winw_v);
3188 float winh = Int_val (winh_v);
3189 float dw = Int_val (dw_v);
3190 float cols = Int_val (cols_v);
3191 float pw = 1.0, ph = 1.0;
3193 if (trylock (__func__)) {
3194 goto done;
3197 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3198 float w = p->pagebox.x1 / cols;
3199 float h = p->pagebox.y1;
3200 if (h > maxh) {
3201 maxh = h;
3202 ph = h;
3203 if (state.fitmodel != FitProportional) pw = w;
3205 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3208 zoom = (((winh / ph) * pw) + dw) / winw;
3209 unlock (__func__);
3210 done:
3211 ret_v = caml_copy_double ((double) zoom);
3212 CAMLreturn (ret_v);
3215 ML (getmaxw (value unit_v))
3217 CAMLparam1 (unit_v);
3218 CAMLlocal1 (ret_v);
3219 int i;
3220 float maxw = -1.;
3221 struct pagedim *p;
3223 if (trylock (__func__)) {
3224 goto done;
3227 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3228 float w = p->pagebox.x1;
3229 maxw = fz_max (maxw, w);
3232 unlock (__func__);
3233 done:
3234 ret_v = caml_copy_double ((double) maxw);
3235 CAMLreturn (ret_v);
3238 ML (draw_string (value pt_v, value x_v, value y_v, value string_v))
3240 CAMLparam4 (pt_v, x_v, y_v, string_v);
3241 CAMLlocal1 (ret_v);
3242 int pt = Int_val(pt_v);
3243 int x = Int_val (x_v);
3244 int y = Int_val (y_v);
3245 float w;
3247 w = draw_string (state.face, pt, x, y, String_val (string_v));
3248 ret_v = caml_copy_double (w);
3249 CAMLreturn (ret_v);
3252 ML (measure_string (value pt_v, value string_v))
3254 CAMLparam2 (pt_v, string_v);
3255 CAMLlocal1 (ret_v);
3256 int pt = Int_val (pt_v);
3257 double w;
3259 w = (double) measure_string (state.face, pt, String_val (string_v));
3260 ret_v = caml_copy_double (w);
3261 CAMLreturn (ret_v);
3264 ML (getpagebox (value opaque_v))
3266 CAMLparam1 (opaque_v);
3267 CAMLlocal1 (ret_v);
3268 fz_rect rect;
3269 fz_irect bbox;
3270 fz_device *dev;
3271 char *s = String_val (opaque_v);
3272 struct page *page = parse_pointer (__func__, s);
3274 ret_v = caml_alloc_tuple (4);
3275 dev = fz_new_bbox_device (state.ctx, &rect);
3277 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3279 fz_close_device (state.ctx, dev);
3280 fz_drop_device (state.ctx, dev);
3281 bbox = fz_round_rect (rect);
3282 Field (ret_v, 0) = Val_int (bbox.x0);
3283 Field (ret_v, 1) = Val_int (bbox.y0);
3284 Field (ret_v, 2) = Val_int (bbox.x1);
3285 Field (ret_v, 3) = Val_int (bbox.y1);
3287 CAMLreturn (ret_v);
3290 ML0 (setaalevel (value level_v))
3292 CAMLparam1 (level_v);
3294 state.aalevel = Int_val (level_v);
3295 CAMLreturn0;
3298 ML0 (setpapercolor (value rgba_v))
3300 CAMLparam1 (rgba_v);
3302 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3303 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3304 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3305 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3306 CAMLreturn0;
3309 value ml_keysymtoutf8 (value keysym_v);
3310 #ifndef CIDER
3311 value ml_keysymtoutf8 (value keysym_v)
3313 CAMLparam1 (keysym_v);
3314 CAMLlocal1 (str_v);
3315 KeySym keysym = Int_val (keysym_v);
3316 Rune rune;
3317 extern long keysym2ucs (KeySym);
3318 int len;
3319 char buf[5];
3321 rune = (Rune) keysym2ucs (keysym);
3322 len = fz_runetochar (buf, rune);
3323 buf[len] = 0;
3324 str_v = caml_copy_string (buf);
3325 CAMLreturn (str_v);
3327 #else
3328 value ml_keysymtoutf8 (value keysym_v)
3330 CAMLparam1 (keysym_v);
3331 CAMLlocal1 (str_v);
3332 long ucs = Long_val (keysym_v);
3333 int len;
3334 char buf[5];
3336 len = fz_runetochar (buf, (int) ucs);
3337 buf[len] = 0;
3338 str_v = caml_copy_string (buf);
3339 CAMLreturn (str_v);
3341 #endif
3343 enum { piunknown, pilinux, pimacos, pibsd };
3345 ML (platform (value unit_v))
3347 CAMLparam1 (unit_v);
3348 CAMLlocal2 (tup_v, arr_v);
3349 int platid = piunknown;
3350 struct utsname buf;
3352 #if defined __linux__
3353 platid = pilinux;
3354 #elif defined __DragonFly__ || defined __FreeBSD__
3355 || defined __OpenBSD__ || defined __NetBSD__
3356 platid = pibsd;
3357 #elif defined __APPLE__
3358 platid = pimacos;
3359 #endif
3360 if (uname (&buf)) err (1, "uname");
3362 tup_v = caml_alloc_tuple (2);
3364 char const *sar[] = {
3365 buf.sysname,
3366 buf.release,
3367 buf.version,
3368 buf.machine,
3369 NULL
3371 arr_v = caml_copy_string_array (sar);
3373 Field (tup_v, 0) = Val_int (platid);
3374 Field (tup_v, 1) = arr_v;
3375 CAMLreturn (tup_v);
3378 ML0 (cloexec (value fd_v))
3380 CAMLparam1 (fd_v);
3381 int fd = Int_val (fd_v);
3383 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3384 uerror ("fcntl", Nothing);
3386 CAMLreturn0;
3389 ML (getpbo (value w_v, value h_v, value cs_v))
3391 CAMLparam2 (w_v, h_v);
3392 CAMLlocal1 (ret_v);
3393 struct bo *pbo;
3394 int w = Int_val (w_v);
3395 int h = Int_val (h_v);
3396 int cs = Int_val (cs_v);
3398 if (state.bo_usable) {
3399 pbo = calloc (sizeof (*pbo), 1);
3400 if (!pbo) {
3401 err (1, "calloc pbo");
3404 switch (cs) {
3405 case 0:
3406 case 1:
3407 pbo->size = w*h*4;
3408 break;
3409 case 2:
3410 pbo->size = w*h*2;
3411 break;
3412 default:
3413 errx (1, "%s: invalid colorspace %d", __func__, cs);
3416 state.glGenBuffersARB (1, &pbo->id);
3417 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3418 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3419 NULL, GL_STREAM_DRAW);
3420 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3421 GL_READ_WRITE);
3422 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3423 if (!pbo->ptr) {
3424 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3425 state.glDeleteBuffersARB (1, &pbo->id);
3426 free (pbo);
3427 ret_v = caml_copy_string ("0");
3429 else {
3430 int res;
3431 char *s;
3433 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3434 if (res < 0) {
3435 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3437 s = malloc (res+1);
3438 if (!s) {
3439 err (1, "malloc %d bytes failed", res+1);
3441 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3442 if (res < 0) {
3443 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3445 ret_v = caml_copy_string (s);
3446 free (s);
3449 else {
3450 ret_v = caml_copy_string ("0");
3452 CAMLreturn (ret_v);
3455 ML0 (freepbo (value s_v))
3457 CAMLparam1 (s_v);
3458 char *s = String_val (s_v);
3459 struct tile *tile = parse_pointer (__func__, s);
3461 if (tile->pbo) {
3462 state.glDeleteBuffersARB (1, &tile->pbo->id);
3463 tile->pbo->id = -1;
3464 tile->pbo->ptr = NULL;
3465 tile->pbo->size = -1;
3467 CAMLreturn0;
3470 ML0 (unmappbo (value s_v))
3472 CAMLparam1 (s_v);
3473 char *s = String_val (s_v);
3474 struct tile *tile = parse_pointer (__func__, s);
3476 if (tile->pbo) {
3477 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3478 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3479 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3481 tile->pbo->ptr = NULL;
3482 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3484 CAMLreturn0;
3487 static void setuppbo (void)
3489 extern void (*wsigladdr (const char *name)) (void);
3490 #pragma GCC diagnostic push
3491 #ifdef __clang__
3492 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3493 #endif
3494 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3495 state.bo_usable = GPA (glBindBufferARB)
3496 && GPA (glUnmapBufferARB)
3497 && GPA (glMapBufferARB)
3498 && GPA (glBufferDataARB)
3499 && GPA (glGenBuffersARB)
3500 && GPA (glDeleteBuffersARB);
3501 #undef GPA
3502 #pragma GCC diagnostic pop
3505 ML (bo_usable (void))
3507 return Val_bool (state.bo_usable);
3510 ML (unproject (value ptr_v, value x_v, value y_v))
3512 CAMLparam3 (ptr_v, x_v, y_v);
3513 CAMLlocal2 (ret_v, tup_v);
3514 struct page *page;
3515 char *s = String_val (ptr_v);
3516 int x = Int_val (x_v), y = Int_val (y_v);
3517 struct pagedim *pdim;
3518 fz_point p;
3520 page = parse_pointer (__func__, s);
3521 pdim = &state.pagedims[page->pdimno];
3523 ret_v = Val_int (0);
3524 if (trylock (__func__)) {
3525 goto done;
3528 p.x = x + pdim->bounds.x0;
3529 p.y = y + pdim->bounds.y0;
3531 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3532 pdim->ctm)));
3534 tup_v = caml_alloc_tuple (2);
3535 ret_v = caml_alloc_small (1, 1);
3536 Field (tup_v, 0) = Val_int (p.x);
3537 Field (tup_v, 1) = Val_int (p.y);
3538 Field (ret_v, 0) = tup_v;
3540 unlock (__func__);
3541 done:
3542 CAMLreturn (ret_v);
3545 ML (project (value ptr_v, value pageno_v, value pdimno_v, value x_v, value y_v))
3547 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3548 CAMLlocal1 (ret_v);
3549 struct page *page;
3550 char *s = String_val (ptr_v);
3551 int pageno = Int_val (pageno_v);
3552 int pdimno = Int_val (pdimno_v);
3553 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3554 struct pagedim *pdim;
3555 fz_point p;
3556 fz_matrix ctm;
3558 ret_v = Val_int (0);
3559 lock (__func__);
3561 if (!*s) {
3562 page = loadpage (pageno, pdimno);
3564 else {
3565 page = parse_pointer (__func__, s);
3567 pdim = &state.pagedims[pdimno];
3569 if (pdf_specifics (state.ctx, state.doc)) {
3570 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3571 ctm = state.pagedims[page->pdimno].tctm;
3573 else {
3574 ctm = fz_identity;
3576 p.x = x + pdim->bounds.x0;
3577 p.y = y + pdim->bounds.y0;
3579 ctm = fz_concat (pdim->tctm, pdim->ctm);
3580 p = fz_transform_point (p, ctm);
3582 ret_v = caml_alloc_tuple (2);
3583 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3584 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3586 if (!*s) {
3587 freepage (page);
3589 unlock (__func__);
3590 CAMLreturn (ret_v);
3593 ML0 (addannot (value ptr_v, value x_v, value y_v, value contents_v))
3595 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3596 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3598 if (pdf) {
3599 pdf_annot *annot;
3600 struct page *page;
3601 fz_rect r;
3602 char *s = String_val (ptr_v);
3604 page = parse_pointer (__func__, s);
3605 annot = pdf_create_annot (state.ctx,
3606 pdf_page_from_fz_page (state.ctx,
3607 page->fzpage),
3608 PDF_ANNOT_TEXT);
3609 r.x0 = Int_val (x_v) - 10;
3610 r.y0 = Int_val (y_v) - 10;
3611 r.x1 = r.x0 + 20;
3612 r.y1 = r.y0 + 20;
3613 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3614 pdf_set_annot_rect (state.ctx, annot, r);
3616 state.dirty = 1;
3618 CAMLreturn0;
3621 ML0 (delannot (value ptr_v, value n_v))
3623 CAMLparam2 (ptr_v, n_v);
3624 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3626 if (pdf) {
3627 struct page *page;
3628 char *s = String_val (ptr_v);
3629 struct slink *slink;
3631 page = parse_pointer (__func__, s);
3632 slink = &page->slinks[Int_val (n_v)];
3633 pdf_delete_annot (state.ctx,
3634 pdf_page_from_fz_page (state.ctx, page->fzpage),
3635 (pdf_annot *) slink->u.annot);
3636 state.dirty = 1;
3638 CAMLreturn0;
3641 ML0 (modannot (value ptr_v, value n_v, value str_v))
3643 CAMLparam3 (ptr_v, n_v, str_v);
3644 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3646 if (pdf) {
3647 struct page *page;
3648 char *s = String_val (ptr_v);
3649 struct slink *slink;
3651 page = parse_pointer (__func__, s);
3652 slink = &page->slinks[Int_val (n_v)];
3653 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3654 String_val (str_v));
3655 state.dirty = 1;
3657 CAMLreturn0;
3660 ML (hasunsavedchanges (void))
3662 return Val_bool (state.dirty);
3665 ML0 (savedoc (value path_v))
3667 CAMLparam1 (path_v);
3668 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3670 if (pdf) {
3671 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3673 CAMLreturn0;
3676 static void makestippletex (void)
3678 const char pixels[] = "\xff\xff\0\0";
3679 glGenTextures (1, &state.stid);
3680 glBindTexture (GL_TEXTURE_1D, state.stid);
3681 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3682 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3683 glTexImage1D (
3684 GL_TEXTURE_1D,
3686 GL_ALPHA,
3689 GL_ALPHA,
3690 GL_UNSIGNED_BYTE,
3691 pixels
3695 ML (fz_version (void))
3697 return caml_copy_string (FZ_VERSION);
3700 ML (llpp_version (void))
3702 extern char llpp_version[];
3703 return caml_copy_string (llpp_version);
3706 static void diag_callback (void *user, const char *message)
3708 printd ("emsg %s %s", (char *) user, message);
3711 ML0 (init (value csock_v, value params_v))
3713 CAMLparam2 (csock_v, params_v);
3714 CAMLlocal2 (trim_v, fuzz_v);
3715 int ret;
3716 int texcount;
3717 char *fontpath;
3718 int colorspace;
3719 int mustoresize;
3721 state.csock = Int_val (csock_v);
3722 state.rotate = Int_val (Field (params_v, 0));
3723 state.fitmodel = Int_val (Field (params_v, 1));
3724 trim_v = Field (params_v, 2);
3725 texcount = Int_val (Field (params_v, 3));
3726 state.sliceheight = Int_val (Field (params_v, 4));
3727 mustoresize = Int_val (Field (params_v, 5));
3728 colorspace = Int_val (Field (params_v, 6));
3729 fontpath = String_val (Field (params_v, 7));
3731 #ifdef CIDER
3732 state.utf8cs = 1;
3733 #else
3734 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3735 if (setlocale (LC_CTYPE, "")) {
3736 const char *cset = nl_langinfo (CODESET);
3737 state.utf8cs = !strcmp (cset, "UTF-8");
3739 else {
3740 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3742 #endif
3744 if (caml_string_length (Field (params_v, 8)) > 0) {
3745 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3747 if (!state.trimcachepath) {
3748 printd ("emsg failed to strdup trimcachepath: %d:%s",
3749 errno, strerror (errno));
3753 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3754 fz_register_document_handlers (state.ctx);
3755 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3756 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3758 state.trimmargins = Bool_val (Field (trim_v, 0));
3759 fuzz_v = Field (trim_v, 1);
3760 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3761 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3762 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3763 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3765 set_tex_params (colorspace);
3767 if (*fontpath) {
3768 state.face = load_font (fontpath);
3770 else {
3771 int len;
3772 const unsigned char *data;
3774 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3775 state.face = load_builtin_font (data, len);
3777 if (!state.face) _exit (1);
3779 realloctexts (texcount);
3780 setuppbo ();
3781 makestippletex ();
3783 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3784 if (ret) {
3785 errx (1, "pthread_create: %s", strerror (ret));
3788 CAMLreturn0;
3791 #if FIXME || !FIXME
3792 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3793 #endif