Use 4.08s %#d format specifier
[llpp.git] / link.c
blobab9c20099c7f269646618c58d5ac0ade8674f5c1
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 struct slice {
93 int h;
94 int texindex;
97 struct tile {
98 int w, h;
99 int slicecount;
100 int sliceheight;
101 struct bo *pbo;
102 fz_pixmap *pixmap;
103 struct slice slices[1];
106 struct pagedim {
107 int pageno;
108 int rotate;
109 int left;
110 int tctmready;
111 fz_irect bounds;
112 fz_rect pagebox;
113 fz_rect mediabox;
114 fz_matrix ctm, zoomctm, tctm;
117 struct slink {
118 enum { SLINK, SANNOT } tag;
119 fz_irect bbox;
120 union {
121 fz_link *link;
122 pdf_annot *annot;
123 } u;
126 struct annot {
127 fz_irect bbox;
128 pdf_annot *annot;
131 struct page {
132 int tgen;
133 int sgen;
134 int agen;
135 int pageno;
136 int pdimno;
137 fz_stext_page *text;
138 fz_page *fzpage;
139 fz_display_list *dlist;
140 fz_link *links;
141 int slinkcount;
142 struct slink *slinks;
143 int annotcount;
144 struct annot *annots;
145 fz_stext_char *fmark, *lmark;
148 enum { FitWidth, FitProportional, FitPage };
150 static struct {
151 int sliceheight;
152 struct pagedim *pagedims;
153 int pagecount;
154 int pagedimcount;
155 fz_document *doc;
156 fz_context *ctx;
157 int w, h;
159 int texindex;
160 int texcount;
161 GLuint *texids;
163 GLenum texiform;
164 GLenum texform;
165 GLenum texty;
167 fz_colorspace *colorspace;
168 float papercolor[4];
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 int utf8cs;
209 } state;
211 struct bo {
212 GLuint id;
213 void *ptr;
214 size_t size;
217 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
219 static void lock (const char *cap)
221 int ret = pthread_mutex_lock (&mutex);
222 if (ret) {
223 errx (1, "%s: pthread_mutex_lock: %s", cap, strerror (ret));
227 static void unlock (const char *cap)
229 int ret = pthread_mutex_unlock (&mutex);
230 if (ret) {
231 errx (1, "%s: pthread_mutex_unlock: %s", cap, strerror (ret));
235 static int trylock (const char *cap)
237 int ret = pthread_mutex_trylock (&mutex);
238 if (ret && ret != EBUSY) {
239 errx (1, "%s: pthread_mutex_trylock: %s", cap, strerror (ret));
241 return ret == EBUSY;
244 static int hasdata (void)
246 int ret, avail;
247 ret = ioctl (state.csock, FIONREAD, &avail);
248 if (ret) err (1, "hasdata: FIONREAD error ret=%d", ret);
249 return avail > 0;
252 value ml_hasdata (value fd_v);
253 value ml_hasdata (value fd_v)
255 CAMLparam1 (fd_v);
256 int ret, avail;
258 ret = ioctl (Int_val (fd_v), FIONREAD, &avail);
259 if (ret) uerror ("ioctl (FIONREAD)", Nothing);
260 CAMLreturn (Val_bool (avail > 0));
263 static void readdata (int fd, void *p, int size)
265 ssize_t n;
267 again:
268 n = read (fd, p, size);
269 if (n - size) {
270 if (n < 0 && errno == EINTR) goto again;
271 if (!n) errx (1, "EOF while reading");
272 errx (1, "read (fd %d, req %d, ret %zd)", fd, size, n);
276 static void writedata (int fd, char *p, int size)
278 ssize_t n;
279 uint32_t size4 = size;
280 struct iovec iov[2] = {
281 { .iov_base = &size4, .iov_len = 4 },
282 { .iov_base = p, .iov_len = size }
285 again:
286 n = writev (fd, iov, 2);
287 if (n < 0 && errno == EINTR) goto again;
288 if (n - size - 4) {
289 if (!n) errx (1, "EOF while writing data");
290 err (1, "writev (fd %d, req %d, ret %zd)", fd, size + 4, n);
294 static int readlen (int fd)
296 uint32_t u;
297 readdata (fd, &u, 4);
298 return u;
301 void ml_wcmd (value fd_v, value bytes_v, value len_v);
302 void ml_wcmd (value fd_v, value bytes_v, value len_v)
304 CAMLparam3 (fd_v, bytes_v, len_v);
305 writedata (Int_val (fd_v), &Byte (bytes_v, 0), Int_val (len_v));
306 CAMLreturn0;
309 value ml_rcmd (value fd_v);
310 value 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 fz_rect rootmediabox = fz_empty_rect;
637 int pageno, trim, show;
638 int trimw = 0, cxcount;
639 fz_context *ctx = state.ctx;
640 pdf_document *pdf = pdf_specifics (ctx, state.doc);
642 fz_var (trimw);
643 fz_var (trimf);
644 fz_var (cxcount);
646 if (state.trimmargins && state.trimcachepath) {
647 trimf = fopen (state.trimcachepath, "rb");
648 if (!trimf) {
649 trimf = fopen (state.trimcachepath, "wb");
650 trimw = 1;
654 cxcount = state.pagecount;
655 if (pdf) {
656 pdf_obj *obj;
657 obj = pdf_dict_getp (ctx, pdf_trailer (ctx, pdf),
658 "Root/Pages/MediaBox");
659 rootmediabox = pdf_to_rect (ctx, obj);
660 pdf_load_page_tree (ctx, pdf);
663 for (pageno = 0; pageno < cxcount; ++pageno) {
664 int rotate = 0;
665 struct pagedim *p;
666 fz_rect mediabox = fz_empty_rect;
668 fz_var (rotate);
669 if (pdf) {
670 pdf_obj *pageobj = NULL;
672 fz_var (pageobj);
673 if (pdf->rev_page_map) {
674 for (int i = 0; i < pdf->rev_page_count; ++i) {
675 if (pdf->rev_page_map[i].page == pageno) {
676 pageobj = pdf_get_xref_entry (
677 ctx, pdf, pdf->rev_page_map[i].object
678 )->obj;
679 break;
683 if (!pageobj) {
684 pageobj = pdf_lookup_page_obj (ctx, pdf, pageno);
687 rotate = pdf_to_int (ctx, pdf_dict_gets (ctx, pageobj, "Rotate"));
689 if (state.trimmargins) {
690 pdf_obj *obj;
691 pdf_page *page;
693 fz_try (ctx) {
694 page = pdf_load_page (ctx, pdf, pageno);
695 obj = pdf_dict_gets (ctx, pageobj, "llpp.TrimBox");
696 trim = state.trimanew || !obj;
697 if (trim) {
698 fz_rect rect;
699 fz_device *dev;
700 fz_matrix ctm, page_ctm;
702 dev = fz_new_bbox_device (ctx, &rect);
703 pdf_page_transform (ctx, page, &mediabox, &page_ctm);
704 ctm = fz_invert_matrix (page_ctm);
705 pdf_run_page (ctx, page, dev, fz_identity, NULL);
706 fz_close_device (ctx, dev);
707 fz_drop_device (ctx, dev);
709 rect.x0 += state.trimfuzz.x0;
710 rect.x1 += state.trimfuzz.x1;
711 rect.y0 += state.trimfuzz.y0;
712 rect.y1 += state.trimfuzz.y1;
713 rect = fz_transform_rect (rect, ctm);
714 rect = fz_intersect_rect (rect, mediabox);
716 if (!fz_is_empty_rect (rect)) {
717 mediabox = rect;
720 obj = pdf_new_array (ctx, pdf, 4);
721 pdf_array_push (ctx, obj,
722 pdf_new_real (ctx, mediabox.x0));
723 pdf_array_push (ctx, obj,
724 pdf_new_real (ctx, mediabox.y0));
725 pdf_array_push (ctx, obj,
726 pdf_new_real (ctx, mediabox.x1));
727 pdf_array_push (ctx, obj,
728 pdf_new_real (ctx, mediabox.y1));
729 pdf_dict_puts (ctx, pageobj, "llpp.TrimBox", obj);
731 else {
732 mediabox.x0 = pdf_to_real (ctx,
733 pdf_array_get (ctx, obj, 0));
734 mediabox.y0 = pdf_to_real (ctx,
735 pdf_array_get (ctx, obj, 1));
736 mediabox.x1 = pdf_to_real (ctx,
737 pdf_array_get (ctx, obj, 2));
738 mediabox.y1 = pdf_to_real (ctx,
739 pdf_array_get (ctx, obj, 3));
742 fz_drop_page (ctx, &page->super);
743 show = trim ? pageno % 5 == 0 : pageno % 20 == 0;
744 if (show) {
745 printd ("progress %f Trimming %d",
746 (double) (pageno + 1) / state.pagecount,
747 pageno + 1);
750 fz_catch (ctx) {
751 printd ("emsg failed to load page %d", pageno);
754 else {
755 int empty = 0;
756 fz_rect cropbox;
758 mediabox =
759 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "MediaBox"));
760 if (fz_is_empty_rect (mediabox)) {
761 mediabox.x0 = 0;
762 mediabox.y0 = 0;
763 mediabox.x1 = 612;
764 mediabox.y1 = 792;
765 empty = 1;
768 cropbox =
769 pdf_to_rect (ctx, pdf_dict_gets (ctx, pageobj, "CropBox"));
770 if (!fz_is_empty_rect (cropbox)) {
771 if (empty) {
772 mediabox = cropbox;
774 else {
775 mediabox = fz_intersect_rect (mediabox, cropbox);
778 else {
779 if (empty) {
780 if (fz_is_empty_rect (rootmediabox)) {
781 printd ("emsg cannot find page size for page %d",
782 pageno);
784 else {
785 mediabox = rootmediabox;
791 else {
792 if (state.trimmargins && trimw) {
793 fz_page *page;
795 fz_try (ctx) {
796 page = fz_load_page (ctx, state.doc, pageno);
797 mediabox = fz_bound_page (ctx, page);
798 if (state.trimmargins) {
799 fz_rect rect;
800 fz_device *dev;
802 dev = fz_new_bbox_device (ctx, &rect);
803 fz_run_page (ctx, page, dev, fz_identity, NULL);
804 fz_close_device (ctx, dev);
805 fz_drop_device (ctx, dev);
807 rect.x0 += state.trimfuzz.x0;
808 rect.x1 += state.trimfuzz.x1;
809 rect.y0 += state.trimfuzz.y0;
810 rect.y1 += state.trimfuzz.y1;
811 rect = fz_intersect_rect (rect, mediabox);
813 if (!fz_is_empty_rect (rect)) {
814 mediabox = rect;
817 fz_drop_page (ctx, page);
819 fz_catch (ctx) {
821 if (trimf) {
822 size_t n = fwrite (&mediabox, sizeof (mediabox), 1, trimf);
823 if (n - 1) {
824 err (1, "fwrite trim mediabox");
828 else {
829 if (trimf) {
830 size_t n = fread (&mediabox, sizeof (mediabox), 1, trimf);
831 if (n - 1) {
832 err (1, "fread trim mediabox %d", pageno);
835 else {
836 fz_page *page;
837 fz_try (ctx) {
838 page = fz_load_page (ctx, state.doc, pageno);
839 mediabox = fz_bound_page (ctx, page);
840 fz_drop_page (ctx, page);
842 show = !state.trimmargins && pageno % 20 == 0;
843 if (show) {
844 printd ("progress %f Gathering dimensions %d",
845 (double) (pageno) / state.pagecount,
846 pageno);
849 fz_catch (ctx) {
850 printd ("emsg failed to load page %d", pageno);
856 if (state.pagedimcount == 0
857 || ((void) (p = &state.pagedims[state.pagedimcount-1])
858 , p->rotate != rotate)
859 || memcmp (&p->mediabox, &mediabox, sizeof (mediabox))) {
860 size_t size;
862 size = (state.pagedimcount + 1) * sizeof (*state.pagedims);
863 state.pagedims = realloc (state.pagedims, size);
864 if (!state.pagedims) {
865 err (1, "realloc pagedims to %zu (%d elems)",
866 size, state.pagedimcount + 1);
869 p = &state.pagedims[state.pagedimcount++];
870 p->rotate = rotate;
871 p->mediabox = mediabox;
872 p->pageno = pageno;
875 state.trimanew = 0;
876 if (trimf) {
877 if (fclose (trimf)) {
878 err (1, "fclose");
883 static void layout (void)
885 int pindex;
886 fz_rect box;
887 fz_matrix ctm;
888 struct pagedim *p = NULL;
889 float zw, w, maxw = 0.0, zoom = 1.0;
891 if (state.pagedimcount == 0) return;
893 switch (state.fitmodel) {
894 case FitProportional:
895 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
896 float x0, x1;
898 p = &state.pagedims[pindex];
899 box = fz_transform_rect (p->mediabox,
900 fz_rotate (p->rotate + state.rotate));
902 x0 = fz_min (box.x0, box.x1);
903 x1 = fz_max (box.x0, box.x1);
905 w = x1 - x0;
906 maxw = fz_max (w, maxw);
907 zoom = state.w / maxw;
909 break;
911 case FitPage:
912 maxw = state.w;
913 break;
915 case FitWidth:
916 break;
918 default:
919 ARSERT (0 && state.fitmodel);
922 for (pindex = 0; pindex < state.pagedimcount; ++pindex) {
923 p = &state.pagedims[pindex];
924 ctm = fz_rotate (state.rotate);
925 box = fz_transform_rect (p->mediabox,
926 fz_rotate (p->rotate + state.rotate));
927 w = box.x1 - box.x0;
928 switch (state.fitmodel) {
929 case FitProportional:
930 p->left = (int) (((maxw - w) * zoom) / 2.f);
931 break;
932 case FitPage:
934 float zh, h;
935 zw = maxw / w;
936 h = box.y1 - box.y0;
937 zh = state.h / h;
938 zoom = fz_min (zw, zh);
939 p->left = (int) ((maxw - (w * zoom)) / 2.f);
941 break;
942 case FitWidth:
943 p->left = 0;
944 zoom = state.w / w;
945 break;
948 p->zoomctm = fz_scale (zoom, zoom);
949 ctm = fz_concat (p->zoomctm, ctm);
951 p->pagebox = p->mediabox;
952 p->pagebox = fz_transform_rect (p->pagebox, fz_rotate (p->rotate));
953 p->pagebox.x1 -= p->pagebox.x0;
954 p->pagebox.y1 -= p->pagebox.y0;
955 p->pagebox.x0 = 0;
956 p->pagebox.y0 = 0;
957 p->bounds = fz_round_rect (fz_transform_rect (p->pagebox, ctm));
958 p->ctm = ctm;
960 ctm = fz_concat (fz_translate (0, -p->mediabox.y1),
961 fz_scale (zoom, -zoom));
962 p->tctmready = 0;
965 do {
966 int x0 = fz_mini (p->bounds.x0, p->bounds.x1);
967 int y0 = fz_mini (p->bounds.y0, p->bounds.y1);
968 int x1 = fz_maxi (p->bounds.x0, p->bounds.x1);
969 int y1 = fz_maxi (p->bounds.y0, p->bounds.y1);
970 int boundw = x1 - x0;
971 int boundh = y1 - y0;
973 printd ("pdim %d %d %d %d", p->pageno, boundw, boundh, p->left);
974 } while (p-- != state.pagedims);
977 static struct pagedim *pdimofpageno (int pageno)
979 struct pagedim *pdim = state.pagedims;
981 for (int i = 0; i < state.pagedimcount; ++i) {
982 if (state.pagedims[i].pageno > pageno)
983 break;
984 pdim = &state.pagedims[i];
986 return pdim;
989 static void recurse_outline (fz_outline *outline, int level)
991 while (outline) {
992 if (outline->page >= 0) {
993 fz_point p = {.x = outline->x, .y = outline->y};
994 struct pagedim *pdim = pdimofpageno (outline->page);
995 int h = fz_maxi (fz_absi (pdim->bounds.y1 - pdim->bounds.y0), 0);
996 p = fz_transform_point (p, pdim->ctm);
997 printd ("o %d %d %d %d %s",
998 level, outline->page, (int) p.y, h, outline->title);
1000 else {
1001 printd ("on %d %s", level, outline->title);
1003 if (outline->down) {
1004 recurse_outline (outline->down, level + 1);
1006 outline = outline->next;
1010 static void process_outline (void)
1012 fz_outline *outline;
1014 if (!state.needoutline || !state.pagedimcount) return;
1016 state.needoutline = 0;
1017 outline = fz_load_outline (state.ctx, state.doc);
1018 if (outline) {
1019 recurse_outline (outline, 0);
1020 fz_drop_outline (state.ctx, outline);
1024 static char *strofline (fz_stext_line *line)
1026 char *p;
1027 char utf8[10];
1028 fz_stext_char *ch;
1029 size_t size = 0, cap = 80;
1031 p = malloc (cap + 1);
1032 if (!p) return NULL;
1034 for (ch = line->first_char; ch; ch = ch->next) {
1035 int n = fz_runetochar (utf8, ch->c);
1036 if (size + n > cap) {
1037 cap *= 2;
1038 p = realloc (p, cap + 1);
1039 if (!p) return NULL;
1042 memcpy (p + size, utf8, n);
1043 size += n;
1045 p[size] = 0;
1046 return p;
1049 static int matchline (regex_t *re, fz_stext_line *line,
1050 int stop, int pageno, double start)
1052 int ret;
1053 char *p;
1054 regmatch_t rm;
1056 p = strofline (line);
1057 if (!p) return -1;
1059 ret = regexec (re, p, 1, &rm, 0);
1060 if (ret) {
1061 free (p);
1062 if (ret != REG_NOMATCH) {
1063 size_t size;
1064 char errbuf[80];
1065 size = regerror (ret, re, errbuf, sizeof (errbuf));
1066 printd ("msg regexec error `%.*s'",
1067 (int) size, errbuf);
1068 return -1;
1070 return 0;
1072 else {
1073 fz_quad s, e;
1074 fz_stext_char *ch;
1075 int o = 0;
1077 for (ch = line->first_char; ch; ch = ch->next) {
1078 o += fz_runelen (ch->c);
1079 if (o > rm.rm_so) {
1080 s = ch->quad;
1081 break;
1084 for (;ch; ch = ch->next) {
1085 o += fz_runelen (ch->c);
1086 if (o > rm.rm_eo) break;
1088 e = ch->quad;
1090 if (!stop) {
1091 printd ("firstmatch %d %d %f %f %f %f %f %f %f %f",
1092 pageno, 1,
1093 s.ul.x, s.ul.y,
1094 e.ur.x, s.ul.y,
1095 e.lr.x, e.lr.y,
1096 s.ul.x, e.lr.y);
1098 printd ("progress 1 found at %d `%.*s' in %f sec",
1099 pageno + 1, (int) (rm.rm_eo - rm.rm_so), &p[rm.rm_so],
1100 now () - start);
1102 else {
1103 printd ("match %d %d %f %f %f %f %f %f %f %f",
1104 pageno, 2,
1105 s.ul.x, s.ul.y,
1106 e.ur.x, s.ul.y,
1107 e.lr.x, e.lr.y,
1108 s.ul.x, e.lr.y);
1110 free (p);
1111 return 1;
1115 /* wishful thinking function */
1116 static void search (regex_t *re, int pageno, int y, int forward)
1118 fz_device *tdev;
1119 fz_stext_page *text;
1120 struct pagedim *pdim;
1121 int stop = 0, niters = 0;
1122 double start, end;
1123 fz_page *page;
1124 fz_stext_block *block;
1126 start = now ();
1127 while (pageno >= 0 && pageno < state.pagecount && !stop) {
1128 if (niters++ == 5) {
1129 niters = 0;
1130 if (hasdata ()) {
1131 printd ("progress 1 attention requested aborting search at %d",
1132 pageno);
1133 stop = 1;
1135 else {
1136 printd ("progress %f searching in page %d",
1137 (double) (pageno + 1) / state.pagecount,
1138 pageno);
1141 pdim = pdimofpageno (pageno);
1142 text = fz_new_stext_page (state.ctx, pdim->mediabox);
1143 tdev = fz_new_stext_device (state.ctx, text, 0);
1145 page = fz_load_page (state.ctx, state.doc, pageno);
1146 fz_run_page (state.ctx, page, tdev, pagectm1 (page, pdim), NULL);
1148 fz_close_device (state.ctx, tdev);
1149 fz_drop_device (state.ctx, tdev);
1151 if (forward) {
1152 for (block = text->first_block; block; block = block->next) {
1153 fz_stext_line *line;
1155 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1156 for (line = block->u.t.first_line; line; line = line->next) {
1157 if (line->bbox.y0 < y + 1) continue;
1159 switch (matchline (re, line, stop, pageno, start)) {
1160 case 0: break;
1161 case 1: stop = 1; break;
1162 case -1: stop = 1; goto endloop;
1167 else {
1168 for (block = text->last_block; block; block = block->prev) {
1169 fz_stext_line *line;
1171 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
1172 for (line = block->u.t.last_line; line; line = line->prev) {
1173 if (line->bbox.y0 < y + 1) continue;
1175 switch (matchline (re, line, stop, pageno, start)) {
1176 case 0: break;
1177 case 1: stop = 1; break;
1178 case -1: stop = 1; goto endloop;
1184 if (forward) {
1185 pageno += 1;
1186 y = 0;
1188 else {
1189 pageno -= 1;
1190 y = INT_MAX;
1192 endloop:
1193 fz_drop_stext_page (state.ctx, text);
1194 fz_drop_page (state.ctx, page);
1196 end = now ();
1197 if (!stop) {
1198 printd ("progress 1 no matches %f sec", end - start);
1200 printd ("clearrects");
1203 static void set_tex_params (int colorspace)
1205 switch (colorspace) {
1206 case 0:
1207 state.texiform = GL_RGBA8;
1208 state.texform = GL_RGBA;
1209 state.texty = GL_UNSIGNED_BYTE;
1210 state.colorspace = fz_device_rgb (state.ctx);
1211 break;
1212 case 1:
1213 state.texiform = GL_LUMINANCE_ALPHA;
1214 state.texform = GL_LUMINANCE_ALPHA;
1215 state.texty = GL_UNSIGNED_BYTE;
1216 state.colorspace = fz_device_gray (state.ctx);
1217 break;
1218 default:
1219 errx (1, "invalid colorspce %d", colorspace);
1223 static void realloctexts (int texcount)
1225 size_t size;
1227 if (texcount == state.texcount) return;
1229 if (texcount < state.texcount) {
1230 glDeleteTextures (state.texcount - texcount,
1231 state.texids + texcount);
1234 size = texcount * (sizeof (*state.texids) + sizeof (*state.texowners));
1235 state.texids = realloc (state.texids, size);
1236 if (!state.texids) {
1237 err (1, "realloc texs %zu", size);
1240 state.texowners = (void *) (state.texids + texcount);
1241 if (texcount > state.texcount) {
1242 glGenTextures (texcount - state.texcount,
1243 state.texids + state.texcount);
1244 for (int i = state.texcount; i < texcount; ++i) {
1245 state.texowners[i].w = -1;
1246 state.texowners[i].slice = NULL;
1249 state.texcount = texcount;
1250 state.texindex = 0;
1253 static char *mbtoutf8 (char *s)
1255 char *p, *r;
1256 wchar_t *tmp;
1257 size_t i, ret, len;
1259 if (state.utf8cs) {
1260 return s;
1263 len = mbstowcs (NULL, s, strlen (s));
1264 if (len == 0 || len == (size_t) -1) {
1265 if (len)
1266 printd ("emsg mbtoutf8: mbstowcs: %d:%s", errno, strerror (errno));
1267 return s;
1270 tmp = calloc (len, sizeof (wchar_t));
1271 if (!tmp) {
1272 printd ("emsg mbtoutf8: calloc(%zu, %zu): %d:%s",
1273 len, sizeof (wchar_t), errno, strerror (errno));
1274 return s;
1277 ret = mbstowcs (tmp, s, len);
1278 if (ret == (size_t) -1) {
1279 printd ("emsg mbtoutf8: mbswcs %zu characters failed: %d:%s",
1280 len, errno, strerror (errno));
1281 free (tmp);
1282 return s;
1285 len = 0;
1286 for (i = 0; i < ret; ++i) {
1287 len += fz_runelen (tmp[i]);
1290 p = r = malloc (len + 1);
1291 if (!r) {
1292 printd ("emsg mbtoutf8: malloc(%zu)", len);
1293 free (tmp);
1294 return s;
1297 for (i = 0; i < ret; ++i) {
1298 p += fz_runetochar (p, tmp[i]);
1300 *p = 0;
1301 free (tmp);
1302 return r;
1305 value ml_mbtoutf8 (value s_v);
1306 value ml_mbtoutf8 (value s_v)
1308 CAMLparam1 (s_v);
1309 CAMLlocal1 (ret_v);
1310 char *s, *r;
1312 s = String_val (s_v);
1313 r = mbtoutf8 (s);
1314 if (r == s) {
1315 ret_v = s_v;
1317 else {
1318 ret_v = caml_copy_string (r);
1319 free (r);
1321 CAMLreturn (ret_v);
1324 static void * mainloop (void UNUSED_ATTR *unused)
1326 char *p = NULL;
1327 int len, ret, oldlen = 0;
1329 fz_var (p);
1330 fz_var (oldlen);
1331 for (;;) {
1332 len = readlen (state.csock);
1333 if (len == 0) {
1334 errx (1, "readlen returned 0");
1337 if (oldlen < len + 1) {
1338 p = realloc (p, len + 1);
1339 if (!p) {
1340 err (1, "realloc %d failed", len + 1);
1342 oldlen = len + 1;
1344 readdata (state.csock, p, len);
1345 p[len] = 0;
1347 if (!strncmp ("open", p, 4)) {
1348 int off, usedoccss, ok = 0, layouth;
1349 char *password;
1350 char *filename;
1351 char *utf8filename;
1352 size_t filenamelen;
1354 fz_var (ok);
1355 ret = sscanf (p + 5, " %d %d %n", &usedoccss, &layouth, &off);
1356 if (ret != 2) {
1357 errx (1, "malformed open `%.*s' ret=%d", len, p, ret);
1360 filename = p + 5 + off;
1361 filenamelen = strlen (filename);
1362 password = filename + filenamelen + 1;
1364 if (password[strlen (password) + 1]) {
1365 fz_set_user_css (state.ctx, password + strlen (password) + 1);
1368 lock ("open");
1369 fz_set_use_document_css (state.ctx, usedoccss);
1370 fz_try (state.ctx) {
1371 ok = openxref (filename, password, layouth);
1373 fz_catch (state.ctx) {
1374 utf8filename = mbtoutf8 (filename);
1375 printd ("emsg Error loading %s: %s",
1376 utf8filename, fz_caught_message (state.ctx));
1377 if (utf8filename != filename) {
1378 free (utf8filename);
1381 if (ok) {
1382 docinfo ();
1383 initpdims ();
1385 unlock ("open");
1386 state.needoutline = ok;
1388 else if (!strncmp ("cs", p, 2)) {
1389 int i, colorspace;
1391 ret = sscanf (p + 2, " %d", &colorspace);
1392 if (ret != 1) {
1393 errx (1, "malformed cs `%.*s' ret=%d", len, p, ret);
1395 lock ("cs");
1396 set_tex_params (colorspace);
1397 for (i = 0; i < state.texcount; ++i) {
1398 state.texowners[i].w = -1;
1399 state.texowners[i].slice = NULL;
1401 unlock ("cs");
1403 else if (!strncmp ("freepage", p, 8)) {
1404 void *ptr;
1406 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1407 if (ret != 1) {
1408 errx (1, "malformed freepage `%.*s' ret=%d", len, p, ret);
1410 lock ("freepage");
1411 freepage (ptr);
1412 unlock ("freepage");
1414 else if (!strncmp ("freetile", p, 8)) {
1415 void *ptr;
1417 ret = sscanf (p + 8, " %" SCNxPTR, (uintptr_t *) &ptr);
1418 if (ret != 1) {
1419 errx (1, "malformed freetile `%.*s' ret=%d", len, p, ret);
1421 lock ("freetile");
1422 freetile (ptr);
1423 unlock ("freetile");
1425 else if (!strncmp ("search", p, 6)) {
1426 int icase, pageno, y, len2, forward;
1427 char *pattern;
1428 regex_t re;
1430 ret = sscanf (p + 6, " %d %d %d %d,%n",
1431 &icase, &pageno, &y, &forward, &len2);
1432 if (ret != 4) {
1433 errx (1, "malformed search `%s' ret=%d", p, ret);
1436 pattern = p + 6 + len2;
1437 ret = regcomp (&re, pattern,
1438 REG_EXTENDED | (icase ? REG_ICASE : 0));
1439 if (ret) {
1440 char errbuf[80];
1441 size_t size;
1443 size = regerror (ret, &re, errbuf, sizeof (errbuf));
1444 printd ("msg regcomp failed `%.*s'", (int) size, errbuf);
1446 else {
1447 lock ("search");
1448 search (&re, pageno, y, forward);
1449 unlock ("search");
1450 regfree (&re);
1453 else if (!strncmp ("geometry", p, 8)) {
1454 int w, h, fitmodel;
1456 printd ("clear");
1457 ret = sscanf (p + 8, " %d %d %d", &w, &h, &fitmodel);
1458 if (ret != 3) {
1459 errx (1, "malformed geometry `%.*s' ret=%d", len, p, ret);
1462 lock ("geometry");
1463 state.h = h;
1464 if (w != state.w) {
1465 state.w = w;
1466 for (int i = 0; i < state.texcount; ++i) {
1467 state.texowners[i].slice = NULL;
1470 state.fitmodel = fitmodel;
1471 layout ();
1472 process_outline ();
1474 state.gen++;
1475 unlock ("geometry");
1476 printd ("continue %d", state.pagecount);
1478 else if (!strncmp ("reqlayout", p, 9)) {
1479 char *nameddest;
1480 int rotate, off, h;
1481 int fitmodel;
1482 pdf_document *pdf;
1484 printd ("clear");
1485 ret = sscanf (p + 9, " %d %d %d %n",
1486 &rotate, &fitmodel, &h, &off);
1487 if (ret != 3) {
1488 errx (1, "bad reqlayout line `%.*s' ret=%d", len, p, ret);
1490 lock ("reqlayout");
1491 pdf = pdf_specifics (state.ctx, state.doc);
1492 if (state.rotate != rotate || state.fitmodel != fitmodel) {
1493 state.gen += 1;
1495 state.rotate = rotate;
1496 state.fitmodel = fitmodel;
1497 state.h = h;
1498 layout ();
1499 process_outline ();
1501 nameddest = p + 9 + off;
1502 if (pdf && nameddest && *nameddest) {
1503 fz_point xy;
1504 struct pagedim *pdim;
1505 int pageno = pdf_lookup_anchor (state.ctx, pdf, nameddest,
1506 &xy.x, &xy.y);
1507 pdim = pdimofpageno (pageno);
1508 xy = fz_transform_point (xy, pdim->ctm);
1509 printd ("a %d %d %d", pageno, (int) xy.x, (int) xy.y);
1512 state.gen++;
1513 unlock ("reqlayout");
1514 printd ("continue %d", state.pagecount);
1516 else if (!strncmp ("page", p, 4)) {
1517 double a, b;
1518 struct page *page;
1519 int pageno, pindex;
1521 ret = sscanf (p + 4, " %d %d", &pageno, &pindex);
1522 if (ret != 2) {
1523 errx (1, "bad page line `%.*s' ret=%d", len, p, ret);
1526 lock ("page");
1527 a = now ();
1528 page = loadpage (pageno, pindex);
1529 b = now ();
1530 unlock ("page");
1532 printd ("page %" PRIxPTR " %f", (uintptr_t) page, b - a);
1534 else if (!strncmp ("tile", p, 4)) {
1535 int x, y, w, h;
1536 struct page *page;
1537 struct tile *tile;
1538 double a, b;
1539 void *data;
1541 ret = sscanf (p + 4, " %" SCNxPTR " %d %d %d %d %" SCNxPTR,
1542 (uintptr_t *) &page, &x, &y, &w, &h,
1543 (uintptr_t *) &data);
1544 if (ret != 6) {
1545 errx (1, "bad tile line `%.*s' ret=%d", len, p, ret);
1548 lock ("tile");
1549 a = now ();
1550 tile = rendertile (page, x, y, w, h, data);
1551 b = now ();
1552 unlock ("tile");
1554 printd ("tile %d %d %" PRIxPTR " %u %f",
1555 x, y, (uintptr_t) (tile),
1556 tile->w * tile->h * tile->pixmap->n,
1557 b - a);
1559 else if (!strncmp ("trimset", p, 7)) {
1560 fz_irect fuzz;
1561 int trimmargins;
1563 ret = sscanf (p + 7, " %d %d %d %d %d",
1564 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1565 if (ret != 5) {
1566 errx (1, "malformed trimset `%.*s' ret=%d", len, p, ret);
1568 lock ("trimset");
1569 state.trimmargins = trimmargins;
1570 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1571 state.trimanew = 1;
1572 state.trimfuzz = fuzz;
1574 unlock ("trimset");
1576 else if (!strncmp ("settrim", p, 7)) {
1577 fz_irect fuzz;
1578 int trimmargins;
1580 ret = sscanf (p + 7, " %d %d %d %d %d",
1581 &trimmargins, &fuzz.x0, &fuzz.y0, &fuzz.x1, &fuzz.y1);
1582 if (ret != 5) {
1583 errx (1, "malformed settrim `%.*s' ret=%d", len, p, ret);
1585 printd ("clear");
1586 lock ("settrim");
1587 state.trimmargins = trimmargins;
1588 state.needoutline = 1;
1589 if (memcmp (&fuzz, &state.trimfuzz, sizeof (fuzz))) {
1590 state.trimanew = 1;
1591 state.trimfuzz = fuzz;
1593 state.pagedimcount = 0;
1594 free (state.pagedims);
1595 state.pagedims = NULL;
1596 initpdims ();
1597 layout ();
1598 process_outline ();
1599 unlock ("settrim");
1600 printd ("continue %d", state.pagecount);
1602 else if (!strncmp ("sliceh", p, 6)) {
1603 int h;
1605 ret = sscanf (p + 6, " %d", &h);
1606 if (ret != 1) {
1607 errx (1, "malformed sliceh `%.*s' ret=%d", len, p, ret);
1609 if (h != state.sliceheight) {
1610 state.sliceheight = h;
1611 for (int i = 0; i < state.texcount; ++i) {
1612 state.texowners[i].w = -1;
1613 state.texowners[i].h = -1;
1614 state.texowners[i].slice = NULL;
1618 else if (!strncmp ("interrupt", p, 9)) {
1619 printd ("vmsg interrupted");
1621 else {
1622 errx (1, "unknown command %.*s", len, p);
1625 return 0;
1628 value ml_isexternallink (value uri_v);
1629 value ml_isexternallink (value uri_v)
1631 CAMLparam1 (uri_v);
1632 int ext = fz_is_external_link (state.ctx, String_val (uri_v));
1633 CAMLreturn (Val_bool (ext));
1636 value ml_uritolocation (value uri_v);
1637 value ml_uritolocation (value uri_v)
1639 CAMLparam1 (uri_v);
1640 CAMLlocal1 (ret_v);
1641 int pageno;
1642 fz_point xy;
1643 struct pagedim *pdim;
1645 pageno = fz_resolve_link (state.ctx, state.doc, String_val (uri_v),
1646 &xy.x, &xy.y);
1647 pdim = pdimofpageno (pageno);
1648 xy = fz_transform_point (xy, pdim->ctm);
1649 ret_v = caml_alloc_tuple (3);
1650 Field (ret_v, 0) = Val_int (pageno);
1651 Field (ret_v, 1) = caml_copy_double ((double) xy.x);
1652 Field (ret_v, 2) = caml_copy_double ((double) xy.y);
1653 CAMLreturn (ret_v);
1656 value ml_realloctexts (value texcount_v);
1657 value 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 rs->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 void ml_begintiles (void);
2124 void ml_begintiles (void)
2126 glEnable (TEXT_TYPE);
2127 glTexCoordPointer (2, GL_FLOAT, 0, state.texcoords);
2128 glVertexPointer (2, GL_FLOAT, 0, state.vertices);
2131 void ml_endtiles (void);
2132 void ml_endtiles (void)
2134 glDisable (TEXT_TYPE);
2137 void ml_drawtile (value args_v, value ptr_v);
2138 void ml_drawtile (value args_v, value ptr_v)
2140 CAMLparam2 (args_v, ptr_v);
2141 int dispx = Int_val (Field (args_v, 0));
2142 int dispy = Int_val (Field (args_v, 1));
2143 int dispw = Int_val (Field (args_v, 2));
2144 int disph = Int_val (Field (args_v, 3));
2145 int tilex = Int_val (Field (args_v, 4));
2146 int tiley = Int_val (Field (args_v, 5));
2147 char *s = String_val (ptr_v);
2148 struct tile *tile = parse_pointer (__func__, s);
2149 int slicey, firstslice;
2150 struct slice *slice;
2151 GLfloat *texcoords = state.texcoords;
2152 GLfloat *vertices = state.vertices;
2154 firstslice = tiley / tile->sliceheight;
2155 slice = &tile->slices[firstslice];
2156 slicey = tiley % tile->sliceheight;
2158 while (disph > 0) {
2159 int dh;
2161 dh = slice->h - slicey;
2162 dh = fz_mini (disph, dh);
2163 uploadslice (tile, slice);
2165 texcoords[0] = tilex; texcoords[1] = slicey;
2166 texcoords[2] = tilex+dispw; texcoords[3] = slicey;
2167 texcoords[4] = tilex; texcoords[5] = slicey+dh;
2168 texcoords[6] = tilex+dispw; texcoords[7] = slicey+dh;
2170 vertices[0] = dispx; vertices[1] = dispy;
2171 vertices[2] = dispx+dispw; vertices[3] = dispy;
2172 vertices[4] = dispx; vertices[5] = dispy+dh;
2173 vertices[6] = dispx+dispw; vertices[7] = dispy+dh;
2175 #if TEXT_TYPE == GL_TEXTURE_2D
2176 for (int i = 0; i < 8; ++i) {
2177 texcoords[i] /= ((i & 1) == 0 ? tile->w : slice->h);
2179 #endif
2181 glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2182 dispy += dh;
2183 disph -= dh;
2184 slice++;
2185 ARSERT (!(slice - tile->slices >= tile->slicecount && disph > 0));
2186 slicey = 0;
2188 CAMLreturn0;
2191 static void drawprect (struct page *page, int xoff, int yoff, value rects_v)
2193 fz_matrix ctm;
2194 fz_point p1, p2, p3, p4;
2195 GLfloat *vertices = state.vertices;
2197 xoff -= state.pagedims[page->pdimno].bounds.x0;
2198 yoff -= state.pagedims[page->pdimno].bounds.y0;
2199 ctm = fz_concat (pagectm (page), fz_translate (xoff, yoff));
2201 glEnable (GL_BLEND);
2202 glVertexPointer (2, GL_FLOAT, 0, vertices);
2204 glColor4d (
2205 Double_array_field (rects_v, 0),
2206 Double_array_field (rects_v, 1),
2207 Double_array_field (rects_v, 2),
2208 Double_array_field (rects_v, 3)
2210 p1.x = (float) Double_array_field (rects_v, 4);
2211 p1.y = (float) Double_array_field (rects_v, 5);
2213 p2.x = (float) Double_array_field (rects_v, 6);
2214 p2.y = p1.y;
2216 p3.x = p2.x;
2217 p3.y = (float) Double_array_field (rects_v, 7);
2219 p4.x = p1.x;
2220 p4.y = p3.y;
2221 solidrect (ctm, p1, p2, p3, p4, vertices);
2222 glDisable (GL_BLEND);
2225 value ml_postprocess (value ptr_v, value hlinks_v,
2226 value xoff_v, value yoff_v,
2227 value li_v);
2228 value ml_postprocess (value ptr_v, value hlinks_v,
2229 value xoff_v, value yoff_v,
2230 value li_v)
2232 CAMLparam5 (ptr_v, hlinks_v, xoff_v, yoff_v, li_v);
2233 int xoff = Int_val (xoff_v);
2234 int yoff = Int_val (yoff_v);
2235 int noff = Int_val (Field (li_v, 0));
2236 char *targ = String_val (Field (li_v, 1));
2237 mlsize_t tlen = caml_string_length (Field (li_v, 1));
2238 int hfsize = Int_val (Field (li_v, 2));
2239 char *s = String_val (ptr_v);
2240 int hlmask = Int_val (hlinks_v);
2241 struct page *page = parse_pointer (__func__, s);
2243 if (!page->fzpage) {
2244 /* deal with loadpage failed pages */
2245 goto done;
2248 if (trylock (__func__)) {
2249 noff = -1;
2250 goto done;
2253 ensureannots (page);
2254 if (hlmask & 1) highlightlinks (page, xoff, yoff);
2255 if (hlmask & 2) {
2256 highlightslinks (page, xoff, yoff, noff, targ, tlen, hfsize);
2257 noff = page->slinkcount;
2259 if (page->tgen == state.gen) {
2260 showsel (page, xoff, yoff);
2262 unlock (__func__);
2264 done:
2265 CAMLreturn (Val_int (noff));
2268 void ml_drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v);
2269 void ml_drawprect (value ptr_v, value xoff_v, value yoff_v, value rects_v)
2271 CAMLparam4 (ptr_v, xoff_v, yoff_v, rects_v);
2272 int xoff = Int_val (xoff_v);
2273 int yoff = Int_val (yoff_v);
2274 char *s = String_val (ptr_v);
2275 struct page *page = parse_pointer (__func__, s);
2277 drawprect (page, xoff, yoff, rects_v);
2278 CAMLreturn0;
2281 static struct annot *getannot (struct page *page, int x, int y)
2283 fz_point p;
2284 fz_matrix ctm;
2285 const fz_matrix *tctm;
2286 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
2288 if (!page->annots) return NULL;
2290 if (pdf) {
2291 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
2292 tctm = &state.pagedims[page->pdimno].tctm;
2294 else {
2295 tctm = &fz_identity;
2298 p.x = x;
2299 p.y = y;
2301 ctm = fz_concat (*tctm, state.pagedims[page->pdimno].ctm);
2302 ctm = fz_invert_matrix (ctm);
2303 p = fz_transform_point (p, ctm);
2305 if (pdf) {
2306 for (int i = 0; i < page->annotcount; ++i) {
2307 struct annot *a = &page->annots[i];
2308 fz_rect rect;
2310 rect = pdf_bound_annot (state.ctx, a->annot);
2311 if (p.x >= rect.x0 && p.x <= rect.x1) {
2312 if (p.y >= rect.y0 && p.y <= rect.y1)
2313 return a;
2317 return NULL;
2320 static fz_link *getlink (struct page *page, int x, int y)
2322 fz_point p;
2323 fz_link *link;
2325 ensureslinks (page);
2327 p.x = x;
2328 p.y = y;
2330 p = fz_transform_point (p, fz_invert_matrix (pagectm (page)));
2332 for (link = page->links; link; link = link->next) {
2333 if (p.x >= link->rect.x0 && p.x <= link->rect.x1) {
2334 if (p.y >= link->rect.y0 && p.y <= link->rect.y1) {
2335 return link;
2339 return NULL;
2342 static void ensuretext (struct page *page)
2344 if (state.gen != page->tgen) {
2345 droptext (page);
2346 page->tgen = state.gen;
2348 if (!page->text) {
2349 fz_device *tdev;
2351 page->text = fz_new_stext_page (state.ctx,
2352 state.pagedims[page->pdimno].mediabox);
2353 tdev = fz_new_stext_device (state.ctx, page->text, 0);
2354 fz_run_display_list (state.ctx, page->dlist,
2355 tdev, pagectm (page), fz_infinite_rect, NULL);
2356 fz_close_device (state.ctx, tdev);
2357 fz_drop_device (state.ctx, tdev);
2361 value ml_find_page_with_links (value start_page_v, value dir_v);
2362 value ml_find_page_with_links (value start_page_v, value dir_v)
2364 CAMLparam2 (start_page_v, dir_v);
2365 CAMLlocal1 (ret_v);
2366 int i, dir = Int_val (dir_v);
2367 int start_page = Int_val (start_page_v);
2368 int end_page = dir > 0 ? state.pagecount : -1;
2369 pdf_document *pdf;
2371 fz_var (end_page);
2372 ret_v = Val_int (0);
2373 lock (__func__);
2374 pdf = pdf_specifics (state.ctx, state.doc);
2375 for (i = start_page + dir; i != end_page; i += dir) {
2376 int found;
2378 fz_var (found);
2379 if (pdf) {
2380 pdf_page *page = NULL;
2382 fz_var (page);
2383 fz_try (state.ctx) {
2384 page = pdf_load_page (state.ctx, pdf, i);
2385 found = !!page->links || !!page->annots;
2387 fz_catch (state.ctx) {
2388 found = 0;
2390 if (page) {
2391 fz_drop_page (state.ctx, &page->super);
2394 else {
2395 fz_page *page = fz_load_page (state.ctx, state.doc, i);
2396 fz_link *link = fz_load_links (state.ctx, page);
2397 found = !!link;
2398 fz_drop_link (state.ctx, link);
2399 fz_drop_page (state.ctx, page);
2402 if (found) {
2403 ret_v = caml_alloc_small (1, 1);
2404 Field (ret_v, 0) = Val_int (i);
2405 goto unlock;
2408 unlock:
2409 unlock (__func__);
2410 CAMLreturn (ret_v);
2413 enum { dir_first, dir_last };
2414 enum { dir_first_visible, dir_left, dir_right, dir_down, dir_up };
2416 value ml_findlink (value ptr_v, value dir_v);
2417 value ml_findlink (value ptr_v, value dir_v)
2419 CAMLparam2 (ptr_v, dir_v);
2420 CAMLlocal2 (ret_v, pos_v);
2421 struct page *page;
2422 int dirtag, i, slinkindex;
2423 struct slink *found = NULL ,*slink;
2424 char *s = String_val (ptr_v);
2426 page = parse_pointer (__func__, s);
2427 ret_v = Val_int (0);
2428 lock (__func__);
2429 ensureslinks (page);
2431 if (Is_block (dir_v)) {
2432 dirtag = Tag_val (dir_v);
2433 switch (dirtag) {
2434 case dir_first_visible:
2436 int x0, y0, dir, first_index, last_index;
2438 pos_v = Field (dir_v, 0);
2439 x0 = Int_val (Field (pos_v, 0));
2440 y0 = Int_val (Field (pos_v, 1));
2441 dir = Int_val (Field (pos_v, 2));
2443 if (dir >= 0) {
2444 dir = 1;
2445 first_index = 0;
2446 last_index = page->slinkcount;
2448 else {
2449 first_index = page->slinkcount - 1;
2450 last_index = -1;
2453 for (i = first_index; i != last_index; i += dir) {
2454 slink = &page->slinks[i];
2455 if (slink->bbox.y0 >= y0 && slink->bbox.x0 >= x0) {
2456 found = slink;
2457 break;
2461 break;
2463 case dir_left:
2464 slinkindex = Int_val (Field (dir_v, 0));
2465 found = &page->slinks[slinkindex];
2466 for (i = slinkindex - 1; i >= 0; --i) {
2467 slink = &page->slinks[i];
2468 if (slink->bbox.x0 < found->bbox.x0) {
2469 found = slink;
2470 break;
2473 break;
2475 case dir_right:
2476 slinkindex = Int_val (Field (dir_v, 0));
2477 found = &page->slinks[slinkindex];
2478 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2479 slink = &page->slinks[i];
2480 if (slink->bbox.x0 > found->bbox.x0) {
2481 found = slink;
2482 break;
2485 break;
2487 case dir_down:
2488 slinkindex = Int_val (Field (dir_v, 0));
2489 found = &page->slinks[slinkindex];
2490 for (i = slinkindex + 1; i < page->slinkcount; ++i) {
2491 slink = &page->slinks[i];
2492 if (slink->bbox.y0 >= found->bbox.y0) {
2493 found = slink;
2494 break;
2497 break;
2499 case dir_up:
2500 slinkindex = Int_val (Field (dir_v, 0));
2501 found = &page->slinks[slinkindex];
2502 for (i = slinkindex - 1; i >= 0; --i) {
2503 slink = &page->slinks[i];
2504 if (slink->bbox.y0 <= found->bbox.y0) {
2505 found = slink;
2506 break;
2509 break;
2512 else {
2513 dirtag = Int_val (dir_v);
2514 switch (dirtag) {
2515 case dir_first:
2516 found = page->slinks;
2517 break;
2519 case dir_last:
2520 if (page->slinks) {
2521 found = page->slinks + (page->slinkcount - 1);
2523 break;
2526 if (found) {
2527 ret_v = caml_alloc_small (2, 1);
2528 Field (ret_v, 0) = Val_int (found - page->slinks);
2531 unlock (__func__);
2532 CAMLreturn (ret_v);
2535 enum { uuri, utext, uannot };
2537 value ml_getlink (value ptr_v, value n_v);
2538 value ml_getlink (value ptr_v, value n_v)
2540 CAMLparam2 (ptr_v, n_v);
2541 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2542 fz_link *link;
2543 struct page *page;
2544 char *s = String_val (ptr_v);
2545 struct slink *slink;
2547 ret_v = Val_int (0);
2548 page = parse_pointer (__func__, s);
2550 lock (__func__);
2551 ensureslinks (page);
2552 slink = &page->slinks[Int_val (n_v)];
2553 if (slink->tag == SLINK) {
2554 link = slink->u.link;
2555 str_v = caml_copy_string (link->uri);
2556 ret_v = caml_alloc_small (1, uuri);
2557 Field (ret_v, 0) = str_v;
2559 else {
2560 ret_v = caml_alloc_small (1, uannot);
2561 tup_v = caml_alloc_tuple (2);
2562 Field (ret_v, 0) = tup_v;
2563 Field (tup_v, 0) = ptr_v;
2564 Field (tup_v, 1) = n_v;
2566 unlock (__func__);
2568 CAMLreturn (ret_v);
2571 value ml_getannotcontents (value ptr_v, value n_v);
2572 value ml_getannotcontents (value ptr_v, value n_v)
2574 CAMLparam2 (ptr_v, n_v);
2575 CAMLlocal1 (ret_v);
2576 pdf_document *pdf;
2577 const char *contents = "";
2579 lock (__func__);
2580 pdf = pdf_specifics (state.ctx, state.doc);
2581 if (pdf) {
2582 char *s = String_val (ptr_v);
2583 struct page *page;
2584 struct slink *slink;
2586 page = parse_pointer (__func__, s);
2587 slink = &page->slinks[Int_val (n_v)];
2588 contents = pdf_annot_contents (state.ctx, (pdf_annot *) slink->u.annot);
2590 unlock (__func__);
2591 ret_v = caml_copy_string (contents);
2592 CAMLreturn (ret_v);
2595 value ml_getlinkcount (value ptr_v);
2596 value ml_getlinkcount (value ptr_v)
2598 CAMLparam1 (ptr_v);
2599 struct page *page;
2600 char *s = String_val (ptr_v);
2602 page = parse_pointer (__func__, s);
2603 CAMLreturn (Val_int (page->slinkcount));
2606 value ml_getlinkrect (value ptr_v, value n_v);
2607 value ml_getlinkrect (value ptr_v, value n_v)
2609 CAMLparam2 (ptr_v, n_v);
2610 CAMLlocal1 (ret_v);
2611 struct page *page;
2612 struct slink *slink;
2613 char *s = String_val (ptr_v);
2615 page = parse_pointer (__func__, s);
2616 ret_v = caml_alloc_tuple (4);
2617 lock (__func__);
2618 ensureslinks (page);
2620 slink = &page->slinks[Int_val (n_v)];
2621 Field (ret_v, 0) = Val_int (slink->bbox.x0);
2622 Field (ret_v, 1) = Val_int (slink->bbox.y0);
2623 Field (ret_v, 2) = Val_int (slink->bbox.x1);
2624 Field (ret_v, 3) = Val_int (slink->bbox.y1);
2625 unlock (__func__);
2626 CAMLreturn (ret_v);
2629 value ml_whatsunder (value ptr_v, value x_v, value y_v);
2630 value ml_whatsunder (value ptr_v, value x_v, value y_v)
2632 CAMLparam3 (ptr_v, x_v, y_v);
2633 CAMLlocal4 (ret_v, tup_v, str_v, gr_v);
2634 fz_link *link;
2635 struct annot *annot;
2636 struct page *page;
2637 char *ptr = String_val (ptr_v);
2638 int x = Int_val (x_v), y = Int_val (y_v);
2639 struct pagedim *pdim;
2641 ret_v = Val_int (0);
2642 if (trylock (__func__)) {
2643 goto done;
2646 page = parse_pointer (__func__, ptr);
2647 pdim = &state.pagedims[page->pdimno];
2648 x += pdim->bounds.x0;
2649 y += pdim->bounds.y0;
2652 annot = getannot (page, x, y);
2653 if (annot) {
2654 int i, n = -1;
2656 ensureslinks (page);
2657 for (i = 0; i < page->slinkcount; ++i) {
2658 if (page->slinks[i].tag == SANNOT
2659 && page->slinks[i].u.annot == annot->annot) {
2660 n = i;
2661 break;
2664 ret_v = caml_alloc_small (1, uannot);
2665 tup_v = caml_alloc_tuple (2);
2666 Field (ret_v, 0) = tup_v;
2667 Field (tup_v, 0) = ptr_v;
2668 Field (tup_v, 1) = Val_int (n);
2669 goto unlock;
2673 link = getlink (page, x, y);
2674 if (link) {
2675 str_v = caml_copy_string (link->uri);
2676 ret_v = caml_alloc_small (1, uuri);
2677 Field (ret_v, 0) = str_v;
2679 else {
2680 fz_rect *b;
2681 fz_stext_block *block;
2683 ensuretext (page);
2685 for (block = page->text->first_block; block; block = block->next) {
2686 fz_stext_line *line;
2688 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2689 b = &block->bbox;
2690 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2691 continue;
2693 for (line = block->u.t.first_line; line; line = line->next) {
2694 fz_stext_char *ch;
2696 b = &line->bbox;
2697 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2698 continue;
2700 for (ch = line->first_char; ch; ch = ch->next) {
2701 fz_quad *q = &ch->quad;
2703 if (x >= q->ul.x && x <= q->ur.x
2704 && y >= q->ul.y && y <= q->ll.y) {
2705 const char *n2 = fz_font_name (state.ctx, ch->font);
2706 FT_FaceRec *face = fz_font_ft_face (state.ctx,
2707 ch->font);
2709 if (!n2) n2 = "<unknown font>";
2711 if (face && face->family_name) {
2712 char *s;
2713 char *n1 = face->family_name;
2714 size_t l1 = strlen (n1);
2715 size_t l2 = strlen (n2);
2717 if (l1 != l2 || memcmp (n1, n2, l1)) {
2718 s = malloc (l1 + l2 + 2);
2719 if (s) {
2720 memcpy (s, n2, l2);
2721 s[l2] = '=';
2722 memcpy (s + l2 + 1, n1, l1 + 1);
2723 str_v = caml_copy_string (s);
2724 free (s);
2728 if (str_v == Val_unit) {
2729 str_v = caml_copy_string (n2);
2731 ret_v = caml_alloc_small (1, utext);
2732 Field (ret_v, 0) = str_v;
2733 goto unlock;
2739 unlock:
2740 unlock (__func__);
2742 done:
2743 CAMLreturn (ret_v);
2746 enum { mark_page, mark_block, mark_line, mark_word };
2748 void ml_clearmark (value ptr_v);
2749 void ml_clearmark (value ptr_v)
2751 CAMLparam1 (ptr_v);
2752 char *s = String_val (ptr_v);
2753 struct page *page;
2755 if (trylock (__func__)) {
2756 goto done;
2759 page = parse_pointer (__func__, s);
2760 page->fmark = NULL;
2761 page->lmark = NULL;
2763 unlock (__func__);
2764 done:
2765 CAMLreturn0;
2768 static int uninteresting (int c)
2770 return isspace (c) || ispunct (c);
2773 value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v);
2774 value ml_markunder (value ptr_v, value x_v, value y_v, value mark_v)
2776 CAMLparam4 (ptr_v, x_v, y_v, mark_v);
2777 CAMLlocal1 (ret_v);
2778 fz_rect *b;
2779 struct page *page;
2780 fz_stext_line *line;
2781 fz_stext_block *block;
2782 struct pagedim *pdim;
2783 int mark = Int_val (mark_v);
2784 char *s = String_val (ptr_v);
2785 int x = Int_val (x_v), y = Int_val (y_v);
2787 ret_v = Val_bool (0);
2788 if (trylock (__func__)) {
2789 goto done;
2792 page = parse_pointer (__func__, s);
2793 pdim = &state.pagedims[page->pdimno];
2795 ensuretext (page);
2797 if (mark == mark_page) {
2798 page->fmark = page->text->first_block->u.t.first_line->first_char;
2799 page->lmark = page->text->last_block->u.t.last_line->last_char;
2800 ret_v = Val_bool (1);
2801 goto unlock;
2804 x += pdim->bounds.x0;
2805 y += pdim->bounds.y0;
2807 for (block = page->text->first_block; block; block = block->next) {
2808 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2809 b = &block->bbox;
2810 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2811 continue;
2813 if (mark == mark_block) {
2814 page->fmark = block->u.t.first_line->first_char;
2815 page->lmark = block->u.t.last_line->last_char;
2816 ret_v = Val_bool (1);
2817 goto unlock;
2820 for (line = block->u.t.first_line; line; line = line->next) {
2821 fz_stext_char *ch;
2823 b = &line->bbox;
2824 if (!(x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1))
2825 continue;
2827 if (mark == mark_line) {
2828 page->fmark = line->first_char;
2829 page->lmark = line->last_char;
2830 ret_v = Val_bool (1);
2831 goto unlock;
2834 for (ch = line->first_char; ch; ch = ch->next) {
2835 fz_stext_char *ch2, *first = NULL, *last = NULL;
2836 fz_quad *q = &ch->quad;
2837 if (x >= q->ul.x && x <= q->ur.x
2838 && y >= q->ul.y && y <= q->ll.y) {
2839 for (ch2 = line->first_char; ch2 != ch; ch2 = ch2->next) {
2840 if (uninteresting (ch2->c)) first = NULL;
2841 else if (!first) first = ch2;
2843 for (ch2 = ch; ch2; ch2 = ch2->next) {
2844 if (uninteresting (ch2->c)) break;
2845 last = ch2;
2848 page->fmark = first;
2849 page->lmark = last;
2850 ret_v = Val_bool (1);
2851 goto unlock;
2856 unlock:
2857 if (!Bool_val (ret_v)) {
2858 page->fmark = NULL;
2859 page->lmark = NULL;
2861 unlock (__func__);
2863 done:
2864 CAMLreturn (ret_v);
2867 value ml_rectofblock (value ptr_v, value x_v, value y_v);
2868 value ml_rectofblock (value ptr_v, value x_v, value y_v)
2870 CAMLparam3 (ptr_v, x_v, y_v);
2871 CAMLlocal2 (ret_v, res_v);
2872 fz_rect *b = NULL;
2873 struct page *page;
2874 struct pagedim *pdim;
2875 fz_stext_block *block;
2876 char *s = String_val (ptr_v);
2877 int x = Int_val (x_v), y = Int_val (y_v);
2879 ret_v = Val_int (0);
2880 if (trylock (__func__)) {
2881 goto done;
2884 page = parse_pointer (__func__, s);
2885 pdim = &state.pagedims[page->pdimno];
2886 x += pdim->bounds.x0;
2887 y += pdim->bounds.y0;
2889 ensuretext (page);
2891 for (block = page->text->first_block; block; block = block->next) {
2892 switch (block->type) {
2893 case FZ_STEXT_BLOCK_TEXT:
2894 b = &block->bbox;
2895 break;
2897 case FZ_STEXT_BLOCK_IMAGE:
2898 b = &block->bbox;
2899 break;
2901 default:
2902 continue;
2905 if (x >= b->x0 && x <= b->x1 && y >= b->y0 && y <= b->y1)
2906 break;
2907 b = NULL;
2909 if (b) {
2910 res_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
2911 ret_v = caml_alloc_small (1, 1);
2912 Store_double_field (res_v, 0, (double) b->x0);
2913 Store_double_field (res_v, 1, (double) b->x1);
2914 Store_double_field (res_v, 2, (double) b->y0);
2915 Store_double_field (res_v, 3, (double) b->y1);
2916 Field (ret_v, 0) = res_v;
2918 unlock (__func__);
2920 done:
2921 CAMLreturn (ret_v);
2924 void ml_seltext (value ptr_v, value rect_v);
2925 void ml_seltext (value ptr_v, value rect_v)
2927 CAMLparam2 (ptr_v, rect_v);
2928 struct page *page;
2929 struct pagedim *pdim;
2930 char *s = String_val (ptr_v);
2931 int x0, x1, y0, y1;
2932 fz_stext_char *ch;
2933 fz_stext_line *line;
2934 fz_stext_block *block;
2935 fz_stext_char *fc, *lc;
2937 if (trylock (__func__)) {
2938 goto done;
2941 page = parse_pointer (__func__, s);
2942 ensuretext (page);
2944 pdim = &state.pagedims[page->pdimno];
2945 x0 = Int_val (Field (rect_v, 0)) + pdim->bounds.x0;
2946 y0 = Int_val (Field (rect_v, 1)) + pdim->bounds.y0;
2947 x1 = Int_val (Field (rect_v, 2)) + pdim->bounds.x0;
2948 y1 = Int_val (Field (rect_v, 3)) + pdim->bounds.y0;
2950 if (y0 > y1) {
2951 int t = y0;
2952 y0 = y1;
2953 y1 = t;
2954 x0 = x1;
2955 x1 = t;
2958 fc = page->fmark;
2959 lc = page->lmark;
2961 for (block = page->text->first_block; block; block = block->next) {
2962 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
2963 for (line = block->u.t.first_line; line; line = line->next) {
2964 for (ch = line->first_char; ch; ch = ch->next) {
2965 fz_quad q = ch->quad;
2966 if (x0 >= q.ul.x && x0 <= q.ur.x
2967 && y0 >= q.ul.y && y0 <= q.ll.y) {
2968 fc = ch;
2970 if (x1 >= q.ul.x && x1 <= q.ur.x
2971 && y1 >= q.ul.y && y1 <= q.ll.y) {
2972 lc = ch;
2977 if (x1 < x0 && fc == lc) {
2978 fz_stext_char *t;
2980 t = fc;
2981 fc = lc;
2982 lc = t;
2985 page->fmark = fc;
2986 page->lmark = lc;
2988 unlock (__func__);
2990 done:
2991 CAMLreturn0;
2994 static int pipechar (FILE *f, fz_stext_char *ch)
2996 char buf[4];
2997 int len;
2998 size_t ret;
3000 len = fz_runetochar (buf, ch->c);
3001 ret = fwrite (buf, len, 1, f);
3002 if (ret != 1) {
3003 printd ("emsg failed to write %d bytes ret=%zu: %d:%s",
3004 len, ret, errno, strerror (errno));
3005 return -1;
3007 return 0;
3010 value ml_spawn (value command_v, value fds_v);
3011 value ml_spawn (value command_v, value fds_v)
3013 CAMLparam2 (command_v, fds_v);
3014 CAMLlocal2 (l_v, tup_v);
3015 int ret, ret1;
3016 pid_t pid = (pid_t) -1;
3017 char *msg = NULL;
3018 value earg_v = Nothing;
3019 posix_spawnattr_t attr;
3020 posix_spawn_file_actions_t fa;
3021 char *argv[] = { "/bin/sh", "-c", NULL, NULL };
3023 argv[2] = String_val (command_v);
3025 if ((ret = posix_spawn_file_actions_init (&fa)) != 0) {
3026 unix_error (ret, "posix_spawn_file_actions_init", Nothing);
3029 if ((ret = posix_spawnattr_init (&attr)) != 0) {
3030 msg = "posix_spawnattr_init";
3031 goto fail1;
3034 #ifdef POSIX_SPAWN_USEVFORK
3035 if ((ret = posix_spawnattr_setflags (&attr, POSIX_SPAWN_USEVFORK)) != 0) {
3036 msg = "posix_spawnattr_setflags POSIX_SPAWN_USEVFORK";
3037 goto fail;
3039 #endif
3041 for (l_v = fds_v; l_v != Val_int (0); l_v = Field (l_v, 1)) {
3042 int fd1, fd2;
3044 tup_v = Field (l_v, 0);
3045 fd1 = Int_val (Field (tup_v, 0));
3046 fd2 = Int_val (Field (tup_v, 1));
3047 if (fd2 < 0) {
3048 if ((ret = posix_spawn_file_actions_addclose (&fa, fd1)) != 0) {
3049 msg = "posix_spawn_file_actions_addclose";
3050 earg_v = tup_v;
3051 goto fail;
3054 else {
3055 if ((ret = posix_spawn_file_actions_adddup2 (&fa, fd1, fd2)) != 0) {
3056 msg = "posix_spawn_file_actions_adddup2";
3057 earg_v = tup_v;
3058 goto fail;
3063 if ((ret = posix_spawn (&pid, "/bin/sh", &fa, &attr, argv, environ))) {
3064 msg = "posix_spawn";
3065 goto fail;
3068 fail:
3069 if ((ret1 = posix_spawnattr_destroy (&attr)) != 0) {
3070 printd ("emsg posix_spawnattr_destroy: %d:%s", ret1, strerror (ret1));
3073 fail1:
3074 if ((ret1 = posix_spawn_file_actions_destroy (&fa)) != 0) {
3075 printd ("emsg posix_spawn_file_actions_destroy: %d:%s",
3076 ret1, strerror (ret1));
3079 if (msg)
3080 unix_error (ret, msg, earg_v);
3082 CAMLreturn (Val_int (pid));
3085 value ml_hassel (value ptr_v);
3086 value ml_hassel (value ptr_v)
3088 CAMLparam1 (ptr_v);
3089 CAMLlocal1 (ret_v);
3090 struct page *page;
3091 char *s = String_val (ptr_v);
3093 ret_v = Val_bool (0);
3094 if (trylock (__func__)) {
3095 goto done;
3098 page = parse_pointer (__func__, s);
3099 ret_v = Val_bool (page->fmark && page->lmark);
3100 unlock (__func__);
3101 done:
3102 CAMLreturn (ret_v);
3105 void ml_copysel (value fd_v, value ptr_v);
3106 void ml_copysel (value fd_v, value ptr_v)
3108 CAMLparam2 (fd_v, ptr_v);
3109 FILE *f;
3110 int seen = 0;
3111 struct page *page;
3112 fz_stext_line *line;
3113 fz_stext_block *block;
3114 int fd = Int_val (fd_v);
3115 char *s = String_val (ptr_v);
3117 if (trylock (__func__)) {
3118 goto done;
3121 page = parse_pointer (__func__, s);
3123 if (!page->fmark || !page->lmark) {
3124 printd ("emsg nothing to copy on page %d", page->pageno);
3125 goto unlock;
3128 f = fdopen (fd, "w");
3129 if (!f) {
3130 printd ("emsg failed to fdopen sel pipe (from fd %d): %d:%s",
3131 fd, errno, strerror (errno));
3132 f = stdout;
3135 for (block = page->text->first_block; block; block = block->next) {
3136 if (block->type != FZ_STEXT_BLOCK_TEXT) continue;
3137 for (line = block->u.t.first_line; line; line = line->next) {
3138 fz_stext_char *ch;
3139 for (ch = line->first_char; ch; ch = ch->next) {
3140 if (seen || ch == page->fmark) {
3141 do {
3142 pipechar (f, ch);
3143 if (ch == page->lmark) goto close;
3144 } while ((ch = ch->next));
3145 seen = 1;
3146 break;
3149 if (seen) fputc ('\n', f);
3152 close:
3153 if (f != stdout) {
3154 int ret = fclose (f);
3155 fd = -1;
3156 if (ret == -1) {
3157 if (errno != ECHILD) {
3158 printd ("emsg failed to close sel pipe: %d:%s",
3159 errno, strerror (errno));
3163 unlock:
3164 unlock (__func__);
3166 done:
3167 if (fd >= 0) {
3168 if (close (fd)) {
3169 printd ("emsg failed to close sel pipe: %d:%s",
3170 errno, strerror (errno));
3173 CAMLreturn0;
3176 value ml_getpdimrect (value pagedimno_v);
3177 value ml_getpdimrect (value pagedimno_v)
3179 CAMLparam1 (pagedimno_v);
3180 CAMLlocal1 (ret_v);
3181 int pagedimno = Int_val (pagedimno_v);
3182 fz_rect box;
3184 ret_v = caml_alloc_small (4 * Double_wosize, Double_array_tag);
3185 if (trylock (__func__)) {
3186 box = fz_empty_rect;
3188 else {
3189 box = state.pagedims[pagedimno].mediabox;
3190 unlock (__func__);
3193 Store_double_field (ret_v, 0, (double) box.x0);
3194 Store_double_field (ret_v, 1, (double) box.x1);
3195 Store_double_field (ret_v, 2, (double) box.y0);
3196 Store_double_field (ret_v, 3, (double) box.y1);
3198 CAMLreturn (ret_v);
3201 value ml_zoom_for_height (value winw_v, value winh_v,
3202 value dw_v, value cols_v);
3203 value ml_zoom_for_height (value winw_v, value winh_v,
3204 value dw_v, value cols_v)
3206 CAMLparam4 (winw_v, winh_v, dw_v, cols_v);
3207 CAMLlocal1 (ret_v);
3208 int i;
3209 float zoom = -1.;
3210 float maxh = 0.0;
3211 struct pagedim *p;
3212 float winw = Int_val (winw_v);
3213 float winh = Int_val (winh_v);
3214 float dw = Int_val (dw_v);
3215 float cols = Int_val (cols_v);
3216 float pw = 1.0, ph = 1.0;
3218 if (trylock (__func__)) {
3219 goto done;
3222 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3223 float w = p->pagebox.x1 / cols;
3224 float h = p->pagebox.y1;
3225 if (h > maxh) {
3226 maxh = h;
3227 ph = h;
3228 if (state.fitmodel != FitProportional) pw = w;
3230 if ((state.fitmodel == FitProportional) && w > pw) pw = w;
3233 zoom = (((winh / ph) * pw) + dw) / winw;
3234 unlock (__func__);
3235 done:
3236 ret_v = caml_copy_double ((double) zoom);
3237 CAMLreturn (ret_v);
3240 value ml_getmaxw (value unit_v);
3241 value ml_getmaxw (value unit_v)
3243 CAMLparam1 (unit_v);
3244 CAMLlocal1 (ret_v);
3245 int i;
3246 float maxw = -1.;
3247 struct pagedim *p;
3249 if (trylock (__func__)) {
3250 goto done;
3253 for (i = 0, p = state.pagedims; i < state.pagedimcount; ++i, ++p) {
3254 float w = p->pagebox.x1;
3255 maxw = fz_max (maxw, w);
3258 unlock (__func__);
3259 done:
3260 ret_v = caml_copy_double ((double) maxw);
3261 CAMLreturn (ret_v);
3264 value ml_draw_string (value pt_v, value x_v,
3265 value y_v, value string_v);
3266 value ml_draw_string (value pt_v, value x_v,
3267 value y_v, value string_v)
3269 CAMLparam4 (pt_v, x_v, y_v, string_v);
3270 CAMLlocal1 (ret_v);
3271 int pt = Int_val(pt_v);
3272 int x = Int_val (x_v);
3273 int y = Int_val (y_v);
3274 float w;
3276 w = draw_string (state.face, pt, x, y, String_val (string_v));
3277 ret_v = caml_copy_double (w);
3278 CAMLreturn (ret_v);
3281 value ml_measure_string (value pt_v, value string_v);
3282 value ml_measure_string (value pt_v, value string_v)
3284 CAMLparam2 (pt_v, string_v);
3285 CAMLlocal1 (ret_v);
3286 int pt = Int_val (pt_v);
3287 double w;
3289 w = (double) measure_string (state.face, pt, String_val (string_v));
3290 ret_v = caml_copy_double (w);
3291 CAMLreturn (ret_v);
3294 value ml_getpagebox (value opaque_v);
3295 value ml_getpagebox (value opaque_v)
3297 CAMLparam1 (opaque_v);
3298 CAMLlocal1 (ret_v);
3299 fz_rect rect;
3300 fz_irect bbox;
3301 fz_device *dev;
3302 char *s = String_val (opaque_v);
3303 struct page *page = parse_pointer (__func__, s);
3305 ret_v = caml_alloc_tuple (4);
3306 dev = fz_new_bbox_device (state.ctx, &rect);
3308 fz_run_page (state.ctx, page->fzpage, dev, pagectm (page), NULL);
3310 fz_close_device (state.ctx, dev);
3311 fz_drop_device (state.ctx, dev);
3312 bbox = fz_round_rect (rect);
3313 Field (ret_v, 0) = Val_int (bbox.x0);
3314 Field (ret_v, 1) = Val_int (bbox.y0);
3315 Field (ret_v, 2) = Val_int (bbox.x1);
3316 Field (ret_v, 3) = Val_int (bbox.y1);
3318 CAMLreturn (ret_v);
3321 void ml_setaalevel (value level_v);
3322 void ml_setaalevel (value level_v)
3324 CAMLparam1 (level_v);
3326 state.aalevel = Int_val (level_v);
3327 CAMLreturn0;
3330 void ml_setpapercolor (value rgba_v);
3331 void ml_setpapercolor (value rgba_v)
3333 CAMLparam1 (rgba_v);
3335 state.papercolor[0] = (float) Double_val (Field (rgba_v, 0));
3336 state.papercolor[1] = (float) Double_val (Field (rgba_v, 1));
3337 state.papercolor[2] = (float) Double_val (Field (rgba_v, 2));
3338 state.papercolor[3] = (float) Double_val (Field (rgba_v, 3));
3339 CAMLreturn0;
3342 value ml_keysymtoutf8 (value keysym_v);
3343 #ifndef CIDER
3344 value ml_keysymtoutf8 (value keysym_v)
3346 CAMLparam1 (keysym_v);
3347 CAMLlocal1 (str_v);
3348 KeySym keysym = Int_val (keysym_v);
3349 Rune rune;
3350 extern long keysym2ucs (KeySym);
3351 int len;
3352 char buf[5];
3354 rune = (Rune) keysym2ucs (keysym);
3355 len = fz_runetochar (buf, rune);
3356 buf[len] = 0;
3357 str_v = caml_copy_string (buf);
3358 CAMLreturn (str_v);
3360 #else
3361 value ml_keysymtoutf8 (value keysym_v)
3363 CAMLparam1 (keysym_v);
3364 CAMLlocal1 (str_v);
3365 long ucs = Long_val (keysym_v);
3366 int len;
3367 char buf[5];
3369 len = fz_runetochar (buf, (int) ucs);
3370 buf[len] = 0;
3371 str_v = caml_copy_string (buf);
3372 CAMLreturn (str_v);
3374 #endif
3376 enum { piunknown, pilinux, pimacos, pibsd };
3378 value ml_platform (value unit_v);
3379 value ml_platform (value unit_v)
3381 CAMLparam1 (unit_v);
3382 CAMLlocal2 (tup_v, arr_v);
3383 int platid = piunknown;
3384 struct utsname buf;
3386 #if defined __linux__
3387 platid = pilinux;
3388 #elif defined __DragonFly__ || defined __FreeBSD__
3389 || defined __OpenBSD__ || defined __NetBSD__
3390 platid = pibsd;
3391 #elif defined __APPLE__
3392 platid = pimacos;
3393 #endif
3394 if (uname (&buf)) err (1, "uname");
3396 tup_v = caml_alloc_tuple (2);
3398 char const *sar[] = {
3399 buf.sysname,
3400 buf.release,
3401 buf.version,
3402 buf.machine,
3403 NULL
3405 arr_v = caml_copy_string_array (sar);
3407 Field (tup_v, 0) = Val_int (platid);
3408 Field (tup_v, 1) = arr_v;
3409 CAMLreturn (tup_v);
3412 void ml_cloexec (value fd_v);
3413 void ml_cloexec (value fd_v)
3415 CAMLparam1 (fd_v);
3416 int fd = Int_val (fd_v);
3418 if (fcntl (fd, F_SETFD, FD_CLOEXEC, 1)) {
3419 uerror ("fcntl", Nothing);
3421 CAMLreturn0;
3424 value ml_getpbo (value w_v, value h_v, value cs_v);
3425 value ml_getpbo (value w_v, value h_v, value cs_v)
3427 CAMLparam2 (w_v, h_v);
3428 CAMLlocal1 (ret_v);
3429 struct bo *pbo;
3430 int w = Int_val (w_v);
3431 int h = Int_val (h_v);
3432 int cs = Int_val (cs_v);
3434 if (state.bo_usable) {
3435 pbo = calloc (sizeof (*pbo), 1);
3436 if (!pbo) {
3437 err (1, "calloc pbo");
3440 switch (cs) {
3441 case 0:
3442 case 1:
3443 pbo->size = w*h*4;
3444 break;
3445 case 2:
3446 pbo->size = w*h*2;
3447 break;
3448 default:
3449 errx (1, "%s: invalid colorspace %d", __func__, cs);
3452 state.glGenBuffersARB (1, &pbo->id);
3453 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, pbo->id);
3454 state.glBufferDataARB (GL_PIXEL_UNPACK_BUFFER_ARB, (GLsizei) pbo->size,
3455 NULL, GL_STREAM_DRAW);
3456 pbo->ptr = state.glMapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB,
3457 GL_READ_WRITE);
3458 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3459 if (!pbo->ptr) {
3460 printd ("emsg glMapBufferARB failed: %#x", glGetError ());
3461 state.glDeleteBuffersARB (1, &pbo->id);
3462 free (pbo);
3463 ret_v = caml_copy_string ("0");
3465 else {
3466 int res;
3467 char *s;
3469 res = snprintf (NULL, 0, "%" PRIxPTR, (uintptr_t) pbo);
3470 if (res < 0) {
3471 err (1, "snprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3473 s = malloc (res+1);
3474 if (!s) {
3475 err (1, "malloc %d bytes failed", res+1);
3477 res = sprintf (s, "%" PRIxPTR, (uintptr_t) pbo);
3478 if (res < 0) {
3479 err (1, "sprintf %" PRIxPTR " failed", (uintptr_t) pbo);
3481 ret_v = caml_copy_string (s);
3482 free (s);
3485 else {
3486 ret_v = caml_copy_string ("0");
3488 CAMLreturn (ret_v);
3491 void ml_freepbo (value s_v);
3492 void ml_freepbo (value s_v)
3494 CAMLparam1 (s_v);
3495 char *s = String_val (s_v);
3496 struct tile *tile = parse_pointer (__func__, s);
3498 if (tile->pbo) {
3499 state.glDeleteBuffersARB (1, &tile->pbo->id);
3500 tile->pbo->id = -1;
3501 tile->pbo->ptr = NULL;
3502 tile->pbo->size = -1;
3504 CAMLreturn0;
3507 void ml_unmappbo (value s_v);
3508 void ml_unmappbo (value s_v)
3510 CAMLparam1 (s_v);
3511 char *s = String_val (s_v);
3512 struct tile *tile = parse_pointer (__func__, s);
3514 if (tile->pbo) {
3515 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, tile->pbo->id);
3516 if (state.glUnmapBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB) == GL_FALSE) {
3517 errx (1, "glUnmapBufferARB failed: %#x\n", glGetError ());
3519 tile->pbo->ptr = NULL;
3520 state.glBindBufferARB (GL_PIXEL_UNPACK_BUFFER_ARB, 0);
3522 CAMLreturn0;
3525 static void setuppbo (void)
3527 extern void (*wsigladdr (const char *name)) (void);
3528 #pragma GCC diagnostic push
3529 #ifdef __clang__
3530 #pragma GCC diagnostic ignored "-Wbad-function-cast"
3531 #endif
3532 #define GPA(n) (*(uintptr_t *) &state.n = (uintptr_t) wsigladdr (#n))
3533 state.bo_usable = GPA (glBindBufferARB)
3534 && GPA (glUnmapBufferARB)
3535 && GPA (glMapBufferARB)
3536 && GPA (glBufferDataARB)
3537 && GPA (glGenBuffersARB)
3538 && GPA (glDeleteBuffersARB);
3539 #undef GPA
3540 #pragma GCC diagnostic pop
3543 value ml_bo_usable (void);
3544 value ml_bo_usable (void)
3546 return Val_bool (state.bo_usable);
3549 value ml_unproject (value ptr_v, value x_v, value y_v);
3550 value ml_unproject (value ptr_v, value x_v, value y_v)
3552 CAMLparam3 (ptr_v, x_v, y_v);
3553 CAMLlocal2 (ret_v, tup_v);
3554 struct page *page;
3555 char *s = String_val (ptr_v);
3556 int x = Int_val (x_v), y = Int_val (y_v);
3557 struct pagedim *pdim;
3558 fz_point p;
3560 page = parse_pointer (__func__, s);
3561 pdim = &state.pagedims[page->pdimno];
3563 ret_v = Val_int (0);
3564 if (trylock (__func__)) {
3565 goto done;
3568 p.x = x + pdim->bounds.x0;
3569 p.y = y + pdim->bounds.y0;
3571 p = fz_transform_point (p, fz_invert_matrix (fz_concat (pdim->tctm,
3572 pdim->ctm)));
3574 tup_v = caml_alloc_tuple (2);
3575 ret_v = caml_alloc_small (1, 1);
3576 Field (tup_v, 0) = Val_int (p.x);
3577 Field (tup_v, 1) = Val_int (p.y);
3578 Field (ret_v, 0) = tup_v;
3580 unlock (__func__);
3581 done:
3582 CAMLreturn (ret_v);
3585 value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3586 value x_v, value y_v);
3587 value ml_project (value ptr_v, value pageno_v, value pdimno_v,
3588 value x_v, value y_v)
3590 CAMLparam5 (ptr_v, pageno_v, pdimno_v, x_v, y_v);
3591 CAMLlocal1 (ret_v);
3592 struct page *page;
3593 char *s = String_val (ptr_v);
3594 int pageno = Int_val (pageno_v);
3595 int pdimno = Int_val (pdimno_v);
3596 float x = (float) Double_val (x_v), y = (float) Double_val (y_v);
3597 struct pagedim *pdim;
3598 fz_point p;
3599 fz_matrix ctm;
3601 ret_v = Val_int (0);
3602 lock (__func__);
3604 if (!*s) {
3605 page = loadpage (pageno, pdimno);
3607 else {
3608 page = parse_pointer (__func__, s);
3610 pdim = &state.pagedims[pdimno];
3612 if (pdf_specifics (state.ctx, state.doc)) {
3613 trimctm (pdf_page_from_fz_page (state.ctx, page->fzpage), page->pdimno);
3614 ctm = state.pagedims[page->pdimno].tctm;
3616 else {
3617 ctm = fz_identity;
3619 p.x = x + pdim->bounds.x0;
3620 p.y = y + pdim->bounds.y0;
3622 ctm = fz_concat (pdim->tctm, pdim->ctm);
3623 p = fz_transform_point (p, ctm);
3625 ret_v = caml_alloc_tuple (2);
3626 Field (ret_v, 0) = caml_copy_double ((double) p.x);
3627 Field (ret_v, 1) = caml_copy_double ((double) p.y);
3629 if (!*s) {
3630 freepage (page);
3632 unlock (__func__);
3633 CAMLreturn (ret_v);
3636 void ml_addannot (value ptr_v, value x_v, value y_v, value contents_v);
3637 void ml_addannot (value ptr_v, value x_v, value y_v, value contents_v)
3639 CAMLparam4 (ptr_v, x_v, y_v, contents_v);
3640 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3642 if (pdf) {
3643 pdf_annot *annot;
3644 struct page *page;
3645 fz_rect r;
3646 char *s = String_val (ptr_v);
3648 page = parse_pointer (__func__, s);
3649 annot = pdf_create_annot (state.ctx,
3650 pdf_page_from_fz_page (state.ctx,
3651 page->fzpage),
3652 PDF_ANNOT_TEXT);
3653 r.x0 = Int_val (x_v) - 10;
3654 r.y0 = Int_val (y_v) - 10;
3655 r.x1 = r.x0 + 20;
3656 r.y1 = r.y0 + 20;
3657 pdf_set_annot_contents (state.ctx, annot, String_val (contents_v));
3658 pdf_set_annot_rect (state.ctx, annot, r);
3660 state.dirty = 1;
3662 CAMLreturn0;
3665 void ml_delannot (value ptr_v, value n_v);
3666 void ml_delannot (value ptr_v, value n_v)
3668 CAMLparam2 (ptr_v, n_v);
3669 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3671 if (pdf) {
3672 struct page *page;
3673 char *s = String_val (ptr_v);
3674 struct slink *slink;
3676 page = parse_pointer (__func__, s);
3677 slink = &page->slinks[Int_val (n_v)];
3678 pdf_delete_annot (state.ctx,
3679 pdf_page_from_fz_page (state.ctx, page->fzpage),
3680 (pdf_annot *) slink->u.annot);
3681 state.dirty = 1;
3683 CAMLreturn0;
3686 void ml_modannot (value ptr_v, value n_v, value str_v);
3687 void ml_modannot (value ptr_v, value n_v, value str_v)
3689 CAMLparam3 (ptr_v, n_v, str_v);
3690 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3692 if (pdf) {
3693 struct page *page;
3694 char *s = String_val (ptr_v);
3695 struct slink *slink;
3697 page = parse_pointer (__func__, s);
3698 slink = &page->slinks[Int_val (n_v)];
3699 pdf_set_annot_contents (state.ctx, (pdf_annot *) slink->u.annot,
3700 String_val (str_v));
3701 state.dirty = 1;
3703 CAMLreturn0;
3706 value ml_hasunsavedchanges (void);
3707 value ml_hasunsavedchanges (void)
3709 return Val_bool (state.dirty);
3712 void ml_savedoc (value path_v);
3713 void ml_savedoc (value path_v)
3715 CAMLparam1 (path_v);
3716 pdf_document *pdf = pdf_specifics (state.ctx, state.doc);
3718 if (pdf) {
3719 pdf_save_document (state.ctx, pdf, String_val (path_v), NULL);
3721 CAMLreturn0;
3724 static void makestippletex (void)
3726 const char pixels[] = "\xff\xff\0\0";
3727 glGenTextures (1, &state.stid);
3728 glBindTexture (GL_TEXTURE_1D, state.stid);
3729 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3730 glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3731 glTexImage1D (
3732 GL_TEXTURE_1D,
3734 GL_ALPHA,
3737 GL_ALPHA,
3738 GL_UNSIGNED_BYTE,
3739 pixels
3743 value ml_fz_version (void);
3744 value ml_fz_version (void)
3746 return caml_copy_string (FZ_VERSION);
3749 value ml_llpp_version (void);
3750 value ml_llpp_version (void)
3752 extern char llpp_version[];
3753 return caml_copy_string (llpp_version);
3756 static void diag_callback (void *user, const char *message)
3758 printd ("emsg %s %s", (char *) user, message);
3761 void ml_init (value csock_v, value params_v);
3762 void ml_init (value csock_v, value params_v)
3764 CAMLparam2 (csock_v, params_v);
3765 CAMLlocal2 (trim_v, fuzz_v);
3766 int ret;
3767 int texcount;
3768 char *fontpath;
3769 int colorspace;
3770 int mustoresize;
3772 state.csock = Int_val (csock_v);
3773 state.rotate = Int_val (Field (params_v, 0));
3774 state.fitmodel = Int_val (Field (params_v, 1));
3775 trim_v = Field (params_v, 2);
3776 texcount = Int_val (Field (params_v, 3));
3777 state.sliceheight = Int_val (Field (params_v, 4));
3778 mustoresize = Int_val (Field (params_v, 5));
3779 colorspace = Int_val (Field (params_v, 6));
3780 fontpath = String_val (Field (params_v, 7));
3782 #ifdef CIDER
3783 state.utf8cs = 1;
3784 #else
3785 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html */
3786 if (setlocale (LC_CTYPE, "")) {
3787 const char *cset = nl_langinfo (CODESET);
3788 state.utf8cs = !strcmp (cset, "UTF-8");
3790 else {
3791 printd ("emsg setlocale: %d:%s", errno, strerror (errno));
3793 #endif
3795 if (caml_string_length (Field (params_v, 8)) > 0) {
3796 state.trimcachepath = ystrdup (String_val (Field (params_v, 8)));
3798 if (!state.trimcachepath) {
3799 printd ("emsg failed to strdup trimcachepath: %d:%s",
3800 errno, strerror (errno));
3804 state.ctx = fz_new_context (NULL, NULL, mustoresize);
3805 fz_register_document_handlers (state.ctx);
3806 fz_set_error_callback (state.ctx, diag_callback, "[e]");
3807 fz_set_warning_callback (state.ctx, diag_callback, "[w]");
3809 state.trimmargins = Bool_val (Field (trim_v, 0));
3810 fuzz_v = Field (trim_v, 1);
3811 state.trimfuzz.x0 = Int_val (Field (fuzz_v, 0));
3812 state.trimfuzz.y0 = Int_val (Field (fuzz_v, 1));
3813 state.trimfuzz.x1 = Int_val (Field (fuzz_v, 2));
3814 state.trimfuzz.y1 = Int_val (Field (fuzz_v, 3));
3816 set_tex_params (colorspace);
3818 if (*fontpath) {
3819 state.face = load_font (fontpath);
3821 else {
3822 int len;
3823 const unsigned char *data;
3825 data = pdf_lookup_substitute_font (state.ctx, 0, 0, 0, 0, &len);
3826 state.face = load_builtin_font (data, len);
3828 if (!state.face) _exit (1);
3830 realloctexts (texcount);
3831 setuppbo ();
3832 makestippletex ();
3834 ret = pthread_create (&state.thread, NULL, mainloop, NULL);
3835 if (ret) {
3836 errx (1, "pthread_create: %s", strerror (ret));
3839 CAMLreturn0;
3842 #if FIXME || !FIXME
3843 static void UNUSED_ATTR NO_OPTIMIZE_ATTR refmacs (void) {}
3844 #endif